问:
How to locate the code location that causes the application to receive SIGTTIN under linux?
One of my c++ applications will hang after running for an indeterminate length of time, because it is not terminated, so it cannot be restarted by the parent process.

It is known that SIGTTIN can prevent the program from being suspended by nohup or by using </dev/null to redirect standard input, but this does not solve the problem fundamentally.

So, does anyone know how to debug or locate the location of the code that produces the SIGTTIN signal?

// this is a example, exec command to get SIGTTIN: ./a.out &
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int main(int argc, char* argv[]) {
        int len;
        char buf[64];

        while(1) {
                len = read(STDIN_FILENO, buf, 64);
                if (len > 0) {
                        write(STDOUT_FILENO, buf, len);
                }
                else {
                        perror("read");
                }
        }
        return 0;
}

```

答:
Thank everyone for your reply. The problem has been solved.

Sometimes I know the reason for SIGTTIN, but I can't locate the code that caused the error. For example, the program does not directly use scanf, read(0, ...), cin, ... system calls or library functions, which are more prominent when the program is larger or when using multiple threads.

Here's how to locate the code location that causes SIGTTIN:

Use ps to query the pid of your program (if you need to debug the thread, you can use ps -eLf to get tid).

Use strace -p $(YOUR PID) -e read to track the system call of the program. If necessary, add the -v option. If you want to track the process and all its sub-threads to locate the code, use  Strace -fp $(YOUR PID) -e read.When the program is executed in the background, all read(0, ..., ...) calls may cause SIGTTIN. According to the parameters or return values of read(0, ..., ...), the corresponding code can be found position.


来源: stackexchange

问:
Linq - how to convert this code to linq
My Linq-fu is not good enough to translate the following into hopefully one or two lines.</p>

```<code> var errors = new List<string>();
 foreach (var key in ModelState.Keys)
 {
   errors.Add(ModelState[key].Errors.FirstOrDefault().ErrorMessage);
 }

 return Json(new { success = false, errors = errors });
</code>```

答:
The closes translation (which is unsafe because FirstOrDefault() could return null in which case your code would throw a null reference exception) would be:

```<code>return Json(new { success = false,
                  errors = ModelState.Values
                      .Select(ms => ms.Errors.FirstOrDefault().ErrorMessage)
                      .ToList() });
</code>```

You could make it a bit safer using:

```<code>return Json(new {
    success = false,
    errors =
        ModelState.Values
                  .Select(ms =>
                          {
                              var error = ms.Errors.FirstOrDefault();
                              return error == null ? error.ErrorMessage : "";
                          })
                  .ToList() });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Linq - how to convert this code to linq

Body:
My Linq-fu is not good enough to translate the following into hopefully one or two lines.

 var errors = new List<string>();
 foreach (var key in ModelState.Keys)
 {
   errors.Add(ModelState[key].Errors.FirstOrDefault().ErrorMessage);
 }

 return Json(new { success = false, errors = errors });

Body:
The closes translation (which is unsafe because FirstOrDefault() could return null in which case your code would throw a null reference exception) would be:

return Json(new { success = false,
                  errors = ModelState.Values
                      .Select(ms => ms.Errors.FirstOrDefault().ErrorMessage)
                      .ToList() });

You could make it a bit safer using:

return Json(new {
    success = false,
    errors =
        ModelState.Values
                  .Select(ms =>
                          {
                              var error = ms.Errors.FirstOrDefault();
                              return error == null ? error.ErrorMessage : "";
                          })
                  .ToList() });


问:
Operator '<' cannot be applied to operands of type 'method group' and 'Type'
I'm trying to register automatically the classes for Dependency Injection in a loop instead of manually. However the method I'm using is not compiling.

Method that is working:

```<code>containerBuilder.RegisterType<MyClass>().As<IMyClass>();
</code>```

Method that doesn't compile:

```<code>List<Type> servicesList = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace.Services").Where(type => type.IsClass && !type.IsAbstract && !type.IsGenericType && !type.IsNested).ToList<Type>();
for (int i = 0; i < servicesList.Count; i++)
{
    containerBuilder.RegisterType<servicesList[i]>();
}
</code>```

The compiler throws this error message:

```<code>Operator '<' cannot be applied to operands of type 'method group' and 'Type'
</code>```

答:
You are using generic arguments incorrectly.

You can register by type

```<code>containerBuilder.RegisterType(servicesList[i]);
</code>```

Reference Reflection Components: Register by Type

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to register automatically the classes for Dependency Injection in a loop instead of manually. However the method I'm using is not compiling.

Method that is working:

containerBuilder.RegisterType<MyClass>().As<IMyClass>();

Method that doesn't compile:

List<Type> servicesList = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace.Services").Where(type => type.IsClass && !type.IsAbstract && !type.IsGenericType && !type.IsNested).ToList<Type>();
for (int i = 0; i < servicesList.Count; i++)
{
    containerBuilder.RegisterType<servicesList[i]>();
}

The compiler throws this error message:

Operator '<' cannot be applied to operands of type 'method group' and 'Type'

Body:
You are using generic arguments incorrectly.

You can register by type

containerBuilder.RegisterType(servicesList[i]);

Reference Reflection Components: Register by Type


问:
How to match string in between nth occurrence of whitespace and nth occurrence of comma?
I am editing in PL/SQL.

I have the following string

59 W Grand Ave Chicago, IL 60654

I need to match the string 'Chicago', and I can do that by matching everything in between the fourth space character, and the first comma character.  So far I have come up with:

```<code>(?<=\s)(.*)(?=,)
</code>```

However, even though that matches everything up to the comma, it starts from the first space character.  How can I start the match from the 4th space character instead?

I have tried (?<=\s){4}(.*)(?=,) but then it doesn't match anything.

答:
This expression would be slightly complicated. Let's maybe try another approach and maybe focus on the two letter State and swipe back to the word before which, using an expression similar to:

```<code>^.+?(\w+)[,\s]+?[A-Z]{2}.+$
</code>```

Demo 1

We can see that we would face problem if the City has more than one word. If, however, we would have a list of fixed words such as Ave, BLVD, ST right before the city, we could most likely come up with a better expression, such as:

```<code>^.+Ave\s+(.+?)[,\s]+?[A-Z]{2}.+$
</code>```

Demo 2

which we would expand it to:

```<code>^.+(Ave|Street|ST|BLVD)\s+(.+?)[,\s]+?[A-Z]{2}.+$
</code>```

Demo 3

RegEx Circuit

jex.im visualizes regular expressions:

Test

