问:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]
I am trying to do a mini react project and am using external API. I am getting this weird error. Before I was getting error when doing any type of import, but then I added type: "module" in package.json, so now instead I get completely different type of error.

```<code>Error:
node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".tmp" for /Users/rokas/Projects/quiz-website/src/node_7c47523b50d8c.tmp
    at new NodeError (node:internal/errors:393:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:121:38)
    at defaultLoad (node:internal/modules/esm/load:81:20)
    at nextLoad (node:internal/modules/esm/loader:163:28)
    at ESMLoader.load (node:internal/modules/esm/loader:605:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
    at new ModuleJob (node:internal/modules/esm/module_job:63:26)
    at #createModuleJob (node:internal/modules/esm/loader:480:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Node.js v18.12.1

</code>```

Thoughts?

Title: TypeError [ERR_UNKNOWN_FILE_EXTENSION]

Body:
I am trying to do a mini react project and am using external API. I am getting this weird error. Before I was getting error when doing any type of import, but then I added type: "module" in package.json, so now instead I get completely different type of error.

Error:
node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".tmp" for /Users/rokas/Projects/quiz-website/src/node_7c47523b50d8c.tmp
    at new NodeError (node:internal/errors:393:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:121:38)
    at defaultLoad (node:internal/modules/esm/load:81:20)
    at nextLoad (node:internal/modules/esm/loader:163:28)
    at ESMLoader.load (node:internal/modules/esm/loader:605:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
    at new ModuleJob (node:internal/modules/esm/module_job:63:26)
    at #createModuleJob (node:internal/modules/esm/loader:480:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Node.js v18.12.1

Thoughts?


来源: stackexchange

问:
Need explanation on a Powershell syntax
I'm working on a script and while searching for something on the internet, I found these lines in PowerShell:

```<code>Function Add-Script ([string] $script, [bool] $reboot = $false) {
    $script:scripts += ,@($script, $reboot)
}
</code>```

I tried to search in the Microsoft documentation but I'm not finding any concept related to the $script:scripts part and I don't understand why there is a comma after the +=.

The $scripts object is created with a global scope and we can use it if by calling '$scripts'. It will contain an array of array and will become bigger if we call this function many times.

So is there anyone who understand the this last line of code and maybe send the documentation related to it ? It would be really nice.

Thanks !

ContentLicense: CC BY-SA 4.0

Title: Need explanation on a Powershell syntax

Body:
I'm working on a script and while searching for something on the internet, I found these lines in PowerShell:

Function Add-Script ([string] $script, [bool] $reboot = $false) {
    $script:scripts += ,@($script, $reboot)
}

I tried to search in the Microsoft documentation but I'm not finding any concept related to the $script:scripts part and I don't understand why there is a comma after the +=.

The $scripts object is created with a global scope and we can use it if by calling '$scripts'. It will contain an array of array and will become bigger if we call this function many times.

So is there anyone who understand the this last line of code and maybe send the documentation related to it ? It would be really nice.

Thanks !


问:
Audio Detection for Python
I wanted to make a python program which detects system audio. Just like open-cv match template, is there any module which can detect a certain "characteristic" of an image (or audio for my case) and we can set a threshold value, and if the threshold value is crossed, we can pass a function. Basically, I am making this program for fishing in Minecraft. There is a mod which "pings" me or makes a sound whenever a fish is stuck in the fishing rod. I wanted to input and save the sound in the program (which can be easily done using modules) and see if the audio passes a certain threshold value in order to carry out the process of right clicking the mouse (which can be done by pyautogui module). I want this program to run infinitely until I press a key (which can be done using keyboard.is_pressed("ctrl") ).

I tried googling for a solution but due to my near to no knowledge of sound processing, I was unable to come to a solution. A logic for doing the infinite loop thing was to change the input setting in windows to system sounds and then recording and saving an audio wave file every five seconds and as soon as the file is saved, the program "tries" (try and except block) to delete its previous file in order to save storage and processing the current sound in the same loop.

Following is a sample code I made using open-cv using image detection:
(NOTE: You don't necessarily need to look into this code to solve my problem, this is just for an idea and I want a similar code but with audio instead of image detection)

```<code>import cv2 as cv
import os
import pyautogui
import time
from PIL import ImageGrab
import keyboard

path_1 = r"C:\Users\Aditya\AppData\Roaming\.minecraft\screenshots\2022-12-21_11.37.40 - Copy.png"   #path_1 is the path of the "template" i.e. the image that I am trying to detect on the screen

threshold = 50672740  #this number was obtained after experimentally testing

path = "C:\\Users\\Aditya\\Documents\\fishing_pics\\"
#path variable is the path where the screenshots are being saved

n = len(os.listdir(path))+1

while keyboard.is_pressed("ctrl")==False:

    filename = path+str(n)+".png"
    prev2_filename = path+str(n-2)+".png"

    n+=1
    screenshot = ImageGrab.grab()
    screenshot.save(filename,"PNG")

    try:
            os.remove(prev2_filename)
    except:
        print (prev2_filename+" doesn't exists")

    haystack_img = cv.imread(filename,0)
    needle_img = cv.imread(path_1,0)

    haystack_img = cv.cvtColor(haystack_img,cv.COLOR_BGR2GRAY)
    needle_img = cv.cvtColor(needle_img,cv.COLOR_BGR2GRAY)

    result = cv.matchTemplate(needle_img,haystack_img,cv.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

    if max_val>=threshold:
        pyautogui.click(button='right')
        time.sleep(1)
        pyautogui.click(button='right')

    time.sleep(0.1)

for file_name in os.listdir(path):
    file = path + file_name
    os.remove(file)
</code>```

#this is used to remove any file left in the folder where screenshots are saved in order to save strorage

LOGIC >>> Ignore variable "n" because its just used to name the file as 1.png,2.png,etc...
I am capturing and saving a picture of my screen using ImageGrab from Pillow (PIL) and then comparing it to the template image in order to get a threshold value and if the threshold value is greater than a certain value (set by me) then it performs a function

Title: Audio Detection for Python

Body:
I wanted to make a python program which detects system audio. Just like open-cv match template, is there any module which can detect a certain "characteristic" of an image (or audio for my case) and we can set a threshold value, and if the threshold value is crossed, we can pass a function. Basically, I am making this program for fishing in Minecraft. There is a mod which "pings" me or makes a sound whenever a fish is stuck in the fishing rod. I wanted to input and save the sound in the program (which can be easily done using modules) and see if the audio passes a certain threshold value in order to carry out the process of right clicking the mouse (which can be done by pyautogui module). I want this program to run infinitely until I press a key (which can be done using keyboard.is_pressed("ctrl") ).

I tried googling for a solution but due to my near to no knowledge of sound processing, I was unable to come to a solution. A logic for doing the infinite loop thing was to change the input setting in windows to system sounds and then recording and saving an audio wave file every five seconds and as soon as the file is saved, the program "tries" (try and except block) to delete its previous file in order to save storage and processing the current sound in the same loop.

Following is a sample code I made using open-cv using image detection:
(NOTE: You don't necessarily need to look into this code to solve my problem, this is just for an idea and I want a similar code but with audio instead of image detection)

import cv2 as cv
import os
import pyautogui
import time
from PIL import ImageGrab
import keyboard

path_1 = r"C:\Users\Aditya\AppData\Roaming\.minecraft\screenshots\2022-12-21_11.37.40 - Copy.png"   #path_1 is the path of the "template" i.e. the image that I am trying to detect on the screen

threshold = 50672740  #this number was obtained after experimentally testing

path = "C:\\Users\\Aditya\\Documents\\fishing_pics\\"
#path variable is the path where the screenshots are being saved

n = len(os.listdir(path))+1

while keyboard.is_pressed("ctrl")==False:

    filename = path+str(n)+".png"
    prev2_filename = path+str(n-2)+".png"

    n+=1
    screenshot = ImageGrab.grab()
    screenshot.save(filename,"PNG")

    try:
            os.remove(prev2_filename)
    except:
        print (prev2_filename+" doesn't exists")

    haystack_img = cv.imread(filename,0)
    needle_img = cv.imread(path_1,0)

    haystack_img = cv.cvtColor(haystack_img,cv.COLOR_BGR2GRAY)
    needle_img = cv.cvtColor(needle_img,cv.COLOR_BGR2GRAY)

    result = cv.matchTemplate(needle_img,haystack_img,cv.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

    if max_val>=threshold:
        pyautogui.click(button='right')
        time.sleep(1)
        pyautogui.click(button='right')

    time.sleep(0.1)

for file_name in os.listdir(path):
    file = path + file_name
    os.remove(file)

#this is used to remove any file left in the folder where screenshots are saved in order to save strorage

LOGIC >>> Ignore variable "n" because its just used to name the file as 1.png,2.png,etc...
I am capturing and saving a picture of my screen using ImageGrab from Pillow (PIL) and then comparing it to the template image in order to get a threshold value and if the threshold value is greater than a certain value (set by me) then it performs a function


问:
Fit concatenated modules throws error regarding the input
I have 3 models that are pre-trained. I want to concat the models and then add a fully connected network on top:

```<code>output = concatenate(
            [
                resnet.layers[-2].output, # model1
                cnn2.layers[-2].output, #model2
                cnn.layers[-2].output #model3
            ], axis=-1)

fc = Dense(units=4096, activation="relu")(output)
fc = Dense(units=4096, activation="relu")(fc)
logits = Dense(3, activation="sigmoid")(fc)
model = Model(inputs=[resnet.inputs, cnn2.inputs, cnn.inputs], outputs=logits)

model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["acc"])

epochs = 10
x_train_second, x_val_second, y_train_second, y_val_second = train_test_split(x_train, y_train, test_size=0.15)
history = model.fit(
    datagen.flow([x_train_second, x_train_second, x_train_second], y=y_train_second, batch_size=64),
    epochs=epochs, steps_per_epoch=x_train_second.shape[0] // 64,
)
</code>```

I get the error:

```<code>ValueError: Layer "model_68" expects 3 input(s), but it received 2 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, None, None, None) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, None, None, None) dtype=float32>]
</code>```

Which is a bit confusing since I am passing 3 inputs to x in model.fit(). Even if I insert 4 or 5 inputs there I also get the same error, which suggests that something is way off...

Update: So I think it is because of datagen.flow(), because if I use:

```<code>model.fit([x_train_second, x_train_second, x_train_second], y=y_train_second, batch_size=64,
    epochs=epochs
)
</code>```

It is working.So the question is to use ImageDataGenerator.flow() for merged module

Body:
I have 3 models that are pre-trained. I want to concat the models and then add a fully connected network on top:

output = concatenate(
            [
                resnet.layers[-2].output, # model1
                cnn2.layers[-2].output, #model2
                cnn.layers[-2].output #model3
            ], axis=-1)

fc = Dense(units=4096, activation="relu")(output)
fc = Dense(units=4096, activation="relu")(fc)
logits = Dense(3, activation="sigmoid")(fc)
model = Model(inputs=[resnet.inputs, cnn2.inputs, cnn.inputs], outputs=logits)

model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["acc"])

epochs = 10
x_train_second, x_val_second, y_train_second, y_val_second = train_test_split(x_train, y_train, test_size=0.15)
history = model.fit(
    datagen.flow([x_train_second, x_train_second, x_train_second], y=y_train_second, batch_size=64),
    epochs=epochs, steps_per_epoch=x_train_second.shape[0] // 64,
)

I get the error:

ValueError: Layer "model_68" expects 3 input(s), but it received 2 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, None, None, None) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, None, None, None) dtype=float32>]

