问:
AWS CDK VPC with 2 subnets running 2 Fargate services
i am having troubles setting up my AWS VPC via cdk.
I want to create a VPC with 2 subnets, one public and one private_isolated, with no nat gateways and one internet gateway. In the public i will host my node web server and in the private my java microservice. Since i don't know a lot about networking in general, i used a private dns namespace and got the 2 services communicate to each other via AWS Service Discovery*.
The thing is, when i deploy my stack, it gets stuck in creating the java fargate service, and i think the problem is because of the private_isolated subnet. So i added interface endpoints for ecr_docker and ecr and even an s3 gateway endpoint, but the service still remains stuck on create in progress.
Here's my code:

```<code>export class EcsServiceDiscoveryStack extends Stack {
 readonly serviceBack = "back-service";
 readonly servicePdf = "pdf-service";
 readonly namespace = "env.test";
 readonly vpc: Vpc;
 readonly cluster: Cluster;
 readonly dnsNamespace: PrivateDnsNamespace;
 readonly ingressSecurityGroup: SecurityGroup;
 readonly egressSecurityGroup: SecurityGroup;

 constructor(scope: Construct, id: string, props?: StackProps) {
  super(scope, id, props);

  /* ----------------------------------- VPC ---------------------------------- */

  const subnetConfig: ec2.SubnetConfiguration[] = [
   {
    name: "test-public-subnet",
   subnetType: SubnetType.PUBLIC,
   },
   {
    name: "test-private-subnet",
    subnetType: SubnetType.PRIVATE_ISOLATED,
   },
  ];

  this.vpc = new ec2.Vpc(this, "test-vpc", {
   maxAzs: 1,
   subnetConfiguration: subnetConfig,
   gatewayEndpoints: {
    S3: { service: ec2.GatewayVpcEndpointAwsService.S3 },
   },
  });

  /* ------------------------- INTERFACE VPC ENDPOINT ------------------------- */
  this.vpc.addInterfaceEndpoint("aws-ecr_docker-endpoint", {
   service: ec2.InterfaceVpcEndpointAwsService.ECR_DOCKER,
   privateDnsEnabled: true,
   subnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
   open: true,
  });

  this.vpc.addInterfaceEndpoint("aws-ecr-endpoint", {
   service: ec2.InterfaceVpcEndpointAwsService.ECR,
   privateDnsEnabled: true,
   subnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
   open: true,
  });

  /* --------------------------------- CLUSTER -------------------------------- */

  this.cluster = new ecs.Cluster(this, "test-cluster", {
   clusterName: "test-cluster",
   vpc: this.vpc,
  });

  /* ------------------------------ DNS NAMESPACE ----------------------------- */

  this.dnsNamespace = new servicediscovery.PrivateDnsNamespace(
   this,
   "DnsNamespace",
   {
    name: this.namespace,
    vpc: this.vpc,
    description: "Private DnsNamespace for test environment",
   }
  );

  /* -------------------------------- TASK ROLE ------------------------------- */

  //NODE
  const backTaskrole = new iam.Role(this, "backTaskExecutionRole", {
   assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
  });

  backTaskrole.addManagedPolicy(
   iam.ManagedPolicy.fromAwsManagedPolicyName(
    "service-role/AmazonECSTaskExecutionRolePolicy"
   )
  );

  //JAVA
  const pdfTaskRole = new iam.Role(this, "pdfTaskExecutionRole", {
   assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
  });

  pdfTaskRole.addManagedPolicy(
   iam.ManagedPolicy.fromAwsManagedPolicyName(
    "service-role/AmazonECSTaskExecutionRolePolicy"
   )
  );

  /* ---------------------------- TASKS DEFINITIONS ---------------------------- */

  //NODE
  const backFargateTaskDefinition = new ecs.FargateTaskDefinition(
   this,
   `${this.serviceBack}ServiceTaskDef`,
   {
    cpu: 256,
    memoryLimitMiB: 512,
    taskRole: backTaskrole,
   }
  );

  //JAVA
  const pdfFargateTaskDefinition = new ecs.FargateTaskDefinition(
   this,
   `${this.servicePdf}ServiceTaskDef`,
   {
    cpu: 256,
    memoryLimitMiB: 512,
    taskRole: pdfTaskRole,
   }
  );

  /* ---------------------------- SERVICE LOG GROUP --------------------------- */

  //NODE
  const backServiceLogGroup = new logs.LogGroup(
   this,
   `${this.serviceBack}ServiceLogGroup`,
   {
    logGroupName: `/ecs/${this.serviceBack}Service`,
    removalPolicy: RemovalPolicy.DESTROY,
   }
  );

  //JAVA
  const pdfServiceLogGroup = new logs.LogGroup(
   this,
   `${this.servicePdf}ServiceLogGroup`,
   {
    logGroupName: `/ecs/${this.servicePdf}Service`,
    removalPolicy: RemovalPolicy.DESTROY,
   }
  );

  /* ------------------------------- LOG DRIVER ------------------------------- */

  //NODE

  const backServiceLogDriver = new ecs.AwsLogDriver({
   logGroup: backServiceLogGroup,

---
  streamPrefix: `${this.serviceBack}Service`,
  });

  //JAVA

  const pdfServiceLogDriver = new ecs.AwsLogDriver({
   logGroup: pdfServiceLogGroup,
   streamPrefix: `${this.servicePdf}Service`,
  });

  /* ---------------------------- REPOISTORY (ECR) ---------------------------- */

  //NODE
  const repoBackNode = Repository.fromRepositoryName(
   this,
   "back-nodejs",
   "task-nodejs-test"
  );

  //JAVA
  const repoBackJava = Repository.fromRepositoryName(
   this,
   "pdf-java",
   "task-nodejs-test"
  );

  /* -------------------------------- CONTAINER ------------------------------- */

  //NODE

  const backServiceContainer = backFargateTaskDefinition.addContainer(
   `${this.serviceBack}ServiceContainer`,
   {
    containerName: `${this.serviceBack}ServiceContainer`,
    essential: true,
    image: ecs.ContainerImage.fromEcrRepository(repoBackNode),
    logging: backServiceLogDriver,
    portMappings: [{ containerPort: 80 }],
    environment: {
     PORT: "80",
     NAME: "back-nodejs",
     PDF_HOST: `http://${this.servicePdf}.${this.namespace}:80`,
    },
   }
  );

  //JAVA
  const pdfServiceContainer = pdfFargateTaskDefinition.addContainer(
   `${this.servicePdf}ServiceContainer`,
   {
    containerName: `${this.servicePdf}ServiceContainer`,
    image: ecs.ContainerImage.fromEcrRepository(repoBackJava),
    logging: pdfServiceLogDriver,
    portMappings: [{ containerPort: 80 }],
    environment: {
     PORT: "80",
     NAME: "pdf-java",
     PDF_HOST: this.servicePdf,
    },
   }
  );

  /* ----------------------------- SECURITY GROUP ----------------------------- */
  //VPC
  this.ingressSecurityGroup = new ec2.SecurityGroup(
   this,
   `IngressSecurityGroup`,
   {
    allowAllOutbound: true,
    securityGroupName: `IngressSecurityGroup`,
    vpc: this.vpc,
    description: "IngressSecurityGroup for the VPC",
   }
  );

  this.ingressSecurityGroup.connections.allowFromAnyIpv4(ec2.Port.tcp(80));

  //NODE
  const backServiceSecGroup = new ec2.SecurityGroup(
   this,
   `${this.serviceBack}ServiceSecurityGroup`,
   {
    allowAllOutbound: true,
    securityGroupName: `${this.serviceBack}ServiceSecurityGroup`,
    vpc: this.vpc,
    description: "Security Group for the nodejs server",
   }
  );

  backServiceSecGroup.connections.allowFrom(
   new ec2.Connections({
    securityGroups: [this.ingressSecurityGroup],
   }),
   ec2.Port.tcp(80),
   "Allow traffic on port 80 from the VPC ingress security group"
  );

  //JAVA
  const pdfServiceSecGroup = new ec2.SecurityGroup(
   this,
   `${this.servicePdf}ServiceSecurityGroup`,
   {
    allowAllOutbound: true,
    securityGroupName: `${this.servicePdf}ServiceSecurityGroup`,
    vpc: this.vpc,
    description: "Security Group for the java pdf service",
   }
  );
  pdfServiceSecGroup.connections.allowFrom(
   new ec2.Connections({
    securityGroups: [backServiceSecGroup],
   }),
   ec2.Port.tcp(80),
   "Allow traffic on port 80 from the backService security group"
  );

  /* ----------------------------- FARGATE SERVICE ---------------------------- */

  //NODE
  const backFargateService = new ecs.FargateService(
   this,
   `${this.serviceBack}Service`,
   {
    cluster: this.cluster,
    taskDefinition: backFargateTaskDefinition,
    assignPublicIp: true,
    desiredCount: 1,
    securityGroups: [backServiceSecGroup],
    cloudMapOptions: {
     name: this.serviceBack,
     cloudMapNamespace: this.dnsNamespace,
     dnsRecordType: servicediscovery.DnsRecordType.A,
    },
   }
  );

  //JAVA
  const pdfFargateService = new ecs.FargateService(
   this,
   `${this.servicePdf}Service`,
   {
    cluster: this.cluster,
    taskDefinition: pdfFargateTaskDefinition,
    desiredCount: 1,
    securityGroups: [pdfServiceSecGroup],
    cloudMapOptions: {
     name: this.servicePdf,
     cloudMapNamespace: this.dnsNamespace,
     dnsRecordType: servicediscovery.DnsRecordType.A,
    },
   }
  );
 }
}

