问:
Rails: ActiveRecord::AssociationTypeMismatch error
Is it possible to have the following two columns on an table and save them with active_record:

user_name_id (which is an association)

user_name (just text)

To demonstrate an attempt to save the association field user_name_id and the text field user_name

Here are the models:

```<code>#app/models/blog.rb
class Blog < ApplicationRecord
  belongs_to :user_name
end

#app/models/user_name.rb
class UserName < ApplicationRecord
  has_many :blogs
end
</code>```

The form:

```<code><%= form_for(blog) do |f| %>
  <% if blog.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(blog.errors.count, "error") %> prohibited this blog from being saved:</h2>

      <ul>
      <% blog.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :user_name %>
    <%= f.text_field :user_name %>
  </div>

  <div class="field">
    <%= f.label :user_name_id %>
    <%= f.collection_select :user_name_id, UserName.all, :id, :name %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

The strong params:

```<code>def blog_params
  params.require(:blog).permit(:user_name, :user_name_id)
end
</code>```

When I submit the form in order to create a new blog, it errors out. The params hash looks ok:

```<code>“blog”=>{“user_name_id"=>"1", “user_name"=>”foo”}
</code>```

However I am getting the following error:

ActiveRecord::AssociationTypeMismatch
  UserName(#70119900697480) expected, got String(#70119800086640)

Update: I understand that, ideally: the column name of one of these attributes should change.  Nonetheless: is it possible to do this with rails?  What would it take?

答:
When you do:

```<code>belongs_to :user_name
</code>```

ActiveRecord assumes that Blog has an attribute user_name_id (which it looks like you have - so far, so good). As stated in the Guide, you also get a setter method, user_name= which expects that you're going to pass it a UserName instance.

When you do something like:

```<code>Blog.new(“user_name_id"=>"1", “user_name"=>”foo”)
</code>```

ActiveRecord is expecting user_name to be an instance of class UserName. But you just passed it a String. Which is exactly what the error is telling you.

Also, I agree with Alexey. I don't know why you would persist user_name (as a string) on Blog. If the class UserName has a name attribute, then you can always just do something like:

```<code>blog.user_name.name
</code>```

I also agree with Alexey that UserName is a weird class name. Alexey's recommendations on naming are good ones, so please consider them.

Body:
Is it possible to have the following two columns on an table and save them with active_record:

user_name_id (which is an association)

user_name (just text)

To demonstrate an attempt to save the association field user_name_id and the text field user_name

Here are the models:

#app/models/blog.rb
class Blog < ApplicationRecord
  belongs_to :user_name
end

#app/models/user_name.rb
class UserName < ApplicationRecord
  has_many :blogs
end

The form:

<%= form_for(blog) do |f| %>
  <% if blog.errors.any? %>

<%= pluralize(blog.errors.count, "error") %> prohibited this blog from being saved:

      <% blog.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :user_name %>
    <%= f.text_field :user_name %>

    <%= f.label :user_name_id %>
    <%= f.collection_select :user_name_id, UserName.all, :id, :name %>

    <%= f.submit %>

<% end %>

The strong params:

def blog_params
  params.require(:blog).permit(:user_name, :user_name_id)
end

When I submit the form in order to create a new blog, it errors out. The params hash looks ok:

“blog”=>{“user_name_id"=>"1", “user_name"=>”foo”}

However I am getting the following error:

ActiveRecord::AssociationTypeMismatch
  UserName(#70119900697480) expected, got String(#70119800086640)

Update: I understand that, ideally: the column name of one of these attributes should change.  Nonetheless: is it possible to do this with rails?  What would it take?

Body:
When you do:

belongs_to :user_name

ActiveRecord assumes that Blog has an attribute user_name_id (which it looks like you have - so far, so good). As stated in the Guide, you also get a setter method, user_name= which expects that you're going to pass it a UserName instance.

When you do something like:

Blog.new(“user_name_id"=>"1", “user_name"=>”foo”)

ActiveRecord is expecting user_name to be an instance of class UserName. But you just passed it a String. Which is exactly what the error is telling you.

Also, I agree with Alexey. I don't know why you would persist user_name (as a string) on Blog. If the class UserName has a name attribute, then you can always just do something like:

blog.user_name.name

I also agree with Alexey that UserName is a weird class name. Alexey's recommendations on naming are good ones, so please consider them.


来源: stackexchange

问:
Distance between lat/long points using the haversine formula
I am trying to find the distance between two longitude and latitude points.  I am trying ot use the great circle distance.  This is the formula:

I am not sure why but my program is not working.  This is the result I am getting:

```<code>Change Angle: 0.00016244370761414
Earth Radius: 6371

RESULTS:
Correct  Distance: 24.883 km
Computed Distance: 1.0349288612097
</code>```

Source:

```<code>$latStart = 44.638;
$longStart = -63.587;

$latFinish = 44.644;
$longFinish = -63.597;

# Convert Input to Radians
$latStart = deg2Rad($latStart);
$longStart = deg2Rad($longStart);

$latFinish = deg2Rad($latFinish);
$longFinish = deg2Rad($longFinish);

# Because the Earth is not perfectly spherical, no single value serves as its
# natural radius. Distances from points on the surface to the center range from
# 6,353 km to 6,384 km (≈3,947–3,968 mi). Several different ways of modeling the
# Earth as a sphere each yield a convenient mean radius of 6371 km (≈3,959 mi).
# http://en.wikipedia.org/wiki/Earth_radius
$earthRadius = 6371;

# difference in Long/Lat
$latChange = $latFinish - $latStart;
$longChange = $longFinish - $longStart;

# haversine formula
# numerically stable for small distances
# http://en.wikipedia.org/wiki/Great-circle_distance
$changeAngle = 2 * asin(
                sqrt(
                        pow(sin($latChange/2),2) +
                        cos($latStart) * cos($latFinish) * pow(sin($longChange/2),2)
                )
        );

echo "Change Angle: $changeAngle\n";
echo "Earth Radius: $earthRadius\n";
</code>```

答:
Let's do a back-of-the-envelope check using a planar approximation. The difference in latitude is 0.006°, and the difference in longitude is 0.01°, but multiply by cosine of latitude to get 0.0075°. Apply Pythagoras:

```<code>>>> sqrt(0.006 ** 2 + 0.0075 ** 2)
0.0096046863561492727
</code>```

which is about 0.000167 radians, pretty close to your computation. (Even more back-of-the-envelope check: a degree is about 69 miles, which is a bit over 100 km, so 0.01° should be a bit over 1 km.)

So I think it's your alleged "Correct distance" that's wrong, not your computation.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to find the distance between two longitude and latitude points.  I am trying ot use the great circle distance.  This is the formula:

I am not sure why but my program is not working.  This is the result I am getting:

Change Angle: 0.00016244370761414
Earth Radius: 6371

RESULTS:
Correct  Distance: 24.883 km
Computed Distance: 1.0349288612097

Source:

$latStart = 44.638;
$longStart = -63.587;

$latFinish = 44.644;
$longFinish = -63.597;

# Convert Input to Radians
$latStart = deg2Rad($latStart);
$longStart = deg2Rad($longStart);

$latFinish = deg2Rad($latFinish);
$longFinish = deg2Rad($longFinish);

# Because the Earth is not perfectly spherical, no single value serves as its
# natural radius. Distances from points on the surface to the center range from
# 6,353 km to 6,384 km (≈3,947–3,968 mi). Several different ways of modeling the
# Earth as a sphere each yield a convenient mean radius of 6371 km (≈3,959 mi).
# http://en.wikipedia.org/wiki/Earth_radius
$earthRadius = 6371;

# difference in Long/Lat
$latChange = $latFinish - $latStart;
$longChange = $longFinish - $longStart;

# haversine formula
# numerically stable for small distances
# http://en.wikipedia.org/wiki/Great-circle_distance
$changeAngle = 2 * asin(
                sqrt(
                        pow(sin($latChange/2),2) +
                        cos($latStart) * cos($latFinish) * pow(sin($longChange/2),2)
                )
        );

echo "Change Angle: $changeAngle\n";
echo "Earth Radius: $earthRadius\n";

Body:
Let's do a back-of-the-envelope check using a planar approximation. The difference in latitude is 0.006°, and the difference in longitude is 0.01°, but multiply by cosine of latitude to get 0.0075°. Apply Pythagoras:

>>> sqrt(0.006 ** 2 + 0.0075 ** 2)
0.0096046863561492727

which is about 0.000167 radians, pretty close to your computation. (Even more back-of-the-envelope check: a degree is about 69 miles, which is a bit over 100 km, so 0.01° should be a bit over 1 km.)

So I think it's your alleged "Correct distance" that's wrong, not your computation.


问:
Update d3 chart with react props on componentWillReceiveProps
So, I have a d3 react component and there are a few things that I would like to change about it. But I'm having a hard time. Specifically with controlling the d3 via updating props without having to redraw the graph. Here's the code:

```<code>function createChart(dom, props){
    // var node = d3.select(dom);

    //Remove prev pie chart before drawing new one
    d3.select('#pie').remove();

    var input = d3.selectAll("input")

    var initMeasure = input[0].map(x => {if (x.checked){return(x.value)}})[0]

    var root = props.data

    var width = props.width,
        height = props.height,
        radius = (Math.min(width, height) / 2) - 20;

    var x = d3.scale.linear()
        .range([0, 2 * Math.PI]);

    var y = d3.scale.sqrt()
        .range([0, radius]);

    var color = d3.scale.category20();

    var tooltip = d3.select("body")
        .append("div")
        .attr("id", "tooltip")
        .style("position", "absolute")
        .style("z-index", "10")
        .style("opacity", 0)
        .on("mouseover", mouseOutArc);

    function format_number(x) {
        x = x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return x
    }

    function format_description(d) {
        var description = d.description;
        return  '<b>' + d.key + '</b></br>'+ '(' + format_number(d.value) + ')';
    }

    function computeTextRotation(d) {
        var angle=(d.x +d.dx/2)*180/Math.PI - 90

        return angle;
    }

    function mouseOverArc(d) {
        d3.select(this).attr("stroke","black")

        tooltip.html(format_description(d));
        return tooltip.transition()
            .duration(50)
            .style("opacity", 0.9);
    }

    function mouseOutArc(){
        d3.select(this).attr("stroke","grey")
        return tooltip.style("opacity", 0);
    }

    function mouseMoveArc (d) {
        return tooltip
            .style("top", (d3.event.pageY-10)+"px")
            .style("left", (d3.event.pageX+10)+"px");
    }

    var root_ = null;

    var svg = d3.select(dom).append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("id", 'pie')
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + (height / 2 + 10) + ")");

    var initvalue
    switch(initMeasure) {
        case 'dollars':
            initvalue = function(d) { return d.dollars; };
            break;
        case 'units':
            initvalue = function(d) { return d.units; };
            break;
        case 'tdps':
            initvalue = function(d) { return d.tdps; };
            break;
    }

    var partition = d3.layout.partition()
        .sort(null)
        .value(function(d) { return d.dollars; })
        .children(function(d) {return d.values});

    var arc = d3.svg.arc()
        .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
        .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
        .innerRadius(function(d) { return Math.max(0, y(d.y)); })
        .outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); });

