问:
Pythonic way to modify a list of dictionaries
Looking for an efficient way to modify a dictionary

I have a list of dictionaries in this format:

```<code>>>> x = [{'server': 's1', 'disk' : 'd1', 'size': 10},{'server': 's2', 'disk' : 'd2', 'size': 20},{'server': 's3', 'disk' : 'd3', 'size': 30}, {'server': 's1', 'disk' : 'd4', 'size': 40}]
</code>```

I'd like it to be restructured so the value of 'server' becomes the key and contains a list of dictionaries with disk and size information that are all within that server

```<code>{'s1': [{'disk': 'd1', 'size': 10}, {'disk': 'd4', 'size': 40}], 's2': [{'disk': 'd2', 'size': 20}], 's3': [{'disk': 'd3', 'size': 30}]}
</code>```

This is what ive tried:

```<code>>>> y = {y[i.pop('server')].append(i) if i['server'] in y else i.pop('server'): [i] for i in x}
>>> y
{'s1': [{'disk': 'd4', 'size': 40}], 's2': [{'disk': 'd2', 'size': 20}], 's3': [{'disk': 'd3', 'size': 30}]}

>>> out = {'s1' : [{'disk' : 'd1', 'size': 10},{'disk' : 'd4', 'size': 40}], 's2' : [{'disk' : 'd2', 'size': 20}], 's3' : [{'disk' : 'd3', 'size': 30}]}
</code>```

答:
The approach you have is fine, but I might suggest creating a new dictionary instead of modify what we already have
For that, you can iterate over the list and create your required dictionary as follows

```<code>x = [{'server': 's1', 'disk' : 'd1', 'size': 10},{'server': 's2', 'disk' : 'd2', 'size': 20},{'server': 's3', 'disk' : 'd3', 'size': 30}, {'server': 's1', 'disk' : 'd4', 'size': 40}]

from collections import defaultdict

dct = defaultdict(list)

#Iterate over the list
for item in x:
    #Use server value as key, and the remainining k,v pairs as dict and append them to a list
    dct[item['server']].append({k:v for k,v in item.items() if k != 'server'})

print(dict(dct))
</code>```

Or if you want to follow the dict.pop() approach, pop the key server and use it as a key in your dictionary

```<code>x = [{'server': 's1', 'disk' : 'd1', 'size': 10},{'server': 's2', 'disk' : 'd2', 'size': 20},{'server': 's3', 'disk' : 'd3', 'size': 30}, {'server': 's1', 'disk' : 'd4', 'size': 40}]

from collections import defaultdict

dct = defaultdict(list)

#Iterate over the list
for item in x:
    #Get server value after popping server key
    server = item.pop('server')

    #Use that value and append the remaining dict to a list
    dct[server].append(item)

print(dict(dct))
</code>```

The output will be same in both cases, which is

```<code>{'s1': [{'disk': 'd1', 'size': 10}, {'disk': 'd4', 'size': 40}], 's2': [{'disk': 'd2', 'size': 20}], 's3': [{'disk': 'd3', 'size': 30}]}
</code>```

Body:
Looking for an efficient way to modify a dictionary

I have a list of dictionaries in this format:

>>> x = [{'server': 's1', 'disk' : 'd1', 'size': 10},{'server': 's2', 'disk' : 'd2', 'size': 20},{'server': 's3', 'disk' : 'd3', 'size': 30}, {'server': 's1', 'disk' : 'd4', 'size': 40}]

I'd like it to be restructured so the value of 'server' becomes the key and contains a list of dictionaries with disk and size information that are all within that server

{'s1': [{'disk': 'd1', 'size': 10}, {'disk': 'd4', 'size': 40}], 's2': [{'disk': 'd2', 'size': 20}], 's3': [{'disk': 'd3', 'size': 30}]}

This is what ive tried:

>>> y = {y[i.pop('server')].append(i) if i['server'] in y else i.pop('server'): [i] for i in x}
>>> y
{'s1': [{'disk': 'd4', 'size': 40}], 's2': [{'disk': 'd2', 'size': 20}], 's3': [{'disk': 'd3', 'size': 30}]}

>>> out = {'s1' : [{'disk' : 'd1', 'size': 10},{'disk' : 'd4', 'size': 40}], 's2' : [{'disk' : 'd2', 'size': 20}], 's3' : [{'disk' : 'd3', 'size': 30}]}

Body:
The approach you have is fine, but I might suggest creating a new dictionary instead of modify what we already have
For that, you can iterate over the list and create your required dictionary as follows

x = [{'server': 's1', 'disk' : 'd1', 'size': 10},{'server': 's2', 'disk' : 'd2', 'size': 20},{'server': 's3', 'disk' : 'd3', 'size': 30}, {'server': 's1', 'disk' : 'd4', 'size': 40}]

from collections import defaultdict

dct = defaultdict(list)

#Iterate over the list
for item in x:
    #Use server value as key, and the remainining k,v pairs as dict and append them to a list
    dct[item['server']].append({k:v for k,v in item.items() if k != 'server'})

print(dict(dct))

Or if you want to follow the dict.pop() approach, pop the key server and use it as a key in your dictionary

x = [{'server': 's1', 'disk' : 'd1', 'size': 10},{'server': 's2', 'disk' : 'd2', 'size': 20},{'server': 's3', 'disk' : 'd3', 'size': 30}, {'server': 's1', 'disk' : 'd4', 'size': 40}]

from collections import defaultdict

dct = defaultdict(list)

#Iterate over the list
for item in x:
    #Get server value after popping server key
    server = item.pop('server')

    #Use that value and append the remaining dict to a list
    dct[server].append(item)

print(dict(dct))

The output will be same in both cases, which is

{'s1': [{'disk': 'd1', 'size': 10}, {'disk': 'd4', 'size': 40}], 's2': [{'disk': 'd2', 'size': 20}], 's3': [{'disk': 'd3', 'size': 30}]}


来源: stackexchange

问:
Need to delete particular commit from bit bucket
I have a commit in my remote branch and I want to delete that commit. Is there any way to do it? I am the only user of the this branch. Below is a screen shot.

答:
You can achieve that by dropping the commit and force pushing the updated branch to your remote. Note: careful if other persons have checkout the branch.

Supposing your history is like the following and you want to delete commit 200:

commit 300 commit 200 commit 100

Do the following:

```<code>git rebase -i HEAD~3
</code>```

Now, delete the line of commit 200.

Save the file, and then force push the branch to the remote:

```<code>git push -f origin <branch_name>
</code>```

This work perfectly for me.
Reference:Completely remove commit from Bitbucket history

ContentLicense: CC BY-SA 3.0

Body:
You can achieve that by dropping the commit and force pushing the updated branch to your remote. Note: careful if other persons have checkout the branch.

Supposing your history is like the following and you want to delete commit 200:

commit 300 commit 200 commit 100

Do the following:

git rebase -i HEAD~3

Now, delete the line of commit 200.

Save the file, and then force push the branch to the remote:

git push -f origin <branch_name>

This work perfectly for me.
Reference:Completely remove commit from Bitbucket history

ContentLicense: CC BY-SA 4.0


问:
Guarding resources with Singleton?
I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge:

Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).

Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).

My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).

Is my choice of making this class a singleton class a bad decision?

答: I personally think it is reasonable to use Singletons when appropriate.  There certainly may be overuse of them in general, but in my opinion they are useful for manager classes controlling hardware resources, which is what you are doing.</p>

Title: Guarding resources with Singleton?


问:
Conversion of Daily pandas dataframe to minute frequency
I have a dataframe as defined below (df) with daily frequency and I would like to convert this to minute frequency, starting at 8:30 and ending at 16:00.

```<code>import pandas as pd
dict = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '0.2'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.2'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '0.2'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2'},
{'ticker':'amzn','date': '2016-11-28','returns': '0.2'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2'},
{'ticker':'ge', 'date': '2016-11-29','returns': '0.2'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2'},
{'ticker':'aapl','date': '2016-11-29','returns': '0.2'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2'},
{'ticker':'amzn','date': '2016-11-29','returns': '0.2'}
]
df = pd.DataFrame(dict)
df['date']      = pd.to_datetime(df['date'])
df=df.set_index(['date','ticker'], drop=True)
</code>```

Can anyone suggest how to do this?

答:
I believe you need reshape by DataFrame.unstack for DatetimeIndex, then set minute frequency by DataFrame.asfreq, filter times by DataFrame.between_time and last use DataFrame.stack for MultiIndex:

```<code>df1 = df.unstack().asfreq('Min', method='ffill').between_time('8:30','16:00').stack()
print (df1.head(10))

                           returns
date                ticker
2016-11-28 08:30:00 aapl       0.2
                    amzn       0.2
                    fb         0.2
                    ge         0.2
                    jpm        0.2
                    msft       0.2
2016-11-28 08:31:00 aapl       0.2
                    amzn       0.2
                    fb         0.2
                    ge         0.2
</code>```

Body:
I have a dataframe as defined below (df) with daily frequency and I would like to convert this to minute frequency, starting at 8:30 and ending at 16:00.

