问:
text over img hover with jquery
I'm a complete beginner at coding and I've already searched here but I couldn't really find a proper solution to my problem.

I'm trying to get a text to appear in place of the image when I hover over the image with the mouse.
Unfortunately jQuery has to be used, I know it can be done by just using CSS.

So far I have the following which I found on here:

In the head:

```<code><script>
 $(function(){
    $('.parent').mouseenter(function(){
        $(this).children('.child').fadeIn();
    }).mouseleave(function(){
        $(this).children('.child').fadeOut();
    });
});
</script>
</code>```

In the body:

```<code><div class='parent'>
<img src='https://ichef.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg' alt='image'/>
<div class='child'>
<p>Random text.</p>
</div>
</div>
</code>```

CSS:

```<code>.parent
{
    position:relative;
}
.child
{
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: black;
    opacity: 0.5;
    padding:10px;

    display:none;
}
</code>```

Thank you for an easy tip or explanation on what I'm doing wrong and how I can solve that problem.

Edit:

This is my full code in my PHP file:

```<code>    echo "
    <!DOCTYPE html>
    <html lang=\"en\">
    <head>
        <meta charset=\"UTF-8\">
        <title>Test Blog</title>

    <script>
$(document).ready(function() {

      $('.gallery-item').hover(function() {
        $(this).find('.img-title').fadeIn(300);
      }, function() {
        $(this).find('.img-title').fadeOut(100);
      });

    });
    </script>

    </head>
    <body>

    <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>

    <div class=\"wrapper clearfix\">

      <figure class=\"gallery-item\">
        <img src='https://ichef.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg' alt='image'>
        <figcaption class=\"img-title\">
          <h5>Random text.</h5>
        </figcaption>
      </figure>

    </div>
</code>```

And there it continues with a dropdown menu routing to the other pages.
The CSS code is in my CSS file which I linked to above (the link is correct since all the other CSS code is working).

答:
You have to define the size of the overly - I did that with the position settings below. Also, I erased the opacity setting. Not sure what else you want, but basically it works now.

$(document).ready(function() {
  $('.parent').mouseenter(function() {
    $(this).children('.child').fadeIn();
  }).mouseleave(function() {
    $(this).children('.child').fadeOut();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  position: relative;
}

.child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: black;
  padding: 10px;
  display: none;
}

.child p {
  color: white;
  text-align: center;
  margin-top: 100px;
  font-size: 30px;
}</code>```

Random text.

```

Title: text over img hover with jquery

Body:
I'm a complete beginner at coding and I've already searched here but I couldn't really find a proper solution to my problem.

I'm trying to get a text to appear in place of the image when I hover over the image with the mouse.
Unfortunately jQuery has to be used, I know it can be done by just using CSS.

So far I have the following which I found on here:

In the head:

In the body:

Random text.

CSS:

.parent
{
    position:relative;
}
.child
{
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: black;
    opacity: 0.5;
    padding:10px;

    display:none;
}

Thank you for an easy tip or explanation on what I'm doing wrong and how I can solve that problem.

Edit:

This is my full code in my PHP file:

    echo "
    <!DOCTYPE html>

        <meta charset=\"UTF-8\">
        <title>Test Blog</title>

Random text.

And there it continues with a dropdown menu routing to the other pages.
The CSS code is in my CSS file which I linked to above (the link is correct since all the other CSS code is working).

Body:
You have to define the size of the overly - I did that with the position settings below. Also, I erased the opacity setting. Not sure what else you want, but basically it works now.

$(document).ready(function() {
  $('.parent').mouseenter(function() {
    $(this).children('.child').fadeIn();
  }).mouseleave(function() {
    $(this).children('.child').fadeOut();
  });
});

.parent {
  position: relative;
}

.child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: black;
  padding: 10px;
  display: none;
}

.child p {
  color: white;
  text-align: center;
  margin-top: 100px;
  font-size: 30px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
  <img src='https://ichef.bbci.co.uk/news/660/cpsprodpb/37B5/production/_89716241_thinkstockphotos-523060154.jpg' alt='image' />
  <div class='child'>
    <p>Random text.</p>
  </div>
</div>


来源: stackexchange

问:
Reload chart data via JSON with Highcharts
I am trying to reload the data for a Highcharts chart via JSON based on a button click elsewhere in the page. Initially I would like to display a default set of data (spending by category) but then load new data based on user input (spending by month, for example). The easiest way I can think of to output the JSON from the server is by passing a GET request to the PHP page, for example $.get('/dough/includes/live-chart.php?mode=month', retrieving this value from the button's ID attribute.

Here is what I have so far to retrieve the default data (spending by category). Need to find how to load completely different data into the pie chart, based on user input, on demand:

```<code>$(document).ready(function() {
            //This is an example of how I would retrieve the value for the button
            $(".clickMe").click(function() {
                var clickID = $(this).attr("id");
            });
            var options = {
                chart: {
                    renderTo: 'graph-container',
                    margin: [10, 175, 40, 40]
                },
                title: {
                    text: 'Spending by Category'
                },
                plotArea: {
                    shadow: null,
                    borderWidth: null,
                    backgroundColor: null
                },
                tooltip: {
                    formatter: function() {
                        return '<b>'+ this.point.name +'</b>: $'+ this.y;
                    }
                },
                credits: {
                    enabled: false
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            formatter: function() {
                                if (this.y > 5) return '$' + this.y;
                            },
                            color: 'white',
                            style: {
                                font: '13px Trebuchet MS, Verdana, sans-serif'
                            }
                        }
                    }
                },
                legend: {
                    layout: 'vertical',
                    style: {
                        left: 'auto',
                        bottom: 'auto',
                        right: '50px',
                        top: '100px'
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Spending',
                    data: []
                }]
            };
            $.get('/dough/includes/live-chart.php', function(data) {
            var lines = data.split('\n');
            $.each(lines, function(lineNo, line) {
                var items = line.split(',');
                var data = {};
                $.each(items, function(itemNo, item) {
                    if (itemNo === 0) {
                        data.name = item;
                    } else {
                        data.y = parseFloat(item);
                    }
                });
                options.series[0].data.push(data);
            });
            // Create the chart
            var chart = new Highcharts.Chart(options);
        });
        });
</code>```

Any help would be greatly appreciated

EDIT

Here is the updated Javascript thanks to Robodude. John, you have me on the right track here - thanks! I'm now getting stuck with how to replace the data on the chart from the AJAX request. I must admit that the code following the $.get() is most likely from sample code, I do not fully understand what is going on when it is run - perhaps there is a better way to format the data?

I was able to make some progress in that the chart now loads new data but it is added on top of what is already there. I suspect that the culprit is this line:

```<code>options.series[0].data.push(data);
</code>```

I tried options.series[0].setData(data); but nothing happens. On the bright side, the AJAX request works flawlessly based on the value of the select menu and there are no Javascript errors. Here is the code in question, sans chart options:

```<code>$.get('/dough/includes/live-chart.php?mode=cat', function(data) {
            var lines = data.split('\n');
            $.each(lines, function(lineNo, line) {
                var items = line.split(',');
                var data = {};
                $.each(items, function(itemNo, item) {
                    if (itemNo === 0) {
                        data.name = item;
                    } else {
                        data.y = parseFloat(item);
                    }
                });
                options.series[0].data.push(data);
            });
            // Create the chart
            var chart = new Highcharts.Chart(options);
        });
        $("#loadChart").click(function() {
            var loadChartData = $("#chartCat").val();
                $.get('/dough/includes/live-chart.php?mode=' + loadChartData, function(data) {
                var lines = data.split('\n');
                $.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                });
                // Create the chart
                var chart = new Highcharts.Chart(options);
            });
        });
    });
</code>```

EDIT 2
This is the format that the chart is pulling from - very simple, category name and value with \n after each.

```<code>Coffee, 4.08
Dining Out, 5.05
Dining: ODU, 5.97
Dining: Work, 38.41
Entertainment, 4.14
Gas, 79.65
Groceries, 228.23
Household, 11.21
Misc, 12.20
Snacks, 20.27
</code>```

答:
You need to clear the old array out before you push the new data in.  There are many ways to accomplish this but I used this one:

```<code>options.series[0].data.length = 0;
</code>```

So your code should look like this:

```<code>options.series[0].data.length = 0;
$.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                });
</code>```

Now when the button is clicked the old data is purged and only the new data should show up.  Hope that helps.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to reload the data for a Highcharts chart via JSON based on a button click elsewhere in the page. Initially I would like to display a default set of data (spending by category) but then load new data based on user input (spending by month, for example). The easiest way I can think of to output the JSON from the server is by passing a GET request to the PHP page, for example $.get('/dough/includes/live-chart.php?mode=month', retrieving this value from the button's ID attribute.

Here is what I have so far to retrieve the default data (spending by category). Need to find how to load completely different data into the pie chart, based on user input, on demand:

$(document).ready(function() {
            //This is an example of how I would retrieve the value for the button
            $(".clickMe").click(function() {
                var clickID = $(this).attr("id");
            });
            var options = {
                chart: {
                    renderTo: 'graph-container',
                    margin: [10, 175, 40, 40]
                },
                title: {
                    text: 'Spending by Category'
                },
                plotArea: {
                    shadow: null,
                    borderWidth: null,
                    backgroundColor: null
                },
                tooltip: {
                    formatter: function() {
                        return ''+ this.point.name +': $'+ this.y;
                    }
                },
                credits: {
                    enabled: false
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            formatter: function() {
                                if (this.y > 5) return '$' + this.y;
                            },
                            color: 'white',
                            style: {
                                font: '13px Trebuchet MS, Verdana, sans-serif'
                            }
                        }
                    }
                },
                legend: {
                    layout: 'vertical',
                    style: {
                        left: 'auto',
                        bottom: 'auto',
                        right: '50px',
                        top: '100px'
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Spending',
                    data: []
                }]
            };
            $.get('/dough/includes/live-chart.php', function(data) {
            var lines = data.split('\n');
            $.each(lines, function(lineNo, line) {
                var items = line.split(',');
                var data = {};
                $.each(items, function(itemNo, item) {
                    if (itemNo === 0) {
                        data.name = item;
                    } else {
                        data.y = parseFloat(item);
                    }
                });
                options.series[0].data.push(data);
            });
            // Create the chart
            var chart = new Highcharts.Chart(options);
        });
        });

Any help would be greatly appreciated

EDIT

Here is the updated Javascript thanks to Robodude. John, you have me on the right track here - thanks! I'm now getting stuck with how to replace the data on the chart from the AJAX request. I must admit that the code following the $.get() is most likely from sample code, I do not fully understand what is going on when it is run - perhaps there is a better way to format the data?

I was able to make some progress in that the chart now loads new data but it is added on top of what is already there. I suspect that the culprit is this line:

options.series[0].data.push(data);

I tried options.series[0].setData(data); but nothing happens. On the bright side, the AJAX request works flawlessly based on the value of the select menu and there are no Javascript errors. Here is the code in question, sans chart options:

$.get('/dough/includes/live-chart.php?mode=cat', function(data) {
            var lines = data.split('\n');
            $.each(lines, function(lineNo, line) {
                var items = line.split(',');
                var data = {};
                $.each(items, function(itemNo, item) {
                    if (itemNo === 0) {
                        data.name = item;
                    } else {
                        data.y = parseFloat(item);
                    }
                });
                options.series[0].data.push(data);
            });
            // Create the chart
            var chart = new Highcharts.Chart(options);
        });
        $("#loadChart").click(function() {
            var loadChartData = $("#chartCat").val();
                $.get('/dough/includes/live-chart.php?mode=' + loadChartData, function(data) {
                var lines = data.split('\n');
                $.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                });
                // Create the chart
                var chart = new Highcharts.Chart(options);
            });
        });
    });

