问:
Trying to store input as a Hashmap in ruby
I am trying to store a user input as a hashmap using Ruby. The desired result from this would be (assuming the user inputs, 5,5,N)

position = {"x" => 5; "y" => 5; D => "N"}

```<code>def rover_position()
  position = {}
  puts "Please input the rovers X position  "
  position["x"] = gets.chomp
  puts "Please input the rovers Y position  "
  position["y"] = gets.chomp
  puts "Please input the rovers Direction (N,E,S,W)  "
  position["D"] = gets.chomp

end
</code>```

答:
Don't rebuild the hash, you've already built it. Just do:

```<code>def rover_position()
  position = {}
  puts "Please input the rovers X position  "
  position["x"] = gets.chomp
  puts "Please input the rovers Y position  "
  position["y"] = gets.chomp
  puts "Please input the rovers Direction (N,E,S,W)  "
  position["D"] = gets.chomp
  position
end
</code>```

In console, that looks like:

```<code>2.3.1 :001 > def rover_position()
2.3.1 :002?>   position = {}
2.3.1 :003?>   puts "Please input the rovers X position  "
2.3.1 :004?>   position["x"] = gets.chomp
2.3.1 :005?>   puts "Please input the rovers Y position  "
2.3.1 :006?>   position["y"] = gets.chomp
2.3.1 :007?>   puts "Please input the rovers Direction (N,E,S,W)  "
2.3.1 :008?>   position["D"] = gets.chomp
2.3.1 :009?>   position
2.3.1 :010?> end
 => :rover_position
2.3.1 :011 >
2.3.1 :012 >   position = rover_position
Please input the rovers X position
5
Please input the rovers Y position
5
Please input the rovers Direction (N,E,S,W)
N
 => {"x"=>"5", "y"=>"5", "D"=>"N"}
2.3.1 :013 > position
 => {"x"=>"5", "y"=>"5", "D"=>"N"}
</code>```

If you wanted, you could clean that up a little and do something like:

```<code>def rover_position
  {
    x: "x position",
    y: "y position",
    D: "Direction (N,E,S,W)"
  }.each_with_object({}) do |(key, message), hsh|
    puts "Please input the rovers #{message}"
    hsh[key] = gets.chomp
  end
end
</code>```

Again, in console:

```<code>2.3.1 :001 > def rover_position
2.3.1 :002?>   {
2.3.1 :003 >     x: "x position",
2.3.1 :004 >     y: "y position",
2.3.1 :005 >     D: "Direction (N,E,S,W)"
2.3.1 :006?>   }.each_with_object({}) do |(key, message), hsh|
2.3.1 :007 >     puts "Please input the rovers #{message}"
2.3.1 :008?>     hsh[key] = gets.chomp
2.3.1 :009?>   end
2.3.1 :010?> end
 => :rover_position
2.3.1 :011 > position = rover_position
Please input the rovers x position
5
Please input the rovers y position
5
Please input the rovers Direction (N,E,S,W)
N
 => {:x=>"5", :y=>"5", :D=>"N"}
2.3.1 :012 > position[:x]
 => "5"
2.3.1 :013 > position[:y]
 => "5"
2.3.1 :014 > position[:D]
 => "N"
</code>```

Body:
I am trying to store a user input as a hashmap using Ruby. The desired result from this would be (assuming the user inputs, 5,5,N)

position = {"x" => 5; "y" => 5; D => "N"}

def rover_position()
  position = {}
  puts "Please input the rovers X position  "
  position["x"] = gets.chomp
  puts "Please input the rovers Y position  "
  position["y"] = gets.chomp
  puts "Please input the rovers Direction (N,E,S,W)  "
  position["D"] = gets.chomp

end

Body:
Don't rebuild the hash, you've already built it. Just do:

def rover_position()
  position = {}
  puts "Please input the rovers X position  "
  position["x"] = gets.chomp
  puts "Please input the rovers Y position  "
  position["y"] = gets.chomp
  puts "Please input the rovers Direction (N,E,S,W)  "
  position["D"] = gets.chomp
  position
end

In console, that looks like:

2.3.1 :001 > def rover_position()
2.3.1 :002?>   position = {}
2.3.1 :003?>   puts "Please input the rovers X position  "
2.3.1 :004?>   position["x"] = gets.chomp
2.3.1 :005?>   puts "Please input the rovers Y position  "
2.3.1 :006?>   position["y"] = gets.chomp
2.3.1 :007?>   puts "Please input the rovers Direction (N,E,S,W)  "
2.3.1 :008?>   position["D"] = gets.chomp
2.3.1 :009?>   position
2.3.1 :010?> end
 => :rover_position
2.3.1 :011 >
2.3.1 :012 >   position = rover_position
Please input the rovers X position
5
Please input the rovers Y position
5
Please input the rovers Direction (N,E,S,W)
N
 => {"x"=>"5", "y"=>"5", "D"=>"N"}
2.3.1 :013 > position
 => {"x"=>"5", "y"=>"5", "D"=>"N"}

If you wanted, you could clean that up a little and do something like:

def rover_position
  {
    x: "x position",
    y: "y position",
    D: "Direction (N,E,S,W)"
  }.each_with_object({}) do |(key, message), hsh|
    puts "Please input the rovers #{message}"
    hsh[key] = gets.chomp
  end
end

Again, in console:

2.3.1 :001 > def rover_position
2.3.1 :002?>   {
2.3.1 :003 >     x: "x position",
2.3.1 :004 >     y: "y position",
2.3.1 :005 >     D: "Direction (N,E,S,W)"
2.3.1 :006?>   }.each_with_object({}) do |(key, message), hsh|
2.3.1 :007 >     puts "Please input the rovers #{message}"
2.3.1 :008?>     hsh[key] = gets.chomp
2.3.1 :009?>   end
2.3.1 :010?> end
 => :rover_position
2.3.1 :011 > position = rover_position
Please input the rovers x position
5
Please input the rovers y position
5
Please input the rovers Direction (N,E,S,W)
N
 => {:x=>"5", :y=>"5", :D=>"N"}
2.3.1 :012 > position[:x]
 => "5"
2.3.1 :013 > position[:y]
 => "5"
2.3.1 :014 > position[:D]
 => "N"


来源: stackexchange

问:
How to set the modified date of a file to that of the most recently modified of a list of files?
During a build process using Ant, I want to update the last modified date of a generated file.  I am concatenating (using concat task) several files to generate this file, and I want to set the modified date of this file to the date of the most recently modified of the source files.

I don't see any option in the touch task to use several files as the source for the date.

答:
Here's an example solution:

```<code><scriptdef name="filedate" language="javascript">
  <attribute name="file"/>
  <attribute name="property"/>
  <![CDATA[
    var file_name = attributes.get( "file" );
    var property_to_set = attributes.get( "property" );

    var file = new java.io.File( file_name );
    var file_date = file.lastModified();

    project.setProperty( property_to_set, file_date );
  ]]>
</scriptdef>

<last id="last.dir">
  <sort>
    <fileset dir="folder" includes="*" />
    <date />
  </sort>
</last>

<filedate file="${ant.refid:last.dir}" property="file.ts" />

<touch file="concat.file" millis="${file.ts}" />
</code>```

The scriptdef is derived from this answer by David W. and simplified as we don't need to format the date-time, we can just use the "epoch milliseconds" that Java File lastModified() provides and the Ant touch task expects.

ContentLicense: CC BY-SA 3.0

Body:
Here's an example solution:

<scriptdef name="filedate" language="javascript">
  <attribute name="file"/>
  <attribute name="property"/>
  <![CDATA[
    var file_name = attributes.get( "file" );
    var property_to_set = attributes.get( "property" );

    var file = new java.io.File( file_name );
    var file_date = file.lastModified();

    project.setProperty( property_to_set, file_date );
  ]]>
</scriptdef>

<last id="last.dir">
  <sort>
    <fileset dir="folder" includes="*" />
    <date />
  </sort>
</last>

<filedate file="${ant.refid:last.dir}" property="file.ts" />

<touch file="concat.file" millis="${file.ts}" />

