问:
How do I get more space between labels on the y axis
```<code>dt5 <- gapminder %>%
  filter(continent == "Asia" & year == 2007)
dt5
ggplot(dt5,
       aes(x=lifeExp,
           y=reorder(country, lifeExp))) +
  geom_point(size = 3,color="blue") +
  geom_segment(aes(x = 40,   # 起始位置
               xend = lifeExp,
               y = reorder(country, lifeExp),
               yend = reorder(country, lifeExp)),
               color = "lightgrey") +
  labs (x = "Life Expectancy (years)",
        y = "",
        title = "Life Expectancy by Country",
        subtitle = "GapMinder data for Asia - 2007") +
  theme_minimal() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())

</code>```

I want more space between the lines, I think the current picture is too crowded

enter image description here

答:
Since you only want more space between all labels, I think you can simply solve this by saving your plot with  ggsave() and specifying a width and height argument.

Two examples:

```<code>ggsave('version1.png', width = 6, height = 6)
</code>```

```<code>ggsave('version2.png', width = 6, height = 10)
</code>```

Body:
dt5 <- gapminder %>%
  filter(continent == "Asia" & year == 2007)
dt5
ggplot(dt5,
       aes(x=lifeExp,
           y=reorder(country, lifeExp))) +
  geom_point(size = 3,color="blue") +
  geom_segment(aes(x = 40,   # 起始位置
               xend = lifeExp,
               y = reorder(country, lifeExp),
               yend = reorder(country, lifeExp)),
               color = "lightgrey") +
  labs (x = "Life Expectancy (years)",
        y = "",
        title = "Life Expectancy by Country",
        subtitle = "GapMinder data for Asia - 2007") +
  theme_minimal() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())

I want more space between the lines, I think the current picture is too crowded

enter image description here

Body:
Since you only want more space between all labels, I think you can simply solve this by saving your plot with  ggsave() and specifying a width and height argument.

Two examples:

ggsave('version1.png', width = 6, height = 6)

ggsave('version2.png', width = 6, height = 10)


来源: stackexchange

问:
VSCode Jupyter not connecting to python kernel
Launching a cell will make this message appear: Connecting to kernel: Python 3.9.6 64-bit: Activating Python Environment 'Python 3.9.6 64-bit'. This message will then stay up loading indefinitely, without anything happening. No actual error message.

I've already tried searching for this problem, but every other post seem to obtain at least an error message, which isn't the case here. I still looked at some of these, which seemed to indicate the problem might have come from the traitlets package. I tried to downgrade it to what was recommended, but it didn't solve anything, so I reverted the downgrade.

The main problem here is that I have no idea what could cause such a problem, without even an error message. If you think additional info could help, please do ask, I have no idea what could be of use right now.

答: Not sure what did the trick but downgrading VSCode to November version and after that reinstalling Jupyter extension worked for me.</p>

ContentLicense: CC BY-SA 4.0


问:
Change name of audio file downloaded from youtube-dl
I am writing a shell script to download audio.

I used youtube-dl -f 'bestaudio[ext=m4a]' <myurl>
The resulting file is the title along with-mSc76Q90C4.m4a where m4a is the format

I would like to set the filename during download and also have it in .wav format

PS: To covert to .wav, I tried youtube-dl -f 'bestaudio[ext=wav]' <myurl>  but it did not seem to work. Error thrown is basically - cannot use specified format.

Here is the relavent part of my shell script

```<code>   `read -p "Copy and paste the YouTube url" URL
    echo $URL
    read -p "Enter the song name" SONG
    youtube-dl -f 'bestaudio[ext=m4a]' $URL`
</code>```

I would like the string in $SONG to be the filename.

So if $SONG = "mysongname"
I want the file to be mysongname.wav

答:
In the documentation of youtube-dl you'll find a --output option that lets you set the filename directly:

youtube-dl -f 'bestaudio[ext=m4a]' -o "$SONG" "$URL"
```

There's also a --audio-format option that seems to convert the extracted audio stream from a video to a given audio format but I'm not sure that it'll work for non-video files.

Body:
I am writing a shell script to download audio.

I used youtube-dl -f 'bestaudio[ext=m4a]' <myurl>
The resulting file is the title along with-mSc76Q90C4.m4a where m4a is the format

I would like to set the filename during download and also have it in .wav format

PS: To covert to .wav, I tried youtube-dl -f 'bestaudio[ext=wav]' <myurl>  but it did not seem to work. Error thrown is basically - cannot use specified format.

Here is the relavent part of my shell script

   `read -p "Copy and paste the YouTube url" URL
    echo $URL
    read -p "Enter the song name" SONG
    youtube-dl -f 'bestaudio[ext=m4a]' $URL`

I would like the string in $SONG to be the filename.

So if $SONG = "mysongname"
I want the file to be mysongname.wav

Body:
In the documentation of youtube-dl you'll find a --output option that lets you set the filename directly:

youtube-dl -f 'bestaudio[ext=m4a]' -o "$SONG" "$URL"

There's also a --audio-format option that seems to convert the extracted audio stream from a video to a given audio format but I'm not sure that it'll work for non-video files.


问:
Requiring unknown module "3"
Requiring unknown module "3". If you are sure the module exists, try restarting Metro. You may also want to run 'yarn' or 'npm intall'.

Any one can help me with this erro on react-native. I'm using vscode and android studio.

答:
Firstly, I encountered the same error message. Then I needed to solve the problem which occurred when I changed the folder structure, influences paths of imported files  after I ran the app (on runtime). Actually the error  message gives us the cause of the problem but I slogged on handling this error as a newbie on React Native. Frankly, the problem we have faced is about the packager as far as i have learnt.

It’s all about how the packager works. Packaging happens once before runtime so those variables don't have values yet.

Variables are components we have imported from other files in our situation.

The packager only works with statically analyzable “imports”. Treat “import” like a keyword.

As an example, let’s imagine you have folders in the root path of your project. If you run your Android Emulator, then packaging is carried through by Gradle under the hood.

```<code>import styles from './styles'
import StepCurrent from './images/stepcurrent.png'
import StepDone from './images/stepdone.png'
import StepNext from './images/stepnext.png'
</code>```

Then if you try to change folder structure and call these components from another path, error occurs because packaging happened at the first phase, running the emulator, before your changes. Emulator does not read your current file paths.

```<code>import styles from './exampleFolder/styles'
import StepCurrent from './exampleFolder/images/stepcurrent.png'
import StepDone from './exampleFolder/images/stepdone.png'
import StepNext from './exampleFolder/images/stepnext.png'
</code>```

So, you can restart your emulator to restart your packager. Then the problem disappears.
References:

The packager only works with statically analyzable 'requires'.

Packaging happens once before runtime.

Solution way is to restart packager.

Title: Requiring unknown module "3"

Body:
Firstly, I encountered the same error message. Then I needed to solve the problem which occurred when I changed the folder structure, influences paths of imported files  after I ran the app (on runtime). Actually the error  message gives us the cause of the problem but I slogged on handling this error as a newbie on React Native. Frankly, the problem we have faced is about the packager as far as i have learnt.

It’s all about how the packager works. Packaging happens once before runtime so those variables don't have values yet.

Variables are components we have imported from other files in our situation.

The packager only works with statically analyzable “imports”. Treat “import” like a keyword.

As an example, let’s imagine you have folders in the root path of your project. If you run your Android Emulator, then packaging is carried through by Gradle under the hood.

import styles from './styles'
import StepCurrent from './images/stepcurrent.png'
import StepDone from './images/stepdone.png'
import StepNext from './images/stepnext.png'

Then if you try to change folder structure and call these components from another path, error occurs because packaging happened at the first phase, running the emulator, before your changes. Emulator does not read your current file paths.

import styles from './exampleFolder/styles'
import StepCurrent from './exampleFolder/images/stepcurrent.png'
import StepDone from './exampleFolder/images/stepdone.png'
import StepNext from './exampleFolder/images/stepnext.png'

So, you can restart your emulator to restart your packager. Then the problem disappears.
References:

The packager only works with statically analyzable 'requires'.

Packaging happens once before runtime.

Solution way is to restart packager.


问:
How to make a button, that is inside a dialog but not inside a form, respond to Enter key being pressed
I need that a button inside a dialog responds to the key.enter event.

I have searched and all the examples are buttons that are inside a <form> which is not the case

Do I need to put the button inside a "dummy form" for this to work? can I do that without losing the current button style

This is what I have tried...

<mat-dialog-actions class="buttons">
    <button mat-button mat-dialog-close (click)="onCancelClick()">
        {{data.cancel}}
    </button>
    <button class="action nonDefault" mat-button mat-dialog-close color="accent" class="action"
        (click)="cancelOrClose()" (keyup.enter)="cancelOrClose()">
        {{data.cancelOrClose}}
    </button>
</mat-dialog-actions>
```

Hitting enter with the dialog open does nothing

similar questions that I have found

Angular 5 Button Submit On Enter Key Press

angular 2 material keyup.enter does not fire at all