EDIT 2
This is the format that the chart is pulling from - very simple, category name and value with \n after each.

Coffee, 4.08
Dining Out, 5.05
Dining: ODU, 5.97
Dining: Work, 38.41
Entertainment, 4.14
Gas, 79.65
Groceries, 228.23
Household, 11.21
Misc, 12.20
Snacks, 20.27

Body:
You need to clear the old array out before you push the new data in.  There are many ways to accomplish this but I used this one:

options.series[0].data.length = 0;

So your code should look like this:

options.series[0].data.length = 0;
$.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                });

Now when the button is clicked the old data is purged and only the new data should show up.  Hope that helps.


问:
Trying to get an object value in from a key in Javascript
I'm trying to get a country label (name) from a value (country code) in an object.

In Vue.js I'm trying to build a computed property to return the name of the country based on the country code from an API request.

In the template:

```<code>countryLabel () {
    var countries = require('../../plugins/countries')
    var countryCode = this.content.country
    function getLabelByValue(countries, countryCode) {
        return Object.keys(countries).find(label => countries[value] === countryCode)
    }
}
</code>```

From a list of countries:

```<code>module.exports = [
    { value: 'AF', label: 'Afghanistan' },
    { value: 'AX', label: 'Aland Islands' },
    { value: 'AL', label: 'Albania' },
    { value: 'DZ', label: 'Algeria' },
    { value: 'AS', label: 'American Samoa' },
    { value: 'AD', label: 'Andorra' },
    { value: 'AO', label: 'Angola' },
    { value: 'AI', label: 'Anguilla' },
    { value: 'AQ', label: 'Antarctica' },
    { value: 'AG', label: 'Antigua and Barbuda' },
    ...
]
</code>```

答:
A better way to do this would be to use an object, which is always the fastest way to lookup anything in javascript because objects are dictionaries. So if you changed your export to look like:

{
    AF: 'Afghanistan',
    AX: 'Aland Islands',
    etc...
}

then you'd be able to do instant lookups by doing countries[countryCode].

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get a country label (name) from a value (country code) in an object.

In Vue.js I'm trying to build a computed property to return the name of the country based on the country code from an API request.

In the template:

countryLabel () {
    var countries = require('../../plugins/countries')
    var countryCode = this.content.country
    function getLabelByValue(countries, countryCode) {
        return Object.keys(countries).find(label => countries[value] === countryCode)
    }
}

From a list of countries:

module.exports = [
    { value: 'AF', label: 'Afghanistan' },
    { value: 'AX', label: 'Aland Islands' },
    { value: 'AL', label: 'Albania' },
    { value: 'DZ', label: 'Algeria' },
    { value: 'AS', label: 'American Samoa' },
    { value: 'AD', label: 'Andorra' },
    { value: 'AO', label: 'Angola' },
    { value: 'AI', label: 'Anguilla' },
    { value: 'AQ', label: 'Antarctica' },
    { value: 'AG', label: 'Antigua and Barbuda' },
    ...
]


问:
Veracode throws "Technology-Specific Input Validation Problems (CWE ID 100)" for a public string property in C#
Veracode throws "Technology-Specific Input Validation Problems (CWE ID 100)" for a public string property in C#.

These are the formats I have tried already, and all give same flaw.

Option: 1

```<code>    public string MyProperty { get; set; }
</code>```

Option: 2

```<code>    private string _myProperty;
    public string MyProperty
    {
        get
        {
            return _myProperty;
        }
        set
        {
            _myProperty = value;
        }
    }
</code>```

Option: 3

```<code>    private string _myProperty;
    public string MyProperty
    {
        get
        {
            return _myProperty ?? string.Empty;
        }
        set
        {
            _myProperty = value;
        }
    }
</code>```

Can anyone tell why?

答:
This URL has some information suggesting a potential fix to the flow:

https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

So, ultimately, the property just needs an attribute and it would look like this:

```<code>[Required]
public string MyProperty { get; set; }
</code>```

This is the whole list of possible attributes from System.ComponentModel.DataAnnotations Namespace.

https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx

Body:
Veracode throws "Technology-Specific Input Validation Problems (CWE ID 100)" for a public string property in C#.

These are the formats I have tried already, and all give same flaw.

Option: 1

    public string MyProperty { get; set; }

Option: 2

    private string _myProperty;
    public string MyProperty
    {
        get
        {
            return _myProperty;
        }
        set
        {
            _myProperty = value;
        }
    }

Option: 3

    private string _myProperty;
    public string MyProperty
    {
        get
        {
            return _myProperty ?? string.Empty;
        }
        set
        {
            _myProperty = value;
        }
    }

Can anyone tell why?

Body:
This URL has some information suggesting a potential fix to the flow:

https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

So, ultimately, the property just needs an attribute and it would look like this:

[Required]
public string MyProperty { get; set; }

This is the whole list of possible attributes from System.ComponentModel.DataAnnotations Namespace.

https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx


问:
Substring of string matching regex in a bash shell
In a bash shell, I want to take the take a given string that matches a regex, and then take the part of the string.

For example, given https://github.com/PatrickConway/repo-name.git, I want to extract the repo-name substring.

How would I go about doing this? Should I do this all in a shell script, or is there another way to approach this?

答:
Here's a bashy way of doing it:

```<code>var="https://github.com/PatrickConway/repo-name.git"
basevar=${var##*/}
echo ${basevar%.*}
</code>```

...which gives repo-name

Body:
Here's a bashy way of doing it:

var="https://github.com/PatrickConway/repo-name.git"
basevar=${var##*/}
echo ${basevar%.*}

...which gives repo-name


问:
Categorize text using nltk
I am new in NLP concepts. I need to categorize my mails in my inbox to bills, health, ads etc. I am planning to use nltk to categorize and read that nltk.classify.naivebayes is a good choice for it. Where do I start? Can anyone give me a simple sample code. I have seen a lot of post which explains naivebayes and its algorithm. </p>

答:
First, as already mentioned, you should annotate your data. That means assigning tags (e.g. bills, health) to the e-mails you already have in your inbox.
Afterwards, you have to normalize it, that means splitting it into tokens and turning all words to lower case.

To start working with the data, it has to be represented as vectors in dictionaries.

Here is also a good Tutorial I find pretty useful.

Title: Categorize text using nltk


问:
Attach external disks at particular position
By using this code i can attach disks sequentially.

device 2, device 3, device 4

But i want to attach disks for a particular position.
I want to directly attach 3rd disk or 4th disk.
Without upgrading the previous disks

code

```<code>            for disk in external_disks:
                    obj = {}
                    obj['id'] = getDiskPriceId(client, disk)
                    #obj['id'] = 2277
                    #logger.info("disk %s size: %s --\n" ,(str(disk_num)), (str(disk)))
                    if  obj['id'] == "":
                            print("Invalid external disk size")
                            exit(1)
                    categories = {}
                    categories['categoryCode'] = "guest_disk"+str(disk_num)
                    categories['complexType'] = "SoftLayer_Product_Item_Category"
                    obj['categories'] =[categories]
                    obj["complexType"] = "SoftLayer_Product_Item_Price"
                    prices.append(obj)
                    disk_num = disk_num + 1

            response = client.call('SoftLayer_Product_Order','placeOrder', {
                                      "virtualGuests": [{
                                                     "id":  id
                                            }],
                                      "prices": prices,
                                      "properties": [{
                                                       "name": "NOTE_GENERAL",
                                                       "value": "adding disks"
                                              },{
                                                       "name": "MAINTENANCE_WINDOW",
                                                       "value": "now"
                                             }],
                                      "complexType": "SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade"
                      })
</code>```

答:
You can attach directly to an specific position through the attribute categoryCode, following is the order:

guest_disk1  for  Second Disk

guest_disk2  for  Third Disk

guest_disk3  for  Fourth Disk

guest_disk4  for  Fifth Disk

Make sure that item prices have the categoryCode you need, you can verify it by using the method SoftLayer_Virtual_Guest::getUpgradeItemPrices as following:

```<code>https://[username]:[apikey]@api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest/[deviceId]/getUpgradeItemPrices
</code>```

Following structure about prices allows to attach disks directly to the Third and Fourth position.

```<code>prices = [
    {
        'id': 2299,
        'categories': [
            {
                'categoryCode': 'guest_disk2',
                'complexType': 'SoftLayer_Product_Item_Category'
            }
        ],
        'complexType': 'SoftLayer_Product_Item_Price'
    },

    {
        'id': 2288,
        'categories': [
            {
                'categoryCode': 'guest_disk3',
                'complexType': 'SoftLayer_Product_Item_Category'
            }
        ],
        'complexType': 'SoftLayer_Product_Item_Price'
    }
]
</code>```

In your code the disk_num value needs to be between 2 and 3 to attach disks directly to the third and fourth position.

Note:
If you want to change/replace disk by another one with more/less space, you only need to apply the same idea. Set the categoryCode of new disk with the same categoryCode value of current disk.

I hope this help you.

Body:
By using this code i can attach disks sequentially.

device 2, device 3, device 4

But i want to attach disks for a particular position.
I want to directly attach 3rd disk or 4th disk.
Without upgrading the previous disks

code

            for disk in external_disks:
                    obj = {}
                    obj['id'] = getDiskPriceId(client, disk)
                    #obj['id'] = 2277
                    #logger.info("disk %s size: %s --\n" ,(str(disk_num)), (str(disk)))
                    if  obj['id'] == "":
                            print("Invalid external disk size")
                            exit(1)
                    categories = {}
                    categories['categoryCode'] = "guest_disk"+str(disk_num)
                    categories['complexType'] = "SoftLayer_Product_Item_Category"
                    obj['categories'] =[categories]
                    obj["complexType"] = "SoftLayer_Product_Item_Price"
                    prices.append(obj)
                    disk_num = disk_num + 1

            response = client.call('SoftLayer_Product_Order','placeOrder', {
                                      "virtualGuests": [{
                                                     "id":  id
                                            }],
                                      "prices": prices,
                                      "properties": [{
                                                       "name": "NOTE_GENERAL",
                                                       "value": "adding disks"
                                              },{
                                                       "name": "MAINTENANCE_WINDOW",
                                                       "value": "now"
                                             }],
                                      "complexType": "SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade"
                      })

Body:
You can attach directly to an specific position through the attribute categoryCode, following is the order:

guest_disk1  for  Second Disk

guest_disk2  for  Third Disk

guest_disk3  for  Fourth Disk

guest_disk4  for  Fifth Disk

Make sure that item prices have the categoryCode you need, you can verify it by using the method SoftLayer_Virtual_Guest::getUpgradeItemPrices as following:

https://[username]:[apikey]@api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest/[deviceId]/getUpgradeItemPrices

Following structure about prices allows to attach disks directly to the Third and Fourth position.

prices = [
    {
        'id': 2299,
        'categories': [
            {
                'categoryCode': 'guest_disk2',
                'complexType': 'SoftLayer_Product_Item_Category'
            }
        ],
        'complexType': 'SoftLayer_Product_Item_Price'
    },

    {
        'id': 2288,
        'categories': [
            {
                'categoryCode': 'guest_disk3',
                'complexType': 'SoftLayer_Product_Item_Category'
            }
        ],
        'complexType': 'SoftLayer_Product_Item_Price'
    }
]

In your code the disk_num value needs to be between 2 and 3 to attach disks directly to the third and fourth position.

Note:
If you want to change/replace disk by another one with more/less space, you only need to apply the same idea. Set the categoryCode of new disk with the same categoryCode value of current disk.

I hope this help you.


问:
Python 3: How to write to the same file from multiple processes without messing it up?
I have a program that can be started or stopped at any moment. The program is used to download data from web pages. First, a user will define a bunch of web pages in a .csv file, then save that .csv file, then start the program. That program will read the .csv file and turn it into a list of jobs. Next, the jobs are split among 5 separate downloader functions that work in parallel but may take different times to download.

After a downloader (which there are 5 of) finished downloading a web page, I need it to open the .csv file and remove the link. This way, as time passes, the .csv file will get smaller and smaller. The issue is that sometimes two download functions will try to update the .csv file at the same time and will cause the program to crash. How can I deal with this?

答:
Use a 'Lock' from the multiprocessing library to serialize operations with the file.

You will want to pass the lock into each process. Each process should 'acquire' the lock before it opens the file and 'release' the lock after it closes the file.

https://docs.python.org/2/library/multiprocessing.html


问:
why use<bean:include instead of <jsp:include in struts?
why use<bean:include instead of <jsp:include in struts?

答: bean:include works almost like jsp:include except that the result is stored in the page scope. This means that your code on the current page can access the results and manipulate it. See this page.</p>


问:
How do I create a simple callback in static classes in c#
I have a static class that has a method that again calls two other static class methods

Basically In the first static class I want to know once the operation is done in the two other static classes

```<code> public static class FirstClass{

    public static async System.Threading.Tasks.Task FirstClassMethod()
        {
            SecondClass. SecondClassMethod();
            ThirdClass. ThirdClassMethod();
        }
 }

 public static class SecondClass{

    public static async System.Threading.Tasks.Task SecondClassMethod()
        {

        }
 }

 public static class ThirdClass{

    public static async System.Threading.Tasks.Task ThirdClassMethod()
        {

        }
 }
</code>```

Any help on solving my problem would be appreciated very much

答:
Using Task.WhenAll, you can create a single task that wraps several tasks and completes when all wrapped tasks are completed.

```<code> public static class FirstClass{

    public static async System.Threading.Tasks.Task FirstClassMethod()
        {
            return await Task.WhenAll(
                SecondClass.SecondClassMethod(),
                ThirdClass.ThirdClassMethod()
            );
        }
 }

 public static class SecondClass{

    public static async System.Threading.Tasks.Task SecondClassMethod()
        {

        }
 }

 public static class ThirdClass{

    public static async System.Threading.Tasks.Task ThirdClassMethod()
        {

        }
 }
</code>```

Body:
I have a static class that has a method that again calls two other static class methods

Basically In the first static class I want to know once the operation is done in the two other static classes

 public static class FirstClass{

    public static async System.Threading.Tasks.Task FirstClassMethod()
        {
            SecondClass. SecondClassMethod();
            ThirdClass. ThirdClassMethod();
        }
 }

 public static class SecondClass{

    public static async System.Threading.Tasks.Task SecondClassMethod()
        {

        }
 }

 public static class ThirdClass{

    public static async System.Threading.Tasks.Task ThirdClassMethod()
        {

        }
 }

Any help on solving my problem would be appreciated very much

Body:
Using Task.WhenAll, you can create a single task that wraps several tasks and completes when all wrapped tasks are completed.

 public static class FirstClass{

    public static async System.Threading.Tasks.Task FirstClassMethod()
        {
            return await Task.WhenAll(
                SecondClass.SecondClassMethod(),
                ThirdClass.ThirdClassMethod()
            );
        }
 }

 public static class SecondClass{

    public static async System.Threading.Tasks.Task SecondClassMethod()
        {

        }
 }

 public static class ThirdClass{

    public static async System.Threading.Tasks.Task ThirdClassMethod()
        {

        }
 }


问:
How can I get the old and new value using directive in Angular 2?
Does anyone know how can I get the old and new value inside the directive? I need to compare if the value was changed to add a css class.

HTML:

```<code><ul>
    <li *ngFor="let item of list" [addClass]="item.name">{{item.name}}</li>
</ul>
</code>```

add-class.directive.ts

```<code>import { Directive, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[addClass]'
})

export class AddClassDirective implements OnInit {
  @Input('addClass') addClass: string;

  constructor() {
  }

  ngOnInit() {
    console.log(this.addClass);
  }

}
</code>```

答:
method 1:

```<code>ngOnChanges(changes: SimpleChanges) {
  if (changes['addClass'] && !changes['addClass'].isFirstChange()) {
    const prev: string = changes['addClass'].previousValue;
    const cur: string = changes['addClass'].currentValue;

    // do something with prev and cur
  }
}
</code>```

method 2:

```<code>private _addClass: string;

@Input() set addClass(value: string) {
  const prev = this._addClass;
  this._addClass = value;
  const cur = value;

  if (typeof prev !== 'undefined') {
    // do something with prev and cur
  }
}

get addClass() {
  return this._addClass;
}
</code>```

Note that both these methods will also be called when the directive is first initialized. In those cases the previous value will be undefined (which you can test for in ngOnChanges using the isFirstChange() method).

Body:
Does anyone know how can I get the old and new value inside the directive? I need to compare if the value was changed to add a css class.

HTML:

{{item.name}}

add-class.directive.ts

import { Directive, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[addClass]'
})

export class AddClassDirective implements OnInit {
  @Input('addClass') addClass: string;

  constructor() {
  }

  ngOnInit() {
    console.log(this.addClass);
  }

}

Body:
method 1:

ngOnChanges(changes: SimpleChanges) {
  if (changes['addClass'] && !changes['addClass'].isFirstChange()) {
    const prev: string = changes['addClass'].previousValue;
    const cur: string = changes['addClass'].currentValue;

    // do something with prev and cur
  }
}

method 2:

private _addClass: string;

@Input() set addClass(value: string) {
  const prev = this._addClass;
  this._addClass = value;
  const cur = value;

  if (typeof prev !== 'undefined') {
    // do something with prev and cur
  }
}

get addClass() {
  return this._addClass;
}

Note that both these methods will also be called when the directive is first initialized. In those cases the previous value will be undefined (which you can test for in ngOnChanges using the isFirstChange() method).


问:
WPF popup location issue
I am experiencing a strange WPF popup placement issue.

I have defined this XAML:

```<code><Window x:Class="PositionBug.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="300" Width="525">
<Grid>
    <TextBlock Name="Textblock1" Height="60" Width="300" Background="LightGray" HorizontalAlignment="Center"
               VerticalAlignment="Bottom">The PlacementTarget</TextBlock>
    <Popup Name="Popup1" PlacementTarget="{Binding ElementName=Textblock1}" Placement="Top" Width="120" Margin="198,0,199,0" IsOpen="True">
        <TextBlock Background="LightBlue" FontSize="18">This is a Popup</TextBlock>
    </Popup>
</Grid>
</code>```

