问:
How to merge two rectangles given arrays of their coordinates?
Say I have two arrays of coordinates (x,y) of two rectangles, for example [(0, 0), (0, 1), (2, 1), (2, 0)] and [(1, 0), (1, 2), (3, 2), (3, 0)], how would I merge these two coordinate arrays into one array that represents the resulting polygon?

It might look like this, graphically:

```<code>   _ _
 _|_  |
|_|_|_|
</code>```

to

```<code>   _ _
 _|   |
|_ _ _|
</code>```

with resulting array [(0, 0), (0, 1), (1, 1), (1, 2), (3, 2), (3, 0)].

I'm trying to design some sort of merge algorithm but I'm not sure where to get started.

For input, there will be two arrays, and this method will return one merged array.

I'm just totally lost on where to start.

答:
There are many degrees of freedom regaring the approaches and actual implementation here. Some relevant questions to consider, just from the tip of my head:

Are the coordinates always integers?

Are the input shapes always (axis-aligned) rectangles?

Do the rectangles always overlap?

Are the points always at different coordinates?

Are the edges never equal?

...

In some cases (if the first three questions are answered with "Yes"), you could probably go for a technically very simple approach: Just consider the whole input as a "grid", where the rectanges define the grid cells that are "filled", and in the end, return the border of the filled area.

If the answer to one of them may be "No", then you're opening a can of worms, with many, many subtleties.

Fortunately, the people at Sun/Oracle have worked this out pretty well, and there may still be a simple solution even for very complex problems: You can convert the input into shapes, and then use the Area#add method to compute the merged shape.

This is implemented in this example. But note that this is not very efficient, compared to, say, the grid-based approach that could be used for simpler cases. And it still leaves the question open about what should happen for non-overlapping rectangles. However, at least for the given inputs, the result is the expected one:

```<code>import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RectangleMerge {

    public static void main(String[] args) {
        List<Point2D> pointsA = Arrays.asList(new Point(0, 0), new Point(0, 1), new Point(2, 1), new Point(2, 0));
        List<Point2D> pointsB = Arrays.asList(new Point(1, 0), new Point(1, 2), new Point(3, 2), new Point(3, 0));

        System.out.println(merge(pointsA, pointsB));
    }

    private static List<Point2D> merge(List<? extends Point2D> pointsA, List<? extends Point2D> pointsB) {
        Area aa = new Area(toShape(pointsA));
        aa.add(new Area(toShape(pointsB)));
        return toPoints(aa);
    }

    private static Shape toShape(List<? extends Point2D> points) {
        Path2D path = new Path2D.Double();
        for (int i = 0; i < points.size(); i++) {
            Point2D p = points.get(i);
            if (i == 0) {
                path.moveTo(p.getX(), p.getY());
            } else {
                path.lineTo(p.getX(), p.getY());
            }
        }
        path.closePath();
        return path;
    }

    private static List<Point2D> toPoints(Shape shape) {
        List<Point2D> result = new ArrayList<Point2D>();
        PathIterator pi = shape.getPathIterator(null, 0.0);
        double[] coords = new double[6];
        while (!pi.isDone()) {
            int segment = pi.currentSegment(coords);
            switch (segment) {
            case PathIterator.SEG_MOVETO:
            case PathIterator.SEG_LINETO:
                result.add(new Point2D.Double(coords[0], coords[1]));
                break;
            }
            pi.next();
        }
        return result;
    }

}
</code>```

Body:
Say I have two arrays of coordinates (x,y) of two rectangles, for example [(0, 0), (0, 1), (2, 1), (2, 0)] and [(1, 0), (1, 2), (3, 2), (3, 0)], how would I merge these two coordinate arrays into one array that represents the resulting polygon?

It might look like this, graphically:

   _ _
 _|_  |
|_|_|_|

to

   _ _
 _|   |
|_ _ _|

with resulting array [(0, 0), (0, 1), (1, 1), (1, 2), (3, 2), (3, 0)].

I'm trying to design some sort of merge algorithm but I'm not sure where to get started.

For input, there will be two arrays, and this method will return one merged array.

I'm just totally lost on where to start.

Body:
There are many degrees of freedom regaring the approaches and actual implementation here. Some relevant questions to consider, just from the tip of my head:

Are the coordinates always integers?

Are the input shapes always (axis-aligned) rectangles?

Do the rectangles always overlap?

Are the points always at different coordinates?

Are the edges never equal?

...

In some cases (if the first three questions are answered with "Yes"), you could probably go for a technically very simple approach: Just consider the whole input as a "grid", where the rectanges define the grid cells that are "filled", and in the end, return the border of the filled area.

If the answer to one of them may be "No", then you're opening a can of worms, with many, many subtleties.

Fortunately, the people at Sun/Oracle have worked this out pretty well, and there may still be a simple solution even for very complex problems: You can convert the input into shapes, and then use the Area#add method to compute the merged shape.

This is implemented in this example. But note that this is not very efficient, compared to, say, the grid-based approach that could be used for simpler cases. And it still leaves the question open about what should happen for non-overlapping rectangles. However, at least for the given inputs, the result is the expected one:

import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RectangleMerge {

    public static void main(String[] args) {
        List<Point2D> pointsA = Arrays.asList(new Point(0, 0), new Point(0, 1), new Point(2, 1), new Point(2, 0));
        List<Point2D> pointsB = Arrays.asList(new Point(1, 0), new Point(1, 2), new Point(3, 2), new Point(3, 0));

        System.out.println(merge(pointsA, pointsB));
    }

    private static List<Point2D> merge(List<? extends Point2D> pointsA, List<? extends Point2D> pointsB) {
        Area aa = new Area(toShape(pointsA));
        aa.add(new Area(toShape(pointsB)));
        return toPoints(aa);
    }

    private static Shape toShape(List<? extends Point2D> points) {
        Path2D path = new Path2D.Double();
        for (int i = 0; i < points.size(); i++) {
            Point2D p = points.get(i);
            if (i == 0) {
                path.moveTo(p.getX(), p.getY());
            } else {
                path.lineTo(p.getX(), p.getY());
            }
        }
        path.closePath();
        return path;
    }

    private static List<Point2D> toPoints(Shape shape) {
        List<Point2D> result = new ArrayList<Point2D>();
        PathIterator pi = shape.getPathIterator(null, 0.0);
        double[] coords = new double[6];
        while (!pi.isDone()) {
            int segment = pi.currentSegment(coords);
            switch (segment) {
            case PathIterator.SEG_MOVETO:
            case PathIterator.SEG_LINETO:
                result.add(new Point2D.Double(coords[0], coords[1]));
                break;
            }
            pi.next();
        }
        return result;
    }

}


来源: stackexchange

问:
How to hide the Accordion widget detail?
I'm having trouble with the Expand/Not Expand. I've followed instruction from the Vendor rating template but still no luck..

What I've done :

Creating an paper accordion widget (not cards) named AccordionServeur with this script in the onDataLoad event :

```<code>var rows = widget.children._values;
    for (var i = 0; i < rows.length; i++) {
      if (rows[i].name.indexOf('AccordionServeurDetail') === -1) {
        rows[i].styles = ['collapsed'];
      }
    }
</code>```

Add some TextBox inside the AccordionServeurRow to edit the value (i.e. with datalink)

Create the client script with this code:

```<code>function expandAccordionRow(accordionRow) {
  var rows = accordionRow.parent.children._values;
  var i = 0;
  for (i = 0; i < rows.length; i++) {
    if (rows[i].name.indexOf('AccordionServeurDetail') > -1) {
      rows[i].styles = [];
    } else {
      rows[i].styles = ['collapsed'];
    }
  }
  accordionRow.styles = [];
}
</code>```

```<code>function collapseAccordionRow(accordionRow) {
  var rows = accordionRow.parent.children._values;
  var i = 0;
  accordionRow.styles = ['collapsed'];
  for (i = 0; i < rows.length; i++) {
    if (rows[i].name.indexOf('AccordionServeurDetail') > -1) {
      rows[i].styles = ['hidden'];
    }
  }
}
</code>```

```<code>function toggleAccordionRow(accordionRow) {
  if (accordionRow.styles.length === 0) {
     collapseAccordionRow(accordionRow);
  } else {
        expandAccordionRow(accordionRow);
  }
}
</code>```

On the AccordionServeurRow, in the onAttach event, I run this script:

```<code>widget.styles = ['collapsed'];
widget.getElement().removeAttribute('aria-expanded');
</code>```

On the AccordionServeurRow, in the onClick event, I run this script:

```<code>toggleAccordionRow(widget);
</code>```

On the AccordionServeurDetail, in the dataLoad event, I run this script:

```<code>widget.styles=['hidden'];
</code>```

But it still expands the detail when I open the page where the widget is.
Plus the detail stays expanded event if I click on the AccordionRow.
Did I miss something in the script or is it because of parameters in the widget ?

EDIT :
I've found the solution. You have to create style "collapsed" and to call them in the script above :

```<code>.app-AccordionRow.collapsed {
  margin: 0 !important;
}

.app-AccordionDetail.hidden {
  display: none !important;
}

</code>```

答:
You have to create style "collapsed" and "Hidden" in the style editor in the global style part to call them in the script above :</p>