The scriptdef is derived from this answer by David W. and simplified as we don't need to format the date-time, we can just use the "epoch milliseconds" that Java File lastModified() provides and the Ant touch task expects.


问:
R: Keep values below the 99 quantile for groups in data frame
I have a dataframe with groups and values. Firstly, I calculate 99% quantile per group. Now, I want to remove the values above the 99% quantile for every group.

```<code>df<-data.frame(group = rep(c("A", "B"), each = 4),
               value = c(c(6,5,80,4,60)*10,3,5,4))

# data
  group value
1     A    60
2     A    50
3     A   800
4     A    40
5     B   600
6     B     3
7     B     5
8     B     4
</code>```

Calculate quantils for individual groups

```<code>quant<-aggregate(df$value, by = list(df$group), FUN = quantile, probs  = 0.99)

> quant
  Group.1      x
1       A 777.80
2       B 582.15
</code>```

I tried to apply the vector of quantiles to select lower values. However, it miss the group specification..

```<code>df[df$value < quant$x,]
</code>```

Expected result:

```<code>  group value
1     A    60
2     A    50
4     A    40
5     B     3
6     B     5
7     B     4
</code>```

How to apply vector of quantiles to keep only values below 99% by group in data frame?

答:
We can do a filter after grouping

```<code>library(dplyr)
df %>%
   group_by(group) %>%
   filter(value < quantile(value, probs = 0.99))
# A tibble: 6 x 2
# Groups:   group [2]
#   group value
#  <fctr> <dbl>
#1      A    60
#2      A    50
#3      A    40
#4      B     3
#5      B     5
#6      B     4
</code>```

Or similar syntax with data.table

```<code>library(data.table)
setDT(df)[, .(value = value[value < quantile(value, probs = 0.99)]), by = group]
</code>```

Or using base R using ave

