问:
React useEffect behavior
Having such a simple React component:

```<code>import React, { FunctionComponent, useEffect, useState } from 'react';

export function useMediaQuery(query:string) {

    console.log("useMediaQuery")

    useEffect(() => {
        console.log("useEffect outer")
        // ...
    });

}

const Sidebar: FunctionComponent = () => {

    const istoBeHidden = useMediaQuery('(min-width: 700px)')
    console.log("returned from useMediaQuery")
    useEffect(() => console.log("useEffect inner"))

    return (
        <div>
            <p>Sidebar</p>
            {/* <button onClick={myFunction}>Click me</button> */}
        </div>
    )
};

export {Sidebar}
</code>```

I'm getting the following output in the console:

useMediaQuery

returned from useMediaQuery

useEffect outer

useEffect inner

My question is WHY does the useEffect outer is called AFTER returning from the
useMediaQuery function (why does the line useEffect outer appears AFTER the line returned from useMediaQuery)!?

答:
useMediaQuery is a hook inside a functional component. Custom hook is just a way to encapsulate some logic into a function, which might/might not use state.

The custom hook code runs on every render. But you cannot expect the hook to run all its useEffects and get done with. The useEffect inside the custom hook is just like any useEffect, it will run based on its dependency array.

It has no dependency array, so it will be called everytime there is a render, which happens every time the component rerenders.

function useMediaQuery(query) {
    console.log("useMediaQuery")
    React.useEffect(() => {
        console.log("useEffect outer")
    });

}

function App() {
    const istoBeHidden = useMediaQuery('(min-width: 700px)');
   const [count,setCount] =  React.useState(0);
    console.log("returned from useMediaQuery",count)
    React.useEffect(() => console.log("useEffect inner"))

    return (
<button onClick={() => setCount(count => count+1)}>Sidebar</button>
);
};

ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>

<div id="root"></div></code>```

Title: React useEffect behavior

Body:
Having such a simple React component:

import React, { FunctionComponent, useEffect, useState } from 'react';

export function useMediaQuery(query:string) {

    console.log("useMediaQuery")

    useEffect(() => {
        console.log("useEffect outer")
        // ...
    });

}

const Sidebar: FunctionComponent = () => {

    const istoBeHidden = useMediaQuery('(min-width: 700px)')
    console.log("returned from useMediaQuery")
    useEffect(() => console.log("useEffect inner"))

    return (

Sidebar

            {/* <button onClick={myFunction}>Click me</button> */}

    )
};

export {Sidebar}

I'm getting the following output in the console:

useMediaQuery

returned from useMediaQuery

useEffect outer

useEffect inner

My question is WHY does the useEffect outer is called AFTER returning from the
useMediaQuery function (why does the line useEffect outer appears AFTER the line returned from useMediaQuery)!?

Body:
useMediaQuery is a hook inside a functional component. Custom hook is just a way to encapsulate some logic into a function, which might/might not use state.

The custom hook code runs on every render. But you cannot expect the hook to run all its useEffects and get done with. The useEffect inside the custom hook is just like any useEffect, it will run based on its dependency array.

It has no dependency array, so it will be called everytime there is a render, which happens every time the component rerenders.

function useMediaQuery(query) {
    console.log("useMediaQuery")
    React.useEffect(() => {
        console.log("useEffect outer")
    });

}

function App() {
    const istoBeHidden = useMediaQuery('(min-width: 700px)');
   const [count,setCount] =  React.useState(0);
    console.log("returned from useMediaQuery",count)
    React.useEffect(() => console.log("useEffect inner"))

    return (<div><button onClick={() => setCount(count => count+1)}>Sidebar</button></div>);
};

ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>

<div id="root"></div>


来源: stackexchange

问:
Unable to get input data value in console in NestJS
I am making an post request where I am posting phone number via Postman request.In Postman I have set Content-Type:application/json but I am getting empty obbject {} in console.Below is my Postman screenshot of setting header and posting value.

Below is my code:

subscriber.controller.ts

```<code>@Controller()
export class SubscribeController {
constructor(private subscribeService:SubscribeService){}

    @Post('location')
    async getLocation(@Body() phoneNumber:String){

    const loc = await this.subscribeService.getLocation(phoneNumber);
    return loc;
   }
}
</code>```

subscriber.service.ts

```<code>@Injectable()
export class SubscribeService {
constructor(private httpService: HttpService){}