```<code>.app-AccordionRow.collapsed {
  margin: 0 !important;
}

.app-AccordionDetail.hidden {
  display: none !important;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having trouble with the Expand/Not Expand. I've followed instruction from the Vendor rating template but still no luck..

What I've done :

Creating an paper accordion widget (not cards) named AccordionServeur with this script in the onDataLoad event :

var rows = widget.children._values;
    for (var i = 0; i < rows.length; i++) {
      if (rows[i].name.indexOf('AccordionServeurDetail') === -1) {
        rows[i].styles = ['collapsed'];
      }
    }

Add some TextBox inside the AccordionServeurRow to edit the value (i.e. with datalink)

Create the client script with this code:

function expandAccordionRow(accordionRow) {
  var rows = accordionRow.parent.children._values;
  var i = 0;
  for (i = 0; i < rows.length; i++) {
    if (rows[i].name.indexOf('AccordionServeurDetail') > -1) {
      rows[i].styles = [];
    } else {
      rows[i].styles = ['collapsed'];
    }
  }
  accordionRow.styles = [];
}

function collapseAccordionRow(accordionRow) {
  var rows = accordionRow.parent.children._values;
  var i = 0;
  accordionRow.styles = ['collapsed'];
  for (i = 0; i < rows.length; i++) {
    if (rows[i].name.indexOf('AccordionServeurDetail') > -1) {
      rows[i].styles = ['hidden'];
    }
  }
}

function toggleAccordionRow(accordionRow) {
  if (accordionRow.styles.length === 0) {
     collapseAccordionRow(accordionRow);
  } else {
        expandAccordionRow(accordionRow);
  }
}

On the AccordionServeurRow, in the onAttach event, I run this script:

widget.styles = ['collapsed'];
widget.getElement().removeAttribute('aria-expanded');

On the AccordionServeurRow, in the onClick event, I run this script:

toggleAccordionRow(widget);

On the AccordionServeurDetail, in the dataLoad event, I run this script:

widget.styles=['hidden'];

But it still expands the detail when I open the page where the widget is.
Plus the detail stays expanded event if I click on the AccordionRow.
Did I miss something in the script or is it because of parameters in the widget ?

EDIT :
I've found the solution. You have to create style "collapsed" and to call them in the script above :

.app-AccordionRow.collapsed {
  margin: 0 !important;
}

.app-AccordionDetail.hidden {
  display: none !important;
}

Body:
You have to create style "collapsed" and "Hidden" in the style editor in the global style part to call them in the script above :

.app-AccordionRow.collapsed {
  margin: 0 !important;
}

.app-AccordionDetail.hidden {
  display: none !important;
}


问:
Can i change the text "view project" on button with javascript or jquery?
I would like to change the text "view project" of button at this page:
https://new.emanuelemarazzi.com/pacchetti-creativi/

If you see the code there is a span under a class.

I tried to use jQuery with this code:

```<code>$('.button-style5 span').text('Text changed');
</code>```

答:
Try this</p>

```<code>$(".owl-item .button-style5 span").each(function() {
  this.textContent = "Text Changed";
});
</code>```

Body:
I would like to change the text "view project" of button at this page:
https://new.emanuelemarazzi.com/pacchetti-creativi/

If you see the code there is a span under a class.

I tried to use jQuery with this code:

$('.button-style5 span').text('Text changed');

Body:
Try this

$(".owl-item .button-style5 span").each(function() {
  this.textContent = "Text Changed";
});


问:
How to split on commas and dot?
You are given a string consisting only of digits, commas, and dots. Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in. It's guaranteed that every comma and every dot in is preceded and followed by a digit.

Sample Input 0

100,000,000.000

Sample Output 0
```

<p>I am using Python 3.7.2 and I tried <code>re.split</code> by using <code>\,*</code> and <code>\.*</code> as shown below in the code but it seems to print after every numeral.</p>

```regex_pattern = r"\,*\.*"

import re
print("\n".join(re.split(regex_pattern, input())))
```

<p>However, this seems to be printing in the wrong order. </p>

<p>What should I add in <code>regex_pattern</code>?</p>

<p>Expected result was:</p>

<pre class="lang-none prettyprint-override"><code>100
000
000
000
</code>```

However, I am getting:

1
0
0

0
0
0

0
0
0
```

答:
Your solution is quite close to working as expected. Your regex uses the * wildcard, which matches 0 or more instances of the character it follows, in your case , and . literals. The subtle thing here is that they can both be exactly zero matches, so it will split between every character!

To improve your regex to do what you were intending, you could modify it to use the + wildcard, which matches one or more of the character. Strictly speaking you probably only have exactly one of the character, in which case you may not need a quantifier at all! If you use the + wildcard however, you will also need to add in the | operator so it matches either , or ..

Ultimately, your regular expression should look like r"\,+|\.+" or better yet, use [] group like so r"[\,\.]", which will match exactly one, or .. Add the + wildcard to match one or more.

Title: How to split on commas and dot?

Body:
You are given a string consisting only of digits, commas, and dots. Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in. It's guaranteed that every comma and every dot in is preceded and followed by a digit.

Sample Input 0

100,000,000.000

Sample Output 0

I am using Python 3.7.2 and I tried re.split by using \,* and \.* as shown below in the code but it seems to print after every numeral.

regex_pattern = r"\,*\.*"

import re
print("\n".join(re.split(regex_pattern, input())))

However, this seems to be printing in the wrong order.

What should I add in regex_pattern?

Expected result was:

100
000
000
000

However, I am getting:

1
0
0

0
0
0

0
0
0


问:
How to do video annotations using javascript?
My question is how to do video annotations like youtube, but in the file html with my own video, using javascript. The annotations wolud like be links and also text only. And can put the annotation anywhere in the video.
Thanks </p>

答:
I believe you may be looking for this library: https://github.com/contently/videojs-annotation-comments

From the github page the usage which may give you hint how to use it:

```<code>plugin.fire('newAnnotation', {
   id: 1,
   range: { start: 20, end: null },
   shape: { // NOTE - x/y vals are % based (Floats) in video, not pixel values
       x1: null,
       x2: null,
       y1: null,
       y2: null
   }
   commentStr: "This is my comment." // THIS DATA YOU NEED TO FILL
});
</code>```

Additionally, for YouTube like annotations you can use https://github.com/brightcove/videojs-overlay

ContentLicense: CC BY-SA 3.0

Body:
I believe you may be looking for this library: https://github.com/contently/videojs-annotation-comments

From the github page the usage which may give you hint how to use it:

plugin.fire('newAnnotation', {
   id: 1,
   range: { start: 20, end: null },
   shape: { // NOTE - x/y vals are % based (Floats) in video, not pixel values
       x1: null,
       x2: null,
       y1: null,
       y2: null
   }
   commentStr: "This is my comment." // THIS DATA YOU NEED TO FILL
});

Additionally, for YouTube like annotations you can use https://github.com/brightcove/videojs-overlay


问:
Visiblity set to Visible if collection contains
I have 2 dependency properties:

```<code>public static readonly DependencyProperty GroupsProperty = DependencyProperty.Register(
            nameof(Groups), typeof(IEnumerable<string>), typeof(MyControl), new PropertyMetadata(null, GroupsChangedCallback));

public IEnumerable<string> Groups
{
    get => (IEnumerable<string>) GetValue(GroupsProperty);
    set => SetValue(GroupsProperty, value);
}

public static readonly DependencyProperty VisibleGroupsProperty = DependencyProperty.Register(
    nameof(VisibleGroups), typeof(IEnumerable<string>), typeof(MyControl), new PropertyMetadata(null));

public IEnumerable<string> VisibleGroups
{
    get => (IEnumerable<string>)GetValue(GroupsProperty);
    set => SetValue(GroupsProperty, value);
}
</code>```

I bind ItemsControl to Groups and in DataTemplate I would like to set Visibility to Collapsed if the current group doesn't exist in VisibleGroups.

```<code><ItemsControl ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyControl}}, Path=Groups}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <DockPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
           <!-- here -->
            <Grid  Visibility="{Visible if VisibleGroups contains current group}">

            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

Is there any easy way to accomplish that or I should create a separate "Group" ViewModel like:

```<code>public class Group
{
    public string Name {get;set;}
    public bool IsVisible {get;set;}
}
</code>```

答:
There is no "easy way" to accomplish this. You need to write some code that determines whether a reference to the current item is available in VisibleGroups.

You could for example create an IMultiValueConverter that checks whether values[1] contains values[0]:

```<code><Grid>
    <Grid.Visibility>
        <MultiBinding Converter="{StaticResource converter}">
            <Binding Path="." />
            <Binding Path="VisibleGroups" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyControl}}" />
        </MultiBinding>
    </Grid.Visibility>
...

</Grid>
</code>```

Body:
I have 2 dependency properties:

public static readonly DependencyProperty GroupsProperty = DependencyProperty.Register(
            nameof(Groups), typeof(IEnumerable<string>), typeof(MyControl), new PropertyMetadata(null, GroupsChangedCallback));

public IEnumerable<string> Groups
{
    get => (IEnumerable<string>) GetValue(GroupsProperty);
    set => SetValue(GroupsProperty, value);
}

public static readonly DependencyProperty VisibleGroupsProperty = DependencyProperty.Register(
    nameof(VisibleGroups), typeof(IEnumerable<string>), typeof(MyControl), new PropertyMetadata(null));

public IEnumerable<string> VisibleGroups
{
    get => (IEnumerable<string>)GetValue(GroupsProperty);
    set => SetValue(GroupsProperty, value);
}

I bind ItemsControl to Groups and in DataTemplate I would like to set Visibility to Collapsed if the current group doesn't exist in VisibleGroups.

<ItemsControl ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyControl}}, Path=Groups}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <DockPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>

            <Grid  Visibility="{Visible if VisibleGroups contains current group}">

            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Is there any easy way to accomplish that or I should create a separate "Group" ViewModel like:

public class Group
{
    public string Name {get;set;}
    public bool IsVisible {get;set;}
}

Body:
There is no "easy way" to accomplish this. You need to write some code that determines whether a reference to the current item is available in VisibleGroups.

You could for example create an IMultiValueConverter that checks whether values[1] contains values[0]:

<Grid>
    <Grid.Visibility>
        <MultiBinding Converter="{StaticResource converter}">
            <Binding Path="." />
            <Binding Path="VisibleGroups" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyControl}}" />
        </MultiBinding>
    </Grid.Visibility>
...

</Grid>


问:
How to write lossless WebP files with PerlMagick
I'm trying to convert PNG files to lossless WebP in Perl with Graphics::Magick.  Command line for that is:

```<code>$ gm convert in.png -define webp:lossless=true out.webp
</code>```

My Perl code looks something like that:

```<code>use Graphics::Magick;

