问:
Media Player - Seek bar and Time lable is not progressing
IDK why but after just coping the entier mainactivty.java file from this video

IDK why my seek bar and timetable are not showing any progress

there is an exception I have 2 audio files but the video show has only one so I have doubled all the methods also the onClick and a dialog which is different from it

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    MediaPlayer player1;
    MediaPlayer player2;
    SeekBar seekBar1;
    SeekBar seekBar2;
    TextView elapsedTimeLable1;
    TextView elapsedTimeLable2;
    TextView remainingTimeLable1;
    TextView remainingTimeLable2;
    ImageView play1;
    ImageView play2;
    int totalTime1;
    int totalTime2;

    @Override

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

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

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

        // TimeLables

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

        // MediaPlayer

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

        //SeekBar

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

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

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

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

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

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

                }
            }
        }).start();

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

                }
            }
        }).start();

        // Admob Banner Ad

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

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

        // Caution dialog

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

            showDialog();
        }

    }

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

    private  Handler handler1 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //Update SeekBar
            seekBar1.setProgress(currentPosition1);
            // Update Timelable
            String elapsedTime1 = createTimerLable1(currentPosition1);
            elapsedTimeLable1.setText(elapsedTime1);
            String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
            remainingTimeLable1.setText("- " + remainingTime1);

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

        }
    };

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

    }

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

    }

    public void playBtnClick1(View view) {

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

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

    }

    public void playBtnClick2(View view) {

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

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

    }

}
</code>```

答:
Replace Thread.sleep(1000000000) to Thread.sleep(1000) because you just need to update text and seek bar every second

```<code> new Thread(() -> {
        while (player1 != null) {
            try {
                Message msg = new Message();
                msg.what = player1.getCurrentPosition();
                handler1.sendMessage(msg);
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
        }
    }).start();

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

                }
            }
        }).start();
</code>```

Body:
IDK why but after just coping the entier mainactivty.java file from this video

IDK why my seek bar and timetable are not showing any progress

there is an exception I have 2 audio files but the video show has only one so I have doubled all the methods also the onClick and a dialog which is different from it

MainActivity.java

public class MainActivity extends AppCompatActivity {
    MediaPlayer player1;
    MediaPlayer player2;
    SeekBar seekBar1;
    SeekBar seekBar2;
    TextView elapsedTimeLable1;
    TextView elapsedTimeLable2;
    TextView remainingTimeLable1;
    TextView remainingTimeLable2;
    ImageView play1;
    ImageView play2;
    int totalTime1;
    int totalTime2;

    @Override

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

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

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

        // TimeLables

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

        // MediaPlayer

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

        //SeekBar

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

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

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

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

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

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

                }
            }
        }).start();

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

                }
            }
        }).start();

        // Admob Banner Ad

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

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

        // Caution dialog

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

            showDialog();
        }

    }

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

    private  Handler handler1 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //Update SeekBar
            seekBar1.setProgress(currentPosition1);
            // Update Timelable
            String elapsedTime1 = createTimerLable1(currentPosition1);
            elapsedTimeLable1.setText(elapsedTime1);
            String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
            remainingTimeLable1.setText("- " + remainingTime1);

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

        }
    };

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

    }

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

    }

    public void playBtnClick1(View view) {

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

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

    }

    public void playBtnClick2(View view) {

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

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

    }

}

Body:
Replace Thread.sleep(1000000000) to Thread.sleep(1000) because you just need to update text and seek bar every second

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

            }
        }
    }).start();

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

                }
            }
        }).start();


来源: stackexchange

问:
How do you make the program auto restart after value error - Python
So I have this program to convert a binary to hex. I also have a part that returns a value error if you put in a non 0 or 1 or if the string is  more or less than 8 digits.

But what I want now with it is if the program does get the value error how do I code it so that it automatically restarts after the value error.

答:
Here's a small program to put it in context:

```<code>while True:
    possible = input("Enter 8-bit binary number:").rstrip()
    if possible == 'quit':
        break
    try:
        hex = bin2hex(possible)
    except ValueError as e:
        print(e)
        print("%s is not a valid 8-bit binary number" % possible)
    else:
        print("\n%s == %x\n" % (possible, hex))
</code>```

It only stops when you type in quit.

ContentLicense: CC BY-SA 3.0

Body:
Here's a small program to put it in context:

while True:
    possible = input("Enter 8-bit binary number:").rstrip()
    if possible == 'quit':
        break
    try:
        hex = bin2hex(possible)
    except ValueError as e:
        print(e)
        print("%s is not a valid 8-bit binary number" % possible)
    else:
        print("\n%s == %x\n" % (possible, hex))

It only stops when you type in quit.


问:
React Firebase read data results in too many renders
I'm using Firebase realtime database for my react project. I try to follow the firebase documentation and use "onValue()" to retrieve data. Here is my code:

```<code>export default function Home() {

    const {currentUser} = useAuth();
    const [userinfo,setUserinfo] = React.useState();

    const uid = currentUser.uid
    const db = getDatabase();

    onValue(ref(db,`users/${uid}`),snapshot=>{
        const data = snapshot.val();
        setUserinfo(data);
    })

    console.log(userinfo);

    return (
    <main id="home">
        <Hero />
    </main>
    )
}
</code>```

This would result in an error of too many re-renders. I don't know how to retrieve the data. If I use

```<code>onValue(ref(db,`users/${uid}`),snapshot=>{
        const data = snapshot.val();
        console.log(data);
    })
</code>```

then the proper data would print out in the console perfectly fine. I also tried the following:

```<code>let info;
onValue(ref(db,`users/${uid}`),snapshot=>{
        const data = snapshot.val();
        info = data;
    })