```<code>df[with(df, as.logical(ave(value, group, FUN= function(x) x <quantile(x, probs = 0.99)))), ]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe with groups and values. Firstly, I calculate 99% quantile per group. Now, I want to remove the values above the 99% quantile for every group.

df<-data.frame(group = rep(c("A", "B"), each = 4),
               value = c(c(6,5,80,4,60)*10,3,5,4))

# data
  group value
1     A    60
2     A    50
3     A   800
4     A    40
5     B   600
6     B     3
7     B     5
8     B     4

Calculate quantils for individual groups

quant<-aggregate(df$value, by = list(df$group), FUN = quantile, probs  = 0.99)

> quant
  Group.1      x
1       A 777.80
2       B 582.15

I tried to apply the vector of quantiles to select lower values. However, it miss the group specification..

df[df$value < quant$x,]

Expected result:

  group value
1     A    60
2     A    50
4     A    40
5     B     3
6     B     5
7     B     4

How to apply vector of quantiles to keep only values below 99% by group in data frame?

Body:
We can do a filter after grouping

library(dplyr)
df %>%
   group_by(group) %>%
   filter(value < quantile(value, probs = 0.99))
# A tibble: 6 x 2
# Groups:   group [2]
#   group value
#  <fctr> <dbl>
#1      A    60
#2      A    50
#3      A    40
#4      B     3
#5      B     5
#6      B     4

Or similar syntax with data.table

library(data.table)
setDT(df)[, .(value = value[value < quantile(value, probs = 0.99)]), by = group]

Or using base R using ave

df[with(df, as.logical(ave(value, group, FUN= function(x) x <quantile(x, probs = 0.99)))), ]


问:
How to convert MM/YY to MM/DD/YYYY in Excel (missing day)
The day is missing so it just needs to be first of the month so:

11/17 would be 11/01/2017

Is there a formula that can do this?

答:
This is probably a stupid formula but it worked for me;

```<code>=DATE(100 + RIGHT(TEXT(A6,"MM/YY"),2),LEFT(TEXT(A6,"MM/YY"),2),1)
</code>```

Try it out it takes the existing "MM/YY" format and converts it to a MM/DD/YYYY date using the date foromula =DATE(Year,Month,Day).  It works if the date is in date format or text format.

Body:
This is probably a stupid formula but it worked for me;

=DATE(100 + RIGHT(TEXT(A6,"MM/YY"),2),LEFT(TEXT(A6,"MM/YY"),2),1)

Try it out it takes the existing "MM/YY" format and converts it to a MM/DD/YYYY date using the date foromula =DATE(Year,Month,Day).  It works if the date is in date format or text format.


问:
D3 V3 to D3 V4 Tree Array Reordered Wrong Using Hierarchy
This may sound more complex than I intend it to, however, I am switching from D3 V3 to D3 V4. ALL of my other graphs and charts have transferred over really easily, but this specific one (a tree) is causing all sorts of grief from changing from d3.layout.tree and simply using the .children() function then setting nodes/links the old way to the new way using d3.hierarchy(). I set it the way that I've seen in countless tutorials.

I have 2 different Plunkers set up.
This one is in D3 V3 and is working/displaying properly with the correct array order:
https://plnkr.co/edit/qXDWDGzhNIM2tTOoAXRa?p=preview

```<code>var tree = d3.layout.tree()
                .nodeSize([0, 75])
                .children(function(d) {
                    return d.subsidiaries;
                });

            var line = d3.svg.line().interpolate('step')
                .x(function(d) {
                    return d.x;
                })
                .y(function(d) {
                    return d.y - 12;
                });

            // Define 'div' for tooltips
            var div = d3.select('#tree')
                // Declare the tooltip div
                .append('div')
                // Apply the 'tooltip' class
                .attr('class', 'tooltip')
                .style('opacity', 0);

            var svg = d3.select('#tree').append('svg')
                .attr('width', width + margin.left + margin.right)
                .append('g')
                .attr('transform', `translate(${ margin.left },${ margin.top })`);

            function lineData(d) {
                var points = [{
                    x: d.source.y,
                    y: d.source.x
                }, {
                    x: d.target.y,
                    y: d.target.x
                }];

                return line(points);
            }

            root = treeData;
            root.x0 = 0;
            root.y0 = 0;

            update(root);

            function update(source) {
                // Compute the flattened node list.
                var nodes = tree.nodes(root);
                console.log(nodes);

                var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

                d3.select('svg').transition()
                    .duration(duration)
                    .attr('height', height);

                d3.select(window.frameElement).transition()
                    .duration(duration)
                    .style('height', `${ height }px`);

                // Compute the layout.
                nodes.forEach(function(n, i) {
                    n.x = i * barHeight;
                });

                // Update the nodes.
                var node = svg.selectAll('g.node')
                    .data(nodes, function(d) {
                        return d.id || (d.id = ++i);
                    });
</code>```

This second one is in D3 V4, and it's clear to tell that the array order is extremely incorrect. Many of the objects are moved up the list from where they are supposed to be, so it's causing a weird collided effect as seen here:
https://plnkr.co/edit/PGPw92URj24yDMrPenwE?p=preview

```<code>function _drawTree(treeData) {
            // This solves the maximum call stack issue with d3 layout function
            const margin = {
                    top: 55,
                    right: 20,
                    bottom: 30,
                    left: 30
                },
                width = 960 - margin.left - margin.right,
                barHeight = 65,
                barWidth = width * 0.35,
                duration = 400,
                treeMap = d3.tree()
                    .nodeSize([0, 75]);

            let i = 0,
                root;

            var line = d3.line()
                .x(d => d.x)
                .y(d => d.y - 12)
                .curve(d3.curveStep);

            // Define 'div' for tooltips
            var div = d3.select('#tree')
                // Declare the tooltip div
                .append('div')
                // Apply the 'tooltip' class
                .attr('class', 'tooltip')
                .style('opacity', 0);

            var svg = d3.select('#tree').append('svg')
                .attr('width', width + margin.left + margin.right)
                .append('g')
                .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

             function lineData(d) {
                var points = [{
                    x: d.source.y,
                    y: d.source.x
                }, {
                    x: d.target.y,
                    y: d.target.x
                }];

                return line(points);
            }

            root = d3.hierarchy(treeData, d => {
                return d.subsidiaries;
                });
            root.x0 = 0;
            root.y0 = 0;

            update(root);

            function update(source) {
                var tree = treeMap(root);

                var nodes = tree.descendants(root);

                console.log(nodes);

                // Compute the flattened node list.
                var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

                d3.select('svg').transition()
                    .duration(duration)
                    .attr('height', height);

                d3.select(window.frameElement).transition()
                    .duration(duration)
                    .style('height', height + 'px');

                // Compute the layout.
                nodes.forEach((n, i) => {
                    n.x = i * barHeight;
                });
</code>```

I've logged the necessary variables, and you can view them by popping open your dev console.

I'm not sure if this is enough information or not, please let me know if you need more! Thanks for the help!!!

答:
It turns out that the answer was actually relatively simple. I was using forEach instead of eachBefore when laying out the nodes. The solution on this GitHub Issue.

They link to this example, and the correct fix is this:

```<code>// Compute the "layout". TODO https://github.com/d3/d3-hierarchy/issues/67
var index = -1;
root.eachBefore(function(n) {
    n.x = ++index * barHeight;
    n.y = n.depth * 20;
});
</code>```

I have also updated my Plunker with the correct code in action...

Body:
This may sound more complex than I intend it to, however, I am switching from D3 V3 to D3 V4. ALL of my other graphs and charts have transferred over really easily, but this specific one (a tree) is causing all sorts of grief from changing from d3.layout.tree and simply using the .children() function then setting nodes/links the old way to the new way using d3.hierarchy(). I set it the way that I've seen in countless tutorials.

I have 2 different Plunkers set up.
This one is in D3 V3 and is working/displaying properly with the correct array order:
https://plnkr.co/edit/qXDWDGzhNIM2tTOoAXRa?p=preview

var tree = d3.layout.tree()
                .nodeSize([0, 75])
                .children(function(d) {
                    return d.subsidiaries;
                });

            var line = d3.svg.line().interpolate('step')
                .x(function(d) {
                    return d.x;
                })
                .y(function(d) {
                    return d.y - 12;
                });

            // Define 'div' for tooltips
            var div = d3.select('#tree')
                // Declare the tooltip div
                .append('div')
                // Apply the 'tooltip' class
                .attr('class', 'tooltip')
                .style('opacity', 0);

            var svg = d3.select('#tree').append('svg')
                .attr('width', width + margin.left + margin.right)
                .append('g')
                .attr('transform', `translate(${ margin.left },${ margin.top })`);

            function lineData(d) {
                var points = [{
                    x: d.source.y,
                    y: d.source.x
                }, {
                    x: d.target.y,
                    y: d.target.x
                }];

                return line(points);
            }

            root = treeData;
            root.x0 = 0;
            root.y0 = 0;

            update(root);

            function update(source) {
                // Compute the flattened node list.
                var nodes = tree.nodes(root);
                console.log(nodes);

                var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

                d3.select('svg').transition()
                    .duration(duration)
                    .attr('height', height);

                d3.select(window.frameElement).transition()
                    .duration(duration)
                    .style('height', `${ height }px`);

                // Compute the layout.
                nodes.forEach(function(n, i) {
                    n.x = i * barHeight;
                });

                // Update the nodes.
                var node = svg.selectAll('g.node')
                    .data(nodes, function(d) {
                        return d.id || (d.id = ++i);
                    });

This second one is in D3 V4, and it's clear to tell that the array order is extremely incorrect. Many of the objects are moved up the list from where they are supposed to be, so it's causing a weird collided effect as seen here:
https://plnkr.co/edit/PGPw92URj24yDMrPenwE?p=preview

function _drawTree(treeData) {
            // This solves the maximum call stack issue with d3 layout function
            const margin = {
                    top: 55,
                    right: 20,
                    bottom: 30,
                    left: 30
                },
                width = 960 - margin.left - margin.right,
                barHeight = 65,
                barWidth = width * 0.35,
                duration = 400,
                treeMap = d3.tree()
                    .nodeSize([0, 75]);

            let i = 0,
                root;

            var line = d3.line()
                .x(d => d.x)
                .y(d => d.y - 12)
                .curve(d3.curveStep);

            // Define 'div' for tooltips
            var div = d3.select('#tree')
                // Declare the tooltip div
                .append('div')
                // Apply the 'tooltip' class
                .attr('class', 'tooltip')
                .style('opacity', 0);

            var svg = d3.select('#tree').append('svg')
                .attr('width', width + margin.left + margin.right)
                .append('g')
                .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

             function lineData(d) {
                var points = [{
                    x: d.source.y,
                    y: d.source.x
                }, {
                    x: d.target.y,
                    y: d.target.x
                }];

                return line(points);
            }

            root = d3.hierarchy(treeData, d => {
                return d.subsidiaries;
                });
            root.x0 = 0;
            root.y0 = 0;

            update(root);

            function update(source) {
                var tree = treeMap(root);

                var nodes = tree.descendants(root);

                console.log(nodes);

                // Compute the flattened node list.
                var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

                d3.select('svg').transition()
                    .duration(duration)
                    .attr('height', height);

                d3.select(window.frameElement).transition()
                    .duration(duration)
                    .style('height', height + 'px');

                // Compute the layout.
                nodes.forEach((n, i) => {
                    n.x = i * barHeight;
                });

I've logged the necessary variables, and you can view them by popping open your dev console.

I'm not sure if this is enough information or not, please let me know if you need more! Thanks for the help!!!

Body:
It turns out that the answer was actually relatively simple. I was using forEach instead of eachBefore when laying out the nodes. The solution on this GitHub Issue.

They link to this example, and the correct fix is this:

// Compute the "layout". TODO https://github.com/d3/d3-hierarchy/issues/67
var index = -1;
root.eachBefore(function(n) {
    n.x = ++index * barHeight;
    n.y = n.depth * 20;
});

I have also updated my Plunker with the correct code in action...


问:
Rails - ActiveAdmin and Papertrail - a DRY approach
I have lot of Models where I use PaperTrail, like:

```<code>class User < ActiveRecord::Base
  has_paper_trail
end
</code>```

In the ActiveAdmin model's file I have:

```<code>ActiveAdmin.register User do

  ...

  # versioning part
  action_item :history, only: :show do
    link_to('History', history_backend_user_path(user), method: :get)
  end

  sidebar :versionate, :partial => "layouts/version", :only => :show

  member_action :history do
    @user = User.find(params[:id])
    @versions = @user.versions.reorder(created_at: :desc)
    render "layouts/history"
  end
end
</code>```

I have to repeat this lines for every model and I'm wondering how I could dry it up.

答:
Try separating the common code into a concern.  You can then use ActiveAdmin's include method to incorporate the common code into your resources.

Here is the module which should contain your common code:

```<code># app/admin/concerns/versionable.rb
module Versionable
  def self.included(dsl)
    dsl.action_item :history, only: :show do
      link_to 'History', dsl.history_backend_user_path(user), method: :get
    end

    dsl.sidebar :versionate, :partial => "layouts/version", :only => :show

    dsl.member_action :history do
      @user = User.find(params[:id])
      @versions = @user.versions.reorder(created_at: :desc)
      render "layouts/history"
    end
  end
end
</code>```

You can then include this module in your ActiveAdmin resources.  For example:

```<code># app/admin/user.rb
ActiveAdmin.register User do
  include Versionable
  ...
end
</code>```

This is based on this Stack Overflow post.  It has not been tested.

Body:
I have lot of Models where I use PaperTrail, like:

class User < ActiveRecord::Base
  has_paper_trail
end

In the ActiveAdmin model's file I have:

ActiveAdmin.register User do

  ...

  # versioning part
  action_item :history, only: :show do
    link_to('History', history_backend_user_path(user), method: :get)
  end

  sidebar :versionate, :partial => "layouts/version", :only => :show

  member_action :history do
    @user = User.find(params[:id])
    @versions = @user.versions.reorder(created_at: :desc)
    render "layouts/history"
  end
end

I have to repeat this lines for every model and I'm wondering how I could dry it up.

Body:
Try separating the common code into a concern.  You can then use ActiveAdmin's include method to incorporate the common code into your resources.

Here is the module which should contain your common code:

# app/admin/concerns/versionable.rb
module Versionable
  def self.included(dsl)
    dsl.action_item :history, only: :show do
      link_to 'History', dsl.history_backend_user_path(user), method: :get
    end

    dsl.sidebar :versionate, :partial => "layouts/version", :only => :show

    dsl.member_action :history do
      @user = User.find(params[:id])
      @versions = @user.versions.reorder(created_at: :desc)
      render "layouts/history"
    end
  end
end

You can then include this module in your ActiveAdmin resources.  For example:

# app/admin/user.rb
ActiveAdmin.register User do
  include Versionable
  ...
end

This is based on this Stack Overflow post.  It has not been tested.


问:
Trying to dectect when WKWebKit start loading video, to stop animation
I conformed to "WKNavigationDelegate" and according to the document I am using
these methods, but it seems like they're not getting call. I am not getting any result.

```<code>func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    stopAnimating()

    print("didStart Video is loading...")
}

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    stopAnimating()

    print("Video is loading...")
}
</code>```

Complete Code, anyhelp in the right direction would help, Thanks!

```<code>override func viewDidAppear(_ animated: Bool) {
    NVActivityIndicatorView.DEFAULT_BLOCKER_SIZE = CGSize(width: 35, height: 35)
    startAnimating(message:"Loading...", type: .lineScale, color: .lightGray)

    guard let url = holdUrl else {return}

    if let url = URL(string:url) {
        let request = URLRequest(url: url)
        myWebView.load(request)
        myWebView.scrollView.isScrollEnabled = false
    }
</code>```

答: Adding "myWebView.navigationDelegate = self" fixed my problem...</p>

Body:
I conformed to "WKNavigationDelegate" and according to the document I am using
these methods, but it seems like they're not getting call. I am not getting any result.

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    stopAnimating()

    print("didStart Video is loading...")
}

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    stopAnimating()

    print("Video is loading...")
}

Complete Code, anyhelp in the right direction would help, Thanks!

override func viewDidAppear(_ animated: Bool) {
    NVActivityIndicatorView.DEFAULT_BLOCKER_SIZE = CGSize(width: 35, height: 35)
    startAnimating(message:"Loading...", type: .lineScale, color: .lightGray)

    guard let url = holdUrl else {return}

    if let url = URL(string:url) {
        let request = URLRequest(url: url)
        myWebView.load(request)
        myWebView.scrollView.isScrollEnabled = false
    }


问:
Laravel Dingo API - Only log 500 error, never send error details via api?
I made the below controller to demonstrate the issue of handling 500 errors I am having with dingo api in laravel. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

```<code>class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}
</code>```

This is what the client sees:

In my controllers, I handle errors manually by returning a success/error json response from within the controllers, but if an error occurs that I did not expect, the api returns it and it has too much details for the client to see. Instead, these unexpected errors should bubble up to some sort of handler to return a generic error occurred response. In Laravel, setting APP_DEBUG = false in .env works for laravel (but not for dingo api), this has no effect and the full error is returned to the client. Looking for a safety net for errors that slip through the cracks.

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

答:
You should check your dingo config and set these two parameters to false.

```<code>APP_DEBUG=false
API_DEBUG=false
</code>```

If you still encounter the issue, just as suggested in the comment ensure you are in production.

Finally if you are still having the same issues (which by now normally should not exist after setting those fields to false) then you might be interested in checking this issue (date back since 2015).

The fix from one of the comment says (verbatim):

```<code>app(\Dingo\Api\Exception\Handler::class)->register(function (\Exception $exception) {
    if (!env('API_DEBUG') && !$exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
        // Whatever other handling you want goes here..

        // Mimic the normal API response with a different message
        return \Response::make([
            'message'     => 'Internal server error',
            'status_code' => 500,
        ], 500);
    }
});
</code>```

Beware that I didnt test this myself.

Body:
I made the below controller to demonstrate the issue of handling 500 errors I am having with dingo api in laravel. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}

This is what the client sees:

In my controllers, I handle errors manually by returning a success/error json response from within the controllers, but if an error occurs that I did not expect, the api returns it and it has too much details for the client to see. Instead, these unexpected errors should bubble up to some sort of handler to return a generic error occurred response. In Laravel, setting APP_DEBUG = false in .env works for laravel (but not for dingo api), this has no effect and the full error is returned to the client. Looking for a safety net for errors that slip through the cracks.

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

Body:
You should check your dingo config and set these two parameters to false.

APP_DEBUG=false
API_DEBUG=false

If you still encounter the issue, just as suggested in the comment ensure you are in production.

Finally if you are still having the same issues (which by now normally should not exist after setting those fields to false) then you might be interested in checking this issue (date back since 2015).

The fix from one of the comment says (verbatim):

app(\Dingo\Api\Exception\Handler::class)->register(function (\Exception $exception) {
    if (!env('API_DEBUG') && !$exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
        // Whatever other handling you want goes here..

        // Mimic the normal API response with a different message
        return \Response::make([
            'message'     => 'Internal server error',
            'status_code' => 500,
        ], 500);
    }
});

Beware that I didnt test this myself.


问:
MVC bypass client-side validation ("save progress" vs "submit")
I have a form that I want to be able to save without validating, but validates on submit. I've got two buttons on this form to either save or submit.

The problem is: if I use a "submit" button to save (and then do a switch on which action in the controller), jquery.validate kicks in and I can't save a partially-filled out form.

If I do it as a link, I don't know how to make the form post to the new action in the controller.

Here's the HTML from the view:

```<code><a class="btn  btn-default" data-placement="right" data-title="Save your progress." href="/Summary/Save/2" rel="tooltip"><i class="glyphicon glyphicon-floppy-disk"></i> Save Summary</a>
<a class="btn  btn-default" confirm="Are you sure you want to revert to the previous saved copy? You will lose all changes since your last save." data-placement="right" data-title="Revert back to your last saved copy." href="/Summary/Revert/2" rel="tooltip"><i class="glyphicon glyphicon-remove"></i> Revert Changes</a>
<button class="btn-default  btn btn-primary" confirm="This will submit the summary to the evaluator for review. No changes will be allowed unless the evaluator returns it. Are you sure?" type="submit">Submit Summary</button>
</code>```

答:
BTW, the current answer is deprecated according to the docs on Skipping validation on submit:

To skip validation while still using a submit-button, add the attribute "formnovalidate" to that input:

```<code><input type="submit" name="go" value="Submit">
<input type="submit" formnovalidate name="cancel" value="Cancel">
</code>```

This used to work by adding class="cancel" to the input, this is now deprecated.

Although, as of version 1.17, both methods still appear in the source code:

...blob/1.17.0/src/core.js#L34:

// Allow suppressing validation by adding a cancel class to the submit button
if ( $( this ).hasClass( "cancel" ) ) {
    validator.cancelSubmit = true;
}

// Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
    validator.cancelSubmit = true;
}
```

Further Reading: jQuery Validation plugin: disable validation for specified submit buttons

Body:
I have a form that I want to be able to save without validating, but validates on submit. I've got two buttons on this form to either save or submit.

The problem is: if I use a "submit" button to save (and then do a switch on which action in the controller), jquery.validate kicks in and I can't save a partially-filled out form.

If I do it as a link, I don't know how to make the form post to the new action in the controller.

Here's the HTML from the view:

 Save Summary
 Revert Changes
<button class="btn-default  btn btn-primary" confirm="This will submit the summary to the evaluator for review. No changes will be allowed unless the evaluator returns it. Are you sure?" type="submit">Submit Summary</button>

Body:
BTW, the current answer is deprecated according to the docs on Skipping validation on submit:

To skip validation while still using a submit-button, add the attribute "formnovalidate" to that input:

<input type="submit" name="go" value="Submit">
<input type="submit" formnovalidate name="cancel" value="Cancel">

This used to work by adding class="cancel" to the input, this is now deprecated.

Although, as of version 1.17, both methods still appear in the source code:

...blob/1.17.0/src/core.js#L34:

// Allow suppressing validation by adding a cancel class to the submit button
if ( $( this ).hasClass( "cancel" ) ) {
    validator.cancelSubmit = true;
}

// Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
    validator.cancelSubmit = true;
}