</code>```

Where did i do wrong? Thanks in advance for your time

*i did a try with only public subnet, in order to verify service discovery was working

Body:
i am having troubles setting up my AWS VPC via cdk.
I want to create a VPC with 2 subnets, one public and one private_isolated, with no nat gateways and one internet gateway. In the public i will host my node web server and in the private my java microservice. Since i don't know a lot about networking in general, i used a private dns namespace and got the 2 services communicate to each other via AWS Service Discovery*.
The thing is, when i deploy my stack, it gets stuck in creating the java fargate service, and i think the problem is because of the private_isolated subnet. So i added interface endpoints for ecr_docker and ecr and even an s3 gateway endpoint, but the service still remains stuck on create in progress.
Here's my code:

export class EcsServiceDiscoveryStack extends Stack {
 readonly serviceBack = "back-service";
 readonly servicePdf = "pdf-service";
 readonly namespace = "env.test";
 readonly vpc: Vpc;
 readonly cluster: Cluster;
 readonly dnsNamespace: PrivateDnsNamespace;
 readonly ingressSecurityGroup: SecurityGroup;
 readonly egressSecurityGroup: SecurityGroup;

 constructor(scope: Construct, id: string, props?: StackProps) {
  super(scope, id, props);

  /* ----------------------------------- VPC ---------------------------------- */

  const subnetConfig: ec2.SubnetConfiguration[] = [
   {
    name: "test-public-subnet",
   subnetType: SubnetType.PUBLIC,
   },
   {
    name: "test-private-subnet",
    subnetType: SubnetType.PRIVATE_ISOLATED,
   },
  ];

  this.vpc = new ec2.Vpc(this, "test-vpc", {
   maxAzs: 1,
   subnetConfiguration: subnetConfig,
   gatewayEndpoints: {
    S3: { service: ec2.GatewayVpcEndpointAwsService.S3 },
   },
  });

  /* ------------------------- INTERFACE VPC ENDPOINT ------------------------- */
  this.vpc.addInterfaceEndpoint("aws-ecr_docker-endpoint", {
   service: ec2.InterfaceVpcEndpointAwsService.ECR_DOCKER,
   privateDnsEnabled: true,
   subnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
   open: true,
  });

  this.vpc.addInterfaceEndpoint("aws-ecr-endpoint", {
   service: ec2.InterfaceVpcEndpointAwsService.ECR,
   privateDnsEnabled: true,
   subnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
   open: true,
  });

  /* --------------------------------- CLUSTER -------------------------------- */

  this.cluster = new ecs.Cluster(this, "test-cluster", {
   clusterName: "test-cluster",
   vpc: this.vpc,
  });

  /* ------------------------------ DNS NAMESPACE ----------------------------- */

  this.dnsNamespace = new servicediscovery.PrivateDnsNamespace(
   this,
   "DnsNamespace",
   {
    name: this.namespace,
    vpc: this.vpc,
    description: "Private DnsNamespace for test environment",
   }
  );

  /* -------------------------------- TASK ROLE ------------------------------- */

  //NODE
  const backTaskrole = new iam.Role(this, "backTaskExecutionRole", {
   assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
  });

  backTaskrole.addManagedPolicy(
   iam.ManagedPolicy.fromAwsManagedPolicyName(
    "service-role/AmazonECSTaskExecutionRolePolicy"
   )
  );

  //JAVA
  const pdfTaskRole = new iam.Role(this, "pdfTaskExecutionRole", {
   assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
  });

  pdfTaskRole.addManagedPolicy(
   iam.ManagedPolicy.fromAwsManagedPolicyName(
    "service-role/AmazonECSTaskExecutionRolePolicy"
   )
  );

  /* ---------------------------- TASKS DEFINITIONS ---------------------------- */

  //NODE
  const backFargateTaskDefinition = new ecs.FargateTaskDefinition(
   this,
   `${this.serviceBack}ServiceTaskDef`,
   {
    cpu: 256,
    memoryLimitMiB: 512,
    taskRole: backTaskrole,
   }
  );

  //JAVA
  const pdfFargateTaskDefinition = new ecs.FargateTaskDefinition(
   this,
   `${this.servicePdf}ServiceTaskDef`,
   {
    cpu: 256,
    memoryLimitMiB: 512,
    taskRole: pdfTaskRole,
   }
  );

  /* ---------------------------- SERVICE LOG GROUP --------------------------- */

  //NODE
  const backServiceLogGroup = new logs.LogGroup(
   this,
   `${this.serviceBack}ServiceLogGroup`,
   {
    logGroupName: `/ecs/${this.serviceBack}Service`,
    removalPolicy: RemovalPolicy.DESTROY,
   }
  );

  //JAVA
  const pdfServiceLogGroup = new logs.LogGroup(
   this,
   `${this.servicePdf}ServiceLogGroup`,
   {
    logGroupName: `/ecs/${this.servicePdf}Service`,
    removalPolicy: RemovalPolicy.DESTROY,
   }
  );

  /* ------------------------------- LOG DRIVER ------------------------------- */

  //NODE

  const backServiceLogDriver = new ecs.AwsLogDriver({
   logGroup: backServiceLogGroup,

---
  streamPrefix: `${this.serviceBack}Service`,
  });

  //JAVA

  const pdfServiceLogDriver = new ecs.AwsLogDriver({
   logGroup: pdfServiceLogGroup,
   streamPrefix: `${this.servicePdf}Service`,
  });

  /* ---------------------------- REPOISTORY (ECR) ---------------------------- */

  //NODE
  const repoBackNode = Repository.fromRepositoryName(
   this,
   "back-nodejs",
   "task-nodejs-test"
  );

  //JAVA
  const repoBackJava = Repository.fromRepositoryName(
   this,
   "pdf-java",
   "task-nodejs-test"
  );

  /* -------------------------------- CONTAINER ------------------------------- */

  //NODE

  const backServiceContainer = backFargateTaskDefinition.addContainer(
   `${this.serviceBack}ServiceContainer`,
   {
    containerName: `${this.serviceBack}ServiceContainer`,
    essential: true,
    image: ecs.ContainerImage.fromEcrRepository(repoBackNode),
    logging: backServiceLogDriver,
    portMappings: [{ containerPort: 80 }],
    environment: {
     PORT: "80",
     NAME: "back-nodejs",
     PDF_HOST: `http://${this.servicePdf}.${this.namespace}:80`,
    },
   }
  );

  //JAVA
  const pdfServiceContainer = pdfFargateTaskDefinition.addContainer(
   `${this.servicePdf}ServiceContainer`,
   {
    containerName: `${this.servicePdf}ServiceContainer`,
    image: ecs.ContainerImage.fromEcrRepository(repoBackJava),
    logging: pdfServiceLogDriver,
    portMappings: [{ containerPort: 80 }],
    environment: {
     PORT: "80",
     NAME: "pdf-java",
     PDF_HOST: this.servicePdf,
    },
   }
  );

  /* ----------------------------- SECURITY GROUP ----------------------------- */
  //VPC
  this.ingressSecurityGroup = new ec2.SecurityGroup(
   this,
   `IngressSecurityGroup`,
   {
    allowAllOutbound: true,
    securityGroupName: `IngressSecurityGroup`,
    vpc: this.vpc,
    description: "IngressSecurityGroup for the VPC",
   }
  );

  this.ingressSecurityGroup.connections.allowFromAnyIpv4(ec2.Port.tcp(80));

  //NODE
  const backServiceSecGroup = new ec2.SecurityGroup(
   this,
   `${this.serviceBack}ServiceSecurityGroup`,
   {
    allowAllOutbound: true,
    securityGroupName: `${this.serviceBack}ServiceSecurityGroup`,
    vpc: this.vpc,
    description: "Security Group for the nodejs server",
   }
  );

  backServiceSecGroup.connections.allowFrom(
   new ec2.Connections({
    securityGroups: [this.ingressSecurityGroup],
   }),
   ec2.Port.tcp(80),
   "Allow traffic on port 80 from the VPC ingress security group"
  );

  //JAVA
  const pdfServiceSecGroup = new ec2.SecurityGroup(
   this,
   `${this.servicePdf}ServiceSecurityGroup`,
   {
    allowAllOutbound: true,
    securityGroupName: `${this.servicePdf}ServiceSecurityGroup`,
    vpc: this.vpc,
    description: "Security Group for the java pdf service",
   }
  );
  pdfServiceSecGroup.connections.allowFrom(
   new ec2.Connections({
    securityGroups: [backServiceSecGroup],
   }),
   ec2.Port.tcp(80),
   "Allow traffic on port 80 from the backService security group"
  );

  /* ----------------------------- FARGATE SERVICE ---------------------------- */

  //NODE
  const backFargateService = new ecs.FargateService(
   this,
   `${this.serviceBack}Service`,
   {
    cluster: this.cluster,
    taskDefinition: backFargateTaskDefinition,
    assignPublicIp: true,
    desiredCount: 1,
    securityGroups: [backServiceSecGroup],
    cloudMapOptions: {
     name: this.serviceBack,
     cloudMapNamespace: this.dnsNamespace,
     dnsRecordType: servicediscovery.DnsRecordType.A,
    },
   }
  );

  //JAVA
  const pdfFargateService = new ecs.FargateService(
   this,
   `${this.servicePdf}Service`,
   {
    cluster: this.cluster,
    taskDefinition: pdfFargateTaskDefinition,
    desiredCount: 1,
    securityGroups: [pdfServiceSecGroup],
    cloudMapOptions: {
     name: this.servicePdf,
     cloudMapNamespace: this.dnsNamespace,
     dnsRecordType: servicediscovery.DnsRecordType.A,
    },
   }
  );
 }
}

Where did i do wrong? Thanks in advance for your time

*i did a try with only public subnet, in order to verify service discovery was working


来源: stackexchange

问:
Recorder only records 9 seconds in android 12 using mediaRecorder
I have an application which records calls , it works fine so far and it does record the calls , the issue is about the duration that the mediaRecorder records which is roughly 9 seconds in android 12  , when i try on android 11 and downwards , it works pretty fine , i'm not sure why it does not record the whole call in android 12 , any reason why ?? Thank you for the help in advance .

This is receiver where i start recording the call

```<code>
 class PhoneCallReceiver  : BroadcastReceiver() {
    private lateinit var notificationManager: NotificationManager
    var prevState: String = TelephonyManager.EXTRA_STATE_IDLE
    private  var mediaRecorder: MediaRecorder? = null
    private lateinit var filePath : String

    override fun onReceive(context: Context?, intent: Intent?) {

        notificationManager = context!!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val bundle = intent?.extras ?: return
        val state = bundle.getString(TelephonyManager.EXTRA_STATE)

        if(state == TelephonyManager.EXTRA_STATE_IDLE && prevState == TelephonyManager.EXTRA_STATE_IDLE){
            Toast.makeText(context,"Call Ended",Toast.LENGTH_LONG).show()
            stopRecording(context)
            prevState = state!!
        } else if (state == TelephonyManager.EXTRA_STATE_RINGING){
            Toast.makeText(context,"Phone Ringing",Toast.LENGTH_LONG).show()
        } else if(state == TelephonyManager.EXTRA_STATE_OFFHOOK){
            startRecording(context)
            Toast.makeText(context,"Call Answered",Toast.LENGTH_LONG).show()
        }
    }

    private fun startRecording(context: Context){
        var recordingPath = "xxxxxxxx"
        showNotification(context = context,"Recording ...","Recording started ...")
        mediaRecorder = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            MediaRecorder(context)
        } else {
            MediaRecorder()
        }

        val file = File(Environment.getExternalStorageDirectory().toString() + "/RecordingFolder")
        if(!file.exists()){
            file.mkdir()
        }
        mediaRecorder!!.setAudioSource(AudioSource.MIC)

        val choice = Extras.getPrefs(context)

        mediaRecorder!!.setOutputFormat(choice)
        mediaRecorder!!.setAudioEncoder(AudioEncoder.AMR_NB)
        mediaRecorder!!.setOutputFile(recordingPath)

        try {
            mediaRecorder!!.prepare()
            mediaRecorder!!.start()
        } catch (ex : Exception) {
            Log.d("TAG","Exception Caught")
        }

    }

    private fun stopRecording(context: Context){
        notificationManager.cancel(1)
        showNotification(context = context,"Recording Ended","Recording was successful")
        if(mediaRecorder != null){
            mediaRecorder!!.stop()
            mediaRecorder!!.release()
            mediaRecorder = null
        }
    }
    private fun showNotification(context: Context,contentTitle : String , contentText : String){

        val notificationCompat = NotificationCompat.Builder(context, Extras.NOTIFICATION_ID)
            .setContentTitle(contentTitle)
            .setContentText(contentText)
            .setSmallIcon(R.drawable.ic_baseline_circle_notifications_24)
            .build()

        NotificationManagerCompat.from(context).notify(1,notificationCompat)
    }
}
</code>```

