答:
<map> and <area> tags are not rendered on the screen. They just define mouse actions area for the browser to understand so that it can perform actions on the underlying image/svg element.

If you want areas to change colors, you need to recolor the underlying image or use external libraries. This is a very challenging problem and might take a lot of time and effort to do on your own.

http://www.outsharked.com/ImageMapster/default.aspx?what.html is a robust minimal library for the task.

Title: html map area hover effect with css

Body:
How can we change image map area background color with hover and click without any third party plugin. I tried this.

$(document).on('click', '.states', function(){
         $(this).css("background-color","red")
});

$(document).on('mouseover', '.states', function(){
          $(this).css("background-color","blue")
});

<map name="image-map">
    <area class="states" target="" alt="" title="Western Australia" href="#" coords="322,390,306,399,289,402,276,403,260,414,247,426,239,435,221,437,204,431,188,435,175,446,152,460,131,456,123,444,113,440,117,432,127,428,127,406,121,382,117,354,105,312,92,293,99,295,104,291,105,278,90,251,99,226,98,210,103,222,111,209,125,199,138,192,156,188,176,178,203,173,223,144,222,132,230,119,243,138,245,124,245,113,256,114,260,98,268,100,268,93,272,89,268,83,278,81,287,70,300,73,310,84,310,94,316,96,317,85,323,88,323,96" shape="poly">
    <area class="states" target="" alt="" title="Northern Territory" href="#" shape="poly" coords="325, 91, 326, 285, 461, 285, 459, 114, 447, 104, 441, 104, 433, 96, 423, 88, 420, 87, 428, 74, 430, 70, 429, 66, 425, 63, 430, 57, 435, 53, 440, 47, 443, 43, 438, 40, 435, 39, 431, 41, 427, 41, 419, 41, 415, 39, 410, 35, 404, 38, 398, 33, 392, 33, 384, 31, 379, 22, 369, 22, 368, 25, 374, 28, 379, 29, 373, 37, 366, 40, 357, 39, 354, 41, 351, 43, 349, 50, 344, 44, 342, 52, 340, 54, 343, 60, 337, 62, 332, 65, 333, 73, 331, 77, 336, 81, 338, 82, 335, 86, 335, 92" />
    <area class="states" target="" alt="" title="Queensland" href="#" shape="poly" coords="506, 340, 621, 341, 633, 331, 650, 334, 662, 341, 667, 336, 674, 330, 682, 327, 692, 327, 688, 319, 685, 310, 685, 299, 681, 283, 681, 271, 673, 264, 668, 257, 660, 249, 655, 244, 653, 239, 651, 237, 651, 221, 645, 219, 638, 219, 633, 210, 626, 197, 623, 189, 616, 178, 609, 174, 604, 169, 599, 166, 589, 161, 583, 157, 581, 149, 581, 141, 581, 131, 577, 127, 572, 114, 572, 97, 568, 85, 558, 77, 548, 71, 546, 78, 543, 62, 542, 51, 539, 41, 530, 26, 524, 19, 519, 25, 517, 38, 515, 45, 514, 56, 512, 68, 512, 81, 513, 97, 510, 108, 504, 118, 500, 128, 491, 133, 482, 134, 477, 124, 467, 121, 458, 115, 459, 283, 508, 286" />
    <area class="states" target="" alt="" title="South Australia" href="#" shape="poly" coords="324, 285, 506, 286, 503, 527, 493, 515, 486, 509, 488, 505, 484, 503, 488, 497, 489, 491, 481, 480, 483, 471, 482, 468, 475, 468, 471, 470, 464, 474, 461, 474, 469, 461, 462, 446, 460, 443, 456, 455, 449, 462, 443, 463, 450, 455, 454, 449, 453, 441, 457, 434, 460, 423, 461, 418, 455, 409, 451, 418, 447, 424, 441, 432, 437, 442, 428, 451, 425, 461, 420, 452, 417, 443, 413, 435, 410, 424, 403, 422, 401, 417, 402, 411, 397, 407, 387, 398, 378, 398, 371, 397, 364, 391, 355, 389, 346, 389, 342, 390, 329, 391, 324, 391" />
    <area class="states" target="" alt="" title="New South Wales & ACT" href="#" shape="poly" coords="503, 445, 502, 525, 514, 531, 518, 531, 527, 531, 533, 537, 547, 543, 551, 536, 557, 530, 557, 526, 562, 520, 566, 521, 567, 526, 567, 535, 574, 535, 576, 541, 586, 541, 592, 539, 598, 533, 602, 523, 607, 522, 616, 521, 634, 517, 636, 517, 620, 511, 612, 507, 607, 503, 603, 492, 594, 488, 581, 485, 566, 483, 560, 488, 553, 482, 544, 477, 541, 470, 532, 465, 537, 461, 532, 459, 524, 457, 521, 450, 513, 446, 508, 448" />
    <area class="states" target="" alt="" title="Victoria" href="#" shape="poly" coords="506, 340, 626, 341, 631, 335, 638, 333, 640, 333, 646, 332, 655, 335, 656, 339, 660, 343, 664, 346, 666, 341, 669, 337, 669, 330, 674, 328, 678, 327, 684, 327, 687, 327, 692, 327, 692, 335, 691, 348, 684, 349, 689, 352, 689, 364, 684, 367, 684, 377, 684, 386, 677, 405, 677, 414, 671, 414, 671, 414, 671, 414, 658, 434, 653, 447, 650, 461, 647, 473, 642, 483, 639, 502, 639, 509, 636, 514, 629, 508, 619, 505, 610, 499, 607, 488, 604, 482, 594, 482, 589, 482, 583, 482, 581, 481, 572, 478, 568, 477, 564, 479, 561, 480, 560, 483, 552, 474, 550, 470, 541, 463, 539, 455, 535, 453, 530, 450, 527, 454, 526, 453, 524, 445, 520, 443, 512, 443, 502, 441" />
</map>


来源: stackexchange

问:
Conditionally assign ref in react
I'm working on something in react and have encountered a challenge I'm not being able to solve myself. I've searched here and others places and I found topics with similar titles but didn't have anything to do with the problem I'm having, so here we go:

So I have an array which will be mapped into React, components, normally like so:

```<code>export default ParentComponent = () => {

//bunch of stuff here and there is an array called arr

return (<>

    {arr.map((item, id) => {<ChildComponent props={item} key={id}>})}

</>)

}
</code>```

but the thing is, there's a state in the parent element which stores the id of one of the ChildComponents that is currently selected (I'm doing this by setting up a context and setting this state inside the ChildComponent), and then the problem is that I have to reference a node inside of the ChildComponent which is currently selected. I can forward a ref no problem, but I also want to assign the ref only on the currently selected ChildComponent, I would like to do this:

```<code>export default ParentComponent = () => {

//bunch of stuff here and there is an array called arr and there's a state which holds the id of a  selected ChildComponent called selectedObjectId

const selectedRef = createRef();

return (<>
    <someContextProvider>
    {arr.map((item, id) => {
       <ChildComponent
        props={item}
        key={id}
        ref={selectedObjectId == id ? selectedRef : null}
       >
    })}
   <someContextProvider />
</>)

}
</code>```

But I have tried and we can't do that. So how can dynamically assign the ref to only one particular element of an array if a certain condition is true?

答:
You can use the props spread operator {...props} to pass a conditional ref by building the props object first. E.g.

