问:
How to create different commands as alias with oclif?
Oclif can create multiple commands like these:

```<code>mycli do1
mycli do2
mycli do3
</code>```

I want to get alias for the above commands:

```<code>myclido1 # alias for 'mycli do1'
myclido2
myclido3
</code>```

Is possible for oclif to create such alias? Or only using a script to create the alias outside oclif?

Body:
Oclif can create multiple commands like these:

mycli do1
mycli do2
mycli do3

I want to get alias for the above commands:

myclido1 # alias for 'mycli do1'
myclido2
myclido3

Is possible for oclif to create such alias? Or only using a script to create the alias outside oclif?


来源: stackexchange

问:
Firebase hosting nextjs app causes one route not to call getServerSideProps
I am currently hosting my nextjs app on vercel, but have decided to migrate to firebase hosting. I followed the firebase guide for hosting an SSR nextjs app using their platform (https://firebase.google.com/docs/hosting/nextjs). After deploying the website, everything seemed fine, except for the fact that on the /account route, the getServerSideProps method was returning an empty array; when run locally it returns a list of items the user can control.

Below is the code being run on the account page:

```<code>export const getServerSideProps = async (context) => {
  const { res } = context;
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=0, stale-while-revalidate=0'
  );

  const cookie = await decodeAuthCookie(context, true);
  if (cookie.uid === '') {
    return {
      redirect: {
        destination: '/',
        permanent: true
      }
    };
  }

  const data = await getReviewsForUser(cookie.uid);

  return {
    props: {
      data
    }
  }
};
</code>```

I am unsure whether there is some limit to the size of the firebase functions that have to be generated to handle executing this method.

ContentLicense: CC BY-SA 4.0

Body:
I am currently hosting my nextjs app on vercel, but have decided to migrate to firebase hosting. I followed the firebase guide for hosting an SSR nextjs app using their platform (https://firebase.google.com/docs/hosting/nextjs). After deploying the website, everything seemed fine, except for the fact that on the /account route, the getServerSideProps method was returning an empty array; when run locally it returns a list of items the user can control.

Below is the code being run on the account page:

export const getServerSideProps = async (context) => {
  const { res } = context;
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=0, stale-while-revalidate=0'
  );

  const cookie = await decodeAuthCookie(context, true);
  if (cookie.uid === '') {
    return {
      redirect: {
        destination: '/',
        permanent: true
      }
    };
  }

  const data = await getReviewsForUser(cookie.uid);

  return {
    props: {
      data
    }
  }
};

I am unsure whether there is some limit to the size of the firebase functions that have to be generated to handle executing this method.


问:
Selenium: Driver ignores custom profile when headless mode is enabled
I have the following code:

```<code>    options = webdriver.ChromeOptions()
    options.add_argument('log-level=3')
    options.add_experimental_option('excludeSwitches', ['enable-logging'])
    options.add_argument("--user-data-dir=C:\\users\\eirik\\AppData\\Local\\Google\\Chrome\\User Data")
    options.add_argument("--profile-directory=Bot")
    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(executable_path="C:\\Program Files\\chromedriver.exe", options=options)
</code>```

This code functions properly, however, If I were to add options.add_argument("--headless") the browser will work as expected with the exception of the custom profile being completely ignored. So browser presets, such as logins and extensions are missing.

I'd be glad for any help!

Kind Regards

-Eirik

Body:
I have the following code:

    options = webdriver.ChromeOptions()
    options.add_argument('log-level=3')
    options.add_experimental_option('excludeSwitches', ['enable-logging'])
    options.add_argument("--user-data-dir=C:\\users\\eirik\\AppData\\Local\\Google\\Chrome\\User Data")
    options.add_argument("--profile-directory=Bot")
    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(executable_path="C:\\Program Files\\chromedriver.exe", options=options)

This code functions properly, however, If I were to add options.add_argument("--headless") the browser will work as expected with the exception of the custom profile being completely ignored. So browser presets, such as logins and extensions are missing.

I'd be glad for any help!

Kind Regards

-Eirik


问:
Hiding an html Element based on Session ID
So I have these html elements on my navbar that I would like to exchange which is visible based on if a user is logged in or not, and I had created some middleware that was going to read the session id and then change the classlists added to each element, but it doesn't exactly work because the middleware script itself isn't called in the html document(at least, that is my assumption, please correct me if I am wrong.)

`

```<code><ul class="navbar-nav navbar-right">
                    <li class="nav-item" id="navLogin">
                        <a href="./login.html" class="nav-link">
                        Login
                        </a>
                    </li>
                    <li class="nav-item nav-hidden" id="navAccount">
                        <a href="#" class="nav-link">
                            Account
                        </a>
                    </li>
                </ul>
</code>```

```<code>export async function checkLoggedIn(req, res, next) {
    const users = (await Database.get('users')) || [];

    for (let i = 0; i < users.length; i++) {
        const user = users[i];
        if (user.sessionID == req.session) {

            document.addEventListener("DOMContentLoaded", () => {
                const navLogin = document.querySelector("#navlogin");
                const navAccount = document.querySelector("#navAccount");

                navLogin.classList.add("formHidden");
                navAccount.classList.remove("formHidden");
            });
            next();
        }
        next();
    }
}
</code>```

`

Can I fix this error by just including the file I create the middleware function on in every html page where I would call the function so that it can properly read 'document'?

I am assuming I can't so heres the next questions I have - my idea for solving this would be to have the middleware just send a variable to the html page that I would then read in js script to add/remove the class from the elements class list, but I'm not sure how to get that working. I know, or at least think that I know, that if I add

app.get('/', (req,res) =>{ res.render({variableName: variableValue}); });
to the server I can send variables to the page? But I'm not sure how I would use that to read it in another js file. Any suggestions on how I can solve this?

tldr - trying to hide an html element by reading the session id, using express, nodejs.

Body:
So I have these html elements on my navbar that I would like to exchange which is visible based on if a user is logged in or not, and I had created some middleware that was going to read the session id and then change the classlists added to each element, but it doesn't exactly work because the middleware script itself isn't called in the html document(at least, that is my assumption, please correct me if I am wrong.)

`

                        Login

                            Account

export async function checkLoggedIn(req, res, next) {
    const users = (await Database.get('users')) || [];

    for (let i = 0; i < users.length; i++) {
        const user = users[i];
        if (user.sessionID == req.session) {

            document.addEventListener("DOMContentLoaded", () => {
                const navLogin = document.querySelector("#navlogin");
                const navAccount = document.querySelector("#navAccount");

                navLogin.classList.add("formHidden");
                navAccount.classList.remove("formHidden");
            });
            next();
        }
        next();
    }
}

`

Can I fix this error by just including the file I create the middleware function on in every html page where I would call the function so that it can properly read 'document'?

I am assuming I can't so heres the next questions I have - my idea for solving this would be to have the middleware just send a variable to the html page that I would then read in js script to add/remove the class from the elements class list, but I'm not sure how to get that working. I know, or at least think that I know, that if I add

app.get('/', (req,res) =>{ res.render({variableName: variableValue}); });
to the server I can send variables to the page? But I'm not sure how I would use that to read it in another js file. Any suggestions on how I can solve this?

tldr - trying to hide an html element by reading the session id, using express, nodejs.


问:
Adding string to object emailaddresses
I'm trying to add a string to the emailaddresses objects of an Exchange mailbox.
But when I add the string, it doesn't show anything.

```<code>    Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,PrimarySmtpAddress, @{Name="EmailAddresses";Expression={($_.EmailAddresses | Where-Object {$_ -clike "*smtp*"} | ForEach-Object {$_ -join '_OLD'})}} | where-object {($_.primarysmtpaddress -like "juan@contoso.com")}
</code>```

but when I do a replace operation, it shows me the emailaddresses replaced correctly. Why doesn't it add the string but replace it?

```<code>    Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,PrimarySmtpAddress, @{Name="EmailAddresses";Expression={($_.EmailAddresses | Where-Object {$_ -clike "*smtp*"} | ForEach-Object {$_ -replace "smtp:","Remp:"}) -join "OLD"}} | where-object {($_.primarysmtpaddress -like "juan@contoso.com")}
</code>```

I have also tried with the concatenation operator, but I get the same result.

thanks in advance.

Title: Adding string to object emailaddresses

Body:
I'm trying to add a string to the emailaddresses objects of an Exchange mailbox.
But when I add the string, it doesn't show anything.

    Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,PrimarySmtpAddress, @{Name="EmailAddresses";Expression={($_.EmailAddresses | Where-Object {$_ -clike "*smtp*"} | ForEach-Object {$_ -join '_OLD'})}} | where-object {($_.primarysmtpaddress -like "juan@contoso.com")}

but when I do a replace operation, it shows me the emailaddresses replaced correctly. Why doesn't it add the string but replace it?

    Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,PrimarySmtpAddress, @{Name="EmailAddresses";Expression={($_.EmailAddresses | Where-Object {$_ -clike "*smtp*"} | ForEach-Object {$_ -replace "smtp:","Remp:"}) -join "OLD"}} | where-object {($_.primarysmtpaddress -like "juan@contoso.com")}

I have also tried with the concatenation operator, but I get the same result.

thanks in advance.


问:
RiverPod StateNotifierProvider causing causing "setState() or markNeedsBuild() called during build"
In my app I am trying to a notifications indicator in the app bar. To do this I am using RiverPod's StateNotifierProvider and followed their documentation for v2 to set it up.

Here is my code for this notifier:

```<code>class NotificationNotifier extends StateNotifier<List<UserNotification>> {
  NotificationNotifier() : super([]);

  List<UserNotification> get getState => state;

  Future<List<UserNotification>> fetchUserNotifications(uid) async {
    state = [];
    try {
      final res = await http.get(Uri.parse("${Environment().config.baseApiUrl}/users/$uid/notifications"));
      final data = jsonDecode(res.body);
      List<UserNotification> retrievedNotifications = [];
      for (var i = 0; i < data["notifications"].length; i++) {
        UserNotification tmpNotifications = UserNotification.fromJson(data["notifications"][i]);
        retrievedNotifications.add(tmpNotifications);
      }
      state = [...state, ...retrievedNotifications];

      print("fetchUserNotifications:state: $state");

      return state;
    } catch (err) {
      throw Exception("Unable to fetch user notifications: $err");
    }
  }

  Future<int> onClickNotification(UserNotification notification) async {
    print("UserRepositoryNotifier:onClickNotification");

    for (var n = 0; n < state.length; n++) {
      if (state[n].notificationId == notification.notificationId) {
        try {
          final response = await http.patch(
            Uri.parse("${Environment().config.baseApiUrl}/notifications/${state[n].notificationId}"),
          );

          return response.statusCode;
        } catch (err) {
          throw Exception("Unable to fetch user frieds: $err");
        }
      }
    }

    return 1;
  }
}
</code>```

To keep the icon in the app bar updated I need to call fetchUserNotifications, which I've tried to do in initState, didChangeDependencies, and build. However, since it sets the state property with state = [...state, ...retrievedNotifications]; it triggers a rebuild which causes Flutter to complain with this error:

```<code>Unhandled Exception: setState() or markNeedsBuild() called during build.
</code>```

I'm not sure how to fix this since I think I need to set the state property for this to work. Or maybe I'm misunderstanding how this all comes together?

Body:
In my app I am trying to a notifications indicator in the app bar. To do this I am using RiverPod's StateNotifierProvider and followed their documentation for v2 to set it up.

Here is my code for this notifier:

class NotificationNotifier extends StateNotifier<List<UserNotification>> {
  NotificationNotifier() : super([]);

  List<UserNotification> get getState => state;

  Future<List<UserNotification>> fetchUserNotifications(uid) async {
    state = [];
    try {
      final res = await http.get(Uri.parse("${Environment().config.baseApiUrl}/users/$uid/notifications"));
      final data = jsonDecode(res.body);
      List<UserNotification> retrievedNotifications = [];
      for (var i = 0; i < data["notifications"].length; i++) {
        UserNotification tmpNotifications = UserNotification.fromJson(data["notifications"][i]);
        retrievedNotifications.add(tmpNotifications);
      }
      state = [...state, ...retrievedNotifications];

      print("fetchUserNotifications:state: $state");

      return state;
    } catch (err) {
      throw Exception("Unable to fetch user notifications: $err");
    }
  }

  Future<int> onClickNotification(UserNotification notification) async {
    print("UserRepositoryNotifier:onClickNotification");

    for (var n = 0; n < state.length; n++) {
      if (state[n].notificationId == notification.notificationId) {
        try {
          final response = await http.patch(
            Uri.parse("${Environment().config.baseApiUrl}/notifications/${state[n].notificationId}"),
          );

          return response.statusCode;
        } catch (err) {
          throw Exception("Unable to fetch user frieds: $err");
        }
      }
    }

    return 1;
  }
}

To keep the icon in the app bar updated I need to call fetchUserNotifications, which I've tried to do in initState, didChangeDependencies, and build. However, since it sets the state property with state = [...state, ...retrievedNotifications]; it triggers a rebuild which causes Flutter to complain with this error:

Unhandled Exception: setState() or markNeedsBuild() called during build.

I'm not sure how to fix this since I think I need to set the state property for this to work. Or maybe I'm misunderstanding how this all comes together?


问:
How to manage Workspace settings for a folder but open the project individually
I got the following problem for which I can’t find any solution.

I want to have multiple folders for each language I write.

When I open a project inside the folder I want that it only has the Plugins I selected for the (language) directory workspace and not all the other ones.

I can’t find any for solution for it where I only have opened one project and not like the whole folder.


问:
Selenium tests not running in Selenium hub configuration with Kubernetes
I have configured my Selenium Hub with 2 Chrome nodes in Selenium 4.
When I run the command
minikube service selenium-hub --url
I get the URLs like http://127.0.0.1:58317 and I am able to see the hub-node configuration up and running correctly.
I wrote a simple java code to test this configuration. However, when I run my run it fails.
My code is -

```<code>    ChromeOptions chromeOptions = new ChromeOptions();

    chromeOptions.addArguments("--headless",
            "--disable-gpu",
            "--window-size=1920,1200",
            "--ignore-certificate-errors",
            "--disable-extensions",
            "--no-sandbox",
            "--disable-dev-shm-usage",
            "--allow-insecure-localhost",
            "allow-running-insecure-content");

    WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:58317/wd/hub"), chromeOptions);

    System.out.println("******************** STARTED TEST EXECUTION ********************************");
    driver.manage().window().maximize();
    driver.get("https://www.google.com/");
    driver.close();
</code>```

When I run the test, I am getting this error -

```<code>INFO: Using OpenTelemetry for tracing
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: Could not start a new session. Could not start a new session. Error while creating session with the driver service. Stopping driver service: Could not start a new session. Response code 500. Message: unknown error: Chrome failed to start: crashed.
  (chrome not reachable)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'selenium-node-chrome-78784d568c-mqlc7', ip: '172.17.0.2', os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.49-linuxkit', java.version: '11.0.11'
Driver info: driver.version: unknown
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'selenium-node-chrome-78784d568c-mqlc7', ip: '172.17.0.2', os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.49-linuxkit', java.version: '11.0.11'
Driver info: driver.version: unknown
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'selenium-hub-66f9f7d979-wqslh', ip: '172.17.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.49-linuxkit', java.version: '11.0.11'
Driver info: driver.version: unknown
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'UM01416', ip: '2a02:1210:3edc:4a00:e5da:1807:9574:1abc%en0', os.name: 'Mac OS X', os.arch: 'aarch64', os.version: '12.6.1', java.version: '11.0.17'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
</code>```

I am attaching an image of my Selenium Hub configuration.

Body:
I have configured my Selenium Hub with 2 Chrome nodes in Selenium 4.
When I run the command
minikube service selenium-hub --url
I get the URLs like http://127.0.0.1:58317 and I am able to see the hub-node configuration up and running correctly.
I wrote a simple java code to test this configuration. However, when I run my run it fails.
My code is -

    ChromeOptions chromeOptions = new ChromeOptions();

    chromeOptions.addArguments("--headless",
            "--disable-gpu",
            "--window-size=1920,1200",
            "--ignore-certificate-errors",
            "--disable-extensions",
            "--no-sandbox",
            "--disable-dev-shm-usage",
            "--allow-insecure-localhost",
            "allow-running-insecure-content");

    WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:58317/wd/hub"), chromeOptions);

    System.out.println("******************** STARTED TEST EXECUTION ********************************");
    driver.manage().window().maximize();
    driver.get("https://www.google.com/");
    driver.close();

When I run the test, I am getting this error -

INFO: Using OpenTelemetry for tracing
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: Could not start a new session. Could not start a new session. Error while creating session with the driver service. Stopping driver service: Could not start a new session. Response code 500. Message: unknown error: Chrome failed to start: crashed.
  (chrome not reachable)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'selenium-node-chrome-78784d568c-mqlc7', ip: '172.17.0.2', os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.49-linuxkit', java.version: '11.0.11'
Driver info: driver.version: unknown
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'selenium-node-chrome-78784d568c-mqlc7', ip: '172.17.0.2', os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.49-linuxkit', java.version: '11.0.11'
Driver info: driver.version: unknown
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'selenium-hub-66f9f7d979-wqslh', ip: '172.17.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.49-linuxkit', java.version: '11.0.11'
Driver info: driver.version: unknown
Build info: version: '4.0.0', revision: '3a21814679'
System info: host: 'UM01416', ip: '2a02:1210:3edc:4a00:e5da:1807:9574:1abc%en0', os.name: 'Mac OS X', os.arch: 'aarch64', os.version: '12.6.1', java.version: '11.0.17'
Driver info: org.openqa.selenium.remote.RemoteWebDriver

I am attaching an image of my Selenium Hub configuration.


问:
How do I run the Google Cloud Functions example project KotlinHelloWorld.kt in IntelliJ on Windows 11?
I am developing a Kotlin backend that is going to run in Google Cloud Functions. I am unsing the example code that Google has given, however I do not know how I can run the code on my local Windows 11 machine with IntelliJ.

There is no option to run the file. Even when I go to "Run/Debug Configurations" I cannot select the KotlinHelloWorld.kt file as my main class to run.

Below is the sample code given from https://cloud.google.com/functions/docs/concepts/jvm-langs.

src/main/kotlin/functions/KotlinHelloWorld.kt

```<code>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package functions

// [START functions_helloworld_get]
import com.google.cloud.functions.HttpFunction
import com.google.cloud.functions.HttpRequest
import com.google.cloud.functions.HttpResponse
import java.io.IOException
import java.util.logging.Logger

class HelloWorld : HttpFunction {
    // Simple function to return "Hello World"
    @Throws(IOException::class)
    override fun service(request: HttpRequest, response: HttpResponse) {
        response.writer.write("Hello World!")
    }
}
// [END functions_helloworld_get]
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>

<!--
  Copyright 2020 Google LLC
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<!-- [START functions_kotlin_pom] -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example.cloud.functions</groupId>
  <artifactId>functions-kotlin-hello-world</artifactId>

  <!-- [END functions_kotlin_pom] -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>
  <!-- [START functions_kotlin_pom] -->

  <properties>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <kotlin.version>1.6.21</kotlin.version>
  </properties>

  <dependencies>
    <!-- Required for Function primitives -->
    <dependency>
      <groupId>com.google.cloud.functions</groupId>
      <artifactId>functions-framework-api</artifactId>
      <version>1.0.4</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-stdlib-jdk8</artifactId>
      <version>${kotlin.version}</version>
    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-test</artifactId>
      <version>${kotlin.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- [END functions_kotlin_pom] -->
    <!-- The following dependencies are only required for testing -->
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>4.5.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.google.truth</groupId>
      <artifactId>truth</artifactId>
      <version>1.1.3</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava-testlib</artifactId>
      <version>31.1-jre</version>
      <scope>test</scope>
    </dependency>
    <!-- [START functions_kotlin_pom] -->
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <!--
          Google Cloud Functions Framework Maven plugin
          This plugin allows you to run Cloud Functions Java code
          locally. Use the following terminal command to run a
          given function locally:
          mvn function:run -Drun.functionTarget=your.package.yourFunction
        -->
        <groupId>com.google.cloud.functions</groupId>
        <artifactId>function-maven-plugin</artifactId>
        <version>0.10.1</version>
        <configuration>
          <functionTarget>functions.HelloWorld</functionTarget>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <version>${kotlin.version}</version>
        <executions>
          <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <sourceDirs>
                <source>src/main/kotlin</source>
              </sourceDirs>
            </configuration>
          </execution>
          <execution>
            <id>test-compile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>test-compile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <jvmTarget>1.8</jvmTarget>
        </configuration>
      </plugin>
      <!-- [END functions_kotlin_pom] -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M7</version>
        <configuration>
          <skipTests>${skipTests}</skipTests>
          <reportNameSuffix>sponge_log</reportNameSuffix>
          <trimStackTrace>false</trimStackTrace>
        </configuration>
      </plugin>
      <!-- [START functions_kotlin_pom] -->
    </plugins>
  </build>
</project>
<!-- [END functions_kotlin_pom] -->
</code>```

Body:
I am developing a Kotlin backend that is going to run in Google Cloud Functions. I am unsing the example code that Google has given, however I do not know how I can run the code on my local Windows 11 machine with IntelliJ.

There is no option to run the file. Even when I go to "Run/Debug Configurations" I cannot select the KotlinHelloWorld.kt file as my main class to run.

Below is the sample code given from https://cloud.google.com/functions/docs/concepts/jvm-langs.

src/main/kotlin/functions/KotlinHelloWorld.kt

/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package functions

// [START functions_helloworld_get]
import com.google.cloud.functions.HttpFunction
import com.google.cloud.functions.HttpRequest
import com.google.cloud.functions.HttpResponse
import java.io.IOException
import java.util.logging.Logger

class HelloWorld : HttpFunction {
    // Simple function to return "Hello World"
    @Throws(IOException::class)
    override fun service(request: HttpRequest, response: HttpResponse) {
        response.writer.write("Hello World!")
    }
}
// [END functions_helloworld_get]

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example.cloud.functions</groupId>
  <artifactId>functions-kotlin-hello-world</artifactId>

  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>

  <properties>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <kotlin.version>1.6.21</kotlin.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>com.google.cloud.functions</groupId>
      <artifactId>functions-framework-api</artifactId>
      <version>1.0.4</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-stdlib-jdk8</artifactId>
      <version>${kotlin.version}</version>
    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-test</artifactId>
      <version>${kotlin.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>4.5.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.google.truth</groupId>
      <artifactId>truth</artifactId>
      <version>1.1.3</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava-testlib</artifactId>
      <version>31.1-jre</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>

        <groupId>com.google.cloud.functions</groupId>
        <artifactId>function-maven-plugin</artifactId>
        <version>0.10.1</version>
        <configuration>
          <functionTarget>functions.HelloWorld</functionTarget>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <version>${kotlin.version}</version>
        <executions>
          <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <sourceDirs>
                <source>src/main/kotlin</source>
              </sourceDirs>
            </configuration>
          </execution>
          <execution>
            <id>test-compile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>test-compile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <jvmTarget>1.8</jvmTarget>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M7</version>
        <configuration>
          <skipTests>${skipTests}</skipTests>
          <reportNameSuffix>sponge_log</reportNameSuffix>
          <trimStackTrace>false</trimStackTrace>
        </configuration>
      </plugin>

    </plugins>
  </build>
</project>


问:
I want to put this text-cursor at the position of r and I should be able to move it. How to do so?
I have created a random list and I want to put text cursor to be at the position of r and it should be able to move both at beginning and end of the output list.

I have added the code till printing the list elements


问:
Multiples resolutionStrategy in build.gradle
I need to add two resolutrionStrategy into configurations.all, in build.gradle

The new resolutionStrategy is the following:

```<code>resolutionStrategy.eachDependency {
    if (requested.group == "org.jfrog.cardinalcommerce.gradle" && requested.name == "cardinalmobilesdk") {
        useVersion("2.2.7-2")
        because("user data consent per Google's Data Safety Policy")
    }
}
</code>```

but my current configurations.all is the following:

```<code>configurations.all {
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }
}
</code>```

so, how can I add the new resolutionStrategy without affecting the current?
I think this can be a good way, but I don't know how to check if is correct

```<code>configurations.all {
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }

    resolutionStrategy.eachDependency {
        if (requested.group == "org.jfrog.cardinalcommerce.gradle" && requested.name == "cardinalmobilesdk") {
            useVersion("2.2.7-2")
            because("user data consent per Google's Data Safety Policy")
        }
    }
}
</code>```

Body:
I need to add two resolutrionStrategy into configurations.all, in build.gradle

The new resolutionStrategy is the following:

resolutionStrategy.eachDependency {
    if (requested.group == "org.jfrog.cardinalcommerce.gradle" && requested.name == "cardinalmobilesdk") {
        useVersion("2.2.7-2")
        because("user data consent per Google's Data Safety Policy")
    }
}

but my current configurations.all is the following:

configurations.all {
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }
}

so, how can I add the new resolutionStrategy without affecting the current?
I think this can be a good way, but I don't know how to check if is correct

configurations.all {
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }

    resolutionStrategy.eachDependency {
        if (requested.group == "org.jfrog.cardinalcommerce.gradle" && requested.name == "cardinalmobilesdk") {
            useVersion("2.2.7-2")
            because("user data consent per Google's Data Safety Policy")
        }
    }
}