Permissions which are granted

```<code>     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an application which records calls , it works fine so far and it does record the calls , the issue is about the duration that the mediaRecorder records which is roughly 9 seconds in android 12  , when i try on android 11 and downwards , it works pretty fine , i'm not sure why it does not record the whole call in android 12 , any reason why ?? Thank you for the help in advance .

This is receiver where i start recording the call

 class PhoneCallReceiver  : BroadcastReceiver() {
    private lateinit var notificationManager: NotificationManager
    var prevState: String = TelephonyManager.EXTRA_STATE_IDLE
    private  var mediaRecorder: MediaRecorder? = null
    private lateinit var filePath : String

    override fun onReceive(context: Context?, intent: Intent?) {

        notificationManager = context!!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val bundle = intent?.extras ?: return
        val state = bundle.getString(TelephonyManager.EXTRA_STATE)

        if(state == TelephonyManager.EXTRA_STATE_IDLE && prevState == TelephonyManager.EXTRA_STATE_IDLE){
            Toast.makeText(context,"Call Ended",Toast.LENGTH_LONG).show()
            stopRecording(context)
            prevState = state!!
        } else if (state == TelephonyManager.EXTRA_STATE_RINGING){
            Toast.makeText(context,"Phone Ringing",Toast.LENGTH_LONG).show()
        } else if(state == TelephonyManager.EXTRA_STATE_OFFHOOK){
            startRecording(context)
            Toast.makeText(context,"Call Answered",Toast.LENGTH_LONG).show()
        }
    }

    private fun startRecording(context: Context){
        var recordingPath = "xxxxxxxx"
        showNotification(context = context,"Recording ...","Recording started ...")
        mediaRecorder = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            MediaRecorder(context)
        } else {
            MediaRecorder()
        }

        val file = File(Environment.getExternalStorageDirectory().toString() + "/RecordingFolder")
        if(!file.exists()){
            file.mkdir()
        }
        mediaRecorder!!.setAudioSource(AudioSource.MIC)

        val choice = Extras.getPrefs(context)

        mediaRecorder!!.setOutputFormat(choice)
        mediaRecorder!!.setAudioEncoder(AudioEncoder.AMR_NB)
        mediaRecorder!!.setOutputFile(recordingPath)

        try {
            mediaRecorder!!.prepare()
            mediaRecorder!!.start()
        } catch (ex : Exception) {
            Log.d("TAG","Exception Caught")
        }

    }

    private fun stopRecording(context: Context){
        notificationManager.cancel(1)
        showNotification(context = context,"Recording Ended","Recording was successful")
        if(mediaRecorder != null){
            mediaRecorder!!.stop()
            mediaRecorder!!.release()
            mediaRecorder = null
        }
    }
    private fun showNotification(context: Context,contentTitle : String , contentText : String){

        val notificationCompat = NotificationCompat.Builder(context, Extras.NOTIFICATION_ID)
            .setContentTitle(contentTitle)
            .setContentText(contentText)
            .setSmallIcon(R.drawable.ic_baseline_circle_notifications_24)
            .build()

        NotificationManagerCompat.from(context).notify(1,notificationCompat)
    }
}

Permissions which are granted

     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


问:
Angular 14: Getting 'An index signature parameter type must be either 'string' or 'number' error on vs2022 while build the application
"Error  TS1023  Build:An index signature parameter type must be either 'string' or 'number'.    \node_modules@angular\router\index.d.ts"

Above is the build error i am facing. In local the application is running perfectly but while we go with CICD pipeline and vs2022 application build it throws angular build error.

In local angular build no error.

Below is my package.json

```<code>"dependencies": {
    "@angular/animations": "^14.0.1",
    "@angular/cdk": "^14.0.1",
    "@angular/common": "^14.0.1",
    "@angular/compiler": "^14.0.1",
    "@angular/core": "^14.0.1",
    "@angular/forms": "^14.0.1",
    "@angular/material": "^14.0.1",
    "@angular/platform-browser": "^14.0.1",
    "@angular/platform-browser-dynamic": "^14.0.1",
    "@angular/router": "14.0.0",
    "angular2-multiselect-dropdown": "^5.0.0",
    "bootstrap": "^4.6.1",
    "ngx-bootstrap": "^9.0.0",
    "hammerjs": "^2.0.8",
    "ngx-spinner": "14.0.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.0.1",
    "@angular/cli": "~14.0.1",
    "@angular/compiler-cli": "^14.0.1",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.1.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.7.2"
  },
</code>```

This is the error i am facing in vs2022 application

Tried in different type of angular 14 version but same result. Any other suggestions to resolve this?

Body:
"Error  TS1023  Build:An index signature parameter type must be either 'string' or 'number'.    \node_modules@angular\router\index.d.ts"

Above is the build error i am facing. In local the application is running perfectly but while we go with CICD pipeline and vs2022 application build it throws angular build error.

In local angular build no error.

Below is my package.json

"dependencies": {
    "@angular/animations": "^14.0.1",
    "@angular/cdk": "^14.0.1",
    "@angular/common": "^14.0.1",
    "@angular/compiler": "^14.0.1",
    "@angular/core": "^14.0.1",
    "@angular/forms": "^14.0.1",
    "@angular/material": "^14.0.1",
    "@angular/platform-browser": "^14.0.1",
    "@angular/platform-browser-dynamic": "^14.0.1",
    "@angular/router": "14.0.0",
    "angular2-multiselect-dropdown": "^5.0.0",
    "bootstrap": "^4.6.1",
    "ngx-bootstrap": "^9.0.0",
    "hammerjs": "^2.0.8",
    "ngx-spinner": "14.0.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.0.1",
    "@angular/cli": "~14.0.1",
    "@angular/compiler-cli": "^14.0.1",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.1.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.7.2"
  },

This is the error i am facing in vs2022 application

Tried in different type of angular 14 version but same result. Any other suggestions to resolve this?


问:
Show all dates in the StockChart's x-axis (categoryAxis) and the Navigator axis (Kendo StockChart Angular)
Currently, the Stockchart renders some dates and skips few dates automatically. Usually, the x-axis has 3 days gap between dates and the navigator axis has 1 day gap. We want the chart to display all dates from the dataset.

Please refer this link for the POC app: https://stackblitz.com/edit/kendo-stockchart-v2?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

Another issue: the alternate date label is not shown on the cateogryAxis (x-axis).

Kindly help. Thank you.


问:
VBA to compare two sheets and copy different columns in the new sheet with their unique ID from cell 'A' from sheet1 and sheet 2
I have two columns in two sheets  and  I want to output their differences in third sheet with their unique ID. Therefore, I have problem just to get their ID's from  both table where they have differences.

Here are the tables:

Sheet1: i rename it to NEW:

ID
Salesmen
Product
Net Sales

1
William
TV

2
Simon
AC
2600

3
Maja
Fridge
1000

Sheet2: i rename it to OLD:

ID
Salesman
Product
Net Sales

1
William
Chair
1111

2
Simon
Table
2600

3
Ivan
Remote
1000

And, the third sheet  , I rename i to DIFF:  I output all differences form sheet 1 and sheet  2

ID
Column_names
NEW
OLD

Product
TV
Chair

Net Sales

111

Product
AC
Table

Salesman
maja
Ivan

Product
Fridge
Remote

I need help with third sheet DIFF. How to get ID's from OLD sheet and the NEW sheet ?

Any idea how to figure to put ID in my VBA code?

Expected results:

ID
Column_names
NEW
OLD

1
Product
TV
Chair

1
Net Sales

111

2
Product
AC
Table

3
Salesman
maja
Ivan

3
Product
Fridge
Remote

This is my current VBA code:

Option Explicit
Sub Compare_Two_Excel_Sheets()
    'Define Fields
    Dim Flag As Double

    Dim iR As Double, iC As Double, oRw As Double, i As Double ', oCw As Double
    Dim iRow_M As Double, iCol_M As Double ', IDCol_C As Double
    Dim s1 As Worksheet, s2 As Worksheet
    Dim s3 As Worksheet
    Dim rng As Range
    Dim criteria As Variant
    Dim result As Double

    Flag = 0
    Set s1 = ThisWorkbook.Sheets(1)
    Set s2 = ThisWorkbook.Sheets(2)
    Set s3 = ThisWorkbook.Sheets(3)

    Sheets(1).Name = "NEW"
    Sheets(2).Name = "OLD"
    Sheets(3).Name = "DIFF"

    VBA.Interaction.MsgBox "Clear the previous differences?"
    Sheets("diff").Cells.Clear

     Sheets("diff").Cells.Range("A7").Value = "ID"
     Sheets("diff").Cells.Range("B7").Value = "Column"
     Sheets("diff").Cells.Range("C7").Value = "OLD"
     Sheets("diff").Cells.Range("D7").Value = "NEW"

    iRow_M = s1.UsedRange.Rows.Count
    iCol_M = s1.UsedRange.Columns.Count
    'IDCol_C = s1.UsedRange.Rows.Count

    For iR = 1 To iRow_M
    For iC = 1 To iCol_M
    'For IDC = 1 To IDCol_C

        s1.Cells(iR, iC).Interior.Color = xlNone
        s2.Cells(iR, iC).Interior.Color = xlNone

        If s1.Cells(iR, iC) <> s2.Cells(iR, iC) Then
           s1.Cells(iR, iC).Interior.Color = vbYellow
           s2.Cells(iR, iC).Interior.Color = vbYellow
           's1.Cells(ID).Value = "test"

           oRw = oRw + 1
           'oCw = oCw + 1
          ' s3.Cells.Range(oCw, 2).Value = "Column"

           s3.Cells(oRw, 2) = s2.Cells(iC)
           s3.Cells(oRw, 3) = s1.Cells(iR, iC)
           s3.Cells(oRw, 4) = s2.Cells(iR, iC)
           's3.Cells(oRw, 1) = s2.Range("A2:A5").Value

          Flag = Flag + 1

        End If

   ' Next IDC
    Next iC
    Next iR

Set rng = Sheets("diff").Cells.Range("C1:D6")

   result = WorksheetFunction.CountIf(rng, "*")

    If Flag > 0 Then
        VBA.Interaction.MsgBox "Differences found: " & result & ", please check the sheet: DIFF!"
        Else: VBA.Interaction.MsgBox "No differences found!"

  End If

End Sub
```