console.log(info)
</code>```

but info would just be undefined. I can't seem to figure out the problem here. How can I use the data?

答:
It throws error too many re-renders because you are not using any lifecycle hook or function to update/change state value and once you update your state it will again re-render your whole component and then again you update the state and the same thing happens in the loop causing too many re-renders.

So to avoid this you need to put code that is responsible for listening to changes from DB and changing state inside a block which will only get called on specific events or function calls or etc.

In your case, I suggest using useEffect hook. see below code -

```<code>export default function Home() {

    const { currentUser } = useAuth();
    const [userinfo, setUserinfo] = React.useState();

    const uid = currentUser.uid
    const db = getDatabase();

    // this useEffect will get called only
    // when component gets mounted first time
    useEffect(() => {
        // here onValue will get initialized once
        // and on db changes its callback will get invoked
        // resulting in changing your state value
        onValue(ref(db, `users/${uid}`), snapshot => {
            const data = snapshot.val();
            setUserinfo(data);
        })
        return () => {
            // this is cleanup function, will call just on component will unmount
            // you can clear your events listeners or any async calls here
        }
    }, [])

    console.log(userinfo);

    return (
        <main id="home">
            <Hero />
        </main>
    )
}
</code>```

Note - I have not worked with firebase real-time DB recently but by looking at the code and error I have added this answer, let me know if anything needs correction.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Firebase realtime database for my react project. I try to follow the firebase documentation and use "onValue()" to retrieve data. Here is my code:

export default function Home() {

    const {currentUser} = useAuth();
    const [userinfo,setUserinfo] = React.useState();

    const uid = currentUser.uid
    const db = getDatabase();

    onValue(ref(db,`users/${uid}`),snapshot=>{
        const data = snapshot.val();
        setUserinfo(data);
    })

    console.log(userinfo);

    return (

        <Hero />

    )
}

This would result in an error of too many re-renders. I don't know how to retrieve the data. If I use

onValue(ref(db,`users/${uid}`),snapshot=>{
        const data = snapshot.val();
        console.log(data);
    })

then the proper data would print out in the console perfectly fine. I also tried the following:

let info;
onValue(ref(db,`users/${uid}`),snapshot=>{
        const data = snapshot.val();
        info = data;
    })
console.log(info)

but info would just be undefined. I can't seem to figure out the problem here. How can I use the data?

Body:
It throws error too many re-renders because you are not using any lifecycle hook or function to update/change state value and once you update your state it will again re-render your whole component and then again you update the state and the same thing happens in the loop causing too many re-renders.

So to avoid this you need to put code that is responsible for listening to changes from DB and changing state inside a block which will only get called on specific events or function calls or etc.

In your case, I suggest using useEffect hook. see below code -

export default function Home() {

    const { currentUser } = useAuth();
    const [userinfo, setUserinfo] = React.useState();

    const uid = currentUser.uid
    const db = getDatabase();

    // this useEffect will get called only
    // when component gets mounted first time
    useEffect(() => {
        // here onValue will get initialized once
        // and on db changes its callback will get invoked
        // resulting in changing your state value
        onValue(ref(db, `users/${uid}`), snapshot => {
            const data = snapshot.val();
            setUserinfo(data);
        })
        return () => {
            // this is cleanup function, will call just on component will unmount
            // you can clear your events listeners or any async calls here
        }
    }, [])

    console.log(userinfo);

    return (
        <main id="home">
            <Hero />
        </main>
    )
}

Note - I have not worked with firebase real-time DB recently but by looking at the code and error I have added this answer, let me know if anything needs correction.


问:
Loop live update Julia plot
I'm brand new to Julia (v1.7.1) and I've been using VSCode as an IDE. In VSCode (v1.64) I've installed the Julia Extension (v1.5.10). When plotting in VSCode, the plot shows up in the plot pane by default. I'm using the Plots (v1.25.7) package and the "gr" backend, as it's one of the "faster" options.

I'm trying to make a "live" time series plot, in which the series is updated in a loop. This seems to be a popular problem, as there are many questions addressing this, but I've found no "clean" solution yet. I should emphasize that I'm not trying to make an animation, which is fabricated upon termination of the loop. I want to update the plot as the loop is running. I've looked at SmoothLivePlot, but I think this requires that I know the series size before hand, which is not the case in my application. Then again, maybe I'm misinterpreting the package.

I'm going to present what I've done this far, with hopes for improvement. I first created a plotting function

```<code>function plt_update(p,time_series,var_series)
    plot!(time_series, var_series,
        label = "",
        linecolor = :red)
    display(p)