      async getLocation(phoneNumber:String){

      return console.log(phoneNumber);
    }
}
</code>```

Someone let me know why its showing empty object in console.

答:
You are trying to pass a body object as a string value, update your @Body decorator with JSON key to specify phoneNumber data field:

  @Post('location')
  async getLocation(@Body('phoneNumber') thisIsJustTheVariableName: string) {
    console.log(thisIsJustTheVariableName); // will extract phoneNumber from your body object
  }
```
<hr />
<p>The better way of handling Request Body is to determine some <code>dto</code> objects for your example:</p>
<pre class="lang-js prettyprint-override"><code>  class SubscriberDto {
    phoneNumber: string;
    // may be some additional fields
  }

  @Post('location')
  async getLocation(@Body() sub: SubscriberDto) {
    console.log(sub.phoneNumber); // will extract phoneNumber from your body object
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making an post request where I am posting phone number via Postman request.In Postman I have set Content-Type:application/json but I am getting empty obbject {} in console.Below is my Postman screenshot of setting header and posting value.

Below is my code:

subscriber.controller.ts

@Controller()
export class SubscribeController {
constructor(private subscribeService:SubscribeService){}

    @Post('location')
    async getLocation(@Body() phoneNumber:String){

    const loc = await this.subscribeService.getLocation(phoneNumber);
    return loc;
   }
}

subscriber.service.ts

@Injectable()
export class SubscribeService {
constructor(private httpService: HttpService){}

      async getLocation(phoneNumber:String){

      return console.log(phoneNumber);
    }
}

Someone let me know why its showing empty object in console.

Body:
You are trying to pass a body object as a string value, update your @Body decorator with JSON key to specify phoneNumber data field:

  @Post('location')
  async getLocation(@Body('phoneNumber') thisIsJustTheVariableName: string) {
    console.log(thisIsJustTheVariableName); // will extract phoneNumber from your body object
  }

The better way of handling Request Body is to determine some dto objects for your example:

  class SubscriberDto {
    phoneNumber: string;
    // may be some additional fields
  }

  @Post('location')
  async getLocation(@Body() sub: SubscriberDto) {
    console.log(sub.phoneNumber); // will extract phoneNumber from your body object
  }


问:
How to create an array with random numbers and send it to listener without randomizing it again?
So i'm trying to create a program that create an array of 100 random numbers (without changing everytime user reacts to it), and allow users to check the numbers by entering the index of it. However, the array keep randomizing everytime the user pressed the Show Element button.

I also tried to create the array on the main program, but I then faced the error because the listener can't access the array. Please enlighten me as I'm new to this Java GUI Programming. Any help is much appreciated.

```<code>import java.util.Random;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;

public class P3Q2 extends JFrame {

    private JTextField text1 = new JTextField(10);
    private JTextField text2 = new JTextField(10);
    private int arr[];

    private JButton jbtShow = new JButton("Show Element");

    public P3Q2() {
        JPanel jpTextField = new JPanel();
        jpTextField.setLayout(new GridLayout(3, 2));
        jpTextField.add(new JLabel("Array Index"));
        jpTextField.add(text1);
        jpTextField.add(new JLabel("Array Element"));
        jpTextField.add(text2);
        text2.setEditable(false);

        JPanel jpButtons = new JPanel();
        jpButtons.add(jbtShow);

        add(jpTextField);
        add(jpButtons, BorderLayout.SOUTH);

        jbtShow.addActionListener(new ButtonListener());

        setTitle("Display: Show Bounds Error");
        setSize(400, 150);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            try {
                Random rd = new Random(); // creating Random object
                int[] arr = new int[100];
                for (int i = 0; i < arr.length; i++) {
                    arr[i] = rd.nextInt(); // storing random integers in an array
                }

                if (e.getSource() == jbtShow) {
                    int num = Integer.parseInt(text1.getText());
                    int result = arr[num];
                    text2.setText("" + result);
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                text2.setText("Out of bound!");
            }

        }
    }

    public static void main(String[] args) {
        P3Q2 test = new P3Q2();
    }
}
</code>```

答:
In the constructor you are assigning the random numbers to a local variable arr that is overriding the private attribute arr with the same name

Try changing it to:

```<code>Random rd = new Random(); // creating Random object
arr = new int[100];
for (int i = 0; i < arr.length; i++) {
    arr[i] = rd.nextInt(); // storing random integers in an array
}
</code>```

Body:
So i'm trying to create a program that create an array of 100 random numbers (without changing everytime user reacts to it), and allow users to check the numbers by entering the index of it. However, the array keep randomizing everytime the user pressed the Show Element button.

I also tried to create the array on the main program, but I then faced the error because the listener can't access the array. Please enlighten me as I'm new to this Java GUI Programming. Any help is much appreciated.

import java.util.Random;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;

public class P3Q2 extends JFrame {

    private JTextField text1 = new JTextField(10);
    private JTextField text2 = new JTextField(10);
    private int arr[];

    private JButton jbtShow = new JButton("Show Element");

    public P3Q2() {
        JPanel jpTextField = new JPanel();
        jpTextField.setLayout(new GridLayout(3, 2));
        jpTextField.add(new JLabel("Array Index"));
        jpTextField.add(text1);
        jpTextField.add(new JLabel("Array Element"));
        jpTextField.add(text2);
        text2.setEditable(false);

        JPanel jpButtons = new JPanel();
        jpButtons.add(jbtShow);

        add(jpTextField);
        add(jpButtons, BorderLayout.SOUTH);

        jbtShow.addActionListener(new ButtonListener());

        setTitle("Display: Show Bounds Error");
        setSize(400, 150);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            try {
                Random rd = new Random(); // creating Random object
                int[] arr = new int[100];
                for (int i = 0; i < arr.length; i++) {
                    arr[i] = rd.nextInt(); // storing random integers in an array
                }

                if (e.getSource() == jbtShow) {
                    int num = Integer.parseInt(text1.getText());
                    int result = arr[num];
                    text2.setText("" + result);
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                text2.setText("Out of bound!");
            }

        }
    }

    public static void main(String[] args) {
        P3Q2 test = new P3Q2();
    }
}

Body:
In the constructor you are assigning the random numbers to a local variable arr that is overriding the private attribute arr with the same name

Try changing it to:

Random rd = new Random(); // creating Random object
arr = new int[100];
for (int i = 0; i < arr.length; i++) {
    arr[i] = rd.nextInt(); // storing random integers in an array
}


问:
Do smart contract needs a SFT to call esdt_local_mint
My smart contract owns the SFT HAT-a1a1a1-01.

The SFT HAT-a1a1a1-02 also exists but isn't owned by the SC.

When I add local quantity to the SFT with the 02 nonce through a function, my transaction fails with this error:

```<code>new NFT data on sender
</code>```

Do I need to own the SFT HAT-a1a1a1-02 to mint it?

答:
I got an answer in another group:

Yes, you need to own at least 1 to AddQuantity, since otherwise, you wouldn't have the attributes. When you send an NFT/SFT, if your balance after is 0, the metadata is erased from your account.

Body:
My smart contract owns the SFT HAT-a1a1a1-01.

The SFT HAT-a1a1a1-02 also exists but isn't owned by the SC.

When I add local quantity to the SFT with the 02 nonce through a function, my transaction fails with this error:

new NFT data on sender

Do I need to own the SFT HAT-a1a1a1-02 to mint it?


问:
onBackPressed location update android
i have a problem. I have 2 MapActivitys. In first i display some places on the map and have i listView with that places. When i click on listView it opens second Map and display one place on map and under some info about that place. Update location is good, but when i press Back button it displays first activity with a location not updated. My question is how to update location in first activity when pressed back button in second??? This is what i have done:

```<code>@Override
public void onBackPressed() {
    Intent data = new Intent();
    data.putExtra("Latitude", location.getLatitude() );
    data.putExtra("Longitude", location.getLongitude());
    setResult(RESULT_OK,data);
    super.onBackPressed();

}
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == request_Code){
        if(resultCode == RESULT_OK){
                            Location location = new Location(provider);
            location.setLatitude(data.getDoubleExtra("Latitude", 0));
            location.setLongitude(data.getDoubleExtra("Longitude", 0));
            listener.onLocationChanged(location);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
</code>```

This is solution for my problem

答:
You can override onResume() using the following code:

```<code>@Override
protected void onResume() {
    super.onResume();
    // update your location here
}
</code>```

This is called every time an Activity gets resumed - in your case it pauses when you go to the details view, and resumes when you go back.

ContentLicense: CC BY-SA 3.0

Title: onBackPressed location update android

Body:
i have a problem. I have 2 MapActivitys. In first i display some places on the map and have i listView with that places. When i click on listView it opens second Map and display one place on map and under some info about that place. Update location is good, but when i press Back button it displays first activity with a location not updated. My question is how to update location in first activity when pressed back button in second??? This is what i have done:

@Override
public void onBackPressed() {
    Intent data = new Intent();
    data.putExtra("Latitude", location.getLatitude() );
    data.putExtra("Longitude", location.getLongitude());
    setResult(RESULT_OK,data);
    super.onBackPressed();

}
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == request_Code){
        if(resultCode == RESULT_OK){
                            Location location = new Location(provider);
            location.setLatitude(data.getDoubleExtra("Latitude", 0));
            location.setLongitude(data.getDoubleExtra("Longitude", 0));
            listener.onLocationChanged(location);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

This is solution for my problem

Body:
You can override onResume() using the following code:

@Override
protected void onResume() {
    super.onResume();
    // update your location here
}

This is called every time an Activity gets resumed - in your case it pauses when you go to the details view, and resumes when you go back.


问:
How to save the excel file using excel dart package?
I'm trying to implement a function which could select an excel file from phone's storage, edit some values and then finally save it using excel dart package. My function :

```<code>Future<void> createExcel() async {
   File file = await selectFile() //this is working fine

   //setting some configurations for excel
    var bytes = file!.readAsBytesSync();
    var excel = Excel.decodeBytes(bytes);
    Sheet sheetObject = excel['Sheet1'];

   //Updating excel values logic
   for(int i = 1; i<1000; ++i){
     var cell = sheetObject.cell(CellIndex.indexByString("A$i"));
     cell.value = 8; // dynamic values support provided;
   }

    //saving excel
    excel.encode()!.then((onValue) {   //this line is giving error: "The method 'then' isn't defined for the type 'List'. "
        File(join(file!.path))
        ..createSync(recursive: true)
        ..writeAsBytesSync(onValue);
    });

}
</code>```

I couldn't be able to use .then() with excel.encode() Is there any way to solve this ?

答:
sounds like... your encode method returns a LIST and not a Future<List>... so put your excel.encode direct in your writeAsBytesSync method

like this:

```<code>     Future<void> createExcel() async {
   File file = await selectFile() //this is working fine

   //setting some configurations for excel
    var bytes = file!.readAsBytesSync();
    var excel = Excel.decodeBytes(bytes);
    Sheet sheetObject = excel['Sheet1'];

   //Updating excel values logic
   for(int i = 1; i<1000; ++i){
     var cell = sheetObject.cell(CellIndex.indexByString("A$i"));
     cell.value = 8; // dynamic values support provided;
   }

    //saving excel
    File(join(file!.path))
    ..createSync(recursive: true)
    ..writeAsBytesSync(excel.encode()!);
  }
</code>```

Body:
I'm trying to implement a function which could select an excel file from phone's storage, edit some values and then finally save it using excel dart package. My function :

Future<void> createExcel() async {
   File file = await selectFile() //this is working fine

   //setting some configurations for excel
    var bytes = file!.readAsBytesSync();
    var excel = Excel.decodeBytes(bytes);
    Sheet sheetObject = excel['Sheet1'];

   //Updating excel values logic
   for(int i = 1; i<1000; ++i){
     var cell = sheetObject.cell(CellIndex.indexByString("A$i"));
     cell.value = 8; // dynamic values support provided;
   }

    //saving excel
    excel.encode()!.then((onValue) {   //this line is giving error: "The method 'then' isn't defined for the type 'List'. "
        File(join(file!.path))
        ..createSync(recursive: true)
        ..writeAsBytesSync(onValue);
    });

}

I couldn't be able to use .then() with excel.encode() Is there any way to solve this ?

Body:
sounds like... your encode method returns a LIST and not a Future<List>... so put your excel.encode direct in your writeAsBytesSync method

like this:

     Future<void> createExcel() async {
   File file = await selectFile() //this is working fine

   //setting some configurations for excel
    var bytes = file!.readAsBytesSync();
    var excel = Excel.decodeBytes(bytes);
    Sheet sheetObject = excel['Sheet1'];

   //Updating excel values logic
   for(int i = 1; i<1000; ++i){
     var cell = sheetObject.cell(CellIndex.indexByString("A$i"));
     cell.value = 8; // dynamic values support provided;
   }

    //saving excel
    File(join(file!.path))
    ..createSync(recursive: true)
    ..writeAsBytesSync(excel.encode()!);
  }


问:
Why does vs code show so many untracked files whenever I try to see the code for a built-in flutter widget?
While working in Flutter, sometimes I wish to see how a certain built-in or third-party widget works internally. And when I do ctrl+click on my vs code on that widget and hope to see its code, vs code then suddenly shows me like 140-150 untracked files. It only happens when I try to view the code for built-in or third-party widgets.
Help me!!!!
Thanks...

答:
I encountered the same problem and found this question.

VS code has an option to hide a specific repository non-related to a .gitignore file existence nor its contents.

The steps are:

Files ➜ Preferences ➜ Settings

➜ User / Workspace, depends on the scope needed to be applied to.

Search for Git: Ignored Repositories.

Append your local flutter repository location, in my case: c:\flutter

Close it manually for the last time, either by restarting VS code or by right clicking it and pressing close repository.


问:
How should I make this button design responsive on android?
I've spent the last two days trying to wrap my head around this layout I got asked by the designer to do, the shape is something like:

```<code>|         ___         |
|___ ___ /   \ ___ ___|
|btn|btn\\btn//btn|btn|
|___|____\\_//____|___|
</code>```

That part of the screen is a button row at the bottom of the screen, the problem comes with responsiveness, if I use an image button on the non square buttons they dont resize properly, adding margins instead of reshaping the image itself, but if I use regular buttons, i lose the cool shapes they ask for. Any ideas/tutorials I could use? Maybe I'm not looking it up as it should be done, but I don't seem to find anything relevant to my problem.

答:
I have made this with the help of floating action button and the bottom navigation view.Check out given code.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purple_500"
    tools:context=".MainActivity">

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/btmbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/purple_200"
        app:fabCradleMargin="10dp"
        app:fabCradleRoundedCornerRadius="40dp"
        app:fabCradleVerticalOffset="10dp">

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/menu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:background="@android:color/transparent"
            app:labelVisibilityMode="unlabeled"
            app:menu="@menu/btm_menu" />

    </com.google.android.material.bottomappbar.BottomAppBar>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:alpha="10"
        android:background="@null"
        android:elevation="0dp"
        android:src="@drawable/fire"
        app:backgroundTint="@android:color/transparent"
        app:elevation="0dp"
        app:fabSize="normal"
        app:layout_anchor="@id/btmbar"
        app:tint="@null" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Output will look like this:

You can make the changes in below properties to make the space between the bottom app bar.

```<code>    app:fabCradleMargin="16dp"

    app:fabCradleRoundedCornerRadius="40dp"

    app:fabCradleVerticalOffset="10dp"
</code>```

Body:
I've spent the last two days trying to wrap my head around this layout I got asked by the designer to do, the shape is something like:

|         ___         |
|___ ___ /   \ ___ ___|
|btn|btn\\btn//btn|btn|
|___|____\\_//____|___|

That part of the screen is a button row at the bottom of the screen, the problem comes with responsiveness, if I use an image button on the non square buttons they dont resize properly, adding margins instead of reshaping the image itself, but if I use regular buttons, i lose the cool shapes they ask for. Any ideas/tutorials I could use? Maybe I'm not looking it up as it should be done, but I don't seem to find anything relevant to my problem.

Body:
I have made this with the help of floating action button and the bottom navigation view.Check out given code.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purple_500"
    tools:context=".MainActivity">

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/btmbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/purple_200"
        app:fabCradleMargin="10dp"
        app:fabCradleRoundedCornerRadius="40dp"
        app:fabCradleVerticalOffset="10dp">

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/menu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:background="@android:color/transparent"
            app:labelVisibilityMode="unlabeled"
            app:menu="@menu/btm_menu" />

    </com.google.android.material.bottomappbar.BottomAppBar>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:alpha="10"
        android:background="@null"
        android:elevation="0dp"
        android:src="@drawable/fire"
        app:backgroundTint="@android:color/transparent"
        app:elevation="0dp"
        app:fabSize="normal"
        app:layout_anchor="@id/btmbar"
        app:tint="@null" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Output will look like this:

You can make the changes in below properties to make the space between the bottom app bar.

    app:fabCradleMargin="16dp"

    app:fabCradleRoundedCornerRadius="40dp"

    app:fabCradleVerticalOffset="10dp"


问:
stop flickering
I have an old program written in borland pascal and in Delphi if I use the Form1.Canvas.LineTo and MoveTo functions I get a flickering effect. Can anyone tell me how to get rid of the flickering?</p>

答:
Double Buffering is one way but not always sufficient. Imagine you paint a shape at runtime, it depends on your repaint method. Forces the control to repaint its image on the screen could be crucial.

Call Repaint to force the control to repaint its image immediately. If the ControlStyle property includes csOpaque, the control paints itself directly.
So double buffering plus invalidate and [csOpaque] as controlstyle could be an improvement:

```<code>var Compass: TPaintBox;
procedure TForm1ForceRepaint(Sender: TObject);
{Called when display type or compass angle changes}
begin
  compass.controlstyle:= [csOpaque];
  while heading.value<0 do heading.Value:=heading.Value+360;
  while heading.value>360 do heading.Value:=heading.Value-360;
  compass.Invalidate;
end;
</code>```

Title: stop flickering

Body:
Double Buffering is one way but not always sufficient. Imagine you paint a shape at runtime, it depends on your repaint method. Forces the control to repaint its image on the screen could be crucial.

Call Repaint to force the control to repaint its image immediately. If the ControlStyle property includes csOpaque, the control paints itself directly.
So double buffering plus invalidate and [csOpaque] as controlstyle could be an improvement:

var Compass: TPaintBox;
procedure TForm1ForceRepaint(Sender: TObject);
{Called when display type or compass angle changes}
begin
  compass.controlstyle:= [csOpaque];
  while heading.value<0 do heading.Value:=heading.Value+360;
  while heading.value>360 do heading.Value:=heading.Value-360;
  compass.Invalidate;
end;


问:
Create a single DF from multiple DFs
If anyone can help, I would like to create a single DF from multiple DFs.

This is my code, so far..

```<code>from functools import reduce

# Function responsible for making a query that returns a DB count and whether they are MATCHED or UNMATCHED.
def get_count(field,cdw_field,table,cdw_table,condition):
    query = f"""
    SELECT '{field}',count(a.{field}) as COUNT_MX, sum(CASE WHEN a.{field} = c.{cdw_field} THEN 1 ELSE 0 END) as MATCHED,
    sum(CASE WHEN a.{field}<> IFNULL(c.{cdw_field},'99999') THEN 1 ELSE 0 END) as UNMATCHED
    FROM {table} a
    LEFT JOIN {cdw_table} c ON a.MurexRootContractId = c.MurexRootContractId {condition};
    """
    df = pd.read_sql_query(query,conn)
#     display(df)
    return df

# call the function with the parameters
portfolio = get_count('Portfolio','Portfolio',"coreTrades_eod", "cdw_eod", "AND a.TradeStatus = 'Live'")
buySell = get_count('BuySell','BuySell','coreTrades_eod','cdw_eod', "AND a.TradeStatus = 'Live'")
ContractPrice = get_count('ContractPrice','Price','coreTrades_eod','cdw_eod', f"AND a.TradeStatus = 'Live' AND {conditions_price}")
counterparty = get_count('MurexCounterpartyRef','Counterparty','coreTrades_eod','cdw_eod',"AND a.TradeStatus = 'Live'")

# Make unique DataFrame
dfs = [portfolio,buySell,ContractPrice,counterparty]
df = reduce(lambda left,right: pd.merge(left,right),dfs)
display(df)

# Output -> These are the DF header.
'Portfolio' 'BuySell'   'ContractPrice' 'MurexCounterpartyRef'  COUNT_MX    MATCHED UNMATCHED

</code>```

But, I would like to have DF formatted this way:

```<code>  'Field_Name'    COUNT_MX      MATCHED   UNMATCHED
0   Portfolio     15800          15177      623
1   BuySell1      5800           15177      623
2 ContractPrice   15800          15177      623

</code>```

I wonder if this is possible, because the name 'Portfolio'in the above example will change with each function execution, i.e. the header of the next column will be 'BuySell', for example.

If anyone has a suggestion for doing it differently, please let me know I am open to suggestions.

答:
If you want to concatenate your dfs (horizontal):

```<code>dfs= pd.concat([portfolio,buySell,ContractPrice,counterparty], axis=1)
</code>```

Otherwise you should put axis = 0

And may what you need is just to transpose:

```<code>dfs.T
</code>```

Title: Create a single DF from multiple DFs

Body:
If anyone can help, I would like to create a single DF from multiple DFs.

This is my code, so far..

from functools import reduce

# Function responsible for making a query that returns a DB count and whether they are MATCHED or UNMATCHED.
def get_count(field,cdw_field,table,cdw_table,condition):
    query = f"""
    SELECT '{field}',count(a.{field}) as COUNT_MX, sum(CASE WHEN a.{field} = c.{cdw_field} THEN 1 ELSE 0 END) as MATCHED,
    sum(CASE WHEN a.{field}<> IFNULL(c.{cdw_field},'99999') THEN 1 ELSE 0 END) as UNMATCHED
    FROM {table} a
    LEFT JOIN {cdw_table} c ON a.MurexRootContractId = c.MurexRootContractId {condition};
    """
    df = pd.read_sql_query(query,conn)
#     display(df)
    return df

# call the function with the parameters
portfolio = get_count('Portfolio','Portfolio',"coreTrades_eod", "cdw_eod", "AND a.TradeStatus = 'Live'")
buySell = get_count('BuySell','BuySell','coreTrades_eod','cdw_eod', "AND a.TradeStatus = 'Live'")
ContractPrice = get_count('ContractPrice','Price','coreTrades_eod','cdw_eod', f"AND a.TradeStatus = 'Live' AND {conditions_price}")
counterparty = get_count('MurexCounterpartyRef','Counterparty','coreTrades_eod','cdw_eod',"AND a.TradeStatus = 'Live'")

# Make unique DataFrame
dfs = [portfolio,buySell,ContractPrice,counterparty]
df = reduce(lambda left,right: pd.merge(left,right),dfs)
display(df)

# Output -> These are the DF header.
'Portfolio' 'BuySell'   'ContractPrice' 'MurexCounterpartyRef'  COUNT_MX    MATCHED UNMATCHED

But, I would like to have DF formatted this way:

  'Field_Name'    COUNT_MX      MATCHED   UNMATCHED
0   Portfolio     15800          15177      623
1   BuySell1      5800           15177      623
2 ContractPrice   15800          15177      623

I wonder if this is possible, because the name 'Portfolio'in the above example will change with each function execution, i.e. the header of the next column will be 'BuySell', for example.

If anyone has a suggestion for doing it differently, please let me know I am open to suggestions.

Body:
If you want to concatenate your dfs (horizontal):

dfs= pd.concat([portfolio,buySell,ContractPrice,counterparty], axis=1)

Otherwise you should put axis = 0

And may what you need is just to transpose:

dfs.T


问:
Search for an element in a complete ternary tree
The function I need: return the index of the node in the tree if the key is found, return -1 otherwise.

My pseudo-code:

```<code>int search(Node node,int key){
   if(node->key==key){
      return node->index;
   }
   if(node->leftchild exists){
     search(node->leftchild,key);
   }
   if(node->middlechild exists){
     search(node->middlechild,key);
   }
   if(node->rightchild exists){
     search(node->rightchild,key);
   }
}
</code>```

When I call the function I will initially pass the root:

```<code>int result = search(root,key);
</code>```

The part I'm missing:

```<code>After every recursion call has been made, if the condition node->key==key was never met, return -1
</code>```

What is the right way to add the part I'm missing in the function I wrote above in pseudo-code?

答:
First, your code does not utilize the recursive calls you make. -1 is more like a default value. I would suggest this modification of your pseudocode:

```<code>int search(Node node,int key){
   if(node->key==key){
      return node->index;
   }
   int result = -1;
   if(node->leftchild exists){
      result = max(result, search(node->leftchild,key));
   }
   if(node->middlechild exists){
     result = max(result, search(node->middlechild,key));
   }
   if(node->rightchild exists){
     result = max(result, search(node->rightchild,key));
   }
   return result;
}
</code>```

Important note: this code assumes that all keys are non-negative. If this condition is true you may see that result would be only updated if the search finds the node (returning -1 would not change the result). If this condition is not true, code just gets less tidy with a lot of ifs, also they are necessary if you want to return as soon as you have found one key saving performance. This code would be:

```<code>int search(Node node,int key){
   if(node->key==key){
      return node->index;
   }
   if(node->leftchild exists){
      int result = search(node->leftchild,key);
      if (result != -1) {
         return result;
      }
   }
   if(node->middlechild exists){
      int result = search(node->middlechild,key);
      if (result != -1) {
         return result;
      }
   }
   if(node->rightchild exists){
      int result = search(node->rightchild,key);
      if (result != -1) {
         return result;
      }
   }
   return -1;
}
</code>```

This code has a lot of copy-paste, but the best way to get rid of it depends on the actual programming language and constraints on the keys.

Body:
The function I need: return the index of the node in the tree if the key is found, return -1 otherwise.

My pseudo-code:

int search(Node node,int key){
   if(node->key==key){
      return node->index;
   }
   if(node->leftchild exists){
     search(node->leftchild,key);
   }
   if(node->middlechild exists){
     search(node->middlechild,key);
   }
   if(node->rightchild exists){
     search(node->rightchild,key);
   }
}

When I call the function I will initially pass the root:

int result = search(root,key);

The part I'm missing:

After every recursion call has been made, if the condition node->key==key was never met, return -1

What is the right way to add the part I'm missing in the function I wrote above in pseudo-code?

Body:
First, your code does not utilize the recursive calls you make. -1 is more like a default value. I would suggest this modification of your pseudocode:

int search(Node node,int key){
   if(node->key==key){
      return node->index;
   }
   int result = -1;
   if(node->leftchild exists){
      result = max(result, search(node->leftchild,key));
   }
   if(node->middlechild exists){
     result = max(result, search(node->middlechild,key));
   }
   if(node->rightchild exists){
     result = max(result, search(node->rightchild,key));
   }
   return result;
}

Important note: this code assumes that all keys are non-negative. If this condition is true you may see that result would be only updated if the search finds the node (returning -1 would not change the result). If this condition is not true, code just gets less tidy with a lot of ifs, also they are necessary if you want to return as soon as you have found one key saving performance. This code would be:

int search(Node node,int key){
   if(node->key==key){
      return node->index;
   }
   if(node->leftchild exists){
      int result = search(node->leftchild,key);
      if (result != -1) {
         return result;
      }
   }
   if(node->middlechild exists){
      int result = search(node->middlechild,key);
      if (result != -1) {
         return result;
      }
   }
   if(node->rightchild exists){
      int result = search(node->rightchild,key);
      if (result != -1) {
         return result;
      }
   }
   return -1;
}

This code has a lot of copy-paste, but the best way to get rid of it depends on the actual programming language and constraints on the keys.


问:
Flutter/Dart : Parsing 'yyyy-MM-dd HH:MM:SS' producing wrong output?
I am parsing a date in format yyyy-MM-dd HH:MM:SS using DateFormat

But I am getting some other date in parsed output

```<code>final dt = '2022-02-07 05:00:11';
final datm =  DateFormat('yyyy-MM-dd HH:MM:SS').parse(dt);

print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");
</code>```

Actual Output:

```<code>DATE_CALC 7 - 2 - 2021 5 : 0 : 0
</code>```

Expected :

```<code>DATE_CALC 07 - 12 - 2022 05 : 00 : 11
</code>```

Why I am getting some wrong date ? Am I doing anything wrong ?

答:
Your formate is wrong

yyyy-MM-dd HH:MM:SS replace to 'yyyy-MM-dd HH:mm:ss'

Body:
I am parsing a date in format yyyy-MM-dd HH:MM:SS using DateFormat

But I am getting some other date in parsed output

final dt = '2022-02-07 05:00:11';
final datm =  DateFormat('yyyy-MM-dd HH:MM:SS').parse(dt);

print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");

Actual Output:

DATE_CALC 7 - 2 - 2021 5 : 0 : 0

Expected :

DATE_CALC 07 - 12 - 2022 05 : 00 : 11

Why I am getting some wrong date ? Am I doing anything wrong ?


问:
how do i prevent typescript from complaining in this useEffect hook
i am trying to use this useEffect hook but cant fix the type constraint of typescript</p>
```<code>useEffect(() => {
        const {
            isFetching: isLoading,
            isFetchingNextPage: loadingMore,
            fetchNextPage,
            hasNextPage,
            data,
            error,
        } = useProductsQuery({ limit: 20, pageParam: 1, ...query });
        if (error) return <p>{error.message}</p>;
    }, [])
</code>```

答:
There is no need to use an effect at all:</p>
```<code> const {
            isFetching: isLoading,
            isFetchingNextPage: loadingMore,
            fetchNextPage,
            hasNextPage,
            data,
            error,
        } = useProductsQuery({ limit: 20, pageParam: 1, ...query });

...

if (error)  {
    return <p>{error.message}</p>
}

return <... non error elements />

</code>```

Body:
i am trying to use this useEffect hook but cant fix the type constraint of typescript

useEffect(() => {
        const {
            isFetching: isLoading,
            isFetchingNextPage: loadingMore,
            fetchNextPage,
            hasNextPage,
            data,
            error,
        } = useProductsQuery({ limit: 20, pageParam: 1, ...query });
        if (error) return
{error.message}
;
    }, [])

Body:
There is no need to use an effect at all:

 const {
            isFetching: isLoading,
            isFetchingNextPage: loadingMore,
            fetchNextPage,
            hasNextPage,
            data,
            error,
        } = useProductsQuery({ limit: 20, pageParam: 1, ...query });

...

if (error)  {
    return <p>{error.message}</p>
}

return <... non error elements />


问:
What is the trick for swap_pointers to work?
I am doing an exercise where the task is to fix swap_pointer().

Two string should be swapped.

```<code>s1 = "I should print second.";
s2 = "I should print first.";
</code>```

My work so far:

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

void swap_nums(int *, int *);
void swap_pointers(char *x, char *y);

int main(void) {

    int a = 3, b = 4;
    char *s1, *s2;

    swap_nums(&a, &b);

    printf("a is %d\n", a);
    printf("b is %d\n", b);

    s1 = "I should be printed second.";
    s2 = "I should be printed first.";

    /* swap_pointers(s1, s2); */

    printf("s1 is %s\n", s1);
    printf("s2 is %s\n", s2);

    return 0;
}

void swap_nums(int *x, int *y) {

    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

void swap_pointers(char *x, char *y) {

    char tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}
</code>```

I think that not appending & to s1 and s2 before I pass them to the function for swap_pointers is the error?

If anyone can fix my issue here, please don't give the whole solution! I want to use what you give me as a tool to fix it by my own. If I really can't fix it by my own I will adress this later.

Ty in advance!

答:
Let's at first consider this code snippet

```<code>int a = 3, b = 4;

swap_nums(&a, &b);
</code>```

To swap the objects a and b you need to pass then to the function swap_nums by reference through pointers to them. Thus within the function dereferencing the pointers we can get a direct access to original objects and change their values.

```<code>void swap_nums(int *x, int *y) {

    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}
</code>```

The same we need to do with the variables s1 and s2. That is we need to pass them to the function swap_pointers by reference through pointers to them.

So you need to write

```<code>swap_ponters( &s1, &s2 );
</code>```

and the function will be declared and defined like

```<code>void swap_ponters(char **x, char **y)
{
    char *tmp = *x;
    *x = *y;
    *y = tmp;
}
</code>```

In general if you have two objects like

```<code>T a;
T b;
</code>```

where T is some type specifier then to change the objects in a function you need to pass them to the function by reference through pointers to them. So the declaration of the function swap will look like

```<code>void swap( T *a, T *b );
</code>```

and the function will be called like

```<code>swap( &a, &b );
</code>```

In your program a and b has the type int, that is T is an alias for the type int.

```<code>typedef int T;

T a = 3, b = 4;
</code>```

so the function declaration will look like

```<code>  void swap_nums( T *x, T *y );
</code>```

For the variables s1 and s2 you can write

```<code>typedef char *T;

T s1, s2;
</code>```

and again the function declaration will look like

```<code>void swap_pointers( T *x, T *y );
</code>```

and the function will be called like

```<code>swap_pointers( &s1, &s2 );
</code>```

As in this case T is an alias for the type char * then the function declaration can be rewritten like

```<code>void swap_pointers( char * *x, char * *y );
</code>```

Body:
I am doing an exercise where the task is to fix swap_pointer().

Two string should be swapped.

s1 = "I should print second.";
s2 = "I should print first.";

My work so far:

#include <stdio.h>

void swap_nums(int *, int *);
void swap_pointers(char *x, char *y);

int main(void) {

    int a = 3, b = 4;
    char *s1, *s2;

    swap_nums(&a, &b);

    printf("a is %d\n", a);
    printf("b is %d\n", b);

    s1 = "I should be printed second.";
    s2 = "I should be printed first.";

    /* swap_pointers(s1, s2); */

    printf("s1 is %s\n", s1);
    printf("s2 is %s\n", s2);

    return 0;
}

void swap_nums(int *x, int *y) {

    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

void swap_pointers(char *x, char *y) {

    char tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

I think that not appending & to s1 and s2 before I pass them to the function for swap_pointers is the error?

If anyone can fix my issue here, please don't give the whole solution! I want to use what you give me as a tool to fix it by my own. If I really can't fix it by my own I will adress this later.

Ty in advance!

Body:
Let's at first consider this code snippet

int a = 3, b = 4;

swap_nums(&a, &b);

To swap the objects a and b you need to pass then to the function swap_nums by reference through pointers to them. Thus within the function dereferencing the pointers we can get a direct access to original objects and change their values.

void swap_nums(int *x, int *y) {

    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

The same we need to do with the variables s1 and s2. That is we need to pass them to the function swap_pointers by reference through pointers to them.

So you need to write

swap_ponters( &s1, &s2 );

and the function will be declared and defined like

void swap_ponters(char **x, char **y)
{
    char *tmp = *x;
    *x = *y;
    *y = tmp;
}

In general if you have two objects like

T a;
T b;

where T is some type specifier then to change the objects in a function you need to pass them to the function by reference through pointers to them. So the declaration of the function swap will look like

void swap( T *a, T *b );

and the function will be called like

swap( &a, &b );

In your program a and b has the type int, that is T is an alias for the type int.

typedef int T;

T a = 3, b = 4;

so the function declaration will look like

  void swap_nums( T *x, T *y );

For the variables s1 and s2 you can write

typedef char *T;

T s1, s2;

and again the function declaration will look like

void swap_pointers( T *x, T *y );

and the function will be called like

swap_pointers( &s1, &s2 );

As in this case T is an alias for the type char * then the function declaration can be rewritten like

void swap_pointers( char * *x, char * *y );


问:
Download a sub stream with youtube_explode_dart
I'm developing a Flutter app, using the package youtube_explode_dart.
Currently I download all the audio stream, then crop it using ffmpeg. Quickly this looks like :

var id = "aboZctrHfK8";
var file = File("mySong.mp4");
var start = "2000ms";
var end = "5000ms";

// Downloading audio only
var manifest = await yt.videos.streamsClient.getManifest(id);
var audio = manifest.audioOnly.first;
var audioStream = yt.videos.streamsClient.get(audio);
var output = file.openWrite(mode: FileMode.writeOnlyAppend);
for (final data in audioStream) {
    output.add(data);
}

// Croping audio
FlutterFFmpeg _flutterFFmpeg = new FlutterFFmpeg();
await _flutterFFmpeg.executeWithArguments([
      "-v", "error",
      "-ss", start,
      "-to", end,
      "-i", file.path,
      "-acodec", "copy", "myCroppedSong.mp4"]);
```
<p>Now I'm facing another issue: Some videos are really heavy and take a while to download. This is not acceptable for my end users, especially since I only want part of the original audio.</p>
<p><strong>Is there a way to download only a subset of the audio stream?</strong></p>
<p>Something like:</p>
<pre class="lang-dart prettyprint-override"><code>for (final data in audioStream.subset(start, end)) {
    output.add(data);
}
</code>```

It would be anwsome!

答:
```<code>String youTubeLink = "https://www.youtube.com/watch?v=Ja-85lFDSEM";
Future<void> _downloadVideo(youTubeLink) async{
final yt = YoutubeExplode();
final video = await yt.videos.get(youTubeLink);
// Get the video manifest.
final manifest = await yt.videos.streamsClient.getManifest(youTubeLink);
final streams = manifest.muxed;
final audio = streams.first;
final audioStream = yt.videos.streamsClient.get(audio);
final fileName = '${video.title}.${audio.container.name.toString()}'
    .replaceAll(r'\', '')
    .replaceAll('/', '')
    .replaceAll('*', '')
    .replaceAll('?', '')
    .replaceAll('"', '')
    .replaceAll('<', '')
    .replaceAll('>', '')
    .replaceAll('|', '');

final dir = await getApplicationDocumentsDirectory();
final path = dir.path;
final directory = Directory('$path/video/');
await directory.create(recursive: true);
final file = File('$path/video/$fileName');
final output = file.openWrite(mode: FileMode.writeOnlyAppend);
var len = audio.size.totalBytes;
var count = 0;
var msg = 'Downloading ${video.title}.${audio.container.name}';
stdout.writeln(msg);
await for (final data in audioStream){
  count += data.length;
  var progress = ((count / len) * 100).ceil();
  print(progress);
  output.add(data);
}
await output.flush();
await output.close();
</code>```
<p>}</p>

Body:
I'm developing a Flutter app, using the package youtube_explode_dart.
Currently I download all the audio stream, then crop it using ffmpeg. Quickly this looks like :

var id = "aboZctrHfK8";
var file = File("mySong.mp4");
var start = "2000ms";
var end = "5000ms";

// Downloading audio only
var manifest = await yt.videos.streamsClient.getManifest(id);
var audio = manifest.audioOnly.first;
var audioStream = yt.videos.streamsClient.get(audio);
var output = file.openWrite(mode: FileMode.writeOnlyAppend);
for (final data in audioStream) {
    output.add(data);
}

// Croping audio
FlutterFFmpeg _flutterFFmpeg = new FlutterFFmpeg();
await _flutterFFmpeg.executeWithArguments([
      "-v", "error",
      "-ss", start,
      "-to", end,
      "-i", file.path,
      "-acodec", "copy", "myCroppedSong.mp4"]);

Now I'm facing another issue: Some videos are really heavy and take a while to download. This is not acceptable for my end users, especially since I only want part of the original audio.

Is there a way to download only a subset of the audio stream?

Something like:

for (final data in audioStream.subset(start, end)) {
    output.add(data);
}

It would be anwsome!

Body:
String youTubeLink = "https://www.youtube.com/watch?v=Ja-85lFDSEM";
Future<void> _downloadVideo(youTubeLink) async{
final yt = YoutubeExplode();
final video = await yt.videos.get(youTubeLink);
// Get the video manifest.
final manifest = await yt.videos.streamsClient.getManifest(youTubeLink);
final streams = manifest.muxed;
final audio = streams.first;
final audioStream = yt.videos.streamsClient.get(audio);
final fileName = '${video.title}.${audio.container.name.toString()}'
    .replaceAll(r'\', '')
    .replaceAll('/', '')
    .replaceAll('*', '')
    .replaceAll('?', '')
    .replaceAll('"', '')
    .replaceAll('<', '')
    .replaceAll('>', '')
    .replaceAll('|', '');

final dir = await getApplicationDocumentsDirectory();
final path = dir.path;
final directory = Directory('$path/video/');
await directory.create(recursive: true);
final file = File('$path/video/$fileName');
final output = file.openWrite(mode: FileMode.writeOnlyAppend);
var len = audio.size.totalBytes;
var count = 0;
var msg = 'Downloading ${video.title}.${audio.container.name}';
stdout.writeln(msg);
await for (final data in audioStream){
  count += data.length;
  var progress = ((count / len) * 100).ceil();
  print(progress);
  output.add(data);
}
await output.flush();
await output.close();

}


问:
MKMapView's scale is not shown
I'm doing an iOS application. In Xcode 9.1 I create a MKMapView by

```<code>let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
mapView.isUserInteractionEnabled = false
mapView.mapType = .satellite
mapView.showsCompass = false
mapView.showsScale = true
view.addSubview(mapView)
</code>```

but when I run it in the simulator the scale is not shown and I get three messages in the log:

Could not inset compass from edges 9

Could not inset scale from edge 9

Could not inset legal attribution from corner 4

The compass is not shown (as expected) but it's not shown if I change mapView.showsCompass to trueeither. However, the Legal link is shown. What am I missing here? I'm guessing it's something about the new safe areas introduced with iOS 11, but I fail to see how that is important for a view I want to be covering the whole screen.

答:
Objective c equivalent:-</p>
```<code>if (@available(iOS 11.0, *)) {
        // switch OFF the standard scale (otherwise both will be visible when zoom in/out)
    self.map.showsScale = false;

        // build the view

    MKScaleView* scale = [MKScaleView scaleViewWithMapView:self.map];

        // we want to use autolayout
    scale.translatesAutoresizingMaskIntoConstraints = false;

        // scale should be visible all the time
    scale.scaleVisibility = MKFeatureVisibilityVisible;// always visible

    // add it to the map
    [self.view addSubview:scale];

        // get the current safe area of the map
    UILayoutGuide * guide = self.view.safeAreaLayoutGuide;

        // Activate this array of constraints, which at the time removes leftovers if any
        [NSLayoutConstraint activateConstraints:
            @[
                // LEFT (I do not want a change if right-to-left language) margin with an offset to safe area
                // alternative would be ".leadingAnchor", which switches to the right margin, if right-to-left language is used
               //[scale.leftAnchor constraintEqualToAnchor: guide.centerXAnchor constant: -(scale.frame.size.width/2.0)],

                // right edge will be the middle of the map
                [scale.rightAnchor constraintEqualToAnchor: guide.centerXAnchor constant: (scale.frame.size.width/2.0)],

                // top margin is the top safe area
                [scale.bottomAnchor constraintEqualToAnchor: guide.bottomAnchor constant:-self.toolBar.frame.size.height],

                // view will be 20 points high
                [scale.heightAnchor constraintEqualToConstant: 50.0]
            ]
        ];

    [self.view bringSubviewToFront:scale];
}
</code>```

Title: MKMapView's scale is not shown

Body:
I'm doing an iOS application. In Xcode 9.1 I create a MKMapView by

let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
mapView.isUserInteractionEnabled = false
mapView.mapType = .satellite
mapView.showsCompass = false
mapView.showsScale = true
view.addSubview(mapView)

but when I run it in the simulator the scale is not shown and I get three messages in the log:

Could not inset compass from edges 9

Could not inset scale from edge 9

Could not inset legal attribution from corner 4

The compass is not shown (as expected) but it's not shown if I change mapView.showsCompass to trueeither. However, the Legal link is shown. What am I missing here? I'm guessing it's something about the new safe areas introduced with iOS 11, but I fail to see how that is important for a view I want to be covering the whole screen.

Body:
Objective c equivalent:-

if (@available(iOS 11.0, *)) {
        // switch OFF the standard scale (otherwise both will be visible when zoom in/out)
    self.map.showsScale = false;

        // build the view

    MKScaleView* scale = [MKScaleView scaleViewWithMapView:self.map];

        // we want to use autolayout
    scale.translatesAutoresizingMaskIntoConstraints = false;

        // scale should be visible all the time
    scale.scaleVisibility = MKFeatureVisibilityVisible;// always visible

    // add it to the map
    [self.view addSubview:scale];

        // get the current safe area of the map
    UILayoutGuide * guide = self.view.safeAreaLayoutGuide;

        // Activate this array of constraints, which at the time removes leftovers if any
        [NSLayoutConstraint activateConstraints:
            @[
                // LEFT (I do not want a change if right-to-left language) margin with an offset to safe area
                // alternative would be ".leadingAnchor", which switches to the right margin, if right-to-left language is used
               //[scale.leftAnchor constraintEqualToAnchor: guide.centerXAnchor constant: -(scale.frame.size.width/2.0)],

                // right edge will be the middle of the map
                [scale.rightAnchor constraintEqualToAnchor: guide.centerXAnchor constant: (scale.frame.size.width/2.0)],

                // top margin is the top safe area
                [scale.bottomAnchor constraintEqualToAnchor: guide.bottomAnchor constant:-self.toolBar.frame.size.height],

                // view will be 20 points high
                [scale.heightAnchor constraintEqualToConstant: 50.0]
            ]
        ];

    [self.view bringSubviewToFront:scale];
}


问:
Refreshing async requests/ async with event listener
I was wondering how to refresh an async request. For example, I have this code and I want to see a different message every time i click a button.

```<code>async function start() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    console.log(data)
    let html = `<p>${data.activity}</p>`
    document.querySelector('button').addEventListener('click', toDo.bind(this, html))
}

function toDo(html) {
    document.querySelector('.msg').insertAdjacentHTML('beforeend', html)
}

start()
</code>```

As a "solution" I did this:

```<code>document.querySelector('button').addEventListener('click', toDo);
async function toDo() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    let html = `<p>${data.activity}</p>`
    document.querySelector('.msg').insertAdjacentHTML('beforeend', html)
}
</code>```

Not sure if it's an ok practice since it could take some time before you see a result. In my case there is a slight delay which is understandable.

答:
If you do not want a delay, you need to fetch the text before you need it and display it. Basic idea is load first one when page loads. After you display the new entry, you fetch the next text.

function textGen () {

  const updateElem = document.querySelector('.msg');

  let currentText = '';
  let isFetching = false;

  async function fetchText () {
    isFetching = true;
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    currentText = data.activity;
    isFetching = false;
  }

  fetchText();

  return {
    addNext: function () {
      if (isFetching) return;
      const html = `<p>${currentText}</p>`;
      updateElem.insertAdjacentHTML('beforeend', html);
      fetchText();
    }
  }
}

const myTextGen = textGen();
document.querySelector("button").addEventListener("click", myTextGen.addNext);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Next</button>
<div class="msg"></div></code>```

Body:
I was wondering how to refresh an async request. For example, I have this code and I want to see a different message every time i click a button.

async function start() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    console.log(data)
    let html = `<p>${data.activity}</p>`
    document.querySelector('button').addEventListener('click', toDo.bind(this, html))
}

function toDo(html) {
    document.querySelector('.msg').insertAdjacentHTML('beforeend', html)
}

start()

As a "solution" I did this:

document.querySelector('button').addEventListener('click', toDo);
async function toDo() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    let html = `<p>${data.activity}</p>`
    document.querySelector('.msg').insertAdjacentHTML('beforeend', html)
}

Not sure if it's an ok practice since it could take some time before you see a result. In my case there is a slight delay which is understandable.

Body:
If you do not want a delay, you need to fetch the text before you need it and display it. Basic idea is load first one when page loads. After you display the new entry, you fetch the next text.

function textGen () {

  const updateElem = document.querySelector('.msg');

  let currentText = '';
  let isFetching = false;

  async function fetchText () {
    isFetching = true;
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    currentText = data.activity;
    isFetching = false;
  }

  fetchText();

  return {
    addNext: function () {
      if (isFetching) return;
      const html = `<p>${currentText}</p>`;
      updateElem.insertAdjacentHTML('beforeend', html);
      fetchText();
    }
  }
}

const myTextGen = textGen();
document.querySelector("button").addEventListener("click", myTextGen.addNext);

<button>Next</button>
<div class="msg"></div>


问:
Making some traffic hazard in Carla simulator
In Carla simulator I can make some traffic using generate_traffic.py
But I want to make some cars or pedestrians ignoring traffic lights.
In this case what code should I change?</p>

答:
If you are using any class derived from BasicAgent (PythonAPI\carla\agents\navigation\basic_agent.py) to control the generated actors, then you can pass ignore_traffic_lights = True to opt_dict constructor parameter.
Also, you can alter the following function of BasicAgent in order to customize the actors affected by traffic lights.

```<code>def _affected_by_traffic_light(self, lights_list=None, max_distance=None):
</code>```

Body:
If you are using any class derived from BasicAgent (PythonAPI\carla\agents\navigation\basic_agent.py) to control the generated actors, then you can pass ignore_traffic_lights = True to opt_dict constructor parameter.
Also, you can alter the following function of BasicAgent in order to customize the actors affected by traffic lights.

def _affected_by_traffic_light(self, lights_list=None, max_distance=None):


问:
Use 'import module' or 'from module import'?
I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python and I'm trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?

答:
I personally always use

```<code>from package.subpackage.subsubpackage import module
</code>```

and then access everything as

```<code>module.function
module.modulevar
</code>```

etc. The reason is that at the same time you have short invocation, and you clearly define the module namespace of each routine, something that is very useful if you have to search for usage of a given module in your source.

Needless to say, do not use the import *, because it pollutes your namespace and it does not tell you where a given function comes from (from which module)

Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like

```<code>from package1.subpackage import module
from package2.subpackage import module
</code>```

in this case, of course you run into troubles, but then there's a strong hint that your package layout is flawed, and you have to rethink it.

OwnerDisplayName: kRON

Body:
I personally always use

from package.subpackage.subsubpackage import module

and then access everything as

module.function
module.modulevar

etc. The reason is that at the same time you have short invocation, and you clearly define the module namespace of each routine, something that is very useful if you have to search for usage of a given module in your source.

Needless to say, do not use the import *, because it pollutes your namespace and it does not tell you where a given function comes from (from which module)

Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like

from package1.subpackage import module
from package2.subpackage import module

in this case, of course you run into troubles, but then there's a strong hint that your package layout is flawed, and you have to rethink it.

OwnerDisplayName: Stefano Borini

ContentLicense: CC BY-SA 2.5


问:
Change background-image with jQuery - doesn´t work
```<code>$('#areaView').css('background-image', 'url(/areaNr1.jpg)');
</code>```

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

答:
Since the image is at mydomain.com/jQuery/areaNr1.jpg, you need to include the folder, too. If it was CSS, you could make it relative to CSS's folder, but not with JS.

```<code>$('#areaView').css('background-image', 'url("jQuery/areaNr1.jpg")');
</code>```

Body:
$('#areaView').css('background-image', 'url(/areaNr1.jpg)');

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

Body:
Since the image is at mydomain.com/jQuery/areaNr1.jpg, you need to include the folder, too. If it was CSS, you could make it relative to CSS's folder, but not with JS.

$('#areaView').css('background-image', 'url("jQuery/areaNr1.jpg")');


问:
can't select element created using map() function
I have displayed some element using Array.map function but now i cannot select any element that are created using Array.map function.when I select console log an element that is created using that map function it shows null

const fetchData = function() {
  let display = products.map(function(product) {
    return `

   ${product.category}

   ${product.name}

${product.price}

  <button
id="name"
    class="btn-add  absolute right-5 bottom-3 bg-orange-400 rounded text-sm px-2 py-2 text-white font-medium"
  >
    Add To Cart
  </button>

`;
  });

  display = display.join("");
  mainSection.innerHTML = display;
};

window.addEventListener("DOMContentLoaded", fetchData);

let btnAdd = document.querySelector(".btn-add")

console.log(btnAdd)```

答:
It happens that the fetchData method is called only after the DOM finishes loading, but the search for the element of your button is performed even before the loading of the DOM is finished (and in any case the element does not yet exist and the value is null)
If you search for the value "after" the loading of the DOM it will find the element</p>


问:
FindOneAndUpdate overriding and updating only the first id
I am simply trying to update the content according to the id, but whichever id I am using, it updates only the first id by overriding it.
The flow goes as routes => controller => repository
Following is the code:
Routes =>

```<code>router.post("/:pageId/content", async (req, res, next) => {
  try {
    const pageId = req.params;
    const pageContent = req.body;
    if (!pageId || !pageContent) {
      throw {
        statusCode: 200,
        customMessage: "All parameters are required"
      };
    }
    const result: any = await webpageController.createContent(
      pageId,
      pageContent
    );
    if (result.isError) {
      throw result.error;
    }
    res.status(200).json(result.data);
  } catch (error) {
    next(error);
  }
});
</code>```

Controller =>

```<code>const createContent = async (pageId: any, pageContent: any) => {
  try {
    // calls repository to create content
    const result = await webpageRepository.createContent(pageId, pageContent);
    // if result is not success, throw error
    if (!result.success) {
      throw {
        statusCode: 400,
        customMessage: "Unable to create web page content"
      };
    }

    return {
      isError: false,
      data: result.data
    };
</code>```

Repository =>

```<code>export const createContent = async (pageId: any, content: any) => {
  try {
    const result = await webpage.findOneAndUpdate(pageId, { content });
    return {
      data: result,
      success: true
    };
  } catch (error) {
    logger.error(
      `at:"repositories/webpage/createContent" => ${JSON.stringify(error)}`
    );
    return {
      success: false
    };
  }
};
</code>```

Here it can be seen that the id I have used in the route and the id getting updated is different.
What am I doing wrong here?

Following is the schema:

```<code>const mongoose = require('mongoose');
const { Schema } = mongoose;

const webpage = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
      maxlength: 25,
    },
    slug: {
      type: String,
    //   required: true,
    },
    url: {
      type: String,
      required: true,
      unique: true
    },
    content: Object,
  },
  {
    timestamps: true,
  },
);