Further Reading: jQuery Validation plugin: disable validation for specified submit buttons


问:
Need assistance with Xcode/database in Mac OS
I am new to Mac OS and I am unable to understand whether I have any database installed in my system or not. As far as my knowledge is concerned about Mac OS, I am not able to see any database under Applications/Utilities or Applications/Developer.

Can anyone help me choose a basic database I can install in Mac OS? My intent is to learn to connect a DB with the Native app which I am trying to create.

It would be helpful if you could provide me with some useful links for installation and connecting the DB.

答:
Have a start with the Core Data framework.

http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/CoreData/cdProgrammingGuide.html

But you could specify what sort of database you want to connect to for a real answer.

ContentLicense: CC BY-SA 2.5


问:
Exchange token from AWS Cognito to AWS API Gateway
I'm preparing my degree thesis ( focuses on cloud computing ) so I'm a student and not expert at all my apologies if the question looks stupid.

I'm building a serverless architecture based on NodeJS and Javascript ( back-end and front-end ).
I'd like to manage the user through AWS Cognito.
I've configured my user pool and the GUI in order to register a user or allow the user to use an identity provider like Facebook or Google ( auth login ).

I'm stuck because after the user clicks on the Facebook login I'm able to retrieve the token in my callback page ( it looks like xxxx-xxxx-xxxx-xxxx ) but if I try to use that token as "Authorization" in the header in order to access to an API ( AWS API gateway ) I'm getting an unauthorized request.