end
</code>```

Then I initialized the plot

```<code>model_time = 100
p = plot([0.0],[0.0],
    label = "",
    linecolor = :red,
    xlims = (0, model_time),
    ylims = (0, 1),

display(p)
</code>```

My loop is then called (NOTE: that all the code shown in this post is wrapped in a function and run in the RPEL, hence variables do not need to be defined with "global" inside the while loop. This is due to Julia's optimization and scope design...from what I've read. See another discussion on this for an example).

```<code>run_time = 0.0
time_series = [0.0]
var_series = [0.0]
while run_time < model_time

    # Calculate new timestep
    timestep = rand(Float64)  # Be sure to add Random
    run_time += timestep

    # Computations
    sleep(timestep/10)

    # Build vector
    push!(time_series,run_time)
    push!(var_series,timestep)

    # Live plots
    plt_update(p,time_series,var_series)

end
</code>```

I've encountered a few problems with this. First, I don't know if this is just an issue with VSCode or who to point the finger at, but putting display(p) inside the function to update the plot in the VSCode plot pane ends up creating a new plot for each iteration in the loop. Clearly this is not what is intended. I found that if I shut off the "plot in pane" option (File > Preferences > Settings > Extensions > Julia), then a single plot window is created. I'm not sure if "create new plot in pane" is expected or an issue (again, I'm new to this). Nevertheless, when plotting outside the VSCode, the above code works as I expected.

For the next issue, which I think is most important here, is that inside the plotting function, the call to plot! adds a new vector to p, while saving the previous one as well. In other words, p is not being updated with the new series, it is growing by appending a whole new vector. This is clear as the plotting comes to a grinding halt after many iterations. Also, if you remove the "color" attribute, you'll see the line changes color with each iteration. In effect, what is being plotted is many lines, all overlapping.

I then dove into p to look more closely at what is going on and made some changes to the plotting function

```<code>function plt_update(p,time_series,var_series)
    push!(p.series_list[1].plotattributes[:x],time_series[:][end])
    push!(p.series_list[1].plotattributes[:y],var_series[:][end])
    display(p)
end
</code>```

Above, instead of creating a new series_list (as was the case before w/ plot!), I'm now updating the series w/ the new data. This works much better than before and behaves as expected. While it's only a slight improvement, I've further modified the function and the function call by passing a scalar instead of a vecotr

```<code>function plt_update(p,run_time,variable)
    push!(p.series_list[1].plotattributes[:x],run_time)
    push!(p.series_list[1].plotattributes[:y],variable)
    display(p)
end
</code>```

in which the function call is now plt_update(p,run_time,timestep). As you can see, I sleep for a random time then divide that by 10, which I found to be about as much lag as I can afford before it loses it's "near realtime" appeal. Dividing by 100, for example, results in rather noticeable lag.

So my question is...is there a way to improve this, where the lag is reduced? Being new to Julia, I'm not aware of all the plotting options or how to access the "guts" to make improvements on my own.

EDIT:

I've just become aware of "Makie" and "Observables". I'm going to do a bit more research on those to see if this offers an improvement in the latency.

EDIT2:

In my research, I found a much cleaner way to express the last function (also see here for further confirmation of the approach)

```<code>function plt_update(p,run_time,variable)
    push!(p,1,run_time,variable)
    display(p)
end
</code>```

答:
The solution I found w/ Makie & observables is without a doubt the best! Between the YouTube video and code, I was able to apply it to my example above. Granted, my loop is only ~150 iterations, there is negligible lag (which was far from the case prior). Taking out the sleep function, the plot is instantaneous. I would encourage others to try this approach for "near real-time" plots.

The packages needed are

```<code>using GLMakie
using GeometryTypes
</code>```

I'm not sure if GeometryTypes is needed explicitly (I thought GLMakie would bring in the necessary libs), but I was getting an error stating that Point2f was not found.

First, create the observable (note that it's a vector of type Point2f)

```<code>pt_series = Observable([Point2f(0, 0)])
</code>```

Then initialize the plot

```<code>fig = Figure(); display(fig)
ax = Axis(fig[1,1])

lines!(ax, pt_series; linewidth = 4, color = :purple)

# Static elements
ax.title = "Time Series"
ax.xlabel = "Time (s)"
ax.ylabel = "Data"
xlims!(ax, 0, 100)
ylims!(ax, 0, 1)
</code>```

Then run the loop

```<code>model_time = 100
run_time = 0.0
while run_time < model_time

    # Calculate new timestep
    timestep = rand(Float64)
    run_time += timestep

    # Computations
    #sleep(timestep/1000)

    # Live plots
    push!(pt_series[], Point2f(run_time, timestep))
    notify(pt_series) # let the observable know that a change has happened

end
</code>```

As I stated in the question, all of the code above should be wrapped in a function to prevent scoping errors.

Title: Loop live update Julia plot

Body:
I'm brand new to Julia (v1.7.1) and I've been using VSCode as an IDE. In VSCode (v1.64) I've installed the Julia Extension (v1.5.10). When plotting in VSCode, the plot shows up in the plot pane by default. I'm using the Plots (v1.25.7) package and the "gr" backend, as it's one of the "faster" options.

I'm trying to make a "live" time series plot, in which the series is updated in a loop. This seems to be a popular problem, as there are many questions addressing this, but I've found no "clean" solution yet. I should emphasize that I'm not trying to make an animation, which is fabricated upon termination of the loop. I want to update the plot as the loop is running. I've looked at SmoothLivePlot, but I think this requires that I know the series size before hand, which is not the case in my application. Then again, maybe I'm misinterpreting the package.

I'm going to present what I've done this far, with hopes for improvement. I first created a plotting function

function plt_update(p,time_series,var_series)
    plot!(time_series, var_series,
        label = "",
        linecolor = :red)
    display(p)
end

Then I initialized the plot

model_time = 100
p = plot([0.0],[0.0],
    label = "",
    linecolor = :red,
    xlims = (0, model_time),
    ylims = (0, 1),

display(p)

My loop is then called (NOTE: that all the code shown in this post is wrapped in a function and run in the RPEL, hence variables do not need to be defined with "global" inside the while loop. This is due to Julia's optimization and scope design...from what I've read. See another discussion on this for an example).

run_time = 0.0
time_series = [0.0]
var_series = [0.0]
while run_time < model_time

    # Calculate new timestep
    timestep = rand(Float64)  # Be sure to add Random
    run_time += timestep

    # Computations
    sleep(timestep/10)

    # Build vector
    push!(time_series,run_time)
    push!(var_series,timestep)

    # Live plots
    plt_update(p,time_series,var_series)

end

I've encountered a few problems with this. First, I don't know if this is just an issue with VSCode or who to point the finger at, but putting display(p) inside the function to update the plot in the VSCode plot pane ends up creating a new plot for each iteration in the loop. Clearly this is not what is intended. I found that if I shut off the "plot in pane" option (File > Preferences > Settings > Extensions > Julia), then a single plot window is created. I'm not sure if "create new plot in pane" is expected or an issue (again, I'm new to this). Nevertheless, when plotting outside the VSCode, the above code works as I expected.

For the next issue, which I think is most important here, is that inside the plotting function, the call to plot! adds a new vector to p, while saving the previous one as well. In other words, p is not being updated with the new series, it is growing by appending a whole new vector. This is clear as the plotting comes to a grinding halt after many iterations. Also, if you remove the "color" attribute, you'll see the line changes color with each iteration. In effect, what is being plotted is many lines, all overlapping.

I then dove into p to look more closely at what is going on and made some changes to the plotting function

function plt_update(p,time_series,var_series)
    push!(p.series_list[1].plotattributes[:x],time_series[:][end])
    push!(p.series_list[1].plotattributes[:y],var_series[:][end])
    display(p)
end

Above, instead of creating a new series_list (as was the case before w/ plot!), I'm now updating the series w/ the new data. This works much better than before and behaves as expected. While it's only a slight improvement, I've further modified the function and the function call by passing a scalar instead of a vecotr

function plt_update(p,run_time,variable)
    push!(p.series_list[1].plotattributes[:x],run_time)
    push!(p.series_list[1].plotattributes[:y],variable)
    display(p)
end

in which the function call is now plt_update(p,run_time,timestep). As you can see, I sleep for a random time then divide that by 10, which I found to be about as much lag as I can afford before it loses it's "near realtime" appeal. Dividing by 100, for example, results in rather noticeable lag.

So my question is...is there a way to improve this, where the lag is reduced? Being new to Julia, I'm not aware of all the plotting options or how to access the "guts" to make improvements on my own.

EDIT:

I've just become aware of "Makie" and "Observables". I'm going to do a bit more research on those to see if this offers an improvement in the latency.

EDIT2:

In my research, I found a much cleaner way to express the last function (also see here for further confirmation of the approach)

function plt_update(p,run_time,variable)
    push!(p,1,run_time,variable)
    display(p)
end

Body:
The solution I found w/ Makie & observables is without a doubt the best! Between the YouTube video and code, I was able to apply it to my example above. Granted, my loop is only ~150 iterations, there is negligible lag (which was far from the case prior). Taking out the sleep function, the plot is instantaneous. I would encourage others to try this approach for "near real-time" plots.

The packages needed are

using GLMakie
using GeometryTypes

I'm not sure if GeometryTypes is needed explicitly (I thought GLMakie would bring in the necessary libs), but I was getting an error stating that Point2f was not found.

First, create the observable (note that it's a vector of type Point2f)

pt_series = Observable([Point2f(0, 0)])

Then initialize the plot

fig = Figure(); display(fig)
ax = Axis(fig[1,1])

lines!(ax, pt_series; linewidth = 4, color = :purple)

# Static elements
ax.title = "Time Series"
ax.xlabel = "Time (s)"
ax.ylabel = "Data"
xlims!(ax, 0, 100)
ylims!(ax, 0, 1)

Then run the loop

model_time = 100
run_time = 0.0
while run_time < model_time

    # Calculate new timestep
    timestep = rand(Float64)
    run_time += timestep

    # Computations
    #sleep(timestep/1000)

    # Live plots
    push!(pt_series[], Point2f(run_time, timestep))
    notify(pt_series) # let the observable know that a change has happened

end

As I stated in the question, all of the code above should be wrapped in a function to prevent scoping errors.


问:
How do you make a bot that sends embed welcome messages?
I currently am having trouble running this code it used to stop the bot/replit when a person joins the bot/replit now it declares it as an empty message</p>
```<code>let Discord = require("discord.js");
let client = new Discord.Client();

client.on("ready", () => {
  client.user.setPresence({ 'activity': { name: "Test}})
})

client.on('guildMemberAdd', member => {
 const embed = new Discord.MessageEmbed()
 .setTitle(`Welcome ${member.user.tag}!`)
 .setDescription(`You are member ${member.guild.memberCount}`)
  const channel = member.guild.channels.cache.find(ch => ch.name ===   'welcome-channel')
  channel.send({
    embeds: [embed]
  })
})

client.login("")
</code>```

答:
You can use client.on('guildMemberAdd') and this for the embed =>

client.on('guildMemberAdd', member => {
  const embed = new MessageEmbed()
    .setTitle(`Welcome ${member.user.tag}!`)
    .setDescription(`You are member ${member.guild.memberCount}!`)
  const channel = member.guild.channels.cache.find(ch => ch.name === 'welcome-channel')
  channel.send({
    embeds: [embed]
  })
})```

Body:
I currently am having trouble running this code it used to stop the bot/replit when a person joins the bot/replit now it declares it as an empty message

let Discord = require("discord.js");
let client = new Discord.Client();

client.on("ready", () => {
  client.user.setPresence({ 'activity': { name: "Test}})
})

client.on('guildMemberAdd', member => {
 const embed = new Discord.MessageEmbed()
 .setTitle(`Welcome ${member.user.tag}!`)
 .setDescription(`You are member ${member.guild.memberCount}`)
  const channel = member.guild.channels.cache.find(ch => ch.name ===   'welcome-channel')
  channel.send({
    embeds: [embed]
  })
})

client.login("")


问:
Google Drive API: "contains" does not match string in middle in files().list(q="name contains 'SMITH'")?
I have a folder named SMITH_JOHN TAYLER_DAVID, I can only search SMITH or TAYLER but not any other ways, i.e.:

```<code>files().list(q="name contains 'SMITH'")  => OK
files().list(q="name contains 'TAYLER'") => OK
files().list(q="name contains 'JOHN'")   => No match!
files().list(q="name contains 'DAVID'")  => No match!
files().list(q="name contains 'MITH'")   => No match!
</code>```

So looks like that I can only search word from the beginning of the folder name or after a space. This happens to you as well? What does "contains" mean in the REST API and how does the Python implemented this (perhaps using "match" instead of "search")?

答:
So looks like that I can only search word from the beginning of the folder name or after a space. This happens to you as well?

In my environment, I confirmed the same situation with you. In your situation, the folder name is SMITH_JOHN TAYLER_DAVID. I thought that in this case, _ might be the reason for this issue. For example, when the folder name is SMITH JOHN TAYLER DAVID, your all search queries can retrieve the folder. It seems that the top letter and the letter after a space can be searched. I thought that this might be the current specification.

What does "contains" mean in the REST API and how does the Python implemented this (perhaps using "match" instead of "search")?

This is used as the search query. Ref This search query is used for the method of "Files: list".

For example, if you want to retrieve the folder of the folder name of SMITH_JOHN TAYLER_DAVID by searching the values of 'SMITH','TAYLER','JOHN','DAVID','MITH' instead of the search query of name='SMITH_JOHN TAYLER_DAVID', you can use the following flow.

Retrieve the folder list using the search query of name contains 'SMITH' and mimeType='application/vnd.google-apps.folder' and trashed=false.

By this, the folder list includes SMITH.

Retrieve the folder by searching the values of 'SMITH','TAYLER','JOHN','DAVID','MITH' from the retrieved folder list.

By this flow, the folder of SMITH_JOHN TAYLER_DAVID can be retrieved by one API call. When this flow is reflected in a sample script using googleapis for python, it becomes as follows.

Sample script:

```<code>drive_service = build('drive', 'v3', credentials=creds) # Please use your credential.

q = "name contains 'SMITH' and mimeType='application/vnd.google-apps.folder' and trashed=false"
response = drive_service.files().list(q=q, fields='files(id, name)', pageSize=1000).execute()
search = ['TAYLER', 'JOHN', 'DAVID', 'MITH']
for file in response.get('files'):
    name = file.get('name')
    if all(e for e in search if e in name):
        print(name)
</code>```

When this script is run, the folder of SMITH_JOHN TAYLER_DAVID can be obtained.

In this sample, it supposes that the number of folders including the value of SMITH is less than 1000. Please be careful about this.

References:

Files: list

Search for files and folders

Body:
I have a folder named SMITH_JOHN TAYLER_DAVID, I can only search SMITH or TAYLER but not any other ways, i.e.:

files().list(q="name contains 'SMITH'")  => OK
files().list(q="name contains 'TAYLER'") => OK
files().list(q="name contains 'JOHN'")   => No match!
files().list(q="name contains 'DAVID'")  => No match!
files().list(q="name contains 'MITH'")   => No match!

So looks like that I can only search word from the beginning of the folder name or after a space. This happens to you as well? What does "contains" mean in the REST API and how does the Python implemented this (perhaps using "match" instead of "search")?

Body:
So looks like that I can only search word from the beginning of the folder name or after a space. This happens to you as well?

In my environment, I confirmed the same situation with you. In your situation, the folder name is SMITH_JOHN TAYLER_DAVID. I thought that in this case, _ might be the reason for this issue. For example, when the folder name is SMITH JOHN TAYLER DAVID, your all search queries can retrieve the folder. It seems that the top letter and the letter after a space can be searched. I thought that this might be the current specification.

What does "contains" mean in the REST API and how does the Python implemented this (perhaps using "match" instead of "search")?

This is used as the search query. Ref This search query is used for the method of "Files: list".

For example, if you want to retrieve the folder of the folder name of SMITH_JOHN TAYLER_DAVID by searching the values of 'SMITH','TAYLER','JOHN','DAVID','MITH' instead of the search query of name='SMITH_JOHN TAYLER_DAVID', you can use the following flow.

Retrieve the folder list using the search query of name contains 'SMITH' and mimeType='application/vnd.google-apps.folder' and trashed=false.

By this, the folder list includes SMITH.

Retrieve the folder by searching the values of 'SMITH','TAYLER','JOHN','DAVID','MITH' from the retrieved folder list.

By this flow, the folder of SMITH_JOHN TAYLER_DAVID can be retrieved by one API call. When this flow is reflected in a sample script using googleapis for python, it becomes as follows.

Sample script:

drive_service = build('drive', 'v3', credentials=creds) # Please use your credential.

q = "name contains 'SMITH' and mimeType='application/vnd.google-apps.folder' and trashed=false"
response = drive_service.files().list(q=q, fields='files(id, name)', pageSize=1000).execute()
search = ['TAYLER', 'JOHN', 'DAVID', 'MITH']
for file in response.get('files'):
    name = file.get('name')
    if all(e for e in search if e in name):
        print(name)

When this script is run, the folder of SMITH_JOHN TAYLER_DAVID can be obtained.

In this sample, it supposes that the number of folders including the value of SMITH is less than 1000. Please be careful about this.

References:

Files: list

Search for files and folders


问:
Data get repeated with json_arrayagg
The output getting from the query id repeated it the data inside is multiple

```<code>select json_arrayagg(json_object("network", basics_profiles.network, "username", basics_profiles.username, "url", basics_profiles.url)) as profiles from basics_profiles;
</code>```

Ok here when i run this code  the in work section even when there it is only 2 data. it get doubled. if there was only single data. then there is no issue.

output while there is more tan 1 data:

```<code>[
    {
        "url": "twitter.com/naruto",
        "network": "Twitter",
        "username": "uzumakinaruto"
    },
    {
        "url": "twitter.com/naruto",
        "network": "Twitter",
        "username": "uzumakinaruto"
    },
    {
        "url": "instagram.com/naruto",
        "network": "Instagram",
        "username": "uzumakinaruto"
    },
    {
        "url": "instagram.com/naruto",
        "network": "Instagram",
        "username": "uzumakinaruto"
    }
]
</code>```

i wanted something like this

```<code>[
    {
        "url": "twitter.com/naruto",
        "network": "Twitter",
        "username": "uzumakinaruto"
    },
    {
        "url": "instagram.com/naruto",
        "network": "Instagram",
        "username": "uzumakinaruto"
    }
]
</code>```

u can try with the thsi table:

```<code>create table basics_profiles(network text, url text, username text);

insert into basics_profiles values("twitter","jhaajdka.com","naruto");

insert into basics_profiles values("instagram","jhasdasdasdsdd.com","sasuke");
</code>```

答:
Thanks for Helping me out. i got my issue. With the about code it was showing all the data in a single row if i had multiple row of data, for me the issue was when joining 2 tables the data get repeated again and again.</p>
```<code>select
   basics_information.*,
   (select json_arrayagg(json_object("name", interests.name, "keywords", interests.keywords))
    from interests
    where basics_information.id = interests.resumeId) as interests
from basics_information
left join interests on basics_information.id = interests.resumeId
group by basics_information.id;
</code>```

Title: Data get repeated with json_arrayagg

Body:
The output getting from the query id repeated it the data inside is multiple

select json_arrayagg(json_object("network", basics_profiles.network, "username", basics_profiles.username, "url", basics_profiles.url)) as profiles from basics_profiles;

Ok here when i run this code  the in work section even when there it is only 2 data. it get doubled. if there was only single data. then there is no issue.

output while there is more tan 1 data:

[
    {
        "url": "twitter.com/naruto",
        "network": "Twitter",
        "username": "uzumakinaruto"
    },
    {
        "url": "twitter.com/naruto",
        "network": "Twitter",
        "username": "uzumakinaruto"
    },
    {
        "url": "instagram.com/naruto",
        "network": "Instagram",
        "username": "uzumakinaruto"
    },
    {
        "url": "instagram.com/naruto",
        "network": "Instagram",
        "username": "uzumakinaruto"
    }
]

i wanted something like this

[
    {
        "url": "twitter.com/naruto",
        "network": "Twitter",
        "username": "uzumakinaruto"
    },
    {
        "url": "instagram.com/naruto",
        "network": "Instagram",
        "username": "uzumakinaruto"
    }
]

u can try with the thsi table:

create table basics_profiles(network text, url text, username text);

insert into basics_profiles values("twitter","jhaajdka.com","naruto");

insert into basics_profiles values("instagram","jhasdasdasdsdd.com","sasuke");

Body:
Thanks for Helping me out. i got my issue. With the about code it was showing all the data in a single row if i had multiple row of data, for me the issue was when joining 2 tables the data get repeated again and again.

select
   basics_information.*,
   (select json_arrayagg(json_object("name", interests.name, "keywords", interests.keywords))
    from interests
    where basics_information.id = interests.resumeId) as interests
from basics_information
left join interests on basics_information.id = interests.resumeId
group by basics_information.id;


问:
Why wont the ../ file path work in css and html?
You see, whenever I try to use ../ in CSS or HTML, it doesn't appear to work, It just gives me this error: GET file:///C:/Users/MYUSERNAME/Desktop/Coin%20Clicker/source/coin.png net::ERR_FILE_NOT_FOUND even though I used ../images/. Keep in mind coin.png is in images, not source. However, if I do this in javascript, which is in a different file than the HTML file, it does appear to work. Any idea why this occurs? here is my code:

CSS:

#coin {
  background-image: url("../images/coin.png");
  border: none;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 200px 200px;
  background-color: white;
  border-radius: 50%;
  width: 200px;
  height: 200px;
}
#coin:active {
  background-image: url("../images/coin-pressed-in.png");
}
```
<p>HTML:</p>
<pre class="lang-html prettyprint-override"><code><div>
  <span id="count">0¢</span>
</div>

  <button id="coin" alt="coin" onclick="plusOne()"></button>

<script src="script.js"></script>
</code>```

javascript:

var dollar = 0;
var cents = 0;
var count = document.getElementById("count");

function plusOne() {
  if (cents < 95) {
    cents +=5;
    count.innerHTML = cents + " ¢";
  } else if (cents == 95) {
    dollar = 1;
    cents = 100;
    count.innerHTML = dollar + " $";
  } else if (dollar >= 1) {
    dollar += 0.05;
    count.innerHTML = round(dollar, 2) + " $";
  }
}

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

document.getElementById("favicon").href = "coin.png";

document.addEventListener("visibilitychange", (event) => {
  if (document.visibilityState == "visible") {
    document.getElementById("favicon").href = "../images/coin.png";
  } else {
    document.getElementById("favicon").href = "../images/coin-disabled.png";
  }
});
```
<p>File directory:</p>
<pre class="lang-none prettyprint-override"><code>- images/
    * coin.png
    * coin-disabled.png
    * coin-pressed-in.png
- source/
    * coin.html
    * script.js
</code>```

答:
It seems your root folder (The folder designated as the origin for your project is source). This is evidenced by the filenotfound error showcasing it is looking for the image in the source folder, not the images folder. You have a few options:

Move the images folder INSIDE the source folder
Change the Project folder to Coin%20Clicker
Move the images folder INSIDE the source folder AND make a separate folder for the html and js to keep them separated.

Body:
You see, whenever I try to use ../ in CSS or HTML, it doesn't appear to work, It just gives me this error: GET file:///C:/Users/MYUSERNAME/Desktop/Coin%20Clicker/source/coin.png net::ERR_FILE_NOT_FOUND even though I used ../images/. Keep in mind coin.png is in images, not source. However, if I do this in javascript, which is in a different file than the HTML file, it does appear to work. Any idea why this occurs? here is my code:

CSS:

#coin {
  background-image: url("../images/coin.png");
  border: none;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 200px 200px;
  background-color: white;
  border-radius: 50%;
  width: 200px;
  height: 200px;
}
#coin:active {
  background-image: url("../images/coin-pressed-in.png");
}

HTML:

  0¢

  <button id="coin" alt="coin" onclick="plusOne()"></button>

javascript:

var dollar = 0;
var cents = 0;
var count = document.getElementById("count");

function plusOne() {
  if (cents < 95) {
    cents +=5;
    count.innerHTML = cents + " ¢";
  } else if (cents == 95) {
    dollar = 1;
    cents = 100;
    count.innerHTML = dollar + " $";
  } else if (dollar >= 1) {
    dollar += 0.05;
    count.innerHTML = round(dollar, 2) + " $";
  }
}

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

document.getElementById("favicon").href = "coin.png";

document.addEventListener("visibilitychange", (event) => {
  if (document.visibilityState == "visible") {
    document.getElementById("favicon").href = "../images/coin.png";
  } else {
    document.getElementById("favicon").href = "../images/coin-disabled.png";
  }
});

File directory:

- images/
    * coin.png
    * coin-disabled.png
    * coin-pressed-in.png
- source/
    * coin.html
    * script.js


问:
Trying to run a calculation inside an if-else statement and it's stalling - C
I'm in an introductory code class for C and I'm trying to run this square and cube calculation if a number greater than 1 is entered, but it stalls if I run it. I'm not getting any errors and I've tried different ways to make this work through tips here, but nothing is happening and I don't know enough to get what's wrong.</p>
```<code>#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", &square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}
</code>```

答:
```<code>#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", &num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }
    else
        printf("\nPlease enter a number greater than 1.");

    return 0;
}
</code>```

printf("%d", num); you made mistake use printf("%d", num); when you use Address operator & in print statement it will print address not value so

```<code>printf("%d", square); // remove & sign
</code>```

Also put last print statement under else otherwise it will run everytime

Why we should use ampersand (&) in scanf. The ampersand (&) allows us to pass the address of variable number which is the place in memory where we store the information that scanf read.

Body:
I'm in an introductory code class for C and I'm trying to run this square and cube calculation if a number greater than 1 is entered, but it stalls if I run it. I'm not getting any errors and I've tried different ways to make this work through tips here, but nothing is happening and I don't know enough to get what's wrong.

#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", &square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}

Body:
#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", &num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }
    else
        printf("\nPlease enter a number greater than 1.");

    return 0;
}

printf("%d", num); you made mistake use printf("%d", num); when you use Address operator & in print statement it will print address not value so

printf("%d", square); // remove & sign

Also put last print statement under else otherwise it will run everytime

Why we should use ampersand (&) in scanf. The ampersand (&) allows us to pass the address of variable number which is the place in memory where we store the information that scanf read.


问:
If two consecutive cells are blank then second cell equals value
I was able to get this much working but not able to get it to start from Range("B12:B500").</p>
```<code>Sub findTwoEmptyCells()
Dim lastRow As Long, i As Long
Dim firstEmptyCell As Range

lastRow = Cells(Rows.Count, 2).End(xlUp).Row

For i = 1 To lastRow
If Cells(i, 1).Value = "" And Cells(i, 1).Offset(1, 0).Value = "" Then
    Set firstEmptyCell = Cells(i, 1)
    Exit For
End If
Next i

End If

firstEmptyCell.Value = "x"

End Sub
</code>```

答:
Thanks to @Dominique & @FaneDuru, i was able to get the result as per the below by combining both their ideas :</p>
```<code>Sub findTwoEmptyCells()
Dim lastRow As Long, i As Long
Dim firstEmptyCell As Range

lastRow = Cells(Rows.Count, 12).End(xlUp).Row

For i = 12 To lastRow
If Cells(i, 2).Value = "" And Cells(i + 1, 1).Value = "" Then
    Set firstEmptyCell = Cells(i, 1)
    Exit For
End If
Next i

If firstEmptyCell Is Nothing Then
MsgBox ("There are no two empty cells in a row")
Exit Sub
End If

firstEmptyCell.Value = "x"

End Sub
</code>```

Body:
I was able to get this much working but not able to get it to start from Range("B12:B500").

Sub findTwoEmptyCells()
Dim lastRow As Long, i As Long
Dim firstEmptyCell As Range

lastRow = Cells(Rows.Count, 2).End(xlUp).Row

For i = 1 To lastRow
If Cells(i, 1).Value = "" And Cells(i, 1).Offset(1, 0).Value = "" Then
    Set firstEmptyCell = Cells(i, 1)
    Exit For
End If
Next i

End If

firstEmptyCell.Value = "x"

End Sub

Body:
Thanks to @Dominique & @FaneDuru, i was able to get the result as per the below by combining both their ideas :

Sub findTwoEmptyCells()
Dim lastRow As Long, i As Long
Dim firstEmptyCell As Range

lastRow = Cells(Rows.Count, 12).End(xlUp).Row

For i = 12 To lastRow
If Cells(i, 2).Value = "" And Cells(i + 1, 1).Value = "" Then
    Set firstEmptyCell = Cells(i, 1)
    Exit For
End If
Next i

If firstEmptyCell Is Nothing Then
MsgBox ("There are no two empty cells in a row")
Exit Sub
End If

firstEmptyCell.Value = "x"

End Sub


问:
Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.?
My code show error  Firebase has not been correctly initialized.?

```<code>**Usually this means you've attempted to use a Firebase service before calling `Firebase.initializeApp`.
E/flutter (25616):
E/flutter (25616): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization
E/flutter (25616):
E/flutter (25616): #0      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)
E/flutter (25616): <asynchronous suspension>
E/flutter (25616): #1      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)
E/flutter (25616): <asynchronous suspension>
E/flutter (25616): #2      main (package:a_store_online_shop/main.dart:11:3)
E/flutter (
25616): <asynchronous suspension>
E/flutter (25616):
</code>```

It is our main.dart file which in occure error code firebase has not been correctly initialized.....................................................................................................................................................?

main.dart

```<code>import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:a_store_online_shop/Screens/main_screen.dart';
import 'package:a_store_online_shop/Screens/on_boarding_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get_storage/get_storage.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await GetStorage.init();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      // title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SplashScreen(),
      initialRoute: SplashScreen.id,
      routes: {
        SplashScreen.id: (context) => const SplashScreen(),
        OnBoardingScreen.id: (context) => const OnBoardingScreen(),
      },
    );
  }
}

class SplashScreen extends StatefulWidget {
  const SplashScreen({Key? key}) : super(key: key);
  static const String id = "splash-screen";

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  final store = GetStorage();
  @override
  void initState() {
    Timer(const Duration(seconds: 3), () {
      bool? _boarding = store.read('onBoarding');
      _boarding == null
          ? Navigator.pushReplacementNamed(context, OnBoardingScreen.id)
          : _boarding == true
              ? Navigator.pushReplacementNamed(context, MainScreen.id)
              : Navigator.pushReplacementNamed(context, OnBoardingScreen.id);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge, overlays: []);
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
        child: Image.asset("assets/images/logo.jpg"),
      ),
    );
  }
}
</code>```

答:
So for everybody else getting this error I figured it out myself, for IOS, the line

```<code>Firebase.initializeApp()
</code>```

it needs an option:

```<code>Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform)
</code>```

for that follow the instructions on this link:

https://firebase.flutter.dev/docs/cli

Body:
My code show error  Firebase has not been correctly initialized.?

**Usually this means you've attempted to use a Firebase service before calling `Firebase.initializeApp`.
E/flutter (25616):
E/flutter (25616): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization
E/flutter (25616):
E/flutter (25616): #0      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)
E/flutter (25616): <asynchronous suspension>
E/flutter (25616): #1      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)
E/flutter (25616): <asynchronous suspension>
E/flutter (25616): #2      main (package:a_store_online_shop/main.dart:11:3)
E/flutter (
25616): <asynchronous suspension>
E/flutter (25616):

It is our main.dart file which in occure error code firebase has not been correctly initialized.....................................................................................................................................................?

main.dart

import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:a_store_online_shop/Screens/main_screen.dart';
import 'package:a_store_online_shop/Screens/on_boarding_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get_storage/get_storage.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await GetStorage.init();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      // title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SplashScreen(),
      initialRoute: SplashScreen.id,
      routes: {
        SplashScreen.id: (context) => const SplashScreen(),
        OnBoardingScreen.id: (context) => const OnBoardingScreen(),
      },
    );
  }
}