export default mongoose.model('webpages', webpage);
</code>```

答:
I think you should use a dictionary as the parameter.

```<code>const result = await webpage.findOneAndUpdate({_id:pageId.pageId}, {content});
</code>```

You can check on this documentation about how to use the "findOneAndUpdate" https://mongoosejs.com/docs/tutorials/findoneandupdate.html#getting-started

Body:
I am simply trying to update the content according to the id, but whichever id I am using, it updates only the first id by overriding it.
The flow goes as routes => controller => repository
Following is the code:
Routes =>

router.post("/:pageId/content", async (req, res, next) => {
  try {
    const pageId = req.params;
    const pageContent = req.body;
    if (!pageId || !pageContent) {
      throw {
        statusCode: 200,
        customMessage: "All parameters are required"
      };
    }
    const result: any = await webpageController.createContent(
      pageId,
      pageContent
    );
    if (result.isError) {
      throw result.error;
    }
    res.status(200).json(result.data);
  } catch (error) {
    next(error);
  }
});

Controller =>

const createContent = async (pageId: any, pageContent: any) => {
  try {
    // calls repository to create content
    const result = await webpageRepository.createContent(pageId, pageContent);
    // if result is not success, throw error
    if (!result.success) {
      throw {
        statusCode: 400,
        customMessage: "Unable to create web page content"
      };
    }

    return {
      isError: false,
      data: result.data
    };

Repository =>

export const createContent = async (pageId: any, content: any) => {
  try {
    const result = await webpage.findOneAndUpdate(pageId, { content });
    return {
      data: result,
      success: true
    };
  } catch (error) {
    logger.error(
      `at:"repositories/webpage/createContent" => ${JSON.stringify(error)}`
    );
    return {
      success: false
    };
  }
};

Here it can be seen that the id I have used in the route and the id getting updated is different.
What am I doing wrong here?

Following is the schema:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const webpage = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
      maxlength: 25,
    },
    slug: {
      type: String,
    //   required: true,
    },
    url: {
      type: String,
      required: true,
      unique: true
    },
    content: Object,
  },
  {
    timestamps: true,
  },
);

export default mongoose.model('webpages', webpage);

Body:
I think you should use a dictionary as the parameter.

const result = await webpage.findOneAndUpdate({_id:pageId.pageId}, {content});

You can check on this documentation about how to use the "findOneAndUpdate" https://mongoosejs.com/docs/tutorials/findoneandupdate.html#getting-started


问:
Extraneous input '\' expecting {')', ','}. Query working in sql notebook cell but not in databricks connect
When executing the following query

```<code>SELECT * FROM companies JOIN employments on companies.company_normalized LIKE CONCAT('%',
    replace(employments.displayname_normalized, '\\', ''), '%') or employments.displayname_normalized LIKE CONCAT(
    '%', replace(companies.company_normalized,'\\', ''), '%')