my $image = Graphics::Magick->new();
$image->Read("in.png");
my $image_data = $image->ImageToBlock(magick => "webp");
print $out_fh $image_data;
</code>```

This code writes lossy WebP files perfectly, but how can I express the "-define" thing in terms of Perl API?

Thanks,

Update: looks like I need to call AddDefiniton API function (http://www.graphicsmagick.org/api/image.html#adddefinition).  Looks like it's not exported via Perl API as of now.

答:
I know it is of no help to you, but for those interested in how to do it in PHP, here is how:

$im = new \Gmagick($src);
$im->setimageformat('WEBP');

// Not completely sure if setimageoption() has always been there, so lets check first.
if (method_exists($im, 'setimageoption')) {
    $im->setimageoption('webp', 'lossless', 'true');
}
$imageBlob = $im->getImageBlob();
$success = @file_put_contents($destination, $imageBlob);
```

For more webp options, check out this code

Body:
I'm trying to convert PNG files to lossless WebP in Perl with Graphics::Magick.  Command line for that is:

$ gm convert in.png -define webp:lossless=true out.webp

My Perl code looks something like that:

use Graphics::Magick;

my $image = Graphics::Magick->new();
$image->Read("in.png");
my $image_data = $image->ImageToBlock(magick => "webp");
print $out_fh $image_data;

This code writes lossy WebP files perfectly, but how can I express the "-define" thing in terms of Perl API?

Thanks,

Update: looks like I need to call AddDefiniton API function (http://www.graphicsmagick.org/api/image.html#adddefinition).  Looks like it's not exported via Perl API as of now.

Body:
I know it is of no help to you, but for those interested in how to do it in PHP, here is how:

$im = new \Gmagick($src);
$im->setimageformat('WEBP');

// Not completely sure if setimageoption() has always been there, so lets check first.
if (method_exists($im, 'setimageoption')) {
    $im->setimageoption('webp', 'lossless', 'true');
}
$imageBlob = $im->getImageBlob();
$success = @file_put_contents($destination, $imageBlob);

For more webp options, check out this code


问:
Java 8 predicates using methods bodies are called only once?
I have examined the following snippet:

```<code>public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> computed = new ConcurrentHashMap<>();/*IS THIS LINE CALLED ONCE ON STREAM->FILTER NOT MATTER HOW LONG THE STREAM IS*/
    return t -> {return computed.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;};
}

private void test(){
    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();
    System.out.println("d = " + d);
}
</code>```

This code is not mine. I know that using a ConcurrentMap is not the right choice in this example and I should use ConcurrentMap instead of Map in this case, but this is not my concern now.

I thought that the distinctByKey method is called or interpreted in each iteration of the Stream. I mean the Map being instantiated in each turn, but it's not!

Is the body of the Predicate method called only once?

In the Stream iteration, is this an assertion?

Because when I try the following code:

```<code>final Function<String,Integer>a = (name)->name.length();
System.out.println(distinctByKey(a).test("JOHN"));
System.out.println(distinctByKey(a).test("STEPHEN"));
System.out.println(distinctByKey(a).test("ORTIZ"));
System.out.println(distinctByKey(a).test("RONDON"));
</code>```

I can see that the body of the method is indeed called in each line. What makes the body of the filter to only be called once?

答:
I thought that the distinctByKey method is called or interpreted in
  each iteration of the Stream i mean the Map being instance in each
  turn but it's not! my question is the body of the Predicate method
  call only one time? in the Stream iteration is this a assertion?

No.  Streams are not magic, and they do not overthrow standard Java semantics.  Consider the code presented:

```<code>    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();
</code>```

Taking specific types and methods out of the picture, that has this general form:

```<code>long x = A.b(y).c(z).d(w);
</code>```

There's no reason to expect that any of a(), b(), or c() is invoked more than once in that chain, and or that their arguments are evaluated more than once each. That is not affected by some of the types being Stream.

What happens instead in your case is that the Predicate returned by (the sole invocation of) your distinctByKey() method is used more than once as the stream in which it is embedded is processed.  That Predicate contains a reference to a Map, which it uses and modifies in performing its work.

Body:
I have examined the following snippet:

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> computed = new ConcurrentHashMap<>();/*IS THIS LINE CALLED ONCE ON STREAM->FILTER NOT MATTER HOW LONG THE STREAM IS*/
    return t -> {return computed.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;};
}

private void test(){
    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();
    System.out.println("d = " + d);
}

This code is not mine. I know that using a ConcurrentMap is not the right choice in this example and I should use ConcurrentMap instead of Map in this case, but this is not my concern now.

I thought that the distinctByKey method is called or interpreted in each iteration of the Stream. I mean the Map being instantiated in each turn, but it's not!

Is the body of the Predicate method called only once?

In the Stream iteration, is this an assertion?

Because when I try the following code:

final Function<String,Integer>a = (name)->name.length();
System.out.println(distinctByKey(a).test("JOHN"));
System.out.println(distinctByKey(a).test("STEPHEN"));
System.out.println(distinctByKey(a).test("ORTIZ"));
System.out.println(distinctByKey(a).test("RONDON"));

I can see that the body of the method is indeed called in each line. What makes the body of the filter to only be called once?

Body:
I thought that the distinctByKey method is called or interpreted in
  each iteration of the Stream i mean the Map being instance in each
  turn but it's not! my question is the body of the Predicate method
  call only one time? in the Stream iteration is this a assertion?

No.  Streams are not magic, and they do not overthrow standard Java semantics.  Consider the code presented:

    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();

Taking specific types and methods out of the picture, that has this general form:

long x = A.b(y).c(z).d(w);

There's no reason to expect that any of a(), b(), or c() is invoked more than once in that chain, and or that their arguments are evaluated more than once each. That is not affected by some of the types being Stream.

What happens instead in your case is that the Predicate returned by (the sole invocation of) your distinctByKey() method is used more than once as the stream in which it is embedded is processed.  That Predicate contains a reference to a Map, which it uses and modifies in performing its work.


问:
How to place 3D object (.scn file) on detected vertical plane which should be parallel to plane in ARKIt?
I am going to detect horizontal and vertical plane in ARKit. After detecting whether it is horizontal or vertical surface, respectively add plane of gray color on detected surface.On tap on detected plane I am going to add 3D object of .scn file.

My code is working fine for placing 3D object (.scn file) on horizontal plane but not working correctly with vertical plane.

3D object (.scn file) for vertical plane like photo frame is facing right in SceneKit editor. So I changed it’s EularAngleY to -0 and it’s facing front now in SceneKit Editor. When I tap on detected vertical plane which is facing to front then also photo frame is facing to right and If I move device facing right and place photo frame then it’s correct.

I want to place 3D object .scn file which should be parallel to plane (If vertical plane is facing front then it should be face front even in .scn file it faces to any direction).That 3D object is not parallel to detected plane.

Have I needed to change rotation also with respect to detected plane’s angle or need to do any changes in .scn file in SceneKit editor? How can I achieve it?

Please check below code on hitting detected vertical plane. Is there anything wrong?

```<code>@objc func addObjectToSceneView1(withGestureRecognizer recognizer: UIGestureRecognizer){
    let tapLocation = recognizer.location(in: sceneView)
    let hitTestResults = sceneView.hitTest(tapLocation, types: .existingPlaneUsingExtent)

    guard let hitTestResult = hitTestResults.first, let anchor = hitTestResult.anchor as? ARPlaneAnchor else { return }

    let translation = hitTestResult.worldTransform.columns.3

    let x = translation.x
    let y = translation.y
    let z = translation.z

    guard let shipScene = SCNScene(named: "art.scnassets/frame/frame.scn"),
        let shipNode = shipScene.rootNode.childNode(withName: "frame", recursively: true)
        else { return }

    shipNode.position = SCNVector3(x,y,z)

    sceneView.scene.rootNode.addChildNode(shipNode)
}
</code>```

.scn file is like below. Is this .scn file correct? Or x should be with frame's depth?  Everytime whenever I tap on plane it will show image like this only.

答:
As I mentioned in the answer here, it is better to add an ARAnchor to the ARSession rather than directly adding an SCNNode into the scene graph after doing a hit test. Currently the code you posted doesn't take into account the rotation of the detected plane. For the code to work you would need to determine the normal of the detected plane take the dot product and cross product with the desired orientation of the model calculate the rotation, then apply the rotation. However, the ARSession will do all of that for you. By using ARAnchor(transform: hitTestResult.worldTransform) the rotation is encoded into the anchor. So you will only need to deal with transformations with the models own local coordinate space.

For example:

```<code>@objc func addObjectToSceneView1(withGestureRecognizer recognizer: UIGestureRecognizer){
    let tapLocation = recognizer.location(in: sceneView)
    let hitTestResults = sceneView.hitTest(tapLocation, types: .existingPlaneUsingExtent)

    guard let hitTestResult = hitTestResults.first, let anchor = hitTestResult.anchor as? ARPlaneAnchor else { return }
    // create anchor and add to session and wait for callback
    let anchor = ARAnchor(transform: hitTestResult.worldTransform)
    sceneView.session.add(anchor: anchor)
}
</code>```

Then in your session delegate call back:

```<code>func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
    if anchor is ARPlaneAnchor {
        // node for plane anchor
        let anchorNode = SCNNode()
        return anchorNode
    } else {
        // must be node for most recent hit test
        guard let frameScene = SCNScene(named: "art.scnassets/frame/frame.scn"),
              let frameNode = frameScene.rootNode.childNode(withName: "frame", recursively: true) else { return nil }
        return frameNode
    }
}
</code>```

In you're scn file you'll want the model to be located at the origin laying flat without any transforms. This means you'll likely need to nest nodes and position the underlying model relative to a parent empty node.

Here "frame" is the outer node with no transform that is returned from nodeForAnchor and "picture" is rotated to be flat and scaled to the size of the content.

Final result:

Body:
I am going to detect horizontal and vertical plane in ARKit. After detecting whether it is horizontal or vertical surface, respectively add plane of gray color on detected surface.On tap on detected plane I am going to add 3D object of .scn file.

My code is working fine for placing 3D object (.scn file) on horizontal plane but not working correctly with vertical plane.