const regex = /^.+Ave\s+(.+?)[,\s]+?[A-Z]{2}.+$/gm;
const str = `59 W Grand Ave Chicago, IL 60654
59 E Grand Hotel Ave Chicago IL 60654
59 E George Washington Ave New York, NY 60654
59 E George Washington Ave San Diego CA 60654
59 E George Washington Ave St. Petersburg, CA 60654`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```

Body:
I am editing in PL/SQL.

I have the following string

59 W Grand Ave Chicago, IL 60654

I need to match the string 'Chicago', and I can do that by matching everything in between the fourth space character, and the first comma character.  So far I have come up with:

(?<=\s)(.*)(?=,)

However, even though that matches everything up to the comma, it starts from the first space character.  How can I start the match from the 4th space character instead?

I have tried (?<=\s){4}(.*)(?=,) but then it doesn't match anything.

Body:
This expression would be slightly complicated. Let's maybe try another approach and maybe focus on the two letter State and swipe back to the word before which, using an expression similar to:

^.+?(\w+)[,\s]+?[A-Z]{2}.+$

Demo 1

We can see that we would face problem if the City has more than one word. If, however, we would have a list of fixed words such as Ave, BLVD, ST right before the city, we could most likely come up with a better expression, such as:

^.+Ave\s+(.+?)[,\s]+?[A-Z]{2}.+$

Demo 2

which we would expand it to:

^.+(Ave|Street|ST|BLVD)\s+(.+?)[,\s]+?[A-Z]{2}.+$

Demo 3

RegEx Circuit

jex.im visualizes regular expressions:

Test

const regex = /^.+Ave\s+(.+?)[,\s]+?[A-Z]{2}.+$/gm;
const str = `59 W Grand Ave Chicago, IL 60654
59 E Grand Hotel Ave Chicago IL 60654
59 E George Washington Ave New York, NY 60654
59 E George Washington Ave San Diego CA 60654
59 E George Washington Ave St. Petersburg, CA 60654`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);


问:
Dereference a pointer in specific case
Can anyone tell me why this piece of code does not work? It always says segmentation fault

```<code>int main()
{
    int a = 10;
    int b = (int)&a;
    int *c = (int*)b;
    printf("%d", *c);

    return 0;
}
</code>```

When I print the value of c, it is the address of a as I expect, but when I deference it, a segmentation fault happens. Assume that this is a 32bit compiler.

答:
Sometimes it will work and sometimes do not , it depends on your machine , maybe the size of integer is less than the size of the pointer in your machine , so if the address that's casted and assigned to integer is larger than the size of int ,it will overflow and the integer will hold an incorrect address so the output will give segmentation fault.

Note

you can check the size of the type using sizeof function.

```<code>size_t a,b;
a=sizeof(int);
b=sizeof(int*);
if(a>=b)
printf("Valid assignment with no errors\n);
else
printf("This may cause an error if the address is larger than integer size\n);
</code>```

Title: Dereference a pointer in specific case

Body:
Can anyone tell me why this piece of code does not work? It always says segmentation fault

int main()
{
    int a = 10;
    int b = (int)&a;
    int *c = (int*)b;
    printf("%d", *c);

    return 0;
}

When I print the value of c, it is the address of a as I expect, but when I deference it, a segmentation fault happens. Assume that this is a 32bit compiler.

Body:
Sometimes it will work and sometimes do not , it depends on your machine , maybe the size of integer is less than the size of the pointer in your machine , so if the address that's casted and assigned to integer is larger than the size of int ,it will overflow and the integer will hold an incorrect address so the output will give segmentation fault.

Note

you can check the size of the type using sizeof function.

size_t a,b;
a=sizeof(int);
b=sizeof(int*);
if(a>=b)
printf("Valid assignment with no errors\n);
else
printf("This may cause an error if the address is larger than integer size\n);


问:
How to redirect http:// to https:// like firebase hosting
Firebase hosting already had https:// redirects, in the firebase.json. I have an Angular app, and to prepare for SSR, I migrated from firebase hosting to Cloud Run. At first I didn't know whether I was supposed to mess with Angular Universal or something to do this, I seen a similar question on here but it was answered with Nginx, which is not what I need.

I tried to do really dumb things with the server.ts file and that was not the answer at all. I honestly do not know exactly where to start. I have scoured google for the answer, including of google cloud run docs here:

https://cloud.google.com/run/docs/authenticating/public

but I have no idea where to go from here.

答:
The Cloud Run Front-end handles both HTTP and HTTPS. From Cloud Run to your software running inside the container is over HTTP port 8080 (the current default port that might change).

Since your code is running HTTP, you need to detect the HTTP headers that Cloud Run includes with requests. This header is x-forwarded-proto. This header tells you what protocols the client is using to connect to the Cloud Run Front-end. If the protocol is HTTP, then your software needs to send a redirect (HTTP 301) to the correct URI.

The following code snipped with read the Request Headers, check x-forwarded-proto for HTTP and redirect if True.

```<code>if (req.headers['x-forwarded-proto'] != 'https')
    res.redirect('https://' + req.hostname + req.url)
</code>```

Body:
The Cloud Run Front-end handles both HTTP and HTTPS. From Cloud Run to your software running inside the container is over HTTP port 8080 (the current default port that might change).

Since your code is running HTTP, you need to detect the HTTP headers that Cloud Run includes with requests. This header is x-forwarded-proto. This header tells you what protocols the client is using to connect to the Cloud Run Front-end. If the protocol is HTTP, then your software needs to send a redirect (HTTP 301) to the correct URI.

The following code snipped with read the Request Headers, check x-forwarded-proto for HTTP and redirect if True.

if (req.headers['x-forwarded-proto'] != 'https')
    res.redirect('https://' + req.hostname + req.url)


问:
Java program to write csv is going to next tab
HiExperts

I am writing simple write csv program in java and I would need to have 3 headers and values in next row for each header. basically the content needs to go 2 next tab. but it working instead its writing in same cell.

```<code>            try {
                File file =new File("C:\\test\\working.csv");

                System.out.println("create new file"+(int)file.length());
                if(!file.exists()){
                    file.createNewFile();
                }
                FileWriter fw = new FileWriter(file,true);

            // No need give the headers Like: id, Name on builder.append
                BufferedWriter bw = new BufferedWriter(fw);
                PrintWriter pw = new PrintWriter(bw);
                if((int)file.length()==0) {
                String header = "Name"+'\t' +"Desc"+'\t'+"check"+'\t';
                bw.write(header);
                }
                bw.append('\n');
                bw.write("test");
                bw.append('\t');
                bw.write("happy");
                bw.append('\t');
                bw.write("working");
                bw.close();
                System.out.println("Data successfully appended at the end of file");

            }
</code>```

I have provided the sample code. I used /t. but still its writing i same cell.

I need 3 header and 3 values in next row. can someone please assist here and let me knw what is missing, Thanks

答:
You're creating a TSV (tab-separated value) file, not a CSV (comma-separated value) file.

If you open it in your spreadsheet application, you need to import it as a TSV file or indicate that the tab character is used as a value-separator.

Body:
HiExperts

I am writing simple write csv program in java and I would need to have 3 headers and values in next row for each header. basically the content needs to go 2 next tab. but it working instead its writing in same cell.

            try {
                File file =new File("C:\\test\\working.csv");

                System.out.println("create new file"+(int)file.length());
                if(!file.exists()){
                    file.createNewFile();
                }
                FileWriter fw = new FileWriter(file,true);

            // No need give the headers Like: id, Name on builder.append
                BufferedWriter bw = new BufferedWriter(fw);
                PrintWriter pw = new PrintWriter(bw);
                if((int)file.length()==0) {
                String header = "Name"+'\t' +"Desc"+'\t'+"check"+'\t';
                bw.write(header);
                }
                bw.append('\n');
                bw.write("test");
                bw.append('\t');
                bw.write("happy");
                bw.append('\t');
                bw.write("working");
                bw.close();
                System.out.println("Data successfully appended at the end of file");

            }

I have provided the sample code. I used /t. but still its writing i same cell.

I need 3 header and 3 values in next row. can someone please assist here and let me knw what is missing, Thanks


问:
What is the difference between applying batch norm in DNN vs. using just weights and bias?
Batch Norm is a set of operations applied to each layers' input value. It has the advantage of speedup the learning of network and introducing noise in each layer.

The operation can be summarized as follow :

$$\mu = frac{1}{m} \sum{z^{(i)}}$$

$$\sigma^2 = \frac{1}{m} \sum{(z^{(i)} - \mu)^2}$$

$$z^{(i)}_{norm} = \frac{z^{(i)} - \mu}{\sqrt{\sigma^2 + \epsilon}}$$

$$\tilde z^{(i)} = \gamma z^{(i)}_{norm} + \beta$$

The $\gamma, \beta$ are just scalar parameters that multiplied to the input value of each layer. Weights and bias at that layer does the same thing. What are the differences between them.

Is adding new learnable parameter $\gamma, \beta$ trying to achieve the same effect of doubling the hidden layer in neural network ?

答: batch norm is normalizing the input each mini batch, otherwise, it doesn't.</p>


问:
Mongo DB Atlas. Is it safe to whitelist all ip because someone attempting to access the database needs a password
I have a google app engine with my express server. I also have my db in MongoDB Atlas. I currently have my MongoDB Atlas whitelisting all ip. The connection string is in the code for my express server running on Google Cloud. Presumable any attacker trying to get into the database would still need a user name and password for the connection string.

Is it safe to do this?

If it's not safe, then how do I whitelist my google app engine on Mongo Atlas?

答:
Is it safe to do this?

"Safe" is a relative term. It is safer than having an unauthed database open to the internet, but the weakest link is now your password.

A whitelist is an additional layer of security, so that if someone knows or can guess your password, they can't just connect from anywhere. They must be connecting from a set of known IP addresses. This makes the attack surface smaller, so the database is less likely to be broken into by a random person in the internet.

If it's not safe, then how do I whitelist my google app engine on Mongo Atlas?

You would need to determine the IP ranges of your application, and plug in that range into the whitelist.


问:
How to use default csrf-token from AJAX request in Laravel
I'm using Vuejs and I want to make an secure AJAX request (with axios) to my laravel server, but I think that CSRF protections doesn't work because I change the token of the frontend part and even then I can interact with the database.

I read that Laravel come with a file named [bootstrap.js] (https://laravel.com/docs/5.8/csrf#csrf-introduction) it is assumed that this file does this task by default, but it doesn't work for me. I think it's beacuse webpack doens't load the file when I run npm run watch but I don't know how to load it,

I searched for an answer but I only find Bootstrap tutorials :/

答:
In head:

```<code><meta name="csrf-token" content="{{ csrf_token() }}">
</code>```

In ajax:

```<code>window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content');
};

</code>```

Body:
In head:

<meta name="csrf-token" content="{{ csrf_token() }}">

In ajax:

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content');
};


问:
AWS ECS: Run Tasks Failed Reasons : ["ATTRIBUTE"]
While trying to run a task in EC2 instances, I get this terrible error message.

```<code>Run tasks failed
Reasons : ["ATTRIBUTE"]
</code>```

Like many others, I was referred to check out the "requiresAttributes" section of my task where I found this list:

```<code>  "requiresAttributes": [
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-ecr-pull"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.task-eni"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.ecr-auth"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.task-iam-role"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-awslogs"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
    }
  ]
</code>```

While trying to added these seemingly useless attributes to my cluster's instances, I am blocked. The AWS console says that certain prefixes like ecs are not allowed to be customized/added.

How does one match the attributes when the platform doesn't allow it?

I've also researched into creating instances with different AMIs, but Amazon ECS doesn't allow this and simply defaults with their most recent.

Amazon ECS is a really cool product, but this reflects some of its immaturity. I actually went into ECS from a beanstalk background hoping that the professional suite would be as promised to orchestrate containers. Instead, I have a handful of reasonable complaints after using it for 3 hours!

答:
I ran into this same situation trying to run a Windows docker container in ECS.

In my case, the task definition showed the following required attributes:

Describing the ECS instance with aws ecs describe-container-instances --cluster=ClusterName --container-instances arn:<rest of the instance arn> showed that they were missing the ecs.capability.execution-role-awslogs and com.amazonaws.ecs.capability.logging-driver.awslogs attributes.

The solution was documented at https://github.com/aws/amazon-ecs-agent/issues/1395, and was to set the ECS_ENABLE_AWSLOGS_EXECUTIONROLE_OVERRIDE environment variable to True with the command [Environment]::SetEnvironmentVariable("ECS_ENABLE_AWSLOGS_EXECUTIONROLE_OVERRIDE",
$TRUE, "Machine"). Once the Amazon ECS service was restarted, I could deploy my tasks.

So depending on your situation you may find there is some override that you can apply to give your ECS instances the attributes they require.

Body:
While trying to run a task in EC2 instances, I get this terrible error message.

Run tasks failed
Reasons : ["ATTRIBUTE"]

Like many others, I was referred to check out the "requiresAttributes" section of my task where I found this list:

  "requiresAttributes": [
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-ecr-pull"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.task-eni"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.ecr-auth"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.task-iam-role"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-awslogs"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
    }
  ]

While trying to added these seemingly useless attributes to my cluster's instances, I am blocked. The AWS console says that certain prefixes like ecs are not allowed to be customized/added.

How does one match the attributes when the platform doesn't allow it?

I've also researched into creating instances with different AMIs, but Amazon ECS doesn't allow this and simply defaults with their most recent.

Amazon ECS is a really cool product, but this reflects some of its immaturity. I actually went into ECS from a beanstalk background hoping that the professional suite would be as promised to orchestrate containers. Instead, I have a handful of reasonable complaints after using it for 3 hours!


问:
I can await fs.readdir but I don't know why
https://github.com/SimulatedGREG/electron-vue

I used this template to make electron.

And I am using this library.

https://www.npmjs.com/package/fs-extra

https://nodejs.org/docs/latest-v11.x/api/fs.html

By this document, I can write like this.

```<code>await fs.readdir
</code>```

But the electron template, it is using electron@2.0.4 and which is using node@8.9.3.

So I checked here.

https://nodejs.org/docs/latest-v8.x/api/fs.html

It looks like the function doesn't return promise.

But I actually can await fs functions using fs-extra in electron@2.0.4.

Both develop and build.

Why is this?

result of

```<code>console.log(fs.readdir())
</code>```

Is like below.

It's Promise.

But I don't know why I can do this in electron@2.0.4.

答:
Sorry, I am not good at English.

And, I am a beginner web developer.

This is just an anticipation.

I saw package.json of "fs-extra".

And I could not find "fs" inside that.

It is using a library called "graceful-fs", but this library does not require "fs" neither.

Maybe, "fs-extra" is not relevant to "fs".

And it has own logic that is already promisified even in node lower than verstion10.

Any one know the truth?

Body:
https://github.com/SimulatedGREG/electron-vue

I used this template to make electron.

And I am using this library.

https://www.npmjs.com/package/fs-extra

https://nodejs.org/docs/latest-v11.x/api/fs.html

By this document, I can write like this.

await fs.readdir

But the electron template, it is using electron@2.0.4 and which is using node@8.9.3.

So I checked here.

https://nodejs.org/docs/latest-v8.x/api/fs.html

It looks like the function doesn't return promise.

But I actually can await fs functions using fs-extra in electron@2.0.4.

Both develop and build.

Why is this?

result of

console.log(fs.readdir())

Is like below.

It's Promise.

But I don't know why I can do this in electron@2.0.4.


问:
Removing Wordpress code from footer that uses do_action
I am reading documentation on how to remove sections/content of a parent theme that uses do_action('action_name') from my child theme. As much as I think I understand it, it is still not working. All I am trying to do at the moment is remove the footer parent theme copyright section in my child theme. I have the action name and the parent function that calls it. I can add content to the footer but I can not remove what is currently there.

I have looked through my theme parent theme files and construction_base_footer_copyright is indeed what calls the footer info I am trying to remove. I don't understand what I am doing wrong. Thanks for any help you can give.

I don't understand what I am doing wrong. Thanks for your help.

** Parent Theme Footer.php **

```<code><?php
  /**
   * Hook - construction_base_action_footer.
   *
   * @hooked construction_base_footer_copyright - 10
   */
  do_action( 'construction_base_action_footer' );