// Keep track of the node that is currently being displayed as the root.
    var node;

    node = root;
    var path = svg.datum(root).selectAll("path")
        .data(partition.nodes)
        .enter().append("path")
        .attr("d", arc)
        .attr("id", "arc")
        .style("fill", function(d) { return color((d.values ? d : d.parent).key); })
        .attr("stroke","grey")
        .transition().duration(750).attrTween("d", arcTweenData)
        .on("click", click)
        .on("mouseover", mouseOverArc)
        .on("mousemove", mouseMoveArc)
        .on("mouseout", mouseOutArc)
        .each(stash);

    d3.selectAll("input").on("change", function change() {
        if (this.name === 'measurement') {
            var value
            switch(this.value) {
                case 'dollars':
                    value = function(d) {return d.dollars};
                    break;
                case 'units':
                    value = function(d) {return d.units};
                    break;
                case 'tdps':
                    value = function(d) {return d.tdps};
                    break;
            }
        }
        path
            .data(partition.value(value).nodes)
            .transition()
            .duration(1000)
            .attrTween("d", arcTweenData);
    });

    function click(d) {
        node = d;
        path.transition()
            .duration(1000)
            .attrTween("d", arcTweenZoom(d));
        console.log('clicked: ', d.key)
    }

    d3.select(self.frameElement).style("height", height + "px");

// Setup for switching data: stash the old values for transition.
    function stash(d) {
        d.x0 = d.x;
        d.dx0 = d.dx;
    }

// When switching data: interpolate the arcs in data space.
    function arcTweenData(a, i) {
        var oi = d3.interpolate({x: a.x0, dx: a.dx0}, a);
        function tween(t) {
            var b = oi(t);
            a.x0 = b.x;
            a.dx0 = b.dx;
            return arc(b);
        }
        if (i == 0) {
            // If we are on the first arc, adjust the x domain to match the root node
            // at the current zoom level. (We only need to do this once.)
            var xd = d3.interpolate(x.domain(), [node.x, node.x + node.dx]);
            return function(t) {
                x.domain(xd(t));
                return tween(t);
            };
        } else {
            return tween;
        }
    }

// When zooming: interpolate the scales.
    function arcTweenZoom(d) {
        var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
            yd = d3.interpolate(y.domain(), [d.y, 1]),
            yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
        return function(d, i) {
            return i
                ? function(t) { return arc(d); }
                : function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return arc(d); };
        };
    }

};

@observer
class SunburstChart extends React.Component {

    constructor(props) {
        super(props);
        this.state = {}
    }

    componentDidMount() {
        var dom =  ReactDOM.findDOMNode(this);
        createChart(dom, this.props);
    }

    componentWillReceiveProps(x) {
        console.log('props received: ', x)
        var dom =  ReactDOM.findDOMNode(this);
        createChart(dom, x);

    }

    render() {
        console.log('sunburst chart rendered: ')
        return (
            <div>
                <RadioButtonGroup name="measurement" defaultSelected="dollars">
                    <RadioButton
                        value="dollars"
                        label="Dollars"
                    />
                    <RadioButton
                        value="units"
                        label="Units"
                    />
                    <RadioButton
                        value="tdps"
                        label="Tdps"
                    />
                </RadioButtonGroup>
            </div>
        );
    }
};
</code>```

When the component receives props I currently redraw the chart. However, I would love to be able to just alter the existing chart. If that isn't possible it would be great to have some transitions on the initial load of the chart.

Also; that line of code that looks at the input:

```<code>d3.selectAll("input").on("change", function change() {
        if (this.name === 'measurement') {
            var value
            switch(this.value) {
                case 'dollars':
                    value = function(d) {return d.dollars};
                    break;
                case 'units':
                    value = function(d) {return d.units};
                    break;
                case 'tdps':
                    value = function(d) {return d.tdps};
                    break;
            }
        }
        path
            .data(partition.value(value).nodes)
            .transition()
            .duration(1000)
            .attrTween("d", arcTweenData);
    });
</code>```

It would be great if I could pass that and control it through props, as well.

Any advice is greatly appreciated! Thanks for reading!

答:
I'll answer 1. Question.

Here is an idea:

Render pie chart initially with the code as you do (so that d3 generates svg element with id you provide)

Create update function for piechart (see d3 thinking with joins) and when component receives new props execute that function without removing piechart from the dom but only select existing svg with id you know and instruct d3 to change svg dom attributes for (insert, update - d3 sets)

ContentLicense: CC BY-SA 3.0

Body:
So, I have a d3 react component and there are a few things that I would like to change about it. But I'm having a hard time. Specifically with controlling the d3 via updating props without having to redraw the graph. Here's the code:

function createChart(dom, props){
    // var node = d3.select(dom);

    //Remove prev pie chart before drawing new one
    d3.select('#pie').remove();

    var input = d3.selectAll("input")

    var initMeasure = input[0].map(x => {if (x.checked){return(x.value)}})[0]

    var root = props.data

    var width = props.width,
        height = props.height,
        radius = (Math.min(width, height) / 2) - 20;

    var x = d3.scale.linear()
        .range([0, 2 * Math.PI]);

    var y = d3.scale.sqrt()
        .range([0, radius]);

    var color = d3.scale.category20();

    var tooltip = d3.select("body")
        .append("div")
        .attr("id", "tooltip")
        .style("position", "absolute")
        .style("z-index", "10")
        .style("opacity", 0)
        .on("mouseover", mouseOutArc);

    function format_number(x) {
        x = x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return x
    }

    function format_description(d) {
        var description = d.description;
        return  '' + d.key + '
'+ '(' + format_number(d.value) + ')';
    }

    function computeTextRotation(d) {
        var angle=(d.x +d.dx/2)*180/Math.PI - 90

        return angle;
    }

    function mouseOverArc(d) {
        d3.select(this).attr("stroke","black")

        tooltip.html(format_description(d));
        return tooltip.transition()
            .duration(50)
            .style("opacity", 0.9);
    }

    function mouseOutArc(){
        d3.select(this).attr("stroke","grey")
        return tooltip.style("opacity", 0);
    }

    function mouseMoveArc (d) {
        return tooltip
            .style("top", (d3.event.pageY-10)+"px")
            .style("left", (d3.event.pageX+10)+"px");
    }

    var root_ = null;

    var svg = d3.select(dom).append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("id", 'pie')
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + (height / 2 + 10) + ")");

    var initvalue
    switch(initMeasure) {
        case 'dollars':
            initvalue = function(d) { return d.dollars; };
            break;
        case 'units':
            initvalue = function(d) { return d.units; };
            break;
        case 'tdps':
            initvalue = function(d) { return d.tdps; };
            break;
    }

    var partition = d3.layout.partition()
        .sort(null)
        .value(function(d) { return d.dollars; })
        .children(function(d) {return d.values});

    var arc = d3.svg.arc()
        .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
        .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
        .innerRadius(function(d) { return Math.max(0, y(d.y)); })
        .outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); });

// Keep track of the node that is currently being displayed as the root.
    var node;

    node = root;
    var path = svg.datum(root).selectAll("path")
        .data(partition.nodes)
        .enter().append("path")
        .attr("d", arc)
        .attr("id", "arc")
        .style("fill", function(d) { return color((d.values ? d : d.parent).key); })
        .attr("stroke","grey")
        .transition().duration(750).attrTween("d", arcTweenData)
        .on("click", click)
        .on("mouseover", mouseOverArc)
        .on("mousemove", mouseMoveArc)
        .on("mouseout", mouseOutArc)
        .each(stash);

    d3.selectAll("input").on("change", function change() {
        if (this.name === 'measurement') {
            var value
            switch(this.value) {
                case 'dollars':
                    value = function(d) {return d.dollars};
                    break;
                case 'units':
                    value = function(d) {return d.units};
                    break;
                case 'tdps':
                    value = function(d) {return d.tdps};
                    break;
            }
        }
        path
            .data(partition.value(value).nodes)
            .transition()
            .duration(1000)
            .attrTween("d", arcTweenData);
    });

    function click(d) {
        node = d;
        path.transition()
            .duration(1000)
            .attrTween("d", arcTweenZoom(d));
        console.log('clicked: ', d.key)
    }

    d3.select(self.frameElement).style("height", height + "px");

// Setup for switching data: stash the old values for transition.
    function stash(d) {
        d.x0 = d.x;
        d.dx0 = d.dx;
    }

// When switching data: interpolate the arcs in data space.
    function arcTweenData(a, i) {
        var oi = d3.interpolate({x: a.x0, dx: a.dx0}, a);
        function tween(t) {
            var b = oi(t);
            a.x0 = b.x;
            a.dx0 = b.dx;
            return arc(b);
        }
        if (i == 0) {
            // If we are on the first arc, adjust the x domain to match the root node
            // at the current zoom level. (We only need to do this once.)
            var xd = d3.interpolate(x.domain(), [node.x, node.x + node.dx]);
            return function(t) {
                x.domain(xd(t));
                return tween(t);
            };
        } else {
            return tween;
        }
    }

// When zooming: interpolate the scales.
    function arcTweenZoom(d) {
        var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
            yd = d3.interpolate(y.domain(), [d.y, 1]),
            yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
        return function(d, i) {
            return i
                ? function(t) { return arc(d); }
                : function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return arc(d); };
        };
    }

};

@observer
class SunburstChart extends React.Component {

    constructor(props) {
        super(props);
        this.state = {}
    }

    componentDidMount() {
        var dom =  ReactDOM.findDOMNode(this);
        createChart(dom, this.props);
    }

    componentWillReceiveProps(x) {
        console.log('props received: ', x)
        var dom =  ReactDOM.findDOMNode(this);
        createChart(dom, x);

    }

    render() {
        console.log('sunburst chart rendered: ')
        return (

                <RadioButtonGroup name="measurement" defaultSelected="dollars">
                    <RadioButton
                        value="dollars"
                        label="Dollars"
                    />
                    <RadioButton
                        value="units"
                        label="Units"
                    />
                    <RadioButton
                        value="tdps"
                        label="Tdps"
                    />
                </RadioButtonGroup>

        );
    }
};

When the component receives props I currently redraw the chart. However, I would love to be able to just alter the existing chart. If that isn't possible it would be great to have some transitions on the initial load of the chart.

Also; that line of code that looks at the input:

d3.selectAll("input").on("change", function change() {
        if (this.name === 'measurement') {
            var value
            switch(this.value) {
                case 'dollars':
                    value = function(d) {return d.dollars};
                    break;
                case 'units':
                    value = function(d) {return d.units};
                    break;
                case 'tdps':
                    value = function(d) {return d.tdps};
                    break;
            }
        }
        path
            .data(partition.value(value).nodes)
            .transition()
            .duration(1000)
            .attrTween("d", arcTweenData);
    });

It would be great if I could pass that and control it through props, as well.

Any advice is greatly appreciated! Thanks for reading!


问:
Jsf pages to plain/text without header html
I need to show output in a jsf page that is not formatted as html (without header and without html tags), but as a simple text file. This is possible with JSF 2.0 or I necessarily need a servlet? Thanks

EDIT:
a client makes a request through url (with parameters) and I have to give it a response. I know that I can use a servlet for this but wanted to know if it was possible to use a Bean/JSF instead. the problem is that I have to give response that can not be an html file but a text file (for simple parsing), but that should not be downloaded but displayed directly in the browser. I hope I was clear

答:
JSF only renders HTML if you use components that generate such content.
You can produce text/html content like this:

<f:view xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    contentType="text/plain"
    encoding="UTF-8">
    <ui:composition>
        Your plain text goes here.
        You can use expressions as usual: #{myBean.value}.
    </ui:composition>
</f:view>
```