3D object (.scn file) for vertical plane like photo frame is facing right in SceneKit editor. So I changed it’s EularAngleY to -0 and it’s facing front now in SceneKit Editor. When I tap on detected vertical plane which is facing to front then also photo frame is facing to right and If I move device facing right and place photo frame then it’s correct.

I want to place 3D object .scn file which should be parallel to plane (If vertical plane is facing front then it should be face front even in .scn file it faces to any direction).That 3D object is not parallel to detected plane.

Have I needed to change rotation also with respect to detected plane’s angle or need to do any changes in .scn file in SceneKit editor? How can I achieve it?

Please check below code on hitting detected vertical plane. Is there anything wrong?

@objc func addObjectToSceneView1(withGestureRecognizer recognizer: UIGestureRecognizer){
    let tapLocation = recognizer.location(in: sceneView)
    let hitTestResults = sceneView.hitTest(tapLocation, types: .existingPlaneUsingExtent)

    guard let hitTestResult = hitTestResults.first, let anchor = hitTestResult.anchor as? ARPlaneAnchor else { return }

    let translation = hitTestResult.worldTransform.columns.3

    let x = translation.x
    let y = translation.y
    let z = translation.z

    guard let shipScene = SCNScene(named: "art.scnassets/frame/frame.scn"),
        let shipNode = shipScene.rootNode.childNode(withName: "frame", recursively: true)
        else { return }

    shipNode.position = SCNVector3(x,y,z)

    sceneView.scene.rootNode.addChildNode(shipNode)
}

.scn file is like below. Is this .scn file correct? Or x should be with frame's depth?  Everytime whenever I tap on plane it will show image like this only.

Body:
As I mentioned in the answer here, it is better to add an ARAnchor to the ARSession rather than directly adding an SCNNode into the scene graph after doing a hit test. Currently the code you posted doesn't take into account the rotation of the detected plane. For the code to work you would need to determine the normal of the detected plane take the dot product and cross product with the desired orientation of the model calculate the rotation, then apply the rotation. However, the ARSession will do all of that for you. By using ARAnchor(transform: hitTestResult.worldTransform) the rotation is encoded into the anchor. So you will only need to deal with transformations with the models own local coordinate space.

For example:

@objc func addObjectToSceneView1(withGestureRecognizer recognizer: UIGestureRecognizer){
    let tapLocation = recognizer.location(in: sceneView)
    let hitTestResults = sceneView.hitTest(tapLocation, types: .existingPlaneUsingExtent)

    guard let hitTestResult = hitTestResults.first, let anchor = hitTestResult.anchor as? ARPlaneAnchor else { return }
    // create anchor and add to session and wait for callback
    let anchor = ARAnchor(transform: hitTestResult.worldTransform)
    sceneView.session.add(anchor: anchor)
}

Then in your session delegate call back:

func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
    if anchor is ARPlaneAnchor {
        // node for plane anchor
        let anchorNode = SCNNode()
        return anchorNode
    } else {
        // must be node for most recent hit test
        guard let frameScene = SCNScene(named: "art.scnassets/frame/frame.scn"),
              let frameNode = frameScene.rootNode.childNode(withName: "frame", recursively: true) else { return nil }
        return frameNode
    }
}

In you're scn file you'll want the model to be located at the origin laying flat without any transforms. This means you'll likely need to nest nodes and position the underlying model relative to a parent empty node.

Here "frame" is the outer node with no transform that is returned from nodeForAnchor and "picture" is rotated to be flat and scaled to the size of the content.

Final result:


问:
Need to find turn around time
I'm calculating TAT. I have 3 params like Current Date, TAT period and List of Holidays(Date).

```<code>    static List<DateTime> Holidates = new List<DateTime>();
    static DateTime StartDate = DateTime.Now;
    static void Main(string[] args)
    {
        Holidates.Add(DateTime.Now.AddDays(20));
        Holidates.Add(DateTime.Now.AddDays(10));
        Holidates.Add(DateTime.Now.AddDays(3));

        TatDueDateCalculator(DateTime.Now, 10, Holidates);
    }

    private static DateTime TatDueDateCalculator(DateTime AssignDate, int TatPeriod, List<DateTime> Holidays)
    {
        DateTime dueDate = AssignDate.AddDays(TatPeriod);

        int holiDayCount = Holidays.FindAll(x => x >= AssignDate && x <= AssignDate.AddDays(30)).Where(y => dueDate >= AssignDate && dueDate <= y).Count();

        if (holiDayCount > 0)
            dueDate = dueDate.AddDays(holiDayCount);

        return dueDate;
    }
</code>```

TatDueDateCalculator() need to return dueDate.

Followings are the cases:

Continuous Holidays

List<DateTime>Holiday contains only one matching dueDate, but having greater values in the List.

For eg.

DueDate is "2019-05-13", Holiday List contains following dates.
"2019-05-10","2019-05-13","2019-05-12". In this case i have getting 2 TAT. But expected is 1

答:
Lasse Vågsæther Karlsen's answer working fine for me.

Link: gist.github.com/lassevk/bbee7a626b3126ebb8e59a21ebdcb15b

Code:

```<code>public static DateTime TatDueDateCalculator(DateTime assigningDate, int tatCount, IEnumerable<DateTime> holidays)
    {
        HashSet <DateTime> holidayLookup = new HashSet<DateTime>(holidays.Select(dt => dt.Date));

        DateTime dueDate = assigningDate.Date;
        while (tatCount > 1)
        {
            dueDate = dueDate.AddDays(1);
            while (holidayLookup.Contains(dueDate))
                dueDate = dueDate.AddDays(1);
            tatCount--;
        }
        return dueDate;
    }
</code>```

Title: Need to find turn around time

Body:
I'm calculating TAT. I have 3 params like Current Date, TAT period and List of Holidays(Date).

    static List<DateTime> Holidates = new List<DateTime>();
    static DateTime StartDate = DateTime.Now;
    static void Main(string[] args)
    {
        Holidates.Add(DateTime.Now.AddDays(20));
        Holidates.Add(DateTime.Now.AddDays(10));
        Holidates.Add(DateTime.Now.AddDays(3));

        TatDueDateCalculator(DateTime.Now, 10, Holidates);
    }

    private static DateTime TatDueDateCalculator(DateTime AssignDate, int TatPeriod, List<DateTime> Holidays)
    {
        DateTime dueDate = AssignDate.AddDays(TatPeriod);

        int holiDayCount = Holidays.FindAll(x => x >= AssignDate && x <= AssignDate.AddDays(30)).Where(y => dueDate >= AssignDate && dueDate <= y).Count();

        if (holiDayCount > 0)
            dueDate = dueDate.AddDays(holiDayCount);

        return dueDate;
    }

TatDueDateCalculator() need to return dueDate.

Followings are the cases:

Continuous Holidays

List<DateTime>Holiday contains only one matching dueDate, but having greater values in the List.

For eg.

DueDate is "2019-05-13", Holiday List contains following dates.
"2019-05-10","2019-05-13","2019-05-12". In this case i have getting 2 TAT. But expected is 1

Body:
Lasse Vågsæther Karlsen's answer working fine for me.

Link: gist.github.com/lassevk/bbee7a626b3126ebb8e59a21ebdcb15b

Code:

public static DateTime TatDueDateCalculator(DateTime assigningDate, int tatCount, IEnumerable<DateTime> holidays)
    {
        HashSet <DateTime> holidayLookup = new HashSet<DateTime>(holidays.Select(dt => dt.Date));

        DateTime dueDate = assigningDate.Date;
        while (tatCount > 1)
        {
            dueDate = dueDate.AddDays(1);
            while (holidayLookup.Contains(dueDate))
                dueDate = dueDate.AddDays(1);
            tatCount--;
        }
        return dueDate;
    }


问:
Easiest way to upgrade intellij 2018 -> 2019?
I'm on ubuntu 18.04, and I want to upgrade my intellij commmunity version.

I know I can go to the website and download the binaries manually, but I have githount account synced to my 2018 preferences and settings.

Thus, it would far more preferable if I could make the upgrade without actually deleting my 2018 version.

Is there any way to accomplish this? (I have not installed intellij via snap -- doing sudo snap refresh intellij-idea-community did not work)

答:
A quick Google search came up with this relevant question. The accepted answer has the information you are looking for, particularly this part:

If you make an upgrade to another major version then (during installation) your home directory is scanned and you will be asked whether you want to reuse existing settings from a previous version of IntelliJ IDEA. The settings are migrated if you agree (copied to a new version-specific directory).

You can find more information about updating IntelliJ in general here.


问:
encoding - displaying EURO symbol and more - UTF-8 charset
this is driving me bonkers. I have a column in my table with all currency symbols and am trying to display them but to no avail.

my page is set as utf8

```<code><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</code>```

I have tried mb_convert_encoding, utf8_encode but cant seem to s=get it to display correctly.

At the moment I have

```<code>function isUTF8($str) {
    if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) {
        return true;
    } else {
        return false;
    }
}
echo ( isUTF8( $ar['currrency_symbol'] ) ? $ar['currrency_symbol'] : mb_convert_encoding( $ar['currrency_symbol'], 'UTF-8' ) );
</code>```

which also doesn't work.

any help is much appreciated.

EDIT

```<code>function get_currency_symbol( $code ) {
$con = Database::getInstance();
    $re = $con->query("SELECT * FROM `countryinfo` WHERE currency_code = '$code'");
    if( $re->num_rows == 0 ) {
        return '£';
    }
    $ar = $re->fetch_assoc();
    echo ( isUTF8( $ar['currrency_symbol'] ) ? $ar['currrency_symbol'] : mb_convert_encoding( $ar['currrency_symbol'], 'UTF-8' ) );
    //return iconv( mb_detect_encoding( $ar['currrency_symbol'] ), 'UTF-8//TRANSLIT', $ar['currrency_symbol'] );
}
</code>```

///

```<code>abstract class Database {
    private static $instance = NULL;
    private function __clone() {}
    public function __construct() {}
    public static function getInstance() {
        if ( NULL === self::$instance ) {
            self::$instance = new MySQLi( DBSERVER, DBUSER, DBPASS, DBNAME );
        }
        self::$instance->query("SET NAMES 'utf8'");
        return self::$instance;
    }
    public function kill_con() {
        self::$instance->close();
    }
}
</code>```