答:
You need autofocus and (keyup.enter) on the button so that it processes the key events

<button class="action nonDefault" #btnFocus [autofocus]="btnFocus.focus()" mat-button
    (keyup.enter)="cancelOrClose()" (click)="cancelOrClose()" mat-dialog-close>
    {{data.cancelOrClose}}
</button>
```

Body:
I need that a button inside a dialog responds to the key.enter event.

I have searched and all the examples are buttons that are inside a <form> which is not the case

Do I need to put the button inside a "dummy form" for this to work? can I do that without losing the current button style

This is what I have tried...

<mat-dialog-actions class="buttons">
    <button mat-button mat-dialog-close (click)="onCancelClick()">
        {{data.cancel}}
    </button>
    <button class="action nonDefault" mat-button mat-dialog-close color="accent" class="action"
        (click)="cancelOrClose()" (keyup.enter)="cancelOrClose()">
        {{data.cancelOrClose}}
    </button>
</mat-dialog-actions>

Hitting enter with the dialog open does nothing

similar questions that I have found

Angular 5 Button Submit On Enter Key Press

angular 2 material keyup.enter does not fire at all


问:
The correct way to determine if service is running
I am running foreground services in my app and I need to deremine if they running in my activity.
From my searches I found that this is the option:

```<code>private fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
    val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    for (service in manager.getRunningServices(Int.MAX_VALUE)) {
        if (serviceClass.name == service.service.className) {
            return true
        }
    }
    return false
}
</code>```

but:

getRunningServices(Int): is deprecated.

So I am using one of 3 ways.

Binding the service to the activity with onResume. But I think it a bit overkill for something small just to check if service is running.

Make the Intent public and check if its null, but there can be some cases where the intent not null but service not running

Check if the foreground service persistent notification is active, but this is workaround.

What is the most correct way to check if service is running?

答:
You can create a SharedPreferences in the onCreate method of the Service and append some boolean value in it.

getSharedPreferences( getString( R.string.app_name ) , Context.MODE_PRIVATE )
     .edit()
     .putBoolean( getString( R.string.service_running_status_key ) , true )
     .apply()
```

Similarly, in the onDestroy method, append false to the same key. You can then use SharedPreferences.getBoolean to check if the Service is running in foreground.

Body:
I am running foreground services in my app and I need to deremine if they running in my activity.
From my searches I found that this is the option:

private fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
    val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    for (service in manager.getRunningServices(Int.MAX_VALUE)) {
        if (serviceClass.name == service.service.className) {
            return true
        }
    }
    return false
}

but:

getRunningServices(Int): is deprecated.

So I am using one of 3 ways.

Binding the service to the activity with onResume. But I think it a bit overkill for something small just to check if service is running.

Make the Intent public and check if its null, but there can be some cases where the intent not null but service not running

Check if the foreground service persistent notification is active, but this is workaround.

What is the most correct way to check if service is running?

Body:
You can create a SharedPreferences in the onCreate method of the Service and append some boolean value in it.

getSharedPreferences( getString( R.string.app_name ) , Context.MODE_PRIVATE )
     .edit()
     .putBoolean( getString( R.string.service_running_status_key ) , true )
     .apply()

Similarly, in the onDestroy method, append false to the same key. You can then use SharedPreferences.getBoolean to check if the Service is running in foreground.


问:
How to build linux tools via MingW64 in 2021?
I'm trying to follow this example to build wget2:
https://gnutoolchains.com/building/

I've installed x86_64-8.1.0-win32-seh-rt_v6-rev0 preset (?) and first tried to build old version of wget1, but I've reached dead end. There is no way to run ./configure to create build target rules. Did I install something wrong? How I'm supposed to know what exactly is to install? Is it each new preset for each application I want to build? How I'm supposed to handle the insane list of requirements of wget2:

https://gitlab.com/gnuwget/wget2#build-requirements

And lastly - why is it so jank? Is it by design?

答:
There is a way to run ./configure on Windows. You need MSYS2 for that, which will give you a bash shell and the tools needed by ./configure.

MSYS2 comes with a package manager (pacman) which allows you to install a more recent MinGW-w64.


问:
Merge two JSON into one JSON using Java and validate in karate feature file
Json1 {"key1" :"one","key2":"two"}
Json2 {"FN": "AB","LN":"XY"}
I wish to have Json3 {"key1" :"one","key2":"two","FN": "AB","LN":"XY"}

I have used below code but it does not work:

```<code>        JSONObject mergedJSON = new JSONObject();
        try {
            mergedJSON = new JSONObject(json1, JSONObject.getNames(json1));
            for (String Key : JSONObject.getNames(json2)) {
                mergedJSON.put(Key, json2.get(Key));
            }

        } catch (JSONException e) {

            throw new RuntimeException("JSON Exception" + e);
        }
        return mergedJSON;
    }

      * call defaultCOM {ID: "COM-123"}
        * def defaultResponse = response.data.default
        * def jMap = mergeJSON.toMap(defaultResponse)
Here error comes (language: Java, type: com.intuit.karate.graal.JsMap) to Java type 'org.json.JSONObject': Unsupported target type
</code>```

答:
Well, if you just don't care about key collisions this should work:

```<code>String jsons01 = "{\"key1\" :\"one\",\"key2\":\"two\"}";
String jsons02 = "{\"FN\": \"AB\",\"LN\":\"XY\"}";
JSONObject jsono01 = new JSONObject(jsons01);
JSONObject jsono02 = new JSONObject(jsons02);
JSONObject merged = new JSONObject(jsono01, Object.getNames(jsono01));
for (String key : JSONObject.getNames(jsono02)) {
    merged.append(key, jsono02.get(key));
}
System.out.println(merged);
</code>```

Result is: {"key1":"one","FN":["AB"],"key2":"two","LN":["XY"]}

Body:
Json1 {"key1" :"one","key2":"two"}
Json2 {"FN": "AB","LN":"XY"}
I wish to have Json3 {"key1" :"one","key2":"two","FN": "AB","LN":"XY"}

I have used below code but it does not work:

        JSONObject mergedJSON = new JSONObject();
        try {
            mergedJSON = new JSONObject(json1, JSONObject.getNames(json1));
            for (String Key : JSONObject.getNames(json2)) {
                mergedJSON.put(Key, json2.get(Key));
            }

        } catch (JSONException e) {

            throw new RuntimeException("JSON Exception" + e);
        }
        return mergedJSON;
    }

      * call defaultCOM {ID: "COM-123"}
        * def defaultResponse = response.data.default
        * def jMap = mergeJSON.toMap(defaultResponse)
Here error comes (language: Java, type: com.intuit.karate.graal.JsMap) to Java type 'org.json.JSONObject': Unsupported target type

Body:
Well, if you just don't care about key collisions this should work:

String jsons01 = "{\"key1\" :\"one\",\"key2\":\"two\"}";
String jsons02 = "{\"FN\": \"AB\",\"LN\":\"XY\"}";
JSONObject jsono01 = new JSONObject(jsons01);
JSONObject jsono02 = new JSONObject(jsons02);
JSONObject merged = new JSONObject(jsono01, Object.getNames(jsono01));
for (String key : JSONObject.getNames(jsono02)) {
    merged.append(key, jsono02.get(key));
}
System.out.println(merged);

Result is: {"key1":"one","FN":["AB"],"key2":"two","LN":["XY"]}


问:
How to convert widget to widget??
the handlerFunc wants to widget? but i have widget. And i have an error : The argument type 'SplashScreen Function(BuildContext, Map<String, dynamic>)' can't be assigned to the parameter type 'Widget? Function(BuildContext?, Map<String, List>)'.

class Flurouter {
  static final FluroRouter router = FluroRouter();

  static final Handler _splashHandler = Handler(
      handlerFunc: (BuildContext context, Map<String, dynamic> params) =>
          SplashScreen());

  static final Handler _mainHandler = Handler(
      handlerFunc: (BuildContext context, Map<String, dynamic> params) =>
          LandingPage(
            page: params['name'][0],
            extra: '',
          )); // this one is for one paramter passing...

  // lets create for two parameters tooo...
  static final Handler _mainHandler2 = Handler(
      handlerFunc: (BuildContext context, Map<String, dynamic> params) =>
          LandingPage(
            page: params['name'][0],
            extra: params['extra'][0],
          ));

  // ok its all set now .....
  // now lets have a handler for passing parameter tooo....

  static void setupRouter() {
    router.define(
      '/',
      handler: _splashHandler,
    );
    router.define(
      '/main/:name',
      handler: _mainHandler,
      transitionType: TransitionType.fadeIn,
    );

    router.define(
      '/main/:name/:extra',
      handler: _mainHandler2,
      transitionType: TransitionType.fadeIn,
    );
  }
}```

答:
I realized that I can't convert the widget. But I can ensure null safety like this:

class Flurouter {
  static final FluroRouter router = FluroRouter();

  //Handlers setup here Where will I go?

  //parameterless redirects
  static final Handler _splashHandler = Handler(
      handlerFunc: (BuildContext? context, Map<String, dynamic> params) {
    return const SplashScreen();
  });

  // one parameter redirects if you add extra thing
  static final Handler _mainHandler = Handler(
      handlerFunc: (BuildContext? context, Map<String, dynamic> params) {
    return LandingPage(
      page: params['name'][0],
      extra: '',
    );
  });

  static void setupRouter() {
    router.define('/', handler: _splashHandler);
    router.define('/:name', handler: _mainHandler);
  }
}```