class SplashScreen extends StatefulWidget {
  const SplashScreen({Key? key}) : super(key: key);
  static const String id = "splash-screen";

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  final store = GetStorage();
  @override
  void initState() {
    Timer(const Duration(seconds: 3), () {
      bool? _boarding = store.read('onBoarding');
      _boarding == null
          ? Navigator.pushReplacementNamed(context, OnBoardingScreen.id)
          : _boarding == true
              ? Navigator.pushReplacementNamed(context, MainScreen.id)
              : Navigator.pushReplacementNamed(context, OnBoardingScreen.id);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge, overlays: []);
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
        child: Image.asset("assets/images/logo.jpg"),
      ),
    );
  }
}

Body:
So for everybody else getting this error I figured it out myself, for IOS, the line

Firebase.initializeApp()

it needs an option:

Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform)

for that follow the instructions on this link:

https://firebase.flutter.dev/docs/cli


问:
What are the 'rules' for names with getters/settings in a class?
What are the restrictions on using getters and setters in javascript? For example, here are a few scenarios I've seen when just doing trial-and-error:

class User {

    // 1 - must have an alias somewhere or will get loop
    constructor(name) {
        this.name = name;
    }

    get name() {
        console.log('--- Getter ---');
        return this.name;
    }
    set name(name) {
        console.log('--- Setter --- ');
        this.name = name;
    }
}