</code>```

it works fine on databricks sql notebook cell.

However, when attempting to run this same query using spark sql executor, ie spark.sql(query), this errors out saying:
Extraneous input '' expecting {')', ','} within the replace clause.

Is there a fix for this?

答:
You need either a single backslash, if you are using regex:

```<code>spark.sql("SELECT * FROM companies JOIN employments on companies.company_normalized LIKE CONCAT('%',
replace(employments.displayname_normalized, '\', ''), '%') or employments.displayname_normalized LIKE CONCAT(
'%', replace(companies.company_normalized,'\', ''), '%')")
</code>```

or you need to escape slashes, then you need to double escape using "\\\\":

```<code>spark.sql("SELECT * FROM companies JOIN employments on companies.company_normalized LIKE CONCAT('%',
replace(employments.displayname_normalized, '\\\\', ''), '%') or employments.displayname_normalized LIKE CONCAT(
'%', replace(companies.company_normalized,'\\\\', ''), '%')")
</code>```

Body:
When executing the following query

SELECT * FROM companies JOIN employments on companies.company_normalized LIKE CONCAT('%',
    replace(employments.displayname_normalized, '\\', ''), '%') or employments.displayname_normalized LIKE CONCAT(
    '%', replace(companies.company_normalized,'\\', ''), '%')

it works fine on databricks sql notebook cell.

However, when attempting to run this same query using spark sql executor, ie spark.sql(query), this errors out saying:
Extraneous input '' expecting {')', ','} within the replace clause.

Is there a fix for this?

Body:
You need either a single backslash, if you are using regex:

spark.sql("SELECT * FROM companies JOIN employments on companies.company_normalized LIKE CONCAT('%',
replace(employments.displayname_normalized, '\', ''), '%') or employments.displayname_normalized LIKE CONCAT(
'%', replace(companies.company_normalized,'\', ''), '%')")

or you need to escape slashes, then you need to double escape using "\\\\":

spark.sql("SELECT * FROM companies JOIN employments on companies.company_normalized LIKE CONCAT('%',
replace(employments.displayname_normalized, '\\\\', ''), '%') or employments.displayname_normalized LIKE CONCAT(
'%', replace(companies.company_normalized,'\\\\', ''), '%')")


问:
/v1/billing/subscriptions/I-XXXXXXXX/revise RESOURCE_NOT_FOUND cannot revise plan
I am following this documentation:
https://developer.paypal.com/docs/platforms/subscriptions/customize/revise-subscriptions/

I can make a get subscription request and I do find the resource, so it does exists, I'm trying to change a plan for user with no success.

I have tried multiple subscriptions upgrades and keep getting this error:

```<code>{
    "name": "RESOURCE_NOT_FOUND",
    "message": "The specified resource does not exist.",
    "debug_id": "badd307417e54",
    "details": [
        {
            "issue": "INVALID_RESOURCE_ID",
            "description": "Requested resource ID was not found."
        }
    ],
    "links": [
        {
            "href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#RESOURCE_NOT_FOUND",
            "rel": "information_link",
            "method": "GET"
        }
    ]
}
</code>```

I'm testing my personal user on production environment.

Request made using postman:

```<code>curl --location --request POST 'https://api-m.paypal.com/v1/billing/subscriptions/I-XXXXXX/revise' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer xXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxX' \
--data-raw '{"plan_id":"P-XXXXXXXXXXXXXXX"}'
</code>```

答:
After posting here I have found other questions about the /revise endpoint, none was answered, after that we have initiated a communication with PayPal's merchant support and apparently there is a bug.

The issue was escalated to PayPal's engineers, not sure when it will be resolved.

If anyone else is having this issue at the moment and is looking to change a plan, we have found a functioning workaround:

Create a new subscription - Users need approve the new price on PayPal

You will have to manually calculate the first payment in case of an upgrade

Once the new subscription activated - cancel the old subscription

We didn't find a way update an existing subscription plan

I hope it will help someone save some time

Body:
I am following this documentation:
https://developer.paypal.com/docs/platforms/subscriptions/customize/revise-subscriptions/

I can make a get subscription request and I do find the resource, so it does exists, I'm trying to change a plan for user with no success.

I have tried multiple subscriptions upgrades and keep getting this error:

{
    "name": "RESOURCE_NOT_FOUND",
    "message": "The specified resource does not exist.",
    "debug_id": "badd307417e54",
    "details": [
        {
            "issue": "INVALID_RESOURCE_ID",
            "description": "Requested resource ID was not found."
        }
    ],
    "links": [
        {
            "href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#RESOURCE_NOT_FOUND",
            "rel": "information_link",
            "method": "GET"
        }
    ]
}

I'm testing my personal user on production environment.

Request made using postman:

curl --location --request POST 'https://api-m.paypal.com/v1/billing/subscriptions/I-XXXXXX/revise' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer xXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxX' \
--data-raw '{"plan_id":"P-XXXXXXXXXXXXXXX"}'


问:
The method '>=' was called on null. Receiver: null Tried calling: >=(0.0), until I remove and replace
So I have a flutter program which is reading values from Cloud Firestore and stores them into variables. I can normally show their value with Text(), or change them.
Now I wanted to make a Color display with a simple if statement. So if the Firestore value for example is bigger than 1 (>1), the color shall be blue. If it is smaller, then red.

But for some reason, when opening the page, it gives me this error: The method '>=' was called on null. Receiver: null Tried calling: >=(0.0)

But if I simply remove my if code, start the program again, and then add it again, it works just fine. It seems that it has a problem with the start values, but how do I fix that?

```<code>                            stream: FirebaseFirestore.instance
                                .collection('Digitaluhr')
                                .snapshots(),
                            builder: (context,
                                AsyncSnapshot<QuerySnapshot> snapshot) {
                              int itemCount =
                                  snapshot.data.docs.length; //Dokumentlänge
                              itemCount--; //-1 weil Index
                              Luftguete = snapshot.data.docs[itemCount]
                                  ['Luftgüte']; //Luftgüte Wert zum Verarbeiten
                              return ListTile(

if (Luftguete > 2.00 && Luftguete <= 3.00)
                              Container(
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  border: Border.all(
                                      width: 40, color: Colors.yellow),
                                ),
                                child: Text('Mäßig',
                                    style: TextStyle(
                                        height: 0.00001,
                                        color: Colors.white,
                                        backgroundColor: Colors.yellow)),
                              ),

                            if (Luftguete > 3.00 && Luftguete <= 4.00)
                              Container(
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  border: Border.all(
                                      width: 40, color: Colors.orange),
                                ),
                                child: Text('Schlecht',
                                    style: TextStyle(
                                        height: 0.00001,
                                        color: Colors.white,
                                        backgroundColor: Colors.orange)),
                              ),
</code>```

答:
Well, this is guesswork, because you did not actually post the code in question... but Luftguete seems to be not a local variable, but probably in your state. So... before your StreamBuilder (I guess, not in your code either) fires the first time, it is null. And you probably access it somewhere else. If you make Luftguete a local variable, you will find where else you access it. Because you will get compiler errors :)

Or, maybe you have a data point where snapshot.data.docs[itemCount]['Luftgüte'] is simply null. We don't know your data. You would need to check that.

See also: What is a NoSuchMethod error and how do I fix it?

Body:
So I have a flutter program which is reading values from Cloud Firestore and stores them into variables. I can normally show their value with Text(), or change them.
Now I wanted to make a Color display with a simple if statement. So if the Firestore value for example is bigger than 1 (>1), the color shall be blue. If it is smaller, then red.

But for some reason, when opening the page, it gives me this error: The method '>=' was called on null. Receiver: null Tried calling: >=(0.0)

But if I simply remove my if code, start the program again, and then add it again, it works just fine. It seems that it has a problem with the start values, but how do I fix that?

                            stream: FirebaseFirestore.instance
                                .collection('Digitaluhr')
                                .snapshots(),
                            builder: (context,
                                AsyncSnapshot<QuerySnapshot> snapshot) {
                              int itemCount =
                                  snapshot.data.docs.length; //Dokumentlänge
                              itemCount--; //-1 weil Index
                              Luftguete = snapshot.data.docs[itemCount]
                                  ['Luftgüte']; //Luftgüte Wert zum Verarbeiten
                              return ListTile(

if (Luftguete > 2.00 && Luftguete <= 3.00)
                              Container(
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  border: Border.all(
                                      width: 40, color: Colors.yellow),
                                ),
                                child: Text('Mäßig',
                                    style: TextStyle(
                                        height: 0.00001,
                                        color: Colors.white,
                                        backgroundColor: Colors.yellow)),
                              ),

                            if (Luftguete > 3.00 && Luftguete <= 4.00)
                              Container(
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  border: Border.all(
                                      width: 40, color: Colors.orange),
                                ),
                                child: Text('Schlecht',
                                    style: TextStyle(
                                        height: 0.00001,
                                        color: Colors.white,
                                        backgroundColor: Colors.orange)),
                              ),


问:
fecth api not posting data to nodeserver
i have a node backend set up, when i send a get request, it works perfectly, but when i send a post request it doesn't send the data to the backend.
Here is my code:

```<code>  fetch("http://localhost:3000/", { method: "POST",body:{"title":title.value,"content":content.value}})
    .then((res) => res.json())
    .then((data) => {
      console.log(data);
    });
</code>```

i have even tried sending it through the formdata object it is still not working:

```<code>  const formdata = new FormData();
    formdata.append("title",title.value)
    formdata.append("content",content.value)

    fetch("http://localhost:3000/", { method: "POST",body:formdata})
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      });
</code>```

this is the console.log:
enter image description here

this is the backend:

```<code>//crud applications
app.post("/", async (req, res) => {
  const { title, content } = req.body;

  try {
    const newPost = await postModel.create({ title, content });
    res.json(newPost);
  } catch (error) {
    res.status(500).send(error);
  }
});
</code>```

答:
instead of using fetch, use Axios. import it in your HTML with this CDN

and then use this code it should work:

```<code>  const data = {
      title: title.value,
      content: content.value,
    };
    axios.post("http://localhost:3000/", data).then((response) => {
      const result = response.data;
      console.log(result);

    });
</code>```

Body:
i have a node backend set up, when i send a get request, it works perfectly, but when i send a post request it doesn't send the data to the backend.
Here is my code:

  fetch("http://localhost:3000/", { method: "POST",body:{"title":title.value,"content":content.value}})
    .then((res) => res.json())
    .then((data) => {
      console.log(data);
    });

i have even tried sending it through the formdata object it is still not working:

  const formdata = new FormData();
    formdata.append("title",title.value)
    formdata.append("content",content.value)

    fetch("http://localhost:3000/", { method: "POST",body:formdata})
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      });

this is the console.log:
enter image description here

this is the backend:

//crud applications
app.post("/", async (req, res) => {
  const { title, content } = req.body;

  try {
    const newPost = await postModel.create({ title, content });
    res.json(newPost);
  } catch (error) {
    res.status(500).send(error);
  }
});

Body:
instead of using fetch, use Axios. import it in your HTML with this CDN <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

and then use this code it should work:

  const data = {
      title: title.value,
      content: content.value,
    };
    axios.post("http://localhost:3000/", data).then((response) => {
      const result = response.data;
      console.log(result);

    });


问:
The client has been disconnected while trying to perform the connection
When trying to connect to a Mosquitto MQTT queue running locally, I get the following error.

```<code>Unhandled exception. System.AggregateException: One or more errors occurred. (The client  has been disconnected while trying to perform the connection)
 ---> System.Net.Mqtt.MqttClientException: The client  has been disconnected while trying to perform the connection
   at System.Net.Mqtt.Sdk.MqttClientImpl.ConnectAsync(MqttClientCredentials credentials, MqttLastWill will, Boolean cleanSession)
</code>```

I am using the default options when setting up the System.Net.Mqtt.MqttClient.

var config = new MqttConfiguration() {
  Port = 1883
};
var client = MqttClient.CreateAsync("localhost", config).Result;
var sessionState = client.ConnectAsync(
                new MqttClientCredentials(clientId: "camerasim")).Result;
```
<p>The following errors show up in the Mosquitto MQTT log.</p>
```1644497589: New connection from 172.17.0.1:56792 on port 1883.

1644497589: New client connected from 172.17.0.1:56792 as camerasim (p2, c0, k0).

1644497589: Bad socket read/write on client camerasim: Invalid arguments provided.
```

答:
I was able to successfully make a connection by changing the default KeepAliveSecs property when setting up the MqttConfiguration.

var config = new MqttConfiguration() {
  KeepAliveSecs = 1,
  Port = 1883
};
```

Body:
When trying to connect to a Mosquitto MQTT queue running locally, I get the following error.

Unhandled exception. System.AggregateException: One or more errors occurred. (The client  has been disconnected while trying to perform the connection)
 ---> System.Net.Mqtt.MqttClientException: The client  has been disconnected while trying to perform the connection
   at System.Net.Mqtt.Sdk.MqttClientImpl.ConnectAsync(MqttClientCredentials credentials, MqttLastWill will, Boolean cleanSession)

I am using the default options when setting up the System.Net.Mqtt.MqttClient.

var config = new MqttConfiguration() {
  Port = 1883
};
var client = MqttClient.CreateAsync("localhost", config).Result;
var sessionState = client.ConnectAsync(
                new MqttClientCredentials(clientId: "camerasim")).Result;

The following errors show up in the Mosquitto MQTT log.

1644497589: New connection from 172.17.0.1:56792 on port 1883.

1644497589: New client connected from 172.17.0.1:56792 as camerasim (p2, c0, k0).

1644497589: Bad socket read/write on client camerasim: Invalid arguments provided.


问:
Raycast only works at a specific height
I want to make a 3D platformer for a school project.
Since I'm not that experienced in game development, I followed Plai's tutorial. My biggest problem are that I keep sliding down slopes and the slope detection. It detects the slope only if there's a surface below the slope, the player has some distance from the ground yet is not too far from the ground.

This is the method shown to detect the slope.
Tried editing it but nothing seems to work.

```<code>    if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight / 2 * 5f))
    {
        if (slopeHit.normal != Vector3.up) return true;
    }

    Color rayColor;
    if (slopeHit.collider != null) rayColor = Color.green;
    else rayColor = Color.red;

    Debug.DrawRay(transform.position, Vector3.down, rayColor);

    return slopeHit.collider != null;
