问:
Unable to send a file via an HTTP POST request because the file extension is incorrect for a Buffer retrieved from AWS S3
I am in a Node.JS application. (Node version 14 if that matters)

Also I am using node-fetch (v2) to send my request.

I am trying to send a Send Fax Request to Documo.  The documentation can be found here: https://docs.documo.com/#da8dc725-8327-470c-83e4-34b40205cfa2.

As part of the request I want to send a pdf file that I have stored in S3.  I have the following code to accomplish that:

```<code>
const s3Object = await s3Client.send(
   new GetObjectCommand({
          Bucket: bucket,
          Key: key,
   })

const formData = new FormData();
formData.append("faxNumber", faxNumber);
formData.append("coverPage", "true");
formData.append("recipientName", recipientName);
formData.append("senderName", senderName);
formData.append("subject", subject);
formData.append("notes", note);
formData.append("webhookId", webhookId);
formData.append("attachments", s3Object.Body);

// ERROR: File extension 'pdf%22&x-id=getobject' is not allowed. Allowed formats: doc,docx,fodt,gif,htm,html,jpeg,jpg,odp,ods,odt,pdf,png,ppt,pptx,rtf,tif,tiff,txt,xls,xlsx,csv
const response = await fetch(`${BASE_DOCUMO_URL}/v1/faxes`, {
    method: "POST",
    headers: {
      Authorization: DEMO_API_KEY,
      ContentType: "multipart/form-data",
    },
    body: formData,
});
</code>```

I am getting the following error from Documo:

"File extension 'pdf%22&x-id=getobject' is not allowed. Allowed formats: doc,docx,fodt,gif,htm,html,jpeg,jpg,odp,ods,odt,pdf,png,ppt,pptx,rtf,tif,tiff,txt,xls,xlsx,csv"

From what I understand it looks like the GetObjectCommand from S3 is appending an x-id in the file stream which the Documo client is not happy with.  Ideally I don't want to recreate this file in memory and I just want to take the result from S3 to send through my POST request.  (Although I could be convinced to just do that if there is no better option or I don't need to worry about holding files in memory).

What are my options.  I've tried playing around with ResponseContentDisposition in GetObjectCommand to no avail

Body:
I am in a Node.JS application. (Node version 14 if that matters)

Also I am using node-fetch (v2) to send my request.

I am trying to send a Send Fax Request to Documo.  The documentation can be found here: https://docs.documo.com/#da8dc725-8327-470c-83e4-34b40205cfa2.

As part of the request I want to send a pdf file that I have stored in S3.  I have the following code to accomplish that:

const s3Object = await s3Client.send(
   new GetObjectCommand({
          Bucket: bucket,
          Key: key,
   })

const formData = new FormData();
formData.append("faxNumber", faxNumber);
formData.append("coverPage", "true");
formData.append("recipientName", recipientName);
formData.append("senderName", senderName);
formData.append("subject", subject);
formData.append("notes", note);
formData.append("webhookId", webhookId);
formData.append("attachments", s3Object.Body);

// ERROR: File extension 'pdf%22&x-id=getobject' is not allowed. Allowed formats: doc,docx,fodt,gif,htm,html,jpeg,jpg,odp,ods,odt,pdf,png,ppt,pptx,rtf,tif,tiff,txt,xls,xlsx,csv
const response = await fetch(`${BASE_DOCUMO_URL}/v1/faxes`, {
    method: "POST",
    headers: {
      Authorization: DEMO_API_KEY,
      ContentType: "multipart/form-data",
    },
    body: formData,
});

I am getting the following error from Documo:

"File extension 'pdf%22&x-id=getobject' is not allowed. Allowed formats: doc,docx,fodt,gif,htm,html,jpeg,jpg,odp,ods,odt,pdf,png,ppt,pptx,rtf,tif,tiff,txt,xls,xlsx,csv"

From what I understand it looks like the GetObjectCommand from S3 is appending an x-id in the file stream which the Documo client is not happy with.  Ideally I don't want to recreate this file in memory and I just want to take the result from S3 to send through my POST request.  (Although I could be convinced to just do that if there is no better option or I don't need to worry about holding files in memory).

What are my options.  I've tried playing around with ResponseContentDisposition in GetObjectCommand to no avail


来源: stackexchange

问:
Flutter/Supabase and object relational mapping?
I am considering the use of Supabase for my next Flutter project, but I can’t find any guidance on how to manage object to relational mapping.

Coming from a Java background I’m used to employing Hibernate and JPA for this area, but I can’t find an equivalent for Flutter.

For example, I have a Dart class ‘ExampleX’ which has two properties…

```<code>Class ExampleX {
   ExampleA a = ExampleA();
   ExampleB b = ExampleB();
}
</code>```

Any suggestions on how to handle this?

ContentLicense: CC BY-SA 4.0

Body:
I am considering the use of Supabase for my next Flutter project, but I can’t find any guidance on how to manage object to relational mapping.

Coming from a Java background I’m used to employing Hibernate and JPA for this area, but I can’t find an equivalent for Flutter.

For example, I have a Dart class ‘ExampleX’ which has two properties…

Class ExampleX {
   ExampleA a = ExampleA();
   ExampleB b = ExampleB();
}

Any suggestions on how to handle this?


问:
JwtAuthenticationToken is not being saved to HttpSessionSecurityContextRepository: spring authorization server 0.4.0, spring 5.7
I am using spring authorization server for oauth2 authentication, with resource server configuration for handling authentication outside of the server. My use case is as follows:

user makes a request to authorize end point

since the session is not authenticated, system caches the request and redirect the user to an external end point for authentication.

Once authentication is successful external system creates a short lived jwt token.

Jwt token is sent to authorization server, which it will validate and redirect the request to the saved previous request (which is the authorize end point call in step 1)

Since the jwt token was authenticated, I want the authorize call to succeed this time.

With spring version 5.6, the securitycontextholder was able to save the authentication, and any subsequent requests in the same session was able to use the jwtauthentication. Now since the transient check is added on the HttpSessionSecurityContextRepository.java, jwtauthentication is not saved between requests and my functionality is broken.

How can I handle this scenario?  I would like to use the jwt authentication from an external source in conjunction with spring authorization server. Any suggestions are appreciated.

I already have checked a similar question- JwtAuthenticationToken is not being saved to HttpSessionSecurityContextRepository after upgrading to 5.7 version which didnt have any inputs. I also have checked the github discussions for both spring 5.7 release and authorization server 0.4.0 release and was not able to find any guides.


问:
Mediawiki dumpBackup parameters
I fail to understand some options in the dumpBackup.php maintenance script of Mediawiki.

What is the effect of --include-files? In my test wiki, dumpBackup.php --current --include-files and dumpBackup.php --current both contain the pages of the File: namespace and I see no difference.

What is the effect of --uploads? In my test wiki I see that the xml file contains a tiny bit more of xml but, to me, it looks like this is all information which is there already as part of the File: page. What is the use of this flag?

When I add both --include-files and --uploads I get the next surprise. I actually expected the combined effect of both options, but what I get is the file content of the uploaded files and the upload record. Why did I not get the file contents when I used --include-files alone?

When I use only --include-files and --uploads but no --current I would have expected to get the content of the uploaded files and the upload record (and none of the other pages). However ,I get the warning no valid action specified and no further information at all

I am completely confused since I do not understand the logic behind all of this.

Title: Mediawiki dumpBackup parameters


问:
Is it possible to modify a running Windows app to change the GUI?
I realize this is a broad question, and depends on the framework/runtime in use, but in the example case I encountered an installer program that displays a License Agreement screen.  In order to proceed, the user must scroll through the agreement then check the Agree box.  In this case, the app is not loading a license agreement, so it's not possible to scroll to trigger the checkbox, so it's stuck on this screen.

Obviously the simple solution is to reach out the developer and request support, but I'm asking this question on a more general basis: is there a way to inject commands to an app's message handler/wndproc or query/change the app's config in a structured way to send direct commands and/or modify the GUI controls directly?

UPDATE: I just discovered CheatEngine (cheatengine.org) which appears to do exactly what I'm referring to: debug and manipulate running processes. NOTE: I have not yet confirmed whether the cheatengine executables are safe to download.


问:
XAMPP PHP Named Arguments gives " syntax error, unexpected ':', expecting ')'"
In an include file I declare a function

```<code>function patch_163_output_row_header(
    string $title,
    string $label,
    $help,
    bool $read_only=false,
    bool $required=false,
    string $label_cell
    )
</code>```

and when I compile this using the XAMPP PHP compiler (8.1.6 as far as I can tell) it is OK
In another file I try to use the function

```<code>    patch_163_output_row_header(
        title:$title,
        label:$label,
        help:$help,
        read_only:$read_only,
        required:$required,
        label_cell:$label_cell
        );

</code>```

when I try to compile I get the error mentioned above on the"title" line.

I can see no obvious issues - title does not seem to be a reserved word?

The strange thing then is that these two files are part of a website and when they are executed by the same XAMPP stack (presumably using the same PHP compiler?) there are no errors reported and they work.

Body:
In an include file I declare a function

function patch_163_output_row_header(
    string $title,
    string $label,
    $help,
    bool $read_only=false,
    bool $required=false,
    string $label_cell
    )

and when I compile this using the XAMPP PHP compiler (8.1.6 as far as I can tell) it is OK
In another file I try to use the function

    patch_163_output_row_header(
        title:$title,
        label:$label,
        help:$help,
        read_only:$read_only,
        required:$required,
        label_cell:$label_cell
        );

when I try to compile I get the error mentioned above on the"title" line.

I can see no obvious issues - title does not seem to be a reserved word?

The strange thing then is that these two files are part of a website and when they are executed by the same XAMPP stack (presumably using the same PHP compiler?) there are no errors reported and they work.


问:
big commerce Wish Lists not exposed on category template
I am trying to add wish list functionality to the Big Commerce category.html. I have exposed wish lists to the page using the below frontmatter, but customer.wishlists always returns null instead of a list of wish lists (my user has two created).

Frontmatter - category.html

---
category:
    shop_by_price: true
    products:
        limit: {{theme_settings.categorypage_products_per_page}}
customer:
    wishlists:
        limit: 10
---
```
<p>Context</p>
<pre class="lang-json prettyprint-override"><code>"customer": {
"id": 1,
"name": "user name",
"email": "user@email.co.uk",
"phone": "",
"store_credit": {},
"shipping_address": {},
"recently_viewed_products": null,
"wishlists": null,
</code>```

Anyone have ideas of why this isn't returning the correct data? Have I missed a step maybe?

Body:
I am trying to add wish list functionality to the Big Commerce category.html. I have exposed wish lists to the page using the below frontmatter, but customer.wishlists always returns null instead of a list of wish lists (my user has two created).

Frontmatter - category.html

---
category:
    shop_by_price: true
    products:
        limit: {{theme_settings.categorypage_products_per_page}}
