问:
Forkjoin vs Threadpool difference
I am bit confused how Forkjoin internally works vs Thread Pool. Below is the code snippet for the same. Both are having single parallelism. Ideally it should behave same as Thread pool and it should not pick the task unless it finishes.

```<code>public class Sample {

public static void main(String[] args) {
    // Use either ThreadPoolExecutor or ForkJoin.
    //ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
    ForkJoinPool pool = new ForkJoinPool(1);
    List<Integer> items = new ArrayList<>();
    items.add(1);
    items.add(2);
    // Create 2 task and submit to thread pool. Wait for it to execute all the task.
    pool.submit(() -> {
        try {
            startProcessing(items.get(0));
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    pool.submit(() -> {
        try {
            startProcessing(items.get(1));
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

    try {
        pool.shutdown();
        pool.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
private static void startProcessing(int itemVal) throws ExecutionException, InterruptedException {
    doProcessing(itemVal).get();
    System.out.println("Ended :" + itemVal);
}

private static CompletableFuture<Integer> doProcessing(int itemVal) throws InterruptedException {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    System.out.println("Started :" + itemVal);
    // I was assuming as this is waiting for child thread to also complete,
    // so this thread will be waiting and hence will be waiting for task 1 untill it finishes.
    // BUT IT GOT CONTEXT SWITCHED AND PICKED THE TASK 2.
    asyncCall(future, itemVal);
    return future;
}

// This is the place where new thread is created.
private static void asyncCall(CompletableFuture<Integer> future, int itemVal) {
    Thread t = new Thread(() -> {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        future.complete(itemVal);
    });
    t.start();
}
</code>```

}

Below is the output if using Thread pool:

```<code>Started :1
Ended :1
Started :2
Ended :2
</code>```

And below is the output if using Fork Join:

```<code>Started :1
Started :2
Ended :1
Ended :2
</code>```

Why is this difference in behavior for Fork Join compared to thread pool?

Title: Forkjoin vs Threadpool difference

Body:
I am bit confused how Forkjoin internally works vs Thread Pool. Below is the code snippet for the same. Both are having single parallelism. Ideally it should behave same as Thread pool and it should not pick the task unless it finishes.