?>
<?php wp_footer(); ?>
</body>
</html>
</code>```

Child Theme Functions.php

```<code>add_action('construction_base_action_footer', 'action_name');

function action_name() {
  remove_action( 'construction_base_action_footer', 'construction_base_footer_copyright', 10 );
  echo "<p>Additional text</p>";
}
</code>```

答:
What is happening is that, because your hook and the parent's hook have the same priority (10), your remove_action is not happening fast enough, before the parent's hook triggers. You have a couple options here to fix this.

A) Up the priority of your own function so that remove_action happens before the copyright triggers. Change:

add_action('construction_base_action_footer', 'action_name');
```

<p>to:</p>

<pre class="lang-php prettyprint-override"><code>add_action('construction_base_action_footer', 'action_name', 1);
</code>```

That should be enough to fix it, but is not really a "best practices" approach.

B) You could just change the call to the action in footer.php. Copy the file to your child theme directory, and remove the do_action('construction_base_action_footer'); line entirely and replace it with whatever content you want, or change it to call your own custom action function with a different action name. Either of these is a much better approach than option A.

Body:
I am reading documentation on how to remove sections/content of a parent theme that uses do_action('action_name') from my child theme. As much as I think I understand it, it is still not working. All I am trying to do at the moment is remove the footer parent theme copyright section in my child theme. I have the action name and the parent function that calls it. I can add content to the footer but I can not remove what is currently there.

I have looked through my theme parent theme files and construction_base_footer_copyright is indeed what calls the footer info I am trying to remove. I don't understand what I am doing wrong. Thanks for any help you can give.

I don't understand what I am doing wrong. Thanks for your help.

** Parent Theme Footer.php **

<?php
  /**
   * Hook - construction_base_action_footer.
   *
   * @hooked construction_base_footer_copyright - 10
   */
  do_action( 'construction_base_action_footer' );
?>
<?php wp_footer(); ?>

Child Theme Functions.php

add_action('construction_base_action_footer', 'action_name');

function action_name() {
  remove_action( 'construction_base_action_footer', 'construction_base_footer_copyright', 10 );
  echo "
Additional text
";
}

Body:
What is happening is that, because your hook and the parent's hook have the same priority (10), your remove_action is not happening fast enough, before the parent's hook triggers. You have a couple options here to fix this.

A) Up the priority of your own function so that remove_action happens before the copyright triggers. Change:

add_action('construction_base_action_footer', 'action_name');

to:

add_action('construction_base_action_footer', 'action_name', 1);

That should be enough to fix it, but is not really a "best practices" approach.

B) You could just change the call to the action in footer.php. Copy the file to your child theme directory, and remove the do_action('construction_base_action_footer'); line entirely and replace it with whatever content you want, or change it to call your own custom action function with a different action name. Either of these is a much better approach than option A.


问:
How can I secure an ASP .NET website that already uses Forms authentication?
I've got an ASP .NET website which uses Forms authentication to secure certain parts of the site. We have a test version of the site on a server and are making it available to partners over the web, e.g. at test.mydomain.com.

I need to secure all parts of the site so that only our partners can use it. Ideally it would be nice to have basic authentication pop up when they first hit the site, then have it work as normal thereafter, i.e. forms auth for certain areas.

However it seems ASP .NET and IIS don't support this. I'm aware of MADAM but that achieves something slightly different to what I need.

I'm considering restricting access by IP but that has two drawbacks, one it requires parters to "sign up" with their IP, and two, their IP could change.

Does anyone else have any suggestions?

答:
Assuming your site implements roles, you can block access using traditional forms authentication and the location attributes. Something like:

```<code><configuration>
 <location path="Testing">
  <system.web>
     <authorization>
        <allow roles="partners" />
        <deny users="*" />
     </authorization>
  </system.web>
 </location>
</configuration>
</code>```

You would then need to make sure all of the users that need access to that part of the site were in the partners role.

Body:
Assuming your site implements roles, you can block access using traditional forms authentication and the location attributes. Something like:

<configuration>
 <location path="Testing">
  <system.web>
     <authorization>
        <allow roles="partners" />
        <deny users="*" />
     </authorization>
  </system.web>
 </location>
</configuration>

You would then need to make sure all of the users that need access to that part of the site were in the partners role.


问:
How can GHC convert a polymorphic numeric literal into an arbitrary type with an instance of Num?
As far as I can tell, GHC can convert any numeric literal with default polymorphic type Num a => a into any type with an instance of Num. I'd like to know whether this is true and a little about the underlying mechanism.

To explore this, I have written a datatype called MySum which replicates (part of) the functionality of Sum from Data.Monoid. The most important part is that it contains instance Num a => Num (MySum a).

Note - This just so happens to be where my question go its start. The Monoid is not specifically relevant. I've included a portion of that code at the bottom of this question, just in case it is useful for an answer to refer to the contents.

It seems that GHCi will happily comply with an input of the form "v :: MySum t", under the following conditions:

v is a polymorphic value of type Num a => a

t is a (possibly polymorphic) type under Num

As far as I can tell, the only numeric literals compatible with the type Num a => a are ones that look like integers. Is this always the case? It seems to imply that a value can instantiated to any type under Num exactly when that value is integral. If this is correct, then I understand how something like 5 :: MySum Int might work, given the function fromInteger in Num.

With all of that said, I can't figure out how something like this works:

```<code>*Main Data.Monoid> 5 :: Fractional a => MySum a
MySum {getMySum = 5.0}
</code>```

If it's possible to explain this in a novice-friendly way, I would appreciate it.

The instance Num a => Num (MySum a), as promised:

```<code>import Control.Applicative

newtype MySum a = MySum {getMySum :: a}
  deriving Show

instance Functor MySum where
  fmap f (MySum a) = MySum (f a)

instance Applicative MySum where
  pure = MySum
  (MySum f) <*> (MySum a) = MySum (f a)

instance Num a => Num (MySum a) where
  (+) = liftA2 (+)
  (-) = liftA2 (-)
  (*) = liftA2 (*)
  negate = fmap negate
  abs = fmap abs
  signum = fmap signum
  fromInteger = pure . fromInteger