const user = new User('David');
console.log(user.name);```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class User {

    name;

    // 2 - setter/getter must have a property with exact name in constructor?
    constructor(name) {
        this._name = name;
    }
    get name() {
        console.log('--- Getter ---');
        return this._name;
    }
    set name(name) {
        console.log('--- Setter --- ');
        this._name = name;
    }
}

const user = new User('David');
console.log(user.name);
user.name = 'Keith';
console.log(user.name);</code>```

Is a correct understanding of a setter/getter that:

The name must be aliased.

The setter/getter must have that exact name defined in the constructor.

Finally, putting it all togther, does the following seem like a good pattern to hide fields when user a getter/setter, as it seems like #name (private) and name (public) act like two different variables.

class User {
    #name;
    constructor(name) {
        this.name = name;
    }
    get name() {
        console.log('-getter-');
        return this.#name;
    }
    set name(name) {
        console.log('-setter-');
        this.#name = name
    }
}
bob = new User('Bob');
bob.name = 'Bobby';
console.log(bob.name);```

答:
Giving a stab at the comments from @Bergi:

[ From question, incorrect assumption that] "The setter/getter must have that exact name defined in the constructor."

No, A constructor does not need to assign the property at all; you can also leave it uninitialised.

class Person {
    name;
    set name(y) {
        console.log('setName');
        this.name = y;
    }
    get name() {
        console.log('getName');
        return this.name;
    }
}
let bob = new Person();
bob.name = 'Bob'
console.log(bob.name);```
</div>
</div>
</p>
<ol start="2">
<li>Or even initialise the underlying <code>._name</code> directly.</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Person {
    constructor(x) {
        this.someOtherName = x;
    }
    set name(y) {
        console.log('setName');
        this.someOtherName = y;
    }
    get name() {
        console.log('getName');
        return this.someOtherName;
    }
}
let bob = new Person();
bob.name = 'Bob'
console.log(bob.name);</code>```

Body:
What are the restrictions on using getters and setters in javascript? For example, here are a few scenarios I've seen when just doing trial-and-error:

class User {

    // 1 - must have an alias somewhere or will get loop
    constructor(name) {
        this.name = name;
    }

    get name() {
        console.log('--- Getter ---');
        return this.name;
    }
    set name(name) {
        console.log('--- Setter --- ');
        this.name = name;
    }
}

const user = new User('David');
console.log(user.name);

class User {

    name;

    // 2 - setter/getter must have a property with exact name in constructor?
    constructor(name) {
        this._name = name;
    }
    get name() {
        console.log('--- Getter ---');
        return this._name;
    }
    set name(name) {
        console.log('--- Setter --- ');
        this._name = name;
    }
}

const user = new User('David');
console.log(user.name);
user.name = 'Keith';
console.log(user.name);

Is a correct understanding of a setter/getter that:

The name must be aliased.

The setter/getter must have that exact name defined in the constructor.

Finally, putting it all togther, does the following seem like a good pattern to hide fields when user a getter/setter, as it seems like #name (private) and name (public) act like two different variables.

class User {
    #name;
    constructor(name) {
        this.name = name;
    }
    get name() {
        console.log('-getter-');
        return this.#name;
    }
    set name(name) {
        console.log('-setter-');
        this.#name = name
    }
}
bob = new User('Bob');
bob.name = 'Bobby';
console.log(bob.name);

Body:
Giving a stab at the comments from @Bergi:

[ From question, incorrect assumption that] "The setter/getter must have that exact name defined in the constructor."

No, A constructor does not need to assign the property at all; you can also leave it uninitialised.

class Person {
    name;
    set name(y) {
        console.log('setName');
        this.name = y;
    }
    get name() {
        console.log('getName');
        return this.name;
    }
}
let bob = new Person();
bob.name = 'Bob'
console.log(bob.name);

Or even initialise the underlying ._name directly.

class Person {
    constructor(x) {
        this.someOtherName = x;
    }
    set name(y) {
        console.log('setName');
        this.someOtherName = y;
    }
    get name() {
        console.log('getName');
        return this.someOtherName;
    }
}
let bob = new Person();
bob.name = 'Bob'
console.log(bob.name);


问:
Replace variable markers with values from dictionary
I need to write a function that takes a string and a dictionary as input.

The string will be like Hello <name> and the function will return Hello value

where value is the mapping of character in the dictionary. How could I write a function to replace all such variable occurrences?

I couldn't find any way of writing a regex that would allow me to loop over the variables in angular brackets and replace them with dictionary values in python.

Sample Input and Output:

Key is the template, value is the expected output:

```<code>variables={
    "name": "Mars",
    "pet": "dog",
    "age": 22,
}
</code>```

Test cases.

```<code>test_cases={
    "Hello <name>!" : "Hello Mars!",
    # "Good day, <name>. You look happy <name>": "Good day, Mars. You look happy Mars",
    # "Good day, Miss": "Good day, Miss",
    # "Hello <name>. How is your <pet>": "Hello Mars. How is your dog",
    # "Hello <name>! I am <age>": "Hello Mars! I am 22",
    # "Hello <name! I am <age>":"Hello <name! I am 22",
    # "Hello <name!": "Hello <name!",
    # "Hello name>! I am <age>":"Hello name>! I am 22",
    # "Hello <<name>>!" : "Hello <Mars>!",
}
</code>```

My Thoughts:

I have tried simple looping over the string, and when a < is encountered, I store the characters in a separate variable till > is encountered and
 then fetch the value from the dictionary and add it to the final string. This seems to be working with some minimal flaws. But it gets messy with a lot of nested if-else statements

答:
You can replace values using regular expressions. The pattern contains a matching group (the part between the angular brackets) which can be used to look up the corresponding value in your variables dict:

text = "Hello <name>!"

result = re.sub(r'<([^>]+)>', lambda match: variables[match.group(1)], text)
```
<p>gives <code>'Hello Mars!'</code>.</p>
<p>You can also extract the replacement function to make it a bit clearer:</p>
<pre class="lang-py prettyprint-override"><code>def replace(match):
    keyword = match.group(1)
    return variables[keyword]

