问:
Animate custom vector shape
I'd like to animate the following vector shape, unfortunately due to the edges converting it into a path is not possible. (If anyone knows a way to preserve the shape as a path, kudos for that!)

The goal would be to have an animation that follows the shape:

I was playing around with SVG animations, but it seems to be not possible to animate a shape. Path animations are possible. My question is, is it possible to use a <canvas> element like in the attached fiddle and animate it there?

http://jsfiddle.net/Na6X5/

答:
I recreated the shape in Illustrator so it's not quite perfect, but it's very close. I then saved it as an SVG path.

Here is the working code to do what I think you want.

SVG Shape:

```<code><?xml version="1.0" encoding="utf-8"?>
<svg id="myshape" version="1.1" id="Layer_1" xmlns="http://www.w3.org  /2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 571.1 437.5" style="enable-background:new 0 0 571.1 437.5;" xml:space="preserve" stroke="#000" stroke-width="90" stroke-miterlimit="10">
<g>
  <path id="mypath" d="M519,300.4l-76.4,75.9c-14,13.9-36.7,13.9-50.7-0.1l-83.5-83.5c-13.2-13.2-34.6-13.3-48-0.2
    l-93.9,92.1c-11.2,11-29.4,10.4-39.9-1.4l-73.5-82.6c-11.4-12.8-10.8-32.2,1.3-44.3L255.7,55.5c14-14,36.6-14,50.7-0.1l212.5,210.7
    C528.5,275.6,528.5,291,519,300.4z" />
</g>
</svg>
</code>```

JavaScript

```<code>drawTime = 2000; //2 seconds
path = document.getElementById("mypath");
length = path.getTotalLength();
path.style.strokeDashoffset = length; //starting position
path.style.strokeDasharray = length + ', ' + length;
path.style.fill = "none"; //make it have no fill to begin with
path.style.transition = path.style.WebkitTransition = 'none';
path.getBoundingClientRect();
path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset ' + (drawTime / 1000) + 's ease-in-out';
path.style.strokeDashoffset = '0'; //finishing position
</code>```

JSFiddle (pure JavaScript): https://jsfiddle.net/900nayr2/4/

JSFiddle (with my jQuery plugin I wrote): https://jsfiddle.net/vL5bz5mn/1/

For the jQuery one... I wrote the DrawSVG plugin approximately a year ago for jQuery 1.10 or something like that. I hope this helps! You could just use the JavaScript one if you like.

Title: Animate custom vector shape

Body:
I recreated the shape in Illustrator so it's not quite perfect, but it's very close. I then saved it as an SVG path.

Here is the working code to do what I think you want.

SVG Shape:

<?xml version="1.0" encoding="utf-8"?>
<svg id="myshape" version="1.1" id="Layer_1" xmlns="http://www.w3.org  /2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 571.1 437.5" style="enable-background:new 0 0 571.1 437.5;" xml:space="preserve" stroke="#000" stroke-width="90" stroke-miterlimit="10">
<g>
  <path id="mypath" d="M519,300.4l-76.4,75.9c-14,13.9-36.7,13.9-50.7-0.1l-83.5-83.5c-13.2-13.2-34.6-13.3-48-0.2
    l-93.9,92.1c-11.2,11-29.4,10.4-39.9-1.4l-73.5-82.6c-11.4-12.8-10.8-32.2,1.3-44.3L255.7,55.5c14-14,36.6-14,50.7-0.1l212.5,210.7
    C528.5,275.6,528.5,291,519,300.4z" />
</g>
</svg>

JavaScript

drawTime = 2000; //2 seconds
path = document.getElementById("mypath");
length = path.getTotalLength();
path.style.strokeDashoffset = length; //starting position
path.style.strokeDasharray = length + ', ' + length;
path.style.fill = "none"; //make it have no fill to begin with
path.style.transition = path.style.WebkitTransition = 'none';
path.getBoundingClientRect();
path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset ' + (drawTime / 1000) + 's ease-in-out';
path.style.strokeDashoffset = '0'; //finishing position

JSFiddle (pure JavaScript): https://jsfiddle.net/900nayr2/4/

JSFiddle (with my jQuery plugin I wrote): https://jsfiddle.net/vL5bz5mn/1/

For the jQuery one... I wrote the DrawSVG plugin approximately a year ago for jQuery 1.10 or something like that. I hope this helps! You could just use the JavaScript one if you like.


来源: stackexchange

问:
Placing button over ListView expands beyond page
I have Xamarin Forms project. In xaml, I would like to have ListView and over it a button that will be clickable and transparent (Opacity=0.9). There is one label above ListView and one label below it. I used RelativeLayout to place ListView and transparent button and wrapped it inside StackLayout with two labels. Problem is ListView expands beyond page.

Here is my code for xaml file:

```<code><StackLayout VerticalOptions="FillAndExpand" BackgroundColor="#4d4d4d" HorizontalOptions="FillAndExpand">
  <Label Text="2600 Michelson" HorizontalOptions="Center" />
  <RelativeLayout VerticalOptions="FillAndExpand">
    <ListView ItemsSource ="{Binding Meters}" HasUnevenRows="True"
      RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
      RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height}" >
    ...
    </ListView>
    <Button Text="Green button" BackgroundColor="#299164" Opacity="0.9"
        RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.5, Constant=-50}"
        RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1, Constant=-100}">
    </Button>
  </RelativeLayout>
  <Label Text="This label is not visible" TextColor="#0000ff"></Label>
<StackLayout>
</code>```

Here is a screenshot:

I am still far from end design, but this is how it should look like:

答:
I think you can use a Grid. Try this code

XAML

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestRelativeLayout.MyPage1"
             Title="TabbedPage">
             <StackLayout VerticalOptions="FillAndExpand">
                <Button Clicked="Handle_Clicked" Text = "Press">
            </Button>
                    <Grid VerticalOptions = "FillAndExpand">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="4*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="3*" />
                        <ColumnDefinition Width="2*" />
                        <ColumnDefinition Width="3*" />
                    </Grid.ColumnDefinitions>

                    <ListView ItemsSource="{Binding Lista}" Grid.Row = "0" Grid.Column = "0" Grid.RowSpan = "2" Grid.ColumnSpan = "3" VerticalOptions = "FillAndExpand" HorizontalOptions="FillAndExpand">
                        <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextCell Text="{Binding .}" />
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <Button Text = "ButtonOver" Opacity="0.5" BackgroundColor = "Fuchsia" Grid.Row="1" Grid.Column = "1"/>

            </Grid>
    </StackLayout>
