问:
Getting 403 Permission Denied with GCP DLP API
I am writing a Python script to check the content of some files existing in Google Cloud Storage, if the contain some PII. Script is as below

```<code>dlp = google.cloud.dlp_v2.DlpServiceClient()

url = "gs://{}/{}".format("my-bucket-name", "my_file_name")
storage_config = {"cloud_storage_options": {"file_set": {"url": url}}}

parent = dlp.project_path("my-project-name")

inspect_job = {
    "inspect_config": inspect_config,
    "storage_config": storage_config
}

operation = dlp.create_dlp_job(parent, inspect_job=inspect_job)

job_done = threading.Event()

job = dlp.get_dlp_job(operation.name)
try:
    if job.inspect_details.result.info_type_stats:
        for finding in job.inspect_details.result.info_type_stats:
            print("Info type: {}; Count: {}".format(finding.info_type.name, finding.count))
    else:
        print("No findings.")
    job_done.set()
except Exception as e:
    print(e)
    raise

finished = job_done.wait(timeout=3000)
if not finished:
    print(
        "No event received before the timeout. Please verify that the "
        "subscription provided is subscribed to the topic provided."
    )
</code>```

I read in the documentation that DLP API created a service account of its own with the required set of permission.

When the Cloud DLP is enabled, a service account is added to the project.

To access both Google Cloud resources and execute calls to Cloud DLP
  by means of a JobTrigger, Cloud DLP uses the credentials of the Google
  APIs service account to authenticate to other APIs. The Google APIs
  service account is designed specifically to run internal Google
  processes on your behalf. The service account is identifiable using
  the email:

service-[PROJECT_NUMBER]@dlp-api.iam.gserviceaccount.com

When I run the code, I get a 403 error stating it does not have required permission dlp.jobs.create. I updated IAM policy for the account to contain a custom role with the below-mentioned policy set(since this is only a project for learning purpose).

```<code>dlp.analyzeRiskTemplates.create
dlp.analyzeRiskTemplates.delete
dlp.analyzeRiskTemplates.get
dlp.analyzeRiskTemplates.list
dlp.analyzeRiskTemplates.update
dlp.deidentifyTemplates.create
dlp.deidentifyTemplates.delete
dlp.deidentifyTemplates.get
dlp.deidentifyTemplates.list
dlp.deidentifyTemplates.update
dlp.inspectTemplates.create
dlp.inspectTemplates.delete
dlp.inspectTemplates.get
dlp.inspectTemplates.list
dlp.inspectTemplates.update
dlp.jobTriggers.create
dlp.jobTriggers.delete
dlp.jobTriggers.get
dlp.jobTriggers.list
dlp.jobTriggers.update
dlp.jobs.cancel
dlp.jobs.create
dlp.jobs.delete
dlp.jobs.get
dlp.jobs.list
dlp.kms.encrypt
dlp.storedInfoTypes.create
dlp.storedInfoTypes.delete
dlp.storedInfoTypes.get
dlp.storedInfoTypes.list
dlp.storedInfoTypes.update
serviceusage.services.use
</code>```

My Service account has two separate permission sets:

DLP permissions separately:

dlp.jobs.create

dlp.jobs.cancel

dlp.jobs.delete

dlp.jobs.get

dlp.jobs.list

Owner permission so it has unrestricted access to all google resources.

roles/owner

However, when I run the script now, It still gives the following error:

```<code>grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
    status = StatusCode.PERMISSION_DENIED
    details = "Not allowed, access denied for permission dlp.jobs.create."
    debug_error_string = "{"created":"@1581682593.219000000","description":"Error received from peer ipv4:xxx.xxx.x.x","file":"src/core/lib/surface/call.cc","file_line":1056,"grpc_message":"Not allowed, access denied for permission dlp.jobs.create.","grpc_status":7}"

google.api_core.exceptions.PermissionDenied: 403 Not allowed, access denied for permission dlp.jobs.create.
</code>```

答:
Please read the official documentation Authenticating to the Cloud DLP API

You must authenticate to the Cloud DLP API in order to use it

You have  to use a service account to authenticate to the Cloud DLP API:

Create a Service Account