public class Sample {

public static void main(String[] args) {
    // Use either ThreadPoolExecutor or ForkJoin.
    //ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
    ForkJoinPool pool = new ForkJoinPool(1);
    List<Integer> items = new ArrayList<>();
    items.add(1);
    items.add(2);
    // Create 2 task and submit to thread pool. Wait for it to execute all the task.
    pool.submit(() -> {
        try {
            startProcessing(items.get(0));
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    pool.submit(() -> {
        try {
            startProcessing(items.get(1));
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

    try {
        pool.shutdown();
        pool.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
private static void startProcessing(int itemVal) throws ExecutionException, InterruptedException {
    doProcessing(itemVal).get();
    System.out.println("Ended :" + itemVal);
}

private static CompletableFuture<Integer> doProcessing(int itemVal) throws InterruptedException {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    System.out.println("Started :" + itemVal);
    // I was assuming as this is waiting for child thread to also complete,
    // so this thread will be waiting and hence will be waiting for task 1 untill it finishes.
    // BUT IT GOT CONTEXT SWITCHED AND PICKED THE TASK 2.
    asyncCall(future, itemVal);
    return future;
}

// This is the place where new thread is created.
private static void asyncCall(CompletableFuture<Integer> future, int itemVal) {
    Thread t = new Thread(() -> {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        future.complete(itemVal);
    });
    t.start();
}

}

Below is the output if using Thread pool:

Started :1
Ended :1
Started :2
Ended :2

And below is the output if using Fork Join:

Started :1
Started :2
Ended :1
Ended :2

Why is this difference in behavior for Fork Join compared to thread pool?


来源: stackexchange

问:
create a scrolling SPA with different components and call them without using fragment identifier (#) in the address bar
I created a web page with navigational bar and I want my page to scroll to the screen vertically to a page when the user clicks on the navbar link. At the same time, my page should not show "#" symbol in address bar.

App.jsx

```<code>function App() {
  const [ContactusShow, setContactusShow] = useState(false);

  const ContentWrapper = () => {
    return (
      <div className="ContentWrapper">
        <HomePage setContactusShow={setContactusShow} />
        <ServicePage />
        <CategoryPage />
        <ProjectsPage />
        <BlogPage />
        <MemberPage />
        <ClientsPage />
      </div>
    );
  };

  return (
    <div className="App">
      <Header />
      <Routes>
        <Route
          path="/"
          element={<ContentWrapper setContactusShow={setContactusShow} />}
        />
        <Route path="/ProsolPage" element={<ProsolPage />} />
        <Route path="/PropediaPage" element={<PropediaPage />} />
        <Route path="/GoosparesPage" element={<GoosparesPage />} />
      </Routes>
      <Footer />

      {ContactusShow && <ContactusPage setContactusShow={setContactusShow} />}
    </div>
  );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a web page with navigational bar and I want my page to scroll to the screen vertically to a page when the user clicks on the navbar link. At the same time, my page should not show "#" symbol in address bar.

App.jsx

function App() {
  const [ContactusShow, setContactusShow] = useState(false);

  const ContentWrapper = () => {
    return (

        <HomePage setContactusShow={setContactusShow} />
        <ServicePage />
        <CategoryPage />
        <ProjectsPage />
        <BlogPage />
        <MemberPage />
        <ClientsPage />

    );
  };

  return (

      <Routes>
        <Route
          path="/"
          element={<ContentWrapper setContactusShow={setContactusShow} />}
        />
        <Route path="/ProsolPage" element={<ProsolPage />} />
        <Route path="/PropediaPage" element={<PropediaPage />} />
        <Route path="/GoosparesPage" element={<GoosparesPage />} />
      </Routes>

      {ContactusShow && <ContactusPage setContactusShow={setContactusShow} />}

  );
}


问:
String boot Application Validations not working
Hi in my Spring boot application, validation are specified correctly but they are not working. the application is firing up correctly and handler methods and view pages are working as expected, but the issue here is with the validations part, below given are code snippet of view, controller, and domain class along with Screenshot of Referenced libraries in the project.

Domain Class:

```<code>package tacos;

import java.util.List;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import lombok.Data;

@Data
public class Taco {

@NotNull
@Size(min=5, message="Name must be at least 5 character long")
private String name;

@Size(min=1, message="You must choose at least 1 ingredient")
private List<String> ingredients;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public List<String> getIngredients() {
    return ingredients;
}
public void setIngredients(List<String> ingredients) {
    this.ingredients = ingredients;
}
</code>```

Libraries are present.

Controller code:

```<code>    @PostMapping
    public String processDesign(@Valid Taco design, Errors errors) {

    if(errors.hasErrors()) {
        return "design";
    }

    log.info("Processing design: " + design);

    return "redirect:/orders/current";
}
</code>```

view page code:

```<code>       <span class="validationError"
         th:if="${#fields.hasErrors('ingredients')}"
         th:errors="*{ingredients}">Ingredient Error</span>

   <div>
      <h3>Name your taco creation:</h3>
      <input type="text" th:field="*{name}"/>

      <span th:text="${#fields.hasErrors('name')}">XXX</span>
      <span class="validationError"
            th:if="${#fields.hasErrors('name')}"
            th:errors="*{name}">Name Error</span>

      <br><br/>

      <button>Submit your taco</button>
   </div>
</code>```

i tried adding the dependencies manually but still it has no change. please help.

Body:
Hi in my Spring boot application, validation are specified correctly but they are not working. the application is firing up correctly and handler methods and view pages are working as expected, but the issue here is with the validations part, below given are code snippet of view, controller, and domain class along with Screenshot of Referenced libraries in the project.

Domain Class:

package tacos;

import java.util.List;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import lombok.Data;

@Data
public class Taco {

@NotNull
@Size(min=5, message="Name must be at least 5 character long")
private String name;

@Size(min=1, message="You must choose at least 1 ingredient")
private List<String> ingredients;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public List<String> getIngredients() {
    return ingredients;
}
public void setIngredients(List<String> ingredients) {
    this.ingredients = ingredients;
}

Libraries are present.

Controller code:

    @PostMapping
    public String processDesign(@Valid Taco design, Errors errors) {

    if(errors.hasErrors()) {
        return "design";
    }

    log.info("Processing design: " + design);

    return "redirect:/orders/current";
}

view page code:

       Ingredient Error

Name your taco creation:

      <input type="text" th:field="*{name}"/>

      XXX
      Name Error

      <button>Submit your taco</button>

i tried adding the dependencies manually but still it has no change. please help.


问:
Snakeyaml default value implementation if field is null
I have YAML file where exists a lot of empty lists. So after parsing I want to change them to new ArrayList(). It will reduce amounts of null checks.

I have a model like this:

```<code>@Data
public class Model
{
  private List<Object> list;
}
</code>```

after:

```<code>String content = "list:";
Yaml yaml = new Yaml();
yaml.loadAs(content, Model.class);
</code>```

I get a null List;

but I want change it to new ArrayList()

So how can I change default value using SnakeYaml?

Body:
I have YAML file where exists a lot of empty lists. So after parsing I want to change them to new ArrayList(). It will reduce amounts of null checks.

I have a model like this:

@Data
public class Model
{
  private List<Object> list;
}

after:

String content = "list:";
Yaml yaml = new Yaml();
yaml.loadAs(content, Model.class);

I get a null List;

but I want change it to new ArrayList()

So how can I change default value using SnakeYaml?


问:
How to mirror all gitlab repos to bitbucket workspace?
I have cloned multiple GitLab Repositories. I need to migrate all of the to BitBucket.
Do we have any way to upload same repos into bitbucket?

I know the "git push --mirror" but we have lot of repos and for mirror we need to setup remote in each repo, So can anyone suggest any python script to automate this?

Thanks


问:
How to fix Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'String' in flutter?
Right now I'm working on the create profile page section. Which before coming to this page will verify the identity by using the otp code and will receive the token of the user as well in order to check whether this token has already applied to the system. If you haven't applied yet, you will come to the profile creation page. But if you have already applied, you can go straight to the main page.

But now I'm stuck with the problem that When pressing the confirm button on the profile creation page, this error occurs. where i want to fetch data from local storage which i have created sharedpreference to store and retrieve data already After that I created a model in response to the profiling, created the dio package used to build the network api in flutter, but I still can't find where it went wrong.

it's dio_client.dart

```<code>Future<ProfileUserResponseModel> createProfile({
  required String fullName,
  required String idLine,
  required String birthDate,
  required String? gender,
}) async {
  final request = ProfileUserRequestModel(
      fullName: fullName, idLine: idLine, birthDate: birthDate, gender: gender);
  final response =
      await dioToken().post(ApiConstants.createProfile, data: request.toJson());
  try {
    if (response.statusCode == 201) {
      return ProfileUserResponseModel.fromJson(response.data);
    } else {
      throw Exception('Failed to create your profile');
    }
  } on DioError catch (e) {
    throw Exception(e);
  }
}
</code>```

it's profile_user_request_model.dart

```<code>class ProfileUserRequestModel {
  ProfileUserRequestModel(
      {required this.fullName,
      required this.idLine,
      required this.birthDate,
      required this.gender});

  String fullName;
  String idLine;
  String birthDate;
  String? gender;

  factory ProfileUserRequestModel.fromJson(Map<String, dynamic> json) {
    return ProfileUserRequestModel(
      fullName: json["full_name"],
      idLine: json["id_line"],
      birthDate: json["birth_date"],
      gender: json["gender"],
    );
  }

  Map<String, dynamic> toJson() => {
        "full_name": fullName,
        "id_line": idLine,
        "birth_date": birthDate,
        "gender": gender,
      };
}
</code>```

I think it may be caused by mistake getting gender variable from radio button. But I have already defined it as a string. But it can't be used. If anyone knows a way to fix the problem. Feel free to reply in the comments. Thank you very much.

Body:
Right now I'm working on the create profile page section. Which before coming to this page will verify the identity by using the otp code and will receive the token of the user as well in order to check whether this token has already applied to the system. If you haven't applied yet, you will come to the profile creation page. But if you have already applied, you can go straight to the main page.

But now I'm stuck with the problem that When pressing the confirm button on the profile creation page, this error occurs. where i want to fetch data from local storage which i have created sharedpreference to store and retrieve data already After that I created a model in response to the profiling, created the dio package used to build the network api in flutter, but I still can't find where it went wrong.

it's dio_client.dart

Future<ProfileUserResponseModel> createProfile({
  required String fullName,
  required String idLine,
  required String birthDate,
  required String? gender,
}) async {
  final request = ProfileUserRequestModel(
      fullName: fullName, idLine: idLine, birthDate: birthDate, gender: gender);
  final response =
      await dioToken().post(ApiConstants.createProfile, data: request.toJson());
  try {
    if (response.statusCode == 201) {
      return ProfileUserResponseModel.fromJson(response.data);
    } else {
      throw Exception('Failed to create your profile');
    }
  } on DioError catch (e) {
    throw Exception(e);
  }
}

it's profile_user_request_model.dart

class ProfileUserRequestModel {
  ProfileUserRequestModel(
      {required this.fullName,
      required this.idLine,
      required this.birthDate,
      required this.gender});

  String fullName;
  String idLine;
  String birthDate;
  String? gender;

  factory ProfileUserRequestModel.fromJson(Map<String, dynamic> json) {
    return ProfileUserRequestModel(
      fullName: json["full_name"],
      idLine: json["id_line"],
      birthDate: json["birth_date"],
      gender: json["gender"],
    );
  }

  Map<String, dynamic> toJson() => {
        "full_name": fullName,
        "id_line": idLine,
        "birth_date": birthDate,
        "gender": gender,
      };
}

I think it may be caused by mistake getting gender variable from radio button. But I have already defined it as a string. But it can't be used. If anyone knows a way to fix the problem. Feel free to reply in the comments. Thank you very much.


问:
Deleted dags appear in dags list and db
I'm trying to delete a dag named 'twitterQueryParse' which you can see in this screenshot from my dags list:

```<code>airflow dags list
</code>```

I've executed:

```<code>airflow dags delete twitterQueryParse
</code>```

So I'm getting the anticipated error message:

```<code>[2022-12-25 09:39:49,657] {__init__.py:42} INFO - Loaded API auth backend: airflow.api.auth.backend.session
This will drop all existing records related to the specified DAG. Proceed? (y/n)y
[2022-12-25 09:39:53,555] {delete_dag.py:46} INFO - Deleting DAG: twitterQueryParse
Traceback (most recent call last):
  File "/home/rony/anaconda3/bin/airflow", line 8, in <module>
    sys.exit(main())
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/__main__.py", line 39, in main
    args.func(args)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/cli/cli_parser.py", line 52, in command
    return func(*args, **kwargs)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/utils/cli.py", line 103, in wrapper
    return f(*args, **kwargs)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/cli/commands/dag_command.py", line 163, in dag_delete
    message = api_client.delete_dag(dag_id=args.dag_id)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/api/client/local_client.py", line 38, in delete_dag
    count = delete_dag.delete_dag(dag_id)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/utils/session.py", line 75, in wrapper
    return func(*args, session=session, **kwargs)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/api/common/delete_dag.py", line 57, in delete_dag
    raise DagNotFound(f"Dag id {dag_id} not found")
airflow.exceptions.DagNotFound: Dag id twitterQueryParse not found
</code>```

But when I list the dags again twitterQueryParse remains on the list, even following a reset and initialization of the airflow db:

```<code>airflow db reset
airflow db init
</code>```

My airflow version is 2.4.2

How do I delete this dag completely from the airflow system?

Title: Deleted dags appear in dags list and db

Body:
I'm trying to delete a dag named 'twitterQueryParse' which you can see in this screenshot from my dags list:

airflow dags list

I've executed:

airflow dags delete twitterQueryParse

So I'm getting the anticipated error message:

[2022-12-25 09:39:49,657] {__init__.py:42} INFO - Loaded API auth backend: airflow.api.auth.backend.session
This will drop all existing records related to the specified DAG. Proceed? (y/n)y
[2022-12-25 09:39:53,555] {delete_dag.py:46} INFO - Deleting DAG: twitterQueryParse
Traceback (most recent call last):
  File "/home/rony/anaconda3/bin/airflow", line 8, in <module>
    sys.exit(main())
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/__main__.py", line 39, in main
    args.func(args)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/cli/cli_parser.py", line 52, in command
    return func(*args, **kwargs)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/utils/cli.py", line 103, in wrapper
    return f(*args, **kwargs)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/cli/commands/dag_command.py", line 163, in dag_delete
    message = api_client.delete_dag(dag_id=args.dag_id)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/api/client/local_client.py", line 38, in delete_dag
    count = delete_dag.delete_dag(dag_id)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/utils/session.py", line 75, in wrapper
    return func(*args, session=session, **kwargs)
  File "/home/rony/anaconda3/lib/python3.7/site-packages/airflow/api/common/delete_dag.py", line 57, in delete_dag
    raise DagNotFound(f"Dag id {dag_id} not found")
airflow.exceptions.DagNotFound: Dag id twitterQueryParse not found

But when I list the dags again twitterQueryParse remains on the list, even following a reset and initialization of the airflow db:

airflow db reset
airflow db init

My airflow version is 2.4.2

How do I delete this dag completely from the airflow system?


问:
Post install script within nodejs process doesn't recognize node path
I have some node.js code I'm running in a NodeJS process that I generate a package.json and I perform an NPM install like so:

```<code>import childProcess from "child_process";

const exec = childProcess.exec;

const { stderr, stdout } = await exec(`${process.execPath} npm install`, {
      env: {
        'PATH': process.execPath,
      }
    });

</code>```

The npm install works, but the post install script doesn't. and it outputs the following:

```<code>npm WARN lifecycle npm is using /~/.nvm/versions/node/v16.15.1/bin/node but there is no node binary in the current PATH. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.

> core-js@2.6.12 postinstall ~/project/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

npm ERR! code ELIFECYCLE
npm ERR! syscall spawn sh
npm ERR! file sh
npm ERR! path sh
npm ERR! errno -2
npm ERR! core-js@2.6.12 postinstall: `node -e "try{require('./postinstall')}catch(e){}"`
npm ERR! spawn sh ENOENT
npm ERR!
npm ERR! Failed at the core-js@2.6.12 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

</code>```

I tried adding the process.execPath to be set to the PATH variable of my NodeJS process but that didn't seem to work. I know process.execPath allows me to get the node process that started the process, but I also want to use it to invoke the post install scripts.

Body:
I have some node.js code I'm running in a NodeJS process that I generate a package.json and I perform an NPM install like so:

import childProcess from "child_process";

const exec = childProcess.exec;

const { stderr, stdout } = await exec(`${process.execPath} npm install`, {
      env: {
        'PATH': process.execPath,
      }
    });

The npm install works, but the post install script doesn't. and it outputs the following:

npm WARN lifecycle npm is using /~/.nvm/versions/node/v16.15.1/bin/node but there is no node binary in the current PATH. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.

> core-js@2.6.12 postinstall ~/project/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

npm ERR! code ELIFECYCLE
npm ERR! syscall spawn sh
npm ERR! file sh
npm ERR! path sh
npm ERR! errno -2
npm ERR! core-js@2.6.12 postinstall: `node -e "try{require('./postinstall')}catch(e){}"`
npm ERR! spawn sh ENOENT
npm ERR!
npm ERR! Failed at the core-js@2.6.12 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I tried adding the process.execPath to be set to the PATH variable of my NodeJS process but that didn't seem to work. I know process.execPath allows me to get the node process that started the process, but I also want to use it to invoke the post install scripts.


问:
Fatal Exception: java.lang.IllegalArgumentException: com.appname: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE
My react native app is crashing on start for android 12 (for some user). I have received error report on crashlytics dashboard. I can't also reproduce the error since app running on my android device just fine. This is the error in crashlytics dashbord. looks like problem with a third party library react-native-firebase but not sure how to fix this, anyone here facing the same problem ?

error:

```<code>Fatal Exception: java.lang.IllegalArgumentException: com.halkhata: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
       at android.app.PendingIntent.checkFlags(PendingIntent.java:382)
       at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:465)
       at android.app.PendingIntent.getActivity(PendingIntent.java:451)
       at android.app.PendingIntent.getActivity(PendingIntent.java:415)
       at com.google.firebase.messaging.CommonNotificationBuilder.createContentIntent(CommonNotificationBuilder.java:26)
       at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(CommonNotificationBuilder.java:69)
       at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(CommonNotificationBuilder.java:34)
       at com.google.firebase.messaging.DisplayNotification.handleNotification(DisplayNotification.java:28)
       at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(FirebaseMessagingService.java:36)
       at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(FirebaseMessagingService.java:130)
       at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(FirebaseMessagingService.java:12)
       at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(FirebaseMessagingService.java:89)
       at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(EnhancedIntentService.java:1)
       at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(EnhancedIntentService.java:6)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
       at com.google.android.gms.common.util.concurrent.zza.run(zza.java:6)
       at java.lang.Thread.run(Thread.java:1012)
</code>```

Body:
My react native app is crashing on start for android 12 (for some user). I have received error report on crashlytics dashboard. I can't also reproduce the error since app running on my android device just fine. This is the error in crashlytics dashbord. looks like problem with a third party library react-native-firebase but not sure how to fix this, anyone here facing the same problem ?

error:

Fatal Exception: java.lang.IllegalArgumentException: com.halkhata: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
       at android.app.PendingIntent.checkFlags(PendingIntent.java:382)
       at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:465)
       at android.app.PendingIntent.getActivity(PendingIntent.java:451)
       at android.app.PendingIntent.getActivity(PendingIntent.java:415)
       at com.google.firebase.messaging.CommonNotificationBuilder.createContentIntent(CommonNotificationBuilder.java:26)
       at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(CommonNotificationBuilder.java:69)
       at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(CommonNotificationBuilder.java:34)
       at com.google.firebase.messaging.DisplayNotification.handleNotification(DisplayNotification.java:28)
       at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(FirebaseMessagingService.java:36)
       at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(FirebaseMessagingService.java:130)
       at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(FirebaseMessagingService.java:12)
       at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(FirebaseMessagingService.java:89)
       at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(EnhancedIntentService.java:1)
       at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(EnhancedIntentService.java:6)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
       at com.google.android.gms.common.util.concurrent.zza.run(zza.java:6)
       at java.lang.Thread.run(Thread.java:1012)


问:
how to pass a django variable of an object fetched from the database in css
I want a background image to be an image uploaded by a user.

what tryed:

```<code><div class="slider-image" style="background-image: url({{latestArticle.image.url}});"></div>
</code>```


问:
how to create a class variable from a class funtion using python?
I want to create a class variable in python with arguments of the funtion

example :

```<code>class test:
    def __init__(self):
        self.name = "test"
        self.age = 20

    def get_variable (self, name, age):
        # this function should declare a variable which is name_age
        self.test_20 = 'some value'
        ##this self.test_20 will become my flag for the class
        ## I want declare a variable which is test_20 from name and age argument of this function

t = test()
t.get_variable('test', 20)

#if I call t.test_20, it should return 'some value'

</code>```

It seems easy but I am not able to get it done
any help is appreciated

Body:
I want to create a class variable in python with arguments of the funtion

example :

class test:
    def __init__(self):
        self.name = "test"
        self.age = 20

    def get_variable (self, name, age):
        # this function should declare a variable which is name_age
        self.test_20 = 'some value'
        ##this self.test_20 will become my flag for the class
        ## I want declare a variable which is test_20 from name and age argument of this function

t = test()
t.get_variable('test', 20)

#if I call t.test_20, it should return 'some value'

It seems easy but I am not able to get it done
any help is appreciated


问:
How to make awx take list of variable?
I am trying to create different users using awx, but whenever I run it I am getting such errors
the value ['user1', 'user2', 'user3'] (type list) in a string field was converted to "['user1', 'user2', 'user3']" (type string). If this does not look like what you expect, quote the entire value to ensure it does not change.
This is how I have added the varibale in awx ui

I have tried passing using json

Title: How to make awx take list of variable?


问:
I have a build a image classification model with CNN using keras but when I tried to train the model I got the following error
Datasets Preparation Code

```<code>categories = ['eye_open','eye_close','mouth_open','mouth_close']
ds = []
for c in categories:
    path = os.path.join('datasets',c)
    class_num = categories.index(c)
    for img in os.listdir(path):
        try:
            img_arr = cv2.imread(os.path.join(path,img),cv2.IMREAD_UNCHANGED)
            new_arr = cv2.resize(img_arr, (175, 175))
            ds.append([new_arr,class_num])
        except:
            pass

random.shuffle(ds)
X =[]
y =[]
for features, label in ds:
    X.append(features)
    y.append(label)
X = (np.array(X)/255).reshape(-1,175,175,3)
Y = np.eye(4)[y]
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size= 0.1,random_state=4)
</code>```

This is my model code

```<code>input_layer = L.Input(shape=(175,175,3))
c = L.Conv2D(48,kernel_size=(3,3),padding='same')(input_layer)
c = L.BatchNormalization()(c)
c = L.MaxPool2D((3,3),strides=2,padding='same')(c)
c = L.Conv2D(56,kernel_size=(3,3),padding='same')(c)
c = L.BatchNormalization()(c)
c = L.MaxPool2D((3,3),strides=2,padding='same')(c)

t1 = L.MaxPool2D((3,3),padding='same',strides=1)(c)
t1 = L.Conv2D(256,(1,1))(t1)

t2 = L.Conv2D(256,(1,1),padding='same')(c)
t2 = L.Conv2D(256,(5,5),padding='same')(t2)

t3 = L.Conv2D(256,(1,1),padding='same')(c)
t3 = L.Conv2D(256,(3,3),padding='same')(t3)

t4 = L.Conv2D(256,(1,1))(c)

merged = L.concatenate(\[t1,t2,t3,t4\],axis=1)

conv = L.MaxPool2D((3,3),padding='same',strides=2)(merged)

conv2 = L.Conv2D(64,(3,3),padding='same')(conv)
conv2 = L.Conv2D(64,(3,3),padding='same')(conv2)
conv2 = L.Conv2D(72,(3,3),padding='same')(conv2)
conv2 = L.MaxPool2D((3,3),padding='same',strides=2)(conv2)
m = L.Flatten()(conv2)
o = L.Dense(128)(m)
o = L.Dense(6)(o)
o = L.Dense(4)(o)
model = models.Model(input_layer,o)
</code>```

Model Compilation and fit code

```<code>model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=\['accuracy'\])
model.fit(x=X_train, y=y_train, validation_data=(X_test,y_test), epochs=2, callbacks=\[K.callbacks.TensorBoard()\])
</code>```

While compiling and fitting the above model with datasets it gives me an error of graph execution error. Please guide me what did I mistake in the above code.

Body:
Datasets Preparation Code

categories = ['eye_open','eye_close','mouth_open','mouth_close']
ds = []
for c in categories:
    path = os.path.join('datasets',c)
    class_num = categories.index(c)
    for img in os.listdir(path):
        try:
            img_arr = cv2.imread(os.path.join(path,img),cv2.IMREAD_UNCHANGED)
            new_arr = cv2.resize(img_arr, (175, 175))
            ds.append([new_arr,class_num])
        except:
            pass

random.shuffle(ds)
X =[]
y =[]
for features, label in ds:
    X.append(features)
    y.append(label)
X = (np.array(X)/255).reshape(-1,175,175,3)
Y = np.eye(4)[y]
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size= 0.1,random_state=4)

This is my model code

input_layer = L.Input(shape=(175,175,3))
c = L.Conv2D(48,kernel_size=(3,3),padding='same')(input_layer)
c = L.BatchNormalization()(c)
c = L.MaxPool2D((3,3),strides=2,padding='same')(c)
c = L.Conv2D(56,kernel_size=(3,3),padding='same')(c)
c = L.BatchNormalization()(c)
c = L.MaxPool2D((3,3),strides=2,padding='same')(c)

t1 = L.MaxPool2D((3,3),padding='same',strides=1)(c)
t1 = L.Conv2D(256,(1,1))(t1)

t2 = L.Conv2D(256,(1,1),padding='same')(c)
t2 = L.Conv2D(256,(5,5),padding='same')(t2)

t3 = L.Conv2D(256,(1,1),padding='same')(c)
t3 = L.Conv2D(256,(3,3),padding='same')(t3)

t4 = L.Conv2D(256,(1,1))(c)

merged = L.concatenate(\[t1,t2,t3,t4\],axis=1)

conv = L.MaxPool2D((3,3),padding='same',strides=2)(merged)

conv2 = L.Conv2D(64,(3,3),padding='same')(conv)
conv2 = L.Conv2D(64,(3,3),padding='same')(conv2)
conv2 = L.Conv2D(72,(3,3),padding='same')(conv2)
conv2 = L.MaxPool2D((3,3),padding='same',strides=2)(conv2)
m = L.Flatten()(conv2)
o = L.Dense(128)(m)
o = L.Dense(6)(o)
o = L.Dense(4)(o)
model = models.Model(input_layer,o)

Model Compilation and fit code

model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=\['accuracy'\])
model.fit(x=X_train, y=y_train, validation_data=(X_test,y_test), epochs=2, callbacks=\[K.callbacks.TensorBoard()\])

While compiling and fitting the above model with datasets it gives me an error of graph execution error. Please guide me what did I mistake in the above code.


问:
Rotativa.AspNetCore doesn't convert javascript output to PDF
I am using Javascript code to create a chart, then I have a button which by clicking on it converts the whole ASP.NET Core MVC page to PDF (including the chart) everything will be in PDF page except the chart. The project is in Visual Studio 2022 using ASP.NET Core 6 MVC.

This is the code for making the PDF by Rotativa:

```<code>return new ViewAsPdf("PrintPDF", result)
           {
               CustomSwitches = "--enable-javascript --debug-javascript --no-stop-slow-scripts --javascript-delay 10000",
               IsJavaScriptDisabled = false,
               FileName ="result.pdf",
           };
</code>```

This is the code I use for making the chart

```<code>        var BeforeWorkshop = [];

        @if(Model.ResultCategoriesDtos.Count>0)
        {
            foreach(var item in Model.ResultCategoriesDtos)
            {
                @:BeforeWorkshop.push(@item.Answer3_1);
            }
        }

         var RadarChart = document.getElementById('radarchart').getContext('2d');
        var chart = new Chart(RadarChart, {
            type: 'radar',

            data: {
                labels: labels
                datasets: [{
                    label: "First",
                    data: BeforeWorkshop,
                    fill: true,
                    backgroundColor: 'rgba(255, 99, 132, 0.2)',
                    borderColor: 'rgb(255, 99, 255)',
                    pointBackgroundColor: 'rgb(255, 99, 132)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgb(255, 99, 132)',

                }
                ]
            },

            // Configuration options
            options: {
                tooltips: {
                    callbacks: {
                        label: function (tooltipItem, data) {
                            return data.datasets[tooltipItem.datasetIndex].label + ": " + tooltipItem.yLabel;
                        }
                    }
                }
            }
        });
</code>```

I increased the delay time for Rotativa to javascript to be executed , but no success. the element which displays the javascript output is empty in PDF.

How can I get Rotativa.AspNetCore to work with Javascript code and convert it to PDF too?

Body:
I am using Javascript code to create a chart, then I have a button which by clicking on it converts the whole ASP.NET Core MVC page to PDF (including the chart) everything will be in PDF page except the chart. The project is in Visual Studio 2022 using ASP.NET Core 6 MVC.

This is the code for making the PDF by Rotativa:

return new ViewAsPdf("PrintPDF", result)
           {
               CustomSwitches = "--enable-javascript --debug-javascript --no-stop-slow-scripts --javascript-delay 10000",
               IsJavaScriptDisabled = false,
               FileName ="result.pdf",
           };

This is the code I use for making the chart

        var BeforeWorkshop = [];

        @if(Model.ResultCategoriesDtos.Count>0)
        {
            foreach(var item in Model.ResultCategoriesDtos)
            {
                @:BeforeWorkshop.push(@item.Answer3_1);
            }
        }

         var RadarChart = document.getElementById('radarchart').getContext('2d');
        var chart = new Chart(RadarChart, {
            type: 'radar',

            data: {
                labels: labels
                datasets: [{
                    label: "First",
                    data: BeforeWorkshop,
                    fill: true,
                    backgroundColor: 'rgba(255, 99, 132, 0.2)',
                    borderColor: 'rgb(255, 99, 255)',
                    pointBackgroundColor: 'rgb(255, 99, 132)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgb(255, 99, 132)',

                }
                ]
            },

            // Configuration options
            options: {
                tooltips: {
                    callbacks: {
                        label: function (tooltipItem, data) {
                            return data.datasets[tooltipItem.datasetIndex].label + ": " + tooltipItem.yLabel;
                        }
                    }
                }
            }
        });

I increased the delay time for Rotativa to javascript to be executed , but no success. the element which displays the javascript output is empty in PDF.

How can I get Rotativa.AspNetCore to work with Javascript code and convert it to PDF too?


问:
Unable to verify user token stored in cookie in MERN app
I am trying to verify a logged In user token in my MERN. However, I am getting "undefined" on client-side as API response.

When I hit the endpoint http://127.0.0.1:1000/api/v1/users/login in postman to login a user and this endpoint http://127.0.0.1:1000/api/v1/users/verify to verify a user's token, the token is returned.

But when I do the same in my react app, the token returns undefined. I have spent hours debugging it but unable to figure it out.

Please I need help.

Here is my React (client side) code:

    axios.defaults.withCredentials = true;

    function Welcome() {
      const [user, setUser] = useState("");
      const sendRequest = async () => {
        const res = await axios
          .get("http://127.0.0.1:1000/api/v1/users/verify", {
            withCredentials: true,
          })
          .catch((err) => console.log(err));
        const data = await res.data;
        return data;
      };
      React.useEffect(() => {
        sendRequest().then((response) => console.log(response.data));
      }, []);

      return
Welcome
;
    }
```
<p>Here is my login endpoint.</p>
<pre class="lang-js prettyprint-override"><code>        exports.loginUser = async (req, res) => {
          const { name, password } = req.body;

          let existingUser;
          try {
            existingUser = await User.findOne({ name: name });
          } catch (err) {
            return new Error(err);
          }
          if (!existingUser) {
            return res.status(400).json({ status: "fail", message: "user not found" });
          }

          const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
          if (!isPasswordCorrect) {
            return res
              .status(400)
              .json({ status: "fail", message: "invalid email or password" });
          }
          const token = jwt.sign({ id: existingUser._id }, process.env.JWT_SECRET, {
            expiresIn: process.env.JWT_EXPIRES_IN,
          });

          res.cookie("jwt", token, {
            path: "/",
            expires: new Date(Date.now() + 1000 * 70),
            httpOnly: true,
            sameSite: "lax",
          });

          return res
            .status(200)
            .json({ message: "Succesfully loggedIn", user: existingUser, token });
        };

</code>```

Here is my verifyToken endpoint

     exports.verifyToken = (req, res, next) => {
       const cookies = req.headers.cookie;
       const token = cookies.split("=")[1];
         if (!token) {
        res.status(404).json({ message: "no token found" });
      }

          jwt.verify(String(token), process.env.JWT_SECRET, (err, user) => {
            if (err) {
              return res.status(400).json({ message: "Invalid token" });
            }

            req.id = user.id;
          });
          next();
        };

```
<p>router.route("/verify").get(verifyToken, getUser);//endpoint</p>
```exports.getUser = async (req, res, next) => {
  const userId = req.id;
  let user;
  try {
    user = await User.findById(userId, "-password");
  } catch (err) {
    return new Error(err);
  }

  if (!user) {
    return res.status(404).json({ status: "fail", message: "user not found" });
  }

  return res.status(200).json({ user });
};
```

Body:
I am trying to verify a logged In user token in my MERN. However, I am getting "undefined" on client-side as API response.

When I hit the endpoint http://127.0.0.1:1000/api/v1/users/login in postman to login a user and this endpoint http://127.0.0.1:1000/api/v1/users/verify to verify a user's token, the token is returned.

But when I do the same in my react app, the token returns undefined. I have spent hours debugging it but unable to figure it out.

Please I need help.

Here is my React (client side) code:

    axios.defaults.withCredentials = true;

    function Welcome() {
      const [user, setUser] = useState("");
      const sendRequest = async () => {
        const res = await axios
          .get("http://127.0.0.1:1000/api/v1/users/verify", {
            withCredentials: true,
          })
          .catch((err) => console.log(err));
        const data = await res.data;
        return data;
      };
      React.useEffect(() => {
        sendRequest().then((response) => console.log(response.data));
      }, []);

      return
Welcome
;
    }

Here is my login endpoint.

        exports.loginUser = async (req, res) => {
          const { name, password } = req.body;

          let existingUser;
          try {
            existingUser = await User.findOne({ name: name });
          } catch (err) {
            return new Error(err);
          }
          if (!existingUser) {
            return res.status(400).json({ status: "fail", message: "user not found" });
          }

          const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
          if (!isPasswordCorrect) {
            return res
              .status(400)
              .json({ status: "fail", message: "invalid email or password" });
          }
          const token = jwt.sign({ id: existingUser._id }, process.env.JWT_SECRET, {
            expiresIn: process.env.JWT_EXPIRES_IN,
          });

          res.cookie("jwt", token, {
            path: "/",
            expires: new Date(Date.now() + 1000 * 70),
            httpOnly: true,
            sameSite: "lax",
          });

          return res
            .status(200)
            .json({ message: "Succesfully loggedIn", user: existingUser, token });
        };

Here is my verifyToken endpoint

     exports.verifyToken = (req, res, next) => {
       const cookies = req.headers.cookie;
       const token = cookies.split("=")[1];
         if (!token) {
        res.status(404).json({ message: "no token found" });
      }

          jwt.verify(String(token), process.env.JWT_SECRET, (err, user) => {
            if (err) {
              return res.status(400).json({ message: "Invalid token" });
            }

            req.id = user.id;
          });
          next();
        };

router.route("/verify").get(verifyToken, getUser);//endpoint

exports.getUser = async (req, res, next) => {
  const userId = req.id;
  let user;
  try {
    user = await User.findById(userId, "-password");
  } catch (err) {
    return new Error(err);
  }

  if (!user) {
    return res.status(404).json({ status: "fail", message: "user not found" });
  }

  return res.status(200).json({ user });
};


问:
How to check for the existence of a queue using rabbitmq-c?
I am trying to use rabbitmq-c to write a program that inserts messages into a queue that already exists. The queue should have already been created by a different process. If the queue does not exist it should report an error. The program takes the name of the queue as a commandline argument. I have seen examples of the usage of the function die_on_amqp_error, for example

```<code>amqp_channel_open(conn, 1);
die_on_amqp_error(amqp_get_rpc_reply(conn), "error in opening channel");
</code>```

Can this same function be used with amqp_basic_publish ? For example

```<code>amqp_basic_publish(conn, 1, amqp_cstring_bytes("amq.direct"), amqp_cstring_bytes(queue), 0, 0, &props, amqp_cstring_bytes(messagebody));
die_on_amqp_error(amqp_get_rpc_reply(conn), "error in publishing message");
</code>```

I am not able to find the documentation of die_on_amqp_error here
https://alanxz.github.io/rabbitmq-c/docs/0.2/index.html

Has this function been deprecated?

Body:
I am trying to use rabbitmq-c to write a program that inserts messages into a queue that already exists. The queue should have already been created by a different process. If the queue does not exist it should report an error. The program takes the name of the queue as a commandline argument. I have seen examples of the usage of the function die_on_amqp_error, for example

amqp_channel_open(conn, 1);
die_on_amqp_error(amqp_get_rpc_reply(conn), "error in opening channel");

Can this same function be used with amqp_basic_publish ? For example

amqp_basic_publish(conn, 1, amqp_cstring_bytes("amq.direct"), amqp_cstring_bytes(queue), 0, 0, &props, amqp_cstring_bytes(messagebody));
die_on_amqp_error(amqp_get_rpc_reply(conn), "error in publishing message");

I am not able to find the documentation of die_on_amqp_error here
https://alanxz.github.io/rabbitmq-c/docs/0.2/index.html

Has this function been deprecated?


问:
DllNotFoundException: Unable to load DLL 'pocketsphinx': The specified module could not be found
I am new at unity and my question may be simple, but I have a problem with .so files. I am using pocketsphinx and it needs 2 dll to work:  'pocketsphinx', 'sphinxbase'. I created same .so files for android. It works fine in Editor, but when I try to run it on Android logcat displays this error:

DllNotFoundException: Unable to load DLL 'pocketsphinx': The specified
module could not be found. Path to .so files: C:\unity\My
project\Assets\Plugins\Android\Libs\ARMv7

I tried to move files there:

```<code>C:\unity\My project\Assets\UnitySphinx\Plugins\Android\Libs\ARMv7
</code>```

It doesn't work

I apologize for any mistakes, inaccuracies and my English is not my native language

Body:
I am new at unity and my question may be simple, but I have a problem with .so files. I am using pocketsphinx and it needs 2 dll to work:  'pocketsphinx', 'sphinxbase'. I created same .so files for android. It works fine in Editor, but when I try to run it on Android logcat displays this error:

DllNotFoundException: Unable to load DLL 'pocketsphinx': The specified
module could not be found. Path to .so files: C:\unity\My
project\Assets\Plugins\Android\Libs\ARMv7

I tried to move files there:

C:\unity\My project\Assets\UnitySphinx\Plugins\Android\Libs\ARMv7

It doesn't work

I apologize for any mistakes, inaccuracies and my English is not my native language


问:
firestore not creating document with setDoc
When i add new user on my firebase database, it is created successfully on authentication and his profil picture is added successfully on the storage. The successuful toast is appearing. But the document with his informations is not created. i'm using the setDoc method to create de document.

It's a react app.

Help me please

firebase.config.js

```<code>import { initializeApp } from "firebase/app";

import { getAuth } from 'firebase/auth'
import { getStorage } from 'firebase/storage'
import { getFirestore } from 'firebase/firestore'

const firebaseConfig = {
   apiKey: "AIzaSyCsnZPoO6LIhvXwxjKkJe60AvmkgNqYhqM",
   authDomain: "le-prof-e863b.firebaseapp.com",
   projectId: "le-prof-e863b",
   storageBucket: "le-prof-e863b.appspot.com",
   messagingSenderId: "433335960615",
   appId: "1:433335960615:web:650aa77f403efff66f3a02",
   measurementId: "G-6N2HDEQVXV"
 };

 // Initialize Firebase
 const app = initializeApp(firebaseConfig);

 export const auth = getAuth(app)
 export const db = getFirestore(app)
 export const storage = getStorage(app)

 export default app
</code>```

Signup.jsx

```<code>import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { setDoc, doc } from 'firebase/firestore';

import { auth } from '../../firebase.config'
import { storage } from '../../firebase.config';
import { db } from '../../firebase.config';

const userCredential = await createUserWithEmailAndPassword(auth, email, password)

  const user = userCredential.user

  const storageRef = ref(storage, `images/${username}`)
  const uploadTask = uploadBytesResumable(storageRef, file)

  uploadTask.on((error)=>{
    toast.error(error.message)
  },()=>{
    getDownloadURL(uploadTask.snapshot.ref).then(async(downloadURL)=>{

      // update user profile
      await updateProfile(user, {
        displayName: username,
        photoURL: downloadURL
      })

      // store user data in firestore database
      await setDoc(doc(db, 'users', user.uid), {
        uid: user.uid,
        displayName: username,
        phone,
        email,
        sex: userSex,
        photoURL: downloadURL
      })
    })
  })

  toast.success('Account created')
  setLoading(false)

} catch (error) {
  setLoading(false)
  toast.error('Something went wrong')
}
}
</code>```

Body:
When i add new user on my firebase database, it is created successfully on authentication and his profil picture is added successfully on the storage. The successuful toast is appearing. But the document with his informations is not created. i'm using the setDoc method to create de document.

It's a react app.

Help me please

firebase.config.js

import { initializeApp } from "firebase/app";

import { getAuth } from 'firebase/auth'
import { getStorage } from 'firebase/storage'
import { getFirestore } from 'firebase/firestore'

const firebaseConfig = {
   apiKey: "AIzaSyCsnZPoO6LIhvXwxjKkJe60AvmkgNqYhqM",
   authDomain: "le-prof-e863b.firebaseapp.com",
   projectId: "le-prof-e863b",
   storageBucket: "le-prof-e863b.appspot.com",
   messagingSenderId: "433335960615",
   appId: "1:433335960615:web:650aa77f403efff66f3a02",
   measurementId: "G-6N2HDEQVXV"
 };

 // Initialize Firebase
 const app = initializeApp(firebaseConfig);

 export const auth = getAuth(app)
 export const db = getFirestore(app)
 export const storage = getStorage(app)

 export default app

Signup.jsx

import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { setDoc, doc } from 'firebase/firestore';

import { auth } from '../../firebase.config'
import { storage } from '../../firebase.config';
import { db } from '../../firebase.config';

const userCredential = await createUserWithEmailAndPassword(auth, email, password)

  const user = userCredential.user

  const storageRef = ref(storage, `images/${username}`)
  const uploadTask = uploadBytesResumable(storageRef, file)

  uploadTask.on((error)=>{
    toast.error(error.message)
  },()=>{
    getDownloadURL(uploadTask.snapshot.ref).then(async(downloadURL)=>{

      // update user profile
      await updateProfile(user, {
        displayName: username,
        photoURL: downloadURL
      })

      // store user data in firestore database
      await setDoc(doc(db, 'users', user.uid), {
        uid: user.uid,
        displayName: username,
        phone,
        email,
        sex: userSex,
        photoURL: downloadURL
      })
    })
  })

  toast.success('Account created')
  setLoading(false)

} catch (error) {
  setLoading(false)
  toast.error('Something went wrong')
}
}


问:
How to set number of elements to show in a CarouselSlider per page, using carousel_slider in flutter
I'm creating a vertical carousel slider using carousel_slider but there's a huge empty space between elements and I can't display the previous element on the screen. What is the best way to remove the empty space and also show the previous element.

My screen is set as follows

```<code>Column(
      children: [
        Container(
          margin: const EdgeInsets.fromLTRB(16, 16, 16, 16),
          child: TextField(
            controller: controller,

          ),
        ),
//Carousel built here
        Expanded(
                child: CarouselSlider.builder(
                  itemCount: cars.length,
                  itemBuilder: (context, index, pageViewIndex) => CarTile(
                    car: cars[index],
                    onpress: () => Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                CarDetailsScreen(car: cars[index]))),
                  ),
                  options: CarouselOptions(
                    scrollDirection: Axis.vertical,
                    enlargeCenterPage: true,
                  ),
                ),
              ),
      ],
    );
</code>```

CarTile code is as follows:

```<code>class CarTile extends StatelessWidget {
  final Car car;
  final VoidCallback onpress;
  const CarTile({super.key, required this.onpress, required this.car});

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return GestureDetector(
      onTap: onpress,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
        child: Column(
          children: [
            Image.network(
              height: 150,
              width: size.width,
              fit: BoxFit.fitWidth,
              car.image,
            ),
            const SizedBox(
              height: 5,
            ),
            Padding(
              padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
              child: Row(
                children: [
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.circular(5)),
                    child: Text(
                      car.features[0],
                      style: const TextStyle(fontWeight: FontWeight.w500),
                    ),
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.circular(5)),
                    child: Text(
                      car.features[1],
                      style: const TextStyle(fontWeight: FontWeight.w500),
                    ),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                Text(
                  '${car.brand} ${car.model}',
                  style: const TextStyle(fontWeight: FontWeight.w900),
                ),
                const Spacer(),
                Text(
                  'Tsh. ${NumberFormat.decimalPattern().format(car.price)} / hr',
                  style: const TextStyle(fontWeight: FontWeight.w900),
                ),
              ],
            ),
            Align(alignment: Alignment.centerLeft, child: Text('${car.year}'))
          ],
        ),
      ),
    );
  }
}
</code>```

And this is my current results

Body:
I'm creating a vertical carousel slider using carousel_slider but there's a huge empty space between elements and I can't display the previous element on the screen. What is the best way to remove the empty space and also show the previous element.

My screen is set as follows

Column(
      children: [
        Container(
          margin: const EdgeInsets.fromLTRB(16, 16, 16, 16),
          child: TextField(
            controller: controller,

          ),
        ),
//Carousel built here
        Expanded(
                child: CarouselSlider.builder(
                  itemCount: cars.length,
                  itemBuilder: (context, index, pageViewIndex) => CarTile(
                    car: cars[index],
                    onpress: () => Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                CarDetailsScreen(car: cars[index]))),
                  ),
                  options: CarouselOptions(
                    scrollDirection: Axis.vertical,
                    enlargeCenterPage: true,
                  ),
                ),
              ),
      ],
    );

CarTile code is as follows:

class CarTile extends StatelessWidget {
  final Car car;
  final VoidCallback onpress;
  const CarTile({super.key, required this.onpress, required this.car});

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return GestureDetector(
      onTap: onpress,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
        child: Column(
          children: [
            Image.network(
              height: 150,
              width: size.width,
              fit: BoxFit.fitWidth,
              car.image,
            ),
            const SizedBox(
              height: 5,
            ),
            Padding(
              padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
              child: Row(
                children: [
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.circular(5)),
                    child: Text(
                      car.features[0],
                      style: const TextStyle(fontWeight: FontWeight.w500),
                    ),
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.circular(5)),
                    child: Text(
                      car.features[1],
                      style: const TextStyle(fontWeight: FontWeight.w500),
                    ),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                Text(
                  '${car.brand} ${car.model}',
                  style: const TextStyle(fontWeight: FontWeight.w900),
                ),
                const Spacer(),
                Text(
                  'Tsh. ${NumberFormat.decimalPattern().format(car.price)} / hr',
                  style: const TextStyle(fontWeight: FontWeight.w900),
                ),
              ],
            ),
            Align(alignment: Alignment.centerLeft, child: Text('${car.year}'))
          ],
        ),
      ),
    );
  }
}