问:
How to draw horizontal lines For (First candle) in year
I am trying to draw horizontal lines on first candle in year , lines on high and low for candle .. For example, if the time frame is daily, we want to put two lines, higher and lower, on the first candle of the year, and on the weekly, we can specify the first weekly candle of the year, and so on. Can I help with this?enter image description here</p>
```<code>//@version=5
indicator("OPOFHL", overlay=true)

is_new(resolution) =>
    t = time(resolution)
    not na(t) and (na(t[1]) or t > t[1])

is_new_year() => is_new('12M')

var float hi = na
var float lo = na

hi := is_new_year() ? high : hi
lo := is_new_year() ? low : lo

plot(hi, "High", color.green, 1, plot.style_circles)
plot(lo, "Low", color.red, 1, plot.style_circles)
</code>```

Body:
I am trying to draw horizontal lines on first candle in year , lines on high and low for candle .. For example, if the time frame is daily, we want to put two lines, higher and lower, on the first candle of the year, and on the weekly, we can specify the first weekly candle of the year, and so on. Can I help with this?enter image description here

//@version=5
indicator("OPOFHL", overlay=true)

is_new(resolution) =>
    t = time(resolution)
    not na(t) and (na(t[1]) or t > t[1])

is_new_year() => is_new('12M')

var float hi = na
var float lo = na

hi := is_new_year() ? high : hi
lo := is_new_year() ? low : lo

plot(hi, "High", color.green, 1, plot.style_circles)
plot(lo, "Low", color.red, 1, plot.style_circles)


问:
JPA persist methods return unexpected ID on nextval(sequence)
It's about persistence with SpringDataJPA, using strategy = GenerationType.SEQUENCE, my database is created through a sql script.

My problem is SpringData's persist methods doesn't return the expected id after being executed.

I've configured it to have the sequence incremented by 50. But when I persist a new entity, the increment is only 1.

Ok so here's the entity id (ommited allocationSize = 50 caused it's the defaut value) :

```<code>
@Entity
@Table(name = "theme", schema = "public")
public class Theme {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "theme_seq_gen")
    @SequenceGenerator(name = "theme_seq_gen", sequenceName = "theme_sequence", initialValue = 100)
    private Long id;

    private String name;

    // other fields
}

</code>```

Here's the persistence related properties

```<code># ===============================
# = DATA SOURCE
# ===============================
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/game-library-dev-db
spring.datasource.username=postgres
spring.datasource.password=postgres

# ===============================
# = JPA / HIBERNATE
# ===============================
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=validate

spring.jpa.show-sql=true
spring.jpa.open-in-view=false

# JPA configuration - development (with statistics)
spring.jpa.properties.hibernate.format_sql=true

# useful to detect n+1 issues
# do not use in production
spring.jpa.properties.hibernate.generate_statistics=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation = true

# create and fill db
spring.sql.init.schema-locations=classpath:sql/schema.sql
spring.sql.init.data-locations=classpath:sql/data.sql
</code>```

And this is an extract from the script.sql

DROP SCHEMA IF EXISTS public CASCADE;
CREATE SCHEMA public;

CREATE SEQUENCE theme_sequence START 100 INCREMENT BY 50;

CREATE TABLE IF NOT EXISTS theme
(
    id              BIGINT      NOT NULL DEFAULT nextval('theme_sequence'),
    name            VARCHAR(50) NOT NULL,
    CONSTRAINT theme_pkey
        PRIMARY KEY (id)
);
ALTER TABLE theme
    OWNER TO postgres;

```
<p>And now a part of the <code>data.sql</code></p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO public.theme(id, name)
VALUES (nextval('theme_sequence'), 'Médiéval'),
       (nextval('theme_sequence'), 'Urbanisme'),
       (nextval('theme_sequence'), 'Espace'),
       (nextval('theme_sequence'), 'Espionnage'),
       (nextval('theme_sequence') 'Commerce'),
# and so on...
</code>```

When the db is filled with data.sql it's all good and the increment is 50 :

Value goes from 100 to 650, good.

But when I use the following persist method (I've typed a Hibernate methods but SpringData Repo's methods behave the same : wrong nextval)

    @Override
    public Theme saveTheme(Theme theme) {
        entityManager.persist(theme);
        entityManager.flush();

        return new Theme(theme.getId(), theme.getName());
    }

```

For example I persist a theme called "NEW THEME"

It got the ID 651, so the increment is wrong.

Am I missing something ?

Body:
It's about persistence with SpringDataJPA, using strategy = GenerationType.SEQUENCE, my database is created through a sql script.

My problem is SpringData's persist methods doesn't return the expected id after being executed.

I've configured it to have the sequence incremented by 50. But when I persist a new entity, the increment is only 1.

Ok so here's the entity id (ommited allocationSize = 50 caused it's the defaut value) :

@Entity
@Table(name = "theme", schema = "public")
public class Theme {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "theme_seq_gen")
    @SequenceGenerator(name = "theme_seq_gen", sequenceName = "theme_sequence", initialValue = 100)
    private Long id;

    private String name;

    // other fields
}

Here's the persistence related properties

# ===============================
# = DATA SOURCE
# ===============================
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/game-library-dev-db
spring.datasource.username=postgres
spring.datasource.password=postgres

# ===============================
# = JPA / HIBERNATE
# ===============================
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=validate

spring.jpa.show-sql=true
spring.jpa.open-in-view=false

# JPA configuration - development (with statistics)
spring.jpa.properties.hibernate.format_sql=true

# useful to detect n+1 issues
# do not use in production
spring.jpa.properties.hibernate.generate_statistics=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation = true

# create and fill db
spring.sql.init.schema-locations=classpath:sql/schema.sql
spring.sql.init.data-locations=classpath:sql/data.sql

And this is an extract from the script.sql

DROP SCHEMA IF EXISTS public CASCADE;
CREATE SCHEMA public;

CREATE SEQUENCE theme_sequence START 100 INCREMENT BY 50;

CREATE TABLE IF NOT EXISTS theme
(
    id              BIGINT      NOT NULL DEFAULT nextval('theme_sequence'),
    name            VARCHAR(50) NOT NULL,
    CONSTRAINT theme_pkey
        PRIMARY KEY (id)
);
ALTER TABLE theme
    OWNER TO postgres;

And now a part of the data.sql

INSERT INTO public.theme(id, name)
VALUES (nextval('theme_sequence'), 'Médiéval'),
       (nextval('theme_sequence'), 'Urbanisme'),
       (nextval('theme_sequence'), 'Espace'),
       (nextval('theme_sequence'), 'Espionnage'),
       (nextval('theme_sequence') 'Commerce'),
# and so on...

When the db is filled with data.sql it's all good and the increment is 50 :

Value goes from 100 to 650, good.

But when I use the following persist method (I've typed a Hibernate methods but SpringData Repo's methods behave the same : wrong nextval)

    @Override
    public Theme saveTheme(Theme theme) {
        entityManager.persist(theme);
        entityManager.flush();

        return new Theme(theme.getId(), theme.getName());
    }

For example I persist a theme called "NEW THEME"

It got the ID 651, so the increment is wrong.

Am I missing something ?


问:
Cannot change value on input after axios
```<code>    const [something, setSomething] = useState({
        Name: "getbyID.Name",
        Category: "",
        type: "",
        Description: "",
        className: '',
        start: '',
        TargetDate: ''
    });
    const handleChangeInput= async function(event) {
        console.log("Value from event:", event.target.value);
        const { name, value } = event.target;
        setSomething({
            ...something,
            [name]: value
        });}
    useEffect(() => {
        var data = {
            "resource": "",
            "action": "get",
            "params": {
                "Id__eq": handleSelected,
            }
        };
        if (handleSelected) {
            axios({
                method: 'post',
                url: '',
                data: JSON.stringify(data),
                headers: {
                    Auth: auth.user.token
                },
                contentType: "json",
                dataType: "json",
            }).then((response) => {
                setGetbyID(response.data[0]);
                set(response.data[0]);
                var prevData = response.data[0];
            })
        }
    }, [handleSelected])
    <Form.Check inline label = "Professional" value = "Professional" name = "Category" type = "radio" id = "Category-1" onChange = {handleChangeInput}onClick = {FormHandlerProfessional}/>

< Form.Check inline label = ""value = ""name = "Category" type = "radio" onChange = {handleChangeInput}/> < /div>