I've understood that I need to exchange this token with a valid AWS identity token but I'm not able to understand how to do that in JS with AWS JS SDK.

I've found a couple of examples online that uses username and password, but if I don't have those data but just the token that comes from Facebook or Google how can I grab the AWS identity token?

I'll really appreciate if someone can help me!

答:
If you want to use Facebook and Google with Amazon Web Services you should know about Amazon Cognito Federated Identities

Amazon Cognito Federated Identities enable you to create unique identities and assign permissions for users. Your identity pool can include:

Users in an Amazon Cognito user pool

Users who authenticate with federated identity providers such as
Facebook, Google, or a SAML-based identity provider

Users authenticated via your own existing authentication process


问:
pushing to nexus, I get "Repository path must have another '/' after initial '/'"
When running python setup.py bdist_wheel upload -r ournexus I get "Repository path must have another '/' after initial '/'".

I'm trying to push to a private PyPi repository on a company nexus.

答:
The problem was that, in my .pypirc, it said:

```<code>[ournexus]
repository=[my URL]/repository/[repositoryname]
username=[username]
password=[password]
</code>```

where it should have said

```<code>[ournexus]
repository=[my URL]/repository/[repositoryname]/
username=[username]
password=[password]
</code>```

(note the forward slash after [repositoryname])

Which, judging from the documentation and tutorials online seems to be fine for the public pypi, but doesn't seem to be accepted by nexus.

Body:
The problem was that, in my .pypirc, it said:

[ournexus]
repository=[my URL]/repository/[repositoryname]
username=[username]
password=[password]

where it should have said

[ournexus]
repository=[my URL]/repository/[repositoryname]/
username=[username]
password=[password]

(note the forward slash after [repositoryname])

Which, judging from the documentation and tutorials online seems to be fine for the public pypi, but doesn't seem to be accepted by nexus.


问:
Get Value from local .resx file
How can i get value from local .resx file in asp.net?</p>

答:
You can use this method to read from your resource file. You can keep the file path in your config or make it a constant and remove it from your method. You can also make it a static method for better practice.</p>

```<code>/// <summary>
/// method for reading a value from a resource file
/// (.resx file)
/// </summary>
/// <param name="file">file to read from</param>
/// <param name="key">key to get the value for</param>
/// <returns>a string value</returns>
public string ReadResourceValue(string file, string key)
{
    //value for our return value
    string resourceValue = string.Empty;
    try
    {
        // specify your resource file name
        string resourceFile = file;
        // get the path of your file
        string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
        // create a resource manager for reading from
        //the resx file
        ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
        // retrieve the value of the specified key
        resourceValue = resourceManager.GetString(key);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        resourceValue = string.Empty;
    }
    return resourceValue;
}
</code>```

Title: Get Value from local .resx file

Body:
You can use this method to read from your resource file. You can keep the file path in your config or make it a constant and remove it from your method. You can also make it a static method for better practice.

/// <summary>
/// method for reading a value from a resource file
/// (.resx file)
/// </summary>
/// <param name="file">file to read from</param>
/// <param name="key">key to get the value for</param>
/// <returns>a string value</returns>
public string ReadResourceValue(string file, string key)
{
    //value for our return value
    string resourceValue = string.Empty;
    try
    {
        // specify your resource file name
        string resourceFile = file;
        // get the path of your file
        string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
        // create a resource manager for reading from
        //the resx file
        ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
        // retrieve the value of the specified key
        resourceValue = resourceManager.GetString(key);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        resourceValue = string.Empty;
    }
    return resourceValue;
}


问:
Apache Flume + Hdfs Sink
Can we add a delimiter for HDFS Sink ?
When is file is written , how can we add a record seperator ?

Following are the configuration :-

```<code> tier1.sinks.hdfssink.type = hdfs
 tier1.sinks.hdfssink.channel = memory
 tier1.sinks.hdfssink.hdfs.path=tmp/kafka/%{topic}/%y-%m-%d
 tier1.sinks.hdfssink.hdfs.rollSize=268435456
 tier1.sinks.hdfssink.hdfs.rollCount=0
 tier1.sinks.hdfssink.hdfs.rollInterval = 0
 tier1.sinks.hdfssink.hdfs.useLocalTimeStamp=true
 tier1.sinks.hdfssink.hdfs.fileType=DataStream
 tier1.sinks.hdfssink.hdfs.inUseSuffix=.tmp
 tier1.sinks.hdfssink.hdfs.batchSize=10000
</code>```

答:
I would lean towards using a Flume EventSerializer whose configuration would be similar than this one:

```<code>tier1.sinks.hdfssink.serializer = <your serialization class>
tier1.sinks.hdfssink.serializer.delimiter = < your delimiter>
</code>```

You might reference the following github site for details and code snippets.

https://github.com/relistan/flume-serializers

Hope this help!

Title: Apache Flume + Hdfs Sink

Body:
Can we add a delimiter for HDFS Sink ?
When is file is written , how can we add a record seperator ?

Following are the configuration :-

 tier1.sinks.hdfssink.type = hdfs
 tier1.sinks.hdfssink.channel = memory
 tier1.sinks.hdfssink.hdfs.path=tmp/kafka/%{topic}/%y-%m-%d
 tier1.sinks.hdfssink.hdfs.rollSize=268435456
 tier1.sinks.hdfssink.hdfs.rollCount=0
 tier1.sinks.hdfssink.hdfs.rollInterval = 0
 tier1.sinks.hdfssink.hdfs.useLocalTimeStamp=true
 tier1.sinks.hdfssink.hdfs.fileType=DataStream
 tier1.sinks.hdfssink.hdfs.inUseSuffix=.tmp
 tier1.sinks.hdfssink.hdfs.batchSize=10000

Body:
I would lean towards using a Flume EventSerializer whose configuration would be similar than this one:

tier1.sinks.hdfssink.serializer = <your serialization class>
tier1.sinks.hdfssink.serializer.delimiter = < your delimiter>

You might reference the following github site for details and code snippets.

https://github.com/relistan/flume-serializers

Hope this help!


问:
Center a LinearLayout and "percentage" margins
Edit: I have received already two comprehensive answers regarding fixed margins. While I've decided altogether to use fixed margins instead of weight margins, the original question remains open.

I am trying to obtain the following design in Android:

A centered vertical list of stuff (TextViews, EditViews etc.) which leaves about 10% of the horizontal space free as left/right margin, with background.

What I tried and did not work/worked partially:

LinearLayout, vertical, as top-level layout. If the gravity is set to "centered", the background is limited to the size of the layout. Also, how does one set percentage margins (widths) in this manner?

LinearLayout on RelativeLayout: Background works, horizontal centering works, weights don't exist.

LinearLayout on LinearLayout: Background works, weights work, horizontal centering pushes all available space to the right.