And this is my current results


问:
statsmodels.tsa.x13.x13_arima_analysis & Change Specifications
I want to use "X-13ARIMA-SEATS Seasonal Adjustment Program" via Python. I know statsmodels.tsa.x13.x13_arima_analysis is the Python wrapper.

Using statsmodels, is it possible to provide the inputs (specification) files into the Seasonal adjustment procedure?

Eg, I want to add/drop certain outliers or regressors. How do I go about doing it in statsmodels?


问:
How do i use prototype.$loading in vue 3 and vuex application?
I am using Element-plus ui for this crud app. Which is build in laravel -8 and vue -3 But when ever i am trying to access prototype.$loading or $notify is is showing the error Cannot read properties of undefined (reading '$loading')
Now how i will do?
I am new in vue 3.

action.js

```<code>import axios from "axios";
import { createApp } from 'vue';

let loader = null;

function showLoader(text = "Loading") {

    loader = createApp.prototype.$loading({
        lock: true,
        text: text,
        spinner: 'el-icon-loading',
        background: 'rgb(255,255,255,0.85)',
    })
}

function hideLoader() {
    loader.close();
}

export const saveStudent = ({commit}, payload) => {
    let url = `/save-student`;

    showLoader('Saving Student Data');
    axios.post(url, payload)
        .then(res => {
            createApp.prototype.$notify({
                title: 'Success',
                message: 'Student Created Successfully',
                type: 'success'
            });
            hideLoader();
            window.location.href = "/students";
        })
}

</code>```