On most computers this is the result, as expected:

However, on multiple units of one specific computer model, the result is presented like this:

Is there any way to force Placement to both Top AND Left?

答:
I had the same issue with popups in an application I'm working on. I can't expect customers to change the settings on their Tablet PCs, so I used this code to fix the popup positioning for everyone:</p>

```<code>var simplePlacement = new CustomPopupPlacement(new Point(0, 0), PopupPrimaryAxis.None);
popup.Placement = PlacementMode.Custom;
popup.CustomPopupPlacementCallback = new CustomPopupPlacementCallback((popupSize, targetSize, offset) => new [] { simplePlacement });
</code>```

Title: WPF popup location issue

Body:
I am experiencing a strange WPF popup placement issue.

I have defined this XAML:

<Window x:Class="PositionBug.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="300" Width="525">
<Grid>
    <TextBlock Name="Textblock1" Height="60" Width="300" Background="LightGray" HorizontalAlignment="Center"
               VerticalAlignment="Bottom">The PlacementTarget</TextBlock>
    <Popup Name="Popup1" PlacementTarget="{Binding ElementName=Textblock1}" Placement="Top" Width="120" Margin="198,0,199,0" IsOpen="True">
        <TextBlock Background="LightBlue" FontSize="18">This is a Popup</TextBlock>
    </Popup>
</Grid>

On most computers this is the result, as expected:

However, on multiple units of one specific computer model, the result is presented like this:

Is there any way to force Placement to both Top AND Left?

Body:
I had the same issue with popups in an application I'm working on. I can't expect customers to change the settings on their Tablet PCs, so I used this code to fix the popup positioning for everyone:

var simplePlacement = new CustomPopupPlacement(new Point(0, 0), PopupPrimaryAxis.None);
popup.Placement = PlacementMode.Custom;
popup.CustomPopupPlacementCallback = new CustomPopupPlacementCallback((popupSize, targetSize, offset) => new [] { simplePlacement });


问:
What type of navigation in React works well with login authentication?
I wonder what type of navigation works well with login authentication? Right now i use conditional rendering for certain pages or components to display and through

```<code>if (this.state.loggedIn) {
    return <UI loggedIn={this.state.loggedIn} showUser=
{this.state.showUser} logout={this.logout.bind(this)} />;

            };
</code>```

i can render something after the validation. What would it look like if i wanted to render a couple of more different pages? Should i put a state on each page that will change on onclicks and cause the app to render desired page?

Thank you lads

答:
This is an issue which nearly every modern application must tackle. Because of this, many libraries have already solved these issues for you. Take this code for example which uses react-router:

In my example I am showing you what the routes would look like in a routes.js file and then a separate file for what the acl would look like. The acl is a function which is passed into the onEnter of each route you want to protect. You can call it anything you like.

routes.js

import React from 'react';
import { hashHistory, Router, Route, IndexRoute } from 'react-router';

import { acl } from './util/acl-util';

import AppContainer from './containers/app-container';
import DashboardPage from './pages/dashboard-page';

export default class Routes extends React.Component {
  render() {
    return (
      <Router history={hashHistory}>
        <Route path="/" component={AppContainer}>
          {/* NON-AUTH ROUTES */}
          <Route
            path="login"
            components={{
              main: LoginPage,
              aside: null,
              header: this.getHeader,
            }}
          />

          {/* AUTH-REQUIRED ROUTES */}
          <Route
            onEnter={acl}
            path="dashboard"
            components={{ main: DashboardPage }}
          />
      </Router>
    );
  }
}```
</div>
</div>
</p>

<p><strong>acl-util.js</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { hasAuth } from './auth-util';

export function acl(nextState, replace) {
  const { pathname, search } = nextState.location;

  if (!hasAuth(theState)) {
    window.alert(
      'Please Log in!'
    );
    replace(`/login?loginRedirect=${encodeURIComponent(pathname + search)}`);
  }
}</code>```

I threw this example together from cutting out part of my code that won't apply directly to this concept - and therefore this code won't run as is. You'll need to define your pages, and set up a store etc.

You'd need to define a hasAuth function which can look into your state and determine whether a user is authenticated. For my hasAuth function I am looking for a jwt token and parsing the date, if the date is still in the future, I know they are still authed and any subsequent rest api calls will work.

I know you weren't asking for a certain library, but I recommend this because the app I took this code from has dozens of routes and the acl function also implements a role matrix which looks at what a user can and cannot do based on their jwt token. Our application is pretty massive and this approach keeps it organized.

Without having something like react-router, you're right, you'd need to manually manage which page is showing and manually check for auth state in each component or make a parent component to do it. In my example the "parent component to manage it" is react-router and my onEnter method called acl. In traditional applications acl stands for access control list - you can expand the code in whichever way you like.

edit:

as someone mentioned in a comment about . Your frontend application is only as secure as the backend service it is grabbing data from or posting data to. In my example, the react code attempts to mirror the auth state in the jwt token. But, at the end of the day, your real security will only be provided by your back end services. Just because the frontend thinks a user can be logged in, shouldn't mean the backend should assume they are - you need backend authentication since all frontend application state can be modified by technical users.

Body:
I wonder what type of navigation works well with login authentication? Right now i use conditional rendering for certain pages or components to display and through

if (this.state.loggedIn) {
    return <UI loggedIn={this.state.loggedIn} showUser=
{this.state.showUser} logout={this.logout.bind(this)} />;

            };

i can render something after the validation. What would it look like if i wanted to render a couple of more different pages? Should i put a state on each page that will change on onclicks and cause the app to render desired page?

Thank you lads

Body:
This is an issue which nearly every modern application must tackle. Because of this, many libraries have already solved these issues for you. Take this code for example which uses react-router:

In my example I am showing you what the routes would look like in a routes.js file and then a separate file for what the acl would look like. The acl is a function which is passed into the onEnter of each route you want to protect. You can call it anything you like.

routes.js

import React from 'react';
import { hashHistory, Router, Route, IndexRoute } from 'react-router';

import { acl } from './util/acl-util';

import AppContainer from './containers/app-container';
import DashboardPage from './pages/dashboard-page';

export default class Routes extends React.Component {
  render() {
    return (
      <Router history={hashHistory}>
        <Route path="/" component={AppContainer}>
          {/* NON-AUTH ROUTES */}
          <Route
            path="login"
            components={{
              main: LoginPage,
              aside: null,
              header: this.getHeader,
            }}
          />

          {/* AUTH-REQUIRED ROUTES */}
          <Route
            onEnter={acl}
            path="dashboard"
            components={{ main: DashboardPage }}
          />
      </Router>
    );
  }
}

acl-util.js

import { hasAuth } from './auth-util';

export function acl(nextState, replace) {
  const { pathname, search } = nextState.location;

  if (!hasAuth(theState)) {
    window.alert(
      'Please Log in!'
    );
    replace(`/login?loginRedirect=${encodeURIComponent(pathname + search)}`);
  }
}

I threw this example together from cutting out part of my code that won't apply directly to this concept - and therefore this code won't run as is. You'll need to define your pages, and set up a store etc.

You'd need to define a hasAuth function which can look into your state and determine whether a user is authenticated. For my hasAuth function I am looking for a jwt token and parsing the date, if the date is still in the future, I know they are still authed and any subsequent rest api calls will work.

I know you weren't asking for a certain library, but I recommend this because the app I took this code from has dozens of routes and the acl function also implements a role matrix which looks at what a user can and cannot do based on their jwt token. Our application is pretty massive and this approach keeps it organized.

Without having something like react-router, you're right, you'd need to manually manage which page is showing and manually check for auth state in each component or make a parent component to do it. In my example the "parent component to manage it" is react-router and my onEnter method called acl. In traditional applications acl stands for access control list - you can expand the code in whichever way you like.

edit:

as someone mentioned in a comment about . Your frontend application is only as secure as the backend service it is grabbing data from or posting data to. In my example, the react code attempts to mirror the auth state in the jwt token. But, at the end of the day, your real security will only be provided by your back end services. Just because the frontend thinks a user can be logged in, shouldn't mean the backend should assume they are - you need backend authentication since all frontend application state can be modified by technical users.


问:
Why is Range-v3 slower than the STL in this example?
I'm playing around with the Range-v3 library to perform a glorified find_if and was curious why google-benchmark consistently ranks my Range-v3 code worse than my std::find_if approach. Both g++ and clang give the same pattern with -O3 and #define NDEBUG.

The specific example I have in mind is the following using the STL:

```<code>std::vector<int> lengths(large_number, random_number);

auto const to_find = std::accumulate(lengths.begin(), lengths.end(), 0l) / 2;
auto accumulated_length = 0l;
auto found = std::find_if(lengths.begin(), lengths.end(), [&](auto const &val) {
                              accumulated_length += val;
                              return to_find < accumulated_length;
                          });
auto found_index = std::distance(lengths.begin(), found);
</code>```

This is somewhat contrived for the purpose of this illustration, but there would usually be a random generator for the to_find variable and random values in the lengths vector.

Using the Range-v3 library, I get the following code

```<code>using namespace ranges;

std::vector<int> lengths(large_number, random_number);

auto const to_find = accumulate(lengths, 0l) / 2;

auto found_index = distance(lengths | view::partial_sum()
                                    | view::take_while([=](auto const i) {
                                         return i < to_find;
                                      }));
</code>```

My question is why the Range-v3 is slower than the STL implementation. I understand this is still an experimental library, but perhaps there is something wrong with the code example or am I misusing the range concepts?

Edit

An example google-bench driver (not sure if correct)

