问:
Using flow control commands in string processing
Given the following string:

int[] array = {12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87}

Using the given string as a starting point, you need to create two new integer strings:

within the first it is necessary to find all the positive numbers in a given sequence;
within the second string it is necessary to find all negative numbers in the given string.
In other words, from array array it is necessary to extract all positive elements and place them in a separate array and extract all negative elements and place them in a separate array. Finally, it is necessary to print the values of all members of the two output arrays.

The task is best solved using a loop, which would be used to iterate over the given string. In each iteration of the loop, the value of the array member would be checked and depending on the value, it would be placed in the appropriate destination array (positive/negative).

using System;
namespace Assignment
{
class Program
{
static void Main(string[] args)
{
int[] array = { 12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87 };

```<code>        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] < 0)
                Console.WriteLine("Negative number is: " + " " + array[i]);
        }

        for (int j = 0; j < array.Length; j++)
        {
            if (array[j] > 0)
                Console.WriteLine("Positive number is: " + " " + array[j]);
        }

    }
}
</code>```

Body:
Given the following string:

int[] array = {12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87}

Using the given string as a starting point, you need to create two new integer strings:

within the first it is necessary to find all the positive numbers in a given sequence;
within the second string it is necessary to find all negative numbers in the given string.
In other words, from array array it is necessary to extract all positive elements and place them in a separate array and extract all negative elements and place them in a separate array. Finally, it is necessary to print the values of all members of the two output arrays.

The task is best solved using a loop, which would be used to iterate over the given string. In each iteration of the loop, the value of the array member would be checked and depending on the value, it would be placed in the appropriate destination array (positive/negative).

using System;
namespace Assignment
{
class Program
{
static void Main(string[] args)
{
int[] array = { 12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87 };

        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] < 0)
                Console.WriteLine("Negative number is: " + " " + array[i]);
        }

        for (int j = 0; j < array.Length; j++)
        {
            if (array[j] > 0)
                Console.WriteLine("Positive number is: " + " " + array[j]);
        }

    }
}


来源: stackexchange

问:
Android Service Sending Camera Live Feed using socket.io to Electron JS application
I am creating an Android Application, which sends Camera live feed to Electron JS Application. I don't want the Screen to be on to use the battery so that's why I'm using service to to send this live Feed.
I need help from where exactly should I start?
Following is the code of Camera Class which I created...</p>
```<code>public class Camera {

    private Context context ;
    private Camera camera;

    public Camera(Context context) {
        this.context = context;
    }

    public void startUp(int cameraID){
        camera = Camera.open(cameraID);
        Parameters parameters = camera.getParameters();
        camera.setParameters(parameters);
        camera.startPreview();
    }
    private void sendCamFeed(byte [] data){

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            JSONObject object = new JSONObject();
            object.put("camFeed",true);
            object.put("buffer" , bos.toByteArray());
            IOSocket.getInstance().getIoSocket().emit("camLiveFeed" , object);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void releaseCamera(){
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating an Android Application, which sends Camera live feed to Electron JS Application. I don't want the Screen to be on to use the battery so that's why I'm using service to to send this live Feed.
I need help from where exactly should I start?
Following is the code of Camera Class which I created...

public class Camera {

    private Context context ;
    private Camera camera;

    public Camera(Context context) {
        this.context = context;
    }

    public void startUp(int cameraID){
        camera = Camera.open(cameraID);
        Parameters parameters = camera.getParameters();
        camera.setParameters(parameters);
        camera.startPreview();
    }
    private void sendCamFeed(byte [] data){

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            JSONObject object = new JSONObject();
            object.put("camFeed",true);
            object.put("buffer" , bos.toByteArray());
            IOSocket.getInstance().getIoSocket().emit("camLiveFeed" , object);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void releaseCamera(){
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

}


问:
Hi, I am using Django rest framework and when I want to encrypt my videos inside sections view I get error can someone help me
I am using Django rest framework and when I want to encrypt my videos inside sections view I get error and I installed cryptography package and I write the code for encrypting and decrypting but when I run the code it gives me error also I add encrypt key inside settings.py here is my code

views.py

```<code>class ChapterSectionList(generics.ListAPIView):
serializer_class=SectionSerializer

def get_queryset(self):
    chapter_id=self.kwargs['chapter_id']
    chapter=models.Chapter.objects.get(pk=chapter_id)
    l=[]
    for i in chapter_id:
        i['encrypt_key']=encrypt(i['chapter_id'])
        i['chapter_id']=i['chapter_id']
        l.append(i)
    return models.Section.objects.filter(chapter=l)
</code>```

encryption_util.py

```<code>   from cryptography.fernet import Fernet
   import base64
   import logging
   import traceback
   from django.conf import settings

   def encrypt(text):
       try:
          txt = str(txt)
          cipher_suite = Fernet(settings.ENCRYPT_KEY)
          encrypted_text =
          cipher_suite.encrypt(txt.encode('ascii'))
          encrypted_text =
          base64.urlsafe_b64encode(encrypted_text).decode("ascii")
          return encrypted_text
        except Exception as e:
           print(e)
    logging.getLogger("error_logger").error(traceback.format_exc())
    return None

    def decrypt(txt):
        try:
           txt = base64.urlsafe_b64encode(txt)
           cipher_suite = Fernet(settings.ENCRYPT_KEY)
           decoded_text = cipher_suite.decrypt(txt).decode("ascii")
           return decoded_text
       except Exception as e:
    logging.getLogger("error_logger").error(traceback.format_exc())
    return None
</code>```

urls.py

```<code>    path('chapter-section-list/<str:chapter_id>/',
    views.ChapterSectionList.as_view()),
</code>```

I want to get solution to my problem

Body:
I am using Django rest framework and when I want to encrypt my videos inside sections view I get error and I installed cryptography package and I write the code for encrypting and decrypting but when I run the code it gives me error also I add encrypt key inside settings.py here is my code

views.py

class ChapterSectionList(generics.ListAPIView):
serializer_class=SectionSerializer

def get_queryset(self):
    chapter_id=self.kwargs['chapter_id']
    chapter=models.Chapter.objects.get(pk=chapter_id)
    l=[]
    for i in chapter_id:
        i['encrypt_key']=encrypt(i['chapter_id'])
        i['chapter_id']=i['chapter_id']
        l.append(i)
    return models.Section.objects.filter(chapter=l)

encryption_util.py

   from cryptography.fernet import Fernet
   import base64
   import logging
   import traceback
   from django.conf import settings

   def encrypt(text):
       try:
          txt = str(txt)
          cipher_suite = Fernet(settings.ENCRYPT_KEY)
          encrypted_text =
          cipher_suite.encrypt(txt.encode('ascii'))
          encrypted_text =
          base64.urlsafe_b64encode(encrypted_text).decode("ascii")
          return encrypted_text
        except Exception as e:
           print(e)
    logging.getLogger("error_logger").error(traceback.format_exc())
    return None

    def decrypt(txt):
        try:
           txt = base64.urlsafe_b64encode(txt)
           cipher_suite = Fernet(settings.ENCRYPT_KEY)
           decoded_text = cipher_suite.decrypt(txt).decode("ascii")
           return decoded_text
       except Exception as e:
    logging.getLogger("error_logger").error(traceback.format_exc())
    return None

urls.py

    path('chapter-section-list/<str:chapter_id>/',
    views.ChapterSectionList.as_view()),

I want to get solution to my problem


问:
Powershell -ErrorAction SilentlyContinue does not add any errors to $Error variable
I am trying to figure out why when I set ErrorAction to SilentlyContinue, no errors are written to the $Error variable.

This is the command I am using:
Import-CSV C:\Users\User\Documents\list.csv | foreach{Remove-DistributionGroupMember -Identity mydladdress@mysite.com -Member $_.email -Confirm:$false -ErrorAction SilentlyContinue}.

When I run the command without the ErrorAction, the errors are printed to the $Error variable but it also displays the errors in the console which I do not want.

Your assistance will be appreciated!

Kind regards,
Dust


问:
terratest Error AuthFailure: AWS was not able to validate the provided access credentials for apigateway
This is my first terratest code following the [getting started][1] to my api-gateway tf code base. My code base consists of backend with s3 as state file. and my apigateway output.tf is as follow

```<code>output "deployment_invoke_url" {
  description = "Deployment invoke url"
  value       = "${aws_api_gateway_stage.my_stage.invoke_url}/resource"
}
</code>```

my backend.tf looks like this:

```<code>terraform {
  backend "s3" {}
}
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.47.0"
    }
  }
}
provider "aws" {
  region     = var.aws_region
  access_key = var.access_key
  secret_key = var.secret_key
  token      = var.token
}
</code>```

now my apigateway_test.go looks like this:

```<code>package apigateway

import (
    "github.com/gruntwork-io/terratest/modules/aws"
    "github.com/gruntwork-io/terratest/modules/random"
    "github.com/gruntwork-io/terratest/modules/terraform"
    "github.com/stretchr/testify/assert"
    "log"
    "net/http"
    "testing"
    "time"
    "fmt"
    "strings"
)

func TestApiGateway(t *testing.T) {
    t.Parallel()

    awsRegion := aws.GetRandomRegion(t, nil, nil)
    uniqueId := random.UniqueId()
    // Create an S3 bucket where we can store state
    bucketName := fmt.Sprintf("test-terraform-backend-example-%s", strings.ToLower(uniqueId))
    defer cleanupS3Bucket(t, awsRegion, bucketName)
    aws.CreateS3Bucket(t, awsRegion, bucketName)

    key := fmt.Sprintf("%s/terraform.tfstate", uniqueId)
    data := fmt.Sprintf("data-for-test-%s", uniqueId)
    secretKey, accessKey := key, key

    terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
        TerraformDir: "../../",
        Vars: map[string]interface{}{
            "token": data,
            "region": awsRegion,
            "access_key": accessKey,
            "secret_key": secretKey,
        },
        BackendConfig: map[string]interface{}{
            "bucket": bucketName,
            "key":    key,
            "region": awsRegion,
        },
        // Environment variables to set when running Terraform
        EnvVars: map[string]string{
            "AWS_DEFAULT_REGION": awsRegion,
            "AWS_ACCESS_KEY_ID": accessKey,
            "AWS_SECRET_ACCESS_KEY": secretKey,
        },
    })
    defer terraform.Destroy(t, terraformOptions)
    terraform.InitAndApply(t, terraformOptions)
    stageUrl := terraform.Output(t, terraformOptions, "deployment_invoke_url")
    time.Sleep(30 * time.Second)
    statusCode := DoGetRequest(t, stageUrl)
    assert.Equal(t, 200, statusCode)
}

func DoGetRequest(t *testing.T, api string) int {
    resp, err := http.Get(api)
    if err != nil {
        log.Fatalln(err)
    }
    //We Read the response status on the line below.
    return resp.StatusCode
}