</ContentPage>
</code>```

this is the result

ContentLicense: CC BY-SA 3.0

Body:
I have Xamarin Forms project. In xaml, I would like to have ListView and over it a button that will be clickable and transparent (Opacity=0.9). There is one label above ListView and one label below it. I used RelativeLayout to place ListView and transparent button and wrapped it inside StackLayout with two labels. Problem is ListView expands beyond page.

Here is my code for xaml file:

<StackLayout VerticalOptions="FillAndExpand" BackgroundColor="#4d4d4d" HorizontalOptions="FillAndExpand">

  <RelativeLayout VerticalOptions="FillAndExpand">
    <ListView ItemsSource ="{Binding Meters}" HasUnevenRows="True"
      RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
      RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height}" >
    ...
    </ListView>
    <Button Text="Green button" BackgroundColor="#299164" Opacity="0.9"
        RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.5, Constant=-50}"
        RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1, Constant=-100}">
    </Button>
  </RelativeLayout>

<StackLayout>

Here is a screenshot:

I am still far from end design, but this is how it should look like:

Body:
I think you can use a Grid. Try this code

XAML

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestRelativeLayout.MyPage1"
             Title="TabbedPage">
             <StackLayout VerticalOptions="FillAndExpand">
                <Button Clicked="Handle_Clicked" Text = "Press">
            </Button>
                    <Grid VerticalOptions = "FillAndExpand">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="4*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="3*" />
                        <ColumnDefinition Width="2*" />
                        <ColumnDefinition Width="3*" />
                    </Grid.ColumnDefinitions>

                    <ListView ItemsSource="{Binding Lista}" Grid.Row = "0" Grid.Column = "0" Grid.RowSpan = "2" Grid.ColumnSpan = "3" VerticalOptions = "FillAndExpand" HorizontalOptions="FillAndExpand">
                        <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextCell Text="{Binding .}" />
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <Button Text = "ButtonOver" Opacity="0.5" BackgroundColor = "Fuchsia" Grid.Row="1" Grid.Column = "1"/>

            </Grid>
    </StackLayout>
</ContentPage>

this is the result


问:
Count number of appearances in JSON data for nested element
How I can get the appearance of elements in JSON data for nested element?

```<code>[
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_cpu_average",
                            "issued":1490774610,
                            "executed":1490774610,
                            "duration":0.142,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.223,
                            "output":"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
                            "status":2,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.216,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"cpu_average",
                            "issued":1490774613,
                            "executed":1490774613,
                            "duration":0.124,
                            "output":"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
                            "status":2,
                            "type":"standard"
                    }
    }
</code>```

]

I need to count the number of appearances of WARNING and CRITICAL appeared, if it's appeared in output(check -> output).

Please excuse if this is a novice question. I'm new to this.

答:
You could use Array#forEach to iterate over every output entry and look for warning or critical keywords.

var json = [{client:"172.16.109.96",check:{command:"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",standalone:!0,interval:5,name:"vm_cpu_average",issued:1490774610,executed:1490774610,duration:.142,output:"CheckGraphiteStat WARNING: No data from Graphite\n",status:3,type:"standard"}},{client:"172.16.109.96",check:{command:"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",standalone:!0,interval:5,name:"mem_average",issued:1490774614,executed:1490774614,duration:.223,output:"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",status:2,type:"standard"}},{client:"172.16.109.96",check:{command:"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",standalone:!0,interval:5,name:"vm_mem_average",issued:1490774614,executed:1490774614,duration:.216,output:"CheckGraphiteStat WARNING: No data from Graphite\n",status:3,type:"standard"}},{client:"172.16.109.96",check:{command:"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",standalone:!0,interval:5,name:"cpu_average",issued:1490774613,executed:1490774613,duration:.124,output:"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",status:2,type:"standard"}}],
    obj = {};
    json.forEach(function(v){
      var elem = v.check.output.match(/critical|warning/i)[0];
      !obj[elem] ? obj[elem] = 1 : obj[elem]++;
    });

    console.log(obj);```

Body:
How I can get the appearance of elements in JSON data for nested element?

[
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_cpu_average",
                            "issued":1490774610,
                            "executed":1490774610,
                            "duration":0.142,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.223,
                            "output":"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
                            "status":2,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.216,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"cpu_average",
                            "issued":1490774613,
                            "executed":1490774613,
                            "duration":0.124,
                            "output":"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
                            "status":2,
                            "type":"standard"
                    }
    }

]

I need to count the number of appearances of WARNING and CRITICAL appeared, if it's appeared in output(check -> output).

Please excuse if this is a novice question. I'm new to this.


问:
Enumerate or list all variables in a program of [your favorite language here]
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:

```
#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
        "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue
```

which will output something like:

```
__builtins__ is <type 'str'> and is equal to  <module '__builtin__' (built-in)>
__doc__ is <type 'str'> and is equal to  None
__file__ is <type 'str'> and is equal to  ./foo.py
__name__ is <type 'str'> and is equal to  __main__
foo1 is <type 'str'> and is equal to  Hello world
foo2 is <type 'str'> and is equal to  bar
foo3 is <type 'str'> and is equal to  {'1': 'a', '2': 'b'}
foo4 is <type 'str'> and is equal to  1+1
```

I have so far found a partial way in PHP (courtesy of link text) but it only lists all variables and their types, not the contents:

```
<?php
// create a few variables
$bar = 'foo';
$foo ='bar';
// create a new array object
$arrayObj = new ArrayObject(get_defined_vars());
// loop over the array object and echo variables and values
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next())
        {
        echo $iterator->key() . ' => ' . $iterator->current() . '<br />';
        }
?>
```

So I put it to you: how do you list all variables and their contents in your favorite language?

Edit by VonC: I propose this question follows the spirit of a little "code-challenge".

If you do not agree, just edit and remove the tag and the link.

答:
In php you could do this:</p>

```<code>$defined = get_defined_vars();
foreach($defined as $varName => $varValue){
 echo "$varName is of type ".gettype($varValue)." and has value $varValue <br>";
}
</code>```

OwnerDisplayName: Kurt

ContentLicense: CC BY-SA 2.5

Body:
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:

#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
        "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue

which will output something like:

__builtins__ is <type 'str'> and is equal to  <module '__builtin__' (built-in)>
__doc__ is <type 'str'> and is equal to  None
__file__ is <type 'str'> and is equal to  ./foo.py
__name__ is <type 'str'> and is equal to  __main__
foo1 is <type 'str'> and is equal to  Hello world
foo2 is <type 'str'> and is equal to  bar
foo3 is <type 'str'> and is equal to  {'1': 'a', '2': 'b'}
foo4 is <type 'str'> and is equal to  1+1

I have so far found a partial way in PHP (courtesy of link text) but it only lists all variables and their types, not the contents:

<?php
// create a few variables
$bar = 'foo';
$foo ='bar';
// create a new array object
$arrayObj = new ArrayObject(get_defined_vars());
// loop over the array object and echo variables and values
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next())
        {
        echo $iterator->key() . ' => ' . $iterator->current() . '
';
        }