答:
It could help to convert your document to UTF-8 (without BOM) using for example Notepad++.

In case you are using a database to fetch the data, execute the following query before all other queries:

```<code>mysql_query("SET NAMES 'UTF8'");
</code>```

Body:
this is driving me bonkers. I have a column in my table with all currency symbols and am trying to display them but to no avail.

my page is set as utf8

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

I have tried mb_convert_encoding, utf8_encode but cant seem to s=get it to display correctly.

At the moment I have

function isUTF8($str) {
    if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) {
        return true;
    } else {
        return false;
    }
}
echo ( isUTF8( $ar['currrency_symbol'] ) ? $ar['currrency_symbol'] : mb_convert_encoding( $ar['currrency_symbol'], 'UTF-8' ) );

which also doesn't work.

any help is much appreciated.

EDIT

function get_currency_symbol( $code ) {
$con = Database::getInstance();
    $re = $con->query("SELECT * FROM `countryinfo` WHERE currency_code = '$code'");
    if( $re->num_rows == 0 ) {
        return '£';
    }
    $ar = $re->fetch_assoc();
    echo ( isUTF8( $ar['currrency_symbol'] ) ? $ar['currrency_symbol'] : mb_convert_encoding( $ar['currrency_symbol'], 'UTF-8' ) );
    //return iconv( mb_detect_encoding( $ar['currrency_symbol'] ), 'UTF-8//TRANSLIT', $ar['currrency_symbol'] );
}

///

abstract class Database {
    private static $instance = NULL;
    private function __clone() {}
    public function __construct() {}
    public static function getInstance() {
        if ( NULL === self::$instance ) {
            self::$instance = new MySQLi( DBSERVER, DBUSER, DBPASS, DBNAME );
        }
        self::$instance->query("SET NAMES 'utf8'");
        return self::$instance;
    }
    public function kill_con() {
        self::$instance->close();
    }
}

Body:
It could help to convert your document to UTF-8 (without BOM) using for example Notepad++.

In case you are using a database to fetch the data, execute the following query before all other queries:

mysql_query("SET NAMES 'UTF8'");


问:
C#: Getting Names of properties in a chain from lambda expression
I'm developing a API that uses lambda expressions to specify properties. I'm using this famous piece of code similar to this one (this is simplified and incomplete, just to make clear what I'm talking about):

```<code>public void Foo<T, P>(Expression<Func<T, P>> action)
{
    var expression = (MemberExpression)action.Body;
    string propertyName = expression.Member.Name;
    // ...
}
</code>```

To be called like this:

```<code>Foo((String x) => x.Length);
</code>```

Now I would like to specify a property path by chaining property names, like this:

```<code>Foo((MyClass x) => x.Name.Length);
</code>```

Foo should be able to split the path into its property names ("Name" and "Length"). Is there a way to do this with reasonable effort?

There is a somehow similar looking question, but I think they are trying to combine lambda expressions there.

Another question also is dealing with nested property names, but I don't really understand what they are talking about.

答:
I have a shared .NET standard DTO between client and server and expressions are a great way to create query strings that can be rebuilt and executed Api side.

A perfect way to create Type safe queries over the wire.

I digress, I needed a property path also

```<code>x => x.Siblings.Age
</code>```

To produce a string like

```<code>"Siblings.Age"
</code>```

I went with this

```<code>    public static string GetMemberPath(MemberExpression me)
    {
        var parts = new List<string>();

        while (me != null)
        {
            parts.Add(me.Member.Name);
            me = me.Expression as MemberExpression;
        }

        parts.Reverse();
        return string.Join(".", parts);
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm developing a API that uses lambda expressions to specify properties. I'm using this famous piece of code similar to this one (this is simplified and incomplete, just to make clear what I'm talking about):

public void Foo<T, P>(Expression<Func<T, P>> action)
{
    var expression = (MemberExpression)action.Body;
    string propertyName = expression.Member.Name;
    // ...
}

To be called like this:

Foo((String x) => x.Length);

Now I would like to specify a property path by chaining property names, like this:

Foo((MyClass x) => x.Name.Length);

Foo should be able to split the path into its property names ("Name" and "Length"). Is there a way to do this with reasonable effort?

There is a somehow similar looking question, but I think they are trying to combine lambda expressions there.

Another question also is dealing with nested property names, but I don't really understand what they are talking about.

Body:
I have a shared .NET standard DTO between client and server and expressions are a great way to create query strings that can be rebuilt and executed Api side.

A perfect way to create Type safe queries over the wire.

I digress, I needed a property path also

x => x.Siblings.Age

To produce a string like

"Siblings.Age"

I went with this

    public static string GetMemberPath(MemberExpression me)
    {
        var parts = new List<string>();

        while (me != null)
        {
            parts.Add(me.Member.Name);
            me = me.Expression as MemberExpression;
        }

        parts.Reverse();
        return string.Join(".", parts);
    }


问:
Allocating the Sub items to the main Items in pandas
I'm looking for pandas/python solution to summarize/group items in an invoice, based on it's main code.
please refer the first attached image

each item value (price X qty) which has a MainCode should be added to the the item # total. Look for the Similar color. (Please Note some items may be repeated. eg : Green & Blue ) Qty SHOULD NOT be added. only the Values.

The answer should be as as follows

I'm New to Pandas & Since This is a bit Advanced problem, I couldn't come up with any code. hence, posted here. please direct me to solve this...

Things to note

Item combination can be repeated. eg see Green & Blue

Once Done Sub items should be removed (eg item # 371 is removed).

totalamt should equal to the total of individual item's price X Qty

In this example all sub item codes are 371. but it may have several codes. eg 371, 58, etc

Sub Item 371 can be sold separately without a MainCode. In that case, it should not be allocated & it should remain.

UPDATED DATA

答:
Hope you enjoy it. Next time please provide input data not as images but as text.

```<code>import pandas as pd

data_raw = [[260, 1500, 3, 0, 4500], [260, 1500, 1, 0, 1500], [258, 1500, 4, 0, 6000], [1054, 1200, 1, 0, 1200],
[371, 700, 3, 260, 2100], [371, 700, 1, 260, 700], [371, 700, 1, 1054, 700], [371, 700, 4, 258, 2800]]

 data = pd.DataFrame(data_raw, columns=['item', 'price', 'qty','Main code','Total'])

remove_index= []
for index, row in data.iterrows():
     try:
         # find item in Main code
         main_code_data = data.loc[data['Main code'] == row['item']]
         # merge values
         data.at[index, 'Total'] = row['Total'] + row['qty']* (main_code_data['Total'].values[0]/main_code_data['qty'].values[0])
         # get indexes to remove
         for item in main_code_data.index:
            remove_index.append(item)
     except:
         # if no match
         pass

 # remove used lines
 data = data.drop(remove_index)
</code>```

Output:

```<code>   item  price  qty  Main code  Total
0   260   1500    3          0   6600
1   260   1500    1          0   2200
2   258   1500    4          0   8800
3  1054   1200    1          0   1900
</code>```

Body:
Hope you enjoy it. Next time please provide input data not as images but as text.

import pandas as pd

data_raw = [[260, 1500, 3, 0, 4500], [260, 1500, 1, 0, 1500], [258, 1500, 4, 0, 6000], [1054, 1200, 1, 0, 1200],
[371, 700, 3, 260, 2100], [371, 700, 1, 260, 700], [371, 700, 1, 1054, 700], [371, 700, 4, 258, 2800]]

 data = pd.DataFrame(data_raw, columns=['item', 'price', 'qty','Main code','Total'])

remove_index= []
for index, row in data.iterrows():
     try:
         # find item in Main code
         main_code_data = data.loc[data['Main code'] == row['item']]
         # merge values
         data.at[index, 'Total'] = row['Total'] + row['qty']* (main_code_data['Total'].values[0]/main_code_data['qty'].values[0])
         # get indexes to remove
         for item in main_code_data.index:
            remove_index.append(item)
     except:
         # if no match
         pass

 # remove used lines
 data = data.drop(remove_index)

Output:

   item  price  qty  Main code  Total
0   260   1500    3          0   6600
1   260   1500    1          0   2200
2   258   1500    4          0   8800
3  1054   1200    1          0   1900


问:
using tone.js within angular6
I'm trying to import tone.js in angular 6. As mention in tone.js installation doc, I installed tone.js.

```<code>npm - npm install tone
</code>```

I tried to import Tone in app.module.ts

```<code>import { ToneJs } from 'tone';
imports: [
   ToneJs,
   ...
]
</code>```

I got this exception:

```<code>Error: Unexpected value 'undefined' imported by the module 'AppModule'
</code>```

How I can import and use tone.js with angular?

Here my angular version

```<code>ng -v
Angular CLI: 6.0.1
Node: 8.11.1
OS: darwin x64
Angular: 6.0.1
</code>```

Edit:

When I try to load it in a component

```<code>import { Component } from '@angular/core';
import { ToneJs } from 'tone';
@Component({
  selector: 'app-player',
  templateUrl: './player.component.html',
  styleUrls: ['./player.component.css']
})
export class PlayerComponent {
    constructor(private toneJs: toneJs) { }
}
</code>```

I get:

```<code>Error: Can't resolve all parameters for PlayerComponent: (?).
</code>```

答: Someone named Dylan Lawrence created a nice starter I found while googling on this topic this morning. Super helpful!</p>

Title: using tone.js within angular6

Body:
I'm trying to import tone.js in angular 6. As mention in tone.js installation doc, I installed tone.js.

npm - npm install tone

I tried to import Tone in app.module.ts

import { ToneJs } from 'tone';
imports: [
   ToneJs,
   ...
]

I got this exception:

Error: Unexpected value 'undefined' imported by the module 'AppModule'

How I can import and use tone.js with angular?

Here my angular version

ng -v
Angular CLI: 6.0.1
Node: 8.11.1
OS: darwin x64
Angular: 6.0.1

Edit:

When I try to load it in a component

import { Component } from '@angular/core';
import { ToneJs } from 'tone';
@Component({
  selector: 'app-player',
  templateUrl: './player.component.html',
  styleUrls: ['./player.component.css']
})
export class PlayerComponent {
    constructor(private toneJs: toneJs) { }
}

I get:

Error: Can't resolve all parameters for PlayerComponent: (?).


问:
Send all Google Forms to the same Sheets gid with Google Apps Script
I have a script creating multiple Google Forms that all link to one Google Sheets. I use the function FormApp.create(name).setDestination(FormApp.DestinationType.SPREADSHEET,destSheetId); multiple times to accomplish this. This works for the most part, however when I go to the destination Sheets, each Form pastes its information into a different gid of the Sheets. For example, one Form leads to https://docs.google.com/spreadsheets/d/1O8R/edit#gid=0 while another goes to https://docs.google.com/spreadsheets/d/1O8R/edit#gid=1. Is there any way to either make the Script assign each Form the same gid, or view all the gids in the Sheet at the same time, or anything similar to this?

Thanks!

答:
It does not seem apparent anyway to have the form write to the same sheet within the same spreadsheet after you've set the destination.  You would probably need to write the entire write To functionality of the responses and then have the actual form hidden.

Alternatively, you can create a "Master Tab" that compiles all the form responses. You would use the below function, updating the sheet and column names with yours to compile all the responses onto a single sheet.  I start at Row2 and hardcode the headers in the master spreadsheet.

```<code>=SORT({'Form Responses 1'!A2:B;'Form Responses 2'!A2:B;'Form Responses 3'!A2:B},1,0)
</code>```

Body:
It does not seem apparent anyway to have the form write to the same sheet within the same spreadsheet after you've set the destination.  You would probably need to write the entire write To functionality of the responses and then have the actual form hidden.

Alternatively, you can create a "Master Tab" that compiles all the form responses. You would use the below function, updating the sheet and column names with yours to compile all the responses onto a single sheet.  I start at Row2 and hardcode the headers in the master spreadsheet.

=SORT({'Form Responses 1'!A2:B;'Form Responses 2'!A2:B;'Form Responses 3'!A2:B},1,0)


问:
git clone in utf8 instead of us-ascii
When I run git clone SOMEREPO from GitHub the file received are in us-ascii:

$ file -bi index.php
text/plain; charset=us-ascii

How can I receive them in utf8?

Thanks

答:
There are two ways to detect a file is utf-8: implicit or explicit. In implicit form, you have to look at the content and try to guess: remember utf-8 is a superset of ASC-II, so if you actually don't use any utf-8 special chars in a particular file, there's no way to distinguish if it's UTF-8 or ASC-II so guessing tools will assume ASC-II.

In explicit form, there's a BOM (byte-order marker) in the start of file, informing it's meant for UTF-8 usage. This was borrowed from USC-2/UTF-16 backgrounds, as there it was needed for informing both the encoding and the byte order. In UTF-8 there's no byte order (or it's agnostic, if you prefer).

The implicit form is the usual in Linux and almost every utf-8 compliant system, where the explicit form is not recommended. The exception (as usual) is Windows, where most editors can only guess if there's a BOM, as utf-8 is not entirely natively supported (as the usual forms are either a codepage or UCS-2 with slowly progressing towards UTF-16, UCS-2 being a poor subset of the former, lacking correct more-than-two-bytes-per-char compliance).

If you want a particular tool to assume utf-8 instead of ASC-II, you may have to either provide a BOM (explicit form) or configure it, or even change it. I.e. apache http servers may assume asc-ii by looking at file file content's but you can override settings to make it report utf-8 unconditionally (or the other way around).

Title: git clone in utf8 instead of us-ascii


问:
Creating a C++ application with Python code included
I'm trying to create a "helloworld" app in C++, with an integrated Python code. I include Python.h, and it is seen by static analyzer fine. As I build my code I get undefined reference to '_imp__Py_Initialize', so make failed

I'm running Windows7-x64 with Python3.5-x32, MinGW-x64, CLion to write code. None of guides i found show the complete step-by-step solutions. If I have to re-install some specific versions of software, I need to know - what to do...

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.12)
project(sample)
find_package(PythonLibs 3.5 REQUIRED)
find_package(PythonInterp 3.5 REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
set(CMAKE_CXX_STANDARD 14)
add_executable(sample main.cpp)
</code>```

main.cpp

#include <Python.h>
int main() {
  Py_Initialize();
  PyRun_SimpleString("print('hello, python')");
  Py_Finalize();
  return 0;
}
```

<p>So the subject raises, i have an undefined reference. As i add <code>target_link_libraries(${PYTHON_LIBRARIES})</code> to my <code>CMakeLists.txt</code> i get another exception:</p>

```Cannot specify link libraries for target
"C:/Users/...../Python35-32/python35.dll"
which is not built by this target.
```

Please provide me some more ideas, what to do with this, if you don't mind.

答:
target_link_libraries takes the target as first parameter.
From the documentation of target_link_libraries:

The named target must have been created in the current directory by
  a command such as add_executable() or add_library(). The remaining
  arguments specify library names or flags.

Your target is sample, not because of the project(sample) at the beginning, but because of add_executable(sample main.cpp), so add

```<code>`target_link_libraries(sample ${PYTHON_LIBRARIES})`
</code>```

after the add_executable line.

Body:
I'm trying to create a "helloworld" app in C++, with an integrated Python code. I include Python.h, and it is seen by static analyzer fine. As I build my code I get undefined reference to '_imp__Py_Initialize', so make failed

I'm running Windows7-x64 with Python3.5-x32, MinGW-x64, CLion to write code. None of guides i found show the complete step-by-step solutions. If I have to re-install some specific versions of software, I need to know - what to do...

CMakeLists.txt

cmake_minimum_required(VERSION 3.12)
project(sample)
find_package(PythonLibs 3.5 REQUIRED)
find_package(PythonInterp 3.5 REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
set(CMAKE_CXX_STANDARD 14)
add_executable(sample main.cpp)

main.cpp

#include <Python.h>
int main() {
  Py_Initialize();
  PyRun_SimpleString("print('hello, python')");
  Py_Finalize();
  return 0;
}

So the subject raises, i have an undefined reference. As i add target_link_libraries(${PYTHON_LIBRARIES}) to my CMakeLists.txt i get another exception:

Cannot specify link libraries for target
"C:/Users/...../Python35-32/python35.dll"
which is not built by this target.

Please provide me some more ideas, what to do with this, if you don't mind.

Body:
target_link_libraries takes the target as first parameter.
From the documentation of target_link_libraries:

The named target must have been created in the current directory by
  a command such as add_executable() or add_library(). The remaining
  arguments specify library names or flags.

Your target is sample, not because of the project(sample) at the beginning, but because of add_executable(sample main.cpp), so add

`target_link_libraries(sample ${PYTHON_LIBRARIES})`

after the add_executable line.


问:
PHP Function pt_register
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

```<code>function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}
</code>```

Can anyone walk through this in English for me?

答:
It looks like it's extracting variables stored in arrays like $_POST and $_GET and making them global, so instead of accessing a post variable with $_POST['var'], you can just use $var. There isn't really a good reason for doing this, and it opens unnecessary security vulnerabilities if you forget to properly sanitize input. For example:

```<code>if (/* some condition */)
  $admin = true;