import pandas as pd
dict = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '0.2'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.2'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '0.2'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2'},
{'ticker':'amzn','date': '2016-11-28','returns': '0.2'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2'},
{'ticker':'ge', 'date': '2016-11-29','returns': '0.2'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2'},
{'ticker':'aapl','date': '2016-11-29','returns': '0.2'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2'},
{'ticker':'amzn','date': '2016-11-29','returns': '0.2'}
]
df = pd.DataFrame(dict)
df['date']      = pd.to_datetime(df['date'])
df=df.set_index(['date','ticker'], drop=True)

Can anyone suggest how to do this?

Body:
I believe you need reshape by DataFrame.unstack for DatetimeIndex, then set minute frequency by DataFrame.asfreq, filter times by DataFrame.between_time and last use DataFrame.stack for MultiIndex:

df1 = df.unstack().asfreq('Min', method='ffill').between_time('8:30','16:00').stack()
print (df1.head(10))

                           returns
date                ticker
2016-11-28 08:30:00 aapl       0.2
                    amzn       0.2
                    fb         0.2
                    ge         0.2
                    jpm        0.2
                    msft       0.2
2016-11-28 08:31:00 aapl       0.2
                    amzn       0.2
                    fb         0.2
                    ge         0.2


问:
Does setState() have any limitations with regard to updating UI
I am trying to update a TextField to show an error text until the email is validated by an external validators package. However, the UI does not update even though I am calling the setState from within the build method. I tried debugging by using print statements(screenshot attached) and the behavior is as expected. Why then does the UI not update showing the TextField with the error text below it if I try to pass in an updated TextField UI in the setState() ?

Code that does work

Code that does not work

```<code>                    child:  TextField(
                      decoration: InputDecoration(
                          hintText: "Enter Email Id",
                          border: OutlineInputBorder()),
                      onChanged: (String value) {
                        emailId = value;
                        setState(() {
                          isEmail(value)
                              ? print("true")
                              : TextField(
                                  decoration: InputDecoration(
                                      errorText: "Enter valid email"),
                                );
                        });
                      },
</code>```

答:
Your code doesn't work because you're not changing the state of the parent widget
inside its onChanged: property. You are creating a new widget on set state

```<code>child: TextField( //parent
      decoration: InputDecoration(
      hintText: "Enter Email Id",
      border: OutlineInputBorder()),
              onChanged: (String value) {
              emailId = value;
              setState(() {
                 isEmail(value)
                    ? print("true")
                    : TextField( //this is not the same widget.
                        decoration: InputDecoration(
                         errorText: "Enter valid email"),
                     );
                    });
                  },
</code>```

You can solve this by declaring String invalidEmailError and set this on  errorText property of TextField. Later update this this string to get the desired result.

```<code>TextField(
      decoration: InputDecoration(
      hintText: "Enter Email Id",
          errorText: invalidEmailError,
          border: OutlineInputBorder()),
          onChanged: (String value) {
          emailId = value;
        setState(() {
            isEmail(value)
                ? invalidEmailError = null
                : invalidEmailError = "Enter valid email";
        });
      },
      )
</code>```

Body:
I am trying to update a TextField to show an error text until the email is validated by an external validators package. However, the UI does not update even though I am calling the setState from within the build method. I tried debugging by using print statements(screenshot attached) and the behavior is as expected. Why then does the UI not update showing the TextField with the error text below it if I try to pass in an updated TextField UI in the setState() ?

Code that does work

Code that does not work

                    child:  TextField(
                      decoration: InputDecoration(
                          hintText: "Enter Email Id",
                          border: OutlineInputBorder()),
                      onChanged: (String value) {
                        emailId = value;
                        setState(() {
                          isEmail(value)
                              ? print("true")
                              : TextField(
                                  decoration: InputDecoration(
                                      errorText: "Enter valid email"),
                                );
                        });
                      },

Body:
Your code doesn't work because you're not changing the state of the parent widget
inside its onChanged: property. You are creating a new widget on set state

child: TextField( //parent
      decoration: InputDecoration(
      hintText: "Enter Email Id",
      border: OutlineInputBorder()),
              onChanged: (String value) {
              emailId = value;
              setState(() {
                 isEmail(value)
                    ? print("true")
                    : TextField( //this is not the same widget.
                        decoration: InputDecoration(
                         errorText: "Enter valid email"),
                     );
                    });
                  },

You can solve this by declaring String invalidEmailError and set this on  errorText property of TextField. Later update this this string to get the desired result.

TextField(
      decoration: InputDecoration(
      hintText: "Enter Email Id",
          errorText: invalidEmailError,
          border: OutlineInputBorder()),
          onChanged: (String value) {
          emailId = value;
        setState(() {
            isEmail(value)
                ? invalidEmailError = null
                : invalidEmailError = "Enter valid email";
        });
      },
      )


问:
How to create dock icon for running terminal command in Mac OS
Now I open jmeter using terminal using command: open /usr/local/bin/jmeter

I need it frequently, so I want to create dock icon to run this command.

How can I do it?

I tried to make a right click and choose 'keep in dock' option. However, it disappears when I close the application.

答:
I suggest you have a look at the answer to this question in the apple stackexchange.  It pretty much does exactly what you want (although I have no idea what jmeter does).

The answer is, essentially, use automator to run your script, save the automator job as an app (not a workflow), and drag the resulting object to the dock, once you have it working the way you want.

https://apple.stackexchange.com/questions/73897/how-can-i-launch-a-virtualbox-vm-from-the-dock

or the wayback machine copy:
https://web.archive.org/web/20160921184459/https://apple.stackexchange.com/questions/73897/how-can-i-launch-a-virtualbox-vm-from-the-dock


问:
Bluetooth programming - available devices
I used the following function, gots from Microsoft:

```<code>        public List<Device> DiscoverAllDevices()
        {
            List<Device> devices = new List<Device>();

            // Initialize WinSock
            WsaData wsadata = new WsaData();

            int result =
                BluetoothHelper.WSAStartup(BluetoothHelper.MakeWord(2, 2),
                                           ref wsadata);
            if (result != 0)
                BluetoothHelper.GetError();

            // Scan for bluetooth devices
            QuerySet wsaq = new QuerySet();
            //Initialize queryset structure with device specific
            //information.
            wsaq.Size = Marshal.SizeOf(typeof(QuerySet));
            wsaq.NameSpace = BluetoothHelper.NS_BTH;
            IntPtr lookup = IntPtr.Zero;
            uint flags = BluetoothHelper.LUP_RETURN_NAME
                           | BluetoothHelper.LUP_CONTAINERS
                           | BluetoothHelper.LUP_RETURN_ADDR
                           | BluetoothHelper.LUP_FLUSHCACHE
                           | BluetoothHelper.LUP_RETURN_TYPE
                           | BluetoothHelper.LUP_RETURN_BLOB
                           | BluetoothHelper.LUP_RES_SERVICE;

            //Initiates a client query that is constrained by the
            //information contained within a queryset structure.

            result = BluetoothHelper.WSALookupServiceBegin(wsaq,
                                                           flags,
                                                           ref lookup);
            if (result != 0)
                BluetoothHelper.GetError();

            while (0 == result)
            {
                int buffer = 0x10000;

                IntPtr bufferPtr = Marshal.AllocHGlobal(buffer);
                QuerySet qsResult = new QuerySet();

                //Retrieves the requested device information.
                result = BluetoothHelper.WSALookupServiceNext(lookup,
                                                         flags,
                                                         ref buffer,
                                                         bufferPtr);
                if (0 == result)
                {
                    Marshal.PtrToStructure(bufferPtr, qsResult);
                    devices.Add(new Device(qsResult));
                }
                else
                {
                    BluetoothHelper.GetError();
                }
            }
            //end device-lookup
            result = BluetoothHelper.WSALookupServiceEnd(lookup);
            if (result != 0)
                BluetoothHelper.GetError();

            // cleanup winsock
            result = BluetoothHelper.WSACleanup();

            if (result != 0)
                BluetoothHelper.GetError();

            return devices;
        }
</code>```

but I need to know actual data if device in range or not. This code always find device, if it was found before, even if this device is switched off. Why and how to solve this problem?
I spent almost full day to find solution
Thanks

答:
There is no direct API for that unfortunately. :-(  It's a major gap in the API of the Microsoft Bluetooth stack on Win32.

However it is possible by combining an number of APIs.  I investigated and implemented this for my my shared-source .NET Bluetooth, http://32feet.codeplex.com  If your program could be written in managed code then it will save you much time in using Bluetooth. :-)

Anyway my way of getting the 'discoverable only' device list is documented at http://32feetnetdev.wordpress.com/2010/11/15/device-discovery-improvements-on-msftwin32/  So that's to use the Bluetooth events API to see the discovered devices, and run a normal discovery at the same time.

Body:
I used the following function, gots from Microsoft:

        public List<Device> DiscoverAllDevices()
        {
            List<Device> devices = new List<Device>();

            // Initialize WinSock
            WsaData wsadata = new WsaData();

            int result =
                BluetoothHelper.WSAStartup(BluetoothHelper.MakeWord(2, 2),
                                           ref wsadata);
            if (result != 0)
                BluetoothHelper.GetError();

            // Scan for bluetooth devices
            QuerySet wsaq = new QuerySet();
            //Initialize queryset structure with device specific
            //information.
            wsaq.Size = Marshal.SizeOf(typeof(QuerySet));
            wsaq.NameSpace = BluetoothHelper.NS_BTH;
            IntPtr lookup = IntPtr.Zero;
            uint flags = BluetoothHelper.LUP_RETURN_NAME
                           | BluetoothHelper.LUP_CONTAINERS
                           | BluetoothHelper.LUP_RETURN_ADDR
                           | BluetoothHelper.LUP_FLUSHCACHE
                           | BluetoothHelper.LUP_RETURN_TYPE
                           | BluetoothHelper.LUP_RETURN_BLOB
                           | BluetoothHelper.LUP_RES_SERVICE;

            //Initiates a client query that is constrained by the
            //information contained within a queryset structure.

            result = BluetoothHelper.WSALookupServiceBegin(wsaq,
                                                           flags,
                                                           ref lookup);
            if (result != 0)
                BluetoothHelper.GetError();

            while (0 == result)
            {
                int buffer = 0x10000;

                IntPtr bufferPtr = Marshal.AllocHGlobal(buffer);
                QuerySet qsResult = new QuerySet();

                //Retrieves the requested device information.
                result = BluetoothHelper.WSALookupServiceNext(lookup,
                                                         flags,
                                                         ref buffer,
                                                         bufferPtr);
                if (0 == result)
                {
                    Marshal.PtrToStructure(bufferPtr, qsResult);
                    devices.Add(new Device(qsResult));
                }
                else
                {
                    BluetoothHelper.GetError();
                }
            }
            //end device-lookup
            result = BluetoothHelper.WSALookupServiceEnd(lookup);
            if (result != 0)
                BluetoothHelper.GetError();

            // cleanup winsock
            result = BluetoothHelper.WSACleanup();

            if (result != 0)
                BluetoothHelper.GetError();

            return devices;
        }

but I need to know actual data if device in range or not. This code always find device, if it was found before, even if this device is switched off. Why and how to solve this problem?
I spent almost full day to find solution
Thanks


问:
What is the point of google.protobuf.StringValue?
I've recently encountered all sorts of wrappers in Google's protobuf package.  I'm struggling to imagine the use case.  Can anyone shed the light: what problem were these intended to solve?

Here's one of the documentation links: https://developers.google.com/protocol-buffers/docs/reference/csharp/class/google/protobuf/well-known-types/string-value (it says nothing about what can this be used for).

One thing that will be different in behavior between this, and simple string type is that this field will be written less efficiently (a couple extra bytes, plus a redundant memory allocation).  For other wrappers, the story is even worse, since the repeated variants of those fields will be written inefficiently (official Google's Protobuf serializer doesn't support packed encoding for non-numeric types).

Neither seems to be desirable.  So, what's this all about?

答:
There's a few reasons, mostly to do with where these are used - see struct.proto.

StringValue can be null, string often can't be in a language interfacing with protobufs. e.g. in Go strings are always set; the "zero value" for a string is "", the empty string, so it's impossible to distinguish between "this value is intentionally set to empty string" and "there was no value present". StringValue can be null and so solves this problem. It's especially important when they're used in a StructValue, which may represent arbitrary JSON: to do so it needs to distinguish between a JSON key which was set to empty string (StringValue with an empty string) or a JSON key which wasn't set at all (null StringValue).

Also if you look at struct.proto, you'll see that these aren't fully fledged message types in the proto - they're all generated from message Value, which has a oneof kind { number_value, string_value, bool_value... etc. By using a oneof struct.proto can represent a variety of different values in one field. Again this makes sense considering what struct.proto is designed to handle - arbitrary JSON - you don't know what type of value a given JSON key has ahead of time.


问:
Conditionally assign std::string as references
I have some code that is part of a larger function that is working. However, in order to optimize it and eliminate the unnecessary need for string copying I want to rewrite this code with references. My code relies on largerStr being a longer string than smallerStr. I want to rewrite this with references but I can't seem to get it to work. If I try and make largerStr and smallerStr references without explicitly initializing them the compiler tells me need to initialize it at declaration. If I try and put it as a temporary variable in the if statement I end up having both variables referencing the same string.

What is the best solution?

```<code>//str1 and str2 are std::strings
std::string largerStr, smallerStr;

if(str1.length() > str2.length()) {
    largerStr = str1;
    smallerStr = str2;
} else {
    largerStr = str2;
    smallerStr = str1;
}
</code>```

答:
You can use C++17's structured binding declaration to unpack a std::tie'd tuple of references.

```<code>auto [largerStr, smallerStr] = str1.length() > str2.length() ?
                               std::tie(str1, str2)          :
                               std::tie(str2, str1)          ;
</code>```

The structured bindings aren't variables or references per-se, but they avoid the copies and act like references in every way that seems important to you.

Body:
I have some code that is part of a larger function that is working. However, in order to optimize it and eliminate the unnecessary need for string copying I want to rewrite this code with references. My code relies on largerStr being a longer string than smallerStr. I want to rewrite this with references but I can't seem to get it to work. If I try and make largerStr and smallerStr references without explicitly initializing them the compiler tells me need to initialize it at declaration. If I try and put it as a temporary variable in the if statement I end up having both variables referencing the same string.

What is the best solution?

//str1 and str2 are std::strings
std::string largerStr, smallerStr;

if(str1.length() > str2.length()) {
    largerStr = str1;
    smallerStr = str2;
} else {
    largerStr = str2;
    smallerStr = str1;
}

Body:
You can use C++17's structured binding declaration to unpack a std::tie'd tuple of references.

auto [largerStr, smallerStr] = str1.length() > str2.length() ?
                               std::tie(str1, str2)          :
                               std::tie(str2, str1)          ;

The structured bindings aren't variables or references per-se, but they avoid the copies and act like references in every way that seems important to you.


答:
You can use ternary operator to initialize them.</p>

```<code>#include <string>
int main() {
    std::string str1, str2;
    const bool str1_longer = str1.length() > str2.length();
    std::string& largerStr  = str1_longer ? str1 : str2;
    std::string& smallerStr = str1_longer ? str2 : str1;
}
</code>```

Title: Conditionally assign std::string as references

Body:
You can use ternary operator to initialize them.

#include <string>
int main() {
    std::string str1, str2;
    const bool str1_longer = str1.length() > str2.length();
    std::string& largerStr  = str1_longer ? str1 : str2;
    std::string& smallerStr = str1_longer ? str2 : str1;
}


问:
Enum from String
I have an Enum and a function to create it from a String because i couldn't find a built in way to do it

enum Visibility{VISIBLE,COLLAPSED,HIDDEN}

Visibility visibilityFromString(String value){
  return Visibility.values.firstWhere((e)=>
      e.toString().split('.')[1].toUpperCase()==value.toUpperCase());
}

//used as
Visibility x = visibilityFromString('COLLAPSED');
```

<p>but it seems like i have to rewrite this function for every Enum i have, is there a way to write the same function where it takes the Enum type as parameter? i tried to but i figured out that i can't cast to Enum.</p>

<pre class="lang-dart prettyprint-override"><code>//is something with the following signiture actually possible?
     dynamic enumFromString(Type enumType,String value){

     }
</code>```

答:
This is all so complicated I made a simple library that gets the job done:

https://pub.dev/packages/enum_to_string

import 'package:enum_to_string:enum_to_string.dart';

enum TestEnum { testValue1 };

convert(){
    String result = EnumToString.parse(TestEnum.testValue1);
    //result = 'testValue1'

    String resultCamelCase = EnumToString.parseCamelCase(TestEnum.testValue1);
    //result = 'Test Value 1'

    final result = EnumToString.fromString(TestEnum.values, "testValue1");
    // TestEnum.testValue1
}
```
<p><strong>Update: 2022/02/10</strong>
Dart v2.15 has implemented some additional enum methods that may solve your problems.</p>
<p>From here: https://medium.com/dartlang/dart-2-15-7e7a598e508a</p>
<p>Improved enums in the dart:core library</p>
<p>We’ve made a number of convenience additions to the enum APIs in the dart:core library (language issue #1511). You can now get the String value for each enum value using .name:</p>
```enum MyEnum {
  one, two, three
}
void main() {
  print(MyEnum.one.name);  // Prints "one".
}
```
<p>You can also look up an enum value by name:</p>
```print(MyEnum.values.byName('two') == MyEnum.two);  // Prints "true".
```
<p>Finally, you can get a map of all name-value pairs:</p>
```final map = MyEnum.values.asNameMap();
print(map['three'] == MyEnum.three);  // Prints "true".

```

Title: Enum from String

Body:
I have an Enum and a function to create it from a String because i couldn't find a built in way to do it

enum Visibility{VISIBLE,COLLAPSED,HIDDEN}

Visibility visibilityFromString(String value){
  return Visibility.values.firstWhere((e)=>
      e.toString().split('.')[1].toUpperCase()==value.toUpperCase());
}

//used as
Visibility x = visibilityFromString('COLLAPSED');

but it seems like i have to rewrite this function for every Enum i have, is there a way to write the same function where it takes the Enum type as parameter? i tried to but i figured out that i can't cast to Enum.

//is something with the following signiture actually possible?
     dynamic enumFromString(Type enumType,String value){

     }

Body:
This is all so complicated I made a simple library that gets the job done:

https://pub.dev/packages/enum_to_string

import 'package:enum_to_string:enum_to_string.dart';

enum TestEnum { testValue1 };

convert(){
    String result = EnumToString.parse(TestEnum.testValue1);
    //result = 'testValue1'

    String resultCamelCase = EnumToString.parseCamelCase(TestEnum.testValue1);
    //result = 'Test Value 1'

    final result = EnumToString.fromString(TestEnum.values, "testValue1");
    // TestEnum.testValue1
}

Update: 2022/02/10
Dart v2.15 has implemented some additional enum methods that may solve your problems.

From here: https://medium.com/dartlang/dart-2-15-7e7a598e508a

Improved enums in the dart:core library

We’ve made a number of convenience additions to the enum APIs in the dart:core library (language issue #1511). You can now get the String value for each enum value using .name:

enum MyEnum {
  one, two, three
}
void main() {
  print(MyEnum.one.name);  // Prints "one".
}

You can also look up an enum value by name:

print(MyEnum.values.byName('two') == MyEnum.two);  // Prints "true".

Finally, you can get a map of all name-value pairs:

final map = MyEnum.values.asNameMap();
print(map['three'] == MyEnum.three);  // Prints "true".


问:
What is the most EVIL code you have ever seen in a production enterprise environment?
What is the most evil or dangerous code fragment you have ever seen in a production environment at a company?  I've never encountered production code that I would consider to be deliberately malicious and evil, so I'm quite curious to see what others have found.

The most dangerous code I have ever seen was a stored procedure two linked-servers away from our core production database server.  The stored procedure accepted any NVARCHAR(8000) parameter and executed the parameter on the target production server via an double-jump sp_executeSQL command.  That is to say, the sp_executeSQL command executed another sp_executeSQL command in order to jump two linked servers.  Oh, and the linked server account had sysadmin rights on the target production server.

答:
I remember seeing a login handler that took a post request, and redirected to a GET with the user name and password passed in as parameters.  This was for an "enterprise class" medical system.

I noticed this while checking some logs - I was very tempted to send the CEO his password.

OwnerDisplayName: InnerJoin

LastEditorDisplayName: Noah

OwnerDisplayName: chris

ContentLicense: CC BY-SA 2.5


问:
Laravel - How to Transform Raw Query to Eloquent in Laravel
How do I transform my raw query to Laravel Eloquent

I want to transform

```<code>        $games = DB::table('game_point')
                     ->select('game_point.game_name','game_point.description','game_point.point_assigned', DB::raw("DATE(game_point.created_at) as created_at"))
                       ->paginate(15);
</code>```

to

```<code>$games= new GamePoint();
</code>```

答:
You can directly change it by using date() in blade or in controller depend upon your usage.
try the following code

```<code>$data = GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at')->paginate(15);
</code>```

Or In the blade or contrller you can use it just paste it where you using inside foreach

```<code>date('Y-m-d', strtotime($user->from_date));
</code>```

Or you can use carbon which is already included in laravel for working with date and time.

You can read about this package here

Body:
How do I transform my raw query to Laravel Eloquent

I want to transform

        $games = DB::table('game_point')
                     ->select('game_point.game_name','game_point.description','game_point.point_assigned', DB::raw("DATE(game_point.created_at) as created_at"))
                       ->paginate(15);

to

$games= new GamePoint();

Body:
You can directly change it by using date() in blade or in controller depend upon your usage.
try the following code

$data = GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at')->paginate(15);

Or In the blade or contrller you can use it just paste it where you using inside foreach

date('Y-m-d', strtotime($user->from_date));

Or you can use carbon which is already included in laravel for working with date and time.

You can read about this package here


问:
How to insert items into existing array
Assume I have two arrays as below

```<code>array:2 [
  0 => {#1995
    +"id": 6
    +"sales_target_amount": "30000.00"
  }
  1 => {#1996
    +"id": 10
    +"sales_target_amount": "1000.00"
  }
]
</code>```

second array

```<code>array:2 [
  0 => {#1994
    +"sales_total": "4165.80"
    +"staff_id": 6
  }
  1 => {#1513
    +"sales_total": "1335.60"
    +"staff_id": 10
  }
]
</code>```

I'm trying to insert the first array sales_target_amount into the second array if the id is matched to the staff_id.

code

```<code>  $sum = array_merge($second_array[],$firs_array);
</code>```

The code above will merge the two array together but not insert the items based on the id.

Expected Result

```<code>array:2 [
      0 => {#1994
        +"sales_total": "4165.80"
        +"staff_id": 6
        +"sales_target_amount": "30000.00"
      }
      1 => {#1513
        +"sales_total": "1335.60"
        +"staff_id": 10
        +"sales_target_amount": "1000.00"
      }
    ]
</code>```

答:
Use hashed map to group values by staff_id

```<code><?php
$arr1 = [
    [
        'id' => 6,
        'sales_target_amount' => '30000.00'
    ],
    [
        'id' => 10,
        'sales_target_amount' => '1000.00'
    ]
];

$arr2 = [
    [
        'sales_total' => '4165.80',
        'staff_id' => 6
    ],
    [
        'sales_total' => '1335.60',
        'staff_id' => 10
    ]
];

$results = [];

foreach ($arr1 as $value) {
    $results[$value['id']] = [
        'sales_target_amount' => $value['sales_target_amount']
    ];
}

foreach ($arr2 as $value) {
    $results[$value['staff_id']] = array_merge($results[$value['staff_id']], $value);
}

print_r(array_values($results));
</code>```

Title: How to insert items into existing array

Body:
Assume I have two arrays as below

array:2 [
  0 => {#1995
    +"id": 6
    +"sales_target_amount": "30000.00"
  }
  1 => {#1996
    +"id": 10
    +"sales_target_amount": "1000.00"
  }
]

second array

array:2 [
  0 => {#1994
    +"sales_total": "4165.80"
    +"staff_id": 6
  }
  1 => {#1513
    +"sales_total": "1335.60"
    +"staff_id": 10
  }
]

I'm trying to insert the first array sales_target_amount into the second array if the id is matched to the staff_id.

code

  $sum = array_merge($second_array[],$firs_array);

The code above will merge the two array together but not insert the items based on the id.

Expected Result

array:2 [
      0 => {#1994
        +"sales_total": "4165.80"
        +"staff_id": 6
        +"sales_target_amount": "30000.00"
      }
      1 => {#1513
        +"sales_total": "1335.60"
        +"staff_id": 10
        +"sales_target_amount": "1000.00"
      }
    ]

Body:
Use hashed map to group values by staff_id

<?php
$arr1 = [
    [
        'id' => 6,
        'sales_target_amount' => '30000.00'
    ],
    [
        'id' => 10,
        'sales_target_amount' => '1000.00'
    ]
];

$arr2 = [
    [
        'sales_total' => '4165.80',
        'staff_id' => 6
    ],
    [
        'sales_total' => '1335.60',
        'staff_id' => 10
    ]
];

$results = [];

foreach ($arr1 as $value) {
    $results[$value['id']] = [
        'sales_target_amount' => $value['sales_target_amount']
    ];
}

foreach ($arr2 as $value) {
    $results[$value['staff_id']] = array_merge($results[$value['staff_id']], $value);
}

print_r(array_values($results));


问:
failed to run Angular application getting error : Schema validation failed
I am using Angular 7 for my Application and I am getting error while running it on development server .

I did ng serve

but I got error below

```<code>      D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1>ng lint -fix Your
     global Angular CLI version (7.3.9) is greater than your local version
     (7.1.4). The local Angular CLI version is used.

     To disable this warning use "ng config -g cli.warnings.versionMismatch
     false".

 Schema validation failed with the following errors:
 Data path ".builders['app-shell']" should have required property 'class'.
     Error: Schema validation failed with the following errors:
Data path ".builders['app-shell']" should have required property 'class'.
         at MergeMapSubscriber.project (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\@angular-devkit\core\src\workspace\workspace.js:215:42)
         at MergeMapSubscriber._tryNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:69:27)
        at MergeMapSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:59:18)
         at MergeMapSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
         at MergeMapSubscriber.notifyNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:92:26)
        at InnerSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\InnerSubscriber.js:28:21)
        at InnerSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
         at MapSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\map.js:55:26)
        at MapSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
        at SwitchMapSubscriber.notifyNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\switchMap.js:86:26)
