问:
Checking multiple columns have any of multiple values in a Table value parameter
I am trying to create a query to help get a list of accounts from an existing database. I will have two lists of integers passed in through two Table Value Parameters(TVP) from C#. I then need to see if multiple columns have any of the values in the corresponding TVP tables. The TVP lists of integers are provided by different clients and may differ between clients. That is why they are TVP's to allow the values to be passed in as parameters.

The data structure cannot be changed, it is created based on data from another system. Comments about changing the data structure won't be helpful. To help I will talk about an example table that would help show what I need.

Looking at a table like the following:

```<code>Table Accounts
  varchar(200) AccountId
  int StatusId1
  int StatusId2
  int StatusId3
  int StatusId4
  int Identifier1
  int Identifier2
  int Identifier3
  int Identifier4
  int Identifier5
</code>```

I know that I can do a sql statement like:

Select AccountId from Accounts where StatusId1 In (1,2,3)

I was able to learn that I can reverse the In command as well:

Select AccountId from Accounts where 1 In (StatusId1, StatusId2, StatusId3, StatusId4)

This only lets me check one value against each column. The problem is I need to mix the two while using the TVP for the list of integers.

The closest I have been able to create is the following:

```<code>--Load the TVP lists
SELECT * INTO #StatusCodes FROM @StatusId
SELECT * INTO #IdentityCodes FROM @IdentifierId

--Find the Accounts that have the chosen Ids
SELECT AccountId
FROM Accounts
WHERE StatusId1 IN( SELECT Id FROM #StatusCodes)
OR StatusId2 IN( SELECT Id FROM #StatusCodes)
OR StatusId3 IN( SELECT Id FROM #StatusCodes)
OR StatusId4 IN( SELECT Id FROM #StatusCodes)
OR Identifier1 IN (SELECT Id FROM #IdentityCodes)
OR Identifier2 IN (SELECT Id FROM #IdentityCodes)
OR Identifier3 IN (SELECT Id FROM #IdentityCodes)
OR Identifier4 IN (SELECT Id FROM #IdentityCodes)
OR Identifier5 IN (SELECT Id FROM #IdentityCodes)
</code>```

This query worked in my prototype and I got back the list of accounts that had at least one of these ids.  I see a lot of select statements and it doesn't look very good. I am not sure how well it performs either. I am wondering if there is a better way to do this?

This is for a system that creates a report based on conditions our clients make. Each client runs from a couple to 100 reports each night. That means this is run possibly hundreds of times each night. While it isn't a system running thousands of times per hour, it does process a lot of data. Some of the databases it will search will be big with lots of accounts to search.

答:
One option uses exists:

```<code>select a.acountId
from accounts a
where
    exists (
        select 1
        from #StatusCodes s
        where s.id in (a.StatusId1, a.StatusId2, a.StatusId3, a.StatusId4)
    )
    or exists (
        select 1
        from #IdentityCodes i
        where i.id in (a.Identifier1, a.Identifier2, a.Identifier3, a.Identifier4)
    )
</code>```

Body:
I am trying to create a query to help get a list of accounts from an existing database. I will have two lists of integers passed in through two Table Value Parameters(TVP) from C#. I then need to see if multiple columns have any of the values in the corresponding TVP tables. The TVP lists of integers are provided by different clients and may differ between clients. That is why they are TVP's to allow the values to be passed in as parameters.

The data structure cannot be changed, it is created based on data from another system. Comments about changing the data structure won't be helpful. To help I will talk about an example table that would help show what I need.

Looking at a table like the following:

Table Accounts
  varchar(200) AccountId
  int StatusId1
  int StatusId2
  int StatusId3
  int StatusId4
  int Identifier1
  int Identifier2
  int Identifier3
  int Identifier4
  int Identifier5

I know that I can do a sql statement like:

Select AccountId from Accounts where StatusId1 In (1,2,3)

I was able to learn that I can reverse the In command as well:

Select AccountId from Accounts where 1 In (StatusId1, StatusId2, StatusId3, StatusId4)

This only lets me check one value against each column. The problem is I need to mix the two while using the TVP for the list of integers.

The closest I have been able to create is the following:

--Load the TVP lists
SELECT * INTO #StatusCodes FROM @StatusId
SELECT * INTO #IdentityCodes FROM @IdentifierId