问:
Do GCP Internal Load Balancers support gRPC with Serverless Negs
I am running a number of Cloud Run services which all have VPC access via a VPC connector and setting all egress to run through this connector. I have an ILB set up which points to a Regional Backend Service with Serverless Network Endpoint Group type. When you select this type you are unable to choose the protocol for the service (HTTP, HTTPS, HTTP/2)

The receiving Cloud Run is set to ingress unauthenticated and to allow internal/cloud-load-balancing.

When my client tries to send messages to my server via an address that resolves to the ILB it fails with a very non-descript error: rpc error: code = Unknown desc =.

I have tried using the direct cloud run url as opposed to going via my ILB and this does work. I would prefer to use my internal DNS though if possible.


问:
My maui app throws exception if I open second window and close it then attempt to displayalert
in my app adding new client will display alert that tells the user that the new client is added successfully and it works fine but after opening a second window (displays a client info) and  closing it attempting to add new client throws an exception (the client is added to the database successfully but the exception is thrown at displaying the alert)

The exception

```<code>Exception thrown: 'System.Runtime.InteropServices.COMException' in WinRT.Runtime.dll
WinRT information: The WinUI Desktop Window object has already been closed.
Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Private.CoreLib.dll
WinRT information: The WinUI Desktop Window object has already been closed.
The program '[77340] VetOrg.exe' has exited with code 3221226107 (0xc000027b).

</code>```