< SmallCalendar onChange = {handleChangeInput}value = {something.TargetDate}/>
</code>```

After getting values from Axios call I can't change the values from locking on the axios value and can't update the input text values are working correctly.

The handling is done in handleChangeInput and on it's fired on on change listener

The problem is on radio button and datepicker only

Body:
    const [something, setSomething] = useState({
        Name: "getbyID.Name",
        Category: "",
        type: "",
        Description: "",
        className: '',
        start: '',
        TargetDate: ''
    });
    const handleChangeInput= async function(event) {
        console.log("Value from event:", event.target.value);
        const { name, value } = event.target;
        setSomething({
            ...something,
            [name]: value
        });}
    useEffect(() => {
        var data = {
            "resource": "",
            "action": "get",
            "params": {
                "Id__eq": handleSelected,
            }
        };
        if (handleSelected) {
            axios({
                method: 'post',
                url: '',
                data: JSON.stringify(data),
                headers: {
                    Auth: auth.user.token
                },
                contentType: "json",
                dataType: "json",
            }).then((response) => {
                setGetbyID(response.data[0]);
                set(response.data[0]);
                var prevData = response.data[0];
            })
        }
    }, [handleSelected])
    <Form.Check inline label = "Professional" value = "Professional" name = "Category" type = "radio" id = "Category-1" onChange = {handleChangeInput}onClick = {FormHandlerProfessional}/>

< Form.Check inline label = ""value = ""name = "Category" type = "radio" onChange = {handleChangeInput}/>

< SmallCalendar onChange = {handleChangeInput}value = {something.TargetDate}/>

After getting values from Axios call I can't change the values from locking on the axios value and can't update the input text values are working correctly.

The handling is done in handleChangeInput and on it's fired on on change listener

The problem is on radio button and datepicker only


问:
.it returns'ValueError: Found input variables with inconsistent numbers of samples: [5472, 1824]'
hello I have problem with this part of my code. when I run the metrics for assessment of knn algorithm on my data.jupyter says that

```<code>
</code>```

your textprint('R^2:',metrics.r2_score(y_train, y_pred))
your textprint('MAE:',metrics.mean_absolute_error(y_train, y_pred))
your textprint('MSE:',metrics.mean_squared_error(y_train, y_pred))
your textprint('RMSE:',np.sqrt(metrics.mean_squared_error(y_train, y_pred)))'
"Found input variables with inconsistent numbers of samples: [5472, 1824]"
I try a lot of things

Body:
hello I have problem with this part of my code. when I run the metrics for assessment of knn algorithm on my data.jupyter says that

your textprint('R^2:',metrics.r2_score(y_train, y_pred))
your textprint('MAE:',metrics.mean_absolute_error(y_train, y_pred))
your textprint('MSE:',metrics.mean_squared_error(y_train, y_pred))
your textprint('RMSE:',np.sqrt(metrics.mean_squared_error(y_train, y_pred)))'
"Found input variables with inconsistent numbers of samples: [5472, 1824]"
I try a lot of things


问:
Xcode: Failed to add the "CloudKit" capability to a new Commandline target in a project
I have a project with a Mac-OS target that uses CloudKit.
Therefore the CloudKit capability is enabled.

Now I added a new target for a commandline tool.

Because this tool shall connect to the same CloudKit Data, I tried to add the CloudKit capability to this target too.

Unfortunately in the "Signing & Capabilities" dialog of this target I can only find "App Sandbox" when I try to add a new capability.

Any Ideas, what I am doing wrong?


问:
Can't print value of variable in screen field
I can't see the value of the variable i (2424) in my screen form. How can I print the value in the designated screen field? This is the Python code I'm using:

label0 = tk.Label(root, text='TOTAL RECORDS IN TABLE SONG: ')
label0.config(font=('helvetica', 12))
canvas1.create_window(210, 90, window=label0)
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                        'Server=MSI;'
                        'Database=MUSIC;'
                        'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT Count(*) FROM dbo.MUSIC_STG_MUSIC_SONGS')
for i in cursor:
        print(i)
entry1 = tk.Entry (root)
##canvas1.create_window(415, 90, window=entry1)
for item in range(1):
        canvas1.create_window(415, 90, i, window=entry1)
```
<p>I tried to use several commands in the code, like <code>get("i")</code>, or <code>print(i)</code>.
<code>print(i)</code> works but puts the value <code>2424</code> in the Python Idle shell, and not in my screen field.</p>
<p>The variable <code>i</code> stands for the number of records in the table of songs.
This number of records is pulled out by the query.</p>
<p>But I get the following error:</p>
```Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\PYTHON\00000_PROJECTS\MUSIC\MUSIC.py", line 181, in <lambda>
    edit.add_command(label ='12.6   COUNT SONGS PER MUSIC TYPE', command = lambda: checkrecordsmusictype())
  File "C:\PYTHON\00000_PROJECTS\MUSIC\MUSIC.py", line 391, in checkrecordsmusictype
    canvas1.create_window(415, 90, list(i), window=entry1)
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 2843, in create_window
    return self._create('window', args, kw)
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 2805, in _create
    return self.tk.getint(self.tk.call(
_tkinter.TclError: unknown option "2424"

When i put the +str(i) after the line of text i get the following error: unsupported operand type(s) for +: 'Label' and 'str'.
Thxs for your support Tim.

```

Body:
I can't see the value of the variable i (2424) in my screen form. How can I print the value in the designated screen field? This is the Python code I'm using:

label0 = tk.Label(root, text='TOTAL RECORDS IN TABLE SONG: ')
label0.config(font=('helvetica', 12))
canvas1.create_window(210, 90, window=label0)
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                        'Server=MSI;'
                        'Database=MUSIC;'
                        'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT Count(*) FROM dbo.MUSIC_STG_MUSIC_SONGS')
for i in cursor:
        print(i)
entry1 = tk.Entry (root)
##canvas1.create_window(415, 90, window=entry1)
for item in range(1):
        canvas1.create_window(415, 90, i, window=entry1)

I tried to use several commands in the code, like get("i"), or print(i).
print(i) works but puts the value 2424 in the Python Idle shell, and not in my screen field.

The variable i stands for the number of records in the table of songs.
This number of records is pulled out by the query.