app.js

```<code>import './bootstrap';
import { createApp } from 'vue';
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import {store} from './store/store.js'
import axios from "axios";

const app = createApp({});

import StudentForm from './components/student/StudentForm.vue';
app.component('student-form-component', StudentForm);
app.config.globalProperties.$axios = axios;
app.use(ElementPlus);
app.use(store);

app.mount('#app');
</code>```

store.js

```<code>import {createStore} from "vuex";

import * as getters from './getters.js'
import * as mutations from './mutations.js'
import * as  actions from './actions.js'

export const store = createStore({
    modules: {},
    state: {},
    mutations,
    getters,
    actions,
})
</code>```

Body:
I am using Element-plus ui for this crud app. Which is build in laravel -8 and vue -3 But when ever i am trying to access prototype.$loading or $notify is is showing the error Cannot read properties of undefined (reading '$loading')
Now how i will do?
I am new in vue 3.

action.js

import axios from "axios";
import { createApp } from 'vue';

let loader = null;

function showLoader(text = "Loading") {

    loader = createApp.prototype.$loading({
        lock: true,
        text: text,
        spinner: 'el-icon-loading',
        background: 'rgb(255,255,255,0.85)',
    })
}

function hideLoader() {
    loader.close();
}

export const saveStudent = ({commit}, payload) => {
    let url = `/save-student`;

    showLoader('Saving Student Data');
    axios.post(url, payload)
        .then(res => {
            createApp.prototype.$notify({
                title: 'Success',
                message: 'Student Created Successfully',
                type: 'success'
            });
            hideLoader();
            window.location.href = "/students";
        })
}