This is how I open Second window

```<code> public async void GetOwnerInfo()
        {
            Window window = new Window(new ClientView(new ClientViewModel(db, SelectedOwner)));

            Application.Current.OpenWindow(window);

        }
</code>```

This is How I display alert

```<code> await App.Current.MainPage.DisplayAlert("Done", AppRes.DoneOwnerPetComplaint, AppRes.Ok);
</code>```

I expected the display alert to work fine since the main window is still open and.

Body:
in my app adding new client will display alert that tells the user that the new client is added successfully and it works fine but after opening a second window (displays a client info) and  closing it attempting to add new client throws an exception (the client is added to the database successfully but the exception is thrown at displaying the alert)

The exception

Exception thrown: 'System.Runtime.InteropServices.COMException' in WinRT.Runtime.dll
WinRT information: The WinUI Desktop Window object has already been closed.
Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Private.CoreLib.dll
WinRT information: The WinUI Desktop Window object has already been closed.
The program '[77340] VetOrg.exe' has exited with code 3221226107 (0xc000027b).

This is how I open Second window

 public async void GetOwnerInfo()
        {
            Window window = new Window(new ClientView(new ClientViewModel(db, SelectedOwner)));

            Application.Current.OpenWindow(window);

        }

This is How I display alert

 await App.Current.MainPage.DisplayAlert("Done", AppRes.DoneOwnerPetComplaint, AppRes.Ok);

I expected the display alert to work fine since the main window is still open and.


问:
Null value returned by a Google sheet regex
I am trying to write a script in Google sheet that should extract a piece of a string using a regex.For example if I have "test test $1.00 test test" I would like to extract only "1.00"

What I have done so far is:

```<code>function myFunction() {
  var regExp = new RegExp("\$(.*)\s+");
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  var range = sheet.getDataRange();
  var values = range.getValues();
  var item_description = 0;
  var quantity = 1;
  var quantity_flat = [];
  var item_flat = [];

  for (var j = 0; j < values[quantity].length; j++) {
    if (values[quantity][j] == "") {
      quantity_flat.push(0);
    } else {
      quantity_flat.push(values[quantity][j]);
    }
  }

  for (var j = 0; j < values[item_description].length; j++) {
    var test = regExp.exec(values[item_description][j]);
    item_flat.push(test);
  }
}
</code>```