Just plain text will be rendered. With the f:view component attributes you set the response headers.

Body:
JSF only renders HTML if you use components that generate such content.
You can produce text/html content like this:

<f:view xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    contentType="text/plain"
    encoding="UTF-8">
    <ui:composition>
        Your plain text goes here.
        You can use expressions as usual: #{myBean.value}.
    </ui:composition>
</f:view>

Just plain text will be rendered. With the f:view component attributes you set the response headers.


问:
I am wondering if my ER model is good
I would be really eppreciated if you can tell me if my ER model is good. What's batter for Author table to be in separated table or in Book table?ER model

Thanks for your help!

答:
I made relational model in MySQL. Is it ok?
Relational model</p>

Title: I am wondering if my ER model is good


问:
What is the proper way to have a django 1.10 API serve static HTML content in DEBUG?
I am attempting to build a simple single-page web app where a web server just serves static content, unless a route begins with "/api" - in which case requests are routed to django.

File structure like so:

ROOT
- manage.py
- static/ (static content)
  - index.html
  - app.min.js
  - ...etc
- djangoapp/ (django "project")
  - __init__.py
  - settings.py
  - urls.py
  - wsgi.py
- api/ (django "app")
  - __init__.py
  - admin.py
  - apps.py
  - models.py
  - tests.py
  - views.py

In development (DEBUG=true), I would like django to serve the static content as a traditional web server would. That means content not under /api should just be served from /static, and a GET for '/' should return index.html.

I have taken these steps:

created the root django "project" with django-admin startproject djangoapp

created a django "app" with ./manage.py startapp api

created a folder, static, with a dummy index.html and dummy.html.

altered the django "app" to create a simple "hello I am the api" endpoint, at /api/hello, and created the appropriate routes

From this point, I can successfully set up a docker-compose cluster to perform as expected - calls to the nginx edge for '/' load the static index.html in ROOT/static/index.html, calls to '/api/hello' are proxied to a uwgi server and return accordingly. However, I cannot for the life of me get django to do this from its ./manage.py runserver

I quickly found a guide to do this from Django itself here: https://docs.djangoproject.com/en/1.10/howto/static-files/

However, none of the suggestions listed on that doc actually work.

setting

'STATIC_URL' to '/'

'STATIC_ROOT' to the project's on-disk physical root via os.path.join(BASE_DIR, "static")

...does not alter the behavior in any way - requests to a static page like GET /dummy.html do not route

while altering the project's urls.py to include the result of...

django.conf.urls.static.static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

...also does not alter behavior in any way. Just 404s.

I found that by omitting a STATIC_ROOT value, and setting a STATICFILES_DIRS value to the physical on-disk document root would successfully serve static files - but break all other endpoints (they throw 404).

Environment:

Debian jessie (stable)

python 2.7.13 (installed via pyenv)

django 1.10.6 (installed via pip)

答:
The core issue seems to surround the default INSTALLED_APP entry, django.contrib.staticfiles. Disabling it in settings.py was the solution.

Step by step instructions to building a "/api only" django 1.10 that will serve static content in DEBUG mode.

Have python 2.7/3.5+ and django installed.

Create a new django project with django-admin startproject PROJECTNAME

cd into PROJECTNAME, create the API "app" with ./manage.py startapp api

Create a staticfiles folder with mkdir static, populate it with your transpiled/bundled web client.

Open PROJECTNAME/settings.py, and change the following settings:

Remove an entry from the INSTALLED_APPS array: django.contrib.staticfiles

Add an entry to the TEMPLATES.DIRS array: os.path.join(BASE_DIR, "static")

Change STATIC_URL to STATIC_URL = '/'

Change STATIC_ROOT to STATIC_ROOT = os.path.join(BASE_DIR, "static")

Route your api app's endpoints with the following steps

Create a proof-of-concept API endpoint in 'api/views.py' as follows

from django.http import HttpResponse

def hello(request):
    return HttpResponse('{"response":"Hello. I am the API!"}', "application/json")
```

<p>...and set up your api app's internal routing in api/urls.py like so:</p>

<pre class="lang-py prettyprint-override"><code>from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^hello$', views.hello, name='hello'),
]
</code>```

Add your api app to the project's url structure by editing PROJECTNAME/urls.py as follows:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^api/', include('api.urls')),
    url(r'^admin/', admin.site.urls),
]
```

<ol start="7">
<li>Add DEBUG-only routes for static content by altering PROJECTNAME/urls.py as follows:</li>
</ol>

<pre class="lang-py prettyprint-override"><code>import os
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^api/', include('api.urls')),
    url(r'^admin/', admin.site.urls),
]

if settings.DEBUG:
    from django.views.generic.base import TemplateView
    urlpatterns += [url(r'^$', TemplateView.as_view(template_name='index.html'))]

    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT, show_indexes=True)
</code>```

...you should now be able to run your django site in "dev mode", with manage.py runserver, and have django serve your static content. In production (DEBUG != True), none of that content will be served - as it should be handled by a web server specializing in delivering static content.

visiting http://localhost:8000/ returns index.html as expected

visiting http://loocalhost:8000/somefile.html returns somefile.html as expected

visiting http://localhost:8000/api/hello returns the "hello" api endpoint's response as expected.

Body:
The core issue seems to surround the default INSTALLED_APP entry, django.contrib.staticfiles. Disabling it in settings.py was the solution.

Step by step instructions to building a "/api only" django 1.10 that will serve static content in DEBUG mode.

Have python 2.7/3.5+ and django installed.

Create a new django project with django-admin startproject PROJECTNAME

cd into PROJECTNAME, create the API "app" with ./manage.py startapp api

Create a staticfiles folder with mkdir static, populate it with your transpiled/bundled web client.

Open PROJECTNAME/settings.py, and change the following settings:

Remove an entry from the INSTALLED_APPS array: django.contrib.staticfiles

Add an entry to the TEMPLATES.DIRS array: os.path.join(BASE_DIR, "static")

Change STATIC_URL to STATIC_URL = '/'

Change STATIC_ROOT to STATIC_ROOT = os.path.join(BASE_DIR, "static")

Route your api app's endpoints with the following steps

Create a proof-of-concept API endpoint in 'api/views.py' as follows

from django.http import HttpResponse

def hello(request):
    return HttpResponse('{"response":"Hello. I am the API!"}', "application/json")

...and set up your api app's internal routing in api/urls.py like so:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^hello$', views.hello, name='hello'),
]

Add your api app to the project's url structure by editing PROJECTNAME/urls.py as follows:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^api/', include('api.urls')),
    url(r'^admin/', admin.site.urls),
]