</code>```

答:
As you have found out, the integer literal 5 amounts to:

```<code>fromInteger 5
</code>```

As the type of fromInteger is Num a => Integer -> a, you can instantiate 5 to the Num instance of your choice, be it Int, Double, MySum Double, or anything else. In particular, given that Fractional is a subclass of Num, and that you wrote a Num a => Num (MySum a) instance, 5 :: Fractional a => MySum a works just fine:

```<code>5 :: Fractional a => MySum a
fromInteger 5 :: Fractional a => MySum a
(pure . fromInteger) 5 :: Fractional a => MySum a
MySum (fromInteger 5 :: Fractional a => a)
</code>```

It seems to imply that a value can instantiated to any type under Num exactly when that value is integral.

Things get a little subtle here. An integral value can be converted to any type under Num (via fromInteger and, in the general case, fromIntegral). We can instantiate an integer literal like 5 as anything under Num because GHC handles the conversion for us, by desugaring it to fromInteger 5 :: Num a => a. However, we can't instantiate the monomorphic value 5 :: Integer as a Double, nor can we instantiate 5 :: Integral a => a to a non-Integral type like Double. In those two cases, the type annotations further restrict the type, so that we have to perform the conversion explicitly if we want a Double.

Body:
As far as I can tell, GHC can convert any numeric literal with default polymorphic type Num a => a into any type with an instance of Num. I'd like to know whether this is true and a little about the underlying mechanism.

To explore this, I have written a datatype called MySum which replicates (part of) the functionality of Sum from Data.Monoid. The most important part is that it contains instance Num a => Num (MySum a).

Note - This just so happens to be where my question go its start. The Monoid is not specifically relevant. I've included a portion of that code at the bottom of this question, just in case it is useful for an answer to refer to the contents.

It seems that GHCi will happily comply with an input of the form "v :: MySum t", under the following conditions:

v is a polymorphic value of type Num a => a

t is a (possibly polymorphic) type under Num

As far as I can tell, the only numeric literals compatible with the type Num a => a are ones that look like integers. Is this always the case? It seems to imply that a value can instantiated to any type under Num exactly when that value is integral. If this is correct, then I understand how something like 5 :: MySum Int might work, given the function fromInteger in Num.

With all of that said, I can't figure out how something like this works:

*Main Data.Monoid> 5 :: Fractional a => MySum a
MySum {getMySum = 5.0}

If it's possible to explain this in a novice-friendly way, I would appreciate it.

The instance Num a => Num (MySum a), as promised:

import Control.Applicative

newtype MySum a = MySum {getMySum :: a}
  deriving Show

instance Functor MySum where
  fmap f (MySum a) = MySum (f a)

instance Applicative MySum where
  pure = MySum
  (MySum f) <*> (MySum a) = MySum (f a)

instance Num a => Num (MySum a) where
  (+) = liftA2 (+)
  (-) = liftA2 (-)
  (*) = liftA2 (*)
  negate = fmap negate
  abs = fmap abs
  signum = fmap signum
  fromInteger = pure . fromInteger

Body:
As you have found out, the integer literal 5 amounts to:

fromInteger 5

As the type of fromInteger is Num a => Integer -> a, you can instantiate 5 to the Num instance of your choice, be it Int, Double, MySum Double, or anything else. In particular, given that Fractional is a subclass of Num, and that you wrote a Num a => Num (MySum a) instance, 5 :: Fractional a => MySum a works just fine:

5 :: Fractional a => MySum a
fromInteger 5 :: Fractional a => MySum a
(pure . fromInteger) 5 :: Fractional a => MySum a
MySum (fromInteger 5 :: Fractional a => a)

It seems to imply that a value can instantiated to any type under Num exactly when that value is integral.

Things get a little subtle here. An integral value can be converted to any type under Num (via fromInteger and, in the general case, fromIntegral). We can instantiate an integer literal like 5 as anything under Num because GHC handles the conversion for us, by desugaring it to fromInteger 5 :: Num a => a. However, we can't instantiate the monomorphic value 5 :: Integer as a Double, nor can we instantiate 5 :: Integral a => a to a non-Integral type like Double. In those two cases, the type annotations further restrict the type, so that we have to perform the conversion explicitly if we want a Double.


问:
what follows after clustering
I am trying to cluster images based on their similarities with SIFT and Affinity Propagation, I did the clustering but I just don't want to visualize the results. How can I test with a random image from the obtained labels? Or maybe there's more to it?

Other than data visualization, I just don't know what follows after clustering. How do I verify the 'clustering'

答: since clustering is unsupervised, there isn't an objective way to evaluate it. Typically, you just observe and see if there is some features for a certain cluster. </p>

Title: what follows after clustering


问:
How to get last sunday's date from today's date using shell script?
I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date.  I tried this,

```<code>a=`date -dlast-sunday +%Y%m%d`
</code>```

but this gives a date of Sunday before the last one.

答:
You can do that simply with the date command itself using the date -d option where:

```<code>date -d "today - $(date -d today +"%u") days"
</code>```

Where you would pass whatever date you like as today (which is used as an example) and it will give the date of the previous Sunday. It does so by subtracting the current day of the week (date -d today +"%u") number of days from the given date (today in the example). You can use an if before checking if [ "$(date -d today +"%u")" -eq '7' ]; then date; else ... fi to simply output the current date if today is Sunday.

Example

```<code>$ date -d "today - $(date -d today +"%u") days"
Sun May 26 23:04:44 CDT 2019
</code>```

Body:
I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date.  I tried this,

a=`date -dlast-sunday +%Y%m%d`

but this gives a date of Sunday before the last one.

Body:
You can do that simply with the date command itself using the date -d option where:

date -d "today - $(date -d today +"%u") days"

Where you would pass whatever date you like as today (which is used as an example) and it will give the date of the previous Sunday. It does so by subtracting the current day of the week (date -d today +"%u") number of days from the given date (today in the example). You can use an if before checking if [ "$(date -d today +"%u")" -eq '7' ]; then date; else ... fi to simply output the current date if today is Sunday.

Example

$ date -d "today - $(date -d today +"%u") days"
Sun May 26 23:04:44 CDT 2019


问:
Implementation of Worker inside Clean Swift Architecture
I'm developing a new project from scratch and there are some concepts about this architecture that I would like to implement in the best way.

In many references on the Internet I can see some examples to deal with Clean Swift Architecture. In this architecture you can find that Interactor has a dependency of Worker classes

```<code>   protocol InteractorLogic {
     // Functions
   }

   class Interactor: InteractorLogic {
     var presenter: PresenterLogic?
     var worker: AWorker?
   }
</code>```

The doubt I have is about implementing this Worker because I saw in some examples that inside this Worker they put all the "use cases" related to the scene:

```<code>    protocol SceneWorkerLogic {

     func getPosts(success: ((Posts) -> Void), error: ((Error) -> Void)))
     func getUser(success: ((User) -> Void), error: ((Error) -> Void)))

   }

   class SceneWorker {

     func getPosts(success: ((Posts) -> Void), error: ((Error) -> Void))) {

     }

     func getUser(success: ((User) -> Void), error: ((Error) -> Void))) {

     }
   }

</code>```

and in another examples, they divide functionality in different Workers like UserWorker and PostWorker where CRUD functions related with Users and Posts are implemented:

```<code>   protocol PostWorkerLogic {

     func getPosts(success: ((Posts) -> Void), error: ((Error) -> Void)))

   }

   class PostWorker {

     func getPosts(success: ((Posts) -> Void), error: ((Error) -> Void))) {

     }

   }
</code>```

I consider that the second approach is better in terms of Clean Code but I've realized that it could be even cleaner if we use a file for a single CRUD operation like getUser or getPosts.

How can I improve this?

答:
There are a lot of ways to do! The way that was showed on the clean swift book isn't my favorite...

I prefer to use workers with dependency injections to use as a facade pattern to get the data! Doing this you will have the scene worker and specific workers to do the jobs.

Example: You have a scene that present a list of movies. This list could be fetched from network or coredata so you will have a worker that receive the kind of datasource that you will use on its init method and implements a protocol with the method getMovies and this will be the scene worker! Then you will have other worker to get this from network and another one for coredata, both of them must to implement that protocol with getMovies!

I think that will be better if you get a sample app that i built from scratch using this architecture to understand it better! I really think that this way is much better than the way that he uses on his clean swift sample app (clean store).

Here is my sample app using clean swift: https://github.com/chavitos/TheMovieDB

Body:
I'm developing a new project from scratch and there are some concepts about this architecture that I would like to implement in the best way.

In many references on the Internet I can see some examples to deal with Clean Swift Architecture. In this architecture you can find that Interactor has a dependency of Worker classes

   protocol InteractorLogic {
     // Functions
   }

   class Interactor: InteractorLogic {
     var presenter: PresenterLogic?
     var worker: AWorker?
   }

The doubt I have is about implementing this Worker because I saw in some examples that inside this Worker they put all the "use cases" related to the scene:

    protocol SceneWorkerLogic {

     func getPosts(success: ((Posts) -> Void), error: ((Error) -> Void)))
     func getUser(success: ((User) -> Void), error: ((Error) -> Void)))

   }

   class SceneWorker {

     func getPosts(success: ((Posts) -> Void), error: ((Error) -> Void))) {

     }

     func getUser(success: ((User) -> Void), error: ((Error) -> Void))) {

     }
   }

and in another examples, they divide functionality in different Workers like UserWorker and PostWorker where CRUD functions related with Users and Posts are implemented:

   protocol PostWorkerLogic {

     func getPosts(success: ((Posts) -> Void), error: ((Error) -> Void)))

   }

   class PostWorker {

     func getPosts(success: ((Posts) -> Void), error: ((Error) -> Void))) {

     }

   }

I consider that the second approach is better in terms of Clean Code but I've realized that it could be even cleaner if we use a file for a single CRUD operation like getUser or getPosts.

How can I improve this?


问:
Spring data JPA update multiple rows
purpose: update some columns of same table by given list of primary keys and return ordered int[] to indicate if a row update is successful or not

query (not native):

```<code>update MyEntity e set e.col_1 = :v1, e.col_2 = :v2 where e.id in :ids
</code>```

Spring Data JPA method:

```<code>@Modifying(clearAutomatically = true)
@Transactional
public int updateCols(@Param("v1") String v1, @Param("v2") String v2, @Param("ids") List<Long> idList);
</code>```

Spring JpaTransactionManager is used

Questions: 1) With Spring Data JPA only, how to do that? (customize repository not an option due to large existing codes), we want to achieve effects equivalent to JDBC batch update with Spring data JPA only.

2) Is it possible that spring data JAP will return an integer by the update method above that is less then the input list size? If that could happen, how do we know which one on my input list failed? In any order?

3) Noticed that after the above method successfully finished, database rows not being updated at all. How could we force it synchronized with database with spring data jpa?

4) If the entity update not flushed by spring data JPA, then even we update one by one instead of in a batch, still we will not see database changes?
Thanks in advance

答:
```<code>@Query("select t from SixxxoView t where t.idbien IN (:idbienes) ")
 public List<SixxxoView> findByIdbienes(
         @Param("idbienes") List<Long> idbienes);