When I check the type of test, I get that it is an Object and has a value of null.
Not sure where is the error. Ideally, I would like to get back a number so that I can push it in an array.
Thanks!

Body:
I am trying to write a script in Google sheet that should extract a piece of a string using a regex.For example if I have "test test $1.00 test test" I would like to extract only "1.00"

What I have done so far is:

function myFunction() {
  var regExp = new RegExp("\$(.*)\s+");
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  var range = sheet.getDataRange();
  var values = range.getValues();
  var item_description = 0;
  var quantity = 1;
  var quantity_flat = [];
  var item_flat = [];

  for (var j = 0; j < values[quantity].length; j++) {
    if (values[quantity][j] == "") {
      quantity_flat.push(0);
    } else {
      quantity_flat.push(values[quantity][j]);
    }
  }

  for (var j = 0; j < values[item_description].length; j++) {
    var test = regExp.exec(values[item_description][j]);
    item_flat.push(test);
  }
}

When I check the type of test, I get that it is an Object and has a value of null.
Not sure where is the error. Ideally, I would like to get back a number so that I can push it in an array.
Thanks!


问:
Difference between stellarium and pyephem entering the sun a constellation
I've noticed that Stellarium uses the center of the sun for entering a constellation but pyephem seems to use the edge and so there are a few hours of difference.

What's the correct calculation (center or edge) ??

If it is stellarium... how to calculate entering the center of the sun in pyephem ??

Thanks


问:
printing a specific item from a list c++
im trying to print a number from a list in c++

`

```<code>#include <algorithm>
#include <iostream>
#include <list>
#include <random>
int main() {
    int lenght, number;
    lenght = 0;
    std::list<int> list = {1,2,3,4,5,6,7,8,9};
    int index = rand() % lenght; // pick a random index
    int value = list[index]; // a random value taken from that list
    for (int i : list){
        lenght + 1;
    }
    return 0;

}
</code>```

this line of code`
int value = list[index]; // a random value taken from that list
is giving me this error

```<code>operand types are: std::__cxx11::list<int, std::allocator<int>> [ int ]
</code>```

Body:
im trying to print a number from a list in c++

`

#include <algorithm>
#include <iostream>
#include <list>
#include <random>
int main() {
    int lenght, number;
    lenght = 0;
    std::list<int> list = {1,2,3,4,5,6,7,8,9};
    int index = rand() % lenght; // pick a random index
    int value = list[index]; // a random value taken from that list
    for (int i : list){
        lenght + 1;
    }
    return 0;

}

this line of code`
int value = list[index]; // a random value taken from that list
is giving me this error

operand types are: std::__cxx11::list<int, std::allocator<int>> [ int ]


问:
Get a table that groups by value and provides two columns containing each a different count for that value
I have a table like the below

Pet Name
Test
Result

Celine
A
Positive

Diogo
A
Negative

Jordah
A
Positive

Diogo
B
Positive

Jordah
B
Negative

Caesar
A
Negative

I need to come up with a query (or a view) showing the below

Pet Name
Total tests
Positive

Diogo
2
1

Jordah
2
1

Celine
1
1

Caesar
1
0

I tried a query like

```<code>SELECT Pet Name, COUNT(*)
WHERE Result=‘Positive’
GROUP BY Pet Name
ORDER BY COUNT(*) DESC
</code>```

which is ok, but it doesn’t provide me with the number of tests done by each pet.

The CASE WHEN sort of options do not seem to be applicable as the table gets populated with more Pet Names as vet makes new friends.

Thanks in advance.

This has been identified as duplicate of this, but I don't think it's the case. As I mentioned in above, it's the actual query that will provide the pet name, I won't know that name in advance, so no conditions such as IF or CASE WHEN sounds like helpful.

Body:
I have a table like the below

Pet Name
Test
Result

Celine
A
Positive

Diogo
A
Negative

Jordah
A
Positive

Diogo
B
Positive

Jordah
B
Negative

Caesar
A
Negative

I need to come up with a query (or a view) showing the below

Pet Name
Total tests
Positive

Diogo
2
1

Jordah
2
1

Celine
1
1

Caesar
1
0

I tried a query like

SELECT Pet Name, COUNT(*)
WHERE Result=‘Positive’
GROUP BY Pet Name
ORDER BY COUNT(*) DESC

which is ok, but it doesn’t provide me with the number of tests done by each pet.

The CASE WHEN sort of options do not seem to be applicable as the table gets populated with more Pet Names as vet makes new friends.

Thanks in advance.

This has been identified as duplicate of this, but I don't think it's the case. As I mentioned in above, it's the actual query that will provide the pet name, I won't know that name in advance, so no conditions such as IF or CASE WHEN sounds like helpful.


问:
When my gameThread is sleeping, whenever the gameThread stops sleeping, for every gametick the pause screen wasup, those ticks effect player
What I'm trying to do is create a pause button that stops everything in the game at once. All entities are controlled via the gameThread. I have tried putting if(!gamePaused) around update and draw methods and that didn't fix it. This is my GamePanel which has the gameThread in it. Any pointers in the right direction would be a godsend. I've been working on this for hours.

`

```<code>package main;

import entity.*;
import entity.Background;

import javax.swing.*;
import java.awt.*;

public class GamePanel extends JPanel implements Runnable {

    //Panel Settings
    public final int originalTileSize = 16; //16x16 pixels per tile
    public final int scale = 1;
    public final int tileSize = originalTileSize * scale; //48x48 pixels per tile
    public final int screenColums = 16;
    public final int screenRows = 16;
    public final int screenWidth = tileSize * screenColums; //256 pixels width
    public final int screenHeight = tileSize * screenRows; //256 pixels width
    public final int FPS = 40;
    public boolean gameFinished = false;

    public boolean gamePaused = false;

    //Initialize Components
    KeyHandler keyHandler = new KeyHandler();
    MouseHandler mouseHandler = new MouseHandler();
    public Thread gameThread;
    Player player = new Player(this, this.keyHandler, this.mouseHandler);
    CapePowerUp capePowerUp = new CapePowerUp(this);
    HelmetPowerUp helmetPowerUp = new HelmetPowerUp(this);
    Pipe pipe = new Pipe(this);
    Background background = new Background(this);

    public GamePanel() {
        this.setPreferredSize(new Dimension(screenWidth, screenHeight));
        this.setBackground(Color.BLACK);
        this.setDoubleBuffered(true);
        this.addKeyListener(keyHandler);
        this.addMouseListener(mouseHandler);
        this.setFocusable(true);
        this.setVisible(true);
    }

    public void startGameThread() {
        gameThread = new Thread(this);
        gameThread.start();
    }