```<code>#define NDEBUG

#include <numeric>
#include <vector>

#include <benchmark/benchmark.h>

#include <range/v3/all.hpp>

static void stl_search(benchmark::State &state) {

    using namespace ranges;

    std::vector<long> lengths(state.range(0), 1l);

    auto const to_find = std::accumulate(lengths.begin(), lengths.end(), 0l) / 2;

    while (state.KeepRunning()) {

        auto accumulated_length = 0l;
        auto const found = std::find_if(lengths.begin(), lengths.end(), [&](auto const& val) {
                               accumulated_length += val;
                               return to_find < accumulated_length;
                           });
        volatile long val = std::distance(lengths.begin(), found);
    }
    state.SetBytesProcessed(int64_t(state.iterations()) *
                            int64_t(state.range(0)) * sizeof(long));
}

static void ranges_search(benchmark::State &state) {

    using namespace ranges;

    std::vector<long> lengths(state.range(0), 1l);

    auto const to_find = accumulate(lengths, 0l) / 2;

    while (state.KeepRunning())
    {
        volatile long val = distance(lengths | view::partial_sum()
                                             | view::take_while([=](auto const& i) {
                                                   return i <= to_find;
                                               }));
    }
    state.SetBytesProcessed(int64_t(state.iterations()) *
                            int64_t(state.range(0)) * sizeof(long));
}

BENCHMARK(ranges_search)->Range(8 << 8, 8 << 16);
BENCHMARK(stl_search)->Range(8 << 8, 8 << 16);

BENCHMARK_MAIN();
</code>```

Gives

```<code>ranges_search/2048          756 ns        756 ns     902091   20.1892GB/s
ranges_search/4096         1495 ns       1494 ns     466681   20.4285GB/s
ranges_search/32768       11872 ns      11863 ns      58902   20.5801GB/s
ranges_search/262144      94982 ns      94892 ns       7364   20.5825GB/s
ranges_search/524288     189870 ns     189691 ns       3688   20.5927GB/s
stl_search/2048             348 ns        348 ns    2000964   43.8336GB/s
stl_search/4096             690 ns        689 ns    1008295   44.2751GB/s
stl_search/32768           5497 ns       5492 ns     126097    44.452GB/s
stl_search/262144         44725 ns      44681 ns      15882   43.7122GB/s
stl_search/524288         91027 ns      90936 ns       7616   42.9563GB/s
</code>```

with clang 4.0.1 and

```<code>ranges_search/2048         2309 ns       2307 ns     298507   6.61496GB/s
ranges_search/4096         4558 ns       4554 ns     154520   6.70161GB/s
ranges_search/32768       36482 ns      36454 ns      19191   6.69726GB/s
ranges_search/262144     287072 ns     286801 ns       2438   6.81004GB/s
ranges_search/524288     574230 ns     573665 ns       1209   6.80928GB/s
stl_search/2048             299 ns        298 ns    2340691   51.1437GB/s
stl_search/4096             592 ns        591 ns    1176783   51.6363GB/s
stl_search/32768           4692 ns       4689 ns     149460   52.0711GB/s
stl_search/262144         37718 ns      37679 ns      18611   51.8358GB/s
stl_search/524288         75247 ns      75173 ns       9244   51.9633GB/s
</code>```

with gcc 6.3.1.  My machine has a Haswell generation processor.  Both were compiled and executed with

```<code>g++ -Wall -O3 -std=c++14 Ranges.cpp -lbenchmark -lpthread && ./a.out
clang++ -Wall -O3 -std=c++14 Ranges.cpp -lbenchmark -lpthread && ./a.out
</code>```

答:
view::partial_sum over a range of int produces a range of int. If to_find > INT_MAX, the internal accumulator will overflow resulting in UB. In practice the algorithm most likely walks the entire input and returns the end iterator.

Conversely, your accumulated_length in the non-range-v3 approach is a long. It does not overflow, and thus has defined behavior / returns before processing the entire input.

The range-v3 approach will have correct behavior if you transform the input range into a range of long before passing it through partial_sum:

```<code>auto found_index = distance(lengths
  | view::transform(convert_to<long>{}) | view::partial_sum()
  | view::take_while([=](auto const i) { return i < to_find; }));
</code>```

Even with this correctness fix, it is still remarkedly slower than using the standard algorithms in my testing. Compiling this test program:

```<code>#include <chrono>
#include <iostream>
#include <random>
#include <vector>

#ifdef USE_RV3
#include <range/v3/core.hpp>
#include <range/v3/algorithm.hpp>
#include <range/v3/numeric.hpp>
#include <range/v3/view.hpp>

#else
#include <algorithm>
#include <numeric>
#endif

int main() {
    constexpr size_t large_number = 1UL << 30;

    int random_number = 42;

    std::vector<int> const lengths(large_number, random_number);

    using clock_t = std::chrono::steady_clock;
    auto const start = clock_t::now();

#ifdef USE_RV3
    auto const to_find = ranges::accumulate(lengths, 0l) / 2;
#else
    auto const to_find = std::accumulate(lengths.begin(), lengths.end(), 0l) / 2;
#endif

    auto const elapsed1 = clock_t::now() - start;

#ifdef USE_RV3
    auto const found_index = ranges::distance(lengths
            | ranges::view::transform(ranges::convert_to<long>{})
            | ranges::view::partial_sum()
            | ranges::view::take_while([=](auto const i) { return !(to_find < i); }));
#else
    auto accumulated_length = 0l;
    auto found = std::find_if(lengths.begin(), lengths.end(), [&](auto const &val) {
                                accumulated_length += val;
                                return to_find < accumulated_length;
                            });
    auto const found_index = std::distance(lengths.begin(), found);
#endif

    auto const elapsed2 = clock_t::now() - start;

    std::cout << "elapsed1: "
        << std::chrono::duration<double, std::milli>(elapsed1).count()
        << " ms, to_find: " << to_find << "\n"
           "elapsed2: "
        << std::chrono::duration<double, std::milli>(elapsed2).count()
        << " ms, result: " << found_index << '\n';
}
</code>```

with

```
g++-6 -std=c++14 -Ofast -march=native -DNDEBUG rv3.cpp -I ~/dev/range-v3/include -S -o -
```

both without and with -DUSE_RV3 and diffing the assembly output is interesting. The code generated up through the initialization of elapsed1 is identical for both cases. There are notable differences in the intermediate section between the initializations of elapsed1 and elapsed2. gcc does a much better job of optimizing the std version: the hot loop is all together in a single code run with branches for terminating conditions. The range-v3 version is uglier and jumps around quite a bit; I speculate that we need to wiggle the details of the implementation of partial_sum to make it more transparent to optimizers.

Body:
I'm playing around with the Range-v3 library to perform a glorified find_if and was curious why google-benchmark consistently ranks my Range-v3 code worse than my std::find_if approach. Both g++ and clang give the same pattern with -O3 and #define NDEBUG.

The specific example I have in mind is the following using the STL:

std::vector<int> lengths(large_number, random_number);

auto const to_find = std::accumulate(lengths.begin(), lengths.end(), 0l) / 2;
auto accumulated_length = 0l;
auto found = std::find_if(lengths.begin(), lengths.end(), [&](auto const &val) {
                              accumulated_length += val;
                              return to_find < accumulated_length;
                          });
auto found_index = std::distance(lengths.begin(), found);

This is somewhat contrived for the purpose of this illustration, but there would usually be a random generator for the to_find variable and random values in the lengths vector.

Using the Range-v3 library, I get the following code

using namespace ranges;

std::vector<int> lengths(large_number, random_number);

auto const to_find = accumulate(lengths, 0l) / 2;

auto found_index = distance(lengths | view::partial_sum()
                                    | view::take_while([=](auto const i) {
                                         return i < to_find;
                                      }));

My question is why the Range-v3 is slower than the STL implementation. I understand this is still an experimental library, but perhaps there is something wrong with the code example or am I misusing the range concepts?

Edit

An example google-bench driver (not sure if correct)

#define NDEBUG

#include <numeric>
#include <vector>

#include <benchmark/benchmark.h>

#include <range/v3/all.hpp>

static void stl_search(benchmark::State &state) {

    using namespace ranges;

    std::vector<long> lengths(state.range(0), 1l);

    auto const to_find = std::accumulate(lengths.begin(), lengths.end(), 0l) / 2;

    while (state.KeepRunning()) {

        auto accumulated_length = 0l;
        auto const found = std::find_if(lengths.begin(), lengths.end(), [&](auto const& val) {
                               accumulated_length += val;
                               return to_find < accumulated_length;
                           });
        volatile long val = std::distance(lengths.begin(), found);
    }
    state.SetBytesProcessed(int64_t(state.iterations()) *
                            int64_t(state.range(0)) * sizeof(long));
}

static void ranges_search(benchmark::State &state) {

    using namespace ranges;

    std::vector<long> lengths(state.range(0), 1l);

    auto const to_find = accumulate(lengths, 0l) / 2;

    while (state.KeepRunning())
    {
        volatile long val = distance(lengths | view::partial_sum()
                                             | view::take_while([=](auto const& i) {
                                                   return i <= to_find;
                                               }));
    }
    state.SetBytesProcessed(int64_t(state.iterations()) *
                            int64_t(state.range(0)) * sizeof(long));
}

BENCHMARK(ranges_search)->Range(8 << 8, 8 << 16);
BENCHMARK(stl_search)->Range(8 << 8, 8 << 16);

BENCHMARK_MAIN();

Gives

ranges_search/2048          756 ns        756 ns     902091   20.1892GB/s
ranges_search/4096         1495 ns       1494 ns     466681   20.4285GB/s
ranges_search/32768       11872 ns      11863 ns      58902   20.5801GB/s
ranges_search/262144      94982 ns      94892 ns       7364   20.5825GB/s
ranges_search/524288     189870 ns     189691 ns       3688   20.5927GB/s
stl_search/2048             348 ns        348 ns    2000964   43.8336GB/s
stl_search/4096             690 ns        689 ns    1008295   44.2751GB/s
stl_search/32768           5497 ns       5492 ns     126097    44.452GB/s
stl_search/262144         44725 ns      44681 ns      15882   43.7122GB/s
stl_search/524288         91027 ns      90936 ns       7616   42.9563GB/s

with clang 4.0.1 and