</code>```

Title: Spring data JPA update multiple rows

Body:
purpose: update some columns of same table by given list of primary keys and return ordered int[] to indicate if a row update is successful or not

query (not native):

update MyEntity e set e.col_1 = :v1, e.col_2 = :v2 where e.id in :ids

Spring Data JPA method:

@Modifying(clearAutomatically = true)
@Transactional
public int updateCols(@Param("v1") String v1, @Param("v2") String v2, @Param("ids") List<Long> idList);

Spring JpaTransactionManager is used

Questions: 1) With Spring Data JPA only, how to do that? (customize repository not an option due to large existing codes), we want to achieve effects equivalent to JDBC batch update with Spring data JPA only.

2) Is it possible that spring data JAP will return an integer by the update method above that is less then the input list size? If that could happen, how do we know which one on my input list failed? In any order?

3) Noticed that after the above method successfully finished, database rows not being updated at all. How could we force it synchronized with database with spring data jpa?

4) If the entity update not flushed by spring data JPA, then even we update one by one instead of in a batch, still we will not see database changes?
Thanks in advance


问:
How to refer to other things in R loop
Say that I have this data:

```<code>library(dplyr)
data <- data.frame(num=c(1:6), val=c('1998-99', '1999-00', '2000-01', '2001-02', '2002-03', '2003-04'))
</code>```

I then have several things that would be useful to figures out, mainly about how the values in a loop refer to other values and how to automate this process.

It would be best to put this in a loop. How to do so with data frame names? In other words, how to refer to the name of a data.frame in a loop?

```<code>data03 <- filter(data, num<=1)
data04 <- filter(data, num<=2)
data05 <- filter(data, num<=3)
data06 <- filter(data, num<=4)
data07 <- filter(data, num<=5)
data08 <- filter(data, num<=6)
</code>```

Then, how to make this loop work and simplified?

```<code>for (i in c(03, 04, 05, 06, 07, 08)) {
    #I want to print the number corresponding to i
    if(i=="03") print(1)
    if(i=="04") print(2)
    if(i=="05") print(3)
    if(i=="06") print(4)
    if(i=="07") print(5)
    if(i=="08") print(6)
    #I want to get the value corresponding to i for the plot title
    if(i=="03") title="1998-99"
    if(i=="04") title="1999-00"
    if(i=="05") title="2000-01"
    if(i=="06") title="2001-02"
    if(i=="07") title="2002-03"
    if(i=="08") title="2003-04"
    #I want to open the data frame, data+i
    df <- paste(data,i)
    #I want to plot, using the title saved above
    plot(df$num, main=title)
}
</code>```

Title: How to refer to other things in R loop

Body:
Say that I have this data:

library(dplyr)
data <- data.frame(num=c(1:6), val=c('1998-99', '1999-00', '2000-01', '2001-02', '2002-03', '2003-04'))

I then have several things that would be useful to figures out, mainly about how the values in a loop refer to other values and how to automate this process.

It would be best to put this in a loop. How to do so with data frame names? In other words, how to refer to the name of a data.frame in a loop?

data03 <- filter(data, num<=1)
data04 <- filter(data, num<=2)
data05 <- filter(data, num<=3)
data06 <- filter(data, num<=4)
data07 <- filter(data, num<=5)
data08 <- filter(data, num<=6)

Then, how to make this loop work and simplified?

for (i in c(03, 04, 05, 06, 07, 08)) {
    #I want to print the number corresponding to i
    if(i=="03") print(1)
    if(i=="04") print(2)
    if(i=="05") print(3)
    if(i=="06") print(4)
    if(i=="07") print(5)
    if(i=="08") print(6)
    #I want to get the value corresponding to i for the plot title
    if(i=="03") title="1998-99"
    if(i=="04") title="1999-00"
    if(i=="05") title="2000-01"
    if(i=="06") title="2001-02"
    if(i=="07") title="2002-03"
    if(i=="08") title="2003-04"
    #I want to open the data frame, data+i
    df <- paste(data,i)
    #I want to plot, using the title saved above
    plot(df$num, main=title)
}

Body:
You don't need a for loop. You can use lapply the output is a list and you can further use lapply for subsequent analysis.

lapply(1:6, function(x) data %>% filter(num <= x))
# [[1]]
#   num     val
# 1   1 1998-99
#
# [[2]]
#   num     val
# 1   1 1998-99
# 2   2 1999-00
#
# [[3]]
#   num     val
# 1   1 1998-99
# 2   2 1999-00
# 3   3 2000-01
#
# [[4]]
#   num     val
# 1   1 1998-99
# 2   2 1999-00
# 3   3 2000-01
# 4   4 2001-02
#
# [[5]]
#   num     val
# 1   1 1998-99
# 2   2 1999-00
# 3   3 2000-01
# 4   4 2001-02
# 5   5 2002-03
#
# [[6]]
#   num     val
# 1   1 1998-99
# 2   2 1999-00
# 3   3 2000-01
# 4   4 2001-02
# 5   5 2002-03
# 6   6 2003-04

And here is the complete code to filter the data frame and then create plots.

dat <- lapply(1:6, function(x) data %>% filter(num <= x))

lapply(dat, function(x){
  plot(x$num, main = x$val[nrow(x)])
})


问:
Access promise resolve in on click handler in React
This use case has three steps:

1.Make API call to check if record exists

2.If record exists, then ask user if they want to add it to a group

3.If user clicks ok on the displayed modal where we ask them, continue with another network request.

I am trying to get User Input using a modal confirm written in a custom component and based on the fact if user clicks Ok or cancel, I want to make a network request.

I cannot get access to the promise resolve function, even if I assign it to a variable that is accessible by the "onClick" handler.

I've already tried to access the promise resolve function inside the onClick handler of the button that the user clicks. It turns out to be undefined.

getUserResponse is sent as an argument to another function that exists in a separate JS file where all network calls are made. It is being called there after the record has been found to exist as a result of an API call

```<code>let outsideResolve;
const getUserResponse = async () => {
    return await new Promise((resolve, reject) => {
      outsideResolve = resolve;
    });
  };

const confirmAddRecord = event => {
    event.preventDefault();
    //resolve the promise after the button click
    outsideResolve(); //error: outsideResolve is not a function
    };

return (
      <div>
        <p>Record Exists would you like to add them to the group?</p>
        <button onClick={confirmAddRecord}>Add Existing record !</button>
      </div>
    );

*********************************
in another file (networkCalls.js), getUserResponse is sent
as an argument to a method called in the file summarized above
try {
    let userResponse = await getUserResponse();
    console.log(userResponse);
    //Do more stuff after the reply comes in
  } catch (error) {
    console.log(error);
  }
</code>```

I have created a codeSandbox to re-create the problem in more detail:
https://codesandbox.io/s/promisemodal-tke67

答:
I feel network.js should only return promise and those promises should resolved in your main component

```<code>import React, { useState } from "react";
import ReactDOM from "react-dom";

import { ADD_NEW_RECORD } from "./networkCalls";

import "./styles.css";

function App() {
  const [isModalOpen, setIsModelOpen] = useState(false);

  let createRecordPromsie = null;
  const createRecord = () => {
    createRecordPromsie = ADD_NEW_RECORD();
    createRecordPromsie.then(data => {
      setIsModelOpen(true);
    });
  };

  const getUserResponse = new Promise((resolve, reject) => {
    resolve();
  });

  const confirmAddRecord = event => {
    event.preventDefault();
    //resolve the promise after the button click
    console.log("Added Existing record");
    getUserResponse.then(data => {
      setIsModelOpen(false);
    }); //this turns out to be undefined
  };

  const renderModal = () => {
    return (
      <div>
        <p>Record Exists would you like to add them to the group?</p>
        <button onClick={confirmAddRecord}>Add Existing record !</button>
      </div>
    );
  };

  return (
    <div className="App">
      <p>Add record by pressing this button</p>
      <button onClick={createRecord}>Create record </button>
      {isModalOpen ? renderModal() : ""}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

</code>```

Network.js

```<code>export const ADD_NEW_RECORD = async () => {
  //checking from an API of record exists

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Record Exists");
      resolve("Record Exists");
    }, 1000);
  });
};
</code>```

Body:
This use case has three steps:

1.Make API call to check if record exists

2.If record exists, then ask user if they want to add it to a group

3.If user clicks ok on the displayed modal where we ask them, continue with another network request.

I am trying to get User Input using a modal confirm written in a custom component and based on the fact if user clicks Ok or cancel, I want to make a network request.

I cannot get access to the promise resolve function, even if I assign it to a variable that is accessible by the "onClick" handler.

I've already tried to access the promise resolve function inside the onClick handler of the button that the user clicks. It turns out to be undefined.

getUserResponse is sent as an argument to another function that exists in a separate JS file where all network calls are made. It is being called there after the record has been found to exist as a result of an API call

let outsideResolve;
const getUserResponse = async () => {
    return await new Promise((resolve, reject) => {
      outsideResolve = resolve;
    });
  };

const confirmAddRecord = event => {
    event.preventDefault();
    //resolve the promise after the button click
    outsideResolve(); //error: outsideResolve is not a function
    };

return (

Record Exists would you like to add them to the group?

        <button onClick={confirmAddRecord}>Add Existing record !</button>

    );

*********************************
in another file (networkCalls.js), getUserResponse is sent
as an argument to a method called in the file summarized above
try {
    let userResponse = await getUserResponse();
    console.log(userResponse);
    //Do more stuff after the reply comes in
  } catch (error) {
    console.log(error);
  }

I have created a codeSandbox to re-create the problem in more detail:
https://codesandbox.io/s/promisemodal-tke67

Body:
I feel network.js should only return promise and those promises should resolved in your main component

import React, { useState } from "react";
import ReactDOM from "react-dom";

import { ADD_NEW_RECORD } from "./networkCalls";

import "./styles.css";

function App() {
  const [isModalOpen, setIsModelOpen] = useState(false);

  let createRecordPromsie = null;
  const createRecord = () => {
    createRecordPromsie = ADD_NEW_RECORD();
    createRecordPromsie.then(data => {
      setIsModelOpen(true);
    });
  };

  const getUserResponse = new Promise((resolve, reject) => {
    resolve();
  });

  const confirmAddRecord = event => {
    event.preventDefault();
    //resolve the promise after the button click
    console.log("Added Existing record");
    getUserResponse.then(data => {
      setIsModelOpen(false);
    }); //this turns out to be undefined
  };

  const renderModal = () => {
    return (
      <div>
        <p>Record Exists would you like to add them to the group?</p>
        <button onClick={confirmAddRecord}>Add Existing record !</button>
      </div>
    );
  };

  return (
    <div className="App">
      <p>Add record by pressing this button</p>
      <button onClick={createRecord}>Create record </button>
      {isModalOpen ? renderModal() : ""}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Network.js

export const ADD_NEW_RECORD = async () => {
  //checking from an API of record exists

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Record Exists");
      resolve("Record Exists");
    }, 1000);
  });
};


问:
How to use frame to set x position in loop on Swift
I have an array that count is between 1 to 3 varies.
I want to frame them in the middle of the screen with a certain distance
Also the width of the labels is fixed

```<code>let array = ["some1", "some2", "some3"]