</code>```

Details OF my Angular Application

Angular.json - >

```<code>  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ftoss": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "styleext": "scss"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ftoss",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ],
            "styles": [
              "node_modules/font-awesome/scss/font-awesome.scss",
              "node_modules/angular-bootstrap-md/scss/bootstrap/bootstrap.scss",
              "node_modules/angular-bootstrap-md/scss/mdb-free.scss",
              "src/fonts/styles.css",
              "src/fonts/stylesheet.css",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/chart.js/dist/Chart.js",
              "node_modules/hammerjs/hammer.min.js"

            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "4mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angularev-server",
          "options": {
            "browserTarget": "ftoss:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ftoss:buildroduction"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ftoss:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.scss"
            ],
            "scripts": ["/src/firebase-messaging-sw.js"],
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ftoss-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angularrotractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "ftosserve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ftosserveroduction"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "ftoss"
}
</code>```

What I tried -  >

I uninstalled npm from my project and again installed it , again I got same issue

I did npm  cache clear again I got same issue

List item

答:
I think its with the rxjs incompatibility. Try running this

npm install rxjs-compat

Body:
I am using Angular 7 for my Application and I am getting error while running it on development server .

I did ng serve

but I got error below

      D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1>ng lint -fix Your
     global Angular CLI version (7.3.9) is greater than your local version
     (7.1.4). The local Angular CLI version is used.

     To disable this warning use "ng config -g cli.warnings.versionMismatch
     false".

 Schema validation failed with the following errors:
 Data path ".builders['app-shell']" should have required property 'class'.
     Error: Schema validation failed with the following errors:
Data path ".builders['app-shell']" should have required property 'class'.
         at MergeMapSubscriber.project (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\@angular-devkit\core\src\workspace\workspace.js:215:42)
         at MergeMapSubscriber._tryNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:69:27)
        at MergeMapSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:59:18)
         at MergeMapSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
         at MergeMapSubscriber.notifyNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\mergeMap.js:92:26)
        at InnerSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\InnerSubscriber.js:28:21)
        at InnerSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
         at MapSubscriber._next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\map.js:55:26)
        at MapSubscriber.Subscriber.next (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\Subscriber.js:67:18)
        at SwitchMapSubscriber.notifyNext (D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1\node_modules\rxjs\internal\operators\switchMap.js:86:26)

Details OF my Angular Application

Angular.json - >

  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ftoss": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "styleext": "scss"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ftoss",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ],
            "styles": [
              "node_modules/font-awesome/scss/font-awesome.scss",
              "node_modules/angular-bootstrap-md/scss/bootstrap/bootstrap.scss",
              "node_modules/angular-bootstrap-md/scss/mdb-free.scss",
              "src/fonts/styles.css",
              "src/fonts/stylesheet.css",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/chart.js/dist/Chart.js",
              "node_modules/hammerjs/hammer.min.js"

            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "4mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angularev-server",
          "options": {
            "browserTarget": "ftoss:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ftoss:buildroduction"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ftoss:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.scss"
            ],
            "scripts": ["/src/firebase-messaging-sw.js"],
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ftoss-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angularrotractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "ftosserve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ftosserveroduction"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "ftoss"
}

What I tried -  >

I uninstalled npm from my project and again installed it , again I got same issue

I did npm  cache clear again I got same issue

List item


问:
Is there a way to scrape the download file from a site that isn't just the HTML link?
So I am individually going through each link to download the file for photoshop presets, it is a little tiring to say the least. I've been researching ways to actually scrape the file and not just the HTML link or some way to take all the files at once from a page, but I've not had any luck. I am not versed in python so it doesn't make any sense to me, and the programs I have installed to do this for me aren't downloading what I am looking for.

I've tried chrome extensions, web scraping software, but it has not worked the way I am looking for.

https://www.brusheezy.com/brushes/22482-star-glow-brushes

this is just one of the links on one page

I expect to find something that will actually download the zip file from the link on the page.

答:
Note: I have not gotten this to work yet but thought the approach might be worth considering. I'll try to come back and either improve or delete it.

You might be able to do something along these lines in the browser's dev tools. You'll have to disable your popup blocker for this. This doesn't quite work for me because the download button started throwing up an account signup dialog. I suspect they might do this after some number of downloads, but you might have better luck if you have an account and are logged in.

Navigate to an uploader's page, open the browser's developer tools, paste in the code below and hit enter.

```<code>function go () {
    // get all the links from the grid on the current page
    const hrefs = Array.from(document.querySelectorAll('.ez-resource-grid a[href]')).map(a => a.href);

    // start the loading
    next(hrefs);
}