Which is a bit confusing since I am passing 3 inputs to x in model.fit(). Even if I insert 4 or 5 inputs there I also get the same error, which suggests that something is way off...

Update: So I think it is because of datagen.flow(), because if I use:

model.fit([x_train_second, x_train_second, x_train_second], y=y_train_second, batch_size=64,
    epochs=epochs
)

It is working.So the question is to use ImageDataGenerator.flow() for merged module


问:
Assembly: Which Value when using 'Load Immediate(li)'
Helloo,

I'm learning MIPS Assembly righ know at University and I'm bit confused.
When using the command 'li' for example in li $v0, ()... when do I use which value for the brackets? I saw now 1s and 4s.

Please Help

I tried using different values but I dont understand it.


问:
How can I get access to a fragment of a Navigation Drawer Project?
I am trying to refresh a fragment with the code given in this answer:

```<code>// Reload current fragment
Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
</code>```

However, I don't know what is the tag of my fragment, which is a Navigation Drawer Fragment.

As "Your_Fragment_Tag" I have tried to use the id of content_main.xml, "nav_host_fragment_content_main":

```<code><fragment
    android:id="@+id/nav_host_fragment_content_main"
    android:name="androidx.navigation.fragment.NavHostFragment"
    .... />
</code>```

And the id of the fragment in mobile_navigation.xml, "nav_settings":

