问:
Improving point within polygon calculations with python
For my project in python I need to define to which country belongs a large number of coordinates (lat,lon). I have managed to do so using the shapely Point.within(Polygon) method (see code below), provided a shapefile of country borders downloaded from  natural earth (the shapefile must be split into singleparts polygons first, I didn't find how to handle multipart polygons properly).

Although the method works fine, it is a bit slow for making tons of queries. Probably that the performance is strongly linked to the shapefile resolution, however precision is needed. I have already done some progress with a bounding box pre-selection round (only polygons having the coordinate inside their bounding box are checked ) but I am trying to improve it further. How could I proceed ? I was thinking  to use an inner-bounding box to quickly discriminate unambiguous points, but then I don't know how to build them. Or maybe it is better to make once and for all some fancy lookup table ? I must say that I am not familiar with hash tables and alike, would it be an option ?

Thanks

```<code>#env python3
from shapely.geometry import Polygon, Point
import shapefile

class CountryLoc:
    def __init__(self, shppath, alpha3pos = 1):
        polygon = shapefile.Reader(shppath)
        self.sbbox = [pol.bbox for pol in polygon.shapes()]
        self.shapePoints = [pol.points for pol in polygon.shapes()]
        self.shapeCnames = [pol.record[alpha3pos] for pol in polygon.shapeRecords()]
        self.shapecount = polygon.numRecords

    def which_country(self,lat,lon):
        countries = self._pointcountry(lat,lon)
        if len(countries) > 1:
            print('too many countries at coord ({:.3f},{:.3f}) : {}'.format(lat,lon,countries))
        try:
            return countries[0]
        except:
            #print('no country ref @ latlon ({},{})'.format(lat,lon))
            return 'OXO'

    def _findBboxMatch(self,lat,lon):
        matchidslist = []
        for ids in range(self.shapecount):
            if lat >= self.sbbox[ids][1] and lat <= self.sbbox[ids][3]:
                if self.sbbox[ids][0] > self.sbbox[ids][2] :
                # rem RUS and USA BBOX are spanning accross the +180-180 cut
                    if not(lon >= self.sbbox[ids][2] and lon <= self.sbbox[ids][0]):
                        matchidslist.append(ids)
                else:
                    if lon >= self.sbbox[ids][0] and lon <= self.sbbox[ids][2]:
                        matchidslist.append(ids)
        return matchidslist

    def _pointcountry(self,lat,lon):
        coord = Point(lon,lat)
        matchidlist = self._findBboxMatch(lat,lon) ## BBOX PRESELECT
        matchcountrylist = []
        for ids in matchidlist:
            pp = Polygon(self.shapePoints[ids])
            if coord.within(pp):
                matchcountrylist.append(self.shapeCnames[ids])
        return matchcountrylist

    def printCountry(self,lat,lon):
        ctry = self.which_country(lat,lon)
        print('coord. ({},{}) is in {}'.format(lat,lon,ctry))
        bbmatch = self._findBboxMatch(lat,lon)
        print('matching BBOXs are {}'.format([self.shapeCnames[k] for k in bbmatch]))
        print(' ')

if __name__ == '__main__':
    # testing
    cc = input('lat,lon ? ')
    coords = [float(cc.split(',')[0]) , float(cc.split(',')[1])]
    coloc = CountryLoc('./borders_shapefile.shp', alpha3pos=9)
    coloc.printCountry(coords[0],coords[1])
</code>```

答:
You want an acceleration structure, such as a quadtree, a k-d tree, a spatial hash table, and others.

When setting up your shape data, you'll load the structure based on where the shapes lie in the plane. With a quadtree, for instance, you recursively subdivide space into four quadrants until each leaf quadrant overlaps some small number of shapes (or none of them). Then you record a list of shape references at each of those leaves.

Later, when you're searching for the shape that overlaps a specific point, you traverse the tree of subdivisions based on just two comparison operations at each of about log n levels. When you reach the proper leaf quadrant, you need only check a small number of shapes with the Point.within function.

Body:
For my project in python I need to define to which country belongs a large number of coordinates (lat,lon). I have managed to do so using the shapely Point.within(Polygon) method (see code below), provided a shapefile of country borders downloaded from  natural earth (the shapefile must be split into singleparts polygons first, I didn't find how to handle multipart polygons properly).

Although the method works fine, it is a bit slow for making tons of queries. Probably that the performance is strongly linked to the shapefile resolution, however precision is needed. I have already done some progress with a bounding box pre-selection round (only polygons having the coordinate inside their bounding box are checked ) but I am trying to improve it further. How could I proceed ? I was thinking  to use an inner-bounding box to quickly discriminate unambiguous points, but then I don't know how to build them. Or maybe it is better to make once and for all some fancy lookup table ? I must say that I am not familiar with hash tables and alike, would it be an option ?

Thanks

#env python3
from shapely.geometry import Polygon, Point
import shapefile

class CountryLoc:
    def __init__(self, shppath, alpha3pos = 1):
        polygon = shapefile.Reader(shppath)
        self.sbbox = [pol.bbox for pol in polygon.shapes()]
        self.shapePoints = [pol.points for pol in polygon.shapes()]
        self.shapeCnames = [pol.record[alpha3pos] for pol in polygon.shapeRecords()]
        self.shapecount = polygon.numRecords

    def which_country(self,lat,lon):
        countries = self._pointcountry(lat,lon)
        if len(countries) > 1:
            print('too many countries at coord ({:.3f},{:.3f}) : {}'.format(lat,lon,countries))
        try:
            return countries[0]
        except:
            #print('no country ref @ latlon ({},{})'.format(lat,lon))
            return 'OXO'

    def _findBboxMatch(self,lat,lon):
        matchidslist = []
        for ids in range(self.shapecount):
            if lat >= self.sbbox[ids][1] and lat <= self.sbbox[ids][3]:
                if self.sbbox[ids][0] > self.sbbox[ids][2] :
                # rem RUS and USA BBOX are spanning accross the +180-180 cut
                    if not(lon >= self.sbbox[ids][2] and lon <= self.sbbox[ids][0]):
                        matchidslist.append(ids)
                else:
                    if lon >= self.sbbox[ids][0] and lon <= self.sbbox[ids][2]:
                        matchidslist.append(ids)
        return matchidslist

    def _pointcountry(self,lat,lon):
        coord = Point(lon,lat)
        matchidlist = self._findBboxMatch(lat,lon) ## BBOX PRESELECT
        matchcountrylist = []
        for ids in matchidlist:
            pp = Polygon(self.shapePoints[ids])
            if coord.within(pp):
                matchcountrylist.append(self.shapeCnames[ids])
        return matchcountrylist

    def printCountry(self,lat,lon):
        ctry = self.which_country(lat,lon)
        print('coord. ({},{}) is in {}'.format(lat,lon,ctry))
        bbmatch = self._findBboxMatch(lat,lon)
        print('matching BBOXs are {}'.format([self.shapeCnames[k] for k in bbmatch]))
        print(' ')

if __name__ == '__main__':
    # testing
    cc = input('lat,lon ? ')
    coords = [float(cc.split(',')[0]) , float(cc.split(',')[1])]
    coloc = CountryLoc('./borders_shapefile.shp', alpha3pos=9)
    coloc.printCountry(coords[0],coords[1])


来源: stackexchange

问:
AWS API Gateway Custom Domain
I am trying to map my api to custom domain. Let's say I have a website hosted through route 53 (example.com ), then I want my the api to be at api.example.com. So, I am following this link, I did everything as it said. But, when I do https://api.example.com/apiresource ,it says cannot resolve DNS. So, I am not sure if I have to setup another hosted zone for api.example.com and create NS record set ? The documentation doesn't say about it. I would appreciate any help. </p>

答: I solved it by creating host zone for api.example.com.</p>

ContentLicense: CC BY-SA 3.0

Title: AWS API Gateway Custom Domain


问:
Race condition appending to mutable Map in future
I need to append to a Map structure from within a future, and I couldn't find a way to make the Map immutable (See below). I'm afraid that if the Map is mutable then I will have a race condition. How to fix the code below?

```<code>object TestFutures extends App {

  val m = collection.mutable.Map[Int,String]()

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val f2 = Future { 2 }
  val f3 = Future { 3 }
  val f4 = Future { 4 }

  val fx = Seq(f0,f1,f2,f3,f4)

  fx.map {
     i =>
       i.map {
         x =>
           val s = x + ""
           m += ( x -> s )
     }
  }

  Thread.sleep(5000)
  println(m)
}
</code>```

答:
Here's one way to get the result as an immutable Map.

```<code>val fx = Future.sequence(Seq(f0,f1,f2,f3,f4))
               .map(_.map(i => i -> s"$i").toMap)
//fx: Future[scala.collection.immutable.Map[Int,String]]
</code>```

Body:
I need to append to a Map structure from within a future, and I couldn't find a way to make the Map immutable (See below). I'm afraid that if the Map is mutable then I will have a race condition. How to fix the code below?

object TestFutures extends App {

  val m = collection.mutable.Map[Int,String]()

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val f2 = Future { 2 }
  val f3 = Future { 3 }
  val f4 = Future { 4 }

  val fx = Seq(f0,f1,f2,f3,f4)

  fx.map {
     i =>
       i.map {
         x =>
           val s = x + ""
           m += ( x -> s )
     }
  }

  Thread.sleep(5000)
  println(m)
}

Body:
Here's one way to get the result as an immutable Map.

val fx = Future.sequence(Seq(f0,f1,f2,f3,f4))
               .map(_.map(i => i -> s"$i").toMap)
//fx: Future[scala.collection.immutable.Map[Int,String]]


问:
Is there a way to optimize the code and improve to K number of sum terms instead of 4?
```<code>#include <stdio.h>
int main() {
  int N = 133;
  int a, b, c, d;
  int flag = 0;
    for ( int j = 1; j < (N/2); j++)
    {
     a = j;
      for ( int k = 1; k < (N/2); k++)
      {
      b = k;
        for ( int l = 1; l < (N/2); l++)
      {
        c = l;
        for ( int m = 1; m < (N/2); m++)
        {
        d = m;
        if ( a+b+c+d == N && (a != 0 && b!= 0 && c != 0 && d!= 0))
        {
                printf("\n %d + %d + %d + %d = %d" , a, b, c, d, N);
                flag = 1;
                break;
        }
        }
        if(flag)
          break;
      }
        if(flag)
          break;
      }
        if(flag)
          break;
    }
return 0;
}
</code>```

The code currently outputs

```<code>1 + 2 + 65 + 65 = 133
</code>```

As you can see, I am getting the sum using 4 numbers to form N (133) in this case. Is there a way to improve the code to 'k' numbers without using nested 'k' for loops?

```<code>Desired Output: ( a + b + c + d + e + f + ...... + k = N )
</code>```

say for a given value of N represented using sum of k terms, where k is an input parameter.

Notes:

None of the 'k' terms is zero.

Original question had loops starting from 0; updated to start from 1.

Specific Requirement, I want the terms (a to k) to have the lowest possible standard deviation among all the sums. So breaking out at the first sum is not ideal for that scenario, but this is the baseline code I have reached. Once I figure out reducing number of loops, I know how to modify for lowest S.D.

Also pretty obvious but k < N in all cases.

答:
Much simpler code that does the same thing as yours:

```<code>#include <stdio.h>
int main()
{
  int N = 133;
  for ( int j = 1; j < (N/2); j++)
    for ( int k = 1; k < (N/2); k++)
      for ( int l = 1; l < (N/2); l++)
        for ( int m = 1; m < (N/2); m++)
          if ( j+k+l+m == N) {
            printf("\n %d + %d + %d + %d = %d" , j, k, l , m, N);
            return 0;
          }
}
</code>```

And to your problem, which is a bit vague, but seems to be finding k numbers a_1, a_2 ... a_k such that 1 < a_n < N/2 for all n and a_1+a_2+...+a_k=N. Here is very simple code to do that, using your algorithm but extended for arbitrary k:

```<code>#define N 133
#define k 8

int main()
{
  int arr[k];
  for(int i=0; i<k; i++)
    arr[i]=1;
  for(int i=0,c=k; c<N; c++) {
    arr[i]++;
    if(arr[i]>=N/2) {
      c--;
      i++;
    }
  }
  for(int i=0; i<k-2; i++)
    printf("%d + ", arr[i]);
  printf("%d = %d\n", arr[k-1], N);
}
</code>```

It has no error checking. The problem is not solvable for k=1 and k>N. And because integer division is rounded down, it is not solvable for k=2 if N is odd.

But here is some MUCH more efficient code. The problem is very simple, so it's not about finding the numbers a_1, a_2, a_3 ... a_k. It's really only about finding a_1 and a_2. The rest are one.

```<code>#define N 19
#define k 5

int main()
{
  for(int i=0; i<k-2; i++)
    printf("1 + ");

  int c=N/2-(k-2);
  if (c<1)
    c=1;
  printf("%d + ", c);
  printf("%d = %d\n", N-(k-2)-c, N);
}
</code>```

Again, no error check is made.

Body:
#include <stdio.h>
int main() {
  int N = 133;
  int a, b, c, d;
  int flag = 0;
    for ( int j = 1; j < (N/2); j++)
    {
     a = j;
      for ( int k = 1; k < (N/2); k++)
      {
      b = k;
        for ( int l = 1; l < (N/2); l++)
      {
        c = l;
        for ( int m = 1; m < (N/2); m++)
        {
        d = m;
        if ( a+b+c+d == N && (a != 0 && b!= 0 && c != 0 && d!= 0))
        {
                printf("\n %d + %d + %d + %d = %d" , a, b, c, d, N);
                flag = 1;
                break;
        }
        }
        if(flag)
          break;
      }
        if(flag)
          break;
      }
        if(flag)
          break;
    }
return 0;
}

The code currently outputs

1 + 2 + 65 + 65 = 133

As you can see, I am getting the sum using 4 numbers to form N (133) in this case. Is there a way to improve the code to 'k' numbers without using nested 'k' for loops?

Desired Output: ( a + b + c + d + e + f + ...... + k = N )

say for a given value of N represented using sum of k terms, where k is an input parameter.

Notes:

None of the 'k' terms is zero.

Original question had loops starting from 0; updated to start from 1.

Specific Requirement, I want the terms (a to k) to have the lowest possible standard deviation among all the sums. So breaking out at the first sum is not ideal for that scenario, but this is the baseline code I have reached. Once I figure out reducing number of loops, I know how to modify for lowest S.D.

Also pretty obvious but k < N in all cases.

Body:
Much simpler code that does the same thing as yours:

#include <stdio.h>
int main()
{
  int N = 133;
  for ( int j = 1; j < (N/2); j++)
    for ( int k = 1; k < (N/2); k++)
      for ( int l = 1; l < (N/2); l++)
        for ( int m = 1; m < (N/2); m++)
          if ( j+k+l+m == N) {
            printf("\n %d + %d + %d + %d = %d" , j, k, l , m, N);
            return 0;
          }
}

And to your problem, which is a bit vague, but seems to be finding k numbers a_1, a_2 ... a_k such that 1 < a_n < N/2 for all n and a_1+a_2+...+a_k=N. Here is very simple code to do that, using your algorithm but extended for arbitrary k:

#define N 133
#define k 8

int main()
{
  int arr[k];
  for(int i=0; i<k; i++)
    arr[i]=1;
  for(int i=0,c=k; c<N; c++) {
    arr[i]++;
    if(arr[i]>=N/2) {
      c--;
      i++;
    }
  }
  for(int i=0; i<k-2; i++)
    printf("%d + ", arr[i]);
  printf("%d = %d\n", arr[k-1], N);
}

It has no error checking. The problem is not solvable for k=1 and k>N. And because integer division is rounded down, it is not solvable for k=2 if N is odd.

But here is some MUCH more efficient code. The problem is very simple, so it's not about finding the numbers a_1, a_2, a_3 ... a_k. It's really only about finding a_1 and a_2. The rest are one.

#define N 19
#define k 5

int main()
{
  for(int i=0; i<k-2; i++)
    printf("1 + ");

  int c=N/2-(k-2);
  if (c<1)
    c=1;
  printf("%d + ", c);
  printf("%d = %d\n", N-(k-2)-c, N);
}

Again, no error check is made.


问:
Pipe complete array-objects instead of array items one at a time?

How do you send the output from one CmdLet to the next one in a pipeline as a complete array-object instead of the individual items in the array one at a time?

The problem - Generic description

As can be seen in help for about_pipelines (help pipeline) powershell sends objects one at the time down the pipeline¹. So Get-Process -Name notepad | Stop-Process sends one process at the time down the pipe.

Lets say we have a 3rd party CmdLet (Do-SomeStuff) that can't be modified or changed in any way. Do-SomeStuff perform different if it is passed an array of strings or if it is passed a single string object.

Do-SomeStuff is just an example, it could be substituted for ForEach-Object, Select-Object, Write-Host (or any other CmdLet accepting pipeline input)

Do-SomeStuff will in this example process the individual items in the array one at the time.

```<code>$theArray = @("A", "B", "C")
$theArray | Do-SomeStuff
</code>```

If we want to send the complete array as one object to Do-SomeStuff one might try something like this

```<code>@($theArray) | Do-SomeStuff
</code>```

But it does not produce the expected result since PowerShell "ignores" the new single-item-array.

So, how do you "force" $theArray to be passed down the pipe as a single array-object instead of the content items one at the time?

The problem - practical example

As shown below the output of Write-Host is different if passed an array or if it passed the individual items in the array one at the time.

```<code>PS C:\> $theArray = @("A", "B", "C")
PS C:\> Write-Host $theArray
A B C
PS C:\> $theArray | foreach{Write-Host $_}
A
B
C
PS C:\> @($theArray) | foreach{Write-Host $_}
A
B
C
</code>```

How do you do to get $theArray | foreach{Write-Host $_} to produce the same output as Write-Host $theArray ?

FOOTNOTES

Pipeline processing in Powershell

A normal array of strings

```<code>PS C:\> @("A", "B", "C").GetType().FullName
System.Object[]
</code>```

A normal array of strings piped to Foreach-Object

```<code>PS C:\> @("A", "B", "C") | foreach{$_.GetType().FullName}
System.String
System.String
System.String
</code>```

Each string in the array is processed one at the time by the ForEach-Object CmdLet.

An array of arrays, where the "inner" arrays are arrays of strings.

```<code>PS C:\> @(@("A", "B", "C"), @("D", "E", "F"), @("G", "H", "I")) | foreach{$_.GetType().FullName}
System.Object[]
System.Object[]
System.Object[]
</code>```

Each array in the array is processed one at the time by the ForEach-Object CmdLet, and the content of each sub-array from the input is handled as one object even though it is an array.

答:
There's an old-school solution, if you don't mind that your process is a function.

Example:  You want an array copied to the clipboard in a way that allows you to build it again on another system without any PSRemoting connectivity.  So you want an array containing "A", "B", and "C" to transmute to a string:
@("A","B","C")
...instead of a literal array.

So you build this (which isn't optimal for other reasons, but stay on topic):

```<code># Serialize-List

param
(
    [Parameter(Mandatory, ValueFromPipeline)]
    [string[]]$list
)
    $output = "@(";

    foreach ($element in $list)
    {
        $output += "`"$element`","
    }

    $output = $output.Substring(0, $output.Length - 1)
    $output += ")"
    $output
</code>```

and it works when you specify the array as a parameter directly:

```<code>Serialize-List $list
@("A","B","C")
</code>```

...but not so much when you pass it through the pipeline:

```<code>$list | Serialize-List
@("C")
</code>```

But refactor your function with begin, process, and end blocks:

```<code># Serialize-List

param
(
    [Parameter(Mandatory, ValueFromPipeline)]
    [string[]]$list
)

begin
{
    $output = "@(";
}

process
{
    foreach ($element in $list)
    {
        $output += "`"$element`","
    }
}

end
{
    $output = $output.Substring(0, $output.Length - 1)
    $output += ")"
    $output
}
</code>```

...and you get the desired output both ways.

```<code>Serialize-List $list
@("A","B","C")

$list | Serialize-List
@("A","B","C")
</code>```

Body:
How do you send the output from one CmdLet to the next one in a pipeline as a complete array-object instead of the individual items in the array one at a time?

The problem - Generic description

As can be seen in help for about_pipelines (help pipeline) powershell sends objects one at the time down the pipeline¹. So Get-Process -Name notepad | Stop-Process sends one process at the time down the pipe.

Lets say we have a 3rd party CmdLet (Do-SomeStuff) that can't be modified or changed in any way. Do-SomeStuff perform different if it is passed an array of strings or if it is passed a single string object.

Do-SomeStuff is just an example, it could be substituted for ForEach-Object, Select-Object, Write-Host (or any other CmdLet accepting pipeline input)

Do-SomeStuff will in this example process the individual items in the array one at the time.

$theArray = @("A", "B", "C")
$theArray | Do-SomeStuff

If we want to send the complete array as one object to Do-SomeStuff one might try something like this

@($theArray) | Do-SomeStuff

But it does not produce the expected result since PowerShell "ignores" the new single-item-array.

So, how do you "force" $theArray to be passed down the pipe as a single array-object instead of the content items one at the time?

The problem - practical example

As shown below the output of Write-Host is different if passed an array or if it passed the individual items in the array one at the time.

PS C:\> $theArray = @("A", "B", "C")
PS C:\> Write-Host $theArray
A B C
PS C:\> $theArray | foreach{Write-Host $_}
A
B
C
PS C:\> @($theArray) | foreach{Write-Host $_}
A
B
C

How do you do to get $theArray | foreach{Write-Host $_} to produce the same output as Write-Host $theArray ?

FOOTNOTES

Pipeline processing in Powershell

A normal array of strings

PS C:\> @("A", "B", "C").GetType().FullName
System.Object[]

A normal array of strings piped to Foreach-Object

PS C:\> @("A", "B", "C") | foreach{$_.GetType().FullName}
System.String
System.String
System.String

Each string in the array is processed one at the time by the ForEach-Object CmdLet.

An array of arrays, where the "inner" arrays are arrays of strings.

PS C:\> @(@("A", "B", "C"), @("D", "E", "F"), @("G", "H", "I")) | foreach{$_.GetType().FullName}
System.Object[]
System.Object[]
System.Object[]

Each array in the array is processed one at the time by the ForEach-Object CmdLet, and the content of each sub-array from the input is handled as one object even though it is an array.

Body:
There's an old-school solution, if you don't mind that your process is a function.

Example:  You want an array copied to the clipboard in a way that allows you to build it again on another system without any PSRemoting connectivity.  So you want an array containing "A", "B", and "C" to transmute to a string:
@("A","B","C")
...instead of a literal array.

So you build this (which isn't optimal for other reasons, but stay on topic):

# Serialize-List

param
(
    [Parameter(Mandatory, ValueFromPipeline)]
    [string[]]$list
)
    $output = "@(";

    foreach ($element in $list)
    {
        $output += "`"$element`","
    }

    $output = $output.Substring(0, $output.Length - 1)
    $output += ")"
    $output

and it works when you specify the array as a parameter directly:

Serialize-List $list
@("A","B","C")

...but not so much when you pass it through the pipeline:

$list | Serialize-List
@("C")

But refactor your function with begin, process, and end blocks:

# Serialize-List

param
(
    [Parameter(Mandatory, ValueFromPipeline)]
    [string[]]$list
)

begin
{
    $output = "@(";
}

process
{
    foreach ($element in $list)
    {
        $output += "`"$element`","
    }
}

end
{
    $output = $output.Substring(0, $output.Length - 1)
    $output += ")"
    $output
}

...and you get the desired output both ways.

Serialize-List $list
@("A","B","C")

$list | Serialize-List
@("A","B","C")

ContentLicense: CC BY-SA 4.0


问:
Force DOM redraw/refresh on Chrome/Mac
Every once in a while, Chrome will render perfectly valid HTML/CSS incorrectly or not at all.   Digging in through the DOM inspector is often enough to get it to realize the error of its ways and redraw correctly, so it's provably the case that the markup is good.  This happens frequently (and predictably) enough in a project I'm working on that I've put code in place to force a redraw in certain circumstances.

This works in most browser/os combinations:

```<code>    el.style.cssText += ';-webkit-transform:rotateZ(0deg)'
    el.offsetHeight
    el.style.cssText += ';-webkit-transform:none'
</code>```

As in, tweak some unused CSS property, then ask for some information that forces a redraw, then untweak the property.  Unfortunately, the bright team behind Chrome for the Mac seem to have found a way to get that offsetHeight without redrawing.  Thus killing an otherwise useful hack.

Thus far, the best I've come up with to get the same effect on Chrome/Mac is this piece of ugliness:

```<code>    $(el).css("border", "solid 1px transparent");
    setTimeout(function()
    {
        $(el).css("border", "solid 0px transparent");
    }, 1000);
</code>```

As in, actually force the element to jump a bit, then chill a second and jump it back.  Making it worse, if you drop that timeout below 500ms (to where it would be less noticeable), it often won't have the desired effect, since the browser won't get around to redrawing before it goes back to its original state.

Anybody care to offer a better version of this redraw/refresh hack (preferably based on the first example above)  that works on Chrome/Mac?

答:
I ran into a similar issue and this simple line of JS helped to fix it:

```<code>document.getElementsByTagName('body')[0].focus();
</code>```

In my case it was a bug with a Chrome extension not redrawing the page after changing its CSS from within the extension.

Title: Force DOM redraw/refresh on Chrome/Mac

Body:
Every once in a while, Chrome will render perfectly valid HTML/CSS incorrectly or not at all.   Digging in through the DOM inspector is often enough to get it to realize the error of its ways and redraw correctly, so it's provably the case that the markup is good.  This happens frequently (and predictably) enough in a project I'm working on that I've put code in place to force a redraw in certain circumstances.

This works in most browser/os combinations:

    el.style.cssText += ';-webkit-transform:rotateZ(0deg)'
    el.offsetHeight
    el.style.cssText += ';-webkit-transform:none'

As in, tweak some unused CSS property, then ask for some information that forces a redraw, then untweak the property.  Unfortunately, the bright team behind Chrome for the Mac seem to have found a way to get that offsetHeight without redrawing.  Thus killing an otherwise useful hack.

Thus far, the best I've come up with to get the same effect on Chrome/Mac is this piece of ugliness:

    $(el).css("border", "solid 1px transparent");
    setTimeout(function()
    {
        $(el).css("border", "solid 0px transparent");
    }, 1000);

As in, actually force the element to jump a bit, then chill a second and jump it back.  Making it worse, if you drop that timeout below 500ms (to where it would be less noticeable), it often won't have the desired effect, since the browser won't get around to redrawing before it goes back to its original state.

Anybody care to offer a better version of this redraw/refresh hack (preferably based on the first example above)  that works on Chrome/Mac?

Body:
I ran into a similar issue and this simple line of JS helped to fix it:

document.getElementsByTagName('body')[0].focus();

In my case it was a bug with a Chrome extension not redrawing the page after changing its CSS from within the extension.


问:
prime numbers algorithm efficiency
I have a question about prime numbers algorithm.

why in the following pseudo code i increases by 6 and not by 2 every iteration?

```<code>function is_prime(n)
if n ≤ 1
    return false
else if n ≤ 3
    return true
else if n mod 2 = 0 or n mod 3 = 0
    return false
let i ← 5
while i * i ≤ n
    if n mod i = 0 or n mod (i + 2) = 0
        return false
    i ← i + 6
return true
</code>```

Thanks!

答:
The algorithm is based on the fact that prime numbers can be predicted using the formula 6k ± 1 and this does not apply on 2 and 3.

For instance

(6 * 1) - 1 = 5

(6 * 2) - 1 = 11

(6 * 3) - 1 = 17

The list goes on and on.

Title: prime numbers algorithm efficiency

Body:
I have a question about prime numbers algorithm.

why in the following pseudo code i increases by 6 and not by 2 every iteration?

function is_prime(n)
if n ≤ 1
    return false
else if n ≤ 3
    return true
else if n mod 2 = 0 or n mod 3 = 0
    return false
let i ← 5
while i * i ≤ n
    if n mod i = 0 or n mod (i + 2) = 0
        return false
    i ← i + 6
return true

Thanks!


问:
Trigger select from an anchor
This is something really simple what I need to do is pass a variable or something to my method.
the problem with this code is that when the onPickupClock is triggered it opens the first component, that is the <md-select name="price"> and not the component itself

My question is:
How can I set it to open the component itself, the <md-select name="clocktime">?

this is the angular material select doc if you want to take a look

home.component.ts

```<code>import { MdSelect } from '@angular/material';

@Component({
....
})

export class HomeComponent {

  @ViewChild(MdSelect) dp: MdSelect;

  onPickupClock(e) {
   this.dp.toggle(e);
  }
}
</code>```

home.component.html

```<code> <md-select [(ngModel)]="selectedPrice" floatPlaceholder="never" name="price">
    <md-option *ngFor="let price of prices" [value]="price.value">
     {{price.viewValue}}
    </md-option>
 </md-select>
...
<div>
 <a (click)="onPickupClock()">
   <img src="/assets/home/xxx.png">
 </a>
</div>

 <md-select [(ngModel)]="selectedClockPickup" floatPlaceholder="never" name="clocktime">

  <md-option *ngFor="let clocktime of clocktimes [value]="clocktime.value">
   {{clocktime.viewValue}}
  </md-option>

 </md-select>
</code>```

答:
Option #1: Use ViewChild properties

Define your selects with template reference variables

```<code><md-select #priceSelect>
</md-select>

<md-select #clockTimeSelect>
</md-select>
</code>```

Update home.component.ts and create two ViewChild properties on your component.

```<code>  @ViewChild('priceSelect') priceSelect: MdSelect;
  @ViewChild('clockTimeSelect') clockTimeSelect: MdSelect;
</code>```

Notice the selectors for the ViewChild decorator are template reference variables you used in the template. This gives you direct access the components.

```<code>  onPickupClock() {
    this.clockTimeSelect.toggle();
  }
</code>```

Option #2: Pass Template reference directly to calling function

Pass the template reference variable to the click event.

First give your md-select a local template variable name, called #clockTimeSelect

```<code> <md-select #clockTimeSelect [(ngModel)]="selectedClockPickup" floatPlaceholder="never" name="clocktime">
  <md-option *ngFor="let clocktime of clocktimes [value]="clocktime.value">
   {{clocktime.viewValue}}
  </md-option>
 </md-select>
</code>```

Then update your click to pass the template reference variable.

```<code> <a (click)="onPickupClock(clockTimeSelect)">
   <img src="/assets/home/xxx.png">
 </a>
</code>```

Update the component function to receive a MdSelect

```<code>onPickupClock(mdSelect: MdSelect) {
  mdSelect.toggle();
}
</code>```

Title: Trigger select from an anchor

Body:
This is something really simple what I need to do is pass a variable or something to my method.
the problem with this code is that when the onPickupClock is triggered it opens the first component, that is the <md-select name="price"> and not the component itself

My question is:
How can I set it to open the component itself, the <md-select name="clocktime">?

this is the angular material select doc if you want to take a look

home.component.ts

import { MdSelect } from '@angular/material';

@Component({
....
})

export class HomeComponent {

  @ViewChild(MdSelect) dp: MdSelect;

  onPickupClock(e) {
   this.dp.toggle(e);
  }
}

home.component.html

 <md-select [(ngModel)]="selectedPrice" floatPlaceholder="never" name="price">
    <md-option *ngFor="let price of prices" [value]="price.value">
     {{price.viewValue}}
    </md-option>
 </md-select>
...

 <md-select [(ngModel)]="selectedClockPickup" floatPlaceholder="never" name="clocktime">

  <md-option *ngFor="let clocktime of clocktimes [value]="clocktime.value">
   {{clocktime.viewValue}}
  </md-option>

 </md-select>

Body:
Option #1: Use ViewChild properties

Define your selects with template reference variables

<md-select #priceSelect>
</md-select>

<md-select #clockTimeSelect>
</md-select>

Update home.component.ts and create two ViewChild properties on your component.

  @ViewChild('priceSelect') priceSelect: MdSelect;
  @ViewChild('clockTimeSelect') clockTimeSelect: MdSelect;

Notice the selectors for the ViewChild decorator are template reference variables you used in the template. This gives you direct access the components.

  onPickupClock() {
    this.clockTimeSelect.toggle();
  }

Option #2: Pass Template reference directly to calling function

Pass the template reference variable to the click event.

First give your md-select a local template variable name, called #clockTimeSelect

 <md-select #clockTimeSelect [(ngModel)]="selectedClockPickup" floatPlaceholder="never" name="clocktime">
  <md-option *ngFor="let clocktime of clocktimes [value]="clocktime.value">
   {{clocktime.viewValue}}
  </md-option>
 </md-select>

Then update your click to pass the template reference variable.

 <a (click)="onPickupClock(clockTimeSelect)">
   <img src="/assets/home/xxx.png">
 </a>

Update the component function to receive a MdSelect

onPickupClock(mdSelect: MdSelect) {
  mdSelect.toggle();
}


问:
Python Boolean and Logical Operators
Given two input boolean values I want to print out the following results:

True True ->  False

  True False -> False

  False True -> False

  False False ->  True

I tried doing this:

```<code>if boolInput1 and boolInput2 == True:
    print(False)
elif boolInput1 == True and boolInput2 == False:
    print(False)
elif boolInput1 == False and boolInput2 == True:
    print(False)
elif boolInput1 and boolInput2 == False:
    print(True)
</code>```

but it doesn't work as this is the output:

```<code>Test  Input    Expected Actual
1   True True   False   False
2   True False  False   False
3   False True  False   False
4   False False True    False
</code>```

I've tried searching for an answer online but can't find anything.

答:
elif boolInput1 and boolInput2 == False: isn't doing what you think it's doing.

Each side of the and are evaluated as separate booleans.

To condense what the computer is doing on that statement:

```<code>boolInput1 and boolInput2 == False
False and False == False
False and True
False #Does not enter if Statement
</code>```

This should show you that your logic on all 4 is actually wrong and there are ways to mess it up. Try to avoid boolean == true kind of statements wherever possible, and just say if boolean

Working version:

```<code>if boolInput1 and boolInput2:
    print(False)
elif boolInput1 and not boolInput2:
    print(False)
elif not boolInput1 and boolInput2:
    print(False)
elif not boolInput1 and not boolInput2:
    print(True)
</code>```

Though depending on your reason for this code, there are even more simple ways to do it.

Title: Python Boolean and Logical Operators

Body:
Given two input boolean values I want to print out the following results:

True True ->  False

  True False -> False

  False True -> False

  False False ->  True

I tried doing this:

if boolInput1 and boolInput2 == True:
    print(False)
elif boolInput1 == True and boolInput2 == False:
    print(False)
elif boolInput1 == False and boolInput2 == True:
    print(False)
elif boolInput1 and boolInput2 == False:
    print(True)

but it doesn't work as this is the output:

Test  Input    Expected Actual
1   True True   False   False
2   True False  False   False
3   False True  False   False
4   False False True    False

I've tried searching for an answer online but can't find anything.

Body:
elif boolInput1 and boolInput2 == False: isn't doing what you think it's doing.

Each side of the and are evaluated as separate booleans.

To condense what the computer is doing on that statement:

boolInput1 and boolInput2 == False
False and False == False
False and True
False #Does not enter if Statement

This should show you that your logic on all 4 is actually wrong and there are ways to mess it up. Try to avoid boolean == true kind of statements wherever possible, and just say if boolean

Working version:

if boolInput1 and boolInput2:
    print(False)
elif boolInput1 and not boolInput2:
    print(False)
elif not boolInput1 and boolInput2:
    print(False)
elif not boolInput1 and not boolInput2:
    print(True)

Though depending on your reason for this code, there are even more simple ways to do it.


问:
indexOf() function not working on arrays
I have two divs as shown below:

```<code><div class="container"></div>
<div class="container"></div>
</code>```

I created an array using these two divs:

```<code>var containers = document.querySelectorAll(".container");
</code>```

I also created a variable to represent the first div:

```<code>var div1 = document.querySelectorAll(".container")[0];
</code>```

When I use indexOf() to get the index of the first div in the array, I get an error:

containers.indexOf is not a function

Here is a snippet summarizing my problem:

var containers = document.querySelectorAll(".container");
var div1 = document.querySelectorAll(".container")[0];
containers.indexOf(div1); // returns the error```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container"></div>
<div class="container"></div></code>```

答: querySelectorAll returns a NodeList, not an array. You can convert the NodeList to an array by calling Array.from(...).

Body:
I have two divs as shown below:

I created an array using these two divs:

var containers = document.querySelectorAll(".container");

I also created a variable to represent the first div:

var div1 = document.querySelectorAll(".container")[0];

When I use indexOf() to get the index of the first div in the array, I get an error:

containers.indexOf is not a function

Here is a snippet summarizing my problem:

var containers = document.querySelectorAll(".container");
var div1 = document.querySelectorAll(".container")[0];
containers.indexOf(div1); // returns the error


问:
Accessing Oracle from Mainframe
I am looking for information about accessing data present in ORACLE from IBM Mainframe applications (Z/OS). The data is lying on Oracle which is on a separate server and the IBM Mainframe system, by using COBOL programs need to access the data from Oracle.
I heard that by using 'Oracle Access Manager for CICS' we can access Oracle data directly from IBM mainframe applications (using COBOL program). If yes, then are there any limitations/considerations on the Oracle version we are using ? I heard that the gateway 'Oracle Access Manager for CICS/IMS' is only supported in older versions of Oracle(i.e. 10g) but not in 11g or 12c ? Is Oracle still supporting 'Oracle Access Manager for CICS/IMS' ? Has anyone done this or do you have suggestions?

Thanks in advance for your help.
Sai

答:
There are a lot of ways this can be done, depending on how much data you're talking about and how real-time your needs are. If you're a commercial customer of Oracle's, you're probably paying them a bundle - don't hesitate to call and put the burden on Oracle to figure out the best way to do what you're trying to do.

Otherwise, IBM and other vendors have a variety of integration products that can help, if you don't mind using a vendor solution. One example is the IBM Integration Bus - it's pretty much an ESB that can connect to nearly any type of database (as well as REST services, etc) with client-side support on z/OS. There are plenty of similar services out there from other vendors such as Tibco.

If you want more of an open solution, we've had good luck with JDBC on z/OS, but this isn't particularly easy to connect to COBOL...it is possible to call Java from COBOL, but it's not the easiest thing for someone with limited mainframe experience, and you'll need to worry about things like ASCII vs. EBCDIC and so on. Still, it's basically free and fast, and the Oracle JDBC drivers run fine on z/OS.

If you just need to do read-only queries against Oracle, some people use an ETL approach to keep a reasonably up to date copy of your Oracle data on z/OS in (say) DB2. This can help prevent overloading your Oracle server and your network since your mainframe apps process locally on the mainframe instead of sending every transaction to your Oracle database in realtime. Informatica and SyncSort are two leading vendors in this space.

Finally, it does look like Oracle continues to support things like the Oracle Database Gateway for APPC, at least as of Oracle 12c. This would let you access Oracle over an APPC network without any sort of client library on z/OS. If your COBOL is running in CICS or another mainframe environment with good APPC support, it's not even very difficult to program. Of course, APPC is an old technology, and configuring SNA networking is definitely a dying skill in many sites...something to watch for.

Title: Accessing Oracle from Mainframe


问:
How can I parse Apache's error log in PHP?
I want to create a script that parses or makes sense of apache's error log to see what the most recent error was. I was wondering if anyone out there has something that does this or has any ideas where to start?</p>

答:
Here's a small-ish class that makes it easy to read a number of characters from the back of a large file w/o overloading memory.  The test setting lets you see it in action cannibalizing itself.</p>

```<code>BigFile.php
<?php
$run_test = true;
$test_file = 'BigFile.php';

class BigFile
{
private $file_handle;

/**
 *
 * Load the file from a filepath
 * @param string $path_to_file
 * @throws Exception if path cannot be read from
 */
public function __construct( $path_to_log )
{
    if( is_readable($path_to_log) )
    {
        $this->file_handle = fopen( $path_to_log, 'r');
    }
    else
    {
        throw new Exception("The file path to the file is not valid");
    }
}

/**
 *
 * 'Finish your breakfast' - Jay Z's homme Strict
 */
public function __destruct()
{
    fclose($this->file_handle);
}

/**
 *
 * Returns a number of characters from the end of a file w/o loading the entire file into memory
 * @param integer $number_of_characters_to_get
 * @return string $characters
 */
public function getFromEnd( $number_of_characters_to_get )
{
    $offset = -1*$number_of_characters_to_get;
    $text = "";

    fseek( $this->file_handle, $offset , SEEK_END);

    while(!feof($this->file_handle))
    {
        $text .= fgets($this->file_handle);
    }

    return $text;
}
}

if( $run_test )
{
$number_of_characters_to_get =  100000;
$bf = new BigFile($test_file);
$text = $bf->getFromEnd( $number_of_characters_to_get );
echo "$test_file has the following $number_of_characters_to_get characters at the end:
    <br/> ```$text```";
}

?>
</code>```

OwnerDisplayName: SeanDowney

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
Here's a small-ish class that makes it easy to read a number of characters from the back of a large file w/o overloading memory.  The test setting lets you see it in action cannibalizing itself.

BigFile.php
<?php
$run_test = true;
$test_file = 'BigFile.php';

class BigFile
{
private $file_handle;

/**
 *
 * Load the file from a filepath
 * @param string $path_to_file
 * @throws Exception if path cannot be read from
 */
public function __construct( $path_to_log )
{
    if( is_readable($path_to_log) )
    {
        $this->file_handle = fopen( $path_to_log, 'r');
    }
    else
    {
        throw new Exception("The file path to the file is not valid");
    }
}

/**
 *
 * 'Finish your breakfast' - Jay Z's homme Strict
 */
public function __destruct()
{
    fclose($this->file_handle);
}

/**
 *
 * Returns a number of characters from the end of a file w/o loading the entire file into memory
 * @param integer $number_of_characters_to_get
 * @return string $characters
 */
public function getFromEnd( $number_of_characters_to_get )
{
    $offset = -1*$number_of_characters_to_get;
    $text = "";

    fseek( $this->file_handle, $offset , SEEK_END);

    while(!feof($this->file_handle))
    {
        $text .= fgets($this->file_handle);
    }

    return $text;
}
}

if( $run_test )
{
$number_of_characters_to_get =  100000;
$bf = new BigFile($test_file);
$text = $bf->getFromEnd( $number_of_characters_to_get );
echo "$test_file has the following $number_of_characters_to_get characters at the end:
    <br/> <pre>$text</pre>";
}

?>


问:
Calculate the the value of all EvenChild elements javascript / php
I have this table, that holds 3 colums , name , price and remove button.
What It needs is a way to calculate the sum of all even childs from the TR parent (every second TD since its the one that contains the price).

I am assuming Javascript will do that but im not sure how its gonna address Even or Odd elements.
I've also thought about using CSS to add some type of markers for the Even or Odd elements and use these markers to guide js but this is beyond my current knowledge.

I searched a lot for a solution to this, but to no avail..
Something along the lines of -

```<code>function count() {

var oddchildren = document.getElementByID('#order-table').childNodes.OddchildNodes;
var result = oddchildren + oddchildren;
}
</code>```

I know this piece of code isnt even nearly proper, its just pseudo-code to represent the basic idea of what we need for the end result.

Here is the JS FIDDLE https://jsfiddle.net/x8usjfs6/

答:
window.addEventListener('DOMContentLoaded', () => {

  function calc() {
    // get the price elements
    let prices = document.querySelectorAll('.price');

    // turn them into an array and add up the prices
    let total = [].slice
      .call(prices)
      .reduce((prev, curr) => parseInt(curr.innerText) + prev, 0);

    // display the total
    document.querySelector('.total').innerHTML = total;
  }

  function remove(el) {
    // keep going up the tree until you find the row
    while (el.tagName !== "TR") {
      el = el.parentElement;
    }
    // remove the row
    el.remove();
  }

  // each time a button is clicked, remove a row and
  // recalculate the total
  function removeAndRecalc() {
    remove(this);
    calc();
  }

  // add click listeners to the remove buttons
  [].slice
    .call(document.querySelectorAll('.remove'))
    .forEach(el => el.addEventListener('click', removeAndRecalc));

  // calculate the total right off the bat
  calc();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.price:before {
  content: '$'
}

.total:before {
  content: '$'
}</code>```

<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>

      Item
      Price

      Engineering Suit Level I
      100
      <button class="remove">Remove</button>

      Engineering Suit Level I
      100
      <button class="remove">Remove</button>

      Standart Plasma Cutter
      120
      <button class="remove">Remove</button>

      Standart Plasma Cutter
      120
      <button class="remove">Remove</button>

      Total:

```

Body:
I have this table, that holds 3 colums , name , price and remove button.
What It needs is a way to calculate the sum of all even childs from the TR parent (every second TD since its the one that contains the price).

I am assuming Javascript will do that but im not sure how its gonna address Even or Odd elements.
I've also thought about using CSS to add some type of markers for the Even or Odd elements and use these markers to guide js but this is beyond my current knowledge.

I searched a lot for a solution to this, but to no avail..
Something along the lines of -

function count() {

var oddchildren = document.getElementByID('#order-table').childNodes.OddchildNodes;
var result = oddchildren + oddchildren;
}

I know this piece of code isnt even nearly proper, its just pseudo-code to represent the basic idea of what we need for the end result.

Here is the JS FIDDLE https://jsfiddle.net/x8usjfs6/

Body:
window.addEventListener('DOMContentLoaded', () => {

  function calc() {
    // get the price elements
    let prices = document.querySelectorAll('.price');

    // turn them into an array and add up the prices
    let total = [].slice
      .call(prices)
      .reduce((prev, curr) => parseInt(curr.innerText) + prev, 0);

    // display the total
    document.querySelector('.total').innerHTML = total;
  }

  function remove(el) {
    // keep going up the tree until you find the row
    while (el.tagName !== "TR") {
      el = el.parentElement;
    }
    // remove the row
    el.remove();
  }

  // each time a button is clicked, remove a row and
  // recalculate the total
  function removeAndRecalc() {
    remove(this);
    calc();
  }

  // add click listeners to the remove buttons
  [].slice
    .call(document.querySelectorAll('.remove'))
    .forEach(el => el.addEventListener('click', removeAndRecalc));

  // calculate the total right off the bat
  calc();
});

.price:before {
  content: '$'
}

.total:before {
  content: '$'
}

<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<table>
  <thead>
    <tr>
      <td>Item</td>
      <td>Price</td>
      <td></td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Engineering Suit Level I</td>
      <td class="price">100</td>
      <td><button class="remove">Remove</button></td>
    </tr>
    <tr>
      <td>Engineering Suit Level I</td>
      <td class="price">100</td>
      <td><button class="remove">Remove</button></td>
    </tr>
    <tr>
      <td>Standart Plasma Cutter</td>
      <td class="price">120</td>
      <td><button class="remove">Remove</button></td>
    </tr>
    <tr>
      <td>Standart Plasma Cutter</td>
      <td class="price">120</td>
      <td><button class="remove">Remove</button></td>
    </tr>
    <tr>
      <td>Total:</td>
      <td class="total"></td>
      <td></td>
    </tr>
  </tbody>
</table>


问:
Logging warnings in Django: filter not returning anything
I am trying to setup Django logging to log deprecation warnings. I normally wouldn't have a formatter like this or output it to console, that is just to test and show it is not working.

Here is my code:

```<code>def is_deprecated(record):
    if record.exc_info:
        exc_type, exc_value = record.exc_info[:2]
        print(exc_value)
        if isinstance(exc_value, DeprecationWarning) or isinstance(exc_value, PendingDeprecationWarning):
            return True
    return False

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'stuff': {
            'format': 'This works!'
        }
    },
    'filters': {
      'is_deprecated': {
          '()': 'django.utils.log.CallbackFilter',
          'callback': is_deprecated,
      },
    },
    'handlers': {
        'console': {
            'filters': ['is_deprecated'],
            'class': 'logging.StreamHandler',
            'formatter': 'stuff',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
}
</code>```

It should output "This works!" when it hits a deprecation warning however it won't. I am running python with these alerts on

python -Wd

So I can see the regular Django alert but I can't get the logger to detect them.

答:
Apparently, the you use the -Wd argument it displays the warning but is not treated as an exception (Django log only handles exceptions) you can change this behavior using warnings.simplefilter('error') in some initial part (like the settings.py, init.py, manage.py, etc.) or use the python -W error command

reference: https://docs.python.org/2/library/warnings.html#the-warnings-filter

Body:
I am trying to setup Django logging to log deprecation warnings. I normally wouldn't have a formatter like this or output it to console, that is just to test and show it is not working.

Here is my code:

def is_deprecated(record):
    if record.exc_info:
        exc_type, exc_value = record.exc_info[:2]
        print(exc_value)
        if isinstance(exc_value, DeprecationWarning) or isinstance(exc_value, PendingDeprecationWarning):
            return True
    return False

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'stuff': {
            'format': 'This works!'
        }
    },
    'filters': {
      'is_deprecated': {
          '()': 'django.utils.log.CallbackFilter',
          'callback': is_deprecated,
      },
    },
    'handlers': {
        'console': {
            'filters': ['is_deprecated'],
            'class': 'logging.StreamHandler',
            'formatter': 'stuff',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
}

It should output "This works!" when it hits a deprecation warning however it won't. I am running python with these alerts on

python -Wd

So I can see the regular Django alert but I can't get the logger to detect them.


问:
override default docker run from host with options/arguments
```<code>FROM alpine:3.5
CMD ["echo", "hello world"]
</code>```

So after building docker build -t hello . I can run hello by calling docker run hello and I get the output hello world.

Now let's assume I wish to run ls or sh - this is fine. But what I really want is to be able to pass arguments. e.g. ls -al, or even tail -f /dev/null to keep the container running without having to change the Dockerfile

How do I go about doing this? my attempt at exec mode fails miserably... docker run hello --cmd=["ls", "-al"]

答:
Q. But what I really want is to be able to pass arguments. e.g. ls -al, or even tail -f /dev/null to keep the container running without having to change the Dockerfile

This is just achieved with:

```<code> docker run -d hello tail -f /dev/null
</code>```

So the container is running in background, and it let you to execute arbitrary commands inside it:

```<code>docker exec <container-id> ls -la
</code>```

And, for example a shell:

```<code>docker exec -it <container-id> bash
</code>```

Also, I recommend  you what @BMitch says.

Body:
FROM alpine:3.5
CMD ["echo", "hello world"]

So after building docker build -t hello . I can run hello by calling docker run hello and I get the output hello world.

Now let's assume I wish to run ls or sh - this is fine. But what I really want is to be able to pass arguments. e.g. ls -al, or even tail -f /dev/null to keep the container running without having to change the Dockerfile

How do I go about doing this? my attempt at exec mode fails miserably... docker run hello --cmd=["ls", "-al"]

Body:
Q. But what I really want is to be able to pass arguments. e.g. ls -al, or even tail -f /dev/null to keep the container running without having to change the Dockerfile

This is just achieved with:

 docker run -d hello tail -f /dev/null

So the container is running in background, and it let you to execute arbitrary commands inside it:

docker exec <container-id> ls -la

And, for example a shell:

docker exec -it <container-id> bash

Also, I recommend  you what @BMitch says.


问:
How to run `AWS CLI` command within `aws lambda` function?
I would like to run aws cli command (actually aws s3 sync) from within the aws lambda function. How do I do that? Ideally in python, but javascript (or java) would work too.

Using python I tried achieving this by Creating a Deployment Package where i would have awscli as a python package, so that I can use it later.
However, the aws command is not available during lambda function execution, and only the awscli package is.

How can I:

either: make sure that I have awscli available to be called during lambda function execution?

or: construct a aws s3 sync call directly from python awscli library?

答: Look the project https://github.com/lucioveloso/cli2cloudformation and you will figure out how to wrapper the cli inside a lambda function.</p>


问:
nodejs How do I dynamically load resource javascript files
I have a resource loader JS file running on a nodejs server. I want to drop in a bunch of resource js files that the resource loader will load into an array on initialization.

```<code>    // resource loader js file
    var Resources = (function () {

    var resources = {};

    function Resources(){
    ... loading code here

    // example of use after loading
    resources[key].doStuff();
    }
})();
module.exports.Resources = Resources;
</code>```

In the same directory the developer can just drop in new resource.js files as needed.

```<code>// resource file
var ResourceA = (function () {

function ResourceA(){
... loading code here

// example of use after loading
  ResourceA.prototype.doStuff= function () {
        // do stuff
    };

})();
</code>```

答:
New and more simple:

Install

```<code>npm install eloader
</code>```

Usage

```<code>const eloader = require('eloader');
const db = require('db');

eloader.add('db', db)
       .add('list', [2,8]
       .run(__dirname + '\\routes\\');
</code>```

Git
https://github.com/augustoeliezer/eloader

Body:
I have a resource loader JS file running on a nodejs server. I want to drop in a bunch of resource js files that the resource loader will load into an array on initialization.

    // resource loader js file
    var Resources = (function () {

    var resources = {};

    function Resources(){
    ... loading code here

    // example of use after loading
    resources[key].doStuff();
    }
})();
module.exports.Resources = Resources;

In the same directory the developer can just drop in new resource.js files as needed.

// resource file
var ResourceA = (function () {

function ResourceA(){
... loading code here

// example of use after loading
  ResourceA.prototype.doStuff= function () {
        // do stuff
    };

})();

Body:
New and more simple:

Install

npm install eloader

Usage

const eloader = require('eloader');
const db = require('db');

eloader.add('db', db)
       .add('list', [2,8]
       .run(__dirname + '\\routes\\');

Git
https://github.com/augustoeliezer/eloader


问:
Updating a data attribute of a TR with jQuery
I have read many of the answers and I am still not quite sure how to update an attribute of a TR.  The idea of my code is to combine similar rows into one while updating the first row's data-auditidentity attribute.

What in the blue blazes am I missing??  The end result should be one table row for procedure and the data-auditidentity property should have all four comma separated keys.  Trying to update using attr to have all four values comma separated fails.

var uniqueKeys = [];
var resultsTable = $('#results');
$(resultsTable).find('tbody > tr').each(function() {

  var tableName = $(this).find('td:eq(0)').text();
  var tableAction = $(this).find('td:eq(1)').text();
  var uniqueKey = tableName + '#' + tableAction;

  if (uniqueKeys.indexOf(uniqueKey) < 0) {
    uniqueKeys.push(uniqueKey);
  } else {

    var initValue = '',
      newCombinedValues = '',
      auditidentity = '';
    initValue = $(resultsTable).find(" tr td:first-child:contains(" + tableName + ")").parent().attr('data-auditidentity');

    var activityLogId = $(this).data('activitylogid');
    auditidentity = $(this).data('auditidentity');

    newCombinedValues = initValue + "," + auditidentity;

    $(resultsTable).find("tbody tr td:first:contains(" + tableName + ")").parent().attr('data-auditidentity', newCombinedValues);

    // After we have what we need, remove the combined row as we are combining the keys into one row
    //$(this).remove();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results">
<tbody role="alert" aria-live="polite" aria-relevant="all" data-auditidentity="18487179,18487183">
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
    <td class="  sorting_1">Selection</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487181" data-auditid="a2768380-8c4a-4070-9834-900f95db77a2">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487182" data-auditid="cb54deca-2bc4-4b71-ba5a-0e6d075b7b26">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487183" data-auditid="05803858-aaba-4f9b-9128-fc0c265cfaf6">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
</tbody></table></code>```

The END RESULT SHOULD BE THIS

```<code><table id="results">
<tbody role="alert" aria-live="polite" aria-relevant="all" data-auditidentity="18487179,18487183">
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
    <td class="  sorting_1">Selection</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179,18487181,18487182,18487183" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
</tbody></table>
</code>```

答:
The problem is the selector $(resultsTable).find("tbody tr td:first:contains(" + tableName + ")"). :first means to select the first td in the whole document, not the first td in each row. This should be :first-child. Then you need to use :first after that to select the first of all these in the document. So the whole selector should be resultsTable.find("tbody tr td:first-child:contains(" + tableName + "):first")

BTW, you don't need to wrap resultsTable in $(). It's already a jQuery object.

var uniqueKeys = [];
var resultsTable = $('#results');
$(resultsTable).find('tbody > tr').each(function() {

  var tableName = $(this).find('td:eq(0)').text();
  var tableAction = $(this).find('td:eq(1)').text();
  var uniqueKey = tableName + '#' + tableAction;

  if (uniqueKeys.indexOf(uniqueKey) < 0) {
    uniqueKeys.push(uniqueKey);
  } else {

    var initValue = '',
      newCombinedValues = '',
      auditidentity = '';
    initValue = resultsTable.find(" tr td:first-child:contains(" + tableName + ")").parent().attr('data-auditidentity');

    var activityLogId = $(this).data('activitylogid');
    auditidentity = $(this).data('auditidentity');

    newCombinedValues = initValue + "," + auditidentity;

    resultsTable.find("tbody tr td:first-child:contains(" + tableName + "):first").parent().attr('data-auditidentity', newCombinedValues);

    // After we have what we need, remove the combined row as we are combining the keys into one row
    //$(this).remove();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results">
<tbody role="alert" aria-live="polite" aria-relevant="all" data-auditidentity="18487179,18487183">
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
    <td class="  sorting_1">Selection</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487181" data-auditid="a2768380-8c4a-4070-9834-900f95db77a2">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487182" data-auditid="cb54deca-2bc4-4b71-ba5a-0e6d075b7b26">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487183" data-auditid="05803858-aaba-4f9b-9128-fc0c265cfaf6">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
</tbody></table></code>```

Body:
I have read many of the answers and I am still not quite sure how to update an attribute of a TR.  The idea of my code is to combine similar rows into one while updating the first row's data-auditidentity attribute.

What in the blue blazes am I missing??  The end result should be one table row for procedure and the data-auditidentity property should have all four comma separated keys.  Trying to update using attr to have all four values comma separated fails.

var uniqueKeys = [];
var resultsTable = $('#results');
$(resultsTable).find('tbody > tr').each(function() {

  var tableName = $(this).find('td:eq(0)').text();
  var tableAction = $(this).find('td:eq(1)').text();
  var uniqueKey = tableName + '#' + tableAction;

  if (uniqueKeys.indexOf(uniqueKey) < 0) {
    uniqueKeys.push(uniqueKey);
  } else {

    var initValue = '',
      newCombinedValues = '',
      auditidentity = '';
    initValue = $(resultsTable).find(" tr td:first-child:contains(" + tableName + ")").parent().attr('data-auditidentity');

    var activityLogId = $(this).data('activitylogid');
    auditidentity = $(this).data('auditidentity');

    newCombinedValues = initValue + "," + auditidentity;

    $(resultsTable).find("tbody tr td:first:contains(" + tableName + ")").parent().attr('data-auditidentity', newCombinedValues);

    // After we have what we need, remove the combined row as we are combining the keys into one row
    //$(this).remove();
  }
});

    Selection
    Update

    Procedure
    Update

    Procedure
    Update

    Procedure
    Update

    Procedure
    Update

The END RESULT SHOULD BE THIS

    Selection
    Update

    Procedure
    Update

Body:
The problem is the selector $(resultsTable).find("tbody tr td:first:contains(" + tableName + ")"). :first means to select the first td in the whole document, not the first td in each row. This should be :first-child. Then you need to use :first after that to select the first of all these in the document. So the whole selector should be resultsTable.find("tbody tr td:first-child:contains(" + tableName + "):first")

BTW, you don't need to wrap resultsTable in $(). It's already a jQuery object.

var uniqueKeys = [];
var resultsTable = $('#results');
$(resultsTable).find('tbody > tr').each(function() {

  var tableName = $(this).find('td:eq(0)').text();
  var tableAction = $(this).find('td:eq(1)').text();
  var uniqueKey = tableName + '#' + tableAction;

  if (uniqueKeys.indexOf(uniqueKey) < 0) {
    uniqueKeys.push(uniqueKey);
  } else {

    var initValue = '',
      newCombinedValues = '',
      auditidentity = '';
    initValue = resultsTable.find(" tr td:first-child:contains(" + tableName + ")").parent().attr('data-auditidentity');

    var activityLogId = $(this).data('activitylogid');
    auditidentity = $(this).data('auditidentity');

    newCombinedValues = initValue + "," + auditidentity;

    resultsTable.find("tbody tr td:first-child:contains(" + tableName + "):first").parent().attr('data-auditidentity', newCombinedValues);

    // After we have what we need, remove the combined row as we are combining the keys into one row
    //$(this).remove();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results">
<tbody role="alert" aria-live="polite" aria-relevant="all" data-auditidentity="18487179,18487183">
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
    <td class="  sorting_1">Selection</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487181" data-auditid="a2768380-8c4a-4070-9834-900f95db77a2">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487182" data-auditid="cb54deca-2bc4-4b71-ba5a-0e6d075b7b26">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487183" data-auditid="05803858-aaba-4f9b-9128-fc0c265cfaf6">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
</tbody></table>


问:
PhoneGap upload Image to server on form submit
I am facing problem here as in phonegap image is uploaded to the server once u select a picture.I don't want to upload image before submitting form. Image is uploaded automatically to server which is something i don't want.I want to upload image with the form, where form contains many more fields which is required to send along with image.  What are the possible ways to submit with form?  </p>

```<code><!DOCTYPE HTML >
<html>
<head>
<title>Registration Form</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<script type="text/javascript" charset="utf-8">

    // Wait for PhoneGap to load
    document.addEventListener("deviceready", onDeviceReady, false);

    // PhoneGap is ready
    function onDeviceReady() {
// Do cool things here...
    }

    function getImage() {
        // Retrieve image file location from specified source
        navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});}
    function uploadPhoto(imageURI) {
        var options = new FileUploadOptions();
        options.fileKey="file";
        options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
        options.mimeType="image/jpeg";

        var params = new Object();
        params.value1 = "test";
        params.value2 = "param";

        options.params = params;
        options.chunkedMode = false;

        var ft = new FileTransfer();
        ft.upload(imageURI, "http://yourdomain.com/upload.php", win, fail, options);
    }

    function win(r) {
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
        alert(r.response);
    }

    function fail(error) {
        alert("An error has occurred: Code = " = error.code);
    }

    </script>
</head>
<body>
<form id="regform">
<button onclick="getImage();">select Avatar<button>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="text" id="workPlace" name="workPlace" class="" />
<input type="submit" id="btnSubmit" value="Submit" />
</form>
</body>
</html>
</code>```

答:
I could not get these plugins to upload a file with the other answers.

The problem seemed to stem from the FileTransfer plugin, which states:

fileURL: Filesystem URL representing the file on the device or a data URI.

But that did not appear to work properly for me.  Instead I needed to use the File plugin to create a temporary file using the data uri to get me a blob object: in their example, writeFile is a function which takes a fileEntry (returned by createFile) and dataObj (blob).  Once the file is written, its path can be retrieved and passed to the FileTransfer instance.  Seems like an awful lot of work, but at least it's now uploading.

Body:
I am facing problem here as in phonegap image is uploaded to the server once u select a picture.I don't want to upload image before submitting form. Image is uploaded automatically to server which is something i don't want.I want to upload image with the form, where form contains many more fields which is required to send along with image.  What are the possible ways to submit with form?

<!DOCTYPE HTML >

<title>Registration Form</title>

<form id="regform">
<button onclick="getImage();">select Avatar<button>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="text" id="workPlace" name="workPlace" class="" />
<input type="submit" id="btnSubmit" value="Submit" />
</form>


答:
Queryselectorall returns non-live node list. The indexOf method is not defined on that. More info is here

https://developer.mozilla.org/en-US/docs/Web/API/NodeList

You could use Array.from() to convert to array and then use indexOf

Title: indexOf() function not working on arrays


问:
Why aren't my animation keyframes triggering on hover?
Description:

I can't figure out why the items with the class .specialItem's animation wont trigger. If you can figure out why, that would be great. The background / border changes no hover but it won't fade in like it should.

$(window).on("resize", function() {
    var itemPercent = $("#percent");
    var itemCE = $("#ce");
    var itemC = $("#c");
    var itemDEL = $("#del");
    var itemDivide = $("#divide");
    var itemRoot = $("#squareRoot");
    var itemSeven = $("#seven");
    var itemEight = $("#eight");
    var itemNine = $("#nine");
    var itemMultiply = $("#multiply");
    var itemSupTwo = $("#supTwo");
    var itemFour = $("#four");
    var itemFive = $("#five");
    var itemSix = $("#six");
    var itemMinus = $("#minus");
    var itemSupThree = $("#supThree");
    var itemOne = $("#one");
    var itemTwo = $("#two");
    var itemThree = $("#three");
    var itemPlus = $("#plus");
    var itemUnSymbol = $("#unknownSymbol");
    var itemPosNeg = $("#posNeg");
    var itemZero = $("#zero");
    var itemDecimal = $("#decimal");
    var itemEquals = $("#equals");

    var defaultHeightCalc = $(window).height() - $(".output").height() - $(".special").height();
    $(".default").css("height", defaultHeightCalc);

    var itemHeightCalc = ($(".default").height() / 5 - 13);
    var itemWidthCalc = ($(".default").width() / 5 - 10);
    $(".item").css({
        "height": itemHeightCalc,
        "width": itemWidthCalc
    });
    $(".itemIconAlign").css("top", ($(".item").height() / 2) - ($(".itemIconAlign").height() / 2));
}).resize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Pacifico|Oxygen);
body {
    background: #EEEEEE;
    overflow: hidden;
}
.wrapper {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
}
.storage {
    height: 100%;
    width: 19%;
    position: absolute;
    top: 0px;
    right: 0px;
}
.main {
    height: 100%;
    width: 81%;
    position: absolute;
    top: 0px;
    left: 0px;
}
.output {
    height: 25%;
    width: 100%;
    position: relative;
    top: 0px;
    left: 0px;
    font-family: 'Roboto', sans-serif;
    font-weight: 900;
    font-size: 104px;
    text-align: right;
}
.numLineAlign {
    position: relative;
    top: 30%;
    right: 0px;
    width: 100%;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.input {
    width: 100%;
    position: relative;
    top: 0%;
    left: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.special {
    height: 50px;
    width: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
}
.default {
    width: 100%;
    position: absolute;
    top: 50px;
    left: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.storageNav {
    height: 70px;
    width: 100%;
    position: relative;
    top: 0px;
    right: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.storageTab {
    height: 25%;
    position: relative;
    top: 25%;
    left: 0px;
    color: black;
    text-align: center;
    padding: 20px;
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-weight: 600;
    cursor: default;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.item {
    text-align: center;
    background: white;
    display: inline-block;
    margin: 2px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor: pointer;
    min-height: 50px;
}
.item:hover {
    -webkit-filter: brightness(80%);
    filter: brightness(80%);
}
#percent, #ce, #c, #del, #divide, #decimal, #minus, #plus, #equals,
#squareRoot, #supTwo, #supThree, #unknownSymbol, #posNeg, #multiply {
    background: #E0E0E0;
    font-family: 'Raleway', sans-serif;
    font-weight: 400;
    font-size: 20px;
}
#one, #two, #three, #four, #five,
#six, #seven, #eight, #nine, #zero {
    font-family: 'Raleway', sans-serif;
    font-weight: 800;
    font-size: 20px;
}
.itemIconAlign {
    position: relative;
    left: 0px;
}
.specialItem {
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-weight: 800;
    font-size: 12px;
    text-align: center;
    padding: 25px;
    margin-top: -23px;
    cursor: pointer;
    border: 2px solid transparent;
}
.specialItem:hover {
    background: #E0E0E0;
    border: 2px solid white;
    animation: fade 1s;
}
@keyframes fade {
    0% {
        background: #E0E0E0;
        border: 2px solid white;
    }
    100% {
        background: #E0E0E0;
        border: 2px solid white;
    }
}</code>```

History

Memory

                0

MC

MR

M+

M-

MS

%

CE

C

DEL

÷

√

7

8

9

*

x2

4

5

6

-

x3

1

2

3

+

1/x

±

0

●

=

```

答:
It is working! (In Chrome at least)

The problem is that the animation doesn't change anything, rather the animation's @keyframes are the exact same as the values that are set in the :hover.

I changed the keyframe's value to display the difference.

$(window).on("resize", function() {
    var itemPercent = $("#percent");
    var itemCE = $("#ce");
    var itemC = $("#c");
    var itemDEL = $("#del");
    var itemDivide = $("#divide");
    var itemRoot = $("#squareRoot");
    var itemSeven = $("#seven");
    var itemEight = $("#eight");
    var itemNine = $("#nine");
    var itemMultiply = $("#multiply");
    var itemSupTwo = $("#supTwo");
    var itemFour = $("#four");
    var itemFive = $("#five");
    var itemSix = $("#six");
    var itemMinus = $("#minus");
    var itemSupThree = $("#supThree");
    var itemOne = $("#one");
    var itemTwo = $("#two");
    var itemThree = $("#three");
    var itemPlus = $("#plus");
    var itemUnSymbol = $("#unknownSymbol");
    var itemPosNeg = $("#posNeg");
    var itemZero = $("#zero");
    var itemDecimal = $("#decimal");
    var itemEquals = $("#equals");

    var defaultHeightCalc = $(window).height() - $(".output").height() - $(".special").height();
    $(".default").css("height", defaultHeightCalc);

    var itemHeightCalc = ($(".default").height() / 5 - 13);
    var itemWidthCalc = ($(".default").width() / 5 - 10);
    $(".item").css({ "height" : itemHeightCalc, "width" : itemWidthCalc });
    $(".itemIconAlign").css("top", ($(".item").height() / 2) - ($(".itemIconAlign").height() / 2));
   }).resize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Pacifico|Oxygen);

body {
background: #EEEEEE;
overflow: hidden;
}

.wrapper {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}

.storage {
height: 100%;
width: 19%;
position: absolute;
top: 0px;
right: 0px;
}

.main {
height: 100%;
width: 81%;
position: absolute;
top: 0px;
left: 0px;
}

.output {
height: 25%;
width: 100%;
position: relative;
top: 0px;
left: 0px;
font-family: 'Roboto', sans-serif;
font-weight: 900;
font-size: 104px;
text-align: right;
}

.numLineAlign {
position: relative;
top: 30%;
right: 0px;
width: 100%;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.input {
width: 100%;
position: relative;
top: 0%;
left: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.special {
height: 50px;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
}

.default {
width: 100%;
position: absolute;
top: 50px;
left: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.storageNav {
height: 70px;
width: 100%;
position: relative;
top: 0px;
right: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.storageTab {
height: 25%;
position: relative;
top: 25%;
left: 0px;
color: black;
text-align: center;
padding: 20px;
display: inline-block;
font-family: 'Raleway', sans-serif;
font-weight: 600;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.item {
text-align: center;
background: white;
display: inline-block;
margin: 2px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
min-height: 50px;
}

.item:hover {
-webkit-filter: brightness(80%);
filter: brightness(80%);
}

#percent, #ce, #c, #del, #divide, #decimal, #minus, #plus, #equals, #squareRoot, #supTwo, #supThree, #unknownSymbol, #posNeg, #multiply {
background: #E0E0E0;
font-family: 'Raleway', sans-serif;
font-weight: 400;
font-size: 20px;
}

#one, #two, #three, #four, #five, #six, #seven, #eight, #nine, #zero {
font-family: 'Raleway', sans-serif;
font-weight: 800;
font-size: 20px;
}

.itemIconAlign {
position: relative;
left: 0px;
}

.specialItem {
display: inline-block;
font-family: 'Raleway', sans-serif;
font-weight: 800;
font-size: 12px;
text-align: center;
padding: 25px;
margin-top: -23px;
cursor: pointer;
border: 2px solid transparent;
}

.specialItem:hover {
animation: fade 1s;
}

@keyframes fade {
0% {background: transparent; border: 2px solid transparent;}
100% {background: #E0E0E0; border: 2px solid white;}
}</code>```

History

Memory

        0

MC

MR

M+

M-

MS

%

CE

C

DEL

÷

√

7

8

9

*

x2

4

5

6

-

x3

1

2

3

+

1/x

±

0

●

=

```

Body:
Description:

I can't figure out why the items with the class .specialItem's animation wont trigger. If you can figure out why, that would be great. The background / border changes no hover but it won't fade in like it should.

$(window).on("resize", function() {
    var itemPercent = $("#percent");
    var itemCE = $("#ce");
    var itemC = $("#c");
    var itemDEL = $("#del");
    var itemDivide = $("#divide");
    var itemRoot = $("#squareRoot");
    var itemSeven = $("#seven");
    var itemEight = $("#eight");
    var itemNine = $("#nine");
    var itemMultiply = $("#multiply");
    var itemSupTwo = $("#supTwo");
    var itemFour = $("#four");
    var itemFive = $("#five");
    var itemSix = $("#six");
    var itemMinus = $("#minus");
    var itemSupThree = $("#supThree");
    var itemOne = $("#one");
    var itemTwo = $("#two");
    var itemThree = $("#three");
    var itemPlus = $("#plus");
    var itemUnSymbol = $("#unknownSymbol");
    var itemPosNeg = $("#posNeg");
    var itemZero = $("#zero");
    var itemDecimal = $("#decimal");
    var itemEquals = $("#equals");

    var defaultHeightCalc = $(window).height() - $(".output").height() - $(".special").height();
    $(".default").css("height", defaultHeightCalc);

    var itemHeightCalc = ($(".default").height() / 5 - 13);
    var itemWidthCalc = ($(".default").width() / 5 - 10);
    $(".item").css({
        "height": itemHeightCalc,
        "width": itemWidthCalc
    });
    $(".itemIconAlign").css("top", ($(".item").height() / 2) - ($(".itemIconAlign").height() / 2));
}).resize();

@import url(https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Pacifico|Oxygen);
body {
    background: #EEEEEE;
    overflow: hidden;
}
.wrapper {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
}
.storage {
    height: 100%;
    width: 19%;
    position: absolute;
    top: 0px;
    right: 0px;
}
.main {
    height: 100%;
    width: 81%;
    position: absolute;
    top: 0px;
    left: 0px;
}
.output {
    height: 25%;
    width: 100%;
    position: relative;
    top: 0px;
    left: 0px;
    font-family: 'Roboto', sans-serif;
    font-weight: 900;
    font-size: 104px;
    text-align: right;
}
.numLineAlign {
    position: relative;
    top: 30%;
    right: 0px;
    width: 100%;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.input {
    width: 100%;
    position: relative;
    top: 0%;
    left: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.special {
    height: 50px;
    width: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
}
.default {
    width: 100%;
    position: absolute;
    top: 50px;
    left: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.storageNav {
    height: 70px;
    width: 100%;
    position: relative;
    top: 0px;
    right: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.storageTab {
    height: 25%;
    position: relative;
    top: 25%;
    left: 0px;
    color: black;
    text-align: center;
    padding: 20px;
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-weight: 600;
    cursor: default;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.item {
    text-align: center;
    background: white;
    display: inline-block;
    margin: 2px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor: pointer;
    min-height: 50px;
}
.item:hover {
    -webkit-filter: brightness(80%);
    filter: brightness(80%);
}
#percent, #ce, #c, #del, #divide, #decimal, #minus, #plus, #equals,
#squareRoot, #supTwo, #supThree, #unknownSymbol, #posNeg, #multiply {
    background: #E0E0E0;
    font-family: 'Raleway', sans-serif;
    font-weight: 400;
    font-size: 20px;
}
#one, #two, #three, #four, #five,
#six, #seven, #eight, #nine, #zero {
    font-family: 'Raleway', sans-serif;
    font-weight: 800;
    font-size: 20px;
}
.itemIconAlign {
    position: relative;
    left: 0px;
}
.specialItem {
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-weight: 800;
    font-size: 12px;
    text-align: center;
    padding: 25px;
    margin-top: -23px;
    cursor: pointer;
    border: 2px solid transparent;
}
.specialItem:hover {
    background: #E0E0E0;
    border: 2px solid white;
    animation: fade 1s;
}
@keyframes fade {
    0% {
        background: #E0E0E0;
        border: 2px solid white;
    }
    100% {
        background: #E0E0E0;
        border: 2px solid white;
    }
}

History

Memory

                0

MC

MR

M+

M-

MS

%

CE

C

DEL

÷

√

7

8

9

*

x2

4

5

6

-

x3

1

2

3

+

1/x

±

0

●

=

Body:
It is working! (In Chrome at least)

The problem is that the animation doesn't change anything, rather the animation's @keyframes are the exact same as the values that are set in the :hover.

I changed the keyframe's value to display the difference.

$(window).on("resize", function() {
    var itemPercent = $("#percent");
    var itemCE = $("#ce");
    var itemC = $("#c");
    var itemDEL = $("#del");
    var itemDivide = $("#divide");
    var itemRoot = $("#squareRoot");
    var itemSeven = $("#seven");
    var itemEight = $("#eight");
    var itemNine = $("#nine");
    var itemMultiply = $("#multiply");
    var itemSupTwo = $("#supTwo");
    var itemFour = $("#four");
    var itemFive = $("#five");
    var itemSix = $("#six");
    var itemMinus = $("#minus");
    var itemSupThree = $("#supThree");
    var itemOne = $("#one");
    var itemTwo = $("#two");
    var itemThree = $("#three");
    var itemPlus = $("#plus");
    var itemUnSymbol = $("#unknownSymbol");
    var itemPosNeg = $("#posNeg");
    var itemZero = $("#zero");
    var itemDecimal = $("#decimal");
    var itemEquals = $("#equals");

    var defaultHeightCalc = $(window).height() - $(".output").height() - $(".special").height();
    $(".default").css("height", defaultHeightCalc);

    var itemHeightCalc = ($(".default").height() / 5 - 13);
    var itemWidthCalc = ($(".default").width() / 5 - 10);
    $(".item").css({ "height" : itemHeightCalc, "width" : itemWidthCalc });
    $(".itemIconAlign").css("top", ($(".item").height() / 2) - ($(".itemIconAlign").height() / 2));
   }).resize();

@import url(https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Pacifico|Oxygen);

body {
background: #EEEEEE;
overflow: hidden;
}

.wrapper {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}

.storage {
height: 100%;
width: 19%;
position: absolute;
top: 0px;
right: 0px;
}

.main {
height: 100%;
width: 81%;
position: absolute;
top: 0px;
left: 0px;
}

.output {
height: 25%;
width: 100%;
position: relative;
top: 0px;
left: 0px;
font-family: 'Roboto', sans-serif;
font-weight: 900;
font-size: 104px;
text-align: right;
}

.numLineAlign {
position: relative;
top: 30%;
right: 0px;
width: 100%;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.input {
width: 100%;
position: relative;
top: 0%;
left: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.special {
height: 50px;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
}

.default {
width: 100%;
position: absolute;
top: 50px;
left: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.storageNav {
height: 70px;
width: 100%;
position: relative;
top: 0px;
right: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.storageTab {
height: 25%;
position: relative;
top: 25%;
left: 0px;
color: black;
text-align: center;
padding: 20px;
display: inline-block;
font-family: 'Raleway', sans-serif;
font-weight: 600;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.item {
text-align: center;
background: white;
display: inline-block;
margin: 2px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
min-height: 50px;
}

.item:hover {
-webkit-filter: brightness(80%);
filter: brightness(80%);
}

#percent, #ce, #c, #del, #divide, #decimal, #minus, #plus, #equals, #squareRoot, #supTwo, #supThree, #unknownSymbol, #posNeg, #multiply {
background: #E0E0E0;
font-family: 'Raleway', sans-serif;
font-weight: 400;
font-size: 20px;
}

#one, #two, #three, #four, #five, #six, #seven, #eight, #nine, #zero {
font-family: 'Raleway', sans-serif;
font-weight: 800;
font-size: 20px;
}

.itemIconAlign {
position: relative;
left: 0px;
}

.specialItem {
display: inline-block;
font-family: 'Raleway', sans-serif;
font-weight: 800;
font-size: 12px;
text-align: center;
padding: 25px;
margin-top: -23px;
cursor: pointer;
border: 2px solid transparent;
}

.specialItem:hover {
animation: fade 1s;
}

@keyframes fade {
0% {background: transparent; border: 2px solid transparent;}
100% {background: #E0E0E0; border: 2px solid white;}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
     <div class="storage">
      <div class="storageNav">
       <div class="storageTab">History</div>
       <div class="storageTab">Memory</div>
      </div>
      <div class="storageBox">

      </div>
     </div>
     <div class="main">
      <div class="output">
       <div class="numLineAlign">
        0
       </div>
      </div>
      <div class="input">
        <div class="special">
         <div class="specialItem" id="memClean">MC</div>
         <div class="specialItem" id="memRead">MR</div>
         <div class="specialItem" id="memAdd">M+</div>
         <div class="specialItem" id="memRemove">M-</div>
         <div class="specialItem" id="memStore">MS</div>
        </div>
        <div class="default">
         <div class="row" id="r1">
          <div class="item" id="percent">
           <div class="itemIconAlign">%</div>
          </div>

          <div class="item" id="ce">
           <div class="itemIconAlign">CE</div>
          </div>

          <div class="item" id="c">
           <div class="itemIconAlign">C</div>
          </div>

          <div class="item" id="del">
           <div class="itemIconAlign">DEL</div>
          </div>

          <div class="item" id="divide">
           <div class="itemIconAlign">÷</div>
          </div>
         </div>
         <div class="row" id="r2">
          <div class="item" id="squareRoot">
           <div class="itemIconAlign">√</div>
          </div>

          <div class="item" id="seven">
           <div class="itemIconAlign">7</div>
          </div>

          <div class="item" id="eight">
           <div class="itemIconAlign">8</div>
          </div>

          <div class="item" id="nine">
           <div class="itemIconAlign">9</div>
          </div>

          <div class="item" id="multiply">
           <div class="itemIconAlign">*</div>
          </div>
         </div>
         <div class="row" id="r3">
          <div class="item" id="supTwo">
           <div class="itemIconAlign">x<sup>2</sup></div>
          </div>

          <div class="item" id="four">
           <div class="itemIconAlign">4</div>
          </div>

          <div class="item" id="five">
           <div class="itemIconAlign">5</div>
          </div>

          <div class="item" id="six">
           <div class="itemIconAlign">6</div>
          </div>

          <div class="item" id="minus">
           <div class="itemIconAlign">-</div>
          </div>
         </div>
         <div class="row" id="r4">
          <div class="item" id="supThree">
           <div class="itemIconAlign">x<sup>3</sup></div>
          </div>

          <div class="item" id="one">
           <div class="itemIconAlign">1</div>
          </div>

          <div class="item" id="two">
           <div class="itemIconAlign">2</div>
          </div>

          <div class="item" id="three">
           <div class="itemIconAlign">3</div>
          </div>

          <div class="item" id="plus">
           <div class="itemIconAlign">+</div>
          </div>
         </div>
         <div class="row" id="r5">
          <div class="item" id="unknownSymbol">
           <div class="itemIconAlign"><sup>1</sup>/x</div>
          </div>

          <div class="item" id="posNeg">
           <div class="itemIconAlign">±</div>
          </div>

          <div class="item" id="zero">
           <div class="itemIconAlign">0</div>
          </div>

          <div class="item" id="decimal">
           <div class="itemIconAlign">●</div>
          </div>

          <div class="item" id="equals">
           <div class="itemIconAlign">=</div>
          </div>
         </div>
        </div>
      </div>
     </div>
  </div>