function next ([current, ...remaining]) {
    // open a new tab/window with the current href;
    const w = window.open(current, '_blank');

    // function to find the download button and "click" it.
    function triggerDownload () {
        try {
            w.querySelector('#download-button').click();
        }
        catch (e) {
            // something went wrong.
        }

        // if we haven't consumed all the links yet, start the next one.
        if (remaining.length) {
            next(remaining);

            // I tried adding a delay here thinking the account signup dialog
            // might be triggered by too many rapid requests, but it didn't
            // seem to matter.
            // setTimeout(() => next(remaining), 6000);
        }
    }

    // give the page a few seconds to load before attempting
    // to trigger the download. This should be replaced with
    // a ready event listener instead of a fixed delay, something
    // like:
    // w.document.addEventListener('readystatechange', triggerDownload)
    // but i'm tired and my first attempt didn't appear to work so i'm
    // throwing in this static delay hack instead.
    setTimeout(triggerDownload, 5000);
}

// kick it off
go();
</code>```

Body:
Note: I have not gotten this to work yet but thought the approach might be worth considering. I'll try to come back and either improve or delete it.

You might be able to do something along these lines in the browser's dev tools. You'll have to disable your popup blocker for this. This doesn't quite work for me because the download button started throwing up an account signup dialog. I suspect they might do this after some number of downloads, but you might have better luck if you have an account and are logged in.

Navigate to an uploader's page, open the browser's developer tools, paste in the code below and hit enter.

function go () {
    // get all the links from the grid on the current page
    const hrefs = Array.from(document.querySelectorAll('.ez-resource-grid a[href]')).map(a => a.href);

    // start the loading
    next(hrefs);
}

function next ([current, ...remaining]) {
    // open a new tab/window with the current href;
    const w = window.open(current, '_blank');

    // function to find the download button and "click" it.
    function triggerDownload () {
        try {
            w.querySelector('#download-button').click();
        }
        catch (e) {
            // something went wrong.
        }

        // if we haven't consumed all the links yet, start the next one.
        if (remaining.length) {
            next(remaining);

            // I tried adding a delay here thinking the account signup dialog
            // might be triggered by too many rapid requests, but it didn't
            // seem to matter.
            // setTimeout(() => next(remaining), 6000);
        }
    }

    // give the page a few seconds to load before attempting
    // to trigger the download. This should be replaced with
    // a ready event listener instead of a fixed delay, something
    // like:
    // w.document.addEventListener('readystatechange', triggerDownload)
    // but i'm tired and my first attempt didn't appear to work so i'm
    // throwing in this static delay hack instead.
    setTimeout(triggerDownload, 5000);
}

// kick it off
go();


问:
PHP Warning: POST Content-Length of 66192047 bytes exceeds the limit of 8388608 bytes
im getting this error when sending a form with uploaded file.

i already put upload_max_filesize  and post_max_size to 1000M in my php.ini without any result.

答:
If you did setting php.ini file and then restart Apache daemon or Server.

Please check your php source files and .htaccess file.

First.

Maybe contain ini_set('upload_max_filesize', '8M') or
  ini_set('post_max_size', '8M').

They can be in index.php file.

Second.

They can be in .htaccessfile.

```<code>php_value upload_max_filesize 10M
php_value post_max_size 10M
</code>```

Body:
If you did setting php.ini file and then restart Apache daemon or Server.

Please check your php source files and .htaccess file.

First.

Maybe contain ini_set('upload_max_filesize', '8M') or
  ini_set('post_max_size', '8M').

They can be in index.php file.

Second.

They can be in .htaccessfile.

php_value upload_max_filesize 10M
php_value post_max_size 10M


问:
Loop Through a Grouped Column in Pandas
I'm trying to compare every combination of phrases within a grouping to match and score them. I'm getting hung up on the looping through the groups:

```<code>import pandas as pd
from fuzzywuzzy import fuzz as fz
import itertools