ranges_search/2048         2309 ns       2307 ns     298507   6.61496GB/s
ranges_search/4096         4558 ns       4554 ns     154520   6.70161GB/s
ranges_search/32768       36482 ns      36454 ns      19191   6.69726GB/s
ranges_search/262144     287072 ns     286801 ns       2438   6.81004GB/s
ranges_search/524288     574230 ns     573665 ns       1209   6.80928GB/s
stl_search/2048             299 ns        298 ns    2340691   51.1437GB/s
stl_search/4096             592 ns        591 ns    1176783   51.6363GB/s
stl_search/32768           4692 ns       4689 ns     149460   52.0711GB/s
stl_search/262144         37718 ns      37679 ns      18611   51.8358GB/s
stl_search/524288         75247 ns      75173 ns       9244   51.9633GB/s

with gcc 6.3.1.  My machine has a Haswell generation processor.  Both were compiled and executed with

g++ -Wall -O3 -std=c++14 Ranges.cpp -lbenchmark -lpthread && ./a.out
clang++ -Wall -O3 -std=c++14 Ranges.cpp -lbenchmark -lpthread && ./a.out

Body:
view::partial_sum over a range of int produces a range of int. If to_find > INT_MAX, the internal accumulator will overflow resulting in UB. In practice the algorithm most likely walks the entire input and returns the end iterator.

Conversely, your accumulated_length in the non-range-v3 approach is a long. It does not overflow, and thus has defined behavior / returns before processing the entire input.

The range-v3 approach will have correct behavior if you transform the input range into a range of long before passing it through partial_sum:

auto found_index = distance(lengths
  | view::transform(convert_to<long>{}) | view::partial_sum()
  | view::take_while([=](auto const i) { return i < to_find; }));

Even with this correctness fix, it is still remarkedly slower than using the standard algorithms in my testing. Compiling this test program:

#include <chrono>
#include <iostream>
#include <random>
#include <vector>

#ifdef USE_RV3
#include <range/v3/core.hpp>
#include <range/v3/algorithm.hpp>
#include <range/v3/numeric.hpp>
#include <range/v3/view.hpp>

#else
#include <algorithm>
#include <numeric>
#endif

int main() {
    constexpr size_t large_number = 1UL << 30;

    int random_number = 42;

    std::vector<int> const lengths(large_number, random_number);

    using clock_t = std::chrono::steady_clock;
    auto const start = clock_t::now();

#ifdef USE_RV3
    auto const to_find = ranges::accumulate(lengths, 0l) / 2;
#else
    auto const to_find = std::accumulate(lengths.begin(), lengths.end(), 0l) / 2;
#endif

    auto const elapsed1 = clock_t::now() - start;

#ifdef USE_RV3
    auto const found_index = ranges::distance(lengths
            | ranges::view::transform(ranges::convert_to<long>{})
            | ranges::view::partial_sum()
            | ranges::view::take_while([=](auto const i) { return !(to_find < i); }));
#else
    auto accumulated_length = 0l;
    auto found = std::find_if(lengths.begin(), lengths.end(), [&](auto const &val) {
                                accumulated_length += val;
                                return to_find < accumulated_length;
                            });
    auto const found_index = std::distance(lengths.begin(), found);
#endif

    auto const elapsed2 = clock_t::now() - start;

    std::cout << "elapsed1: "
        << std::chrono::duration<double, std::milli>(elapsed1).count()
        << " ms, to_find: " << to_find << "\n"
           "elapsed2: "
        << std::chrono::duration<double, std::milli>(elapsed2).count()
        << " ms, result: " << found_index << '\n';
}

with

g++-6 -std=c++14 -Ofast -march=native -DNDEBUG rv3.cpp -I ~/dev/range-v3/include -S -o -

both without and with -DUSE_RV3 and diffing the assembly output is interesting. The code generated up through the initialization of elapsed1 is identical for both cases. There are notable differences in the intermediate section between the initializations of elapsed1 and elapsed2. gcc does a much better job of optimizing the std version: the hot loop is all together in a single code run with branches for terminating conditions. The range-v3 version is uglier and jumps around quite a bit; I speculate that we need to wiggle the details of the implementation of partial_sum to make it more transparent to optimizers.


问:
Odd border around html table cell with colspan?
My question is similar to THIS question, but I'm unable to use divs instead of colspans with a table.

It appears to be an issue that only appears in chrome, but I need to find a workaround.

My use case is very similar to the one below. Notice how the top border for 3.3 spans two columns, which is clearly not right. In my use case, the user is able to change which cells are merged so I can't set the border for a specific cell.

How do you set a cell's border to be confined to its own cell instead of sharing with a common cell whose colspan is greater than 1?

HTML

```<code><div style="padding: 10px">
<table>
    <tr>
        <td>1.1</td>
        <td>1.2</td>
        <td>1.3</td>
        <td>1.4</td>
        <td>1.5</td>
    </tr>
    <tr>
        <td>2.1</td>
        <td>2.2</td>
        <td colspan="2">2.3</td>
        <td>2.5</td>
    </tr>
    <tr>
        <td>3.1</td>
        <td>3.2</td>
        <td>3.3</td>
        <td>3.4</td>
        <td>3.5</td>
    </tr>
    <tr>
        <td>4.1</td>
        <td>4.2</td>
        <td>4.3</td>
        <td>4.4</td>
        <td>4.5</td>
    </tr>
    <tr>
        <td>5.1</td>
        <td>5.2</td>
        <td>5.3</td>
        <td>5.4</td>
        <td>5.5</td>
    </tr>
</table>
</div>
</code>```

CSS

```<code>table {
    table-layout: fixed;
    border-spacing: 0;
    border-collapse: collapse;
}

td {
    border: 1px solid lightgrey;
    height: 60px;
    width: 60px;
    text-align: center;
    vertical-align: middle;
}

td.active {
    border: 1px solid blue;
}

td.brdr-b-hide {
    border-bottom: none;
}
td.brdr-r-hide {
    border-right: none;
}
</code>```

JavaScript

```<code>var fnActivate = function(target) {
    target.addClass('active');

    if(!target.is(':first-child')) {
        target.prev().addClass('brdr-r-hide')
    }

    var tr = target.closest('tr');
    if(!tr.is(':first-child')) {
        var prevTr = tr.prev();
        $('td', prevTr).eq($('td', tr).index(target)).addClass('brdr-b-hide');

    }
};

var fnDeactivate = function(target) {
    target.removeClass('active');

    if(!target.is(':first-child')) {
        target.prev().removeClass('brdr-r-hide')
    }

    var tr = target.closest('tr');
    if(!tr.is(':first-child')) {
        var prevTr = tr.prev();
        $('td', prevTr).eq($('td', tr).index(target)).removeClass('brdr-b-hide');

    }
}

$('table').on('click', 'td', function(e){
        var target = $(e.currentTarget);

        if(e.ctrlKey && target.hasClass('active')){
            fnDeactivate(target);
        } else if(e.ctrlKey) {
            fnActivate(target);
        } else {
            fnDeactivate($('table td.active'));
            fnActivate(target);
        }

    });
</code>```

CODE: Plunkr

答:
Issue was fixed by using:

```<code>table {
  border-collapse: separate;
}
</code>```

Code: Plunkr

It's a little different on the front end as each cell now has its own border of 1px, but it's a good workaround for the time being.

Body:
My question is similar to THIS question, but I'm unable to use divs instead of colspans with a table.

It appears to be an issue that only appears in chrome, but I need to find a workaround.

My use case is very similar to the one below. Notice how the top border for 3.3 spans two columns, which is clearly not right. In my use case, the user is able to change which cells are merged so I can't set the border for a specific cell.

How do you set a cell's border to be confined to its own cell instead of sharing with a common cell whose colspan is greater than 1?

HTML

        1.1
        1.2
        1.3
        1.4
        1.5

        2.1
        2.2
        2.3
        2.5

        3.1
        3.2
        3.3
        3.4
        3.5

        4.1
        4.2
        4.3
        4.4
        4.5

        5.1
        5.2
        5.3
        5.4
        5.5

CSS

table {
    table-layout: fixed;
    border-spacing: 0;
    border-collapse: collapse;
}

td {
    border: 1px solid lightgrey;
    height: 60px;
    width: 60px;
    text-align: center;
    vertical-align: middle;
}

td.active {
    border: 1px solid blue;
}

td.brdr-b-hide {
    border-bottom: none;
}
td.brdr-r-hide {
    border-right: none;
}

JavaScript

var fnActivate = function(target) {
    target.addClass('active');

    if(!target.is(':first-child')) {
        target.prev().addClass('brdr-r-hide')
    }

    var tr = target.closest('tr');
    if(!tr.is(':first-child')) {
        var prevTr = tr.prev();
        $('td', prevTr).eq($('td', tr).index(target)).addClass('brdr-b-hide');

    }
};

var fnDeactivate = function(target) {
    target.removeClass('active');

    if(!target.is(':first-child')) {
        target.prev().removeClass('brdr-r-hide')
    }

    var tr = target.closest('tr');
    if(!tr.is(':first-child')) {
        var prevTr = tr.prev();
        $('td', prevTr).eq($('td', tr).index(target)).removeClass('brdr-b-hide');

    }
}

$('table').on('click', 'td', function(e){
        var target = $(e.currentTarget);

        if(e.ctrlKey && target.hasClass('active')){
            fnDeactivate(target);
        } else if(e.ctrlKey) {
            fnActivate(target);
        } else {
            fnDeactivate($('table td.active'));
            fnActivate(target);
        }

    });

CODE: Plunkr

Body:
Issue was fixed by using:

table {
  border-collapse: separate;
}

Code: Plunkr

It's a little different on the front end as each cell now has its own border of 1px, but it's a good workaround for the time being.


问:
Shared Hash Table for parallel chess search
This is a conceptual question about the shared hashtable algorithm for parallel chess search.

I have implemented an alpha-beta search that spawns 4 threads, each of which conducts a search and returns the best move/evaluation. However, I am observing search instabilities, in which the threads return different results. I am using the lockless hashtable described in the link, so some entries might be overwritten or corrupted, although corrupt data will never actually be used.