Add DEBUG-only routes for static content by altering PROJECTNAME/urls.py as follows:

import os
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^api/', include('api.urls')),
    url(r'^admin/', admin.site.urls),
]

if settings.DEBUG:
    from django.views.generic.base import TemplateView
    urlpatterns += [url(r'^$', TemplateView.as_view(template_name='index.html'))]

    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT, show_indexes=True)

...you should now be able to run your django site in "dev mode", with manage.py runserver, and have django serve your static content. In production (DEBUG != True), none of that content will be served - as it should be handled by a web server specializing in delivering static content.

visiting http://localhost:8000/ returns index.html as expected

visiting http://loocalhost:8000/somefile.html returns somefile.html as expected

visiting http://localhost:8000/api/hello returns the "hello" api endpoint's response as expected.


问:
Make a playlist (start next song) in swift
I have created a sound player in swift with AVFoundation. I am trying to start the next song in array when the playing song is finished. I was trying to implement this code

```<code>if (audioPlayer.currentTime >= audioPlayer.duration){
    var recentSong = songPlaylist[selectedSongNumber + 1]
    audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
            NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)
    audioPlayer.play()
}
</code>```

but I am not being able to implement this code (I do not know where to implement it).Here is my complete code

```<code>import UIKit
import AVFoundation
import AVKit

public var audioPlayer = AVPlayer()
public var selectedSongNumber = Int()
public var songPlaylist:[String] = ["song1", "song2"]
public var recentSong = "song1"
let playImage = UIImage(named: "Play.png") as UIImage!
let pauseImage = UIImage(named: "Pause.png") as UIImage!

class FirstViewController: UIViewController {

@IBOutlet weak var musicSlider: UISlider!

@IBOutlet weak var PlayPause: UIButton!

var audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
    NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    musicSlider.maximumValue = Float(audioPlayer.duration)

    var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)

    if (audioPlayer.currentTime >= audioPlayer.duration){

        var recentSong = songPlaylist[selectedSongNumber + 1]

        audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
            NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)

        audioPlayer.play()

        }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}
@IBAction func PlayPauseButton(sender: AnyObject) {

    if (audioPlayer.playing == false){
        audioPlayer.play()
        PlayPause.setImage(pauseImage, forState: .Normal)
    }else{
        audioPlayer.pause()
        PlayPause.setImage(playImage, forState: .Normal)
    }
}

@IBAction func StopButton(sender: AnyObject) {
    audioPlayer.stop()
    audioPlayer.currentTime = 0
    PlayPause.setImage(playImage, forState: .Normal)
}

@IBAction func musicSliderAction(sender: UISlider) {
    audioPlayer.stop()
    audioPlayer.currentTime = NSTimeInterval(musicSlider.value)
    audioPlayer.play()

}

func updateMusicSlider(){

    musicSlider.value = Float(audioPlayer.currentTime)

}

}
</code>```

答:
I created a sound player in swift with AVFoundation. I used progressView to time the song and then when it hits 0.98743 it will update to the next song automatically this is the Github link: https://github.com/ryan-wlr/MusicPlayerIOS  </p>

```<code>func updateProgressView() {
    if (progressView.progress > a.advanced(by: 0.98743)) {
        audioPlayerDidFinishPlayeing()
    }

    if audioPlayer.isPlaying {
        let progress = Float(audioPlayer.currentTime/audioPlayer.duration)
        progressView.setProgress(progress, animated: true)
    }
}
</code>```

Body:
I have created a sound player in swift with AVFoundation. I am trying to start the next song in array when the playing song is finished. I was trying to implement this code

if (audioPlayer.currentTime >= audioPlayer.duration){
    var recentSong = songPlaylist[selectedSongNumber + 1]
    audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
            NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)
    audioPlayer.play()
}

but I am not being able to implement this code (I do not know where to implement it).Here is my complete code

import UIKit
import AVFoundation
import AVKit

public var audioPlayer = AVPlayer()
public var selectedSongNumber = Int()
public var songPlaylist:[String] = ["song1", "song2"]
public var recentSong = "song1"
let playImage = UIImage(named: "Play.png") as UIImage!
let pauseImage = UIImage(named: "Pause.png") as UIImage!

class FirstViewController: UIViewController {

@IBOutlet weak var musicSlider: UISlider!

@IBOutlet weak var PlayPause: UIButton!

var audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
    NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    musicSlider.maximumValue = Float(audioPlayer.duration)

    var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)

    if (audioPlayer.currentTime >= audioPlayer.duration){

        var recentSong = songPlaylist[selectedSongNumber + 1]

        audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
            NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)

        audioPlayer.play()

        }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}
@IBAction func PlayPauseButton(sender: AnyObject) {

    if (audioPlayer.playing == false){
        audioPlayer.play()
        PlayPause.setImage(pauseImage, forState: .Normal)
    }else{
        audioPlayer.pause()
        PlayPause.setImage(playImage, forState: .Normal)
    }
}

@IBAction func StopButton(sender: AnyObject) {
    audioPlayer.stop()
    audioPlayer.currentTime = 0
    PlayPause.setImage(playImage, forState: .Normal)
}

@IBAction func musicSliderAction(sender: UISlider) {
    audioPlayer.stop()
    audioPlayer.currentTime = NSTimeInterval(musicSlider.value)
    audioPlayer.play()

}

func updateMusicSlider(){

    musicSlider.value = Float(audioPlayer.currentTime)

}

}

Body:
I created a sound player in swift with AVFoundation. I used progressView to time the song and then when it hits 0.98743 it will update to the next song automatically this is the Github link: https://github.com/ryan-wlr/MusicPlayerIOS

func updateProgressView() {
    if (progressView.progress > a.advanced(by: 0.98743)) {
        audioPlayerDidFinishPlayeing()
    }

    if audioPlayer.isPlaying {
        let progress = Float(audioPlayer.currentTime/audioPlayer.duration)
        progressView.setProgress(progress, animated: true)
    }
}


问:
Change placeholder when browser is resized
Im looking to add a placeholder to a textbox when the browser has a smaller width than 800 and im not sure where im going wrong.

```<code><form class="info">
            <script>add();</script>
            <label>Name</label> <input type="text" class="box" name="name" placeholder="" size="40"><br><br>
</form>
</code>```

And the JS

```<code><script>
function add(){
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (w < 800) {
    document.getElementsByName('name')[0].placeholder='Name';
} else
{
}}
</script>
</code>```

答:
```<code>window.addEventListener('resize', function() {
  var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  if (w < 800) {
    document.getElementsByName('name')[0].placeholder='Name';
  } else {
    document.getElementsByName('name')[0].placeholder='';
  }
});
</code>```

DEMO

Body:
Im looking to add a placeholder to a textbox when the browser has a smaller width than 800 and im not sure where im going wrong.

<form class="info">

            Name <input type="text" class="box" name="name" placeholder="" size="40">

</form>

And the JS

Body:
window.addEventListener('resize', function() {
  var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  if (w < 800) {
    document.getElementsByName('name')[0].placeholder='Name';
  } else {
    document.getElementsByName('name')[0].placeholder='';
  }
});

DEMO


问:
Convert list of lists with different lengths to a numpy array
I have list of lists with different lengths (e.g. [[1, 2, 3], [4, 5], [6, 7, 8, 9]]) and want to convert it into a numpy array of integers. I understand that 'sub' arrays in numpy multidimensional array must be the same length. So what is the most efficient way to convert such a list as in example above into a numpy array like this [[1, 2, 3, 0], [4, 5, 0, 0], [6, 7, 8, 9]], i.e. completed with zeros?

答:
Do some preprocessing on the list, by padding the shorter sublists, before converting to a numpy array:</p>

```<code>>>> lst = [[1, 2, 3], [4, 5], [1, 7, 8, 9]]
>>> pad = len(max(lst, key=len))
>>> np.array([i + [0]*(pad-len(i)) for i in lst])
array([[1, 2, 3, 0],
       [4, 5, 0, 0],
       [1, 7, 8, 9]])
</code>```

Body:
Do some preprocessing on the list, by padding the shorter sublists, before converting to a numpy array:

>>> lst = [[1, 2, 3], [4, 5], [1, 7, 8, 9]]
>>> pad = len(max(lst, key=len))
>>> np.array([i + [0]*(pad-len(i)) for i in lst])
array([[1, 2, 3, 0],
       [4, 5, 0, 0],
       [1, 7, 8, 9]])


问:
open and write on file
I created a code which ask a user to enter a list of position on a plain text file, save the position the user entered in the text file as list than ask the user to enter the word each position represent (the same order as the list of position) end re-create the sentence.
However im not sure on thow things:

1) how can i make the plain text document pop out only when the previous one was closed (so only when the file:list_of_numbers has been closed, the other file list_of_words will popup).

2) How to write the output on a plain text file.

here is the code:

```<code>import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as pos_file:
    positions = pos_file.read().spllit()

subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as sentence_file:
    words = sentence_file.read().split()

mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]

print(' '.join(output))
</code>```

答:
It's no problem to find out how to do this by consulting the Python Docs.

 - Popen

- Reading and Wirting Files

A Hint!!! - If you create an object, then you should assign it to a variable!

```<code># DO
process = subprocess.Popen(["notepad","list_of_numbers.txt"])

# DONT
subprocess.Popen(["notepad","list_of_numbers.txt"])
</code>```

Consulting the python docs should take you to a solution like this:

```<code>import subprocess

# don't do anything unless child process has been terminated
with subprocess.Popen(["notepad","list_of_numbers.txt"]) as process:
    pass    # you could leave this line blank but using pass clearer

with open("list_of_numbers.txt","r") as pos_file:
    positions = pos_file.read().split()

process = subprocess.Popen(["notepad","list_of_words.txt"])

with open("list_of_words.txt","r") as sentence_file:
    words = sentence_file.read().split()

mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]

# open a new file in write mode, write data and close the file
with open('new_file.txt', 'w') as f:
    f.write(' '.join(output))
</code>```