func setLabel(){
  var i = -1
  for text in array{
      i += 1
      let label = UILabel()
      label.fram = CGRect(x: screenWidth/2 - (CGFloat(i)*50) + 25, y: 100, width: 50 , height: 20)
      label.text = text
      addSubview(label)
  }
}
</code>```

答:
You can use stackview as suggested by @matt. If you don't want to use stackview you can calculate the x position by array count and label index like this</p>

```<code>let array = ["some1", "some2", "some3"]
func setLabel(){
    var i:CGFloat = 0
    for text in array{
        i += 1
        let label = UILabel()
        label.backgroundColor = .red
        label.frame = CGRect(x: (view.bounds.width/CGFloat(array.count+1))*i-25, y: 100, width: 50 , height: 20)
        label.text = text
        view.addSubview(label)
    }
}
</code>```

Body:
I have an array that count is between 1 to 3 varies.
I want to frame them in the middle of the screen with a certain distance
Also the width of the labels is fixed

let array = ["some1", "some2", "some3"]

func setLabel(){
  var i = -1
  for text in array{
      i += 1
      let label = UILabel()
      label.fram = CGRect(x: screenWidth/2 - (CGFloat(i)*50) + 25, y: 100, width: 50 , height: 20)
      label.text = text
      addSubview(label)
  }
}

Body:
You can use stackview as suggested by @matt. If you don't want to use stackview you can calculate the x position by array count and label index like this

let array = ["some1", "some2", "some3"]
func setLabel(){
    var i:CGFloat = 0
    for text in array{
        i += 1
        let label = UILabel()
        label.backgroundColor = .red
        label.frame = CGRect(x: (view.bounds.width/CGFloat(array.count+1))*i-25, y: 100, width: 50 , height: 20)
        label.text = text
        view.addSubview(label)
    }
}


问:
Data scraping shopee
I am trying to scrape prices from Shopee into googlesheets using the importxml function from  https://shopee.sg/Svelty-Pakkun-decomposition-yeast-120-Tablets-i.139075719.2136980675 but it gives me imported content is empty

tried copying the xpath but it didn work

importxml(https://shopee.sg/Svelty-Pakkun-decomposition-yeast-120-Tablets-i.139075719.2136980675, "//*div[@class='_3n5NQx']")

imported content is empty

答: after disabling JavaScript for a given link you can see that page is empty which means that site is not possible to be scraped by Google Sheets. there are no workarounds. you will need to find yourself some other source.

Title: Data scraping shopee


问:
How to pull submodules with --remote within Gitlab CI?
I need my Gitlab CI to update submodules with --remote flag so that the HEAD is set to the remote's HEAD. After a bit of Googling I found that I need to set GIT_SUBMODULE_STRATEGY to none and run git submodule update --recursive --remote  --init manually:

```<code>variables:
    GIT_STRATEGY: clone
    GIT_SUBMODULE_STRATEGY: none

before_script:
  - apk add git || ( apt-get update && apt-get -y install git )
  - git submodule update --recursive --remote  --init

test:build:
  services:
  - docker:dind
  image: ubuntu
  variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_DRIVER: overlay2
  script:
  - echo "done
</code>```

Unfortunately I'm getting a CI failure (names edited):

```<code>$ git submodule update --recursive --remote  --init
Submodule 'current_project_name/submodule_project_name' (ssh://git@gitlab.someserver.net:9931/someorg/submodule_project_name.git) registered for path 'current_project_name/submodule_project_name'
Cloning into '/builds/someorg/current_project_name/current_project_name/submodule_project_name'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
fatal: clone of 'ssh://git@gitlab.someserver.net:9931/someorg/submodule_project_name.git' into submodule path '/builds/someorg/current_project_name/current_project_name/submodule_project_name' failed
Failed to clone 'current_project_name/submodule_project_name'. Retry scheduled
Cloning into '/builds/someorg/current_project_name/current_project_name/submodule_project_name'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
fatal: clone of 'ssh://git@gitlab.someserver.net:9931/someorg/submodule_project_name.git' into submodule path '/builds/someorg/current_project_name/current_project_name/submodule_project_name' failed
Failed to clone 'current_project_name/submodule_project_name' a second time, aborting
</code>```

I can see that the CI does have permissions to clone that submodule_project_name because if I set GIT_SUBMODULE_STRATEGY e.g. to recursive, CI manages to pull it (but it's not --remote, so it doesn't work the way I want). Unfortunately when my before_script tries to do it, I'm getting the error. How can I bypass it?

答:
I mentioned before updating the ~/.ssh/.known_hosts file, as in here.

This is not needed when fetching the submodules before the script (which is not what you are doing with GIT_SUBMODULE_STRATEGY set to NONE)

With dind (Docker In Docker), consider also this thread, regarding ssh-add for private keys, and .dockerini / .dockerenv SSH directives.

The OP d33tah confirms in the comments:

I actually didn't add any key, assuming that since Gitlab CI's defaults can pull the key, I should be able to as well.

  Then I found that docs say that I needed a deploy key and I added one

Yes: adding the public key on Gitlab side is mandatory.

Body:
I need my Gitlab CI to update submodules with --remote flag so that the HEAD is set to the remote's HEAD. After a bit of Googling I found that I need to set GIT_SUBMODULE_STRATEGY to none and run git submodule update --recursive --remote  --init manually:

variables:
    GIT_STRATEGY: clone
    GIT_SUBMODULE_STRATEGY: none

before_script:
  - apk add git || ( apt-get update && apt-get -y install git )
  - git submodule update --recursive --remote  --init

test:build:
  services:
  - docker:dind
  image: ubuntu
  variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_DRIVER: overlay2
  script:
  - echo "done

Unfortunately I'm getting a CI failure (names edited):

$ git submodule update --recursive --remote  --init
Submodule 'current_project_name/submodule_project_name' (ssh://git@gitlab.someserver.net:9931/someorg/submodule_project_name.git) registered for path 'current_project_name/submodule_project_name'
Cloning into '/builds/someorg/current_project_name/current_project_name/submodule_project_name'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
fatal: clone of 'ssh://git@gitlab.someserver.net:9931/someorg/submodule_project_name.git' into submodule path '/builds/someorg/current_project_name/current_project_name/submodule_project_name' failed
Failed to clone 'current_project_name/submodule_project_name'. Retry scheduled
Cloning into '/builds/someorg/current_project_name/current_project_name/submodule_project_name'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
fatal: clone of 'ssh://git@gitlab.someserver.net:9931/someorg/submodule_project_name.git' into submodule path '/builds/someorg/current_project_name/current_project_name/submodule_project_name' failed
Failed to clone 'current_project_name/submodule_project_name' a second time, aborting

I can see that the CI does have permissions to clone that submodule_project_name because if I set GIT_SUBMODULE_STRATEGY e.g. to recursive, CI manages to pull it (but it's not --remote, so it doesn't work the way I want). Unfortunately when my before_script tries to do it, I'm getting the error. How can I bypass it?


问:
Not able to reset input field in laravel
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

```<code> <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
</code>```

JS for reset button:

```<code>document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };
</code>```

Reset Button:

```<code><button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
</code>```

答:
Your reset button :

```<code><button class="btn btn-primary" id="reset-button" onclick="myFunction()">Reset</button>
</code>```

In js:

```<code>function myFunction(){
   document.getElementById("app_number").value = "";
}
</code>```

Body:
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

 <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>

JS for reset button:

document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };

Reset Button:

<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>

Body:
Your reset button :

<button class="btn btn-primary" id="reset-button" onclick="myFunction()">Reset</button>

In js:

function myFunction(){
   document.getElementById("app_number").value = "";
}


问:
Use Case Apache Spark getting Nameerror running a line with countryCodeMap
I'm very new to this and I'm using a use case found on databricks.com to learn more. (https://databricks.com/blog/2018/07/09/analyze-games-from-european-soccer-leagues-with-apache-spark-and-databricks.html)

I'm running spark through Jupiter notebook and python 3. I have been able to load the files etc but I'm getting a nameError for on of the lines. it says it has not been defined, but I can't see anywhere where to define it or how to do that.
 the line is this:

```<code>gameInfDf = gameInfDf.withColumn("country_code", mapKeyToVal(countryCodeMap) ("country"))
</code>```

the nameError is: name 'countryCodeMap' is not defined
before this I ran this code chunk:

```<code>def mapKeyToVal(mapping):
    def mapKeyToVal_(col):
        return mapping.get(col)
    return udf(mapKeyToVal_, StringType())
</code>```

Can please someone tell me if I'm running it on the wrong program or what my problem is?

Thank you very much in advance.

答:
As per https://databricks.com/blog/2018/07/09/analyze-games-from-european-soccer-leagues-with-apache-spark-and-databricks.html. You missed the space in your return. Not sure how you were able to run this part. I get an error when I try to define the UDF.
Try this:</p>

```<code>def mapKeyToVal(mapping):
    def mapKeyToVal_(col):
        return mapping.get(col)
    return udf(mapKeyToVal_, StringType())
</code>```

Body:
I'm very new to this and I'm using a use case found on databricks.com to learn more. (https://databricks.com/blog/2018/07/09/analyze-games-from-european-soccer-leagues-with-apache-spark-and-databricks.html)

I'm running spark through Jupiter notebook and python 3. I have been able to load the files etc but I'm getting a nameError for on of the lines. it says it has not been defined, but I can't see anywhere where to define it or how to do that.
 the line is this:

gameInfDf = gameInfDf.withColumn("country_code", mapKeyToVal(countryCodeMap) ("country"))

the nameError is: name 'countryCodeMap' is not defined
before this I ran this code chunk:

def mapKeyToVal(mapping):
    def mapKeyToVal_(col):
        return mapping.get(col)
    return udf(mapKeyToVal_, StringType())

Can please someone tell me if I'm running it on the wrong program or what my problem is?

Thank you very much in advance.

Body:
As per https://databricks.com/blog/2018/07/09/analyze-games-from-european-soccer-leagues-with-apache-spark-and-databricks.html. You missed the space in your return. Not sure how you were able to run this part. I get an error when I try to define the UDF.
Try this:

def mapKeyToVal(mapping):
    def mapKeyToVal_(col):
        return mapping.get(col)
    return udf(mapKeyToVal_, StringType())


问:
this.dragmove() interfering with mouseup event wpf
I have a UserControl in WPF.
The UserControl has a MouseLeftMouseButtonUp event.
The problem is- the Window has a this.DragMove() method in its MouseDown event which seems to interfere with the MouseLeftMouseButtonUp in the User Control (I need the this.DragMove() method to move the borderless window).
Any ideas?
Thanks!</p>

答:
```<code>   private void  MouseDown(object sender, MouseButtonEventArgs e)
      {
          e.Handled = true;
          if (e.LeftButton == MouseButtonState.Pressed)
         {
            this.DragMove();
          }

          if (e.LeftButton == MouseButtonState.Released)
          {
          //your mouse up code
          }
      }