Why might search threads return different results? Is this an expected outcome of parallel search, or is it a problem? If expected, how do I know which move to select?

答:
A parallel search is expected to be non-deterministic. Once you share knowledge via the transposition table (aka hashtable), you will have this effect.

If you run parallel searches, there is no easy way to decide what the correct result is. So, what can you do? If you have four threads, you could try a majority vote but I'm not aware of engines that do that.

Note that search stability is an issue that you will even have in a sequential search algorithm once you start using transposition tables.

If you run a sequential search algorithm with a transposition table and later repeat the same search (without resetting the transposition table), you are not guaranteed to get the same results. The same goes for a parallel search, only that a parallel search will not even be deterministic.

Search stability and determinism are not the same thing:

In a sequential search, you can achieve determinism (useful for debugging). In a parallel search, you cannot avoid it in practice.

Neither a sequential nor a parallel search can rule out search stability in practice. In a good search algorithm, it should be relatively unlikely, however.

For an explanation why transposition tables lead to search instability, take a look at this question.


问:
flink streaming window trigger
I have flink stream and I am calucating few things on some time window say 30 seconds.

here what happens it is giving me result my aggregating previous windows as well.

say for first 30 seconds I get result 10.

next thiry seconds I want fresh result, instead I get last window result + new
and so on.

so my question is how I get fresh result for each window.

答:
The functionality you describe can be found in Tumbling Windows: https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/windows.html#tumbling-windows

A bit more detail and/or code would help :)

Title: flink streaming window trigger


问:
Angular2: which is the best way to make multiple sync calls with Observables?
I'm studying the Observables in Angular2/4, before I've used the Promises for my services call.

I'm wondering what is the best way to make multiple sync calls.
Let me explain with an example:
my app component have a getUserInfo() method that need to make 3 calls to 3 different services that depends on each other.

```<code>getUserId():Number // return the logged in user userId from the session
getUserPermissions(userId):Array<String> // return a list of permission from the userId
getUserInfo(userId):String // return some additional info for the user
</code>```

Now let suppose that I have an User object as the following:

```<code>export class User {
id: number;
name: string;
info: string;
permissions: array<string>;
}
</code>```

I need to create a new instance of User class with the results of the 3 services call, so I need to run:

getUserId();

getUserPermissions();

getUserInfo();

What is the best and most polite way to accomplish this through Observable?

With promises I would have something like this:

```<code>this._service.getUserId().then(r1 => {
  let userId: number = r1;
  this._service.getUserPermissions(userId).then(r2 => {
    let userPermissions: Array<String> = r2;
    this._service.getUserInfo(userId).then(r3 => {
      let userInfo: string = r3;
      let user: User = new User(userId, userInfo, userPermissions);
    });
  })
});
</code>```

答:
I can't guarantee that this is the best or most polite way because RxJs is such a powerful library where you can achieve the same result in many different ways, but I'll give it a shot.

I will chip in two options.

Assuming your service looks something like this:

userservice.ts

@Injectable()
export class UserService {

  constructor(private http: Http) { }

  getUserId(): Observable<{ id: number, name: string }> {
    return Observable.of({ id: 3, name: 'Bob' }).delay(300);
    /*
     * replace with http:
     * return this.http.get('http://my.api.com/api/user/id').map(res => res.json());
     */
  }

  getUserPermission(userId: number): Observable<{ permissions: string[] }> {
    return Observable.of({ permissions: ['user', 'admin'] }).delay(300);
    /* return this.http.get(`http://my.api.com/api/user/${userId}/permissions`).map(res => res.json()); */
  }

  getUserInfo(userId: number): Observable<{ info: string }> {
    return Observable.of({ info: 'is a nice person'}).delay(300);
    /* return this.http.get(`http://my.api.com/api/user/${userId}/info`).map(res => res.json()); */
  }
}
```

<p><strong><em>Notice that the methods return Observables of JSON-objects!</em></strong><br>
Since Angular http already returns Observables, it is probably the easiest and cleanest to keep it an Observable-chain all the way down.<br>
Of course you could use the <code>map</code>-operator (f.e. <code>.map(result => result.info)</code>) inside of the service method to make the return type to <code>Observable<string></code> instead of <code>Observable<{ info: string }></code>.</p>

<hr>

<h1>switchMap</h1>

<p><strong>This approach is suited for requests that have to happen in a specific order.</strong></p>

<pre class="lang-js prettyprint-override"><code>this.userService.getUserId()
  .switchMap(userResult =>
    this.userService.getUserPermission(userResult.id)
    .switchMap(permissionsResult =>
      this.userService.getUserInfo(userResult.id)
        .map(infoResult => ({
          id: userResult.id,
          name: userResult.name,
          permissions: permissionsResult.permissions,
          info: infoResult.info
        }))
    )
  )
  .subscribe(v => console.log('switchmap:', v));
</code>```

If you open the network-tab of your browser you will see that the requests are executed in sequence, meaning that each request has to finish before the next one starts. So getUserId() has to finish before getUserPermission() starts, which in turn has to finish before getUserInfo() can run... and so on.

You can also use mergeMap instead. The only difference is, that switchMap can cancel an ongoing http-request when a new value is emitted by the source observable. Look here for a good comparison.

forkJoin

This approach allows you to execute requests in parallel.

this.userService.getUserId()
  .switchMap(userResult => Observable.forkJoin(
    [
      Observable.of(userResult),
      this.userService.getUserPermission(userResult.id),
      this.userService.getUserInfo(userResult.id)
    ]
  ))
  .map(results => ({
    id: results[0].id,
    name: results[0].name,
    permissions: results[1].permissions,
    info: results[2].info
  }))
  .subscribe(v => console.log('forkJoin:', v));
```

<p>Since <code>forkJoin</code> runs all the Observable sequences it has been given in parallel, it is the better option if the requests (or at least some of them) don't depend on each other.<br>
In this example, the <code>getUserId()</code>-request will run first, and once it has finished both <code>getUserPermission()</code> and <code>getUserInfo()</code> will start running in parallel.</p>

<hr>

<p>Both methods will return an object with the following structure:</p>

```{
    "id": 3,
    "name": "Bob"
    "permissions": [
        "user",
        "admin"
    ],
    "info": "is a nice person"
}
```

Body:
I'm studying the Observables in Angular2/4, before I've used the Promises for my services call.

I'm wondering what is the best way to make multiple sync calls.
Let me explain with an example:
my app component have a getUserInfo() method that need to make 3 calls to 3 different services that depends on each other.

getUserId():Number // return the logged in user userId from the session
getUserPermissions(userId):Array<String> // return a list of permission from the userId
getUserInfo(userId):String // return some additional info for the user

Now let suppose that I have an User object as the following:

export class User {
id: number;
name: string;
info: string;
permissions: array<string>;
}

I need to create a new instance of User class with the results of the 3 services call, so I need to run:

getUserId();

getUserPermissions();

getUserInfo();

What is the best and most polite way to accomplish this through Observable?

With promises I would have something like this:

this._service.getUserId().then(r1 => {
  let userId: number = r1;
  this._service.getUserPermissions(userId).then(r2 => {
    let userPermissions: Array<String> = r2;
    this._service.getUserInfo(userId).then(r3 => {
      let userInfo: string = r3;
      let user: User = new User(userId, userInfo, userPermissions);
    });
  })
});

Body:
I can't guarantee that this is the best or most polite way because RxJs is such a powerful library where you can achieve the same result in many different ways, but I'll give it a shot.

I will chip in two options.

Assuming your service looks something like this:

userservice.ts

@Injectable()
export class UserService {

  constructor(private http: Http) { }

  getUserId(): Observable<{ id: number, name: string }> {
    return Observable.of({ id: 3, name: 'Bob' }).delay(300);
    /*
     * replace with http:
     * return this.http.get('http://my.api.com/api/user/id').map(res => res.json());
     */
  }

  getUserPermission(userId: number): Observable<{ permissions: string[] }> {
    return Observable.of({ permissions: ['user', 'admin'] }).delay(300);
    /* return this.http.get(`http://my.api.com/api/user/${userId}/permissions`).map(res => res.json()); */
  }

  getUserInfo(userId: number): Observable<{ info: string }> {
    return Observable.of({ info: 'is a nice person'}).delay(300);
    /* return this.http.get(`http://my.api.com/api/user/${userId}/info`).map(res => res.json()); */
  }
}

Notice that the methods return Observables of JSON-objects!

Since Angular http already returns Observables, it is probably the easiest and cleanest to keep it an Observable-chain all the way down.

Of course you could use the map-operator (f.e. .map(result => result.info)) inside of the service method to make the return type to Observable<string> instead of Observable<{ info: string }>.

switchMap

This approach is suited for requests that have to happen in a specific order.

this.userService.getUserId()
  .switchMap(userResult =>
    this.userService.getUserPermission(userResult.id)
    .switchMap(permissionsResult =>
      this.userService.getUserInfo(userResult.id)
        .map(infoResult => ({
          id: userResult.id,
          name: userResult.name,
          permissions: permissionsResult.permissions,
          info: infoResult.info
        }))
    )
  )
  .subscribe(v => console.log('switchmap:', v));

If you open the network-tab of your browser you will see that the requests are executed in sequence, meaning that each request has to finish before the next one starts. So getUserId() has to finish before getUserPermission() starts, which in turn has to finish before getUserInfo() can run... and so on.

You can also use mergeMap instead. The only difference is, that switchMap can cancel an ongoing http-request when a new value is emitted by the source observable. Look here for a good comparison.

forkJoin

This approach allows you to execute requests in parallel.

this.userService.getUserId()
  .switchMap(userResult => Observable.forkJoin(
    [
      Observable.of(userResult),
      this.userService.getUserPermission(userResult.id),
      this.userService.getUserInfo(userResult.id)
    ]
  ))
  .map(results => ({
    id: results[0].id,
    name: results[0].name,
    permissions: results[1].permissions,
    info: results[2].info
  }))
  .subscribe(v => console.log('forkJoin:', v));

Since forkJoin runs all the Observable sequences it has been given in parallel, it is the better option if the requests (or at least some of them) don't depend on each other.