</code>```

答:
well in the first part

```<code>if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight / 2 * 5f))
{
    if (slopeHit.normal != Vector3.up) return true;
}
</code>```

if you hit something and it is a slope you return already.

Otherwise you execute the rest even if you maybe wouldn't hit anything at all.

You would probably rather do e.g.

```<code>if (Physics.Raycast(transform.position, Vector3.down, out var slopeHit, playerHeight / 2f * 5f))
{
    var isSlope = slopeHit.normal != Vector3.up;

    Debug.DrawLine(transform.position, slopeHit.point, isSlope ? Color.yellow : Color.green);

    return isSlope;
}

//meaning you don't hit anything at all
Debug.DrawRay(transform.position, Vector3.down, Color.red);
return false;
</code>```

Title: Raycast only works at a specific height

Body:
I want to make a 3D platformer for a school project.
Since I'm not that experienced in game development, I followed Plai's tutorial. My biggest problem are that I keep sliding down slopes and the slope detection. It detects the slope only if there's a surface below the slope, the player has some distance from the ground yet is not too far from the ground.

This is the method shown to detect the slope.
Tried editing it but nothing seems to work.

    if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight / 2 * 5f))
    {
        if (slopeHit.normal != Vector3.up) return true;
    }

    Color rayColor;
    if (slopeHit.collider != null) rayColor = Color.green;
    else rayColor = Color.red;

    Debug.DrawRay(transform.position, Vector3.down, rayColor);

    return slopeHit.collider != null;

Body:
well in the first part

if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight / 2 * 5f))
{
    if (slopeHit.normal != Vector3.up) return true;
}

if you hit something and it is a slope you return already.

Otherwise you execute the rest even if you maybe wouldn't hit anything at all.

You would probably rather do e.g.

if (Physics.Raycast(transform.position, Vector3.down, out var slopeHit, playerHeight / 2f * 5f))
{
    var isSlope = slopeHit.normal != Vector3.up;

    Debug.DrawLine(transform.position, slopeHit.point, isSlope ? Color.yellow : Color.green);

    return isSlope;
}

//meaning you don't hit anything at all
Debug.DrawRay(transform.position, Vector3.down, Color.red);
return false;


问:
What is the difference between Generator-Function and Generator-Object
in this code we have to use a = MyGen() to be able to use next(a).

if we just use print (next(MyGen())) the output will always be the first yield.

```<code>def MyGen():
    n=1
    print('first')
    yield n

    n+=1
    print('second')
    yield n

    n+=1
    print('last')
    yield n