```<code>export default ParentComponent = () => {
  const selectedRef = useRef(null);

  return (
    <SomeContextProvider>
      {arr.map((item, id) => {
        const itemProps = selectedObjectId == id ? { ref: selectedRef } : {};
        return (
          <ChildComponent
            props={item}
            key={id}
            {...itemProps}
          />
        );
      })}
    <SomeContextProvider />
  )
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Conditionally assign ref in react

Body:
I'm working on something in react and have encountered a challenge I'm not being able to solve myself. I've searched here and others places and I found topics with similar titles but didn't have anything to do with the problem I'm having, so here we go:

So I have an array which will be mapped into React, components, normally like so:

export default ParentComponent = () => {

//bunch of stuff here and there is an array called arr

return (<>

    {arr.map((item, id) => {<ChildComponent props={item} key={id}>})}

</>)

}

but the thing is, there's a state in the parent element which stores the id of one of the ChildComponents that is currently selected (I'm doing this by setting up a context and setting this state inside the ChildComponent), and then the problem is that I have to reference a node inside of the ChildComponent which is currently selected. I can forward a ref no problem, but I also want to assign the ref only on the currently selected ChildComponent, I would like to do this:

export default ParentComponent = () => {

//bunch of stuff here and there is an array called arr and there's a state which holds the id of a  selected ChildComponent called selectedObjectId

const selectedRef = createRef();

return (<>
    <someContextProvider>
    {arr.map((item, id) => {
       <ChildComponent
        props={item}
        key={id}
        ref={selectedObjectId == id ? selectedRef : null}
       >
    })}
   <someContextProvider />
</>)

}

But I have tried and we can't do that. So how can dynamically assign the ref to only one particular element of an array if a certain condition is true?

Body:
You can use the props spread operator {...props} to pass a conditional ref by building the props object first. E.g.

export default ParentComponent = () => {
  const selectedRef = useRef(null);

  return (
    <SomeContextProvider>
      {arr.map((item, id) => {
        const itemProps = selectedObjectId == id ? { ref: selectedRef } : {};
        return (
          <ChildComponent
            props={item}
            key={id}
            {...itemProps}
          />
        );
      })}
    <SomeContextProvider />
  )
}


问:
"You must add a reference to assembly" compiler error in weird case
I have two applications App1 and App2. App1 added a reference to App2 and App2 added a reference to System.Drawing.

In App2 there's a function with two overloads, the first one is protected and has a parameter from System.Drawing.Bitmap and the second one is public has an integer parameter.

```<code>namespace App1Namespace
{
    class Program
    {
        static void Main(string[] args)
        {
            App2Namespace.StaticClass.Func(4);
</code>```

```<code>namespace App2Namespace
{
    public class StaticClass
    {
        protected static void Func(System.Drawing.Bitmap bitmapParam) { }
        public static void Func(int intParam) { }
</code>```

When the App1 is built, the following compile time error will be thrown:

Error 1   The type 'System.Drawing.Bitmap' is defined in an assembly
  that is not referenced. You must add a reference to assembly
  'System.Drawing, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'.

Although Func which has Bimap param is protected, the App1 needs having a reference to System.Drawing.

The questions are that why does App1 need System.Drawing? and why this error appears only when the second overload is called and doesn't appear when another overload (for example with two parameters) is called?

Note: When the first overload becomes private the error will disappear.

答: The reason is likely because you are declaring StaticClass as a regular class.  So it is possible to override the class in any referencing assemblies (thus why using protected would almost make sense for a static method).  If all the methods are truly static methods, then make the class itself static and change the scope from protected to internal or private.

ContentLicense: CC BY-SA 3.0

Body:
I have two applications App1 and App2. App1 added a reference to App2 and App2 added a reference to System.Drawing.

In App2 there's a function with two overloads, the first one is protected and has a parameter from System.Drawing.Bitmap and the second one is public has an integer parameter.

namespace App1Namespace
{
    class Program
    {
        static void Main(string[] args)
        {
            App2Namespace.StaticClass.Func(4);

namespace App2Namespace
{
    public class StaticClass
    {
        protected static void Func(System.Drawing.Bitmap bitmapParam) { }
        public static void Func(int intParam) { }

When the App1 is built, the following compile time error will be thrown:

Error 1   The type 'System.Drawing.Bitmap' is defined in an assembly
  that is not referenced. You must add a reference to assembly
  'System.Drawing, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'.

Although Func which has Bimap param is protected, the App1 needs having a reference to System.Drawing.

The questions are that why does App1 need System.Drawing? and why this error appears only when the second overload is called and doesn't appear when another overload (for example with two parameters) is called?

Note: When the first overload becomes private the error will disappear.


问:
Accessing Dictionary Elements from Pandas DataFrame
I have a column of dictionaries like this:

id                            element
 1  {'Colour': 'Grey', 'Brand': 'AB'}
 2   {'Colour': 'Blue', 'Brand': 'B'}
 3   {'Colour': 'Red', 'Brand': 'AH'}
```
<p>And I want to create new columns from those dictionaries, like this:</p>
<pre class="lang-py prettyprint-override"><code>id                            element  colour  brand
 1  {'Colour': 'Grey', 'Brand': 'AB'}    Grey     AB
 2   {'Colour': 'Blue', 'Brand': 'B'}    Blue      B
 3   {'Colour': 'Red', 'Brand': 'AH'}     Red     AH
</code>```

I have done the following but it's not working:

def whatever(row):
    tmp_d = {}
    for d in row.values:
        for k in d.keys():
            if k in tmp_d.keys():
                tmp_d[k] += 1
            else:
                tmp_d[k] = 1
    return tmp_d

new_df.colour = df.groupby('element')'element'].apply(whatever).unstack().fillna(0)
```
<p>Data:</p>
```data = {'id': [1, 2, 3],
 'element': ["{'Colour': 'Grey', 'Brand': 'AB'}",
  "{'Colour': 'Blue', 'Brand': 'B'}",
  "{'Colour': 'Red', 'Brand': 'AH'}"]}
```

答:
Here you go:

df.join(pd.json_normalize(df.element))
```
<p>Output:</p>
```   id                            element Colour Brand
0   1  {'Colour': 'Grey', 'Brand': 'AB'}   Grey    AB
1   2   {'Colour': 'Blue', 'Brand': 'B'}   Blue     B
2   3   {'Colour': 'Red', 'Brand': 'AH'}    Red    AH
```
<p>EDIT: since your <code>element</code> column is actually comprised of strings that look like dictionaries, you'll need to convert them to real dictionaries first:</p>
<pre class="lang-py prettyprint-override"><code>import ast

df["element"] = df["element"].apply(ast.literal_eval)

# Solution
new_df = df.join(pd.json_normalize(df.element))
</code>```

Then you can use my solution.

Body:
I have a column of dictionaries like this:

id                            element
 1  {'Colour': 'Grey', 'Brand': 'AB'}
 2   {'Colour': 'Blue', 'Brand': 'B'}
 3   {'Colour': 'Red', 'Brand': 'AH'}

And I want to create new columns from those dictionaries, like this:

id                            element  colour  brand
 1  {'Colour': 'Grey', 'Brand': 'AB'}    Grey     AB
 2   {'Colour': 'Blue', 'Brand': 'B'}    Blue      B
 3   {'Colour': 'Red', 'Brand': 'AH'}     Red     AH

I have done the following but it's not working:

def whatever(row):
    tmp_d = {}
    for d in row.values:
        for k in d.keys():
            if k in tmp_d.keys():
                tmp_d[k] += 1
            else:
                tmp_d[k] = 1
    return tmp_d

new_df.colour = df.groupby('element')'element'].apply(whatever).unstack().fillna(0)

Data:

data = {'id': [1, 2, 3],
 'element': ["{'Colour': 'Grey', 'Brand': 'AB'}",
  "{'Colour': 'Blue', 'Brand': 'B'}",
  "{'Colour': 'Red', 'Brand': 'AH'}"]}

Body:
Here you go:

df.join(pd.json_normalize(df.element))

Output:

   id                            element Colour Brand
0   1  {'Colour': 'Grey', 'Brand': 'AB'}   Grey    AB
1   2   {'Colour': 'Blue', 'Brand': 'B'}   Blue     B
2   3   {'Colour': 'Red', 'Brand': 'AH'}    Red    AH

EDIT: since your element column is actually comprised of strings that look like dictionaries, you'll need to convert them to real dictionaries first:

import ast

df["element"] = df["element"].apply(ast.literal_eval)

# Solution
new_df = df.join(pd.json_normalize(df.element))

Then you can use my solution.


问:
Unity Remote 5 with Android problem : CommandInvokationFailure: Unity Remote requirements check failed
I'm trying to use unity remote 5. Here is what I've done:

In File\Build Settings, Android is selected

In Edit\Project Settings\Editor, Device is set to 'Any Android Device'

In Edit\Preferences\External tools, everything in the Android section is ticked

I have installed the 'Android build support' module with the 'Android SDK & NDK Tools' + 'OpenJDK'

In android studio, in Configure\SDK manager\SDK Tools, the 'Google USB Driver' is well installed

On my phone, I have unlocked the Developer options and enabled the USB debugging

Of course, I have downloaded Unity Remote 5 on my phone and connected it to my computer using a usb cable

But now when I press play in Unity, I got an error message :

```<code>CommandInvokationFailure: Unity Remote requirements check failed
C:\Program Files\Unity\Hub\Editor\2020.2.4f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\adb.exe forward tcp:7201 tcp:7201

stderr[
error: device unauthorized.
This adb server's $ADB_VENDOR_KEYS is not set
Try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.
]
stdout[

]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.ADB.RunInternal (System.String[] command, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.ADB.Run (System.String[] command, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.ADB.Run (System.String[] command, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
</code>```

Does anyone have a solution ?

答:
Try it:

「Build Settings」 -> 「Player Settings」  ->  「Editor」  ->  「Device」  ->  「None」

Finished.

Body:
I'm trying to use unity remote 5. Here is what I've done:

In File\Build Settings, Android is selected

In Edit\Project Settings\Editor, Device is set to 'Any Android Device'

In Edit\Preferences\External tools, everything in the Android section is ticked

I have installed the 'Android build support' module with the 'Android SDK & NDK Tools' + 'OpenJDK'

In android studio, in Configure\SDK manager\SDK Tools, the 'Google USB Driver' is well installed

On my phone, I have unlocked the Developer options and enabled the USB debugging

Of course, I have downloaded Unity Remote 5 on my phone and connected it to my computer using a usb cable

But now when I press play in Unity, I got an error message :

CommandInvokationFailure: Unity Remote requirements check failed
C:\Program Files\Unity\Hub\Editor\2020.2.4f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\adb.exe forward tcp:7201 tcp:7201

stderr[
error: device unauthorized.
This adb server's $ADB_VENDOR_KEYS is not set
Try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.
]
stdout[

]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.ADB.RunInternal (System.String[] command, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.ADB.Run (System.String[] command, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)
UnityEditor.Android.ADB.Run (System.String[] command, System.String errorMsg) (at <a5c628e5460b4ef8b30249ded44d2921>:0)

Does anyone have a solution ?


问:
python method as argument
So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:

```<code>class A:

    def __init__(self):
        self.value = 'a'

    def my_method(self)
        print self.value

class B:

   def __init__(self):
       self.values = 'b'

   def my_method(self, method):
       method()

a = A()
b = B()
b.my_method(a.my_method)
</code>```

Now first this was written just to see how things work. I know I should for example check if my_method 's argument is callable. Now my question is:

How exactly is the method passed here? I mean the output I'm recieving is 'a' so I'm guessing that when a object method is passed as parameter so is the actual object ? In this case when I pass a.my_method the instance a is also passed ?

答:
When you access a.my_method Python sees that it is an attribute of the class and that A.my_method has a method __get__() so it calls A.my_method.__get__(a), that method creates a new object (the 'bound method') which contains both a reference to A.my_method and a reference to a itself. When you call the bound method it passes the call back through to the underlying method.

This happens every time you call any method whether you call it directly or, as in your code, delay the actual call until later. You can find more description of the descriptor protocol as it is known at http://docs.python.org/reference/datamodel.html#descriptors

Title: python method as argument

Body:
So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:

class A:

    def __init__(self):
        self.value = 'a'

    def my_method(self)
        print self.value

class B:

   def __init__(self):
       self.values = 'b'

   def my_method(self, method):
       method()

a = A()
b = B()
b.my_method(a.my_method)

Now first this was written just to see how things work. I know I should for example check if my_method 's argument is callable. Now my question is:

How exactly is the method passed here? I mean the output I'm recieving is 'a' so I'm guessing that when a object method is passed as parameter so is the actual object ? In this case when I pass a.my_method the instance a is also passed ?


问:
Is there any way to stop all workers in a Threadpool if any of the worker raise an Exception in python
I am writing a python script to process an operation through the ThreadPoolExecutor. My requirement is to stop script execution if the exception is raised by any of the workers. I have used the exit method but it only exit/stops the particular thread, not the whole script.

Below is the piece of code:

```<code>def create_dump():
    tenants = get_all_tenants()
    with ThreadPoolExecutor(max_workers=8) as executor:
        executor.map(process_create_dump, tenants, chunksize=1)
    file = open(dump_file_path, 'a')
    json.dump(json_dump, file, indent=1)
    file.close()

def process_create_dump(tenant):
    r_components = dict()
    print("processing.....%s" % tenant)
    try:
        add_clients(r_components, tenant)
    except Exception:
        print("Unexpected exception occurred while processing")
        exit(1)

</code>```

答:
I found a solution using threading.Event and shutdown method of ThreadPoolExecutor. Below is the code:</p>
```<code>event_object = threading.Event()

def create_dump():
    tenants = get_all_tenants()
    with ThreadPoolExecutor(max_workers=8) as executor:
        executor.submit(terminate_executor, executor)
        executor.map(process_create_dump, tenants, chunksize=1)
        executor.submit(set_event_on_success)
    file = open(dump_file_path, 'a')
    json.dump(json_dump, file, indent=1)
    file.close()

def process_create_dump(tenant):
    r_components = dict()
    print("processing.....%s" % tenant)
    try:
        add_clients(r_components, tenant)
    except Exception:
        event_object.set()

def terminate_executor(executor):
    event_object.wait()
    executor.shutdown(wait=False, cancel_futures=True)

def set_event_on_success():
    while not is_process_completed():
        pass
    event_object.set()

</code>```

Body:
I am writing a python script to process an operation through the ThreadPoolExecutor. My requirement is to stop script execution if the exception is raised by any of the workers. I have used the exit method but it only exit/stops the particular thread, not the whole script.

Below is the piece of code:

def create_dump():
    tenants = get_all_tenants()
    with ThreadPoolExecutor(max_workers=8) as executor:
        executor.map(process_create_dump, tenants, chunksize=1)
    file = open(dump_file_path, 'a')
    json.dump(json_dump, file, indent=1)
    file.close()

def process_create_dump(tenant):
    r_components = dict()
    print("processing.....%s" % tenant)
    try:
        add_clients(r_components, tenant)
    except Exception:
        print("Unexpected exception occurred while processing")
        exit(1)

Body:
I found a solution using threading.Event and shutdown method of ThreadPoolExecutor. Below is the code:

event_object = threading.Event()

def create_dump():
    tenants = get_all_tenants()
    with ThreadPoolExecutor(max_workers=8) as executor:
        executor.submit(terminate_executor, executor)
        executor.map(process_create_dump, tenants, chunksize=1)
        executor.submit(set_event_on_success)
    file = open(dump_file_path, 'a')
    json.dump(json_dump, file, indent=1)
    file.close()

def process_create_dump(tenant):
    r_components = dict()
    print("processing.....%s" % tenant)
    try:
        add_clients(r_components, tenant)
    except Exception:
        event_object.set()

def terminate_executor(executor):
    event_object.wait()
    executor.shutdown(wait=False, cancel_futures=True)

def set_event_on_success():
    while not is_process_completed():
        pass
    event_object.set()


问:
javascript random numbers generator
I'm trying to generate 500 random numbers between 1 and 50 and then divide them to my 5 ranges and then print the percentage of each range in the form of stars.
I have written the below piece of code but it only generates 1 number instead of 500.
can anyone help me fix this problem?
I am new to javascript and any help or advice would be appreciated.
Thank you.</p>
```<code>    let temp = Math.floor((Math.random() * 50) + 1);
    let bin1 = 0;
    let bin2 = 0;
    let bin3 = 0;
    let bin4 = 0;
    let bin5 = 0;

    if(temp >= 1 && temp < 11){
    bin1++;
    document.write(bin1 + " numbers are randomly generated between 01 - 10.<br>");
    }
        else if(temp >= 11 && temp < 21){
    bin2++;
    document.write(bin2 + " numbers are randomly generated between 11 - 20.<br>");
    }
        else if(temp >= 21 && temp < 31){
    bin3++;
    document.write(bin3 + " numbers are randomly generated between 21 - 30.<br>");
    }
        else if(temp >= 31 && temp < 41){
     bin4++;
    document.write(bin4 + " numbers are randomly generated between 31 - 40.<br>");
    }
        else if(temp >= 41 && temp < 51){
     bin5++;
     document.write(bin5 + " numbers are randomly generated between 41 - 50.<br>");
    }

    document.write("Histogram of stars as a percentage of the number of values are displayed below: <br>");

    for(let x = 0; x < bin1*100/500; x++){
    document.write("01 - 10: ");
    document.write("*");
    }
    for(let x = 0; x < bin2*100/500; x++){
    document.write("11 - 20: ");
    document.write("*");
    }
    for(let x = 0; x < bin3*100/500; x++){
    document.write("21 - 30: ");
    document.write("*");
    }
    for(let x = 0; x < bin4*100/500; x++){
    document.write("31 - 40: ");
    document.write("*");
    }
    for(let x = 0; x < bin5*100/500; x++){
    document.write("41 - 50: ");
    document.write("*");
    }
</code>```

答:
Looks like you have to wrap in a for-loop.

Trying to do what you are looking for, see the example below:

function generateRandomNumber() {
  return Math.floor(Math.random() * 50);
}

const ranges = {
  "1-11": [],
  "11-21": [],  // instead of array we can have value 0, and increment that incase dont want to track the values in future
  "21-31": [],
  "31-41": [],
  "41-51": [],
}

function updateRanges(num) {
  if(num >= 41 && num < 51) ranges["41-51"].push(num);
  else if(num >= 31 && num < 41) ranges["31-41"].push(num);
  else if(num >= 21 && num < 31) ranges["21-31"].push(num);
  else if(num >= 11 && num < 21) ranges["11-21"].push(num);
  else ranges["1-11"].push(num);
}

for (let i = 0; i < 500; i++) {
  const random =  generateRandomNumber();
  updateRanges(random);
}

const output =  document.getElementById("output");
Object.keys(ranges).forEach(key => {
  output.innerHTML = output.innerHTML +

  `<p>numbers are randomly generated between ${key} : ${ranges[key].length}</p>`
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output"></div></code>```

Title: javascript random numbers generator

Body:
I'm trying to generate 500 random numbers between 1 and 50 and then divide them to my 5 ranges and then print the percentage of each range in the form of stars.
I have written the below piece of code but it only generates 1 number instead of 500.
can anyone help me fix this problem?
I am new to javascript and any help or advice would be appreciated.
Thank you.

    let temp = Math.floor((Math.random() * 50) + 1);
    let bin1 = 0;
    let bin2 = 0;
    let bin3 = 0;
    let bin4 = 0;
    let bin5 = 0;

    if(temp >= 1 && temp < 11){
    bin1++;
    document.write(bin1 + " numbers are randomly generated between 01 - 10.
");
    }
        else if(temp >= 11 && temp < 21){
    bin2++;
    document.write(bin2 + " numbers are randomly generated between 11 - 20.
");
    }
        else if(temp >= 21 && temp < 31){
    bin3++;
    document.write(bin3 + " numbers are randomly generated between 21 - 30.
");
    }
        else if(temp >= 31 && temp < 41){
     bin4++;
    document.write(bin4 + " numbers are randomly generated between 31 - 40.
");
    }
        else if(temp >= 41 && temp < 51){
     bin5++;
     document.write(bin5 + " numbers are randomly generated between 41 - 50.
");
    }

    document.write("Histogram of stars as a percentage of the number of values are displayed below:
");

    for(let x = 0; x < bin1*100/500; x++){
    document.write("01 - 10: ");
    document.write("*");
    }
    for(let x = 0; x < bin2*100/500; x++){
    document.write("11 - 20: ");
    document.write("*");
    }
    for(let x = 0; x < bin3*100/500; x++){
    document.write("21 - 30: ");
    document.write("*");
    }
    for(let x = 0; x < bin4*100/500; x++){
    document.write("31 - 40: ");
    document.write("*");
    }
    for(let x = 0; x < bin5*100/500; x++){
    document.write("41 - 50: ");
    document.write("*");
    }

Body:
Looks like you have to wrap in a for-loop.

Trying to do what you are looking for, see the example below:

function generateRandomNumber() {
  return Math.floor(Math.random() * 50);
}

const ranges = {
  "1-11": [],
  "11-21": [],  // instead of array we can have value 0, and increment that incase dont want to track the values in future
  "21-31": [],
  "31-41": [],
  "41-51": [],
}

function updateRanges(num) {
  if(num >= 41 && num < 51) ranges["41-51"].push(num);
  else if(num >= 31 && num < 41) ranges["31-41"].push(num);
  else if(num >= 21 && num < 31) ranges["21-31"].push(num);
  else if(num >= 11 && num < 21) ranges["11-21"].push(num);
  else ranges["1-11"].push(num);
}

for (let i = 0; i < 500; i++) {
  const random =  generateRandomNumber();
  updateRanges(random);
}

const output =  document.getElementById("output");
Object.keys(ranges).forEach(key => {
  output.innerHTML = output.innerHTML +

  `<p>numbers are randomly generated between ${key} : ${ranges[key].length}</p>`
})

<div id="output"></div>


问:
How to get the value of a node in a list of XElements
I need the string "duplicate-result" but I keep getting a null reference error on the line that reads that element. I have the result name, the template and the name, but I can't get the reason. In the current version subErr throws a "System.NullReferenceException." I tried getting the value of the node but that was an invalid cast. Below is a section of the repeated XML and my little method to read the information. I have looked here and there are no similar examples. I cannot change the XML output.</p>
```<code>       <result succeed="No" template="text" name="Frame Number" testid="123456">
            <errors>
                <error name="duplicate-result"/>
            </errors>
        </result>

    For Each err As XElement In errList
        resultName = err.Attribute("name").Value
        resultTemplate = err.Attribute("template").Value
        errString = "Upload Error: " & resultTemplate & ", " & resultName & " failed. "
        For Each subErr As XElement In err.Elements("errors")
            errString &= subErr.Element("name").Value & ","
        Next
        errString = Left(errString, Len(errString) - 1)
    Next
</code>```

答:
It's an attribute, not an Element. try in the for loop.</p>
```<code>errString &= subErr.Attribute("name").Value & ","
</code>```

Body:
I need the string "duplicate-result" but I keep getting a null reference error on the line that reads that element. I have the result name, the template and the name, but I can't get the reason. In the current version subErr throws a "System.NullReferenceException." I tried getting the value of the node but that was an invalid cast. Below is a section of the repeated XML and my little method to read the information. I have looked here and there are no similar examples. I cannot change the XML output.

       <result succeed="No" template="text" name="Frame Number" testid="123456">
            <errors>
                <error name="duplicate-result"/>
            </errors>
        </result>

    For Each err As XElement In errList
        resultName = err.Attribute("name").Value
        resultTemplate = err.Attribute("template").Value
        errString = "Upload Error: " & resultTemplate & ", " & resultName & " failed. "
        For Each subErr As XElement In err.Elements("errors")
            errString &= subErr.Element("name").Value & ","
        Next
        errString = Left(errString, Len(errString) - 1)
    Next

Body:
It's an attribute, not an Element. try in the for loop.

errString &= subErr.Attribute("name").Value & ","


问:
How to create a 32-bit shared-library on a 64-bit platform with autotools
I'm using autotools to build my system, which consists primarily of a library. On 64-bit Red Hat platforms, I need to be able to produce a library capable of working on 32-bit Red Hat platforms.

When I add -m32 to the compile lines everything works fine to produce a static (.a) library, but as soon as I try to create a shared-library, I get error like this:

```<code>/usr/bin/ld: warning: i386:x86-64 architecture of input file `/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../lib64/crti.o' is incompatible with i386 output
/usr/bin/ld: warning: i386:x86-64 architecture of input file `/usr/lib/gcc/x86_64-redhat-linux/4.1.2/crtbeginS.o' is incompatible with i386 output
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/crtbeginS.o: In function `__do_global_dtors_aux':
crtstuff.c:(.text+0x29): undefined reference to `__DTOR_END__'
collect2: ld returned 1 exit status'
</code>```

I can see the problem is that it's including 64-bit object files out of /usr/lib64 instead of the correct 32-bit ones out of /usr/lib (they're there alright), but I can't figure out how to fix it.

答:
Would you try:

```<code>CFLAGS=-m32 -Wl,-m32
CXXFLAGS=-m32 -Wl,-m32
LDFLAGS=-m32
</code>```

in your makefile, since some scripts try linking using gcc or g++ instead of ld as we expect?

Update: In case you manually modifying every gcc/g++ call, just try use -m32 -Wl,-m32 instead of simple -m32 as additional option.

Body:
I'm using autotools to build my system, which consists primarily of a library. On 64-bit Red Hat platforms, I need to be able to produce a library capable of working on 32-bit Red Hat platforms.

When I add -m32 to the compile lines everything works fine to produce a static (.a) library, but as soon as I try to create a shared-library, I get error like this:

/usr/bin/ld: warning: i386:x86-64 architecture of input file `/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../lib64/crti.o' is incompatible with i386 output
/usr/bin/ld: warning: i386:x86-64 architecture of input file `/usr/lib/gcc/x86_64-redhat-linux/4.1.2/crtbeginS.o' is incompatible with i386 output
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/crtbeginS.o: In function `__do_global_dtors_aux':
crtstuff.c:(.text+0x29): undefined reference to `__DTOR_END__'
collect2: ld returned 1 exit status'

I can see the problem is that it's including 64-bit object files out of /usr/lib64 instead of the correct 32-bit ones out of /usr/lib (they're there alright), but I can't figure out how to fix it.

Body:
Would you try:

CFLAGS=-m32 -Wl,-m32
CXXFLAGS=-m32 -Wl,-m32
LDFLAGS=-m32

in your makefile, since some scripts try linking using gcc or g++ instead of ld as we expect?

Update: In case you manually modifying every gcc/g++ call, just try use -m32 -Wl,-m32 instead of simple -m32 as additional option.


问:
Bash: alias in bash -c
To be short:
How could I execute a

bash -c "set -x; alias ll='ls -l -h'; ll"
```
<p>?</p>
<p>The output is</p>
```+ alias 'll=ls -l -h'
+ ll
bash: ll: command not found
```

Seems bash will add a single quote before my 'll'...

Thanks in advance!

答:
There are two things preventing the alias ll from being expanded:

Aliases are only expanded in an interactive shell or if you use shopt -s expand_aliases.

Aliases are expanded (if they are expanded) when the line containing the command is read, not when it is executed, so only aliases defined on previous lines can be expanded. (Also, bash reads an entire compound command before executing it, so you can't define an alias and use it in the same compound command. That doesn't apply here but it might be useful to know.)

So you need to both mark the bash as interactive and introduce a newline character into the command line. You could, for example, do this:

bash -ic "alias ll='ls -l -h'"$'\n'"ll"
```
<p>But it would be a lot easier to use a function:</p>
<pre class="lang-sh prettyprint-override"><code>bash -c 'll() { ls -l -h "$@"; }; ll'
</code>```

All of that is documented in the Bash manual, §6.6 Aliases:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt…

…Bash always reads at least one complete line of input, and all lines that make up a compound command, before executing any of the commands on that line or the compound command. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias.

That section ends with the advice to use functions instead:

For almost every purpose, shell functions are preferred over aliases.

Title: Bash: alias in bash -c

Body:
To be short:
How could I execute a

bash -c "set -x; alias ll='ls -l -h'; ll"

?

The output is

+ alias 'll=ls -l -h'
+ ll
bash: ll: command not found

Seems bash will add a single quote before my 'll'...

Thanks in advance!

Body:
There are two things preventing the alias ll from being expanded:

Aliases are only expanded in an interactive shell or if you use shopt -s expand_aliases.

Aliases are expanded (if they are expanded) when the line containing the command is read, not when it is executed, so only aliases defined on previous lines can be expanded. (Also, bash reads an entire compound command before executing it, so you can't define an alias and use it in the same compound command. That doesn't apply here but it might be useful to know.)

So you need to both mark the bash as interactive and introduce a newline character into the command line. You could, for example, do this:

bash -ic "alias ll='ls -l -h'"$'\n'"ll"

But it would be a lot easier to use a function:

bash -c 'll() { ls -l -h "$@"; }; ll'

All of that is documented in the Bash manual, §6.6 Aliases:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt…

…Bash always reads at least one complete line of input, and all lines that make up a compound command, before executing any of the commands on that line or the compound command. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias.

That section ends with the advice to use functions instead:

For almost every purpose, shell functions are preferred over aliases.


问:
I am not able to achieve the blur effect in swift
I am not able to achieve the appropriate blur effect as per design in swift.

My code to add blur effect -

```<code>func addBlur() {
    let blurEffect = UIBlurEffect(style: .regular)
    let blurredEffectView = UIVisualEffectView(effect: blurEffect)
    blurredEffectView.alpha = 0.75
    imgView.alpha = 0.75
    blurredEffectView.frame = imgView.bounds
    imgView.subviews.forEach {
        $0.removeFromSuperview()
    }
    imgView.addSubview(blurredEffectView)
    imgView.bringSubviewToFront(blurredEffectView)
}
</code>```

Code to remove blur effect. -

```<code>func removeBlur() {
    for subview in imgView.subviews {
        if subview is UIVisualEffectView {
            imgView.alpha = 1
            subview.removeFromSuperview()
        }
    }
}
</code>```

Below is the design -

Desin blur effect

The one I achieve by my code -

Achieved screenshot

答:
@shawn-frank is right and I want to share one cool article about blur, in this article there is third (alternative) way with Metal.

Different ways to creat blur

Can not comment that why added answer

Body:
I am not able to achieve the appropriate blur effect as per design in swift.

My code to add blur effect -

func addBlur() {
    let blurEffect = UIBlurEffect(style: .regular)
    let blurredEffectView = UIVisualEffectView(effect: blurEffect)
    blurredEffectView.alpha = 0.75
    imgView.alpha = 0.75
    blurredEffectView.frame = imgView.bounds
    imgView.subviews.forEach {
        $0.removeFromSuperview()
    }
    imgView.addSubview(blurredEffectView)
    imgView.bringSubviewToFront(blurredEffectView)
}

Code to remove blur effect. -

func removeBlur() {
    for subview in imgView.subviews {
        if subview is UIVisualEffectView {
            imgView.alpha = 1
            subview.removeFromSuperview()
        }
    }
}

Below is the design -

Desin blur effect

The one I achieve by my code -

Achieved screenshot


问:
Which Angular 12 version is the most stable and the most installed currently?
I am trying to find out which angular 12 version is the most stable and has less number of bug  and also compatible with angular fire ^6.1.5</p>

答: I'm using 12.2.9 from quite log, have found it to be the most stable one. you can also go with the same.</p>


问:
How to query in mysql when involving more than one table?
Here's my problem. I've two tables in the database (A and B). Table A consists of the primary ID (one) while table B consists of the status (Ongoing, Completed) of the ID in table A (status may be more than one). May I know how to get the data only when ALL the status of the ID(ORDER) is completed? I've included an image for further understanding.

Thank you for your time and help.

```<code>Table A
ID     NumberOfOrder
ABC1   2

Table B
ID     A_ID     Status
BEF1   ABC1     ONGOING
BEF2   ABC2     COMPLETED
</code>```

答:
Try this query:</p>
```<code>SELECT A.ID, A.'NUMBER OF ORDER', B.STATUS
FROM B
LEFT JOIN A ON B.A_ID = A.ID
WHERE B.STATUS = 'COMPLETED'
</code>```

Body:
Here's my problem. I've two tables in the database (A and B). Table A consists of the primary ID (one) while table B consists of the status (Ongoing, Completed) of the ID in table A (status may be more than one). May I know how to get the data only when ALL the status of the ID(ORDER) is completed? I've included an image for further understanding.

Thank you for your time and help.

Table A
ID     NumberOfOrder
ABC1   2

Table B
ID     A_ID     Status
BEF1   ABC1     ONGOING
BEF2   ABC2     COMPLETED

Body:
Try this query:

SELECT A.ID, A.'NUMBER OF ORDER', B.STATUS
FROM B
LEFT JOIN A ON B.A_ID = A.ID
WHERE B.STATUS = 'COMPLETED'


问:
Thread that calls function in a HTTP request throws RuntimeError: Working outside of application context
I have route within my Flask application that process a POST request and then sends an email to the client using the Flask-Mail library. I have the route returning a response to the client from checking the database before sending out an email. The email is sent from an individual thread, but I am getting this error thrown when trying to send out the email: RuntimeError: Working outside of application context.. I know that it is being thrown because the request was destroyed before the thread could process its tasks. However, I am not sure how exactly I should fix this error, especially when the route gets processed by a Blueprint.

routes.py:

```<code>from flask import request, Blueprint, redirect, render_template
from flask_app import mail, db
from flask_app.users.forms import Form
from flask_app.models import User
from flask_mail import Message
from threading import Thread
import os, re

users = Blueprint("users", __name__)

@users.route("/newsletter-subscribe", methods=["GET", "POST"])
def newsletter_subscribe():
    form = Form()
    if form.validate_on_submit():
        user = User(name=form.name.data, email=form.email.data)
        db.session.add(user)
        db.session.commit()
        thread_a = Compute(user, request.host_url)
        thread_a.start()

        return "Success"
    return "Failure"

class Compute(Thread):
    def __init__(self, user, host_url):
        Thread.__init__(self)
        self.host_url = host_url
        self.user = user

    def run(self):
        send_welcome_email(self.user, self.host_url)
        print("Finished")

def send_email(user, host_url):
    with mail.connect() as con:
        html = render_template("email.html", name=user.name, host_url=host_url)
        subject = ""
        msg = Message(
            subject=subject,
            recipients=[user.email],
            html=html
        )
        con.send(msg)
</code>```

答:
Seeing that this question is over a year old, you may have solved this already, but I'll post this here for in case anyone else comes across it later.

I think the issue you're having is the same I had, where the send function needs the current flask app context.

You can try this within your send_email function:

Instead of:

```<code>con.send(msg)
</code>```

Replace it with:

```<code>with app.app_context():
    con.send(msg)
</code>```

Just also make sure that you include your app in your includes section.
Change this:

```<code>from flask_app import mail, db
</code>```

To this:

```<code>from flask_app import app, mail, db
</code>```

That should resolve the RuntimeError: Working outside of application context. issue.

Body:
I have route within my Flask application that process a POST request and then sends an email to the client using the Flask-Mail library. I have the route returning a response to the client from checking the database before sending out an email. The email is sent from an individual thread, but I am getting this error thrown when trying to send out the email: RuntimeError: Working outside of application context.. I know that it is being thrown because the request was destroyed before the thread could process its tasks. However, I am not sure how exactly I should fix this error, especially when the route gets processed by a Blueprint.

routes.py:

from flask import request, Blueprint, redirect, render_template
from flask_app import mail, db
from flask_app.users.forms import Form
from flask_app.models import User
from flask_mail import Message
from threading import Thread
import os, re

users = Blueprint("users", __name__)

@users.route("/newsletter-subscribe", methods=["GET", "POST"])
def newsletter_subscribe():
    form = Form()
    if form.validate_on_submit():
        user = User(name=form.name.data, email=form.email.data)
        db.session.add(user)
        db.session.commit()
        thread_a = Compute(user, request.host_url)
        thread_a.start()

        return "Success"
    return "Failure"

class Compute(Thread):
    def __init__(self, user, host_url):
        Thread.__init__(self)
        self.host_url = host_url
        self.user = user

    def run(self):
        send_welcome_email(self.user, self.host_url)
        print("Finished")

def send_email(user, host_url):
    with mail.connect() as con:
        html = render_template("email.html", name=user.name, host_url=host_url)
        subject = ""
        msg = Message(
            subject=subject,
            recipients=[user.email],
            html=html
        )
        con.send(msg)

Body:
Seeing that this question is over a year old, you may have solved this already, but I'll post this here for in case anyone else comes across it later.

I think the issue you're having is the same I had, where the send function needs the current flask app context.

You can try this within your send_email function:

Instead of:

con.send(msg)

Replace it with:

with app.app_context():
    con.send(msg)

Just also make sure that you include your app in your includes section.
Change this:

from flask_app import mail, db

To this:

from flask_app import app, mail, db

That should resolve the RuntimeError: Working outside of application context. issue.


答:
To be short:You can't.

According to man bash:

The rules concerning the definition and use of aliases are somewhat
confusing.  Bash always reads at least one complete line of input, and
all lines that make up a compound command, before executing any of the
commands on that line or the compound command.  Aliases are expanded
when a command is read,  not  when  it  is  executed. Therefore,  an
alias  definition appearing on the same line as another command does
not take effect until the next line of input is read.  The commands
following the alias definition on that line are not affected by  the
new  alias.  This behavior is also an issue when functions are
executed.  Aliases are expanded when a function definition is read,
not when the function is executed, because a function definition is
itself a command.   As a  consequence,  aliases defined in a function
are not available until after that function is executed.  To be safe,
always put alias definitions on a separate line, and do not use alias
in compound commands.

For almost every purpose, aliases are superseded by shell functions.

Use functions instead:

```<code>bash -c "ll(){ ls -l -h; }; ll"
</code>```

Title: Bash: alias in bash -c

Body:
To be short:You can't.

According to man bash:

The rules concerning the definition and use of aliases are somewhat
confusing.  Bash always reads at least one complete line of input, and
all lines that make up a compound command, before executing any of the
commands on that line or the compound command.  Aliases are expanded
when a command is read,  not  when  it  is  executed. Therefore,  an
alias  definition appearing on the same line as another command does
not take effect until the next line of input is read.  The commands
following the alias definition on that line are not affected by  the
new  alias.  This behavior is also an issue when functions are
executed.  Aliases are expanded when a function definition is read,
not when the function is executed, because a function definition is
itself a command.   As a  consequence,  aliases defined in a function
are not available until after that function is executed.  To be safe,
always put alias definitions on a separate line, and do not use alias
in compound commands.

For almost every purpose, aliases are superseded by shell functions.

Use functions instead:

bash -c "ll(){ ls -l -h; }; ll"


问:
How to add a condition to a for loop in Kotlin?
I know that in Java, it is possible to do the following:

```<code>boolean condition = true;

for(int i=0; i<array.length && condition; i++){

}
</code>```

If the condition is false, the for loop stops,
but, how to do the same in Kotlin?

答:
You can also use the below approach for the conditional for loop.

```<code>(0..array.length).takeWhile {
    condition
}.forEach {
    // do something with `it (index)`
}
</code>```

Body:
I know that in Java, it is possible to do the following:

boolean condition = true;

for(int i=0; i<array.length && condition; i++){

}

If the condition is false, the for loop stops,
but, how to do the same in Kotlin?

Body:
You can also use the below approach for the conditional for loop.

(0..array.length).takeWhile {
    condition
}.forEach {
    // do something with `it (index)`
}


问:
How can use elements "getElementById("site") and getElementById("button")" more than one for lists?
I tried to use more than one "List" with changing names of getElementById("site") and getElementById("button") but it dosent work well.

The "submit" button dosnt work correctly
I want each button do separately and open link from own list.

This example for 3 list, but I have more than 10 lists with same name but different addresses.

HTML code:

```<code><html>

<body>
    <form method="get">
        <label for="Links">Choose a Site:</label>
        <select id="site01" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button01">Submit</button>
    <script src="script1.js"></script>
    <form method="get">
        <label for="Links">Choose a Site:</label>
        <select id="site02" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button02">Submit</button>
    <script src="script1.js"></script>
    <form method="get">
        <label for="Links">Choose a Site:</label>
        <select id="site03" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button03">Submit</button>
    <script src="script1.js"></script>
</body>

</html>
</code>```

script1.js code

```<code>var select = document.getElementById('site01');

document.getElementById("button01").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google01.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo01.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn01.com', '_blank');
    }
};

var select = document.getElementById('site02');

document.getElementById("button02").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google02.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo02.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn02.com', '_blank');
    }
};

var select = document.getElementById('site03');

document.getElementById("button03").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google03.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo03.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn03.com', '_blank');
    }
};
</code>```

whats wrong ?

答:
The issue with the code is that, you are keep on updating value for select as

```<code>var select = document.getElementById('site01'); // First
var select = document.getElementById('site02'); // Second
var select = document.getElementById('site03'); // Third
</code>```

Your select variable is declared in global scope, so updating one value will reflect all elements.

Fix to your issue

Move the declaration of select inside the the click listner. This will be redeclared each tim when user clicks the button and hence, the value will be taken correctly.

Working Fiddle

document.getElementById("button01").onclick = function () {
  const select = document.getElementById('site01');
  const value = select.value
  if (value == "Google") {
    window.open('https://www.google01.com', '_blank');
  }
  else if (value == "Yahoo") {
    window.open('https://www.yahoo01.com', '_blank');
  }
  else if (value == "MSN") {
    window.open('https://www.msn01.com', '_blank');
  }
};

document.getElementById("button02").onclick = function () {
  const select = document.getElementById('site02');
  const value = select.value
  if (value == "Google") {
    window.open('https://www.google02.com', '_blank');
  }
  else if (value == "Yahoo") {
    window.open('https://www.yahoo02.com', '_blank');
  }
  else if (value == "MSN") {
    window.open('https://www.msn02.com', '_blank');
  }
};

document.getElementById("button03").onclick = function () {
  const select = document.getElementById('site03');
  const value = select.value
  if (value == "Google") {
    window.open('https://www.google03.com', '_blank');
  }
  else if (value == "Yahoo") {
    window.open('https://www.yahoo03.com', '_blank');
  }
  else if (value == "MSN") {
    window.open('https://www.msn03.com', '_blank');
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site01" name="site" data-node="01">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button01">Submit</button>
<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site02" name="site" data-node="02">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button02">Submit</button>
<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site03" name="site" data-node="03">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button03">Submit</button></code>```

What happens with this is, the value for select will be holding the last node finally, that is the element with id site03. So your select will be holding the value of the third node always. So even if you click the first button or the second button, it will take the value from the third node.

Also donot call  multiple time from template. This should be done only once, best to keep at the bottom of your template section.

Better Approach

Better approach is to, select all your buttons using document.querySelectorAll("[type='button']") and add a click event listner to that. Inside the click event listner, select the targeted select node by accessing the select using e.currentTarget.previousElementSibling.querySelector('select'). You can see the code comment how this selector will point to the required target.

To make the urls dyynamic, you can have some custom data attributes in the select element and check the value for the corresponding data attributes inside the change event. I have added a custom data-node to each select and fetched the value from the change event using select.getAttribute('data-node')

Working Code

document.querySelectorAll("[type='button']").forEach((node) => {
  node.onclick = function (e) {
    const select = e.currentTarget.previousElementSibling.querySelector('select');
    // e.currentTarget => clicked button
    // e.currentTarget.previousElementSibling = Form ust above the button
    // e.currentTarget.previousElementSibling.querySelector('select') = Select inside the form
    const value = select.value
    const nodeAppender = select.getAttribute('data-node');
    console.log(value);
    if (value == "Google") {
      window.open(`https://www.google${nodeAppender}.com`, '_blank');
    }
    else if (value == "Yahoo") {
      window.open(`https://www.yahoo${nodeAppender}.com`, '_blank');
    }
    else if (value == "MSN") {
      window.open(`https://www.msn${nodeAppender}.com`, '_blank');
    }
  };
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site01" name="site" data-node="01">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button01">Submit</button>
<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site02" name="site" data-node="02">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button02">Submit</button>
<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site03" name="site" data-node="03">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button03">Submit</button></code>```

Body:
I tried to use more than one "List" with changing names of getElementById("site") and getElementById("button") but it dosent work well.

The "submit" button dosnt work correctly
I want each button do separately and open link from own list.

This example for 3 list, but I have more than 10 lists with same name but different addresses.

HTML code:

    <form method="get">
        Choose a Site:
        <select id="site01" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button01">Submit</button>

    <form method="get">
        Choose a Site:
        <select id="site02" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button02">Submit</button>

    <form method="get">
        Choose a Site:
        <select id="site03" name="site">
            <option value="Google">Google</option>
            <option value="Yahoo">Yahoo</option>
            <option value="MSN">MSN</option>
        </select>
    </form>
    <button type="button" id="button03">Submit</button>

script1.js code

var select = document.getElementById('site01');

document.getElementById("button01").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google01.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo01.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn01.com', '_blank');
    }
};

var select = document.getElementById('site02');

document.getElementById("button02").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google02.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo02.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn02.com', '_blank');
    }
};

var select = document.getElementById('site03');

document.getElementById("button03").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.open('https://www.google03.com', '_blank');
    }
    else if (value == "Yahoo")
    {
        window.open('https://www.yahoo03.com', '_blank');
    }
    else if (value == "MSN")
    {
        window.open('https://www.msn03.com', '_blank');
    }
};

whats wrong ?

Body:
The issue with the code is that, you are keep on updating value for select as

var select = document.getElementById('site01'); // First
var select = document.getElementById('site02'); // Second
var select = document.getElementById('site03'); // Third

Your select variable is declared in global scope, so updating one value will reflect all elements.

Fix to your issue

Move the declaration of select inside the the click listner. This will be redeclared each tim when user clicks the button and hence, the value will be taken correctly.

Working Fiddle

document.getElementById("button01").onclick = function () {
  const select = document.getElementById('site01');
  const value = select.value
  if (value == "Google") {
    window.open('https://www.google01.com', '_blank');
  }
  else if (value == "Yahoo") {
    window.open('https://www.yahoo01.com', '_blank');
  }
  else if (value == "MSN") {
    window.open('https://www.msn01.com', '_blank');
  }
};

document.getElementById("button02").onclick = function () {
  const select = document.getElementById('site02');
  const value = select.value
  if (value == "Google") {
    window.open('https://www.google02.com', '_blank');
  }
  else if (value == "Yahoo") {
    window.open('https://www.yahoo02.com', '_blank');
  }
  else if (value == "MSN") {
    window.open('https://www.msn02.com', '_blank');
  }
};

document.getElementById("button03").onclick = function () {
  const select = document.getElementById('site03');
  const value = select.value
  if (value == "Google") {
    window.open('https://www.google03.com', '_blank');
  }
  else if (value == "Yahoo") {
    window.open('https://www.yahoo03.com', '_blank');
  }
  else if (value == "MSN") {
    window.open('https://www.msn03.com', '_blank');
  }
};

<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site01" name="site" data-node="01">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button01">Submit</button>
<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site02" name="site" data-node="02">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button02">Submit</button>
<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site03" name="site" data-node="03">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button03">Submit</button>

What happens with this is, the value for select will be holding the last node finally, that is the element with id site03. So your select will be holding the value of the third node always. So even if you click the first button or the second button, it will take the value from the third node.

Also donot call <script src="script1.js"></script> multiple time from template. This should be done only once, best to keep at the bottom of your template section.

Better Approach

Better approach is to, select all your buttons using document.querySelectorAll("[type='button']") and add a click event listner to that. Inside the click event listner, select the targeted select node by accessing the select using e.currentTarget.previousElementSibling.querySelector('select'). You can see the code comment how this selector will point to the required target.

To make the urls dyynamic, you can have some custom data attributes in the select element and check the value for the corresponding data attributes inside the change event. I have added a custom data-node to each select and fetched the value from the change event using select.getAttribute('data-node')

Working Code

document.querySelectorAll("[type='button']").forEach((node) => {
  node.onclick = function (e) {
    const select = e.currentTarget.previousElementSibling.querySelector('select');
    // e.currentTarget => clicked button
    // e.currentTarget.previousElementSibling = Form ust above the button
    // e.currentTarget.previousElementSibling.querySelector('select') = Select inside the form
    const value = select.value
    const nodeAppender = select.getAttribute('data-node');
    console.log(value);
    if (value == "Google") {
      window.open(`https://www.google${nodeAppender}.com`, '_blank');
    }
    else if (value == "Yahoo") {
      window.open(`https://www.yahoo${nodeAppender}.com`, '_blank');
    }
    else if (value == "MSN") {
      window.open(`https://www.msn${nodeAppender}.com`, '_blank');
    }
  };
})

<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site01" name="site" data-node="01">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button01">Submit</button>
<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site02" name="site" data-node="02">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button02">Submit</button>
<form method="get">
  <label for="Links">Choose a Site:</label>
  <select id="site03" name="site" data-node="03">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button03">Submit</button>


问:
Understanding TSQL Coalesce function
I am trying to select all 12 months / year.  And I thought following TSQL code would do this.  However, this does not include all months like I want.  What is the cause of this?  This is modified code:

```<code>DECLARE @END_YEAR VARCHAR(10)
DECLARE @END_MONTH VARCHAR(10)

SET @END_YEAR = '2010'
SET @END_MONTH = '10'

DECLARE @TheMonthLastDate DATETIME
DECLARE @TempDate DATETIME
SET @TempDate = '2010-11-01 00:00:00.000'
SET @TheMonthLastDate = '2010-11-01 00:00:00.000'

;with months
as
(
select dateadd(month, -1, dateadd(day, datediff(day, 0, @TempDate), 0)) as m
union all
select dateadd(month, -1, m)
from months
where   m > dateadd(month, -12, @TempDate)
)
,yourTable(DateOpened, DateClosed)
as
(select TSK_START_DATE, BTK_CLOSED_DATE
FROM [PROC].ALL_AUDIT
WHERE
(BTK_CLOSED_DATE < @TheMonthLastDate OR
TSK_START_DATE < @TheMonthLastDate
)
)
select      yt.DateClosed 'r2', m.m 'r3',
        month(coalesce(yt.DateClosed, m.m)) as 'MonthClosed',
        year(coalesce(yt.DateClosed, m.m)) as 'YearClosed'
from    months m
left join yourTable yt
    on
    (  datepart(year, yt.DateClosed) = DATEPART(year, m.m)
    and datepart(month, yt.DateClosed) = DATEPART(month, m.m)
    or
      datepart(year, yt.DateOpened) = DATEPART(year, m.m)
    and datepart(month, yt.DateOpened) = DATEPART(month, m.m)
    )
AND year(coalesce(yt.DateClosed, m.m)) = 2010
order by yt.DateClosed
</code>```

So above query does not return all months.  But if I change above WHERE lines to:

```<code>FROM [PROC].ALL_AUDIT
    WHERE
BTK_CLOSED_DATE < @TheMonthLastDate
</code>```

then this query does return all 12 months.  How can this be?

Output that I want and that I see when WHERE is BTK_CLOSED_DATE < @TheMonthLastDate:

```<code>r2  r3  MonthClosed YearClosed
NULL    2010-06-01 00:00:00.000 6   2010
NULL    2009-11-01 00:00:00.000 11  2009
2010-01-06 20:02:19.127 2010-01-01 00:00:00.000 1   2010
2010-01-27 23:13:45.570 2010-01-01 00:00:00.000 1   2010
2010-02-15 14:49:14.427 2010-02-01 00:00:00.000 2   2010
2010-02-15 14:49:14.427 2009-12-01 00:00:00.000 2   2010
</code>```

But if I instead use WHERE:
(BTK_CLOSED_DATE < @TheMonthLastDate OR
    TSK_START_DATE < @TheMonthLastDate
    )

then I see:

```<code>r2  r3  MonthClosed YearClosed
NULL    2010-10-01 00:00:00.000 10  2010
NULL    2010-09-01 00:00:00.000 9   2010
NULL    2010-09-01 00:00:00.000 9   2010
NULL    2010-08-01 00:00:00.000 8   2010
NULL    2010-08-01 00:00:00.000 8   2010
...
</code>```

So notice that in first result I see NULL for June 2010, which is what I want.
I think the problem has something to do with the fact that my data contains 2009-2011 data, but I only compare months and not years.  How would I add in this additional logic?

答:
The only place where you are reducing the data is with the WHERE clause you have already identified.  Therefore, the reason you are not getting all the months you expect is down to the column TSK_START_DATE not being less than @TheMonthLastDate for all months.

To prove this hypothesis, run the following section of your query (I have commented out part of the where clause and removed everything under 'yourTable' cte).  The results should show you what is being returned in the TSK_Start_Date column for your missing months and help you identify why the rows are missing when applying the < @TheMonthLastDate clause.

```<code>DECLARE @END_YEAR VARCHAR(10)
DECLARE @END_MONTH VARCHAR(10)

SET @END_YEAR = '2010'
SET @END_MONTH = '10'

DECLARE @TheMonthLastDate DATETIME
DECLARE @TempDate DATETIME
SET @TempDate = '2010-11-01 00:00:00.000'
SET @TheMonthLastDate = '2010-11-01 00:00:00.000'

;with months
as
(
select dateadd(month, -1, dateadd(day, datediff(day, 0, @TempDate), 0)) as m
union all
select dateadd(month, -1, m)
from months
where   m > dateadd(month, -12, @TempDate)
)

,yourTable(DateOpened, DateClosed)
as
(select TSK_START_DATE, BTK_CLOSED_DATE
FROM [PROC].ALL_AUDIT
WHERE
(BTK_CLOSED_DATE < @TheMonthLastDate OR
--TSK_START_DATE < @TheMonthLastDate
)
)
select * , @TheMonthLastDate TheMonthLastDate from yourTable
</code>```

Title: Understanding TSQL Coalesce function

Body:
I am trying to select all 12 months / year.  And I thought following TSQL code would do this.  However, this does not include all months like I want.  What is the cause of this?  This is modified code:

DECLARE @END_YEAR VARCHAR(10)
DECLARE @END_MONTH VARCHAR(10)

SET @END_YEAR = '2010'
SET @END_MONTH = '10'

DECLARE @TheMonthLastDate DATETIME
DECLARE @TempDate DATETIME
SET @TempDate = '2010-11-01 00:00:00.000'
SET @TheMonthLastDate = '2010-11-01 00:00:00.000'

;with months
as
(
select dateadd(month, -1, dateadd(day, datediff(day, 0, @TempDate), 0)) as m
union all
select dateadd(month, -1, m)
from months
where   m > dateadd(month, -12, @TempDate)
)
,yourTable(DateOpened, DateClosed)
as
(select TSK_START_DATE, BTK_CLOSED_DATE
FROM [PROC].ALL_AUDIT
WHERE
(BTK_CLOSED_DATE < @TheMonthLastDate OR
TSK_START_DATE < @TheMonthLastDate
)
)
select      yt.DateClosed 'r2', m.m 'r3',
        month(coalesce(yt.DateClosed, m.m)) as 'MonthClosed',
        year(coalesce(yt.DateClosed, m.m)) as 'YearClosed'
from    months m
left join yourTable yt
    on
    (  datepart(year, yt.DateClosed) = DATEPART(year, m.m)
    and datepart(month, yt.DateClosed) = DATEPART(month, m.m)
    or
      datepart(year, yt.DateOpened) = DATEPART(year, m.m)
    and datepart(month, yt.DateOpened) = DATEPART(month, m.m)
    )
AND year(coalesce(yt.DateClosed, m.m)) = 2010
order by yt.DateClosed

So above query does not return all months.  But if I change above WHERE lines to:

FROM [PROC].ALL_AUDIT
    WHERE
BTK_CLOSED_DATE < @TheMonthLastDate

then this query does return all 12 months.  How can this be?

Output that I want and that I see when WHERE is BTK_CLOSED_DATE < @TheMonthLastDate:

r2  r3  MonthClosed YearClosed
NULL    2010-06-01 00:00:00.000 6   2010
NULL    2009-11-01 00:00:00.000 11  2009
2010-01-06 20:02:19.127 2010-01-01 00:00:00.000 1   2010
2010-01-27 23:13:45.570 2010-01-01 00:00:00.000 1   2010
2010-02-15 14:49:14.427 2010-02-01 00:00:00.000 2   2010
2010-02-15 14:49:14.427 2009-12-01 00:00:00.000 2   2010

But if I instead use WHERE:
(BTK_CLOSED_DATE < @TheMonthLastDate OR
    TSK_START_DATE < @TheMonthLastDate
    )

then I see:

r2  r3  MonthClosed YearClosed
NULL    2010-10-01 00:00:00.000 10  2010
NULL    2010-09-01 00:00:00.000 9   2010
NULL    2010-09-01 00:00:00.000 9   2010
NULL    2010-08-01 00:00:00.000 8   2010
NULL    2010-08-01 00:00:00.000 8   2010
...

So notice that in first result I see NULL for June 2010, which is what I want.
I think the problem has something to do with the fact that my data contains 2009-2011 data, but I only compare months and not years.  How would I add in this additional logic?

Body:
The only place where you are reducing the data is with the WHERE clause you have already identified.  Therefore, the reason you are not getting all the months you expect is down to the column TSK_START_DATE not being less than @TheMonthLastDate for all months.

To prove this hypothesis, run the following section of your query (I have commented out part of the where clause and removed everything under 'yourTable' cte).  The results should show you what is being returned in the TSK_Start_Date column for your missing months and help you identify why the rows are missing when applying the < @TheMonthLastDate clause.

DECLARE @END_YEAR VARCHAR(10)
DECLARE @END_MONTH VARCHAR(10)

SET @END_YEAR = '2010'
SET @END_MONTH = '10'

DECLARE @TheMonthLastDate DATETIME
DECLARE @TempDate DATETIME
SET @TempDate = '2010-11-01 00:00:00.000'
SET @TheMonthLastDate = '2010-11-01 00:00:00.000'

;with months
as
(
select dateadd(month, -1, dateadd(day, datediff(day, 0, @TempDate), 0)) as m
union all
select dateadd(month, -1, m)
from months
where   m > dateadd(month, -12, @TempDate)
)

,yourTable(DateOpened, DateClosed)
as
(select TSK_START_DATE, BTK_CLOSED_DATE
FROM [PROC].ALL_AUDIT
WHERE
(BTK_CLOSED_DATE < @TheMonthLastDate OR
--TSK_START_DATE < @TheMonthLastDate
)
)
select * , @TheMonthLastDate TheMonthLastDate from yourTable


问:
-Wint-in-bool-context warning issue in some compilers
I am a getting warning:
warning: '<<' in boolean context, did you mean '<' ? [-Wint-in-bool-context]
for the code similar to the following:</p>
```<code>int a=7,b=3;
int index=((a<<1)||b)&&5;
</code>```

答:
I got the solution. We should avoid integers using with logical operators (eg. ||,&&). Using integers with bitwise operators (eg. <<,&,|,etc.) is fine.

Sometimes we don't get this problem while running on compilers because of low priority warning filters. In complex and warning sensitive compilers it comes up.

Thanks

Body:
I am a getting warning:
warning: '<<' in boolean context, did you mean '<' ? [-Wint-in-bool-context]
for the code similar to the following:

int a=7,b=3;
int index=((a<<1)||b)&&5;


问:
how to add seperate meta tags for each page using header.php page on wordpress
I want to add the separate meta tags for the each page using the header.php

To add the title,Meta Description,Meta Keywords of the every page
for better SEO Anlayis. I want achieve this through code on header.php page.

```<code><html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<!--<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />-->

<style>
/*.alignleft { left:0px !important;}
*/
</style>

<title>
<?php
    /*
     * Print the <title> tag based on what is being viewed.
     */
    global $page, $paged;
    wp_title( '|', true, 'right' );
    // Add the blog name.
    bloginfo( 'blogname' );
    // Add the blog description for the home/front page.
    $site_description = get_bloginfo( 'description', 'display' );
    if ( $site_description && ( is_home() || is_front_page() ) )
        echo " | $site_description";
    // Add a page number if necessary:
    if ( $paged >= 2 || $page >= 2 )
        echo ' | ' . sprintf( __( 'Page %s'), max( $paged, $page ) );
?>
</title>
</html>
</code>```

Thanks in advance.

答:
Hi can i do this with the nromal phpo website?
function add_meta_data_firefog() {

```<code>if ( is_page('english') ) {
    echo'<meta name="Keywords" content="Keyword1,Keyword2,Keyword3,Keyword4,Keyword5,Keyword6">';
    echo'<meta name="Description" content="Your Description">';
}
if ( is_page('aboutus') ) {
    echo'<meta name="Keywords" content="Keyword1,Keyword2,Keyword3,Keyword4,Keyword5,Keyword6">';
    echo'<meta name="Description" content="Your Description">';
}
if ( is_page('newspaper') ) {
    echo'<meta name="Keywords" content="Keyword1,Keyword2,Keyword3,Keyword4,Keyword5,Keyword6">';
    echo'<meta name="Description" content="Your Description">';
}
</code>```

}
add_action('wp_head', 'add_meta_data_firefog');

Body:
I want to add the separate meta tags for the each page using the header.php

To add the title,Meta Description,Meta Keywords of the every page
for better SEO Anlayis. I want achieve this through code on header.php page.

<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo( 'charset' ); ?>" />

<title>
<?php
    /*
     * Print the <title> tag based on what is being viewed.
     */
    global $page, $paged;
    wp_title( '|', true, 'right' );
    // Add the blog name.
    bloginfo( 'blogname' );
    // Add the blog description for the home/front page.
    $site_description = get_bloginfo( 'description', 'display' );
    if ( $site_description && ( is_home() || is_front_page() ) )
        echo " | $site_description";
    // Add a page number if necessary:
    if ( $paged >= 2 || $page >= 2 )
        echo ' | ' . sprintf( __( 'Page %s'), max( $paged, $page ) );
?>
</title>

Thanks in advance.

Body:
Hi can i do this with the nromal phpo website?
function add_meta_data_firefog() {

if ( is_page('english') ) {
    echo'<meta name="Keywords" content="Keyword1,Keyword2,Keyword3,Keyword4,Keyword5,Keyword6">';
    echo'<meta name="Description" content="Your Description">';
}
if ( is_page('aboutus') ) {
    echo'<meta name="Keywords" content="Keyword1,Keyword2,Keyword3,Keyword4,Keyword5,Keyword6">';
    echo'<meta name="Description" content="Your Description">';
}
if ( is_page('newspaper') ) {
    echo'<meta name="Keywords" content="Keyword1,Keyword2,Keyword3,Keyword4,Keyword5,Keyword6">';
    echo'<meta name="Description" content="Your Description">';
}

}
add_action('wp_head', 'add_meta_data_firefog');


问:
why is git pull request not working and i always get errors?
when i use git pull command I came with an error as below

答:
You need to have an active & tracking branch to pull from, As of this moment, you don’t have one set up.

To confirm an active & track a branch:

git branch --set-upstream-to=origin/‹branch› main

More Information on git pull:
https://www.freecodecamp.org/news/git-pull-explained/amp/


问:
Skipping chunk of a big file with bash
Using bash, how to awk/grep from the middle of a given file and skip 1Gig for instance?  In other words, I don't want awk/grep to search through the first 1Gig of the file but want to start my search in the middle of the file.</p>

答:
Not tested the performance on very large files, compared to tail | grep, but you could try GNU sed:

sed -n '3000001,$ {/your regex/p}' file
```
<p>skips the first 3 millions lines and then prints all lines matching the <code>your regex</code> regular expression. Same with <code>awk</code>:</p>
<pre class="lang-sh prettyprint-override"><code>awk 'NR>3000000 && /your regex/' file
</code>```

Title: Skipping chunk of a big file with bash

Body:
Not tested the performance on very large files, compared to tail | grep, but you could try GNU sed:

sed -n '3000001,$ {/your regex/p}' file

skips the first 3 millions lines and then prints all lines matching the your regex regular expression. Same with awk:

awk 'NR>3000000 && /your regex/' file


问:
Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory \\METADATA
I relatively new to coding so I am not (yet) running virtual environments. Rather, I am just downloading packages with pip straight to my pc to run python 3.7 in atom.

When I tried to use pip the other day to install the scrapy package like so -m pip install --user scrapy

I got this error: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'c:\\users\\adrian\\appdata\\roaming\\python\\python37\\site-packages\\pip-19.0.1.dist-info\\METADATA'

Most of the other answers I have seen on related errors had people use conda to install some type of fix I think? When I tried to use conda to execute one of the fixes I recieved a CondaHTTPError: SSLError(MaxRetryError('HTTPSConnectionPool(host=\'repo.anaconda.com\', port=443): Max retries exceeded with url: /pkgs/free/noarch/repodata.json.bz2 (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available.

Any direction would be heartily appreciated :-)

答:
I had this problem while trying to install pytest on macOS

```<code>ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/Users/<USERNAME>/Projects/venvs/<VIRTUALENV_NAME>/lib/python3.8/site-packages/pytest-6.2.5.dist-info/METADATA
</code>```

I navigated to the site-packages directory and deleted pytest-6.2.5.dist-info folder.
Then try running the package installation command again.

Body:
I had this problem while trying to install pytest on macOS

ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/Users/<USERNAME>/Projects/venvs/<VIRTUALENV_NAME>/lib/python3.8/site-packages/pytest-6.2.5.dist-info/METADATA

I navigated to the site-packages directory and deleted pytest-6.2.5.dist-info folder.
Then try running the package installation command again.


问:
Is 'm' a common instance for Master and Fellow classes in this runtime polymorphism scenario?
I'm a beginner at programming stack and, I have a small question to ask based on these code lines.

Is 'm' a common instance for Master and Fellow classes in this runtime polymorphism scenario?

```<code>class Master{
    void something(){
        System.out.println("Something of Master");
    }
}

class Fellow extends Master{
    void something(){
        System.out.println("Something of Fellow");
    }
}

public class Drive {
    public static void main(String[] args) {
        Master m = new Fellow();
        System.out.println(m instanceof Fellow); //true
        System.out.println(m instanceof Master);  //true
        m.something(); // Something of Fellow
</code>```

答: m is an instance of Fellow. Because Fellow extends Master, every instance of Fellow is also an instance of Master.

Body:
I'm a beginner at programming stack and, I have a small question to ask based on these code lines.

Is 'm' a common instance for Master and Fellow classes in this runtime polymorphism scenario?

class Master{
    void something(){
        System.out.println("Something of Master");
    }
}

class Fellow extends Master{
    void something(){
        System.out.println("Something of Fellow");
    }
}

public class Drive {
    public static void main(String[] args) {
        Master m = new Fellow();
        System.out.println(m instanceof Fellow); //true
        System.out.println(m instanceof Master);  //true
        m.something(); // Something of Fellow


问:
How to scroll in Instagram following window using Selenium and Python?
How would I scroll in the following window on Instagram using Selenium and Python? I've tried everything I've found and none of them work.

Here's what I have to get me to the following window:

```<code>from selenium import webdriver

browser = webdriver.Firefox(executable_path = '/usr/local/bin/geckodriver')
browser.implicitly_wait(5)

browser.get('https://www.instagram.com/')

sleep(2)

username_input = browser.find_element_by_css_selector("input[name='username']")
password_input = browser.find_element_by_css_selector("input[name='password']")

username_input.send_keys("Enter Username Here")
password_input.send_keys("Enter Password Here")

login_button = browser.find_element_by_xpath("//button[@type='submit']")
login_button.click()

sleep(5)

browser.find_element_by_xpath('/html/body/div[1]/section/main/div/div/div/section/div/button').click()

sleep(2)

browser.find_element_by_css_selector('button.aOOlW:nth-child(2)').click()

browser.get('https://www.instagram.com/instagram/')

sleep(2)

browser.find_element_by_css_selector('li.Y8-fY:nth-child(3) > a:nth-child(1) > div:nth-child(1)').click()

sleep(2)

follower_number =int( driver.find_elements_by_xpath('//span [@class="g47SY "]')[2].text)
i=0

while(i<follower_number):
    element = driver.find_elements_by_xpath("//div[@role='dialog']//ul//li")
    driver.execute_script("arguments[0].scrollIntoView(true);",element[i])```
```

答:
have a look at this Question. i tried that and worked.

my code

```<code>from selenium.webdriver.common.action_chains import ActionChains
import time
import re
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.maximize_window()
driver.get("https://www.instagram.com/")
time.sleep(5)
my_email=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')
my_email.send_keys("")

my_password=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')
my_password.send_keys("")
time.sleep(5)

login=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]')
login.click()
time.sleep(5)
driver.get("https://www.instagram.com/instagram/following/")

driver.find_element_by_css_selector('li.Y8-fY:nth-child(3) > a:nth-child(1) > div:nth-child(1)').click()
time.sleep(5)

# this is not perfect but it will get your work done
# getting the number of followers
follower_number  =int( driver.find_elements_by_xpath('//span [@class="g47SY "]')[2].text)
i = 0

# looping for the exact number of followers ...
while(i<follower_number):
    # as the website is dyanamic so updating the follwers list and also the webelement
    element = driver.find_elements_by_xpath("//div[@role='dialog']//ul//li")
    # executing scroll into view script to view the element and thats gonna load the next element(follower ) ..ultimately your scrolling achived
    driver.execute_script("arguments[0].scrollIntoView(true);",element[i])
    time.sleep(2)
    print(i)
    i=i+1

</code>```

Body:
How would I scroll in the following window on Instagram using Selenium and Python? I've tried everything I've found and none of them work.

Here's what I have to get me to the following window:

from selenium import webdriver

browser = webdriver.Firefox(executable_path = '/usr/local/bin/geckodriver')
browser.implicitly_wait(5)

browser.get('https://www.instagram.com/')

sleep(2)

username_input = browser.find_element_by_css_selector("input[name='username']")
password_input = browser.find_element_by_css_selector("input[name='password']")

username_input.send_keys("Enter Username Here")
password_input.send_keys("Enter Password Here")

login_button = browser.find_element_by_xpath("//button[@type='submit']")
login_button.click()

sleep(5)

browser.find_element_by_xpath('/html/body/div[1]/section/main/div/div/div/section/div/button').click()

sleep(2)

browser.find_element_by_css_selector('button.aOOlW:nth-child(2)').click()

browser.get('https://www.instagram.com/instagram/')

sleep(2)

browser.find_element_by_css_selector('li.Y8-fY:nth-child(3) > a:nth-child(1) > div:nth-child(1)').click()

sleep(2)

follower_number =int( driver.find_elements_by_xpath('//span [@class="g47SY "]')[2].text)
i=0

while(i<follower_number):
    element = driver.find_elements_by_xpath("//div[@role='dialog']//ul//li")
    driver.execute_script("arguments[0].scrollIntoView(true);",element[i])```

Body:
have a look at this Question. i tried that and worked.

my code

from selenium.webdriver.common.action_chains import ActionChains
import time
import re
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.maximize_window()
driver.get("https://www.instagram.com/")
time.sleep(5)
my_email=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')
my_email.send_keys("")

my_password=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')
my_password.send_keys("")
time.sleep(5)

login=driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]')
login.click()
time.sleep(5)
driver.get("https://www.instagram.com/instagram/following/")

driver.find_element_by_css_selector('li.Y8-fY:nth-child(3) > a:nth-child(1) > div:nth-child(1)').click()
time.sleep(5)

# this is not perfect but it will get your work done
# getting the number of followers
follower_number  =int( driver.find_elements_by_xpath('//span [@class="g47SY "]')[2].text)
i = 0

# looping for the exact number of followers ...
while(i<follower_number):
    # as the website is dyanamic so updating the follwers list and also the webelement
    element = driver.find_elements_by_xpath("//div[@role='dialog']//ul//li")
    # executing scroll into view script to view the element and thats gonna load the next element(follower ) ..ultimately your scrolling achived
    driver.execute_script("arguments[0].scrollIntoView(true);",element[i])
    time.sleep(2)
    print(i)
    i=i+1


问:
collection creation in mongoDB may cause some conflicts?
Assume $db is a made mongoDB connection with php.

There is no collection exists yet.

I inserted one data

```<code>$db->board_name->board->article->insert(array("title"=>"example"));
</code>```

this is equivalent to

```<code>db.board_name.board.article.insert({"title":"example"})
</code>```

the problem is it inserts not the

db.board_name.board

structure but

just simply inserts "db.board_name.board.article" <--- these three as a string.

Does it just demonstrates like a combined string for now

because there is no other elements after "board_name"?

What if I add more things right after "board_name" like

```<code>db.board_name.rank.insert({"something":"thing"});
</code>```

Does mongoDB smartly recognize "rank" collection as part of "board_name" in that case?

or simply creates other collection with "db.board_name.rank"?

答:
I'm not sure if I understand correctly, but what I think you're asking is, "why is there no collection named board_name.name"? That's because you haven't created one yet.

Each collection in MongoDB simply has a name. The fact that human beings (and drivers) use .s to separate the names into logical namespaces is a convenience to make it easier to use, and to let you logically group related collections, but from MongoDB's perspective, the name is simply a string.

Once you've created board_name.name.article, if you issue a subsequent insert or save operation to another collection, say, board_name.rank, then that collection will be created for you at that time. There will be no conflicts, your insert, update, or save operation will either identify a collection which already exists, and operate on that, or create a new collection and operate on that.

For more on how collections work, see the MongoDB docs.

Body:
Assume $db is a made mongoDB connection with php.

There is no collection exists yet.

I inserted one data

$db->board_name->board->article->insert(array("title"=>"example"));

this is equivalent to

db.board_name.board.article.insert({"title":"example"})

the problem is it inserts not the

db.board_name.board

structure but

just simply inserts "db.board_name.board.article" <--- these three as a string.

Does it just demonstrates like a combined string for now

because there is no other elements after "board_name"?

What if I add more things right after "board_name" like

db.board_name.rank.insert({"something":"thing"});

Does mongoDB smartly recognize "rank" collection as part of "board_name" in that case?

or simply creates other collection with "db.board_name.rank"?