?>

So I put it to you: how do you list all variables and their contents in your favorite language?

Edit by VonC: I propose this question follows the spirit of a little "code-challenge".

If you do not agree, just edit and remove the tag and the link.

LastEditorDisplayName: VonC

Body:
In php you could do this:

$defined = get_defined_vars();
foreach($defined as $varName => $varValue){
 echo "$varName is of type ".gettype($varValue)." and has value $varValue <br>";
}

OwnerDisplayName: Pim Jager


问:
possible to use html images like canvas with getImageData / putImageData?
I'd like to know if there is a way to dynamically modify/access the data contained in html images just as if they were an html5 canvas element. With canvas, you can in javascript access the raw pixel data with getImageData() and putImageData(), but I have thus far been not able to figure out how to do this with images.</p>

答:
<pre class="lang-js prettyprint-override"><code>    // 1) Create a canvas, either on the page or simply in code
    var canvas = document.createElement('canvas');
    var ctx    = canvas.getContext('2d');

    // 2) Copy your image data into the canvas
    var myImgElement = document.getElementById('foo');
    ctx.drawImage( myImgElement, 0, 0 );

    // 3) Read your image data
    var w = myImgElement.width, h=myImgElement.height;
    var imgdata = ctx.getImageData(0,0,w,h);
    var rgba = imgdata.data;

    // 4) Read or manipulate the rgba as you wish
    for (var px=0,ct=w*h*4;px<ct;px+=4){
      var r = rgba[px  ];
      var g = rgba[px+1];
      var b = rgba[px+2];
      var a = rgba[px+3];
    }

    // 5) Update the context with newly-modified data
    ctx.putImageData(imgdata,0,0);

    // 6) Draw the image data elsewhere, if you wish
    someOtherContext.drawImage( ctx.canvas, 0, 0 );
</code>```
<p>Note that step 2 can also be brought in from an image loaded directly into script, not on the page:</p>
<pre class="lang-js prettyprint-override"><code>    // 2b) Load an image from which to get data
    var img = new Image;
    img.onload = function(){
      ctx.drawImage( img, 0, 0 );
      // ...and then steps 3 and on
    };
    img.src = "/images/foo.png"; // set this *after* onload
</code>```

Body:
    // 1) Create a canvas, either on the page or simply in code
    var canvas = document.createElement('canvas');
    var ctx    = canvas.getContext('2d');

    // 2) Copy your image data into the canvas
    var myImgElement = document.getElementById('foo');
    ctx.drawImage( myImgElement, 0, 0 );

    // 3) Read your image data
    var w = myImgElement.width, h=myImgElement.height;
    var imgdata = ctx.getImageData(0,0,w,h);
    var rgba = imgdata.data;

    // 4) Read or manipulate the rgba as you wish
    for (var px=0,ct=w*h*4;px<ct;px+=4){
      var r = rgba[px  ];
      var g = rgba[px+1];
      var b = rgba[px+2];
      var a = rgba[px+3];
    }

    // 5) Update the context with newly-modified data
    ctx.putImageData(imgdata,0,0);

    // 6) Draw the image data elsewhere, if you wish
    someOtherContext.drawImage( ctx.canvas, 0, 0 );

Note that step 2 can also be brought in from an image loaded directly into script, not on the page:

    // 2b) Load an image from which to get data
    var img = new Image;
    img.onload = function(){
      ctx.drawImage( img, 0, 0 );
      // ...and then steps 3 and on
    };
    img.src = "/images/foo.png"; // set this *after* onload

ContentLicense: CC BY-SA 4.0


问:
How to fix overlapping objects
I have recently started understanding on how to code in Android Studio and want to set up basic coding. I created 2 number objects and 1 button, 1 plain text object.
Without writing any piece of code, when I click on Run App button on Android Studio and select any Emulator, all the objects stack up on each other. Is there a simple way to fix this?

Following is the text in activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication70.MainActivity">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Result"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="223dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="60dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="134dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="100dp"
        tools:layout_editor_absoluteY="319dp" />