...

if ($admin)
{
  //do powerful stuff here
}
</code>```

this could be broken by a malicious user calling the page with something like

```<code>page.php?admin=1
</code>```

OwnerDisplayName: HaArD

Title: PHP Function pt_register

Body:
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}

Can anyone walk through this in English for me?

LastEditorDisplayName: RoBorg

Body:
It looks like it's extracting variables stored in arrays like $_POST and $_GET and making them global, so instead of accessing a post variable with $_POST['var'], you can just use $var. There isn't really a good reason for doing this, and it opens unnecessary security vulnerabilities if you forget to properly sanitize input. For example:

if (/* some condition */)
  $admin = true;

...

if ($admin)
{
  //do powerful stuff here
}

this could be broken by a malicious user calling the page with something like

page.php?admin=1

OwnerDisplayName: TenebrousX


问:
Android :: How To Read Not Visible Child Elements Of List View?
I have a list view which contains some 20 odd items from database along with a two Buttons and an extra TextView as a counter enclosed within linear layout. The two buttons usually for increment and decrement the value in an extra TextView. What i want is when i  press button outside the listView should fetch all items along with an value of an extra text. Right now I can fetch Linear layouts and there child items which are visible on screen i.e. out 20 items 10 are visible on screen, so my question is how to fetch the remaining items along with extra Textview values enclosed within linear layout which are not visible which can be viewed when we scroll the Listview?

Here is main.xml file

```<code>   <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation= "horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#CBCBCB">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget64"
android:background="@drawable/toolbar_color"
android:layout_x="0px"
android:layout_y="0px"
android:layout_width="match_parent" android:layout_height="40dip">
    <Button
    android:id="@+id/save_creature_for_encounter"
    android:layout_marginTop="5px"
    android:textSize="10dip"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:background="@drawable/onclick_button_bg"
    android:layout_width="40dip" android:layout_height="50dip"
    android:text="Save"/>

    <Button
    android:id="@+id/back_show_encounter"
    android:layout_width="80dip"
    android:layout_marginTop="5px"
    android:text="Cancel"
    android:textSize="10dip"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/button_color"
    android:layout_height="50dip">
    </Button>
  </RelativeLayout>

        <ListView
    android:id="@+id/list_view"
    android:background="#ffffff"
        android:fadingEdge="none"
        android:cacheColorHint="#ffffff"
        android:layout_weight="1"
               android:layout_gravity="center"
              android:scrollbars="vertical"
     android:layout_marginTop="28dip" android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>
      </FrameLayout>