Note: You still need to fix your assignments to mapping and output in line 17 and 18 as they won't produce the expected result, but that's not part of your question.

Title: open and write on file

Body:
I created a code which ask a user to enter a list of position on a plain text file, save the position the user entered in the text file as list than ask the user to enter the word each position represent (the same order as the list of position) end re-create the sentence.
However im not sure on thow things:

1) how can i make the plain text document pop out only when the previous one was closed (so only when the file:list_of_numbers has been closed, the other file list_of_words will popup).

2) How to write the output on a plain text file.

here is the code:

import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as pos_file:
    positions = pos_file.read().spllit()

subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as sentence_file:
    words = sentence_file.read().split()

mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]

print(' '.join(output))

Body:
It's no problem to find out how to do this by consulting the Python Docs.

 - Popen

- Reading and Wirting Files

A Hint!!! - If you create an object, then you should assign it to a variable!

# DO
process = subprocess.Popen(["notepad","list_of_numbers.txt"])

# DONT
subprocess.Popen(["notepad","list_of_numbers.txt"])

Consulting the python docs should take you to a solution like this:

import subprocess

# don't do anything unless child process has been terminated
with subprocess.Popen(["notepad","list_of_numbers.txt"]) as process:
    pass    # you could leave this line blank but using pass clearer

with open("list_of_numbers.txt","r") as pos_file:
    positions = pos_file.read().split()

process = subprocess.Popen(["notepad","list_of_words.txt"])

with open("list_of_words.txt","r") as sentence_file:
    words = sentence_file.read().split()

mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]

# open a new file in write mode, write data and close the file
with open('new_file.txt', 'w') as f:
    f.write(' '.join(output))

Note: You still need to fix your assignments to mapping and output in line 17 and 18 as they won't produce the expected result, but that's not part of your question.


问:
How to create angular2 jwt token in angular2
I need to create a jwt in  angular2. How do I do that?
I am using this for an api service.

```<code> jwt_token = ?
</code>```

I can create in python with no issue.

答:
@mxii is right, generating jwt token client side exposes ur private key.

If u want to do that anyway, use this: https://github.com/kjur/jsrsasign/wiki/Tutorial-for-JWT-generation

Body:
I need to create a jwt in  angular2. How do I do that?
I am using this for an api service.

 jwt_token = ?

I can create in python with no issue.


答:
You should not use 'user_name' field at all if you already use belongs_to 'user_name'.

Please do not call Model 'UserName' this is not good, maybe this is UserProfile or just User?

Are you sure you want to cache user_name for your blog? If user will change his name it will makes many problems. If you want to cache user_name for blog anyway you can rename column on 'user_name_cached' and updates it on 'UserName' will updates on before_save callback.

UPDATE for authors' update:

belongs_to :your_new_belons_to_name, class_name: 'NameUser', foreign_key: 'name_user_id'

Title: Rails: ActiveRecord::AssociationTypeMismatch error


问:
Example of POST request in Android studio
I just started learning android few days ago and I have a problem with uploading my JSON data to server. I manage to retrieve it via following code:

Edit: I did manage to retrieve files using external OKHTTP library but I would like to do this without using external libraries.

```<code>package cc.demorest;

import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DownloadTask task = new DownloadTask();
        task.execute("myserver.com");
    }
//Downloadtask
    public class DownloadTask extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... urls) {

            String result = "";
                URL url;
            HttpURLConnection urlConnection=null;

            try {
                url = new URL(urls[0]);

                urlConnection=(HttpURLConnection)url.openConnection();
                InputStream in = urlConnection.getInputStream();

                InputStreamReader reader = new InputStreamReader(in);

                int data=reader.read();

                while (data !=-1){

                    char current=(char) data;

                    result += current;
                    data = reader.read();
                }

                return result;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
//After download task
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        try {

            JSONArray jArray=new JSONArray(result);
                JSONObject json_data = jArray.getJSONObject(1);
//Logging data
               Log.i("Podatci: ", "Id: " + json_data.getInt("Id") +
                                ", Name: " + json_data.getString("Name") +
                                ", Years: " + json_data.getString("Age") +
                                ", Email address: " + json_data.getString("Email")
                );
                TextView textView = (TextView) findViewById(R.id.textViewName);
                textView.setText("ID: "+", Name: "+  json_data.getInt("Id")+json_data.getString("Name")+json_data.getString("Age")+json_data.getString("Email"));

/*
        String data = jsonObject.getString("Name");
            Log.i("Website content", data);
*/
        } catch (JSONException e) {
            e.printStackTrace();
        }

        }
    }

}
</code>```

I am now trying to send my data to same server with same fields. I searched internet but most things that I found are outdated.. I would really appriciate some help or example.
Best Regards

答:
Use HttpURLConnection, it does not use external libraries.  If you're going to use an HttpURLConnection, it needs to be an AsyncTask.

Here is my code from a project I completed.  Hope it helps.

First, put this in your manifest.xml file before :

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Calling the AsyncTask:

(Ignore the this, SinceTime, and GoesAddress.  They are just variables I passed in)

```<code>    URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
    new ReceiveData(this, SinceTime, GoesAddress).execute(url);
</code>```

The Class:

```<code>package com.ryan.scrapermain;

import android.content.Context;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class ReceiveData extends AsyncTask<URL, Integer, Long> {

    String response = "";
    String SinceTime;
    String GoesAddress;
    Context myContext;

    ReceiveData(Context context, String since, String goes) {
        this.myContext = context;
        SinceTime = since;
        GoesAddress = goes;
        }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder feedback = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                feedback.append("&");

            feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            feedback.append("=");
            feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return feedback.toString();
    }

    public void getData() throws IOException {

        HashMap<String, String> params = new HashMap<>();
        params.put("DCPID", GoesAddress);
        params.put("SINCE", SinceTime);

        URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
        HttpURLConnection client = null;
        try {
            client = (HttpURLConnection) url.openConnection();
            client.setRequestMethod("POST");
            // You need to specify the context-type.  In this case it is a
            // form submission, so use "multipart/form-data"
            client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
            client.setDoInput(true);
            client.setDoOutput(true);

            OutputStream os = client.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(params));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = client.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            }
            else {
                response = "";
            }
        }
        catch (MalformedURLException e){
            e.printStackTrace();
        }
        finally {
            if(client != null) // Make sure the connection is not null.
                client.disconnect();
        }
    }

    @Override
    protected Long doInBackground(URL... params) {
        try {
            getData();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // This counts how many bytes were downloaded
        final byte[] result = response.getBytes();
        Long numOfBytes = Long.valueOf(result.length);
        return numOfBytes;
    }

    protected void onPostExecute(Long result) {
        System.out.println("Downloaded " + result + " bytes");
        // This is just printing it to the console for now.
        System.out.println(response);
        // In the following two line I pass the string elsewhere and decode it.
        InputCode input = new InputCode();
        input.passToDisplay(myContext, response);
    }
}
</code>```

Body:
I just started learning android few days ago and I have a problem with uploading my JSON data to server. I manage to retrieve it via following code:

Edit: I did manage to retrieve files using external OKHTTP library but I would like to do this without using external libraries.

package cc.demorest;

import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DownloadTask task = new DownloadTask();
        task.execute("myserver.com");
    }
//Downloadtask
    public class DownloadTask extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... urls) {

            String result = "";
                URL url;
            HttpURLConnection urlConnection=null;

            try {
                url = new URL(urls[0]);

                urlConnection=(HttpURLConnection)url.openConnection();
                InputStream in = urlConnection.getInputStream();

                InputStreamReader reader = new InputStreamReader(in);

                int data=reader.read();

                while (data !=-1){

                    char current=(char) data;

                    result += current;
                    data = reader.read();
                }

                return result;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
//After download task
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        try {

            JSONArray jArray=new JSONArray(result);
                JSONObject json_data = jArray.getJSONObject(1);
//Logging data
               Log.i("Podatci: ", "Id: " + json_data.getInt("Id") +
                                ", Name: " + json_data.getString("Name") +
                                ", Years: " + json_data.getString("Age") +
                                ", Email address: " + json_data.getString("Email")
                );
                TextView textView = (TextView) findViewById(R.id.textViewName);
                textView.setText("ID: "+", Name: "+  json_data.getInt("Id")+json_data.getString("Name")+json_data.getString("Age")+json_data.getString("Email"));

/*
        String data = jsonObject.getString("Name");
            Log.i("Website content", data);
*/
        } catch (JSONException e) {
            e.printStackTrace();
        }

        }
    }

}

I am now trying to send my data to same server with same fields. I searched internet but most things that I found are outdated.. I would really appriciate some help or example.
Best Regards

Body:
Use HttpURLConnection, it does not use external libraries.  If you're going to use an HttpURLConnection, it needs to be an AsyncTask.

Here is my code from a project I completed.  Hope it helps.

First, put this in your manifest.xml file before :

<uses-permission android:name="android.permission.INTERNET" />

Calling the AsyncTask:

(Ignore the this, SinceTime, and GoesAddress.  They are just variables I passed in)

    URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
    new ReceiveData(this, SinceTime, GoesAddress).execute(url);

The Class:

package com.ryan.scrapermain;