data = [[1,'ab'],[1,'bc'],[1,'de'],[2,'gh'],[2,'hi'],[2,'jk'],[3,'kl'],[3,'lm'],[3,'yz']]
df = pd.DataFrame(data,columns=['Ids','DESCR'])

def iterated(df):
    for a, b in itertools.product(df['DESCR'],df['DESCR']):
        try:
            print(a, b, fz.partial_ratio(a, b), fz.token_set_ratio(a,b))
        except:
            pass
    return result

df.groupby('Ids').apply(iterated(df))
</code>```

The above is comparing each DESCR against everything in the whole list, rather than restricting it to each grouping. I'm getting:

```<code>ab ab 100 100
ab bc 50 50
ab de 0 0
ab gh 0 0
ab hi 0 0
ab jk 0 0
ab kl 0 0
ab lm 0 0
ab yz 0 0
bc ab 67 50
bc bc 100 100
bc de 0 0
bc gh 0 0
bc hi 0 0
bc jk 0 0
bc kl 0 0
bc lm 0 0
bc yz 0 0
...
</code>```

But it should be:

```<code>ab bc 50 50
ab de 0 0
bc de 0 0
gh hi 50 50
gh jk 0 0
hi jk 50 50
...
</code>```

Thank you.

答:
I think the problem is you aren't handling the groups correctly.  You are grouping and then applying your function based on the DESCR results in the entire df with your command .apply(iterated(df)).  Also, I think you want to use combinations instead of product.

You may need to break it apart and handle the groups individually.  Consider:

```<code>import pandas as pd
import itertools
data = [[1,'ab'],[1,'bc'],[1,'de'],[2,'gh'],[2,'hi'],[2,'jk'],[3,'kl'],[3,'lm'],[3,'yz']]
df = pd.DataFrame(data,columns=['Ids','DESCR'])

def show_combos(df):  #replace with your function...
    combos = itertools.combinations(df.DESCR, 2)
    for c in combos:
        print(c)

groups = df.groupby('Ids')

#iterate through the groups, which are mini-data frames
for name, group in groups:
    print('group name: {}'.format(name))
    show_combos(group)
    print()
</code>```

Which yields the groups you wanted:

```<code>group name: 1
('ab', 'bc')
('ab', 'de')
('bc', 'de')

group name: 2
('gh', 'hi')
('gh', 'jk')
('hi', 'jk')

group name: 3
('kl', 'lm')
('kl', 'yz')
('lm', 'yz')
</code>```

Title: Loop Through a Grouped Column in Pandas

Body:
I'm trying to compare every combination of phrases within a grouping to match and score them. I'm getting hung up on the looping through the groups:

import pandas as pd
from fuzzywuzzy import fuzz as fz
import itertools

data = [[1,'ab'],[1,'bc'],[1,'de'],[2,'gh'],[2,'hi'],[2,'jk'],[3,'kl'],[3,'lm'],[3,'yz']]
df = pd.DataFrame(data,columns=['Ids','DESCR'])

def iterated(df):
    for a, b in itertools.product(df['DESCR'],df['DESCR']):
        try:
            print(a, b, fz.partial_ratio(a, b), fz.token_set_ratio(a,b))
        except:
            pass
    return result

df.groupby('Ids').apply(iterated(df))

The above is comparing each DESCR against everything in the whole list, rather than restricting it to each grouping. I'm getting:

ab ab 100 100
ab bc 50 50
ab de 0 0
ab gh 0 0
ab hi 0 0
ab jk 0 0
ab kl 0 0
ab lm 0 0
ab yz 0 0
bc ab 67 50
bc bc 100 100
bc de 0 0
bc gh 0 0
bc hi 0 0
bc jk 0 0
bc kl 0 0
bc lm 0 0
bc yz 0 0
...

But it should be:

ab bc 50 50
ab de 0 0
bc de 0 0
gh hi 50 50
gh jk 0 0
hi jk 50 50
...

Thank you.

Body:
I think the problem is you aren't handling the groups correctly.  You are grouping and then applying your function based on the DESCR results in the entire df with your command .apply(iterated(df)).  Also, I think you want to use combinations instead of product.

You may need to break it apart and handle the groups individually.  Consider:

import pandas as pd
import itertools
data = [[1,'ab'],[1,'bc'],[1,'de'],[2,'gh'],[2,'hi'],[2,'jk'],[3,'kl'],[3,'lm'],[3,'yz']]
df = pd.DataFrame(data,columns=['Ids','DESCR'])

def show_combos(df):  #replace with your function...
    combos = itertools.combinations(df.DESCR, 2)
    for c in combos:
        print(c)

groups = df.groupby('Ids')

#iterate through the groups, which are mini-data frames
for name, group in groups:
    print('group name: {}'.format(name))
    show_combos(group)
    print()

Which yields the groups you wanted:

group name: 1
('ab', 'bc')
('ab', 'de')
('bc', 'de')

group name: 2
('gh', 'hi')
('gh', 'jk')
('hi', 'jk')

group name: 3
('kl', 'lm')
('kl', 'yz')
('lm', 'yz')


问:
Sending ID input from submit to controller action
I have a view which I need to take a user input, and send it to a controller action. I have tried several things but what references I have found online have not seemed to be working for me. I have an input in a form, and I have the controller and action name listed, however it does not seem to be passing the value from the users input. In fact, unless I hardcode the value into the controllers parameters, when I get to the page I just get error:

```<code>The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'Namespace.Controllers.TerminalReceiptsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</code>```