Granting Roles to Service Accounts ((roles/dlp.user)

Download the key.json file

Set the env variable:

```<code>export GOOGLE_APPLICATION_CREDENTIALS=[PATH_TO_KEY_FILE]
</code>```

The service account that you mentioned service-[PROJECT_NUMBER]@dlp-api.iam.gserviceaccount.com:

The Google APIs service account is designed specifically to run
  internal Google processes on your behalf

Please read about Types of service accounts

User-managed service accounts

Google-managed service account

EDIT

1.Created a new project

```<code>gcloud projects create class-run
gcloud config set project class-run
</code>```

2.Enable Billing

3.Enable DLP Api

4.I tested using To set up a scan job of a Cloud Storage bucket using Cloud DLP:

5.Create a pub sub topic, and a pub sub subscription

6.Create a service account, assign the role and download the key

```<code> gcloud iam service-accounts create test-cloud  --description "test-cloud"  --display-name "test-cloud"
 gcloud projects add-iam-policy-binding class-run   --member serviceAccount:test-cloud@class-run.iam.gserviceaccount.com  --role roles/dlp.user
 gcloud iam service-accounts keys create key.json  --iam-account test-cloud@class-run.iam.gserviceaccount.com
</code>```

7.Set the default credentials

```<code>export GOOGLE_APPLICATION_CREDENTIALS=/home/user/key.json
</code>```

8.Run the script and everything worked as expected.

Body:
I am writing a Python script to check the content of some files existing in Google Cloud Storage, if the contain some PII. Script is as below

dlp = google.cloud.dlp_v2.DlpServiceClient()

url = "gs://{}/{}".format("my-bucket-name", "my_file_name")
storage_config = {"cloud_storage_options": {"file_set": {"url": url}}}

parent = dlp.project_path("my-project-name")

inspect_job = {
    "inspect_config": inspect_config,
    "storage_config": storage_config
}

operation = dlp.create_dlp_job(parent, inspect_job=inspect_job)

job_done = threading.Event()

job = dlp.get_dlp_job(operation.name)
try:
    if job.inspect_details.result.info_type_stats:
        for finding in job.inspect_details.result.info_type_stats:
            print("Info type: {}; Count: {}".format(finding.info_type.name, finding.count))
    else:
        print("No findings.")
    job_done.set()
except Exception as e:
    print(e)
    raise

finished = job_done.wait(timeout=3000)
if not finished:
    print(
        "No event received before the timeout. Please verify that the "
        "subscription provided is subscribed to the topic provided."
    )

I read in the documentation that DLP API created a service account of its own with the required set of permission.

When the Cloud DLP is enabled, a service account is added to the project.

To access both Google Cloud resources and execute calls to Cloud DLP
  by means of a JobTrigger, Cloud DLP uses the credentials of the Google
  APIs service account to authenticate to other APIs. The Google APIs
  service account is designed specifically to run internal Google
  processes on your behalf. The service account is identifiable using
  the email:

service-[PROJECT_NUMBER]@dlp-api.iam.gserviceaccount.com

When I run the code, I get a 403 error stating it does not have required permission dlp.jobs.create. I updated IAM policy for the account to contain a custom role with the below-mentioned policy set(since this is only a project for learning purpose).

dlp.analyzeRiskTemplates.create
dlp.analyzeRiskTemplates.delete
dlp.analyzeRiskTemplates.get
dlp.analyzeRiskTemplates.list
dlp.analyzeRiskTemplates.update
dlp.deidentifyTemplates.create
dlp.deidentifyTemplates.delete
dlp.deidentifyTemplates.get
dlp.deidentifyTemplates.list
dlp.deidentifyTemplates.update
dlp.inspectTemplates.create
dlp.inspectTemplates.delete
dlp.inspectTemplates.get
dlp.inspectTemplates.list
dlp.inspectTemplates.update
dlp.jobTriggers.create
dlp.jobTriggers.delete
dlp.jobTriggers.get
dlp.jobTriggers.list
dlp.jobTriggers.update
dlp.jobs.cancel
dlp.jobs.create
dlp.jobs.delete
dlp.jobs.get
dlp.jobs.list
dlp.kms.encrypt
dlp.storedInfoTypes.create
dlp.storedInfoTypes.delete
dlp.storedInfoTypes.get
dlp.storedInfoTypes.list
dlp.storedInfoTypes.update
serviceusage.services.use

My Service account has two separate permission sets:

DLP permissions separately:

dlp.jobs.create

dlp.jobs.cancel

dlp.jobs.delete

dlp.jobs.get

dlp.jobs.list

Owner permission so it has unrestricted access to all google resources.

roles/owner

However, when I run the script now, It still gives the following error:

grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
    status = StatusCode.PERMISSION_DENIED
    details = "Not allowed, access denied for permission dlp.jobs.create."
    debug_error_string = "{"created":"@1581682593.219000000","description":"Error received from peer ipv4:xxx.xxx.x.x","file":"src/core/lib/surface/call.cc","file_line":1056,"grpc_message":"Not allowed, access denied for permission dlp.jobs.create.","grpc_status":7}"

google.api_core.exceptions.PermissionDenied: 403 Not allowed, access denied for permission dlp.jobs.create.

Body:
Please read the official documentation Authenticating to the Cloud DLP API

You must authenticate to the Cloud DLP API in order to use it

You have  to use a service account to authenticate to the Cloud DLP API:

Create a Service Account

Granting Roles to Service Accounts ((roles/dlp.user)

Download the key.json file

Set the env variable:

export GOOGLE_APPLICATION_CREDENTIALS=[PATH_TO_KEY_FILE]

The service account that you mentioned service-[PROJECT_NUMBER]@dlp-api.iam.gserviceaccount.com:

The Google APIs service account is designed specifically to run
  internal Google processes on your behalf

Please read about Types of service accounts

User-managed service accounts

Google-managed service account

EDIT

1.Created a new project

gcloud projects create class-run
gcloud config set project class-run

2.Enable Billing

3.Enable DLP Api

4.I tested using To set up a scan job of a Cloud Storage bucket using Cloud DLP:

5.Create a pub sub topic, and a pub sub subscription

6.Create a service account, assign the role and download the key

 gcloud iam service-accounts create test-cloud  --description "test-cloud"  --display-name "test-cloud"
 gcloud projects add-iam-policy-binding class-run   --member serviceAccount:test-cloud@class-run.iam.gserviceaccount.com  --role roles/dlp.user
 gcloud iam service-accounts keys create key.json  --iam-account test-cloud@class-run.iam.gserviceaccount.com

7.Set the default credentials

export GOOGLE_APPLICATION_CREDENTIALS=/home/user/key.json

8.Run the script and everything worked as expected.


来源: stackexchange

问:
What is the fix for a swiftUI ios app with Firebase framework error to build and run on a connected device?

What is the fix for a SwiftUI iOS app with Firebase framework error not allowing to build and run on connected devices?

Xcode builds and runs the code flawless in the Canvas panel and Simulator, but does not build and run on connected devices.

(on a new project)

Error Messages :

Thread 1 #0 0x00000001029172ac in __abort_with_payload ()

```<code>dyld`__abort_with_payload:
0x1029172a4 <+0>:  mov    x16, #0x209
0x1029172a8 <+4>:  svc    #0x80
->  0x1029172ac <+8>:  b.lo   0x1029172c8               ; <+36>
0x1029172b0 <+12>: stp    x29, x30, [sp, #-0x10]!
0x1029172b4 <+16>: mov    x29, sp
0x1029172b8 <+20>: bl     0x1029157d8               ; cerror_nocancel
0x1029172bc <+24>: mov    sp, x29
0x1029172c0 <+28>: ldp    x29, x30, [sp], #0x10
0x1029172c4 <+32>: ret
0x1029172c8 <+36>: ret'
</code>```

debug area

```<code>dyld: Library not loaded: @rpath/FBLPromises.framework/FBLPromises
Referenced from: /private/var/containers/Bundle/Application/1ECE175B-46E5-4FC0-A28A-
BC3255C9F124/Bennett Application.app/Bennett Application
Reason: no suitable image found.  Did find:
/private/var/containers/Bundle/Application/1ECE175B-46E5-4FC0-A28A-BC3255C9F124/Bennett
Application.app/Frameworks/FBLPromises.framework/FBLPromises: code signature invalid for
'/private/var/containers/Bundle/Application/1ECE175B-46E5-4FC0-A28A-BC3255C9F124/Bennett
Application.app/Frameworks/FBLPromises.framework/FBLPromises'
</code>```

Also, when you deploy an iOS app to the store, will you encounter similar problems as above?

答: This error was simply fixed by upgrading to the Apple Developers Program.</p>

ContentLicense: CC BY-SA 4.0

Body:
What is the fix for a SwiftUI iOS app with Firebase framework error not allowing to build and run on connected devices?

Xcode builds and runs the code flawless in the Canvas panel and Simulator, but does not build and run on connected devices.

(on a new project)

Error Messages :

Thread 1 #0 0x00000001029172ac in __abort_with_payload ()

dyld`__abort_with_payload:
0x1029172a4 <+0>:  mov    x16, #0x209
0x1029172a8 <+4>:  svc    #0x80
->  0x1029172ac <+8>:  b.lo   0x1029172c8               ; <+36>
0x1029172b0 <+12>: stp    x29, x30, [sp, #-0x10]!
0x1029172b4 <+16>: mov    x29, sp
0x1029172b8 <+20>: bl     0x1029157d8               ; cerror_nocancel
0x1029172bc <+24>: mov    sp, x29
0x1029172c0 <+28>: ldp    x29, x30, [sp], #0x10
0x1029172c4 <+32>: ret
0x1029172c8 <+36>: ret'

debug area

dyld: Library not loaded: @rpath/FBLPromises.framework/FBLPromises
Referenced from: /private/var/containers/Bundle/Application/1ECE175B-46E5-4FC0-A28A-
BC3255C9F124/Bennett Application.app/Bennett Application
Reason: no suitable image found.  Did find:
/private/var/containers/Bundle/Application/1ECE175B-46E5-4FC0-A28A-BC3255C9F124/Bennett
Application.app/Frameworks/FBLPromises.framework/FBLPromises: code signature invalid for
'/private/var/containers/Bundle/Application/1ECE175B-46E5-4FC0-A28A-BC3255C9F124/Bennett
Application.app/Frameworks/FBLPromises.framework/FBLPromises'

Also, when you deploy an iOS app to the store, will you encounter similar problems as above?


问:
Use dictionary to replace parameters in SQL query
I have SQL query as a string:

```<code>SELECT DISTINCT a, b AS value FROM ${source} WHERE b IN (${string}) AND slice_start >= ${date} AND slice_start <= ${date1};
</code>```

And I need to replace the parameters using dictionary , that comes from JSON file looking like this:

```<code>my_dict = {"source": "table", "string": "abc", "date": "2020-01-01", "date1": "2020-01-02"}
</code>```

I am confused how to replace every string that starts with $ and how to attach " (but not on source) at the end and at the begging of every parameter, so the SQL query can be executed later. This is where I am now:

```<code>for k, v in target_groups_queries.items():
    if isinstance(v, dict):
        for k1, v1 in v.items():
            queries = v1['sql'].split()
            final_string = ' '.join(str(my_dict.get(word, word)) for word in queries)
            print(final_string)

    else:
        pass
</code>```

答:
You can use dictionary- or keyword-unpacking as follows:

```<code>my_dict = {"source": "table", "string": "abc", "date": "2020-01-01",
           "date1": "2020-01-02"}
sql = '''SELECT DISTINCT a, b AS value
         FROM ${source}
         WHERE b IN (${string})
             AND slice_start >= ${date}
             AND slice_start <= ${date1};'''

sql.format(**my_dict)
</code>```

Result:

```<code>In [32]: from pprint import pprint

In [33]: pprint(sql.format(**my_dict))
('SELECT DISTINCT a, b AS value FROM $table WHERE b IN ($abc) AND slice_start '
 '>= $2020-01-01 AND slice_start <= $2020-01-02;')
</code>```

Body:
I have SQL query as a string:

SELECT DISTINCT a, b AS value FROM ${source} WHERE b IN (${string}) AND slice_start >= ${date} AND slice_start <= ${date1};

And I need to replace the parameters using dictionary , that comes from JSON file looking like this:

my_dict = {"source": "table", "string": "abc", "date": "2020-01-01", "date1": "2020-01-02"}

I am confused how to replace every string that starts with $ and how to attach " (but not on source) at the end and at the begging of every parameter, so the SQL query can be executed later. This is where I am now:

for k, v in target_groups_queries.items():
    if isinstance(v, dict):
        for k1, v1 in v.items():
            queries = v1['sql'].split()
            final_string = ' '.join(str(my_dict.get(word, word)) for word in queries)
            print(final_string)

    else:
        pass

Body:
You can use dictionary- or keyword-unpacking as follows:

my_dict = {"source": "table", "string": "abc", "date": "2020-01-01",
           "date1": "2020-01-02"}
sql = '''SELECT DISTINCT a, b AS value
         FROM ${source}
         WHERE b IN (${string})
             AND slice_start >= ${date}
             AND slice_start <= ${date1};'''

sql.format(**my_dict)

Result:

In [32]: from pprint import pprint

In [33]: pprint(sql.format(**my_dict))
('SELECT DISTINCT a, b AS value FROM $table WHERE b IN ($abc) AND slice_start '
 '>= $2020-01-01 AND slice_start <= $2020-01-02;')


问:
Why can't local variable be used in GNU C basic inline asm statements?
Why cannot I use local variables from main to be used in basic asm inline? It is only allowed in extended asm, but why so?

(I know local variables are on the stack after return address (and therefore cannot be used once the function return), but that should not be the reason to not use them)

And example of basic asm:

```<code>int a = 10; //global a
int b = 20; //global b
int result;

int main() {
    asm ( "pusha\n\t"
          "movl a, %eax\n\t"
          "movl b, %ebx\n\t"
          "imull %ebx, %eax\n\t"
          "movl %eax, result\n\t"
          "popa");

    printf("the answer is %d\n", result);
    return 0;
}
</code>```

example of extended:

```<code>int main (void) {
    int data1 = 10;  //local var - could be used in extended
    int data2 = 20;
    int result;

    asm ( "imull %%edx, %%ecx\n\t"
          "movl %%ecx, %%eax"
          : "=a"(result)
          : "d"(data1), "c"(data2));

    printf("The result is %d\n",result);
    return 0;
}
</code>```

Compiled with:
gcc -m32 somefile.c

platform:
uname -a:
Linux 5.0.0-32-generic #34-Ubuntu SMP Wed Oct 2 02:06:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

答:
You can use local variables in extended assembly, but you need to tell the extended assembly construct about them. Consider:

```<code>#include <stdio.h>

int main (void)
{
    int data1 = 10;
    int data2 = 20;
    int result;

    __asm__(
        "   movl    %[mydata1], %[myresult]\n"
        "   imull   %[mydata2], %[myresult]\n"
        : [myresult] "=&r" (result)
        : [mydata1] "r" (data1), [mydata2] "r" (data2));

    printf("The result is %d\n",result);

    return 0;
}
</code>```

In this [myresult] "=&r" (result) says to select a register (r) that will be used as an output (=) value for the lvalue result, and that register will be referred to in the assembly as %[myresult] and must be different from the input registers (&). (You can use the same text in both places, result instead of myresult; I just made it different for illustration.)

Similarly [mydata1] "r" (data1) says to put the value of expression data1 into a register, and it will be referred to in the assembly as %[mydata1].

I modified the code in the assembly so that it only modifies the output register. Your original code modifies %ecx but does not tell the compiler it is doing that. You could have told the compiler that by putting "ecx" after a third :, which is where the list of “clobbered” registers goes. However, since my code lets the compiler assign a register, I would not have a specific register to list in the clobbered register. There may be a way to tell the compiler that one of the input registers will be modified but is not needed for output, but I do not know. (Documentation is here.) For this task, a better solution is to tell the compiler to use the same register for one of the inputs as the output:

```<code>    __asm__(
        "   imull   %[mydata1], %[myresult]\n"
        : [myresult] "=r" (result)
        : [mydata1] "r" (data1), [mydata2] "0" (data2));
</code>```

In this, the 0 with data2 says to make it the same as operand 0. The operands are numbered in the order they appear, starting with 0 for the first output operand and continuing into the input operands. So, when the assembly code starts, %[myresult] will refer to some register that the value of data2 has been placed in, and the compiler will expect the new value of result to be in that register when the assembly is done.

When doing this, you have to match the constraint with how a thing will be used in assembly. For the r constraint, the compiler supplies some text that can be used in assembly language where a general processor register is accepted. Others include m for a memory reference, and i for an immediate operand.

Body:
Why cannot I use local variables from main to be used in basic asm inline? It is only allowed in extended asm, but why so?

(I know local variables are on the stack after return address (and therefore cannot be used once the function return), but that should not be the reason to not use them)

And example of basic asm:

int a = 10; //global a
int b = 20; //global b
int result;

int main() {
    asm ( "pusha\n\t"
          "movl a, %eax\n\t"
          "movl b, %ebx\n\t"
          "imull %ebx, %eax\n\t"
          "movl %eax, result\n\t"
          "popa");

    printf("the answer is %d\n", result);
    return 0;
}

example of extended:

int main (void) {
    int data1 = 10;  //local var - could be used in extended
    int data2 = 20;
    int result;

    asm ( "imull %%edx, %%ecx\n\t"
          "movl %%ecx, %%eax"
          : "=a"(result)
          : "d"(data1), "c"(data2));

    printf("The result is %d\n",result);
    return 0;
}

Compiled with:
gcc -m32 somefile.c

platform:
uname -a:
Linux 5.0.0-32-generic #34-Ubuntu SMP Wed Oct 2 02:06:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

Body:
You can use local variables in extended assembly, but you need to tell the extended assembly construct about them. Consider:

#include <stdio.h>

int main (void)
{
    int data1 = 10;
    int data2 = 20;
    int result;

    __asm__(
        "   movl    %[mydata1], %[myresult]\n"
        "   imull   %[mydata2], %[myresult]\n"
        : [myresult] "=&r" (result)
        : [mydata1] "r" (data1), [mydata2] "r" (data2));

    printf("The result is %d\n",result);

    return 0;
}

In this [myresult] "=&r" (result) says to select a register (r) that will be used as an output (=) value for the lvalue result, and that register will be referred to in the assembly as %[myresult] and must be different from the input registers (&). (You can use the same text in both places, result instead of myresult; I just made it different for illustration.)

Similarly [mydata1] "r" (data1) says to put the value of expression data1 into a register, and it will be referred to in the assembly as %[mydata1].

I modified the code in the assembly so that it only modifies the output register. Your original code modifies %ecx but does not tell the compiler it is doing that. You could have told the compiler that by putting "ecx" after a third :, which is where the list of “clobbered” registers goes. However, since my code lets the compiler assign a register, I would not have a specific register to list in the clobbered register. There may be a way to tell the compiler that one of the input registers will be modified but is not needed for output, but I do not know. (Documentation is here.) For this task, a better solution is to tell the compiler to use the same register for one of the inputs as the output:

    __asm__(
        "   imull   %[mydata1], %[myresult]\n"
        : [myresult] "=r" (result)
        : [mydata1] "r" (data1), [mydata2] "0" (data2));

In this, the 0 with data2 says to make it the same as operand 0. The operands are numbered in the order they appear, starting with 0 for the first output operand and continuing into the input operands. So, when the assembly code starts, %[myresult] will refer to some register that the value of data2 has been placed in, and the compiler will expect the new value of result to be in that register when the assembly is done.

When doing this, you have to match the constraint with how a thing will be used in assembly. For the r constraint, the compiler supplies some text that can be used in assembly language where a general processor register is accepted. Others include m for a memory reference, and i for an immediate operand.


问:
Why won't my countdown timer start and stop?
I need to make a simple countdown timer from 5 to zero, with the buttons to START and STOP the counter. The only thing that I don't know is that why won't my counter stop.

The code is presented below:

   function clock() {
     var myTimer = setInterval(myClock, 1000);
     var c = 5;

     function myClock() {
       document.getElementById("demo").innerHTML = --c;
       if (c == 0) {
         clearInterval(myTimer);
         alert("Reached zero");
       }
     }
   }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo">5</p>
<button onclick="clock()">Start counter</button>
<button onclick="clearInterval(myTimer)">Stop counter</button></code>```

答:
This solution worked for me in react JS</p>

```<code>let Timer =(function(){
    let timerObject;
    let callback=null;
    let seconds=0;
    let counter=()=>{
        seconds++;
        console.log("seconds",seconds);
        if (callback!==undefined) callback(seconds);
    }
    let setCallback=(_callback)=>{callback=_callback }
    let getSeconds=()=>{ return seconds;}
    let reset=()=>{ seconds=0;}
    let start=()=>{timerObject=setInterval(counter,1000);}
    let end=()=>{clearInterval(timerObject);}
    return {"start":start,"end":end, "getSeconds":getSeconds, "reset":reset,"setCallback":setCallback}; })();

export default Timer;
</code>```

Body:
I need to make a simple countdown timer from 5 to zero, with the buttons to START and STOP the counter. The only thing that I don't know is that why won't my counter stop.

The code is presented below:

   function clock() {
     var myTimer = setInterval(myClock, 1000);
     var c = 5;

     function myClock() {
       document.getElementById("demo").innerHTML = --c;
       if (c == 0) {
         clearInterval(myTimer);
         alert("Reached zero");
       }
     }
   }

5

<button onclick="clock()">Start counter</button>
<button onclick="clearInterval(myTimer)">Stop counter</button>

Body:
This solution worked for me in react JS

let Timer =(function(){
    let timerObject;
    let callback=null;
    let seconds=0;
    let counter=()=>{
        seconds++;
        console.log("seconds",seconds);
        if (callback!==undefined) callback(seconds);
    }
    let setCallback=(_callback)=>{callback=_callback }
    let getSeconds=()=>{ return seconds;}
    let reset=()=>{ seconds=0;}
    let start=()=>{timerObject=setInterval(counter,1000);}
    let end=()=>{clearInterval(timerObject);}
    return {"start":start,"end":end, "getSeconds":getSeconds, "reset":reset,"setCallback":setCallback}; })();

export default Timer;


问:
Need to group records based on matching reversal in sql
I have a tricky scenario to aggregate the data.

Data in my source table is as follows.

```<code>CustomerId  Transaction Type    Transaction Amount
1               Payment              100
1               ReversePayment      -100
1               payment              100
1               ReversePayment      -100
1               Payment              100
1               Payment              100
</code>```

Requirement is as follows:

If the payment as a assoociated Reversepayment with matched amount, sum these two records.

If the payment does not have an associated Reverse payment, consider it as orphan(dont sum it).

I want output to be like this.

```<code>  CustomerId    Transaction Type                Transaction Amount
   1                Payment,ReversePayment               0
   1                payment,ReversePayment               0
   1                payment                             100
   1               Payment                              100
</code>```

In this scenario,

First record which is payment has an associated reverse payment (2nd record), Hence the sum becomes 0

Third record which is payment has an associated reverse payment (4th record), then the sum becomes 0

Fifth and sixth does not have associated reversals. dont sum these records.

Second Example:

Data in the source as follows:

```<code> CustomerId Transaction Type    Transaction Amount
 1              Payment              100
 1              ReversePayment      -100
 1              payment              300
 1              ReversePayment      -300
 1               Payment              400
 1               Payment              500
</code>```

Expected Output

```<code>CustomerId      Transaction Type                Transaction Amount
 1              Payment,ReversePayment               0
 1              payment,ReversePayment               0
 1              payment                             400
 1              Payment                             500
</code>```

Second example requirement:
-As first and second records (payment and its associated reverse payment got
 matched) ,sum these two records, output is 0.
- As third and fourth records (payment and its associated reverse payment got
  matched), sum these two records, output is 0.
- Fifth and sixth does not have associated reversals. don't sum these records.

I got solutions in group, but data is not always guaranteed to have orphan records as 'payments'. Some times they are 'Payments' and some times they are 'ReversePayments'. Can some help me get ouptut like the below (using rank or rownumber functions ) so that i can group by using RRR column.

```<code>CustomerId  Transaction Type    Transaction Amount         RRR
 1              Payment              100                   1
 1              ReversePayment      -100                   1
 1              payment              100                   2
 1              ReversePayment      -100                   2
 1               Payment              100                   3
 1               Payment              100                   4

 CustomerId Transaction Type    Transaction Amount      RRR
 1              Payment              100                 1
 1              ReversePayment      -100                 1
 1              payment              300                 2
 1              ReversePayment      -300                 2
 1               Payment              400                3
 1               Payment              500                4
</code>```

答:
You can enumerate the different types and then aggregate:</p>

```<code>select customerid,
       listagg(ttype, ',') within group (order by ttype) as types,
       sum(amount) as amount
from (select t.*,
             row_number() over (partition by customerid, ttype, amount order by customerid) as seqnum
      from t
     ) t
group by customerid, seqnum;
</code>```

Body:
I have a tricky scenario to aggregate the data.

Data in my source table is as follows.

CustomerId  Transaction Type    Transaction Amount
1               Payment              100
1               ReversePayment      -100
1               payment              100
1               ReversePayment      -100
1               Payment              100
1               Payment              100

Requirement is as follows:

If the payment as a assoociated Reversepayment with matched amount, sum these two records.

If the payment does not have an associated Reverse payment, consider it as orphan(dont sum it).

I want output to be like this.

  CustomerId    Transaction Type                Transaction Amount
   1                Payment,ReversePayment               0
   1                payment,ReversePayment               0
   1                payment                             100
   1               Payment                              100

In this scenario,

First record which is payment has an associated reverse payment (2nd record), Hence the sum becomes 0

Third record which is payment has an associated reverse payment (4th record), then the sum becomes 0

Fifth and sixth does not have associated reversals. dont sum these records.

Second Example:

Data in the source as follows:

 CustomerId Transaction Type    Transaction Amount
 1              Payment              100
 1              ReversePayment      -100
 1              payment              300
 1              ReversePayment      -300
 1               Payment              400
 1               Payment              500

Expected Output

CustomerId      Transaction Type                Transaction Amount
 1              Payment,ReversePayment               0
 1              payment,ReversePayment               0
 1              payment                             400
 1              Payment                             500

Second example requirement:
-As first and second records (payment and its associated reverse payment got
 matched) ,sum these two records, output is 0.
- As third and fourth records (payment and its associated reverse payment got
  matched), sum these two records, output is 0.
- Fifth and sixth does not have associated reversals. don't sum these records.

I got solutions in group, but data is not always guaranteed to have orphan records as 'payments'. Some times they are 'Payments' and some times they are 'ReversePayments'. Can some help me get ouptut like the below (using rank or rownumber functions ) so that i can group by using RRR column.

CustomerId  Transaction Type    Transaction Amount         RRR
 1              Payment              100                   1
 1              ReversePayment      -100                   1
 1              payment              100                   2
 1              ReversePayment      -100                   2
 1               Payment              100                   3
 1               Payment              100                   4

 CustomerId Transaction Type    Transaction Amount      RRR
 1              Payment              100                 1
 1              ReversePayment      -100                 1
 1              payment              300                 2
 1              ReversePayment      -300                 2
 1               Payment              400                3
 1               Payment              500                4

Body:
You can enumerate the different types and then aggregate:

select customerid,
       listagg(ttype, ',') within group (order by ttype) as types,
       sum(amount) as amount
from (select t.*,
             row_number() over (partition by customerid, ttype, amount order by customerid) as seqnum
      from t
     ) t
group by customerid, seqnum;


问:
C# Linq create a list of derived class inside Group By
I have a method in which I call a method that performs a query returning an IEnumerable of objects, then I perform a group by Linq on this IEnumerable, and elaborate the result of the grouping to insert it in a JQGrid. In the grouping, I create an object containing a list of other objects. I want that this list is not of the base type, but I would like it to be of the derived type.
This is the call to the method that performs the query, returning the IEnumerable object:

```<code>IEnumerable documentList = ObjBase.getAll(string.IsNullOrEmpty(columnList) ? null : columnList.Split(';'), sidx, sord, sqlWhere, out totalRows, userid: userId, siteId: siteId);
</code>```

This is the class of objects that I have after the group by Linq:

```<code>public class DocumentContact : ObjBase
{
    public long? CODE_CUSTOMER_ID { get; set; }
    public long? CODE_CUSTOMERTYPEID { get; set; }
    public long? CODE_CONTRACT_ID { get; set; }
    public long CODE_SITEID { get; set; }
    public string DESC_CONTACT_NUMBER { get; set; }
    public string DESC_CONTRACT_NUMBER { get; set; }
    public string DESC_CONTRACT_STATES { get; set; }
    public List<DocumentModelDates> Documents { get; set; }
}
</code>```

This is the DocumentModel class:

```<code>public class DocumentModel : ObjBase
{
    private long _id;
    private string _documentModel;
    private long? _documentModelTypeId;
    private long? _documentModelIssuingEntityId;
    private string _documentModelFilename;
    private string _documentModelPath;
    private DateTime? _documentModelStart;
    private DateTime? _documentModelEnd;
    private string _documentModelVersion;
    private long _contractId;
    private string _contractNumber;
    private long _contractTypeId;
    private long _contractStateId;
    private string _contractState;
    private long _documentModelStateId;
    private string _documentModelValoId;
    private DateTime? _documentModelUploadDate;
    private byte[] _documentModelContent;
    private long _documentModelFilter;
    private bool _flagDeleted;
    private long _userId;
    private int _orderDocumentModel = 0;
    private string _placeOfIssue;
    private string _issuingEntity;
    private DateTime? _releaseDate;
    private int? _idOpInsert;
    private int? _idOpId;
    private long? _customerId;
    private long? _customerTypeId;
    private string _customerNumber;
    private DateTime? _documentModelInvalidated;
    private bool _flagValidating;
    private string _fileRemotePath;
    private long? _folderId;
    private string _folderName;
    protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
}
</code>```

This is the DocumentModelDates, derived from DocumentModel:

```<code>    public class DocumentModelDates : DocumentModel
{
    public long? DateStart { get; set; }
    public long? DateEnd { get; set; }
    public long? DateUpload { get; set; }

    public DocumentModelDates(DocumentModel document)
    {
        this.CODE_DOCUMENT_MODEL_ID = document.CODE_DOCUMENT_MODEL_ID;
        this.DateStart = document.DATE_DOCUMENT_MODEL_START.Value.Ticks;
        this.DateEnd = document.DATE_DOCUMENT_MODEL_END.Value.Ticks;
        this.DateUpload = document.DATE_DOCUMENT_MODEL_UPLOAD.Value.Ticks;
    }
}
</code>```

This is the Group By Linq operation on these IEnumerable:

```<code>    var documentContact = documentList.GroupBy(c => new
    {
        c.CODE_CUSTOMERID,
        c.DESC_CONTACT_NUMBER,
        c.CODE_CUSTOMERTYPEID,
        c.CODE_CONTRACT_ID,
        c.DESC_CONTRACT_NUMBER,
        c.DESC_CONTRACT_STATES,
    })
    .Select(gcs => new DocumentContact()
    {
        CODE_CUSTOMER_ID = gcs.Key.CODE_CUSTOMERID,
        DESC_CONTACT_NUMBER = gcs.Key.DESC_CONTACT_NUMBER,
        CODE_CUSTOMERTYPEID = gcs.Key.CODE_CUSTOMERTYPEID,
        CODE_CONTRACT_ID = gcs.Key.CODE_CONTRACT_ID,
        DESC_CONTRACT_NUMBER = gcs.Key.DESC_CONTRACT_NUMBER,
        DESC_CONTRACT_STATES = gcs.Key.DESC_CONTRACT_STATES,
        CODE_SITEID = siteId,
        Documents = gcs.ToList(),
    });
</code>```

If I do this, I have a conversion error: Is there a way to create a DocumentModelDates list inside this Select? Thanks.

答:
Try something like this

```<code>   public class DocumentModelDates
    {
        private DateTime _DateStart { get; set; }
        public long DateStart
        {
            get { return _DateStart.ToBinary(); }
            set { _DateStart = DateTime.FromBinary(value);}

        }
    }
</code>```

Body:
I have a method in which I call a method that performs a query returning an IEnumerable of objects, then I perform a group by Linq on this IEnumerable, and elaborate the result of the grouping to insert it in a JQGrid. In the grouping, I create an object containing a list of other objects. I want that this list is not of the base type, but I would like it to be of the derived type.
This is the call to the method that performs the query, returning the IEnumerable object:

IEnumerable documentList = ObjBase.getAll(string.IsNullOrEmpty(columnList) ? null : columnList.Split(';'), sidx, sord, sqlWhere, out totalRows, userid: userId, siteId: siteId);

This is the class of objects that I have after the group by Linq:

public class DocumentContact : ObjBase
{
    public long? CODE_CUSTOMER_ID { get; set; }
    public long? CODE_CUSTOMERTYPEID { get; set; }
    public long? CODE_CONTRACT_ID { get; set; }
    public long CODE_SITEID { get; set; }
    public string DESC_CONTACT_NUMBER { get; set; }
    public string DESC_CONTRACT_NUMBER { get; set; }
    public string DESC_CONTRACT_STATES { get; set; }
    public List<DocumentModelDates> Documents { get; set; }
}

This is the DocumentModel class:

public class DocumentModel : ObjBase
{
    private long _id;
    private string _documentModel;
    private long? _documentModelTypeId;
    private long? _documentModelIssuingEntityId;
    private string _documentModelFilename;
    private string _documentModelPath;
    private DateTime? _documentModelStart;
    private DateTime? _documentModelEnd;
    private string _documentModelVersion;
    private long _contractId;
    private string _contractNumber;
    private long _contractTypeId;
    private long _contractStateId;
    private string _contractState;
    private long _documentModelStateId;
    private string _documentModelValoId;
    private DateTime? _documentModelUploadDate;
    private byte[] _documentModelContent;
    private long _documentModelFilter;
    private bool _flagDeleted;
    private long _userId;
    private int _orderDocumentModel = 0;
    private string _placeOfIssue;
    private string _issuingEntity;
    private DateTime? _releaseDate;
    private int? _idOpInsert;
    private int? _idOpId;
    private long? _customerId;
    private long? _customerTypeId;
    private string _customerNumber;
    private DateTime? _documentModelInvalidated;
    private bool _flagValidating;
    private string _fileRemotePath;
    private long? _folderId;
    private string _folderName;
    protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
}

This is the DocumentModelDates, derived from DocumentModel:

    public class DocumentModelDates : DocumentModel
{
    public long? DateStart { get; set; }
    public long? DateEnd { get; set; }
    public long? DateUpload { get; set; }

    public DocumentModelDates(DocumentModel document)
    {
        this.CODE_DOCUMENT_MODEL_ID = document.CODE_DOCUMENT_MODEL_ID;
        this.DateStart = document.DATE_DOCUMENT_MODEL_START.Value.Ticks;
        this.DateEnd = document.DATE_DOCUMENT_MODEL_END.Value.Ticks;
        this.DateUpload = document.DATE_DOCUMENT_MODEL_UPLOAD.Value.Ticks;
    }
}

This is the Group By Linq operation on these IEnumerable:

    var documentContact = documentList.GroupBy(c => new
    {
        c.CODE_CUSTOMERID,
        c.DESC_CONTACT_NUMBER,
        c.CODE_CUSTOMERTYPEID,
        c.CODE_CONTRACT_ID,
        c.DESC_CONTRACT_NUMBER,
        c.DESC_CONTRACT_STATES,
    })
    .Select(gcs => new DocumentContact()
    {
        CODE_CUSTOMER_ID = gcs.Key.CODE_CUSTOMERID,
        DESC_CONTACT_NUMBER = gcs.Key.DESC_CONTACT_NUMBER,
        CODE_CUSTOMERTYPEID = gcs.Key.CODE_CUSTOMERTYPEID,
        CODE_CONTRACT_ID = gcs.Key.CODE_CONTRACT_ID,
        DESC_CONTRACT_NUMBER = gcs.Key.DESC_CONTRACT_NUMBER,
        DESC_CONTRACT_STATES = gcs.Key.DESC_CONTRACT_STATES,
        CODE_SITEID = siteId,
        Documents = gcs.ToList(),
    });

If I do this, I have a conversion error: Is there a way to create a DocumentModelDates list inside this Select? Thanks.

Body:
Try something like this

   public class DocumentModelDates
    {
        private DateTime _DateStart { get; set; }
        public long DateStart
        {
            get { return _DateStart.ToBinary(); }
            set { _DateStart = DateTime.FromBinary(value);}

        }
    }


问:
Run a Program inside a loop in powershell
I have exe of cwebp that basically can be run like

```<code>cwebp.exe image1.jpg -o image1.webp
</code>```

I'm trying to create simple powershell script to run the exe for all image inside a folder using powershell script, I do have create some script like this

```<code>param ( [string]$FolderName)
Get-ChildItem $FolderName | ForEach-Object {
    &"D:\Downloads\libwebp\bin\cwebp.exe" $_.FullName -o $_.BaseName + ".webp"
}
</code>```

so I can run the ps1 file with the folder name like

```<code>batch-script.ps1 ".\images"
</code>```

but when I run it, got error

```<code>SHCreateStreamOnFile((const LPTSTR)filename, STGM_READ, stream) failed 80070002
Error opening input file .webp (80070002)
OpenInputStream(filename, &stream) failed 80070002
cannot open input file '.webp'
Error! Could not process file .webp
Error! Cannot read input picture file '.webp'
</code>```

the folder content just have jpg image name image1.jpg, image2.jpg, did I miss something?

答:
Try something like this:</p>

```<code>param ( [string]$FolderName)

$images = Get-ChildItem $FolderName

foreach ($img in $images) {
  $outputName = $img.DirectoryName + "\" + $img.BaseName + ".webp"
  &"D:\Downloads\libwebp\bin\cwebp.exe" $img.FullName -o $outputName
}
</code>```

Body:
I have exe of cwebp that basically can be run like

cwebp.exe image1.jpg -o image1.webp

I'm trying to create simple powershell script to run the exe for all image inside a folder using powershell script, I do have create some script like this

param ( [string]$FolderName)
Get-ChildItem $FolderName | ForEach-Object {
    &"D:\Downloads\libwebp\bin\cwebp.exe" $_.FullName -o $_.BaseName + ".webp"
}

so I can run the ps1 file with the folder name like

batch-script.ps1 ".\images"

but when I run it, got error

SHCreateStreamOnFile((const LPTSTR)filename, STGM_READ, stream) failed 80070002
Error opening input file .webp (80070002)
OpenInputStream(filename, &stream) failed 80070002
cannot open input file '.webp'
Error! Could not process file .webp
Error! Cannot read input picture file '.webp'

the folder content just have jpg image name image1.jpg, image2.jpg, did I miss something?

Body:
Try something like this:

param ( [string]$FolderName)

$images = Get-ChildItem $FolderName

foreach ($img in $images) {
  $outputName = $img.DirectoryName + "\" + $img.BaseName + ".webp"
  &"D:\Downloads\libwebp\bin\cwebp.exe" $img.FullName -o $outputName
}


问:
Bulma Extensions switch: how do I get it to switch
When I try to use my switch like the one in the demo, it doesn't move.

I can see it console log the click in my handler when I click it or use the spacebar when it's focused.

Since I'm loading these dynamically, I'm generating my id, name and label "for" with all the same value, IE: isActive-n.

The switch is loading properly on the page, it looks great, it just doesn't move. I've tried a few different id/label value formats and nothing works yet.

Here is the switch part of my react component:

```<code>      <div className="column is-2">
          <div className="field is-pulled-right">
            <input
              id={`isActive-${props.id}`}
              type="checkbox"
              name={`isActive-${props.id}`}
              className="switch is-success is-rounded"
              checked={checked}
              onChange={swithOnChangeHandler}
            />
            <label htmlFor={`isActive-${props.id}`}>{label}</label>
          </div>
        </div>
</code>```

Here is the generated HTML:

```<code><div class="column is-2">
    <div class="field is-pulled-right">
        <input id="isActive-11" type="checkbox" name="isActive-11" class="switch is-success is-rounded is-small">
        <label for="isActive-11">Activate</label>
    </div>
</div>
</code>```

答: Ended up being a problem with the state of the input checked property. My logic for setting it was wrong. I also started using true and false for the checked value.

Body:
When I try to use my switch like the one in the demo, it doesn't move.

I can see it console log the click in my handler when I click it or use the spacebar when it's focused.

Since I'm loading these dynamically, I'm generating my id, name and label "for" with all the same value, IE: isActive-n.

The switch is loading properly on the page, it looks great, it just doesn't move. I've tried a few different id/label value formats and nothing works yet.

Here is the switch part of my react component:

            <input
              id={`isActive-${props.id}`}
              type="checkbox"
              name={`isActive-${props.id}`}
              className="switch is-success is-rounded"
              checked={checked}
              onChange={swithOnChangeHandler}
            />
            <label htmlFor={`isActive-${props.id}`}>{label}

Here is the generated HTML:

        <input id="isActive-11" type="checkbox" name="isActive-11" class="switch is-success is-rounded is-small">
        Activate


问:
Error: Cyclic dependency, node was:"dateA"
I want some information about the best implementation for a scenario like this:
I have a select and two date pickers.
When I choose from the select (idRisk) the parameter PRESENT, the two dates must be required.
If DateA is before the DateB then in the form I want to show a validation error.
What is the best way to achieve this?
I write this for completation, but show this error = Error: Cyclic dependency, node was:"dateA"

validationSchema: Yup.object({
    idRisk: Yup.number().required(),

    dateB: Yup.mixed().when('idRisk', {
        is: Risk.PRESENT,
        then: Yup.mixed().required(),
        otherwise: Yup.mixed()
    }),

    dateA: Yup.mixed()
        .when('idRisk', {
            is: Risk.PRESENT,
            then: Yup.mixed().required(),
            otherwise: Yup.mixed()
        })
        .when(['dateA', 'dateB'], (dateA, dateB) => {
            if (dateA.isBefore(dateB)) return this.required()
        })
})
```

答:
you cannot referrer the parameter ["dateA"] inside dateA:Yup.mixed().when() method, consider to use different approach, on example:

```<code>dateA: Yup.mixed()
  .when(["dateB"],
    (dateB, schema, node) => {
      if (node.value.isBefore(dateB))
        return this.required();
    }
  )
</code>```

you can get dateA value from node.value

Body:
you cannot referrer the parameter ["dateA"] inside dateA:Yup.mixed().when() method, consider to use different approach, on example:

dateA: Yup.mixed()
  .when(["dateB"],
    (dateB, schema, node) => {
      if (node.value.isBefore(dateB))
        return this.required();
    }
  )

you can get dateA value from node.value


问:
Is there a a way in Ruby to increment a Struct object variable inside an array?
```<code>Namepoints = Struct.new(:name, :points)

def arraytesting2()

  x = Namepoints.new("Seasons", 1)
  array = []
  255.times do

    unless array.include? x.name
      array << x.name
      array << x.points
    else
      array[array.index(x.points) + 1 ]
    end
  end
  print array.to_s.gsub(/[\[\]"]/, "")
end

arraytesting2
</code>```

Outcome: Seasons, 1

Expected outcome: Seasons, 255

array[array.index(x.points) + 1 ] will not increment?

Also attempting this another way: array[array.index(x.points + 1 )] receives a conversion error

答:
So you're trying to increment the value of an array found at a given index.

The index being array.index(x.points).

You can do that by:

array[array.index(x.points)] += 1
```

<p>What your code was doing was access the value of the index found after <code>array.index(x.points)</code>:</p>

<pre class="lang-rb prettyprint-override"><code>array[array.index(x.points) + 1]
</code>```

However, note that this still won't print

Seasons, 255

Reason being that after the first iteration, the array will hold:

```<code>['Seasons', 2]
</code>```

And the namepoints value of points is still 1. So next time you search for 1, you will not find it.

To fix this, it depends a bit on what you're trying to achieve. Either increment the value in namepoints as well or use a hash instead of an array. I'm not clear on why you needed the array.

Body:
Namepoints = Struct.new(:name, :points)

def arraytesting2()

  x = Namepoints.new("Seasons", 1)
  array = []
  255.times do

    unless array.include? x.name
      array << x.name
      array << x.points
    else
      array[array.index(x.points) + 1 ]
    end
  end
  print array.to_s.gsub(/[\[\]"]/, "")
end

arraytesting2

Outcome: Seasons, 1

Expected outcome: Seasons, 255

array[array.index(x.points) + 1 ] will not increment?

Also attempting this another way: array[array.index(x.points + 1 )] receives a conversion error

Body:
So you're trying to increment the value of an array found at a given index.

The index being array.index(x.points).

You can do that by:

array[array.index(x.points)] += 1

What your code was doing was access the value of the index found after array.index(x.points):

array[array.index(x.points) + 1]

However, note that this still won't print

Seasons, 255

Reason being that after the first iteration, the array will hold:

['Seasons', 2]

And the namepoints value of points is still 1. So next time you search for 1, you will not find it.

To fix this, it depends a bit on what you're trying to achieve. Either increment the value in namepoints as well or use a hash instead of an array. I'm not clear on why you needed the array.


问:
Run simple script on web page
I have made a simple game script that runs in the console. This game is in python 3.8. It's all been coded on repl.it and I want to run it on a url. I had a go with python anywhere but still struggled.

This is my code:

```<code>from random import randint
import numpy as np

print("The vault has been locked for the night...")
combination = randint(1,1000)

safe_locked = True
int_invalid = True
duplicate = True
guesses_list = list()
one_o_one = 1001
lower_bound = 0
upper_bound = 1001
guess_count = 0
valid_guesses = 0

while safe_locked == True:

  while int_invalid == True:
    try:
      if guess_count > 0:
        if upper_bound == 1001:
          upper_bound -= 1
        if lower_bound == 0:
          lower_bound += 1
        guess = int(input("Take your guess at the combination between [" + str(lower_bound) + "-" + str(upper_bound) + "]..."))
      else:
        guess = int(input("Take your guess at the combination between [1-1000]..."))
        guess_count += 1
      if guess in guesses_list :
        guess += one_o_one
        duplicate = False
      if guess in range(lower_bound,upper_bound):
        guesses_list.append(guess)
        break
      else:
        if duplicate == False:
          print("Invalid combination! Make sure combination isn't a duplicate...")
        else:
          if upper_bound == 1001:
            upper_bound -= 1
          print("Invalid combination! Make sure combination is within [" + str(lower_bound) + "-" + str(upper_bound) + "]...")
          int_invalid = True
    except ValueError:
      print("Invalid combination! Make sure combination only includes numbers...")

  valid_guesses += 1

  if guess_count == 1:
    if guess > combination:
      upper_bound = guess
    else:
      lower_bound = guess

  if guess == combination:
    print("The vault has opened... The jewels are yours!")
    safe_locked = False
    print("Total number of validated guesses required to gain access: " + str(valid_guesses))
    break
  else:
    if guess > combination:
      print("The combination is lower...")
    else:
      print("The combination is higher...")

  guesses_list.sort()
  y = np.array(guesses_list)
  x = combination
  lower,higher=y[y<x],y[y>x]

  if lower.size > 0 and higher.size > 0:
    lower_bound = lower[-1]
    upper_bound = higher[0]
    print("The combination is between [" + str(lower_bound) + "-" + str(upper_bound) + "]")

  if safe_locked == False:
    break
</code>```

How would I have this work on eg python anywhere using flask (maybe??)..

答: You could use Trinket.io to run it and then embed it into your own site using an iframe.</p>

Title: Run simple script on web page

Body:
I have made a simple game script that runs in the console. This game is in python 3.8. It's all been coded on repl.it and I want to run it on a url. I had a go with python anywhere but still struggled.

This is my code:

from random import randint
import numpy as np

print("The vault has been locked for the night...")
combination = randint(1,1000)

safe_locked = True
int_invalid = True
duplicate = True
guesses_list = list()
one_o_one = 1001
lower_bound = 0
upper_bound = 1001
guess_count = 0
valid_guesses = 0

while safe_locked == True:

  while int_invalid == True:
    try:
      if guess_count > 0:
        if upper_bound == 1001:
          upper_bound -= 1
        if lower_bound == 0:
          lower_bound += 1
        guess = int(input("Take your guess at the combination between [" + str(lower_bound) + "-" + str(upper_bound) + "]..."))
      else:
        guess = int(input("Take your guess at the combination between [1-1000]..."))
        guess_count += 1
      if guess in guesses_list :
        guess += one_o_one
        duplicate = False
      if guess in range(lower_bound,upper_bound):
        guesses_list.append(guess)
        break
      else:
        if duplicate == False:
          print("Invalid combination! Make sure combination isn't a duplicate...")
        else:
          if upper_bound == 1001:
            upper_bound -= 1
          print("Invalid combination! Make sure combination is within [" + str(lower_bound) + "-" + str(upper_bound) + "]...")
          int_invalid = True
    except ValueError:
      print("Invalid combination! Make sure combination only includes numbers...")

  valid_guesses += 1

  if guess_count == 1:
    if guess > combination:
      upper_bound = guess
    else:
      lower_bound = guess

  if guess == combination:
    print("The vault has opened... The jewels are yours!")
    safe_locked = False
    print("Total number of validated guesses required to gain access: " + str(valid_guesses))
    break
  else:
    if guess > combination:
      print("The combination is lower...")
    else:
      print("The combination is higher...")

  guesses_list.sort()
  y = np.array(guesses_list)
  x = combination
  lower,higher=y[y<x],y[y>x]

  if lower.size > 0 and higher.size > 0:
    lower_bound = lower[-1]
    upper_bound = higher[0]
    print("The combination is between [" + str(lower_bound) + "-" + str(upper_bound) + "]")

  if safe_locked == False:
    break

How would I have this work on eg python anywhere using flask (maybe??)..


问:
Converting Python Time to MicroPython PyBoard
I have a Python script controlling a Fibonacci clock that works great on the Raspberry Pi 4B, however, when I transfer the code to a PyBoard using MicroPython (which I'm completely new to) it doesn't work. Below is the part I believe to be the error.
...</p>

```<code>import datetime
import time
import sys

from time import sleep

while 1:
    t = datetime.datetime.now()
    hr = t.hour
    mn = t.minute

    if (hr==00) or (hr==12):
        hr = 12
        bulb1Red()
    else:
        bulb1White()

    mn5 = mn%5
    if (mn5 == 0):
        mn = mn/5
    else:
        mn = mn-mn5
        mn = mn/5
    if(hr > 12):
        hr = hr-12
</code>```

答: I managed to get the above effect using RTC and works great except even with a battery permanently connected to the Pyboard, I appear to lose an hour every night, which is pretty poor for a clock, thus I have gone back to using the Raspberry Pi. </p>

Body:
I have a Python script controlling a Fibonacci clock that works great on the Raspberry Pi 4B, however, when I transfer the code to a PyBoard using MicroPython (which I'm completely new to) it doesn't work. Below is the part I believe to be the error.
...

import datetime
import time
import sys

from time import sleep

while 1:
    t = datetime.datetime.now()
    hr = t.hour
    mn = t.minute

    if (hr==00) or (hr==12):
        hr = 12
        bulb1Red()
    else:
        bulb1White()

    mn5 = mn%5
    if (mn5 == 0):
        mn = mn/5
    else:
        mn = mn-mn5
        mn = mn/5
    if(hr > 12):
        hr = hr-12


问:
Recursive data in JSON object
```<code>{
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]
</code>```

}

OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:

["SERVICE_STATUS_PRESETS", "AIRCRAFT_ACTIVATION", "OUT_OF_SERVICE", "PROMO_CODES_REQUESTS", "BANNERS", "DOCUMENTS", "USER"]

I try recursive calls like this, though I only get last three records:

```<code>getRecursive() {
if (Array.isArray(data)) {
       for (let i = 0; i < data.length; i++) {
         if (data[i].subscriptions) {
           return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
         } else if (data[i].groups) {
           return this.getAllTopics(data[i].groups);
         }
       }
     }
     if (data && data.groups) {
      return this.getAllTopics(data.groups);
     }
     return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
}
</code>```

答:
EDIT: Added another way of doing it with .reduce()

You can create an empty array of topics and then navigate through your nested structure recursively, adding a topic each time you come across it, using the javascript .forEach() to cycle through any nested groups or subscriptions.

```<code>let topics = [];

let findTopics = obj => {
   if (obj.groups) {
      obj.groups.forEach(findTopics);
   }
   if (obj.subscriptions) {
      obj.subscriptions.forEach(findTopics);
   }
   if (obj.topic) {
      topics.push(obj.topic);
   }
}

findTopics(data);
</code>```

Or a possibly neater way using .reduce():

```<code>let findTopicsRecursive = (topics, obj) => {
   if (obj.groups) {
      topics = obj.groups.reduce(findTopicsRecursive, topics);
   }
   if (obj.subscriptions) {
      topics = obj.subscriptions.reduce(findTopicsRecursive, topics);
   }
   if (obj.topic) {
      topics.push(obj.topic);
   }
   return topics;
}

let findTopics = data => findTopicsRecursive([], data);

let topics = findTopics(data);
</code>```

Title: Recursive data in JSON object

Body:
{
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]

}

OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:

["SERVICE_STATUS_PRESETS", "AIRCRAFT_ACTIVATION", "OUT_OF_SERVICE", "PROMO_CODES_REQUESTS", "BANNERS", "DOCUMENTS", "USER"]

I try recursive calls like this, though I only get last three records:

getRecursive() {
if (Array.isArray(data)) {
       for (let i = 0; i < data.length; i++) {
         if (data[i].subscriptions) {
           return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
         } else if (data[i].groups) {
           return this.getAllTopics(data[i].groups);
         }
       }
     }
     if (data && data.groups) {
      return this.getAllTopics(data.groups);
     }
     return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
}

Body:
EDIT: Added another way of doing it with .reduce()

You can create an empty array of topics and then navigate through your nested structure recursively, adding a topic each time you come across it, using the javascript .forEach() to cycle through any nested groups or subscriptions.

let topics = [];

let findTopics = obj => {
   if (obj.groups) {
      obj.groups.forEach(findTopics);
   }
   if (obj.subscriptions) {
      obj.subscriptions.forEach(findTopics);
   }
   if (obj.topic) {
      topics.push(obj.topic);
   }
}

findTopics(data);

Or a possibly neater way using .reduce():

let findTopicsRecursive = (topics, obj) => {
   if (obj.groups) {
      topics = obj.groups.reduce(findTopicsRecursive, topics);
   }
   if (obj.subscriptions) {
      topics = obj.subscriptions.reduce(findTopicsRecursive, topics);
   }
   if (obj.topic) {
      topics.push(obj.topic);
   }
   return topics;
}

let findTopics = data => findTopicsRecursive([], data);

let topics = findTopics(data);


答:
You can't safely use globals in Basic Asm statements either; it happens to work with optimization disabled but it's not safe and you're abusing the syntax.

There's very little reason to ever use Basic Asm.  Even for machine-state control like asm("cli") to disable interrupts, you'd often want a "memory" clobber to order it wrt. loads / stores to globals.  In fact, GCC's https://gcc.gnu.org/wiki/ConvertBasicAsmToExtended page recommends never using Basic Asm because it differs between compilers, and GCC might change to treating it as clobbering everything instead of nothing (because of existing buggy code that makes wrong assumptions).  This would make a Basic Asm statement that uses push/pop even more inefficient if the compiler is also generating stores and reloads around it.

Basically the only use-case for Basic Asm is writing the body of an __attribute__((naked)) function, where data inputs/outputs / interaction with other code follows the ABI's calling convention, instead of whatever custom convention the constraints / clobbers describe for a truly inline block of code.

The design of GNU C inline asm is that it's text that you inject into the compiler's normal asm output (which is then fed to the assembler, as).  Extended asm makes the string a template that it can substitute operands into.  And the constraints describe how the asm fits into the data-flow of the program logic, as well as registers it clobbers.

Instead of parsing the string, there is syntax that you need to use to describe exactly what it does.  Parsing the template for var names would only solve part of the language-design problem that operands need to solve, and would make the compiler's code more complicated.  (It would have to know more about every instruction to know whether memory, register, or immediate was allowed, and stuff like that.  Normally its machine-description files only need to know how to go from logical operation to asm, not the other direction.)

Your Basic asm block is broken because you modify C variables without telling the compiler about it.  This could break with optimization enabled (maybe only with more complex surrounding code, but happening to work is not the same thing as actually safe.  This is why merely testing GNU C inline asm code is not even close to sufficient for it to be future proof against new compilers and changes in surrounding code).   There is no implicit "memory" clobber.  (Basic asm is the same as Extended asm except for not doing % substitution on the string literal.  So you don't need %% to get a literal % in the asm output.  It's implicitly volatile like Extended asm with no outputs.)

Also note that if you were targeting i386 MacOS, you'd need _result in your asm.  result only happens to work because the asm symbol name exactly matches the C variable name.  Using Extended asm constraints would make it portable between GNU/Linux (no leading underscore) vs. other platforms that do use a leading _.

Your Extended asm is broken because you modify an input ("c") (without telling the compiler that register is also an output, e.g. an output operand using the same register).
It's also inefficient: if a mov is the first or last instruction of your template, you're almost always doing it wrong and should have used better constraints.

Instead, you can do:

```<code>    asm ("imull %%edx, %%ecx\n\t"
          : "=c"(result)
          : "d"(data1), "c"(data2));
</code>```

Or better, use "+r"(data2) and "r"(data1) operands to give the compiler free choice when doing register allocation instead of potentially forcing the compiler to emit unnecessary mov instructions.  (See @Eric's answer using named operands and "=r" and a matching "0" constraint; that's equivalent to "+r" but lets you use different C names for the input and output.)

Look at the asm output of the compiler to see how code-gen happened around your asm statement, if you want to make sure it was efficient.

Since local vars don't have a symbol / label in the asm text (instead they live in registers or at some offset from the stack or frame pointer, i.e. automatic storage), it can't work to use symbol names for them in asm.

Even for global vars, you want the compiler to be able to optimize around your inline asm as much as possible, so you want to give the compiler the option of using a copy of a global var that's already in a register, instead of getting the value in memory in sync with a store just so your asm can reload that.

Having the compiler try to parse your asm and figure out which C local var names are inputs and outputs would have been possible.  (But would be a complication.)

But if you want it to be efficient, you need to figure out when x in the asm can be a register like EAX, instead of doing something braindead like always storing x into memory before the asm statement, and then replacing x with 8(%rsp) or whatever.  If you want to give the asm statement control over where inputs can be, you need constraints in some form.  Doing it on a per-operand basis makes total sense, and means the inline-asm handling doesn't have to know that bts can take an immediate or register source but not memory, for and other machine-specific details like that.  (Remember; GCC is a portable compiler; baking a huge amount of per-machine info into the inline-asm parser would be bad.)

(MSVC forces all C vars in _asm{} blocks to be memory.  It's impossible to use to efficiently wrap a single instruction because the input has to bounce through memory, even if you wrap it in a function so you can use the officially-supported hack of leaving a value in EAX and falling off the end of a non-void function.  What is the difference between 'asm', '__asm' and '__asm__'?  And in practice MSVC's implementation was apparently pretty brittle and hard to maintain, so much so that they removed it for x86-64, and it was documented as not supported in function with register args even in 32-bit mode!  That's not the fault of the syntax design, though, just the actual implementation.)

Clang does support -fasm-blocks for _asm { ... } MSVC-style syntax where it parses the asm and you use C var names.  It probably forces inputs and outputs into memory but I haven't checked.

Also note that GCC's inline asm syntax with constraints is designed around the same system of constraints that GCC-internals machine-description files use to describe the ISA to the compiler.   (The .md files in the GCC source that tell the compiler about an instruction to add numbers that takes inputs in "r" registers, and has the text string for the mnemonic.  Notice the "r" and "m" in some examples in https://gcc.gnu.org/onlinedocs/gccint/RTL-Template.html).

The design model of asm in GNU C is that it's a black-box for optimizer; you must fully describe the effects of the code (to the optimizer) using constraints.  If you clobber a register, you have to tell the compiler.  If you have an input operand that you want to destroy, you need to use a dummy output operand with a matching constraint, or a "+r" operand to update the corresponding C variable's value.

If you read or write memory pointed-to by a register input, you have to tell the compiler.  How can I indicate that the memory *pointed* to by an inline ASM argument may be used?

If you use the stack, you have to tell the compiler (but you can't, so instead you have to avoid stepping on the red-zone :/  Using base pointer register in C++ inline asm)  See also the inline-assembly tag wiki

GCC's design makes it possible for the compiler to give you an input in a register, and use the same register for a different output.  (Use an early-clobber constraint if that's not ok; GCC's syntax is designed to efficiently wrap a single instruction that reads all its inputs before writing any of its outputs.)

If GCC could only infer all of these things from C var names appearing in asm source, I don't think that level of control would be possible.  (At least not plausible.)  And there'd probably be surprising effects all over the place, not to mention missed optimizations.  You only ever use inline asm when you want maximum control over things, so the last thing you want is the compiler using a lot of complex opaque logic to figure out what to do.

(Inline asm is complex enough in its current design, and not used much compared to plain C, so a design that requires very complex compiler support would probably end up with a lot of compiler bugs.)

GNU C inline asm isn't designed for low-performance low-effort.  If you want easy, just write in pure C or use intrinsics and let the compiler do its job.  (And file missed-optimization bug reports if it makes sub-optimal code.)

Title: Why can't local variable be used in GNU C basic inline asm statements?

Body:
Why cannot I use local variables from main to be used in basic asm inline? It is only allowed in extended asm, but why so?

(I know local variables are on the stack after return address (and therefore cannot be used once the function return), but that should not be the reason to not use them)

And example of basic asm:

int a = 10; //global a
int b = 20; //global b
int result;

int main() {
    asm ( "pusha\n\t"
          "movl a, %eax\n\t"
          "movl b, %ebx\n\t"
          "imull %ebx, %eax\n\t"
          "movl %eax, result\n\t"
          "popa");

    printf("the answer is %d\n", result);
    return 0;
}

example of extended:

int main (void) {
    int data1 = 10;  //local var - could be used in extended
    int data2 = 20;
    int result;

    asm ( "imull %%edx, %%ecx\n\t"
          "movl %%ecx, %%eax"
          : "=a"(result)
          : "d"(data1), "c"(data2));

    printf("The result is %d\n",result);
    return 0;
}

Compiled with:
gcc -m32 somefile.c

platform:
uname -a:
Linux 5.0.0-32-generic #34-Ubuntu SMP Wed Oct 2 02:06:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

Body:
You can't safely use globals in Basic Asm statements either; it happens to work with optimization disabled but it's not safe and you're abusing the syntax.

There's very little reason to ever use Basic Asm.  Even for machine-state control like asm("cli") to disable interrupts, you'd often want a "memory" clobber to order it wrt. loads / stores to globals.  In fact, GCC's https://gcc.gnu.org/wiki/ConvertBasicAsmToExtended page recommends never using Basic Asm because it differs between compilers, and GCC might change to treating it as clobbering everything instead of nothing (because of existing buggy code that makes wrong assumptions).  This would make a Basic Asm statement that uses push/pop even more inefficient if the compiler is also generating stores and reloads around it.

Basically the only use-case for Basic Asm is writing the body of an __attribute__((naked)) function, where data inputs/outputs / interaction with other code follows the ABI's calling convention, instead of whatever custom convention the constraints / clobbers describe for a truly inline block of code.

The design of GNU C inline asm is that it's text that you inject into the compiler's normal asm output (which is then fed to the assembler, as).  Extended asm makes the string a template that it can substitute operands into.  And the constraints describe how the asm fits into the data-flow of the program logic, as well as registers it clobbers.

Instead of parsing the string, there is syntax that you need to use to describe exactly what it does.  Parsing the template for var names would only solve part of the language-design problem that operands need to solve, and would make the compiler's code more complicated.  (It would have to know more about every instruction to know whether memory, register, or immediate was allowed, and stuff like that.  Normally its machine-description files only need to know how to go from logical operation to asm, not the other direction.)

Your Basic asm block is broken because you modify C variables without telling the compiler about it.  This could break with optimization enabled (maybe only with more complex surrounding code, but happening to work is not the same thing as actually safe.  This is why merely testing GNU C inline asm code is not even close to sufficient for it to be future proof against new compilers and changes in surrounding code).   There is no implicit "memory" clobber.  (Basic asm is the same as Extended asm except for not doing % substitution on the string literal.  So you don't need %% to get a literal % in the asm output.  It's implicitly volatile like Extended asm with no outputs.)

Also note that if you were targeting i386 MacOS, you'd need _result in your asm.  result only happens to work because the asm symbol name exactly matches the C variable name.  Using Extended asm constraints would make it portable between GNU/Linux (no leading underscore) vs. other platforms that do use a leading _.

Your Extended asm is broken because you modify an input ("c") (without telling the compiler that register is also an output, e.g. an output operand using the same register).
It's also inefficient: if a mov is the first or last instruction of your template, you're almost always doing it wrong and should have used better constraints.

Instead, you can do:

    asm ("imull %%edx, %%ecx\n\t"
          : "=c"(result)
          : "d"(data1), "c"(data2));

Or better, use "+r"(data2) and "r"(data1) operands to give the compiler free choice when doing register allocation instead of potentially forcing the compiler to emit unnecessary mov instructions.  (See @Eric's answer using named operands and "=r" and a matching "0" constraint; that's equivalent to "+r" but lets you use different C names for the input and output.)

Look at the asm output of the compiler to see how code-gen happened around your asm statement, if you want to make sure it was efficient.

Since local vars don't have a symbol / label in the asm text (instead they live in registers or at some offset from the stack or frame pointer, i.e. automatic storage), it can't work to use symbol names for them in asm.

Even for global vars, you want the compiler to be able to optimize around your inline asm as much as possible, so you want to give the compiler the option of using a copy of a global var that's already in a register, instead of getting the value in memory in sync with a store just so your asm can reload that.

Having the compiler try to parse your asm and figure out which C local var names are inputs and outputs would have been possible.  (But would be a complication.)

But if you want it to be efficient, you need to figure out when x in the asm can be a register like EAX, instead of doing something braindead like always storing x into memory before the asm statement, and then replacing x with 8(%rsp) or whatever.  If you want to give the asm statement control over where inputs can be, you need constraints in some form.  Doing it on a per-operand basis makes total sense, and means the inline-asm handling doesn't have to know that bts can take an immediate or register source but not memory, for and other machine-specific details like that.  (Remember; GCC is a portable compiler; baking a huge amount of per-machine info into the inline-asm parser would be bad.)

(MSVC forces all C vars in _asm{} blocks to be memory.  It's impossible to use to efficiently wrap a single instruction because the input has to bounce through memory, even if you wrap it in a function so you can use the officially-supported hack of leaving a value in EAX and falling off the end of a non-void function.  What is the difference between 'asm', '__asm' and '__asm__'?  And in practice MSVC's implementation was apparently pretty brittle and hard to maintain, so much so that they removed it for x86-64, and it was documented as not supported in function with register args even in 32-bit mode!  That's not the fault of the syntax design, though, just the actual implementation.)

Clang does support -fasm-blocks for _asm { ... } MSVC-style syntax where it parses the asm and you use C var names.  It probably forces inputs and outputs into memory but I haven't checked.

Also note that GCC's inline asm syntax with constraints is designed around the same system of constraints that GCC-internals machine-description files use to describe the ISA to the compiler.   (The .md files in the GCC source that tell the compiler about an instruction to add numbers that takes inputs in "r" registers, and has the text string for the mnemonic.  Notice the "r" and "m" in some examples in https://gcc.gnu.org/onlinedocs/gccint/RTL-Template.html).

The design model of asm in GNU C is that it's a black-box for optimizer; you must fully describe the effects of the code (to the optimizer) using constraints.  If you clobber a register, you have to tell the compiler.  If you have an input operand that you want to destroy, you need to use a dummy output operand with a matching constraint, or a "+r" operand to update the corresponding C variable's value.

If you read or write memory pointed-to by a register input, you have to tell the compiler.  How can I indicate that the memory *pointed* to by an inline ASM argument may be used?

If you use the stack, you have to tell the compiler (but you can't, so instead you have to avoid stepping on the red-zone :/  Using base pointer register in C++ inline asm)  See also the inline-assembly tag wiki

GCC's design makes it possible for the compiler to give you an input in a register, and use the same register for a different output.  (Use an early-clobber constraint if that's not ok; GCC's syntax is designed to efficiently wrap a single instruction that reads all its inputs before writing any of its outputs.)

If GCC could only infer all of these things from C var names appearing in asm source, I don't think that level of control would be possible.  (At least not plausible.)  And there'd probably be surprising effects all over the place, not to mention missed optimizations.  You only ever use inline asm when you want maximum control over things, so the last thing you want is the compiler using a lot of complex opaque logic to figure out what to do.

(Inline asm is complex enough in its current design, and not used much compared to plain C, so a design that requires very complex compiler support would probably end up with a lot of compiler bugs.)

GNU C inline asm isn't designed for low-performance low-effort.  If you want easy, just write in pure C or use intrinsics and let the compiler do its job.  (And file missed-optimization bug reports if it makes sub-optimal code.)


问:
Does events like onClick in React pollute memory heap?
I was learning React and came across events like onCLick. Before that, I read an article saying that if we use addEventListener in pure JS then it can pollute memory heap thus we need to use removeEventListener() to ensure that there is no memory heap pollution. The question is "Is it the case with React?", that is, when we use onCLick or any other event in React, will any of them pollute the memory heap?</p>

答:
Yes. If you do not remove event listeners, they will keep listening.
A good place to add/remove them is componentDidMount / componentWillUnmount.</p>


问:
How can I create mock tags to test with NFC?
How can do i create ndef messages in byte form? I've read somewhere it need to have a special start/end byte, is it true?</p>

答: Not sure why you need the message in bytes, but once you created a NdefMessage you can call the toByteArray() method to return a byte array. Same is true for NdefRecord.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Configuring Log4j2 for multiple packages
This is my properties file.I have defined 2 packages here.I want logger across my whole application.What if i have 10-12 packages in my application.Is this the only approach??</p>

```<code>name=PropertiesConfig
property.filename =/myfolder
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{dd MMM yyyy HH:mm:ss} [%-5p] [%c] [%M] %x - %m%n
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/logs.txt
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=%d{dd MMM yyyy HH:mm:ss} [%-5p] [%c] [%M] %x - %m%n

loggers=file,myfile
logger.file.name=servlets
logger.file.level = debug,info
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

logger.myfile.name=com.util
logger.myfile.level = debug,info
logger.myfile.appenderRefs = file
logger.myfile.appenderRef.myfile.ref = LOGFILE

rootLogger.level =com.debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
</code>```

答:
First, your configuration doesn't look valid to me. You have

```<code>logger.myfile.name=com.util
logger.myfile.level = debug,info
logger.myfile.appenderRefs = file
logger.myfile.appenderRef.myfile.ref = LOGFILE

rootLogger.level =com.debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
</code>```

You cannot specify 2 levels on logger.myfile.level. Specifying debug will include all debug, info, warn, error and fatal events.

Secondly, you have rootLogger.level =com.debug. I would assume this should be rootLogger.level=debug?

To answer your question, yes you have to configure a logger for each pattern you want to match. However the Logger declaration can delegate some of its configuration to its parent. The only thing that is generally required is the level attribute.

So you could specify:

```<code>logger.a.name=com.util.marketing.sub1
logger.a.level=debug
logger.b.name=com.util.marketing.sub2
logger.b.level=error
logger.c.name=com.util.marketing
logger.c.level=info
logger.c.appenderRefs=file
logger.c.appenderRef.file=LOGFILE
</code>```

Personally, I prefer XML as I find it more concise and clearer. The above would be

```<code><Logger name="com.util.marketing.sub1" level="DEBUG"/>
<Logger name="com.util.marketing.sub2" level="ERROR"/>
<Logger name="com.util.marketing" level="INFO">
  <AppenderRef ref="LOGFILE"/>
</Logger>
</code>```

Body:
This is my properties file.I have defined 2 packages here.I want logger across my whole application.What if i have 10-12 packages in my application.Is this the only approach??

name=PropertiesConfig
property.filename =/myfolder
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{dd MMM yyyy HH:mm:ss} [%-5p] [%c] [%M] %x - %m%n
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/logs.txt
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=%d{dd MMM yyyy HH:mm:ss} [%-5p] [%c] [%M] %x - %m%n

loggers=file,myfile
logger.file.name=servlets
logger.file.level = debug,info
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

logger.myfile.name=com.util
logger.myfile.level = debug,info
logger.myfile.appenderRefs = file
logger.myfile.appenderRef.myfile.ref = LOGFILE

rootLogger.level =com.debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

Body:
First, your configuration doesn't look valid to me. You have

logger.myfile.name=com.util
logger.myfile.level = debug,info
logger.myfile.appenderRefs = file
logger.myfile.appenderRef.myfile.ref = LOGFILE

rootLogger.level =com.debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

You cannot specify 2 levels on logger.myfile.level. Specifying debug will include all debug, info, warn, error and fatal events.

Secondly, you have rootLogger.level =com.debug. I would assume this should be rootLogger.level=debug?

To answer your question, yes you have to configure a logger for each pattern you want to match. However the Logger declaration can delegate some of its configuration to its parent. The only thing that is generally required is the level attribute.

So you could specify:

logger.a.name=com.util.marketing.sub1
logger.a.level=debug
logger.b.name=com.util.marketing.sub2
logger.b.level=error
logger.c.name=com.util.marketing
logger.c.level=info
logger.c.appenderRefs=file
logger.c.appenderRef.file=LOGFILE

Personally, I prefer XML as I find it more concise and clearer. The above would be

<Logger name="com.util.marketing.sub1" level="DEBUG"/>
<Logger name="com.util.marketing.sub2" level="ERROR"/>
<Logger name="com.util.marketing" level="INFO">
  <AppenderRef ref="LOGFILE"/>
</Logger>


问:
Overload -> arrow operator in shared_ptr<interface> instance with no pure virtual destructor in interface
I'm trying to overload the -> operator to eventually execute something along the lines:

```<code>MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();
</code>```

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

```<code>#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}
</code>```

Output:

```<code>current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0
</code>```

To reiterate:
This code doesn't compile:

```<code>sharedPtrWrapper->Toggle();
</code>```

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

```<code>void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}
</code>```

答:
Use:

```<code>struct CleanupMyInterface {
  SomeTypeFromLib* somePointerFromLib = nullptr;
  void operator()( MyInterface* ptr ) const {
    if (somePointerFromLib && ptr)
      somePointerFromLib->releaseInterface(ptr);
  }
};
std::shared_ptr<MyInterface> sharedPtr( CreateAnInstanceOfAFromLibrary(), CleanupMyInterface{somePointerFromLib} );
</code>```

shared_ptr has type-erased destruction, there is no need for a virtual destructor.

Body:
I'm trying to overload the -> operator to eventually execute something along the lines:

MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}

Output:

current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0

To reiterate:
This code doesn't compile:

sharedPtrWrapper->Toggle();

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}

Body:
Use:

struct CleanupMyInterface {
  SomeTypeFromLib* somePointerFromLib = nullptr;
  void operator()( MyInterface* ptr ) const {
    if (somePointerFromLib && ptr)
      somePointerFromLib->releaseInterface(ptr);
  }
};
std::shared_ptr<MyInterface> sharedPtr( CreateAnInstanceOfAFromLibrary(), CleanupMyInterface{somePointerFromLib} );

shared_ptr has type-erased destruction, there is no need for a virtual destructor.


问:
How to spy on static data in C modules?

Suppose that I have a module which has some static data, If I want to spy on these values using a test file, Is there an elegant way to do that without using getters?

答:
Unit testing is one of the rare times it makes sense to directly include a .c file.  That will give you access to static functions and variables inside the module.

For example:

```<code>#include <string.h>
#include <assert.h>

#include "file_to_test.c"

int main()
{
    Module_Init();
    assert(strcmp(ModuleArray, "string_to_test") == 0);
}
</code>```

Title: How to spy on static data in C modules?

Body:
Unit testing is one of the rare times it makes sense to directly include a .c file.  That will give you access to static functions and variables inside the module.

For example:

#include <string.h>
#include <assert.h>

#include "file_to_test.c"

int main()
{
    Module_Init();
    assert(strcmp(ModuleArray, "string_to_test") == 0);
}