```<code><fragment
    android:id="@+id/nav_settings"
    android:name="com.geology_quiz_and_guide.mineralogy.ui.settings.SettingsFragment"
    android:label="@string/menu_settings"
    tools:layout="@layout/fragment_settings" />
</code>```

Both produce null object reference error in the line of the detach ft.detach(frg);

How can I access to my fragment dynamically on my Navigation Drawer Project?

Body:
I am trying to refresh a fragment with the code given in this answer:

// Reload current fragment
Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();

However, I don't know what is the tag of my fragment, which is a Navigation Drawer Fragment.

As "Your_Fragment_Tag" I have tried to use the id of content_main.xml, "nav_host_fragment_content_main":

<fragment
    android:id="@+id/nav_host_fragment_content_main"
    android:name="androidx.navigation.fragment.NavHostFragment"
    .... />

And the id of the fragment in mobile_navigation.xml, "nav_settings":

<fragment
    android:id="@+id/nav_settings"
    android:name="com.geology_quiz_and_guide.mineralogy.ui.settings.SettingsFragment"
    android:label="@string/menu_settings"
    tools:layout="@layout/fragment_settings" />

Both produce null object reference error in the line of the detach ft.detach(frg);

How can I access to my fragment dynamically on my Navigation Drawer Project?


问:
Error in setting up a thir party log-in with Google Oauth2 in a PERN app
I was wondering how a third party log in with a Google Oauth2 strategy could be implemented, I have checked all the docs online but I seem to have issues in implementing it in my app and for some reason when I try to perform a post request to the endpoint it says that it is unauthorized even through I must have checked my credentials many times and they look fine to me. See code below:

--server--

app.post('/google', passport.authenticate('googleToken', { session: true }));

app.post('/google/callback', passport.authenticate('google'), function (req, res) {
// Return user back to client
res.send(req.user);
});

--Passport--

```<code>// Google strategy

passport.use('googleToken', new GooglePlusTokenStrategy({
    clientID: "265635454782-8tkv7on6vmqrvotjndr1h5qjcl374ir4.apps.googleusercontent.com",
    clientSecret: "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",
    callbackURL: "http://localhost:5000/google/callback"
}, async (accessToken, refreshToken, profile, done) => {
    // Will have to query the database //
    customer_email = profile.emails[0].value;
    pool.query(`select * from customers where email='${customer_email}'`, (err, result) => {

        if (err) { throw err }

        // If the customer is in the database
        if (result.rows.length > 0) {

            const customer = result.rows[0];
            return done(null, customer, accessToken)
        }
        // If the customer is not in the database
        else {

            return done(null, false);
        }
    });

}));
</code>```

--Login component/ Client--

```<code>/////////////   Google Login   //////////////

async function googleLogin() {
    const url = 'http://localhost:5000/google';
    //let object =
    let result = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': 'http://localhost:5000'
        },
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'include',
        // body: JSON.stringify(object)
    })

    // result = result.json();
    console.log(result)
    return result;

}
</code>```

I do not know whether I am missing something or If there are any mistakes that I could not spot.

Any help would be greatly appreciated.

Body:
I was wondering how a third party log in with a Google Oauth2 strategy could be implemented, I have checked all the docs online but I seem to have issues in implementing it in my app and for some reason when I try to perform a post request to the endpoint it says that it is unauthorized even through I must have checked my credentials many times and they look fine to me. See code below:

--server--

app.post('/google', passport.authenticate('googleToken', { session: true }));

app.post('/google/callback', passport.authenticate('google'), function (req, res) {
// Return user back to client
res.send(req.user);
});

--Passport--

// Google strategy

passport.use('googleToken', new GooglePlusTokenStrategy({
    clientID: "265635454782-8tkv7on6vmqrvotjndr1h5qjcl374ir4.apps.googleusercontent.com",
    clientSecret: "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",
    callbackURL: "http://localhost:5000/google/callback"
}, async (accessToken, refreshToken, profile, done) => {
    // Will have to query the database //
    customer_email = profile.emails[0].value;
    pool.query(`select * from customers where email='${customer_email}'`, (err, result) => {

        if (err) { throw err }

        // If the customer is in the database
        if (result.rows.length > 0) {

            const customer = result.rows[0];
            return done(null, customer, accessToken)
        }
        // If the customer is not in the database
        else {

            return done(null, false);
        }
    });

}));

--Login component/ Client--

/////////////   Google Login   //////////////

async function googleLogin() {
    const url = 'http://localhost:5000/google';
    //let object =
    let result = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': 'http://localhost:5000'
        },
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'include',
        // body: JSON.stringify(object)
    })

    // result = result.json();
    console.log(result)
    return result;

}

I do not know whether I am missing something or If there are any mistakes that I could not spot.

Any help would be greatly appreciated.


问:
Get indent size/tab width config from prettier
Is there a way to get the configuration of the current directory, like the indent size and tab width from prettier? I would imagine something like prettier --get-config tab-width . and getting 2 since that seems to be the default.

I'm trying to solve my vim being set up with 4 spaces when I'm running prettier with no config and with no .editorconfig leaving my formatting to use 2 spaces while my indents are 4 spaces.


问:
How does ionic animation works with angular?
I'm playing with angular animation in a simple ionic 6 app.

the animation is very simple (taken from the Angular doc)

```<code>animations: [
trigger('openClose', [

  state('open', style({
    opacity: 1,
  })),
  state('closed', style({
    opacity: 0,
  })),
  transition('closed => open', [
    animate('2s')
  ]),
]),
</code>```

then in my html code I have used the application:

```<code><ion-card class="test" [@openClose]="loaded ? 'open' : 'closed'">
<div *ngIf="!loaded" style="text-align: center ;">
  <ion-spinner name="lines" color="primary"></ion-spinner>
</div>
<div *ngIf="loaded"  >
  <ion-card-header >
  </ion-card-header>
</div>
</code>```

and yes... it works...

But if I put the animation on the div inside ion-card, well... it doesnt works anymore.

```<code><ion-card class="test" >
<div *ngIf="!loaded" style="text-align: center ;">
  <ion-spinner name="lines" color="primary"></ion-spinner>
</div>
<div *ngIf="loaded"  [@openClose]="loaded ? 'open' : 'closed'">
  <ion-card-header >
  </ion-card-header>
</div>
</code>```

So I'm confused... Why the animation works only in the ion-card element?
And... What is the best practice to animate content in ionic?
I saw css animations, ionic animations and angular animations.... a lot of way to do the same thing...

Thanks for all responses

Body:
I'm playing with angular animation in a simple ionic 6 app.

the animation is very simple (taken from the Angular doc)