Parameter name: parameters

Otherwise, when hard coded into the controller params, it works just fine.

Below is some code.

View import portion:

```<code>@using (Html.BeginForm("Index", "TerminalReceipts"))
 {

  <div>
    <input type="text" name="ID" />
     <input type="submit" value="Find Receipts">
  </div>

   string Id = Request.Form["ID"];
}
</code>```

View table portion:

```<code><div class="row">
<div class="col-md-12" style="overflow-y:scroll">
    <table class="table table-striped table-hover table-bordered" id="terminalReceipts">
        <thead>
            <tr>
                <th>Local Transaction Time</th>
                <th>Amount</th>
                <th>Receipt</th>
            </tr>
        </thead>
        <tbody>

            @foreach (var item in Model.TransactionsTests)
            {
                <tr>
                    <td>@item.TransactionTime</td>
                    @*<td>@Html.DisplayFor(modelItem => item.LocalTransactionTime)</td>*@
                    <td>@item.Amount</td>
                    <td>@Html.ActionLink("View Receipt", "Details", new { Key = 1 }, new { @class = "btn btn-primary btn-sm" }) <br /></td>
                </tr>
            }
        </tbody>
    </table>
</div>
</code>```

Controller action:

```<code>        // GET: TerminalReceipts
    public ActionResult Index(int id )
    {
         var model = TRBL.GetTransactionTestsData(id);
        //var model = new TerminalReceiptsVM();

        return View(model);
    }
</code>```

Where in my code (specifically the view import portion) am I going wrong?

答:
Please try bellow:

Remove string Id = Request.Form["ID"]; from your view and use button instead of input for button control:

```<code>@using (Html.BeginForm("Index", "TerminalReceipts"))
{
   <div>
     <input type="text" name="ID" />
     <button type="submit">Find Receipt</button>
   </div>
}
</code>```

In controller's action, mark the action method as POST to differ it from GET method.

```<code>// GET: TerminalReceipts
[HttpPost]
public ActionResult Index(int id )
{
     var model = TRBL.GetTransactionTestsData(id);
    //var model = new TerminalReceiptsVM();

    return View(model);
}
</code>```

Please note that, if you do not mark an action method as POST, by default it will be considered GET. So the problem you are facing is you are calling the method on GET request where you need to provide the value to the parameter as query string.

PS: For your scenario, I am recommending to use two action methods for Index view. One for GET where it displays the form, the second POST action method to get the data from the form on submission.

Body:
I have a view which I need to take a user input, and send it to a controller action. I have tried several things but what references I have found online have not seemed to be working for me. I have an input in a form, and I have the controller and action name listed, however it does not seem to be passing the value from the users input. In fact, unless I hardcode the value into the controllers parameters, when I get to the page I just get error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'Namespace.Controllers.TerminalReceiptsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Parameter name: parameters

Otherwise, when hard coded into the controller params, it works just fine.

Below is some code.

View import portion:

@using (Html.BeginForm("Index", "TerminalReceipts"))
 {

    <input type="text" name="ID" />
     <input type="submit" value="Find Receipts">

   string Id = Request.Form["ID"];
}

View table portion:

                Local Transaction Time
                Amount
                Receipt

            @foreach (var item in Model.TransactionsTests)
            {

                    @item.TransactionTime
                    @*@Html.DisplayFor(modelItem => item.LocalTransactionTime)	*@
                    @item.Amount
                    @Html.ActionLink("View Receipt", "Details", new { Key = 1 }, new { @class = "btn btn-primary btn-sm" })

            }

Controller action:

        // GET: TerminalReceipts
    public ActionResult Index(int id )
    {
         var model = TRBL.GetTransactionTestsData(id);
        //var model = new TerminalReceiptsVM();

        return View(model);
    }

Where in my code (specifically the view import portion) am I going wrong?

Body:
Please try bellow:

Remove string Id = Request.Form["ID"]; from your view and use button instead of input for button control:

@using (Html.BeginForm("Index", "TerminalReceipts"))
{
   <div>
     <input type="text" name="ID" />
     <button type="submit">Find Receipt</button>
   </div>
}

In controller's action, mark the action method as POST to differ it from GET method.

// GET: TerminalReceipts
[HttpPost]
public ActionResult Index(int id )
{
     var model = TRBL.GetTransactionTestsData(id);
    //var model = new TerminalReceiptsVM();

    return View(model);
}

Please note that, if you do not mark an action method as POST, by default it will be considered GET. So the problem you are facing is you are calling the method on GET request where you need to provide the value to the parameter as query string.

PS: For your scenario, I am recommending to use two action methods for Index view. One for GET where it displays the form, the second POST action method to get the data from the form on submission.


问:
Node Mongo Db Finding Records of few minutes
I am facing an issue, actually I have mongoose module

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var saveVisitorsDetails = new Schema({
  userId : { type: String, unique: true, dropDups: true},
  visitorName : { type: String},
  visitorMobileNumber : { type: Number},
  expireStatus : { type : Number},
  clientUnreadMessageCount : { type : Number},
  adminUnreadMessageCount : { type : Number},
  visibleVisitorChat : { type : Boolean},
  visibleAdminChat : { type : Boolean},
  displayAdminChat : { type : Boolean},
  activeChat : { type : Boolean},
  adminId : { type : String},
  visitorMsg : { type : String},
  msgTiming : { type : Date},
  showVisitorCross : { type : Boolean},
  showVisitorMinimize : { type : Boolean},
  newMessageForAdmin : { type : Boolean},
  expireUserForAdmin : { type : Boolean},
  visitorLocationObject : { type : Object }
});

module.exports = mongoose.model('Visitor',saveVisitorsDetails);
</code>```

I want to query all documents of msgTiming 5 minutes from now, but I can't get it.

My query is

```<code>var express = require('express');
var app = express();
var Visitor = require('./models/visitor');
app.post('/loadVisitorDetails', function(req, res){
    Visitor.collection.find({adminId : req.body.adminId ,expireStatus : 0}).sort({msgTiming : -1}).toArray(function(err, result){
        if(err){
            console.log(err);
        }else{
            var obj = {
                rslt : result,
                id : req.body.adminId
            }
            res.send(obj);
        }
    });
});
</code>```

I don't know how to find all records of 5 minutes from now and response array should be on msgTiming arrangement

Please help me, I have been facing this problem for the past 2 days; any suggestions will be appreciated

Thanks in advance

答:
Nice answer by Manjeet, just a small correction it should be after.getMinutes - 5 instead of +.    </p>

```<code>var express = require('express');
var app = express();
var Visitor = require('./models/visitor');
app.post('/loadVisitorDetails', function (req, res) {
    let now = new Date();
    let after = new Date();
    after.setMinutes(after.getMinutes() - 5);
    let critria = {
        $and: [{
            adminId: req.body.adminId
        }, {
            expireStatus: 0
        }, {
            msgTiming: {
                $gte: now,
                $lte: after
            }
        }]
    };

    let projection = {}
    let options = { sort:{ msgTiming : -1 }}

    Visitor.collection.find(critria,projection,options,function(err,result){
        if(err){
            console.log(err)
        } else {
            console.log(result)
        }
    })
});
</code>```

Body:
I am facing an issue, actually I have mongoose module

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var saveVisitorsDetails = new Schema({
  userId : { type: String, unique: true, dropDups: true},
  visitorName : { type: String},
  visitorMobileNumber : { type: Number},
  expireStatus : { type : Number},
  clientUnreadMessageCount : { type : Number},
  adminUnreadMessageCount : { type : Number},
  visibleVisitorChat : { type : Boolean},
  visibleAdminChat : { type : Boolean},
  displayAdminChat : { type : Boolean},
  activeChat : { type : Boolean},
  adminId : { type : String},
  visitorMsg : { type : String},
  msgTiming : { type : Date},
  showVisitorCross : { type : Boolean},
  showVisitorMinimize : { type : Boolean},
  newMessageForAdmin : { type : Boolean},
  expireUserForAdmin : { type : Boolean},
  visitorLocationObject : { type : Object }
});

module.exports = mongoose.model('Visitor',saveVisitorsDetails);

I want to query all documents of msgTiming 5 minutes from now, but I can't get it.

My query is

var express = require('express');
var app = express();
var Visitor = require('./models/visitor');
app.post('/loadVisitorDetails', function(req, res){
    Visitor.collection.find({adminId : req.body.adminId ,expireStatus : 0}).sort({msgTiming : -1}).toArray(function(err, result){
        if(err){
            console.log(err);
        }else{
            var obj = {
                rslt : result,
                id : req.body.adminId
            }
            res.send(obj);
        }
    });
});

I don't know how to find all records of 5 minutes from now and response array should be on msgTiming arrangement

Please help me, I have been facing this problem for the past 2 days; any suggestions will be appreciated

Thanks in advance

Body:
Nice answer by Manjeet, just a small correction it should be after.getMinutes - 5 instead of +.

var express = require('express');
var app = express();
var Visitor = require('./models/visitor');
app.post('/loadVisitorDetails', function (req, res) {
    let now = new Date();
    let after = new Date();
    after.setMinutes(after.getMinutes() - 5);
    let critria = {
        $and: [{
            adminId: req.body.adminId
        }, {
            expireStatus: 0
        }, {
            msgTiming: {
                $gte: now,
                $lte: after
            }
        }]
    };

    let projection = {}
    let options = { sort:{ msgTiming : -1 }}

    Visitor.collection.find(critria,projection,options,function(err,result){
        if(err){
            console.log(err)
        } else {
            console.log(result)
        }
    })
});


问:
Execute r scripts in a ubuntu server using browser?
I am having a R script which generates a bar chart, i will get the data modified often. So i want to upload the data and then run this from a browser and also get the results generated on the browser it self. I have gone through FastRweb but it is pretty old repo. Can any one help me on this.

Thanks,
Ans.

答:
To do this I would recommend that you run Shiny on your own webserver with full control. Here is a nice link how to do this.

https://deanattali.com/2015/05/09/setup-rstudio-shiny-server-digital-ocean/

I have scripts tat run daily and schedule this task by CRON. This is quite easy to do:

I give my scripts rights to read, write and execute with the following command

sudo chmod 777 /path/script.R

Here is an example of my CRON task:

*/30 * * * * /bin/sh /home/markus/script.R > /tmp/listener2.log 2>&

The script should for example manipulate the data and then store it in the folder of your shiny application, where the shiny application reads the data and renders the expected plot.


问:
Postgres with CTE and return multiple tables
I want to use a CTE to format a complex query and return multiple tables.

below code：

```<code>CREATE OR REPLACE FUNCTION "public"."postgres_return_mutiple_table"(refcursor,refcursor)
RETURNS SETOF "pg_catalog"."refcursor" AS $BODY$
declare return_agents alias for $1;
return_agentpayrate alias for $2;
BEGIN
        with t_agents as (
                    select * from agents join .... where .. /*maybe complex query*/
        ),
        t_agentpayrate as (
                select * from t_agents join .... where .. /*maybe complex query*/
        )
        OPEN return_agents FOR select * from t_agents
        RETURN NEXT return_agents;
        OPEN return_agentpayrate FOR
                     select * from t_agentpayrate RETURN
                NEXT t_agentpayrate;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