app.js

import './bootstrap';
import { createApp } from 'vue';
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import {store} from './store/store.js'
import axios from "axios";

const app = createApp({});

import StudentForm from './components/student/StudentForm.vue';
app.component('student-form-component', StudentForm);
app.config.globalProperties.$axios = axios;
app.use(ElementPlus);
app.use(store);

app.mount('#app');

store.js

import {createStore} from "vuex";

import * as getters from './getters.js'
import * as mutations from './mutations.js'
import * as  actions from './actions.js'

export const store = createStore({
    modules: {},
    state: {},
    mutations,
    getters,
    actions,
})


问:
URLSession with URLCredential
I would like to get data from server, but credential (username, password. Not Basi Authentification) is necessary to get it. Therefore, I try to use URLSession with URLCredential as following:
https://developer.apple.com/documentation/foundation/url_loading_system/handling_an_authentication_challenge

However, I could not understand this document...
So could you tell me how to use URLSession with URLCredential?

I tried URLSession like:

```<code>    func startLoad() {
        let url = URL(string: "https://www.abcde-test-url.com/")!
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("client error: \(error.localizedDescription) \n")
                return
            }

            guard let data = data, let response = response as? HTTPURLResponse else {
                print("no data or no response")
                return
            }

            if response.statusCode == 200 {
                print(data)
            } else {
                print("error status code: \(response.statusCode)\n")
            }
        }
        task.resume()
    }
</code>```