</android.support.constraint.ConstraintLayout>
</code>```

答:
As @RobCo mentioned, the tools namespace attributes are for the editor only:

When you build your app, the build tools remove these attributes so
  there is no effect on your APK size or runtime behavior.

The tools:layout_editor_absolute attributes in your layout file are automatically generated when you move the views in the layout editor, and are only meant to be used as a reference for you when designing your layouts.

Instead, you should take advantage of the app:layout_constraint... attributes, which can also be created in the layout editor. I suggest you take a look at the training documentation to learn how to do this.

Otherwise, as @nbokmans mentioned, you may want to consider a LinearLayout; which could be a little easier to wrap your head around.

Title: How to fix overlapping objects

Body:
I have recently started understanding on how to code in Android Studio and want to set up basic coding. I created 2 number objects and 1 button, 1 plain text object.
Without writing any piece of code, when I click on Run App button on Android Studio and select any Emulator, all the objects stack up on each other. Is there a simple way to fix this?

Following is the text in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication70.MainActivity">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Result"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="223dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="60dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="134dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="100dp"
        tools:layout_editor_absoluteY="319dp" />

</android.support.constraint.ConstraintLayout>


问:
Compare data from two different models with Django
I'm trying to compare two Django models with some common fields (lastname, firstname, ....) in order to apply a process if the answer is "yes" or "no".

I have two models :

Person (which gives the person's identity with lot of fields like lastname, firstname, birthday, ...)

BirthCertificate (it's an act which is filled when a new child is borned with some fields : firstname, lastname, ...)

With this both models, I have common fields and I would to compare these fields in order to apply two different processes.

My models look like :

```<code>class Person(models.Model):

    social_number = models.CharField(max_length=30, null=True, verbose_name='numero social')
    title = models.CharField(max_length=12,choices=TITLE_CHOICES, verbose_name='Civilité')
    young_girl_lastname = models.CharField(max_length=30, verbose_name='Nom de jeune fille', blank=True)
    lastname = models.CharField(max_length=30, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    status = models.CharField(max_length=15, choices=STATUS_CHOICES, verbose_name="Statut civil")
    birthday = models.DateField(verbose_name='Date de naissance')
    birthcity = models.CharField(max_length=30, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    birthmairie = models.CharField(max_length=30, verbose_name='Mairie de naissance')
    nationality = models.CharField(max_length=30, verbose_name='Nationalité')
    job = models.CharField(max_length=30, verbose_name='Profession')
    adress = models.CharField(max_length=30, verbose_name='Adresse')
    city = models.CharField(max_length=30, verbose_name='Ville')
    zip = models.IntegerField(verbose_name='Code Postal')
    country = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays')
    mail = models.CharField(max_length=30, verbose_name='Email', blank=True)
    phone = models.CharField(max_length=20, verbose_name='Téléphone', blank=True)
    created = models.DateTimeField(auto_now_add=True)
    mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie', default=' ')
</code>```

and

```<code>class BirthCertificate(models.Model):

    lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(null=False, verbose_name='Date de naissance')
    birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
    birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    fk_parent1 = models.ForeignKey(Person, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
    fk_parent2 = models.ForeignKey(Person, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
    mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie')
    social_number = models.CharField(max_length=30, null=True, verbose_name='numero social')
    created = models.DateTimeField(auto_now_add=True)
</code>```

First case :

Assuming that we have the same person between Person and BirthCertificate. To do that, we compare 4 fields : lastname, firstname, birthday, birthcity.

If it's true, I pick up the BirthCertificate.social_number and I update my field Person.social_number by the previous value.

If it's false, I create a new social_number in Person and I update Person.social_number by the new one.

Typically, the true possibility corresponds to a new baby. Firstly we make a BirthCertificate then we create an IdentityCertificate with more details. The false possibility corresponds to an adult without BirthCertificate.

To the end, the goal is to give a unique social number to each person.

My function looks like this :

```<code>@login_required
def Identity_Resume(request, id) :

    # Form is validated with an empty `social_number` field
    # I pick up data previously created
    person = get_object_or_404(Person, pk=id)

    blastname = BirthCertificate.objects.all().values("lastname")
    bfirstname = BirthCertificate.objects.all().values("firstname")
    bbirthday = BirthCertificate.objects.all().values("birthday")
    bbirthcity = BirthCertificate.objects.all().values("birthcity")

    if person.lastname == blastname and person.firstname == bfirstname and person.birthday == bbirthday and person.birthcity == bbirthcity :
        # If all fields are identicals, I pick up the `social_number` from the true BirthCertificate id

    else :

        #Homme = 1 / Femme = 2
        sex_number = []
        if person.sex == 'Masculin' :
            sex_number = 1
            print sex_number
        else :
            sex_number = 2
            print sex_number

        #Récupère année de naissance
        birthyear_temp = str(person.birthday.year)
        birthyear_temp2 = str(birthyear_temp.split(" "))
        birthyear = birthyear_temp2[4] + birthyear_temp2[5]

        #Récupère mois de naissance
        birthmonth_temp = person.birthday.month
        if len(str(birthmonth_temp)) == 1 :
            birthmonth = '0' + str(birthmonth_temp)
        else :
            birthmonth = birthmonth_temp

        #Récupère N° Mairie (ici récupère nom mais sera changé en n°)
        birth_mairie = person.birthmairie
        print birth_mairie

        #Génère un nombre aléaloire :
        key_temp = randint(0,999999)
        if len(str(key_temp)) == 1 :
            key = '00000' + str(key_temp)
        elif len(str(key_temp)) == 2 :
            key = '0000' + str(key_temp)
        elif len(str(key_temp)) == 3 :
            key = '000' + str(key_temp)
        elif len(str(key_temp)) == 4 :
            key = '00' + str(key_temp)
        elif len(str(key_temp)) == 5 :
            key = '0' + str(key_temp)
        else :
            key = key_temp
        print key

        social_number = str(sex_number) + ' ' + str(birthyear) + ' ' + str(birthmonth) + ' ' + str(birth_mairie) + ' - ' + str(key)
        print social_number

        #Mise à jour du champ numéro sécurité social
        person.social_number = social_number
        person.save()

    context = {
                "person" : person,
                "social_number" : social_number,
                "blastname" : blastname,
                "bfirstname" : bfirstname,
                "bbirthday" : bbirthday,
                "bbirthcity" : bbirthcity,
    }

    return render(request, 'identity_resume.html', context)
</code>```

My question is :

How I can write the comparing part in my code ?

I apologize for many English mistakes and hopfully being concious.

Thank you

EDIT :

```<code>@login_required
def Identity_Resume(request, id) :

    # Form is validated with an empty `social_number` field
    # I pick up data previously created
    person = get_object_or_404(Person, pk=id)

    social_number = BirthCertificate.objects.filter(firstname=person.firstname, lastname=person.lastname, birthday=person.birthday, birthcity=person.birthcity).values('social_number')
    print social_number

    if social_number.exists() :
        person.social_number = social_number
        person.save()
</code>```

But I get :

```<code><QuerySet [{'social_number': u'2 08 12 STRASBOURG - 039838'}]>
</code>```

and not only :

```<code>2 08 12 STRASBOURG - 039838
</code>```

答:
I think you cannot do this way since BirthCertificate.objects.all().values("lastname") gives a ValueQuerySet

So you can do

```<code>if BirthCertificate.objects.filter(
    firstname=person.firstname,
    lastname=person.lastname,
    etc..).exists(): #etc means other fields.
</code>```

UPDATE

```<code>person = get_object_or_404(Person, pk=id)

obj = BirthCertificate.objects.filter(firstname=person.firstname, lastname=person.lastname, birthday=person.birthday, birthcity=person.birthcity)

if obj:
    sc_obj = obj[0] #check if multiple objects are there, means obj[1]
    person.social_number = sc_obj.social_number
    person.save()
</code>```

Body:
I'm trying to compare two Django models with some common fields (lastname, firstname, ....) in order to apply a process if the answer is "yes" or "no".

I have two models :

Person (which gives the person's identity with lot of fields like lastname, firstname, birthday, ...)

BirthCertificate (it's an act which is filled when a new child is borned with some fields : firstname, lastname, ...)

With this both models, I have common fields and I would to compare these fields in order to apply two different processes.

My models look like :

class Person(models.Model):

    social_number = models.CharField(max_length=30, null=True, verbose_name='numero social')
    title = models.CharField(max_length=12,choices=TITLE_CHOICES, verbose_name='Civilité')
    young_girl_lastname = models.CharField(max_length=30, verbose_name='Nom de jeune fille', blank=True)
    lastname = models.CharField(max_length=30, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    status = models.CharField(max_length=15, choices=STATUS_CHOICES, verbose_name="Statut civil")
    birthday = models.DateField(verbose_name='Date de naissance')
    birthcity = models.CharField(max_length=30, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    birthmairie = models.CharField(max_length=30, verbose_name='Mairie de naissance')
    nationality = models.CharField(max_length=30, verbose_name='Nationalité')
    job = models.CharField(max_length=30, verbose_name='Profession')
    adress = models.CharField(max_length=30, verbose_name='Adresse')
    city = models.CharField(max_length=30, verbose_name='Ville')
    zip = models.IntegerField(verbose_name='Code Postal')
    country = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays')
    mail = models.CharField(max_length=30, verbose_name='Email', blank=True)
    phone = models.CharField(max_length=20, verbose_name='Téléphone', blank=True)
    created = models.DateTimeField(auto_now_add=True)
    mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie', default=' ')

and

class BirthCertificate(models.Model):

    lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(null=False, verbose_name='Date de naissance')
    birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
    birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    fk_parent1 = models.ForeignKey(Person, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
    fk_parent2 = models.ForeignKey(Person, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
    mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie')
    social_number = models.CharField(max_length=30, null=True, verbose_name='numero social')
    created = models.DateTimeField(auto_now_add=True)

First case :

Assuming that we have the same person between Person and BirthCertificate. To do that, we compare 4 fields : lastname, firstname, birthday, birthcity.

If it's true, I pick up the BirthCertificate.social_number and I update my field Person.social_number by the previous value.

If it's false, I create a new social_number in Person and I update Person.social_number by the new one.

Typically, the true possibility corresponds to a new baby. Firstly we make a BirthCertificate then we create an IdentityCertificate with more details. The false possibility corresponds to an adult without BirthCertificate.

To the end, the goal is to give a unique social number to each person.

My function looks like this :

@login_required
def Identity_Resume(request, id) :

    # Form is validated with an empty `social_number` field
    # I pick up data previously created
    person = get_object_or_404(Person, pk=id)

    blastname = BirthCertificate.objects.all().values("lastname")
    bfirstname = BirthCertificate.objects.all().values("firstname")
    bbirthday = BirthCertificate.objects.all().values("birthday")
    bbirthcity = BirthCertificate.objects.all().values("birthcity")

    if person.lastname == blastname and person.firstname == bfirstname and person.birthday == bbirthday and person.birthcity == bbirthcity :
        # If all fields are identicals, I pick up the `social_number` from the true BirthCertificate id

    else :

        #Homme = 1 / Femme = 2
        sex_number = []
        if person.sex == 'Masculin' :
            sex_number = 1
            print sex_number
        else :
            sex_number = 2
            print sex_number

        #Récupère année de naissance
        birthyear_temp = str(person.birthday.year)
        birthyear_temp2 = str(birthyear_temp.split(" "))
        birthyear = birthyear_temp2[4] + birthyear_temp2[5]

        #Récupère mois de naissance
        birthmonth_temp = person.birthday.month
        if len(str(birthmonth_temp)) == 1 :
            birthmonth = '0' + str(birthmonth_temp)
        else :
            birthmonth = birthmonth_temp

        #Récupère N° Mairie (ici récupère nom mais sera changé en n°)
        birth_mairie = person.birthmairie
        print birth_mairie

        #Génère un nombre aléaloire :
        key_temp = randint(0,999999)
        if len(str(key_temp)) == 1 :
            key = '00000' + str(key_temp)
        elif len(str(key_temp)) == 2 :
            key = '0000' + str(key_temp)
        elif len(str(key_temp)) == 3 :
            key = '000' + str(key_temp)
        elif len(str(key_temp)) == 4 :
            key = '00' + str(key_temp)
        elif len(str(key_temp)) == 5 :
            key = '0' + str(key_temp)
        else :
            key = key_temp
        print key

        social_number = str(sex_number) + ' ' + str(birthyear) + ' ' + str(birthmonth) + ' ' + str(birth_mairie) + ' - ' + str(key)
        print social_number

        #Mise à jour du champ numéro sécurité social
        person.social_number = social_number
        person.save()

    context = {
                "person" : person,
                "social_number" : social_number,
                "blastname" : blastname,
                "bfirstname" : bfirstname,
                "bbirthday" : bbirthday,
                "bbirthcity" : bbirthcity,
    }

    return render(request, 'identity_resume.html', context)

My question is :

How I can write the comparing part in my code ?

I apologize for many English mistakes and hopfully being concious.

Thank you

EDIT :

@login_required
def Identity_Resume(request, id) :

    # Form is validated with an empty `social_number` field
    # I pick up data previously created
    person = get_object_or_404(Person, pk=id)

    social_number = BirthCertificate.objects.filter(firstname=person.firstname, lastname=person.lastname, birthday=person.birthday, birthcity=person.birthcity).values('social_number')
    print social_number

    if social_number.exists() :
        person.social_number = social_number
        person.save()

But I get :

<QuerySet [{'social_number': u'2 08 12 STRASBOURG - 039838'}]>

and not only :

2 08 12 STRASBOURG - 039838

Body:
I think you cannot do this way since BirthCertificate.objects.all().values("lastname") gives a ValueQuerySet

So you can do

if BirthCertificate.objects.filter(
    firstname=person.firstname,
    lastname=person.lastname,
    etc..).exists(): #etc means other fields.

UPDATE

person = get_object_or_404(Person, pk=id)

obj = BirthCertificate.objects.filter(firstname=person.firstname, lastname=person.lastname, birthday=person.birthday, birthcity=person.birthcity)

if obj:
    sc_obj = obj[0] #check if multiple objects are there, means obj[1]
    person.social_number = sc_obj.social_number
    person.save()


问:
matrix max a la matlab on gpu
I'm porting some code from Matlab to run on an Nvidia GPU. I can't figure out a way to do the following:

```<code>B = max(A, 0)
</code>```

where A and B are matrices. In words, I need to replace negative values in a matrix with zeros. I know how to write a kernel function to do with, but I'd like to stick with cuBLAS or magma calls if possible (to avoid adding nvcc to my build process).

答:
I've come up with something using thrust:

```<code>thrust::transform(A, A + m*n, [](double x) { thrust::max(x,0.0); });
</code>```

If this is incorrect, or if there is a better solution I'm open for other suggestions.

Title: matrix max a la matlab on gpu

Body:
I'm porting some code from Matlab to run on an Nvidia GPU. I can't figure out a way to do the following:

B = max(A, 0)

where A and B are matrices. In words, I need to replace negative values in a matrix with zeros. I know how to write a kernel function to do with, but I'd like to stick with cuBLAS or magma calls if possible (to avoid adding nvcc to my build process).

Body:
I've come up with something using thrust:

thrust::transform(A, A + m*n, [](double x) { thrust::max(x,0.0); });

If this is incorrect, or if there is a better solution I'm open for other suggestions.


问:
Excel SUMIFS on single criteria with zero and non-zero values
I'm trying to figure out a formula for SUMIFS where a multi-criteria range may or may not contain zero. Take the following table for example.

```<code>|Title    |Age|Color
|---------|---|------
|Odyssey  |5  |Brown
|Tempest  |2  |Yellow
|Iliad    |3  |
|Macbeth  |9  |Brown
</code>```

My goal is to get a SUMIFS where Color is 'Brown' or blank. What I've tried is

```<code>=SUMIFS(B2:B5,C2:C5,{"Brown",""})
</code>```

However, this returns a value of '14' which is a sum of Brown values only and does not sum the '3' from the blank color row. If I switch it up and use

```<code>=SUMIFS(B2:B5,C2:C5,{"","Brown"})
</code>```

it returns '3' which is just the blank value, and not Brown. It seems to only consider the first value in the array.

What am I doing wrong? What's the correct formula for taking an array where the value can be NULL or a specified value?

PS I've also tried ISBLANK, ISNULL, NULL, etc.

答:
You can also do it by summing two regular SUMIF functions like this:

=SUMIF(C2:C5,"Brown",B2:B5)+SUMIF(C2:C5,"",B2:B5). This yields (5 + 9) + (3) = 17.

For large datasets this is allegedly faster than SUMPRODUCT.

```<code>   A        B    C
1|Title    |Age|Color
 |---------|---|------
2|Odyssey  |5  |Brown
3|Tempest  |2  |Yellow
4|Iliad    |3  |
5|Macbeth  |9  |Brown
</code>```

Body:
I'm trying to figure out a formula for SUMIFS where a multi-criteria range may or may not contain zero. Take the following table for example.

|Title    |Age|Color
|---------|---|------
|Odyssey  |5  |Brown
|Tempest  |2  |Yellow
|Iliad    |3  |
|Macbeth  |9  |Brown

My goal is to get a SUMIFS where Color is 'Brown' or blank. What I've tried is

=SUMIFS(B2:B5,C2:C5,{"Brown",""})

However, this returns a value of '14' which is a sum of Brown values only and does not sum the '3' from the blank color row. If I switch it up and use

=SUMIFS(B2:B5,C2:C5,{"","Brown"})

it returns '3' which is just the blank value, and not Brown. It seems to only consider the first value in the array.

What am I doing wrong? What's the correct formula for taking an array where the value can be NULL or a specified value?

PS I've also tried ISBLANK, ISNULL, NULL, etc.

Body:
You can also do it by summing two regular SUMIF functions like this:

=SUMIF(C2:C5,"Brown",B2:B5)+SUMIF(C2:C5,"",B2:B5). This yields (5 + 9) + (3) = 17.

For large datasets this is allegedly faster than SUMPRODUCT.

   A        B    C
1|Title    |Age|Color
 |---------|---|------
2|Odyssey  |5  |Brown
3|Tempest  |2  |Yellow
4|Iliad    |3  |
5|Macbeth  |9  |Brown


问:
Why isn't autotest working?
I'm trying to use autotest for Rails development. It's supposed to run my tests automatically.

Here's my setup:

```<code>$ which ruby
/usr/bin/ruby

$ ruby -v
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]

$ rails -v
Rails 2.3.9

autotest-rails (4.1.0)
ZenTest (4.4.0)

$ echo $PATH
/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/mysql/bin:/Users/ethan/bin:/opt/local/bin:/usr/local/pgsql/bin:/usr/local/git/bin:/usr/local/oracle/instantclient_10_2
</code>```

Here's the gem environment:

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 1.3.7
  - RUBY VERSION: 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]
  - INSTALLATION DIRECTORY: /Library/Ruby/Gems/1.8
  - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-10
  - GEM PATHS:
     - /Library/Ruby/Gems/1.8
     - /Users/ethan/.gem/ruby/1.8
     - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - :sources => ["http://gemcutter.org"]
  - REMOTE SOURCES:
     - http://gemcutter.org
</code>```

Here's the error. It looks like autotest is trying to use some other version of Ruby.

```<code>$ autotest
loading autotest/rails
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -I.:lib:test -rubygems -e "%w[test/unit test/functional/procurements_controller_test.rb].each { |f| require f }" | unit_diff -u
sh: /usr/local/bin/unit_diff: /usr/local/bin/ruby: bad interpreter: No such file or directory
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:108:in `flush': Broken pipe (Errno::EPIPE)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:108:in `output'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:51:in `setup_mediator'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:39:in `start'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278
    from -e:1
</code>```

答: Rails support seems out of the ZenTest core. Install autotest-rails or downgrade to ZenTest 4.0.0 to have it working again.

Title: Why isn't autotest working?

Body:
I'm trying to use autotest for Rails development. It's supposed to run my tests automatically.

Here's my setup:

$ which ruby
/usr/bin/ruby

$ ruby -v
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]

$ rails -v
Rails 2.3.9

autotest-rails (4.1.0)
ZenTest (4.4.0)

$ echo $PATH
/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/mysql/bin:/Users/ethan/bin:/opt/local/bin:/usr/local/pgsql/bin:/usr/local/git/bin:/usr/local/oracle/instantclient_10_2

Here's the gem environment:

RubyGems Environment:
  - RUBYGEMS VERSION: 1.3.7
  - RUBY VERSION: 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]
  - INSTALLATION DIRECTORY: /Library/Ruby/Gems/1.8
  - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-10
  - GEM PATHS:
     - /Library/Ruby/Gems/1.8
     - /Users/ethan/.gem/ruby/1.8
     - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - :sources => ["http://gemcutter.org"]
  - REMOTE SOURCES:
     - http://gemcutter.org

Here's the error. It looks like autotest is trying to use some other version of Ruby.

$ autotest
loading autotest/rails
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -I.:lib:test -rubygems -e "%w[test/unit test/functional/procurements_controller_test.rb].each { |f| require f }" | unit_diff -u
sh: /usr/local/bin/unit_diff: /usr/local/bin/ruby: bad interpreter: No such file or directory
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:108:in `flush': Broken pipe (Errno::EPIPE)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:108:in `output'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:51:in `setup_mediator'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:39:in `start'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278
    from -e:1


问:
Parent class using default constructor; child class' destructor is unexpectedly called
I had a scenario in C++ that calls the child's destructor in a case where I didn't expect it. A minimal repro is below:

```<code>#include <cstdio>
#include <memory>

using namespace std;

class Parent {
public:
};

class Child : public Parent {
    public:
    ~Child() {
        printf("Got here\n");
    }
};

int
main()
{
    shared_ptr<Parent> x(new Child);
}
</code>```

Usually something like this is a bug. The developer intends that the child destructor is called, and the correct action would be to insert into the parent an empty virtual destructor. However, to my shock, both G++ 4.4.7 (yeah, I know it's old) and clang 3.4.2 compile this such that the child destructor is called.

Does this conform to the standard?

答:
A unique ptr would screw up here.  But shared ptr does some "magic" here.

shared_ptr<T> has two things they manage; theT*` and the reference counting block.

The reference counting block contains two atomic<std::size_t>s, one for strong references and one for weak references, and a type-erased deleter.  This std::function-like type-erased deleter remembers how to delete the thing you own.

When you construct any shared_ptr with a U*u, it by default stores [u]{std::default_delete{}(u);} in that deleter.

In effect, it remembers how to delete the object based on the type passed in.

shared_ptr is exceedingly flexible.

You can pass in a custom deleter to replace the default one, you can use the aliasing constructor to split the reference counting block used from the T* stored, you can use make_shared to allocate the reference counting block and a T in the same memory allocation.

The overhead of the reference counting block is why it stores the deleter; it wasn't viewed as overly expensive, given that we needed the block anyhow.  In comparison, unique_ptr by default does no such thing; you have to explicitly add a deleter, and you'd have to manage all of the fancy tricks that shared_ptr does for you by default if you wanted them.  unique_ptr has basically zero overhead over a raw owning pointer; shared_ptr has noticable overhead, but small compared to memory allocation overhead usually.

Body:
I had a scenario in C++ that calls the child's destructor in a case where I didn't expect it. A minimal repro is below:

#include <cstdio>
#include <memory>

using namespace std;

class Parent {
public:
};

class Child : public Parent {
    public:
    ~Child() {
        printf("Got here\n");
    }
};

int
main()
{
    shared_ptr<Parent> x(new Child);
}

Usually something like this is a bug. The developer intends that the child destructor is called, and the correct action would be to insert into the parent an empty virtual destructor. However, to my shock, both G++ 4.4.7 (yeah, I know it's old) and clang 3.4.2 compile this such that the child destructor is called.

Does this conform to the standard?

Body:
A unique ptr would screw up here.  But shared ptr does some "magic" here.

shared_ptr<T> has two things they manage; theT*` and the reference counting block.

The reference counting block contains two atomic<std::size_t>s, one for strong references and one for weak references, and a type-erased deleter.  This std::function-like type-erased deleter remembers how to delete the thing you own.

When you construct any shared_ptr with a U*u, it by default stores [u]{std::default_delete<U>{}(u);} in that deleter.

In effect, it remembers how to delete the object based on the type passed in.

shared_ptr is exceedingly flexible.

You can pass in a custom deleter to replace the default one, you can use the aliasing constructor to split the reference counting block used from the T* stored, you can use make_shared to allocate the reference counting block and a T in the same memory allocation.

The overhead of the reference counting block is why it stores the deleter; it wasn't viewed as overly expensive, given that we needed the block anyhow.  In comparison, unique_ptr by default does no such thing; you have to explicitly add a deleter, and you'd have to manage all of the fancy tricks that shared_ptr does for you by default if you wanted them.  unique_ptr has basically zero overhead over a raw owning pointer; shared_ptr has noticable overhead, but small compared to memory allocation overhead usually.


问:
Typescript, JSON: Mapping nested array always returns empty
I am new to typescript and trying to parse a JSON from a GET request which looks like this (removed some data):

```<code>{
   "currency_rate":1,
   "data":[
     {
        "mapIdfrom":"oslo_no",
        "refr":false,
        "duration":{
        "total":75300,
        "return":0,
        "departure":75300
     },
     "flyTo":"STR"
    }
   ]
}
</code>```

I am getting the "currency_rate" for example, but the "data"-array is empty.

The GET request looks like this (only relevant parts) :

```<code>[...]
api_url = 'https://api.skypicker.com/flights';
[...]
let body =  {
              flyFrom: 'OSL',
              to: 'STR',
              dateFrom: '01%252F04%252F2017',
              dateTo: '20%2F04%2F2017',
              daysInDestinationFrom: 15,
              daysInDestinationTo: 20,
              returnFrom: '01%2F04%2F2017',
              returnTo: '20%2F04%2F2017',
              typeFlight: 'oneway',
              oneforcity: 0,
              one_per_date: 0,
              passengers: 1,
              adults: 1,
              children: 0,
              infants: 0,
              flyDays: '%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D',
              onlyWorkingDays: 0,
              directFlights: 0,
              partner: 'picky',
              partner_market: 'en',
              v: 2,
              xml: 0,
              curr: 'EUR',
              locale: 'en',
              price_from: 1,
              price_to: 10000,
              dtimefrom: '00%3A00',
              dtimeto: '00%3A00',
              atimefrom: '00%3A00',
              atimeto: '00%3A00',
              returndtimefrom: '00%3A00',
              returndtimeto: '00%3A00',
              returnatimefrom: '00%3A00',
              returnatimeto: '00%3A00',
              stopoverfrom: '00%3A00',
              stopoverto: '00%3A00',
              booking_token: 'hashed%20data',
              offset: 0,
              limit: 30,
              sort: 'price',
              asc: 1
            }

let bodyString = JSON.stringify(body)

return this.http.get(`${this.api_url}?${bodyString}`)
  .map(res => <SkyPickerFlight>res.json());
</code>```

The model "SkyPickerFlight" is defined like this:

```<code>import { SkyPickerFlightData } from '../models/skyPickerFlightData';
import { Observable } from 'rxjs/Rx';

export interface SkyPickerFlightI {
  currency: string;
  data: Observable<any[]>;
}
</code>```

I have also tried replacing data: Observable<any[]> with data: Observable<SkyPickerFlightData[]>, the actual object, but also doesn't work.

Here you can get the full GET request:

```<code>https://api.skypicker.com/flights?flyFrom=OSL&to=STR&dateFrom=01%2F04%2F2017&dateTo=20%2F04%2F2017&daysInDestinationFrom=15&daysInDestinationTo=20&returnFrom=01%2F04%2F2017&returnTo=20%2F04%2F2017&typeFlight=oneway&oneforcity=0&one_per_date=0&passengers=1&adults=1&children=0&infants=0&flyDays=%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D&onlyWorkingDays=0&onlyWeekends=0&directFlights=0&partner=picky&partner_market=en&v=2&xml=0&curr=EUR&locale=en&price_from=1&price_to=10000&dtimefrom=00%3A00&dtimeto=00%3A00&atimefrom=00%3A00&atimeto=00%3A00&returndtimefrom=00%3A00&returndtimeto=00%3A00&returnatimefrom=00%3A00&returnatimeto=00%3A00&stopoverfrom=00%3A00&stopoverto=00%3A00&booking_token=hashed%20data&offset=0&limit=30&sort=price&asc=1
</code>```

I am still looking into it but it looks like the GET request is a bit funky using this.http.get(${this.api_url}?${bodyString}) actually returns:

```<code>{"connections":[],"currency":"EUR","del":0,"time":1,"search_params":{"to_type":"anywhere","flyFrom_type":"anywhere","seats":{"infants":0,"passengers":1,"adults":1,"children":0}},"ref_tasks":{},"currency_rate":1.0,"data":[],"refresh":[]}
</code>```

A different result than the GET request above. Not sure if I was clear. But trying the GET request like this (I will spare you with the long definition of the URLSearchParams) ends in a Bad Gateway error:

```<code>return this.http.get(this.api_url, {search: params})
  .map(res => res)
</code>```

---- EDIT -----
It worked after I copy-pasted the entire URL in:

```<code>return this.http.get(<URL PASTED HERE>)
  .map(res => res)
</code>```

Would still like to know how to pass the parameters in a clean way rather than pasting the entire URL in there.

答:
I did not understand what are you trying to achieve by data: Observable<any[]>;. As @suraj said, "A section of your json response would not be an Observable".

As for the answer, I think you do not need to typecast the response into a typical Interface. A simple .map(res => res.json()); would also work. I am assuming you need it like this, but, just saying to make it easier.

Not sure if problem exists there? So, you can do this and check if the data is coming to your GET :

```<code>return Observable.create(observer => {
    this.http.get(`${this.api_url}?${bodyString}`)
      .map(res => res.json())
      .subscribe((data) => {
            console.log("Data : ", data);
            observer.next(data);
      },
      (err) => {
            console.log("Error : ", err);
            observer.error(err);
      });
});
</code>```

Check if above logs the necessary data. If it does then check again by typecasting as you were doing in your code.

Now, here you are returning a new Observable to calling method. So, you will have to subscribe() in calling method as well.

Body:
I am new to typescript and trying to parse a JSON from a GET request which looks like this (removed some data):

{
   "currency_rate":1,
   "data":[
     {
        "mapIdfrom":"oslo_no",
        "refr":false,
        "duration":{
        "total":75300,
        "return":0,
        "departure":75300
     },
     "flyTo":"STR"
    }
   ]
}

I am getting the "currency_rate" for example, but the "data"-array is empty.

The GET request looks like this (only relevant parts) :

[...]
api_url = 'https://api.skypicker.com/flights';
[...]
let body =  {
              flyFrom: 'OSL',
              to: 'STR',
              dateFrom: '01%252F04%252F2017',
              dateTo: '20%2F04%2F2017',
              daysInDestinationFrom: 15,
              daysInDestinationTo: 20,
              returnFrom: '01%2F04%2F2017',
              returnTo: '20%2F04%2F2017',
              typeFlight: 'oneway',
              oneforcity: 0,
              one_per_date: 0,
              passengers: 1,
              adults: 1,
              children: 0,
              infants: 0,
              flyDays: '%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D',
              onlyWorkingDays: 0,
              directFlights: 0,
              partner: 'picky',
              partner_market: 'en',
              v: 2,
              xml: 0,
              curr: 'EUR',
              locale: 'en',
              price_from: 1,
              price_to: 10000,
              dtimefrom: '00%3A00',
              dtimeto: '00%3A00',
              atimefrom: '00%3A00',
              atimeto: '00%3A00',
              returndtimefrom: '00%3A00',
              returndtimeto: '00%3A00',
              returnatimefrom: '00%3A00',
              returnatimeto: '00%3A00',
              stopoverfrom: '00%3A00',
              stopoverto: '00%3A00',
              booking_token: 'hashed%20data',
              offset: 0,
              limit: 30,
              sort: 'price',
              asc: 1
            }

let bodyString = JSON.stringify(body)

return this.http.get(`${this.api_url}?${bodyString}`)
  .map(res => <SkyPickerFlight>res.json());

The model "SkyPickerFlight" is defined like this:

import { SkyPickerFlightData } from '../models/skyPickerFlightData';
import { Observable } from 'rxjs/Rx';

export interface SkyPickerFlightI {
  currency: string;
  data: Observable<any[]>;
}

I have also tried replacing data: Observable<any[]> with data: Observable<SkyPickerFlightData[]>, the actual object, but also doesn't work.

Here you can get the full GET request:

https://api.skypicker.com/flights?flyFrom=OSL&to=STR&dateFrom=01%2F04%2F2017&dateTo=20%2F04%2F2017&daysInDestinationFrom=15&daysInDestinationTo=20&returnFrom=01%2F04%2F2017&returnTo=20%2F04%2F2017&typeFlight=oneway&oneforcity=0&one_per_date=0&passengers=1&adults=1&children=0&infants=0&flyDays=%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D&onlyWorkingDays=0&onlyWeekends=0&directFlights=0&partner=picky&partner_market=en&v=2&xml=0&curr=EUR&locale=en&price_from=1&price_to=10000&dtimefrom=00%3A00&dtimeto=00%3A00&atimefrom=00%3A00&atimeto=00%3A00&returndtimefrom=00%3A00&returndtimeto=00%3A00&returnatimefrom=00%3A00&returnatimeto=00%3A00&stopoverfrom=00%3A00&stopoverto=00%3A00&booking_token=hashed%20data&offset=0&limit=30&sort=price&asc=1

I am still looking into it but it looks like the GET request is a bit funky using this.http.get(${this.api_url}?${bodyString}) actually returns:

{"connections":[],"currency":"EUR","del":0,"time":1,"search_params":{"to_type":"anywhere","flyFrom_type":"anywhere","seats":{"infants":0,"passengers":1,"adults":1,"children":0}},"ref_tasks":{},"currency_rate":1.0,"data":[],"refresh":[]}

A different result than the GET request above. Not sure if I was clear. But trying the GET request like this (I will spare you with the long definition of the URLSearchParams) ends in a Bad Gateway error:

return this.http.get(this.api_url, {search: params})
  .map(res => res)

---- EDIT -----
It worked after I copy-pasted the entire URL in:

return this.http.get(<URL PASTED HERE>)
  .map(res => res)

Would still like to know how to pass the parameters in a clean way rather than pasting the entire URL in there.

Body:
I did not understand what are you trying to achieve by data: Observable<any[]>;. As @suraj said, "A section of your json response would not be an Observable".

As for the answer, I think you do not need to typecast the response into a typical Interface. A simple .map(res => res.json()); would also work. I am assuming you need it like this, but, just saying to make it easier.

Not sure if problem exists there? So, you can do this and check if the data is coming to your GET :

return Observable.create(observer => {
    this.http.get(`${this.api_url}?${bodyString}`)
      .map(res => res.json())
      .subscribe((data) => {
            console.log("Data : ", data);
            observer.next(data);
      },
      (err) => {
            console.log("Error : ", err);
            observer.error(err);
      });
});

Check if above logs the necessary data. If it does then check again by typecasting as you were doing in your code.

Now, here you are returning a new Observable to calling method. So, you will have to subscribe() in calling method as well.


问:
Asking to remove the time in datetime without changing the datatype
I want to ask about this one

How to remove the time in "Tanggal" column, without changing its datatype?

How to remove the 2 last digit 0 in "Harga" column?

Thank you

答:
You can use dateadd() to truncate the time portion like so:

```<code>dateadd(day, datediff(day, 0, b.Tanggal), 0) as Tanggal
</code>```

Body:
You can use dateadd() to truncate the time portion like so:

dateadd(day, datediff(day, 0, b.Tanggal), 0) as Tanggal