</code>```

And here is my custom_list.xml file

```<code>        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:gravity="left|center"
        android:paddingBottom="5px"
        android:paddingTop="5px" android:paddingLeft="5px" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <TextView android:text="test" android:id="@+id/item_creatures_to_encounter"
        android:layout_marginLeft="10px" android:layout_width="180dip" android:layout_height="wrap_content"></TextView>
        <Button
                android:id="@+id/desc"
                android:layout_width="30px"
                android:layout_height="30px"
                android:layout_marginTop="5px"
                android:text="-"
                android:textSize="10dip"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:layout_alignTop="@+id/widget66"
                android:layout_alignParentRight="true"
                android:onClick="myDescClickHandler">
                >
                </Button>
        <Button
                android:id="@+id/asc"
                android:layout_width="30px"
                android:layout_height="30px"
                android:layout_marginTop="5px"
                android:text="+"
                android:textSize="10dip"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:layout_alignTop="@+id/widget66"
                android:layout_alignParentRight="true"
                android:onClick="myAscClickHandler">

                >
                </Button>

                <TextView android:text="@string/counter" android:id="@+id/counter"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip" android:layout_width="30dip"></TextView>
        </LinearLayout>
</code>```

Here is my custom Adapter file

```<code>   public class DomainAdapter extends SimpleCursorAdapter{

    private LayoutInflater mInflater;

    public DomainAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        mInflater = LayoutInflater.from(context);
    }

    public View getView(int position, View convertView, ViewGroup parent, Cursor data) {
        // A ViewHolder keeps references to children views to avoid unneccessary calls
        // to findViewById() on each row.
        //final ViewHolder holder;
        View row = super.getView(position, convertView, parent);
        ViewHolder holder=(ViewHolder)row.getTag();
        if (holder == null) {
            holder = new ViewHolder(row);
            row.setTag(holder);
            holder.add = (Button) row.findViewById(R.id.asc);
            Button.OnClickListener b =
                new Button.OnClickListener() {
                public void onClick(View v) {
                    LinearLayout parent = (LinearLayout)v.getParent();
                    TextView label=(TextView)parent.findViewById(R.id.counter);
                    Log.d("AAAAJJJAAA", ""+ parent);
                    CharSequence value = ((TextView) label).getText();
                    int count = Integer.parseInt((String) value);
                     count++;
                     String inc = String.format("%d", count);
                    label.setText(inc);
                    //parent.refreshDrawableState();
                }
            };
            holder.add.setOnClickListener(b);
        }
        return row;
    }