</code>```

ContentLicense: CC BY-SA 2.5


问:
Can someone assist with translating this Object Oriented Design diagram example into code?
I am going through Sandi Metz's Practical Object Oriented Design. In Chapter 4, Creating Flexible Interfaces, I am presented with some UML diagrams to show the interactions and messages of two classes. For example, below is the following diagram from the book:

The description of this image is the following:

Therefore, this sequence diagram can be read as follows: Customer Moe sends the suitable_trips message to the Trip class, which is activated to process it and then, when finished, returns a response.

Would an implementation like the following be accurate?

```<code>class Customer
  attr_reader :name, :on_date, :of_difficulty, :need_bike
  def initialize(name, on_date, of_difficulty, need_bike)
    @name = name
    @on_date = on_date
    @of_difficulty = of_difficulty
    @need_bike = need_bike
  end
end

class Trip
  attr_reader :trip
  def initialize(trip)
    @trip = trip
  end

  def suitable_trips(on_date, of_difficulty, need_bike)
    #gives list of suitable trips based on factors
  end
end

moe = Customer.new("moe", "now", "easy", "yes")
trip = Trip.new('Grand Canyon')

trip.suitable_trips(moe.on_date, moe.of_difficulty, moe.need_bike)
</code>```

Sometimes I think I get it but then I'll run into another UML diagram and then get confused by wording especially when it comes to receiver and sender. I just want to be sure I'm getting this right so I understand completely where methods are supposed to go and in which class.

答:
Therefore, this sequence diagram can be read as follows: Customer Moe sends the suitable_trips message to the Trip class, which is activated to process it and then, when finished, returns a response.

Let’s implement it exactly as stated.

```<code>class Trip
  class << self # class methods
    def suitable_trips(on_date, of_difficulty, need_bike)
      # gives list of suitable trips based on factors
      [Trip.new(...), Trip.new(...), ...]
    end
  end
end

class Customer
  attr_reader :name
  def initialize(name)
    @name = name
  end
  # this is a search function, specific for Moe
  def best_fit(on_date, of_difficulty, need_bike)
    trips = Trip.suitable_trips(on_date, of_difficulty, need_bike)
    # get the best accordingly to some rules
    #   that are specific for Moe
    trips.find { |trip| ... }
  end
end
</code>```

And use it like:

```<code>moe = Customer.new("Moe")
moe.best_fit("2019-06-01", :hard, false)
#⇒ Trip instance or `nil`
</code>```

Sidenote: there are tons of great books on Ruby and my personal advice would be to pick up one of them instead. Sandi Metz is probably a great populist, but it makes sense to read tutorials from people who are actually good at coding.

Body:
I am going through Sandi Metz's Practical Object Oriented Design. In Chapter 4, Creating Flexible Interfaces, I am presented with some UML diagrams to show the interactions and messages of two classes. For example, below is the following diagram from the book:

The description of this image is the following:

Therefore, this sequence diagram can be read as follows: Customer Moe sends the suitable_trips message to the Trip class, which is activated to process it and then, when finished, returns a response.

Would an implementation like the following be accurate?

class Customer
  attr_reader :name, :on_date, :of_difficulty, :need_bike
  def initialize(name, on_date, of_difficulty, need_bike)
    @name = name
    @on_date = on_date
    @of_difficulty = of_difficulty
    @need_bike = need_bike
  end
end

class Trip
  attr_reader :trip
  def initialize(trip)
    @trip = trip
  end

  def suitable_trips(on_date, of_difficulty, need_bike)
    #gives list of suitable trips based on factors
  end
end

moe = Customer.new("moe", "now", "easy", "yes")
trip = Trip.new('Grand Canyon')

trip.suitable_trips(moe.on_date, moe.of_difficulty, moe.need_bike)

Sometimes I think I get it but then I'll run into another UML diagram and then get confused by wording especially when it comes to receiver and sender. I just want to be sure I'm getting this right so I understand completely where methods are supposed to go and in which class.

Body:
Therefore, this sequence diagram can be read as follows: Customer Moe sends the suitable_trips message to the Trip class, which is activated to process it and then, when finished, returns a response.

Let’s implement it exactly as stated.

class Trip
  class << self # class methods
    def suitable_trips(on_date, of_difficulty, need_bike)
      # gives list of suitable trips based on factors
      [Trip.new(...), Trip.new(...), ...]
    end
  end
end

class Customer
  attr_reader :name
  def initialize(name)
    @name = name
  end
  # this is a search function, specific for Moe
  def best_fit(on_date, of_difficulty, need_bike)
    trips = Trip.suitable_trips(on_date, of_difficulty, need_bike)
    # get the best accordingly to some rules
    #   that are specific for Moe
    trips.find { |trip| ... }
  end
end

And use it like:

moe = Customer.new("Moe")
moe.best_fit("2019-06-01", :hard, false)
#⇒ Trip instance or `nil`

Sidenote: there are tons of great books on Ruby and my personal advice would be to pick up one of them instead. Sandi Metz is probably a great populist, but it makes sense to read tutorials from people who are actually good at coding.


问:
CSS styling not appearing on PHP page
I want to display some styling for my webpage, but the styling I'm defining for it is not appearing.

I've tried looking over the code and nothing I edit seems to work.

(this is part of my functions.php page. echo is the code I am trying to style)

```<code>    function getPro() {

    global $con;

$get_pro = "select * from products order by RAND() LIMIT 0,6";

$run_pro = mysqli_query($con, $get_pro);

while($row_pro=mysqli_fetch_array($run_pro)) {

    $pro_id = $row_pro['product_id'];
    $pro_cat = $row_pro['product_cat'];
    $pro_brand = $row_pro['product_brand'];
    $pro_title = $row_pro['product_title'];
    $pro_price = $row_pro['product_price'];
    $pro_image = $row_pro['product_image'];

echo "
        <div id='single_product'>

            <h3><b>$pro_title<b></h3>

            <img src='admin_area/product_images/$pro_image' width='180' height='180' />

            <p><b> $ $pro_price </b></p>

            <a href='details.php' style='float:left;'>Details</a>
            <a href='index.php'> <button style='float:right'>Add to Cart</button></a>

        </div>  ";
}
</code>```

(this is the styling from my style.css page)

```<code>   #single_product {float:left; margin-left: 20px; padding:10px;}

   #single_product img {border:4px solid black;}
</code>```

(this is part of my index page where functions is executed)

```<code><div class="content_wrapper">
  <div id="sidebar">
    <div id="sidebar_title">Categories</div>

  <ul id="cats">
    <?php getCats(); ?>
  </ul>

 <div id="sidebar_title">Brands</div>
<!-- brands and categories have the same ul id -->
    <ul id="cats">
    <?php getBrands(); ?>
    </ul>
</div>

    <div id="content_area">

        <div id="products_box">

            <?php getPro(); ?>

        </div>

    </div>

</div>
</code>```

I want the styling for 'single_product' set the way it is defined on my css page.

答:
Hi if you want to define css use class and give css like

```<code>echo "<div class='single_product'>
        <h3><b>$pro_title<b></h3>
        <img src='admin_area/product_images/$pro_image' width='180' height='180' />
        <p><b> $ $pro_price </b></p>
        <a href='details.php' style='float:left;'>Details</a>
        <a href='index.php'> <button style='float:right'>Add to Cart</button></a>
    </div>  ";
</code>```

---CSS---

```<code>   .single_product {float:left; margin-left: 20px; padding:10px;}
   .single_product img {border:4px solid black;}
</code>```

beacuse you are using while loop and css define in id thats why not working try to use class and define

Title: CSS styling not appearing on PHP page

Body:
I want to display some styling for my webpage, but the styling I'm defining for it is not appearing.

I've tried looking over the code and nothing I edit seems to work.

(this is part of my functions.php page. echo is the code I am trying to style)

    function getPro() {

    global $con;

$get_pro = "select * from products order by RAND() LIMIT 0,6";

$run_pro = mysqli_query($con, $get_pro);

while($row_pro=mysqli_fetch_array($run_pro)) {

    $pro_id = $row_pro['product_id'];
    $pro_cat = $row_pro['product_cat'];
    $pro_brand = $row_pro['product_brand'];
    $pro_title = $row_pro['product_title'];
    $pro_price = $row_pro['product_price'];
    $pro_image = $row_pro['product_image'];

echo "

$pro_title

 $ $pro_price

            Details
             <button style='float:right'>Add to Cart</button>

  ";
}

(this is the styling from my style.css page)

   #single_product {float:left; margin-left: 20px; padding:10px;}

   #single_product img {border:4px solid black;}

(this is part of my index page where functions is executed)

Categories

    <?php getCats(); ?>

Brands

    <?php getBrands(); ?>

            <?php getPro(); ?>

I want the styling for 'single_product' set the way it is defined on my css page.

Body:
Hi if you want to define css use class and give css like

echo "<div class='single_product'>
        <h3><b>$pro_title<b></h3>
        <img src='admin_area/product_images/$pro_image' width='180' height='180' />
        <p><b> $ $pro_price </b></p>
        <a href='details.php' style='float:left;'>Details</a>
        <a href='index.php'> <button style='float:right'>Add to Cart</button></a>
    </div>  ";

---CSS---

   .single_product {float:left; margin-left: 20px; padding:10px;}
   .single_product img {border:4px solid black;}

beacuse you are using while loop and css define in id thats why not working try to use class and define


问:
Spring webflow prevent GET method in transition
I am using spring webflow 2.3.1.RELEASE in my project.

The customer's security team raised and issue witch is "It is possible to change the http method from POST to GET and the application accepts the change and continues working."

So I need to prevent this change and make my transitions accept only POST method. Or throw exception if I get any request parameter other than execution in the url.

How can I do this?

答:
You could create your own FlowExecutionListener and throw an exception when the request method is different than POST and/or  when request parameters are present.

see the documentation here and API here


问:
How do I get this javascript to run every second?
How do I get this javascript to run every second?

source code:

```<code><script type="text/javascript">
$(function() {
    //More Button
    $('.more').live("click",function()  {
        var ID = $(this).attr("id");
        if(ID) {
            $("#more"+ID).html('<img src="moreajax.gif" />');

            $.ajax({
                type: "POST",
                url: "ajax_more.php",
                data: "lastmsg="+ ID,
                cache: false,
                success: function(html){
                    $("ol#updates").prepend(html);
                    $("#more"+ID).remove();
                }
            });
        } else {
            $(".morebox").html('no posts to display');
        }

        return false;

    });
});

</script>
</code>```

答:
Use setInterval(func, delay) to run the func every delay milliseconds.

setTimeout() runs your function once after delay milliseconds -- it does not run it repeatedly.  A common strategy is to run your code with setTimeout and call setTimeout again at the end of your code.


问:
How can I delete the elements of array on MATLAB?
The following code is executed but I have no idea to delete the elements of array on MATLAB.

And therefore, Array1 and Array2 are written out with the former data.

MATLAB version R2017b

```<code>global Array1
global Array2
filename = 'data.xlsx';
for i = 1:3
    sheet = i
    for j = (1:2)-1
        one = [1];
        two = [2];
        Array1 = [Array1; one]
        Array2 = [Array2; two]
    end
    xlswrite(filename, Array1, sheet, 'A1');
    xlswrite(filename, Array2, sheet, 'B1');
    %here I would like to delete the elements of Array1 and Array2global
    %Array1 = [];
    %Array2 = [];
end
</code>```

答:
Array1(index)=[]

Just insert the index(s) of the array you wish to remove.

Body:
The following code is executed but I have no idea to delete the elements of array on MATLAB.

And therefore, Array1 and Array2 are written out with the former data.

MATLAB version R2017b

global Array1
global Array2
filename = 'data.xlsx';
for i = 1:3
    sheet = i
    for j = (1:2)-1
        one = [1];
        two = [2];
        Array1 = [Array1; one]
        Array2 = [Array2; two]
    end
    xlswrite(filename, Array1, sheet, 'A1');
    xlswrite(filename, Array2, sheet, 'B1');
    %here I would like to delete the elements of Array1 and Array2global
    %Array1 = [];
    %Array2 = [];
end


问:
How to load json from file and set it as global variable in Vue?
I'm new to Vue. I want to read employeeId from a login form and ust it to load some json files named according as employeeId.json like (10000001.json, 20000001.json) and set the json object as a global variable so I can easily access it in all components.

Firstly, I don't know how to dynamically load json files. Using import sees not work. Some one suggested using require should work. But there are not many examples, I don't know where to put require...

Secondly, how do I set the json as global after the employeeId props in? I'm very confused where to put it (inside the export default or not? inside methods or not? or inside created/mounted or not?) and where to use this or not...

This is the script section of my headerNav.vue file.

```<code><script>
//**I placed them here now, it works, but employeeId is hard coded...
import json10000001 from "./json/10000001.json";
import json20000001 from "./json/20000001.json";
import json30000001 from "./json/30000001.json";
// var employeeId = employeeIdFromLogin;
var jsonForGlobal;
var employeeId = 10000001;
var jsonFileCurrentObj;
if (employeeId == "10000001") {
  jsonForGlobal = jsonFileCurrentObj = json10000001;
} else if (employeeId == "20000001") {
  jsonForGlobal = jsonFileCurrentObj = json20000001;
} else if (employeeId == "30000001") {
  jsonForGlobal = jsonFileCurrentObj = json30000001;
}

export default {
  // props:{
  //   employeeIdFromLogin: String,
  // },
  props:['employeeIdFromLogin'],
  jsonForGlobal,
  // employeeIdFromLogin,
  data() {
    return {
      docked: false,
      open: false,
      position: "left",
      userinfo: {},
      jsonFileCurrent: jsonFileCurrentObj,
      // employeeIdFromLogin: this.GLOBAL3.employeeIdFromLogin
      // jsonFile: currentJsonFile
    };
  },
  mounted() {
//**I tried put it here, not working well...
    // var employeeId = this.employeeIdFromLogin;
    // // var jsonForGlobal;
    // console.log("headernav.employeeIdFromLogin="+this.employeeIdFromLogin);
    // // var employeeId = 10000001;
    // var jsonFileCurrentObj;
    // if (employeeId == "10000001") {
    //   this.jsonForGlobal = this.jsonFileCurrentObj = json10000001;
    // } else if (employeeId == "20000001") {
    //   this.jsonForGlobal = this.jsonFileCurrentObj = json20000001;
    // } else if (employeeId == "30000001") {
    //   this.jsonForGlobal = this.jsonFileCurrentObj = json30000001;
    // }
  },
  methods: {
    switchPage(pageName) {
      this.$emit("switchPage", pageName);
    }
//**I don't know how to use the require...
    // var employeeId = 10000001;
    // getJsonFile(employeeId) {
    //   this.currentJsonFile = require("../assets/json/" + employeeId + ".json");
    // }
  }
};
</code>```

答:
You might want to use vuex to manage global store. But if you don't want includes Vuex, there is a simpler way to have global state:

Define globalStore.js

```<code>// globalStore.js
export const globalStore = new Vue({
  data: {
    jsonForGlobal: null
  }
})
</code>```

then import it and use in component:

```<code>import {globalStore} from './globalStore.js'
export default {
  props: ['employeeIdFromLogin'],
  data: function ()
    return {
      jsonLocal: globalStore.jsonForGlobal,
      jsonFileCurrent: null
    }
  },
  watch: {
    employeeIdFromLogin: {
      handler(newVal, oldVal) {
        const data = require('./json/' + this.employeeIdFromLogin + '.json')
        this.jsonFileCurrent = data
        globalStore.jsonForGlobal = data
      }
    }
  }
}
</code>```

Body:
You might want to use vuex to manage global store. But if you don't want includes Vuex, there is a simpler way to have global state:

Define globalStore.js

// globalStore.js
export const globalStore = new Vue({
  data: {
    jsonForGlobal: null
  }
})

then import it and use in component:

import {globalStore} from './globalStore.js'
export default {
  props: ['employeeIdFromLogin'],
  data: function ()
    return {
      jsonLocal: globalStore.jsonForGlobal,
      jsonFileCurrent: null
    }
  },
  watch: {
    employeeIdFromLogin: {
      handler(newVal, oldVal) {
        const data = require('./json/' + this.employeeIdFromLogin + '.json')
        this.jsonFileCurrent = data
        globalStore.jsonForGlobal = data
      }
    }
  }
}


问:
copy and paste same non contiguous cells from different sheets to master sheet
how to copy same non contiguous cell from different sheets and paste in one master sheets ("sheet5") row by row.</p>

```<code>Sub test()

    Dim cel As Range, pasteRange As Range

    Set pasteRange = ThisWorkbook.Sheets("Sheet5").Range("A2")

    For i=1 to 4
        For Each cel In ThisWorkbook.Sheets(i).Range("A2, B4, D5, E1, F3")
            pasteRange.Value = cel.Value
            Set pasteRange = pasteRange.Offset(0, 1)
        Next
    Next