customer:
    wishlists:
        limit: 10
---

Context

"customer": {
"id": 1,
"name": "user name",
"email": "user@email.co.uk",
"phone": "",
"store_credit": {},
"shipping_address": {},
"recently_viewed_products": null,
"wishlists": null,

Anyone have ideas of why this isn't returning the correct data? Have I missed a step maybe?


问:
Ilasm doesn't seem to include resources in dll
I'm using ildasm.exe to decompile a .dll (e.g. myfile.dll) into an .il file, a .res file and several .bmp, .png and some other files. The latter image and other files are probably not included into the .dll file when using ilasm myfile.il /resource:myfile.res /dll.

How to include the images and other resources?

Tried using:

ilasm myfile.il /resource:myfile.res /dll

Expected image resources to be included. Judging by the filesize, this probably didn't happen


问:
what does (0+n)/n mean in pyspark?
I am new to pyspark. I noticed that when I run my code in jupyter it shows something like this: (0 + n) / n
when n equals 1, code is running much faster. So my question is what can I do to make it small?
for example, now I am running a code and n equals 8 and it takes forever to run the code.

for example, now I am running a code and n equals 8 and it takes forever to run the code.

Title: what does (0+n)/n mean in pyspark?


问:
ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[TestComponent -> TestService]:
I am learning how to share a variable between two components with a service.

Component A (Service):

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataSharingService {

  private dataSource = new BehaviorSubject(false);
  data = this.dataSource.asObservable();

  constructor() { }

  setData(data: boolean) {
    this.dataSource.next(data);
  }
}
</code>```

Component B (component that receives value):

```<code>import { DataSharingService } from './data-sharing.service';

@Component({
  // component-specific configurations go here
})
export class Component1 {

  data: boolean;

  constructor(private dataSharingService: DataSharingService) {
    this.dataSharingService.data.subscribe(data => this.data = data);
  }
}
</code>```

Component C (sets the value):

```<code>import { DataSharingService } from './data-sharing.service';

@Component({
  // component-specific configurations go here
})
export class Component2 {

  constructor(private dataSharingService: DataSharingService) { }

  // use the service to set the value of the boolean variable
  someMethod() {
    this.dataSharingService.setData(true);
  }
}
</code>```

When compiling chrome shows error ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[TestComponent -> TestService]

How can I fix it?

Body:
I am learning how to share a variable between two components with a service.

Component A (Service):

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataSharingService {

  private dataSource = new BehaviorSubject(false);
  data = this.dataSource.asObservable();

  constructor() { }

  setData(data: boolean) {
    this.dataSource.next(data);
  }
}

Component B (component that receives value):

import { DataSharingService } from './data-sharing.service';

@Component({
  // component-specific configurations go here
})
export class Component1 {

  data: boolean;

  constructor(private dataSharingService: DataSharingService) {
    this.dataSharingService.data.subscribe(data => this.data = data);
  }
}

Component C (sets the value):

import { DataSharingService } from './data-sharing.service';

@Component({
  // component-specific configurations go here
})
export class Component2 {

  constructor(private dataSharingService: DataSharingService) { }

  // use the service to set the value of the boolean variable
  someMethod() {
    this.dataSharingService.setData(true);
  }
}

When compiling chrome shows error ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[TestComponent -> TestService]

How can I fix it?


问:
FlutterWebApp trouble local host
I have a flutter web app already compiled, I have it local because my DB is also local, when I have an internet connection the web works perfectly, but when I do not have internet does not load, some tips

Do I have to modify something in the code?

Title: FlutterWebApp trouble local host


问:
How to find a path to a specific object from a tree of objects?
I have a "recursive" class like so :

Class FabElement
{
     List<FabElement> FabElements = new List<FabElement>();

     public FabElement()
     {
     }
}

```
<p>Let say I create an object from this class and call it <code>FE</code>. At some point, <code>FE</code> will contain a list of <code>FabElement</code> and mutiple <code>FabElement</code> objects that are identical (reference).</p>
<p>Here's an example of that :</p>
```FE
     - FE_Children#1
          - FE_Children #4
          - **FE_Children #3** (Let's call it Element A)
     - FE_Children#2
     - **FE_Children #3** (Let's call it Element B)
```

As you can see, FE_Children #3 is at 2 places. I want it to be the same so if I change one, the other one also changes (it's a reference).

At some point, the user might decide to break that "link" and thus create a unique Element B (by doing a Deep Copy for example).

If a function to do receives Element B as a parameter, is there a way to differentiate Element A from Element B by the object itself or I need to pass a second parameter that would be it's full path within the FE object?

Thanks!

Body:
I have a "recursive" class like so :

Class FabElement
{
     List<FabElement> FabElements = new List<FabElement>();

     public FabElement()
     {
     }
}

Let say I create an object from this class and call it FE. At some point, FE will contain a list of FabElement and mutiple FabElement objects that are identical (reference).

Here's an example of that :

FE
     - FE_Children#1
          - FE_Children #4
          - **FE_Children #3** (Let's call it Element A)
     - FE_Children#2
     - **FE_Children #3** (Let's call it Element B)

As you can see, FE_Children #3 is at 2 places. I want it to be the same so if I change one, the other one also changes (it's a reference).

At some point, the user might decide to break that "link" and thus create a unique Element B (by doing a Deep Copy for example).

If a function to do receives Element B as a parameter, is there a way to differentiate Element A from Element B by the object itself or I need to pass a second parameter that would be it's full path within the FE object?

Thanks!


问:
Meaning of tags in vb.net project file
I'm working on a project (vbproj) and it has some tags I haven't seen before and googling doesn't lead me to anything useful (or I just have bad google-fu).

Anyway, does anyone know what these tags would be used for in a windows console application (outputtype is exes) or anywhere else for that matter?

```<code><DefaultClientScript>JScript</DefaultClientScript>
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
<DefaultTargetSchema>IE50</DefaultTargetSchema>
</code>```

Fairly sure they are just junk as far as the windows exe is concerned, but it'd be nice to change that to definitely junk.

Title: Meaning of tags in vb.net project file

Body:
I'm working on a project (vbproj) and it has some tags I haven't seen before and googling doesn't lead me to anything useful (or I just have bad google-fu).

Anyway, does anyone know what these tags would be used for in a windows console application (outputtype is exes) or anywhere else for that matter?

<DefaultClientScript>JScript</DefaultClientScript>
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
<DefaultTargetSchema>IE50</DefaultTargetSchema>

Fairly sure they are just junk as far as the windows exe is concerned, but it'd be nice to change that to definitely junk.


问:
Trying to create an axios http service using a generic http interface however linter says it expected 'this' to be used be a method
As per the title, I'm trying to create an axios http service which implements an http interface. Here is the short example:

```<code>import axios from 'axios';

interface IHttpService {
  get<T>(url: string, config?: object): Promise<T>;
}

class AxiosHttpService implements IHttpService {
  async get<T>(url: string, config: object = {}): Promise<T> {
    const response = await axios.get(url, config);
    return response.data;
  }
}

export default AxiosHttpService;
</code>```

However I get the following error by es-lint:

```<code>Expected 'this' to be used by class async method 'get'.
</code>```

Is there something inherintly wrong with how I'm implementing this?

Body:
As per the title, I'm trying to create an axios http service which implements an http interface. Here is the short example:

import axios from 'axios';

interface IHttpService {
  get<T>(url: string, config?: object): Promise<T>;
}

class AxiosHttpService implements IHttpService {
  async get<T>(url: string, config: object = {}): Promise<T> {
    const response = await axios.get(url, config);
    return response.data;
  }
}

export default AxiosHttpService;

However I get the following error by es-lint:

Expected 'this' to be used by class async method 'get'.

Is there something inherintly wrong with how I'm implementing this?


问:
When I write a string to an image field in SQL it gets saved in UTF-16 LE encoding and I need it to be UTF-8
I have about 1200 databases in SQL 2016 Enterprise in which documents are stored as BLOB's in image fields in the database. I migrated all the documents to our Document Management System and now I want to replace the files in the database with shortcuts to the corresponding files in the DMS. I tried it a few months ago and that went well. Now I run into an issue. When I use this command

```<code>convert(varbinary(max), <string value of shortcut>)
</code>```

It get's written to the field. When I try to open the shortcut I get an error. If I create the same shortcut from our DMS it is exactly the same except for the encoding. My binary = UTF-16 little endian and the DMS shortcut is encoded in UTF-8. The filesize has also doubled, which is logical since UTF-16 uses two bytes for every character. When I change the encoding in Notepad++ my shortcut works.

I need my blob to be encoded in UTF-8. That is possible, I can upload a shortcut to the system that the database uses and then it's stored correctly. I can't change the collation of the table or field because this is a vendor database. It's a pretty old-fashioned system. Who uses Blob's in the first place and if you do, why image and not varbinary?

I'm not much of a programmer so any help would be greatly appreciated.

I tried updating the database to the latest client version (not SQL just the application). That didn't change anything.
I tried nvarchar but that doesn't work on image fields.

Body:
I have about 1200 databases in SQL 2016 Enterprise in which documents are stored as BLOB's in image fields in the database. I migrated all the documents to our Document Management System and now I want to replace the files in the database with shortcuts to the corresponding files in the DMS. I tried it a few months ago and that went well. Now I run into an issue. When I use this command

convert(varbinary(max), <string value of shortcut>)

It get's written to the field. When I try to open the shortcut I get an error. If I create the same shortcut from our DMS it is exactly the same except for the encoding. My binary = UTF-16 little endian and the DMS shortcut is encoded in UTF-8. The filesize has also doubled, which is logical since UTF-16 uses two bytes for every character. When I change the encoding in Notepad++ my shortcut works.

I need my blob to be encoded in UTF-8. That is possible, I can upload a shortcut to the system that the database uses and then it's stored correctly. I can't change the collation of the table or field because this is a vendor database. It's a pretty old-fashioned system. Who uses Blob's in the first place and if you do, why image and not varbinary?

I'm not much of a programmer so any help would be greatly appreciated.

I tried updating the database to the latest client version (not SQL just the application). That didn't change anything.
I tried nvarchar but that doesn't work on image fields.


问:
Why is Firestore access so much slower in my Cloud Functions compared to browser?
I have a fairly small Firebase app that I'm using to collect some simple data from some friends and create statistics from it. My project setup is a simple webapp hosted in Firebase, Firestore, and Typescript Cloud Functions.

When I attempt to do anything inside the cloud functions that involves accessing the Firestore, queries will take upwards of 10–60 seconds for simple queries, and 1–4 minutes for anything accessing more than ~100 documents. This has been as persistent as it is frustrating, occurring in everything from callable HTTPS functions to pubsub cron jobs.

The craziest part, to me, is when I attempt to do the same functions on the website. A Cloud Function that takes minutes will barely take 100ms when running in the browser.

This leads me to believe that my logic and access patterns are correct (or at least reasonable), but there is an underlying limitation or a critical mistake that I made in my Cloud Functions setup that's causing everything to slow to a crawl.

My desire is to take this app and make it available to more people, but this issue is kneecapping me to a point where I can barely handle a few hundred kilobytes of data from a dozen users.

This problem has been plaguing every cloud function, but the following is the simplest function I have.

In it, I iterate over all users (~10) and grab all documents in their "Plays" collection (~500), then update the user. My project looks as such:

package.json

"dependencies": {
    "firebase": "^9.15.0",
    "firebase-admin": "^10.0.2",
    "firebase-functions": "^4.1.1",
    "node-fetch": "^2.6.1",
    "spotify-web-api-node": "^5.0.2",
    "typescript": "^4.5.4",
    "uuid": "^9.0.0"
}
```
<p><code>index.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import * as functions from "firebase-functions";
import { firestore } from "firebase-admin";
import { getApps, initializeApp } from "firebase-admin/app";
if (!getApps().length) {
    initializeApp();
}

import {recurringFunction, getUserTotals} from "./endpoints";

exports.cronFunc = functions.pubsub.schedule("0 * * * *").onRun(recurringFunction);
// 2 more like this

exports.getUserTotals = functions.https.onRequest(async (req, res) => {`
    res.status(200).send("Success");
    getUserTotals();
}
// 5 more like this
</code>```

endpoints.ts

export async function getUserTotals() {
    const users = await (await queries.getUsers()).docs;
    users.forEach(async (user) => {
        const allItems = await queries.getAllItems(user.id);
        const total_duration = allItems.docs.map((item) => item.duration).reduce((a, c) => a + c, 0);
        queries.updateUser(user.id, {
            total_duration,
            total_items: allItems.docs.length,
        });
    });
}
```
<p><code>queries.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import {getFirestore, QuerySnapshot} from "firebase-admin/firestore";
const db = getFirestore();

