问:
Saving user_id with new entity, but in database user_id is null
This is how I'm trying to add user_id. The request passes my request rules where's user_id is required, if I remove the line where I add user_id it fails. user_id is added in my model's fillable array. Any idea where should I look for the problem? :/</p>

```<code>    public function store()
    {
        $this->crud->getRequest()->request->add(['user_id' => backpack_user()->id]);
        $response = $this->traitStore();
        return $response;
    }

    public function update()
    {
        $this->crud->getRequest()->request->add(['user_id' => backpack_user()->id]);
        $response = $this->traitUpdate();
        return $response;
    }
</code>```

答:
you have added the value but not the field ...

you should add the field too:

```<code>public function store()
    {
        $this->crud->getRequest()->request->add(['user_id' => backpack_user()->id]);

  $this->crud->addField(["name" => "user_id","type" => "hidden"]);
        $response = $this->traitStore();
        return $response;
    }
</code>```

and the same goes for update ...
make sure you do not have another filed with name 'user_id'

Body:
This is how I'm trying to add user_id. The request passes my request rules where's user_id is required, if I remove the line where I add user_id it fails. user_id is added in my model's fillable array. Any idea where should I look for the problem? :/

    public function store()
    {
        $this->crud->getRequest()->request->add(['user_id' => backpack_user()->id]);
        $response = $this->traitStore();
        return $response;
    }

    public function update()
    {
        $this->crud->getRequest()->request->add(['user_id' => backpack_user()->id]);
        $response = $this->traitUpdate();
        return $response;
    }

Body:
you have added the value but not the field ...

you should add the field too:

public function store()
    {
        $this->crud->getRequest()->request->add(['user_id' => backpack_user()->id]);

  $this->crud->addField(["name" => "user_id","type" => "hidden"]);
        $response = $this->traitStore();
        return $response;
    }

and the same goes for update ...
make sure you do not have another filed with name 'user_id'


来源: stackexchange

问:
What's the best way to stop page scroll within a dropdown menu
I have a dropdown menu on mobile where the page is scrolling at the top when I open the menu.

What's the best way to solve this? here is an example

Tried:

```

<p>Didn't work.</p>

<p>Added css: </p>

```.body-overflow {
   overflow: hidden;
}
```

Didn't work.

What I've realised is that there are two overlapping touchable or scrollable areas. Touching the menu area enables you to move the page behind it. So if there is a way of creating an attribute z-index?

答:
Your link points to #, which is a way of linking to an element on the same page. An empty fragment (#) links to the top of the page, causing the browser to scroll. (If you linked to #some-section, the browser would scroll to the element with the ID of some-section).

So, in your case, you need to change your click handler to:

```<code>onclick="myFunction(this); return false;">
</code>```

This makes the return value of the event handler return false, which signals to the browser that the default browser behavior (scroll) should not take place.

Your code, modified:

```

<p>The other issue (menu pushing the page content down) can be solved with the following CSS:</p>

<pre class="lang-css prettyprint-override"><code>#site-navigation {
  visibility: visible;
  opacity: 1;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  transition: none;
  transform: none;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dropdown menu on mobile where the page is scrolling at the top when I open the menu.

What's the best way to solve this? here is an example

Tried:

Didn't work.

Added css:

.body-overflow {
   overflow: hidden;
}

Didn't work.

What I've realised is that there are two overlapping touchable or scrollable areas. Touching the menu area enables you to move the page behind it. So if there is a way of creating an attribute z-index?

Body:
Your link points to #, which is a way of linking to an element on the same page. An empty fragment (#) links to the top of the page, causing the browser to scroll. (If you linked to #some-section, the browser would scroll to the element with the ID of some-section).

So, in your case, you need to change your click handler to:

onclick="myFunction(this); return false;">

This makes the return value of the event handler return false, which signals to the browser that the default browser behavior (scroll) should not take place.

Your code, modified:

<div class="module widget-handle mobile-toggle right visible-sm visible-xs">
  <a id="mobile-nav" href="#">
    <div class="container1" onclick="myFunction(this); return false;">
      <div class="bar1"></div>
      <div class="bar2"></div>
      <div class="bar3"></div>
    </div>
  </a>
  <script>
    function myFunction(el) {
      el.classList.toggle("change");
    }
  </script>
</div>

The other issue (menu pushing the page content down) can be solved with the following CSS:

#site-navigation {
  visibility: visible;
  opacity: 1;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  transition: none;
  transform: none;
}


问:
Flutter Firebase not loading data for the first time, but at the next tries it loads them many times
```<code>final databaseReference = Firestore.instance.collection("classrooms");
bool hany = false;
var names = new Map<String, dynamic>();
List nevek = [];
List IDS = [];

Future<void> getclasses() async {
  QuerySnapshot snapshot = await databaseReference.getDocuments();

  snapshot.documents.forEach((f) {
    IDS.add(f.documentID);
    x = (f.data.length);
    names.addAll(f.data);
    for (int i = 0; i < names.values.toList().length / x; i++) {
      nevek.add(names.values.toList()[i + 1]);
    }
  });
}

class ScrollableClassroom extends StatefulWidget {
  @override
  _ScrollableClassroomState createState() => _ScrollableClassroomState();
}

class _ScrollableClassroomState extends State<ScrollableClassroom> {
  @override
  void initState() {
    super.initState();
    IDS = [];
    names.clear();
    getclasses();
  }

  Widget build(BuildContext context) {
    print(nevek);
    print(IDS);

    return WillPopScope(
      onWillPop: () async => false,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("Osztályok"),
          leading: Padding(
              padding: const EdgeInsets.only(left: 5.0),
              child: IconButton(
                  icon: Icon(Icons.exit_to_app, color: Colors.black38),
                  onPressed: () {
                    authService.signOut();
                    authService.loggedIn = false;
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => GoogleSignUp()));
                  })),
          actions: <Widget>[
            Padding(
                padding: const EdgeInsets.only(right: 5.0),
                child: Row(
                  children: <Widget>[
                    IconButton(
                        icon: Icon(Icons.add_circle_outline,
                            color: Colors.black38),
                        onPressed: null),
                    IconButton(
                        icon: Icon(Icons.search, color: Colors.black38),
                        onPressed: null),
                  ],
                )),
          ],
        ),
        body: ListView.builder(
          itemCount: nevek.length,
          itemBuilder: (context, index) {
            return Card(
              child: ListTile(
                onTap: () {
                  id = IDS[index];
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => InClassRoom()));
                },
                title: Text(nevek[index]),
              ),
            );
          },
        ),
      ),
    );
  }
}
</code>```

In the Listview, for the first time it shows nothing, but after a hot reload it works fine. However, if I do a second hot reload it shows everything, but twice. Another case is when I press the back button on the left side of the appbar, it takes you to the login screen. If you come back for the first time from the login screen it is fine, but if you do this once more it shows everything twice again. And after that three times, etc.

答:
First of all your missing a setState after the docukents have been mapped

Keep your state variables in your state class

Body:
final databaseReference = Firestore.instance.collection("classrooms");
bool hany = false;
var names = new Map<String, dynamic>();
List nevek = [];
List IDS = [];

Future<void> getclasses() async {
  QuerySnapshot snapshot = await databaseReference.getDocuments();

  snapshot.documents.forEach((f) {
    IDS.add(f.documentID);
    x = (f.data.length);
    names.addAll(f.data);
    for (int i = 0; i < names.values.toList().length / x; i++) {
      nevek.add(names.values.toList()[i + 1]);
    }
  });
}

class ScrollableClassroom extends StatefulWidget {
  @override
  _ScrollableClassroomState createState() => _ScrollableClassroomState();
}

class _ScrollableClassroomState extends State<ScrollableClassroom> {
  @override
  void initState() {
    super.initState();
    IDS = [];
    names.clear();
    getclasses();
  }

  Widget build(BuildContext context) {
    print(nevek);
    print(IDS);

    return WillPopScope(
      onWillPop: () async => false,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("Osztályok"),
          leading: Padding(
              padding: const EdgeInsets.only(left: 5.0),
              child: IconButton(
                  icon: Icon(Icons.exit_to_app, color: Colors.black38),
                  onPressed: () {
                    authService.signOut();
                    authService.loggedIn = false;
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => GoogleSignUp()));
                  })),
          actions: <Widget>[
            Padding(
                padding: const EdgeInsets.only(right: 5.0),
                child: Row(
                  children: <Widget>[
                    IconButton(
                        icon: Icon(Icons.add_circle_outline,
                            color: Colors.black38),
                        onPressed: null),
                    IconButton(
                        icon: Icon(Icons.search, color: Colors.black38),
                        onPressed: null),
                  ],
                )),
          ],
        ),
        body: ListView.builder(
          itemCount: nevek.length,
          itemBuilder: (context, index) {
            return Card(
              child: ListTile(
                onTap: () {
                  id = IDS[index];
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => InClassRoom()));
                },
                title: Text(nevek[index]),
              ),
            );
          },
        ),
      ),
    );
  }
}

In the Listview, for the first time it shows nothing, but after a hot reload it works fine. However, if I do a second hot reload it shows everything, but twice. Another case is when I press the back button on the left side of the appbar, it takes you to the login screen. If you come back for the first time from the login screen it is fine, but if you do this once more it shows everything twice again. And after that three times, etc.


问:
JScrollPane components do not appear
I'm trying to put some components inside of a JScrollPane but every time I launch my program they don't appear. I just started learning about GUIs today so I figure I missed something small but no matter where I look online I can't find an answer. The only thing that appears is the JScrollPane itself.

```<code>class MainFrame extends JFrame{
    public MainFrame(String title){
        //Main Frame Stuff
        super(title);
        setSize(655, 480);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        //Layout
        FlowLayout flow = new FlowLayout();
        setLayout(flow);

        //Components
        JButton spam_button = new JButton("Print");
        JLabel label = new JLabel("What do you want to print?",
                                  JLabel.LEFT);
        JTextField user_input = new JTextField("Type Here", 20);

        //Scroll Pane
        JScrollPane scroll_pane = new JScrollPane(
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll_pane.setPreferredSize(new Dimension(640, 390));

        //Adding to Scroll
        scroll_pane.add(label);
        scroll_pane.add(user_input);
        scroll_pane.add(spam_button);

        //Adding to the Main Frame
        add(scroll_pane);

        //Visibility
        setVisible(true);
    }
}
</code>```

The point of the program is to print whatever you type 100 times but I haven't gotten that far yet because I've been hung up on this scroll problem. When I finally get things to show up in the scroll pane I'm going to move those three components to a JPanel above the scroll pane and then I'm going to add the 100 words to the scroll pane so that you can scroll through it.

答:
I just started learning about GUIs today

So the first place to start is with the Swing tutorial. There is plenty of demo code to download  and test and modify.

```<code>scroll_pane.add(label);
scroll_pane.add(user_input);
scroll_pane.add(spam_button);
</code>```

A JScrollPane is not like a JPanel:

you don't add components directly to the scroll panel. You add a component to the viewport of the scroll pane