import android.content.Context;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class ReceiveData extends AsyncTask<URL, Integer, Long> {

    String response = "";
    String SinceTime;
    String GoesAddress;
    Context myContext;

    ReceiveData(Context context, String since, String goes) {
        this.myContext = context;
        SinceTime = since;
        GoesAddress = goes;
        }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder feedback = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                feedback.append("&");

            feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            feedback.append("=");
            feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return feedback.toString();
    }

    public void getData() throws IOException {

        HashMap<String, String> params = new HashMap<>();
        params.put("DCPID", GoesAddress);
        params.put("SINCE", SinceTime);

        URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
        HttpURLConnection client = null;
        try {
            client = (HttpURLConnection) url.openConnection();
            client.setRequestMethod("POST");
            // You need to specify the context-type.  In this case it is a
            // form submission, so use "multipart/form-data"
            client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
            client.setDoInput(true);
            client.setDoOutput(true);

            OutputStream os = client.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(params));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = client.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            }
            else {
                response = "";
            }
        }
        catch (MalformedURLException e){
            e.printStackTrace();
        }
        finally {
            if(client != null) // Make sure the connection is not null.
                client.disconnect();
        }
    }

    @Override
    protected Long doInBackground(URL... params) {
        try {
            getData();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // This counts how many bytes were downloaded
        final byte[] result = response.getBytes();
        Long numOfBytes = Long.valueOf(result.length);
        return numOfBytes;
    }

    protected void onPostExecute(Long result) {
        System.out.println("Downloaded " + result + " bytes");
        // This is just printing it to the console for now.
        System.out.println(response);
        // In the following two line I pass the string elsewhere and decode it.
        InputCode input = new InputCode();
        input.passToDisplay(myContext, response);
    }
}


问:
Who do I make CSS development suggestions to?
I've got what i think it a useful idea for CSS development but I'm unsure where to make my suggestion or to whom it should be directed.

Is there a universal inbox for CSS improvement suggestions at the W3C? I know it will take forever to get suggestions drafted, tested and put into the CSS specs but there is no time like the present...

答:
The W3C has a Participation FAQ that you might be interested in, but if your idea is development-related, does it really need to be a part of the specification? Or is it the sort of thing that developers of popular (CSS-related, web development) tools could simply add support for?

Rather than going directly to the W3C, I'd suggest first trying to get some more exposure for your idea. Write up a blog post describing it, submit it to some popular sites like A List Apart, Hacker News, or Reddit -- basically, get as many eyes on your idea as you can.

If your suggestion really is a good one, it'll help to gain momentum by getting a lot of attention. Or, if it's a bad idea, you'll quickly find out by having people "review" it. You'll likely get some good suggestions to improve the idea, and you'll definitely spend your time better getting peer feedback than somehow trying to singlehandedly champion it to the W3C.


问:
How to detect where the on demand resources are located after being downloaded?
I implement the app thinning in my project by getting the reference from below two answers:-

https://stackoverflow.com/a/33145955/988169

https://stackoverflow.com/a/31688592/988169

How to detect where the on demand resources are located after being downloaded?

答:
Unless you specified a bundle when you initialized the resource request, the resources are placed in the main bundle by default.  So for example, you could access them this way, if appropriate to your type of resource:</p>

```<code>NSString *path= [[NSBundle mainBundle] pathForResource:@"movie" ofType:@"mp4"  ];
</code>```

Body:
Unless you specified a bundle when you initialized the resource request, the resources are placed in the main bundle by default.  So for example, you could access them this way, if appropriate to your type of resource:

NSString *path= [[NSBundle mainBundle] pathForResource:@"movie" ofType:@"mp4"  ];


问:
Prestashop: Out of Memory (allocated ...) in ../../../classes/Configuration.php
Prestashop suddenly gives an http 500 error. I turned on error log and got this:

"Fatal error: Out of memory (allocated 709623808) (tried to allocate
  130968 bytes) in
  /var/www/vhosts/44/252639/webspace/httpdocs/shop.mywebsite.com/classes/Configuration.php
  on line 206".

I double checked the Configuration.php on line 206 and it's just a standard prestashop file, nothing weird in it. After all it's an "Out of memory" error so maybe I should increase memory.

phpinfo() shows memory_limit 1024M, which is already pretty much, but maybe I should try 2048M. I tried to create a new custom php.ini but that did not work, because (according to phpinfo) the loaded ini file is searched in this directory: /opt/alt/php56/etc.

My hosting provider does not allow me to edit it, it's read only.

What could I do to solve the problem ?

I did not make a backup yet.

答:
I fixed it. It had nothing to do with not having enough memory or whatever. Someone created a product and that caused errors, I don't know what exactly but for everyone in the future:

Create a backup

Turn off third party modules

Delete all products

Delete cache
etc etc. until your webpage loads correctly again ->
after that, restore your backup and just delete what caused the error.

Hope it will work.


问:
AWS S3 : upload only the file change (delta)
Is it possible to upload only the file change (delta) with AWS S3 (using the Node.JS SDK or Pre-signed URL) ? </p>

答:
No. That is not possible

For adding a Delta, you will have to fetch the object locally, add the delta and then upload back to s3


问:
Scheme using input parameter in inner function
I'm new to Scheme and to functional programming in general.

As part of an exercise, I try to implement a function that that takes a number n and prints line by line first n Fibonacci numbers

The problem is that when the program reaches the recursive call, it doesn't recognize n and so I get contract violation error.

From exploring the web I think I need to use let function in some way but I'm not sure how.

Here's the code:

```<code>(define fibo (lambda (n)
           (if (= n 1)
                 1
                 (if (= n 2)
                   (begin
                     (display "1")
                     (newline)
                     1)
                   (begin
                     (display
                      (+ (fibo (- n 1)) (fibo (- n 2))))
                     )))))
</code>```

And the error I get is:

```<code>contract violation
expected: number?
  given: #<void>
  argument position: 1st
  other arguments...:
</code>```

Thank you

答:
Split the problem up. Separate dirty side effects from the function that generates the numbers:

```<code>(define (fib-list from to)
  ...)
(fib-list 10 20)
; ==> (55 89 144 233 377 610 987 1597 2584 4181 6765)
</code>```

Then it's easy to make a function that prints said list:

```<code>(define (print-fib-list from to)
  (for-each displayln (fib-list from to)))
</code>```

This uses for-each but it's pretty much just as easy doing it with recursion.

Body:
I'm new to Scheme and to functional programming in general.

As part of an exercise, I try to implement a function that that takes a number n and prints line by line first n Fibonacci numbers

The problem is that when the program reaches the recursive call, it doesn't recognize n and so I get contract violation error.

From exploring the web I think I need to use let function in some way but I'm not sure how.

Here's the code:

(define fibo (lambda (n)
           (if (= n 1)
                 1
                 (if (= n 2)
                   (begin
                     (display "1")
                     (newline)
                     1)
                   (begin
                     (display
                      (+ (fibo (- n 1)) (fibo (- n 2))))
                     )))))

And the error I get is:

contract violation
expected: number?
  given: #<void>
  argument position: 1st
  other arguments...:

Thank you

Body:
Split the problem up. Separate dirty side effects from the function that generates the numbers:

(define (fib-list from to)
  ...)
(fib-list 10 20)
; ==> (55 89 144 233 377 610 987 1597 2584 4181 6765)

Then it's easy to make a function that prints said list:

(define (print-fib-list from to)
  (for-each displayln (fib-list from to)))

This uses for-each but it's pretty much just as easy doing it with recursion.


问:
Bootstrap 4 align elements right inside a col div
My question is pretty simple but I don't find a proper way (I mean not use absolute positionning of sub elements inside a relative position container) to achieve this in Bootstrap 4.

I have a row with a col-8 and a col-4. My content in col-4 must be right aligned so its content is at the right border.

```<code><h1 class="col-md-8">Applications portfolio</h1>

  <div class="btn-group col-md-4" role="group">
    <p class="float-right">
      <a class="btn btn-secondary btn-md" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
    </p>
  </div>
</code>```

Here is a codepen:

https://codepen.io/anon/pen/QpzVgJ

I want my two buttons to right align within the col-4.

How in Bootstrap 4 to properly align right elements within a col?

答:
The btn-groupclass in that md-4 makes that DIV a flex container, so a regular text-right class for the alignment won't work. Instead, add justify-content: flex-end; in a style attribute to it:

```<code><div class="btn-group col-md-4 text-right" role="group" style="justify-content: flex-end;">
</code>```

https://codepen.io/anon/pen/RpEYEM

(note: I erased the p  tag inside that DIV)

Body:
My question is pretty simple but I don't find a proper way (I mean not use absolute positionning of sub elements inside a relative position container) to achieve this in Bootstrap 4.

I have a row with a col-8 and a col-4. My content in col-4 must be right aligned so its content is at the right border.

Applications portfolio

         Creation

         Report

Here is a codepen:

https://codepen.io/anon/pen/QpzVgJ

I want my two buttons to right align within the col-4.

How in Bootstrap 4 to properly align right elements within a col?

Body:
The btn-groupclass in that md-4 makes that DIV a flex container, so a regular text-right class for the alignment won't work. Instead, add justify-content: flex-end; in a style attribute to it:

<div class="btn-group col-md-4 text-right" role="group" style="justify-content: flex-end;">

https://codepen.io/anon/pen/RpEYEM

(note: I erased the p  tag inside that DIV)


问:
Return response from Phoenix router.ex without controller
Is there a way to return a response from the router without going through a controller? I have tried a few different methods with no success.</p>

```<code>scope "/health_check", ZB do
  get "/" do
    text conn, "ok"
  end
end

get "/health_check" do
  text conn, "ok"
end
</code>```

答:
I got it two work by creating a new file called health_check_router.ex with this:

```<code>defmodule ZB.HealthCheckRouter do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/" do
    send_resp(conn, 200, "ok")
  end
end
</code>```

and adding this at the bottom of router.ex:

```<code>forward "/health_check", ZB.HealthCheckRouter
</code>```

Source: https://elixirforum.com/t/phoenix-router-inline-controllers/727/3

Body:
Is there a way to return a response from the router without going through a controller? I have tried a few different methods with no success.

scope "/health_check", ZB do
  get "/" do
    text conn, "ok"
  end
end