--Find the Accounts that have the chosen Ids
SELECT AccountId
FROM Accounts
WHERE StatusId1 IN( SELECT Id FROM #StatusCodes)
OR StatusId2 IN( SELECT Id FROM #StatusCodes)
OR StatusId3 IN( SELECT Id FROM #StatusCodes)
OR StatusId4 IN( SELECT Id FROM #StatusCodes)
OR Identifier1 IN (SELECT Id FROM #IdentityCodes)
OR Identifier2 IN (SELECT Id FROM #IdentityCodes)
OR Identifier3 IN (SELECT Id FROM #IdentityCodes)
OR Identifier4 IN (SELECT Id FROM #IdentityCodes)
OR Identifier5 IN (SELECT Id FROM #IdentityCodes)

This query worked in my prototype and I got back the list of accounts that had at least one of these ids.  I see a lot of select statements and it doesn't look very good. I am not sure how well it performs either. I am wondering if there is a better way to do this?

This is for a system that creates a report based on conditions our clients make. Each client runs from a couple to 100 reports each night. That means this is run possibly hundreds of times each night. While it isn't a system running thousands of times per hour, it does process a lot of data. Some of the databases it will search will be big with lots of accounts to search.

Body:
One option uses exists:

select a.acountId
from accounts a
where
    exists (
        select 1
        from #StatusCodes s
        where s.id in (a.StatusId1, a.StatusId2, a.StatusId3, a.StatusId4)
    )
    or exists (
        select 1
        from #IdentityCodes i
        where i.id in (a.Identifier1, a.Identifier2, a.Identifier3, a.Identifier4)
    )


来源: stackexchange

问:
How to transfer the pk of one model to another
I have two models task and subtask.
First, a user is supposed to create a task, then the user can create subtasks for the previously created task.

In the model for subtask, I created a foreignkey for task.

The easy way would be to get task name(or id) front the user while making a new subtask to create the link between the two.

But I want to do it the following way.

User creates a task and is redirected to a page where all tasks are listed. The user selects a certain task and then is sent to a page that shows all subtasks for the selected task.
There is a link to create a new subtask on this page and when the user uses this link, a new subtask can be created which automatically gets associated with the selected task.

Forgive me if this question is trivial.
Thanks in advance!!!

EDIT: as Daniel said
I added this in html
Create a subtask

added this in urls.py
path('task/user/subtask/new/<int:pk>', views.SubtaskCreateView.as_view(), name='subtask-create')

This displays the task primary key in url.

the view function for subtask creation is:

```<code>class SubtaskCreateView(CreateView):
    model = Subtask
    form_class = subtaskCreateForm
</code>```

Now how do i capture the task primary key and fit in the foreign key field for Subtask.
I believe this would have been easier if I used function based views.

答:
added post function in the CreateView.</p>

```<code>def post(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        form = SubtaskCreateForm(request.POST)
        if form.is_valid():
            print('forms valid')
            subtask = form.save(commit=False)
            subtask.task = task.objects.get(id = pk)
            form.save()
            return redirect('home')
        print('form invalid')
        return render(request, 'users/subtask_form.html', {'form':form})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two models task and subtask.
First, a user is supposed to create a task, then the user can create subtasks for the previously created task.

In the model for subtask, I created a foreignkey for task.

The easy way would be to get task name(or id) front the user while making a new subtask to create the link between the two.

But I want to do it the following way.

User creates a task and is redirected to a page where all tasks are listed. The user selects a certain task and then is sent to a page that shows all subtasks for the selected task.
There is a link to create a new subtask on this page and when the user uses this link, a new subtask can be created which automatically gets associated with the selected task.

Forgive me if this question is trivial.
Thanks in advance!!!

EDIT: as Daniel said
I added this in html
Create a subtask

added this in urls.py
path('task/user/subtask/new/<int:pk>', views.SubtaskCreateView.as_view(), name='subtask-create')

This displays the task primary key in url.

the view function for subtask creation is:

class SubtaskCreateView(CreateView):
    model = Subtask
    form_class = subtaskCreateForm

Now how do i capture the task primary key and fit in the foreign key field for Subtask.
I believe this would have been easier if I used function based views.

Body:
added post function in the CreateView.

def post(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        form = SubtaskCreateForm(request.POST)
        if form.is_valid():
            print('forms valid')
            subtask = form.save(commit=False)
            subtask.task = task.objects.get(id = pk)
            form.save()
            return redirect('home')
        print('form invalid')
        return render(request, 'users/subtask_form.html', {'form':form})


问:
AWS API Gateway - CORS "access-control-allow-origin" - multiple entries
I have a AWS Lambda instance that connects to a defined AWS API Gateway.  If I enable CORS and give the access-control-allow-origin a definition of http://example.com, then I am able to access the Lambda instance from http://example.com.  However, if I use https://example.com, it doesn't work.

So in AWS, how can I define using multiple access-control-allow-origin values without using a wildcard?  I tried using something like *.example.com, but that doesn't work.

EDIT:  If I use '*' as my value on the API gateway, but setup CORS rules on my S3 bucket, would that be secure?  Example for bucket rules:

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>http://example.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>https://example.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>https://www.example.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
</code>```

答:
I did something like this:

```<code>const handler: APIGatewayProxyHandler = async (event) => {
  const origin = event?.headers?.Origin || event?.headers?.origin;
  const allowedOrigins = ['https://example.com'];
  const headers = {
    'Access-Control-Allow-Origin': allowedOrigins.includes(origin)
      ? origin
      : allowedOrigins[0],
  };

  return {
    headers,
    body: JSON.stringify({
      myResponse: 'data',
    }),
    statusCode: 200,
  };
};
</code>```

Can then test via chrome dev tools by going to your client domain and running a fetch in the console:

```<code>fetch('https://exampleLambda.com/v1/example', {
   method: 'get',
   mode: 'cors'
   headers: new Headers({
     'Authorization': 'Bearer 12345,
   }),
 })
 .then(result => result.json())
 .then(console.log)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a AWS Lambda instance that connects to a defined AWS API Gateway.  If I enable CORS and give the access-control-allow-origin a definition of http://example.com, then I am able to access the Lambda instance from http://example.com.  However, if I use https://example.com, it doesn't work.

So in AWS, how can I define using multiple access-control-allow-origin values without using a wildcard?  I tried using something like *.example.com, but that doesn't work.

EDIT:  If I use '*' as my value on the API gateway, but setup CORS rules on my S3 bucket, would that be secure?  Example for bucket rules:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>http://example.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>https://example.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>https://www.example.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Body:
I did something like this:

const handler: APIGatewayProxyHandler = async (event) => {
  const origin = event?.headers?.Origin || event?.headers?.origin;
  const allowedOrigins = ['https://example.com'];
  const headers = {
    'Access-Control-Allow-Origin': allowedOrigins.includes(origin)
      ? origin
      : allowedOrigins[0],
  };

  return {
    headers,
    body: JSON.stringify({
      myResponse: 'data',
    }),
    statusCode: 200,
  };
};

Can then test via chrome dev tools by going to your client domain and running a fetch in the console:

fetch('https://exampleLambda.com/v1/example', {
   method: 'get',
   mode: 'cors'
   headers: new Headers({
     'Authorization': 'Bearer 12345,
   }),
 })
 .then(result => result.json())
 .then(console.log)


问:
All combinations with variable loops
I need find all combinations of several variables.

Example:

I have Field1[] with 3 values: 36, 38, 40. and
Field2[] with values: R, V, A, B.

Then with this code I have all the combinations.

```<code>for (int x=1;x<=3; x++)
{
    for (int y=1;y<=4;y++)
    {
        debug.print (Field1[x] + "--" + Field2[y]);
    }
}
</code>```

My problem isn't the lenght of "Field1" or "Field2". My problem is that I don't know how many variables "Field1" or "Field2" I have.
Sometimes I can have more FieldX variables, I don't know how many.

How I can do it??

Thanks

答:
This may be what your needing...its a List of objects(arrays).
This will give you your count.

```<code>using System;
using System.Collections;
using System.Collections.Generic;

namespace ArrayCount
{
    class Program
    {
        public static void Main()
        {
            var numbers = new int[] { 36, 38, 40 };
            var letters = new char[] { 'R', 'V', 'A', 'B' };
            var words = new string[] { "this", "is", "the", "example" };

            List<object> arrayList = new List<object>
            {
                numbers,
                letters,
                words
            };

            Console.WriteLine("    Count:    {0}", arrayList.Count);
            Console.WriteLine("    Values:");
            PrintValues(arrayList);
        }

        public static void PrintValues(List<object> arrayList)
        {
            foreach (object obj in arrayList)
            {
                Console.WriteLine("---------------------");
                Console.WriteLine("Type: {0}", obj);
                foreach (var item in (IEnumerable)obj)
                {
                    Console.WriteLine("Value: {0}", item.ToString());
                }
            }
        }
    }
}
</code>```

Title: All combinations with variable loops

Body:
I need find all combinations of several variables.

Example:

I have Field1[] with 3 values: 36, 38, 40. and
Field2[] with values: R, V, A, B.

Then with this code I have all the combinations.

for (int x=1;x<=3; x++)
{
    for (int y=1;y<=4;y++)
    {
        debug.print (Field1[x] + "--" + Field2[y]);
    }
}

My problem isn't the lenght of "Field1" or "Field2". My problem is that I don't know how many variables "Field1" or "Field2" I have.
Sometimes I can have more FieldX variables, I don't know how many.

How I can do it??

Thanks

Body:
This may be what your needing...its a List of objects(arrays).
This will give you your count.

using System;
using System.Collections;
using System.Collections.Generic;

namespace ArrayCount
{
    class Program
    {
        public static void Main()
        {
            var numbers = new int[] { 36, 38, 40 };
            var letters = new char[] { 'R', 'V', 'A', 'B' };
            var words = new string[] { "this", "is", "the", "example" };

            List<object> arrayList = new List<object>
            {
                numbers,
                letters,
                words
            };

            Console.WriteLine("    Count:    {0}", arrayList.Count);
            Console.WriteLine("    Values:");
            PrintValues(arrayList);
        }

        public static void PrintValues(List<object> arrayList)
        {
            foreach (object obj in arrayList)
            {
                Console.WriteLine("---------------------");
                Console.WriteLine("Type: {0}", obj);
                foreach (var item in (IEnumerable)obj)
                {
                    Console.WriteLine("Value: {0}", item.ToString());
                }
            }
        }
    }
}


问:
facebook not showing my images in posts
I have this webpage that I want to post to my profile in FB.  FB absolutely does not see images on my page.  I want it to show one image in particular.  I have used FB Lint debugging and have all my meta og tags filled out. The Lint tool sees everything, EXCEPT the image (it's got its outline, it shows the path, if you click on it, it takes you to the image).  Just. No. Image. Here are my scraped url results.  And here is my graph API.  For reference, here is the page I want to post a link to.  My image is 1.5:1 ratio, the file size is under 100k, it is 720x480, I have stored it in the root folder with the web page.  I dont' know what else to do.  Any ideas what I'm doing wrong?</p>

答:
I know the questions was asked a while ago, but just to post an alternative for those with the same problem.
I had the same problem tried changing de 644 permission to 755, but that didnt work, so I got it back to 644. Finally I found that my .htacess file was blocking these kind of files to be served in other sites (such as facebook) so i just removed it and then it worked.</p>

Title: facebook not showing my images in posts


问:
Put image in a rounded CGRect
I need to put a background image inside of a rounded CGRect.

I can make corner of the CGRect rounded using code below.

```<code>let cornerRadius = CGSize(width: 4.0, height: 4.0)
let bezierPath = UIBezierPath(roundedRect: barRect, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadii: cornerRadius)
context.addPath(bezierPath.cgPath)
context.fillPath()
</code>```

I can draw an image in the CGRect like below.

```<code>context.draw(image, in: barRect)
</code>```

But, I cannot round the corner of the path since I have to use fillPath() and it makes the background as solid color.

答:
Try this extension:

```<code>extension UIImage {

    public func imageWithRounded(corners theCorners: UIRectCorner, radius: CGFloat) -> UIImage {
        let cornerRadius = CGSize(width: radius, height: radius)
        let rect = CGRect(origin: .zero, size: size)
        let renderer = UIGraphicsImageRenderer(size: size)
        let img = renderer.image { ctx in
            UIBezierPath(roundedRect: rect, byRoundingCorners: theCorners, cornerRadii: cornerRadius).addClip()
            draw(in: rect)
        }
        return img
    }

}
</code>```

And use it like this:

```<code>guard let img = UIImage(named: "myImage") else { return }
let roundedImage = img.imageWithRounded(corners: [.topLeft, .topRight], radius: 20.0)
</code>```

Title: Put image in a rounded CGRect

Body:
I need to put a background image inside of a rounded CGRect.

I can make corner of the CGRect rounded using code below.

let cornerRadius = CGSize(width: 4.0, height: 4.0)
let bezierPath = UIBezierPath(roundedRect: barRect, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadii: cornerRadius)
context.addPath(bezierPath.cgPath)
context.fillPath()

I can draw an image in the CGRect like below.

context.draw(image, in: barRect)

But, I cannot round the corner of the path since I have to use fillPath() and it makes the background as solid color.

Body:
Try this extension:

extension UIImage {

    public func imageWithRounded(corners theCorners: UIRectCorner, radius: CGFloat) -> UIImage {
        let cornerRadius = CGSize(width: radius, height: radius)
        let rect = CGRect(origin: .zero, size: size)
        let renderer = UIGraphicsImageRenderer(size: size)
        let img = renderer.image { ctx in
            UIBezierPath(roundedRect: rect, byRoundingCorners: theCorners, cornerRadii: cornerRadius).addClip()
            draw(in: rect)
        }
        return img
    }

}

And use it like this:

guard let img = UIImage(named: "myImage") else { return }
let roundedImage = img.imageWithRounded(corners: [.topLeft, .topRight], radius: 20.0)


问:
Random matrix with diagonal entries 0's and all other entries are 0's and 1's
I tried using the rbern function in R but I realized that the diagonal entries are not all 0's.</p>

Body:
This would be a possible way:

m <- 10
n <- 10
mat <- matrix(sample(0:1,m*n, replace=TRUE),m,n)
diag(mat) <- 0

#> mat
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    0    1    1    0    1    0    0    0    1     0
# [2,]    1    0    1    1    0    0    1    0    0     1
# [3,]    0    0    0    1    0    1    0    0    1     0
# [4,]    0    1    0    0    0    0    0    0    1     0
# [5,]    0    1    1    1    0    0    1    1    0     0
# [6,]    1    0    1    0    1    0    0    0    1     0
# [7,]    1    1    1    0    0    0    0    0    1     1
# [8,]    1    0    1    1    1    1    1    0    1     1
# [9,]    1    1    1    1    1    1    0    0    0     1
#[10,]    1    0    1    0    1    0    0    0    1     0


问:
Remove specific section of string
Hi I have a file that contains several thousand file paths that I am looking to move to Wazhu. Problem is I need directories so what I have looks like
>/apples/oranges/test.ex< What I need is >/apples/oranges<
Not sure if Regex or just using str.replace() is better. As each line is different I would need to find the last / and remove it as well as everything up to <

Hopefully that makes sense.

答:
You could write

```<code>import re

s = '>/apples/oranges/test.ex<'

re.match(r'.*(?=\/)', s).group()
</code>```

which returns

```<code>>/apples/oranges
</code>```

This works because .* is greedy, so it consumes all forward slashes up to the last one. (?=\/) is a positive lookahead. group(0) also works.

Demo

Title: Remove specific section of string

Body:
You could write

import re

s = '>/apples/oranges/test.ex<'

re.match(r'.*(?=\/)', s).group()

which returns

>/apples/oranges

This works because .* is greedy, so it consumes all forward slashes up to the last one. (?=\/) is a positive lookahead. group(0) also works.

Demo


问:
Improper usage of mutex c++
i have problem with my code. This function pushes a product into queue.

```<code>void producent(bool &cont,std::queue<std::string> &queue,std::mutex &mtx, int &milliseconds)
{
    while (cont)
    {
        mtx.lock();
        if (queue.size() >= MAX_QUEUE_SIZE)
        {
            mtx.unlock();
            std::cerr << "buffor full " << std::endl;
        }
        else
        {
            std::string product = generate();
            std::cerr << "producent: " << product << " " << std::endl;
            queue.push(product);
            mtx.unlock();
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
    }
}
</code>```

this function generates a string of 10 signs, which are pushed by void producent function().

```<code>std::string generate() {
    std::string temp;
    temp.resize(10);
    for (int i = 0; i < 10; i++) {
        temp[i] = rand() % ('z' - 'a' + 1) + 'a';
    }
    return temp;
}
</code>```

My question is: why, when i create 2 threads like this:

```<code>std::thread prod(producent, std::ref(wykonuj),std::ref(kolejka), std::ref(kolejka_mtx),std::ref(t));
std::thread prod1(producent, std::ref(wykonuj), std::ref(kolejka), std::ref(kolejka_mtx), std::ref(t));
</code>```

both of them give me same result, for example the outcome is:

```<code>producent: qweasdzxca
producent: qweasdzxca
</code>```

i wanted those outcomes to be different, thats why i used mutex, but it didnt work. Can someone give me some advices?

答:
Assuming your implementation has a thread-safe rand() (probably unwise), both threads are using the same initial random seed (the default of 1, in this case), and thus producing the same sequence. Rather than doing that, embrace the the C++ <random> offerings, and as far as that goes, the uniform distribution offerings as well.

```<code>#include <algorithm>
#include <random>
#include <string>

std::string generate(int n=10)
{
    std::mt19937 prng{ std::random_device{}() };
    std::uniform_int_distribution<int> dist('a', 'z');

    std::string result;
    std::generate_n(std::back_inserter(result), n, [&]() { return dist(prng); });
    return result;
}
</code>```

Executed 10x on 10x threads, this produced:

```<code>ysudtdcaeq
hwpeyiyyav
dlsdshltyo
pkfafhooxr
nmoxerbqpy
ydauzdvoaj
brjqjgxrgg
ezdsmbhygb
fpdgbkxfut
elywaokbyv
</code>```

That, or something similar, should produce what you seek.

Note: the above will not work as-expected on platforms where a..z is non-contiguous. If you're on such a beast (typically OS/400 or OS/390 EBCDIC), an alternate solution is required.

Title: Improper usage of mutex c++

Body:
i have problem with my code. This function pushes a product into queue.

void producent(bool &cont,std::queue<std::string> &queue,std::mutex &mtx, int &milliseconds)
{
    while (cont)
    {
        mtx.lock();
        if (queue.size() >= MAX_QUEUE_SIZE)
        {
            mtx.unlock();
            std::cerr << "buffor full " << std::endl;
        }
        else
        {
            std::string product = generate();
            std::cerr << "producent: " << product << " " << std::endl;
            queue.push(product);
            mtx.unlock();
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
    }
}

this function generates a string of 10 signs, which are pushed by void producent function().

std::string generate() {
    std::string temp;
    temp.resize(10);
    for (int i = 0; i < 10; i++) {
        temp[i] = rand() % ('z' - 'a' + 1) + 'a';
    }
    return temp;
}

My question is: why, when i create 2 threads like this:

std::thread prod(producent, std::ref(wykonuj),std::ref(kolejka), std::ref(kolejka_mtx),std::ref(t));
std::thread prod1(producent, std::ref(wykonuj), std::ref(kolejka), std::ref(kolejka_mtx), std::ref(t));

both of them give me same result, for example the outcome is:

producent: qweasdzxca
producent: qweasdzxca

i wanted those outcomes to be different, thats why i used mutex, but it didnt work. Can someone give me some advices?

Body:
Assuming your implementation has a thread-safe rand() (probably unwise), both threads are using the same initial random seed (the default of 1, in this case), and thus producing the same sequence. Rather than doing that, embrace the the C++ <random> offerings, and as far as that goes, the uniform distribution offerings as well.

#include <algorithm>
#include <random>
#include <string>

std::string generate(int n=10)
{
    std::mt19937 prng{ std::random_device{}() };
    std::uniform_int_distribution<int> dist('a', 'z');

    std::string result;
    std::generate_n(std::back_inserter(result), n, [&]() { return dist(prng); });
    return result;
}

Executed 10x on 10x threads, this produced:

ysudtdcaeq
hwpeyiyyav
dlsdshltyo
pkfafhooxr
nmoxerbqpy
ydauzdvoaj
brjqjgxrgg
ezdsmbhygb
fpdgbkxfut
elywaokbyv

That, or something similar, should produce what you seek.

Note: the above will not work as-expected on platforms where a..z is non-contiguous. If you're on such a beast (typically OS/400 or OS/390 EBCDIC), an alternate solution is required.


问:
Laravel 5 Vagrant box laravel/homestead give 502 bad gateway
Its been 3 days now, still I am unable to solve this. I have just installed the vagrant box on my Yosemite. I am learning to work with vm. Following the steps over Laravel Homestead I had installed vagrant box of homestead. But its giveing me 502 Bad gateway. I had set up laravel.local in host file also.

I tried other links for ngnix (1.8.0) but, I am unable to run laravel on homestead vm!!?

This is the output of /var/log/nginx/laravel.local-error.log

```<code>2015/07/12 18:54:31 [error] 957#0: *20 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.10.1, server: la5.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "la5.dev"
2015/07/12 19:03:07 [error] 1957#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.10.1, server: la5.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "la5.dev"
2015/07/12 19:04:33 [error] 2006#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.10.1, server: la5.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "la5.dev"
</code>```

vagrant@homestead:/var/log/nginx$

And this is my Homestead.yaml

```<code>ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
- ~/.ssh/id_rsa

folders:
- map: /Users/maahedev/code/la5
  to: /home/vagrant/la5

sites:
- map: la5.dev
  to: /home/vagrant/la5/public

databases:
- homestead

variables:
- key: APP_ENV
  value: local

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 93000
#       to: 9300
#     - send: 7777
#       to: 777
#       protocol: udp
</code>```

Any help/suggestion is highly appreciated.

EDIT: output of netstat -antp

```<code> (Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State           PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      2477/nginx: worker
tcp        0      0 0.0.0.0:57219           0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:11300         0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:6379            0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN          2477/nginx: worker
tcp        0      0 10.0.2.15:22            10.0.2.2:50267          ESTABLISHED -
tcp6       0      0 :::22                   :::*                    LISTEN      -
tcp6       0      0 :::5432                 :::*                    LISTEN      -
tcp6       0      0 :::47876                :::*                    LISTEN            -
tcp6       0      0 :::6379                 :::*                    LISTEN      -
tcp6       0      0 :::111                  :::*                    LISTEN      -
</code>```

答:
That worked for me:

from your virtual machine bash, go to the paste /etc/nginx/sites-enabled/

there, run ls -la

you will see your projects there

run sudo nano "your project name"

look for the line: fastcgi-pass ... php/php7.number...

update the "number" variable with 2, so you get: fastcgi-pass ... php/php7.2...

restart nginx and php services with: sudo service nginx restart && sudo service php7.*-fpm restart

than try to run your site again

Body:
Its been 3 days now, still I am unable to solve this. I have just installed the vagrant box on my Yosemite. I am learning to work with vm. Following the steps over Laravel Homestead I had installed vagrant box of homestead. But its giveing me 502 Bad gateway. I had set up laravel.local in host file also.

I tried other links for ngnix (1.8.0) but, I am unable to run laravel on homestead vm!!?

This is the output of /var/log/nginx/laravel.local-error.log

2015/07/12 18:54:31 [error] 957#0: *20 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.10.1, server: la5.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "la5.dev"
2015/07/12 19:03:07 [error] 1957#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.10.1, server: la5.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "la5.dev"
2015/07/12 19:04:33 [error] 2006#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.10.1, server: la5.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "la5.dev"

vagrant@homestead:/var/log/nginx$

And this is my Homestead.yaml

ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
- ~/.ssh/id_rsa

folders:
- map: /Users/maahedev/code/la5
  to: /home/vagrant/la5

sites:
- map: la5.dev
  to: /home/vagrant/la5/public

databases:
- homestead

variables:
- key: APP_ENV
  value: local

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 93000
#       to: 9300
#     - send: 7777
#       to: 777
#       protocol: udp

Any help/suggestion is highly appreciated.

EDIT: output of netstat -antp

 (Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State           PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      2477/nginx: worker
tcp        0      0 0.0.0.0:57219           0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:11300         0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:6379            0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN          2477/nginx: worker
tcp        0      0 10.0.2.15:22            10.0.2.2:50267          ESTABLISHED -
tcp6       0      0 :::22                   :::*                    LISTEN      -
tcp6       0      0 :::5432                 :::*                    LISTEN      -
tcp6       0      0 :::47876                :::*                    LISTEN            -
tcp6       0      0 :::6379                 :::*                    LISTEN      -
tcp6       0      0 :::111                  :::*                    LISTEN      -


问:
How to debug Google app engine Sever Error 500?
I deployed a Django web app to GAE, no errors during deployment.
But whenI try to open the website, it shows Server Error (500).

I tried to see some logs using gcloud app logs read, it only shows

```<code>2020-05-28 16:07:48 default[20200528t144758]  [2020-05-28 16:07:48 +0000] [1] [INFO] Handling signal: term
2020-05-28 16:07:48 default[20200528t144758]  [2020-05-28 16:07:48 +0000] [8] [INFO] Worker exiting (pid: 8)
2020-05-28 16:07:49 default[20200528t144758]  [2020-05-28 16:07:49 +0000] [1] [INFO] Shutting down: Master
2020-05-28 16:07:49 default[20200528t144758]  [2020-05-28 16:07:49 +0000] [1] [INFO] Handling signal: term
2020-05-28 16:07:49 default[20200528t144758]  [2020-05-28 16:07:49 +0000] [8] [INFO] Worker exiting (pid: 8)
2020-05-28 16:07:50 default[20200528t144758]  [2020-05-28 16:07:50 +0000] [1] [INFO] Shutting down: Master
2020-05-28 16:08:06 default[20200528t165550]  "GET /" 500
</code>```

The logs are not informative, so I wonder

1) if I could logon to the App Engine machine, and run my web application manually and see what's the error?

2) if not, what are the suggested ways to debug app engine errors?

答: By setting the DEBUG=1 in Django project settings.py, now I'm able to see error details on GAE.

Body:
I deployed a Django web app to GAE, no errors during deployment.
But whenI try to open the website, it shows Server Error (500).

I tried to see some logs using gcloud app logs read, it only shows

2020-05-28 16:07:48 default[20200528t144758]  [2020-05-28 16:07:48 +0000] [1] [INFO] Handling signal: term
2020-05-28 16:07:48 default[20200528t144758]  [2020-05-28 16:07:48 +0000] [8] [INFO] Worker exiting (pid: 8)
2020-05-28 16:07:49 default[20200528t144758]  [2020-05-28 16:07:49 +0000] [1] [INFO] Shutting down: Master
2020-05-28 16:07:49 default[20200528t144758]  [2020-05-28 16:07:49 +0000] [1] [INFO] Handling signal: term
2020-05-28 16:07:49 default[20200528t144758]  [2020-05-28 16:07:49 +0000] [8] [INFO] Worker exiting (pid: 8)
2020-05-28 16:07:50 default[20200528t144758]  [2020-05-28 16:07:50 +0000] [1] [INFO] Shutting down: Master
2020-05-28 16:08:06 default[20200528t165550]  "GET /" 500

The logs are not informative, so I wonder

1) if I could logon to the App Engine machine, and run my web application manually and see what's the error?

2) if not, what are the suggested ways to debug app engine errors?


问:
How can I get an Input from a User with using CPUlator in ARM Assembly language
I am currently working on a new project. I need to get input from the user. How can I get input from the user using ARM assembly language in CPUlator?

The work I have done so far is as follows

```<code>.global _start
 _start:

LDR R11, =0xFF200100  // buttons adress
LDR R6, [R11] //adress to buttons for get value

 end: B end
 .end
</code>```

CPUlator link: https://cpulator.01xz.net/?sys=arm-de1soc

Any help will be very helpful, Thank you.

答:
Well, you're on the right track. The pushbuttons of CPUlator correspond to the bits in the word in memory at the fixed address of 0xFF200050. So the following will read the word into the r0 register:

```<code>ldr r0, =0xFF200050  //Load the address into a register
ldr r0, [r0] //Load the contents of that address
//Now let's do something with that number...
</code>```

If you check, for example, pushbuttons 0 and 2, that'll give you 5 in r0. Will that do?

The memory address that the button state can be read from is helpfully written in the panel header of CPUlator on the right. The switches panel corresponds to the word at 0xFF200040. I'm not sure what's at 0xFF200100. On a physical device, pushbuttons and switches are probably distinct, but in the CPUlator, I can't see any difference. Use the input source that you like better.

There's also a keyboard panel in the devices, but the processing of that would be more involved.

Body:
I am currently working on a new project. I need to get input from the user. How can I get input from the user using ARM assembly language in CPUlator?

The work I have done so far is as follows

.global _start
 _start:

LDR R11, =0xFF200100  // buttons adress
LDR R6, [R11] //adress to buttons for get value

 end: B end
 .end

CPUlator link: https://cpulator.01xz.net/?sys=arm-de1soc

Any help will be very helpful, Thank you.

Body:
Well, you're on the right track. The pushbuttons of CPUlator correspond to the bits in the word in memory at the fixed address of 0xFF200050. So the following will read the word into the r0 register:

ldr r0, =0xFF200050  //Load the address into a register
ldr r0, [r0] //Load the contents of that address
//Now let's do something with that number...

If you check, for example, pushbuttons 0 and 2, that'll give you 5 in r0. Will that do?

The memory address that the button state can be read from is helpfully written in the panel header of CPUlator on the right. The switches panel corresponds to the word at 0xFF200040. I'm not sure what's at 0xFF200100. On a physical device, pushbuttons and switches are probably distinct, but in the CPUlator, I can't see any difference. Use the input source that you like better.

There's also a keyboard panel in the devices, but the processing of that would be more involved.


问:
How to change text color when custom cursor is on hover
When red cursor is hover on Works text, i want to change the Works text color black to blue and text will be zoom In on that red cursor area. anyone suggest me how to do this in JavaScript

   jQuery(document).ready(function() {
        var mouseX = 0, mouseY = 0;
        var xp = 0, yp = 0;
        $(document).mousemove(function(e){
            mouseX = e.pageX - 30;
            mouseY = e.pageY - 30;
        });
        setInterval(function(){
            xp += ((mouseX - xp)/6);
            yp += ((mouseY - yp)/6);
            $(".cursor").css({left: xp +'px', top: yp +'px'});
        }, 20);
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> h1{
        text-align: center;
        font-size: 5rem;
        margin-top: 20%;
    }
    .cursor{
        position: absolute;
        background: red;
        width: 100px;
        height: 100px;
        border-radius: 50px;
    }</code>```

Works

```

答:
Consider the following code example.

jQuery(function($) {
  var mouseX = 0,
    mouseY = 0,
    xp = 0,
    yp = 0;

  function isOver(e, obj) {
    var o = false,
      x = e.pageX,
      y = e.pageY;
    var pos = obj.offset();
    pos = {
      x1: pos.left,
      y1: pos.top,
      x2: pos.left + obj.width(),
      y2: pos.top + obj.height()
    };
    if ((x >= pos.x1 && x <= pos.x2) && (y >= pos.y1 && y <= pos.y2)) {
      o = true;
    }
    return o;
  }

  function moveCursor(evt) {
    mouseX = evt.pageX - 30;
    mouseY = evt.pageY - 30;
    xp += ((mouseX - xp) / 6);
    yp += ((mouseY - yp) / 6);
    $(".cursor").css({
      left: xp + 'px',
      top: yp + 'px'
    });
    if (isOver(evt, $("h1"))) {
      $("h1").addClass("blue zoom");
    } else {
      $("h1").removeClass("blue zoom");
    }
  }

  $(document).mousemove(moveCursor);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1 {
  text-align: center;
  font-size: 5rem;
  margin-top: 20%;
  transform: scale(1);
}

.blue {
  color: blue;
}

.zoom {
  transform: scale(1.25);
}

.cursor {
  position: absolute;
  background: rgba(255, 0, 0, 0.45);
  width: 100px;
  height: 100px;
  border-radius: 50px;
}</code>```

Works

```

It was not clear to me what you mean by "text will be zoom In on that red cursor area." I suspect you can transform the text maybe? At least this way you can trigger the zoom action you want.

This uses basic collision detection to determine if the mouse isOver() a specific element.

Body:
When red cursor is hover on Works text, i want to change the Works text color black to blue and text will be zoom In on that red cursor area. anyone suggest me how to do this in JavaScript

   jQuery(document).ready(function() {
        var mouseX = 0, mouseY = 0;
        var xp = 0, yp = 0;
        $(document).mousemove(function(e){
            mouseX = e.pageX - 30;
            mouseY = e.pageY - 30;
        });
        setInterval(function(){
            xp += ((mouseX - xp)/6);
            yp += ((mouseY - yp)/6);
            $(".cursor").css({left: xp +'px', top: yp +'px'});
        }, 20);
    });

 h1{
        text-align: center;
        font-size: 5rem;
        margin-top: 20%;
    }
    .cursor{
        position: absolute;
        background: red;
        width: 100px;
        height: 100px;
        border-radius: 50px;
    }

Works

Body:
Consider the following code example.

jQuery(function($) {
  var mouseX = 0,
    mouseY = 0,
    xp = 0,
    yp = 0;

  function isOver(e, obj) {
    var o = false,
      x = e.pageX,
      y = e.pageY;
    var pos = obj.offset();
    pos = {
      x1: pos.left,
      y1: pos.top,
      x2: pos.left + obj.width(),
      y2: pos.top + obj.height()
    };
    if ((x >= pos.x1 && x <= pos.x2) && (y >= pos.y1 && y <= pos.y2)) {
      o = true;
    }
    return o;
  }

  function moveCursor(evt) {
    mouseX = evt.pageX - 30;
    mouseY = evt.pageY - 30;
    xp += ((mouseX - xp) / 6);
    yp += ((mouseY - yp) / 6);
    $(".cursor").css({
      left: xp + 'px',
      top: yp + 'px'
    });
    if (isOver(evt, $("h1"))) {
      $("h1").addClass("blue zoom");
    } else {
      $("h1").removeClass("blue zoom");
    }
  }

  $(document).mousemove(moveCursor);
});

h1 {
  text-align: center;
  font-size: 5rem;
  margin-top: 20%;
  transform: scale(1);
}

.blue {
  color: blue;
}

.zoom {
  transform: scale(1.25);
}

.cursor {
  position: absolute;
  background: rgba(255, 0, 0, 0.45);
  width: 100px;
  height: 100px;
  border-radius: 50px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Works</h1>
<div class="cursor"></div>

It was not clear to me what you mean by "text will be zoom In on that red cursor area." I suspect you can transform the text maybe? At least this way you can trigger the zoom action you want.

This uses basic collision detection to determine if the mouse isOver() a specific element.


问:
How to get a new array containing some random elements from an old array in Javascript
I am making a quiz app in react native, it has this array of objects in which each object contains a question statement,choices and the correct choice. There will be total 15 objects in this, but i require a new array that contains only 5 of the objects of this array. They should be selected at random everytime i start the quiz.
How to get that array, help</p>

```<code>const questions = [
    new quizQuestions(
        'What is capital of Pakistan?',
        ['Karachi', 'Islamabad', 'Lahore', 'Peshawar'],
        'Islamabad',
    ),
    new quizQuestions(
        'What is capital of India?',
        ['delhi', 'Islamabad', 'zcjzj', 'Peshawar'],
        'delhi',
    ),
    new quizQuestions(
        'What is capital of Pakistan?',
        ['Karachi', 'Islamabad', 'Lahore', 'Peshawar'],
        'Islamabad',
    ),
]
</code>```

答:
Almost a repeat of Azad's answer :D but I found our method to be very simple and straight forward.
pass in selectedQuestions as an empty array

function randomizeQuestions(allQuestions,selectedQuestions,numberToSelect)
{
  selectedIndex = [];
  var randIndex;
  for(var i = 0; i < numberToSelect; i++)
  {

   do{
      randIndex = Math.floor(Math.random() * allQuestions.length);
   }while(selectedIndex.includes(randIndex));

   selectedIndex.push(randIndex);
   selectedQuestions.push(allQuestions[randIndex]);
  }
}```

Body:
I am making a quiz app in react native, it has this array of objects in which each object contains a question statement,choices and the correct choice. There will be total 15 objects in this, but i require a new array that contains only 5 of the objects of this array. They should be selected at random everytime i start the quiz.
How to get that array, help

const questions = [
    new quizQuestions(
        'What is capital of Pakistan?',
        ['Karachi', 'Islamabad', 'Lahore', 'Peshawar'],
        'Islamabad',
    ),
    new quizQuestions(
        'What is capital of India?',
        ['delhi', 'Islamabad', 'zcjzj', 'Peshawar'],
        'delhi',
    ),
    new quizQuestions(
        'What is capital of Pakistan?',
        ['Karachi', 'Islamabad', 'Lahore', 'Peshawar'],
        'Islamabad',
    ),
]


问:
Rust need help refactoring excessive functions
(i should mention im pretty new to rust)

hi! im building a 2d particle simulation game using a Vec to hold structs with the info on each particle. right now i need to write out a separate function every time i want to check if an element is touching something with a certain property. basically it searches around the particle in a circle by calculating the index of that position then compares that structs property to the target property like so:

```<code>//check around particle for corrodable particles
pub fn check_touch_corrode(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].corrode {return calc::ul(x_pos)}     //if particle can corrode return particle
    if screen[calc::u(x_pos)].corrode {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].corrode {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].corrode {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].corrode {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].corrode {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].corrode {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].corrode {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

//check around particle for flammable particle
pub fn check_touch_flammable(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].flammable {return calc::ul(x_pos)}   //if particle flammable return particle
    if screen[calc::u(x_pos)].flammable {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].flammable {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].flammable {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].flammable {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].flammable {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].flammable {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].flammable {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}
</code>```

this isnt really scalable considering im planning on having hundreds of elements with all kinds of different properties and interactions. im really wondering if there is any way to reduce this down to one function. ive been messing around with it on my own for a while now and havent been able to make any progress. the issue im running into is that the comparison needs to be calculated in the function and cant be passed in as far as i can tell. is there any way to fix this? like make it so i pass something that says which field of the struct i want to compare after it calculates that the structs index?

答:
I think you want something like this:

// The function returns a tuple of indices, instead of having two functions that return one index each
pub fn check_touch_corrode_flammable(screen: &mut Vec<Particle>, x_pos: usize) -> (usize, usize) {

  let mut results : (usize, usize) = (x_pos, x_pos);

  // We keep track so that we can skip checking cells
  let mut found_corr = false;
  let mut found_flam = false;

  let ul = screen[calc::ul(x_pos)];

  if ul.corrode {
    results.0 = ul;
    found_corr = true;
  }

  if ul.flammable {
    results.1 = ul;
    found_flam = true;
  }

  let u = screen[calc::u(x_pos)];

  if !found_corr && u.corrode {
    results.0 = u;
    found_corr = true;
  }

  if !found_flam && u.flammable) {
    results.1 = u;
    found_flam = true;
  }

  let ur = screen[calc::ur(x_pos)];

  if !found_corr && ur.corrode {
    results.0 = ur;
    found_corr = true;
  }

  if !found_flam && ur.flammable) {
    results.1 = ur;
    found_flam = true;
  }

  // Continuing like this...

  // ...

  // And then at the end:

  let dr = screen[calc::dr(x_pos)];

  if !found_corr && dr.corrode {
    results.0 = dr;
    found_corr = true;
  }

  if !found_flam && dr.flammable) {
    results.1 = dr;
    found_flam = true;
  }

  results
}
```

The main advantage of this solution is that it calculates the indices for the cells we are checking in each direction only once.

Is this more or less what you needed? Lemme know if you need more help :)

Body:
(i should mention im pretty new to rust)

hi! im building a 2d particle simulation game using a Vec to hold structs with the info on each particle. right now i need to write out a separate function every time i want to check if an element is touching something with a certain property. basically it searches around the particle in a circle by calculating the index of that position then compares that structs property to the target property like so:

//check around particle for corrodable particles
pub fn check_touch_corrode(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].corrode {return calc::ul(x_pos)}     //if particle can corrode return particle
    if screen[calc::u(x_pos)].corrode {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].corrode {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].corrode {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].corrode {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].corrode {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].corrode {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].corrode {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

//check around particle for flammable particle
pub fn check_touch_flammable(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].flammable {return calc::ul(x_pos)}   //if particle flammable return particle
    if screen[calc::u(x_pos)].flammable {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].flammable {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].flammable {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].flammable {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].flammable {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].flammable {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].flammable {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

this isnt really scalable considering im planning on having hundreds of elements with all kinds of different properties and interactions. im really wondering if there is any way to reduce this down to one function. ive been messing around with it on my own for a while now and havent been able to make any progress. the issue im running into is that the comparison needs to be calculated in the function and cant be passed in as far as i can tell. is there any way to fix this? like make it so i pass something that says which field of the struct i want to compare after it calculates that the structs index?

Body:
I think you want something like this:

// The function returns a tuple of indices, instead of having two functions that return one index each
pub fn check_touch_corrode_flammable(screen: &mut Vec<Particle>, x_pos: usize) -> (usize, usize) {

  let mut results : (usize, usize) = (x_pos, x_pos);

  // We keep track so that we can skip checking cells
  let mut found_corr = false;
  let mut found_flam = false;

  let ul = screen[calc::ul(x_pos)];

  if ul.corrode {
    results.0 = ul;
    found_corr = true;
  }

  if ul.flammable {
    results.1 = ul;
    found_flam = true;
  }

  let u = screen[calc::u(x_pos)];

  if !found_corr && u.corrode {
    results.0 = u;
    found_corr = true;
  }

  if !found_flam && u.flammable) {
    results.1 = u;
    found_flam = true;
  }

  let ur = screen[calc::ur(x_pos)];

  if !found_corr && ur.corrode {
    results.0 = ur;
    found_corr = true;
  }

  if !found_flam && ur.flammable) {
    results.1 = ur;
    found_flam = true;
  }

  // Continuing like this...

  // ...

  // And then at the end:

  let dr = screen[calc::dr(x_pos)];

  if !found_corr && dr.corrode {
    results.0 = dr;
    found_corr = true;
  }

  if !found_flam && dr.flammable) {
    results.1 = dr;
    found_flam = true;
  }

  results
}

The main advantage of this solution is that it calculates the indices for the cells we are checking in each direction only once.

Is this more or less what you needed? Lemme know if you need more help :)


问:
Check if PHP session_id is in use
I am building a web-app that users can upload certain files and work on them through the web-app interface. I need to store these files for the length of a users session. I am creating a folder for each user using the session_id  as the folder name and storing the files in there.

The problem: There is nothing to indicate that a user walked away from my site and the session is going out of use. I need a cleanup script that takes the name of each folder and checks if that session_id is still active in order to delete unused and now unreachable folders. How can I do this?

答:
If you have access to the crontab or scheduled tasks of the server you could create a php file that only is allowed to execute locally which checks the expiration Date/Time value of all sessions found in your database.  Each time a user updates this expiration Date/Time value would be updated to their next timeout value (+30 minutes, etc.).

Your scheduled task/crontab would find all those users who idled out and clean up the mess they left without logging off.  I wouldn't suggest to have your scheduled task/crontab run too often.  At least have the reoccurance spaced out a number of minutes that makes sense for your situation.

Title: Check if PHP session_id is in use


问:
Greedy algorithm Python. Get all sequences
Trying to get through DP and Greedy algorithms. Please help!

Input has time, range and price. For eg. - (start, end, price) [(0,1,9), (0,3,8),(2,6,5),....(6,11,10)]. If days_for_trading=2, program should give the highest profit, which are (0,1,9),(6,11,10). But it stops on the first satisfied condition with days range (0,1,9), (2,6,5).

Don't know really how to make this iterating further. Thanks!

Updates: Thanks for all participants. It's solved. But the current algorithm doesn't fit the limit of memory usage. I kept the link to the task in comments below if someone needs it

```<code>def get_max(tmp, days_for_trading):
    global best_profit
    for day_start, day_end, price in tmp:
        traiding_sequence=[]
        cur_profit=0
        count=0
        deal=(day_start, day_end, price)
        traiding_sequence.append(deal)
        cur_profit+=price
        for next_day_start, next_day_end, next_price in tmp:
            if days_for_trading==len(traiding_sequence):
                break
            else:
                if next_day_start>traiding_sequence[count][1]:
                    next_deal=(next_day_start, next_day_end, next_price)
                    traiding_sequence.append(next_deal)
                    cur_profit+=next_price
                    count+=1
        best_profit=cur_profit if cur_profit>best_profit else best_profit
</code>```

答:
I assume it is this line as you are excluding the last trading sequence with it (and there there is a typo in your variable)

```<code>if days_for_trading==len(traiding_sequence):
    break
</code>```

try it with

```<code>if days_for_trading > len(traiding_sequence):
    break
</code>```

Body:
Trying to get through DP and Greedy algorithms. Please help!

Input has time, range and price. For eg. - (start, end, price) [(0,1,9), (0,3,8),(2,6,5),....(6,11,10)]. If days_for_trading=2, program should give the highest profit, which are (0,1,9),(6,11,10). But it stops on the first satisfied condition with days range (0,1,9), (2,6,5).

Don't know really how to make this iterating further. Thanks!

Updates: Thanks for all participants. It's solved. But the current algorithm doesn't fit the limit of memory usage. I kept the link to the task in comments below if someone needs it

def get_max(tmp, days_for_trading):
    global best_profit
    for day_start, day_end, price in tmp:
        traiding_sequence=[]
        cur_profit=0
        count=0
        deal=(day_start, day_end, price)
        traiding_sequence.append(deal)
        cur_profit+=price
        for next_day_start, next_day_end, next_price in tmp:
            if days_for_trading==len(traiding_sequence):
                break
            else:
                if next_day_start>traiding_sequence[count][1]:
                    next_deal=(next_day_start, next_day_end, next_price)
                    traiding_sequence.append(next_deal)
                    cur_profit+=next_price
                    count+=1
        best_profit=cur_profit if cur_profit>best_profit else best_profit

Body:
I assume it is this line as you are excluding the last trading sequence with it (and there there is a typo in your variable)

if days_for_trading==len(traiding_sequence):
    break

try it with

if days_for_trading > len(traiding_sequence):
    break


问:
How to convert Active Directory objectGUID to UUID in Coldfusion
I have a CFLDAP query returning the objectGUID. How can I convert this to a valid UUID string in a 8-4-4-4-12 pattern in ColdFusion?

I have specified returnAsBinary="ObjectGUID", but toString(getLDAP.ObjectGUID) does not return the desired result.

Update:

I tried binaryEncode():

```<code><cfset guid = binaryencode(getLDAP.objectguid,"HEX")>
</code>```

Which returns:

```<code>18E0CE3388B79C4EA4D73894AE8CD8F6
</code>```

But I'm expecting this (was extracted and supplied by another process that I cant see their conversion steps).

```<code>3cee018-b788-4e9c-a4d7-3894ae8cd8f6
</code>```

Hummm... Although they don't match, the last half is the same. a4d7-3894ae8cd8f6.

答:
Here is a javascript implementation I did for a Pentaho Kettle "Modified Javascript" step.

It receives the objectGUID from Java as byte[16] array, and continues to use Java classes for processing.

```<code>var b = objectGUID; // JavaArray

// the byte order is: [3] [2] [1] [0] - [5] [4] - [7] [6] - [8] [9] - [10] [11] [12] [13] [14] [15]
var theByteOrder = [3,2,1,0,5,4,7,6,8,9,10,11,12,13,14,15];

var ordered = new java.io.ByteArrayOutputStream(16);
theByteOrder.forEach(function(i) {
    ordered.write(b[i]);
});

var bb = java.nio.ByteBuffer.wrap(ordered.toByteArray());
bb.order(java.nio.ByteOrder.BIG_ENDIAN);
var uuid = new java.util.UUID(bb.getLong(), bb.getLong());

var GUID = uuid.toString();
</code>```

it's not coldfusion dialect, yes, but hopefully it will be useful for somebody scanning the web to solve a similar task.

Body:
I have a CFLDAP query returning the objectGUID. How can I convert this to a valid UUID string in a 8-4-4-4-12 pattern in ColdFusion?

I have specified returnAsBinary="ObjectGUID", but toString(getLDAP.ObjectGUID) does not return the desired result.

Update:

I tried binaryEncode():

<cfset guid = binaryencode(getLDAP.objectguid,"HEX")>

Which returns:

18E0CE3388B79C4EA4D73894AE8CD8F6

But I'm expecting this (was extracted and supplied by another process that I cant see their conversion steps).

3cee018-b788-4e9c-a4d7-3894ae8cd8f6

Hummm... Although they don't match, the last half is the same. a4d7-3894ae8cd8f6.

Body:
Here is a javascript implementation I did for a Pentaho Kettle "Modified Javascript" step.

It receives the objectGUID from Java as byte[16] array, and continues to use Java classes for processing.

var b = objectGUID; // JavaArray

// the byte order is: [3] [2] [1] [0] - [5] [4] - [7] [6] - [8] [9] - [10] [11] [12] [13] [14] [15]
var theByteOrder = [3,2,1,0,5,4,7,6,8,9,10,11,12,13,14,15];

var ordered = new java.io.ByteArrayOutputStream(16);
theByteOrder.forEach(function(i) {
    ordered.write(b[i]);
});

var bb = java.nio.ByteBuffer.wrap(ordered.toByteArray());
bb.order(java.nio.ByteOrder.BIG_ENDIAN);
var uuid = new java.util.UUID(bb.getLong(), bb.getLong());

var GUID = uuid.toString();

it's not coldfusion dialect, yes, but hopefully it will be useful for somebody scanning the web to solve a similar task.


问:
Subclass UIButton with system font, bold, and kerning
You have to use attributed text to do kerning. But. On the other hand, you can't get at system fonts in the IB attributed text menu.

How do I make (in code) a UIButton which has

system font, weight bold

size 11

kern attribute set to -2

Ideally it would collect the text of the button from plain text Title in IB. But if the text has to be set in code that is fine.

```<code>class NiftyButton: UIButton {
    ????
}
</code>```

Normally I initialize UIButton like this .. but I don't even know if that's the best place to do this?  (You can't do it in layoutSubviews, since it will loop of course.)

```<code>class InitializeyButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        common()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    func common() {
        ...
    }
}
</code>```

How to achieve in code ...

system font, weight bold

size 11

kern attribute set to -2

答:
Here is the class you can use to get the desired result:</p>

```<code>class InitializeyButton: UIButton {

   @IBInspectable var spacing:CGFloat = 0 {
      didSet {
        updateTitleOfLabel()
      }
   }

   override func setTitle(_ title: String?, for state: UIControl.State) {

        let color = super.titleColor(for: state) ?? UIColor.black
        let attributedTitle = NSAttributedString(
            string: title ?? "",
            attributes: [NSAttributedString.Key.kern: spacing,
                         NSAttributedString.Key.foregroundColor: color,
                         NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.titleLabel?.font.pointSize ?? 11, weight: .bold)   ])
        super.setAttributedTitle(attributedTitle, for: state)
   }

  private func updateTitleOfLabel() {
    let states:[UIControl.State] = [.normal, .highlighted, .selected, .disabled]
      for state in states {
        let currentText = super.title(for: state)
        self.setTitle(currentText, for: state)
      }
   }
}
</code>```

Body:
You have to use attributed text to do kerning. But. On the other hand, you can't get at system fonts in the IB attributed text menu.

How do I make (in code) a UIButton which has

system font, weight bold

size 11

kern attribute set to -2

Ideally it would collect the text of the button from plain text Title in IB. But if the text has to be set in code that is fine.

class NiftyButton: UIButton {
    ????
}

Normally I initialize UIButton like this .. but I don't even know if that's the best place to do this?  (You can't do it in layoutSubviews, since it will loop of course.)

class InitializeyButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        common()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    func common() {
        ...
    }
}

How to achieve in code ...

system font, weight bold

size 11

kern attribute set to -2

Body:
Here is the class you can use to get the desired result:

class InitializeyButton: UIButton {

   @IBInspectable var spacing:CGFloat = 0 {
      didSet {
        updateTitleOfLabel()
      }
   }

   override func setTitle(_ title: String?, for state: UIControl.State) {

        let color = super.titleColor(for: state) ?? UIColor.black
        let attributedTitle = NSAttributedString(
            string: title ?? "",
            attributes: [NSAttributedString.Key.kern: spacing,
                         NSAttributedString.Key.foregroundColor: color,
                         NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.titleLabel?.font.pointSize ?? 11, weight: .bold)   ])
        super.setAttributedTitle(attributedTitle, for: state)
   }

  private func updateTitleOfLabel() {
    let states:[UIControl.State] = [.normal, .highlighted, .selected, .disabled]
      for state in states {
        let currentText = super.title(for: state)
        self.setTitle(currentText, for: state)
      }
   }
}


问:
Getting a constant value from a series
I want to assign a constant value to a variable. This value comes from a series. The value is 10 bars back, and must stay constant unless there is a new bar.

I tried this code and lots of variations on it, but it didn't work.

```<code>//@version=4
study(title = "X", overlay = false)

var x = 0.0
x := valuewhen(barstate.islast, sum(cht_acum[10], 10), 1)

plot(x, title = "X")
</code>```

I don't get a straight line, or I get NA. How to resolve the issue?

答:
Version 1

Hard to figure out what you want. This may come close. You can use the Inputs to plot only on the last bar:

```<code>//@version=4
study(title = "X", overlay = false)
cht_acum = close
plotOnLastBarOnly = input(false)
x = sum(cht_acum[10], 10)
plot(barstate.islast or not plotOnLastBarOnly ? x : na, title = "X")
</code>```

Version 2

This version uses the brilliant Sum() function from alexgrover found in Functions Allowing Series As Length - PineCoders FAQ, which accepts a series length. Should be closer to your needs:

```<code>//@version=4
study("")
Sum(src,p) => a = cum(src), a - a[max(p,0)]
cond = rising(close, 30)
sourceSeries = 1.
var count = 0.
if cond
    count := 1.
else
    count := min(10, count + 1)
total = Sum(sourceSeries, count)
plot(total)
plotchar(cond, "cond", "•", location.top, size = size.tiny)
</code>```

Title: Getting a constant value from a series

Body:
I want to assign a constant value to a variable. This value comes from a series. The value is 10 bars back, and must stay constant unless there is a new bar.

I tried this code and lots of variations on it, but it didn't work.

//@version=4
study(title = "X", overlay = false)

var x = 0.0
x := valuewhen(barstate.islast, sum(cht_acum[10], 10), 1)

plot(x, title = "X")

I don't get a straight line, or I get NA. How to resolve the issue?

Body:
Version 1

Hard to figure out what you want. This may come close. You can use the Inputs to plot only on the last bar:

//@version=4
study(title = "X", overlay = false)
cht_acum = close
plotOnLastBarOnly = input(false)
x = sum(cht_acum[10], 10)
plot(barstate.islast or not plotOnLastBarOnly ? x : na, title = "X")

Version 2

This version uses the brilliant Sum() function from alexgrover found in Functions Allowing Series As Length - PineCoders FAQ, which accepts a series length. Should be closer to your needs:

//@version=4
study("")
Sum(src,p) => a = cum(src), a - a[max(p,0)]
cond = rising(close, 30)
sourceSeries = 1.
var count = 0.
if cond
    count := 1.
else
    count := min(10, count + 1)
total = Sum(sourceSeries, count)
plot(total)
plotchar(cond, "cond", "•", location.top, size = size.tiny)


问:
Why does dbClearResult() take so long?
I am baffled why a simple query takes so long when executed through MySQLConnect()
I have a MySQL database ncol = 25 and nrow = 10000 is a samll databases,I would like to use MySQLConnect() get some dataframe ,but it's always take a lot of time

      dbClearResult(dbSendQuery)  #take long time but why
      dbDisconnect(DBConnect)   #take long time but why
```

<p>I checked Intelnet ,it's okey ,i use SequelPro for sure it was fast.</p>

<p>this is full code:</p>

```library("DBI")
library("RMySQL")
library("dplyr")
library("data.table")

    MySQLConnect <- function(N=1000) {
      DBConnect <- dbConnect(RMySQL::MySQL(),
                user = "root",
                password = "root",
                dbname = "root",
                host = "root",
                port = 3306,
                )
      dbSendQuery <- dbSendQuery(DBConnect, "SELECT * FROM TABLE")
      dbFetch <- dbFetch(dbSendQuery, n=N)
      data.table <- data.table(dbFetch)
      dbClearResult(dbSendQuery)
      dbDisconnect(DBConnect)
      return(data.table)
      }

#platform       x86_64-apple-darwin15.6.0
#arch           x86_64
#os             darwin15.6.0
#system         x86_64, darwin15.6.0
#status
#major          3
#minor          6.1
#year           2019
#month          07
#day            05
#svn rev        76782
#language       R
#version.string R version 3.6.1 (2019-07-05)
#nickname       Action of the Toes
```

<p>if i was send this, can be disconnect in immediately</p>

<pre class="lang-sql prettyprint-override"><code>SHOW PROCESSLIST FOR SEARCH "SELECT * FROM TABLE" ID;
KILL THIS ID;
"Closing open result sets"
</code>```

how can i do this code for best?

Reason

```<code>  dbSendQuery <- dbSendQuery(DBConnect, "SELECT * FROM TABLE") #it's not run end over so dbClearResult(dbSendQuery) and dbDisconnect(DBConnect) is waiting
</code>```

答:
Very often, it is forgotten that R by default tries to load the whole data frame into the computer's memory, which is a big problem for large tables.

In your examples, you expect linearity in time (1k records : 1-2 seconds :: 10k records : 10-20 seconds), however you may not be taking into account that 10k records may not fit in your computer's available physical memory.

That's when memory swap comes in, usually wrecking havoc.

Usually, it feels like your computer is freezing, even with little to no processing at all (looking through htop linux command's glasses, for instance), because memory swap is rarely signalled by the OS.

So, it is possible that your table is already in your computer (i.e., in the connection layers below R itself) and the bottleneck occurs the minute R tries to choke the memory full of data, when also it starts slowing everything: receiving more data from your server, reacting to your interaction with mouse and keyboard.  For this reason, you can log in to your SQL server's monitor and kill the query right away, because it does not depend on R listening to you for, then, responding.

If you are curious enough, you can try using microbenchmark package to make a response curve for processing time in function of batch size to discover when the linearity breaks downs.

Available solutions:

download the full table locally and work it locally

parallelize the processing if you want

using large data set packages: bigmemory, data.table

discover your bootleneck batch size and work accordingly with batch sizes that big

dbFetch()ing blocks that large and processing them

Title: Why does dbClearResult() take so long?

Body:
I am baffled why a simple query takes so long when executed through MySQLConnect()
I have a MySQL database ncol = 25 and nrow = 10000 is a samll databases,I would like to use MySQLConnect() get some dataframe ,but it's always take a lot of time

      dbClearResult(dbSendQuery)  #take long time but why
      dbDisconnect(DBConnect)   #take long time but why

I checked Intelnet ,it's okey ,i use SequelPro for sure it was fast.

this is full code:

library("DBI")
library("RMySQL")
library("dplyr")
library("data.table")

    MySQLConnect <- function(N=1000) {
      DBConnect <- dbConnect(RMySQL::MySQL(),
                user = "root",
                password = "root",
                dbname = "root",
                host = "root",
                port = 3306,
                )
      dbSendQuery <- dbSendQuery(DBConnect, "SELECT * FROM TABLE")
      dbFetch <- dbFetch(dbSendQuery, n=N)
      data.table <- data.table(dbFetch)
      dbClearResult(dbSendQuery)
      dbDisconnect(DBConnect)
      return(data.table)
      }

#platform       x86_64-apple-darwin15.6.0
#arch           x86_64
#os             darwin15.6.0
#system         x86_64, darwin15.6.0
#status
#major          3
#minor          6.1
#year           2019
#month          07
#day            05
#svn rev        76782
#language       R
#version.string R version 3.6.1 (2019-07-05)
#nickname       Action of the Toes

if i was send this, can be disconnect in immediately

SHOW PROCESSLIST FOR SEARCH "SELECT * FROM TABLE" ID;
KILL THIS ID;
"Closing open result sets"

how can i do this code for best?

Reason

  dbSendQuery <- dbSendQuery(DBConnect, "SELECT * FROM TABLE") #it's not run end over so dbClearResult(dbSendQuery) and dbDisconnect(DBConnect) is waiting


问:
Google App Engine dev_appserver throws error 'python2: command not found' after upgrade to Python 3
Until yesterday I was successfully using the dev_appserver.py app.yaml --enable_console for my development.
Yesterday I attempted to upgrade to python 3.7 for my development.
The upgrade seemed to be Ok, but now I get the following error message.

```<code>server:bones brian$ dev_appserver.py app.yaml --enable_console
ERROR: (dev_appserver) python2: command not found
</code>```

app.yaml:

```<code>application: bones
version: 1
runtime: python37
entrypoint: gunicorn -b :$PORT main:app
api_version: 1
threadsafe: true

handlers:
- url: /static
  static_dir: static

- url: /.*
  script: main.app
</code>```

I am using Mac OS X 10.11.6.

Why is dev_appserver even looking for python2?
And how can I fix this?

答:
I've got a Python 3.7 Google App Engine project and am unable to execute the dev_appserver.py command for the same reason (python2: command not found). For various reasons, it isn't feasible to downgrade to Python 2.7.

I don't think the accepted answer here (that dev_appserver.py is only meant to work with Python 2.7) is accurate; the GAE documentation for Python 3.7 in fact lists dev_appserver.py as an option for local development. This seems more like a gcloud bug.

(Note: I know this would be better as a comment on the previous answer, but because I'm a new-ish SO user, I don't yet have permission to post comments)

Body:
Until yesterday I was successfully using the dev_appserver.py app.yaml --enable_console for my development.
Yesterday I attempted to upgrade to python 3.7 for my development.
The upgrade seemed to be Ok, but now I get the following error message.

server:bones brian$ dev_appserver.py app.yaml --enable_console
ERROR: (dev_appserver) python2: command not found

app.yaml:

application: bones
version: 1
runtime: python37
entrypoint: gunicorn -b :$PORT main:app
api_version: 1
threadsafe: true

handlers:
- url: /static
  static_dir: static

- url: /.*
  script: main.app

I am using Mac OS X 10.11.6.

Why is dev_appserver even looking for python2?
And how can I fix this?


问:
Getting Data out of a container
I wrote a function that creates new Input fields based on the number of input fields needed. That code is below.

```<code>for (i=0;i<number;i++){
    container.appendChild(document.createTextNode("Guest " + (i+1)));
    var input = document.createElement("input");
    input.id = "Guest" + i;
    container.appendChild(input);
    container.appendChild(document.createElement("br"));
    console.log(i.value);
</code>```

It creates a new Id for each input field. In the function below,depending on the number you set for i, the function creates a generated message.

```<code>function sendInput ()
{
    var guestNames = document.getElementById("Guest").value
    var personName = document.getElementById("people").value;
    var eventType = document.getElementById("event").value;
    var date = document.getElementById("date").value;
    var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date +  " Thank you for coming!!";
    document.getElementById('output').innerHTML = output.repeat(i);
}
</code>```

The problem is it is not collecting the data for guestNames. I am pretty new to JS but have searched and cannot find a solution to my problem. Any feedback wouls be helpful.

答:
As far as I can see, when you try to fetch the guest name

```<code>var guestNames = document.getElementById("Guest").value
</code>```

you won't get any element for two reasons because there's no element with id "Guest". In fact you generate them in the form "GuestN"

```<code>`input.id = "Guest" + i;`
</code>```

You probably want to add a parameter i to sendInput () function, so that internally you can concatenate it to Guest as you did above and get the correct element with getElementById().

Title: Getting Data out of a container

Body:
I wrote a function that creates new Input fields based on the number of input fields needed. That code is below.

for (i=0;i<number;i++){
    container.appendChild(document.createTextNode("Guest " + (i+1)));
    var input = document.createElement("input");
    input.id = "Guest" + i;
    container.appendChild(input);
    container.appendChild(document.createElement("br"));
    console.log(i.value);

It creates a new Id for each input field. In the function below,depending on the number you set for i, the function creates a generated message.

function sendInput ()
{
    var guestNames = document.getElementById("Guest").value
    var personName = document.getElementById("people").value;
    var eventType = document.getElementById("event").value;
    var date = document.getElementById("date").value;
    var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date +  " Thank you for coming!!";
    document.getElementById('output').innerHTML = output.repeat(i);
}

The problem is it is not collecting the data for guestNames. I am pretty new to JS but have searched and cannot find a solution to my problem. Any feedback wouls be helpful.

Body:
As far as I can see, when you try to fetch the guest name

var guestNames = document.getElementById("Guest").value

you won't get any element for two reasons because there's no element with id "Guest". In fact you generate them in the form "GuestN"

`input.id = "Guest" + i;`

You probably want to add a parameter i to sendInput () function, so that internally you can concatenate it to Guest as you did above and get the correct element with getElementById().


问:
Moving a node from one queue to another queue in C++
I am having a problem in moving a node from one queue to another in my program. I am implementing Queue using singly linked list in c++. I am making a Corona Test Program. There are three objects of queues testingQueue, quarantineQueue and homeQueue. The user adds people in testing queue one by one and after adding, user checks each person from testing queue for corona test one by one (using FIFO method cuz its a queue). The test result is randomized, it can be positive or negative. If result is positive then that person is sent to quarantineQueue and if result is negative, the person is sent to homeQueue. My program is running fine, there are no errors but when a person is sent to quarantineQueue and after that i run displayQueue() function for quarantineQueue it does not show any person in there. Please Help.

Complete Code:

```<code>#include <string>
#include <stdlib.h>
#include <cstdlib>
using namespace std;

class Person {
public:
    string name;
    string gender;
    int age;
    string testType;
    string result;
    Person* next;
    Person() {
        testType = "Corona Test";
    }
};

class Queue {
public:
    Person* rear;
    Person* front;
public:
    Queue() {
        rear = NULL;
        front = NULL;
    }
    void addPerson() {
        Person* temp = new Person;
        cout << "Enter Name Of The Person: ";
        cin.ignore();
        getline(cin, temp->name);
        cout << "Enter Gender Of The Person: ";
        cin >> temp->gender;
        cout << "Enter Age Of The Person: ";
        cin >> temp->age;
        temp->next = NULL;
        if (front == NULL) {
            front = temp;
            rear = temp;
        }
        else {
            rear->next = temp;
            rear = temp;
        }
    }

    void checkPerson(Queue qq,Queue hq) {
        Person* temp = front;
        int a = rand() % 100 + 1;
        if (a < 50) {
            temp->result = "Positive";
            if (qq.front == NULL) {
                front = temp->next;
                qq.front = temp;
                qq.rear = temp;
                temp->next = NULL;
            }
            else {
                front = temp->next;
                qq.rear->next = temp;
                qq.rear = temp;
                temp->next = NULL;
            }
            cout << "Result Was Positive And Person Has Been Moved To Quarantine." << endl;
        }
        else {
            temp->result = "Negative";
            if (hq.front == NULL) {
                front = temp->next;
                hq.front = temp;
                hq.rear = temp;
                temp->next = NULL;
            }
            else {
                front = temp->next;
                hq.rear->next = temp;
                hq.rear = temp;
                temp->next = NULL;
            }
            cout << "Result Was Negative And Person Has Been Moved To Home." << endl;
        }
    }

    void displayQueue() {
        Person* temp = front;
        while (temp != NULL) {
            cout << endl;
            cout << "Name Of Person: " << temp->name << endl;
            cout << "Gender Of Person: " << temp->gender << endl;
            cout << "Age Of Person: " << temp->age << endl;
            cout << "Test Type Of Person: " << temp->testType << endl;
            cout << "Result Of Person: " << temp->result << endl << endl;
            temp = temp->next;
        }
    }
};

void menu() {
    cout << "\n\n\t\t\t\t   ----------------------------------------------------\n";
    cout << "\t\t\t\t   |        1.Add a Person To Testing Queue           |\n";
    cout << "\t\t\t\t   |       2.Check a Person From Testing Queue        |\n";
    cout << "\t\t\t\t   |     3.Recover a Person From Quarantine Queue     |\n";
    cout << "\t\t\t\t   |      4.Display All People In Testing Queue       |\n";
    cout << "\t\t\t\t   |     5.Display All People In Quarantine Queue     |\n";
    cout << "\t\t\t\t   |         6. Display All People At Home            |\n";
    cout << "\t\t\t\t   |               7. Exit Program                    |\n";
    cout << "\t\t\t\t   ----------------------------------------------------\n";
}

int main() {
    Queue testingQueue, quarantineQueue, homeQueue;
    int op;
Fahad:
    menu();
    cout << "Enter Option: ";
    cin >> op;
    switch (op) {
    case 1:
        testingQueue.addPerson();
        cout << "A Person Has Been Added To Testing Queue." << endl;
        system("pause");
        system("cls");
        goto Fahad;
    case 2:
        testingQueue.checkPerson(quarantineQueue, homeQueue);
        system("pause");
        system("cls");
        goto Fahad;
    case 3:
        system("pause");
        system("cls");
        goto Fahad;
    case 4:
        testingQueue.displayQueue();
        system("pause");
        system("cls");
        goto Fahad;
    case 5:
        quarantineQueue.displayQueue();
        system("pause");
        system("cls");
        goto Fahad;
    case 6:
        homeQueue.displayQueue();
        system("pause");
        system("cls");
        goto Fahad;
    case 7:
        return 0;
    default:
        cout << "Invalid Option." << endl;
        system("pause");
        system("cls");
        goto Fahad;
    }
    system("pause");
}
</code>```

答:
Consider duplicating the interface for std::queue:

```<code>back    Returns a reference to the last element of the queue.
front   Returns a reference to the first element of the queue.
pop     Removes an element from the front of the queue.
push    Adds an element to the back of the queue.
empty   Tests if the queue is empty.
size    Returns the number of elements in the queue.
~Person deletes all nodes in the queue, then deletes the queue.
</code>```

Rather than constantly allocating and freeing nodes, you could consider changing the interface to work with pointers to nodes, and add two more functions:

```<code>new     creates a node, returns a pointer to the node.
delete  deletes a node (input parameter is pointer to node).
back    Returns a pointer to the last  node of the queue.
front   Returns a pointer to the first node of the queue.
pop     Returns a pointer to what was the first node of the queue, which is now removed.
push    Appends an element via pointer to the back of the queue.
empty   Tests if the queue is empty.
size    Returns the number of elements in the queue.
~Person deletes all nodes in the queue, then deletes the queue.
</code>```

Body:
I am having a problem in moving a node from one queue to another in my program. I am implementing Queue using singly linked list in c++. I am making a Corona Test Program. There are three objects of queues testingQueue, quarantineQueue and homeQueue. The user adds people in testing queue one by one and after adding, user checks each person from testing queue for corona test one by one (using FIFO method cuz its a queue). The test result is randomized, it can be positive or negative. If result is positive then that person is sent to quarantineQueue and if result is negative, the person is sent to homeQueue. My program is running fine, there are no errors but when a person is sent to quarantineQueue and after that i run displayQueue() function for quarantineQueue it does not show any person in there. Please Help.

Complete Code:

#include <string>
#include <stdlib.h>
#include <cstdlib>
using namespace std;

class Person {
public:
    string name;
    string gender;
    int age;
    string testType;
    string result;
    Person* next;
    Person() {
        testType = "Corona Test";
    }
};

class Queue {
public:
    Person* rear;
    Person* front;
public:
    Queue() {
        rear = NULL;
        front = NULL;
    }
    void addPerson() {
        Person* temp = new Person;
        cout << "Enter Name Of The Person: ";
        cin.ignore();
        getline(cin, temp->name);
        cout << "Enter Gender Of The Person: ";
        cin >> temp->gender;
        cout << "Enter Age Of The Person: ";
        cin >> temp->age;
        temp->next = NULL;
        if (front == NULL) {
            front = temp;
            rear = temp;
        }
        else {
            rear->next = temp;
            rear = temp;
        }
    }

    void checkPerson(Queue qq,Queue hq) {
        Person* temp = front;
        int a = rand() % 100 + 1;
        if (a < 50) {
            temp->result = "Positive";
            if (qq.front == NULL) {
                front = temp->next;
                qq.front = temp;
                qq.rear = temp;
                temp->next = NULL;
            }
            else {
                front = temp->next;
                qq.rear->next = temp;
                qq.rear = temp;
                temp->next = NULL;
            }
            cout << "Result Was Positive And Person Has Been Moved To Quarantine." << endl;
        }
        else {
            temp->result = "Negative";
            if (hq.front == NULL) {
                front = temp->next;
                hq.front = temp;
                hq.rear = temp;
                temp->next = NULL;
            }
            else {
                front = temp->next;
                hq.rear->next = temp;
                hq.rear = temp;
                temp->next = NULL;
            }
            cout << "Result Was Negative And Person Has Been Moved To Home." << endl;
        }
    }

    void displayQueue() {
        Person* temp = front;
        while (temp != NULL) {
            cout << endl;
            cout << "Name Of Person: " << temp->name << endl;
            cout << "Gender Of Person: " << temp->gender << endl;
            cout << "Age Of Person: " << temp->age << endl;
            cout << "Test Type Of Person: " << temp->testType << endl;
            cout << "Result Of Person: " << temp->result << endl << endl;
            temp = temp->next;
        }
    }
};

void menu() {
    cout << "\n\n\t\t\t\t   ----------------------------------------------------\n";
    cout << "\t\t\t\t   |        1.Add a Person To Testing Queue           |\n";
    cout << "\t\t\t\t   |       2.Check a Person From Testing Queue        |\n";
    cout << "\t\t\t\t   |     3.Recover a Person From Quarantine Queue     |\n";
    cout << "\t\t\t\t   |      4.Display All People In Testing Queue       |\n";
    cout << "\t\t\t\t   |     5.Display All People In Quarantine Queue     |\n";
    cout << "\t\t\t\t   |         6. Display All People At Home            |\n";
    cout << "\t\t\t\t   |               7. Exit Program                    |\n";
    cout << "\t\t\t\t   ----------------------------------------------------\n";
}

int main() {
    Queue testingQueue, quarantineQueue, homeQueue;
    int op;
Fahad:
    menu();
    cout << "Enter Option: ";
    cin >> op;
    switch (op) {
    case 1:
        testingQueue.addPerson();
        cout << "A Person Has Been Added To Testing Queue." << endl;
        system("pause");
        system("cls");
        goto Fahad;
    case 2:
        testingQueue.checkPerson(quarantineQueue, homeQueue);
        system("pause");
        system("cls");
        goto Fahad;
    case 3:
        system("pause");
        system("cls");
        goto Fahad;
    case 4:
        testingQueue.displayQueue();
        system("pause");
        system("cls");
        goto Fahad;
    case 5:
        quarantineQueue.displayQueue();
        system("pause");
        system("cls");
        goto Fahad;
    case 6:
        homeQueue.displayQueue();
        system("pause");
        system("cls");
        goto Fahad;
    case 7:
        return 0;
    default:
        cout << "Invalid Option." << endl;
        system("pause");
        system("cls");
        goto Fahad;
    }
    system("pause");
}

Body:
Consider duplicating the interface for std::queue:

back    Returns a reference to the last element of the queue.
front   Returns a reference to the first element of the queue.
pop     Removes an element from the front of the queue.
push    Adds an element to the back of the queue.
empty   Tests if the queue is empty.
size    Returns the number of elements in the queue.
~Person deletes all nodes in the queue, then deletes the queue.

Rather than constantly allocating and freeing nodes, you could consider changing the interface to work with pointers to nodes, and add two more functions:

new     creates a node, returns a pointer to the node.
delete  deletes a node (input parameter is pointer to node).
back    Returns a pointer to the last  node of the queue.
front   Returns a pointer to the first node of the queue.
pop     Returns a pointer to what was the first node of the queue, which is now removed.
push    Appends an element via pointer to the back of the queue.
empty   Tests if the queue is empty.
size    Returns the number of elements in the queue.
~Person deletes all nodes in the queue, then deletes the queue.