</code>```

When I run this function, it errors:

```<code>ERROR:  syntax error at or near "OPEN"
LINE 12:   OPEN return_agents FOR select * from t_agents;
           ^
, Time: 0.001000s
</code>```

答:
```<code>CREATE OR REPLACE FUNCTION public.fn_get_available_enterprise(
"shortname" varchar,
"filter" varchar,
"recordpage" int4,
"pageindex" int4,
refcursor,
refcursor
) returns setof refcursor
as
$$
declare avail_entp  alias for $5;
        avail_entp_count alias for $6;
begin
   open avail_entp for
         WITH available_enterprise AS (
                 SELECT distinct entinfo,ent.entname,ent.entabbr FROM get_agent_nocontian_entpaymenttype(shortname,filter,recordpage,pageindex)
                 JOIN wxbsenterprise ent  on ent.entname = output_entname
                 where (("filter"!='' and (ent.entname like "filter" or entinfo like "filter" or entabbr like "filter"))
                 or ("filter"='' and 1=1))
                 limit recordpage offset (pageindex-1)*recordpage
          ),
          enterpriserate_link_agent as(
                 select * from agententerprises
                 where entname=@entname and level=1
                 and (validate = true or (validate = false and enddate is not null and enddate >= current_date))
          )
          select * from available_enterprise;
   return next avail_entp;
   open avail_entp_count for
                         WITH available_enterprise_count as (
                                         SELECT distinct entinfo,ent.entname,entabbr FROM get_agent_nocontian_entpaymenttype(shortname,filter,recordpage,pageindex) as epna
                                                                JOIN wxbsenterprise ent  on ent.entname = output_entname
                         )
                        select count(*) from available_enterprise_count;
   return next avail_entp_count;
end;
$$ language plpgsql;

</code>```

Body:
I want to use a CTE to format a complex query and return multiple tables.

below code：

CREATE OR REPLACE FUNCTION "public"."postgres_return_mutiple_table"(refcursor,refcursor)
RETURNS SETOF "pg_catalog"."refcursor" AS $BODY$
declare return_agents alias for $1;
return_agentpayrate alias for $2;
BEGIN
        with t_agents as (
                    select * from agents join .... where .. /*maybe complex query*/
        ),
        t_agentpayrate as (
                select * from t_agents join .... where .. /*maybe complex query*/
        )
        OPEN return_agents FOR select * from t_agents
        RETURN NEXT return_agents;
        OPEN return_agentpayrate FOR
                     select * from t_agentpayrate RETURN
                NEXT t_agentpayrate;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

When I run this function, it errors:

ERROR:  syntax error at or near "OPEN"
LINE 12:   OPEN return_agents FOR select * from t_agents;
           ^
, Time: 0.001000s


问:
How to listen for mousdown event in javascript - react-materialize?
This is the following code return in react

```<code>import {
      Input
    } from "react-materialize";

    <Input
        id="fromDate"
        name="from"
        type="date"
        onChange={this.handleChangeFromDate}
     />
</code>```

How to use mousedown event in the following handler

```<code>handleChangeFromDate(event, value) {
        event.preventDefault();
        let startDate = new Date(value).getTime(value);
}
</code>```

I want to use event.preventDefault in mousedown event. I have jquery code for this, but not sure how to transform it into js code?

```<code>$('.datepicker').on('mousedown',function(event){
    event.preventDefault();
})
</code>```

答:
You can call the same method for mouse down event by calling onMouseDown event

```<code>    onMouseDown={this.handleChangeFromDate}
</code>```

But I am not sure about your '.datepicker' component.  If it is a separate component, you should add onMouseDown to that component's props

Body:
This is the following code return in react

import {
      Input
    } from "react-materialize";

    <Input
        id="fromDate"
        name="from"
        type="date"
        onChange={this.handleChangeFromDate}
     />

How to use mousedown event in the following handler

handleChangeFromDate(event, value) {
        event.preventDefault();
        let startDate = new Date(value).getTime(value);
}

I want to use event.preventDefault in mousedown event. I have jquery code for this, but not sure how to transform it into js code?

$('.datepicker').on('mousedown',function(event){
    event.preventDefault();
})

Body:
You can call the same method for mouse down event by calling onMouseDown event

    onMouseDown={this.handleChangeFromDate}

But I am not sure about your '.datepicker' component.  If it is a separate component, you should add onMouseDown to that component's props


答:
array_merge() do not work with multidimensional array.
Try to use array_merge_recursive().

And you not need use square brackets in this context.
Run function just like

$sum = array_merge_recursive($second_array, $firs_array);
```

Title: How to insert items into existing array


问:
jQuery ul event target - can i find the li that actually is event target?
```<code>$("#slider ul").hover(function(){
  //do something
});
</code>```

Is there a way to find out which child (li) was actually hovered on to make this function work?

This is a long function that when originally written as $("#slider ul li") etc, worked, but only when completely leaving the slider ul area. I need it to work when moving from one li directly to neighboring li, etc.

答:
```<code>$("#slider ul").hover(function(evt){
   var targetElement = evt.target;
   // do something
});
</code>```

Essentially the jQuery hover allows you to pass in the event.  This event holds the target element that triggered the event.

Body:
$("#slider ul").hover(function(){
  //do something
});

Is there a way to find out which child (li) was actually hovered on to make this function work?

This is a long function that when originally written as $("#slider ul li") etc, worked, but only when completely leaving the slider ul area. I need it to work when moving from one li directly to neighboring li, etc.

Body:
$("#slider ul").hover(function(evt){
   var targetElement = evt.target;
   // do something
});

Essentially the jQuery hover allows you to pass in the event.  This event holds the target element that triggered the event.


问:
select count (distinct) returning incorrect count
I'm trying to run a code that will summarise a list of clients based on age categories. I have the client ID and their ages, and am using a CASE WHEN to group the ages into buckets, then trying to count the client ids in each of those buckets.

For info - the Assisted Date field is just the date on which the client was served and this is just included in my testing to keep the results small - so I'm just focusing on Feb 2019 services that aren't Assessments; and the SIR ID is the location at which the service was provided.

```<code>select distinct
    CASE
        when CD.Age between 0 and 5 then '0-5'
        when CD.Age between 6 and 11 then '6-11'
        when CD.Age between 12 and 14 then '12-14'
        when CD.Age between 15 and 17 then '15-17'
        when CD.Age between 18 and 24 then '18-24'
        when CD.Age between 25 and 54 then '25-54'
        when CD.Age between 55 and 64 then '55-64'
        when CD.Age > 65 then '65+'
        else 'Unknown'
    END AS Age_Group,
count(distinct AP.Source_Individual_ID) as "Count"
from dm.Assistance_Provided AP, rpt.ClientsDemographics CD
        where CD.Source_Individual_ID = AP.Source_Individual_ID
        and AP.SIR_ID = '1909'
        and AP.Service_Provided <> 'Assessment'
        and year(AP.Assisted_Date) = '2019'
        and month(AP.Assisted_Date) = 2
group by CD.Age
</code>```

If I run the code excluding the count(distinct) I end up with 17 rows of data. The 17 clients are all aged between 18-24 so the Age-Group for all clients come back as 18-24. So the Case When appears to be operating correctly.

However, if I run the code with the count(distinct), I end up with 3 rows of data. the Age Group 18-24 is listed 3 times and the Count as 2, 4, and 5 respectively for the 3 lines. I definitely have 17 different IDs in the list, but for some reason this is being reduced to a total of 11 when I add the count(distinct).