But I couldn't understand the usage with URLCredential.

Title: URLSession with URLCredential

Body:
I would like to get data from server, but credential (username, password. Not Basi Authentification) is necessary to get it. Therefore, I try to use URLSession with URLCredential as following:
https://developer.apple.com/documentation/foundation/url_loading_system/handling_an_authentication_challenge

However, I could not understand this document...
So could you tell me how to use URLSession with URLCredential?

I tried URLSession like:

    func startLoad() {
        let url = URL(string: "https://www.abcde-test-url.com/")!
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("client error: \(error.localizedDescription) \n")
                return
            }

            guard let data = data, let response = response as? HTTPURLResponse else {
                print("no data or no response")
                return
            }

            if response.statusCode == 200 {
                print(data)
            } else {
                print("error status code: \(response.statusCode)\n")
            }
        }
        task.resume()
    }

But I couldn't understand the usage with URLCredential.


问:
Facebook "fb_dtsg" and "lsd" key. What are they and how can I get them?
I'm trying to create a Facebook Business data crawl website (REACT). Currently, I'm stuck at how to get business ad creation limit.

When tracking Network tabs of https://business.facebook.com/settings/info?business_id=48079066xxxxxxx. I notice there is only a POST request have the response of limit fields. However, this quite difficult to duplicate since int required a lot of 'unknown' fields

{ adAccountLimit: 3}
```
<p>Image of request has ad account limit creation</p>
<p>I found a new way to achieve the same response with API:</p>
<pre class="lang-json prettyprint-override"><code>https://business.facebook.com/business/adaccount/limits/?business_id=xxxxx&__a=1&fb_dtsg=xxxxx&lsd=xxxx
</code>```

But still, it required field fb_dtsg and lsd. I tried gg to search but no use. How can i get/generate it with client side or req from graph api ?

Body:
I'm trying to create a Facebook Business data crawl website (REACT). Currently, I'm stuck at how to get business ad creation limit.

When tracking Network tabs of https://business.facebook.com/settings/info?business_id=48079066xxxxxxx. I notice there is only a POST request have the response of limit fields. However, this quite difficult to duplicate since int required a lot of 'unknown' fields

{ adAccountLimit: 3}

Image of request has ad account limit creation

I found a new way to achieve the same response with API:

https://business.facebook.com/business/adaccount/limits/?business_id=xxxxx&__a=1&fb_dtsg=xxxxx&lsd=xxxx

But still, it required field fb_dtsg and lsd. I tried gg to search but no use. How can i get/generate it with client side or req from graph api ?


问:
Yajra Datatable export all the records
I am using yajra Datatable in laravel 9. I integrate their buttons like: copy, csv, excel, pdf, print.
When I want to export/print it just exports the records that are only visible to table (10 records).
But I want to export all the paginated records also. How can I do it? Can you give me any Solutions?

My Controller,

```<code>public function index(Request $request){
        if($request->ajax()){
            $data = YajraDataTable::select('id','name','email','phone')->get();
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){
                    $btn = '<a href="javascript:void(0)" class="btn btn-primary btn-sm">Edit</a>';
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
        return view('admin.yajra.index');
    }
</code>```

My Blade file,

```<code><script type="text/javascript">
        $(function () {
            var table = $('#user_datatable').DataTable({
                processing: true,
                serverSide: true,
                responsive: true,
                autoWidth:false,
                ajax: "{{ route('yajra.datatable') }}",
                columns: [
                    { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
                    {data: 'name', name: 'name'},
                    {data: 'email', name: 'email'},
                    {data: 'phone', name: 'phone'},
                    {data: 'action', name: 'action', orderable: false, searchable: false},
                ],
                dom: 'lBfrtip',
                buttons: [
                    { extend: 'copy',  exportOptions: { modifier: { page: 'all', search: 'none' } } },
                    { extend: 'excel', exportOptions: { modifier: { page: 'all', search: 'none' } } },
                    { extend: 'csv',   exportOptions: { modifier: { page: 'all', search: 'none' } } },
                    { extend: 'pdf',   exportOptions: { modifier: { page: 'all', search: 'none' } } },
                    { extend: 'print', exportOptions: { modifier: { page: 'all', search: 'none' } } },
                    { extend: 'colvis', exportOptions: { modifier: { page: 'all', search: 'none' } } },
                ],
                "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, 'All'] ]
            });
        });
    </script>
</code>```

Title: Yajra Datatable export all the records

Body:
I am using yajra Datatable in laravel 9. I integrate their buttons like: copy, csv, excel, pdf, print.
When I want to export/print it just exports the records that are only visible to table (10 records).
But I want to export all the paginated records also. How can I do it? Can you give me any Solutions?

My Controller,

