问:
Hibernate single table inheritance with associations in sub-classes using the same JoinColumn
In my domain model, I would like to associate an entity with other entities based on a discriminator column. For example, an address can be associated to a company or to a person. I would like to have only one table for addresses and selectively associate the address to a company or person based on the address type and an id which references the PK of either the company or person table.

Here are the table definitions:

```<code>CREATE TABLE IF NOT EXISTS `address` (
  `entityId` CHAR(26) NOT NULL,
  `addrLine1` VARCHAR(255) NOT NULL,
  `addrLine2` VARCHAR(255) DEFAULT NULL,
  `city` VARCHAR(255) NOT NULL,
  `state` CHAR(2) NOT NULL,
  `zip` CHAR(5) NOT NULL,
  `isBilling` CHAR(1) DEFAULT 'N',
  `type` ENUM('PERSON', 'COMPANY') NOT NULL,
  `addressableId` CHAR(26) NOT NULL,
  `hash` INT UNSIGNED NOT NULL,
  `created` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updated` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`entityId`),
  CONSTRAINT `un_address_hash` UNIQUE (`hash`, `addressableId`),
  INDEX `idx_address_addressableId` (`addressableId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

CREATE TABLE IF NOT EXISTS `company` (
  `entityId` CHAR(26) NOT NULL,
  `groupId` CHAR(26) NOT NULL,
  `name` VARCHAR(255) NOT NULL,
  `type` ENUM('USER', 'CLIENT', 'SUPPLIER', 'CLIENT_SUPPORT', 'USER_SUPPORT') NOT NULL,
  `created` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updated` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`entityId`),
  CONSTRAINT `fk_company_groupId` FOREIGN KEY (`groupId`) REFERENCES `user_group` (`entityId`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

CREATE TABLE IF NOT EXISTS `person` (
  `entityId` CHAR(26) NOT NULL,
  `firstName` VARCHAR(255) NOT NULL,
  `lastName` VARCHAR(255) DEFAULT NULL,
  `companyId` CHAR(26) NOT NULL,
  `created` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updated` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`entityId`),
  CONSTRAINT `fk_person_companyId` FOREIGN KEY (`companyId`) REFERENCES `company` (`entityId`) ON DELETE CASCADE,
  CONSTRAINT `un_person_name` UNIQUE (`companyId`, `firstName`, `lastName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

</code>```

When I translate this to hibernate, I use single-table inheritance on a base Address class with sub-classes CompanyAddress and PersonAddress like so:

```<code>@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@Table(name = "address")
public class Address extends BaseEntity {

    @Column(nullable = false)
    private String addrLine1;

    private String addrLine2;

    @Column(nullable = false)
    private String city;

    @Column(length = 2, nullable = false)
    @Enumerated(EnumType.STRING)
    private State state;

    @Column(length = 5, nullable = false)
    private String zip;
}

@Getter
@Setter
@Entity
@DiscriminatorValue("COMPANY")
public class CompanyAddress extends Address {

    @ManyToOne
    @JoinColumn(name = "addressableId", referencedColumnName = "entityId")
    private Company company;

    @Convert(converter = BooleanConverter.class)
    private Boolean isBilling;

}

@Getter
@Setter
@Entity
@DiscriminatorValue("PERSON")
public class PersonAddress extends Address {

    @ManyToOne
    @JoinColumn(name = "addressableId")
    private Person person;

}

</code>```

As above, I would like to use the addressableId to either reference a Company or a Person based on the subclass (discriminator COMPANY or PERSON). In the Company class, I would like to maintain a list of all CompanyAddress entities:

```<code>@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@Table(name = "company")
public class Company extends BaseEntity {

    @ManyToOne
    @JoinColumn(name = "groupId")
    private UserGroup userGroup;

    @Column(nullable = false)
    private String name;

    //////////

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<Person> people;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<CompanyAddress> addresses;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<CompanyPhone> phoneNumbers;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<CompanyEmail> emailAddresses;

}

</code>```

The problem I have, is that when trying to create a Company with cascading persists on the associated CompanyAddress entities, the primary key of the associated Company is not propagating to the CompanyAddress addressableId, and the save fails since addressableId cannot be null in the address table.

Here is the output I am seeing in the debug logs when saving a Company entity with one CompanyAddress in the companyAddresses list:

```<code>11:54:33.992 [http-nio-8080-exec-11] DEBUG o.h.internal.util.EntityPrinter - Listing entities:
11:54:33.993 [http-nio-8080-exec-11] DEBUG o.h.internal.util.EntityPrinter - io.billme.webservice.data.domain.ClientSupportCompany{addresses=[com.test.webservice.data.domain.CompanyAddress#BKSR47H45CTB8PJXT31PH3YN6W], emailAddresses=[], created=null, name=Some Company Name, entityId=XP8MRLNPDRMTFK4J846G8VF6VC, people=null, updated=null, userGroup=com.test.webservice.data.domain.UserGroup#PWANTBWLBJFZCS9RSBG1ZX88YR, phoneNumbers=[]}
11:54:33.993 [http-nio-8080-exec-11] DEBUG o.h.internal.util.EntityPrinter - io.billme.webservice.data.domain.CompanyAddress{zip=*****, isBilling=false, city=Anywhere, addrLine2=null, created=null, addrLine1=Main St, entityId=BKSR47H45CTB8PJXT31PH3YN6W, company=null, state=**, updated=null}
11:54:33.996 [http-nio-8080-exec-11] DEBUG org.hibernate.SQL - insert into company (name, groupId, type, entityId) values (?, ?, 'CLIENT_SUPPORT', ?)
11:54:34.002 [http-nio-8080-exec-11] DEBUG org.hibernate.SQL - insert into address (addrLine1, addrLine2, city, isBilling, state, zip, addressableId, type, entityId) values (?, ?, ?, ?, ?, ?, ?, 'COMPANY', ?)
11:54:34.020 [
-nio-8080-exec-11] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
java.sql.SQLIntegrityConstraintViolationException: Column 'addressableId' cannot be null
</code>```

Is there anything on the Hibernate side I can do to fit this relational model? It seems that Hibernate should be able to propagate the entityId from the Company entity to the "owning" Address entity.

I have seen this post: https://discourse.hibernate.org/t/two-relationships-to-single-table-inheritance-sub-classes-failing-with-hibernate-5-3/6012
There is a slight difference in the setup, but after upgrading my Hibernate version to 6.1 there was no change.

Body:
In my domain model, I would like to associate an entity with other entities based on a discriminator column. For example, an address can be associated to a company or to a person. I would like to have only one table for addresses and selectively associate the address to a company or person based on the address type and an id which references the PK of either the company or person table.

Here are the table definitions:

CREATE TABLE IF NOT EXISTS `address` (
  `entityId` CHAR(26) NOT NULL,
  `addrLine1` VARCHAR(255) NOT NULL,
  `addrLine2` VARCHAR(255) DEFAULT NULL,
  `city` VARCHAR(255) NOT NULL,
  `state` CHAR(2) NOT NULL,
  `zip` CHAR(5) NOT NULL,
  `isBilling` CHAR(1) DEFAULT 'N',
  `type` ENUM('PERSON', 'COMPANY') NOT NULL,
  `addressableId` CHAR(26) NOT NULL,
  `hash` INT UNSIGNED NOT NULL,
  `created` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updated` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`entityId`),
  CONSTRAINT `un_address_hash` UNIQUE (`hash`, `addressableId`),
  INDEX `idx_address_addressableId` (`addressableId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

CREATE TABLE IF NOT EXISTS `company` (
  `entityId` CHAR(26) NOT NULL,
  `groupId` CHAR(26) NOT NULL,
  `name` VARCHAR(255) NOT NULL,
  `type` ENUM('USER', 'CLIENT', 'SUPPLIER', 'CLIENT_SUPPORT', 'USER_SUPPORT') NOT NULL,
  `created` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updated` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`entityId`),
  CONSTRAINT `fk_company_groupId` FOREIGN KEY (`groupId`) REFERENCES `user_group` (`entityId`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

CREATE TABLE IF NOT EXISTS `person` (
  `entityId` CHAR(26) NOT NULL,
  `firstName` VARCHAR(255) NOT NULL,
  `lastName` VARCHAR(255) DEFAULT NULL,
  `companyId` CHAR(26) NOT NULL,
  `created` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updated` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`entityId`),
  CONSTRAINT `fk_person_companyId` FOREIGN KEY (`companyId`) REFERENCES `company` (`entityId`) ON DELETE CASCADE,
  CONSTRAINT `un_person_name` UNIQUE (`companyId`, `firstName`, `lastName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

When I translate this to hibernate, I use single-table inheritance on a base Address class with sub-classes CompanyAddress and PersonAddress like so:

@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@Table(name = "address")
public class Address extends BaseEntity {

    @Column(nullable = false)
    private String addrLine1;

    private String addrLine2;

    @Column(nullable = false)
    private String city;

    @Column(length = 2, nullable = false)
    @Enumerated(EnumType.STRING)
    private State state;

    @Column(length = 5, nullable = false)
    private String zip;
}

@Getter
@Setter
@Entity
@DiscriminatorValue("COMPANY")
public class CompanyAddress extends Address {

    @ManyToOne
    @JoinColumn(name = "addressableId", referencedColumnName = "entityId")
    private Company company;

    @Convert(converter = BooleanConverter.class)
    private Boolean isBilling;

}

@Getter
@Setter
@Entity
@DiscriminatorValue("PERSON")
public class PersonAddress extends Address {

    @ManyToOne
    @JoinColumn(name = "addressableId")
    private Person person;

}

As above, I would like to use the addressableId to either reference a Company or a Person based on the subclass (discriminator COMPANY or PERSON). In the Company class, I would like to maintain a list of all CompanyAddress entities:

@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@Table(name = "company")
public class Company extends BaseEntity {

    @ManyToOne
    @JoinColumn(name = "groupId")
    private UserGroup userGroup;

    @Column(nullable = false)
    private String name;

    //////////

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<Person> people;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<CompanyAddress> addresses;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<CompanyPhone> phoneNumbers;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private List<CompanyEmail> emailAddresses;

}

The problem I have, is that when trying to create a Company with cascading persists on the associated CompanyAddress entities, the primary key of the associated Company is not propagating to the CompanyAddress addressableId, and the save fails since addressableId cannot be null in the address table.

Here is the output I am seeing in the debug logs when saving a Company entity with one CompanyAddress in the companyAddresses list:

11:54:33.992 [http-nio-8080-exec-11] DEBUG o.h.internal.util.EntityPrinter - Listing entities:
11:54:33.993 [http-nio-8080-exec-11] DEBUG o.h.internal.util.EntityPrinter - io.billme.webservice.data.domain.ClientSupportCompany{addresses=[com.test.webservice.data.domain.CompanyAddress#BKSR47H45CTB8PJXT31PH3YN6W], emailAddresses=[], created=null, name=Some Company Name, entityId=XP8MRLNPDRMTFK4J846G8VF6VC, people=null, updated=null, userGroup=com.test.webservice.data.domain.UserGroup#PWANTBWLBJFZCS9RSBG1ZX88YR, phoneNumbers=[]}
11:54:33.993 [http-nio-8080-exec-11] DEBUG o.h.internal.util.EntityPrinter - io.billme.webservice.data.domain.CompanyAddress{zip=*****, isBilling=false, city=Anywhere, addrLine2=null, created=null, addrLine1=Main St, entityId=BKSR47H45CTB8PJXT31PH3YN6W, company=null, state=**, updated=null}
11:54:33.996 [http-nio-8080-exec-11] DEBUG org.hibernate.SQL - insert into company (name, groupId, type, entityId) values (?, ?, 'CLIENT_SUPPORT', ?)
11:54:34.002 [http-nio-8080-exec-11] DEBUG org.hibernate.SQL - insert into address (addrLine1, addrLine2, city, isBilling, state, zip, addressableId, type, entityId) values (?, ?, ?, ?, ?, ?, ?, 'COMPANY', ?)
11:54:34.020 [
-nio-8080-exec-11] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
java.sql.SQLIntegrityConstraintViolationException: Column 'addressableId' cannot be null

Is there anything on the Hibernate side I can do to fit this relational model? It seems that Hibernate should be able to propagate the entityId from the Company entity to the "owning" Address entity.

I have seen this post: https://discourse.hibernate.org/t/two-relationships-to-single-table-inheritance-sub-classes-failing-with-hibernate-5-3/6012
There is a slight difference in the setup, but after upgrading my Hibernate version to 6.1 there was no change.


来源: stackexchange

问:
Rust book: Why does the match operator behave differently with this expression?
I was following along the rust book's final chapter where we build a simple multi-threaded web server, and once I finished it I decided to go back and clean up all the unwraps as practice. While I was doing that, I also decided to clean up some of the code and make it more succinct. One example of this was "in-lining" (or replacing a variable with the expression it represents, idk what the word for that is) an expression directly into a match expression:

```<code>let message = receiver.lock().unwrap().recv();
match message {
    Ok(job) => {
        println!("Worker {id} got a job: Executing.");
        job()
    },
    Err(_) => {
        println!("Worker {id} disconnected: Shutting down.");
        break;
    },
}
</code>```

Turning it into this:

```<code>match receiver.lock().unwrap().recv() {
    Ok(job) => {
        println!("Worker {id} got a job: Executing.");
        job()
    },
    Err(_) => {
        println!("Worker {id} disconnected: Shutting down.");
        break;
    },
}
</code>```

Coming from other languages, I didn't think that this would have any effect on the behavior of my code, since it seems natural to replace the variable that I only use once. However, this subtle change caused my multi-threaded program to turn into a single-threaded one: every single job requested from any client all got sent to 1 thread, rather than being spread across all threads in the thread pool. For example:

```<code>With the temp variable:
Worker 2 got a job: Executing.
Worker 1 got a job: Executing.
Worker 3 got a job: Executing.
Worker 0 got a job: Executing.
Worker 2 got a job: Executing.
Worker 3 got a job: Executing.
</code>```
```<code>Without the temp variable (note that sometimes it's not always worker 0):
Worker 0 got a job: Executing.
Worker 0 got a job: Executing.
Worker 0 got a job: Executing.
Worker 0 got a job: Executing.
Worker 0 got a job: Executing.
</code>```

I have no idea why this type of behavior would happen. I am going to assume it has something to do with the fact that receiver has type Arc<Mutex<mpsc::Receiver<Job>>>, and something is going wrong there.

Here is the full function for reference. The purpose of this function is to create a Worker under the thread pool that contains an id and a thread option. In the original Rust book guide, they use thread::spawn instead of thread::Builder, but I have confirmed that this behavior is the same either way.

```<code>struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(
        id: usize,
        receiver: Arc<Mutex<mpsc::Receiver<Job>>>,
    ) -> Result<Worker, ThreadPoolError> {

        let builder = thread::Builder::new();

        // Create a new thread from the thread builder
        let thread = builder.spawn(move || loop {
            let message = receiver.lock().unwrap().recv();
            match message {
                Ok(job) => {
                    println!("Worker {id} got a job: Executing.");
                    job()
                },
                Err(_) => { // when we drop the worker
                    println!("Worker {id} disconnected: Shutting down.");
                    break;
                },
            }
        });

        match thread {
            Ok(thread) => Ok(Worker {
                id,
                thread: Some(thread),
            }),
            Err(e) => Err(ThreadPoolError::BuildError(e)),
        }
    }

}
</code>```

Any clarification would be appreciated! I have a feeling that this is a match feature when interacting with Mutexes, but I wasn't able to find it in the Rust book.

ContentLicense: CC BY-SA 4.0

Body:
I was following along the rust book's final chapter where we build a simple multi-threaded web server, and once I finished it I decided to go back and clean up all the unwraps as practice. While I was doing that, I also decided to clean up some of the code and make it more succinct. One example of this was "in-lining" (or replacing a variable with the expression it represents, idk what the word for that is) an expression directly into a match expression:

let message = receiver.lock().unwrap().recv();
match message {
    Ok(job) => {
        println!("Worker {id} got a job: Executing.");
        job()
    },
    Err(_) => {
        println!("Worker {id} disconnected: Shutting down.");
        break;
    },
}

Turning it into this:

match receiver.lock().unwrap().recv() {
    Ok(job) => {
        println!("Worker {id} got a job: Executing.");
        job()
    },
    Err(_) => {
        println!("Worker {id} disconnected: Shutting down.");
        break;
    },
}

Coming from other languages, I didn't think that this would have any effect on the behavior of my code, since it seems natural to replace the variable that I only use once. However, this subtle change caused my multi-threaded program to turn into a single-threaded one: every single job requested from any client all got sent to 1 thread, rather than being spread across all threads in the thread pool. For example:

With the temp variable:
Worker 2 got a job: Executing.
Worker 1 got a job: Executing.
Worker 3 got a job: Executing.
Worker 0 got a job: Executing.
Worker 2 got a job: Executing.
Worker 3 got a job: Executing.

Without the temp variable (note that sometimes it's not always worker 0):
Worker 0 got a job: Executing.
Worker 0 got a job: Executing.
Worker 0 got a job: Executing.
Worker 0 got a job: Executing.
Worker 0 got a job: Executing.

I have no idea why this type of behavior would happen. I am going to assume it has something to do with the fact that receiver has type Arc<Mutex<mpsc::Receiver<Job>>>, and something is going wrong there.

Here is the full function for reference. The purpose of this function is to create a Worker under the thread pool that contains an id and a thread option. In the original Rust book guide, they use thread::spawn instead of thread::Builder, but I have confirmed that this behavior is the same either way.

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(
        id: usize,
        receiver: Arc<Mutex<mpsc::Receiver<Job>>>,
    ) -> Result<Worker, ThreadPoolError> {

        let builder = thread::Builder::new();

        // Create a new thread from the thread builder
        let thread = builder.spawn(move || loop {
            let message = receiver.lock().unwrap().recv();
            match message {
                Ok(job) => {
                    println!("Worker {id} got a job: Executing.");
                    job()
                },
                Err(_) => { // when we drop the worker
                    println!("Worker {id} disconnected: Shutting down.");
                    break;
                },
            }
        });

        match thread {
            Ok(thread) => Ok(Worker {
                id,
                thread: Some(thread),
            }),
            Err(e) => Err(ThreadPoolError::BuildError(e)),
        }
    }

}

Any clarification would be appreciated! I have a feeling that this is a match feature when interacting with Mutexes, but I wasn't able to find it in the Rust book.


问:
Nx Angular - 404 after refresh with PathLocationStrategy
I am working on creating an Nx monorepo workspace for Angular apps. I have a single sandbox app and am configuring routes for it.

My configuration is as follows:

app.module.ts

```<code>@NgModule({
  declarations: [
    AppComponent,
    NxWelcomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {provide: LocationStrategy, useClass: PathLocationStrategy}
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}
</code>```

app-routing.module.ts

```<code>const routes: Routes = [
  {
    path       : 'welcome',
    component  : NxWelcomeComponent
  },
  {path: '', redirectTo: 'welcome', pathMatch: 'full'},
  {path: '**', redirectTo: 'welcome'}
];

const routeConfig: ExtraOptions = {
  scrollPositionRestoration: 'top',
  useHash: false,
}

@NgModule({
  imports: [RouterModule.forRoot(routes, routeConfig)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Sandbox</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
  </head>
  <body>
    <app-root></app-root>
  </body>
</html>
</code>```

app.component.html

```<code><router-outlet></router-outlet>
</code>```

If I serve the app with useHash: true everything works as intended.

Navigate to / redirects to /welcome

Navigate to or refresh from /welcome reloads the page

Navigate to any other path redirects to /welcome

However, when serving with useHase: false the only thing that works is navigating to / and if you refresh or try any other path it gives 404.

To my understanding I have configured everything correctly, and this PathLocationStrategy should be working. However, I have never worked with Nx before, so is there some kind of configuration I am missing that needs to be added to Nx in order to allow the local webserver to recognize the path strategy?

If it is just an issue with Nx serving the app locally and once built and deployed to our production server we can use path location, then im okay with doing something like:

```<code>const routeConfig: ExtraOptions = {
  scrollPositionRestoration: 'top',
  useHash: !environment.production,
}
</code>```

to use hash locally and path when deployed.

Body:
I am working on creating an Nx monorepo workspace for Angular apps. I have a single sandbox app and am configuring routes for it.

My configuration is as follows:

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    NxWelcomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {provide: LocationStrategy, useClass: PathLocationStrategy}
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

app-routing.module.ts

const routes: Routes = [
  {
    path       : 'welcome',
    component  : NxWelcomeComponent
  },
  {path: '', redirectTo: 'welcome', pathMatch: 'full'},
  {path: '**', redirectTo: 'welcome'}
];

const routeConfig: ExtraOptions = {
  scrollPositionRestoration: 'top',
  useHash: false,
}

@NgModule({
  imports: [RouterModule.forRoot(routes, routeConfig)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Sandbox</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />

    <app-root></app-root>

app.component.html

<router-outlet></router-outlet>

If I serve the app with useHash: true everything works as intended.

Navigate to / redirects to /welcome

Navigate to or refresh from /welcome reloads the page

Navigate to any other path redirects to /welcome

However, when serving with useHase: false the only thing that works is navigating to / and if you refresh or try any other path it gives 404.

To my understanding I have configured everything correctly, and this PathLocationStrategy should be working. However, I have never worked with Nx before, so is there some kind of configuration I am missing that needs to be added to Nx in order to allow the local webserver to recognize the path strategy?

If it is just an issue with Nx serving the app locally and once built and deployed to our production server we can use path location, then im okay with doing something like:

const routeConfig: ExtraOptions = {
  scrollPositionRestoration: 'top',
  useHash: !environment.production,
}

to use hash locally and path when deployed.


问:
Cloudformation query
A query on cloud formation. I have two S3 buckets git-bucket and cloud-front-bucket.
Following are my requirements

Only git should be able to write to the 'git-bucket'

Only cloud front should be able to read the 'cloud-front-bucket'

How do I add these conditions to my cloud formation script? Any pointers, please? I believe I need to add a bucket policy or IAM policy, Is my understanding correct? Following is my cloud formation script.

```<code>AWSTemplateFormatVersion: "2010-09-09"
Description: 'Creating S3 bucket'

Resources:
  s3WebArtifacts:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: "Private"
      BucketName: git-bucket
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

  s3WebLive:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: "Private"
      BucketName: cloud-front-bucket
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
</code>```

Title: Cloudformation query

Body:
A query on cloud formation. I have two S3 buckets git-bucket and cloud-front-bucket.
Following are my requirements

Only git should be able to write to the 'git-bucket'

Only cloud front should be able to read the 'cloud-front-bucket'

How do I add these conditions to my cloud formation script? Any pointers, please? I believe I need to add a bucket policy or IAM policy, Is my understanding correct? Following is my cloud formation script.

AWSTemplateFormatVersion: "2010-09-09"
Description: 'Creating S3 bucket'

Resources:
  s3WebArtifacts:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: "Private"
      BucketName: git-bucket
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

  s3WebLive:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: "Private"
      BucketName: cloud-front-bucket
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true


问:
How to customize celebrate message?
this is the celebrate

https://www.npmjs.com/package/celebrate?activeTab=readme

The validation I'm doing this way using celebrate

```<code>sessionsRouter.post(
  '/',
  celebrate({
    [Segments.BODY]: {
      email: Joi.string().email().required(),
      password: Joi.string().required(),
    },
  }),
  sessionsController.create,
);
</code>```

The expected result is this

```<code>{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "celebrate request validation failed",
    "validation": {
        "body": {
            "source": "body",
            "keys": [
                "email"
            ],
            "message": "\"email\" must be a valid email"
        }
    }
}
</code>```

Does anyone know how to customize the email validation message?

Title: How to customize celebrate message?

Body:
this is the celebrate

https://www.npmjs.com/package/celebrate?activeTab=readme

The validation I'm doing this way using celebrate

sessionsRouter.post(
  '/',
  celebrate({
    [Segments.BODY]: {
      email: Joi.string().email().required(),
      password: Joi.string().required(),
    },
  }),
  sessionsController.create,
);

The expected result is this

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "celebrate request validation failed",
    "validation": {
        "body": {
            "source": "body",
            "keys": [
                "email"
            ],
            "message": "\"email\" must be a valid email"
        }
    }
}

Does anyone know how to customize the email validation message?


问:
Manually trigger timer trigger azure function and know when it finished running?
Background:
I have a timer triggered azure function and it will write to DB. In my automation testing (Ready-API from smartBear), after I manually triggered the timer function, I have another step to query the DB to assert the record got inserted.

Problem:
When manually invoking the timer function, it will respond back with 202 immediately. This will tell my automation to continue to the next step ("query DB") without wait the function to be executed. So the "query DB" step will fail from time to time because of the racing problem.

Question:
I don't want to add "delay" in between those test steps because sometimes the function is "cold start" which will take way longer for it to be executed. Wondering are there anyways to know for sure a timer-triggered function finished running?


问:
Newbi - Dividing two JXPATH queries
I have two query JXpath returning me the right value

count(./productItemList/countryOfOrigin)   - Returning me 5
count(./productItemList/customerOrderLine) - Returing me 4

I am looking to combine these queries so I can:

count(./productItemList/customerOrderLine)  DIVIDED BY  count(./productItemList/countryOfOrigin)

thanks for your help

Title: Newbi - Dividing two JXPATH queries


问:
Using a method within a class to add a row of data to a csv file?
I have built a web scraping class. Within the class, I have a method to write some data into a csv file, which works fine.

```<code>def avg_data_to_csv(self, filename):
    # Write scraped average data to csv file
    avg_data = self.avg_data
    df = pd.DataFrame(avg_data, columns=['Town', 'Average Price', 'Average Price per SQFT'])
    csv = df.to_csv(filename + '_listings.csv')
    return csv

</code>```

I want to write a method so that I can add a new row to the same csv file when I get more data. Right now, I have this method--

```<code>def add_to_avg_csv(self, filename):
    avg_data = self.avg_data
    with open(filename + '_listings.csv', 'a') as obj:
        writer_object = writer(obj)
        writer_object.writerow(avg_data)
        obj.close()
    return avg_data
</code>```

But, for some reason, it adds a line to the CSV file that is not the data, but the columns I specified in the earlier class--

```<code>['Town', 'Average Price', 'Average Price per SQFT']
</code>```

I'm trying to append the actual data, which works fine in the def avg_to_csv() method. I have also tried returning Obj instead of avg_data in the add_to_avg_csv() method but it gives me the same problem. What is it that I am doing wrong?

Body:
I have built a web scraping class. Within the class, I have a method to write some data into a csv file, which works fine.

def avg_data_to_csv(self, filename):
    # Write scraped average data to csv file
    avg_data = self.avg_data
    df = pd.DataFrame(avg_data, columns=['Town', 'Average Price', 'Average Price per SQFT'])
    csv = df.to_csv(filename + '_listings.csv')
    return csv

I want to write a method so that I can add a new row to the same csv file when I get more data. Right now, I have this method--

def add_to_avg_csv(self, filename):
    avg_data = self.avg_data
    with open(filename + '_listings.csv', 'a') as obj:
        writer_object = writer(obj)
        writer_object.writerow(avg_data)
        obj.close()
    return avg_data

But, for some reason, it adds a line to the CSV file that is not the data, but the columns I specified in the earlier class--

['Town', 'Average Price', 'Average Price per SQFT']

I'm trying to append the actual data, which works fine in the def avg_to_csv() method. I have also tried returning Obj instead of avg_data in the add_to_avg_csv() method but it gives me the same problem. What is it that I am doing wrong?


问:
Rails 7 Webpack x Cocoon Gem
Im a rookie on rails and javascript but apparently im not succeeding with cocoon because of this issue im getting on my console that im stuck with:

```<code>Uncaught ReferenceError: jQuery is not defined cocoon.js:1
at 342 (cocoon.js:1:11)
at i (bootstrap:19:22)
at bootstrap.esm.js:5208:20
at bootstrap.esm.js:5208:20
at bootstrap.esm.js:5208:20
</code>```

Thank you so so so much in advance!

I ve tried yarn add jquery and adding the following to my app/javascript/application.js:

```<code>import jquery from "jquery"
window.jQuery = jquery
window.$ = jquery

$(function() {
    console.log("hello world")
})
</code>```

Also tried adding jquery-rails gem to my gemfile....but neither worked.

Title: Rails 7 Webpack x Cocoon Gem

Body:
Im a rookie on rails and javascript but apparently im not succeeding with cocoon because of this issue im getting on my console that im stuck with:

Uncaught ReferenceError: jQuery is not defined cocoon.js:1
at 342 (cocoon.js:1:11)
at i (bootstrap:19:22)
at bootstrap.esm.js:5208:20
at bootstrap.esm.js:5208:20
at bootstrap.esm.js:5208:20

Thank you so so so much in advance!

I ve tried yarn add jquery and adding the following to my app/javascript/application.js:

import jquery from "jquery"
window.jQuery = jquery
window.$ = jquery

$(function() {
    console.log("hello world")
})

Also tried adding jquery-rails gem to my gemfile....but neither worked.


问:
Accessing Objects without using Object methods
I need help understanding this specific code:

stocks[item[0]].inventory

How did the code above accessed or pin-pointed what needed to be pin-pointed using this “[item[0]]” on the stocks object? Can you please teach me how to pin-point thru the properties of an object in this way? What keywords or what can I search in Google to see more explanation for this? WHAT and HOW the logic works on this? Thank you!

```<code>const stocks = {
    Mangoes : {
      inventory: 300,
      cost: 2.00
    },
    'Star Apple' : {
      inventory: 400,
      cost: 3.00
    },
    'Jack Fruit' : {
      inventory: 300,
      cost: 4.00
    },
    Apples : 100,
    cost: 6.00
  }

const fruits = {
    items : [['Mangoes', 50],['Apples', 30]]
  }

  fruits.items.every((item) => {
    console.log(stocks[item[0]].inventory >= item[1])
  })

</code>```

Well, I can used Object.entries, keys, or values to alternatively do that but I can'treally seem to   understand how the logic of this code works stocks[item[0]].inventory

Body:
I need help understanding this specific code:

stocks[item[0]].inventory

How did the code above accessed or pin-pointed what needed to be pin-pointed using this “[item[0]]” on the stocks object? Can you please teach me how to pin-point thru the properties of an object in this way? What keywords or what can I search in Google to see more explanation for this? WHAT and HOW the logic works on this? Thank you!

const stocks = {
    Mangoes : {
      inventory: 300,
      cost: 2.00
    },
    'Star Apple' : {
      inventory: 400,
      cost: 3.00
    },
    'Jack Fruit' : {
      inventory: 300,
      cost: 4.00
    },
    Apples : 100,
    cost: 6.00
  }

const fruits = {
    items : [['Mangoes', 50],['Apples', 30]]
  }

  fruits.items.every((item) => {
    console.log(stocks[item[0]].inventory >= item[1])
  })

Well, I can used Object.entries, keys, or values to alternatively do that but I can'treally seem to   understand how the logic of this code works stocks[item[0]].inventory


问:
How to add database to existing Aurora MySQL cluster using CDK?
We are switching from Terraform to CDK using TypeScript.  I was able to create a database cluster (Aurora MySQL) with 2 instances.  Converting the existing terraform used to create the cluster to CDK was straightforward, however, I'm having a hard time finding documentation on adding databases to the cluster using CDK.

Terraform uses a MySQL Provider to add database to a cluster:

```<code># Configure the MySQL provider
provider "mysql" {
  endpoint = "my-database.example.com:3306"
  username = "app-user"
  password = "app-password"
}

# Create a Database
resource "mysql_database" "app" {
  name = "my_awesome_app"
}
</code>```

I've searched around trying to find the equivalent CDK construct and process for adding a database to an existing cluster with no luck.  Is this possible to do in CDK?

--- update ---

Code to standup a cluster with 2 instances in cdk:

```<code>new rds.DatabaseCluster(
    this,
    `db-cluster`,
    {
        clusterIdentifier: `cluster`,
        credentials: rds.Credentials.fromSecret(...),
        engine: rds.DatabaseClusterEngine.auroraMysql({
            version: rds.AuroraMysqlEngineVersion.of(...)
        }),
        instances: 2,
        instanceProps: {
            vpc,
            securityGroups: [dbSecurityGroup],
            instanceType: new ec2.InstanceType(...)
        },
        subnetGroup,
        instanceIdentifierBase: 'instance-',
    })
</code>```

Body:
We are switching from Terraform to CDK using TypeScript.  I was able to create a database cluster (Aurora MySQL) with 2 instances.  Converting the existing terraform used to create the cluster to CDK was straightforward, however, I'm having a hard time finding documentation on adding databases to the cluster using CDK.

Terraform uses a MySQL Provider to add database to a cluster:

# Configure the MySQL provider
provider "mysql" {
  endpoint = "my-database.example.com:3306"
  username = "app-user"
  password = "app-password"
}

# Create a Database
resource "mysql_database" "app" {
  name = "my_awesome_app"
}

I've searched around trying to find the equivalent CDK construct and process for adding a database to an existing cluster with no luck.  Is this possible to do in CDK?

--- update ---

Code to standup a cluster with 2 instances in cdk:

new rds.DatabaseCluster(
    this,
    `db-cluster`,
    {
        clusterIdentifier: `cluster`,
        credentials: rds.Credentials.fromSecret(...),
        engine: rds.DatabaseClusterEngine.auroraMysql({
            version: rds.AuroraMysqlEngineVersion.of(...)
        }),
        instances: 2,
        instanceProps: {
            vpc,
            securityGroups: [dbSecurityGroup],
            instanceType: new ec2.InstanceType(...)
        },
        subnetGroup,
        instanceIdentifierBase: 'instance-',
    })


问:
Fixed-effects contrasts in Matlab coefTest function
what does the Fixed-effects contrasts mean in the Matlab coefTest function?

I am looking at the examples given by the Matlab official tutorial:

https://www.mathworks.com/help/stats/linearmixedmodel.coeftest.html#bt1pl74-1

In the Shift example, they have specified a fixed-effects contrast as [0 1 -1]. I don't understand what are those 0, 1, and -1 means.

When calling pVal = coefTest(lme,[0 1 -1]), it can test if there is any difference between the evening and morning shifts. But I don't understand why. How about if I want to test if there is any difference between evening and night shifts? How can I modify the contrast matrix?


问:
Difficulty deploying Node API because of JWT
Hello developer friends!

I already concluded an (academic) e-commerce project a few months ago and did other projects later... including my portfolio... and I was waiting to complete them to deploy it and attach it to the portfolio.

It turns out that in the meantime Heroku withdrew free access in November as you know...but I managed to find a way to do it with Render.
The front-end and back-end are already running ... but I'm having some difficulty configuring the communication between the two.
I've been looking and seeing some tutorials to configure the environments... but it's a little confusing for me to apply them in the code because the course I took didn't teach about the production environment.

The application on my localhost works perfectly but when accessing the API in production I see that the problem is probably a JWT token but I can't configure it.
Does anyone have a solution that could help me?
Here are the links of the deploys if you need to check:

https://e-commerce-burgershop-api.onrender.com/

https://e-commerce-burgershop.onrender.com/

Repositories:

https://github.com/ed-radanovis/Burgershop_fullstack_project-backend

https://github.com/ed-radanovis/Burgershop_fullstack_project-frontend

[when accessing the API this message appears.]
(https://i.stack.imgur.com/niAwY.png)

If anyone can help me, I'll be immensely grateful because that's all I need to complete my portfolio and try to apply for a vacancy as a Dev.

I tried to configure the environment with dot env files and I also tried to configure it directly on the Render platform without success.  As I mentioned earlier, I'm a beginner and this is my first Full-stack application deployment and I don't know how to proceed.


问:
I have an error starting unit testing in android studio Execution failed for task ':app:testDebugUnitTest'
Please, I have a problem. When I start unit testing in Android Studio, this error appears, knowing that everything is fine in the project. However, when I start the test, this error appears, and it prevents me from conducting tests on applications or projects. Note that when I open a new project, this error does not appear and it works. unit testing well, while if I close the project, even if I don't do anything, the same error appears for no reason.enter image description here

[enter image description here]

(https://i.stack.imgur.com/xPuvI.png)


问:
Deploying an Azure Function to AKS deploys to my local instead of AKS
I'm trying to deploy an Azure Function to my AKS cluster using the following command:

```<code>func kubernetes deploy --name orchestrator --registry <ACR name> --namespace orchestrator
</code>```

Now this builds the image, but then instead of pushing to my ACR and deploying to AKS it builds the image and runs it in my Docker Desktop. I've tried turning Docker Desktop off, but then the func command doesn't work.

I've followed this documentation from Microsoft: https://learn.microsoft.com/en-us/azure/azure-functions/functions-kubernetes-keda

Does anyone have any ideas how to solve this?

EDIT:
The build is being created, but the next command "docker push..." isn't starting for some reason.

I checked to container logs and it seems my function has startup issues due to a missing connection string. I did add this connection string in the local.settings.json, so I don't really know what's up there.

Body:
I'm trying to deploy an Azure Function to my AKS cluster using the following command:

func kubernetes deploy --name orchestrator --registry <ACR name> --namespace orchestrator

Now this builds the image, but then instead of pushing to my ACR and deploying to AKS it builds the image and runs it in my Docker Desktop. I've tried turning Docker Desktop off, but then the func command doesn't work.

I've followed this documentation from Microsoft: https://learn.microsoft.com/en-us/azure/azure-functions/functions-kubernetes-keda

Does anyone have any ideas how to solve this?

EDIT:
The build is being created, but the next command "docker push..." isn't starting for some reason.

I checked to container logs and it seems my function has startup issues due to a missing connection string. I did add this connection string in the local.settings.json, so I don't really know what's up there.


问:
Excel VBA userform with combobox data in the workbook and the application hidden
I have an userform that receive some data in a couple of comboboxes. This data is managed in the workbook and the result is shown as a label in the userform end.

I want to operate this userform with the application hidden to get a cleaner view. I used those codes to open and close:

```<code>Private Sub Workbook_Open()

    Application.Visible = False

    UserForm1.Show

End Sub
</code>```
```<code>Private Sub UserForm_Terminate()

    Application.Quit

End Sub
</code>```

But now none of the comboboxes can communicate with the worksheet.

The calculation is very complex, with many tables and vlookup. So I can't program all in VBA.

Also, don't want the application blinking every time I input a number in a combobox.

Body:
I have an userform that receive some data in a couple of comboboxes. This data is managed in the workbook and the result is shown as a label in the userform end.

I want to operate this userform with the application hidden to get a cleaner view. I used those codes to open and close:

Private Sub Workbook_Open()

    Application.Visible = False

    UserForm1.Show

End Sub

Private Sub UserForm_Terminate()

    Application.Quit

End Sub

But now none of the comboboxes can communicate with the worksheet.

The calculation is very complex, with many tables and vlookup. So I can't program all in VBA.

Also, don't want the application blinking every time I input a number in a combobox.


问:
Import error, cant' find a txt file using Stackblitz
I'm trying to figure out why my Wordle repo refuses to run smoothly on StackBlitz, even though everything works fine on my IDE's local host.

I can't find an answer for this one unfortunately.

The error occurs when importing the txt file from src/wordBank/wordBank.txt to src/wordBank/Words.js

Link to my project on StackBlitz : https://stackblitz.com/github/shaharmes/wordle-react

Thanks in advance


问:
register 3 axis to 3 points
I try to register a set of 3 lines to a set of 3 points. The Coordinate System of both sets are not the same. So I need to find the rotation and translation of the lines so they pass through the points. Does anyone know a good method to do so?
little bit of Context:
the lines are the axis of a drilling wholes obtained by CT Scans and the points are marker obtained from a Motion Capture System. The markers were on the screw inserted into the drilling wholes. I need to match them in order that I can register the CT Data to the MotionCapture System
Thanks for any suggestion,
JG

I tried to match the distance of the three MoCap points to a set of points on the axis. The points estimated on the axis were not at the location as expected.
I also tried Horn's Method (which also not yielded the result expected):
https://www.mathworks.com/matlabcentral/fileexchange/26186-absolute-orientation-horn-s-method

Afterwards I would rotate the new points to the MoCap point with a svd based method.

Here an example (MATLAB):

```<code>MoCap_points = [243.9669  203.8436  215.5850
              104.2774  117.8749   85.7087
             -113.6220 -106.1354 -102.1162];
</code>```

Axis line in form r_0 + s_i*V_dir :

```<code>r_0_ = 1.0e+03 *[0.6269    0.6139    0.6055
                 -1.6006   -1.6178   -1.6009
                 -0.3004   -0.2963   -0.3010];
V_dir =     [0.6183    0.0112   -0.2819
            0.2555   -0.3098    0.3367
            0.7432    0.9507    0.8984];
</code>```

Title: register 3 axis to 3 points

Body:
I try to register a set of 3 lines to a set of 3 points. The Coordinate System of both sets are not the same. So I need to find the rotation and translation of the lines so they pass through the points. Does anyone know a good method to do so?
little bit of Context:
the lines are the axis of a drilling wholes obtained by CT Scans and the points are marker obtained from a Motion Capture System. The markers were on the screw inserted into the drilling wholes. I need to match them in order that I can register the CT Data to the MotionCapture System
Thanks for any suggestion,
JG

I tried to match the distance of the three MoCap points to a set of points on the axis. The points estimated on the axis were not at the location as expected.
I also tried Horn's Method (which also not yielded the result expected):
https://www.mathworks.com/matlabcentral/fileexchange/26186-absolute-orientation-horn-s-method

Afterwards I would rotate the new points to the MoCap point with a svd based method.

Here an example (MATLAB):

MoCap_points = [243.9669  203.8436  215.5850
              104.2774  117.8749   85.7087
             -113.6220 -106.1354 -102.1162];

Axis line in form r_0 + s_i*V_dir :

r_0_ = 1.0e+03 *[0.6269    0.6139    0.6055
                 -1.6006   -1.6178   -1.6009
                 -0.3004   -0.2963   -0.3010];
V_dir =     [0.6183    0.0112   -0.2819
            0.2555   -0.3098    0.3367
            0.7432    0.9507    0.8984];


问:
ObjectionJS - How can I use withGraphJoined, using a comma separeted column of ids as source?
I have a mysql view with a field grouped and concatenated data insidelike this:

```<code>|      a      |      b      |       c       |
----------------------------------------------
|      4      |    lalala   |     7,9,10    |
|      9      |     words   |     29,34,20  |
</code>```

it's possible use the c column to make a WithGraphJoined with another table?

Body:
I have a mysql view with a field grouped and concatenated data insidelike this:

|      a      |      b      |       c       |
----------------------------------------------
|      4      |    lalala   |     7,9,10    |
|      9      |     words   |     29,34,20  |

it's possible use the c column to make a WithGraphJoined with another table?


问:
Cloufront Signed URLs (or Cookies) for Wordpress Functions.php
I'm trying to implement signed urls for HLS videos on my wordpress site. Everything is already set from the AWS side (S3 & Cloudfront). I just need to add the php code in the functions.php file. Can anyone help me with that?

A code snippet to insert in the child theme's functions.php file


问:
Can I insert a website inside another with iframe?
I am trying to insert a website into mine, but when I do it the server blocks it with x-frame header.

I tried to use a bypass (https://www.npmjs.com/package/x-frame-bypass) but it didn't work.

Is it possible to make an iframe from another website on mine?


问:
how to use graphics sdl with QEMU
I would like to start a VM with the sdl graphics option but I always get the error message

error: internal error: process exited while connecting to monitor: 2022-12-22T20:37:42.896670Z qemu-system-x86_64: Display 'sdl' is not available.

I can't make it works either with gtk, as I get while I create the VM with wirsh

error: unsupported configuration: unknown graphics device type 'gtk'

I'm working on Ubuntu 20.04

I did install following packages:

sudo apt install  virt-manager spice-client-glib-usb-acl-helper spice-vdagent spice-webdavd spice-client-gtk libpixman-1-dev libcairo2-dev libpango1.0-dev libjpeg8-dev libgif-dev ninja-build qemu qemu-kvm virt-viewer libvirt-clients libvirt-daemon-system bridge-utils virtinst libvirt-daemon

Then I create my xml file with basics options

virt-install --name toto --noautoconsole --print-xml --memory 4000 --import --disk=/var/lib/libvirt/images/ubuntu20.04.qcow2,bus=sata --boot uefi --check all=off --graphics sdl > toto.xml
Works fine, I get inside the xml
<graphics type="sdl" display=":0" xauth="/home/user/.Xauthority"/>

and then I try to create the VM

virsh create toto.xml error: Failed to create domain from toto.xml error: internal error: process exited while connecting to monitor: 2022-12-22T20:41:12.001933Z qemu-system-x86_64: Display 'sdl' is not available.
Any ideas?

Title: how to use graphics sdl with QEMU


问:
BUGS making feature classification in XGboost
Friends can anybody help me to do xgboost classfication with this data found online on bearing fault in python
df = pd.read_csv("https://info.endaq.com/hubfs/Plots/bearing_data.csv")

@thanks

https://www.kaggle.com/code/felicityford/notebookc3b6035ab2
i have tried to compute some and atcahed the output in kaggle but still the train and test confuse me


问:
Test fn call inside same module - JEST
I want to test if a function is called with a parameter or not. It's app.js so this function is being called in the same file since it's the first function in my app.

Here's my app.js

```<code>const app = () => {
  // do something
};

app('test');

export default app;
</code>```

I don't really need a parameter and this is only for learning since I might use it often.

Here's my app.test.js

```<code>jest.mock('./app');
import app from './app';

test('app is called with an argument', () => {
  app();
  expect(app).toBeCalledWith('test');
});
</code>```

Of course it doesn't work since the testing here is on that app(); call inside test, not the original call with "test" parameter. This works well when I test a call for another function (in another module) inside app for example. I just import the function and change expect(app) to expect(otherFunctionName).

So, how can I test that initial app call? For example, I want to do a test that will fail if not given a specific parameter, in this case "test". Doing it inside the test makes no sense because I want to check the original code, the app("test"); call inside app.js.

Title: Test fn call inside same module - JEST

Body:
I want to test if a function is called with a parameter or not. It's app.js so this function is being called in the same file since it's the first function in my app.

Here's my app.js

const app = () => {
  // do something
};

app('test');

export default app;

I don't really need a parameter and this is only for learning since I might use it often.

Here's my app.test.js

jest.mock('./app');
import app from './app';

test('app is called with an argument', () => {
  app();
  expect(app).toBeCalledWith('test');
});

Of course it doesn't work since the testing here is on that app(); call inside test, not the original call with "test" parameter. This works well when I test a call for another function (in another module) inside app for example. I just import the function and change expect(app) to expect(otherFunctionName).

So, how can I test that initial app call? For example, I want to do a test that will fail if not given a specific parameter, in this case "test". Doing it inside the test makes no sense because I want to check the original code, the app("test"); call inside app.js.


问:
Why is my Pillow Image not being considered a File when I try to save it into my django image field?
I'm writing a Form Creation/Filling out forms app, and I'm to the point where I'm taking canvas data from the front-end and filled out fields of text input and draw them on a picture of the form with the pillow library. The problem is when I try to save the data for the form I get this error from "serializer.error" from django-rest-framework: "'FilledForm': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]}"

Here is the Api view:

```<code>@api_view(['POST'])
def postForm(request):
   dataDict = request.data
   FieldCoords = {}
   # Define Formtype

   selectedForm = dataDict["SelectedForm"]
   del dataDict["SelectedForm"]

   # Get Datalist for form creation
   datalist = list(FormData.objects.filter(FormType=selectedForm).values())

   #Set Signature Images on Form and Fill form with inputs

   for field in datalist:
    #Get Field Positions of Model
       if field["FieldType"] == "SignatureField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"])
       elif field["FieldType"] == "TextField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"],abs(field["height"]))
       elif field["FieldType"] == "DateField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"])

#print(FieldCoords)

#Place Signature Fields On FormImage

   sigFields = json.loads(dataDict["Signatures"])
   FormImage = Image.open(f"{MEDIA_ROOT}/{selectedForm}")
   del dataDict["Signatures"]
   for field in sigFields:
       datauri = sigFields[field]
       uri = datauri.split("base64,")
       sNameselect = field.split("  -  ")

       bytes = base64.b64decode(uri[1])
       img = Image.open(io.BytesIO(bytes))

       for keyCoordSet in FieldCoords:
           print(keyCoordSet)
           print("Name" + sNameselect[0])
           if sNameselect[0] == keyCoordSet:
               print("Im here")
               FormImage.paste(img, FieldCoords[keyCoordSet], mask=img)

#Place Text Fields On FormImage
   d1 = ImageDraw.Draw(FormImage)
   for field in dataDict:
       for keyCoordSet in FieldCoords:
           if field == keyCoordSet:
               myFont = ImageFont.truetype("LiberationMono-Regular.ttf",size=FieldCoords[keyCoordSet][2] - 10)
               d1.text((FieldCoords[keyCoordSet][0]+5,FieldCoords[keyCoordSet][1]+5), dataDict[field], fill =(255, 255, 255),font=myFont)
   time = str(timezone.now()).split(" ")

   image_bytes = io.BytesIO(FormImage.tobytes())
   imageFile = ContentFile(image_bytes.getvalue())
   print(imageFile.read())
   data = {                                           # Final data structure
       "FormType": selectedForm,
       "DateCreated": time[0],
       "Data": json.dumps(dataDict, indent = 4),
       "FilledForm": (str(selectedForm),imageFile)

   }

   serializer = FilledFormdataSerializer(data=data)

   print(type(imageFile))
   if serializer.is_valid():
       print("Im Valid")
       #serializer.save()
   else:
       print(serializer.errors)

   return Response("Returned Data")
</code>```

Here is the Model

```<code>class FilledForm(models.Model):
    FormType = models.CharField(max_length=100)
    DateCreated = models.DateField(default=timezone.now())
    Data = models.JSONField()
    FilledForm = models.ImageField()
</code>```

Here is the serializer

```<code>class FilledFormdataSerializer(serializers.ModelSerializer):
    class Meta:
        model = FilledForm
        fields = ["FormType", "DateCreated", "Data", "FilledForm"]

    def create(self, validated_data):
        print(validated_data)
        return FilledForm.objects.create(**validated_data)
</code>```

Heres the part of the Code where the issue is

```<code>#Place Text Fields On FormImage
d1 = ImageDraw.Draw(FormImage)
for field in dataDict:
    for keyCoordSet in FieldCoords:
        if field == keyCoordSet:
            myFont = ImageFont.truetype("LiberationMono-Regular.ttf",size=FieldCoords[keyCoordSet][2] - 10)
            d1.text((FieldCoords[keyCoordSet][0]+5,FieldCoords[keyCoordSet][1]+5), dataDict[field], fill =(255, 255, 255),font=myFont)
time = str(timezone.now()).split(" ")

image_bytes = io.BytesIO(FormImage.tobytes())
imageFile = ContentFile(image_bytes.getvalue())
print(imageFile.read())
data = {                                           # Final data structure
    "FormType": selectedForm,
    "DateCreated": time[0],
    "Data": json.dumps(dataDict, indent = 4),
    "FilledForm": (str(selectedForm),imageFile)

}

serializer = FilledFormdataSerializer(data=data)

print(type(imageFile))
if serializer.is_valid():
    print("Im Valid")
    #serializer.save()
else:
    print(serializer.errors)
</code>```

Here's all the module imported

```<code>from rest_framework.response import Response
from rest_framework.decorators import api_view
from api.serializer import DataSerializer, FilledFormdataSerializer
from django.core.files import File
from django.utils import timezone
from backend.models import FormData
from django.core.files.base import ContentFile
import json
from PIL import Image, ImageDraw, ImageFont
import base64
import io
from FormApp.settings import BASE_DIR, MEDIA_ROOT
</code>```

For some reason it's saying its not reading it as a file even though I'm converting it to bytes and rapping it in the ContentFile() object. Can I get some advice on why it's not saving to the image field?

Body:
I'm writing a Form Creation/Filling out forms app, and I'm to the point where I'm taking canvas data from the front-end and filled out fields of text input and draw them on a picture of the form with the pillow library. The problem is when I try to save the data for the form I get this error from "serializer.error" from django-rest-framework: "'FilledForm': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]}"

Here is the Api view:

@api_view(['POST'])
def postForm(request):
   dataDict = request.data
   FieldCoords = {}
   # Define Formtype

   selectedForm = dataDict["SelectedForm"]
   del dataDict["SelectedForm"]

   # Get Datalist for form creation
   datalist = list(FormData.objects.filter(FormType=selectedForm).values())

   #Set Signature Images on Form and Fill form with inputs

   for field in datalist:
    #Get Field Positions of Model
       if field["FieldType"] == "SignatureField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"])
       elif field["FieldType"] == "TextField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"],abs(field["height"]))
       elif field["FieldType"] == "DateField":
           FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"])

#print(FieldCoords)

#Place Signature Fields On FormImage

   sigFields = json.loads(dataDict["Signatures"])
   FormImage = Image.open(f"{MEDIA_ROOT}/{selectedForm}")
   del dataDict["Signatures"]
   for field in sigFields:
       datauri = sigFields[field]
       uri = datauri.split("base64,")
       sNameselect = field.split("  -  ")

       bytes = base64.b64decode(uri[1])
       img = Image.open(io.BytesIO(bytes))

       for keyCoordSet in FieldCoords:
           print(keyCoordSet)
           print("Name" + sNameselect[0])
           if sNameselect[0] == keyCoordSet:
               print("Im here")
               FormImage.paste(img, FieldCoords[keyCoordSet], mask=img)

#Place Text Fields On FormImage
   d1 = ImageDraw.Draw(FormImage)
   for field in dataDict:
       for keyCoordSet in FieldCoords:
           if field == keyCoordSet:
               myFont = ImageFont.truetype("LiberationMono-Regular.ttf",size=FieldCoords[keyCoordSet][2] - 10)
               d1.text((FieldCoords[keyCoordSet][0]+5,FieldCoords[keyCoordSet][1]+5), dataDict[field], fill =(255, 255, 255),font=myFont)
   time = str(timezone.now()).split(" ")

   image_bytes = io.BytesIO(FormImage.tobytes())
   imageFile = ContentFile(image_bytes.getvalue())
   print(imageFile.read())
   data = {                                           # Final data structure
       "FormType": selectedForm,
       "DateCreated": time[0],
       "Data": json.dumps(dataDict, indent = 4),
       "FilledForm": (str(selectedForm),imageFile)

   }

   serializer = FilledFormdataSerializer(data=data)

   print(type(imageFile))
   if serializer.is_valid():
       print("Im Valid")
       #serializer.save()
   else:
       print(serializer.errors)

   return Response("Returned Data")

Here is the Model

class FilledForm(models.Model):
    FormType = models.CharField(max_length=100)
    DateCreated = models.DateField(default=timezone.now())
    Data = models.JSONField()
    FilledForm = models.ImageField()

Here is the serializer

class FilledFormdataSerializer(serializers.ModelSerializer):
    class Meta:
        model = FilledForm
        fields = ["FormType", "DateCreated", "Data", "FilledForm"]

    def create(self, validated_data):
        print(validated_data)
        return FilledForm.objects.create(**validated_data)

Heres the part of the Code where the issue is

#Place Text Fields On FormImage
d1 = ImageDraw.Draw(FormImage)
for field in dataDict:
    for keyCoordSet in FieldCoords:
        if field == keyCoordSet:
            myFont = ImageFont.truetype("LiberationMono-Regular.ttf",size=FieldCoords[keyCoordSet][2] - 10)
            d1.text((FieldCoords[keyCoordSet][0]+5,FieldCoords[keyCoordSet][1]+5), dataDict[field], fill =(255, 255, 255),font=myFont)
time = str(timezone.now()).split(" ")

image_bytes = io.BytesIO(FormImage.tobytes())
imageFile = ContentFile(image_bytes.getvalue())
print(imageFile.read())
data = {                                           # Final data structure
    "FormType": selectedForm,
    "DateCreated": time[0],
    "Data": json.dumps(dataDict, indent = 4),
    "FilledForm": (str(selectedForm),imageFile)

}

serializer = FilledFormdataSerializer(data=data)

print(type(imageFile))
if serializer.is_valid():
    print("Im Valid")
    #serializer.save()
else:
    print(serializer.errors)

Here's all the module imported

from rest_framework.response import Response
from rest_framework.decorators import api_view
from api.serializer import DataSerializer, FilledFormdataSerializer
from django.core.files import File
from django.utils import timezone
from backend.models import FormData
from django.core.files.base import ContentFile
import json
from PIL import Image, ImageDraw, ImageFont
import base64
import io
from FormApp.settings import BASE_DIR, MEDIA_ROOT

For some reason it's saying its not reading it as a file even though I'm converting it to bytes and rapping it in the ContentFile() object. Can I get some advice on why it's not saving to the image field?


问:
How to install and have two Fortify Static Code Analyzer in the same machine
I have a Fortify SCA version 21.x in a linux machine, planning to upgrade the version to 22.x. But I would like to have both the versions in the same machine since I would take time to validate the working of 22.x version before uninstalling the 21.x version.

To install I have the command from the document : ./Fortify_SCA_and_Apps__linux_x64.run --mode
unattended

And it is to be noted that the below was mentioned in the document.

```<code>If you have multiple versions installed on the same system, the most recently installed version is
invoked when you run the command from the command line. Scanning source code from the Secure
Code Plugins also uses the most recently installed version of Fortify Static Code Analyzer.
</code>```

So will it work if I intend to keep both the SCA installed in different locations of the same machine, then executing and validating the scans using 22.x.

&

I have scenario to be aware if SCA 21.x will work when SCA 22.x is uninstalled.

Body:
I have a Fortify SCA version 21.x in a linux machine, planning to upgrade the version to 22.x. But I would like to have both the versions in the same machine since I would take time to validate the working of 22.x version before uninstalling the 21.x version.

To install I have the command from the document : ./Fortify_SCA_and_Apps__linux_x64.run --mode
unattended

And it is to be noted that the below was mentioned in the document.

If you have multiple versions installed on the same system, the most recently installed version is
invoked when you run the command from the command line. Scanning source code from the Secure
Code Plugins also uses the most recently installed version of Fortify Static Code Analyzer.

So will it work if I intend to keep both the SCA installed in different locations of the same machine, then executing and validating the scans using 22.x.

&

I have scenario to be aware if SCA 21.x will work when SCA 22.x is uninstalled.


问:
Using segmantic image segmentation
I tried using the following example for an image I have. You can find the link here. To reproduce the results I am getting consider the following image

When I apply the following code

```<code>import pixellib
from pixellib.semantic import semantic_segmentation

segment_image = semantic_segmentation()
segment_image.load_pascalvoc_model("deeplabv3_xception_tf_dim_ordering_tf_kernels.h5")
segment_image.segmentAsPascalvoc("125.jpg", output_image_name = "output.jpg")
</code>```

I just get a black image. What I want is to segment the packages in the belt.

Title: Using segmantic image segmentation

Body:
I tried using the following example for an image I have. You can find the link here. To reproduce the results I am getting consider the following image

When I apply the following code

import pixellib
from pixellib.semantic import semantic_segmentation

segment_image = semantic_segmentation()
segment_image.load_pascalvoc_model("deeplabv3_xception_tf_dim_ordering_tf_kernels.h5")
segment_image.segmentAsPascalvoc("125.jpg", output_image_name = "output.jpg")

I just get a black image. What I want is to segment the packages in the belt.


问:
Multithreading gethostbyaddr causes wifi to drop
So I'm writing a python script that takes a large amount of IPs in a set (~20k) and the goal is to resolve the hostname of each IP using gethostbyaddr. In an attempt to make the script run as fast as possible I implemented multithreading. Note that my computer running the script is on a wired ethernet connection. The issue is that while running the script, I've noticed that my wifi connection drops (on my phone, on every other household device) however the script will continue to run fine and once completed, wifi is restored. I've tweaked around with the amount of threads active at once and this is likely the issue. If I set the limit to say 500 threads, the script will complete in 2 minutes, but the wifi will be dropped. If I lower it down to <50 threads the wifi is fine, but the script will take ages to complete. As the limit goes higher, the wifi connection suffers until a point of just dropping. So I see that I am essentially DDoSing myself so my question is if there is a way to efficiently complete the script without bottlenecking my wifi. Or maybe there is something wrong with my implementation. My code is below:</p>
```<code>def lookup_IP(ip):
    result = tuple()
    try:
        host, aliases, _ = socket.gethostbyaddr(ip)
        result = (ip, host)
    except socket.herror:
        result = (ip, 'no host found')
    except Exception:
        result = (ip, 'error finding host')
    return result

with futures.ThreadPoolExecutor(500) as executor:
    submitted_threads = {executor.submit(lookup_IP, ip): ip for ip in all_IPs}
    for thread in futures.as_completed(submitted_threads):
        try:
            data = thread.result()
            #add data to a dictionary
        except Exception as err:
            #print error

#rest of code
</code>```

Body:
So I'm writing a python script that takes a large amount of IPs in a set (~20k) and the goal is to resolve the hostname of each IP using gethostbyaddr. In an attempt to make the script run as fast as possible I implemented multithreading. Note that my computer running the script is on a wired ethernet connection. The issue is that while running the script, I've noticed that my wifi connection drops (on my phone, on every other household device) however the script will continue to run fine and once completed, wifi is restored. I've tweaked around with the amount of threads active at once and this is likely the issue. If I set the limit to say 500 threads, the script will complete in 2 minutes, but the wifi will be dropped. If I lower it down to <50 threads the wifi is fine, but the script will take ages to complete. As the limit goes higher, the wifi connection suffers until a point of just dropping. So I see that I am essentially DDoSing myself so my question is if there is a way to efficiently complete the script without bottlenecking my wifi. Or maybe there is something wrong with my implementation. My code is below:

def lookup_IP(ip):
    result = tuple()
    try:
        host, aliases, _ = socket.gethostbyaddr(ip)
        result = (ip, host)
    except socket.herror:
        result = (ip, 'no host found')
    except Exception:
        result = (ip, 'error finding host')
    return result

with futures.ThreadPoolExecutor(500) as executor:
    submitted_threads = {executor.submit(lookup_IP, ip): ip for ip in all_IPs}
    for thread in futures.as_completed(submitted_threads):
        try:
            data = thread.result()
            #add data to a dictionary
        except Exception as err:
            #print error

#rest of code


问:
I can't build Flutter app after 1 year, but I don't know what the problem is
Hi, I want to build a flutter app after 1 year, but I don't know what is problematic,

I don't know why there is nothing at below the path in the error code, when I open them there is nothing with error 404!

Error code:

```<code>    PS D:\projects\soalDarsiApp\Flutter\untitled\android> flutter build apk --release
Changing current working directory to: D:\projects\soalDarsiApp\Flutter\untitled

Building with sound null safety.

Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:lintVitalRelease'.
> Could not resolve all artifacts for configuration ':url_launcher_android:debugUnitTestRuntimeClasspath'.
   > Could not find core-1.0.0.aar (androidx.test:core:1.0.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/androidx/test/core/1.0.0/core-1.0.0.aar
   > Could not find monitor-1.2.0.aar (androidx.test:monitor:1.2.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/androidx/test/monitor/1.2.0/monitor-1.2.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s
Running Gradle task 'assembleRelease'...                           14.4s
Gradle task assembleRelease failed with exit code 1
</code>```

gradle-wrapper.properties:

```<code>#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip
</code>```

./android/build.gradle:

```<code>buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
</code>```

./android/app/build.gradle:

```<code>android {

    // compileSdkVersion flutter.compileSdkVersion
    compileSdkVersion 32
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
...

}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

</code>```

I'm confused.

Thank you!

Body:
Hi, I want to build a flutter app after 1 year, but I don't know what is problematic,

I don't know why there is nothing at below the path in the error code, when I open them there is nothing with error 404!

Error code:

    PS D:\projects\soalDarsiApp\Flutter\untitled\android> flutter build apk --release
Changing current working directory to: D:\projects\soalDarsiApp\Flutter\untitled

Building with sound null safety.

Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:lintVitalRelease'.
> Could not resolve all artifacts for configuration ':url_launcher_android:debugUnitTestRuntimeClasspath'.
   > Could not find core-1.0.0.aar (androidx.test:core:1.0.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/androidx/test/core/1.0.0/core-1.0.0.aar
   > Could not find monitor-1.2.0.aar (androidx.test:monitor:1.2.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/androidx/test/monitor/1.2.0/monitor-1.2.0.aar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s
Running Gradle task 'assembleRelease'...                           14.4s
Gradle task assembleRelease failed with exit code 1

gradle-wrapper.properties:

#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip

./android/build.gradle:

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

./android/app/build.gradle:

android {

    // compileSdkVersion flutter.compileSdkVersion
    compileSdkVersion 32
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
...

}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

I'm confused.

Thank you!


问:
FFmpeg remuxing parts of an audio file
I'm trying to remux individual tracks from a FLAC file using the FFmpeg libraries.
I get the starting timestamps from a Cue sheet, I seek to the timestamps using avformat_seek_file. However after writing the packets to output files, they only have data from the beginning of the input file.

This is the code snippet which opens the input FLAC and also creates an output AVFormatContext for each track. I'm guessing the issue is avformat_seek_file, it doesn't seem to do anything, since even though I seek to the beginning of a track, the output file contains data from the beginning of the input.

```<code>    for(int i = 0; i <= sheet.ntracks; i++) {
        sheet.avfmtctx = avformat_alloc_context();
        if(avformat_open_input(&sheet.avfmtctx, sheet.file, NULL, NULL) < 0) {
            fprintf(stderr,
                    "avformat_open_input(): failed to open %s\n",
                    sheet.file);
            return 1;
        }
        int audio_stream_idx = -1;
        for(int i = 0; i < sheet.avfmtctx->nb_streams; i++) {
            if(sheet.avfmtctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
                audio_stream_idx = i;
                break;
            }
        }
        avformat_find_stream_info(sheet.avfmtctx, NULL);
        AVFormatContext *output;
        char *filepath = title_to_filepath(&sheet.tracks[i], sheet.file);
        avformat_alloc_output_context2(&output, NULL, NULL, filepath);
        AVStream *out_audio_stream = avformat_new_stream(output, NULL);
        avcodec_parameters_copy(out_audio_stream->codecpar,
                                sheet.avfmtctx->streams[audio_stream_idx]->codecpar);

        if(avio_open(&output->pb, filepath, AVIO_FLAG_WRITE) < 0) {
            fprintf(stderr, "Failed to open %s for writing\n", filepath);
            return 1;
        }
        if(avformat_write_header(output, NULL) < 0) {
            fprintf(stderr, "avformat_write_header() failed\n");
            return 1;
        }
        int64_t current_frame = sheet.tracks[i].index;
        int64_t next_track_index = (i < sheet.ntracks) ?
                                   sheet.tracks[i + 1].index :
                                   INT64_MAX;
        if(avformat_seek_file(sheet.avfmtctx,
                           -1,
                           INT64_MIN,
                           current_frame,
                           current_frame,
                           0) < 0) {
            fprintf(stderr, "Failed to seek to the index of track %d\n", i);
            avformat_free_context(sheet.avfmtctx);
            sheet.avfmtctx = NULL;
            av_write_trailer(output);
            avio_closep(&output->pb);
            avformat_free_context(output);
            free(filepath);
            continue;
        }
        AVPacket *pkt = av_packet_alloc();
        int64_t pts_diff = AV_NOPTS_VALUE, dts_diff = AV_NOPTS_VALUE;
        while(current_frame < next_track_index && !avio_feof(output->pb)) {
            int ret;
            if((ret = av_read_frame(sheet.avfmtctx, pkt)) < 0) {
                if(ret != AVERROR_EOF)
                    fprintf(stderr, "av_read_frame() failed: %s\n", av_err2str(ret));
                break;
            }
            if(pkt->stream_index != audio_stream_idx)
                continue;
            // runs only once
            if(pts_diff == AV_NOPTS_VALUE && dts_diff == AV_NOPTS_VALUE) {
                pts_diff = pkt->pts;
                dts_diff = pkt->dts;
            }

            pkt->stream_index = 0; // first and only stream
            pkt->pts -= pts_diff;
            pkt->dts -= dts_diff;
            pkt->pos = -1;
            av_interleaved_write_frame(output, pkt);

            current_frame++;
        }

        avformat_free_context(sheet.avfmtctx);
        sheet.avfmtctx = NULL;

        av_write_trailer(output);
        av_packet_free(&pkt);
        avio_closep(&output->pb);
        avformat_free_context(output);

        free(filepath);
    }

</code>```

current_frame and next_track_index are calculated from the INDEX lines in the Cue sheet: MM * 60 * 75 + SS * 75 + FF.
Can someone tell me what I'm doing wrong, and how to get the data I need from the input?

Title: FFmpeg remuxing parts of an audio file

Body:
I'm trying to remux individual tracks from a FLAC file using the FFmpeg libraries.
I get the starting timestamps from a Cue sheet, I seek to the timestamps using avformat_seek_file. However after writing the packets to output files, they only have data from the beginning of the input file.

This is the code snippet which opens the input FLAC and also creates an output AVFormatContext for each track. I'm guessing the issue is avformat_seek_file, it doesn't seem to do anything, since even though I seek to the beginning of a track, the output file contains data from the beginning of the input.

    for(int i = 0; i <= sheet.ntracks; i++) {
        sheet.avfmtctx = avformat_alloc_context();
        if(avformat_open_input(&sheet.avfmtctx, sheet.file, NULL, NULL) < 0) {
            fprintf(stderr,
                    "avformat_open_input(): failed to open %s\n",
                    sheet.file);
            return 1;
        }
        int audio_stream_idx = -1;
        for(int i = 0; i < sheet.avfmtctx->nb_streams; i++) {
            if(sheet.avfmtctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
                audio_stream_idx = i;
                break;
            }
        }
        avformat_find_stream_info(sheet.avfmtctx, NULL);
        AVFormatContext *output;
        char *filepath = title_to_filepath(&sheet.tracks[i], sheet.file);
        avformat_alloc_output_context2(&output, NULL, NULL, filepath);
        AVStream *out_audio_stream = avformat_new_stream(output, NULL);
        avcodec_parameters_copy(out_audio_stream->codecpar,
                                sheet.avfmtctx->streams[audio_stream_idx]->codecpar);

        if(avio_open(&output->pb, filepath, AVIO_FLAG_WRITE) < 0) {
            fprintf(stderr, "Failed to open %s for writing\n", filepath);
            return 1;
        }
        if(avformat_write_header(output, NULL) < 0) {
            fprintf(stderr, "avformat_write_header() failed\n");
            return 1;
        }
        int64_t current_frame = sheet.tracks[i].index;
        int64_t next_track_index = (i < sheet.ntracks) ?
                                   sheet.tracks[i + 1].index :
                                   INT64_MAX;
        if(avformat_seek_file(sheet.avfmtctx,
                           -1,
                           INT64_MIN,
                           current_frame,
                           current_frame,
                           0) < 0) {
            fprintf(stderr, "Failed to seek to the index of track %d\n", i);
            avformat_free_context(sheet.avfmtctx);
            sheet.avfmtctx = NULL;
            av_write_trailer(output);
            avio_closep(&output->pb);
            avformat_free_context(output);
            free(filepath);
            continue;
        }
        AVPacket *pkt = av_packet_alloc();
        int64_t pts_diff = AV_NOPTS_VALUE, dts_diff = AV_NOPTS_VALUE;
        while(current_frame < next_track_index && !avio_feof(output->pb)) {
            int ret;
            if((ret = av_read_frame(sheet.avfmtctx, pkt)) < 0) {
                if(ret != AVERROR_EOF)
                    fprintf(stderr, "av_read_frame() failed: %s\n", av_err2str(ret));
                break;
            }
            if(pkt->stream_index != audio_stream_idx)
                continue;
            // runs only once
            if(pts_diff == AV_NOPTS_VALUE && dts_diff == AV_NOPTS_VALUE) {
                pts_diff = pkt->pts;
                dts_diff = pkt->dts;
            }

            pkt->stream_index = 0; // first and only stream
            pkt->pts -= pts_diff;
            pkt->dts -= dts_diff;
            pkt->pos = -1;
            av_interleaved_write_frame(output, pkt);

            current_frame++;
        }

        avformat_free_context(sheet.avfmtctx);
        sheet.avfmtctx = NULL;

        av_write_trailer(output);
        av_packet_free(&pkt);
        avio_closep(&output->pb);
        avformat_free_context(output);

        free(filepath);
    }

current_frame and next_track_index are calculated from the INDEX lines in the Cue sheet: MM * 60 * 75 + SS * 75 + FF.
Can someone tell me what I'm doing wrong, and how to get the data I need from the input?


问:
Vue test utils cannot find child component
I am running a Vue 3.0 with Quasar library. In the application there is a component that has a child component in it. With vue test utils v 2.2.6, I cannot seem to locate the child components in order to generate events. Why?

Simplified Parent Component

```<code><template>
  <q-dialog square persistent transition-show="scale" transition-hide="scale" >
      <q-card-section  class="q-px-xs q-pt-none">
        <ChildComponent/>
      </q-card-section>
  </q-dialog>
</template>
<script setup>
//imports, props, etc
</script>

<style> ... </style>
</code>```

Simplified Child Component

```<code><template>
<q-card square bordered id="new-recipient-root-element" class="new-recipient">
<q-form>...</q-form>
</q-card>
</template>
<script setup>
//imports, props, etc
</script>

<style> ... </style>
</code>```

Using Jest / vue test utils like so:

```<code> wrapper = mount(ParentComponent, {
      props: { ...},
      global: {
        plugins: [i18n],
        provide: {
          store: ...
        },
        mocks: { ...        }
      }
    });
    wrapper.vm.show();
    await nextTick();
    domWrapper = new DOMWrapper(document.body);

...

 await domWrapper.findComponent(ChildComponent).vm.$emit('myEvent');
</code>```

domWrapper.findComponent(ChildComponent) always returns nothing. If I try  domWrapper.findAllComponents(), it returns an empty array.
Also noticed that I can locate all the elements, but if I click on a button, no event seems to be generated since the handlers are not called and wrapper.emitted() contains nothing.

What am I missing?

Body:
I am running a Vue 3.0 with Quasar library. In the application there is a component that has a child component in it. With vue test utils v 2.2.6, I cannot seem to locate the child components in order to generate events. Why?

Simplified Parent Component

<template>
  <q-dialog square persistent transition-show="scale" transition-hide="scale" >
      <q-card-section  class="q-px-xs q-pt-none">
        <ChildComponent/>
      </q-card-section>
  </q-dialog>
</template>

Simplified Child Component

<template>
<q-card square bordered id="new-recipient-root-element" class="new-recipient">
<q-form>...</q-form>
</q-card>
</template>

Using Jest / vue test utils like so:

 wrapper = mount(ParentComponent, {
      props: { ...},
      global: {
        plugins: [i18n],
        provide: {
          store: ...
        },
        mocks: { ...        }
      }
    });
    wrapper.vm.show();
    await nextTick();
    domWrapper = new DOMWrapper(document.body);

...

 await domWrapper.findComponent(ChildComponent).vm.$emit('myEvent');

domWrapper.findComponent(ChildComponent) always returns nothing. If I try  domWrapper.findAllComponents(), it returns an empty array.
Also noticed that I can locate all the elements, but if I click on a button, no event seems to be generated since the handlers are not called and wrapper.emitted() contains nothing.

What am I missing?


问:
how could I hook a boolean function and change the return value with frida?
I am new to frida and I tried several methods with no luck..
I am attempting to modify the return value of the boolean function to be false but I keep getting the following error:
Process crashed: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.cgflauowyeim.pxhvwigtoc.App.I()' on a null object reference

This is the class:

```<code>public class App extends Application {
    private static App M;
    public libInterface f = null;
    public int g = 0;

    /* renamed from: K  reason: collision with other method in class */
    public boolean m42K() {
        return false;
    }

    public boolean I() {
        try {
            if (!Build.FINGERPRINT.startsWith(v.K((Object) "\u000fQ\u0006Q\u001a]\u000b"))) {
                if (!m42K()) {
                    if (Build.FINGERPRINT.startsWith(u.K("&a&e?d")) || Build.MODEL.contains(v.K((Object) "S\u0007[\u000fX\rk\u001bP\u0003")) || Build.MODEL.contains(u.K("\rg=f)~'x")) || Build.MODEL.contains(v.K((Object) "/w-\u0014\u0010\f^\u0014\u0018\\\u0007Z\r")) || Build.MODEL.contains(u.K("Y<k&n)x,*\u0018I")) || Build.MODEL.contains(v.K((Object) ")Z\fF\u0007]\f\u0014;p#")) || Build.MODEL.contains(u.K(";n#U/z e&o")) || Build.MODEL.contains(v.K((Object) "u'g8")) || Build.MODEL.contains(u.K("\u00102pz:e")) || Build.MODEL.contains(v.K((Object) ">]\u001a@\u001dU\u0004")) || Build.MODEL.contains(u.K("\u001eG?k:o")) || Build.MANUFACTURER.contains(v.K((Object) "$}%}<q,")) || Build.MANUFACTURER.contains(u.K("\u0005E\nC\u0004O")) || Build.MANUFACTURER.contains(v.K((Object) "b%C\tF\r")) || Build.MANUFACTURER.contains(u.K("\\!x<)f")) || Build.MANUFACTURER.contains(v.K((Object) "e-y=")) || Build.MANUFACTURER.contains(u.K("&a&e?d")) || Build.MANUFACTURER.contains(v.K((Object) "s\rZ\u0011Y\u0007V\u0001X\r")) || Build.MANUFACTURER.contains(u.K("\u000fo&s%e<c'd")) || ((Build.BRAND.startsWith(v.K((Object) "\u000fQ\u0006Q\u001a]\u000b")) && Build.DEVICE.startsWith(u.K("m-d-x!i"))) || v.K((Object) "S\u0007[\u000fX\rk\u001bP\u0003").equals(Build.PRODUCT))) {
                        return true;
                    }
                    return false;
                }
            }
        } catch (Exception unused) {
        }
        return true;
    }

    public void onCreate() {
        super.onCreate();
        if (!I()) {
            try {
                if (M == null) {
                    K(this);
                }
                Thread.setDefaultUncaughtExceptionHandler(new u());
                o.K().m50K();
                v.K().m55K((Context) this);
                aa.K().I();
                l.K().I(this);
                startForegroundService(new Intent(this, ServiceHandler.class));
                I();
            } catch (Exception unused) {
            }
        }
    }

    private static synchronized /* synthetic */ void K(App app) {
        synchronized (App.class) {
            M = app;
        }
    }

    /* renamed from: K  reason: collision with other method in class */
    public void m41K() {
        try {
            System.exit(0);
        } catch (Exception unused) {
        }
    }

    public static App K() {
        return M;
    }
}
</code>```

This is my frida script:

```<code>Java.perform(function() {
  var App = Java.use('com.cgflauowyeim.pxhvwigtoc.App');
  App.I.implementation = function() {
    console.log('I method called, returning false');
    return false;
  };

  // Register a hook that is executed before the onCreate method is called
  App.onCreate.before(function() {
    console.log('onCreate method called, replacing I method');
    App.I.implementation = function() {
      console.log('I method called, returning false');
      return false;
    };
  });
});
</code>```

I managed to bypass the vm detection editing the smali code and compiling it back but I would like to try to achieve the same result using frida. also i tried to enumerate the overload but didnt find any and kept getting the same error "Attempt to invoke virtual method 'boolean com.cgflauowyeim.pxhvwigtoc.App.I()' on a null object reference".

Any ideas?

Body:
I am new to frida and I tried several methods with no luck..
I am attempting to modify the return value of the boolean function to be false but I keep getting the following error:
Process crashed: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.cgflauowyeim.pxhvwigtoc.App.I()' on a null object reference

This is the class:

public class App extends Application {
    private static App M;
    public libInterface f = null;
    public int g = 0;

    /* renamed from: K  reason: collision with other method in class */
    public boolean m42K() {
        return false;
    }

    public boolean I() {
        try {
            if (!Build.FINGERPRINT.startsWith(v.K((Object) "\u000fQ\u0006Q\u001a]\u000b"))) {
                if (!m42K()) {
                    if (Build.FINGERPRINT.startsWith(u.K("&a&e?d")) || Build.MODEL.contains(v.K((Object) "S\u0007[\u000fX\rk\u001bP\u0003")) || Build.MODEL.contains(u.K("\rg=f)~'x")) || Build.MODEL.contains(v.K((Object) "/w-\u0014\u0010\f^\u0014\u0018\\\u0007Z\r")) || Build.MODEL.contains(u.K("Y<k&n)x,*\u0018I")) || Build.MODEL.contains(v.K((Object) ")Z\fF\u0007]\f\u0014;p#")) || Build.MODEL.contains(u.K(";n#U/z e&o")) || Build.MODEL.contains(v.K((Object) "u'g8")) || Build.MODEL.contains(u.K("\u00102pz:e")) || Build.MODEL.contains(v.K((Object) ">]\u001a@\u001dU\u0004")) || Build.MODEL.contains(u.K("\u001eG?k:o")) || Build.MANUFACTURER.contains(v.K((Object) "$}%}<q,")) || Build.MANUFACTURER.contains(u.K("\u0005E\nC\u0004O")) || Build.MANUFACTURER.contains(v.K((Object) "b%C\tF\r")) || Build.MANUFACTURER.contains(u.K("\\!x<)f")) || Build.MANUFACTURER.contains(v.K((Object) "e-y=")) || Build.MANUFACTURER.contains(u.K("&a&e?d")) || Build.MANUFACTURER.contains(v.K((Object) "s\rZ\u0011Y\u0007V\u0001X\r")) || Build.MANUFACTURER.contains(u.K("\u000fo&s%e<c'd")) || ((Build.BRAND.startsWith(v.K((Object) "\u000fQ\u0006Q\u001a]\u000b")) && Build.DEVICE.startsWith(u.K("m-d-x!i"))) || v.K((Object) "S\u0007[\u000fX\rk\u001bP\u0003").equals(Build.PRODUCT))) {
                        return true;
                    }
                    return false;
                }
            }
        } catch (Exception unused) {
        }
        return true;
    }

    public void onCreate() {
        super.onCreate();
        if (!I()) {
            try {
                if (M == null) {
                    K(this);
                }
                Thread.setDefaultUncaughtExceptionHandler(new u());
                o.K().m50K();
                v.K().m55K((Context) this);
                aa.K().I();
                l.K().I(this);
                startForegroundService(new Intent(this, ServiceHandler.class));
                I();
            } catch (Exception unused) {
            }
        }
    }

    private static synchronized /* synthetic */ void K(App app) {
        synchronized (App.class) {
            M = app;
        }
    }

    /* renamed from: K  reason: collision with other method in class */
    public void m41K() {
        try {
            System.exit(0);
        } catch (Exception unused) {
        }
    }

    public static App K() {
        return M;
    }
}

This is my frida script:

Java.perform(function() {
  var App = Java.use('com.cgflauowyeim.pxhvwigtoc.App');
  App.I.implementation = function() {
    console.log('I method called, returning false');
    return false;
  };

  // Register a hook that is executed before the onCreate method is called
  App.onCreate.before(function() {
    console.log('onCreate method called, replacing I method');
    App.I.implementation = function() {
      console.log('I method called, returning false');
      return false;
    };
  });
});

I managed to bypass the vm detection editing the smali code and compiling it back but I would like to try to achieve the same result using frida. also i tried to enumerate the overload but didnt find any and kept getting the same error "Attempt to invoke virtual method 'boolean com.cgflauowyeim.pxhvwigtoc.App.I()' on a null object reference".

Any ideas?