Title: How to convert widget to widget??


问:
Save the selection state of the current selected item on a list
A macOS app that works with local files need to reload the files when it gets focused again. This is to load any new files that might have been placed there while the app was in the background.

The issue is that when I clear the list, reload the files (rebuilding the list), the first item is always selected, so if I was working on an item I'm being forced to select it again to continue working on it.

I tried keeping the current UUID of the selected note and passing that back, but I have no clue whether this is correct, or how to programmatically select an item in the list matching the UUID saved.

How do I keep the current selected item, and then go to it when I reload the data?

Code I tried:

```<code>struct DataItem: Codable, Hashable, Identifiable {
    let id: UUID
    var text: String
}

struct AllData: View {

    @EnvironmentObject private var data: DataModel //array of DataItem's
    @State var selectedItemId: UUID?
    @State var currentItemId: UUID?

     NavigationView {
            List(data.prices.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) }) { price in
                NavigationLink(
                    destination: PriceView(price: price, text: price.text),
                    tag: price.id,
                    selection: $selectedItemId
                ) {
                    VStack(alignment: .leading) {
                        Text(getTitle(titleText: price.text)).font(.body).fontWeight(.bold)
                    }
                    .padding(.vertical, 10)
                }
            }

     }
    .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
            self.currentItemId = self.selectedItemId
            if getCurrentSaveDirectory(for: "savedDirectory") != "" {
                if !isDirectoryEmpty() {
                    data.price.removeAll()
                    loadFiles(dataModel: data)
                    self.selectedItemId = self.currentItemId
                }
            }
        }
}
</code>```

答:
I think using the current UUID of the selected note as you do is a good idea.
Without all the code it is difficult to test my answer, however you could
try this approach, using a List selection variable and adding the simple code in onReceive,
such as this example code:

```<code>struct AllData: View {

    @EnvironmentObject private var data: DataModel //array of DataItem's
    @State var selectedItemId: UUID?
    @State var currentItemId: UUID?

    @State var listSelection: DataItem?  // <--- here selection

    var body: some View {
        NavigationView {
            List(data.prices.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) },
                 selection: $listSelection) { price in  // <--- here selection
                NavigationLink(
                    destination: PriceView(price: price, text: price.text),
                    tag: price.id,
                    selection: $selectedItemId
                ) {
                    VStack(alignment: .leading) {
                        Text(getTitle(titleText: price.text)).font(.body).fontWeight(.bold)
                    }
                    .padding(.vertical, 10)
                }
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
            self.currentItemId = self.selectedItemId
            if getCurrentSaveDirectory(for: "savedDirectory") != "" {
                if !isDirectoryEmpty() {
                    data.price.removeAll()
                    loadFiles(dataModel: data)
                    self.selectedItemId = self.currentItemId
                    // --- here ---
                    if let theItem = data.first(where: {$0.id == selectedItemId}) {
                        listSelection = theItem
                    }
                }
            }
        }
    }
}
</code>```

Body:
A macOS app that works with local files need to reload the files when it gets focused again. This is to load any new files that might have been placed there while the app was in the background.

The issue is that when I clear the list, reload the files (rebuilding the list), the first item is always selected, so if I was working on an item I'm being forced to select it again to continue working on it.

I tried keeping the current UUID of the selected note and passing that back, but I have no clue whether this is correct, or how to programmatically select an item in the list matching the UUID saved.

How do I keep the current selected item, and then go to it when I reload the data?

Code I tried:

struct DataItem: Codable, Hashable, Identifiable {
    let id: UUID
    var text: String
}

struct AllData: View {

    @EnvironmentObject private var data: DataModel //array of DataItem's
    @State var selectedItemId: UUID?
    @State var currentItemId: UUID?

     NavigationView {
            List(data.prices.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) }) { price in
                NavigationLink(
                    destination: PriceView(price: price, text: price.text),
                    tag: price.id,
                    selection: $selectedItemId
                ) {
                    VStack(alignment: .leading) {
                        Text(getTitle(titleText: price.text)).font(.body).fontWeight(.bold)
                    }
                    .padding(.vertical, 10)
                }
            }

     }
    .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
            self.currentItemId = self.selectedItemId
            if getCurrentSaveDirectory(for: "savedDirectory") != "" {
                if !isDirectoryEmpty() {
                    data.price.removeAll()
                    loadFiles(dataModel: data)
                    self.selectedItemId = self.currentItemId
                }
            }
        }
}

Body:
I think using the current UUID of the selected note as you do is a good idea.
Without all the code it is difficult to test my answer, however you could
try this approach, using a List selection variable and adding the simple code in onReceive,
such as this example code:

struct AllData: View {

    @EnvironmentObject private var data: DataModel //array of DataItem's
    @State var selectedItemId: UUID?
    @State var currentItemId: UUID?

    @State var listSelection: DataItem?  // <--- here selection

    var body: some View {
        NavigationView {
            List(data.prices.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) },
                 selection: $listSelection) { price in  // <--- here selection
                NavigationLink(
                    destination: PriceView(price: price, text: price.text),
                    tag: price.id,
                    selection: $selectedItemId
                ) {
                    VStack(alignment: .leading) {
                        Text(getTitle(titleText: price.text)).font(.body).fontWeight(.bold)
                    }
                    .padding(.vertical, 10)
                }
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
            self.currentItemId = self.selectedItemId
            if getCurrentSaveDirectory(for: "savedDirectory") != "" {
                if !isDirectoryEmpty() {
                    data.price.removeAll()
                    loadFiles(dataModel: data)
                    self.selectedItemId = self.currentItemId
                    // --- here ---
                    if let theItem = data.first(where: {$0.id == selectedItemId}) {
                        listSelection = theItem
                    }
                }
            }
        }
    }
}


问:
Edit Text doesn't wrap around content in Android Studio
I've this simple bit of xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/cost_of_service"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"

        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

It seems that the EditText does not wrap itself horizontally even though the layout_height is set to "wrap content". Could anybody tell me why this is occurring? Sorry if this might seem like a dumb question, I'm quite new to android.

答:
Try changing the default background and text size:</p>
```<code>android:background="@null"
android:textSize="1sp"

</code>```

Body:
I've this simple bit of xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/cost_of_service"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"

        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

It seems that the EditText does not wrap itself horizontally even though the layout_height is set to "wrap content". Could anybody tell me why this is occurring? Sorry if this might seem like a dumb question, I'm quite new to android.

Body:
Try changing the default background and text size:

android:background="@null"
android:textSize="1sp"


问:
How to get real height layout with layout_height="0dp"?
I need to set the height of the FrameLayout android:id="@+id/heart_strength according to the height of the FrameLayout android:id="@+id/heart_strength_background, whose height is set like this:

```<code>            <FrameLayout
                android:id="@+id/cardiogram_background_light"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="@dimen/default_screen_margin"
                android:layout_marginTop="@dimen/chart_widget_margin_top"
                android:layout_marginEnd="@dimen/default_screen_margin"
                android:background="@drawable/chart_widget_background_light_gray"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHeight_percent="0.184"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/heart_rate_diagram_background_light" />

            <FrameLayout
                android:id="@+id/heart_strength_background"
                android:layout_width="@dimen/cardiogram_status_bar_width"
                android:layout_height="0dp"
                android:layout_marginEnd="@dimen/default_screen_margin"
                android:background="@drawable/chart_widget_background_dark_gray"
                app:layout_constraintBottom_toBottomOf="@+id/cardiogram_background_light"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/cardiogram_background_light" >

                <FrameLayout
                    android:id="@+id/heart_strength"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    app:heartStrength="@{viewmodel.heartStrengthLiveData}"
                    android:background="@drawable/chart_widget_background_light_gray"
                    android:backgroundTint="@color/turquoise"
                    android:layout_gravity="bottom"/>
            </FrameLayout>
</code>```

When I try to get real height of heart_strength.parent layout with:

```<code>    @JvmStatic
    @BindingAdapter("app:heartStrength")
    fun setHeartStrengthViewHeight(bar: FrameLayout, level: Int) {
        val barParent = bar.parent as FrameLayout
        println("bar parent height: ${barParent.layoutParams.height}")
    }
</code>```

I get 0. How can I know the actual height?

I have a card (cardiogram_background_light). Its height changes dynamically in %. Because of this, the maximum height of the bar located in this card also changes dynamically. Previously, I set its height as maxHeight * Value /100. But now maxHeight dynamically changes on different screen sizes and I want to know its value.