public function index(Request $request){
        if($request->ajax()){
            $data = YajraDataTable::select('id','name','email','phone')->get();
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){
                    $btn = 'Edit';
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
        return view('admin.yajra.index');
    }

My Blade file,


问:
Create a dynamic form using dynamic SelectListItem dropdown lists in ASP.NET core
I am using ASP.NET core and I'm trying to create a dynamic filter form based on the input values I get from the form. If the user selects a certain value, the View is supposed to render a number of dropdown select options based on the inputs given.
I have a sample of dropdown lists already initialized in my controller as shown.

```<code>    public IActionResult DataFilter(){
        //these are SelectListItem lists with Text and Value
        ViewBag.studentDropdown = dropdownContent.StudentsDropdown();
        ViewBag.subjectDropdown = dropdownContent.SubjectDropdown();
        ViewBag.gradeDropdown = dropdownContent.GradeDropdown();
    return View();
    }
</code>```

The input field in the view would look like this

```<code>    <form ..>
    ....
        <select name="filter-field" class="form-control">
           <option value=1>Student report</option>
           <option value=2>Subject report</option>
           <option value=3>Grade report</option>
        </select>
        <button class="btn btn-info" type="submit">Get filters</button>
    </form
</code>```

How can I make it that if a user selects option 1, Student reports, the form looks like

```<code>    <div class="form-group col-md-4"><label class="control-label">Student list</label>
        <select name="students" class="form-control" asp-items="@(new SelectList(ViewBag.studentDropdown, "Value", "Text"))">
            <option value="">Select an option...</option
        </select>
    </div>
</code>```

If a user selects option 2 subject report, the resultant form looks like this

```<code>    <div class="form-group col-md-4"><label class="control-label">Student list Module</label>
        <select name="students" class="form-control" asp-items="@(new SelectList(ViewBag.studentDropdown, "Value", "Text"))">
            <option value="">Select an option...</option
        </select>
    </div>
    <div class="form-group col-md-4"><label class="control-label">Subject list</label>
        <select name="students" class="form-control" asp-items="@(new SelectList(ViewBag.subjectDropdown, "Value", "Text"))">
            <option value="">Select an option...</option
        </select>
    </div>
</code>```

There are many input fields with varied filter parameters so the number of select list items will vary.
I tried placing all the lists in one list and saving their indexes in the database so that when a value is selected from the filter field form, it retrieves the indexes as an array and loops through them, but it resulted in an error.

Body:
I am using ASP.NET core and I'm trying to create a dynamic filter form based on the input values I get from the form. If the user selects a certain value, the View is supposed to render a number of dropdown select options based on the inputs given.
I have a sample of dropdown lists already initialized in my controller as shown.

    public IActionResult DataFilter(){
        //these are SelectListItem lists with Text and Value
        ViewBag.studentDropdown = dropdownContent.StudentsDropdown();
        ViewBag.subjectDropdown = dropdownContent.SubjectDropdown();
        ViewBag.gradeDropdown = dropdownContent.GradeDropdown();
    return View();
    }

The input field in the view would look like this

    <form ..>
    ....
        <select name="filter-field" class="form-control">
           <option value=1>Student report</option>
           <option value=2>Subject report</option>
           <option value=3>Grade report</option>
        </select>
        <button class="btn btn-info" type="submit">Get filters</button>
    </form

How can I make it that if a user selects option 1, Student reports, the form looks like

Student list
        <select name="students" class="form-control" asp-items="@(new SelectList(ViewBag.studentDropdown, "Value", "Text"))">
            <option value="">Select an option...</option
        </select>

If a user selects option 2 subject report, the resultant form looks like this

Student list Module
        <select name="students" class="form-control" asp-items="@(new SelectList(ViewBag.studentDropdown, "Value", "Text"))">
            <option value="">Select an option...</option
        </select>

Subject list
        <select name="students" class="form-control" asp-items="@(new SelectList(ViewBag.subjectDropdown, "Value", "Text"))">
            <option value="">Select an option...</option
        </select>

There are many input fields with varied filter parameters so the number of select list items will vary.
I tried placing all the lists in one list and saving their indexes in the database so that when a value is selected from the filter field form, it retrieves the indexes as an array and loops through them, but it resulted in an error.


问:
Fill Image to max width of parent
I want the image to fill the max width of container, and have a specific height. I tried using ContentScale.FillWidth, but it still leaves some background (green).

```<code>@Preview(showBackground = true)
@Composable
fun testImg() {
    Card(modifier = Modifier.fillMaxWidth()) {
        Image(
            painter = painterResource(id = R.drawable.jwimage1),
            null,
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
                .background(Green),
            contentScale = ContentScale.FillWidth
        )
    }
}
</code>```

prefview fro testImg

I tried using different ContentScale, adding height specification, but they don't change the result.

Edit: Solved! It's really silly that I used a png image with two transparent strips on its sides :(

Title: Fill Image to max width of parent

Body:
I want the image to fill the max width of container, and have a specific height. I tried using ContentScale.FillWidth, but it still leaves some background (green).

@Preview(showBackground = true)
@Composable
fun testImg() {
    Card(modifier = Modifier.fillMaxWidth()) {
        Image(
            painter = painterResource(id = R.drawable.jwimage1),
            null,
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
                .background(Green),
            contentScale = ContentScale.FillWidth
        )
    }
}

prefview fro testImg

I tried using different ContentScale, adding height specification, but they don't change the result.

Edit: Solved! It's really silly that I used a png image with two transparent strips on its sides :(


问:
How to get intellisense working for boost.test with vscode on mac?
Has anyone got intellisense working for c++ boost.test with Visual Studio code?

boost is installed in /usr/local/Cellar/boost/1.80.0/include

Things have tried:

add the above path to c++ intellisense configuration as /usr/local/Cellar/boost/1.80.0/include/**

add -L /usr/local/Cellar/boost/1.80.0/include to compiler args in to c++ intellisense configuration

add -L /usr/local/Cellar/boost/1.80.0/include to compiler args in to tasks.json

add path to settings.json as browse path and/or include path

Not working so far.


问:
Nginx Adaptive bit rate streaming not playing on VLC player
i have installed Nginx, with adaptive bit rate playback feature on my Ubuntu server v20. i can stream to my server successfully from OBS. But my VLC player can't playback the source URL.

My OBS stream out url is as below

URL- rtmp://MYIP/streaming

Stream Key - test

When i am trying to play this adaptive bit rate video from my vlc player entering the url as below

http://MYIP:8080/live/test.m3u8

The vlc can't play the source. My nginx config file is as below

```<code>user www-data;
worker_processes auto;
worker_rlimit_nofile 8192;
pid /run/nginx.pid;
rtmp_auto_push on;

events {
    worker_connections 4096;
}

rtmp {
    server {
        listen 1935;
        chunk_size 4096;
        max_message 1M;

        application streaming {
            live on;

            exec ffmpeg -i rtmp://localhost/streaming/$name
              -c:a aac -b:a 32k  -c:v libx264 -b:v 128K -f flv rtmp://localhost/hls/$name_low
              -c:a aac -b:a 64k  -c:v libx264 -b:v 256k -f flv rtmp://localhost/hls/$name_mid
              -c:a aac -b:a 128k -c:v libx264 -b:v 512K -f flv rtmp://localhost/hls/$name_hi;
        }

        application hls {
            live on;
            hls on;
            hls_path /etc/nginx/live;
            hls_nested on;

            hls_fragment 6s;
            hls_playlist_length 30s;

            hls_variant _low BANDWIDTH=160000;
            hls_variant _mid BANDWIDTH=320000;
            hls_variant _hi  BANDWIDTH=640000;
        }
    }
}

http {
    server {
        listen 8080;
        root /etc/nginx;

        location /live {
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
            }
            add_header Cache-Control no-cache;
        }
    }
}
</code>```

Please point me what should be exact url for vlc player placyback.

Body:
i have installed Nginx, with adaptive bit rate playback feature on my Ubuntu server v20. i can stream to my server successfully from OBS. But my VLC player can't playback the source URL.

My OBS stream out url is as below

URL- rtmp://MYIP/streaming

Stream Key - test

When i am trying to play this adaptive bit rate video from my vlc player entering the url as below

http://MYIP:8080/live/test.m3u8

The vlc can't play the source. My nginx config file is as below

user www-data;
worker_processes auto;
worker_rlimit_nofile 8192;
pid /run/nginx.pid;
rtmp_auto_push on;

events {
    worker_connections 4096;
}

rtmp {
    server {
        listen 1935;
        chunk_size 4096;
        max_message 1M;

        application streaming {
            live on;

            exec ffmpeg -i rtmp://localhost/streaming/$name
              -c:a aac -b:a 32k  -c:v libx264 -b:v 128K -f flv rtmp://localhost/hls/$name_low
              -c:a aac -b:a 64k  -c:v libx264 -b:v 256k -f flv rtmp://localhost/hls/$name_mid
              -c:a aac -b:a 128k -c:v libx264 -b:v 512K -f flv rtmp://localhost/hls/$name_hi;
        }

        application hls {
            live on;
            hls on;
            hls_path /etc/nginx/live;
            hls_nested on;

            hls_fragment 6s;
            hls_playlist_length 30s;

            hls_variant _low BANDWIDTH=160000;
            hls_variant _mid BANDWIDTH=320000;
            hls_variant _hi  BANDWIDTH=640000;
        }
    }
}

http {
    server {
        listen 8080;
        root /etc/nginx;

        location /live {
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
            }
            add_header Cache-Control no-cache;
        }
    }
}

Please point me what should be exact url for vlc player placyback.


问:
why a flake.nix file prevent to nixos-rebuild
I'm trying to do this tutorial.

I've added these lines in /etc/nixos/configuration.nix

```<code>services.nginx.enable = true;
services.nginx.virtualHosts."test.local.cetacean.club" = {
     root = "/srv/http/test.local.cetacean.club";
};
</code>```

I've made these commands

```<code>sudo mkdir -p /srv/http/test.local.cetacean.club
sudo chown nixos:nginx /srv/http/test.local.cetacean.club
</code>```

I've defined these file /etc/nixos/flake.nix like this

```<code>{
  inputs = {
    nixpkgs.url = "nixpkgs/nixos-unstable";
  };

  outputs = { self, nixpkgs, ... }: {
    nixosConfigurations.nixos = nixpkgs.lib.nixosSystem {
      system = "x86_64-linux";
      modules = [
        ./configuration.nix

        # add things here
      ];
    };
  };
}
</code>```

the following command works. It means that my file is ok
sudo nix flake check /etc/nixos

but this command doesn't work

```<code>sudo nixos-rebuild switch
</code>```

I don't understand the problem . This command worked before the definition of /etc/nixos/flake.nix.  I don't understand why this prevent to rebuild /etc/nixos/configuration.nix.

Now the error message

>× systemd-sysctl.service - Apply Kernel Variables
     Loaded: loaded (/etc/systemd/system/systemd-sysctl.service; enabled; preset: enabled)
    Drop-In: /nix/store/9mnkvlaxvwlp3iw50mf2p91rm3simizr-system-units/systemd-sysctl.service.d
             └─overrides.conf
     Active: failed (Result: exit-code) since Sun 2022-12-25 08:26:30 UTC; 64ms ago
   Duration: 29min 7.255s
       Docs: man:systemd-sysctl.service(8)
             man:sysctl.d(5)
    Process: 10842 ExecStart=/nix/store/9rjdvhq7hnzwwhib8na2gmllsrh671xg-systemd-252.1/lib/systemd/systemd-sysctl (code=exited, status=243/CREDENTIALS)
   Main PID: 10842 (code=exited, status=243/CREDENTIALS)
         IP: 0B in, 0B out

>Dec 25 08:26:30 nixos systemd[1]: Starting Apply Kernel Variables...
Dec 25 08:26:30 nixos systemd[10842]: systemd-sysctl.service: Failed to set up credentials: Protocol error
Dec 25 08:26:30 nixos systemd[10842]: systemd-sysctl.service: Failed at step CREDENTIALS spawning /nix/store/9rjdvhq7hnzwwhib8na2gmllsrh671xg-systemd-252.1/lib/systemd/systemd-sysctl: Protocol error
Dec 25 08:26:30 nixos systemd[1]: systemd-sysctl.service: Main process exited, code=exited, status=243/CREDENTIALS
Dec 25 08:26:30 nixos systemd[1]: systemd-sysctl.service: Failed with result 'exit-code'.
Dec 25 08:26:30 nixos systemd[1]: Failed to start Apply Kernel Variables.

× systemd-tmpfiles-setup-dev.service - Create Static Device Nodes in /dev
     Loaded: loaded (/etc/systemd/system/systemd-tmpfiles-setup-dev.service; enabled; preset: enabled)
     Active: failed (Result: exit-code) since Sun 2022-12-25 08:26:30 UTC; 68ms ago
   Duration: 29min 7.256s
       Docs: man:tmpfiles.d(5)
             man:systemd-tmpfiles(8)
    Process: 10844 ExecStart=systemd-tmpfiles --prefix=/dev --create --boot (code=exited, status=243/CREDENTIALS)
   Main PID: 10844 (code=exited, status=243/CREDENTIALS)
         IP: 0B in, 0B out

>Dec 25 08:26:30 nixos systemd[1]: Starting Create Static Device Nodes in /dev...
Dec 25 08:26:30 nixos systemd[10844]: systemd-tmpfiles-setup-dev.service: Failed to set up credentials: Protocol error
Dec 25 08:26:30 nixos systemd[10844]: systemd-tmpfiles-setup-dev.service: Failed at step CREDENTIALS spawning systemd-tmpfiles: Protocol error
Dec 25 08:26:30 nixos systemd[1]: systemd-tmpfiles-setup-dev.service: Main process exited, code=exited, status=243/CREDENTIALS
Dec 25 08:26:30 nixos systemd[1]: systemd-tmpfiles-setup-dev.service: Failed with result 'exit-code'.
Dec 25 08:26:30 nixos systemd[1]: Failed to start Create Static Device Nodes in /dev.
warning: error(s) occurred while switching to the new configuration
```

Body:
I'm trying to do this tutorial.

I've added these lines in /etc/nixos/configuration.nix

services.nginx.enable = true;
services.nginx.virtualHosts."test.local.cetacean.club" = {
     root = "/srv/http/test.local.cetacean.club";
};

I've made these commands

sudo mkdir -p /srv/http/test.local.cetacean.club
sudo chown nixos:nginx /srv/http/test.local.cetacean.club

I've defined these file /etc/nixos/flake.nix like this

{
  inputs = {
    nixpkgs.url = "nixpkgs/nixos-unstable";
  };

  outputs = { self, nixpkgs, ... }: {
    nixosConfigurations.nixos = nixpkgs.lib.nixosSystem {
      system = "x86_64-linux";
      modules = [
        ./configuration.nix

        # add things here
      ];
    };
  };
}

the following command works. It means that my file is ok
sudo nix flake check /etc/nixos

but this command doesn't work

sudo nixos-rebuild switch

I don't understand the problem . This command worked before the definition of /etc/nixos/flake.nix.  I don't understand why this prevent to rebuild /etc/nixos/configuration.nix.

Now the error message

>× systemd-sysctl.service - Apply Kernel Variables
     Loaded: loaded (/etc/systemd/system/systemd-sysctl.service; enabled; preset: enabled)
    Drop-In: /nix/store/9mnkvlaxvwlp3iw50mf2p91rm3simizr-system-units/systemd-sysctl.service.d
             └─overrides.conf
     Active: failed (Result: exit-code) since Sun 2022-12-25 08:26:30 UTC; 64ms ago
   Duration: 29min 7.255s
       Docs: man:systemd-sysctl.service(8)
             man:sysctl.d(5)
    Process: 10842 ExecStart=/nix/store/9rjdvhq7hnzwwhib8na2gmllsrh671xg-systemd-252.1/lib/systemd/systemd-sysctl (code=exited, status=243/CREDENTIALS)
   Main PID: 10842 (code=exited, status=243/CREDENTIALS)
         IP: 0B in, 0B out

>Dec 25 08:26:30 nixos systemd[1]: Starting Apply Kernel Variables...
Dec 25 08:26:30 nixos systemd[10842]: systemd-sysctl.service: Failed to set up credentials: Protocol error
Dec 25 08:26:30 nixos systemd[10842]: systemd-sysctl.service: Failed at step CREDENTIALS spawning /nix/store/9rjdvhq7hnzwwhib8na2gmllsrh671xg-systemd-252.1/lib/systemd/systemd-sysctl: Protocol error
Dec 25 08:26:30 nixos systemd[1]: systemd-sysctl.service: Main process exited, code=exited, status=243/CREDENTIALS
Dec 25 08:26:30 nixos systemd[1]: systemd-sysctl.service: Failed with result 'exit-code'.
Dec 25 08:26:30 nixos systemd[1]: Failed to start Apply Kernel Variables.

× systemd-tmpfiles-setup-dev.service - Create Static Device Nodes in /dev
     Loaded: loaded (/etc/systemd/system/systemd-tmpfiles-setup-dev.service; enabled; preset: enabled)
     Active: failed (Result: exit-code) since Sun 2022-12-25 08:26:30 UTC; 68ms ago
   Duration: 29min 7.256s
       Docs: man:tmpfiles.d(5)
             man:systemd-tmpfiles(8)
    Process: 10844 ExecStart=systemd-tmpfiles --prefix=/dev --create --boot (code=exited, status=243/CREDENTIALS)
   Main PID: 10844 (code=exited, status=243/CREDENTIALS)
         IP: 0B in, 0B out

>Dec 25 08:26:30 nixos systemd[1]: Starting Create Static Device Nodes in /dev...
Dec 25 08:26:30 nixos systemd[10844]: systemd-tmpfiles-setup-dev.service: Failed to set up credentials: Protocol error
Dec 25 08:26:30 nixos systemd[10844]: systemd-tmpfiles-setup-dev.service: Failed at step CREDENTIALS spawning systemd-tmpfiles: Protocol error
Dec 25 08:26:30 nixos systemd[1]: systemd-tmpfiles-setup-dev.service: Main process exited, code=exited, status=243/CREDENTIALS
Dec 25 08:26:30 nixos systemd[1]: systemd-tmpfiles-setup-dev.service: Failed with result 'exit-code'.
Dec 25 08:26:30 nixos systemd[1]: Failed to start Create Static Device Nodes in /dev.
warning: error(s) occurred while switching to the new configuration


问:
I installed mongodb and I want to connect it to next and I got error 500
This is the error on my screen
This is my console

this my address mongo :

```<code>MONGODB_URI= mongodb://localhost:27017/sinema
</code>```

this page util/mongodb.js
`

```<code>import mongoose from 'mongoose';
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
  throw new Error("Your mongodb uri is not defined!");
}
let cached = global.mongoose;
if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}
export async function connectToDatabase() {
  if (cached.conn) {
    return cached.conn;
  }
  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      bufferCommands:false,
      bufferMaxWntries: 0 ,
      useFindAndModify: false,
      useCreateIndex: true
    };

    cached.promise = mongoose.connect(MONGODB_URI, opts).then((client) => {
      return client
    });
  }
  cached.conn = await cached.promise;

  return cached.conn;
}

</code>```

`

`
this my index page

```<code>
export async function getServerSideProps(context) {
  const client = await connectToDatabase();

  const isConnected = await client.connections[0].readyState;

  return {
    props: {
      isConnected,
    },
  };
}

</code>```

`

I tried version 5 and 6 and the addresses MONGODB_URI= mongodb://127.0.0.1:27017/sinema
And
mongodb://localhost:27017

I tried but nothing changed

Body:
This is the error on my screen
This is my console

this my address mongo :

MONGODB_URI= mongodb://localhost:27017/sinema

this page util/mongodb.js
`

import mongoose from 'mongoose';
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
  throw new Error("Your mongodb uri is not defined!");
}
let cached = global.mongoose;
if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}
export async function connectToDatabase() {
  if (cached.conn) {
    return cached.conn;
  }
  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      bufferCommands:false,
      bufferMaxWntries: 0 ,
      useFindAndModify: false,
      useCreateIndex: true
    };

    cached.promise = mongoose.connect(MONGODB_URI, opts).then((client) => {
      return client
    });
  }
  cached.conn = await cached.promise;

  return cached.conn;
}

`

`
this my index page

export async function getServerSideProps(context) {
  const client = await connectToDatabase();

  const isConnected = await client.connections[0].readyState;

  return {
    props: {
      isConnected,
    },
  };
}

`

I tried version 5 and 6 and the addresses MONGODB_URI= mongodb://127.0.0.1:27017/sinema
And
mongodb://localhost:27017

I tried but nothing changed


问:
How to create a SlotOfQImage in QT Rust?
I'm trying to define a custom QT Slot/Signal for passing a QImage.

I'm using qt_widgets crate which has many predefined slot types like SlotOfQIcon. However it doesn't have one for QImage. I've looked at the source code which is generated with this tool: https://github.com/rust-qt/ritual.

Is it possible to do this in regular Rust project without running complex multistage build involving code generation?

List of implemented slots for reference:

https://docs.rs/qt_widgets/0.3.0/x86_64-pc-windows-msvc/qt_widgets/

I've tried to copy paste generated code for other widgets and modify it, but it doesn't look like a right approach. I don't want to regenerate the whole library just for this case. Are there any simpler options?


问:
How to save some Polars dfs into one file for partial data request was avaliable
I want to save some Polars dataframes into one file, and next I want to request data from file with filter by timestamp (datetime) column. I don't need to take all the file in memory, but only filtered part.

I see, Polars API list has Feather/IPC and Parquet files that can do it in a theory, but I don't know how to read this files in Polars with a filter by data.

Before for Pandas I used hdf5 format and it was very clear, but I have not expirience with that new formats for me. Maybe you can help me how to make it most effective.