func cleanupS3Bucket(t *testing.T, awsRegion string, bucketName string) {
    aws.EmptyS3Bucket(t, awsRegion, bucketName)
    aws.DeleteS3Bucket(t, awsRegion, bucketName)
}
</code>```

go test I'm getting below error:

```<code>region.go:64: Error finding AWS credentials. Did you set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables or configure an AWS profile? Underlying error: NoCredentialProviders: no valid providers in chain. Deprecated.
                For verbose messaging see aws.Config.CredentialsChainVerboseErrors
--- FAIL: TestApiGateway (5.31s)
</code>```

Even if I have added env variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in ENV in terraformOPtions it still shows me same error.

Hence as a workaround I tried this, which fixed my error

```<code> export AWS_ACCESS_KEY_ID="xxxxx"
export AWS_SECRET_ACCESS_KEY="yyyyy"
</code>```

however now it's giving me error as below

```<code>region.go:64: AuthFailure: AWS was not able to validate the provided access credentials
                status code: 401, request id: 1f7d65d9-8019-40a3-abc3-11de4af8cd51
</code>```

Does anyone knows right way to test this?

Body:
This is my first terratest code following the [getting started][1] to my api-gateway tf code base. My code base consists of backend with s3 as state file. and my apigateway output.tf is as follow

output "deployment_invoke_url" {
  description = "Deployment invoke url"
  value       = "${aws_api_gateway_stage.my_stage.invoke_url}/resource"
}

my backend.tf looks like this:

terraform {
  backend "s3" {}
}
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.47.0"
    }
  }
}
provider "aws" {
  region     = var.aws_region
  access_key = var.access_key
  secret_key = var.secret_key
  token      = var.token
}

now my apigateway_test.go looks like this:

package apigateway

import (
    "github.com/gruntwork-io/terratest/modules/aws"
    "github.com/gruntwork-io/terratest/modules/random"
    "github.com/gruntwork-io/terratest/modules/terraform"
    "github.com/stretchr/testify/assert"
    "log"
    "net/http"
    "testing"
    "time"
    "fmt"
    "strings"
)

func TestApiGateway(t *testing.T) {
    t.Parallel()

    awsRegion := aws.GetRandomRegion(t, nil, nil)
    uniqueId := random.UniqueId()
    // Create an S3 bucket where we can store state
    bucketName := fmt.Sprintf("test-terraform-backend-example-%s", strings.ToLower(uniqueId))
    defer cleanupS3Bucket(t, awsRegion, bucketName)
    aws.CreateS3Bucket(t, awsRegion, bucketName)

    key := fmt.Sprintf("%s/terraform.tfstate", uniqueId)
    data := fmt.Sprintf("data-for-test-%s", uniqueId)
    secretKey, accessKey := key, key

    terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
        TerraformDir: "../../",
        Vars: map[string]interface{}{
            "token": data,
            "region": awsRegion,
            "access_key": accessKey,
            "secret_key": secretKey,
        },
        BackendConfig: map[string]interface{}{
            "bucket": bucketName,
            "key":    key,
            "region": awsRegion,
        },
        // Environment variables to set when running Terraform
        EnvVars: map[string]string{
            "AWS_DEFAULT_REGION": awsRegion,
            "AWS_ACCESS_KEY_ID": accessKey,
            "AWS_SECRET_ACCESS_KEY": secretKey,
        },
    })
    defer terraform.Destroy(t, terraformOptions)
    terraform.InitAndApply(t, terraformOptions)
    stageUrl := terraform.Output(t, terraformOptions, "deployment_invoke_url")
    time.Sleep(30 * time.Second)
    statusCode := DoGetRequest(t, stageUrl)
    assert.Equal(t, 200, statusCode)
}

func DoGetRequest(t *testing.T, api string) int {
    resp, err := http.Get(api)
    if err != nil {
        log.Fatalln(err)
    }
    //We Read the response status on the line below.
    return resp.StatusCode
}

func cleanupS3Bucket(t *testing.T, awsRegion string, bucketName string) {
    aws.EmptyS3Bucket(t, awsRegion, bucketName)
    aws.DeleteS3Bucket(t, awsRegion, bucketName)
}

go test I'm getting below error:

region.go:64: Error finding AWS credentials. Did you set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables or configure an AWS profile? Underlying error: NoCredentialProviders: no valid providers in chain. Deprecated.
                For verbose messaging see aws.Config.CredentialsChainVerboseErrors
--- FAIL: TestApiGateway (5.31s)

Even if I have added env variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in ENV in terraformOPtions it still shows me same error.

Hence as a workaround I tried this, which fixed my error

 export AWS_ACCESS_KEY_ID="xxxxx"
export AWS_SECRET_ACCESS_KEY="yyyyy"

however now it's giving me error as below

region.go:64: AuthFailure: AWS was not able to validate the provided access credentials
                status code: 401, request id: 1f7d65d9-8019-40a3-abc3-11de4af8cd51

Does anyone knows right way to test this?


问:
Unable to start docker desktop application on Windows 10
I have been using docker on my windows 10 laptop from last 1 month, all of a sudden it started giving an error msg as "failed to start docker instance". Then I tried to uninstall and install it again, but now its giving a error as "rootNode subnodes: constucting.... invalid character '\x00'looking for beginning of value" you can find the error screenshot below.

I am new to docker plaese help me to fix this issue. Thank You.

I tried restarting my laptop, and uninstalled docker and deleteted all the temp files by tying "%temp%" and then reinstalled the docker, from then its giving different error as "rootNodes constructing" like this.

I am expecting docker to be started, but its not starting.


问:
Hyperledger Sawtooth: change Devmode consensus to PBFT/POET
I have a single node sawtooth cluster with Devmode consensus running. I want to change consensus algorithim to PBFT or PoET. But when I am starting new nodes and making existing running node as a peer, then already commited blocks are not getting synced on new nodes completly.Few starting blocks gets synced on new nodes but not all the blocks. I am able to submit new proposal create transaction on existing node to update consensus settings successfully but existing blocks are not getting synced with new nodes for that consensus change to reflect. So I need help with below queries.

Can Sawtooth consensus be updated from Devmode to PBFT/PoET.

What could be possible reasonses preventing blocks getting synced till latest HEAD. And how can i fix it.


问:
While running POSA model: Runtime Error in smplx/body_models.py, reset_params function
I was going through the POSA repository to find the contact vertices of SMPL body and scene. Link to POSA GitHub repository

```<code>Traceback (most recent call last):
  File "src/affordance.py", line 105, in <module>
    vertices_org, vertices_can, faces_arr, body_model, R_can, pelvis, torch_param, vertices_clothed = data_utils.pkl_to_canonical(
  File "<path>/POSA/src/data_utils.py", line 83, in pkl_to_canonical
    body_model.reset_params(**torch_param)
  File "<path>/lib/python3.8/site-packages/torch/autograd/grad_mode.py", line 28, in decorate_context
    return func(*args, **kwargs)
  File “<path>/lib/python3.8/site-packages/smplx-0.1.28-py3.8.egg/smplx/body_models.py", line 289, in reset_params
RuntimeError: The expanded size of the tensor (16) must match the existing size (10) at non-singleton dimension 1.  Target sizes: [1, 16].  Tensor sizes: [10]
</code>```

The above Runtime Error is coming when running the sample commands like:

python src/affordance.py --config cfg_files/contact_semantics.yaml --checkpoint_path $POSA_dir/trained_models/contact_semantics.pt --pkl_file_path $POSA_dir/POSA_rp_poses/rp_aaron_posed_001_0_0.pkl --scene_name MPH16 --render 1 --viz 1 --use_cuda False
```
<pre class="lang-bash prettyprint-override"><code>python src/gen_rand_samples.py --config cfg_files/contact.yaml --checkpoint_path $POSA_dir/trained_models/contact.pt --pkl_file_path $POSA_dir/POSA_rp_poses/rp_aaron_posed_001_0_0.pkl --render 1 --viz 1 --num_rand_samples 3
</code>```

I tried to print the arguments which were being passed into the reset_params function which is torch_param. After looking at the shapes of the tensors in torch_param I tried to truncate tensors to 10 in order to resolve this error but it started giving new error and after going through the code I realised that truncating like this is not a right thing.

Body:
I was going through the POSA repository to find the contact vertices of SMPL body and scene. Link to POSA GitHub repository

Traceback (most recent call last):
  File "src/affordance.py", line 105, in <module>
    vertices_org, vertices_can, faces_arr, body_model, R_can, pelvis, torch_param, vertices_clothed = data_utils.pkl_to_canonical(
  File "<path>/POSA/src/data_utils.py", line 83, in pkl_to_canonical
    body_model.reset_params(**torch_param)
  File "<path>/lib/python3.8/site-packages/torch/autograd/grad_mode.py", line 28, in decorate_context
    return func(*args, **kwargs)
  File “<path>/lib/python3.8/site-packages/smplx-0.1.28-py3.8.egg/smplx/body_models.py", line 289, in reset_params
RuntimeError: The expanded size of the tensor (16) must match the existing size (10) at non-singleton dimension 1.  Target sizes: [1, 16].  Tensor sizes: [10]

The above Runtime Error is coming when running the sample commands like:

python src/affordance.py --config cfg_files/contact_semantics.yaml --checkpoint_path $POSA_dir/trained_models/contact_semantics.pt --pkl_file_path $POSA_dir/POSA_rp_poses/rp_aaron_posed_001_0_0.pkl --scene_name MPH16 --render 1 --viz 1 --use_cuda False

python src/gen_rand_samples.py --config cfg_files/contact.yaml --checkpoint_path $POSA_dir/trained_models/contact.pt --pkl_file_path $POSA_dir/POSA_rp_poses/rp_aaron_posed_001_0_0.pkl --render 1 --viz 1 --num_rand_samples 3

I tried to print the arguments which were being passed into the reset_params function which is torch_param. After looking at the shapes of the tensors in torch_param I tried to truncate tensors to 10 in order to resolve this error but it started giving new error and after going through the code I realised that truncating like this is not a right thing.


问:
See the contents of OpenAI Fine Tuned Model Results in Python using the OpenAI API
I have fine tuned a GPT-3 model for classification. The model status still shows pending. However, the model events show that "Fine-tune succeeded. I even get an event showing the uploaded file id. When I download the results file using the following code and print its content, I see the following result:

```<code>content = openai.File.download("file-coumSxxxxxxxxxxxxxxxx")
contents = content.decode()

# Print the contents of the file
print(content)
</code>```

Results:

```<code>b'{\n  "object": "file",\n  "id": "file-coumSxMyXfxQhXEVYLNMWL5F",\n  "purpose": "fine-tune-results",\n  "filename": "compiled_results.csv",\n  "bytes": 168364,\n  "created_at": 1673135506,\n  "status": "processed",\n  "status_details": null\n}\n'
</code>```

Can somebody recommend how I can see the contents of the compiled_results.csv file?

Body:
I have fine tuned a GPT-3 model for classification. The model status still shows pending. However, the model events show that "Fine-tune succeeded. I even get an event showing the uploaded file id. When I download the results file using the following code and print its content, I see the following result:

content = openai.File.download("file-coumSxxxxxxxxxxxxxxxx")
contents = content.decode()

# Print the contents of the file
print(content)

Results:

b'{\n  "object": "file",\n  "id": "file-coumSxMyXfxQhXEVYLNMWL5F",\n  "purpose": "fine-tune-results",\n  "filename": "compiled_results.csv",\n  "bytes": 168364,\n  "created_at": 1673135506,\n  "status": "processed",\n  "status_details": null\n}\n'

Can somebody recommend how I can see the contents of the compiled_results.csv file?


问:
Can you left factor this grammar, whose production bodies have no common prefixes?
The grammar is as follows:

```<code>R -> R + T | T
T -> T F | F
F -> F * | P
P -> a | b
</code>```

Terminals: {+, *, a, b}

Non-terminals: {R, T, F, P}

My understanding is that as there are no common prefixes among the alternatives for any of the nonterminals, this grammar cannot be left factored.

For example, R has alternatives R + T and T, and neither of these share a common prefix.

Is my understanding correct?

I tried eliminating left recursion first, to see if the result could be left factored. But this doesn't seem to be the case:

```<code>R  -> T R'
R' -> + T R' | ε
T  -> F T'
T' -> F T' | ε
F  -> P F'
F' -> * F' | ε
P  -> a | b
</code>```

Body:
The grammar is as follows:

R -> R + T | T
T -> T F | F
F -> F * | P
P -> a | b

Terminals: {+, *, a, b}

Non-terminals: {R, T, F, P}

My understanding is that as there are no common prefixes among the alternatives for any of the nonterminals, this grammar cannot be left factored.

For example, R has alternatives R + T and T, and neither of these share a common prefix.

Is my understanding correct?

I tried eliminating left recursion first, to see if the result could be left factored. But this doesn't seem to be the case:

R  -> T R'
R' -> + T R' | ε
T  -> F T'
T' -> F T' | ε
F  -> P F'
F' -> * F' | ε
P  -> a | b


问:
Puppeteer - How can I open a new page with different session?
I am building an API that requires users to login in a website and I'm handling this with Puppeteer.

The problem here is when two users using the API at the same time (Or in the same browser session), I get an error saying that the user is already logged in and I think this happened because it is the same session.

Here is my current code:

```<code>import express from "express";
import puppeteer from "puppeteer";

const myRoutes = express.Router();

myRoutes.get("/login", async (request, response) => {
  const loginAuth = request.body;

  try {
    const browser = await MyBrowser.initialize();
    const page = await browser.newPage();

    await page.goto("https://website.com/login");
    await page.waitForNetworkIdle({ idleTime: 3000 });

    await page.$eval("#userName", (el, value) => (el.value = value), loginAuth.userName);
    await page.$eval("#password", (el, value) => (el.value = value), loginAuth.password);

    await page.$eval("#loginBtn", (el) => el.click());

    await page.$eval("#loginBtn", (el) => el.click());

    // MyBrowser.closeBrowser();
  } catch (err) {
    console.log("ERRORR OCCURED...");
    console.log(err);
  }

  response.end("No message");
});

class MyBrowser {
  static #browser;

  static async initialize() {
    if (!MyBrowser.#browser?.isConnected())
      MyBrowser.#browser = await puppeteer.launch({ args: ["--no-sandbox"] });
  }

  static async closeBrowser() {
    if (MyBrowser.#browser?.isConnected()) await MyBrowser.#browser.close();
  }
}

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

when I send 2 requests at the same time, I get the following error:

Error: Error: failed to find element matching selector "#userName" at ElementHandle.$eval

This error is occurring because the first request user has already logged in and the element is no longer present on the page for the second request.

So I want to make sure that if two or more users using the API, they each will have their own session.

I know that I could use another puppeteer.launch() but it may require a large amount of memory and I want to avoid that...

I have also tried to close the browser using MyBrowser.closeBrowser() before the end of the request, but I encountered this error when I tried to send two requests at the same time:

Error: Protocol error (Runtime.callFunctionOn): Session closed. Most likely the page has been closed. at CDPSessionImpl.send

It works fine if I wait some times before each request.

Body:
I am building an API that requires users to login in a website and I'm handling this with Puppeteer.

The problem here is when two users using the API at the same time (Or in the same browser session), I get an error saying that the user is already logged in and I think this happened because it is the same session.

Here is my current code:

import express from "express";
import puppeteer from "puppeteer";

const myRoutes = express.Router();

myRoutes.get("/login", async (request, response) => {
  const loginAuth = request.body;

  try {
    const browser = await MyBrowser.initialize();
    const page = await browser.newPage();

    await page.goto("https://website.com/login");
    await page.waitForNetworkIdle({ idleTime: 3000 });

    await page.$eval("#userName", (el, value) => (el.value = value), loginAuth.userName);
    await page.$eval("#password", (el, value) => (el.value = value), loginAuth.password);

    await page.$eval("#loginBtn", (el) => el.click());

    await page.$eval("#loginBtn", (el) => el.click());

    // MyBrowser.closeBrowser();
  } catch (err) {
    console.log("ERRORR OCCURED...");
    console.log(err);
  }

  response.end("No message");
});

class MyBrowser {
  static #browser;

  static async initialize() {
    if (!MyBrowser.#browser?.isConnected())
      MyBrowser.#browser = await puppeteer.launch({ args: ["--no-sandbox"] });
  }

  static async closeBrowser() {
    if (MyBrowser.#browser?.isConnected()) await MyBrowser.#browser.close();
  }
}

export { myRoutes };

when I send 2 requests at the same time, I get the following error:

Error: Error: failed to find element matching selector "#userName" at ElementHandle.$eval

This error is occurring because the first request user has already logged in and the element is no longer present on the page for the second request.

So I want to make sure that if two or more users using the API, they each will have their own session.

I know that I could use another puppeteer.launch() but it may require a large amount of memory and I want to avoid that...

I have also tried to close the browser using MyBrowser.closeBrowser() before the end of the request, but I encountered this error when I tried to send two requests at the same time:

Error: Protocol error (Runtime.callFunctionOn): Session closed. Most likely the page has been closed. at CDPSessionImpl.send

It works fine if I wait some times before each request.


问:
Trying to login with google credentials with Dash using dash_google_oauth.google_auth?
```<code>import os
import dash
from dash import html
from dash.dependencies import Input, Output

import google.auth
import googleapiclient.discovery

from dotenv import load_dotenv

load_dotenv()

# Set up the Dash app
app = dash.Dash(
    __name__,
    external_stylesheets=["https://codepen.io/chriddyp/pen/bWLwgP.css"],
)

from dash_google_oauth.google_auth import GoogleAuth
auth = GoogleAuth(app)

# Define the app layout
app.layout = html.Div([
    html.Button(id="button", children="Access Google Drive"),
    html.Div(id="output")
])

if __name__ == "__main__":
    app.run_server(debug=True)
</code>```

I created a google project and created a GOOGLE_AUTH_CLIENT_ID and GOOGLE_AUTH_CLIENT_SECRET. And stored in a .env file. The secrets are accessible via os.getenv(). When I start the  application I get this

screen.

Body:
import os
import dash
from dash import html
from dash.dependencies import Input, Output

import google.auth
import googleapiclient.discovery

from dotenv import load_dotenv

load_dotenv()

# Set up the Dash app
app = dash.Dash(
    __name__,
    external_stylesheets=["https://codepen.io/chriddyp/pen/bWLwgP.css"],
)

from dash_google_oauth.google_auth import GoogleAuth
auth = GoogleAuth(app)

# Define the app layout
app.layout = html.Div([
    html.Button(id="button", children="Access Google Drive"),
    html.Div(id="output")
])

if __name__ == "__main__":
    app.run_server(debug=True)

I created a google project and created a GOOGLE_AUTH_CLIENT_ID and GOOGLE_AUTH_CLIENT_SECRET. And stored in a .env file. The secrets are accessible via os.getenv(). When I start the  application I get this

screen.


问:
Navigation Buttons appears when I touch a spinner
I need help with this. I have a theme with:

```<code><style name="Theme.CuentameUnCuento" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">#4CAF50</item>
    <item name="colorPrimaryVariant">#388E3C</item>
    <item name="colorOnPrimary">@color/white</item>
    <!-- Secondary brand color. -->
    <item name="colorSecondary">#009688</item>
    <item name="colorSecondaryVariant">#00796B</item>
    <item name="colorOnSecondary">@color/white</item>
    <!-- Status bar color. -->
    <item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
    <!-- Customize your theme here. -->
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:fontFamily">@font/anna</item>
</style>
</code>```

Then I have, in the MainActivity.java, after the setContentView.

```<code>    View decorView = getWindow().getDecorView();
    int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN;
    decorView.setSystemUiVisibility(uiOptions);
</code>```

With all of this I can set the full screen mode in the app.

All seems to works fine, except when I touch a spinner adapter. Then the navigation buttons appears.
In the actitvity_main.xml the spinner:

```<code><Spinner
    android:id="@+id/sp_idioma_menu"
    style="@style/spinner_style"
    android:layout_width="80dp"
    android:layout_height="60dp"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="36dp"
    app:layout_constraintBottom_toTopOf="@+id/btn_salir"
    app:layout_constraintEnd_toEndOf="parent"
    android:stateListAnimator="@null"/>
</code>```

The styles.xml is:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="spinner_style">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@drawable/diseny_spinner</item>
        <item name="android:paddingLeft">8dp</item>
        <item name="android:paddingRight">20dp</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>
</resources>
</code>```

The diseny_spinner.xml is:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item><layer-list>
        <item><shape>
        </shape></item>
    </layer-list></item>
</selector>
</code>```

Images:
Screenshot when I touch the Spinner
Screenshot when Spinner is not opened

How can I solve this? Thanks

Body:
I need help with this. I have a theme with:

Then I have, in the MainActivity.java, after the setContentView.

    View decorView = getWindow().getDecorView();
    int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN;
    decorView.setSystemUiVisibility(uiOptions);

With all of this I can set the full screen mode in the app.

All seems to works fine, except when I touch a spinner adapter. Then the navigation buttons appears.
In the actitvity_main.xml the spinner:

<Spinner
    android:id="@+id/sp_idioma_menu"
    style="@style/spinner_style"
    android:layout_width="80dp"
    android:layout_height="60dp"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="36dp"
    app:layout_constraintBottom_toTopOf="@+id/btn_salir"
    app:layout_constraintEnd_toEndOf="parent"
    android:stateListAnimator="@null"/>

The styles.xml is:

<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>

The diseny_spinner.xml is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item><layer-list>
        <item><shape>
        </shape></item>
    </layer-list></item>
</selector>

Images:
Screenshot when I touch the Spinner
Screenshot when Spinner is not opened

How can I solve this? Thanks


问:
How can I make the image list wont appear again if it is used already?
what I will use to prevent the image from appearing again. I want the image won't reapeat appearing but don't know what can I use to do that.</p>
```<code>public ImageView imgViewQuestion;

int [] image_list = {

            R.drawable.forms,
            R.drawable.tags,
            R.drawable.tables,
            R.drawable.radiobutton,
            R.drawable.checkbox,
            R.drawable.font,
            R.drawable.anchors,
            R.drawable.html
    };

</code>```
```<code> private void setupList() {
        Random random = new Random();
        int imageSelected = image_list[random.nextInt(image_list.length)];
        imgViewQuestion.setImageResource(imageSelected);
        fourinfoassucommon.imageSelected = imageSelected;

        correct_answer = getResources().getResourceName(imageSelected);
        correct_answer = correct_answer.substring(correct_answer.lastIndexOf("/") + 1);

        answer = correct_answer.toCharArray();

        fourinfoassucommon.user_submit_answer = new char[answer.length];

        suggestSource.clear();
        for (char item : answer) {
            suggestSource.add(String.valueOf(item));

</code>```

Body:
what I will use to prevent the image from appearing again. I want the image won't reapeat appearing but don't know what can I use to do that.

public ImageView imgViewQuestion;

int [] image_list = {

            R.drawable.forms,
            R.drawable.tags,
            R.drawable.tables,
            R.drawable.radiobutton,
            R.drawable.checkbox,
            R.drawable.font,
            R.drawable.anchors,
            R.drawable.html
    };

 private void setupList() {
        Random random = new Random();
        int imageSelected = image_list[random.nextInt(image_list.length)];
        imgViewQuestion.setImageResource(imageSelected);
        fourinfoassucommon.imageSelected = imageSelected;

        correct_answer = getResources().getResourceName(imageSelected);
        correct_answer = correct_answer.substring(correct_answer.lastIndexOf("/") + 1);

        answer = correct_answer.toCharArray();

        fourinfoassucommon.user_submit_answer = new char[answer.length];

        suggestSource.clear();
        for (char item : answer) {
            suggestSource.add(String.valueOf(item));


问:
react-pagination hangs when requesting a server with react-query
When I click on a pagination element, for example: "2", then a class add to it, which changes the color to the active element. At this moment, braking is felt, and if, for example, you quickly switch between phenomena, then this is clearly noticeable. If you remove the TransactionLayout component, then the hang disappears.

Here I make a request to the server, I also add filters, page to the react-query dependency so that when the filters change, a new request to the server is made.

```<code>export default function TransactionPage() {
  const [limit, setLimit] = useState(10);
  const [filters, setFilters] = useState({ limit });

  const [page, setPage] = useState(1);
  const [cachedTotalPage, setTotalPage] = useState(0);
  const { data, isLoading, isError, error } =   useQuery(
    ['transactions', {...filters, page}],
    () => TransactionService.getAll({...filters, page}),

    {
      cacheTime: 60 * 60 * 1000,
      staleTime: 60 * 60 * 1000,
    }
  );

  const handlePage = (e) => {
    setPage(e.selected + 1);
  };

  useEffect(() => {
    if (data && data.count !== cachedTotalPage) {
      setTotalPage(Math.floor(data.count / limit));
    }
  }, [data, limit]);

  return (
      <Card py="20px">
        <TransactionFilters
          data={data}
          filters={filters}
          setFilters={setFilters}
          setLimit={setLimit}
          limit={limit}
        />
        <TransactionsLayout
          data={data}
          isLoading={isLoading}
          isError={isError}
          error={error}
        />

        <Box ml="20px">
       <ReactPaginate
      breakLabel="..."
      nextLabel="›"
      onPageChange={handlePage}
      pageRangeDisplayed={5}
      pageCount={cachedTotalPage}
      previousLabel="‹"
      renderOnZeroPageCount={false}
      containerClassName={styles.pagination__container}
      disabledClassName={styles.pagination__disabled}
      pageLinkClassName={styles.pagination__item}
      previousLinkClassName={styles.pagination__arrow}
      nextLinkClassName={styles.pagination__arrow}
      activeLinkClassName={styles['pagination__item--active']}
    />
        </Box>
      </Card>
  );
}
</code>```

With the current business logic, if you comment out TransactionLayout, then the hang disappears.
And I also decided to use a regular axios query instead of useQuery, which places the result in the data state, and these freezes disappear. This means the problem is in useQuery. Are there any solutions?

Body:
When I click on a pagination element, for example: "2", then a class add to it, which changes the color to the active element. At this moment, braking is felt, and if, for example, you quickly switch between phenomena, then this is clearly noticeable. If you remove the TransactionLayout component, then the hang disappears.

Here I make a request to the server, I also add filters, page to the react-query dependency so that when the filters change, a new request to the server is made.

export default function TransactionPage() {
  const [limit, setLimit] = useState(10);
  const [filters, setFilters] = useState({ limit });

  const [page, setPage] = useState(1);
  const [cachedTotalPage, setTotalPage] = useState(0);
  const { data, isLoading, isError, error } =   useQuery(
    ['transactions', {...filters, page}],
    () => TransactionService.getAll({...filters, page}),

    {
      cacheTime: 60 * 60 * 1000,
      staleTime: 60 * 60 * 1000,
    }
  );

  const handlePage = (e) => {
    setPage(e.selected + 1);
  };

  useEffect(() => {
    if (data && data.count !== cachedTotalPage) {
      setTotalPage(Math.floor(data.count / limit));
    }
  }, [data, limit]);

  return (
      <Card py="20px">
        <TransactionFilters
          data={data}
          filters={filters}
          setFilters={setFilters}
          setLimit={setLimit}
          limit={limit}
        />
        <TransactionsLayout
          data={data}
          isLoading={isLoading}
          isError={isError}
          error={error}
        />

        <Box ml="20px">
       <ReactPaginate
      breakLabel="..."
      nextLabel="›"
      onPageChange={handlePage}
      pageRangeDisplayed={5}
      pageCount={cachedTotalPage}
      previousLabel="‹"
      renderOnZeroPageCount={false}
      containerClassName={styles.pagination__container}
      disabledClassName={styles.pagination__disabled}
      pageLinkClassName={styles.pagination__item}
      previousLinkClassName={styles.pagination__arrow}
      nextLinkClassName={styles.pagination__arrow}
      activeLinkClassName={styles['pagination__item--active']}
    />
        </Box>
      </Card>
  );
}

With the current business logic, if you comment out TransactionLayout, then the hang disappears.
And I also decided to use a regular axios query instead of useQuery, which places the result in the data state, and these freezes disappear. This means the problem is in useQuery. Are there any solutions?


问:
Changing the variables in Rust
How can I change the variables (a and b) from the cycle?
The code shall take 2 variables (from input) and subtract one from another but it does not happen.</p>
```<code>let mut a: i32 = inputs[0].parse().unwrap();
let mut b: i32 = inputs[1].parse().unwrap();

let mut counter:i32 = 0;

while a >= 0 || b >= 0   {
    if  a > b {
        let a = a - b;
        counter +=1;
    }
    else if b > a {
        let b = b-a;
        counter +=1;
    }
    else {
        counter +=1;

    }
    println!("{counter}");
</code>```

Title: Changing the variables in Rust

Body:
How can I change the variables (a and b) from the cycle?
The code shall take 2 variables (from input) and subtract one from another but it does not happen.

let mut a: i32 = inputs[0].parse().unwrap();
let mut b: i32 = inputs[1].parse().unwrap();

let mut counter:i32 = 0;

while a >= 0 || b >= 0   {
    if  a > b {
        let a = a - b;
        counter +=1;
    }
    else if b > a {
        let b = b-a;
        counter +=1;
    }
    else {
        counter +=1;

    }
    println!("{counter}");


问:
cannot read properties of undefined (reading '1')at plugin.manipulateoptions
this react native app was working perfectly and a week or so ago it just start throwing this arror cannot read properties of undefined (reading '1')at plugin.manipulateoptions.
you can view more detail in the attached photo here error message

```<code>Here is my package json:

"dependencies": {
"@react-native-async-storage/async-storage": "^1.17.11",
"@react-navigation/bottom-tabs": "^6.5.1",
"@react-navigation/drawer": "^6.5.5",
"@react-navigation/native": "^6.1.1",
"@react-navigation/stack": "^6.3.9",
"dayjs": "^1.11.7",
"express": "^4.18.2",
"firebase": "^9.15.0",
"morgan": "^1.10.0",
"peerjs": "^1.4.7",
"react": "18.1.0",
"react-native": "^0.70.6",
"react-native-animatable": "^1.3.3",
"react-native-dotenv": "^3.4.7",
"react-native-event-listeners": "^1.0.7",
"react-native-gesture-handler": "^2.8.0",
"react-native-incall-manager": "^4.0.1",
"react-native-paper": "^5.0.2",
"react-native-reanimated": "^2.13.0",
"react-native-safe-area-context": "^4.4.1",
"react-native-screens": "^3.18.2",
"react-native-slider": "^0.11.0",
"react-native-track-player": "^3.2.0",
"react-native-vector-icons": "^9.2.0",
"react-native-webview": "^11.26.0",
"socket.io": "^4.5.4",
"socket.io-client": "^4.5.4"
"devDependencies": {
"@babel/core": "^7.12.9",
"@babel/preset-flow": "^7.0.0",
"@babel/runtime": "^7.20.7",
"@react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^29.3.1",
"babel-plugin-module-resolver": "^4.1.0",
"eslint": "^7.32.0",
"jest": "^26.6.3",
"metro": "^0.73.7",
"metro-core": "^0.73.7",
"metro-react-native-babel-preset": "^0.73.7",
"react-test-renderer": "18.1.0"
</code>```

},

I've tried uninstall nodemodule and packagelock, I even initialize another application, I upgraded babel plugins, but none of it works.

Body:
this react native app was working perfectly and a week or so ago it just start throwing this arror cannot read properties of undefined (reading '1')at plugin.manipulateoptions.
you can view more detail in the attached photo here error message

Here is my package json:

"dependencies": {
"@react-native-async-storage/async-storage": "^1.17.11",
"@react-navigation/bottom-tabs": "^6.5.1",
"@react-navigation/drawer": "^6.5.5",
"@react-navigation/native": "^6.1.1",
"@react-navigation/stack": "^6.3.9",
"dayjs": "^1.11.7",
"express": "^4.18.2",
"firebase": "^9.15.0",
"morgan": "^1.10.0",
"peerjs": "^1.4.7",
"react": "18.1.0",
"react-native": "^0.70.6",
"react-native-animatable": "^1.3.3",
"react-native-dotenv": "^3.4.7",
"react-native-event-listeners": "^1.0.7",
"react-native-gesture-handler": "^2.8.0",
"react-native-incall-manager": "^4.0.1",
"react-native-paper": "^5.0.2",
"react-native-reanimated": "^2.13.0",
"react-native-safe-area-context": "^4.4.1",
"react-native-screens": "^3.18.2",
"react-native-slider": "^0.11.0",
"react-native-track-player": "^3.2.0",
"react-native-vector-icons": "^9.2.0",
"react-native-webview": "^11.26.0",
"socket.io": "^4.5.4",
"socket.io-client": "^4.5.4"
"devDependencies": {
"@babel/core": "^7.12.9",
"@babel/preset-flow": "^7.0.0",
"@babel/runtime": "^7.20.7",
"@react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^29.3.1",
"babel-plugin-module-resolver": "^4.1.0",
"eslint": "^7.32.0",
"jest": "^26.6.3",
"metro": "^0.73.7",
"metro-core": "^0.73.7",
"metro-react-native-babel-preset": "^0.73.7",
"react-test-renderer": "18.1.0"

},

I've tried uninstall nodemodule and packagelock, I even initialize another application, I upgraded babel plugins, but none of it works.


问:
How do I attach a pdf file to my whatsapp desktop app on process start? (C# and WA desktop app)
Writing a local WinForm app that will run on a single pc. The App creates a Document, converts to PDF, and then the invoice (generated pdf) has to be sent to the client using the desktop version of Whatsapp. I am not going for API as I am making the software for free.

private void btnAMFormPrintPDF_Click(object sender, EventArgs e)
{

```<code>        //Custom class DPFController creates pdf document called doc
        PDFController control = new PDFController(dtable);
        Document  doc = control.CreateDocument();

        //render the document to pdf
        PdfDocumentRenderer render = new PdfDocumentRenderer();
        render.Document = doc;
        render.RenderDocument();

        //name the pdf
        string openPDF = "PreviewPDF.pdf";

        //save the pdf to the directory
        string fileName =   Convert.ToString(Path.GetDirectoryName
        (System.Reflection.Assembly.GetExecutingAssembly().Location))
                + "\\PDF\\"+ openPDF;
        render.PdfDocument.Save(fileName);

        //open the pdf in adobe
       // Process.Start(openPDF);

        //THIS IS THE PROBLEMATIC LINE!!!

        var process = $"whatsapp://send?phone={0616589} &attachment={fileName}";
        Process.Start(process);

    }
</code>```

that is what I am trying to use and tried some variations therof, but to no avail:

var process = $"whatsapp://send?phone={0616589} &attachment={fileName}";

Body:
Writing a local WinForm app that will run on a single pc. The App creates a Document, converts to PDF, and then the invoice (generated pdf) has to be sent to the client using the desktop version of Whatsapp. I am not going for API as I am making the software for free.

private void btnAMFormPrintPDF_Click(object sender, EventArgs e)
{

        //Custom class DPFController creates pdf document called doc
        PDFController control = new PDFController(dtable);
        Document  doc = control.CreateDocument();

        //render the document to pdf
        PdfDocumentRenderer render = new PdfDocumentRenderer();
        render.Document = doc;
        render.RenderDocument();

        //name the pdf
        string openPDF = "PreviewPDF.pdf";

        //save the pdf to the directory
        string fileName =   Convert.ToString(Path.GetDirectoryName
        (System.Reflection.Assembly.GetExecutingAssembly().Location))
                + "\\PDF\\"+ openPDF;
        render.PdfDocument.Save(fileName);

        //open the pdf in adobe
       // Process.Start(openPDF);

        //THIS IS THE PROBLEMATIC LINE!!!

        var process = $"whatsapp://send?phone={0616589} &attachment={fileName}";
        Process.Start(process);

    }

that is what I am trying to use and tried some variations therof, but to no avail:

var process = $"whatsapp://send?phone={0616589} &attachment={fileName}";


问:
getting null pointer exception java.lang.Class java.lang.Object.getClass()
I implemented Direction API in my app it works perfectly on debug build but getting crash on release build I think it is because of proguard rules what rule I want to add in proguard to resolve this issue.</p>
```<code>private void getDirections() {
            DirectionsResult result = getDirectionsDetails("place_id:" + pickupPlaceID, "place_id:" + dropPlaceID, TravelMode.DRIVING);
            if (result != null) {
                addPolyline(result);
                positionCamera(result.routes[0]);
            }
    }

private DirectionsResult getDirectionsDetails(String origin, String destination, TravelMode mode) {
            return DirectionsApi.newRequest(geoApiContext).mode(mode).origin(origin).destination(destination).await();

    }
private void addPolyline(DirectionsResult results) {

                try {

                    DirectionsRoute[] routes = results.routes;
                    DirectionsRoute route = routes[0];
                    EncodedPolyline overviewPolyline = route.overviewPolyline; //getting error here
                    String encodedPath = overviewPolyline.getEncodedPath();
                    List<LatLng> decodedPath = PolyUtil.decode(encodedPath);
                    nGoogleMap.addPolyline(new PolylineOptions().addAll(decodedPath));
                }catch (Exception e){
                    e.printStackTrace();
                }

    }
</code>```
```<code>java.lang.NullPointerException:
Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
System.err com.example.newapp at com.example.newapp.ui.home.HomeFragment.lambda$addPolyline$30(HomeFragment.java:1110)
</code>```

Body:
I implemented Direction API in my app it works perfectly on debug build but getting crash on release build I think it is because of proguard rules what rule I want to add in proguard to resolve this issue.

private void getDirections() {
            DirectionsResult result = getDirectionsDetails("place_id:" + pickupPlaceID, "place_id:" + dropPlaceID, TravelMode.DRIVING);
            if (result != null) {
                addPolyline(result);
                positionCamera(result.routes[0]);
            }
    }

private DirectionsResult getDirectionsDetails(String origin, String destination, TravelMode mode) {
            return DirectionsApi.newRequest(geoApiContext).mode(mode).origin(origin).destination(destination).await();

    }
private void addPolyline(DirectionsResult results) {

                try {

                    DirectionsRoute[] routes = results.routes;
                    DirectionsRoute route = routes[0];
                    EncodedPolyline overviewPolyline = route.overviewPolyline; //getting error here
                    String encodedPath = overviewPolyline.getEncodedPath();
                    List<LatLng> decodedPath = PolyUtil.decode(encodedPath);
                    nGoogleMap.addPolyline(new PolylineOptions().addAll(decodedPath));
                }catch (Exception e){
                    e.printStackTrace();
                }

    }

java.lang.NullPointerException:
Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
System.err com.example.newapp at com.example.newapp.ui.home.HomeFragment.lambda$addPolyline$30(HomeFragment.java:1110)


问:
Something is wrong with my GLSL shader for Minecraft
While i was making my shader for minecraft ive run into a problem

```<code>0(13) : error C0000: syntax error, unexpected ';', expecting '{' at token ";"
0(14) : error C0000: syntax error, unexpected ';', expecting '{' at token ";"
0(18) : error C1503: undefined variable "gbufferModelView"
0(18) : error C1503: undefined variable "gbufferProjection"
[16:24:00] [Client thread/ERROR] [net.optifine.shaders.SMCLog]: [Shaders] Error linking program: 20 (gbuffers_terrain
[16:24:00] [Client thread/INFO] [net.optifine.shaders.SMCLog]: [Shaders] Info log: gbuffers_terrain
Vertex info
0(13) : error C0000: syntax error, unexpected ';', expecting '{' at token ";"
0(14) : error C0000: syntax error, unexpected ';', expecting '{' at token ";"
0(18) : error C1503: undefined variable "gbufferModelView"
0(18) : error C1503: undefined variable "gbufferProjection"
(0) : error C2003: incompatible options for link
[16:24:00] [Client thread/ERROR] [net.optifine.shaders.SMCLog]: [Shaders] OpenGL error: 1282 (Invalid operation), program: gbuffers_terrain, at: useProgram
[16:24:00] [Client thread/INFO] [minecraft/GuiNewChat]: [CHAT] �eOpenGL Error�f: 1282 (Invalid operation)
[16:24:00] [Client thread/ERROR] [net.optifine.shaders.SMCLog]: [Shaders] [Shaders] Error: Invalid program "gbuffers_terrain"
[16:24:00] [Client thread/INFO] [minecraft/GuiNewChat]: [CHAT] [Shaders] Error: Invalid program "gbuffers_terrain"
[16:24:00] [Client thread/INFO] [net.optifine.shaders.SMCLog]: [Shaders] Shader info log: /shaders/gbuffers_block.fsh
0(13) : warning C7533: global variable gl_FragData is deprecated after version 120
Fragment info

#version 460
#define lightBlocks
#define intensity 1 //[0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0]
#define BlocksOfLight 20 //[1 5 10 15 20 25 30 40 50 60 70 80 90 100 120 140 150 170 190 200]
layout(location = 0) in vec3 p;
int Num = 0;
//uniform sampler2D texture;
out vec4 color;
out vec4 texcoord;
out vec4 lmcoord;
uniform gbufferModelView;
uniform gbufferProjection;
void main() {
    gl_Position = gbufferModelView * gbufferProjection * p;
    color = vec4(1.0f,0.5f,1.0f,1.0f);
}

#version 120
uniform sampler2D texture;
uniform int worldTime;
float fac = 1.0f-abs(sin((worldTime/24000.0f)*3.14159f+3.14159f/4.0f));
in vec4 color;
in vec4 texcoord;
in vec4 lmcoord;
vec4 tex = texture2D(texture, texcoord.st);
vec3 colD = vec3(1.0f);
vec3 colN = vec3(0.0f,0.0f,0.5f);
vec3 light = (colD+(fac)*colN)/(fac+1.0f);
void main()
{
    gl_FragColor = vec4(tex.r*color.r*(lmcoord.s+light.r),tex.g*color.g*(lmcoord.s+light.g),tex.b*color.b*(lmcoord.s+light.b),tex.a);
}

</code>```

1st - Vertex 2nd - Fragment

Once, ive got wrong rendering of all blocks (all blocks in one single chunk somehow...), but then gbufferModelView and gbufferProjection stopped their work at all. Im on Minecraft 1.12.2

Body:
While i was making my shader for minecraft ive run into a problem

0(13) : error C0000: syntax error, unexpected ';', expecting '{' at token ";"
0(14) : error C0000: syntax error, unexpected ';', expecting '{' at token ";"
0(18) : error C1503: undefined variable "gbufferModelView"
0(18) : error C1503: undefined variable "gbufferProjection"
[16:24:00] [Client thread/ERROR] [net.optifine.shaders.SMCLog]: [Shaders] Error linking program: 20 (gbuffers_terrain
[16:24:00] [Client thread/INFO] [net.optifine.shaders.SMCLog]: [Shaders] Info log: gbuffers_terrain
Vertex info
0(13) : error C0000: syntax error, unexpected ';', expecting '{' at token ";"
0(14) : error C0000: syntax error, unexpected ';', expecting '{' at token ";"
0(18) : error C1503: undefined variable "gbufferModelView"
0(18) : error C1503: undefined variable "gbufferProjection"
(0) : error C2003: incompatible options for link
[16:24:00] [Client thread/ERROR] [net.optifine.shaders.SMCLog]: [Shaders] OpenGL error: 1282 (Invalid operation), program: gbuffers_terrain, at: useProgram
[16:24:00] [Client thread/INFO] [minecraft/GuiNewChat]: [CHAT] �eOpenGL Error�f: 1282 (Invalid operation)
[16:24:00] [Client thread/ERROR] [net.optifine.shaders.SMCLog]: [Shaders] [Shaders] Error: Invalid program "gbuffers_terrain"
[16:24:00] [Client thread/INFO] [minecraft/GuiNewChat]: [CHAT] [Shaders] Error: Invalid program "gbuffers_terrain"
[16:24:00] [Client thread/INFO] [net.optifine.shaders.SMCLog]: [Shaders] Shader info log: /shaders/gbuffers_block.fsh
0(13) : warning C7533: global variable gl_FragData is deprecated after version 120
Fragment info

#version 460
#define lightBlocks
#define intensity 1 //[0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0]
#define BlocksOfLight 20 //[1 5 10 15 20 25 30 40 50 60 70 80 90 100 120 140 150 170 190 200]
layout(location = 0) in vec3 p;
int Num = 0;
//uniform sampler2D texture;
out vec4 color;
out vec4 texcoord;
out vec4 lmcoord;
uniform gbufferModelView;
uniform gbufferProjection;
void main() {
    gl_Position = gbufferModelView * gbufferProjection * p;
    color = vec4(1.0f,0.5f,1.0f,1.0f);
}

#version 120
uniform sampler2D texture;
uniform int worldTime;
float fac = 1.0f-abs(sin((worldTime/24000.0f)*3.14159f+3.14159f/4.0f));
in vec4 color;
in vec4 texcoord;
in vec4 lmcoord;
vec4 tex = texture2D(texture, texcoord.st);
vec3 colD = vec3(1.0f);
vec3 colN = vec3(0.0f,0.0f,0.5f);
vec3 light = (colD+(fac)*colN)/(fac+1.0f);
void main()
{
    gl_FragColor = vec4(tex.r*color.r*(lmcoord.s+light.r),tex.g*color.g*(lmcoord.s+light.g),tex.b*color.b*(lmcoord.s+light.b),tex.a);
}

1st - Vertex 2nd - Fragment

Once, ive got wrong rendering of all blocks (all blocks in one single chunk somehow...), but then gbufferModelView and gbufferProjection stopped their work at all. Im on Minecraft 1.12.2


问:
Pyhon how to get Desktop Audio
Do you know an way to get the real time desktop audio using Python on Linux, or only the Audio from an specific Application or Game?

I have only found methods that work on Windows or where saving the output in an file, Not streaming them in real time.

Title: Pyhon how to get Desktop Audio


问:
Memory Usage in Jupyter Notebook
On the top right hand corner of my Jupyter Notebook, it is showing only the memory in use without showing all that is avaialable.  How can I fix this?

And then how do I increase the Jupyter memory limit?

I have tried editing the config.py file but I cannot find the line to edit

Title: Memory Usage in Jupyter Notebook


问:
How to get the language from toggle?
I want do create a multilanguage site (English and German). The toggle works but I don't know how to get the language in order to select the language and to show the words in the right language.

How can I get the value of the toggle (if posible using PHP and not Javascript)?
Thanks in advance for any help.

```<code>--------------------------------
<!DOCTYPE HTML>
<html lang="de" html>

 <head>
    <link rel="stylesheet" href="style.css">
 </head>
 <body>
    <div class="switch">
        <input id="language-toggle" class="check-toggle check-toggle-round-flat" type="checkbox">
        <label for="language-toggle"></label>
        <span id="de" class="on">DE</span>
        <span id="en" class="off">EN</span>
    </div>
   <?php
       $lang = "en";
       require_once("Language/lang.".$lang.".php");
   ?>
    <p style="font-size:30px;"><?php echo $language["text1"]; ?></p>
 </body>
</html>

</code>```
```<code>---------------lang.de.php-------------------

<?php
$language['text1'] = 'Willkommen';
?>

</code>```
```<code>---------------lang.en.php-------------------

<?php
$language['text1'] = 'Welcome';
?>
</code>```
```<code>
---------------------style.css-----------------------

  .switch {
    position: relative;
    display: inline-block;
    margin: -4px 0px;
    line-height:45px;
  }

  .switch > span {
    position: absolute;
    top: 0px;
    pointer-events: none;
    font-family: 'Helvetica', Arial, sans-serif;
    font-weight: bold;
    font-size: 12px;
    text-transform: uppercase;
    text-shadow: 0 1px 0 rgba(0, 0, 0, .06);
    width: 50%;
    line-height:45px;
    text-align: center;
  }

  input.check-toggle-round-flat:checked ~ .off {
    color: #333;
  }

  input.check-toggle-round-flat:checked ~ .on {
    color: #fff;
  }

  .switch > span.on {
    left: 0;
    padding-left: 2px;
    color: #333;
  }

  .switch > span.off {
    right: 0;
    padding-right: 4px;
    color: #fff;
  }

  .check-toggle {
    position: absolute;
    margin-left: -9999px;
    visibility: hidden;
  }
  .check-toggle + label {
    display: block;
    position: relative;
    cursor: pointer;
    outline: none;
    -webkit-user-select: none;
      -moz-user-select: none;
        -ms-user-select: none;
          user-select: none;
  }

  input.check-toggle-round-flat + label {
    padding: 2px;
    width: 97px;
    height: 35px;
    background-color: #333;
    -webkit-border-radius: 60px;
       -moz-border-radius: 60px;
          -ms-border-radius: 60px;
            -o-border-radius: 60px;
              border-radius: 60px;
  }
  input.check-toggle-round-flat + label:before, input.check-toggle-round-flat + label:after {
    display: block;
    position: absolute;
    content: "";
  }

  input.check-toggle-round-flat + label:before {
    top: 2px;
    left: 2px;
    bottom: 2px;
    right: 2px;
    background-color: #333;
    -webkit-moz-border-radius: 60px;
      -ms-border-radius: 60px;
        -o-border-radius: 60px;
          border-radius: 60px;
  }
  input.check-toggle-round-flat + label:after {
    top: 4px;
    left: 4px;
    bottom: 4px;
    width: 48px;
    background-color: #fff;
    -webkit-border-radius: 52px;
      -moz-border-radius: 52px;
        -ms-border-radius: 52px;
          -o-border-radius: 52px;
             border-radius: 52px;
    -webkit-transition: margin 0.2s;
      -moz-transition: margin 0.2s;
        -o-transition: margin 0.2s;
          transition: margin 0.2s;
  }

  input.check-toggle-round-flat:checked + label {
  }

  input.check-toggle-round-flat:checked + label:after {
    margin-left: 44px;
  }

</code>```

Title: How to get the language from toggle?

Body:
I want do create a multilanguage site (English and German). The toggle works but I don't know how to get the language in order to select the language and to show the words in the right language.

How can I get the value of the toggle (if posible using PHP and not Javascript)?
Thanks in advance for any help.

--------------------------------
<!DOCTYPE HTML>

    <link rel="stylesheet" href="style.css">

        <input id="language-toggle" class="check-toggle check-toggle-round-flat" type="checkbox">

        DE
        EN

   <?php
       $lang = "en";
       require_once("Language/lang.".$lang.".php");
   ?>

<?php echo $language["text1"]; ?>

---------------lang.de.php-------------------

<?php
$language['text1'] = 'Willkommen';
?>

---------------lang.en.php-------------------

<?php
$language['text1'] = 'Welcome';
?>

---------------------style.css-----------------------

  .switch {
    position: relative;
    display: inline-block;
    margin: -4px 0px;
    line-height:45px;
  }

  .switch > span {
    position: absolute;
    top: 0px;
    pointer-events: none;
    font-family: 'Helvetica', Arial, sans-serif;
    font-weight: bold;
    font-size: 12px;
    text-transform: uppercase;
    text-shadow: 0 1px 0 rgba(0, 0, 0, .06);
    width: 50%;
    line-height:45px;
    text-align: center;
  }

  input.check-toggle-round-flat:checked ~ .off {
    color: #333;
  }

  input.check-toggle-round-flat:checked ~ .on {
    color: #fff;
  }

  .switch > span.on {
    left: 0;
    padding-left: 2px;
    color: #333;
  }

  .switch > span.off {
    right: 0;
    padding-right: 4px;
    color: #fff;
  }

  .check-toggle {
    position: absolute;
    margin-left: -9999px;
    visibility: hidden;
  }
  .check-toggle + label {
    display: block;
    position: relative;
    cursor: pointer;
    outline: none;
    -webkit-user-select: none;
      -moz-user-select: none;
        -ms-user-select: none;
          user-select: none;
  }

  input.check-toggle-round-flat + label {
    padding: 2px;
    width: 97px;
    height: 35px;
    background-color: #333;
    -webkit-border-radius: 60px;
       -moz-border-radius: 60px;
          -ms-border-radius: 60px;
            -o-border-radius: 60px;
              border-radius: 60px;
  }
  input.check-toggle-round-flat + label:before, input.check-toggle-round-flat + label:after {
    display: block;
    position: absolute;
    content: "";
  }

  input.check-toggle-round-flat + label:before {
    top: 2px;
    left: 2px;
    bottom: 2px;
    right: 2px;
    background-color: #333;
    -webkit-moz-border-radius: 60px;
      -ms-border-radius: 60px;
        -o-border-radius: 60px;
          border-radius: 60px;
  }
  input.check-toggle-round-flat + label:after {
    top: 4px;
    left: 4px;
    bottom: 4px;
    width: 48px;
    background-color: #fff;
    -webkit-border-radius: 52px;
      -moz-border-radius: 52px;
        -ms-border-radius: 52px;
          -o-border-radius: 52px;
             border-radius: 52px;
    -webkit-transition: margin 0.2s;
      -moz-transition: margin 0.2s;
        -o-transition: margin 0.2s;
          transition: margin 0.2s;
  }

  input.check-toggle-round-flat:checked + label {
  }

  input.check-toggle-round-flat:checked + label:after {
    margin-left: 44px;
  }


问:
How to create gradient blur in HTML & CSS?
I have Layout.js which has Navigationbar inside navigation bar is just unordered list of list items

```<code>function Layout(props) {
    return <div>
        <NavigationBar />
        <main className={classes.main}>
            {props.children}
        </main>
    </div>
}
</code>```

navbar.module.css is

.container {
    position: fixed;
    top: 0px;
    ..
    background: linear-gradient(rgba(37, 47, 81, 0.6),rgba(37, 47, 81, 0));
    backdrop-filter: blur(3px);
    ..

}
```

I want backdrop-filter: blur to be linear gradient as color because now it's just line where its starts to blur. Can someone help me easily fix this?

I tried webkit but it write warning that it is not supported by browsers.

Body:
I have Layout.js which has Navigationbar inside navigation bar is just unordered list of list items

function Layout(props) {
    return

        <NavigationBar />

            {props.children}

}

navbar.module.css is

.container {
    position: fixed;
    top: 0px;
    ..
    background: linear-gradient(rgba(37, 47, 81, 0.6),rgba(37, 47, 81, 0));
    backdrop-filter: blur(3px);
    ..

}

I want backdrop-filter: blur to be linear gradient as color because now it's just line where its starts to blur. Can someone help me easily fix this?

I tried webkit but it write warning that it is not supported by browsers.


问:
Moving existing mamba/conda environments to micromamba
I want to migrate all my existing environments to micromamba on my Mac (i.e., move my envs to /Users/UserName/micromamba/envs/) to use micromamba exclusively. What's the best way to move my existing environments?

I'm not sure where to begin with this - not sure if simply copying/pasting my existing environments would work and don't want to break them accidentally.


问:
Manipulating closure scoped dom element inside promise callback
I am writing a Chrome extension to modify site contents.
I am fetching some data from a backend API through the background script and then updating the website contents to reflect that data.
Initially, I was confused that after modifying the elements' innerHTML the change wasn't reflected in the page.
After some debugging I found out element.isConnected is false inside the callback function.
Now, I'm unable to figure out a way to fix this and update the DOM elements.
The basic outline is that I'm reading rows of data from a table and for each row I'm reading the cell contents and updating cell contents after the API returns. Each row of the table is stored as an element of an array and is operated on by a map function.

Here is my relevant code:

```<code>let tableRows = document.querySelectorAll(".tablerow");
let tableRowsArray = Array.from(tableRows);
tableRowsArray.map(function (row) {
  let tableCells = row.innerHTML.split("</td>");
  (async () => {
    console.log(row.isconnected);                         //returns true here
    const response = await chrome.runtime.sendMessage(/*{some data}*/);
    let fetcheda = response.a;
    tableCells.splice(12, 0, "<td><output>" + fetcheda + "</output></td>");
    console.log(row.isConnected);                         //returns false here
    row.innerHTML = tableCells.join("");
    console.log(row);                                     //the correct row is modified correctly but does not reflect in the page
  })();
});
</code>```

I tried .then() for the promise instead of await and the problem remains. I also replace chrome.runtime.sendMessage() with a timeout promise and the problem remains the same.
Here is the code using .then():

```<code>let tableRows = document.querySelectorAll(".tablerow");
let tableRowsArray = Array.from(tableRows);
tableRowsArray.map(function (row) {
  let tableCells = row.innerHTML.split("</td>");
  console.log(row.isconnected);                           //returns true here
  chrome.runtime.sendMessage(/*{some data}*/).then((response) => {
    let fetcheda = response.a;
    tableCells.splice(12, 0, "<td><output>" + fetcheda + "</output></td>");
    console.log(row.isConnected);                         //returns false here
    row.innerHTML = tableCells.join("");
    console.log(row);                                     //the correct row is modified correctly but does not reflect in the page
  })
});
</code>```

I believe that somehow some properties of the row variable are stripped inside the .then() callback as row now becomes closure scoped instead of local scoped. I would like to know some way to be able to modify the DOM inside the .then() callback. And I also cannot simply get the respective row again  for which the API request was made.

Body:
I am writing a Chrome extension to modify site contents.
I am fetching some data from a backend API through the background script and then updating the website contents to reflect that data.
Initially, I was confused that after modifying the elements' innerHTML the change wasn't reflected in the page.
After some debugging I found out element.isConnected is false inside the callback function.
Now, I'm unable to figure out a way to fix this and update the DOM elements.
The basic outline is that I'm reading rows of data from a table and for each row I'm reading the cell contents and updating cell contents after the API returns. Each row of the table is stored as an element of an array and is operated on by a map function.

Here is my relevant code:

let tableRows = document.querySelectorAll(".tablerow");
let tableRowsArray = Array.from(tableRows);
tableRowsArray.map(function (row) {
  let tableCells = row.innerHTML.split("	");
  (async () => {
    console.log(row.isconnected);                         //returns true here
    const response = await chrome.runtime.sendMessage(/*{some data}*/);
    let fetcheda = response.a;
    tableCells.splice(12, 0, "<output>" + fetcheda + "</output>	");
    console.log(row.isConnected);                         //returns false here
    row.innerHTML = tableCells.join("");
    console.log(row);                                     //the correct row is modified correctly but does not reflect in the page
  })();
});

I tried .then() for the promise instead of await and the problem remains. I also replace chrome.runtime.sendMessage() with a timeout promise and the problem remains the same.
Here is the code using .then():

let tableRows = document.querySelectorAll(".tablerow");
let tableRowsArray = Array.from(tableRows);
tableRowsArray.map(function (row) {
  let tableCells = row.innerHTML.split("	");
  console.log(row.isconnected);                           //returns true here
  chrome.runtime.sendMessage(/*{some data}*/).then((response) => {
    let fetcheda = response.a;
    tableCells.splice(12, 0, "<output>" + fetcheda + "</output>	");
    console.log(row.isConnected);                         //returns false here
    row.innerHTML = tableCells.join("");
    console.log(row);                                     //the correct row is modified correctly but does not reflect in the page
  })
});

I believe that somehow some properties of the row variable are stripped inside the .then() callback as row now becomes closure scoped instead of local scoped. I would like to know some way to be able to modify the DOM inside the .then() callback. And I also cannot simply get the respective row again  for which the API request was made.


问:
TypeError: tf__test_function() missing 1 required positional argument: 'steps_per_execution'
I don't know whats going really going on here, I want it to print (answer) but stopped prematurely. https://colab.research.google.com/drive/1hvHkDusyqEsdZg5ZRVhhriZrDagpFdU6?usp=sharing

```<code>import os
import warnings
from zipfile import ZipFile
import random
from shutil import copyfile
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.image import imread
import pathlib
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten,
Dense, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import pandas as pd
import numpy as np
!pip install keras --upgrade
from keras_preprocessing.image import load_img, img_to_array

os.environ['KAGGLE_USERNAME'] = 'keneannooks'
os.environ['KAGGLE_KEY'] = "7e6dbd3a834880bc798dfe3d8c25b06e"
!kaggle datasets download -d shubhamgoel27/dermnet

file_name = "/content/dermnet.zip"
with ZipFile(file_name,'r') as zip:
zip.extractall()

model = Sequential([
 Conv2D(16, (3, 3), activation='relu', input_shape=(img_height,
 img_width, 3)), MaxPooling2D(2, 2),
 Conv2D(32, (3, 3), activation='relu'), MaxPooling2D(2,2),
 Conv2D(64, (3, 3), activation='relu'),
 Conv2D(64, (3, 3), activation='relu'),
 MaxPooling2D(2, 2),
 Conv2D(128, (3, 3), activation='relu'),
 Conv2D(128, (3, 3), activation='relu'),
 MaxPooling2D(2, 2),
 Conv2D(256, (3, 3), activation='relu'),
 Conv2D(256, (3, 3), activation='relu'),
 Conv2D(256, (3, 3), activation='relu'),
 MaxPooling2D(2, 2),
 Flatten(),
 Dense(512, activation='relu'),
 Dense(512, activation='relu'),
 Dense(11, activation='softmax')
 ])
 model.summary()

 # Read Test Images Dir and their labels
 test_images_dir = '/content/Picture_Test/'
 test_df = pd.read_csv('/content/skin-picture_test.csv')

 # put them in a list
 test_dfToList = test_df['Image_id'].tolist()
 test_ids = [str(item) for item in test_dfToList]

 test_images = [test_images_dir+item for item in test_ids]
 test_preprocessed_images = np.vstack([preprocess_image(fn) for fn in
 test_images])
 np.save('/content/test_preproc_CNN.npy', test_preprocessed_images)

 array = model.predict(test_preprocessed_images, batch_size=1,
 verbose=1)
 answer = np.argmax(array, axis=1)
 print(answer)
</code>```

I get:

            TypeError                                 Traceback (most recent call last)
                <ipython-input-39-d8f7c0dd70e9> in <module>
                ----> 1 array = model.predict(test_preprocessed_images, batch_size=1, verbose=1)
                      2 answer = np.argmax(array, axis=1)
                      3 print(answer)

                1 frames
                /usr/local/lib/python3.8/dist-packages/tensorflow/python/autograph/impl/api.py in converted_call(f, args, kwargs, caller_fn_scope, options)
                    437     try:
                    438       if kwargs is not None:
                --> 439         result = converted_f(*effective_args, **kwargs)
                    440       else:
                    441         result = converted_f(*effective_args)

                TypeError: in user code:

                    TypeError: tf__test_function() missing 1 required positional argument: 'steps_per_execution'
```

I think something may be wrong with my model or something since its "missing 1 required positional argument: 'steps_per_execution' ". Trying to get it to run but it looks like its not my day.

Body:
I don't know whats going really going on here, I want it to print (answer) but stopped prematurely. https://colab.research.google.com/drive/1hvHkDusyqEsdZg5ZRVhhriZrDagpFdU6?usp=sharing

import os
import warnings
from zipfile import ZipFile
import random
from shutil import copyfile
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.image import imread
import pathlib
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten,
Dense, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import pandas as pd
import numpy as np
!pip install keras --upgrade
from keras_preprocessing.image import load_img, img_to_array

os.environ['KAGGLE_USERNAME'] = 'keneannooks'
os.environ['KAGGLE_KEY'] = "7e6dbd3a834880bc798dfe3d8c25b06e"
!kaggle datasets download -d shubhamgoel27/dermnet

file_name = "/content/dermnet.zip"
with ZipFile(file_name,'r') as zip:
zip.extractall()

model = Sequential([
 Conv2D(16, (3, 3), activation='relu', input_shape=(img_height,
 img_width, 3)), MaxPooling2D(2, 2),
 Conv2D(32, (3, 3), activation='relu'), MaxPooling2D(2,2),
 Conv2D(64, (3, 3), activation='relu'),
 Conv2D(64, (3, 3), activation='relu'),
 MaxPooling2D(2, 2),
 Conv2D(128, (3, 3), activation='relu'),
 Conv2D(128, (3, 3), activation='relu'),
 MaxPooling2D(2, 2),
 Conv2D(256, (3, 3), activation='relu'),
 Conv2D(256, (3, 3), activation='relu'),
 Conv2D(256, (3, 3), activation='relu'),
 MaxPooling2D(2, 2),
 Flatten(),
 Dense(512, activation='relu'),
 Dense(512, activation='relu'),
 Dense(11, activation='softmax')
 ])
 model.summary()

 # Read Test Images Dir and their labels
 test_images_dir = '/content/Picture_Test/'
 test_df = pd.read_csv('/content/skin-picture_test.csv')

 # put them in a list
 test_dfToList = test_df['Image_id'].tolist()
 test_ids = [str(item) for item in test_dfToList]

 test_images = [test_images_dir+item for item in test_ids]
 test_preprocessed_images = np.vstack([preprocess_image(fn) for fn in
 test_images])
 np.save('/content/test_preproc_CNN.npy', test_preprocessed_images)

 array = model.predict(test_preprocessed_images, batch_size=1,
 verbose=1)
 answer = np.argmax(array, axis=1)
 print(answer)

I get:

            TypeError                                 Traceback (most recent call last)
                <ipython-input-39-d8f7c0dd70e9> in <module>
                ----> 1 array = model.predict(test_preprocessed_images, batch_size=1, verbose=1)
                      2 answer = np.argmax(array, axis=1)
                      3 print(answer)

                1 frames
                /usr/local/lib/python3.8/dist-packages/tensorflow/python/autograph/impl/api.py in converted_call(f, args, kwargs, caller_fn_scope, options)
                    437     try:
                    438       if kwargs is not None:
                --> 439         result = converted_f(*effective_args, **kwargs)
                    440       else:
                    441         result = converted_f(*effective_args)

                TypeError: in user code:

                    TypeError: tf__test_function() missing 1 required positional argument: 'steps_per_execution'

I think something may be wrong with my model or something since its "missing 1 required positional argument: 'steps_per_execution' ". Trying to get it to run but it looks like its not my day.


问:
Vue APP When IDM Grab the PDF file get an error
I have a button and then when user Click on it on Chrome the PDF file download automatically with Chrome Download Manager without any problem.

When I Installed Internet Download Manager and Click on Button, IDM handle the download and download it completely but I get an error on Vue app. (PDF download completely and healthy by IDM but the vue app show an unexpected error).

```<code><a ref="printElement" download />

const file = new Blob([result.data], { type: 'application/pdf' });

const fileURL = URL.createObjectURL(file);

printElement.setAttribute('href', ${fileURL as string});

nextTick();

printElement.click();

responseEncoding: 'arraybuffer',

responseType: 'arraybuffer',
</code>```

enter image description here

I mentioned again that with this error PDF downloaded completely and healthy. How I can fix this error?

Body:
I have a button and then when user Click on it on Chrome the PDF file download automatically with Chrome Download Manager without any problem.

When I Installed Internet Download Manager and Click on Button, IDM handle the download and download it completely but I get an error on Vue app. (PDF download completely and healthy by IDM but the vue app show an unexpected error).

const file = new Blob([result.data], { type: 'application/pdf' });

const fileURL = URL.createObjectURL(file);

printElement.setAttribute('href', ${fileURL as string});

nextTick();

printElement.click();

responseEncoding: 'arraybuffer',

responseType: 'arraybuffer',

enter image description here

I mentioned again that with this error PDF downloaded completely and healthy. How I can fix this error?


问:
ReactNative HeadlessJS equivalent in Flutter
I am looking for ReactNative HeadlessJS equivalent solution in Flutter to trigger dart code from native side in background!

For example, I want to define in the 'Android side' a BroadcastReceiver with BOOT_COMPLETE and then, I reboot the phone, and when its onReceive method get called, to trigger dart code in the 'Flutter side' (maybe through EventChannel) and this will be done totally in the background.

Is such thing possible?


问:
Strapi custom service methods not accessible unless in specific file
I have a custom endpoint at api/report/ with custom route and custom controller, all generated using the CLI.

I've created a series of custom service methods at api/report/services/report without any issues, however the file is getting unwieldy. Through trial and error (because I can't find anything about it in the docs), it looks like I can add multiple files to api/report/services and they'll appear as their own services when running strapi services:list from the cli.

For example, if I create a file at api/report/services/clients I'll see a service listed as api::report.clients. However none of the methods I add to this service seem to work, even though I'm copying them over from api/report/service/report verbatim.

For reference, I'm using the 'simple'(?) method of registered services, not the factory method:

```<code>module.export = {
  methodName: async ( some, params) =>{
    try {
      //Do some stuff
    } catch (err) {
      //handle error
    }
  }
}
</code>```

And it works perfectly in api/report/services/report but not in api/report/services/clients.

Here's what happens if I try to log the service within my controller:

```<code>console.log( strapi.service("api::report.report") );
> { methodName: [AsyncFunction: methodName] }
</code>```
```<code>console.log( strapi.service("api::report.cities") );
> {}
</code>```

Even though the file contents are exactly the same. Note that thinking perhaps there was a conflict having two methods of the same name (which doesn't really make sense, but just in case) I removed the method from the report.report service and it still didn't work.

Any idea what to do?

Body:
I have a custom endpoint at api/report/ with custom route and custom controller, all generated using the CLI.

I've created a series of custom service methods at api/report/services/report without any issues, however the file is getting unwieldy. Through trial and error (because I can't find anything about it in the docs), it looks like I can add multiple files to api/report/services and they'll appear as their own services when running strapi services:list from the cli.

For example, if I create a file at api/report/services/clients I'll see a service listed as api::report.clients. However none of the methods I add to this service seem to work, even though I'm copying them over from api/report/service/report verbatim.

For reference, I'm using the 'simple'(?) method of registered services, not the factory method:

module.export = {
  methodName: async ( some, params) =>{
    try {
      //Do some stuff
    } catch (err) {
      //handle error
    }
  }
}

And it works perfectly in api/report/services/report but not in api/report/services/clients.

Here's what happens if I try to log the service within my controller:

console.log( strapi.service("api::report.report") );
> { methodName: [AsyncFunction: methodName] }

console.log( strapi.service("api::report.cities") );
> {}

Even though the file contents are exactly the same. Note that thinking perhaps there was a conflict having two methods of the same name (which doesn't really make sense, but just in case) I removed the method from the report.report service and it still didn't work.

Any idea what to do?


问:
Sequelize: "Model has not been defined" when want to add relationship (Help !! )
This is My Model

I'm trying to instanciate one sequelize per Database. Some tables in DB1 has relationships with tables in DB2.
I have user table and Message table and create relation and working well but when I try for job table I have this error

```<code>module.exports = (sequelize, DataTypes) => {
  const Jobs = sequelize.define("Jobs", {
    title: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    description: {
      type: DataTypes.TEXT('long'),
      allowNull: false,
    },
    city: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    area: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    imageUrl: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    mode: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    aplicationCount: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    companyId: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },

    },{ timestamp : false, createdAt: false,  updatedAt: false, });

    let Requests = sequelize.model('Requests')
    Jobs.hasMany(Requests,{as: 'Requests', foreignKey: 'jobId'})
    return Jobs;
};
</code>```

This is the error

Body:
This is My Model

I'm trying to instanciate one sequelize per Database. Some tables in DB1 has relationships with tables in DB2.
I have user table and Message table and create relation and working well but when I try for job table I have this error

module.exports = (sequelize, DataTypes) => {
  const Jobs = sequelize.define("Jobs", {
    title: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    description: {
      type: DataTypes.TEXT('long'),
      allowNull: false,
    },
    city: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    area: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    imageUrl: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    mode: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    aplicationCount: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    companyId: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },

    },{ timestamp : false, createdAt: false,  updatedAt: false, });

    let Requests = sequelize.model('Requests')
    Jobs.hasMany(Requests,{as: 'Requests', foreignKey: 'jobId'})
    return Jobs;
};

This is the error


问:
MySQL spatial geom query
Hi I'm very new regarding PostGIS so forgive me if this is a dumb question.
I'm trying to make this query run fast

```<code>SELECT a.col1, a.col2, a.col3..,
b.col1,  b.col2, b.col3.....

FROM table1 a
JOIN table2 b
WHERE ST_CONTAINS(b.Shape, a.Point)
</code>```

index:
Spatial Shape_Idx ON table2 (Shape)
ID_Idx on table2(ID)

Explain shows

```<code>select type: Simple
table:b
type:ALL
possible Keys: Shape
rows: 40k+

table:a
type:ALL
rows: 7m+
Extra: Using where, Using join buffer
</code>```

table2 has a unique id for each geom shape and spatial index doesn't seem to work?
What should be my approach to solve this problem? Any tips is appreciated. Thank you!

Title: MySQL spatial geom query

Body:
Hi I'm very new regarding PostGIS so forgive me if this is a dumb question.
I'm trying to make this query run fast

SELECT a.col1, a.col2, a.col3..,
b.col1,  b.col2, b.col3.....

FROM table1 a
JOIN table2 b
WHERE ST_CONTAINS(b.Shape, a.Point)

index:
Spatial Shape_Idx ON table2 (Shape)
ID_Idx on table2(ID)

Explain shows

select type: Simple
table:b
type:ALL
possible Keys: Shape
rows: 40k+

table:a
type:ALL
rows: 7m+
Extra: Using where, Using join buffer

table2 has a unique id for each geom shape and spatial index doesn't seem to work?
What should be my approach to solve this problem? Any tips is appreciated. Thank you!


问:
The text will not update when the variable has changed
This GUI script I´m working on seems to have difficulty displaying the new string variable when it is redefined later. Initially, the variable is set to (''), displaying an empty string, however it is meant to change when the button is pressed. '.update()' command doesn´t seem to work despite being in the function triggered by the button. What am I missing?
code:

```<code>win = App(title="Command Desk")

#this function is simply meant to put all the code for the window's elements in one function. This was done to solve a problem with binding the variables in the launchVe command.

def runComDesk():

    #this function is the command that is triggered whenever the user pushes the button. It  adds one to the integer talNum, and displays a message on the window.

    def launchVe():
        nonlocal talNum
        talNum += 1
        nonlocal tal
        tal = "Rocket vehicle launched! You've launched", talNum, "rocket propelled skycraft so far!"
        win.update()

#this block sets the tal and talNum variables to their initial values, of 0 and "", (which displays no text while also getting the variable declaired), respectively.

    talNum = 0
    tal = ""
    launchComSig = PushButton(win, text="Launch", command=launchVe)
    mess = Text(win, text=tal)

#runs the main function and creates the window.
runComDesk()
win.display
</code>```

I expected the text would change when the variable did. It didn´t. I know I needan update command, but all I found was '.update()', which isn´t working to update the GUI text.

Body:
This GUI script I´m working on seems to have difficulty displaying the new string variable when it is redefined later. Initially, the variable is set to (''), displaying an empty string, however it is meant to change when the button is pressed. '.update()' command doesn´t seem to work despite being in the function triggered by the button. What am I missing?
code:

win = App(title="Command Desk")

#this function is simply meant to put all the code for the window's elements in one function. This was done to solve a problem with binding the variables in the launchVe command.

def runComDesk():

    #this function is the command that is triggered whenever the user pushes the button. It  adds one to the integer talNum, and displays a message on the window.

    def launchVe():
        nonlocal talNum
        talNum += 1
        nonlocal tal
        tal = "Rocket vehicle launched! You've launched", talNum, "rocket propelled skycraft so far!"
        win.update()

#this block sets the tal and talNum variables to their initial values, of 0 and "", (which displays no text while also getting the variable declaired), respectively.

    talNum = 0
    tal = ""
    launchComSig = PushButton(win, text="Launch", command=launchVe)
    mess = Text(win, text=tal)

#runs the main function and creates the window.
runComDesk()
win.display

I expected the text would change when the variable did. It didn´t. I know I needan update command, but all I found was '.update()', which isn´t working to update the GUI text.