答:
It is because the views are not drawn yet when setHeartStrengthViewHeight is called. To solve this, try the following:

```<code>@JvmStatic
@BindingAdapter("app:heartStrength")
fun setHeartStrengthViewHeight(bar: FrameLayout, level: Int) {
    val barParent = bar.parent as FrameLayout

    val observer : ViewTreeObserver = barParent.viewTreeObserver
    observer.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            println("bar parent height: ${barParent.height}")
            barParent.viewTreeObserver.removeOnGlobalLayoutListener(this)
        }
    })

}
</code>```

Body:
I need to set the height of the FrameLayout android:id="@+id/heart_strength according to the height of the FrameLayout android:id="@+id/heart_strength_background, whose height is set like this:

            <FrameLayout
                android:id="@+id/cardiogram_background_light"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="@dimen/default_screen_margin"
                android:layout_marginTop="@dimen/chart_widget_margin_top"
                android:layout_marginEnd="@dimen/default_screen_margin"
                android:background="@drawable/chart_widget_background_light_gray"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHeight_percent="0.184"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/heart_rate_diagram_background_light" />

            <FrameLayout
                android:id="@+id/heart_strength_background"
                android:layout_width="@dimen/cardiogram_status_bar_width"
                android:layout_height="0dp"
                android:layout_marginEnd="@dimen/default_screen_margin"
                android:background="@drawable/chart_widget_background_dark_gray"
                app:layout_constraintBottom_toBottomOf="@+id/cardiogram_background_light"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/cardiogram_background_light" >

                <FrameLayout
                    android:id="@+id/heart_strength"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    app:heartStrength="@{viewmodel.heartStrengthLiveData}"
                    android:background="@drawable/chart_widget_background_light_gray"
                    android:backgroundTint="@color/turquoise"
                    android:layout_gravity="bottom"/>
            </FrameLayout>

When I try to get real height of heart_strength.parent layout with:

    @JvmStatic
    @BindingAdapter("app:heartStrength")
    fun setHeartStrengthViewHeight(bar: FrameLayout, level: Int) {
        val barParent = bar.parent as FrameLayout
        println("bar parent height: ${barParent.layoutParams.height}")
    }

I get 0. How can I know the actual height?

I have a card (cardiogram_background_light). Its height changes dynamically in %. Because of this, the maximum height of the bar located in this card also changes dynamically. Previously, I set its height as maxHeight * Value /100. But now maxHeight dynamically changes on different screen sizes and I want to know its value.

Body:
It is because the views are not drawn yet when setHeartStrengthViewHeight is called. To solve this, try the following:

@JvmStatic
@BindingAdapter("app:heartStrength")
fun setHeartStrengthViewHeight(bar: FrameLayout, level: Int) {
    val barParent = bar.parent as FrameLayout

    val observer : ViewTreeObserver = barParent.viewTreeObserver
    observer.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            println("bar parent height: ${barParent.height}")
            barParent.viewTreeObserver.removeOnGlobalLayoutListener(this)
        }
    })

}


问:
Why is pypy flask aplication slower than cpython?
I have a flask application (app.py) which returns a string,

```<code>from flask import Flask
import os

app = Flask(__name__)

@app.route("/")
def hello():
    return "Flask inside Docker!!"

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 6000))
    app.run(debug=True,host='0.0.0.0',port=port)
</code>```

I ran this application using the below dockerfile content, which gave me the throughput of 320/sec

```<code>FROM opensuse/leap:15.3
RUN zypper -n install python3 python3-pip python3-Flask
COPY . /app
WORKDIR /app
ENTRYPOINT ["python3"]
CMD ["app.py"]

</code>```

However with pypy3, I got only 200/sec throughput, the docker file is given below.

```<code>FROM opensuse/leap:15.3
FROM pypy:3
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["pypy3"]
CMD ["app.py"]

</code>```

where requirements.txt contains only "flask".

What could be the reason for this performance degradation?

答:
Brushing aside the fact that PyPy might really be intrinsically slower for your case, there are some factors that could be making it unnecessarily slower:

Profiling is known to slow PyPy a lot more than CPython.

Some debugging/logging code can disable optimizations (by, e.g., forcing frames).

The server you're using can be a dominant factor in performance (think about how awful classic CGI would be with a JIT: it would never warm up). It can also simply influence results (different WSGI servers have shown various speed-ups).

Old-style classes are slower than new-style ones.

Even if everything is in memory, you could be hitting e.g. slow paths in PyPy's SQLite.

A nightly build will probably be faster too, as there are many improvements relative to 1.5.

Body:
I have a flask application (app.py) which returns a string,

from flask import Flask
import os

app = Flask(__name__)

@app.route("/")
def hello():
    return "Flask inside Docker!!"

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 6000))
    app.run(debug=True,host='0.0.0.0',port=port)

I ran this application using the below dockerfile content, which gave me the throughput of 320/sec

FROM opensuse/leap:15.3
RUN zypper -n install python3 python3-pip python3-Flask
COPY . /app
WORKDIR /app
ENTRYPOINT ["python3"]
CMD ["app.py"]

However with pypy3, I got only 200/sec throughput, the docker file is given below.

FROM opensuse/leap:15.3
FROM pypy:3
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["pypy3"]
CMD ["app.py"]

where requirements.txt contains only "flask".

What could be the reason for this performance degradation?


问:
TS2339: Property 'text' does not exist on type '{}'
I am actually facing this line problem :- <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">here .text extension make problem. Here I used Angular11.  here is my code.

Question.component.html

```<code><mat-card >

<mat-card-content>

<form>

    <mat-form-field>
      <mat-label>Question</mat-label>
      <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">
    </mat-form-field>

  </form>
</mat-card-content>

<mat-card-actions>
    <button (click)="post(question)" mat-button>POST</button>
</mat-card-actions>

</mat-card>

</code>```

question.component.ts

```<code>import {Component} from '@angular/core'
import {ApiService} from './api.service'

@Component({

   selector:'question',
   templateUrl:'./question.component.html'

})

export class QuestionComponent{

    question = {}

    constructor(private api:ApiService){}

    post(question)
    {
        this.api.postQuestion(question);
    }
}
</code>```

when i run my application.then i found these error:-

```<code>src/app/question.component.ts:7:16
    7    templateUrl:'./question.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component QuestionComponent.

Error: src/app/question.component.html:9:36 - error TS2339: Property 'text' does not exist on type '{}'.

9       <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">
                                     ~~~~

  src/app/question.component.ts:7:16
    7    templateUrl:'./question.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component QuestionComponent.

</code>```

How I resolve this issue?

答:
You have to declare the type of the property named after 'question'. You can try following,

```<code>question:any = {};
</code>```

It's a typescript strict type checking issue of recent update version. If you are using Angular then you can easily turn off this strict type checking by this way, Turn off strict type checking in Angular

Body:
I am actually facing this line problem :- <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">here .text extension make problem. Here I used Angular11.  here is my code.

Question.component.html

<mat-card >

<mat-card-content>

<form>

    <mat-form-field>
      <mat-label>Question</mat-label>
      <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">
    </mat-form-field>

  </form>
</mat-card-content>

<mat-card-actions>
    <button (click)="post(question)" mat-button>POST</button>
</mat-card-actions>

</mat-card>

question.component.ts

import {Component} from '@angular/core'
import {ApiService} from './api.service'

@Component({

   selector:'question',
   templateUrl:'./question.component.html'

})

export class QuestionComponent{

    question = {}

    constructor(private api:ApiService){}

    post(question)
    {
        this.api.postQuestion(question);
    }
}

when i run my application.then i found these error:-

src/app/question.component.ts:7:16
    7    templateUrl:'./question.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component QuestionComponent.

Error: src/app/question.component.html:9:36 - error TS2339: Property 'text' does not exist on type '{}'.

9       <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">
                                     ~~~~

  src/app/question.component.ts:7:16
    7    templateUrl:'./question.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component QuestionComponent.

How I resolve this issue?

Body:
You have to declare the type of the property named after 'question'. You can try following,

question:any = {};

It's a typescript strict type checking issue of recent update version. If you are using Angular then you can easily turn off this strict type checking by this way, Turn off strict type checking in Angular


问:
Change a rotation of AnchorEntity in RealityKit
I placed 3d object to ARViewController after 3 seconds of placing object, then I want to rotate object by 90 degrees:

```<code>arView.scene.addAnchor(anchorEntity)

DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {

    print("after 3 sec ! ")

    let radians = 90.0 * Float.pi / 180.0

    anchorEntity.orientation = simd_quatf(angle: radians,
                                           axis: SIMD3(x: 0, y: 1, z: 0))
}
</code>```

It works very well but the problem is that I want to smooth rotation , as you can see short video, it suddenly rotate which seem weird.

How can I do this?

https://youtu.be/Ixk2elm-bfU

答:
Try move(...) instance method:

```<code>import UIKit
import RealityKit
import SceneKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let box = try! Experience.loadBox()
        let entity = box.steelBox!

        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {

            let currentMatrix = entity.transform.matrix

            // Nothing prevents you from using even SceneKit's matrix methods
            let rotation = simd_float4x4(SCNMatrix4MakeRotation(.pi/2, 0,1,0))

            let transform = simd_mul(currentMatrix, rotation)
            entity.move(to: transform, relativeTo: nil, duration: 3.0)
        }
        arView.scene.anchors.append(box)
    }
}
</code>```

Body:
I placed 3d object to ARViewController after 3 seconds of placing object, then I want to rotate object by 90 degrees:

arView.scene.addAnchor(anchorEntity)

DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {

    print("after 3 sec ! ")

    let radians = 90.0 * Float.pi / 180.0

    anchorEntity.orientation = simd_quatf(angle: radians,
                                           axis: SIMD3(x: 0, y: 1, z: 0))
}

It works very well but the problem is that I want to smooth rotation , as you can see short video, it suddenly rotate which seem weird.

How can I do this?

https://youtu.be/Ixk2elm-bfU

Body:
Try move(...) instance method:

import UIKit
import RealityKit
import SceneKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let box = try! Experience.loadBox()
        let entity = box.steelBox!

        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {

            let currentMatrix = entity.transform.matrix

            // Nothing prevents you from using even SceneKit's matrix methods
            let rotation = simd_float4x4(SCNMatrix4MakeRotation(.pi/2, 0,1,0))

            let transform = simd_mul(currentMatrix, rotation)
            entity.move(to: transform, relativeTo: nil, duration: 3.0)
        }
        arView.scene.anchors.append(box)
    }
}


问:
Unable to start the server in Django after including polls.urls in mysite/urls.py
I was creating my first view using this in Django I have included all the codes mentioned. I included the below code in ~/testsite/polls/urls.py

```<code>from django.urls import path
from . import views
urlpatterns = [
        path('', views.index, name='index'),
]
</code>```

And I added the line in ~/testsite/testsite/urls.py

```<code>path('polls/', include('polls.urls')),/home/neonreddeye/testsite/polls"""te>
The `urlpatterns` list routes URLs to views. For more information please se>    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
</code>```

When I start the server in linux using

```<code>$ python3 manage.py runserver
</code>```

This is the error I'm getting

```<code>Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.9/threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.9/dist-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 124, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 438, in check
    all_issues = checks.run_checks(
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/registry.py", line 77, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 448, in check
    for pattern in self.url_patterns:
  File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 634, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 627, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/neonreddeye/testsite/testsite/urls.py", line 1
    /home/neonreddeye/testsite/polls"""testsite URL Configuration
    ^
SyntaxError: invalid syntax
</code>```

What Do I Do to fix this?

答:
That's causing the error you have syntax error. Your path() must be inside urlpatterns[] which you already have so remove that part as

```<code>"""
The `urlpatterns` list routes URLs to views. For more information please se>    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
</code>```

Body:
I was creating my first view using this in Django I have included all the codes mentioned. I included the below code in ~/testsite/polls/urls.py

from django.urls import path
from . import views
urlpatterns = [
        path('', views.index, name='index'),
]

And I added the line in ~/testsite/testsite/urls.py

path('polls/', include('polls.urls')),/home/neonreddeye/testsite/polls"""te>
The `urlpatterns` list routes URLs to views. For more information please se>    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

When I start the server in linux using

$ python3 manage.py runserver

This is the error I'm getting

Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.9/threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.9/dist-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 124, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 438, in check
    all_issues = checks.run_checks(
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/registry.py", line 77, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 448, in check
    for pattern in self.url_patterns:
  File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 634, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 627, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/neonreddeye/testsite/testsite/urls.py", line 1
    /home/neonreddeye/testsite/polls"""testsite URL Configuration
    ^
SyntaxError: invalid syntax

What Do I Do to fix this?

Body:
That's causing the error you have syntax error. Your path() must be inside urlpatterns[] which you already have so remove that part as