But I get the following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\PYTHON\00000_PROJECTS\MUSIC\MUSIC.py", line 181, in <lambda>
    edit.add_command(label ='12.6   COUNT SONGS PER MUSIC TYPE', command = lambda: checkrecordsmusictype())
  File "C:\PYTHON\00000_PROJECTS\MUSIC\MUSIC.py", line 391, in checkrecordsmusictype
    canvas1.create_window(415, 90, list(i), window=entry1)
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 2843, in create_window
    return self._create('window', args, kw)
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 2805, in _create
    return self.tk.getint(self.tk.call(
_tkinter.TclError: unknown option "2424"

When i put the +str(i) after the line of text i get the following error: unsupported operand type(s) for +: 'Label' and 'str'.
Thxs for your support Tim.


问:
Puppeteer $eval() with parent element
page.$eval() runs document.querySelector, but I want to use it with parent element.

There is element.querySelector but there isn't element.$eval() in puppeteer, and also I cannot manually put parent inside selector because I am iterating arrays of elements found by page.$$eval().

I have to use puppeteer screenshot, so element.evaluate(el => el.querySelector()) won't work too.

Title: Puppeteer $eval() with parent element


问:
reset id whenever a row deleted in django
i wanted to start id from 1 .
whenever a row deleted it skips that number and jump to next number.

like in this image it skips number from 1-6 and 8.

i want to set it as 1,2,3

this is my models.py

```<code>class dish(models.Model):
id = models.AutoField(primary_key=True)
dish_id = models.AutoField
dish_name = models.CharField(max_length=255, blank=True, null=True)
dish_category = models.CharField(max_length=255, blank=True, null=True)
dish_size = models.CharField(max_length=7, blank=True, null=True)
dish_price = models.IntegerField(blank=True, null=True)
dish_description = models.CharField(max_length=255, blank=True, null=True)
# dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
dish_date = models.DateField()

def __str__(self):
    return self.dish_name
</code>```

this is views.py

```<code>def delete(request, id):
dishs = dish.objects.get(id=id)
dishs.delete()
return HttpResponseRedirect(reverse('check'))
</code>```

Body:
i wanted to start id from 1 .
whenever a row deleted it skips that number and jump to next number.

like in this image it skips number from 1-6 and 8.

i want to set it as 1,2,3

this is my models.py

class dish(models.Model):
id = models.AutoField(primary_key=True)
dish_id = models.AutoField
dish_name = models.CharField(max_length=255, blank=True, null=True)
dish_category = models.CharField(max_length=255, blank=True, null=True)
dish_size = models.CharField(max_length=7, blank=True, null=True)
dish_price = models.IntegerField(blank=True, null=True)
dish_description = models.CharField(max_length=255, blank=True, null=True)
# dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
dish_date = models.DateField()

def __str__(self):
    return self.dish_name

this is views.py

def delete(request, id):
dishs = dish.objects.get(id=id)
dishs.delete()
return HttpResponseRedirect(reverse('check'))


问:
Strapi CORS error although middleware is configured
I know there are similar questions out here, but nothing helped me so far. I'm getting a cors error in strapi v4.5.3 although I have configured it to allow the origin. Strapi doesn't seem to take the origins I'm using. My middleware.ts looks like this:

```<code>export default [
  'strapi::errors',
  'strapi::security',
  {
    name: 'strapi::cors',
    config: {
      enabled: true,
      origin: process.env.CORS_ORIGINS
        ? process.env.CORS_ORIGINS.split(', ')
        : '*',
      credentials: true,
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
      headers: ['Content-Type', 'Authorization', 'Origin', 'Accept'],
      keepHeaderOnError: true,
    },
  },
  'strapi::poweredBy',
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
]
</code>```

with the following .env value:

```<code>CORS_ORIGINS=http://localhost:1337, http://localhost:6006, http://localhost:18082, https://portal-cms.example.de, https://portal-cms.example.bop
</code>```

When I'm calling from localhost:6006 or localhost:18082 to localhost:1337 everything works fine. My dev server is available at https://portal-cms.example.de and when I try to call it from localhost:6006 or localhost:18082 I'm getting the following cors error:

```<code>Access to XMLHttpRequest at 'https://portal-cms.example.de/api/contact-infos?locale=en' from origin 'http://localhost:6006' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://portal-cms.example.bop' that is not equal to the supplied origin.
</code>```

The request is made via axios from a vue component and looks like this:

```<code>console.log(await axios.get('https://portal-cms.example.de/api/contact-infos?locale=en'))
</code>```

The response header has the value access-control-allow-origin: https://portal-cms.example.bop. I would have expected it to have the value that I configured in my middleware.ts. Am I understanding it wrong? and is there any way to make this error go away?

Body:
I know there are similar questions out here, but nothing helped me so far. I'm getting a cors error in strapi v4.5.3 although I have configured it to allow the origin. Strapi doesn't seem to take the origins I'm using. My middleware.ts looks like this:

export default [
  'strapi::errors',
  'strapi::security',
  {
    name: 'strapi::cors',
    config: {
      enabled: true,
      origin: process.env.CORS_ORIGINS
        ? process.env.CORS_ORIGINS.split(', ')
        : '*',
      credentials: true,
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
      headers: ['Content-Type', 'Authorization', 'Origin', 'Accept'],
      keepHeaderOnError: true,
    },
  },
  'strapi::poweredBy',
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
]

with the following .env value:

CORS_ORIGINS=http://localhost:1337, http://localhost:6006, http://localhost:18082, https://portal-cms.example.de, https://portal-cms.example.bop

When I'm calling from localhost:6006 or localhost:18082 to localhost:1337 everything works fine. My dev server is available at https://portal-cms.example.de and when I try to call it from localhost:6006 or localhost:18082 I'm getting the following cors error:

Access to XMLHttpRequest at 'https://portal-cms.example.de/api/contact-infos?locale=en' from origin 'http://localhost:6006' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://portal-cms.example.bop' that is not equal to the supplied origin.

The request is made via axios from a vue component and looks like this:

console.log(await axios.get('https://portal-cms.example.de/api/contact-infos?locale=en'))

The response header has the value access-control-allow-origin: https://portal-cms.example.bop. I would have expected it to have the value that I configured in my middleware.ts. Am I understanding it wrong? and is there any way to make this error go away?


问:
Is there a way to write .wav file where I can append data on specific timestamps?
I have audio data, and I want to convert it into .wav file.
The data is in list like:[[time_stamp, stereo_buffer], [time_stamp, stereo_buffer], [time_stamp, stereo_buffer],…]
Where
time_stamp = datetime(10:30:25.500)
Stereo_buffer = [[123, 123],[557, 557],[7688,7688],…]
Length of stereo_buffer is 4000
And each next timestamp is after 500 milliseconds in the data list, and some time stamps are missing.
I want to create .wav file of the data.
Is there a way to writeframes on given timestamps so that, where the timestamps are missing there should be no audio.

Thanks

I’ve tried wave in python

```<code>Wave_file.setnchannels(2)
Wave_file.setsamplewidth(2)
Wave_file.setframerate(8000)
for buffer in data:
   buff=buffer[1]
   data=np.array(buff)
   data=data.astype(np.int16)
   frame=n.chararray.tobyte(data)
   Wave_file.writeframe(frame)
</code>```

This works fine creates a wav file that plays as well but all audio is in sequence and no gap is there (where time stamps are missing).
But I want to append frame on corresponding timestamp so that, where timestamps are missing the audio should also be missing on that time.

Body:
I have audio data, and I want to convert it into .wav file.
The data is in list like:[[time_stamp, stereo_buffer], [time_stamp, stereo_buffer], [time_stamp, stereo_buffer],…]
Where
time_stamp = datetime(10:30:25.500)
Stereo_buffer = [[123, 123],[557, 557],[7688,7688],…]
Length of stereo_buffer is 4000
And each next timestamp is after 500 milliseconds in the data list, and some time stamps are missing.
I want to create .wav file of the data.
Is there a way to writeframes on given timestamps so that, where the timestamps are missing there should be no audio.

Thanks

I’ve tried wave in python

Wave_file.setnchannels(2)
Wave_file.setsamplewidth(2)
Wave_file.setframerate(8000)
for buffer in data:
   buff=buffer[1]
   data=np.array(buff)
   data=data.astype(np.int16)
   frame=n.chararray.tobyte(data)
   Wave_file.writeframe(frame)

This works fine creates a wav file that plays as well but all audio is in sequence and no gap is there (where time stamps are missing).
But I want to append frame on corresponding timestamp so that, where timestamps are missing the audio should also be missing on that time.


问:
predicate checking for UUID not working in swift
My attempts to fetch records from coredata based on a matching UUID is crashing the app, I get the correct instance for binding and there is no other error , but the error

```<code>Could not cast value of type 'SwiftUI.Binding<Swift.Optional<Foundation.UUID>>' (0x14f02c810) to 'Swift.CVarArg' (0x14f02c8c8).
</code>```

keeps showing up every time I try and fetch the records , can any one kindly suggest where is my issue

```<code>import SwiftUI
import CoreData

    struct EditViewData: View {

        @Environment(\.managedObjectContext) var moc
        @Binding var carData: CarDetails
        @ObservedObject var dataEdit: DataController
        @FetchRequest var mycarsdata: FetchedResults<CarDetails>
        init(carData: Binding<CarDetails>, dataEdit: DataController) {
            _mycarsdata = FetchRequest(entity: CarDetails.entity(), sortDescriptors: [], predicate: NSPredicate(format: "carid == %@", carData.carid as! CVarArg ))
            self._carData = carData
            self.dataEdit = dataEdit
        }
        var body: some View {
            VStack {
                TextField("Brand", text: .init(
                    get: { self.carData.brandNameTemp  },
                    set: { self.carData.brandName = $0 }
                )) {
                    let carChange = CarDetails(context: moc)
                    for item in mycarsdata {
                        item.brandName = carData.brandNameTemp
                    }
                    dataEdit.save()
                }

            }
            .navigationBarBackButtonHidden(true)

        }
    }
</code>```

Edited Working Code with no insertion with updates

```<code>   import SwiftUI
import CoreData

struct EditViewData: View {

    @Environment(\.managedObjectContext) var moc
    @ObservedObject var carData: CarDetails
    @ObservedObject var dataEdit: DataController

    var body: some View {
        VStack {
            TextField("Brand", text: .init(
                get: { self.carData.brandNameTemp  },
                set: { self.carData.brandName = $0 }
            )) {

                dataEdit.save()
            }

        }
      //  .navigationBarBackButtonHidden(true)

    }
}
</code>```

Body:
My attempts to fetch records from coredata based on a matching UUID is crashing the app, I get the correct instance for binding and there is no other error , but the error

Could not cast value of type 'SwiftUI.Binding<Swift.Optional<Foundation.UUID>>' (0x14f02c810) to 'Swift.CVarArg' (0x14f02c8c8).

keeps showing up every time I try and fetch the records , can any one kindly suggest where is my issue

import SwiftUI
import CoreData

    struct EditViewData: View {

        @Environment(\.managedObjectContext) var moc
        @Binding var carData: CarDetails
        @ObservedObject var dataEdit: DataController
        @FetchRequest var mycarsdata: FetchedResults<CarDetails>
        init(carData: Binding<CarDetails>, dataEdit: DataController) {
            _mycarsdata = FetchRequest(entity: CarDetails.entity(), sortDescriptors: [], predicate: NSPredicate(format: "carid == %@", carData.carid as! CVarArg ))
            self._carData = carData
            self.dataEdit = dataEdit
        }
        var body: some View {
            VStack {
                TextField("Brand", text: .init(
                    get: { self.carData.brandNameTemp  },
                    set: { self.carData.brandName = $0 }
                )) {
                    let carChange = CarDetails(context: moc)
                    for item in mycarsdata {
                        item.brandName = carData.brandNameTemp
                    }
                    dataEdit.save()
                }

            }
            .navigationBarBackButtonHidden(true)

        }
    }

Edited Working Code with no insertion with updates

   import SwiftUI
import CoreData

struct EditViewData: View {

    @Environment(\.managedObjectContext) var moc
    @ObservedObject var carData: CarDetails
    @ObservedObject var dataEdit: DataController

    var body: some View {
        VStack {
            TextField("Brand", text: .init(
                get: { self.carData.brandNameTemp  },
                set: { self.carData.brandName = $0 }
            )) {

                dataEdit.save()
            }

        }
      //  .navigationBarBackButtonHidden(true)

    }
}


问:
Assigning CSS ID to product archive in WooCommerce
I'm having a problem on product archive page that I have created on WordPress; I have designed it in a way according to client's demand, header with banner image & after that there are two sections one is for text, another is for image & there after that I have 2 sections where one is for product navigation which is created through menu in WP & menu is created through product category in WooCommerce so I can't assign separate CSS ID's to these category & the reason that I want to do that is because if we're hitting any option in product category it's taking a user at the top of the page so the user experience is broken can anyone guide me how I can assign separate CSS ID's to these categories & place to ID's in the heading of "Our Products" so when a user hits any product category it lands us on "Our Product" heading.

I have tried the digits ID's (Placed them in heading) which was set by WooCommerce by default when we create a product, it's not working, I'm expecting if a user hits any link in product navigation it lands us to the Our Product heading not at the top of our page


问:
C++ LuDecomposer.mpi.exe ended prematurely and may have crashed. exit code 0xc0000005
i'm new in mpi, when i try to run my code i get this error.

PS C:\Users\dhaua\source\repos\LuDecomposer.mpi\Debug> mpiexec .\LuDecomposer.mpi.exe

job aborted:
[ranks] message

[0-1] terminated

[2] process exited without calling finalize

[3] terminated

---- error analysis -----

[2] on DESKTOP-0U5JD54
.\LuDecomposer.mpi.exe ended prematurely and may have crashed. exit code 0xc0000005

---- error analysis -----

main.cpp:

```<code>#include "stdio.h"
#include "math.h"
#include "conio.h"
#include "LuDecomposer.h"
#include <malloc.h>
#include <string.h>
#include "LuTests.h"
#include "mpi.h"
//#include <omp.h>

int main()
{
    int thread_rank, thread_size, processor_name_length;
    int* thread_range;
    double cpu_time_start, cpu_time_fini;
    char* processor_name = new char[MPI_MAX_PROCESSOR_NAME * sizeof(char)];
    MPI_Status status;
    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &thread_size);

    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &thread_rank);

    int name_len;
    MPI_Get_processor_name(processor_name, &name_len);

    LuDecomposer decomposer(thread_size, thread_rank);
    LuTests tests(&decomposer);

    if (thread_rank == 0) { printf("============= Runing tests\n"); };

    printf("=============MaltiplicationTestTwo\n");
    tests.MaltiplicationTestTwo(thread_size, thread_rank);

    MPI_Finalize();
    return 0;
}
</code>```

TestLy.cpp:

```<code>void LuTests::MaltiplicationTestTwo(int thread_size, int thread_rank)
{
    double A[] = {
        0, 0, 0, 0, 0,
        0, 0, 1, 2, 0,
        0, 0, 3, 4, 0,
        0, 0, 5, 6, 0,
        0, 0, 0, 0, 0
    };

    double B[] = {
        0, 0, 0, 0, 0,
        0, 0, 1, 3, 5,
        0, 0, 2, 4, 6,
        0, 0, 0, 0, 0,
        0, 0, 0, 0, 0
    };

    double expectedAA[] = {
        5, 11, 17,
        11, 25, 39,
        17, 39, 61
    };

    double* AA = new double[9]();

    decomposer->Multiplication(A, B, AA, 5, 3, 2, 1, 2, 1, 2);
    if (thread_rank == 0) {
        bool isCorrect = decomposer->AreEqual(AA, expectedAA, 3);

        if (isCorrect)
            printf("============= Success!\n");
        else
        {
            printf("============= Error!\n");
            printf("============= Print AA\n");
            decomposer->PrintMatrix(AA, 3);
        }
    }
}
</code>```

LuDecomposer.cpp:

```<code>void LuDecomposer::Multiplication(double* A, double* B, double* Res, int size, int subMatrixHeight, int subMatrixWidth, int rowBiasA, int colBiasA, int rowBiasB, int colBiasB)
{
    int u, v, p;

    MPI_Status status;
        int* range = new int[2];
        if (thread_rank == 0)
        {
            interval[0] = 0;
            interval[1] = subMatrixHeight;

            cpu_time_start = MPI_Wtime();
        }
        MPI_Bcast(&interval, 1, MPI_INT, 0, MPI_COMM_WORLD);

            range = get_interval(thread_rank, thread_size, interval);

            for (range[0]; range[0] < range[1]; range[0]++)
            {
                u = (range[0] + rowBiasA) * size + colBiasA;
                for (int j = 0; j < subMatrixWidth; j++)
                {
                    v = (j + rowBiasB) * size + colBiasB;
                    p = u + j;

                    for (int t = 0; t < subMatrixHeight; t++)
                    {
                        Res[range[0] * subMatrixHeight + t] += A[p] * B[v + t];
                    }
                }
            }
            if (thread_rank == 0)
        {
            cpu_time_fini = MPI_Wtime();
    //      printf("CPU Time: %lf ms\n", (cpu_time_fini - cpu_time_start) * 1000);
        }

    }
</code>```

Body:
i'm new in mpi, when i try to run my code i get this error.

PS C:\Users\dhaua\source\repos\LuDecomposer.mpi\Debug> mpiexec .\LuDecomposer.mpi.exe

job aborted:
[ranks] message

[0-1] terminated

[2] process exited without calling finalize

[3] terminated

---- error analysis -----

[2] on DESKTOP-0U5JD54
.\LuDecomposer.mpi.exe ended prematurely and may have crashed. exit code 0xc0000005

---- error analysis -----

main.cpp:

#include "stdio.h"
#include "math.h"
#include "conio.h"
#include "LuDecomposer.h"
#include <malloc.h>
#include <string.h>
#include "LuTests.h"
#include "mpi.h"
//#include <omp.h>

int main()
{
    int thread_rank, thread_size, processor_name_length;
    int* thread_range;
    double cpu_time_start, cpu_time_fini;
    char* processor_name = new char[MPI_MAX_PROCESSOR_NAME * sizeof(char)];
    MPI_Status status;
    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &thread_size);

    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &thread_rank);

    int name_len;
    MPI_Get_processor_name(processor_name, &name_len);

    LuDecomposer decomposer(thread_size, thread_rank);
    LuTests tests(&decomposer);

    if (thread_rank == 0) { printf("============= Runing tests\n"); };

    printf("=============MaltiplicationTestTwo\n");
    tests.MaltiplicationTestTwo(thread_size, thread_rank);

    MPI_Finalize();
    return 0;
}