function getUsers() {
    return db.collection("User").get() as Promise<QuerySnapshot<User>>;
}

async function getAllItems(userId: string) {
    return db.collection("User").doc(userId).collection("Items").get() as Promise<QuerySnapshot<Item>>;
}

// 20-30 more functions to get/set/update/create/delete
</code>```

When I call /getUserTotals from the site, it'll look something like this in the Logs Explorer:

Timestamp
Column B

2023-01-05 00:00:00.000 MST
Function execution started

2023-01-05 00:00:03.000 MST
Function execution took 3000 ms, finished with status code: 200

2023-01-05 00:00:10.000 MST
getUsers: 7.000s

2023-01-05 00:00:10.000 MST
users.length 10

2023-01-05 00:02:00.000 MST
getAllItems user0 2:00:000 (m:ss.mmm)

2023-01-05 00:04:00.000 MST
getAllItems user1 4:00:000 (m:ss.mmm)

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

I have tried rewriting the function to be recursive, and that will at least keep the snapshots from timing out, but I can only run through ~4 users before I hit the 15-minute timeout. I've also run the function back to back, so it's not a cold start (though this seems way more extreme than the single-digit seconds that I've seen with most cold start complaints) with no difference.

When I run what is essentially the same getUserTotals function on the website, though, it takes ~500ms and returns 800 documents for this user I'm testing. The network call shows that I'm getting about 500 Kb of data when making the call.

Am I making some critical mistake? Is this a buggy library? I'm going to continue testing and update the thread with any answers I come up with

Edit: Converting the function.https.onRequest to function.https.onCall and returning the list of results seems to have cut down the time to about 20 seconds.

This is more tolerable, but still taking an order of magnitude longer than I would want, and also doesn't extend to the cron functions. But at least workable

Body:
I have a fairly small Firebase app that I'm using to collect some simple data from some friends and create statistics from it. My project setup is a simple webapp hosted in Firebase, Firestore, and Typescript Cloud Functions.

When I attempt to do anything inside the cloud functions that involves accessing the Firestore, queries will take upwards of 10–60 seconds for simple queries, and 1–4 minutes for anything accessing more than ~100 documents. This has been as persistent as it is frustrating, occurring in everything from callable HTTPS functions to pubsub cron jobs.

The craziest part, to me, is when I attempt to do the same functions on the website. A Cloud Function that takes minutes will barely take 100ms when running in the browser.

This leads me to believe that my logic and access patterns are correct (or at least reasonable), but there is an underlying limitation or a critical mistake that I made in my Cloud Functions setup that's causing everything to slow to a crawl.

My desire is to take this app and make it available to more people, but this issue is kneecapping me to a point where I can barely handle a few hundred kilobytes of data from a dozen users.

This problem has been plaguing every cloud function, but the following is the simplest function I have.

In it, I iterate over all users (~10) and grab all documents in their "Plays" collection (~500), then update the user. My project looks as such:

package.json

"dependencies": {
    "firebase": "^9.15.0",
    "firebase-admin": "^10.0.2",
    "firebase-functions": "^4.1.1",
    "node-fetch": "^2.6.1",
    "spotify-web-api-node": "^5.0.2",
    "typescript": "^4.5.4",
    "uuid": "^9.0.0"
}

index.ts

import * as functions from "firebase-functions";
import { firestore } from "firebase-admin";
import { getApps, initializeApp } from "firebase-admin/app";
if (!getApps().length) {
    initializeApp();
}

import {recurringFunction, getUserTotals} from "./endpoints";

exports.cronFunc = functions.pubsub.schedule("0 * * * *").onRun(recurringFunction);
// 2 more like this

exports.getUserTotals = functions.https.onRequest(async (req, res) => {`
    res.status(200).send("Success");
    getUserTotals();
}
// 5 more like this

endpoints.ts

export async function getUserTotals() {
    const users = await (await queries.getUsers()).docs;
    users.forEach(async (user) => {
        const allItems = await queries.getAllItems(user.id);
        const total_duration = allItems.docs.map((item) => item.duration).reduce((a, c) => a + c, 0);
        queries.updateUser(user.id, {
            total_duration,
            total_items: allItems.docs.length,
        });
    });
}

queries.ts

import {getFirestore, QuerySnapshot} from "firebase-admin/firestore";
const db = getFirestore();

function getUsers() {
    return db.collection("User").get() as Promise<QuerySnapshot<User>>;
}

async function getAllItems(userId: string) {
    return db.collection("User").doc(userId).collection("Items").get() as Promise<QuerySnapshot<Item>>;
}

// 20-30 more functions to get/set/update/create/delete

When I call /getUserTotals from the site, it'll look something like this in the Logs Explorer:

Timestamp
Column B

2023-01-05 00:00:00.000 MST
Function execution started

2023-01-05 00:00:03.000 MST
Function execution took 3000 ms, finished with status code: 200

2023-01-05 00:00:10.000 MST
getUsers: 7.000s

2023-01-05 00:00:10.000 MST
users.length 10

2023-01-05 00:02:00.000 MST
getAllItems user0 2:00:000 (m:ss.mmm)

2023-01-05 00:04:00.000 MST
getAllItems user1 4:00:000 (m:ss.mmm)

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

2023-01-05 00:06:00.000 MST
Exception from a finished function: Error: 9 FAILED_PRECONDITION: The requested snapshot version is too old.