"""
The `urlpatterns` list routes URLs to views. For more information please se>    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]


问:
Checking for empty Queue in python's multiprocessing
I have a program using python's packages multiprocessing and Queue. One of my functions have this structure:

```<code>from multiprocessing import Process, Queue
def foo(queue):
   while True:
       try:
           a = queue.get(block = False)
           doAndPrintStuff(a)
       except:
           print "the end"
           break

   if __name__ == "__main__"
     nthreads = 4
     queue = Queue.Queue()
     # put stuff in the queue here
     for stuff in moreStuff:
         queue.put(stuff)
     procs = [Process(target = foo, args = (queue,)) for i in xrange(nthreads)]
     for p in procs:
       p.start()
     for p in procs:
       p.join()
</code>```

the idea is that when I try to extract from the queue and it is empty, it'll raise an exception and terminate the loop. So I have two questions:

1) is this a safe idiom? Are there better ways to do this?

2) I tried to find what is the exact exception that is raised when I try to .get() from an empty queue. Currently my program is catching all exceptions, which sucks when the error is somewhere else and I only get a "the end" message.

I tried:

```<code>  import Queue
  queue = Queue.Queue()
  [queue.put(x) for x in xrange(10)]
  try:
       print queue.get(block = False)
  except Queue.Empty:
       print "end"
       break
</code>```

but I got the error as if I hadn't caught the exception. What's the correct exception to catch?

答: Try reading the queue library docs.  Aren't you looking for Queue.empty()?</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a program using python's packages multiprocessing and Queue. One of my functions have this structure:

from multiprocessing import Process, Queue
def foo(queue):
   while True:
       try:
           a = queue.get(block = False)
           doAndPrintStuff(a)
       except:
           print "the end"
           break

   if __name__ == "__main__"
     nthreads = 4
     queue = Queue.Queue()
     # put stuff in the queue here
     for stuff in moreStuff:
         queue.put(stuff)
     procs = [Process(target = foo, args = (queue,)) for i in xrange(nthreads)]
     for p in procs:
       p.start()
     for p in procs:
       p.join()

the idea is that when I try to extract from the queue and it is empty, it'll raise an exception and terminate the loop. So I have two questions:

1) is this a safe idiom? Are there better ways to do this?

2) I tried to find what is the exact exception that is raised when I try to .get() from an empty queue. Currently my program is catching all exceptions, which sucks when the error is somewhere else and I only get a "the end" message.

I tried:

  import Queue
  queue = Queue.Queue()
  [queue.put(x) for x in xrange(10)]
  try:
       print queue.get(block = False)
  except Queue.Empty:
       print "end"
       break

but I got the error as if I hadn't caught the exception. What's the correct exception to catch?


问:
Bot Framework V4 - TypeError: Cannot perform 'get' on a proxy that has been revoked
I am trying to make a rest query against a database that stores knowledge articles for users and returns an array of results based on what the user has searched for. Whenever I try to search I get:

"TypeError: Cannot perform 'get' on a proxy that has been revoked"

I have tried adding it to async as shown but I still keep getting the same error. Any idea what I am doing wrong?

```<code>const Response = async (turnContext) => {
    if (turnContext.activity.value.choice === 'feedbackProvider') {
        try {
            const feedbackBody = turnContext.activity.value.feedbackBody;
            const feedbackEmail = turnContext.activity.value.feedbackEmail;
            storage.write(feedbackBody, feedbackEmail);
            await turnContext.sendActivity(`Feedback Sent`);
        } catch (err) {
            console.log('fetch failed', err);
        }
    } else if (turnContext.activity.value.choice === 'issueRaiser') {
        try {
            const bugTitle = turnContext.activity.value.issueTitle;
            const bugDesc = turnContext.activity.value.issueDescription;
            const bugEmail = turnContext.activity.value.issueEmail;
            const request = require('request');
            request({
                method: 'Post',
                uri: `<uri>issues?title=${ bugTitle }&description=${ bugDesc } ${ bugEmail }&labels=bug`,
                json: true,
                headers: {
                    'Private-Token': '<token>'
                }
            });
            turnContext.sendActivity(`Issue Raised`);
        } catch (err) {
            console.log('fetch failed', err);
        }
    } else if (turnContext.activity.value.choice === 'knowledgeBaseSearch') {
        try {
            const knowledgeBaseTopic = turnContext.activity.value.knowledgeBaseTopic;
            request({
                url: process.env.SN_KB_URL + knowledgeBaseTopic,
                json: true,
                auth: {
                    'username': process.env.Ticket_User,
                    'password': process.env.Ticket_Key
                }
            }, async (error, response, body) => {
                try {
                    var stuff = [];
                    for (var i = 0, len = body.result.length; i < len; i++) {
                        stuff.push(
                            CardFactory.heroCard(body.result[i].short_description, ['imageUrl1'], [`${ process.env.SN_KB_Resp_URl }${ body.result[i].number }`])

                        );
                    }
                    let messageWithCarouselOfCards = MessageFactory.carousel(stuff);
                    await turnContext.sendActivity(messageWithCarouselOfCards);
                } catch (err) {
                    console.log(error);
                }
            });
        } catch (err) {
            console.log('fetch failed', err);
        }
    }
};
</code>```

Full Error Message:

```<code>TypeError: Cannot perform 'get' on a proxy that has been revoked
cardMiddleware.js:35
    at Request.request [as _callback] (c:\Bots\sdk4-2\skills\cardMiddleware.js:35:45)
    at Request.self.callback (c:\Bots\sdk4-2\node_modules\request\request.js:186:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (c:\Bots\sdk4-2\node_modules\request\request.js:1163:10)
    at emitOne (events.js:116:13)
    at Request.emit (events.js:211:7)
    at IncomingMessage.<anonymous> (c:\Bots\sdk4-2\node_modules\request\request.js:1085:12)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)
</code>```

From my post on the forum I was informed that I was using a request module that did not support Promises, which I believe was causing my error. I've now began to use Axios for my request which is shown below;

```<code>try {
    return await axios.get(process.env.SN_KB_URL + knowledgeBaseTopic, {
        headers: {
          auth: {
          username: process.env.Ticket_User,
          password: process.env.Ticket_Key
        }
      }
    })
  }
</code>```

However now when I run the request I get a 401 'Unauthorised' error and I'm not sure what is wrong with my request.

答:
Check for lines that needs await inside any aync function.  I hope that azure will point usto which file or line specifically but I have not figured it out until I looked at all my functions.

Okay, so this is indeed a very cryptic error message as the github thread here suggested .

But I found that I was not await ing in this block:

    this.onMessage(async (context, next) => {.
      const didBotWelcomedUser = await this.welcomedUserProperty.get(
        context,
        "false"
      );

      if (didBotWelcomedUser === false) {
        // first time user is in chat
        await this.sendWelcomeMessage(context); `<-------- await here was missing`
      } else {
        await this.sendSuggestedAction(context); `<-------- await here was missing`
      }

      await next();
    });

    this.onMembersAdded(async (context, next) => {

      await this.sendWelcomeMessage(context);
      await next();
    });
  }```

I thought await.next() is enough.  We all gotta learn this somehow... Hope you resolve yours.

Body:
I am trying to make a rest query against a database that stores knowledge articles for users and returns an array of results based on what the user has searched for. Whenever I try to search I get:

"TypeError: Cannot perform 'get' on a proxy that has been revoked"

I have tried adding it to async as shown but I still keep getting the same error. Any idea what I am doing wrong?

const Response = async (turnContext) => {
    if (turnContext.activity.value.choice === 'feedbackProvider') {
        try {
            const feedbackBody = turnContext.activity.value.feedbackBody;
            const feedbackEmail = turnContext.activity.value.feedbackEmail;
            storage.write(feedbackBody, feedbackEmail);
            await turnContext.sendActivity(`Feedback Sent`);
        } catch (err) {
            console.log('fetch failed', err);
        }
    } else if (turnContext.activity.value.choice === 'issueRaiser') {
        try {
            const bugTitle = turnContext.activity.value.issueTitle;
            const bugDesc = turnContext.activity.value.issueDescription;
            const bugEmail = turnContext.activity.value.issueEmail;
            const request = require('request');
            request({
                method: 'Post',
                uri: `<uri>issues?title=${ bugTitle }&description=${ bugDesc } ${ bugEmail }&labels=bug`,
                json: true,
                headers: {
                    'Private-Token': '<token>'
                }
            });
            turnContext.sendActivity(`Issue Raised`);
        } catch (err) {
            console.log('fetch failed', err);
        }
    } else if (turnContext.activity.value.choice === 'knowledgeBaseSearch') {
        try {
            const knowledgeBaseTopic = turnContext.activity.value.knowledgeBaseTopic;
            request({
                url: process.env.SN_KB_URL + knowledgeBaseTopic,
                json: true,
                auth: {
                    'username': process.env.Ticket_User,
                    'password': process.env.Ticket_Key
                }
            }, async (error, response, body) => {
                try {
                    var stuff = [];
                    for (var i = 0, len = body.result.length; i < len; i++) {
                        stuff.push(
                            CardFactory.heroCard(body.result[i].short_description, ['imageUrl1'], [`${ process.env.SN_KB_Resp_URl }${ body.result[i].number }`])

                        );
                    }
                    let messageWithCarouselOfCards = MessageFactory.carousel(stuff);
                    await turnContext.sendActivity(messageWithCarouselOfCards);
                } catch (err) {
                    console.log(error);
                }
            });
        } catch (err) {
            console.log('fetch failed', err);
        }
    }
};

Full Error Message:

TypeError: Cannot perform 'get' on a proxy that has been revoked
cardMiddleware.js:35
    at Request.request [as _callback] (c:\Bots\sdk4-2\skills\cardMiddleware.js:35:45)
    at Request.self.callback (c:\Bots\sdk4-2\node_modules\request\request.js:186:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (c:\Bots\sdk4-2\node_modules\request\request.js:1163:10)
    at emitOne (events.js:116:13)
    at Request.emit (events.js:211:7)
    at IncomingMessage.<anonymous> (c:\Bots\sdk4-2\node_modules\request\request.js:1085:12)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)

From my post on the forum I was informed that I was using a request module that did not support Promises, which I believe was causing my error. I've now began to use Axios for my request which is shown below;

try {
    return await axios.get(process.env.SN_KB_URL + knowledgeBaseTopic, {
        headers: {
          auth: {
          username: process.env.Ticket_User,
          password: process.env.Ticket_Key
        }
      }
    })
  }

However now when I run the request I get a 401 'Unauthorised' error and I'm not sure what is wrong with my request.

Body:
Check for lines that needs await inside any aync function.  I hope that azure will point usto which file or line specifically but I have not figured it out until I looked at all my functions.

Okay, so this is indeed a very cryptic error message as the github thread here suggested .

But I found that I was not await ing in this block:

    this.onMessage(async (context, next) => {.
      const didBotWelcomedUser = await this.welcomedUserProperty.get(
        context,
        "false"
      );

      if (didBotWelcomedUser === false) {
        // first time user is in chat
        await this.sendWelcomeMessage(context); `<-------- await here was missing`
      } else {
        await this.sendSuggestedAction(context); `<-------- await here was missing`
      }

      await next();
    });

    this.onMembersAdded(async (context, next) => {

      await this.sendWelcomeMessage(context);
      await next();
    });
  }

I thought await.next() is enough.  We all gotta learn this somehow... Hope you resolve yours.


问:
How do I get the winnings for each cycle to accumulate?
```<code>int rounds = 0;
        do
        {
            int winnings = lottery.showWinnings(setA);
            rounds = rounds + 1;
        }
        while (rounds != weeks);
</code>```

lottery.showWinnings(setA) returns an integer value. I want the winnings value in the first cycle of the loop to be taken and added to the winnings value in the second cycle of the loop and so on until the cycle has been repeated the number of times that the integer weeks holds. Is there anyway to do that? I've tried a for loop but that has the same issue

答:
This should work :-</p>
```<code>int rounds = 0;
int winnings = 0;
        do
        {
            winnings += lottery.showWinnings(setA);
            rounds ++;
        }
        while (rounds != weeks);
</code>```

Body:
int rounds = 0;
        do
        {
            int winnings = lottery.showWinnings(setA);
            rounds = rounds + 1;
        }
        while (rounds != weeks);

lottery.showWinnings(setA) returns an integer value. I want the winnings value in the first cycle of the loop to be taken and added to the winnings value in the second cycle of the loop and so on until the cycle has been repeated the number of times that the integer weeks holds. Is there anyway to do that? I've tried a for loop but that has the same issue

Body:
This should work :-

int rounds = 0;
int winnings = 0;
        do
        {
            winnings += lottery.showWinnings(setA);
            rounds ++;
        }
        while (rounds != weeks);


问:
Cannot change class objects within vector
I'm having difficulties with understanding how to change the value of a class object which is stored in a vector. From the example below, I thought the case would be that "ferrari" would be yellow after I change the color, however it is still black.

From what I understand this has to do with that I'm making a new copy of vector each time and therefore not changing the object I want. I have read that it might help to write the vector like a reference instead like so: vector<Car> &cars;, but this gives an error "reference variable 'cars' requires an initializer" which I don't understand how to solve.

```<code>#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Car
{
public:
    string brand;
    string color;
    Car(string brand, string color)
        : brand(brand), color(color)
    {
    }
    // setter
    void setColor(string newColor)
    {
        color = newColor;
    }
};

int main()
{
    vector<Car> cars;
    cars.push_back(Car("bmw", "blue"));
    cars.push_back(Car("tesla", "red"));
    cars.push_back(Car("ferrari", "black"));

    for (Car car : cars)
    {
        if (car.brand == "ferrari")
        {
            car.setColor("yellow");
        }
    }

    for (Car car : cars)
    {
        cout << car.brand << " " << car.color << endl;
    }

    return 0;
}

</code>```

答:
In your for loop:

```<code>for (Car car : cars)
</code>```

So when it loops, it will make a copy of the cars elements, not the element itself.

Change that to

```<code>for (Car &car : cars)
</code>```

Body:
I'm having difficulties with understanding how to change the value of a class object which is stored in a vector. From the example below, I thought the case would be that "ferrari" would be yellow after I change the color, however it is still black.

From what I understand this has to do with that I'm making a new copy of vector each time and therefore not changing the object I want. I have read that it might help to write the vector like a reference instead like so: vector<Car> &cars;, but this gives an error "reference variable 'cars' requires an initializer" which I don't understand how to solve.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Car
{
public:
    string brand;
    string color;
    Car(string brand, string color)
        : brand(brand), color(color)
    {
    }
    // setter
    void setColor(string newColor)
    {
        color = newColor;
    }
};

int main()
{
    vector<Car> cars;
    cars.push_back(Car("bmw", "blue"));
    cars.push_back(Car("tesla", "red"));
    cars.push_back(Car("ferrari", "black"));

    for (Car car : cars)
    {
        if (car.brand == "ferrari")
        {
            car.setColor("yellow");
        }
    }

    for (Car car : cars)
    {
        cout << car.brand << " " << car.color << endl;
    }

    return 0;
}

Body:
In your for loop:

for (Car car : cars)

So when it loops, it will make a copy of the cars elements, not the element itself.

Change that to

for (Car &car : cars)


问:
Flutter: How can I set initial value to a textController and change it after?
I have a stepper and some TextFormFields with controller in the first step. I want to show in the TextField an initialValue and if I change the value want to set the new value to the controller and keep it on change step.
Now, I can change the value of the controller but not keep it on change step

Edit Page

class EditProfilePage extends StatefulWidget {
  final String uid;

  const EditProfilePage({Key? key, required this.uid}) : super(key: key);

  @override
  _EditProfilePageState createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  final TextEditingController _nameController = TextEditingController();

 int _index = 0;

  @override
  void initState() {
    super.initState();
    _nameController.addListener(() {
      final String text = _nameController.text;
      _nameController.value = _nameController.value.copyWith(
        text: text,
      );
    });
  }

  @override
  void dispose() {
    super.dispose();
    _nameController.dispose();
  }

  @override
  Widget build(BuildContext context) {
;
final UserProvider userProvider = Provider.of<UserProvider>(context);

_nameController.text = userProvider.getUser.name;
return Scaffold(
    ...
    body: Stepper(
        controlsBuilder: (BuildContext context, ControlsDetails details) {
          if (_index == 2) {
            return Container(
              padding: const EdgeInsets.only(right: 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () {
                      userProvider.updateName(
                          _nameController.text, userProvider.getUser.uid);
                    },
                    child: const Text('SAVE'),
                  ),
                ],
              ),
            );
          } else {
            return Row();
          }
        },
        currentStep: _index,
        onStepCancel: () {
          _index > 0 ? setState(() => _index -= 1) : null;
        },
        onStepContinue: () {
          _index < 2 ? setState(() => _index += 1) : null;
        },
        onStepTapped: (int index) {
          setState(() {
            _index = index;
          });
        },
        steps: <Step>[
          Step(
            title: const Text('Personal Info'),
            content: Container(
                padding: const EdgeInsets.all(5),
                child: Column(children: [
                  TextFormField(
                    controller: _nameController,
                    decoration: InputDecoration(
                      labelText: 'Name',
                      labelStyle: const TextStyle(color: Colors.black54),
                      border: const OutlineInputBorder(),
                      focusedBorder: OutlineInputBorder(
                        borderSide: Divider.createBorderSide(context),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: Divider.createBorderSide(context),
                      ),
                      filled: true,
                      contentPadding: const EdgeInsets.all(8),
                    ),
                  ),
                  const SizedBox(
                    height: 24,
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
```
<p><strong>UserProvider</strong></p>
```class UserProvider with ChangeNotifier {
  User? _user;
  final AuthMethods _authMethods = AuthMethods();

  User get getUser => _user!;

  Future<void> refreshUser() async {
    User user = await _authMethods.getUserDetails();
    _user = user;
    notifyListeners();
  }

  }
```

答:
You can use

TextEditingController.fromValue(TextEditingValue(text: "initial value"));
```
<p>or</p>
<pre class="lang-dart prettyprint-override"><code>TextEditingController(text: "initial value")
</code>```

Update

using nullable TextEditingController and getting context using WidgetsBinding.instance?.addPostFrameCallback inside initState to read provider.

class UserProvider with ChangeNotifier {
  String userName = "intial UserName";
  Future<void> setUser(String name) async {
    userName = name;
    notifyListeners();
  }
}

class EditProfilePage extends StatefulWidget {
  final String uid;

  const EditProfilePage({Key? key, required this.uid}) : super(key: key);

  @override
  _EditProfilePageState createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  TextEditingController? _nameController;

  int _index = 0;

  @override
  void initState() {
    super.initState(); // to have context
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      final provider = Provider.of<UserProvider>(context, listen: false);

      debugPrint("Got Name : ${provider.userName}");
      _nameController = TextEditingController(text: provider.userName);
      _nameController?.addListener(() {
        final text = _nameController == null ? "" : _nameController!.text;
        provider.setUser(text);
      });
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    _nameController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Consumer<UserProvider>(
            builder: (context, value, child) {
              return Text(value.userName);
            },
          ),
          TextFormField(
            controller: _nameController,
            decoration: InputDecoration(
              labelText: 'Name',
              labelStyle: const TextStyle(color: Colors.black54),
              border: const OutlineInputBorder(),
              focusedBorder: OutlineInputBorder(
                borderSide: Divider.createBorderSide(context),
              ),
              enabledBorder: OutlineInputBorder(
                borderSide: Divider.createBorderSide(context),
              ),
              filled: true,
              contentPadding: const EdgeInsets.all(8),
            ),
          ),
          const SizedBox(
            height: 24,
          ),
        ],
      ),
    );
  }
}
```

More about TextEditingController.

Body:
I have a stepper and some TextFormFields with controller in the first step. I want to show in the TextField an initialValue and if I change the value want to set the new value to the controller and keep it on change step.
Now, I can change the value of the controller but not keep it on change step

Edit Page

class EditProfilePage extends StatefulWidget {
  final String uid;

  const EditProfilePage({Key? key, required this.uid}) : super(key: key);

  @override
  _EditProfilePageState createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  final TextEditingController _nameController = TextEditingController();

 int _index = 0;

  @override
  void initState() {
    super.initState();
    _nameController.addListener(() {
      final String text = _nameController.text;
      _nameController.value = _nameController.value.copyWith(
        text: text,
      );
    });
  }

  @override
  void dispose() {
    super.dispose();
    _nameController.dispose();
  }

  @override
  Widget build(BuildContext context) {
;
final UserProvider userProvider = Provider.of<UserProvider>(context);

_nameController.text = userProvider.getUser.name;
return Scaffold(
    ...
    body: Stepper(
        controlsBuilder: (BuildContext context, ControlsDetails details) {
          if (_index == 2) {
            return Container(
              padding: const EdgeInsets.only(right: 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () {
                      userProvider.updateName(
                          _nameController.text, userProvider.getUser.uid);
                    },
                    child: const Text('SAVE'),
                  ),
                ],
              ),
            );
          } else {
            return Row();
          }
        },
        currentStep: _index,
        onStepCancel: () {
          _index > 0 ? setState(() => _index -= 1) : null;
        },
        onStepContinue: () {
          _index < 2 ? setState(() => _index += 1) : null;
        },
        onStepTapped: (int index) {
          setState(() {
            _index = index;
          });
        },
        steps: <Step>[
          Step(
            title: const Text('Personal Info'),
            content: Container(
                padding: const EdgeInsets.all(5),
                child: Column(children: [
                  TextFormField(
                    controller: _nameController,
                    decoration: InputDecoration(
                      labelText: 'Name',
                      labelStyle: const TextStyle(color: Colors.black54),
                      border: const OutlineInputBorder(),
                      focusedBorder: OutlineInputBorder(
                        borderSide: Divider.createBorderSide(context),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: Divider.createBorderSide(context),
                      ),
                      filled: true,
                      contentPadding: const EdgeInsets.all(8),
                    ),
                  ),
                  const SizedBox(
                    height: 24,
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

UserProvider

class UserProvider with ChangeNotifier {
  User? _user;
  final AuthMethods _authMethods = AuthMethods();

  User get getUser => _user!;

  Future<void> refreshUser() async {
    User user = await _authMethods.getUserDetails();
    _user = user;
    notifyListeners();
  }

  }

Body:
You can use

TextEditingController.fromValue(TextEditingValue(text: "initial value"));

or

TextEditingController(text: "initial value")

Update

using nullable TextEditingController and getting context using WidgetsBinding.instance?.addPostFrameCallback inside initState to read provider.

class UserProvider with ChangeNotifier {
  String userName = "intial UserName";
  Future<void> setUser(String name) async {
    userName = name;
    notifyListeners();
  }
}

class EditProfilePage extends StatefulWidget {
  final String uid;

  const EditProfilePage({Key? key, required this.uid}) : super(key: key);

  @override
  _EditProfilePageState createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  TextEditingController? _nameController;

  int _index = 0;

  @override
  void initState() {
    super.initState(); // to have context
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      final provider = Provider.of<UserProvider>(context, listen: false);

      debugPrint("Got Name : ${provider.userName}");
      _nameController = TextEditingController(text: provider.userName);
      _nameController?.addListener(() {
        final text = _nameController == null ? "" : _nameController!.text;
        provider.setUser(text);
      });
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    _nameController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Consumer<UserProvider>(
            builder: (context, value, child) {
              return Text(value.userName);
            },
          ),
          TextFormField(
            controller: _nameController,
            decoration: InputDecoration(
              labelText: 'Name',
              labelStyle: const TextStyle(color: Colors.black54),
              border: const OutlineInputBorder(),
              focusedBorder: OutlineInputBorder(
                borderSide: Divider.createBorderSide(context),
              ),
              enabledBorder: OutlineInputBorder(
                borderSide: Divider.createBorderSide(context),
              ),
              filled: true,
              contentPadding: const EdgeInsets.all(8),
            ),
          ),
          const SizedBox(
            height: 24,
          ),
        ],
      ),
    );
  }
}

More about TextEditingController.


答:
In for (Car car : cars), car is a copy of the corresponding vector element. Changing the copy doesn't affect the original.

Use for (Car &car : cars) if you want to modify the elements. Even if you only want to read (print) them, use for (const Car &car : cars) to avoid the unnecessary copy that you're currently making.

Also note that your constructor and setter are suboptimal. They need some std::moves:

```<code>class Car
{
public:
    string brand;
    string color;
    Car(string brand, string color)
        : brand(std::move(brand)), color(std::move(color))
    {
    }
    // setter
    void setColor(string newColor)
    {
        color = std::move(newColor);
    }
};
</code>```

Title: Cannot change class objects within vector

Body:
In for (Car car : cars), car is a copy of the corresponding vector element. Changing the copy doesn't affect the original.

Use for (Car &car : cars) if you want to modify the elements. Even if you only want to read (print) them, use for (const Car &car : cars) to avoid the unnecessary copy that you're currently making.

Also note that your constructor and setter are suboptimal. They need some std::moves:

class Car
{
public:
    string brand;
    string color;
    Car(string brand, string color)
        : brand(std::move(brand)), color(std::move(color))
    {
    }
    // setter
    void setColor(string newColor)
    {
        color = std::move(newColor);
    }
};


问:
Attach event listener through javascript to radio button
I have several radio buttons with the same name. Like this:

```<code><form name="formA">
<input type="radio" name="myradio" value="A"/>
<input type="radio" name="myradio" value="B"/>
<input type="radio" name="myradio" value="C"/>
<input type="radio" name="myradio" value="D"/>
</form>
</code>```

Now I have to add event listener through javascript to all the radio buttons. If the below pseudocode is wrong, then please tell me how to do it-

```<code>var radios = document.forms["formA"].elements["myradio"];
  for(radio in radios) {
    radio.onclick = function() {
        alert(radio.value);
    }
}
</code>```

答:
Try this :</p>
```<code>var radioButtonSection = document.getElementsByName('eazi_auto_loan_option');

for (var i = 0; i < radioButtonSection.length; i++) {
        radioButtonSection[i].onclick = function() {
            console.log(this.value);
        }
    }
</code>```

Body:
I have several radio buttons with the same name. Like this:

<form name="formA">
<input type="radio" name="myradio" value="A"/>
<input type="radio" name="myradio" value="B"/>
<input type="radio" name="myradio" value="C"/>
<input type="radio" name="myradio" value="D"/>
</form>

Now I have to add event listener through javascript to all the radio buttons. If the below pseudocode is wrong, then please tell me how to do it-

var radios = document.forms["formA"].elements["myradio"];
  for(radio in radios) {
    radio.onclick = function() {
        alert(radio.value);
    }
}

Body:
Try this :

var radioButtonSection = document.getElementsByName('eazi_auto_loan_option');

for (var i = 0; i < radioButtonSection.length; i++) {
        radioButtonSection[i].onclick = function() {
            console.log(this.value);
        }
    }


答:
To set the initial value to a TextEditingController

```<code> final _nameController = TextEditingController(text: 'initial value');
</code>```

And to update the value:

```<code> _nameController.text='new value';
</code>```

Title: Flutter: How can I set initial value to a textController and change it after?

Body:
To set the initial value to a TextEditingController

 final _nameController = TextEditingController(text: 'initial value');

And to update the value:

 _nameController.text='new value';


问:
Time complexity of functions Omega, O, and Theta
```<code>void Q2a(int N)
{
    int j, k;
    for (j = 1; j <= N; j *= 3)
        for (k = 1; k <= N; k *= 2)
            printf(" SC1007 \n");
}
</code>```

Can someone help to explain the time complexity? I understand the simple concepts and definition of O, omega and theta. As well as the scenario where the for loop just runs for n-1 times (int i = 1; i<n; i++). But when conditions such as this comes out, I'm totally lost. Online videos always seem to write random equations to start things off. I know which means upper, lower and average case etc and how they come about. But when I look at algorithms, how do I start ? This question asks for the big theta of the function. The solution to this is :

inner loop:

2^(K−1) ≤ N < 2^K

(K − 1) ≤ log2(N) < K

K ≤ log2 N + 1 < K + 1

K = ⌊log2 N + 1⌋ = ⌊log2 N⌋ + 1

Where does the first line come from?

答:
Where does the first line come from?

The first line is “2^(K−1) ≤ N < 2^K ”. In the inner loop, we have for (k = 1; k <= N; k *= 2). The values k takes on in this loop are 1, 2, 4, 8, 16, 32,…, namely 2K in iteration number K (starting with 0).

If k <= N is true, the loop continues. Once it is false, the loop stops. If the loop stops before iteration K, then 2K ≤ N is false, so N < 2K. And, since the loop did not stop on the previous iteration, K−1, it must be that 2K−1 ≤ N is true (supposing that the loop executed at least one iteration, so that there is a previous iteration).

Therefore 2K−1 ≤ N < 2K.

Body:
void Q2a(int N)
{
    int j, k;
    for (j = 1; j <= N; j *= 3)
        for (k = 1; k <= N; k *= 2)
            printf(" SC1007 \n");
}

Can someone help to explain the time complexity? I understand the simple concepts and definition of O, omega and theta. As well as the scenario where the for loop just runs for n-1 times (int i = 1; i<n; i++). But when conditions such as this comes out, I'm totally lost. Online videos always seem to write random equations to start things off. I know which means upper, lower and average case etc and how they come about. But when I look at algorithms, how do I start ? This question asks for the big theta of the function. The solution to this is :

inner loop:

2^(K−1) ≤ N < 2^K

(K − 1) ≤ log2(N) < K

K ≤ log2 N + 1 < K + 1

K = ⌊log2 N + 1⌋ = ⌊log2 N⌋ + 1

Where does the first line come from?


问:
Find all permutations code Problem (Java)
I wrote this code to find all possible permutations of some numbers. But i dosen't want to use one digit twice:

123,132,213 are OK, but it produces numbers like 122, 121 etc.

What am i doing wrong?

```<code>import java.util.HashSet;

public class main {

public static void main(String[] args) {

    HashSet<Integer> l = new HashSet<Integer>();
    for(int i=0;i<=3;i++){
        l.add(i);
    }
    perm(l,3,new StringBuffer());

}

 static void perm(HashSet<Integer> in, int depth,StringBuffer out){
    if(depth==0){
        System.out.println(out);
        return;
    }

    int len = in.size();
    HashSet<Integer> tmp = in;

    for(int i=0;i<len;i++){
        out.append(in.toArray()[i]);
        tmp.remove(i);

        perm(tmp,depth-1,out);

        out.deleteCharAt(out.length()-1);
        tmp.add(i);
    }
}
}
</code>```

答: It looks like Autoboxing is getting you.  When you call the remove with 'i', My guess is that 'i' has been boxed to a different object and is thus not found in your HashSet.</p>

Body:
I wrote this code to find all possible permutations of some numbers. But i dosen't want to use one digit twice:

123,132,213 are OK, but it produces numbers like 122, 121 etc.

What am i doing wrong?

import java.util.HashSet;

public class main {

public static void main(String[] args) {

    HashSet<Integer> l = new HashSet<Integer>();
    for(int i=0;i<=3;i++){
        l.add(i);
    }
    perm(l,3,new StringBuffer());

}

 static void perm(HashSet<Integer> in, int depth,StringBuffer out){
    if(depth==0){
        System.out.println(out);
        return;
    }

    int len = in.size();
    HashSet<Integer> tmp = in;

    for(int i=0;i<len;i++){
        out.append(in.toArray()[i]);
        tmp.remove(i);

        perm(tmp,depth-1,out);

        out.deleteCharAt(out.length()-1);
        tmp.add(i);
    }
}
}