</code>```

}

答: get the ListView's adapter instance and then try calling getItem ( http://developer.android.com/reference/android/widget/Adapter.html#getItem%28int%29)</p>

Body:
I have a list view which contains some 20 odd items from database along with a two Buttons and an extra TextView as a counter enclosed within linear layout. The two buttons usually for increment and decrement the value in an extra TextView. What i want is when i  press button outside the listView should fetch all items along with an value of an extra text. Right now I can fetch Linear layouts and there child items which are visible on screen i.e. out 20 items 10 are visible on screen, so my question is how to fetch the remaining items along with extra Textview values enclosed within linear layout which are not visible which can be viewed when we scroll the Listview?

Here is main.xml file

   <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation= "horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#CBCBCB">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget64"
android:background="@drawable/toolbar_color"
android:layout_x="0px"
android:layout_y="0px"
android:layout_width="match_parent" android:layout_height="40dip">
    <Button
    android:id="@+id/save_creature_for_encounter"
    android:layout_marginTop="5px"
    android:textSize="10dip"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:background="@drawable/onclick_button_bg"
    android:layout_width="40dip" android:layout_height="50dip"
    android:text="Save"/>

    <Button
    android:id="@+id/back_show_encounter"
    android:layout_width="80dip"
    android:layout_marginTop="5px"
    android:text="Cancel"
    android:textSize="10dip"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/button_color"
    android:layout_height="50dip">
    </Button>
  </RelativeLayout>

        <ListView
    android:id="@+id/list_view"
    android:background="#ffffff"
        android:fadingEdge="none"
        android:cacheColorHint="#ffffff"
        android:layout_weight="1"
               android:layout_gravity="center"
              android:scrollbars="vertical"
     android:layout_marginTop="28dip" android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>
      </FrameLayout>

And here is my custom_list.xml file

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:gravity="left|center"
        android:paddingBottom="5px"
        android:paddingTop="5px" android:paddingLeft="5px" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <TextView android:text="test" android:id="@+id/item_creatures_to_encounter"
        android:layout_marginLeft="10px" android:layout_width="180dip" android:layout_height="wrap_content"></TextView>
        <Button
                android:id="@+id/desc"
                android:layout_width="30px"
                android:layout_height="30px"
                android:layout_marginTop="5px"
                android:text="-"
                android:textSize="10dip"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:layout_alignTop="@+id/widget66"
                android:layout_alignParentRight="true"
                android:onClick="myDescClickHandler">
                >
                </Button>
        <Button
                android:id="@+id/asc"
                android:layout_width="30px"
                android:layout_height="30px"
                android:layout_marginTop="5px"
                android:text="+"
                android:textSize="10dip"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:layout_alignTop="@+id/widget66"
                android:layout_alignParentRight="true"
                android:onClick="myAscClickHandler">

                >
                </Button>

                <TextView android:text="@string/counter" android:id="@+id/counter"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip" android:layout_width="30dip"></TextView>
        </LinearLayout>

Here is my custom Adapter file

   public class DomainAdapter extends SimpleCursorAdapter{

    private LayoutInflater mInflater;

    public DomainAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        mInflater = LayoutInflater.from(context);
    }

    public View getView(int position, View convertView, ViewGroup parent, Cursor data) {
        // A ViewHolder keeps references to children views to avoid unneccessary calls
        // to findViewById() on each row.
        //final ViewHolder holder;
        View row = super.getView(position, convertView, parent);
        ViewHolder holder=(ViewHolder)row.getTag();
        if (holder == null) {
            holder = new ViewHolder(row);
            row.setTag(holder);
            holder.add = (Button) row.findViewById(R.id.asc);
            Button.OnClickListener b =
                new Button.OnClickListener() {
                public void onClick(View v) {
                    LinearLayout parent = (LinearLayout)v.getParent();
                    TextView label=(TextView)parent.findViewById(R.id.counter);
                    Log.d("AAAAJJJAAA", ""+ parent);
                    CharSequence value = ((TextView) label).getText();
                    int count = Integer.parseInt((String) value);
                     count++;
                     String inc = String.format("%d", count);
                    label.setText(inc);
                    //parent.refreshDrawableState();
                }
            };
            holder.add.setOnClickListener(b);
        }
        return row;
    }

}


问:
DATE_SUB(NOW(), INTERVAL 5 MINUTE) not working in PDO statement
I am converting my site to use prepared statements instead of mysqli. However I have come across an issue which I know worked using mysqli but it doesn't work using prepared statements. I want to delete all records that are 5 minutes older than than the time recorded in the database which in this case is stored in column last_fail_login.
I am not getting an error but it delete's every record in the db table no matter how many minutes old it is which is not correct.
I have pasted the code below: </p>

```<code>$stmt1 = $conn->prepare("DELETE FROM login_fail WHERE `last_fail_login` < DATE_SUB(NOW(), INTERVAL 5 MINUTE)");
$stmt1->execute();
</code>```

答: I have finally worked out why this wasn't working. I still understand how this affected it but once I set my timezone using date_default_timezone_set('Europe/London'); the query worked. Strange that I didn't have to set this when using MYSQLI. Thanks for all suggestions.

Body:
I am converting my site to use prepared statements instead of mysqli. However I have come across an issue which I know worked using mysqli but it doesn't work using prepared statements. I want to delete all records that are 5 minutes older than than the time recorded in the database which in this case is stored in column last_fail_login.
I am not getting an error but it delete's every record in the db table no matter how many minutes old it is which is not correct.
I have pasted the code below:

$stmt1 = $conn->prepare("DELETE FROM login_fail WHERE `last_fail_login` < DATE_SUB(NOW(), INTERVAL 5 MINUTE)");
$stmt1->execute();


问:
Can't apply background image in css (flask template)
I want to apply background image in internal css. I'm using flask template. this is my directory

```<code>src - templates - image - img.jpg
src- templates - upload.html
</code>```

I want to apply the background image at upload.html. but I got 404 error. can someone help me please?

my code:

```<code>background-image: url("/image/img.jpg");
</code>```

error message:

get /image/img.jpg HTTP/1.1 404

答:
There could be multiple issues like :

Incorrect directory-URL: Try specifying the whole URL - instead of "/image/img.jpg" try "/templates/image/img.jpg".

Misspelled directory-name - check it properly.

Reassure yourself that the specified image is in the correct format (.jpg).

Body:
I want to apply background image in internal css. I'm using flask template. this is my directory

src - templates - image - img.jpg
src- templates - upload.html

I want to apply the background image at upload.html. but I got 404 error. can someone help me please?

my code:

background-image: url("/image/img.jpg");

error message:

get /image/img.jpg HTTP/1.1 404


问:
Dynamically change the url of a route in Zuul based on query param
As the title suggests I want to change the url based on a given query parameter. So for example if I request:

http://api.company.com/path?service=A >> route to upstream A

http://api.company.com/path?service=B >> route to upstream B

I've tried multiple different versions based on this, this, this or that. None of these examples worked or provide a complete list environment (code + config files).

Current non working version:

application.yml:

```<code>zuul:
  ignoredServices: '*'
  routes:
    serviceA:
      path: /statistics/**
      url: http://localhost:3000/a
    serviceB:
      path: /statistics/**
      url: http://localhost:3000/b
</code>```

PreFilter for Zuul

```<code>import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import java.net.URL;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;

public class QueryParamServiceIdPreFilter extends ZuulFilter {

    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER + 1;
    }

    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    public Object run() {
        RequestContext ctx = getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        // always null
        URL routeHost = getCurrentContext().getRouteHost();

        if ( "A".equals(request.getParameter("serviceUrl")) ) {
            ctx.put("serviceId", "serviceA");
        }

        if ( "B".equals(request.getParameter("serviceUrl")) ) {
            ctx.put("serviceId", "serviceB");
        }

        return null;
    }
}
</code>```

Fake micro service:

```<code>var express = require('express');
var app = express();
app.get('/a', function (req, res) {
  res.send('Service A');
});

app.get('/b', function (req, res) {
  res.send('Service B');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
</code>```

Result on call

```<code>$ curl "localhost:8071/statistics?serviceUrl=B" ;  echo; curl "localhost:8071/statistics?serviceUrl=A"
Service B
Service B⏎
</code>```

答:
Your code looks good, thing you are missing is service discovery.
You said:

```<code>ctx.put("serviceId", "serviceA");
</code>```

but you do not have defined service id, instead you are using service url, here:

```<code>serviceA:
  path: /statistics/**
  url: http://localhost:3000/a
</code>```

after you configure service discovery you will have:

```<code>serviceA:
  path: /statistics/**
  serviceId: serviceA
</code>```

Check my answers here and here

Body:
As the title suggests I want to change the url based on a given query parameter. So for example if I request:

http://api.company.com/path?service=A >> route to upstream A

http://api.company.com/path?service=B >> route to upstream B

I've tried multiple different versions based on this, this, this or that. None of these examples worked or provide a complete list environment (code + config files).

Current non working version:

application.yml:

zuul:
  ignoredServices: '*'
  routes:
    serviceA:
      path: /statistics/**
      url: http://localhost:3000/a
    serviceB:
      path: /statistics/**
      url: http://localhost:3000/b

PreFilter for Zuul

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import java.net.URL;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;

public class QueryParamServiceIdPreFilter extends ZuulFilter {

    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER + 1;
    }

    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    public Object run() {
        RequestContext ctx = getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        // always null
        URL routeHost = getCurrentContext().getRouteHost();

        if ( "A".equals(request.getParameter("serviceUrl")) ) {
            ctx.put("serviceId", "serviceA");
        }

        if ( "B".equals(request.getParameter("serviceUrl")) ) {
            ctx.put("serviceId", "serviceB");
        }

        return null;
    }
}

Fake micro service:

var express = require('express');
var app = express();
app.get('/a', function (req, res) {
  res.send('Service A');
});

app.get('/b', function (req, res) {
  res.send('Service B');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Result on call

$ curl "localhost:8071/statistics?serviceUrl=B" ;  echo; curl "localhost:8071/statistics?serviceUrl=A"
Service B
Service B⏎

Body:
Your code looks good, thing you are missing is service discovery.
You said:

ctx.put("serviceId", "serviceA");

but you do not have defined service id, instead you are using service url, here:

serviceA:
  path: /statistics/**
  url: http://localhost:3000/a

after you configure service discovery you will have:

serviceA:
  path: /statistics/**
  serviceId: serviceA

Check my answers here and here


问:
How to get Sum from List in another List as a property with linq
My classes are like below.

```<code>public class ModelMMaster
{
    public string OrderID { get; set; }
    public bool IsActive { get; set; }
    public List<ModelDetail> _detail { get; set; }
}
public class ModelDetail
{
    public string SKUCode { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
}
</code>```

And I have an order list like

```<code>List<ModelMMaster> _listMaster = new List<ModelMMaster>
</code>```

I want to calculate Sum(Quantity * Price) with LINQ, over _listMaster.

I am stuck at this.

```<code>double _sum =_listMaster.Where(f => f.IsActive == true).Select(f => f._detail)......
</code>```

How can i calculate Sum(Quantity * Price) from _listMaster  with LINQ?

答:
You can achieve it couple of ways

Option 1

```<code>double _sum =_listMaster.Where(f => f.IsActive)
                         .Sum(x=>x._detail.Sum(c=>c.Price * c.Quantity));
</code>```

Option 2

```<code>double _sum =_listMaster.Where(f => f.IsActive)
                        .Aggregate(0d,(result,item)=>result + item._detail.Sum(x=>x.Price * x.Quantity));
</code>```

Option 3

```<code>double _sum =_listMaster.Where(f => f.IsActive)
                        .SelectMany(x=>x._detail)
                        .Sum(x=>x.Price * x.Quantity);
</code>```

Body:
My classes are like below.

public class ModelMMaster
{
    public string OrderID { get; set; }
    public bool IsActive { get; set; }
    public List<ModelDetail> _detail { get; set; }
}
public class ModelDetail
{
    public string SKUCode { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
}

And I have an order list like

List<ModelMMaster> _listMaster = new List<ModelMMaster>

I want to calculate Sum(Quantity * Price) with LINQ, over _listMaster.

I am stuck at this.

double _sum =_listMaster.Where(f => f.IsActive == true).Select(f => f._detail)......

How can i calculate Sum(Quantity * Price) from _listMaster  with LINQ?

Body:
You can achieve it couple of ways

Option 1

double _sum =_listMaster.Where(f => f.IsActive)
                         .Sum(x=>x._detail.Sum(c=>c.Price * c.Quantity));

Option 2

double _sum =_listMaster.Where(f => f.IsActive)
                        .Aggregate(0d,(result,item)=>result + item._detail.Sum(x=>x.Price * x.Quantity));

Option 3

double _sum =_listMaster.Where(f => f.IsActive)
                        .SelectMany(x=>x._detail)
                        .Sum(x=>x.Price * x.Quantity);


问:
Map property with corresponding value in another property
I have a function that gets the LCID (locale ID) from the current user. I want to map this number with the corresponding language in another property. For example, I  first extract the LCID from the user, let's say "1043" for Dutch. I have a property with "1043: Dutch" and I want to extract the name from this property with the ID.

My code:

```<code>export class Languages {
  public static languages = {
    1033: 'English',
    1035: 'Finnish',
    1036: 'French',
    1037: 'Hebrew',
    1038: 'Hungarian',
    1040: 'Italian',
    1041: 'Japanese',
    1042: 'Korean',
    1043: 'Dutch',
    1044: 'Norwegian',
    1045: 'Polish',
  };
}

localeId = applicationContext.pageContext.legacyPageContext.currentLanguage; //get the LCID
}

let language: any;

const pos: number = Object.keys(Languages.languages).indexOf(localeId.toString());
//WRONG BELOW
if (pos > -1) {

  let languageObject = Object.keys(Languages.languages).map(e => Languages.languages[pos]);
  language = languageObject;

  //WRONG UP
}

return language; //Should return the correct NAME of the languages via the ID
}
</code>```

See the code where I wrote, "wrong below". It doesn't return the correct value. For example, if the localeId is 1043, then it would return "Dutch" which it doesn't.

答:
Just use bracket notation:

const languages = {1033:'English',1035:'Finnish',1036:'French',1037:'Hebrew',1038:'Hungarian',1040:'Italian',1041:'Japanese',1042:'Korean',1043:'Dutch',1044:'Norwegian',1045:'Polish'};
const id = 1036;
const language = languages[id];
console.log(language);```

Body:
I have a function that gets the LCID (locale ID) from the current user. I want to map this number with the corresponding language in another property. For example, I  first extract the LCID from the user, let's say "1043" for Dutch. I have a property with "1043: Dutch" and I want to extract the name from this property with the ID.

My code:

export class Languages {
  public static languages = {
    1033: 'English',
    1035: 'Finnish',
    1036: 'French',
    1037: 'Hebrew',
    1038: 'Hungarian',
    1040: 'Italian',
    1041: 'Japanese',
    1042: 'Korean',
    1043: 'Dutch',
    1044: 'Norwegian',
    1045: 'Polish',
  };
}

localeId = applicationContext.pageContext.legacyPageContext.currentLanguage; //get the LCID
}

let language: any;

const pos: number = Object.keys(Languages.languages).indexOf(localeId.toString());
//WRONG BELOW
if (pos > -1) {

  let languageObject = Object.keys(Languages.languages).map(e => Languages.languages[pos]);
  language = languageObject;

  //WRONG UP
}

return language; //Should return the correct NAME of the languages via the ID
}

See the code where I wrote, "wrong below". It doesn't return the correct value. For example, if the localeId is 1043, then it would return "Dutch" which it doesn't.


问:
Saving timestamp in mysql table using php
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

```<code>INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')
</code>```

Body:
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')

Body:
pass like this

date('Y-m-d H:i:s','1299762201428')


问:
How to translateX, translateY to a certain coordinate rather than a relative point?
My question is about using translateX and translateY in react and/or react-native animations, to animate an object to a certain point.

These two transformations move an object relative to the existing point.

But for the scenario, the existing coordinate is not important and I want to assure the object moves to a certain point wherever it may exist in the screen.

Additional limitation is, I can not animate styles top, bottom, left and right because in react-native, if we animate these styles then we can not use the useNativeDriver={true} directive which causes performance problems.

答:
You can use the onLayout prop to get position (relative to parent) and height/width on any View component.

Something like this should work. You might need to get position of more parent View components, depending on your current structure.

```<code>componentDidMount() {
  this.animatedValue = new Animated.Value(0);
}

animate() {
  const { parentYPosition } = this.state;
  Animated.Timing(this.animatedValue, {
    toValue: FINAL_POSITION - parentYPosition
  }).start();
}

render() {
  return (
    <View
      onLayout={event => {
        const { y } = event.nativeEvent.layout;
        this.setState({parentYPosition: y})
      }}
    >
      <Animated.View
        style={{
          position: 'absolute',
          top: 0,
          transform: [
          {
            translateY: this.animatedValue
          }
      />
    />
  );
}
</code>```

https://facebook.github.io/react-native/docs/view#onlayout

Body:
You can use the onLayout prop to get position (relative to parent) and height/width on any View component.

Something like this should work. You might need to get position of more parent View components, depending on your current structure.

componentDidMount() {
  this.animatedValue = new Animated.Value(0);
}

animate() {
  const { parentYPosition } = this.state;
  Animated.Timing(this.animatedValue, {
    toValue: FINAL_POSITION - parentYPosition
  }).start();
}

render() {
  return (
    <View
      onLayout={event => {
        const { y } = event.nativeEvent.layout;
        this.setState({parentYPosition: y})
      }}
    >
      <Animated.View
        style={{
          position: 'absolute',
          top: 0,
          transform: [
          {
            translateY: this.animatedValue
          }
      />
    />
  );
}

https://facebook.github.io/react-native/docs/view#onlayout