animations: [
trigger('openClose', [

  state('open', style({
    opacity: 1,
  })),
  state('closed', style({
    opacity: 0,
  })),
  transition('closed => open', [
    animate('2s')
  ]),
]),

then in my html code I have used the application:

<ion-card class="test" [@openClose]="loaded ? 'open' : 'closed'">

  <ion-spinner name="lines" color="primary"></ion-spinner>

  <ion-card-header >
  </ion-card-header>

and yes... it works...

But if I put the animation on the div inside ion-card, well... it doesnt works anymore.

<ion-card class="test" >

  <ion-spinner name="lines" color="primary"></ion-spinner>

  <ion-card-header >
  </ion-card-header>

So I'm confused... Why the animation works only in the ion-card element?
And... What is the best practice to animate content in ionic?
I saw css animations, ionic animations and angular animations.... a lot of way to do the same thing...

Thanks for all responses


问:
Random Graph Generation but with weights
Hey so I'm doing a project where cities will be symbolized by vertices and streets with edges. I found this very cool erdos_renyi_graph function but I need some features that I couldn't find so far:

every edge should have their (also random) weight

I need to be sure that every vertice have at least 2 edges.

Can I do this with Erdős–Rényi Generator or maybe there is some other function I could use?

I was trying to use "er_np" function to adresse my 1st issue but I believe thats not really what I'm looking for. I was also checking fast_gnp_random_graph() and gnp_random_graph() function but those don't have weights parameters neither.


问:
GoRouter: Incorrect URL after pop

What I noticed is that the query params in URL still there not remove when I pop back to previews screen.

Here is how the URLs look on web:

Expected results:
In the Address bar of the browser, it should: #/

Actual results:
In the Address bar of the browser, it shows: #/?sort=asc

using: go_route: ^6.0.0

```<code>import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';

final Map<String, dynamic> _families = {
  "f1": {
    "name": "Doe",
    "people": {
      "p1": {"name": "Jane", "age": 23},
      "p2": {"name": "John", "age": 6}
    }
  },
  "f2": {
    "name": "Wong",
    "people": {
      "p1": {"name": "June", "age": 51},
      "p2": {"name": "Xin", "age": 44}
    }
  }
};

void main() => runApp(App());

/// The main app.
class App extends StatelessWidget {
  /// Creates an [App].
  App({Key? key}) : super(key: key);

  /// The title of the app.
  static const String title = 'GoRouter Example: Query Parameters';

  // add the login info into the tree as app state that can change over time
  @override
  Widget build(BuildContext context) => MaterialApp.router(
        routerConfig: _router,
        title: title,
        debugShowCheckedModeBanner: false,
      );

  late final GoRouter _router = GoRouter(
    initialLocation: '/',
    redirect: (context, state) {
      print('Subloc: ${state.subloc}');
    },
    debugLogDiagnostics: true,
    routerNeglect: true,
    routes: <GoRoute>[
      GoRoute(
        path: '/',
        builder: (BuildContext context, GoRouterState state) {
          return const HomeScreen();
        },
        routes: <GoRoute>[
          GoRoute(
              name: 'family',
              path: 'family/:fid',
              builder: (BuildContext context, GoRouterState state) {
                return FamilyScreen(
                  fid: state.params['fid']!,
                  asc: state.queryParams['sort'] == 'asc',
                );
              }),
        ],
      ),
    ],
  );
}

/// The home screen that shows a list of families.
class HomeScreen extends StatelessWidget {
  /// Creates a [HomeScreen].
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(App.title),
      ),
      body: ListView(
        children: <Widget>[
          for (final String fid in _families.keys)
            ListTile(
              title: Text(_families[fid]['name']),
              onTap: () {
                context.goNamed(
                  'family',
                  params: {'fid': fid},
                  queryParams: {'sort': 'asc'},
                );
              },
            )
        ],
      ),
    );
  }
}

/// The screen that shows a list of persons in a family.
class FamilyScreen extends StatelessWidget {
  /// Creates a [FamilyScreen].
  const FamilyScreen({required this.fid, required this.asc, Key? key})
      : super(key: key);

  /// The family to display.
  final String fid;

  /// Whether to sort the name in ascending order.
  final bool asc;

  @override
  Widget build(BuildContext context) {
    final Map<String, String> newQueries;
    final List<String> names = _families[fid]['people']
        .values
        .map<String>((dynamic p) => p['name'] as String)
        .toList();
    names.sort();
    if (asc) {
      newQueries = const <String, String>{'sort': 'desc'};
    } else {
      newQueries = const <String, String>{'sort': 'asc'};
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(_families[fid]['name']),
        leading: BackButton(
          onPressed: () {
            GoRouter.of(context).pop();
          },
        ),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              context.goNamed('family',
                  params: <String, String>{'fid': fid},
                  queryParams: newQueries);
            },
            tooltip: 'sort ascending or descending',
            icon: const Icon(Icons.sort),
          )
        ],
      ),
      body: ListView(
        children: <Widget>[
          for (final String name in asc ? names : names.reversed)
            ListTile(
              title: Text(name),
            ),
        ],
      ),
    );
  }
}

</code>```

Title: GoRouter: Incorrect URL after pop

Body:
What I noticed is that the query params in URL still there not remove when I pop back to previews screen.

Here is how the URLs look on web:

Expected results:
In the Address bar of the browser, it should: #/

Actual results:
In the Address bar of the browser, it shows: #/?sort=asc

using: go_route: ^6.0.0

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';

final Map<String, dynamic> _families = {
  "f1": {
    "name": "Doe",
    "people": {
      "p1": {"name": "Jane", "age": 23},
      "p2": {"name": "John", "age": 6}
    }
  },
  "f2": {
    "name": "Wong",
    "people": {
      "p1": {"name": "June", "age": 51},
      "p2": {"name": "Xin", "age": 44}
    }
  }
};

void main() => runApp(App());

/// The main app.
class App extends StatelessWidget {
  /// Creates an [App].
  App({Key? key}) : super(key: key);

  /// The title of the app.
  static const String title = 'GoRouter Example: Query Parameters';

  // add the login info into the tree as app state that can change over time
  @override
  Widget build(BuildContext context) => MaterialApp.router(
        routerConfig: _router,
        title: title,
        debugShowCheckedModeBanner: false,
      );

  late final GoRouter _router = GoRouter(
    initialLocation: '/',
    redirect: (context, state) {
      print('Subloc: ${state.subloc}');
    },
    debugLogDiagnostics: true,
    routerNeglect: true,
    routes: <GoRoute>[
      GoRoute(
        path: '/',
        builder: (BuildContext context, GoRouterState state) {
          return const HomeScreen();
        },
        routes: <GoRoute>[
          GoRoute(
              name: 'family',
              path: 'family/:fid',
              builder: (BuildContext context, GoRouterState state) {
                return FamilyScreen(
                  fid: state.params['fid']!,
                  asc: state.queryParams['sort'] == 'asc',
                );
              }),
        ],
      ),
    ],
  );
}

/// The home screen that shows a list of families.
class HomeScreen extends StatelessWidget {
  /// Creates a [HomeScreen].
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(App.title),
      ),
      body: ListView(
        children: <Widget>[
          for (final String fid in _families.keys)
            ListTile(
              title: Text(_families[fid]['name']),
              onTap: () {
                context.goNamed(
                  'family',
                  params: {'fid': fid},
                  queryParams: {'sort': 'asc'},
                );
              },
            )
        ],
      ),
    );
  }
}

/// The screen that shows a list of persons in a family.
class FamilyScreen extends StatelessWidget {
  /// Creates a [FamilyScreen].
  const FamilyScreen({required this.fid, required this.asc, Key? key})
      : super(key: key);