a = MyGen()
print(next(a))
print(next(a))

print(next(MyGen()))
print(next(MyGen()))
</code>```

output:

```<code>first
1
second
2
first
1
first
1
</code>```

What is the difference between Generator-Function and Generator-Object?

and What is stored in Generator-Object (like a) that causes this?

thanks.

答:
It's similiar to class vs instance:
MyGen() is kinda like a class, in that calling it will create a new object every time, going from the beggining of the method. That's why you get first every time you call next(MyGen()) - because each of them is a separate, unnamed generator object.
When you assign MyGen() to some variable like a you keep the reference to one specific object, and you can keep calling next(a) on that one object to continue execution from last yield to the next one.

Body:
in this code we have to use a = MyGen() to be able to use next(a).

if we just use print (next(MyGen())) the output will always be the first yield.

def MyGen():
    n=1
    print('first')
    yield n

    n+=1
    print('second')
    yield n

    n+=1
    print('last')
    yield n

a = MyGen()
print(next(a))
print(next(a))

print(next(MyGen()))
print(next(MyGen()))

output:

first
1
second
2
first
1
first
1

What is the difference between Generator-Function and Generator-Object?

and What is stored in Generator-Object (like a) that causes this?

thanks.


问:
jquery datepicker with multiple months in vertical column
I need to display jquery datepicker calendar with multiple months options in vertical column. Looks like next month lies below previous one.
Does any body know, how to do that?

Thank you!

答:
Here you go http://jsbin.com/idavik
Try adding more styles. </p>