get "/health_check" do
  text conn, "ok"
end

Body:
I got it two work by creating a new file called health_check_router.ex with this:

defmodule ZB.HealthCheckRouter do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/" do
    send_resp(conn, 200, "ok")
  end
end

and adding this at the bottom of router.ex:

forward "/health_check", ZB.HealthCheckRouter

Source: https://elixirforum.com/t/phoenix-router-inline-controllers/727/3


问:
How to make a JLabel looks like a tab header of JTabbedPane
Providing the text of the JLabel is "Text",

I want a JLabel object looks like this in Nimbus:

like this in Metal:

i.e. the same as a tab header of a JTabbedPane.
Is it possible?

Thanks.

答:
Maybe another solution's logic is more easy;

put JLabel into a JPanel. set JPanel's background as you wish (image, drawing with graphics etc.) and setText to JLabel. Create a widget with them and use it ;)

Note: I think @Codemwnci 's method is more acceptable ;)


问:
Why is scanf always returning 1?
```<code>#include <stdio.h>

int main() {
    int days = scanf("%d", &days);
    printf("%d", days);
    return 0;
}
</code>```

The result is 1 no matter what.

```<code>7
1
</code>```

I've used scanf plenty of times and have never encountered this. What's the deal here?

答:
This is correct, because, scanf() returns number of successfully matched and converted elements. Considering proper input in your case, every time your input passes the conversion, so you get to see the value 1.

Point to note, scanf() does not return the scanned value itself, it stores the value in the passed argument.

Quoting C11, chapter §7.21.6.4

[...] the scanf function returns the
  number of input items assigned, which can be fewer than provided for, or even zero, in
  the event of an early matching failure.

Title: Why is scanf always returning 1?

Body:
#include <stdio.h>

int main() {
    int days = scanf("%d", &days);
    printf("%d", days);
    return 0;
}

The result is 1 no matter what.

7
1

I've used scanf plenty of times and have never encountered this. What's the deal here?


问:
PyCharm helpers not appearing in vagrant
I'm trying to configure remote debugging in pycharm on vagrant, but when I run I get the following error:

```<code>ssh://vagrant@127.0.0.1:2222/usr/local/strongarm_venv/bin/python2.7 -u /home/vagrant/.pycharm_helpers/pydev/pydevd.py --multiproc --client '0.0.0.0' --port 49921 --file /vagrant/manage.py runserver 8000
/usr/local/strongarm_venv/bin/python2.7: can't open file '/home/vagrant/.pycharm_helpers/pydev/pydevd.py': [Errno 2] No such file or directory
</code>```

I've searched the internet and my entire drive for a directory called ".pycharm_helpers" but all I can find is that pycharm was supposed to have created it at some point on the VM, which it hasn't done. Where can iI find a copy of it to manually insert, or how do I tell pycharm to put it there?

答: This happened to me if i started IntelliJ before my Vagrant instance. Or if did vagrant destroy/up while IntelliJ was running. Just restarting IntelliJ (or PyCharm) seemed to trigger a login and create the needed /home/vagrant/.pycharm_helpers/.

Body:
I'm trying to configure remote debugging in pycharm on vagrant, but when I run I get the following error:

ssh://vagrant@127.0.0.1:2222/usr/local/strongarm_venv/bin/python2.7 -u /home/vagrant/.pycharm_helpers/pydev/pydevd.py --multiproc --client '0.0.0.0' --port 49921 --file /vagrant/manage.py runserver 8000
/usr/local/strongarm_venv/bin/python2.7: can't open file '/home/vagrant/.pycharm_helpers/pydev/pydevd.py': [Errno 2] No such file or directory

I've searched the internet and my entire drive for a directory called ".pycharm_helpers" but all I can find is that pycharm was supposed to have created it at some point on the VM, which it hasn't done. Where can iI find a copy of it to manually insert, or how do I tell pycharm to put it there?


问:
Random number corresponding to array of UIColors- ERROR
I have a function that creates a CGRect and I am trying to assign a random color to each of them.

I create the colors as variables with the type UIColor and then put them into an array called colors. Then, I create a random number generator and call it when defining the background color of the CGRect, but I get the error:

Cannot call value of non-function type "[UIColor}"

Why is this? Here is my code:

```<code>func addBox(location: CGRect) -> UIView {
    let newBox = UIView(frame: location)

    let red = UIColor(red: (242.0/255.0), green: (186.0/255.0), blue: (201.0/255.0), alpha: 1.0)
    let green = UIColor(red: (186.0/255.0), green: (242.0/255.0), blue: (216.0/255.0), alpha: 1.0)
    let yellow = UIColor(red: (242.0/255.0), green: (226.0/255.0), blue: (186.0/255.0), alpha: 1.0)
    let blue = UIColor(red: (186.0/255.0), green: (216.0/255.0), blue: (242.0/255.0), alpha: 1.0)
    let colors = [red, green, yellow, blue]
    let randomNum:UInt32 = arc4random_uniform(4)

    newBox.backgroundColor = UIColor(colors(randomNum))

    hView.insertSubview(newBox, at: 0)
    return newBox
}
</code>```

If anyone could solve this that would be amazing. Any help would be immensely appreciated!! Thanks a ton in advance.

答:
This:

```<code>newBox.backgroundColor = UIColor(colors(randomNum))
</code>```

should be:

```<code>newBox.backgroundColor = colors[randomNum]
</code>```

colors is an array of UIColor. You just need one element from the array.

You should also change:

```<code>let randomNum:UInt32 = arc4random_uniform(4)
</code>```

to:

```<code>let randomNum = Int(arc4random_uniform(colors.count))
</code>```

This way if you add more colors to the array, you don't need to adjust this line. It makes your code less error prone.

Body:
I have a function that creates a CGRect and I am trying to assign a random color to each of them.

I create the colors as variables with the type UIColor and then put them into an array called colors. Then, I create a random number generator and call it when defining the background color of the CGRect, but I get the error:

Cannot call value of non-function type "[UIColor}"

Why is this? Here is my code:

func addBox(location: CGRect) -> UIView {
    let newBox = UIView(frame: location)

    let red = UIColor(red: (242.0/255.0), green: (186.0/255.0), blue: (201.0/255.0), alpha: 1.0)
    let green = UIColor(red: (186.0/255.0), green: (242.0/255.0), blue: (216.0/255.0), alpha: 1.0)
    let yellow = UIColor(red: (242.0/255.0), green: (226.0/255.0), blue: (186.0/255.0), alpha: 1.0)
    let blue = UIColor(red: (186.0/255.0), green: (216.0/255.0), blue: (242.0/255.0), alpha: 1.0)
    let colors = [red, green, yellow, blue]
    let randomNum:UInt32 = arc4random_uniform(4)

    newBox.backgroundColor = UIColor(colors(randomNum))

    hView.insertSubview(newBox, at: 0)
    return newBox
}

If anyone could solve this that would be amazing. Any help would be immensely appreciated!! Thanks a ton in advance.

Body:
This:

newBox.backgroundColor = UIColor(colors(randomNum))

should be:

newBox.backgroundColor = colors[randomNum]

colors is an array of UIColor. You just need one element from the array.

You should also change:

let randomNum:UInt32 = arc4random_uniform(4)

to:

let randomNum = Int(arc4random_uniform(colors.count))

This way if you add more colors to the array, you don't need to adjust this line. It makes your code less error prone.


问:
Python, pycharm install scrapy error
I got this error:</p>

```<code>error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2

Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at 'C:\Users\emrah\AppData\Local\Programs\Python\Python36-32\python.exe'.
</code>```

答: Follow the error and install Microsoft Visual Studio 2008 Professional Edition.

Title: Python, pycharm install scrapy error

Body:
I got this error:

error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2

Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at 'C:\Users\emrah\AppData\Local\Programs\Python\Python36-32\python.exe'.


问:
How do I pass a value into CLASS in DIV tag?
I'm editing an existing code, for a Progress Bar. Initially, the progress bar can only accept progress value [min, max, progress]. For example [min=0, max=100, progress=30].

I would like to add new input that can change the color. For example, if color="yellow", the progress bar color is yellow. How do I do that?

I would like to make the CLASS value (progress-bar.html), to be changeable.

I've tried several ways, but due to lack of understanding about the syntax, I was unsuccessful.

main.html

```<code><progress-bar [min]="0" [max]="100" [progress]="30" [color]="yellow">
</progress-bar>
</code>```

progress-bar.ts

```<code> export class ProgressBarComponent {

  @Input()
  progress: number;

  @Input()
  min: number;

  @Input()
  max: number;

  @Input()
  color: any;

  constructor() {
  }
</code>```

progress-bar.html

```<code><div style="display:flex;padding-bottom:5px;">
<div class="red" [style.width]="((progress/max) *100) + '%'"></div>
<div class="background-bar" [style.width]="(100-((progress/max) *100)) + '%'"></div>
</code>```

progress-bar.scss

```<code>.red{
    height:10px;
    margin-top:20px;
    background-color:#E64B55;
     -webkit-transition: width 2s;
transition: width 2s;
}

.yellow{
    height:10px;
    margin-top:20px;
    background-color:#db6623;
     -webkit-transition: width 2s;
transition: width 2s;
}
.background-bar{
    height:10px;
    margin-top:20px;
    margin-left:0px;
    background-color:lightgrey;
}
</code>```

答:
You can add more than one class to an element just by separating them with a space in the html. For example:

```<code><div style="display:flex;padding-bottom:5px;">
<div class="foreground-bar-warning yellow" [style.width]="((progress/max) *100) + '%'"></div>
<div class="background-bar" [style.width]="(100-((progress/max) *100)) + '%'">
</div>
</code>```

Adding the yellow class to the 2nd div will make it yellow.

Body:
I'm editing an existing code, for a Progress Bar. Initially, the progress bar can only accept progress value [min, max, progress]. For example [min=0, max=100, progress=30].