  /// The family to display.
  final String fid;

  /// Whether to sort the name in ascending order.
  final bool asc;

  @override
  Widget build(BuildContext context) {
    final Map<String, String> newQueries;
    final List<String> names = _families[fid]['people']
        .values
        .map<String>((dynamic p) => p['name'] as String)
        .toList();
    names.sort();
    if (asc) {
      newQueries = const <String, String>{'sort': 'desc'};
    } else {
      newQueries = const <String, String>{'sort': 'asc'};
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(_families[fid]['name']),
        leading: BackButton(
          onPressed: () {
            GoRouter.of(context).pop();
          },
        ),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              context.goNamed('family',
                  params: <String, String>{'fid': fid},
                  queryParams: newQueries);
            },
            tooltip: 'sort ascending or descending',
            icon: const Icon(Icons.sort),
          )
        ],
      ),
      body: ListView(
        children: <Widget>[
          for (final String name in asc ? names : names.reversed)
            ListTile(
              title: Text(name),
            ),
        ],
      ),
    );
  }
}


问:
How to set surface+x%primary colors in xml layout
In official Material Design 3 resources do not specify how to use these (surface+x%primary) colors in xml layouts.

I tried using these colors in code:

```<code>protected void onCreate(Bundle savedInstanceState) {
   ...
   getWindow().setNavigationBarColor(SurfaceColors.SURFACE_2.getColor(this));
   ...
}
</code>```

Body:
In official Material Design 3 resources do not specify how to use these (surface+x%primary) colors in xml layouts.

I tried using these colors in code:

protected void onCreate(Bundle savedInstanceState) {
   ...
   getWindow().setNavigationBarColor(SurfaceColors.SURFACE_2.getColor(this));
   ...
}


问:
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions
```<code>
training = []
bos_cikti = [0] * len(siniflar)

for belge in belgeler:
    bag = []
    kelime_patternleri = belge[0]
    kelime_patternleri = [ayristirici.lemmatize(kelime.lower()) for kelime in kelime_patternleri]
    for kelime in kelimeler:
        bag.append(1) if kelime in kelime_patternleri else bag.append(0)

    cikti_sira = list(bos_cikti)
    cikti_sira[siniflar.index(belge[1])] = 1
    training.append([bag, cikti_sira])

random.shuffle(training)
training = np.array(training)   ------> This line Wrong

</code>```

It shows the error on this line

```<code>

train_x = list(training[:, 0])
train_y = list(training[:, 1])

#Neural Network (YSA)
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(64, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation="softmax"))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])

model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save("chatbot_model.model")
print("Done")

</code>```

Super confused. When I run my code, I keep on getting this error:

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

```<code>Traceback (most recent call last):
  File "C:\Users\Elvan Ersöz\Desktop\Python\Bitirme Projesi\training.py", line 55, in <module>
    training = np.array(training)
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (20, 2) + inhomogeneous part.

</code>```

I am creating a project using neural networks and natural language processing. While I'm writing my model
from line 55 I get the following error: ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (20, 2) + inhomogeneous part.

enter image description here

Body:
training = []
bos_cikti = [0] * len(siniflar)

for belge in belgeler:
    bag = []
    kelime_patternleri = belge[0]
    kelime_patternleri = [ayristirici.lemmatize(kelime.lower()) for kelime in kelime_patternleri]
    for kelime in kelimeler:
        bag.append(1) if kelime in kelime_patternleri else bag.append(0)

    cikti_sira = list(bos_cikti)
    cikti_sira[siniflar.index(belge[1])] = 1
    training.append([bag, cikti_sira])

random.shuffle(training)
training = np.array(training)   ------> This line Wrong

It shows the error on this line

train_x = list(training[:, 0])
train_y = list(training[:, 1])

#Neural Network (YSA)
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(64, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation="softmax"))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])

model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save("chatbot_model.model")
print("Done")

Super confused. When I run my code, I keep on getting this error:

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

Traceback (most recent call last):
  File "C:\Users\Elvan Ersöz\Desktop\Python\Bitirme Projesi\training.py", line 55, in <module>
    training = np.array(training)
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (20, 2) + inhomogeneous part.

I am creating a project using neural networks and natural language processing. While I'm writing my model
from line 55 I get the following error: ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (20, 2) + inhomogeneous part.

enter image description here


问:
BufferOverflowException in java threads
Receiving an exception "BufferOverflowException" while running sikuli script via threads. The same script works properly without thread object. I have no clue what causes the bufferoverflowexception. Please guide.

Sample Code:-

```<code>import org.sikuli.script.*;  // Library import

public class Sikuli {

    private Screen screen = new Screen();

    private Pattern getPattern(String imagePath) {
        return new Pattern(imagePath);
    }

    public void click(String imagePath) throws FindFailed, InterruptedException {
         screen.click(getPattern(imagePath));
    }

    public void sendKeys(String value) {
        screen.type(value);
    }

import Sukuli // Custom sikuli class import

public class foo {

     Sikuli sk = new Sikuli();

    public void test() {
        Thread t1 = new Thread(() -> {
               sk.click(new Pattern("imagePath"));
               sk.type("fooboo");
            });
            t1.start();
        }
}
</code>```

From Sikuli Library Methods which are being referred by my class methods:-