End Sub
</code>```

答:
```<code>Dim cel As Range, pasteRange As Range
Dim sht As Worksheet

' Do not use 'ThisWorkbook' - what is the macro us ran from another one?
' Use 'ActiveWorkbook' instead or specify its name
Set pasteRange = ActiveWorkbook.Sheets("Sheet5").Range("A2")

'
For Each sht In Sheets
    If sht.name <> "Sheet5" Then
        For Each cel In sht.Range("A2, B4, D5, E1, F3")
            pasteRange.Value = cel.Value
            Set pasteRange = pasteRange.Offset(0, 1)
        Next
    End If
Next
</code>```

Body:
how to copy same non contiguous cell from different sheets and paste in one master sheets ("sheet5") row by row.

Sub test()

    Dim cel As Range, pasteRange As Range

    Set pasteRange = ThisWorkbook.Sheets("Sheet5").Range("A2")

    For i=1 to 4
        For Each cel In ThisWorkbook.Sheets(i).Range("A2, B4, D5, E1, F3")
            pasteRange.Value = cel.Value
            Set pasteRange = pasteRange.Offset(0, 1)
        Next
    Next

End Sub


问:
Is there a way to set-cookies from laravel to another domain after Ajax request?
I'm learning about Laravel passport package and creating a SPA using Vue.js to test it, I'm wondering about saving the Token in the client browser, If I saved it on local storage it would be accessible from Javascript and anyone run js on the browser would be able to read it !
My questions are; What is the solution for this situation ?
If I saved the token in the cookies It would be accessible too, and I read about httpOnly cookies, so How can I set the cookies to save the token from the response from the API if it's not accessible by Javascript ?
Is there a way to save the cookies from the API ?

I hope I can find answers for my Questions.

答:
Well, there are a couple of things to understand here.

HTTP only cookie

First, HTTP cookies are set by the server using set-cookie header. In this case, you as a developer need not do anything. The browser will automatically set it for you and will send back to the server on each Ajax or non-ajax requests. It will send the cookie as long as it is not expired.

LocalStorage

When using LocalStorage for storing the token, any JavaScript code can read it (known as XSS attack if misused). But, the key thing to understand here is that other domain's JavaScript code cannot read the LocalStorage. The scope is restricted to your own site. Other website's JS cannot read it. So, if you are not using any external dependency or compromised CDN, you are safe.

Cross-site cookie

No. It is impossible to set a cross-domain cookie under any circumstances. Only other domain's server can set a cookie for itself (Unless you have some backend mechanism like Gmail + Youtube to share session). However, in case of a subdomain, the following things are allowed:

Parent domain can set a cookie for any child domain. That is example.com can set a cookie for *.example.com.

Child domain can set a cookie for the parent domain. That is xyz.example.com can set a cookie for example.com.

Of course, the rules are more complicated than that. This article should help you understand further.


问:
pointer & array conflict
let

```<code>int*p ,b = 5;
p = &b;
</code>```

denotes a ONE DIMENSIONAL array, then what is the output given by following statement

```<code>printf("%d",p);
</code>```

is it an address? if it is an address then tell me which element it belongs,please explain clearly

答:
address of the first element of the array. (if b was an array)
use p++ to scroll through the array</p>

Title: pointer & array conflict

Body:
let

int*p ,b = 5;
p = &b;

denotes a ONE DIMENSIONAL array, then what is the output given by following statement

printf("%d",p);

is it an address? if it is an address then tell me which element it belongs,please explain clearly