only a single component can be added to the viewport.

So your code should be something like:

```<code>JPanel panel = new JPanel();
panel.add(label);
panel.add(user_input);
panel.add(spam_button);
scrollPane.setViewportView( panel );
</code>```

Title: JScrollPane components do not appear

Body:
I'm trying to put some components inside of a JScrollPane but every time I launch my program they don't appear. I just started learning about GUIs today so I figure I missed something small but no matter where I look online I can't find an answer. The only thing that appears is the JScrollPane itself.

class MainFrame extends JFrame{
    public MainFrame(String title){
        //Main Frame Stuff
        super(title);
        setSize(655, 480);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        //Layout
        FlowLayout flow = new FlowLayout();
        setLayout(flow);

        //Components
        JButton spam_button = new JButton("Print");
        JLabel label = new JLabel("What do you want to print?",
                                  JLabel.LEFT);
        JTextField user_input = new JTextField("Type Here", 20);

        //Scroll Pane
        JScrollPane scroll_pane = new JScrollPane(
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll_pane.setPreferredSize(new Dimension(640, 390));

        //Adding to Scroll
        scroll_pane.add(label);
        scroll_pane.add(user_input);
        scroll_pane.add(spam_button);

        //Adding to the Main Frame
        add(scroll_pane);

        //Visibility
        setVisible(true);
    }
}

The point of the program is to print whatever you type 100 times but I haven't gotten that far yet because I've been hung up on this scroll problem. When I finally get things to show up in the scroll pane I'm going to move those three components to a JPanel above the scroll pane and then I'm going to add the 100 words to the scroll pane so that you can scroll through it.

Body:
I just started learning about GUIs today

So the first place to start is with the Swing tutorial. There is plenty of demo code to download  and test and modify.

scroll_pane.add(label);
scroll_pane.add(user_input);
scroll_pane.add(spam_button);

A JScrollPane is not like a JPanel:

you don't add components directly to the scroll panel. You add a component to the viewport of the scroll pane

only a single component can be added to the viewport.

So your code should be something like:

JPanel panel = new JPanel();
panel.add(label);
panel.add(user_input);
panel.add(spam_button);
scrollPane.setViewportView( panel );


问:
Laravel Carbon differents between two dates
I have weekly discounts on the product on my site, when buying, the user is written how much the discount will still be valid. There is a problem in calculating the time between hours and minutes.

In order to calculate how many days there will be a discount, I do it like this:

```<code>$realTime = Carbon::now();
$diff = $realTime->diffInDays($item->created_at);
$date = 7 - $diff;
    if ($diff < 7) {
        Notify::create(
            [
            'user_id' => $this->user->id,
            'title' => 'Message',
            'message' => 'Discount will be available '.$date.' '.Lang::choice('day|days|', $date, [], 'ru'),'',
            'status' => '2',
        ]);
    }
</code>```

This is returned to me by the inscription that the discount will be available for another 1, 2, 3 ... days.

And now, how i can calculate the remaining hours and minutes?

I try something like this:

```<code>$realTime = Carbon::now();
$diff_hours = $realTime->diffInHours($item->created_at);
$date_hours = 168 - $diff_hours;
    if ($diff == 7) {
        Notify::create(
            [
            'user_id' => $this->user->id,
            'title' => 'Message',
            'message' => 'Discount will be available '.$date_hours .' '.Lang::choice('hour|hours|', $date_hours , [], 'ru'),'',
            'status' => '2',
        ]);
    }
</code>```

168 it's hours at 1 week, but maybe I'm doing something wrong? Because in the end I get a negative value of -17 hours. And by the same method, I try to make a difference in minutes, but again I get a negative and incomprehensible value.

UPD: at my database item has format 2020-05-26 23:40:15 i write:

```<code>$realTime = Carbon::now();
$diff = $realTime->diffInDays($item->created_at);
</code>```

$realTime for date now give me:

```<code>object(Carbon\Carbon)#623 (3) { ["date"]=> string(26) "2020-05-30 18:51:23.846522" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Moscow" }
</code>```

答:
suppose you have your start and end discount dates like this:

```<code>$start  = new Carbon('2018-10-04 15:00:03');
$end    = new Carbon('2018-10-05 17:00:09');
</code>```

you can do like this:

```<code>$diff = $start->diff($end);
</code>```

now $diff will give you full control on days and minutes. you can do following for getting days:

```<code>$diff->d
</code>```

for minutes

```<code>$diff->m
</code>```

means you can concatenate values to create a statement like this:

```<code>$diff->d . 'days ' . $diff->m . 'minutes and ' . $diff->s . ' seconds remaining.'
</code>```

final testing code may look like this:

```<code>$start  = new Carbon('2018-10-04 15:00:03');
        $end    = new Carbon('2018-10-05 17:00:09');
        $diff = $start->diff($end);
        $message = $diff->d . 'days ' . $diff->m . 'minutes and ' . $diff->s . ' seconds remaining.';

        dd($message);
</code>```

Body:
I have weekly discounts on the product on my site, when buying, the user is written how much the discount will still be valid. There is a problem in calculating the time between hours and minutes.

In order to calculate how many days there will be a discount, I do it like this:

$realTime = Carbon::now();
$diff = $realTime->diffInDays($item->created_at);
$date = 7 - $diff;
    if ($diff < 7) {
        Notify::create(
            [
            'user_id' => $this->user->id,
            'title' => 'Message',
            'message' => 'Discount will be available '.$date.' '.Lang::choice('day|days|', $date, [], 'ru'),'',
            'status' => '2',
        ]);
    }

This is returned to me by the inscription that the discount will be available for another 1, 2, 3 ... days.

And now, how i can calculate the remaining hours and minutes?

I try something like this:

$realTime = Carbon::now();
$diff_hours = $realTime->diffInHours($item->created_at);
$date_hours = 168 - $diff_hours;
    if ($diff == 7) {
        Notify::create(
            [
            'user_id' => $this->user->id,
            'title' => 'Message',
            'message' => 'Discount will be available '.$date_hours .' '.Lang::choice('hour|hours|', $date_hours , [], 'ru'),'',
            'status' => '2',
        ]);
    }

168 it's hours at 1 week, but maybe I'm doing something wrong? Because in the end I get a negative value of -17 hours. And by the same method, I try to make a difference in minutes, but again I get a negative and incomprehensible value.

UPD: at my database item has format 2020-05-26 23:40:15 i write:

$realTime = Carbon::now();
$diff = $realTime->diffInDays($item->created_at);

$realTime for date now give me:

object(Carbon\Carbon)#623 (3) { ["date"]=> string(26) "2020-05-30 18:51:23.846522" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Moscow" }

Body:
suppose you have your start and end discount dates like this:

$start  = new Carbon('2018-10-04 15:00:03');
$end    = new Carbon('2018-10-05 17:00:09');

you can do like this:

$diff = $start->diff($end);

now $diff will give you full control on days and minutes. you can do following for getting days:

$diff->d

for minutes

$diff->m

means you can concatenate values to create a statement like this:

$diff->d . 'days ' . $diff->m . 'minutes and ' . $diff->s . ' seconds remaining.'

final testing code may look like this:

$start  = new Carbon('2018-10-04 15:00:03');
        $end    = new Carbon('2018-10-05 17:00:09');
        $diff = $start->diff($end);
        $message = $diff->d . 'days ' . $diff->m . 'minutes and ' . $diff->s . ' seconds remaining.';