```<code> public int type(String text) {
        try {
            return this.keyin((Object)null, text, 0);
        } catch (FindFailed var3) {
            return 0;
        }
    }

private <PFRML> int keyin(PFRML target, String text, int modifiers) throws FindFailed {
        if (target != null && 0 == this.click(target, 0)) {
            return 0;
        } else {
            Debug profiler = Debug.startTimer("Region.type", new Object[0]);
            if (text != null && !"".equals(text)) {
                String showText = "";

                for(int i = 0; i < text.length(); ++i) {
                    showText = showText + Key.toJavaKeyCodeText(text.charAt(i));
                }

                String modText = "";
                String modWindows = null;
                if ((modifiers & 4) != 0) {
                    modifiers -= 4;
                    modifiers |= 4;
                    log(3, "Key.WIN as modifier", new Object[0]);
                    modWindows = "Windows";
                }

                if (modifiers != 0) {
                    modText = String.format("( %s ) ", KeyEvent.getKeyModifiersText(modifiers));
                    if (modWindows != null) {
                        modText = modText.replace("Meta", modWindows);
                    }
                }

                Debug.action("%s TYPE \"%s\"", new Object[]{modText, showText});
                log(3, "%s TYPE \"%s\"", new Object[]{modText, showText});
                profiler.lap("before getting Robot");
                IRobot r = this.getRobotForRegion();
                int pause = 20 + (Settings.TypeDelay > 1.0 ? 1000 : (int)(Settings.TypeDelay * 1000.0));
                Settings.TypeDelay = 0.0;
                profiler.lap("before typing");
                r.typeStarts();

                for(int i = 0; i < text.length(); ++i) {
                    r.pressModifiers(modifiers);
                    r.typeChar(text.charAt(i), KeyMode.PRESS_RELEASE);
                    r.releaseModifiers(modifiers);
                    r.delay(pause);
                }

                r.typeEnds();
                profiler.lap("after typing, before waitForIdle");
                r.waitForIdle();
                profiler.end();
                return 1;
            } else {
                return 0;
            }
        }
    }

</code>```

Trace logs:-

```<code>[log] CLICK on L[1517,53]@S(0) (555 msec)[log]  TYPE "fooboo"Exception in thread "Thread-4" java.nio.BufferOverflowException
        at java.nio.Buffer.nextPutIndex(Buffer.java:521)
        at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:169)
        at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encodeString(AbstractStreamEncoder.java:127)
        at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encodeStringData(AbstractStreamEncoder.java:171)
        at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encode(AbstractStreamEncoder.java:157)
        at org.apache.maven.surefire.booter.spi.EventChannelEncoder.encodeMessage(EventChannelEncoder.java:398)
        at org.apache.maven.surefire.booter.spi.EventChannelEncoder.setOutErr(EventChannelEncoder.java:188)
        at org.apache.maven.surefire.booter.spi.EventChannelEncoder.testOutput(EventChannelEncoder.java:183)
        at org.apache.maven.surefire.api.booter.ForkingRunListener.writeTestOutput(ForkingRunListener.java:113)
        at org.apache.maven.surefire.api.booter.ForkingRunListener.writeTestOutput(ForkingRunListener.java:44)
        at org.apache.maven.surefire.common.junit4.JUnit4RunListener.writeTestOutput(JUnit4RunListener.java:235)
        at org.apache.maven.surefire.api.report.ConsoleOutputCapture$ForwardingPrintStream.println(ConsoleOutputCapture.java:144)
        at org.sikuli.basics.Debug.log(Debug.java:881)
        at org.sikuli.basics.Debug.action(Debug.java:645)
        at org.sikuli.script.Region.keyin(Region.java:4613)
        at org.sikuli.script.Region.type(Region.java:4493)
        at Sikuli.sendKeys(Sikuli.java:87)
</code>```

Title: BufferOverflowException in java threads

Body:
Receiving an exception "BufferOverflowException" while running sikuli script via threads. The same script works properly without thread object. I have no clue what causes the bufferoverflowexception. Please guide.

Sample Code:-

import org.sikuli.script.*;  // Library import

public class Sikuli {

    private Screen screen = new Screen();

    private Pattern getPattern(String imagePath) {
        return new Pattern(imagePath);
    }

    public void click(String imagePath) throws FindFailed, InterruptedException {
         screen.click(getPattern(imagePath));
    }

    public void sendKeys(String value) {
        screen.type(value);
    }

import Sukuli // Custom sikuli class import

public class foo {

     Sikuli sk = new Sikuli();

    public void test() {
        Thread t1 = new Thread(() -> {
               sk.click(new Pattern("imagePath"));
               sk.type("fooboo");
            });
            t1.start();
        }
}

From Sikuli Library Methods which are being referred by my class methods:-