result = re.sub(r'<([^>]+)>', replace, text)
</code>```

Body:
I need to write a function that takes a string and a dictionary as input.

The string will be like Hello <name> and the function will return Hello value

where value is the mapping of character in the dictionary. How could I write a function to replace all such variable occurrences?

I couldn't find any way of writing a regex that would allow me to loop over the variables in angular brackets and replace them with dictionary values in python.

Sample Input and Output:

Key is the template, value is the expected output:

variables={
    "name": "Mars",
    "pet": "dog",
    "age": 22,
}

Test cases.

test_cases={
    "Hello <name>!" : "Hello Mars!",
    # "Good day, <name>. You look happy <name>": "Good day, Mars. You look happy Mars",
    # "Good day, Miss": "Good day, Miss",
    # "Hello <name>. How is your <pet>": "Hello Mars. How is your dog",
    # "Hello <name>! I am <age>": "Hello Mars! I am 22",
    # "Hello <name! I am <age>":"Hello <name! I am 22",
    # "Hello <name!": "Hello <name!",
    # "Hello name>! I am <age>":"Hello name>! I am 22",
    # "Hello <<name>>!" : "Hello <Mars>!",
}

My Thoughts:

I have tried simple looping over the string, and when a < is encountered, I store the characters in a separate variable till > is encountered and
 then fetch the value from the dictionary and add it to the final string. This seems to be working with some minimal flaws. But it gets messy with a lot of nested if-else statements

Body:
You can replace values using regular expressions. The pattern contains a matching group (the part between the angular brackets) which can be used to look up the corresponding value in your variables dict:

text = "Hello <name>!"

result = re.sub(r'<([^>]+)>', lambda match: variables[match.group(1)], text)

gives 'Hello Mars!'.

You can also extract the replacement function to make it a bit clearer:

def replace(match):
    keyword = match.group(1)
    return variables[keyword]

result = re.sub(r'<([^>]+)>', replace, text)


问:
jQuery Animate Question
I have a very basic function which I am using jQuery to slide some content either out (from left to right) or back in (from right to left). The code below works, however, what I am trying to do now is include the "+" at the end of my "overDiv", and make it so that it will always show.

To paint a more lucid picture, right now if you paste that code into your editor and include google's jQuery, you will see that clicking the "+" eliminates the "overDiv" block completely. However, what I want to do is place the "+" at the end of the "overDiv" block so that when the text 'disappears' off of the page, the + will always remain. Hopefully that makes some sense?

Thanks in advance.

```<code><body>