I've also tried removing the distinct from the select i.e. so

```<code>select
    CASE
        when CD.Age between ....
</code>```

If I do that I get 5 rows - still all with age group 18-24, but then with 2,4,5,4,2 respectively - so then back to my total of 17. But I'm not sure why I'm not just getting one line back : Age Group: 18-24; Count: 17

What am I doing wrong?

答:
I suspect that you should actually be aggregating by Source_Individual, and then taking conditional counts everywhere:

```<code>SELECT
    CD.Source_Individual_ID,
    COUNT(CASE WHEN CD.Age BETWEEN 0 AND 5 THEN 1 END) AS [0-5],
    COUNT(CASE WHEN CD.Age BETWEEN 6 AND 11 THEN 1 END) AS [6-11],
    COUNT(CASE WHEN CD.Age BETWEEN 12 AND 14 THEN 1 END) AS [12-14],
    COUNT(CASE WHEN CD.Age BETWEEN 15 AND 17 THEN 1 END) AS [15-17],
    COUNT(CASE WHEN CD.Age BETWEEN 18 AND 24 THEN 1 END) AS [18-24],
    COUNT(CASE WHEN CD.Age BETWEEN 25 AND 54 THEN 1 END) AS [25-54],
    COUNT(CASE WHEN CD.Age BETWEEN 55 AND 64 THEN 1 END) AS [55-64]
    COUNT(CASE WHEN CD.Age > 65 THEN 1 END) AS [65+],
    COUNT(*) AS [Number of Clients Assisted]
FROM dm.Assistance_Provided AP
INNER JOIN rpt.ClientsDemographics CD
    ON CD.Source_Individual_ID = AP.Source_Individual_ID
WHERE
    AP.SIR_ID = '1909' AND
    AP.Service_Provided <> 'Assessment' AND
    YEAR(AP.Assisted_Date) = 2019 AND
    MONTH(AP.Assisted_Date) = 2
GROUP BY
    CD.Source_Individual_ID;
</code>```

Note that I have rewritten your query to use explicit, modern, inner joins, rather than the implicit joins you were using.

Body:
I'm trying to run a code that will summarise a list of clients based on age categories. I have the client ID and their ages, and am using a CASE WHEN to group the ages into buckets, then trying to count the client ids in each of those buckets.

For info - the Assisted Date field is just the date on which the client was served and this is just included in my testing to keep the results small - so I'm just focusing on Feb 2019 services that aren't Assessments; and the SIR ID is the location at which the service was provided.

select distinct
    CASE
        when CD.Age between 0 and 5 then '0-5'
        when CD.Age between 6 and 11 then '6-11'
        when CD.Age between 12 and 14 then '12-14'
        when CD.Age between 15 and 17 then '15-17'
        when CD.Age between 18 and 24 then '18-24'
        when CD.Age between 25 and 54 then '25-54'
        when CD.Age between 55 and 64 then '55-64'
        when CD.Age > 65 then '65+'
        else 'Unknown'
    END AS Age_Group,
count(distinct AP.Source_Individual_ID) as "Count"
from dm.Assistance_Provided AP, rpt.ClientsDemographics CD
        where CD.Source_Individual_ID = AP.Source_Individual_ID
        and AP.SIR_ID = '1909'
        and AP.Service_Provided <> 'Assessment'
        and year(AP.Assisted_Date) = '2019'
        and month(AP.Assisted_Date) = 2
group by CD.Age

If I run the code excluding the count(distinct) I end up with 17 rows of data. The 17 clients are all aged between 18-24 so the Age-Group for all clients come back as 18-24. So the Case When appears to be operating correctly.

However, if I run the code with the count(distinct), I end up with 3 rows of data. the Age Group 18-24 is listed 3 times and the Count as 2, 4, and 5 respectively for the 3 lines. I definitely have 17 different IDs in the list, but for some reason this is being reduced to a total of 11 when I add the count(distinct).

I've also tried removing the distinct from the select i.e. so

select
    CASE
        when CD.Age between ....

If I do that I get 5 rows - still all with age group 18-24, but then with 2,4,5,4,2 respectively - so then back to my total of 17. But I'm not sure why I'm not just getting one line back : Age Group: 18-24; Count: 17

What am I doing wrong?

Body:
I suspect that you should actually be aggregating by Source_Individual, and then taking conditional counts everywhere:

SELECT
    CD.Source_Individual_ID,
    COUNT(CASE WHEN CD.Age BETWEEN 0 AND 5 THEN 1 END) AS [0-5],
    COUNT(CASE WHEN CD.Age BETWEEN 6 AND 11 THEN 1 END) AS [6-11],
    COUNT(CASE WHEN CD.Age BETWEEN 12 AND 14 THEN 1 END) AS [12-14],
    COUNT(CASE WHEN CD.Age BETWEEN 15 AND 17 THEN 1 END) AS [15-17],
    COUNT(CASE WHEN CD.Age BETWEEN 18 AND 24 THEN 1 END) AS [18-24],
    COUNT(CASE WHEN CD.Age BETWEEN 25 AND 54 THEN 1 END) AS [25-54],
    COUNT(CASE WHEN CD.Age BETWEEN 55 AND 64 THEN 1 END) AS [55-64]
    COUNT(CASE WHEN CD.Age > 65 THEN 1 END) AS [65+],
    COUNT(*) AS [Number of Clients Assisted]
FROM dm.Assistance_Provided AP
INNER JOIN rpt.ClientsDemographics CD
    ON CD.Source_Individual_ID = AP.Source_Individual_ID
WHERE
    AP.SIR_ID = '1909' AND
    AP.Service_Provided <> 'Assessment' AND
    YEAR(AP.Assisted_Date) = 2019 AND
    MONTH(AP.Assisted_Date) = 2
GROUP BY
    CD.Source_Individual_ID;

Note that I have rewritten your query to use explicit, modern, inner joins, rather than the implicit joins you were using.


答:
You need to put your case statement in your group by. As it is, since you group by CD.Age it will write a single row for every distinct age. In other words if you have two rows with Age =  12 and one row with Age = 13 you'll get two rows, both with 12-14 as their age group, but with a count of 2 for the first and 1 for the second. To make it more confusing, if you only had one row each, then because both rows are the same and you have the distinct clause it would only return 1 row with a count of 1.

If you put your case statement into the group by, then it will group by each distinct Age_Group instead. i.e., it does the case transformation first, then groups by it.

So try:

```<code>select
    CASE
        when CD.Age between 0 and 5 then '0-5'
        when CD.Age between 6 and 11 then '6-11'
        when CD.Age between 12 and 14 then '12-14'
        when CD.Age between 15 and 17 then '15-17'
        when CD.Age between 18 and 24 then '18-24'
        when CD.Age between 25 and 54 then '25-54'
        when CD.Age between 55 and 64 then '55-64'
        when CD.Age > 65 then '65+'
        else 'Unknown'
    END AS Age_Group,
count(distinct AP.Source_Individual_ID) as "Number of Clients Assisted"
from dm.Assistance_Provided AP, rpt.ClientsDemographics CD
        where CD.Source_Individual_ID = AP.Source_Individual_ID
        and AP.SIR_ID = '1909'
        and AP.Service_Provided <> 'Assessment'
        and year(AP.Assisted_Date) = '2019'
        and month(AP.Assisted_Date) = 2
group by CASE
        when CD.Age between 0 and 5 then '0-5'
        when CD.Age between 6 and 11 then '6-11'
        when CD.Age between 12 and 14 then '12-14'
        when CD.Age between 15 and 17 then '15-17'
        when CD.Age between 18 and 24 then '18-24'
        when CD.Age between 25 and 54 then '25-54'
        when CD.Age between 55 and 64 then '55-64'
        when CD.Age > 65 then '65+'
        else 'Unknown'
    END
</code>```

Title: select count (distinct) returning incorrect count

Body:
You need to put your case statement in your group by. As it is, since you group by CD.Age it will write a single row for every distinct age. In other words if you have two rows with Age =  12 and one row with Age = 13 you'll get two rows, both with 12-14 as their age group, but with a count of 2 for the first and 1 for the second. To make it more confusing, if you only had one row each, then because both rows are the same and you have the distinct clause it would only return 1 row with a count of 1.

If you put your case statement into the group by, then it will group by each distinct Age_Group instead. i.e., it does the case transformation first, then groups by it.

So try:

select
    CASE
        when CD.Age between 0 and 5 then '0-5'
        when CD.Age between 6 and 11 then '6-11'
        when CD.Age between 12 and 14 then '12-14'
        when CD.Age between 15 and 17 then '15-17'
        when CD.Age between 18 and 24 then '18-24'
        when CD.Age between 25 and 54 then '25-54'
        when CD.Age between 55 and 64 then '55-64'
        when CD.Age > 65 then '65+'
        else 'Unknown'
    END AS Age_Group,
count(distinct AP.Source_Individual_ID) as "Number of Clients Assisted"
from dm.Assistance_Provided AP, rpt.ClientsDemographics CD
        where CD.Source_Individual_ID = AP.Source_Individual_ID
        and AP.SIR_ID = '1909'
        and AP.Service_Provided <> 'Assessment'
        and year(AP.Assisted_Date) = '2019'
        and month(AP.Assisted_Date) = 2
group by CASE
        when CD.Age between 0 and 5 then '0-5'
        when CD.Age between 6 and 11 then '6-11'
        when CD.Age between 12 and 14 then '12-14'
        when CD.Age between 15 and 17 then '15-17'
        when CD.Age between 18 and 24 then '18-24'
        when CD.Age between 25 and 54 then '25-54'
        when CD.Age between 55 and 64 then '55-64'
        when CD.Age > 65 then '65+'
        else 'Unknown'
    END