In this example, the getUserId()-request will run first, and once it has finished both getUserPermission() and getUserInfo() will start running in parallel.

Both methods will return an object with the following structure:

{
    "id": 3,
    "name": "Bob"
    "permissions": [
        "user",
        "admin"
    ],
    "info": "is a nice person"
}


问:
Put content in HttpResponseMessage object?
Several months ago, Microsoft decided to change up the HttpResponseMessage class. Before, you could simply pass a data type into the constructor, and then return the message with that data, but not anymore.

Now, you need to use the Content property to set the content of the message. The problem is that it is of type HttpContent, and I can't seem to find a way to convert a string, for example, to HttpContent.

Does anyone know how to deal with this issue?
Thanks a lot.

答:
No doubt that you are correct Florin. I was working on this project, and found that this piece of code:

```<code>product = await response.Content.ReadAsAsync<Product>();
</code>```

Could be replaced with:

```<code>response.Content = new StringContent(string product);
</code>```

Body:
No doubt that you are correct Florin. I was working on this project, and found that this piece of code:

product = await response.Content.ReadAsAsync<Product>();

Could be replaced with:

response.Content = new StringContent(string product);


问:
Correct Way to use Accelerometer
Im using the accelerometer as the steering mechanism for my game. It works fine usually but occasionally it will act very odd. Randomly there is suddenly a large amount of input delay and every rotation I make isn't registered for a while. In some cases there might be a lot of delay in between commands entered right after each other leading to my character drifting in one direction for far too long. Is this due to game lag or is my code at fault? My code below.</p>

```<code>   actionMoveLeft = SKAction.moveBy(x: -3, y: 0, duration: 0.1)
    actionMoveRight = SKAction.moveBy(x: 3, y: 0, duration: 0.1)
    self.addChild(ship)
    if motionManager.isAccelerometerAvailable == true {
        motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler:{
            data, error in
            if (data!.acceleration.y) < -0.05 {
                self.ship.run(self.actionMoveLeft)
            }

            else if data!.acceleration.y > 0.05 {
                self.ship.run(self.actionMoveRight)
            }

        })

    }
</code>```

答:
It's not guaranteed that the accelerometer will give you updates with regular intervals of 0.1 seconds (assuming that the deviceMotionUpdateInterval property of your CMMotionManager instance is set to 0.1). SKActions work fine when every action is executed at a discrete interval of time. But since the accelerometer gives you irregular interval updates, you may end up executing more actions at the same time.

An easy fix for that would be to remove the previous action every time:

```<code>if (data!.acceleration.y) < -0.05 {
    self.ship.removeAction(forKey: "Move")
    self.ship.run(self.actionMoveLeft, withKey: "Move")
}
</code>```

But I still not recommend to use this approach, because the movement still doesn't look smooth, but it looks like your ship is moving jerkily. I suggest to use a SKPhysicsBody and directly manipulate its velocity property. Something like this:

```<code>// Inside the update method, assuming you have saved the acceleration vector
// and you have a deltaTime variable that holds the difference of time
// elapsed from the previous update
self.ship.physicsBody.velocity = CGVector(dx: self.ship.physicsBody.velocity.dx + CGFloat(acceleration.x * deltaTime), dy: self.ship.physicsBody.velocity.dy + CGFloat(acceleration.y * deltaTime))
</code>```

If you don't want to use a physics body because you're just handling physics using your custom functions, then I suggest to compute the position of the ship manually at every frame.

Title: Correct Way to use Accelerometer

Body:
Im using the accelerometer as the steering mechanism for my game. It works fine usually but occasionally it will act very odd. Randomly there is suddenly a large amount of input delay and every rotation I make isn't registered for a while. In some cases there might be a lot of delay in between commands entered right after each other leading to my character drifting in one direction for far too long. Is this due to game lag or is my code at fault? My code below.

   actionMoveLeft = SKAction.moveBy(x: -3, y: 0, duration: 0.1)
    actionMoveRight = SKAction.moveBy(x: 3, y: 0, duration: 0.1)
    self.addChild(ship)
    if motionManager.isAccelerometerAvailable == true {
        motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler:{
            data, error in
            if (data!.acceleration.y) < -0.05 {
                self.ship.run(self.actionMoveLeft)
            }

            else if data!.acceleration.y > 0.05 {
                self.ship.run(self.actionMoveRight)
            }

        })

    }

Body:
It's not guaranteed that the accelerometer will give you updates with regular intervals of 0.1 seconds (assuming that the deviceMotionUpdateInterval property of your CMMotionManager instance is set to 0.1). SKActions work fine when every action is executed at a discrete interval of time. But since the accelerometer gives you irregular interval updates, you may end up executing more actions at the same time.

An easy fix for that would be to remove the previous action every time:

if (data!.acceleration.y) < -0.05 {
    self.ship.removeAction(forKey: "Move")
    self.ship.run(self.actionMoveLeft, withKey: "Move")
}

But I still not recommend to use this approach, because the movement still doesn't look smooth, but it looks like your ship is moving jerkily. I suggest to use a SKPhysicsBody and directly manipulate its velocity property. Something like this:

// Inside the update method, assuming you have saved the acceleration vector
// and you have a deltaTime variable that holds the difference of time
// elapsed from the previous update
self.ship.physicsBody.velocity = CGVector(dx: self.ship.physicsBody.velocity.dx + CGFloat(acceleration.x * deltaTime), dy: self.ship.physicsBody.velocity.dy + CGFloat(acceleration.y * deltaTime))

If you don't want to use a physics body because you're just handling physics using your custom functions, then I suggest to compute the position of the ship manually at every frame.


问:
Manipulating reactive objects in Shiny - Error in <-: invalid (NULL) left side of assignment
I'm running into the error "Error in <-: invalid (NULL) left side of assignment" over and over again as I attempt to take a reactive object in Shiny and further manipulate it. I've provided an illustrative example below.

```<code> testdf <- data.frame(row1 = c(1,3,6), row2 = c(7, 5, 1))

 ui <- fluidPage(

   titlePanel("Education in Tanzania"),

   sidebarLayout(
     sidebarPanel(

       #Select aggregation level of data
       selectInput("AggregationSelect",
                   label = "Aggregation",
                   choices = list("School" = 1,
                                  "District" = 2,
                                  "Region" = 3),
                   selected = 1)
     ),

     mainPanel(
       DT::dataTableOutput("OutputTable")
     )
   )
 )

 server <- function(input, output) {

     Output1 <- reactive({
         testdf
     })

   observe({
     if(2 %in% input$AggregationSelect) {
       observe({Output1()$name[3] <- "b"})
     } else  if(3 %in% input$AggregationSelect) {
       observe({Output1()$name[2] <- "c"})
     } else  if(1 %in% input$AggregationSelect) {
       observe({Output1()$name[1] <- "a"})
     }
   })

   output$OutputTable <- {DT::renderDataTable({
     DT::datatable(Output1(),
                   options = list(pagelength = 25,
                                  searching = TRUE,
                                  paging = TRUE,
                                  lengthChange = FALSE),
                   rownames = FALSE)
     })
   }
 }

 shinyApp(ui = ui, server = server)
</code>```

What I need to do in my actual code is assemble a dataframe through the UI (which I am able to do and therefore have just subbed a random df in here) and then add some information (represented here with the added "names" column) based on what has been selected in the UI. It seems like it shouldn't be all that difficult to add a column to a df, but within the reactive object context, nothing I have attempted has worked. Other ways to modify reactive objects are welcome as long as they can be applied to more complex multi-step scenarios - there's no way I can get everything I need bundled into the initial assignment of the reactive object.

答:
Reactive expressions cannot be modified from outside. You can only modify reactive values.

Generally you should never need to use observe. Use reactive expression if you don't need side effect, use reactive values with observeEvent when needed.

You must read reactive tutorials before going forward. There are quite some concepts need to be understood before you can do anything complex, especially the "force update habit". You need to let Shiny do the update properly and setup the logic correctly.

I suggest you read all the tutorials, articles about reactive in RStudio website, then watch the reactive tutorial video in Shiny conference.

Body:
I'm running into the error "Error in <-: invalid (NULL) left side of assignment" over and over again as I attempt to take a reactive object in Shiny and further manipulate it. I've provided an illustrative example below.

 testdf <- data.frame(row1 = c(1,3,6), row2 = c(7, 5, 1))

 ui <- fluidPage(

   titlePanel("Education in Tanzania"),

   sidebarLayout(
     sidebarPanel(

       #Select aggregation level of data
       selectInput("AggregationSelect",
                   label = "Aggregation",
                   choices = list("School" = 1,
                                  "District" = 2,
                                  "Region" = 3),
                   selected = 1)
     ),

     mainPanel(
       DT::dataTableOutput("OutputTable")
     )
   )
 )

 server <- function(input, output) {

     Output1 <- reactive({
         testdf
     })

   observe({
     if(2 %in% input$AggregationSelect) {
       observe({Output1()$name[3] <- "b"})
     } else  if(3 %in% input$AggregationSelect) {
       observe({Output1()$name[2] <- "c"})
     } else  if(1 %in% input$AggregationSelect) {
       observe({Output1()$name[1] <- "a"})
     }
   })

   output$OutputTable <- {DT::renderDataTable({
     DT::datatable(Output1(),
                   options = list(pagelength = 25,
                                  searching = TRUE,
                                  paging = TRUE,
                                  lengthChange = FALSE),
                   rownames = FALSE)
     })
   }
 }

 shinyApp(ui = ui, server = server)

What I need to do in my actual code is assemble a dataframe through the UI (which I am able to do and therefore have just subbed a random df in here) and then add some information (represented here with the added "names" column) based on what has been selected in the UI. It seems like it shouldn't be all that difficult to add a column to a df, but within the reactive object context, nothing I have attempted has worked. Other ways to modify reactive objects are welcome as long as they can be applied to more complex multi-step scenarios - there's no way I can get everything I need bundled into the initial assignment of the reactive object.