TestLy.cpp:

void LuTests::MaltiplicationTestTwo(int thread_size, int thread_rank)
{
    double A[] = {
        0, 0, 0, 0, 0,
        0, 0, 1, 2, 0,
        0, 0, 3, 4, 0,
        0, 0, 5, 6, 0,
        0, 0, 0, 0, 0
    };

    double B[] = {
        0, 0, 0, 0, 0,
        0, 0, 1, 3, 5,
        0, 0, 2, 4, 6,
        0, 0, 0, 0, 0,
        0, 0, 0, 0, 0
    };

    double expectedAA[] = {
        5, 11, 17,
        11, 25, 39,
        17, 39, 61
    };

    double* AA = new double[9]();

    decomposer->Multiplication(A, B, AA, 5, 3, 2, 1, 2, 1, 2);
    if (thread_rank == 0) {
        bool isCorrect = decomposer->AreEqual(AA, expectedAA, 3);

        if (isCorrect)
            printf("============= Success!\n");
        else
        {
            printf("============= Error!\n");
            printf("============= Print AA\n");
            decomposer->PrintMatrix(AA, 3);
        }
    }
}

LuDecomposer.cpp:

void LuDecomposer::Multiplication(double* A, double* B, double* Res, int size, int subMatrixHeight, int subMatrixWidth, int rowBiasA, int colBiasA, int rowBiasB, int colBiasB)
{
    int u, v, p;

    MPI_Status status;
        int* range = new int[2];
        if (thread_rank == 0)
        {
            interval[0] = 0;
            interval[1] = subMatrixHeight;

            cpu_time_start = MPI_Wtime();
        }
        MPI_Bcast(&interval, 1, MPI_INT, 0, MPI_COMM_WORLD);

            range = get_interval(thread_rank, thread_size, interval);

            for (range[0]; range[0] < range[1]; range[0]++)
            {
                u = (range[0] + rowBiasA) * size + colBiasA;
                for (int j = 0; j < subMatrixWidth; j++)
                {
                    v = (j + rowBiasB) * size + colBiasB;
                    p = u + j;

                    for (int t = 0; t < subMatrixHeight; t++)
                    {
                        Res[range[0] * subMatrixHeight + t] += A[p] * B[v + t];
                    }
                }
            }
            if (thread_rank == 0)
        {
            cpu_time_fini = MPI_Wtime();
    //      printf("CPU Time: %lf ms\n", (cpu_time_fini - cpu_time_start) * 1000);
        }

    }


问:
How to add CORS on static files with HTTPOption support (.NET Core)
How does one specify a CORS policy on static files and allow HTTPOption (preflight) requests? I'm trying to retrieve a static file from application Y into application X via an XHR request. But this gives the following error:

Access to XMLHttpRequest at 'Y/test.jpg' from origin 'X' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

The first problem that seems to occur is that HTTPOption requests are returning 404 errors. Why is that? It would make sense in missing controller endpoints, but in this case the URL leads to a file.

In this answer it seems like the AspNetCoreModuleV2 does not know how to handle HTTPOption.
After modifying the web.config as shown in the answer (removing HTTPOption from the module), I do get a 200 response and the last obstacle is the actual CORS error itself.

Because the HTTPOption is not handled via AspNetCoreModuleV2 after the change, the only way I can think of to add the CORS headers is to do this from the web.config. e.g.:

```<code><add name="Access-Control-Allow-Origin" value="*" />
</code>```

With those two changes, application X can load the data properly. I do think this is not a clean solution, because:

The HTTPOption will not work on controller-specific endpoints because its filtered away from web.config

The CORS headers will be added in all requests, instead of on static files only

The .NET Core CORS (AddCors/UseCors) is not used

Body:
How does one specify a CORS policy on static files and allow HTTPOption (preflight) requests? I'm trying to retrieve a static file from application Y into application X via an XHR request. But this gives the following error:

Access to XMLHttpRequest at 'Y/test.jpg' from origin 'X' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

The first problem that seems to occur is that HTTPOption requests are returning 404 errors. Why is that? It would make sense in missing controller endpoints, but in this case the URL leads to a file.

In this answer it seems like the AspNetCoreModuleV2 does not know how to handle HTTPOption.
After modifying the web.config as shown in the answer (removing HTTPOption from the module), I do get a 200 response and the last obstacle is the actual CORS error itself.

Because the HTTPOption is not handled via AspNetCoreModuleV2 after the change, the only way I can think of to add the CORS headers is to do this from the web.config. e.g.:

<add name="Access-Control-Allow-Origin" value="*" />

With those two changes, application X can load the data properly. I do think this is not a clean solution, because:

The HTTPOption will not work on controller-specific endpoints because its filtered away from web.config

The CORS headers will be added in all requests, instead of on static files only

The .NET Core CORS (AddCors/UseCors) is not used


问:
Need to mock Snowflake setting for connection string for unit test
Trying to write unit test case to mock snowflake DB and pass table as input for mock</p>
```<code>    var ss = new Mock<SnowflakeSettings>();
                ss.SetupAllProperties();
                ss.Setup(x => x.ConnectionString).Returns(snowflake.GetConnectionString());
                Common.Unity.RegisterInstance<SnowflakeSettings>(ss.Object);

Trying this i am getting error As Message = "Invalid setup on a non-virtual (overridable in VB) member: x => x.ConnectionString"
</code>```

Body:
Trying to write unit test case to mock snowflake DB and pass table as input for mock

    var ss = new Mock<SnowflakeSettings>();
                ss.SetupAllProperties();
                ss.Setup(x => x.ConnectionString).Returns(snowflake.GetConnectionString());
                Common.Unity.RegisterInstance<SnowflakeSettings>(ss.Object);

Trying this i am getting error As Message = "Invalid setup on a non-virtual (overridable in VB) member: x => x.ConnectionString"


问:
Display image from SQL database to itext7
I have tried to display image from SQL database to itext7 pdf using ASP.Net Core Entity Framework Core but display only iText.Layout.Element.Image. Here are my samples.

```<code>var query = (from p in _context.Student
                     where p.StudentId == "10001"
                     select new
                     {
                         id = p.StudentId,
                         photo = p.Imgphoto,
                     }).ToList();
        var row = query.ElementAt(0);

Image imge = new Image(ImageDataFactory.Create(row.photo));

Table table = new Table(2).UseAllAvailableWidth();

Cell cell = new Cell(1, 2).Add(new Paragraph("Student Details"));
table.AddCell(cell);

cell = new Cell().Add(new Paragraph("id"));
            cell.SetWidth(100);
            table.AddCell(cell);
cell = new Cell().Add(new Paragraph(Convert.ToString(imge.SetAutoScale(true)).ToString()));
            cell.SetWidth(200);
            table.AddCell(cell);
doc.Add(table);
</code>```

Body:
I have tried to display image from SQL database to itext7 pdf using ASP.Net Core Entity Framework Core but display only iText.Layout.Element.Image. Here are my samples.

var query = (from p in _context.Student
                     where p.StudentId == "10001"
                     select new
                     {
                         id = p.StudentId,
                         photo = p.Imgphoto,
                     }).ToList();
        var row = query.ElementAt(0);

Image imge = new Image(ImageDataFactory.Create(row.photo));

Table table = new Table(2).UseAllAvailableWidth();

Cell cell = new Cell(1, 2).Add(new Paragraph("Student Details"));
table.AddCell(cell);

cell = new Cell().Add(new Paragraph("id"));
            cell.SetWidth(100);
            table.AddCell(cell);
cell = new Cell().Add(new Paragraph(Convert.ToString(imge.SetAutoScale(true)).ToString()));
            cell.SetWidth(200);
            table.AddCell(cell);
doc.Add(table);


问:
psycopg2.ProgrammingError: no results to fetch (fetchall SELECT EXISTS)
```<code>Traceback (most recent call last):
  File "/app/main.py", line 324, in that_function
    links = cur.fetchall()[0]
  File "/app/.heroku/python/lib/python3.10/site-packages/psycopg2/extras.py", line 104, in fetchall
    res = super().fetchall()
psycopg2.ProgrammingError: no results to fetch
</code>```

I don't understand why I get this exception in this code:

```<code>cur.execute(
    "SELECT EXISTS(SELECT 1 FROM images where link = %s)", (original_url,)
)
links = cur.fetchall()[0]
</code>```

What is the logical error in this? What's weird is in my infinite looping Python script, this happens randomly. The database is updated throughout the script however, so I'm not sure what is causing it.

Body:
Traceback (most recent call last):
  File "/app/main.py", line 324, in that_function
    links = cur.fetchall()[0]
  File "/app/.heroku/python/lib/python3.10/site-packages/psycopg2/extras.py", line 104, in fetchall
    res = super().fetchall()
psycopg2.ProgrammingError: no results to fetch

I don't understand why I get this exception in this code:

cur.execute(
    "SELECT EXISTS(SELECT 1 FROM images where link = %s)", (original_url,)
)
links = cur.fetchall()[0]

What is the logical error in this? What's weird is in my infinite looping Python script, this happens randomly. The database is updated throughout the script however, so I'm not sure what is causing it.


问:
Error: JavaFX runtime components are missing using shade
I am trying to generate a jar file by embedding within it the javaFx dependencies needed to run my program.

Below is my pom.xml file that includes the shave plugin which should do exactly that.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>SoftwareRtf</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>SoftwareRtf</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>5.8.2</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics </artifactId>
            <version>11</version>
            <classifier>win</classifier>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics </artifactId>
            <version>11</version>
            <classifier>linux</classifier>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics </artifactId>
            <version>11</version>
            <classifier>mac</classifier>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.openjfx/javafx-media -->
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-media</artifactId>
            <version>20-ea+9</version>
        </dependency>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>17.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.example.softwarertf.MenuExample</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Later from the command line I ran:
mvn package

In doing so, two files are generated:
original-SoftwareRtf-1.0-SNAPSHOT.jar and SoftwareRtf-1.0-SNAPSHOT.jar

That by executing them using the command:
java -jar ....
produce this error

Error: JavaFX runtime components are missing, and are required to run this application

Using the following command I was able to see what is contained in the jar file and I see the JavaFx files inside them.

mvn dependency:tree -Ddetail=true

```<code>com.example:SoftwareRtf:jar:1.0-SNAPSHOT
\[INFO\] +- org.openjfx:javafx-controls:jar:17.0.2:compile
\[INFO\] |  +- org.openjfx:javafx-controls:jar:mac-aarch64:17.0.2:compile
\[INFO\] |  - org.openjfx:javafx-graphics:jar:17.0.2:compile
\[INFO\] |     +- org.openjfx:javafx-graphics:jar:mac-aarch64:17.0.2:compile
\[INFO\] |     - org.openjfx:javafx-base:jar:17.0.2:compile
\[INFO\] |        - org.openjfx:javafx-base:jar:mac-aarch64:17.0.2:compile
\[INFO\] +- org.openjfx:javafx-media:jar:20-ea+9:compile
\[INFO\] |  - org.openjfx:javafx-media:jar:mac-aarch64:20-ea+9:compile
\[INFO\] +- org.openjfx:javafx-fxml:jar:17.0.2:compile
\[INFO\] |  - org.openjfx:javafx-fxml:jar:mac-aarch64:17.0.2:compile
\[INFO\] +- org.junit.jupiter:junit-jupiter-api:jar:5.8.2:test
\[INFO\] |  +- org.opentest4j:opentest4j:jar:1.2.0:test
\[INFO\] |  +- org.junit.platform:junit-platform-commons:jar:1.8.2:test
\[INFO\] |  - org.apiguardian:apiguardian-api:jar:1.1.2:test
\[INFO\] - org.junit.jupiter:junit-jupiter-engine:jar:5.8.2:test
\[INFO\]    - org.junit.platform:junit-platform-engine:jar:1.8.2:test
</code>```

I don't understand what I am doing wrong, could it be some necessary module that was not included? Any input is welcome. Thank you!

Body:
I am trying to generate a jar file by embedding within it the javaFx dependencies needed to run my program.

Below is my pom.xml file that includes the shave plugin which should do exactly that.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>SoftwareRtf</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>SoftwareRtf</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>5.8.2</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics </artifactId>
            <version>11</version>
            <classifier>win</classifier>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics </artifactId>
            <version>11</version>
            <classifier>linux</classifier>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics </artifactId>
            <version>11</version>
            <classifier>mac</classifier>
        </dependency>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-media</artifactId>
            <version>20-ea+9</version>
        </dependency>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>17.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.example.softwarertf.MenuExample</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Later from the command line I ran:
mvn package

In doing so, two files are generated:
original-SoftwareRtf-1.0-SNAPSHOT.jar and SoftwareRtf-1.0-SNAPSHOT.jar

That by executing them using the command:
java -jar ....
produce this error

Error: JavaFX runtime components are missing, and are required to run this application

Using the following command I was able to see what is contained in the jar file and I see the JavaFx files inside them.

mvn dependency:tree -Ddetail=true

com.example:SoftwareRtf:jar:1.0-SNAPSHOT
\[INFO\] +- org.openjfx:javafx-controls:jar:17.0.2:compile
\[INFO\] |  +- org.openjfx:javafx-controls:jar:mac-aarch64:17.0.2:compile
\[INFO\] |  - org.openjfx:javafx-graphics:jar:17.0.2:compile
\[INFO\] |     +- org.openjfx:javafx-graphics:jar:mac-aarch64:17.0.2:compile
\[INFO\] |     - org.openjfx:javafx-base:jar:17.0.2:compile
\[INFO\] |        - org.openjfx:javafx-base:jar:mac-aarch64:17.0.2:compile
\[INFO\] +- org.openjfx:javafx-media:jar:20-ea+9:compile
\[INFO\] |  - org.openjfx:javafx-media:jar:mac-aarch64:20-ea+9:compile
\[INFO\] +- org.openjfx:javafx-fxml:jar:17.0.2:compile
\[INFO\] |  - org.openjfx:javafx-fxml:jar:mac-aarch64:17.0.2:compile
\[INFO\] +- org.junit.jupiter:junit-jupiter-api:jar:5.8.2:test
\[INFO\] |  +- org.opentest4j:opentest4j:jar:1.2.0:test
\[INFO\] |  +- org.junit.platform:junit-platform-commons:jar:1.8.2:test
\[INFO\] |  - org.apiguardian:apiguardian-api:jar:1.1.2:test
\[INFO\] - org.junit.jupiter:junit-jupiter-engine:jar:5.8.2:test
\[INFO\]    - org.junit.platform:junit-platform-engine:jar:1.8.2:test

I don't understand what I am doing wrong, could it be some necessary module that was not included? Any input is welcome. Thank you!


问:
Can't get the current wifi connection using win32com.client in python
I'm trying to make a python script that automatically switch on and off the manual proxy setup in windows 10 (check the image) based on the name of the current network, I'm doing this because a wifi network on my school require a proxy to work and I'm tired of switching it on and off manually and sometimes forgetting to switching it on and waste time trying to understand what's wrong...
screenshot of the settings that I want to controle
So here is the code
`

```<code>import win32com.client
import time

# Replace this with the name of the WiFi network that you want
# the script to enable the proxy for
TARGET_NETWORK_NAME = "ENSIAS-STUDENT"

# Replace this with the address and port of the proxy server
# that you want to use when connected to the target network
PROXY_SERVER_ADDRESS = "10.23.201.11"
PROXY_SERVER_PORT = 3128

def set_proxy(enabled: bool):
    """Enable or disable the manual proxy setup in Windows 10."""
    # Connect to the Windows Management Instrumentation (WMI) service
    wmi = win32com.client.GetObject("winmgmts:")

    # Get the current WiFi connection
    wifi_connection = wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID LIKE 'Wi-Fi'")[0]

    # Get the settings of the current WiFi connection
    settings = wifi_connection.Setting

    # Set the proxy settings of the WiFi connection based on the
    # enabled flag
    settings.IPX.EnableIPSec = False
    settings.IPX.EnableIPsecNATTraversal = False
    settings.IPX.EnableL2TPOverIPSec = False
    settings.IPX.AutoConfigurationEnabled = not enabled
    settings.IPX.ProxyServer = PROXY_SERVER_ADDRESS if enabled else ""
    settings.IPX.ProxyPort = PROXY_SERVER_PORT if enabled else 0
    settings.IPX.EnableProxy = enabled
    settings.Put_()

# Continuously check the name of the currently connected WiFi network
# and enable or disable the proxy accordingly
while True:
    # Connect to the Windows Management Instrumentation (WMI) service
    wmi = win32com.client.GetObject("winmgmts:")

    # Get the current WiFi connection
    wifi_connection = wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID LIKE 'Wi-Fi'")[0]

    # Get the name of the network that the WiFi connection is currently connected to
    network_name = wifi_connection.NetConnectionID

    # Check if the WiFi connection is connected to the target network
    if network_name == TARGET_NETWORK_NAME:
        # Enable the manual proxy setup
        set_proxy(True)
    else:
        # Disable the manual proxy setup
        set_proxy(False)

    # Sleep for 1 second before checking the network again
    time.sleep(1)

</code>```

When I run it it says:
AttributeError: .Setting
after debugging I found that

```<code>    wifi_connection = wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID LIKE 'Wi-Fi'")[0]
</code>```

this line of code returns <COMObject <unknown>> which I believe is wrong and should return something else.
I checked the WMI service and it's running, I tried modifying the query and it always give the samething.

I tried another approach which is using netsh winhttp set proxy proxy-server=http://myproxy:8080 and it says that the proxy server is updated but the network doesn't work.
Can someone help please?

Body:
I'm trying to make a python script that automatically switch on and off the manual proxy setup in windows 10 (check the image) based on the name of the current network, I'm doing this because a wifi network on my school require a proxy to work and I'm tired of switching it on and off manually and sometimes forgetting to switching it on and waste time trying to understand what's wrong...
screenshot of the settings that I want to controle
So here is the code
`

import win32com.client
import time

# Replace this with the name of the WiFi network that you want
# the script to enable the proxy for
TARGET_NETWORK_NAME = "ENSIAS-STUDENT"

# Replace this with the address and port of the proxy server
# that you want to use when connected to the target network
PROXY_SERVER_ADDRESS = "10.23.201.11"
PROXY_SERVER_PORT = 3128

def set_proxy(enabled: bool):
    """Enable or disable the manual proxy setup in Windows 10."""
    # Connect to the Windows Management Instrumentation (WMI) service
    wmi = win32com.client.GetObject("winmgmts:")

    # Get the current WiFi connection
    wifi_connection = wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID LIKE 'Wi-Fi'")[0]

    # Get the settings of the current WiFi connection
    settings = wifi_connection.Setting

    # Set the proxy settings of the WiFi connection based on the
    # enabled flag
    settings.IPX.EnableIPSec = False
    settings.IPX.EnableIPsecNATTraversal = False
    settings.IPX.EnableL2TPOverIPSec = False
    settings.IPX.AutoConfigurationEnabled = not enabled
    settings.IPX.ProxyServer = PROXY_SERVER_ADDRESS if enabled else ""
    settings.IPX.ProxyPort = PROXY_SERVER_PORT if enabled else 0
    settings.IPX.EnableProxy = enabled
    settings.Put_()

# Continuously check the name of the currently connected WiFi network
# and enable or disable the proxy accordingly
while True:
    # Connect to the Windows Management Instrumentation (WMI) service
    wmi = win32com.client.GetObject("winmgmts:")

    # Get the current WiFi connection
    wifi_connection = wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID LIKE 'Wi-Fi'")[0]

    # Get the name of the network that the WiFi connection is currently connected to
    network_name = wifi_connection.NetConnectionID

    # Check if the WiFi connection is connected to the target network
    if network_name == TARGET_NETWORK_NAME:
        # Enable the manual proxy setup
        set_proxy(True)
    else:
        # Disable the manual proxy setup
        set_proxy(False)

    # Sleep for 1 second before checking the network again
    time.sleep(1)

When I run it it says:
AttributeError: .Setting
after debugging I found that

    wifi_connection = wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID LIKE 'Wi-Fi'")[0]

this line of code returns <COMObject <unknown>> which I believe is wrong and should return something else.
I checked the WMI service and it's running, I tried modifying the query and it always give the samething.

I tried another approach which is using netsh winhttp set proxy proxy-server=http://myproxy:8080 and it says that the proxy server is updated but the network doesn't work.
Can someone help please?