 public int type(String text) {
        try {
            return this.keyin((Object)null, text, 0);
        } catch (FindFailed var3) {
            return 0;
        }
    }

private <PFRML> int keyin(PFRML target, String text, int modifiers) throws FindFailed {
        if (target != null && 0 == this.click(target, 0)) {
            return 0;
        } else {
            Debug profiler = Debug.startTimer("Region.type", new Object[0]);
            if (text != null && !"".equals(text)) {
                String showText = "";

                for(int i = 0; i < text.length(); ++i) {
                    showText = showText + Key.toJavaKeyCodeText(text.charAt(i));
                }

                String modText = "";
                String modWindows = null;
                if ((modifiers & 4) != 0) {
                    modifiers -= 4;
                    modifiers |= 4;
                    log(3, "Key.WIN as modifier", new Object[0]);
                    modWindows = "Windows";
                }

                if (modifiers != 0) {
                    modText = String.format("( %s ) ", KeyEvent.getKeyModifiersText(modifiers));
                    if (modWindows != null) {
                        modText = modText.replace("Meta", modWindows);
                    }
                }

                Debug.action("%s TYPE \"%s\"", new Object[]{modText, showText});
                log(3, "%s TYPE \"%s\"", new Object[]{modText, showText});
                profiler.lap("before getting Robot");
                IRobot r = this.getRobotForRegion();
                int pause = 20 + (Settings.TypeDelay > 1.0 ? 1000 : (int)(Settings.TypeDelay * 1000.0));
                Settings.TypeDelay = 0.0;
                profiler.lap("before typing");
                r.typeStarts();

                for(int i = 0; i < text.length(); ++i) {
                    r.pressModifiers(modifiers);
                    r.typeChar(text.charAt(i), KeyMode.PRESS_RELEASE);
                    r.releaseModifiers(modifiers);
                    r.delay(pause);
                }

                r.typeEnds();
                profiler.lap("after typing, before waitForIdle");
                r.waitForIdle();
                profiler.end();
                return 1;
            } else {
                return 0;
            }
        }
    }

Trace logs:-

[log] CLICK on L[1517,53]@S(0) (555 msec)[log]  TYPE "fooboo"Exception in thread "Thread-4" java.nio.BufferOverflowException
        at java.nio.Buffer.nextPutIndex(Buffer.java:521)
        at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:169)
        at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encodeString(AbstractStreamEncoder.java:127)
        at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encodeStringData(AbstractStreamEncoder.java:171)
        at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encode(AbstractStreamEncoder.java:157)
        at org.apache.maven.surefire.booter.spi.EventChannelEncoder.encodeMessage(EventChannelEncoder.java:398)
        at org.apache.maven.surefire.booter.spi.EventChannelEncoder.setOutErr(EventChannelEncoder.java:188)
        at org.apache.maven.surefire.booter.spi.EventChannelEncoder.testOutput(EventChannelEncoder.java:183)
        at org.apache.maven.surefire.api.booter.ForkingRunListener.writeTestOutput(ForkingRunListener.java:113)
        at org.apache.maven.surefire.api.booter.ForkingRunListener.writeTestOutput(ForkingRunListener.java:44)
        at org.apache.maven.surefire.common.junit4.JUnit4RunListener.writeTestOutput(JUnit4RunListener.java:235)
        at org.apache.maven.surefire.api.report.ConsoleOutputCapture$ForwardingPrintStream.println(ConsoleOutputCapture.java:144)
        at org.sikuli.basics.Debug.log(Debug.java:881)
        at org.sikuli.basics.Debug.action(Debug.java:645)
        at org.sikuli.script.Region.keyin(Region.java:4613)
        at org.sikuli.script.Region.type(Region.java:4493)
        at Sikuli.sendKeys(Sikuli.java:87)


问:
How do I convert DataFrame based workflow to DataSet based workflow?
I have a workflow based on DataFrame. I prepare the data, and than I run model.train in the loop.

Here's what I do:

```<code>x,y=load_and_prepare_data()

for i in range(...):
   ....
   model.train(x,y,....)
   ...

</code>```

Normally, this works just fine, but now I have a huge dataset. My process works es expected, except that after running for a few cycles this runs out of GPU memory. From what I understand, this happens because model.train allocates new GPU memory each time I pass x and y into it.

One way to fix the issue is to set TF_GPU_ALLOCATOR=cuda_malloc_async, however, this is bad for performance.

Another way I came up with is to use ft.data.Dataset, which seems to be able to allocate the GPU memory directly so that it doesn't have to be done in the loop. I don't want to convert the rest of my workflow from DataFrame to DataSet, instead I would like to create dataset just before the loop and use it inside the loop

I can convert DataFrame to dataset with tf.data.Dataset.from_tensor_slices(dict(df)).
I have done this for x and y, and model.train complains than when using datasets, I need to use single argument. So I have tried zipping the y and y datasets with work=tf.data.Dataset.zip((x_work,y_work)), where x_work and y_work are dataframes converted to Dataset. model.train refuses to accept this as argument either

How do I get from x and y daraframes to dataset that can be used for model training?

Body:
I have a workflow based on DataFrame. I prepare the data, and than I run model.train in the loop.

Here's what I do:

x,y=load_and_prepare_data()

for i in range(...):
   ....
   model.train(x,y,....)
   ...

Normally, this works just fine, but now I have a huge dataset. My process works es expected, except that after running for a few cycles this runs out of GPU memory. From what I understand, this happens because model.train allocates new GPU memory each time I pass x and y into it.

One way to fix the issue is to set TF_GPU_ALLOCATOR=cuda_malloc_async, however, this is bad for performance.

Another way I came up with is to use ft.data.Dataset, which seems to be able to allocate the GPU memory directly so that it doesn't have to be done in the loop. I don't want to convert the rest of my workflow from DataFrame to DataSet, instead I would like to create dataset just before the loop and use it inside the loop

I can convert DataFrame to dataset with tf.data.Dataset.from_tensor_slices(dict(df)).
I have done this for x and y, and model.train complains than when using datasets, I need to use single argument. So I have tried zipping the y and y datasets with work=tf.data.Dataset.zip((x_work,y_work)), where x_work and y_work are dataframes converted to Dataset. model.train refuses to accept this as argument either

How do I get from x and y daraframes to dataset that can be used for model training?