I have tried rewriting the function to be recursive, and that will at least keep the snapshots from timing out, but I can only run through ~4 users before I hit the 15-minute timeout. I've also run the function back to back, so it's not a cold start (though this seems way more extreme than the single-digit seconds that I've seen with most cold start complaints) with no difference.

When I run what is essentially the same getUserTotals function on the website, though, it takes ~500ms and returns 800 documents for this user I'm testing. The network call shows that I'm getting about 500 Kb of data when making the call.

Am I making some critical mistake? Is this a buggy library? I'm going to continue testing and update the thread with any answers I come up with

Edit: Converting the function.https.onRequest to function.https.onCall and returning the list of results seems to have cut down the time to about 20 seconds.

This is more tolerable, but still taking an order of magnitude longer than I would want, and also doesn't extend to the cron functions. But at least workable


问:
Can a GCP project be disabled using an API?
Use Case : Need to disable a google project using an API .

Also wanted to know whether a project number or project id will help in doing that.

From the Cloud billing API I was able to execute the following command :
curl -X GET

-H "Authorization: Bearer $(gcloud auth print-access-token)"

-H "x-goog-user-project: project-id"

"https://billingbudgets.googleapis.com/v1/billingAccounts/billing-account-id/budgets/budget-id"

I was able to get the project number, however needed to know how to use this project number to disable a project or unlink it from Billing


问:
Why does the get function not work in Cypress?
I'm trying to set up tests with Cypress inside my React / TS app. I installed the package, and when I try to set up a test I get an error:

Test:

```<code>it("displays Text component", () => {
    cy.mount(<Text tag="h1" data-testid="Hello">Hello World</Text>)
    cy.get("[data-testid='Hello']").should("contain.text", "Hello")
})
</code>```

And the error:

```<code>Property 'get' does not exist on type 'typeof import("path/to/package")'.
</code>```

Why does this happen? Did I install something wrong?

Body:
I'm trying to set up tests with Cypress inside my React / TS app. I installed the package, and when I try to set up a test I get an error:

Test:

it("displays Text component", () => {
    cy.mount(<Text tag="h1" data-testid="Hello">Hello World</Text>)
    cy.get("[data-testid='Hello']").should("contain.text", "Hello")
})

And the error:

Property 'get' does not exist on type 'typeof import("path/to/package")'.

Why does this happen? Did I install something wrong?


问:
How to create a dataframe with subindexes in Pandas?
I'm looping over a dataframe using a list of inputs to get stocks returns. The input is a list of stock tickers.

My objective is to create a dataframe which contain different basketes or portfolios. I manage to create this big dataframe, but I want to be able to identify each different portfolio under this big dataframe. So if I can later retrieve data from certain portfolio and analyze the stocks under it.

So maybe some kind of multindexing?

returns_train
AAPL BTC SPY   UST

0.01 0.2 0.001 0.02
0.02 0.1 0.000 0.00
0.01 0.2 0.003 0.01

correlations_high
BTC SPY

UST AAPL

```<code>top_contracts = ['SPY', 'BTC']
portfolio_highs = []
for contract in top_contracts:

    returns = returns_train.loc[:, contract]
    portfolio = []
    correlated_returns = returns_train.loc[:, correlations_high[contract]]
    total_returns = correlated_returns.join(-returns, on=returns.index)
    portfolio.append(total_returns)
    portafolio_returns = pd.concat(portfolio, axis=1)
    portfolio_highs.append(portafolio_returns)

df = pd.concat(portfolio_highs, axis=1)
</code>```

My end result looks like this.

Time   AAPL SPY  UST  BTC

```<code>   0.01 0.001 0.02  0.2
   0.02 0.000 0.00  0.1
   0.01 0.003 0.01  0.2
</code>```

So i get the df which containts all the combinations of stocks of both portfolios (SPY and BTC). But I'd like to also be able to index so i can open either of both portfolios. Something like this.

SPY               BTC

Time   AAPL SPY  UST  BTC

```<code>   0.01 0.001 0.02  0.2
   0.02 0.000 0.00  0.1
   0.01 0.003 0.01  0.2
</code>```

I hope someone understands what I'm trying to do.
Cheers

Body:
I'm looping over a dataframe using a list of inputs to get stocks returns. The input is a list of stock tickers.

My objective is to create a dataframe which contain different basketes or portfolios. I manage to create this big dataframe, but I want to be able to identify each different portfolio under this big dataframe. So if I can later retrieve data from certain portfolio and analyze the stocks under it.

So maybe some kind of multindexing?

returns_train
AAPL BTC SPY   UST

0.01 0.2 0.001 0.02
0.02 0.1 0.000 0.00
0.01 0.2 0.003 0.01

correlations_high
BTC SPY

UST AAPL

top_contracts = ['SPY', 'BTC']
portfolio_highs = []
for contract in top_contracts:

    returns = returns_train.loc[:, contract]
    portfolio = []
    correlated_returns = returns_train.loc[:, correlations_high[contract]]
    total_returns = correlated_returns.join(-returns, on=returns.index)
    portfolio.append(total_returns)
    portafolio_returns = pd.concat(portfolio, axis=1)
    portfolio_highs.append(portafolio_returns)

df = pd.concat(portfolio_highs, axis=1)

My end result looks like this.

Time   AAPL SPY  UST  BTC

   0.01 0.001 0.02  0.2
   0.02 0.000 0.00  0.1
   0.01 0.003 0.01  0.2

So i get the df which containts all the combinations of stocks of both portfolios (SPY and BTC). But I'd like to also be able to index so i can open either of both portfolios. Something like this.

SPY               BTC

Time   AAPL SPY  UST  BTC

   0.01 0.001 0.02  0.2
   0.02 0.000 0.00  0.1
   0.01 0.003 0.01  0.2

I hope someone understands what I'm trying to do.
Cheers


问:
Using both b2clogin.com and custom domain with App service authentication
We have an Azure function secured using App Service authentication (Easyauth) for local user accounts in a B2C tenant using custom policies. The function is called directly from a mobile app (XF) and this all works fine.

Recently, I followed the instructions at https://learn.microsoft.com/en-us/azure/active-directory-b2c/custom-domain?pivots=b2c-custom-policy in order to add a custom domain to our B2C tenant in order to avoid having to use the ‘xxxx.b2clogin.com’ endpoint. Having configured the client app to use the custom endpoints, we can successfully acquire an access token using the MS authentication libraries.

However, when attempting to access the function, we’re seeing a 401 error returned to the client. It seems as though this is because the Idp is configured with an Issuer URL in the form https://xxxx.b2clogin.com/xxxx.onmicrosoft.com/v2.0/.well-known/openid-configuration?p={mySigninPolicy}

Indeed, if I change the Issuer URL to match the issuer claim in the token emitted by B2C, (which is now in the form https://mycustomdomain.com/11111111-1111-1111-1111-111111111111/v2.0/) everything seems to work fine.

We can’t force our users to upgrade to a version of the app which uses the new endpoints, so my question is if there's any way (ideally without code changes) that the App Service authentication can handle tokens with different issuer claims?


问:
Some of megasparkDiff libraries are not importing
I have cloned the MegaSparkDiff project from GitHub and just wanted to try it out. I use IntelliJ IDE, the project has sample examples and different libraries. Unfortunately, some  libraries are not getting imported

I have tried to reload maven, deleted this project, and re-cloned again, but I am getting the same problem, which these libraries/classes are not getting imported :
import org.finra.msd.sparkcompare.SparkCompare;import org.finra.msd.sparkfactory.SparkFactory;
import org.finra.msd.containers.AppleTable;import org.finra.msd.containers.DiffResult;
so, how can I resolve this issue?


问:
Dynamically add rtmp source to running pipeline using compositor
I have a very simple Gstreamer pipeline looking like this

uridecodebin -> compositor -> videoconvert -> autovideosink

I want to be able at any time to add a new uridecodebin on the compositor.
If I add the second source before the pipeline is running, it works fine, but if I delay the addition of the second source, pipeline gets stuck and I have tons of QoS events telling me frames are being dropped.

This issue does not occur if I only read non-live sources, but it happens with my RTMP streams, or if I mix live and non-live sources.

When sync=false is set on the sync, RTMP streams are played, but it does not work with non-live sources.

My assumption is that I am missing a step with time/clock/latency, but I don't know what.

Here is the code (in rust) used to add a new source :

fn connect_pad_added(src_pad: &gst::Pad, src: &gst::Element, compositor: &gst::Element) {
    println!("Received new pad {} from {}", src_pad.name(), src.name());

    let new_pad_caps = src_pad
        .current_caps()
        .expect("Failed to get caps of new pad.");
    let new_pad_struct = new_pad_caps
        .structure(0)
        .expect("Failed to get first structure of caps.");
    let new_pad_type = new_pad_struct.name();

    let is_video = new_pad_type.starts_with("video/x-raw");
    if !is_video {
        println!(
            "It has type {} which is not raw video. Ignoring.",
            new_pad_type
        );
        return;
    }

    println!("Created template");
    let sink_pad = compositor
        .request_pad_simple("sink_%u")
        .expect("Could not get sink pad from compositor");

    println!("Got pad");

    if sink_pad.is_linked() {
        println!("We are already linked. Ignoring.");
        return;
    }

    if sink_pad.name() == "sink_0" {
        sink_pad.set_property("width", 1920i32);
        sink_pad.set_property("height", 1080i32);
    } else {
        sink_pad.set_property("alpha", 0.8f64);
    }

    let res = src_pad.link(&sink_pad);
    if res.is_err() {
        println!("Type is {} but link failed.", new_pad_type);
    } else {
        println!("Link succeeded (type {}).", new_pad_type);
    }

}

fn add_new_element(pipeline: &gst::Pipeline, uri: &str) {
    println!("Adding new element");
    let source = gst::ElementFactory::make("uridecodebin")
        .property("uri", uri)
        .build()
        .unwrap();
    let compositor = pipeline.by_name("compositor").unwrap();
    pipeline.add(&source).unwrap();
    source.connect_pad_added(move |src, src_pad| {
        println!("Received new pad {} from {}", src_pad.name(), src.name());
        connect_pad_added(src_pad, src, &compositor);
    });

    source
        .set_state(gst::State::Paused)
        .expect("Unable to set the uridecodebin to the `Paused` state");

    println!("Added new element");
}
```


问:
Js app runs locally but Heroku Throws and error
I built an app that runs well on locally. But when I deploy on heroku it crashes and shows me this.

```<code>Error: Cannot find module './dist'
2023-01-06T22:40:19.130104+00:00 app[web.1]: Require stack:
2023-01-06T22:40:19.130104+00:00 app[web.1]: - /app/node_modules/optional-require/index.js
2023-01-06T22:40:19.130120+00:00 app[web.1]: - /app/node_modules/mongoose/node_modules/mongodb/lib/core/index.js
2023-01-06T22:40:19.130120+00:00 app[web.1]: - /app/node_modules/mongoose/node_modules/mongodb/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/index.js
2023-01-06T22:40:19.130122+00:00 app[web.1]: - /app/index.js
</code>```

My code is in this repo: https://github.com/Franttisekpetruv/Carelooker
Website is:https://dashboard.heroku.com/apps/calm-crag-33682

I understand that some modules. I re-install npm and it did nothing...
I am expecting my app to run, connect to atlas etc... since it runs locally I even paid $5 to heroku, was that also necessary?

Body:
I built an app that runs well on locally. But when I deploy on heroku it crashes and shows me this.

Error: Cannot find module './dist'
2023-01-06T22:40:19.130104+00:00 app[web.1]: Require stack:
2023-01-06T22:40:19.130104+00:00 app[web.1]: - /app/node_modules/optional-require/index.js
2023-01-06T22:40:19.130120+00:00 app[web.1]: - /app/node_modules/mongoose/node_modules/mongodb/lib/core/index.js
2023-01-06T22:40:19.130120+00:00 app[web.1]: - /app/node_modules/mongoose/node_modules/mongodb/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/index.js
2023-01-06T22:40:19.130122+00:00 app[web.1]: - /app/index.js

My code is in this repo: https://github.com/Franttisekpetruv/Carelooker
Website is:https://dashboard.heroku.com/apps/calm-crag-33682

I understand that some modules. I re-install npm and it did nothing...
I am expecting my app to run, connect to atlas etc... since it runs locally I even paid $5 to heroku, was that also necessary?


问:
How you import / drag & drop a PDF file info into excel cells
How you import / drag & drop a PDF file info into excel cells

I need the info from a PDF file - "408" and "2400550" to be dragged over into an excel file


问:
corrupted file when sending it via POST with reqwest
I'm trying to send a POST request to my server including a file. I can do that with curl following this example with no problems https://gokapi.readthedocs.io/en/latest/advanced.html#interacting-with-the-api, but I can't with Rust.

When I try to implement the request with Rust I have issues, namely the file is corrupted as if it was sent in the wrong way. I tried to get it working with this code,

fn upload(file: &String) -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::blocking::Client::new();
    let mut form = multipart::Form::new()
        .file("file", file)
        .unwrap()
        .text("allowedDownloads", "0")
        .text("expiryDays", "2")
        .text("password", "");
    let res = client
        .post("http://myserver.com/api/files/add")
        .header(ACCEPT, "application/json")
        .header("apikey", "secret")
        .header("Accept-Encoding", "gzip, deflate, br")
        .multipart(form)
        .send();
    let response_json = json::parse(&res.unwrap().text().unwrap()).unwrap();
    let id = &response_json["FileInfo"]["Id"];
    print!("http://myserver.com/downloadFile?id={}", id);
    Ok(())
}

```
<p>but the server receives a bad file, 7zip gives me this error.</p>
<p>tried doing the same script in python, and I got it working in 3 lines.</p>
<pre class="lang-py prettyprint-override"><code>import requests
files = {'file': ("1398608 Fractal Dreamers - Gardens Under a Spring Sky.osz", open("1398608 Fractal Dreamers - Gardens Under a Spring Sky.osz", "rb"), "application/octet-stream")}
request = requests.post("http://myserver/api/files/add", files=files, headers={'apikey': 'api'})
</code>```

the file uploaded from the python script works flawlessly, while the rust doesn't.
Any help is appreciated as I'm still a beginner with Rust.

I also did try Sending attachment with reqwest but I get
{"Result":"error","ErrorMessage":"multipart: NextPart: bufio: buffer full"}

EDIT: the issue looks like it's related to file (being the filename) including some strange characters? Test subject file was "1398608 Fractal Dreamers - Gardens Under a Spring Sky.osz", but changing it to "a.osz" made the issue disappear. I have no clue why and how is that

content of the zip is:
"Fractal Dreamers - Gardens Under a Spring Sky ([Crz]xz1z1z) [Vernal].osu"
"audio.mp3"

I get the error with the full name, but "1398608 Fractal Dreamers - Gardens Under a Spring Sky.zip" works as well. What's the issue with .osz?

Body:
I'm trying to send a POST request to my server including a file. I can do that with curl following this example with no problems https://gokapi.readthedocs.io/en/latest/advanced.html#interacting-with-the-api, but I can't with Rust.

When I try to implement the request with Rust I have issues, namely the file is corrupted as if it was sent in the wrong way. I tried to get it working with this code,

fn upload(file: &String) -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::blocking::Client::new();
    let mut form = multipart::Form::new()
        .file("file", file)
        .unwrap()
        .text("allowedDownloads", "0")
        .text("expiryDays", "2")
        .text("password", "");
    let res = client
        .post("http://myserver.com/api/files/add")
        .header(ACCEPT, "application/json")
        .header("apikey", "secret")
        .header("Accept-Encoding", "gzip, deflate, br")
        .multipart(form)
        .send();
    let response_json = json::parse(&res.unwrap().text().unwrap()).unwrap();
    let id = &response_json["FileInfo"]["Id"];
    print!("http://myserver.com/downloadFile?id={}", id);
    Ok(())
}

but the server receives a bad file, 7zip gives me this error.

tried doing the same script in python, and I got it working in 3 lines.

import requests
files = {'file': ("1398608 Fractal Dreamers - Gardens Under a Spring Sky.osz", open("1398608 Fractal Dreamers - Gardens Under a Spring Sky.osz", "rb"), "application/octet-stream")}
request = requests.post("http://myserver/api/files/add", files=files, headers={'apikey': 'api'})

the file uploaded from the python script works flawlessly, while the rust doesn't.
Any help is appreciated as I'm still a beginner with Rust.

I also did try Sending attachment with reqwest but I get
{"Result":"error","ErrorMessage":"multipart: NextPart: bufio: buffer full"}

EDIT: the issue looks like it's related to file (being the filename) including some strange characters? Test subject file was "1398608 Fractal Dreamers - Gardens Under a Spring Sky.osz", but changing it to "a.osz" made the issue disappear. I have no clue why and how is that

content of the zip is:
"Fractal Dreamers - Gardens Under a Spring Sky ([Crz]xz1z1z) [Vernal].osu"
"audio.mp3"

I get the error with the full name, but "1398608 Fractal Dreamers - Gardens Under a Spring Sky.zip" works as well. What's the issue with .osz?


问:
How to mount a VHD with only one partition?
I'm developing a project and I need the code in C# to assemble a vhd, and assign a letter to it. During the process of creating the vhd, I managed to do it via cmd by diskpart, but at that time I didn't assign a letter to it because the intention is to give the option to the user which letter he wants to mount. But now to mount I have a problem because I have no way of predicting which volume it will be mounted on. PS: The VHD only have and will only have one partition.

VHD Creation Code:

```<code>process.StandardInput.WriteLine("create vdisk file=" + Path.GetTempPath() + "storagedisk.vhd" + " maximum=" + size + " type=fixed");
process.StandardInput.WriteLine("select vdisk file=" + Path.GetTempPath() + "storagedisk.vhd");
process.StandardInput.WriteLine("attach vdisk");
process.StandardInput.WriteLine("convert gpt");
process.StandardInput.WriteLine("create partition primary");
process.StandardInput.WriteLine("format fs=ntfs label=\"ProSafe Disk\" quick");
process.StandardInput.WriteLine("detach vdisk");
process.StandardInput.WriteLine("exit");
</code>```

Body:
I'm developing a project and I need the code in C# to assemble a vhd, and assign a letter to it. During the process of creating the vhd, I managed to do it via cmd by diskpart, but at that time I didn't assign a letter to it because the intention is to give the option to the user which letter he wants to mount. But now to mount I have a problem because I have no way of predicting which volume it will be mounted on. PS: The VHD only have and will only have one partition.

VHD Creation Code:

process.StandardInput.WriteLine("create vdisk file=" + Path.GetTempPath() + "storagedisk.vhd" + " maximum=" + size + " type=fixed");
process.StandardInput.WriteLine("select vdisk file=" + Path.GetTempPath() + "storagedisk.vhd");
process.StandardInput.WriteLine("attach vdisk");
process.StandardInput.WriteLine("convert gpt");
process.StandardInput.WriteLine("create partition primary");
process.StandardInput.WriteLine("format fs=ntfs label=\"ProSafe Disk\" quick");
process.StandardInput.WriteLine("detach vdisk");
process.StandardInput.WriteLine("exit");


问:
Resize program already programmed in IDLE
I programmed in Python an application a couple of years ago in my computer, however I replaced the computer and now my application doesn't fit the screen.

All windows, labels and buttons were placed using coordinates:

```<code>window.geometry("1700x1010")
Label(VentanaCGR, text='"', justify="left").place(x=335, y= 60)
</code>```

Do I need to rearrange everything or is there any way to fit it to the screen regardles the computer resolution configuratio?

Body:
I programmed in Python an application a couple of years ago in my computer, however I replaced the computer and now my application doesn't fit the screen.

All windows, labels and buttons were placed using coordinates:

window.geometry("1700x1010")
Label(VentanaCGR, text='"', justify="left").place(x=335, y= 60)

Do I need to rearrange everything or is there any way to fit it to the screen regardles the computer resolution configuratio?


问:
AWS Datastore GraphQL Unable to Query many to many relations
I am currently following this workflow on the AWS Amplify docs:
https://docs.amplify.aws/lib/datastore/relational/q/platform/js/#many-to-many-relationships
Yet I cannot query my relational join tables. I am confused as to what I have done incorrectly in terms of syntax. This is my code and these are the errors I receive.

```<code>// schema.graph.ql

type Icd10 @model @auth(rules: [{allow: public}]) {
  id: ID!
  Code: String
  Description: String
  MedicalTests: [MedicalTest] @manyToMany(relationName: "Icd10MedicalTest")
  Disease: [Disease] @manyToMany(relationName: "Icd10Disease")
}

type MedicalTest @model @auth(rules: [{allow: public}]) {
  AdditionalIcd10: [String]
  AdditionalTesting: String
  ClinicalUtility: String
  Cpt: [String]
  DescriptiveMethodology: String
  Icd10: [String]
  Icd9: [String]
  Interpretation: String
  Loinc: [String]
  Methodology: String
  Name: String
  Overview: String
  PanelTests: [String]
  ReferenceRanges: String
  References: String
  SpecimenCollection: String
  SpecimenType: String
  Synonyms: [String]
  TurnaroundTime: String
  createdAt: AWSDateTime!
  id: ID!
  updatedAt: AWSDateTime!
  uuid: String
  ratings: [Rating] @manyToMany(relationName: "RatingMedicalTest")
  icd10s: [Icd10] @manyToMany(relationName: "Icd10MedicalTest")
}
</code>```
```<code>// TransferData.js

const value = await DataStore.query(MedicalTest,
    m => m.Name.eq("11-Dehydro-Thromboxane B2, Urine")
)

console.log(value)

const result = await DataStore.query(Icd10,
    m => m.MedicalTests.MedicalTest.id.eq(value.id)
)

console.log("updateIcd10MedicalTest Successful!")
console.log(result)
</code>```

Error Image

I have attempted to change the input values multiple times as I thought maybe I was wrong in reading how my schema functioned as I'm new to GraphQL.

Body:
I am currently following this workflow on the AWS Amplify docs:
https://docs.amplify.aws/lib/datastore/relational/q/platform/js/#many-to-many-relationships
Yet I cannot query my relational join tables. I am confused as to what I have done incorrectly in terms of syntax. This is my code and these are the errors I receive.

// schema.graph.ql

type Icd10 @model @auth(rules: [{allow: public}]) {
  id: ID!
  Code: String
  Description: String
  MedicalTests: [MedicalTest] @manyToMany(relationName: "Icd10MedicalTest")
  Disease: [Disease] @manyToMany(relationName: "Icd10Disease")
}

type MedicalTest @model @auth(rules: [{allow: public}]) {
  AdditionalIcd10: [String]
  AdditionalTesting: String
  ClinicalUtility: String
  Cpt: [String]
  DescriptiveMethodology: String
  Icd10: [String]
  Icd9: [String]
  Interpretation: String
  Loinc: [String]
  Methodology: String
  Name: String
  Overview: String
  PanelTests: [String]
  ReferenceRanges: String
  References: String
  SpecimenCollection: String
  SpecimenType: String
  Synonyms: [String]
  TurnaroundTime: String
  createdAt: AWSDateTime!
  id: ID!
  updatedAt: AWSDateTime!
  uuid: String
  ratings: [Rating] @manyToMany(relationName: "RatingMedicalTest")
  icd10s: [Icd10] @manyToMany(relationName: "Icd10MedicalTest")
}

// TransferData.js

const value = await DataStore.query(MedicalTest,
    m => m.Name.eq("11-Dehydro-Thromboxane B2, Urine")
)

console.log(value)

const result = await DataStore.query(Icd10,
    m => m.MedicalTests.MedicalTest.id.eq(value.id)
)

console.log("updateIcd10MedicalTest Successful!")
console.log(result)

Error Image

I have attempted to change the input values multiple times as I thought maybe I was wrong in reading how my schema functioned as I'm new to GraphQL.


问:
Deployed Gatsby on Netlify is acting differently than development (Gatsby + Material UI + Netlify)
I have tried Googling for a solution for a few hours and after multiple deploys, finally gave up and am asking for help.

Problem:

In Development:

The project acts normal. I have a nav with a about me section below and a background image.

In Production:

It looks as if the background image is pushing the text to the bottom into it's own block.

```<code>    <ThemeProvider theme={darkTheme}>
      <CssBaseline />
      <Header />
      <AboutMe />
    </ThemeProvider>
</code>```

UPDATE
Is the gatsby-plugin-material-ui plugin required to make it work?

I have added picture below. First one is development and second is in production. Now sure why the text is pushed outside of the height for the about-me section

Body:
I have tried Googling for a solution for a few hours and after multiple deploys, finally gave up and am asking for help.

Problem:

In Development:

The project acts normal. I have a nav with a about me section below and a background image.

In Production:

It looks as if the background image is pushing the text to the bottom into it's own block.

    <ThemeProvider theme={darkTheme}>
      <CssBaseline />

      <AboutMe />
    </ThemeProvider>

UPDATE
Is the gatsby-plugin-material-ui plugin required to make it work?

I have added picture below. First one is development and second is in production. Now sure why the text is pushed outside of the height for the about-me section


问:
Assign a value to a Pandas DataFrame column, based on multiple conditions, fastest ways?
I am aware there are some other similar questions but I haven't found a timeit test with a fairly large dataset. I have a ~1.6M rows DF , and I want to use the fastest way to assign a column ['stag'] a 0-1 value depending on the index weekday and hour.

Is there a faster approach I am missing ? suggestions ?

```<code>import timeit
import statistics

...
...

df_backtest['weekday'] = df_backtest.index.weekday

def approach_1():
    df_backtest["stag"]=1
    df_backtest.loc[(df_backtest.index.hour>=2) & (df_backtest.index.hour<=10),"stag" ]=0
    df_backtest.loc[df_backtest.index.strftime('%w')==6,"stag" ]=0
    df_backtest.loc[df_backtest.index.strftime('%w')==0,"stag" ]=0

def approach_2():
    df_backtest['stag'] = 1
    df_backtest.loc[df_backtest.index.hour.isin(range(2, 11)), 'stag'] = 0
    df_backtest.loc[df_backtest.index.strftime('%w').isin(['6', '0']), 'stag'] = 0

def approach_3():
    df_backtest['stag'] = 1
    df_backtest.loc[df_backtest.index.hour.isin(range(2, 11)), 'stag'] = 0
    df_backtest.loc[df_backtest['weekday'].isin(['6', '0']), 'stag'] = 0

def approach_4():
    df_backtest['stag'] = 1
    df_backtest['stag'] = df_backtest['stag'].where((df_backtest.index.hour < 2) | (df_backtest.index.hour > 10))
    df_backtest['stag'] = df_backtest['stag'].where(~df_backtest['weekday'].isin(['6', '0']))

num_repeats = 10
num_loops = 5

print(f'Approach 1: {statistics.mean(timeit.repeat(approach_1, number=num_loops, repeat=num_repeats)) / num_loops} seconds per loop')
print(f'Approach 2: {statistics.mean(timeit.repeat(approach_2, number=num_loops, repeat=num_repeats)) / num_loops} seconds per loop')
print(f'Approach 3: {statistics.mean(timeit.repeat(approach_3, number=num_loops, repeat=num_repeats)) / num_loops} seconds per loop')
print(f'Approach 4: {statistics.mean(timeit.repeat(approach_4, number=num_loops, repeat=num_repeats)) / num_loops} seconds per loop')
print('Shape of DF:',df_backtest.shape)
</code>```

output:

```<code>Approach 1: 4.617 seconds per loop
Approach 2: 2.256 seconds per loop
Approach 3: 0.087 seconds per loop
Approach 4: 0.106 seconds per loop
Shape of DF: (1605144, 7)
</code>```

Hence, it seems approach_3 is the fastest, I assume because it does not use the overhead of 'where' nor managing strings. Any other approach is welcome. Thanks

Body:
I am aware there are some other similar questions but I haven't found a timeit test with a fairly large dataset. I have a ~1.6M rows DF , and I want to use the fastest way to assign a column ['stag'] a 0-1 value depending on the index weekday and hour.

Is there a faster approach I am missing ? suggestions ?

import timeit
import statistics

...
...

df_backtest['weekday'] = df_backtest.index.weekday

def approach_1():
    df_backtest["stag"]=1
    df_backtest.loc[(df_backtest.index.hour>=2) & (df_backtest.index.hour<=10),"stag" ]=0
    df_backtest.loc[df_backtest.index.strftime('%w')==6,"stag" ]=0
    df_backtest.loc[df_backtest.index.strftime('%w')==0,"stag" ]=0

def approach_2():
    df_backtest['stag'] = 1
    df_backtest.loc[df_backtest.index.hour.isin(range(2, 11)), 'stag'] = 0
    df_backtest.loc[df_backtest.index.strftime('%w').isin(['6', '0']), 'stag'] = 0

def approach_3():
    df_backtest['stag'] = 1
    df_backtest.loc[df_backtest.index.hour.isin(range(2, 11)), 'stag'] = 0
    df_backtest.loc[df_backtest['weekday'].isin(['6', '0']), 'stag'] = 0

def approach_4():
    df_backtest['stag'] = 1
    df_backtest['stag'] = df_backtest['stag'].where((df_backtest.index.hour < 2) | (df_backtest.index.hour > 10))
    df_backtest['stag'] = df_backtest['stag'].where(~df_backtest['weekday'].isin(['6', '0']))

num_repeats = 10
num_loops = 5

print(f'Approach 1: {statistics.mean(timeit.repeat(approach_1, number=num_loops, repeat=num_repeats)) / num_loops} seconds per loop')
print(f'Approach 2: {statistics.mean(timeit.repeat(approach_2, number=num_loops, repeat=num_repeats)) / num_loops} seconds per loop')
print(f'Approach 3: {statistics.mean(timeit.repeat(approach_3, number=num_loops, repeat=num_repeats)) / num_loops} seconds per loop')
print(f'Approach 4: {statistics.mean(timeit.repeat(approach_4, number=num_loops, repeat=num_repeats)) / num_loops} seconds per loop')
print('Shape of DF:',df_backtest.shape)

output:

Approach 1: 4.617 seconds per loop
Approach 2: 2.256 seconds per loop
Approach 3: 0.087 seconds per loop
Approach 4: 0.106 seconds per loop
Shape of DF: (1605144, 7)

Hence, it seems approach_3 is the fastest, I assume because it does not use the overhead of 'where' nor managing strings. Any other approach is welcome. Thanks


问:
Fetch data on button click using Yii1 framework
I'm new to Yii framework and i'm trying to fetch data dynamically on button click from DB and onclick replace button with that value. I'm able to fetch the JSON on click which reloads the page but I don't want the page to be reloaded and just replace the button with the json response instead.
Currently i'm doing something like

```<code>'value' => CHtml::button('ButtonValue', array('submit' => array( 'url', 'id' => $id)))
</code>```

Any directions would be much appreciated. TIA

Body:
I'm new to Yii framework and i'm trying to fetch data dynamically on button click from DB and onclick replace button with that value. I'm able to fetch the JSON on click which reloads the page but I don't want the page to be reloaded and just replace the button with the json response instead.
Currently i'm doing something like

'value' => CHtml::button('ButtonValue', array('submit' => array( 'url', 'id' => $id)))

Any directions would be much appreciated. TIA


问:
How to play HDR10 videos using ffplay and ffmpeg?
I'm trying to play on Windows a HDR10 video. My display support 10 bits HDR content.
The command that I'm using to play the HDR10 video is the following.
ffplay -sws_flags print_info -i video.mp4

But the output looks washed out.

the log are the following:

ffplay version 2022-03-28-git-5ee198f9aa-full_build-www.gyan.dev Copyright (c) 2003-2022 the FFmpeg developers built with gcc 11.2.0 (Rev7, Built by MSYS2 project) configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-bzlib --enable-lzma --enable-libsnappy --enable-zlib --enable-librist --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libdav1d --enable-libdavs2 --enable-libuavs3d --enable-libzvbi --enable-librav1e --enable-libsvtav1 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libaom --enable-libopenjpeg --enable-libvpx --enable-mediafoundation --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-libshaderc --enable-vulkan --enable-libplacebo --enable-opencl --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint libavutil      57. 24.101 / 57. 24.101 libavcodec     59. 25.100 / 59. 25.100 libavformat    59. 20.101 / 59. 20.101 libavdevice    59.  6.100 / 59.  6.100 libavfilter     8. 29.100 /  8. 29.100 libswscale      6.  6.100 /  6.  6.100 libswresample   4.  6.100 /  4.  6.100 libpostproc    56.  5.100 / 56.  5.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':=0/0 Metadata: major_brand     : isom minor_version   : 512 compatible_brands: isomiso2mp41 encoder         : Lavf58.29.100 Duration: 00:00:08.78, start: 0.000000, bitrate: 159424 kb/s Stream #0:0[0x1](und): Video: hevc (Main 10) (hev1 / 0x31766568), yuv420p10le(tv, bt2020nc/bt2020/smpte2084, progressive), 3840x2160 [SAR 1:1 DAR 16:9], 159427 kb/s, 60 fps, 60 tbr, 15360 tbn (default) Metadata: handler_name    : VideoHandler vendor_id       : [0][0][0][0] [swscaler @ 000001d62a81d000] [swscaler @ 000001d622aebf80] bicubic scaler, from yuv420p10le to yuv420p using MMXEXT [swscaler @ 000001d62a81d000] [swscaler @ 000001d622aebf80] using unscaled yuv420p10le -> yuv420p special converter [swscaler @ 000001d62a81d000] [swscaler @ 000001d635638600] bicubic scaler, from yuv420p10le to yuv420p using MMXEXT [swscaler @ 000001d62a81d000] [swscaler @ 000001d635638600] using unscaled yuv420p10le -> yuv420p special converter [swscaler @ 000001d62a81d000] [swscaler @ 000001d635661d80] bicubic scaler, from yuv420p10le to yuv420p using MMXEXT [swscaler @ 000001d62a81d000] [swscaler @ 000001d635661d80] using unscaled yuv420p10le -> yuv420p special converter [swscaler @ 000001d62a81d000] [swscaler @ 000001d63567df80] bicubic scaler, from yuv420p10le to yuv420p using MMXEXT [swscaler @ 000001d62a81d000] [swscaler @ 000001d63567df80] using unscaled yuv420p10le -> yuv420p special converter [swscaler @ 000001d62a81d000] [swscaler @ 000001d6356bbf80] bicubic scaler, from yuv420p10le to yuv420p using MMXEXT 3.44 M-V:  0.204 fd=  91 aq=    0KB vq=15552KB sq=    0B f=0/0

With the help of '-sws_flags print_info' flag we can see that there is a downscaling happening from 10 bits to 8 bits "yuv420p10le -> yuv420p"

I have try to play the video using VLC and it is working fine on my display: colour are vivid and display bright.

I have also try to decode first the video and then past metadata directly to ffplay as follow.
Decoding to yuv format with : ffmpeg -i video.mp4 video.yuv
Then play yuv file: ffplay -framerate 60 -video_size 3840x2160 -pixel_format yuv420p10le -color_range tv -color_trc smpte2084 -color_primaries bt2020 -colorspace bt2020nc -i video.yuv

But the result is the same washed out color and "yuv420p10le -> yuv420p" conversion

Is there a way to play a HDR video (encoded or decoded stream) with ffplay?


问:
How to fix 'Call was rejected by callee' error while converting Word to PDF using Python
Im trying to convert word files to PDFs using python but I cant get this code to work.

```<code>import os
import comtypes.client

word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(input_file)
doc.SaveAs(output_file, FileFormat=17)
doc.Close()
word.Quit()

input_file = "C:\\input.docx"
output_file = "C:\\output.pdf"
doc_to_pdf(input_file, output_file)
</code>```

Trying to run this but getting an error "comtypes.COMError: (-2147418111, 'Call was rejected by callee.', None, None)"

Body:
Im trying to convert word files to PDFs using python but I cant get this code to work.

import os
import comtypes.client

word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(input_file)
doc.SaveAs(output_file, FileFormat=17)
doc.Close()
word.Quit()

input_file = "C:\\input.docx"
output_file = "C:\\output.pdf"
doc_to_pdf(input_file, output_file)

Trying to run this but getting an error "comtypes.COMError: (-2147418111, 'Call was rejected by callee.', None, None)"


问:
What does it mean that path analysis RMSEA is 0.00?
I wanted to run a path analysis but could not report the RMSEA and its p-value. The results showed that RMSEA = 0.00 Confidence interval = 0.00 and p-value: NA. I wonder what it does mean.

In my analysis, I have four IVs and three DVs.
This is the code what I wanted to run:

```<code>model1 <-"ML_NC+ML_NS+Preventive ~ TPE+covidconcern+MisinfoEx+CorrectAction"

fit_analysis1 <- sem(model1, data = dataset2)
summary(fit_analysis1, fit.measures=TRUE, standardized=T,rsquare=T)
</code>```

And also, if I want to include the control variables and mediating variables in the path analysis, how do I add these?

This is the results.

```<code>lavaan 0.6-12 ended normally after 15 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        18

  Number of observations                           272

Model Test User Model:

  Test statistic                                 0.000
  Degrees of freedom                                 0

Model Test Baseline Model:

  Test statistic                               419.201
  Degrees of freedom                                15
  P-value                                        0.000

User Model versus Baseline Model:

  Comparative Fit Index (CFI)                    1.000
  Tucker-Lewis Index (TLI)                       1.000

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)               -849.964
  Loglikelihood unrestricted model (H1)       -849.964

  Akaike (AIC)                                1735.928
  Bayesian (BIC)                              1800.833
  Sample-size adjusted Bayesian (BIC)         1743.759

Root Mean Square Error of Approximation:

  RMSEA                                          0.000
  90 Percent confidence interval - lower         0.000
  90 Percent confidence interval - upper         0.000
  P-value RMSEA <= 0.05                             NA

Standardized Root Mean Square Residual:

  SRMR                                           0.000

Parameter Estimates:

  Standard errors                             Standard
  Information                                 Expected
  Information saturated (h1) model          Structured

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
  ML_NC ~
    TPE               0.208    0.044    4.700    0.000    0.208    0.247
    covidconcern      0.113    0.054    2.083    0.037    0.113    0.121
    MisinfoEx         0.298    0.053    5.609    0.000    0.298    0.309
    CorrectAction     0.205    0.066    3.107    0.002    0.205    0.186
  ML_NS ~
    TPE               0.183    0.040    4.633    0.000    0.183    0.245
    covidconcern      0.128    0.049    2.648    0.008    0.128    0.155
    MisinfoEx         0.272    0.048    5.713    0.000    0.272    0.317
    CorrectAction     0.130    0.059    2.205    0.027    0.130    0.132
  Preventive ~
    TPE               0.073    0.052    1.410    0.159    0.073    0.068
    covidconcern      0.610    0.064    9.578    0.000    0.610    0.509
    MisinfoEx        -0.105    0.063   -1.686    0.092   -0.105   -0.085
    CorrectAction     0.300    0.077    3.870    0.000    0.300    0.211

Covariances:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
 .ML_NC ~~
   .ML_NS             0.295    0.034    8.642    0.000    0.295    0.615
   .Preventive        0.008    0.038    0.198    0.843    0.008    0.012
 .ML_NS ~~
   .Preventive        0.053    0.034    1.540    0.123    0.053    0.094

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
   .ML_NC             0.535    0.046   11.662    0.000    0.535    0.744
   .ML_NS             0.429    0.037   11.662    0.000    0.429    0.752
   .Preventive        0.739    0.063   11.662    0.000    0.739    0.623

R-Square:
                   Estimate
    ML_NC             0.256
    ML_NS             0.248
    Preventive        0.377

</code>```

This is data structure, and this is the results

```<code>> dput(head(dataset2))
structure(list(ID = 1:6, Demo = c(1L, 1L, 3L, 3L, 5L, 1L), Gender = c(2L,
1L, 2L, 1L, 2L, 1L), Ethnicity = c(6L, 1L, 2L, 1L, 4L, 3L), Education = c(2L,
3L, 4L, 2L, 6L, 3L), Income = c(1L, 1L, 6L, 5L, 4L, 3L), Poli = c(1,
3, 2, 2, 2, 3), covidconcern = c(4.33333333333333, 4, 5, 5, 5,
2.33333333333333), TPEm = c(4.8, 5, 5, 5, 4.8, 2.8), TPEo = c(5,
5, 5, 5, 4.8, 3.6), TPE = c(0.2, 0, 0, 0, 0, 0.8), MisinfoEx = c(4,
4.83333333333333, 5, 4, 4.66666666666667, 4.16666666666667),
    CorrectAction = c(3.6, 5, 5, 4.6, 4.8, 4.4), ML_NC = c(3.83333333333333,
    4, 5, 4.5, 4.83333333333333, 5), ML_NS = c(4, 4.4, 5, 4.6,
    4.6, 5), ML = c(3.91666666666667, 4.2, 5, 4.55, 4.71666666666667,
    5), Preventive = c(4, 4.75, 4.75, 3.75, 5, 4.5)), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x7f90cc83e2e0>)
>
</code>```

Thank you.

Body:
I wanted to run a path analysis but could not report the RMSEA and its p-value. The results showed that RMSEA = 0.00 Confidence interval = 0.00 and p-value: NA. I wonder what it does mean.

In my analysis, I have four IVs and three DVs.
This is the code what I wanted to run:

model1 <-"ML_NC+ML_NS+Preventive ~ TPE+covidconcern+MisinfoEx+CorrectAction"

fit_analysis1 <- sem(model1, data = dataset2)
summary(fit_analysis1, fit.measures=TRUE, standardized=T,rsquare=T)

And also, if I want to include the control variables and mediating variables in the path analysis, how do I add these?

This is the results.

lavaan 0.6-12 ended normally after 15 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        18

  Number of observations                           272

Model Test User Model:

  Test statistic                                 0.000
  Degrees of freedom                                 0

Model Test Baseline Model:

  Test statistic                               419.201
  Degrees of freedom                                15
  P-value                                        0.000

User Model versus Baseline Model:

  Comparative Fit Index (CFI)                    1.000
  Tucker-Lewis Index (TLI)                       1.000

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)               -849.964
  Loglikelihood unrestricted model (H1)       -849.964

  Akaike (AIC)                                1735.928
  Bayesian (BIC)                              1800.833
  Sample-size adjusted Bayesian (BIC)         1743.759

Root Mean Square Error of Approximation:

  RMSEA                                          0.000
  90 Percent confidence interval - lower         0.000
  90 Percent confidence interval - upper         0.000
  P-value RMSEA <= 0.05                             NA

Standardized Root Mean Square Residual:

  SRMR                                           0.000

Parameter Estimates:

  Standard errors                             Standard
  Information                                 Expected
  Information saturated (h1) model          Structured

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
  ML_NC ~
    TPE               0.208    0.044    4.700    0.000    0.208    0.247
    covidconcern      0.113    0.054    2.083    0.037    0.113    0.121
    MisinfoEx         0.298    0.053    5.609    0.000    0.298    0.309
    CorrectAction     0.205    0.066    3.107    0.002    0.205    0.186
  ML_NS ~
    TPE               0.183    0.040    4.633    0.000    0.183    0.245
    covidconcern      0.128    0.049    2.648    0.008    0.128    0.155
    MisinfoEx         0.272    0.048    5.713    0.000    0.272    0.317
    CorrectAction     0.130    0.059    2.205    0.027    0.130    0.132
  Preventive ~
    TPE               0.073    0.052    1.410    0.159    0.073    0.068
    covidconcern      0.610    0.064    9.578    0.000    0.610    0.509
    MisinfoEx        -0.105    0.063   -1.686    0.092   -0.105   -0.085
    CorrectAction     0.300    0.077    3.870    0.000    0.300    0.211

Covariances:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
 .ML_NC ~~
   .ML_NS             0.295    0.034    8.642    0.000    0.295    0.615
   .Preventive        0.008    0.038    0.198    0.843    0.008    0.012
 .ML_NS ~~
   .Preventive        0.053    0.034    1.540    0.123    0.053    0.094

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
   .ML_NC             0.535    0.046   11.662    0.000    0.535    0.744
   .ML_NS             0.429    0.037   11.662    0.000    0.429    0.752
   .Preventive        0.739    0.063   11.662    0.000    0.739    0.623

R-Square:
                   Estimate
    ML_NC             0.256
    ML_NS             0.248
    Preventive        0.377

This is data structure, and this is the results

> dput(head(dataset2))
structure(list(ID = 1:6, Demo = c(1L, 1L, 3L, 3L, 5L, 1L), Gender = c(2L,
1L, 2L, 1L, 2L, 1L), Ethnicity = c(6L, 1L, 2L, 1L, 4L, 3L), Education = c(2L,
3L, 4L, 2L, 6L, 3L), Income = c(1L, 1L, 6L, 5L, 4L, 3L), Poli = c(1,
3, 2, 2, 2, 3), covidconcern = c(4.33333333333333, 4, 5, 5, 5,
2.33333333333333), TPEm = c(4.8, 5, 5, 5, 4.8, 2.8), TPEo = c(5,
5, 5, 5, 4.8, 3.6), TPE = c(0.2, 0, 0, 0, 0, 0.8), MisinfoEx = c(4,
4.83333333333333, 5, 4, 4.66666666666667, 4.16666666666667),
    CorrectAction = c(3.6, 5, 5, 4.6, 4.8, 4.4), ML_NC = c(3.83333333333333,
    4, 5, 4.5, 4.83333333333333, 5), ML_NS = c(4, 4.4, 5, 4.6,
    4.6, 5), ML = c(3.91666666666667, 4.2, 5, 4.55, 4.71666666666667,
    5), Preventive = c(4, 4.75, 4.75, 3.75, 5, 4.5)), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x7f90cc83e2e0>)
>

Thank you.


问:
Stop React 18 from injecting bundle.js
I'm trying to add a redirect on my site for anyone using IE 11. I'm using ES6 and some packages that just don't play well with IE.

I think it's related to some package updates, but previous code I had to load a simple message saying to use another browser was functioning.

I now get an error saying there is a syntax error in bundle.js, and the screen is blank. What surprises me is that it's loading the bundle at all. When I debug, I can see its injecting

Title: Stop React 18 from injecting bundle.js


问:
New to All of This, Trying to Use "Video Killed the Radio Star"
I thought I'd step a toe into exploring AI for generating music videos, and found the "Video Killed the Radio Star" tool in Colab. Not knowing anything about any of this (and knowing I was going in mostly blind), I thought my tiny bit of familiarity with code could help me muscle through.

Alas, to no avail; each time I have tried I have encountered the same "IndexError: list index out of range" on my compilation step:

```<code>IndexError                                Traceback (most recent call last)
<ipython-input-16-04c12e9d8f67> in <module>
    110 prompt_starts = storyboard.prompt_starts
    111 batch_gen = BackgroundGenerator(
--> 112     [(idx, rec, process_sequence(idx))
    113         for idx, rec in enumerate(prompt_starts)]
    114     ,max_prefetch=2)
</code>```

I figure this means there's a table somewhere that needs to match the output image index the generator will use to create the video file, and for some reason it does not; but, I can't find a way to audit wherever this index may be nor what the discrepancy is.

Does anyone have any pointers where I should start with troubleshooting this error?

Trying to execute: https://github.com/dmarx/video-killed-the-radio-star

Body:
I thought I'd step a toe into exploring AI for generating music videos, and found the "Video Killed the Radio Star" tool in Colab. Not knowing anything about any of this (and knowing I was going in mostly blind), I thought my tiny bit of familiarity with code could help me muscle through.

Alas, to no avail; each time I have tried I have encountered the same "IndexError: list index out of range" on my compilation step:

IndexError                                Traceback (most recent call last)
<ipython-input-16-04c12e9d8f67> in <module>
    110 prompt_starts = storyboard.prompt_starts
    111 batch_gen = BackgroundGenerator(
--> 112     [(idx, rec, process_sequence(idx))
    113         for idx, rec in enumerate(prompt_starts)]
    114     ,max_prefetch=2)

I figure this means there's a table somewhere that needs to match the output image index the generator will use to create the video file, and for some reason it does not; but, I can't find a way to audit wherever this index may be nor what the discrepancy is.

Does anyone have any pointers where I should start with troubleshooting this error?

Trying to execute: https://github.com/dmarx/video-killed-the-radio-star


问:
What credentials to I use for localstack when identity management is set to true?
If I set enforcement of IAM for localstack-pro, I get a permissions error when trying to deploy a stack;

```<code>version: "3.8"

services:
  localstack:
    container_name: "${LOCALSTACK_DOCKER_NAME-localstack_main}"
    image: localstack/localstack-pro
    ports:
      - "127.0.0.1:4566:4566"            # LocalStack Gateway
      - "127.0.0.1:4510-4559:4510-4559"  # external services port range
    environment:
      - DEBUG=${DEBUG-}
      - LAMBDA_EXECUTOR=${LAMBDA_EXECUTOR-}
      - DOCKER_HOST=unix:///var/run/docker.sock
      - LOCALSTACK_API_KEY=GDiVANrxjg
      - ENFORCE_IAM=1
    volumes:
      - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"
</code>```

The given error is;

Building Assets Failed: Error: opensearch-dummy: Access to the specified resource is denied

This is in response to the command;

```<code>cdklocal deploy
</code>```

It worsk as expected if ENFORCE-IAM=0

Q: Is there a default set of user credentials for localstack that allows me to deploy?

Body:
If I set enforcement of IAM for localstack-pro, I get a permissions error when trying to deploy a stack;

version: "3.8"

services:
  localstack:
    container_name: "${LOCALSTACK_DOCKER_NAME-localstack_main}"
    image: localstack/localstack-pro
    ports:
      - "127.0.0.1:4566:4566"            # LocalStack Gateway
      - "127.0.0.1:4510-4559:4510-4559"  # external services port range
    environment:
      - DEBUG=${DEBUG-}
      - LAMBDA_EXECUTOR=${LAMBDA_EXECUTOR-}
      - DOCKER_HOST=unix:///var/run/docker.sock
      - LOCALSTACK_API_KEY=GDiVANrxjg
      - ENFORCE_IAM=1
    volumes:
      - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"

The given error is;

Building Assets Failed: Error: opensearch-dummy: Access to the specified resource is denied

This is in response to the command;

cdklocal deploy

It worsk as expected if ENFORCE-IAM=0

Q: Is there a default set of user credentials for localstack that allows me to deploy?


问:
how do I display the logged-in user session that is in login.php that appear to the coba.php page
I can't bring up the logged-in user session in login.php to the coba.php page and there is an error "undefined array key" in coba.php. how do I make it so that in coba.php the error does not appear and can bring up the logged-in user session in the form of the username

```<code>login.php

<?php

session_start();

include "koneksi.php";

    $username=$_POST['username'];
    $password=$_POST['password'];

    $cek_data= mysqli_query($conn,"select * from anggota where username='$username' and password='$password'");
    $cek = mysqli_num_rows($cek_data);

    if ($cek>0){
    $data = mysqli_fetch_assoc($cek_data);
        $_SESSION['username'] = $username;
        echo "Berhasil Login";

    }else {
        echo "Gagal Login";
    }

?>
</code>```
```<code>coba.php

<?php
session_start();

    echo $_SESSION['username'];
?>
</code>```

I'm trying to get the user username into try.php without the error undefined array key "Username"

Body:
I can't bring up the logged-in user session in login.php to the coba.php page and there is an error "undefined array key" in coba.php. how do I make it so that in coba.php the error does not appear and can bring up the logged-in user session in the form of the username

login.php

<?php

session_start();

include "koneksi.php";

    $username=$_POST['username'];
    $password=$_POST['password'];

    $cek_data= mysqli_query($conn,"select * from anggota where username='$username' and password='$password'");
    $cek = mysqli_num_rows($cek_data);

    if ($cek>0){
    $data = mysqli_fetch_assoc($cek_data);
        $_SESSION['username'] = $username;
        echo "Berhasil Login";

    }else {
        echo "Gagal Login";
    }

?>

coba.php

<?php
session_start();

    echo $_SESSION['username'];
?>

I'm trying to get the user username into try.php without the error undefined array key "Username"


问:
Property 'then' does not exist on type 'void'.ts(2339)
This is the index.ts file:

```<code>import mysql from "mysql2";
import * as dotenv from "dotenv";
dotenv.config({ path: __dirname+'/.env' });

import { app } from "./app";
import {Pools} from "./config/db";

const start = async () => {

  const default_options = {
    host: 'localhost', //(process.env.DB_HOST),
    user: 'a', //(process.env.DB_USER),
    password: '11111', // (process.env.DB_PASSWORD ),
    database: 'users_auth', //(process.env.DB_NAME ),
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  };

  try {
    await Pools.connect(default_options);
    console.log("Connected to MySQL");
  } catch (err) {
    console.log(err);
  }

  app.listen(3000, () => {
    console.log("Listening on port 3000!!!!!!!!");
  });
};

start();
</code>```

I have the following /config/db file:

```<code>import mysql from "mysql2";
import { Pool } from "mysql2/promise";

class Pools {
  static _pools: Pool;

  static connect(options: mysql.PoolOptions) {
    this._pools = mysql.createPool(options).promise();
    this._pools.execute('SELECT 1 + 1;');
  }

  static close() {
    this._pools.end();
  }

  static execute(sql: string, params?: any[] | undefined) {
    this._pools.execute(sql, params);
  }
}

export { Pools };
</code>```

And the following userController file:

```<code>import {Pools}  from "../config/db";

class User {

  static async findAll(req: Request, res: Response, next: NextFunction) {
    await Pools.execute("SELECT * FROM users" )
      .then((rows) => {
        res.send(rows[0]);
      })
      .catch(err => console.log(err));
    next();

  }
}
</code>```

The problem is that I get the following error at this line .then((rows) => { within the userController file:

Property 'then' does not exist on type 'void'.ts(2339)

Body:
This is the index.ts file:

import mysql from "mysql2";
import * as dotenv from "dotenv";
dotenv.config({ path: __dirname+'/.env' });

import { app } from "./app";
import {Pools} from "./config/db";

const start = async () => {

  const default_options = {
    host: 'localhost', //(process.env.DB_HOST),
    user: 'a', //(process.env.DB_USER),
    password: '11111', // (process.env.DB_PASSWORD ),
    database: 'users_auth', //(process.env.DB_NAME ),
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  };

  try {
    await Pools.connect(default_options);
    console.log("Connected to MySQL");
  } catch (err) {
    console.log(err);
  }

  app.listen(3000, () => {
    console.log("Listening on port 3000!!!!!!!!");
  });
};

start();

I have the following /config/db file:

import mysql from "mysql2";
import { Pool } from "mysql2/promise";

class Pools {
  static _pools: Pool;

  static connect(options: mysql.PoolOptions) {
    this._pools = mysql.createPool(options).promise();
    this._pools.execute('SELECT 1 + 1;');
  }

  static close() {
    this._pools.end();
  }

  static execute(sql: string, params?: any[] | undefined) {
    this._pools.execute(sql, params);
  }
}

export { Pools };

And the following userController file:

import {Pools}  from "../config/db";

class User {

  static async findAll(req: Request, res: Response, next: NextFunction) {
    await Pools.execute("SELECT * FROM users" )
      .then((rows) => {
        res.send(rows[0]);
      })
      .catch(err => console.log(err));
    next();

  }
}

The problem is that I get the following error at this line .then((rows) => { within the userController file:

Property 'then' does not exist on type 'void'.ts(2339)


问:
pandas dataframe - reorganize the data by adding a column name based on row data
I am new to pandas and am trying to figure out how to transform a dataframe by grouping by rows.. The column names need to be changed depending on data. Any help will be greatly appreciated. I added the image to show original vs transformed view.

Here is the from to expected data

I tried the following code. The data in 2021_b should show 48.3, but with my code it is still showing 32.2. And also, column a should not be repeated, so ultimately, in this example, I should see only 3 rows.

```<code>df = pd.DataFrame({
    'a':[111, 111, 222, 222, 333, 333],
    'b':[2020, 2021, 2020, 2021, 2020, 2021],
    'c':[33.2, 48.3, 32.2, 45.5, 45.5, 78.4]
})
df = df.assign(**{'b_'+ str(df['b'].iloc[i]): lambda x: x['c'] for i in range(len(df))})
df.drop('b', axis=1, inplace=True)
df.drop('c', axis=1, inplace=True)
print(df)`
</code>```

Body:
I am new to pandas and am trying to figure out how to transform a dataframe by grouping by rows.. The column names need to be changed depending on data. Any help will be greatly appreciated. I added the image to show original vs transformed view.

Here is the from to expected data

I tried the following code. The data in 2021_b should show 48.3, but with my code it is still showing 32.2. And also, column a should not be repeated, so ultimately, in this example, I should see only 3 rows.

df = pd.DataFrame({
    'a':[111, 111, 222, 222, 333, 333],
    'b':[2020, 2021, 2020, 2021, 2020, 2021],
    'c':[33.2, 48.3, 32.2, 45.5, 45.5, 78.4]
})
df = df.assign(**{'b_'+ str(df['b'].iloc[i]): lambda x: x['c'] for i in range(len(df))})
df.drop('b', axis=1, inplace=True)
df.drop('c', axis=1, inplace=True)
print(df)`