<script language="javascript" type="text/javascript">
$(function() {
    // when we click on the a-href id 'togglen', we move the overDiv to the left.
$('#togglen').click(function() {
    // simple animation
    $('#overDiv').animate({
      left: parseInt($('#overDiv').css('left'),10) == 0 ? -$('#overDiv').outerWidth() : 0
    });
  }); //
});

</script>
<div><a href="#" id="togglen">+</a></div>
<div style="background-color:#CCC; width:180px;  position:absolute; left:0; overflow:hidden; float:left;" id="overDiv">Lorem ipsum.</div>
</code>```

答:
Just add something like style="position:absolute; left:190px" to your +.

If you want the + to "stick" to the "overDiv" you can add

```<code>$('#togglen').animate({
        left: parseInt($('#overDiv').css('left'),10) == 0 ? 0 : $('#overDiv').outerWidth()
    });
</code>```

before the other animation.

http://jsfiddle.net/PQxkc/

Title: jQuery Animate Question

Body:
I have a very basic function which I am using jQuery to slide some content either out (from left to right) or back in (from right to left). The code below works, however, what I am trying to do now is include the "+" at the end of my "overDiv", and make it so that it will always show.

To paint a more lucid picture, right now if you paste that code into your editor and include google's jQuery, you will see that clicking the "+" eliminates the "overDiv" block completely. However, what I want to do is place the "+" at the end of the "overDiv" block so that when the text 'disappears' off of the page, the + will always remain. Hopefully that makes some sense?

Thanks in advance.

+

Lorem ipsum.

Body:
Just add something like style="position:absolute; left:190px" to your +.

If you want the + to "stick" to the "overDiv" you can add

$('#togglen').animate({
        left: parseInt($('#overDiv').css('left'),10) == 0 ? 0 : $('#overDiv').outerWidth()
    });

before the other animation.

http://jsfiddle.net/PQxkc/


问:
Given an ERC20 token address, how do you get the current price of a single token of the ERC20?
I'm trying to solve this problem where if I'm given an ERC20 token address such as 0xff75ced57419bcaebe5f05254983b013b0646ef5. And I do not know the name of the token. How can I get the current price for a single token of the ERC20 given the ERC20 token address?
I'm trying to do this in python and I can't seem to find an API that does this. I was searching through Coingecko but it requires the name of the token. Is there any way to go straight to the current price with the address instead of having to know the name of the token?

Thank you so much,
Tony

答:
You can this on-chain with using chainlink oracle. You need to import this first

```<code>import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
</code>```

Then write a function inside the contract

```<code>function getTokenValue(address _token)public view returns(uint256,uint256){
        // price feed address
        address priceFeedAddress=tokenPriceFeedMapping[_token];
        AggregatorV3Interface priceFeed=AggregatorV3Interface(priceFeedAddress);
        (
            uint80 roundID,
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        // decimals returns uint8
        uint256 decimals=uint256(priceFeed.decimals());
        return (uint256(price),decimals);
    }
</code>```

chainlink documentation

Body:
You can this on-chain with using chainlink oracle. You need to import this first

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

Then write a function inside the contract

function getTokenValue(address _token)public view returns(uint256,uint256){
        // price feed address
        address priceFeedAddress=tokenPriceFeedMapping[_token];
        AggregatorV3Interface priceFeed=AggregatorV3Interface(priceFeedAddress);
        (
            uint80 roundID,
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        // decimals returns uint8
        uint256 decimals=uint256(priceFeed.decimals());
        return (uint256(price),decimals);
    }

chainlink documentation


问:
How to kill app on button press
I have an app that has a lot of activities. In the "Settings" page there is a delete account button that is supposed to reset all the saved variables and exit the app. I haven't found a simple solution to exiting the app (eg calling finish only destroys the current activity) What do I call to close the app on a button press (eg when I reopen the the app it should start from the first activity)</p>

答: Easiest way to do this is to register a BroadcastReceiver in all Activity classes that listens for a specific Intent. When you want to close everything then just fire the matching Intent, and in the BroadcastReceiver in each Activity call finish.

Title: How to kill app on button press


问:
order by query using left join
I have the following tables:

Products (id,name,description)

Userproducts(id,user_id,product_id)

I currently have this query:

```<code>SELECT Products.id,Userproducts.user_id
  FROM Products
   LEFT JOIN UserProducts
       ON Products.id = Userproducts.product_id;
</code>```

I'm showing all the products but I want to know how do I make my ORDER BY so the top those products will be Userproducts.user_id =1.

答:
use this</p>
```<code>SELECT Products.id,Userproducts.user_id
FROM Products
LEFT JOIN UserProducts ON Products.id = Userproducts.product_id;
order by Userproducts.user_id
</code>```

Title: order by query using left join

Body:
I have the following tables:

Products (id,name,description)

Userproducts(id,user_id,product_id)

I currently have this query:

SELECT Products.id,Userproducts.user_id
  FROM Products
   LEFT JOIN UserProducts
       ON Products.id = Userproducts.product_id;

I'm showing all the products but I want to know how do I make my ORDER BY so the top those products will be Userproducts.user_id =1.

Body:
use this

SELECT Products.id,Userproducts.user_id
FROM Products
LEFT JOIN UserProducts ON Products.id = Userproducts.product_id;
order by Userproducts.user_id