    @Override
    public void run() {
        double drawInterval = 1000000000/FPS;
        double nextDrawTime = System.nanoTime() + drawInterval;

        while(gameThread != null) {
            if(!gamePaused) {

                update();
                repaint();

                try {
                    double remainingTime = nextDrawTime - System.nanoTime();
                    remainingTime = remainingTime / 1000000;

                    if (remainingTime < 0) {
                        remainingTime = 0;
                    }

                    Thread.sleep((long) remainingTime);
                    nextDrawTime += drawInterval;
                } catch(InterruptedException e){
                    e.printStackTrace();
                }
            } else {
                try {
                    while(gamePaused) {
                        Thread.sleep(100);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void update() {
        if (gamePaused) {
            return;
        }

        player.update();
        pipe.update();
        capePowerUp.update();
        helmetPowerUp.update();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        if (gamePaused) {
            return;
        }

        if(!gameFinished) {
            background.draw(g2);
            player.draw(g2);
            pipe.draw(g2);
            capePowerUp.draw(g2);
            helmetPowerUp.draw(g2);
        }
        if(gameFinished) {
            player.drawDeath(g2);
        }
        g2.dispose();
    }

    public void initializeGameSettings() {
        //Set Variables Back to Default
        Entity.powerUpCounter = 0;
        Entity.score = 0;
        Entity.canSpawnPowerUp = true;
        Entity.capePowerUpEnabled = false;
        Entity.helmetPowerUpEnabled = false;
        Entity.collisionOn = false;
        gameFinished = false;
        keyHandler.spacePressed = false;
        mouseHandler.mouse1Pressed = false;
        mouseHandler.mouse3Pressed = false;
        keyHandler.canMove = true;
        mouseHandler.canMove = true;

        //Re-initialize components
        player.initializePlayer();
        pipe.initializePipe();
        capePowerUp.initializePowerUp();
        helmetPowerUp.initializePowerUp();
    }
}

</code>```

`

Also this is my MyFrame which has the button that controls the game being paused/not.

`

```<code>package main;

import entity.Entity;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class MyFrame extends JFrame {

    public BufferedImage playerframe0;
    GamePanel gamePanel;
    JButton resetButton;
    JButton pauseButton;

    MyFrame() {
        //Gets and Sets icon for JFrame
        BufferedImage image;
        getImage();
        image = playerframe0;
        this.setIconImage(image);

        //JFrame Options/Settings
        this.setTitle("Flappy Leet");
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setSize(270,270);
        this.setResizable(false);

        //FlowLayout for Buttons
        FlowLayout experimentLayout = new FlowLayout(FlowLayout.TRAILING,0,0);
        this.setLayout(experimentLayout);

        //Reset Button Settings
        resetButton = new JButton("Reset");
        resetButton.setForeground(Color.white);
        resetButton.setBackground(Color.BLACK);
        resetButton.setSize(10, 10);
        resetButton.setLocation(25,25);
        resetButton.addActionListener(e -> gamePanel.initializeGameSettings());
        resetButton.setFocusable(false);

        //Reset Button Settings
        pauseButton = new JButton("Pause");
        pauseButton.setForeground(Color.white);
        pauseButton.setBackground(Color.BLACK);
        pauseButton.setSize(10, 10);
        pauseButton.setLocation(25,25);
        pauseButton.addActionListener(e -> gamePanel.gamePaused = !gamePanel.gamePaused);
        pauseButton.setFocusable(false);

        gamePanel = new GamePanel();

        //Components to JFrame
        this.add(pauseButton);
        this.add(resetButton);
        this.add(gamePanel);
        this.setVisible(true);

        //Starts game
        gamePanel.startGameThread();
    }

    public void getImage() {
        //Gets the image for the JFrame
        try {
            playerframe0 = ImageIO.read(Entity.class.getResourceAsStream("/playerframe.png"));
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

</code>```

`

Thanks for anyone who can help me with this. I'm starting to pull my hair out. If you'd like access to my Git to get a better look at the code feel free to message me with your email and I'll send you access.

I have tried setting booleans that flip each other on/off when game is paused, I have tried doing .wait() and using .notify(), I've tried using chatgpt to help me figure out the issue aswell. I feel like I'm going around in circles now. I just want the game to pause and not have the frames the game was paused to effect the player once the game is unpaused.

Body:
What I'm trying to do is create a pause button that stops everything in the game at once. All entities are controlled via the gameThread. I have tried putting if(!gamePaused) around update and draw methods and that didn't fix it. This is my GamePanel which has the gameThread in it. Any pointers in the right direction would be a godsend. I've been working on this for hours.

`

package main;

import entity.*;
import entity.Background;

import javax.swing.*;
import java.awt.*;

public class GamePanel extends JPanel implements Runnable {

    //Panel Settings
    public final int originalTileSize = 16; //16x16 pixels per tile
    public final int scale = 1;
    public final int tileSize = originalTileSize * scale; //48x48 pixels per tile
    public final int screenColums = 16;
    public final int screenRows = 16;
    public final int screenWidth = tileSize * screenColums; //256 pixels width
    public final int screenHeight = tileSize * screenRows; //256 pixels width
    public final int FPS = 40;
    public boolean gameFinished = false;

    public boolean gamePaused = false;

    //Initialize Components
    KeyHandler keyHandler = new KeyHandler();
    MouseHandler mouseHandler = new MouseHandler();
    public Thread gameThread;
    Player player = new Player(this, this.keyHandler, this.mouseHandler);
    CapePowerUp capePowerUp = new CapePowerUp(this);
    HelmetPowerUp helmetPowerUp = new HelmetPowerUp(this);
    Pipe pipe = new Pipe(this);
    Background background = new Background(this);

    public GamePanel() {
        this.setPreferredSize(new Dimension(screenWidth, screenHeight));
        this.setBackground(Color.BLACK);
        this.setDoubleBuffered(true);
        this.addKeyListener(keyHandler);
        this.addMouseListener(mouseHandler);
        this.setFocusable(true);
        this.setVisible(true);
    }

    public void startGameThread() {
        gameThread = new Thread(this);
        gameThread.start();
    }

    @Override
    public void run() {
        double drawInterval = 1000000000/FPS;
        double nextDrawTime = System.nanoTime() + drawInterval;

        while(gameThread != null) {
            if(!gamePaused) {

                update();
                repaint();

                try {
                    double remainingTime = nextDrawTime - System.nanoTime();
                    remainingTime = remainingTime / 1000000;

                    if (remainingTime < 0) {
                        remainingTime = 0;
                    }

                    Thread.sleep((long) remainingTime);
                    nextDrawTime += drawInterval;
                } catch(InterruptedException e){
                    e.printStackTrace();
                }
            } else {
                try {
                    while(gamePaused) {
                        Thread.sleep(100);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void update() {
        if (gamePaused) {
            return;
        }

        player.update();
        pipe.update();
        capePowerUp.update();
        helmetPowerUp.update();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        if (gamePaused) {
            return;
        }

        if(!gameFinished) {
            background.draw(g2);
            player.draw(g2);
            pipe.draw(g2);
            capePowerUp.draw(g2);
            helmetPowerUp.draw(g2);
        }
        if(gameFinished) {
            player.drawDeath(g2);
        }
        g2.dispose();
    }

    public void initializeGameSettings() {
        //Set Variables Back to Default
        Entity.powerUpCounter = 0;
        Entity.score = 0;
        Entity.canSpawnPowerUp = true;
        Entity.capePowerUpEnabled = false;
        Entity.helmetPowerUpEnabled = false;
        Entity.collisionOn = false;
        gameFinished = false;
        keyHandler.spacePressed = false;
        mouseHandler.mouse1Pressed = false;
        mouseHandler.mouse3Pressed = false;
        keyHandler.canMove = true;
        mouseHandler.canMove = true;

        //Re-initialize components
        player.initializePlayer();
        pipe.initializePipe();
        capePowerUp.initializePowerUp();
        helmetPowerUp.initializePowerUp();
    }
}

`

Also this is my MyFrame which has the button that controls the game being paused/not.

`

package main;

import entity.Entity;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class MyFrame extends JFrame {

    public BufferedImage playerframe0;
    GamePanel gamePanel;
    JButton resetButton;
    JButton pauseButton;

    MyFrame() {
        //Gets and Sets icon for JFrame
        BufferedImage image;
        getImage();
        image = playerframe0;
        this.setIconImage(image);

        //JFrame Options/Settings
        this.setTitle("Flappy Leet");
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setSize(270,270);
        this.setResizable(false);

        //FlowLayout for Buttons
        FlowLayout experimentLayout = new FlowLayout(FlowLayout.TRAILING,0,0);
        this.setLayout(experimentLayout);

        //Reset Button Settings
        resetButton = new JButton("Reset");
        resetButton.setForeground(Color.white);
        resetButton.setBackground(Color.BLACK);
        resetButton.setSize(10, 10);
        resetButton.setLocation(25,25);
        resetButton.addActionListener(e -> gamePanel.initializeGameSettings());
        resetButton.setFocusable(false);

        //Reset Button Settings
        pauseButton = new JButton("Pause");
        pauseButton.setForeground(Color.white);
        pauseButton.setBackground(Color.BLACK);
        pauseButton.setSize(10, 10);
        pauseButton.setLocation(25,25);
        pauseButton.addActionListener(e -> gamePanel.gamePaused = !gamePanel.gamePaused);
        pauseButton.setFocusable(false);

        gamePanel = new GamePanel();

        //Components to JFrame
        this.add(pauseButton);
        this.add(resetButton);
        this.add(gamePanel);
        this.setVisible(true);

        //Starts game
        gamePanel.startGameThread();
    }

    public void getImage() {
        //Gets the image for the JFrame
        try {
            playerframe0 = ImageIO.read(Entity.class.getResourceAsStream("/playerframe.png"));
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

`

Thanks for anyone who can help me with this. I'm starting to pull my hair out. If you'd like access to my Git to get a better look at the code feel free to message me with your email and I'll send you access.

I have tried setting booleans that flip each other on/off when game is paused, I have tried doing .wait() and using .notify(), I've tried using chatgpt to help me figure out the issue aswell. I feel like I'm going around in circles now. I just want the game to pause and not have the frames the game was paused to effect the player once the game is unpaused.


问:
ASP.NET Menu is not rendered correctly when using RegisterStartupScript
I've been working through an issue where I want to update some control states prior to downloading a file.  Using info from other StackOverflow users, I've arrived at a solution that works 'mostly'.  I'm updating my controls in the main button click handler then using a RegisterStartupScript to execute a click on a hidden button to perform the actual download.

All that works as-expected.

The issue I'm coming across is that the placement of the startup script seems to be interfering with the normal rendering of my menu at the top of my page.

Normal Menu

Corrupted Menu

I have a menu setup in the site masterpage using an asp:Menu control and LoginView, and this ends up adding a new Sys.WebForms.Menu script at the bottom of the page through whatever magical mystical potion Microsoft uses for this control.

The last few lines of my html source ends up looking like this when the RegisterStartupScript is run:

```<code>
<script type='text/javascript'>document.getElementById('btnHiddenDownloadAction').click();</script><script type='text/javascript'>new Sys.WebForms.Menu({ element: 'MenuLoginView_NavigationMenu', disappearAfter: 500, orientation: 'horizontal', tabIndex: 0, disabled: false });</script></form>
</body>
</html>
</code>```

The first script with the btnHiddenDownloadAction click is what I'm adding via the RegisterStartupScript() call.  The second script is getting placed there by the ASP.NET menu control.

The menu control on my masterpage is defined like this (truncated)

```<code><asp:LoginView ID="MenuLoginView" runat="server" EnableViewState="false">
    <AnonymousTemplate>
    </AnonymousTemplate>
    <RoleGroups>
        <asp:RoleGroup Roles="Administrator">
            <ContentTemplate>
                <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false"
                    IncludeStyleBlock="false" Orientation="Horizontal" OnPreRender="NavigationMenu_PreRender">
                    <StaticSelectedStyle Font-Bold="true" />
                    <Items>
                        <asp:MenuItem NavigateUrl="~/KeyGeneration.aspx" Text="Feature Activation" />
                        <asp:MenuItem NavigateUrl="~/GenerateAALicense.aspx" Text="Generate AA License" />
                        <asp:MenuItem NavigateUrl="~/DevicePasswordGeneration.aspx" Text="Device Password Generator" />
                        <asp:MenuItem Text="Reporting">
                            <asp:MenuItem NavigateUrl="~/KeyHistoryReport.aspx" Text="Feature Activation History Report"></asp:MenuItem>
                            <asp:MenuItem NavigateUrl="~/AALicenseReport.aspx" Text="AA License Report"></asp:MenuItem>
                            <asp:MenuItem NavigateUrl="~/DevicePasswordHistoryReport.aspx" Text="Device Password History Report"></asp:MenuItem>
                        </asp:MenuItem>
                        <asp:MenuItem NavigateUrl="~/ManageUsers.aspx" Text="Manage Users" />
                        <asp:MenuItem NavigateUrl="~/ManageFeatures.aspx" Text="Manage Features" />
                        <asp:MenuItem NavigateUrl="~/ChangePassword.aspx" Text="Change Password" />
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="About" />
                    </Items>
                </asp:Menu>
            </ContentTemplate>
        </asp:RoleGroup>
</code>```

I've tried inserting this as a client script rather than a startup script, but the button control doesn't exist at that point, so the button click doesn't execute.  I've tried reformatting the script to add a 'div' tag, and I've tried simplifying the call to call a script defined elsewhere, both of those still have that menu problem.

Body:
I've been working through an issue where I want to update some control states prior to downloading a file.  Using info from other StackOverflow users, I've arrived at a solution that works 'mostly'.  I'm updating my controls in the main button click handler then using a RegisterStartupScript to execute a click on a hidden button to perform the actual download.

All that works as-expected.

The issue I'm coming across is that the placement of the startup script seems to be interfering with the normal rendering of my menu at the top of my page.

Normal Menu

Corrupted Menu

I have a menu setup in the site masterpage using an asp:Menu control and LoginView, and this ends up adding a new Sys.WebForms.Menu script at the bottom of the page through whatever magical mystical potion Microsoft uses for this control.

The last few lines of my html source ends up looking like this when the RegisterStartupScript is run:

</form>

The first script with the btnHiddenDownloadAction click is what I'm adding via the RegisterStartupScript() call.  The second script is getting placed there by the ASP.NET menu control.

The menu control on my masterpage is defined like this (truncated)

<asp:LoginView ID="MenuLoginView" runat="server" EnableViewState="false">
    <AnonymousTemplate>
    </AnonymousTemplate>
    <RoleGroups>
        <asp:RoleGroup Roles="Administrator">
            <ContentTemplate>
                <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false"
                    IncludeStyleBlock="false" Orientation="Horizontal" OnPreRender="NavigationMenu_PreRender">
                    <StaticSelectedStyle Font-Bold="true" />
                    <Items>
                        <asp:MenuItem NavigateUrl="~/KeyGeneration.aspx" Text="Feature Activation" />
                        <asp:MenuItem NavigateUrl="~/GenerateAALicense.aspx" Text="Generate AA License" />
                        <asp:MenuItem NavigateUrl="~/DevicePasswordGeneration.aspx" Text="Device Password Generator" />
                        <asp:MenuItem Text="Reporting">
                            <asp:MenuItem NavigateUrl="~/KeyHistoryReport.aspx" Text="Feature Activation History Report"></asp:MenuItem>
                            <asp:MenuItem NavigateUrl="~/AALicenseReport.aspx" Text="AA License Report"></asp:MenuItem>
                            <asp:MenuItem NavigateUrl="~/DevicePasswordHistoryReport.aspx" Text="Device Password History Report"></asp:MenuItem>
                        </asp:MenuItem>
                        <asp:MenuItem NavigateUrl="~/ManageUsers.aspx" Text="Manage Users" />
                        <asp:MenuItem NavigateUrl="~/ManageFeatures.aspx" Text="Manage Features" />
                        <asp:MenuItem NavigateUrl="~/ChangePassword.aspx" Text="Change Password" />
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="About" />
                    </Items>
                </asp:Menu>
            </ContentTemplate>
        </asp:RoleGroup>

I've tried inserting this as a client script rather than a startup script, but the button control doesn't exist at that point, so the button click doesn't execute.  I've tried reformatting the script to add a 'div' tag, and I've tried simplifying the call to call a script defined elsewhere, both of those still have that menu problem.


问:
How to upload files with NodeJs express-fileuploaf to a Synology NAS shared folder
I would like to upload files using nodejs and express-fileupload to a NAS (Network attached storage) device but I cannot find any documentation for this online. Does anybody know if this is possible?

I cannot use nodejs path to connect to the NAS server.


问:
Generate columns through a usercontrol on a datagrid
I'm creating a library that contains multiple usercontrols which I'm using in my applications. I'm currently struggling with the datagrid. I've created a custom control that contains a simple datagrid with some styling. I've created a dependency property which holds the columns the datagrid should show.

The dependency property looks like this:

```<code>public ObservableCollection<DataGridColumn> ColumnsSource
        {
            get { return (ObservableCollection<DataGridColumn>)GetValue(ColumnsSourceProperty); }
            set { SetValue(ColumnsSourceProperty, value); }
        }

        public static readonly DependencyProperty ColumnsSourceProperty =
            DependencyProperty.Register("ColumnsSource", typeof(ObservableCollection<DataGridColumn>), typeof(bDataGrid), new PropertyMetadata(new ObservableCollection<DataGridColumn>()));
</code>```

I want to use the control like this in my application:

```<code><custom:bDataGrid>
    <custom:bDataGrid.ColumnsSource>
       <DataGridTextColumn Header="First Column"/>
       <DataGridTextColumn Header="Second Column"/>
       <DataGridTextColumn Header="Third Column"/>
    </custom:bDataGrid.ColumnsSource>
</custom:bDataGrid>
</code>```

I can't figure out how to use it that way. I want the datagrid in the usercontrol to take these values and create the corresponding columnheaders.

Any advise?

All columns that has been set through the usercontrol dependency property should show up in the datagrid as a column.

EDIT:

Solved it by reading the following link
How do I bind a WPF DataGrid to a variable number of columns?

Body:
I'm creating a library that contains multiple usercontrols which I'm using in my applications. I'm currently struggling with the datagrid. I've created a custom control that contains a simple datagrid with some styling. I've created a dependency property which holds the columns the datagrid should show.

The dependency property looks like this:

public ObservableCollection<DataGridColumn> ColumnsSource
        {
            get { return (ObservableCollection<DataGridColumn>)GetValue(ColumnsSourceProperty); }
            set { SetValue(ColumnsSourceProperty, value); }
        }

        public static readonly DependencyProperty ColumnsSourceProperty =
            DependencyProperty.Register("ColumnsSource", typeof(ObservableCollection<DataGridColumn>), typeof(bDataGrid), new PropertyMetadata(new ObservableCollection<DataGridColumn>()));

I want to use the control like this in my application:

<custom:bDataGrid>
    <custom:bDataGrid.ColumnsSource>
       <DataGridTextColumn Header="First Column"/>
       <DataGridTextColumn Header="Second Column"/>
       <DataGridTextColumn Header="Third Column"/>
    </custom:bDataGrid.ColumnsSource>
</custom:bDataGrid>

I can't figure out how to use it that way. I want the datagrid in the usercontrol to take these values and create the corresponding columnheaders.

Any advise?

All columns that has been set through the usercontrol dependency property should show up in the datagrid as a column.

EDIT:

Solved it by reading the following link
How do I bind a WPF DataGrid to a variable number of columns?


问:
Can anyone tell me why the DOM stops updating the order total in my restaurant app when I remove the LAST item in the array?
I'm working on a restaurant ordering app, and when I add items, it adds and removes them from the total display, but when I remove the FINAL item in the cart, the order total still shows the value of the last item that was removed. Here is a link to my code as well as the function itself that contain the order total:

https://codepen.io/vanessalearnsjavascript/pen/qBKGvQP?editors=0011

```<code>function handleOrderSection(){
  let totalPriceArray = [];
  let invoiceHtml = ``;
  let totalPrice = 0;
  orderList.forEach(function(chosenItem, index){
    invoiceHtml += `
      <div class="item-invoice">
       <div class="remove-wpr">
        <h3 class="item-invoice name">${chosenItem.name}</h3>
         <button class="remove-btn" data-remove="${index}">Remove</button>
        </div>
        <h3 class="item-invoice-price">$${chosenItem.price}</h3>
       </div>
    `
    //console.log(chosenItem)
    totalPriceArray.push(chosenItem.price)
    //console.log(totalPriceArray)
    if(totalPriceArray.length >= 1){
      let orderValue = totalPriceArray.reduce(function(total, num){
        return total + num
      })
      console.log(orderValue)
      let customOrder = ``
      customOrder += `
        <div id="order-total" class="total-display">
       Order Total:$ ${totalPriceArray.reduce(function(total, num){
        return total + num
      })}
       </div> `

      document.getElementById("chosen-items").style.display = "block"
      document.getElementById("chosen-items").innerHTML = customOrder
    }
  })
  document.getElementById('ordered-items').innerHTML = invoiceHtml
  if(orderList.length >= 1){
    modal.style.display = "inline"
    completeBtn.style.display = "inline"
  } else {
    modal.style.display = "none"
    completeBtn.style.display = "none"
  }
}
</code>```

Any help is appreciated. Thanks in advance.

I've tried different things like adding the return statement to different parts of the function and even changing the event listeners, and it just continues to confuse me. I don't have too much to add to this part, just that it's been a real head scratcher for me.

Body:
I'm working on a restaurant ordering app, and when I add items, it adds and removes them from the total display, but when I remove the FINAL item in the cart, the order total still shows the value of the last item that was removed. Here is a link to my code as well as the function itself that contain the order total:

https://codepen.io/vanessalearnsjavascript/pen/qBKGvQP?editors=0011

function handleOrderSection(){
  let totalPriceArray = [];
  let invoiceHtml = ``;
  let totalPrice = 0;
  orderList.forEach(function(chosenItem, index){
    invoiceHtml += `

${chosenItem.name}

         <button class="remove-btn" data-remove="${index}">Remove</button>

$${chosenItem.price}

    `
    //console.log(chosenItem)
    totalPriceArray.push(chosenItem.price)
    //console.log(totalPriceArray)
    if(totalPriceArray.length >= 1){
      let orderValue = totalPriceArray.reduce(function(total, num){
        return total + num
      })
      console.log(orderValue)
      let customOrder = ``
      customOrder += `

       Order Total:$ ${totalPriceArray.reduce(function(total, num){
        return total + num
      })}

 `

      document.getElementById("chosen-items").style.display = "block"
      document.getElementById("chosen-items").innerHTML = customOrder
    }
  })
  document.getElementById('ordered-items').innerHTML = invoiceHtml
  if(orderList.length >= 1){
    modal.style.display = "inline"
    completeBtn.style.display = "inline"
  } else {
    modal.style.display = "none"
    completeBtn.style.display = "none"
  }
}

Any help is appreciated. Thanks in advance.

I've tried different things like adding the return statement to different parts of the function and even changing the event listeners, and it just continues to confuse me. I don't have too much to add to this part, just that it's been a real head scratcher for me.


问:
How can I make webpack include unused functions with typescript?
How can I make webpack keep unused functions in the final file, I have functions in a typescript file that are not used in the typescript file, but I need them in the final file since they are used in events like onclick which need a function to execute, this is my webpack.config.js file:

```<code>var webpack = require('webpack');
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    entry: {
        home: "./resources/js/home.ts",
        contact: "./resources/js/contact.ts",
    },
    output: {
        path: path.resolve(__dirname, 'public/js'),
        filename: '[name].js',
    },
    resolve: {
        extensions: ['.js', '.ts'],
    },
    optimization: {
        minimizer: [new TerserPlugin({
            extractComments: false,
        })],
    },
    watch: true,
    module: {
        rules: [
            {
                test: /\.ts?$/,
                use: 'ts-loader',
            },
        ],
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
        })
    ]
};
</code>```

And this is my tsconfig.js file:

```<code>{
    "compilerOptions": {
        "module": "es6",
        "target": "es5",
        "moduleResolution": "node",
        "outDir": "./public/js",
        "rootDir": "./resources/js",
        "removeComments": true,
        "allowJs": true,
        "allowSyntheticDefaultImports":  true,
        "allowUnusedLabels": true,
    },
    "files": [
        "./resources/js/contact.ts",
    ],
}
</code>```

I know the problem is webpack since when compiling using only typescript, I get the unused function in the final file. So how can I make webpack keep unused functions and leave them in the final javascript file?

Body:
How can I make webpack keep unused functions in the final file, I have functions in a typescript file that are not used in the typescript file, but I need them in the final file since they are used in events like onclick which need a function to execute, this is my webpack.config.js file:

var webpack = require('webpack');
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    entry: {
        home: "./resources/js/home.ts",
        contact: "./resources/js/contact.ts",
    },
    output: {
        path: path.resolve(__dirname, 'public/js'),
        filename: '[name].js',
    },
    resolve: {
        extensions: ['.js', '.ts'],
    },
    optimization: {
        minimizer: [new TerserPlugin({
            extractComments: false,
        })],
    },
    watch: true,
    module: {
        rules: [
            {
                test: /\.ts?$/,
                use: 'ts-loader',
            },
        ],
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
        })
    ]
};

And this is my tsconfig.js file:

{
    "compilerOptions": {
        "module": "es6",
        "target": "es5",
        "moduleResolution": "node",
        "outDir": "./public/js",
        "rootDir": "./resources/js",
        "removeComments": true,
        "allowJs": true,
        "allowSyntheticDefaultImports":  true,
        "allowUnusedLabels": true,
    },
    "files": [
        "./resources/js/contact.ts",
    ],
}

I know the problem is webpack since when compiling using only typescript, I get the unused function in the final file. So how can I make webpack keep unused functions and leave them in the final javascript file?


问:
Filling a list within a loop using list.add and loop variable - how to clone variable?
i try to read out a certain XML API. It is my first project in dart and not very optimized, however it works until the loop ... well loops.

Here the code:

```<code>getKategorie(XmlElement element) {
    Kategorie tmpKategorie = Kategorie();
    dynamic iterableElements;
    Board tmpBoard = Board();
    tmpKategorie.id = element.getAttribute("id");
    tmpKategorie.name = element.getElement("name")?.innerText;
    tmpKategorie.description = element.getElement("description")?.innerText;

    iterableElements = element.getElement("boards")?.childElements;
    for (XmlElement tmpElement in iterableElements) {
      if (tmpElement.localName == "board") {
        tmpBoard.id = tmpElement?.getAttribute("id");
        tmpBoard.name = tmpElement?.getElement("name")?.innerText;
        tmpBoard.description = tmpElement?.getElement("description")?.innerText;
        tmpKategorie.boards.add(tmpBoard);
      }
    }
    return tmpKategorie;
  }
</code>```

the custom classes i use:

```<code>class Kategorie {
  List<Board> boards = [];
  dynamic id;
  dynamic name = "NN";
  dynamic description = "NN";
}

class Board {
  dynamic id;
  dynamic name;
  dynamic description;
}
</code>```

Everything works fine until i reach the second Element with localName board. While the tmpBoard variable will be filled with the data from the second/third/whatever Element content, the before added list element in tmpKategore.boards is also changed.
It looks like the add call for the tmpKategorie.boards list is only putting in the reference to the loop variable tmpBoard which ends in my problem: At the end all added list entries are identical to the last one.

How can i copy the object instead of referencing it into the list?

solution like suggested

```<code>if (tmpElement.localName == "board") {
        tmpBoard.id = tmpElement?.getAttribute("id");
</code>```

becomes

```<code>if (tmpElement.localName == "board") {
        tmpBoard = Board();
        tmpBoard.id = tmpElement?.getAttribute("id");
</code>```

Body:
i try to read out a certain XML API. It is my first project in dart and not very optimized, however it works until the loop ... well loops.

Here the code:

getKategorie(XmlElement element) {
    Kategorie tmpKategorie = Kategorie();
    dynamic iterableElements;
    Board tmpBoard = Board();
    tmpKategorie.id = element.getAttribute("id");
    tmpKategorie.name = element.getElement("name")?.innerText;
    tmpKategorie.description = element.getElement("description")?.innerText;

    iterableElements = element.getElement("boards")?.childElements;
    for (XmlElement tmpElement in iterableElements) {
      if (tmpElement.localName == "board") {
        tmpBoard.id = tmpElement?.getAttribute("id");
        tmpBoard.name = tmpElement?.getElement("name")?.innerText;
        tmpBoard.description = tmpElement?.getElement("description")?.innerText;
        tmpKategorie.boards.add(tmpBoard);
      }
    }
    return tmpKategorie;
  }

the custom classes i use:

class Kategorie {
  List<Board> boards = [];
  dynamic id;
  dynamic name = "NN";
  dynamic description = "NN";
}

class Board {
  dynamic id;
  dynamic name;
  dynamic description;
}

Everything works fine until i reach the second Element with localName board. While the tmpBoard variable will be filled with the data from the second/third/whatever Element content, the before added list element in tmpKategore.boards is also changed.
It looks like the add call for the tmpKategorie.boards list is only putting in the reference to the loop variable tmpBoard which ends in my problem: At the end all added list entries are identical to the last one.

How can i copy the object instead of referencing it into the list?

solution like suggested

if (tmpElement.localName == "board") {
        tmpBoard.id = tmpElement?.getAttribute("id");

becomes

if (tmpElement.localName == "board") {
        tmpBoard = Board();
        tmpBoard.id = tmpElement?.getAttribute("id");


问:
Connect versions deployed in different environments
We have a branch per environment i.e

dev branch deploys to the Development env

staging branch deploys to the Staging env

master branch deploys to the Prod env

We create a new build for each env (Because of how the serverless framework works and understand that it is not ideal). Currently, the version is stored in a Config service (AWS SSM) outside of the source files.

I am looking to keep a consistent version when the same code is deployed to different environments. Currently, the version number is incremented independently in each pipeline for each environment with no way to know if version 1.1.3 deployed on env Dev is the same as version 1.1.0 deployed on staging env.

We use the "Merge Commit" strategy in Bitbucket so a Git tag added to a commit in the source branch is not linked to the Merge commit that gets added to the target branch on PR merge.

What options do I have to maintain the same version number across envs for the same codebase?


问:
plt.fill_between gives "ValueError: Input passed into argument "'y1'"is not 1-dimensional"
I am building a gaussian process regression model in TensorFlow with 2 inputs and 1 output. Everything runs okay until I try to plot the 95% confidence interval. The line that is throwing the error is the following:

```<code># Fill the region between the lower and upper bounds of the confidence interval around the linear regression line
plt.fill_between(range(len(X_train)), mean_train - model_confidence_interval_train, mean_train + model_confidence_interval_train, color='#FFA07A', alpha=0.2, label='Confidence interval')

</code>```

My full code is below:

```<code>Y_pred1 = model.predict(X_train)

# Calculate the mean and standard deviation of the predictions on the training set
mean_train, std_train = model.predict(X_train, return_std=True)

# Calculate the 95% confidence interval for the training data
model_confidence_interval_train = 1.96 * std_train

plt.figure(figsize=(10,10))

# Overlay the training and testing data on the plot
plt.scatter(y_train,Y_pred1, color = '#FFA07A', edgecolor="black",s=75, label='Training Prediction')

# Plot the linear regression line
plt.plot([0, 30], [0, 30], color = 'k', label='True Values')

# Fill the region between the lower and upper bounds of the confidence interval around the linear regression line

plt.fill_between(range(len(X_train)), mean_train - model_confidence_interval_train, mean_train + model_confidence_interval_train, color='#FFA07A', alpha=0.2, label='Confidence interval')

#plt.fill_between(range(len(X_train)), mean_train - model_confidence_interval_train, mean_train + model_confidence_interval_train, color='#FFA07A', alpha=0.2, label='Confidence interval')

#plt.fill_between(range(len(X_train)), mean_train.flatten() - model_confidence_interval_train.flatten(), mean_train.flatten() + model_confidence_interval_train.flatten(), color='#FFA07A', alpha=0.2, label=' 95% confidence interval')

#p1 = max(max(y_train), max(Y_pred1))
#p2 = min(min(y_train), min(Y_pred))

plt.xlabel('True Values', fontsize=15)
plt.ylabel('Predictions', fontsize=15)
plt.title('Strength (kN)',fontsize=20)

# Add a legend
plt.legend()

# Make the plot square
plt.axis('equal')

# add a grid
plt.grid(True)

# Show the plot
plt.show()

</code>```

You can  see I have some commented out lines underneath the line throwing the error, but those didn't seem to work either.

Can anyone provide guidance or insight on how to resolve this error and plot the confidence interval? My current figure looks like this:

Regression Plot

Body:
I am building a gaussian process regression model in TensorFlow with 2 inputs and 1 output. Everything runs okay until I try to plot the 95% confidence interval. The line that is throwing the error is the following:

# Fill the region between the lower and upper bounds of the confidence interval around the linear regression line
plt.fill_between(range(len(X_train)), mean_train - model_confidence_interval_train, mean_train + model_confidence_interval_train, color='#FFA07A', alpha=0.2, label='Confidence interval')

My full code is below:

Y_pred1 = model.predict(X_train)

# Calculate the mean and standard deviation of the predictions on the training set
mean_train, std_train = model.predict(X_train, return_std=True)

# Calculate the 95% confidence interval for the training data
model_confidence_interval_train = 1.96 * std_train

plt.figure(figsize=(10,10))

# Overlay the training and testing data on the plot
plt.scatter(y_train,Y_pred1, color = '#FFA07A', edgecolor="black",s=75, label='Training Prediction')

# Plot the linear regression line
plt.plot([0, 30], [0, 30], color = 'k', label='True Values')

# Fill the region between the lower and upper bounds of the confidence interval around the linear regression line

plt.fill_between(range(len(X_train)), mean_train - model_confidence_interval_train, mean_train + model_confidence_interval_train, color='#FFA07A', alpha=0.2, label='Confidence interval')

#plt.fill_between(range(len(X_train)), mean_train - model_confidence_interval_train, mean_train + model_confidence_interval_train, color='#FFA07A', alpha=0.2, label='Confidence interval')

#plt.fill_between(range(len(X_train)), mean_train.flatten() - model_confidence_interval_train.flatten(), mean_train.flatten() + model_confidence_interval_train.flatten(), color='#FFA07A', alpha=0.2, label=' 95% confidence interval')

#p1 = max(max(y_train), max(Y_pred1))
#p2 = min(min(y_train), min(Y_pred))

plt.xlabel('True Values', fontsize=15)
plt.ylabel('Predictions', fontsize=15)
plt.title('Strength (kN)',fontsize=20)

# Add a legend
plt.legend()

# Make the plot square
plt.axis('equal')

# add a grid
plt.grid(True)

# Show the plot
plt.show()

You can  see I have some commented out lines underneath the line throwing the error, but those didn't seem to work either.

Can anyone provide guidance or insight on how to resolve this error and plot the confidence interval? My current figure looks like this:

Regression Plot


问:
Detect SO missing at runtime
I have writing a Qt5/C++ program in Linux which tries to use some library functions.  If that library is not installed, then the user sees warnings on stderr as follows:

```<code>qt.canbus.plugins.socketcan: Cannot load library socketcan: (socketcan: cannot open shared object file: No such file or directory)
qt.canbus.plugins.socketcan: Cannot load library libsocketcan, some functionality will not be available.
</code>```

I know the solution is to install the library, but I would like my code to be able to detect the missing library and shutdown gracefully.  Is this possible in standard C++ or Qt5 ?

Title: Detect SO missing at runtime

Body:
I have writing a Qt5/C++ program in Linux which tries to use some library functions.  If that library is not installed, then the user sees warnings on stderr as follows:

qt.canbus.plugins.socketcan: Cannot load library socketcan: (socketcan: cannot open shared object file: No such file or directory)
qt.canbus.plugins.socketcan: Cannot load library libsocketcan, some functionality will not be available.

I know the solution is to install the library, but I would like my code to be able to detect the missing library and shutdown gracefully.  Is this possible in standard C++ or Qt5 ?


问:
Using prefetch_related / select_related on a GenericForeignKey's own related reverse fields
Is it possible to prefetch a GenericForeignKey that is attached to another GenericForeignKey?

For example, the following is not possible (though I'd like it to be):

Consider the imaginary model below. Homes are generic and can be attached to many different types of objects via the content_object field as usual.

I'd like to do something like prefetch a user, along with their animals, and the animals homes (though I'm aware this below won't work):

User.objects.prefetch_related("animals", "animals__home")

Is there any way to achieve this?

```<code>from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models

class User(models.Model):
    ...

class Animal(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    user = models.ForeignKey(User, related_name="animals")
    ...

class Home(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.UUIDField()
    content_object = GenericForeignKey("content_type", "object_id")
    ...

</code>```

Body:
Is it possible to prefetch a GenericForeignKey that is attached to another GenericForeignKey?

For example, the following is not possible (though I'd like it to be):

Consider the imaginary model below. Homes are generic and can be attached to many different types of objects via the content_object field as usual.

I'd like to do something like prefetch a user, along with their animals, and the animals homes (though I'm aware this below won't work):

User.objects.prefetch_related("animals", "animals__home")

Is there any way to achieve this?

from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models

class User(models.Model):
    ...

class Animal(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    user = models.ForeignKey(User, related_name="animals")
    ...

class Home(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.UUIDField()
    content_object = GenericForeignKey("content_type", "object_id")
    ...


问:
Celery: How to abort running task
calculator.py

```<code>def add(n):
    r = n + n
    time.sleep(15) # long running task
    return r
</code>```

tasks.py

```<code>from calculator import add

REDIS_URL = redis://redis:6379/0

celery_app = Celery(__name__, broker=REDIS_URL, backend=REDIS_URL)

@celery_app.task(bind=True, name="background_task_job", base=AbortableTask)
def background_task_job(self, n):
    abt = "Aborted"
    val = 0

    while not self.is_aborted():

        val = add(n)  # ADD() which calls sleep_one()
        return val

    return abt
</code>```

app.py

```<code>from tasks import background_task_job

# On Start button
result = background_task_job.apply_async(args=(2,))

# On Cancel button
abortable_task = AbortableAsyncResult(result.id)
abortable_task.abort()
</code>```

Observed:
I clicked start button, background task started running. Say after 8 seconds (for eg) I clicked cancel button, I observed no "Aborted" message but the inside add() seems to be alive/running, As after, 7 more seconds which makes 15 seconds [8 + 7] I observed celery returns outputs as 4 [celery| success 15.0sec 4] (for eg).

1.
Why add() not getting aborted which is inside the background_task_job()?
What I am missing?

2.
If so output is returned as 4, why [celery| success 15.0sec 4] and not 8sec as I clicked cancel button at 8 seconds? Is this behavior correct?

Please suggest.

Updated: Code

After replacing time.sleep() with sleep_one(), I am able to get state and status of the task as ABORTED, but still the function runs completely and didnot get aborted.

```<code>def sleep_one(n):
    start = time.time()
    finish = start + 4
    while time.time() < finish:
        pass
    return n
</code>```
```<code>def add(n):
    # time.sleep(15)
    n = 0
   # simulating long running process
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    return n
</code>```

What I am missing?

As while searching, I came across small sample codes only in which there is direct for loop inside the background_task_job().
Since, I am calling add() inside the background_task_job() does it affect or prevent the task from getting aborted?

Title: Celery: How to abort running task

Body:
calculator.py

def add(n):
    r = n + n
    time.sleep(15) # long running task
    return r

tasks.py

from calculator import add

REDIS_URL = redis://redis:6379/0

celery_app = Celery(__name__, broker=REDIS_URL, backend=REDIS_URL)

@celery_app.task(bind=True, name="background_task_job", base=AbortableTask)
def background_task_job(self, n):
    abt = "Aborted"
    val = 0

    while not self.is_aborted():

        val = add(n)  # ADD() which calls sleep_one()
        return val

    return abt

app.py

from tasks import background_task_job

# On Start button
result = background_task_job.apply_async(args=(2,))

# On Cancel button
abortable_task = AbortableAsyncResult(result.id)
abortable_task.abort()

Observed:
I clicked start button, background task started running. Say after 8 seconds (for eg) I clicked cancel button, I observed no "Aborted" message but the inside add() seems to be alive/running, As after, 7 more seconds which makes 15 seconds [8 + 7] I observed celery returns outputs as 4 [celery| success 15.0sec 4] (for eg).

1.
Why add() not getting aborted which is inside the background_task_job()?
What I am missing?

2.
If so output is returned as 4, why [celery| success 15.0sec 4] and not 8sec as I clicked cancel button at 8 seconds? Is this behavior correct?

Please suggest.

Updated: Code

After replacing time.sleep() with sleep_one(), I am able to get state and status of the task as ABORTED, but still the function runs completely and didnot get aborted.

def sleep_one(n):
    start = time.time()
    finish = start + 4
    while time.time() < finish:
        pass
    return n

def add(n):
    # time.sleep(15)
    n = 0
   # simulating long running process
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    n += sleep_one(1)
    return n

What I am missing?

As while searching, I came across small sample codes only in which there is direct for loop inside the background_task_job().
Since, I am calling add() inside the background_task_job() does it affect or prevent the task from getting aborted?