I would like to add new input that can change the color. For example, if color="yellow", the progress bar color is yellow. How do I do that?

I would like to make the CLASS value (progress-bar.html), to be changeable.

I've tried several ways, but due to lack of understanding about the syntax, I was unsuccessful.

main.html

<progress-bar [min]="0" [max]="100" [progress]="30" [color]="yellow">
</progress-bar>

progress-bar.ts

 export class ProgressBarComponent {

  @Input()
  progress: number;

  @Input()
  min: number;

  @Input()
  max: number;

  @Input()
  color: any;

  constructor() {
  }

progress-bar.html

progress-bar.scss

.red{
    height:10px;
    margin-top:20px;
    background-color:#E64B55;
     -webkit-transition: width 2s;
transition: width 2s;
}

.yellow{
    height:10px;
    margin-top:20px;
    background-color:#db6623;
     -webkit-transition: width 2s;
transition: width 2s;
}
.background-bar{
    height:10px;
    margin-top:20px;
    margin-left:0px;
    background-color:lightgrey;
}

Body:
You can add more than one class to an element just by separating them with a space in the html. For example:

<div style="display:flex;padding-bottom:5px;">
<div class="foreground-bar-warning yellow" [style.width]="((progress/max) *100) + '%'"></div>
<div class="background-bar" [style.width]="(100-((progress/max) *100)) + '%'">
</div>

Adding the yellow class to the 2nd div will make it yellow.


问:
Curl Post or Node/Express server converting double quotes to single quotes
I am sending a POST request from curl like this:

```<code>curl -H 'Content-Type:application/json" -X POST -d '{"key":"value"}' http://localhost:3000/parsejson
</code>```

However, I am getting on my Node/Express server:

```<code>{'key':'value'} // req.body
</code>```

So it is unclear to me if it is the curl request or the configuration of my node server. On my node server, I'm using: bodyParser.json() and bodyParser.urlencoded()

Thank you!

答:
First of all this line is incorrect and you cannot run curl with that:

```<code>curl -H 'Content-Type:application/json" -X POST -d '{"key":"value"}' http://localhost:3000/parsejson
</code>```

I'm mentioning it because this is a question about single and double quotes and you have single and double quotes messed up in your example of how you make a request, resulting in a code that cannot possibly be executed. Since this is obviously not how you really make the request, it is not clear how you do.

Now, if you want to see what you really get in the request, then don't use a body parser (temporarily switch it off, remove or comment it out) and run req.pipe(process.stdout) to display the request body on the server. Then you will know what you are getting from the client.

Also run curl with the -v option to see what it is actually sending.

If it turns out that curl is sending a correct JSON and your server gets a correct JSON in the request body then your problem must be somewhere else than in topics that you are asking about in this question.

Of course it's impossible to tell you what is the problem in that case because you didn't include even a single line of code in your question.

Body:
I am sending a POST request from curl like this:

curl -H 'Content-Type:application/json" -X POST -d '{"key":"value"}' http://localhost:3000/parsejson

However, I am getting on my Node/Express server:

{'key':'value'} // req.body

So it is unclear to me if it is the curl request or the configuration of my node server. On my node server, I'm using: bodyParser.json() and bodyParser.urlencoded()

Thank you!

Body:
First of all this line is incorrect and you cannot run curl with that:

curl -H 'Content-Type:application/json" -X POST -d '{"key":"value"}' http://localhost:3000/parsejson

I'm mentioning it because this is a question about single and double quotes and you have single and double quotes messed up in your example of how you make a request, resulting in a code that cannot possibly be executed. Since this is obviously not how you really make the request, it is not clear how you do.

Now, if you want to see what you really get in the request, then don't use a body parser (temporarily switch it off, remove or comment it out) and run req.pipe(process.stdout) to display the request body on the server. Then you will know what you are getting from the client.

Also run curl with the -v option to see what it is actually sending.

If it turns out that curl is sending a correct JSON and your server gets a correct JSON in the request body then your problem must be somewhere else than in topics that you are asking about in this question.

Of course it's impossible to tell you what is the problem in that case because you didn't include even a single line of code in your question.


问:
geom_bar with large number of discrete values not showing bar plot
With a data frame df I have a large number of discrete values for metric and their counts cnt

I wanted to get a bar plot of the counts for each discrete value of metric.

So I do the following,

```<code>df <- read.csv("metric.csv", header=T)
df$metric <- as.factor(df$metric)
ggplot(df, aes(x=metric, y=cnt)) +
  geom_bar(stat = 'identity')
</code>```

With the above I get an empty plot like below with this - why ?

The data I used for the data frame df is here - http://wikisend.com/download/569376/metric.csv

How do I get a bar plot out of this data ?

答:
I'm not immediately aware of any limitations of geom_bar, but it is unsurprising that this doesn't work very well -- I interrupted it on my machine, so I don't even know what it looks like when it finishes rendering.

Are you sure that a bar plot is appropriate for this data?  Which is to say, is the "metric" column effectively a factor?

Running a scatter plot completes rapidly with results that might be more useful (here using a log scale because a linear scale is hurt by the outlier)

```<code>ggplot(df, aes(x=metric, y=cnt) +
  geom_point() +
  scale_y_log10()
</code>```

yields

Body:
With a data frame df I have a large number of discrete values for metric and their counts cnt

I wanted to get a bar plot of the counts for each discrete value of metric.

So I do the following,

df <- read.csv("metric.csv", header=T)
df$metric <- as.factor(df$metric)
ggplot(df, aes(x=metric, y=cnt)) +
  geom_bar(stat = 'identity')

With the above I get an empty plot like below with this - why ?

The data I used for the data frame df is here - http://wikisend.com/download/569376/metric.csv

How do I get a bar plot out of this data ?

Body:
I'm not immediately aware of any limitations of geom_bar, but it is unsurprising that this doesn't work very well -- I interrupted it on my machine, so I don't even know what it looks like when it finishes rendering.

Are you sure that a bar plot is appropriate for this data?  Which is to say, is the "metric" column effectively a factor?

Running a scatter plot completes rapidly with results that might be more useful (here using a log scale because a linear scale is hurt by the outlier)

ggplot(df, aes(x=metric, y=cnt) +
  geom_point() +
  scale_y_log10()

yields


问:
Finding multiple maxima for dictionary of lists
I'm trying to return all maximum values from a dictionary of lists. </p>

```<code>my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

maxima = max(my_dict.items(), key=operator.itemgetter(1))[0]
</code>```

<p>This is only returning '122', rather than both '111' and '122'. How can I modify this to return both keys? </p>

答:
I think maybe this is what you want? This also keeps track of the max values for every key in my_dict.</p>

```<code>maxima = {}
my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

for key in my_dict:
    maxima[key] = max(my_dict[key])

max_keys = [key for key in maxima if maxima[key] == max(maxima.values())]
print max_keys
</code>```

Body:
I'm trying to return all maximum values from a dictionary of lists.

my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

maxima = max(my_dict.items(), key=operator.itemgetter(1))[0]

This is only returning '122', rather than both '111' and '122'. How can I modify this to return both keys?

Body:
I think maybe this is what you want? This also keeps track of the max values for every key in my_dict.

maxima = {}
my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

for key in my_dict:
    maxima[key] = max(my_dict[key])

max_keys = [key for key in maxima if maxima[key] == max(maxima.values())]
print max_keys


问:
Why react-devtools is showing many instances of the application?
Today I started the using of react-devtools and I saw 3 instances of the same application.

Is that right? What should I be doing wrong?

As we can see in the image below, there are 3 instances of Provider for the same application.

答: I suggest that you check the source in the browser maybe your script is included many times.</p>


问:
Vuforia basic app sample for android
I want to know if anyone has an idea where to find basic android samples for vuforia sdk because provided samples are too big for me to fully understand it.</p>

答: The samples provide several examples - focus on the most simple one, which is ImageTargets (.java + renderer), and this is pretty much as minimal as you can find.</p>

Title: Vuforia basic app sample for android


答:
The return type of scanf is to indicate if it successfully read an integer. </p>

<p>This will do what you're expecting </p>

```<code>#include <stdio.h>

int main() {
    int days = 0;
    scanf("%d", &days);
    printf("%d", days);
    return  0;
}
</code>```

Title: Why is scanf always returning 1?

Body:
The return type of scanf is to indicate if it successfully read an integer.

This will do what you're expecting

#include <stdio.h>

int main() {
    int days = 0;
    scanf("%d", &days);
    printf("%d", days);
    return  0;
}


问:
primefaces modal dialog not displaying the correct growl message
```<code>I have two dialogs both are modal dialog.
Dialog 1:dialog1.xhtml
<ui:composition>
<p:dialog modal="true">
<p:commandButton onclick="PF('dialog2widgetVar').open()" />
<ui:include src="dialog2.xhtml"></ui:include>
</p:dialog>
</ui:composition>
Dialog 2:dialog2.xhtml
<ui:composition>
<p:dialog modal="true">
</code>```

when the second dialog is opened the growl is appearing behind the dialog.

how to make growl to appear in the front of the second dialog?

答:
Hi I was having the same issue and I found a workaround:

```<code>.ui-growl {
    z-index: 999999 !important;
}
</code>```

I know that is not a fancy way to solve this problem but it works :)

Body:
I have two dialogs both are modal dialog.
Dialog 1:dialog1.xhtml
<ui:composition>

<ui:include src="dialog2.xhtml"></ui:include>

</ui:composition>
Dialog 2:dialog2.xhtml
<ui:composition>

when the second dialog is opened the growl is appearing behind the dialog.

how to make growl to appear in the front of the second dialog?

Body:
Hi I was having the same issue and I found a workaround:

.ui-growl {
    z-index: 999999 !important;
}

I know that is not a fancy way to solve this problem but it works :)