        dd($message);


问:
Android Emulator gives an Error SO_REUSEPORT and debugging not working
I am getting following error when running emulator, also debugging is not working, it says waiting for debugger to attach. I am wondering if the following has anything to do with getting stuck at "waiting for debugger to attach".

Emulator: E0516 21:01:34.057349753    3279
  socket_utils_common_posix.cc:201] check for SO_REUSEPORT:
  {"created":"@1589644894.057229268","description":"SO_REUSEPORT
  unavailable on compiling
  system","file":"/mnt/tmpfs/src/android/emu-master-dev/external/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc","file_line":169}

My android studio version is below.

Android Studio 3.6.3
Build #AI-192.7142.36.36.6392135, built on April 14, 2020
Runtime version: 1.8.0_212-release-1586-b4-5784211 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 5.4.0-29-generic
GC: ParNew, ConcurrentMarkSweep
Memory: 1246M
Cores: 4
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins:

答:
I had that problem.

I was making a wrong diagnostic.

Running the emulator from  Android/Sdk/emulator/emulator with a command such as:

./emulator @Pixel_3_API_28 -netdelay none -netspeed full -debug all also gave me this error, but it is non-blocking.

The problem disappeared when I:

switched to proprietary driver (nvidia) in Ubuntu in the Software Updater > Settings > Additional Driver

Restarting

Recreating my virtual device.


问:
How to return data when popping multiple screens?
I know I can return data to the previous screen by using

```<code>Navigator.pop(context, 'Value');
</code>```

But in my case I need to pop multiple screens by using

```<code>Navigator.popUntil(context, ModalRoute.withName('/login'));
</code>```

I wonder in this case how do I pass the data back to the corresponding widget?

Thanks in advance.

答:
The flutter API does not have that feature and from this https://github.com/flutter/flutter/issues/30112 discussion, that feature is not on the table yet. A walkaround was suggested though using the Page API.

However, in my opinion, it is cleaner to use the provider package https://pub.dev/packages/provider as part of your app state management to keep the data you want and make it available to any screen of interest. Follow these steps to achieve that.

Add the provider to your pubspec.yaml. Check the link above to see detailed instructions.

Create a notifier class that extends ChangeNotifier class as shown below. ChangeNotifier class is part of the flutter API.

```<code>class MyDataProvider extends ChangeNotifier {

    //define your private data field(s). I'm using int here.
    int _mydata;

    //define a getter
    int get myData => _myData;

    // define a setter
    set myData(newData){
      _myData = newData;
      notifyListeners();
    }
}

</code>```

Wrap your uppermost widget (or the parent of the screens where you want to pass the data) with the provider and instantiate it. I'm using main here.

```<code>void main(){
  runApp(
     ChangeNotifierProvider(create: (context) => MyDataProvider()),
   child: MyApp(),
  )
}

</code>```

Assuming you have five screens: Screen1, Screen2, ..., Screen5 and you want to navigate to screen5, do some operations and return to screen1 with some data. On 1st screen, define a local variable for myData and create an instance of your myDataProvider. When a button is pressed to start the navigation, wrap up the push navigation in an asynchronous call.

```<code>//Screen1

int currentLocalData = 78;

MyDataProvider myProvider = Provider.of<MyDataProvider>(context);

onPressed: () async {
  //Assign localData to myData in the provider
  myProvider.myData = currentLocalData; //calls the setter define in the provider.
  await Navigator.push(context, MaterialPageRoute(
       builder: (context) => Screen5()
  ));

 //Retrieve myData from the provider and assign it to currentLocalData.
//This executes after navigating back from Screen5
  currentLocalData = myProvider.myData;
}
</code>```

Let assume in Screen5 you retrieved the data and added 100 to it. Your aim is to return to Screen1 and make use of the new data, i.e 178. Here you will instantiate the provider again in Screen5 and assign the value 178 to myData.

```<code>//Screen5

MyDataProvider myProvider = Provider.of<MyDataProvider>(context);

myProvider.myData += 100;

//Use navigation.popUntil
Navigation.popUntil(context, ModalRoute.withName('/Screen1'));

</code>```

Body:
I know I can return data to the previous screen by using

Navigator.pop(context, 'Value');

But in my case I need to pop multiple screens by using

Navigator.popUntil(context, ModalRoute.withName('/login'));

I wonder in this case how do I pass the data back to the corresponding widget?

Thanks in advance.

Body:
The flutter API does not have that feature and from this https://github.com/flutter/flutter/issues/30112 discussion, that feature is not on the table yet. A walkaround was suggested though using the Page API.

However, in my opinion, it is cleaner to use the provider package https://pub.dev/packages/provider as part of your app state management to keep the data you want and make it available to any screen of interest. Follow these steps to achieve that.

Add the provider to your pubspec.yaml. Check the link above to see detailed instructions.

Create a notifier class that extends ChangeNotifier class as shown below. ChangeNotifier class is part of the flutter API.

class MyDataProvider extends ChangeNotifier {

    //define your private data field(s). I'm using int here.
    int _mydata;

    //define a getter
    int get myData => _myData;

    // define a setter
    set myData(newData){
      _myData = newData;
      notifyListeners();
    }
}

Wrap your uppermost widget (or the parent of the screens where you want to pass the data) with the provider and instantiate it. I'm using main here.

void main(){
  runApp(
     ChangeNotifierProvider(create: (context) => MyDataProvider()),
   child: MyApp(),
  )
}

Assuming you have five screens: Screen1, Screen2, ..., Screen5 and you want to navigate to screen5, do some operations and return to screen1 with some data. On 1st screen, define a local variable for myData and create an instance of your myDataProvider. When a button is pressed to start the navigation, wrap up the push navigation in an asynchronous call.

//Screen1

int currentLocalData = 78;

MyDataProvider myProvider = Provider.of<MyDataProvider>(context);

onPressed: () async {
  //Assign localData to myData in the provider
  myProvider.myData = currentLocalData; //calls the setter define in the provider.
  await Navigator.push(context, MaterialPageRoute(
       builder: (context) => Screen5()
  ));

 //Retrieve myData from the provider and assign it to currentLocalData.
//This executes after navigating back from Screen5
  currentLocalData = myProvider.myData;
}

Let assume in Screen5 you retrieved the data and added 100 to it. Your aim is to return to Screen1 and make use of the new data, i.e 178. Here you will instantiate the provider again in Screen5 and assign the value 178 to myData.

//Screen5

MyDataProvider myProvider = Provider.of<MyDataProvider>(context);

myProvider.myData += 100;

//Use navigation.popUntil
Navigation.popUntil(context, ModalRoute.withName('/Screen1'));


问:
Array of images into storage
I am making little game in angular and i have problem how to export array with images to storage so when i reload the page it doesn't disappear. Array is made of random items from other array and adding next item is by pressing button.

That's my code in typescript

containers = [];
images = [
  { id: 0, name: "sword", url: "../../../../assets/img/sword.png" },
  { id: 1, name: "sword2", url: "../../../../assets/img/sword2.png" },
];

add() {
  let index = Math.round(Math.random());
  this.containers.push(this.images[index]);
}
```
<p>and this is in html:</p>
<pre class="lang-html prettyprint-override"><code><button (click)="add()">Add</button>
<div id="content">
  <div id="contentInside" *ngFor="let image of containers">
    <img class="item" src="{{image.url}}" />
  </div>
</div>
</code>```

I want to keep it looking like this

答:
You can store a copy of your image array in localstorage as

```<code>localStorage.setItem('images', JSON.stringify(this.images))
</code>```

And retrive those images on browser reload by simply doing

```<code>private images = JSON.parse(localStorage.getItem('images')) || [];
</code>```

Title: Array of images into storage

Body:
I am making little game in angular and i have problem how to export array with images to storage so when i reload the page it doesn't disappear. Array is made of random items from other array and adding next item is by pressing button.

That's my code in typescript

containers = [];
images = [
  { id: 0, name: "sword", url: "../../../../assets/img/sword.png" },
  { id: 1, name: "sword2", url: "../../../../assets/img/sword2.png" },
];

add() {
  let index = Math.round(Math.random());
  this.containers.push(this.images[index]);
}

and this is in html:

<button (click)="add()">Add</button>

I want to keep it looking like this

Body:
You can store a copy of your image array in localstorage as

localStorage.setItem('images', JSON.stringify(this.images))

And retrive those images on browser reload by simply doing

private images = JSON.parse(localStorage.getItem('images')) || [];


问:
Code printing hello world despite being math
I'm trying this on repl.it and it just... prints "hello world" as a default. I don't know exactly what I'm doing wrong.

    import java.util.Scanner;

    class Input{
      public static void mian(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter your first double: ");
        double firstDouble = input.nextDouble();
        System.out.print("You entered " + firstDouble + " as your first number.");

        System.out.print("Enter you second double: ");
        double secondDouble = input.nextDouble();
        System.out.print("You entered " + secondDouble + " as you second number.");

        System.out.print("Enter your third double: ");
        double thirdDouble = input.nextDouble();
        System.out.print("You entered " + thirdDouble + "As your third number.");

        input.close();

      }

    }
```

答:
```<code>import java.util.*;
class Main {
  public static void main(String[] args) {
   Scanner input = new Scanner(System.in);

System.out.print("Enter your first double: ");
double firstDouble = input.nextDouble();
System.out.print("You entered " + firstDouble + " as your first number.");

System.out.print("Enter you second double: ");
double secondDouble = input.nextDouble();
System.out.print("You entered " + secondDouble + " as you second number.");

System.out.print("Enter your third double: ");
double thirdDouble = input.nextDouble();
System.out.print("You entered " + thirdDouble + "As your third number.");

input.close();
  }
}
</code>```

try this code you was getting hello world because repl compiles program with name of Main.java but your program name is Input.java

Body:
import java.util.*;
class Main {
  public static void main(String[] args) {
   Scanner input = new Scanner(System.in);

System.out.print("Enter your first double: ");
double firstDouble = input.nextDouble();
System.out.print("You entered " + firstDouble + " as your first number.");

System.out.print("Enter you second double: ");
double secondDouble = input.nextDouble();
System.out.print("You entered " + secondDouble + " as you second number.");

System.out.print("Enter your third double: ");
double thirdDouble = input.nextDouble();
System.out.print("You entered " + thirdDouble + "As your third number.");

input.close();
  }
}

try this code you was getting hello world because repl compiles program with name of Main.java but your program name is Input.java


问:
How to disable android hardware buttons in ionic 3
I'm building uber type application For that I want to disable all hardware buttons (home button, power button, application drawer button, back button) programmatically for specific screen  </p>

答:
There is no way to change home button functionality.

To change the back button event functionality use this code in your controller:

```<code>ionViewDidEnter() {
    this.platform.registerBackButtonAction(() => {
        //your code
    }, 100);
}
</code>```

Good Luck!

Body:
There is no way to change home button functionality.

To change the back button event functionality use this code in your controller:

ionViewDidEnter() {
    this.platform.registerBackButtonAction(() => {
        //your code
    }, 100);
}

Good Luck!


问:
How can i separate values in an array like this..[(1,3),(2,5),(4,8),(9,10),(5,6),(4,7),(7,10)]?
For example, you have array of entry and exit date of patients(entry, exit)
like [(1,3),(2,5),(4,8),(9,10),(5,6),(4,7),(7,10)] and i want to separate each elements ..
Help me!</p>

答:
Using Python zip and Unzip concept we can separate it easily.
for example :

```<code>a=  [(1,3),(2,5),(4,8),(9,10),(5,6),(4,7),(7,10)]
b=[]

for start_d, end_d in a:
    max_d = end_d - start_d
    b.append(max_d)
    print(f'Duration of stays max_d: {max_d}')
b.sort()
print(b)
print(b[(b.__len__()-1)])
</code>```

and output

```<code>Duration of stays max_d: 2
Duration of stays max_d: 3
Duration of stays max_d: 4
Duration of stays max_d: 1
Duration of stays max_d: 1
Duration of stays max_d: 3
Duration of stays max_d: 3
[1, 1, 2, 3, 3, 3, 4]
4// max-m day stay
</code>```

Body:
Using Python zip and Unzip concept we can separate it easily.
for example :

a=  [(1,3),(2,5),(4,8),(9,10),(5,6),(4,7),(7,10)]
b=[]

for start_d, end_d in a:
    max_d = end_d - start_d
    b.append(max_d)
    print(f'Duration of stays max_d: {max_d}')
b.sort()
print(b)
print(b[(b.__len__()-1)])

and output

Duration of stays max_d: 2
Duration of stays max_d: 3
Duration of stays max_d: 4
Duration of stays max_d: 1
Duration of stays max_d: 1
Duration of stays max_d: 3
Duration of stays max_d: 3
[1, 1, 2, 3, 3, 3, 4]
4// max-m day stay


问:
Weird Error message in Xcode
I have a program that I am trying to make, and so far things seem to be going well. I've been busy debugging a certain chunk of code, and it works fine in the debugger. The problem, however, is that the program still crashes. When I go through the debugger window, it looks like it's something outside of my own code. The error message is:

```<code>Unable to disassemble dyld_stub_writev
</code>```

That's what I see when I look at the console. I've tried to do a search on this, but I seriously got no results. Does anyone have any idea what this error message means?

答: Nevermind, solved it. Turns out I wasn't releasing an NSArray right, so I just set it up as a property in the header file, and it works now.</p>

ContentLicense: CC BY-SA 3.0

Title: Weird Error message in Xcode

Body:
I have a program that I am trying to make, and so far things seem to be going well. I've been busy debugging a certain chunk of code, and it works fine in the debugger. The problem, however, is that the program still crashes. When I go through the debugger window, it looks like it's something outside of my own code. The error message is:

Unable to disassemble dyld_stub_writev

That's what I see when I look at the console. I've tried to do a search on this, but I seriously got no results. Does anyone have any idea what this error message means?


问:
Navigation with Material-UI Icons
How can I use a Material-UI Icon to do navigation using React router Dom?

I tried this but this doesn't work:

```<code> <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon>
</code>```

In case of Buttons, I could do something like component={Link} and to="/vehicles" but I can't figure out how to navigate directly from the icon.

答:
You can use react-router-dom's useHistory hook or from props to push a path whenever the icon is clicked.

const Sidepane = () => {

// Assuming that you've imported it from the react-router-dom package

const history = useHistory()

const onClick = () => history.push("/vehicles")

return (
        <NavigateBeforeIcon onClick={onClick}>
           Go to vehicles
        </NavigateBeforeIcon

        )

}

```

I hope this helps

Title: Navigation with Material-UI Icons

Body:
How can I use a Material-UI Icon to do navigation using React router Dom?

I tried this but this doesn't work:

 <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon>

In case of Buttons, I could do something like component={Link} and to="/vehicles" but I can't figure out how to navigate directly from the icon.

Body:
You can use react-router-dom's useHistory hook or from props to push a path whenever the icon is clicked.

const Sidepane = () => {

// Assuming that you've imported it from the react-router-dom package

const history = useHistory()

const onClick = () => history.push("/vehicles")

return (
        <NavigateBeforeIcon onClick={onClick}>
           Go to vehicles
        </NavigateBeforeIcon

        )

}

I hope this helps


问:
Certifacte verify failed: certificate has expired (_ssl.c:1108)
When trying to run my Discord bot I get this error:

raise ClientConnectorCertificateError(
    aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to
    host discordapp.com:443 ssl:True [SSLCertVerificationError:
   (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
   certificate has expired (_ssl.c:1108)')]
```

It just started happening out of nowhere and happens every time.

I'm using Python 3.8 on Windows 10.

What does this mean and how do I fix it?

答:
To fix this:

Go to discord.com with Internet Explorer (Ran as Administrator)

Click the lock on the top right

Click view certificates

Install one

PS: If your antivirus is active for the web browser and this solution doesn't work, try disabling it and try again.

Body:
When trying to run my Discord bot I get this error:

raise ClientConnectorCertificateError(
    aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to
    host discordapp.com:443 ssl:True [SSLCertVerificationError:
   (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
   certificate has expired (_ssl.c:1108)')]

It just started happening out of nowhere and happens every time.

I'm using Python 3.8 on Windows 10.

What does this mean and how do I fix it?


问:
using time as a parameter in a conditional statement
I have an int(value) in a dictionary that continuously gets assigned a new value within a while loop.
I am trying to set a condition whereby if, '(value) < 0' for x amount of seconds, how would you go about creating this piece of code?

so, I was thinking something along the lines of:

```<code>from datetime import time

dict = {"special number": -0.5}

condition = 5

while true:

    if dict["special number"] < 0 'for more than' condition('%S'):

        del(dict)
</code>```

Apologises in advance, I know this if statement is far from correct, it was just for example purposes.

kindest regards

答:
You'll need to keep track of time yourself. A typical solution might look like this:

When the key first hits your target value, start a timer (that is, store the current time in a variable).

Every time through the loop, check the value of your key. If the value no longer meets your condition, reset the timer.

If the timer expires (i.e., enough time has passed) with the value meeting your condition, perform your desired action.

I would do this with a simple state machine, something like:

```<code>state = 0
while True:
  if state == 0:
    if dict['special number'] < 0:
      start_time = time.time()
      state = 1
  elif state == 1:
    if dict['special number'] >= 0:
      # value failed condition before timer expired
      state = 0
    elif time.time() - start_time  > 5:
      perform_some_action()
      state = 0
</code>```

Body:
I have an int(value) in a dictionary that continuously gets assigned a new value within a while loop.
I am trying to set a condition whereby if, '(value) < 0' for x amount of seconds, how would you go about creating this piece of code?

so, I was thinking something along the lines of:

from datetime import time

dict = {"special number": -0.5}

condition = 5

while true:

    if dict["special number"] < 0 'for more than' condition('%S'):

        del(dict)

Apologises in advance, I know this if statement is far from correct, it was just for example purposes.

kindest regards

Body:
You'll need to keep track of time yourself. A typical solution might look like this:

When the key first hits your target value, start a timer (that is, store the current time in a variable).

Every time through the loop, check the value of your key. If the value no longer meets your condition, reset the timer.

If the timer expires (i.e., enough time has passed) with the value meeting your condition, perform your desired action.

I would do this with a simple state machine, something like:

state = 0
while True:
  if state == 0:
    if dict['special number'] < 0:
      start_time = time.time()
      state = 1
  elif state == 1:
    if dict['special number'] >= 0:
      # value failed condition before timer expired
      state = 0
    elif time.time() - start_time  > 5:
      perform_some_action()
      state = 0


问:
Why are getters prefixed with the word "get"?
Generally speaking, creating a fluid API is something that makes all programmers happy; Both for the creators who write the interface, and the consumers who program against it. Looking beyond conventions, why is it that we prefix all our getters with the word "get". Omitting it usually results in a more fluid, easy to read set of instructions, which ultimately leads to happiness (however small or passive). Consider this very simple example. (pseudo code)

Conventional:

```<code>person = new Person("Joey")
person.getName().toLower().print()
</code>```

Alternative:

```<code>person = new Person("Joey")
person.name().toLower().print()
</code>```

Of course this only applies to languages where getters/setters are the norm, but is not directed at any specific language. Were these conventions developed around technical limitations (disambiguation), or simply through the pursuit of a more explicit, intentional feeling type of interface, or perhaps this is just a case of trickle a down norm. What are your thoughts? And how would simple changes to these conventions impact your happiness / daily attitudes towards your craft (however minimal).

Thanks.

答:
Here's a Smalltalk answer which I like most. One has to know a few rules about Smalltalk BTW.
fields are only accessible in the they are defined.If you dont write "accessors" you won't be able to do anything with them.

The convention there is having a Variable (let's anme it instVar1.
then you write a function instVar1 which just returns instVar1 and instVar: which sets
the value.

I like this convention much more than anything else. If you see a : somewhere you can bet it's some "setter" in one or the other way.

ContentLicense: CC BY-SA 2.5

Body:
Generally speaking, creating a fluid API is something that makes all programmers happy; Both for the creators who write the interface, and the consumers who program against it. Looking beyond conventions, why is it that we prefix all our getters with the word "get". Omitting it usually results in a more fluid, easy to read set of instructions, which ultimately leads to happiness (however small or passive). Consider this very simple example. (pseudo code)

Conventional:

person = new Person("Joey")
person.getName().toLower().print()

Alternative:

person = new Person("Joey")
person.name().toLower().print()

Of course this only applies to languages where getters/setters are the norm, but is not directed at any specific language. Were these conventions developed around technical limitations (disambiguation), or simply through the pursuit of a more explicit, intentional feeling type of interface, or perhaps this is just a case of trickle a down norm. What are your thoughts? And how would simple changes to these conventions impact your happiness / daily attitudes towards your craft (however minimal).

Thanks.


问:
Copy paste generator
How can I make copy paste generator like f.e. lingojam, from which
I will can copy and paste text with all formatting  .

I ask about this problem because I want to do it with another font.

答:
You cannot do it with another font because it's not really formatting, it's rather replacing regular characters with other Unicode characters that look like the same letter in a different design.

For example, the  is the character MATHEMATICAL BOLD SCRIPT SMALL L with code point U+1D4F5.

It is basically abusing the characters that exist in Unicode for a different purpose.

If the character "designs" that you are looking for exist in Unicode already, you can build such a tool very simply, just write code that replaces all occurences of the character l (U+006C) by the character  (U+1D4F5) for example (for all the letters of course). If no such characters exist already, then you are out of luck.

Title: Copy paste generator


问:
How to get AIC value from the pipe.fit() in pmdarima module
I need to get the best estimators like AIC, BIC

```<code>import pmdarima as pm
pipe = Pipeline([
            ("fourier", FourierFeaturizer(m=12, k=4)),
            ("arima",   pm.AutoARIMA(start_p=1, d=None, start_q=1, max_p=4,
                        max_d=3, max_q=4, start_P=1, D=None, start_Q=1, max_P=2,
                        max_D=1, max_Q=2, max_order=10, m=12, seasonal=False,
                        stationary=False, information_criterion='aic', alpha=0.05,
                        ))])

    pipe.fit(y_train,X_train)
    pipe.summary()
</code>```

Summary: Output

How can I fetch estimators value ? Thank you

答:
Try this:

pipe.steps[-1][1].model_.aic()
```

Body:
I need to get the best estimators like AIC, BIC

import pmdarima as pm
pipe = Pipeline([
            ("fourier", FourierFeaturizer(m=12, k=4)),
            ("arima",   pm.AutoARIMA(start_p=1, d=None, start_q=1, max_p=4,
                        max_d=3, max_q=4, start_P=1, D=None, start_Q=1, max_P=2,
                        max_D=1, max_Q=2, max_order=10, m=12, seasonal=False,
                        stationary=False, information_criterion='aic', alpha=0.05,
                        ))])

    pipe.fit(y_train,X_train)
    pipe.summary()

Summary: Output

How can I fetch estimators value ? Thank you


问:
How to reverse the index value in Python using for loop with a given list
I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

For example: a given list

test_board = ['O','O','X','X','X','O','X','O','X']

That show print out like this:

```<code> X | O | X
---|---|---
 X | X | O
---|---|---
 O | O | X
</code>```

I wrote this function:

```<code>def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
</code>```

But i get this print out when i call the function with the given list:

```<code>test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)
</code>```

Output:

```<code> X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O

</code>```

Edited:
Can i use for loop to achieve this without writing multiple print statement like this:

```<code>print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")
</code>```

答:
You can use an iter to achieve this.

Solution

```<code>def display_board(board):
    h_sep = '-' * 3
    it = iter(reversed(board))
    count = 0
    for j in it:
        print(f"{j:^3}|{next(it):^3}|{next(it):^3}")
        if count < 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
            count+=1

test_board = ['X','O','O','O','X','X','X','O','X']
display_board(test_board)
</code>```

Just to visualize the result, I used numbers in your test_board:

```<code>def display_board(board):
    h_sep = '-' * 3
    it = iter(reversed(board))
    for j in it:
        print(f"{int(j)-2:^3}|{int(next(it)):^3}|{int(next(it))+2:^3}")
        if int(j) > 3: print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")

test_board = ['1','2','3','4','5','6','7','8','9']
display_board(test_board)
</code>```

OUT:

```<code> 7 | 8 | 9
---|---|---
 4 | 5 | 6
---|---|---
 1 | 2 | 3
</code>```

Body:
I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

For example: a given list

test_board = ['O','O','X','X','X','O','X','O','X']

That show print out like this:

 X | O | X
---|---|---
 X | X | O
---|---|---
 O | O | X

I wrote this function:

def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")

But i get this print out when i call the function with the given list:

test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)

Output:

 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O

Edited:
Can i use for loop to achieve this without writing multiple print statement like this:

print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")

Body:
You can use an iter to achieve this.

Solution

def display_board(board):
    h_sep = '-' * 3
    it = iter(reversed(board))
    count = 0
    for j in it:
        print(f"{j:^3}|{next(it):^3}|{next(it):^3}")
        if count < 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
            count+=1

test_board = ['X','O','O','O','X','X','X','O','X']
display_board(test_board)

Just to visualize the result, I used numbers in your test_board:

def display_board(board):
    h_sep = '-' * 3
    it = iter(reversed(board))
    for j in it:
        print(f"{int(j)-2:^3}|{int(next(it)):^3}|{int(next(it))+2:^3}")
        if int(j) > 3: print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")

test_board = ['1','2','3','4','5','6','7','8','9']
display_board(test_board)

OUT:

 7 | 8 | 9
---|---|---
 4 | 5 | 6
---|---|---
 1 | 2 | 3


问:
Django model choices from database, another model
I'm trying to figure out how to allow for a model to take only certain values. But I can't use IntegerField with choices option because it's product database with couple thousand products. To be more precise- I'm trying to create app which manages product orders. For now my models are:

```<code>class Order(models.Model):
    timestamp = models.DateField(auto_now_add=True)
    komentarz = models.CharField(max_length=150, unique=False)

class Product(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    r = models.CharField(max_length=50, unique=False)
    s = models.CharField(max_length=50, unique=False)
    p = models.CharField(max_length=50, unique=False)
</code>```

I created another app with product database, it contains around 3000 records.

```<code>class ProductBase(models.Model):
    r = models.CharField(max_length=50, unique=False)
    s = models.CharField(max_length=50, unique=False)
    p = models.CharField(max_length=50, unique=False)
</code>```

Basically I want to allow Product model to take values inside database made thanks to ProductBase model. Any idea what should I use?

EDIT:
To make it more clear:

```<code>R S P
Name 1 Parameter S Parameter P
Name 2 Parameter S Parameter P
Name 3 Parameter S Parameter P
</code>```

This is ProductBase database. I want to allow Product to take only one of these three values. (in reality it's 3000)

答:
To allow only a specific set of values in Product model, base on some 'condition', I would just check this condition in the view function before saving a new Product object to the database.
So if you get r, s, p to create new Product, let say from a form, then check whether the condition is met, then you save new Product object to db or not.

Let just say that set of r, s, p values must be exactly that same in Product and ProductBase. Example could be sth like that:

```<code># receive data from the form
r_value = form.clean_data.get("r")
s_value = form.clean_data.get("s")
p_value = form.clean_data.get("p")

# Your condition
check_db = ProductBase.object.filter(
    s=s_value).filter(r=r_value).filter(p=p_value).exists()

if check_db:
    # create new product
    new_product = Product.object.create( #here goes values r, s, p )
    new_product.save()
else:
    # soma kind of feedback to user

</code>```

The condition could be whatever you want, just change the logic.

Body:
I'm trying to figure out how to allow for a model to take only certain values. But I can't use IntegerField with choices option because it's product database with couple thousand products. To be more precise- I'm trying to create app which manages product orders. For now my models are:

class Order(models.Model):
    timestamp = models.DateField(auto_now_add=True)
    komentarz = models.CharField(max_length=150, unique=False)

class Product(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    r = models.CharField(max_length=50, unique=False)
    s = models.CharField(max_length=50, unique=False)
    p = models.CharField(max_length=50, unique=False)

I created another app with product database, it contains around 3000 records.

class ProductBase(models.Model):
    r = models.CharField(max_length=50, unique=False)
    s = models.CharField(max_length=50, unique=False)
    p = models.CharField(max_length=50, unique=False)

Basically I want to allow Product model to take values inside database made thanks to ProductBase model. Any idea what should I use?

EDIT:
To make it more clear:

R S P
Name 1 Parameter S Parameter P
Name 2 Parameter S Parameter P
Name 3 Parameter S Parameter P

This is ProductBase database. I want to allow Product to take only one of these three values. (in reality it's 3000)

Body:
To allow only a specific set of values in Product model, base on some 'condition', I would just check this condition in the view function before saving a new Product object to the database.
So if you get r, s, p to create new Product, let say from a form, then check whether the condition is met, then you save new Product object to db or not.

Let just say that set of r, s, p values must be exactly that same in Product and ProductBase. Example could be sth like that:

# receive data from the form
r_value = form.clean_data.get("r")
s_value = form.clean_data.get("s")
p_value = form.clean_data.get("p")

# Your condition
check_db = ProductBase.object.filter(
    s=s_value).filter(r=r_value).filter(p=p_value).exists()

if check_db:
    # create new product
    new_product = Product.object.create( #here goes values r, s, p )
    new_product.save()
else:
    # soma kind of feedback to user

The condition could be whatever you want, just change the logic.


问:
debounce or throttle user input onKeyUp for a dropdown filter
I'm trying to implement de-bounce and throttle on user input on the search field for a drop-down filter.

I'm new to hooks, I'd de-bounced onChange functions of class components in a constructor but for some odd reason, hooks approach doesn't seem to work for me.

I tried many things referring to several posts on this, online. Had issues with the target value being null, fixed that but i don't feel like its de-bouncing or throttling user inputs at all.

I did use it directly onKeyUp={ e=>debounce(func, 2000) }, had issues with e being null

Please refer (https://mtsry.csb.app/) to get an idea of what I'm trying to achieve.

```<code>import React, {useState, useEffect} from 'react';
import './dropdownfilter.css';

function DropDownFilter() {

    const [options, setOptions] = useState(['Mytidbit', 'Deepak', 'Wassup', 'Deeps', 'Maolins', 'Test']);

    const [show, setShow] = useState(false);

    const [deBounce, setDebounce] = useState(true);

    const debounce = (fn,delay) => {
        let timeId;
        return function(...args){
            if(timeId){
                clearTimeout(timeId);
            }

            timeId = setTimeout(()=>{
                fn(...args);
            }, delay);
        }
    };

    function throttle(fn, delay){
        let last = 0;

        return (...args)=>{
         const now = new Date().getTime();
         if(now-last < delay){
             return;
         }

          last = now;
          return fn(...args);
        }
     }

    const filterOptions = (e)=>{
        const optionsCopy = [...options];
        let filteredOptions = optionsCopy.filter(opt=>opt.toLowerCase().includes(e.target.value.toLowerCase()));
        setOptions(filteredOptions);
    };

    const debounceKeyUp = (e) => {
        e.persist();
        filterOptions(e);
    };

    const throttleKeyUp = (e)=>{
         e.persist();
         filterOptions(e);
    };

    useEffect(()=>{
       debounce(debounceKeyUp, 2000);
       throttle(throttleKeyUp, 2000);
    },[]);

    const displayFilter = () => {
         setShow(!show);
    };

    const toggleFilter = ()=>{
        setDebounce(!deBounce)
    };

    return (
        <div className="dropdown">
            <button className="dropbtn" onClick={toggleFilter}>Change Filter Type</button><br/>
            <button onClick={displayFilter} className="dropbtn">{deBounce ? "DeBounce" : "Throttle"} <i className="arroww downn"></i></button>
            <div className={`dropdown-content ${show ? "show" : "hide"}`}>
                <input type="text" placeholder={deBounce ? "Try Debounce..." : "Try Throttle..."} className="filter-input" onKeyUp={deBounce ? e => {e.persist(); debounceKeyUp(e)} : e => {e.persist(); throttleKeyUp(e)}} />
                <i className="fa fa-fw fa-search" style={{position: 'relative', bottom: '34px', left: '5px'}}></i>
                {options.map((opt, i)=>(
                    <a key={i}>{opt}</a>
                ))}
            </div>
        </div>
    )
}

export default DropDownFilter;
</code>```

答:
You need to get instances of debounce and throttle function to use them. Unfortunately you are just calling debounce and throttle in useEffect but never use their returned function

You implementation doesn't need useEffect but useCallback like below

```<code>const debounceKeyUp = useCallback(debounce((e)=>{
     e.persist();
     filterOptions(e);
}, 2000), []);

const throttleKeyUp = useCallback(throttle((e)=>{
     e.persist();
     filterOptions(e);
}, 2000), []);
</code>```

Complete code:

function DropDownFilter() {

    const [options, setOptions] = useState(['Mytidbit', 'Deepak', 'Wassup', 'Deeps', 'Maolins', 'Test']);

    const [show, setShow] = useState(false);

    const [deBounce, setDebounce] = useState(true);

    const debounce = (fn,delay) => {
        let timeId;
        return function(...args){
            if(timeId){
                clearTimeout(timeId);
            }

            timeId = setTimeout(()=>{
                fn(...args);
            }, delay);
        }
    };

    function throttle(fn, delay){
        let last = 0;

        return (...args)=>{
         const now = new Date().getTime();
         if(now-last < delay){
             return;
         }

          last = now;
          return fn(...args);
        }
     }

    const filterOptions = (e)=>{
        const optionsCopy = [...options];
        let filteredOptions = optionsCopy.filter(opt=>opt.toLowerCase().includes(e.target.value.toLowerCase()));
        setOptions(filteredOptions);
    };

    const debounceKeyUp = useCallback(debounce((e)=>{
         e.persist();
         filterOptions(e);
    }, 2000), []);

    const throttleKeyUp = useCallback(throttle((e)=>{
         e.persist();
         filterOptions(e);
    }, 2000), []);

    const displayFilter = () => {
         setShow(!show);
    };

    const toggleFilter = ()=>{
        setDebounce(!deBounce)
    };

    return (

            <button className="dropbtn" onClick={toggleFilter}>Change Filter Type</button>

            <button onClick={displayFilter} className="dropbtn">{deBounce ? "DeBounce" : "Throttle"} </button>
            <div className={`dropdown-content ${show ? "show" : "hide"}`}>
                <input type="text" placeholder={deBounce ? "Try Debounce..." : "Try Throttle..."} className="filter-input" onKeyUp={deBounce ? e => {e.persist(); debounceKeyUp(e)} : e => {e.persist(); throttleKeyUp(e)}} />

                {options.map((opt, i)=>(
                    {opt}
                ))}

    )
}

export default DropDownFilter;
```

Body:
I'm trying to implement de-bounce and throttle on user input on the search field for a drop-down filter.

I'm new to hooks, I'd de-bounced onChange functions of class components in a constructor but for some odd reason, hooks approach doesn't seem to work for me.

I tried many things referring to several posts on this, online. Had issues with the target value being null, fixed that but i don't feel like its de-bouncing or throttling user inputs at all.

I did use it directly onKeyUp={ e=>debounce(func, 2000) }, had issues with e being null

Please refer (https://mtsry.csb.app/) to get an idea of what I'm trying to achieve.

import React, {useState, useEffect} from 'react';
import './dropdownfilter.css';

function DropDownFilter() {

    const [options, setOptions] = useState(['Mytidbit', 'Deepak', 'Wassup', 'Deeps', 'Maolins', 'Test']);

    const [show, setShow] = useState(false);

    const [deBounce, setDebounce] = useState(true);

    const debounce = (fn,delay) => {
        let timeId;
        return function(...args){
            if(timeId){
                clearTimeout(timeId);
            }

            timeId = setTimeout(()=>{
                fn(...args);
            }, delay);
        }
    };

    function throttle(fn, delay){
        let last = 0;

        return (...args)=>{
         const now = new Date().getTime();
         if(now-last < delay){
             return;
         }

          last = now;
          return fn(...args);
        }
     }

    const filterOptions = (e)=>{
        const optionsCopy = [...options];
        let filteredOptions = optionsCopy.filter(opt=>opt.toLowerCase().includes(e.target.value.toLowerCase()));
        setOptions(filteredOptions);
    };

    const debounceKeyUp = (e) => {
        e.persist();
        filterOptions(e);
    };

    const throttleKeyUp = (e)=>{
         e.persist();
         filterOptions(e);
    };

    useEffect(()=>{
       debounce(debounceKeyUp, 2000);
       throttle(throttleKeyUp, 2000);
    },[]);

    const displayFilter = () => {
         setShow(!show);
    };

    const toggleFilter = ()=>{
        setDebounce(!deBounce)
    };

    return (

            <button className="dropbtn" onClick={toggleFilter}>Change Filter Type</button>

            <button onClick={displayFilter} className="dropbtn">{deBounce ? "DeBounce" : "Throttle"} </button>
            <div className={`dropdown-content ${show ? "show" : "hide"}`}>
                <input type="text" placeholder={deBounce ? "Try Debounce..." : "Try Throttle..."} className="filter-input" onKeyUp={deBounce ? e => {e.persist(); debounceKeyUp(e)} : e => {e.persist(); throttleKeyUp(e)}} />

                {options.map((opt, i)=>(
                    {opt}
                ))}

    )
}

export default DropDownFilter;

Body:
You need to get instances of debounce and throttle function to use them. Unfortunately you are just calling debounce and throttle in useEffect but never use their returned function

You implementation doesn't need useEffect but useCallback like below

const debounceKeyUp = useCallback(debounce((e)=>{
     e.persist();
     filterOptions(e);
}, 2000), []);

const throttleKeyUp = useCallback(throttle((e)=>{
     e.persist();
     filterOptions(e);
}, 2000), []);

Complete code:

function DropDownFilter() {

    const [options, setOptions] = useState(['Mytidbit', 'Deepak', 'Wassup', 'Deeps', 'Maolins', 'Test']);

    const [show, setShow] = useState(false);

    const [deBounce, setDebounce] = useState(true);

    const debounce = (fn,delay) => {
        let timeId;
        return function(...args){
            if(timeId){
                clearTimeout(timeId);
            }

            timeId = setTimeout(()=>{
                fn(...args);
            }, delay);
        }
    };

    function throttle(fn, delay){
        let last = 0;

        return (...args)=>{
         const now = new Date().getTime();
         if(now-last < delay){
             return;
         }

          last = now;
          return fn(...args);
        }
     }

    const filterOptions = (e)=>{
        const optionsCopy = [...options];
        let filteredOptions = optionsCopy.filter(opt=>opt.toLowerCase().includes(e.target.value.toLowerCase()));
        setOptions(filteredOptions);
    };

    const debounceKeyUp = useCallback(debounce((e)=>{
         e.persist();
         filterOptions(e);
    }, 2000), []);

    const throttleKeyUp = useCallback(throttle((e)=>{
         e.persist();
         filterOptions(e);
    }, 2000), []);

    const displayFilter = () => {
         setShow(!show);
    };

    const toggleFilter = ()=>{
        setDebounce(!deBounce)
    };

    return (
        <div className="dropdown">
            <button className="dropbtn" onClick={toggleFilter}>Change Filter Type</button><br/>
            <button onClick={displayFilter} className="dropbtn">{deBounce ? "DeBounce" : "Throttle"} <i className="arroww downn"></i></button>
            <div className={`dropdown-content ${show ? "show" : "hide"}`}>
                <input type="text" placeholder={deBounce ? "Try Debounce..." : "Try Throttle..."} className="filter-input" onKeyUp={deBounce ? e => {e.persist(); debounceKeyUp(e)} : e => {e.persist(); throttleKeyUp(e)}} />
                <i className="fa fa-fw fa-search" style={{position: 'relative', bottom: '34px', left: '5px'}}></i>
                {options.map((opt, i)=>(
                    <a key={i}>{opt}</a>
                ))}
            </div>
        </div>
    )
}

export default DropDownFilter;


问:
isEmpty condition inside ngFor in Angular
i have a project in which i display doctor's daily schedule.

i have created an array called "dates" which contains next 7 dates in string form

i have a time packet like class called scheduleTime

which have

```<code>export class ScheduleTime{
    date: string;
    hours: number;
    minutes: number;
}
</code>```

i recieve an array called as "Schedule Time"of scheduleTime type which contains the date ,hours and minutes

and i display it accordingly

and here is my html code

```<code>       <div *ngFor="let Date of dates; let z = index" class="dateBox">
                     <div *ngFor="let time of ScheduleTime; let i = index">
                            <div *ngIf="Date == time.date">
                                <div class="timeSlots" [style.background-color]="startSelect>=0 && endSelect>0 && i>startSelect && i<endSelect?'rgb(207, 200, 238)':null" [ngClass]="{'startClass': time.hours == st.sh && time.minutes == st.sm && startDate == time.date, 'endClass': time.hours == et.eh && time.minutes == et.em && startDate == time.date}"
                                            (click)='timeSelector(time,i,todayDate)'>
                                            {{time.hours}}:{{time.minutes | zero}}
                                </div>
                    </div>
              </div>
         </div>
</code>```

in this html code i print time slots for each next 7 dates by comparing the time packets

here is an example image:

here is my relevant data stucode:

```<code>dates = [];

ScheduleTime: ScheduleTime[] = [];

</code>```

the problem is : i want that if there are no time packets for particular date it should display "No available schedules"

答:
On which you want to put the condtion and use that variable and in if put that html which you wanna show and in ng-template put like no record found or something.</p>

```<code>   <div  *ngFor="let Date of dates; let z = index" class="dateBox">
<div *ngIf="ScheduleTime; else notExist";>
                         <div  *ngFor="let time of ScheduleTime; let i = index">
                                <div *ngIf="Date == time.date">
                                    <div class="timeSlots" [style.background-color]="startSelect>=0 && endSelect>0 && i>startSelect && i<endSelect?'rgb(207, 200, 238)':null" [ngClass]="{'startClass': time.hours == st.sh && time.minutes == st.sm && startDate == time.date, 'endClass': time.hours == et.eh && time.minutes == et.em && startDate == time.date}"
                                                (click)='timeSelector(time,i,todayDate)'>
                                                {{time.hours}}:{{time.minutes | zero}}
                                    </div>
                        </div>
                  </div>
</div>
    <ng-template #notExist>
            No available schedules
        </ng-template>
           </div>
</code>```

Body:
i have a project in which i display doctor's daily schedule.

i have created an array called "dates" which contains next 7 dates in string form

i have a time packet like class called scheduleTime

which have

export class ScheduleTime{
    date: string;
    hours: number;
    minutes: number;
}

i recieve an array called as "Schedule Time"of scheduleTime type which contains the date ,hours and minutes

and i display it accordingly

and here is my html code

=0 && endSelect>0 && i>startSelect && i<endSelect?'rgb(207, 200, 238)':null" [ngClass]="{'startClass': time.hours == st.sh && time.minutes == st.sm && startDate == time.date, 'endClass': time.hours == et.eh && time.minutes == et.em && startDate == time.date}"
                                            (click)='timeSelector(time,i,todayDate)'>
                                            {{time.hours}}:{{time.minutes | zero}}

in this html code i print time slots for each next 7 dates by comparing the time packets

here is an example image:

here is my relevant data stucode:

dates = [];

ScheduleTime: ScheduleTime[] = [];

the problem is : i want that if there are no time packets for particular date it should display "No available schedules"

Body:
On which you want to put the condtion and use that variable and in if put that html which you wanna show and in ng-template put like no record found or something.

   <div  *ngFor="let Date of dates; let z = index" class="dateBox">
<div *ngIf="ScheduleTime; else notExist";>
                         <div  *ngFor="let time of ScheduleTime; let i = index">
                                <div *ngIf="Date == time.date">
                                    <div class="timeSlots" [style.background-color]="startSelect>=0 && endSelect>0 && i>startSelect && i<endSelect?'rgb(207, 200, 238)':null" [ngClass]="{'startClass': time.hours == st.sh && time.minutes == st.sm && startDate == time.date, 'endClass': time.hours == et.eh && time.minutes == et.em && startDate == time.date}"
                                                (click)='timeSelector(time,i,todayDate)'>
                                                {{time.hours}}:{{time.minutes | zero}}
                                    </div>
                        </div>
                  </div>
</div>
    <ng-template #notExist>
            No available schedules
        </ng-template>
           </div>


问:
Sorting a list of RGB triplets into a spectrum
I have a list of RGB triplets, and I'd like to plot them in such a way that they form something like a spectrum.

I've converted them to HSV, which people seem to recommend.

```<code>from PIL import Image, ImageDraw
import colorsys

def make_rainbow_rgb(colors, width, height):
    """colors is an array of RGB tuples, with values between 0 and 255"""

    img = Image.new("RGBA", (width, height))
    canvas = ImageDraw.Draw(img)

    def hsl(x):
        to_float = lambda x : x / 255.0
        (r, g, b) = map(to_float, x)
        h, s, l = colorsys.rgb_to_hsv(r,g,b)
        h = h if 0 < h else 1 # 0 -> 1
        return h, s, l

    rainbow = sorted(colors, key=hsl)

    dx = width / float(len(colors))
    x = 0
    y = height / 2.0
    for rgb in rainbow:
        canvas.line((x, y, x + dx, y), width=height, fill=rgb)
        x += dx
    img.show()
</code>```

However, the result doesn't look very much like a nice rainbow-y spectrum. I suspect I need to either convert to a different color space or handle the HSL triplet differently.

Does anyone know what I need to do to make this data look roughly like a rainbow?

Update:

I was playing around with Hilbert curves and revisited this problem. Sorting the RGB values (same colors in both images) by their position along a Hilbert curve yields an interesting (if still not entirely satisfying) result:

答:
Here are some rainbows I made recently, you can modify the idea to do what you want

```<code>from PIL import Image, ImageDraw  # pip install pillow
import numpy as np
from matplotlib import pyplot as plt

strip_h, strip_w = 100, 720
strip = 255*np.ones((strip_h,strip_w,3), dtype='uint8')
image_val = Image.fromarray(strip)
image_sat = Image.fromarray(strip)
draw0 = ImageDraw.Draw(image_val)
draw1 = ImageDraw.Draw(image_sat)
for y in range(strip_h):
    for x in range(strip_w):
        draw0.point([x, y], fill='hsl(%d,%d%%,%d%%)'%(x%360,y,50))
        draw1.point([x, y], fill='hsl(%d,%d%%,%d%%)'%(x%360,100,y))

plt.subplot(2,1,1)
plt.imshow(image_val)
plt.subplot(2,1,2)
plt.imshow(image_sat)
plt.show()
</code>```

Body:
I have a list of RGB triplets, and I'd like to plot them in such a way that they form something like a spectrum.

I've converted them to HSV, which people seem to recommend.

from PIL import Image, ImageDraw
import colorsys

def make_rainbow_rgb(colors, width, height):
    """colors is an array of RGB tuples, with values between 0 and 255"""

    img = Image.new("RGBA", (width, height))
    canvas = ImageDraw.Draw(img)

    def hsl(x):
        to_float = lambda x : x / 255.0
        (r, g, b) = map(to_float, x)
        h, s, l = colorsys.rgb_to_hsv(r,g,b)
        h = h if 0 < h else 1 # 0 -> 1
        return h, s, l

    rainbow = sorted(colors, key=hsl)

    dx = width / float(len(colors))
    x = 0
    y = height / 2.0
    for rgb in rainbow:
        canvas.line((x, y, x + dx, y), width=height, fill=rgb)
        x += dx
    img.show()

However, the result doesn't look very much like a nice rainbow-y spectrum. I suspect I need to either convert to a different color space or handle the HSL triplet differently.

Does anyone know what I need to do to make this data look roughly like a rainbow?

Update:

I was playing around with Hilbert curves and revisited this problem. Sorting the RGB values (same colors in both images) by their position along a Hilbert curve yields an interesting (if still not entirely satisfying) result:

Body:
Here are some rainbows I made recently, you can modify the idea to do what you want

from PIL import Image, ImageDraw  # pip install pillow
import numpy as np
from matplotlib import pyplot as plt

strip_h, strip_w = 100, 720
strip = 255*np.ones((strip_h,strip_w,3), dtype='uint8')
image_val = Image.fromarray(strip)
image_sat = Image.fromarray(strip)
draw0 = ImageDraw.Draw(image_val)
draw1 = ImageDraw.Draw(image_sat)
for y in range(strip_h):
    for x in range(strip_w):
        draw0.point([x, y], fill='hsl(%d,%d%%,%d%%)'%(x%360,y,50))
        draw1.point([x, y], fill='hsl(%d,%d%%,%d%%)'%(x%360,100,y))

plt.subplot(2,1,1)
plt.imshow(image_val)
plt.subplot(2,1,2)
plt.imshow(image_sat)
plt.show()


问:
Django Broken INTERNAL link on otherIPAddress
Why do I get "Broken INTERNAL link on xyz", where xyz is NOT the IP address of the server where the website is hosted?

To be more specific: my website address is 'myExample.com' and there is another IP address let's call it 'anotherExample'. I get 'Broken INTERNAL link on anotherExample'. The referrer is 'http://anotherExample/somePHPFile.php' and the Requested URL is of course '/somePHPFile.php'.

答:
You probably have the middleware django.middleware.common.BrokenLinkEmailsMiddleware enabled. According to Django docs it sends broken link notification emails to MANAGERS.

Solution: just remove the BrokenLinkEmailsMiddleware item from MIDDLEWARES in your settings.py.


问:
Display separate sections of an html page on a button click
Good day,

I'm tring to display separately two sections (p1 and p2) of my html page. In other words, when I click on 1st button, I would like section "p1" to be displayed and section "p2" to be hidden, and conversely when I click on button p2, I would like only section "p2" to be visible.

So far, I am not very successful in my attempts.

Do you have any hints which would be of great help to progress ?

Many thanks for your time and best wishes

Here below is my html code:

```<code><!DOCTYPE html>
  <head>
    <link rel="stylesheet" type="text/css" href="css/mystyle.css?rnd=999" />
    <script type="text/javascript" src="scripts/date_time.js"></script>
    <script type="text/javascript" src="scripts/demo.js"></script>
  </head>
  <body>
  <div class="div_screen">
    <div class="div_screen_left_frame">
        <div class="div_screen_icon">
          <img src="assets/icons/logo_Domoos.png" alt ="" style="width:80px;height:58px;">
        </div>
        <div class="div_screen_nav1">
          <ul id="menu">
            <button class="cupid-blue" href="#p1"> Display section 1 (p1)
            <button class="cupid-blue" href="#p2"> Display section 2 (p2)
          </ul>
        </div>
    </div>
    <div class="div_screen_contents_frame">
    <div class="page" id="p1">
    <section class="icon fa fa-bolt"><span class="title">Bolt</span><span class="hint">This is the first part I would like to show separately</span>    </section>
    </div>
    <div class="page" id="p2">
    <section class="icon fa fa-bolt"><span class="title">Bolt</span><span class="hint">This is the second part I would like to show separately</span>   </section>
    </div>    </div>
    <div class="div_screen_up_frame">
      <div class="div_current_meteo_frame">
        <div class="div_current_meteo_icon">
          <img src="assets/meteo_icons/eclaircies-big.png" alt="" style="width:55px;height:55px;">
        </div>
        <div class="div_current_meteo_temperature">-23°C</div>
        <div class="div_current_meteo_condition">Nuit avec averses de neige faible</div>
        <div class="div_sunrise_sunset">
          <img src="assets/icons/sun_icon.png" alt="" width="14" height="14">↑ 05:38 <img src="assets/icons/sun_icon.png" alt="" width="14" height="14">↓ 21:16
        </div>
          <div style="width:50px;height:50px;border:1px solid #000;"></div>
      </div>
      <div class="div_forecast_meteo_frame">
        <div class="div_forecast_meteo_day1">
          <div class="div_forecast_weekday">Vendredi</div>
          <div class="div_forecast_date">31.05.2020</div>
          <div class="div_forecast_icon">
            <img src="assets/meteo_icons/eclaircies.png" alt="" width="23" height="23">
          </div>
          <div class="div_forecast_text">Nuit avec développement nuageux</div>
          <div class="div_forecast_temperature">24°C | 15°C</div>
        </div>
        <div class="div_forecast_meteo_day2">
          <div class="div_forecast_weekday">Samedi</div>
          <div class="div_forecast_date">99.99.9999</div>
          <div class="div_forecast_icon">
            <img src="assets/meteo_icons/eclaircies.png" alt="" width="23" height="23">
          </div>
          <div class="div_forecast_text">Nuit avec averses de neige faible</div>
          <div class="div_forecast_temperature">-24°C | -20°C</div>
        </div>
        <div class="div_forecast_meteo_day3">
          <div class="div_forecast_weekday">Dimanche</div>
          <div class="div_forecast_date">77.77.7777</div>
          <div class="div_forecast_icon">
            <img src="assets/meteo_icons/eclaircies.png" alt="" width="23" height="23">
          </div>
          <div class="div_forecast_text">Nuit avec averses de neige faible</div>
          <div class="div_forecast_temperature">-24°C | -20°C</div>
        </div>
      </div>
      <div class="div_screen_datetime">
        <div id="date">
          <script type="text/javascript">window.onload = getDate('date');</script>
        </div>
        <div id="time">
          <script type="text/javascript">window.onload = getTime('time');</script>
        </div>
      </div>
    </div>

    <div style="width:900px;height:540px;border:0px solid #ffaacc;"></div>
  </div>
  </body>
</html>
</code>```

Not quite sure if the css might be helpful, but here it is :

```<code>/* Three image containers (use 25% for four, and 50% for two, etc) */
.column {
float: left;
width: 19.0%;
padding: 2px;
}

/* Clear floats after image containers */
.row::after {
content: "";
clear: both;
display: table;
}

.div_screen {
font-family:"Quicksand", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
font-size: 90%;
color: blue;
position: fixed;
top: -3;
left: -3;
width: 1005px;
height: 540 px;
border: 2px solid #de2be4;
}

.div_screen_datetime
{
position: absolute;
right: 1px;
top: 0;
width: 170px;
border: 1px solid red;
font-size: 120%;
text-align: right;
height: 95px; /*50*/
}

.div_screen_up_frame {
position: absolute;
left: 150px;
top: 1px;
width: 852px;
height:95px;
border: 1px solid blue;
}

.div_screen_left_frame {
position: absolute;
left: 1px;
top: 1px;
width: 146px;
height:536px;
border: 1px solid blue;
}

.div_screen_contents_frame {
position: absolute;
left: 150px;
top: 99px;
width: 852px;
height:438px;
border: 1px solid blue;
}

.div_screen_icon {
position: absolute;
left: 0px;
top: 0px;
width: 145px;
height: 95px;
border: 1px solid black;
}

.div_screen_nav1 {
position: absolute;
left: 0px;
top: 95px;
width: 145px;
height: 300px;
border: 1px solid black;
}

.div_screen_nav2 {
position: absolute;
left: 0px;
top: 398px;
width: 145px;
height: 137px;
border: 1px solid black;
}

.div_current_meteo_frame {
position: absolute;
left: 0px;
top: 0px;
width: 185px;
height:95px;
border: 1px solid black;
}

.div_sunrise_sunset {
position: absolute;
font-size: 75%;
left: 2px;
top: 72px;
}

.div_current_meteo_icon {
position: absolute;
left: -5px;
top: 1px;
width: 100px;
}

.div_current_meteo_temperature {
position: absolute;
font-size: 250%;
/*text-align: center;*/
left: 80px;
top: 0px;
color: black;
}

.div_current_meteo_condition {
position: absolute;
font-size: 75%;
/*text-align: center;*/
left: 2px;
top: 55px;
color: black;
}

.div_forecast_meteo_frame {
position: absolute;
left: 186px;
top: 0px;
width: 492px;
height:95px;
border: 1px solid black;
}

.div_forecast_meteo_day1 {
position: absolute;
font-size: 95%;
left: 1px;
top: 1px;
width: 489px;
height:29px;
border: 1px solid #73AD21;
}

.div_forecast_meteo_day2 {
position: absolute;
font-size: 95%;
left: 1px;
top: 31px;
width: 489px;
height:29px;
border: 1px solid #73AD21;
}

.div_forecast_meteo_day3 {
position: absolute;
font-size: 95%;
left: 1px;
top: 61px;
width: 489px;
height:29px;
border: 1px solid #73AD21;
}

.div_forecast_weekday {
position: absolute;
font-size: 100%;
color: black;
left: 0px;
top: 2px;
text-align: left;
border: 1px solid yellow;
}

.div_forecast_date {
position: absolute;
font-size: 100%;
color: black;
left: 65px;
top: 2px;
text-align: left;
border: 1px solid yellow;
}

.div_forecast_icon {
position: absolute;
font-size: 100%;
color: black;
left: 138px;
text-align: left;
border: 1px solid yellow;
}

.div_forecast_text {
position: absolute;
font-size: 100%;
color: black;
left: 165px;
top: 2px;
text-align: left;
border: 1px solid yellow;
}

.div_forecast_temperature {
position: absolute;
font-size: 100%;
color: black;
right: 1px;
top: 2px;
text-align: right;
border: 1px solid yellow;
}

button.cupid-blue {
background-color: #d7e5f5;
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #d7e5f5), color-stop(100%, #cbe0f5));
background-image: -webkit-linear-gradient(top, #d7e5f5, #cbe0f5);
background-image: -moz-linear-gradient(top, #d7e5f5, #cbe0f5);
background-image: -ms-linear-gradient(top, #d7e5f5, #cbe0f5);
background-image: -o-linear-gradient(top, #d7e5f5, #cbe0f5);
background-image: linear-gradient(top, #d7e5f5, #cbe0f5);
border-top: 1px solid #abbbcc;
border-left: 1px solid #a7b6c7;
border-bottom: 1px solid #a1afbf;
border-right: 1px solid #a7b6c7;
border-radius: 12px;
-webkit-box-shadow: inset 0 1px 0 0 white;
box-shadow: inset 0 1px 0 0 white;
color: #1a3e66;
font: normal 11px/1 "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
padding: 6px 0 3px 0;
text-align: center;
text-shadow: 0 1px 1px #fff;
width: 140px;
height: 40px;
margin-top: 5px;
margin-bottom: 5px;
left: 5 px;

}

ul {
  position: absolute;
  z-index: 1;
  top: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 10%;
  padding: 0;
  text-align: center;
 }
</code>```

答:
just find the clicked item related div and show it and hide the other one.
I have created the logic, just use it in your code

$(document).ready(function(){
  $('#menu button').click(function(){
    var hrefId = $(this).attr('href');
    $('.div_screen_contents_frame .page').hide();
    $('.div_screen_contents_frame').find(hrefId).show();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.page{display: none;}
.page.active {display: block;}</code>```

            <button class="cupid-blue" href="#p1"> Display section 1 (p1)
            <button class="cupid-blue" href="#p2"> Display section 2 (p2)

BoltThis is the first part I would like to show separately

BoltThis is the second part I would like to show separately

```
</div>
</div>
</p>

<p>use below part as it is in your code, as you asked in Comment</p>

```

```

<p>as per our Discussion I am adding a pure JS solution here. Check it.</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>function toggleDisplay(className, displayState){
    var elements = document.getElementsByClassName(className)
    for (var i = 0; i < elements.length; i++){
        elements[i].style.display = displayState;
    }
  }
  function toggle(){
    document.onclick = function(e) {
      if (e.target.tagName == 'BUTTON') {
        var href = e.target.getAttribute("href");
        toggleDisplay('page', 'none');
        document.getElementById(href).style.display = 'block';
      }
    }
  }</code>```

.page{display: none;}
.page.active {display: block;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="menu">
        <button class="cupid-blue" href="p1" id="btnOne" onclick="toggle(this)"> Display section 1 (p1)</button>
        <button class="cupid-blue" href="p2" id="btnTwo" onclick="toggle(this)"> Display section 2 (p2)</button>
    </ul>
    </div>
    </div>
    <div class="div_screen_contents_frame">
        <div class="page active" id="p1">
            <section class="icon fa fa-bolt" id="pOne"><span class="title">Bolt</span><span class="hint">This is the first part I would like to show separately</span> </section>
        </div>
        <div class="page" id="p2">
            <section class="icon fa fa-bolt" id="pTwo"><span class="title">Bolt</span><span class="hint">This is the second part I would like to show separately</span> </section>
        </div>
    </div></code>```

Body:
Good day,

I'm tring to display separately two sections (p1 and p2) of my html page. In other words, when I click on 1st button, I would like section "p1" to be displayed and section "p2" to be hidden, and conversely when I click on button p2, I would like only section "p2" to be visible.

So far, I am not very successful in my attempts.

Do you have any hints which would be of great help to progress ?

Many thanks for your time and best wishes

Here below is my html code:

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="css/mystyle.css?rnd=999" />

            <button class="cupid-blue" href="#p1"> Display section 1 (p1)
            <button class="cupid-blue" href="#p2"> Display section 2 (p2)

BoltThis is the first part I would like to show separately

BoltThis is the second part I would like to show separately

-23°C

Nuit avec averses de neige faible

          ↑ 05:38 ↓ 21:16

Vendredi

31.05.2020

Nuit avec développement nuageux

24°C | 15°C

Samedi

99.99.9999

Nuit avec averses de neige faible

-24°C | -20°C

Dimanche

77.77.7777

Nuit avec averses de neige faible

-24°C | -20°C

Not quite sure if the css might be helpful, but here it is :

/* Three image containers (use 25% for four, and 50% for two, etc) */
.column {
float: left;
width: 19.0%;
padding: 2px;
}

/* Clear floats after image containers */
.row::after {
content: "";
clear: both;
display: table;
}

.div_screen {
font-family:"Quicksand", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
font-size: 90%;
color: blue;
position: fixed;
top: -3;
left: -3;
width: 1005px;
height: 540 px;
border: 2px solid #de2be4;
}

.div_screen_datetime
{
position: absolute;
right: 1px;
top: 0;
width: 170px;
border: 1px solid red;
font-size: 120%;
text-align: right;
height: 95px; /*50*/
}

.div_screen_up_frame {
position: absolute;
left: 150px;
top: 1px;
width: 852px;
height:95px;
border: 1px solid blue;
}

.div_screen_left_frame {
position: absolute;
left: 1px;
top: 1px;
width: 146px;
height:536px;
border: 1px solid blue;
}

.div_screen_contents_frame {
position: absolute;
left: 150px;
top: 99px;
width: 852px;
height:438px;
border: 1px solid blue;
}

.div_screen_icon {
position: absolute;
left: 0px;
top: 0px;
width: 145px;
height: 95px;
border: 1px solid black;
}

.div_screen_nav1 {
position: absolute;
left: 0px;
top: 95px;
width: 145px;
height: 300px;
border: 1px solid black;
}

.div_screen_nav2 {
position: absolute;
left: 0px;
top: 398px;
width: 145px;
height: 137px;
border: 1px solid black;
}

.div_current_meteo_frame {
position: absolute;
left: 0px;
top: 0px;
width: 185px;
height:95px;
border: 1px solid black;
}

.div_sunrise_sunset {
position: absolute;
font-size: 75%;
left: 2px;
top: 72px;
}

.div_current_meteo_icon {
position: absolute;
left: -5px;
top: 1px;
width: 100px;
}

.div_current_meteo_temperature {
position: absolute;
font-size: 250%;
/*text-align: center;*/
left: 80px;
top: 0px;
color: black;
}

.div_current_meteo_condition {
position: absolute;
font-size: 75%;
/*text-align: center;*/
left: 2px;
top: 55px;
color: black;
}

.div_forecast_meteo_frame {
position: absolute;
left: 186px;
top: 0px;
width: 492px;
height:95px;
border: 1px solid black;
}

.div_forecast_meteo_day1 {
position: absolute;
font-size: 95%;
left: 1px;
top: 1px;
width: 489px;
height:29px;
border: 1px solid #73AD21;
}

.div_forecast_meteo_day2 {
position: absolute;
font-size: 95%;
left: 1px;
top: 31px;
width: 489px;
height:29px;
border: 1px solid #73AD21;
}

.div_forecast_meteo_day3 {
position: absolute;
font-size: 95%;
left: 1px;
top: 61px;
width: 489px;
height:29px;
border: 1px solid #73AD21;
}

.div_forecast_weekday {
position: absolute;
font-size: 100%;
color: black;
left: 0px;
top: 2px;
text-align: left;
border: 1px solid yellow;
}

.div_forecast_date {
position: absolute;
font-size: 100%;
color: black;
left: 65px;
top: 2px;
text-align: left;
border: 1px solid yellow;
}

.div_forecast_icon {
position: absolute;
font-size: 100%;
color: black;
left: 138px;
text-align: left;
border: 1px solid yellow;
}

.div_forecast_text {
position: absolute;
font-size: 100%;
color: black;
left: 165px;
top: 2px;
text-align: left;
border: 1px solid yellow;
}

.div_forecast_temperature {
position: absolute;
font-size: 100%;
color: black;
right: 1px;
top: 2px;
text-align: right;
border: 1px solid yellow;
}

button.cupid-blue {
background-color: #d7e5f5;
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #d7e5f5), color-stop(100%, #cbe0f5));
background-image: -webkit-linear-gradient(top, #d7e5f5, #cbe0f5);
background-image: -moz-linear-gradient(top, #d7e5f5, #cbe0f5);
background-image: -ms-linear-gradient(top, #d7e5f5, #cbe0f5);
background-image: -o-linear-gradient(top, #d7e5f5, #cbe0f5);
background-image: linear-gradient(top, #d7e5f5, #cbe0f5);
border-top: 1px solid #abbbcc;
border-left: 1px solid #a7b6c7;
border-bottom: 1px solid #a1afbf;
border-right: 1px solid #a7b6c7;
border-radius: 12px;
-webkit-box-shadow: inset 0 1px 0 0 white;
box-shadow: inset 0 1px 0 0 white;
color: #1a3e66;
font: normal 11px/1 "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
padding: 6px 0 3px 0;
text-align: center;
text-shadow: 0 1px 1px #fff;
width: 140px;
height: 40px;
margin-top: 5px;
margin-bottom: 5px;
left: 5 px;

}

ul {
  position: absolute;
  z-index: 1;
  top: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 10%;
  padding: 0;
  text-align: center;
 }

Body:
just find the clicked item related div and show it and hide the other one.
I have created the logic, just use it in your code

$(document).ready(function(){
  $('#menu button').click(function(){
    var hrefId = $(this).attr('href');
    $('.div_screen_contents_frame .page').hide();
    $('.div_screen_contents_frame').find(hrefId).show();
  });
});

.page{display: none;}
.page.active {display: block;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="menu">
            <button class="cupid-blue" href="#p1"> Display section 1 (p1)
            <button class="cupid-blue" href="#p2"> Display section 2 (p2)
          </ul>
        </div>
    </div>
    <div class="div_screen_contents_frame">
    <div class="page active" id="p1">
    <section class="icon fa fa-bolt"><span class="title">Bolt</span><span class="hint">This is the first part I would like to show separately</span>    </section>
    </div>
    <div class="page" id="p2">
    <section class="icon fa fa-bolt"><span class="title">Bolt</span><span class="hint">This is the second part I would like to show separately</span>   </section>
    </div>

use below part as it is in your code, as you asked in Comment

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>$(document).ready(function(){

$('#menu button').click(function(){
   var hrefId = $(this).attr('href');
   $('.div_screen_contents_frame .page').hide();
   $('.div_screen_contents_frame').find(hrefId).show();
 });
});</script>

as per our Discussion I am adding a pure JS solution here. Check it.

function toggleDisplay(className, displayState){
    var elements = document.getElementsByClassName(className)
    for (var i = 0; i < elements.length; i++){
        elements[i].style.display = displayState;
    }
  }
  function toggle(){
    document.onclick = function(e) {
      if (e.target.tagName == 'BUTTON') {
        var href = e.target.getAttribute("href");
        toggleDisplay('page', 'none');
        document.getElementById(href).style.display = 'block';
      }
    }
  }

.page{display: none;}
.page.active {display: block;}

<ul id="menu">
        <button class="cupid-blue" href="p1" id="btnOne" onclick="toggle(this)"> Display section 1 (p1)</button>
        <button class="cupid-blue" href="p2" id="btnTwo" onclick="toggle(this)"> Display section 2 (p2)</button>
    </ul>
    </div>
    </div>
    <div class="div_screen_contents_frame">
        <div class="page active" id="p1">
            <section class="icon fa fa-bolt" id="pOne"><span class="title">Bolt</span><span class="hint">This is the first part I would like to show separately</span> </section>
        </div>
        <div class="page" id="p2">
            <section class="icon fa fa-bolt" id="pTwo"><span class="title">Bolt</span><span class="hint">This is the second part I would like to show separately</span> </section>
        </div>
    </div>