(In the last two cases, my Eclipse also complains that one of the layouts is redundant.)

I have not posted code, having considered that this is somewhat more of a principle-related question. What would be the (best) way of accomplishing this?

Thank you.

XML corresponding to the last one of the test case:

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:baselineAligned="false"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1.0"
    android:weightSum="1.0"
    android:background="#013c57" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.9"
        android:layout_gravity="center"
        android:orientation="vertical" >

        <!-- Stuff -->
    </LinearLayout>
</LinearLayout>
</code>```

答:
With the introduction of ConstraintLayout, you can set percentage margins for your views by constraint them by guidelines.

Here's the example:

```<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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/editText2"
        app:layout_constraintEnd_toStartOf="@+id/endGuideline"
        app:layout_constraintStart_toStartOf="@+id/startGuideline"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        app:layout_constraintBottom_toTopOf="@+id/editText3"
        app:layout_constraintEnd_toStartOf="@+id/endGuideline"
        app:layout_constraintStart_toStartOf="@+id/startGuideline"
        app:layout_constraintTop_toBottomOf="@+id/editText1" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        app:layout_constraintBottom_toTopOf="@+id/editText4"
        app:layout_constraintEnd_toStartOf="@+id/endGuideline"
        app:layout_constraintStart_toStartOf="@+id/startGuideline"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/endGuideline"
        app:layout_constraintStart_toStartOf="@+id/startGuideline"
        app:layout_constraintTop_toBottomOf="@+id/editText3" />

    <android.support.constraint.Guideline
        android:id="@+id/startGuideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.1" />

    <android.support.constraint.Guideline
        android:id="@+id/endGuideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.9" />

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

Body:
Edit: I have received already two comprehensive answers regarding fixed margins. While I've decided altogether to use fixed margins instead of weight margins, the original question remains open.

I am trying to obtain the following design in Android:

A centered vertical list of stuff (TextViews, EditViews etc.) which leaves about 10% of the horizontal space free as left/right margin, with background.

What I tried and did not work/worked partially:

LinearLayout, vertical, as top-level layout. If the gravity is set to "centered", the background is limited to the size of the layout. Also, how does one set percentage margins (widths) in this manner?

LinearLayout on RelativeLayout: Background works, horizontal centering works, weights don't exist.

LinearLayout on LinearLayout: Background works, weights work, horizontal centering pushes all available space to the right.

(In the last two cases, my Eclipse also complains that one of the layouts is redundant.)

I have not posted code, having considered that this is somewhat more of a principle-related question. What would be the (best) way of accomplishing this?

Thank you.

XML corresponding to the last one of the test case:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:baselineAligned="false"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1.0"
    android:weightSum="1.0"
    android:background="#013c57" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.9"
        android:layout_gravity="center"
        android:orientation="vertical" >

    </LinearLayout>
</LinearLayout>

Body:
With the introduction of ConstraintLayout, you can set percentage margins for your views by constraint them by guidelines.

Here's the example:

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/editText2"
        app:layout_constraintEnd_toStartOf="@+id/endGuideline"
        app:layout_constraintStart_toStartOf="@+id/startGuideline"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        app:layout_constraintBottom_toTopOf="@+id/editText3"
        app:layout_constraintEnd_toStartOf="@+id/endGuideline"
        app:layout_constraintStart_toStartOf="@+id/startGuideline"
        app:layout_constraintTop_toBottomOf="@+id/editText1" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        app:layout_constraintBottom_toTopOf="@+id/editText4"
        app:layout_constraintEnd_toStartOf="@+id/endGuideline"
        app:layout_constraintStart_toStartOf="@+id/startGuideline"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/endGuideline"
        app:layout_constraintStart_toStartOf="@+id/startGuideline"
        app:layout_constraintTop_toBottomOf="@+id/editText3" />

    <android.support.constraint.Guideline
        android:id="@+id/startGuideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.1" />

    <android.support.constraint.Guideline
        android:id="@+id/endGuideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.9" />

</android.support.constraint.ConstraintLayout>


问:
Cannot see last item in ListBox after scrolling to the bottom.
I tried the following code:

```<code>Dim visibleItems As Int16 = ListBoxLibraryAirplanes.ClientSize.Height / ListBoxLibraryAirplanes.ItemHeight

ListBoxLibraryAirplanes.TopIndex = Math.Max(ListBoxLibraryAirplanes.Items.Count - visibleItems + 1, 0)
</code>```

Has anyone seen this behavior?

答: I ended up appending a null item to the listbox.  Everything seems to work now. Thanks to Patrick and @Plutonix for your responses.</p>

Body:
I tried the following code:

Dim visibleItems As Int16 = ListBoxLibraryAirplanes.ClientSize.Height / ListBoxLibraryAirplanes.ItemHeight

ListBoxLibraryAirplanes.TopIndex = Math.Max(ListBoxLibraryAirplanes.Items.Count - visibleItems + 1, 0)

Has anyone seen this behavior?


问:
Do arithmetic operators have to promote integral arguments to int?
cppreference says:

In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.

All the major compilers (g++, clang, and msvc) say that decltype(a+b) is int when both a and b are short.

However, the standard says:

Integral promotions  [conv.prom]/1

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank is less than the rank of int can be converted to a prvalue of type int [...].

Usual arithmetic conversions [expr.arith.conv]/1.5.1

-- If both operands have the same type, no further conversion is needed.

I can only see that "can be converted" and I cannot find where it requires integral promotion for arithmetic operators.

Is the cppreference wrong here?

答:
You were one line away from it. From [expr]/11 (N4659):

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

...

Otherwise, the integral promotions (7.6) shall be performed on both operands. Then the following rules shall be applied to the promoted operands:

Emphasis added. [conv.prom] says that they can take place and how they work. [expr]/11 specifies one of the times when they will take place.


问:
SQLite: finding set with specific values
```<code>PEAK (NAME, ELEV, DIFF, MAP, REGION)
CLIMBER (NAME, SEX)
PARTICIPATED (TRIP_ID, NAME)
CLIMBED (TRIP_ID, PEAK, WHEN_CLIMBED)
</code>```

I need to find The peaks that Mark and Mary have climbed

I did this but it doesn't work:

```<code>        select *
        from participated, climbed
        where participated.name="MARY" or "MARK" and participated.trip_id= climbed.trip_id
</code>```

I also tried doing:

```<code>Group By name, peak
Having name="MARY" or "MARK"
</code>```

How would I do this?

答:
You can use IN  </p>

```<code>    select *
    from participated
    INNER JOIN  climbed ON participated.trip_id= climbed.trip_id
    where participated.name IN ("MARY" , "MARK")
</code>```

<p>OR a proper OR </p>

```<code>    select *
    from participated
    INNER JOIN  climbed ON participated.trip_id= climbed.trip_id
    where participated.name = "MARY" OR  participated.name =  "MARK"
</code>```

Body:
PEAK (NAME, ELEV, DIFF, MAP, REGION)
CLIMBER (NAME, SEX)
PARTICIPATED (TRIP_ID, NAME)
CLIMBED (TRIP_ID, PEAK, WHEN_CLIMBED)

I need to find The peaks that Mark and Mary have climbed

I did this but it doesn't work:

        select *
        from participated, climbed
        where participated.name="MARY" or "MARK" and participated.trip_id= climbed.trip_id

I also tried doing:

Group By name, peak
Having name="MARY" or "MARK"

How would I do this?

Body:
You can use IN

    select *
    from participated
    INNER JOIN  climbed ON participated.trip_id= climbed.trip_id
    where participated.name IN ("MARY" , "MARK")

OR a proper OR

    select *
    from participated
    INNER JOIN  climbed ON participated.trip_id= climbed.trip_id
    where participated.name = "MARY" OR  participated.name =  "MARK"


问:
Allow multiple locales as a qualification test in Mechanical Turk
I would like to have a HIT that requires users to be in the U.S. or Canada. I am using the command line tools, but it seems that any qualifications are treated as being all required -- I want a Boolean or. Is this possible?

For example, in the .properties file, I have:

```<code># Worker_NumberHITsApproved > 100
qualification.1:00000000000000000040
qualification.comparator.1:GreaterThan
qualification.value.1:100

# Worker_PercentAssignmentsApproved > 95%
qualification.2:000000000000000000L0
qualification.comparator.2:GreaterThan
qualification.value.2:95

# Worker_Locale
qualification.3:00000000000000000071
qualification.comparator.3:EqualTo
qualification.locale.3:US
</code>```

All three of these qualifications are required. Suppose I want to require the first two and then a locale of either US or CA. Is there syntax for this?

答:
This question and its answers are fairly old at this point, but I was not able to find a solution specifically for the command line tools. I was fortunately able to figure it out after playing around for some time. In your .properties file:

```<code># user must be located in the US or Canada
qualification.1:00000000000000000071
qualification.comparator.1:In
qualification.locale.1.1:US
qualification.locale.1.2:CA
</code>```

A fairly modest solution but one that is not well-documented in my opinion :)

Body:
I would like to have a HIT that requires users to be in the U.S. or Canada. I am using the command line tools, but it seems that any qualifications are treated as being all required -- I want a Boolean or. Is this possible?

For example, in the .properties file, I have:

# Worker_NumberHITsApproved > 100
qualification.1:00000000000000000040
qualification.comparator.1:GreaterThan
qualification.value.1:100

# Worker_PercentAssignmentsApproved > 95%
qualification.2:000000000000000000L0
qualification.comparator.2:GreaterThan
qualification.value.2:95

# Worker_Locale
qualification.3:00000000000000000071
qualification.comparator.3:EqualTo
qualification.locale.3:US

All three of these qualifications are required. Suppose I want to require the first two and then a locale of either US or CA. Is there syntax for this?

Body:
This question and its answers are fairly old at this point, but I was not able to find a solution specifically for the command line tools. I was fortunately able to figure it out after playing around for some time. In your .properties file:

# user must be located in the US or Canada
qualification.1:00000000000000000071
qualification.comparator.1:In
qualification.locale.1.1:US
qualification.locale.1.2:CA

A fairly modest solution but one that is not well-documented in my opinion :)


问:
Powershell runbook errors after update to OMS New Query Language
It turned out that after migration to New Query Language in OMS also WebhookData structure for alert has changed.

I was trying to change my powershell script (which is called at OMS alert via Automation Account runbook) and it works locally for the Input I've copied for some previous (updated) alerts but I cannot get it to work in Automation Account.

Can anyone tell why this don't work in Runbook but works locally?

Here is my runbook input: https://jsonblob.com/adf5e1c2-c948-11e7-af9e-2d30dd548850

I took it from here:

Script:

```<code>$WebhookData = '{"WebhookName":"OMS Alert Remediation b64051e5-b9c5-44db-b74f-51d7cf5a9df2","RequestBody":"{\"WorkspaceId\":\"8547d992-7979-46d0-912b-8fffeabe1c8b\",\"AlertRuleName\":\"SRVR slow response - TEST\",\"SearchQuery\":\"ApplicationInsights | where TelemetryType == \\\"Request\\\" and Computer startswith_cs \\\"SRVR\\\" and Computer != \\\"SRVR-DEVEL\\\" | summarize AggregatedValue = avg(RequestDuration) by bin_at(TimeGenerated, 4m, datetime(2017-11-12T10:32:00.0000000)), Computer | sort by TimeGenerated desc\",\"SearchResult\":{\"tables\":[{\"name\":\"PrimaryResult\",\"columns\":[{\"name\":\"TimeGenerated\",\"type\":\"datetime\"},{\"name\":\"Computer\",\"type\":\"string\"},{\"name\":\"AggregatedValue\",\"type\":\"real\"}],\"rows\":[[\"2017-11-12T10:28:00Z\",\"SRVR-06\",1535.2852333333333],[\"2017-11-12T10:24:00Z\",\"SRVR-06\",718.91287857142856]]}]},\"SearchIntervalStartTimeUtc\":\"2017-11-12T10:27:00Z\",\"SearchIntervalEndtimeUtc\":\"2017-11-12T10:32:00Z\",\"AlertThresholdOperator\":\"Greater Than\",\"AlertThresholdValue\":700,\"ResultCount\":2,\"SearchIntervalInSeconds\":300,\"LinkToSearchResults\":\"https://8547d992-7979-46d0-912b-8fffeabe1c8b.portal.mms.microsoft.com/#Workspace/search/index?_timeInterval.intervalEnd=2017-11-12T10%3a32%3a00.0000000Z&_timeInterval.intervalDuration=300&q=ApplicationInsights%20%20%7C%20where%20TelemetryType%20%3D%3D%20%5C%22Request%5C%22%20and%20Computer%20startswith_cs%20%5C%22SRVR%5C%22%20and%20Computer%20!%3D%20%5C%22SRVR-DEVEL%5C%22%20%20%7C%20summarize%20AggregatedValue%20%3D%20avg(RequestDuration)%20by%20bin_at(TimeGenerated%2C%204m%2C%20datetime(2017-11-12T10%3A32%3A00.0000000))%2C%20Computer%20%20%7C%20sort%20by%20TimeGenerated%20desc\",\"Description\":\"W runbook-u testujemy powershell workflow, zamiast powershel script \",\"Severity\":\"Critical\"}","RequestHeader":{"Connection":"Keep-Alive","Accept":"application/json","Host":"s2events.azure-automation.net","User-Agent":"OMS-Remediation","x-ms-request-id":"9be297e0-c196-45c0-ad23-3b513e165648"}}'

$Input = ConvertFrom-Json $WebhookData
$RequestBody = ConvertFrom-Json -InputObject $Input.RequestBody

$Computers = New-Object -TypeName System.Collections.ArrayList

foreach($row in $RequestBody.SearchResult.tables[0].rows)
{
    $Computers.Add($row[1]) > $null
}

foreach ($Computer in $Computers | Get-Unique)
{
    'Computer: ' + $Computer
    Invoke-Command -Credential $c -ComputerName $Computer -ScriptBlock {
        $date = Get-Date | Out-File -Append 'C:\tmp\test_log.txt'
    }
}
</code>```

And those are errors in Azure Portal:

1.

```<code>ConvertFrom-Json : Invalid JSON primitive: .
At line:9 char:10
+ $Input = ConvertFrom-Json $WebhookData
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
</code>```

2.

```<code>ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:10 char:46
+ $RequestBody = ConvertFrom-Json -InputObject $Input.RequestBody
+                                              ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJs
onCommand
</code>```

3.

```<code>Cannot index into a null array.
At line:14 char:17
+ foreach($row in $RequestBody.SearchResult.tables[0].rows)
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray
</code>```

答:
As you noticed the query language has changed. We have published a new sample here on how to parse results from the new language.

Look here:

https://learn.microsoft.com/en-us/azure/log-analytics/log-analytics-alerts-actions#webhook-actions

Have a look at the new sample and see if you can use that to parse the records.

Thanks,
Anirudh

Body:
It turned out that after migration to New Query Language in OMS also WebhookData structure for alert has changed.

I was trying to change my powershell script (which is called at OMS alert via Automation Account runbook) and it works locally for the Input I've copied for some previous (updated) alerts but I cannot get it to work in Automation Account.

Can anyone tell why this don't work in Runbook but works locally?

Here is my runbook input: https://jsonblob.com/adf5e1c2-c948-11e7-af9e-2d30dd548850

I took it from here:

Script:

$WebhookData = '{"WebhookName":"OMS Alert Remediation b64051e5-b9c5-44db-b74f-51d7cf5a9df2","RequestBody":"{\"WorkspaceId\":\"8547d992-7979-46d0-912b-8fffeabe1c8b\",\"AlertRuleName\":\"SRVR slow response - TEST\",\"SearchQuery\":\"ApplicationInsights | where TelemetryType == \\\"Request\\\" and Computer startswith_cs \\\"SRVR\\\" and Computer != \\\"SRVR-DEVEL\\\" | summarize AggregatedValue = avg(RequestDuration) by bin_at(TimeGenerated, 4m, datetime(2017-11-12T10:32:00.0000000)), Computer | sort by TimeGenerated desc\",\"SearchResult\":{\"tables\":[{\"name\":\"PrimaryResult\",\"columns\":[{\"name\":\"TimeGenerated\",\"type\":\"datetime\"},{\"name\":\"Computer\",\"type\":\"string\"},{\"name\":\"AggregatedValue\",\"type\":\"real\"}],\"rows\":[[\"2017-11-12T10:28:00Z\",\"SRVR-06\",1535.2852333333333],[\"2017-11-12T10:24:00Z\",\"SRVR-06\",718.91287857142856]]}]},\"SearchIntervalStartTimeUtc\":\"2017-11-12T10:27:00Z\",\"SearchIntervalEndtimeUtc\":\"2017-11-12T10:32:00Z\",\"AlertThresholdOperator\":\"Greater Than\",\"AlertThresholdValue\":700,\"ResultCount\":2,\"SearchIntervalInSeconds\":300,\"LinkToSearchResults\":\"https://8547d992-7979-46d0-912b-8fffeabe1c8b.portal.mms.microsoft.com/#Workspace/search/index?_timeInterval.intervalEnd=2017-11-12T10%3a32%3a00.0000000Z&_timeInterval.intervalDuration=300&q=ApplicationInsights%20%20%7C%20where%20TelemetryType%20%3D%3D%20%5C%22Request%5C%22%20and%20Computer%20startswith_cs%20%5C%22SRVR%5C%22%20and%20Computer%20!%3D%20%5C%22SRVR-DEVEL%5C%22%20%20%7C%20summarize%20AggregatedValue%20%3D%20avg(RequestDuration)%20by%20bin_at(TimeGenerated%2C%204m%2C%20datetime(2017-11-12T10%3A32%3A00.0000000))%2C%20Computer%20%20%7C%20sort%20by%20TimeGenerated%20desc\",\"Description\":\"W runbook-u testujemy powershell workflow, zamiast powershel script \",\"Severity\":\"Critical\"}","RequestHeader":{"Connection":"Keep-Alive","Accept":"application/json","Host":"s2events.azure-automation.net","User-Agent":"OMS-Remediation","x-ms-request-id":"9be297e0-c196-45c0-ad23-3b513e165648"}}'

$Input = ConvertFrom-Json $WebhookData
$RequestBody = ConvertFrom-Json -InputObject $Input.RequestBody

$Computers = New-Object -TypeName System.Collections.ArrayList

foreach($row in $RequestBody.SearchResult.tables[0].rows)
{
    $Computers.Add($row[1]) > $null
}

foreach ($Computer in $Computers | Get-Unique)
{
    'Computer: ' + $Computer
    Invoke-Command -Credential $c -ComputerName $Computer -ScriptBlock {
        $date = Get-Date | Out-File -Append 'C:\tmp\test_log.txt'
    }
}

And those are errors in Azure Portal:

1.

ConvertFrom-Json : Invalid JSON primitive: .
At line:9 char:10
+ $Input = ConvertFrom-Json $WebhookData
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

2.

ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:10 char:46
+ $RequestBody = ConvertFrom-Json -InputObject $Input.RequestBody
+                                              ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJs
onCommand

3.

Cannot index into a null array.
At line:14 char:17
+ foreach($row in $RequestBody.SearchResult.tables[0].rows)
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray


问:
What are the key differences between IDA and x64dbg?
IDA pro ,x64Dbg, olldbg & windbg are used to Reverse Engineering purposes(as a Dissembler) and debugging.

What are the main differences among them? when to use each?

答:
It's quite hard to give an answer that is not opinion-based. Trying to stay factual:

OllyDbg and x64Dbg falls roughly under the same category. Their main strength is debugging without symbolic information (although they can also do debugging with symbolic information). OllyDbg (closed source) hasn't been maintained since a long time now and is limited to x86 32-bit. On the other hand x64Dbg is actively maintained,open source and can handle x86 and x64. Both supports plugins.

Windbg is mainly a symbolic debugger (although obviously it works without any symbols). Being maintained by Microsoft it is very powerful when symbols are available. It supports plugins (in C or C++), scripting (it has its own scripting language but it also supports officially JavaScript and a third-party python scripts loader) .NET debugging and can do Kernel debugging (in this aspect it is the de facto Kernel debugger on Windows systems). In its latest version it also supports TTD (Time Travel Debugging).

IDA main strength is that it's an interactive disassembler. You can "interrogate" the binary (more precisely, the database generated from the binary) in many ways from python scripts. It also supports debugging by itself or through other engines (gdb or windbg engines for example).


答:
If you only want to find peaks that both climed then do

```<code>select peak
from participated
join climbed on participated.trip_id = climbed.trip_id
group by peak
having sum(name='MARY') > 0
   and sum(name='MARK') > 0
</code>```

Title: SQLite: finding set with specific values

Body:
If you only want to find peaks that both climed then do

select peak
from participated
join climbed on participated.trip_id = climbed.trip_id
group by peak
having sum(name='MARY') > 0
   and sum(name='MARK') > 0


问:
Rails Jquery-ui autocomplete with nested attribute
I am trying to use an autocomplete function for when the user attempts to enter in an license plate number into the appropriate rails form. I've been going through easyautocomplete and jquery-ui autocomplete. However can't seem to get any of them to work because the license_number attribute is a nested attribute and I can't find a way to get it all associated.

permit.rb

```<code>class Permit < ApplicationRecord
self.primary_key = :permit_id
has_one :vehicle
accepts_nested_attributes_for :vehicle
</code>```

vehicle.rb

```<code>class Vehicle < ApplicationRecord
self.primary_key = :vehicle_id
belongs_to  :permit, optional: true
</code>```

permit form

```<code><%= form_with(model: permit, local: true) do |form| %>
...
<div class="field">
  <%= form.fields_for :vehicle do |f| %>
    <%= f.label :license_number %>
    <%= f.text_field :license_number %>
  <% end %>
</div>
...
</code>```

The vehicle model has a attribute called license_number. How do I grab all of the license numbers from that model and get it associated so I can use an autocomplete function?

edit

permits.coffee

```<code>jQuery ->
$('#vehicle_license_number').autocomplete
    source: vehicle.collect( |car| [car.license_number, car.vehicle_id])
</code>```

答:
I have posted a few answers of this very same nature, just in JS and not Rails.

Basically, make you're own search of each object element verses an array.

```<code>  source: function(req, resp){
    var results = [];
    $.each(car, function(key, val){
      if(val.license_number.indexOf(req.term) == 0){
        results.push(val);
      }
    });
    resp(results);
  }
</code>```

Hope that helps.

If you're entering part of a plate, not exactly the start of the number, you can make it more wildcard like: val.license_number.indexOf(req.term) >= 0

Body:
I am trying to use an autocomplete function for when the user attempts to enter in an license plate number into the appropriate rails form. I've been going through easyautocomplete and jquery-ui autocomplete. However can't seem to get any of them to work because the license_number attribute is a nested attribute and I can't find a way to get it all associated.

permit.rb

class Permit < ApplicationRecord
self.primary_key = :permit_id
has_one :vehicle
accepts_nested_attributes_for :vehicle

vehicle.rb

class Vehicle < ApplicationRecord
self.primary_key = :vehicle_id
belongs_to  :permit, optional: true

permit form

<%= form_with(model: permit, local: true) do |form| %>
...

  <%= form.fields_for :vehicle do |f| %>
    <%= f.label :license_number %>
    <%= f.text_field :license_number %>
  <% end %>

...

The vehicle model has a attribute called license_number. How do I grab all of the license numbers from that model and get it associated so I can use an autocomplete function?

edit

permits.coffee

jQuery ->
$('#vehicle_license_number').autocomplete
    source: vehicle.collect( |car| [car.license_number, car.vehicle_id])

Body:
I have posted a few answers of this very same nature, just in JS and not Rails.

Basically, make you're own search of each object element verses an array.

  source: function(req, resp){
    var results = [];
    $.each(car, function(key, val){
      if(val.license_number.indexOf(req.term) == 0){
        results.push(val);
      }
    });
    resp(results);
  }

Hope that helps.

If you're entering part of a plate, not exactly the start of the number, you can make it more wildcard like: val.license_number.indexOf(req.term) >= 0