问:
Aggregating DataTable Without LINQ
I want to aggregate a datatables rows based on some distinct values. I have to use Select and Compute methods or other non-linq approaches.
My question is: how can I aggregate (sum, count, min and ...) and grouping fields, and get results just like the sql server tables. Consider I have a table with four columns a, b, c, d. When I want to aggregate 'a' based on 'b, I can write:

```<code>Select sum(a) as 'a', b
from myTable
group by b
</code>```

And the sql sever make a table with two columns, 'a' and 'b', so how can i do this in C# and using DataTables?
I saw the examples of DataTable.Compute() in MSDN and the other related sources for aggregating and grouping the data in a datatable, but it return just an object value and it doesn't useful for grouping rows in datatable. in my problem, the user deiced to using of sum, min, max, or ... at run time, and  I trying to find a solution  for creating some dynamic queries.

答:
Try following : </p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication64
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("a", typeof(int));
            dt.Columns.Add("b", typeof(string));
            dt.Columns.Add("c", typeof(string));
            dt.Columns.Add("d", typeof(string));

            dt.Rows.Add(new object[] { 1, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 2, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 3, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 4, "b2", "c", "d" });
            dt.Rows.Add(new object[] { 5, "b2", "c", "d" });
            dt.Rows.Add(new object[] { 6, "b3", "c", "d" });
            dt.Rows.Add(new object[] { 7, "b4", "c", "d" });

            var results = dt.AsEnumerable().GroupBy(x => x.Field<string>("b")).Select(x => new { key = x.Key, sum = x.Sum(y => y.Field<int>("a"))}).ToList();
        }
    }
}
</code>```

Title: Aggregating DataTable Without LINQ

Body:
I want to aggregate a datatables rows based on some distinct values. I have to use Select and Compute methods or other non-linq approaches.
My question is: how can I aggregate (sum, count, min and ...) and grouping fields, and get results just like the sql server tables. Consider I have a table with four columns a, b, c, d. When I want to aggregate 'a' based on 'b, I can write:

Select sum(a) as 'a', b
from myTable
group by b

And the sql sever make a table with two columns, 'a' and 'b', so how can i do this in C# and using DataTables?
I saw the examples of DataTable.Compute() in MSDN and the other related sources for aggregating and grouping the data in a datatable, but it return just an object value and it doesn't useful for grouping rows in datatable. in my problem, the user deiced to using of sum, min, max, or ... at run time, and  I trying to find a solution  for creating some dynamic queries.

Body:
Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication64
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("a", typeof(int));
            dt.Columns.Add("b", typeof(string));
            dt.Columns.Add("c", typeof(string));
            dt.Columns.Add("d", typeof(string));

            dt.Rows.Add(new object[] { 1, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 2, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 3, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 4, "b2", "c", "d" });
            dt.Rows.Add(new object[] { 5, "b2", "c", "d" });
            dt.Rows.Add(new object[] { 6, "b3", "c", "d" });
            dt.Rows.Add(new object[] { 7, "b4", "c", "d" });

            var results = dt.AsEnumerable().GroupBy(x => x.Field<string>("b")).Select(x => new { key = x.Key, sum = x.Sum(y => y.Field<int>("a"))}).ToList();
        }
    }
}


来源: stackexchange

问:
Spark sql version of the same query does not work whereas the normal sql query does
The normal sql query :

```<code>    SELECT DISTINCT(county_geoid), state_geoid, sum(PredResponse), sum(prop_count) FROM table_a GROUP BY county_geoid;
</code>```

Gives me an output. However the spark sql version of this same query used in pyspark is giving me an error. How to resolve this issue?

```<code>    result_county_performance_alpha = spark.sql("SELECT distinct(county_geoid), sum(PredResponse), sum(prop_count), state_geoid FROM table_a group by county_geoid")
</code>```

This gives an error :

```AnalysisException: u"expression 'tract_alpha.`state_geoid`' is neither present in the group by, nor is it an aggregate function. Add to group by or wrap in first() (or first_value) if you don't care which value you get.;```

How to resolve this issue?

答:
Your "normal" query should not work anywhere.  The correct way to write the query is:

```<code>SELECT county_geoid, state_geoid, sum(PredResponse), sum(prop_count)
FROM table_a
GROUP BY county_geoid, state_geoid;
</code>```

This should work on any database (where the columns and tables are defined and of the right types).

Your version has state_geoid in the SELECT, but it is not being aggregated.  That is not correct SQL.  It might happen to work in MySQL, but that is due to a (mis)feature in the database (that is finally being fixed).

Also, you almost never want to use SELECT DISTINCT with GROUP BY.  And, the parentheses after the DISTINCT make no difference.  The construct is SELECT DISTINCT.  DISTINCT is not a function.

ContentLicense: CC BY-SA 3.0

Body:
The normal sql query :

    SELECT DISTINCT(county_geoid), state_geoid, sum(PredResponse), sum(prop_count) FROM table_a GROUP BY county_geoid;

Gives me an output. However the spark sql version of this same query used in pyspark is giving me an error. How to resolve this issue?

    result_county_performance_alpha = spark.sql("SELECT distinct(county_geoid), sum(PredResponse), sum(prop_count), state_geoid FROM table_a group by county_geoid")

This gives an error :

AnalysisException: u"expression 'tract_alpha.`state_geoid`' is neither present in the group by, nor is it an aggregate function. Add to group by or wrap in first() (or first_value) if you don't care which value you get.;

How to resolve this issue?

Body:
Your "normal" query should not work anywhere.  The correct way to write the query is:

SELECT county_geoid, state_geoid, sum(PredResponse), sum(prop_count)
FROM table_a
GROUP BY county_geoid, state_geoid;

This should work on any database (where the columns and tables are defined and of the right types).

Your version has state_geoid in the SELECT, but it is not being aggregated.  That is not correct SQL.  It might happen to work in MySQL, but that is due to a (mis)feature in the database (that is finally being fixed).

Also, you almost never want to use SELECT DISTINCT with GROUP BY.  And, the parentheses after the DISTINCT make no difference.  The construct is SELECT DISTINCT.  DISTINCT is not a function.


问:
Reduce Border bottom length
Hi I want to know that whether can i reduce length of border bottom. I have a div and i have given border-bottom: 2px to that div i want to reduce the length of border. Is this possible.

I have this nav-bar and i have given css to its div want to reduce length of border. How can i do that.

This is my html

```<code>               <div class="row">
        <div class="col-sm-12 col-xs-12 col-lg-12 col-md-12 welcome">
            <ul class="nav navbar-nav navbar-nav-primary">
                <li class="active">
                    <a href="#one" data-toggle="tab">
                        <i class="fa fa-map-marker" aria-hidden="true"></i> <span class="li-text">Location</span>
                    </a>
                </li>
                <li>
                    <a href="#two" data-toggle="tab">
                        <i class="fa fa-heartbeat" aria-hidden="true"></i> <span class="li-text">Heartbeats</span>
                    </a>
                </li>
                <li>
                    <a href="#three" data-toggle="tab">
                        <i class="fa fa-power-off" aria-hidden="true"></i>
                        <span class="li-text">Reboots</span>
                    </a>
                </li>
                <li>
                    <a href="#four" data-toggle="tab">
                        <i class="fa fa-compress" aria-hidden="true"></i>
                        <span class="li-text">Reconnects</span>
                    </a>
                </li>
                <li>
                    <a href="#five" data-toggle="tab">
                        <i class="fa fa-battery-full" aria-hidden="true"></i>
                        <span class="li-text">Charge</span>
                    </a>
                </li>

            </ul>

        </div>
</code>```

This is my CSS

```<code>        .welcome {
              border-bottom: 2px solid #bcbcbc;
              margin-left: 10px;
             }
</code>```

答:
remove the border-bottom css from the class welcome
and use this;

```<code>ul.nav.navbar-nav.navbar-nav-primary {
    border-bottom: 2px solid #ddd;
}
.welcome {
    margin-left: 10px;
}
</code>```

Title: Reduce Border bottom length

Body:
Hi I want to know that whether can i reduce length of border bottom. I have a div and i have given border-bottom: 2px to that div i want to reduce the length of border. Is this possible.

I have this nav-bar and i have given css to its div want to reduce length of border. How can i do that.

This is my html

                         Location

                         Heartbeats

                        Reboots

                        Reconnects

                        Charge

This is my CSS

        .welcome {
              border-bottom: 2px solid #bcbcbc;
              margin-left: 10px;
             }

Body:
remove the border-bottom css from the class welcome
and use this;

ul.nav.navbar-nav.navbar-nav-primary {
    border-bottom: 2px solid #ddd;
}
.welcome {
    margin-left: 10px;
}


问:
CKEditor and ASP.Net MVC 3 RequiredAttribute
I've integrated CKEditor 3 (formerly FCKEditor) into my asp.net MVC (v3 to be specific) application. I have a RequiredAttribute in my model for the field that needs the editor but the client side validation doesn't work correctly with CKEditor. When I try to submit and I've entered data into CKEditor the required validation doesn't see the data. If I try resubmitting again, then it works. I've looked around online and can't find a solution. I am also using Jquery and using the Jquery adapter

http://docs.cksource.com/CKEditor_3.x/Developers_Guide/jQuery_Adapter

答:
For me this code does the trick, it could probably be optimized a bit but it works:

```<code>$('#newsForm').submit(function (event) {
     var editor = $('#Body').ckeditorGet();
     editor.updateElement();
     $(this).validate().form();
});
</code>```

Because I don't know in which order the eventhandlers for submit runs I make sure to both update the value and refresh the validation result.

EDIT: Updated solution

```<code><script type="text/javascript">
    //<![CDATA[
    $(document).ready(function () {
        $('#Body').ckeditor();
        $('#newsForm').bind('submit', onFirstSubmit);
    });

    function onFirstSubmit(event) {
        var editor = $('#Body').ckeditorGet();
        editor.updateElement();
        $(this).validate().form();
        $(this).unbind('submit', onFirstSubmit).submit();
    }

    //]]>
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For me this code does the trick, it could probably be optimized a bit but it works:

$('#newsForm').submit(function (event) {
     var editor = $('#Body').ckeditorGet();
     editor.updateElement();
     $(this).validate().form();
});

Because I don't know in which order the eventhandlers for submit runs I make sure to both update the value and refresh the validation result.

EDIT: Updated solution

<script type="text/javascript">
    //<![CDATA[
    $(document).ready(function () {
        $('#Body').ckeditor();
        $('#newsForm').bind('submit', onFirstSubmit);
    });

    function onFirstSubmit(event) {
        var editor = $('#Body').ckeditorGet();
        editor.updateElement();
        $(this).validate().form();
        $(this).unbind('submit', onFirstSubmit).submit();
    }

    //]]>
</script>


问:
How to get clicked element id in jquery
Here i am creating a shopping list, i have a text box to enter the item and submit button to add the item to array.
on submit the item gets pushed to array and the the list will get updated.what i am trying to do is when i click on the any of the listed item i should be able to get its id, but i couldn't get it.how can i resolve this?

here is what i have done:

'use strict';
(function() {
  var itemslist = [];
  $('#addList').click(function(e) {
    var item = $('#itemname').val();
    if (item == '') {
      alert('Cannot be empty!')
      return false;
    } else {
      e.preventDefault();
      itemslist.push(item);
      update();
    }
  })

  var update = function() {
    $('#shopList').empty();
    itemslist.forEach(function(value, index) {
      $('#shopList').append("
" + value + "
") //list-item gets appended after the successful push of item to array
    })
  }

  $('.items-list').click(function() {
    console.log(this.id); //unable to get the clicked element id
  })

})(window);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <form method="post" name="listform">
    <input id="itemname" type="text" value="" name="item" placeholder="Ex: butter and milk" required>
    <button class="btn btn-peace" id="addList"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Add to List</button>
  </form>
</div>
<div id="shopList">
</div></code>```

答:
```<code>$(this).attr('id')
</code>```

should do the trick

The function isn't working as it is not bound to the dynamically created element.

To bind this, pick an element higher up in the hierarchy and then check which element is clicked. You can do this as below:

```<code>$(body).on('click','.items-list', function() {
    console.log($(this).attr('id') );
});
</code>```

Title: How to get clicked element id in jquery

Body:
Here i am creating a shopping list, i have a text box to enter the item and submit button to add the item to array.
on submit the item gets pushed to array and the the list will get updated.what i am trying to do is when i click on the any of the listed item i should be able to get its id, but i couldn't get it.how can i resolve this?

here is what i have done:

'use strict';
(function() {
  var itemslist = [];
  $('#addList').click(function(e) {
    var item = $('#itemname').val();
    if (item == '') {
      alert('Cannot be empty!')
      return false;
    } else {
      e.preventDefault();
      itemslist.push(item);
      update();
    }
  })

  var update = function() {
    $('#shopList').empty();
    itemslist.forEach(function(value, index) {
      $('#shopList').append("
" + value + "
") //list-item gets appended after the successful push of item to array
    })
  }

  $('.items-list').click(function() {
    console.log(this.id); //unable to get the clicked element id
  })

})(window);

  <form method="post" name="listform">
    <input id="itemname" type="text" value="" name="item" placeholder="Ex: butter and milk" required>
    <button class="btn btn-peace" id="addList"> Add to List</button>
  </form>

Body:
$(this).attr('id')

should do the trick

The function isn't working as it is not bound to the dynamically created element.

To bind this, pick an element higher up in the hierarchy and then check which element is clicked. You can do this as below:

$(body).on('click','.items-list', function() {
    console.log($(this).attr('id') );
});


问:
unsupported pseudo: in-viewport
I'm following this guide to detect when my video element comes in viewport then do "x", but keep getting the title error. Not sure if because Im using wordpress with gulp and piling.js

My page uses Piling and I have a video section, when I scroll to that "stack", I want the video to start play but it starts to play on page load.

```<code>// inside document.ready()

 $('video').each(function(){
    if ($(this).is(":in-viewport")) {
        $(this)[0].play();
    } else {
        $(this)[0].pause();
    }
})
</code>```

Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: in-viewport

```<code><div id='<ID-CHANGES-INSIDE-LOOP>' class='image-block'>
  <video autoplay>
    <source class='video' src='movie.mp4' type='video/mp4'>
  </video>
</div>
</code>```

Is using Piling making this difficult to work?

答: You should be using pagePiling.js callbacks or state classes.</p>

Title: unsupported pseudo: in-viewport

Body:
I'm following this guide to detect when my video element comes in viewport then do "x", but keep getting the title error. Not sure if because Im using wordpress with gulp and piling.js

My page uses Piling and I have a video section, when I scroll to that "stack", I want the video to start play but it starts to play on page load.

// inside document.ready()

 $('video').each(function(){
    if ($(this).is(":in-viewport")) {
        $(this)[0].play();
    } else {
        $(this)[0].pause();
    }
})

Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: in-viewport

<div id='<ID-CHANGES-INSIDE-LOOP>' class='image-block'>
  <video autoplay>
    <source class='video' src='movie.mp4' type='video/mp4'>
  </video>

Is using Piling making this difficult to work?


问:
Is there a way to modify a json string within the html while reading it in?
so I have a complex object structure in my JSON which is a list with many attributes for each element. I want to be able to access the name attribute and output it whole ie: "task one" and add an href on the fly while loading the text which will reference "link-to-task-one".

I'm using knockout js and this is what the line looks like

I know the js function replace doesnt work in html docs, I just want to know if theres a way to force json to be rendered like maybe within certain tags, or if someone can help me figure out a  method to put in there that wouldn't take too much time.

Or if I'm being stupid and should just add another attribute called 'ref' or something in my JSON

答:
Why not add a computed to your model:

```<code>self.link = ko.computed(function () {
    return '#link-to-' + self.taskName().replace(/\s+/g,'-');
}, self);
</code>```

Then:

```<code><a class="this-class" data-bind="text: taskName, attr: { href: link }"></a>
</code>```

Body:
Why not add a computed to your model:

self.link = ko.computed(function () {
    return '#link-to-' + self.taskName().replace(/\s+/g,'-');
}, self);

Then:

<a class="this-class" data-bind="text: taskName, attr: { href: link }"></a>


问:
String manipulation in C#. Inserting "+" between words
This is as far as I have got. My thinking was to stuff the string into an array, format it and recast it into a string.

```<code>    //input search term
    Console.WriteLine("What is your search query?:");
    string searchTerm = Console.ReadLine();

    //stuff the search term into an array to split it out
    string separator = " "; //assumes search terms are separated by spaces
    string[] searchTermArray = searchTerm.Split(separator.ToCharArray());

    //construct the search term
    string searchTermFormat = "";

    for (int i = 0; i < searchTermArray.Length; i++)
    {
        searchTermFormat += searchTermArray[i] + "+";
        //Console.WriteLine(searchTermFormat);
    }
</code>```

Desired output

```<code>word1+word2+word3
</code>```

where the number of words are not fixed.

答: What about myString.Replace(' ', '+');</p>

Body:
This is as far as I have got. My thinking was to stuff the string into an array, format it and recast it into a string.

    //input search term
    Console.WriteLine("What is your search query?:");
    string searchTerm = Console.ReadLine();

    //stuff the search term into an array to split it out
    string separator = " "; //assumes search terms are separated by spaces
    string[] searchTermArray = searchTerm.Split(separator.ToCharArray());

    //construct the search term
    string searchTermFormat = "";

    for (int i = 0; i < searchTermArray.Length; i++)
    {
        searchTermFormat += searchTermArray[i] + "+";
        //Console.WriteLine(searchTermFormat);
    }

Desired output

word1+word2+word3

where the number of words are not fixed.

Body: What about myString.Replace(' ', '+');


问:
Force "git push" to overwrite remote files
I want to push my local files, and have them on a remote repo, without having to deal with merge conflicts. I just want my local version to have priority over the remote one.

How can I do this with Git?

答:
git push -f is a bit destructive because it resets any remote changes that had been made by anyone else on the team. A safer option is

```<code>git push --force-with-lease
</code>```

What --force-with-lease does is refuse to update a branch unless it is the state that we expect; i.e. nobody has updated the branch upstream. In practice this works by checking that the upstream ref is what we expect, because refs are hashes, and implicitly encode the chain of parents into their value.

You can tell --force-with-lease exactly what to check for, but by default will check the current remote ref. What this means in practice is that when Alice updates her branch and pushes it up to the remote repository, the ref pointing head of the branch will be updated. Now, unless Bob does a pull from the remote, his local reference to the remote will be out of date. When he goes to push using --force-with-lease, git will check the local ref against the new remote and refuse to force the push. --force-with-lease effectively only allows you to force-push if no-one else has pushed changes up to the remote in the interim. It's --force with the seatbelt on.

Body:
git push -f is a bit destructive because it resets any remote changes that had been made by anyone else on the team. A safer option is

git push --force-with-lease

What --force-with-lease does is refuse to update a branch unless it is the state that we expect; i.e. nobody has updated the branch upstream. In practice this works by checking that the upstream ref is what we expect, because refs are hashes, and implicitly encode the chain of parents into their value.

You can tell --force-with-lease exactly what to check for, but by default will check the current remote ref. What this means in practice is that when Alice updates her branch and pushes it up to the remote repository, the ref pointing head of the branch will be updated. Now, unless Bob does a pull from the remote, his local reference to the remote will be out of date. When he goes to push using --force-with-lease, git will check the local ref against the new remote and refuse to force the push. --force-with-lease effectively only allows you to force-push if no-one else has pushed changes up to the remote in the interim. It's --force with the seatbelt on.

ContentLicense: CC BY-SA 4.0


问:
Strange matching nodes in Neo4j
I'm having a lot of problem trying to do something that should be very easy.
I have these 3 csv:
First one, Cast CSV ~ 150k records

```<code>idActor,idMovie,nameActor,character
"10990","321612","Belle","Emma Watson"
"221018","321612","Beast","Dan Stevens"
"114019","321612","Gaston","Luke Evans"
"8945","321612","Maurice","Kevin Kline"
</code>```

Second one, Actor CSV ~ 8k records.

```<code>idActor,deathday,gender,birthday,name,place_of_birth,popularity
"10990","null","1","1990-04-15","Emma Watson","Paris; France","54.327581"
"114019","null","2","1979-04-15","Luke Evans","Pontypool; Wales; UK","13.145154"
"54415","null","2","1981-02-23","Josh Gad","Hollywood; Florida; USA","11.418704"
"2283","null","2","1960-11-11","Stanley Tucci","Peekskill; New York; USA","11.013948"
"221018","null","2","1982-10-10","Dan Stevens","Croydon; Surrey; England; UK","27.461241"
"3061","null","2","1971-03-31","Ewan McGregor","Perth; Scotland; UK","18.398385"
</code>```

And the last one, Movie CSV ~ 10k records.

(Header - 1 line)

    idMovie,overview,popularity,companies,
    countries,release_date,revenue,runtime,tagline,vote_average,
    vote_count,budget,genre,title

```<code>"99861","When Tony Stark tries to jumpstart a dormant peacekeeping program, things go awry and Earth’s Mightiest Heroes are put to the ultimate test as the fate of the planet hangs in the balance. As the villainous Ultron emerges, it is up to The Avengers to stop him from enacting his terrible plans, and soon uneasy alliances and unexpected action pave the way for an epic and unique global adventure.","10.836173","Marvel Studios;Prime Focus;Revolution Sun Studios","US","2015-04-22","1405035767","141","A New Age Has Come.","7.3","5868","280000000","Action;Adventure;Science Fiction","Avengers: Age of Ultron"
</code>```

After doing import in Neo4j, converting the necessary field into Integer or Float, I want to do some relationship.

For example,

```<code>MATCH (m:Movie), (c:CastMember), (a:Actor)
WHERE m.idMovie = c.idMovie AND a.idActor = c.idActor
CREATE (a)-[:HAS_ACTED_IN{character:c.character}]->(m)
</code>```

But it create just ~50 relationships, instead of more than 100k.

So, I made other attemps, in particular:

```<code>MATCH (m:Movie), (c:CastMember)
WHERE m.idMovie = c.idMovie
RETURN DISTINCT m.title
</code>```

returns just ~20 matches.

Again,

```<code>MATCH (c:CastMember), (a:Actor)
WHERE c.idActor = a.idActor
RETURN a.name
</code>```

returns just ~5 matches.

The matches change every time I import the CSV. That's very strange.

答:
So, you should have :

```<code>CREATE CONSTRAINT ON (a:Actor) ASSERT a.idActor IS UNIQUE;
CREATE CONSTRAINT ON (m:Movie) ASSERT m.idMovie IS UNIQUE;
</code>```

and then loaded actors and movies with LOAD CSV ... did you count afterwards ... and those numbers are checking out ?

And then you can create the relationship directory in the LOAD CSV of the cast :

```<code>LOAD CSV ... AS line
MATCH (m:Movie {idMovie : line.idMovie})
MATCH (a:Actor {idActor : line.idActor})
MERGE (a)-[:HAS_ACTED_IN {character: line.character}]->(m);
</code>```

I note the following things as well :

The headers on the cast csv are not in the correct order

The WHERE m.id = c.idMovie AND a.idActor = c.idActor can not work as
it should be m.idMovie

but those might be typos.

Hope this helps,
Tom

Title: Strange matching nodes in Neo4j

Body:
I'm having a lot of problem trying to do something that should be very easy.
I have these 3 csv:
First one, Cast CSV ~ 150k records

idActor,idMovie,nameActor,character
"10990","321612","Belle","Emma Watson"
"221018","321612","Beast","Dan Stevens"
"114019","321612","Gaston","Luke Evans"
"8945","321612","Maurice","Kevin Kline"

Second one, Actor CSV ~ 8k records.

idActor,deathday,gender,birthday,name,place_of_birth,popularity
"10990","null","1","1990-04-15","Emma Watson","Paris; France","54.327581"
"114019","null","2","1979-04-15","Luke Evans","Pontypool; Wales; UK","13.145154"
"54415","null","2","1981-02-23","Josh Gad","Hollywood; Florida; USA","11.418704"
"2283","null","2","1960-11-11","Stanley Tucci","Peekskill; New York; USA","11.013948"
"221018","null","2","1982-10-10","Dan Stevens","Croydon; Surrey; England; UK","27.461241"
"3061","null","2","1971-03-31","Ewan McGregor","Perth; Scotland; UK","18.398385"

And the last one, Movie CSV ~ 10k records.

(Header - 1 line)

    idMovie,overview,popularity,companies,
    countries,release_date,revenue,runtime,tagline,vote_average,
    vote_count,budget,genre,title

"99861","When Tony Stark tries to jumpstart a dormant peacekeeping program, things go awry and Earth’s Mightiest Heroes are put to the ultimate test as the fate of the planet hangs in the balance. As the villainous Ultron emerges, it is up to The Avengers to stop him from enacting his terrible plans, and soon uneasy alliances and unexpected action pave the way for an epic and unique global adventure.","10.836173","Marvel Studios;Prime Focus;Revolution Sun Studios","US","2015-04-22","1405035767","141","A New Age Has Come.","7.3","5868","280000000","Action;Adventure;Science Fiction","Avengers: Age of Ultron"

After doing import in Neo4j, converting the necessary field into Integer or Float, I want to do some relationship.

For example,

MATCH (m:Movie), (c:CastMember), (a:Actor)
WHERE m.idMovie = c.idMovie AND a.idActor = c.idActor
CREATE (a)-[:HAS_ACTED_IN{character:c.character}]->(m)

But it create just ~50 relationships, instead of more than 100k.

So, I made other attemps, in particular:

MATCH (m:Movie), (c:CastMember)
WHERE m.idMovie = c.idMovie
RETURN DISTINCT m.title

returns just ~20 matches.

Again,

MATCH (c:CastMember), (a:Actor)
WHERE c.idActor = a.idActor
RETURN a.name

returns just ~5 matches.

The matches change every time I import the CSV. That's very strange.

Body:
So, you should have :

CREATE CONSTRAINT ON (a:Actor) ASSERT a.idActor IS UNIQUE;
CREATE CONSTRAINT ON (m:Movie) ASSERT m.idMovie IS UNIQUE;

and then loaded actors and movies with LOAD CSV ... did you count afterwards ... and those numbers are checking out ?

And then you can create the relationship directory in the LOAD CSV of the cast :

LOAD CSV ... AS line
MATCH (m:Movie {idMovie : line.idMovie})
MATCH (a:Actor {idActor : line.idActor})
MERGE (a)-[:HAS_ACTED_IN {character: line.character}]->(m);

I note the following things as well :

The headers on the cast csv are not in the correct order

The WHERE m.id = c.idMovie AND a.idActor = c.idActor can not work as
it should be m.idMovie

but those might be typos.

Hope this helps,
Tom


问:
Adding two UMats with Modulo in EmguCV 3.2
So far I've worked with EmguCV 2.4 and calculated everything on the CPU.
Now I'm trying to port everything to EmguCV 3.2, working with OpenCL using the UMat class.

And I'm not quite sure how to implement adding two UMats with modulo.
In EmguCV 2.4 I did it by looping through the Matrizes

```<code>for (int row = 0; row < SrcMatrix1.Rows; row++)
{
    for (int col = 0; col < SrcMatrix1.Cols; col++)
    {
        SrcMatrix1[row, col] = (SrcMatrix1[row, col] + SrcMatrix2[row, col]) % MaxValue;
    }
}
</code>```

How would I do that in EmguCV 3.2?
Adressing each element in a UMat works differently and I haven't quite figured out yet how it works. I'd prefer to keep the calculation on the GPU, if possible without converting it to byte[] or Matrix<> because these operations are done on the CPU.
Some example code would be very helpful.

答:
As far as I have been able to determine, there is no way to accomplish this without converting to a Mat.

You might try interworking with managedCUDA, the C# wrapper around CUDA.

You could also do this in two steps, using CudaInvoke.Add() to add the matrices then do a threshold.

Doug

Body:
So far I've worked with EmguCV 2.4 and calculated everything on the CPU.
Now I'm trying to port everything to EmguCV 3.2, working with OpenCL using the UMat class.

And I'm not quite sure how to implement adding two UMats with modulo.
In EmguCV 2.4 I did it by looping through the Matrizes

for (int row = 0; row < SrcMatrix1.Rows; row++)
{
    for (int col = 0; col < SrcMatrix1.Cols; col++)
    {
        SrcMatrix1[row, col] = (SrcMatrix1[row, col] + SrcMatrix2[row, col]) % MaxValue;
    }
}

How would I do that in EmguCV 3.2?
Adressing each element in a UMat works differently and I haven't quite figured out yet how it works. I'd prefer to keep the calculation on the GPU, if possible without converting it to byte[] or Matrix<> because these operations are done on the CPU.
Some example code would be very helpful.


问:
why does Enumerable.Except returns DISTINCT items?
Having just spent over an hour debugging a bug in our code which in the end turned out to be something about the Enumerable.Except method which we didn't know about:

```<code>var ilist = new[] { 1, 1, 1, 1 };
var ilist2 = Enumerable.Empty<int>();
ilist.Except(ilist2); // returns { 1 } as opposed to { 1, 1, 1, 1 }
</code>```

or more generally:

```<code>var ilist3 = new[] { 1 };
var ilist4 = new[] { 1, 1, 2, 2, 3 };
ilist4.Except(ilist3); // returns { 2, 3 } as opposed to { 2, 2, 3 }
</code>```

Looking at the MSDN page:

This method returns those elements in
  first that do not appear in second. It
  does not also return those elements in
  second that do not appear in first.

I get it that in cases like this:

```<code>var ilist = new[] { 1, 1, 1, 1 };
var ilist2 = new[] { 1 };
ilist.Except(ilist2); // returns an empty array
</code>```

you get the empty array because every element in the first array 'appears' in the second and therefore should be removed.

But why do we only get distinct instances of all other items that do not appear in the second array? What's the rationale behind this behaviour?

答:
I certainly cannot say for sure why they decided to do it that way. However, I'll give it a shot.

MSDN describes Except as this:

Produces the set difference of two
  sequences by using the default
  equality comparer to compare values.

A Set is described as this:

A set is a collection of distinct
  objects, considered as an object in
  its own right

Body:
Having just spent over an hour debugging a bug in our code which in the end turned out to be something about the Enumerable.Except method which we didn't know about:

var ilist = new[] { 1, 1, 1, 1 };
var ilist2 = Enumerable.Empty<int>();
ilist.Except(ilist2); // returns { 1 } as opposed to { 1, 1, 1, 1 }

or more generally:

var ilist3 = new[] { 1 };
var ilist4 = new[] { 1, 1, 2, 2, 3 };
ilist4.Except(ilist3); // returns { 2, 3 } as opposed to { 2, 2, 3 }

Looking at the MSDN page:

This method returns those elements in
  first that do not appear in second. It
  does not also return those elements in
  second that do not appear in first.

I get it that in cases like this:

var ilist = new[] { 1, 1, 1, 1 };
var ilist2 = new[] { 1 };
ilist.Except(ilist2); // returns an empty array

you get the empty array because every element in the first array 'appears' in the second and therefore should be removed.

But why do we only get distinct instances of all other items that do not appear in the second array? What's the rationale behind this behaviour?


问:
iOS Facebook SDK MessageDialog error 202
I am trying to set up Facebook sharing with FBSDK in my iOS app.

I have been reading the documentation here, and currently have

```<code>[FBSDKShareDialog showFromViewController:self withContent:content delegate:self];
</code>```

working with a content object - FBSDKShareLinkContent.

However, upon trying to use the similar method as specified for Facebook Messenger sharing,

```<code>[FBSDKMessageDialog showWithContent:content delegate:self];
</code>```

i am getting a crash. I caught the error and logged it in one of the delegate methods, and it states "The operation couldn’t be completed. (com.facebook.sdk.share error 202.)
"

I have searched for this specific error but have not found anything directly with the same error. Here is full code

```<code>FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
content.contentURL = [NSURL URLWithString:kAPPShareLink];
content.contentDescription = kAPPShareDescription;
content.contentTitle = kAPPShareTitle;

if (buttonIndex == 0) {
    // Facebook

    [FBSDKShareDialog showFromViewController:self withContent:content delegate:self];
} else if (buttonIndex == 1) {
    // Facebook Messenger

    [FBSDKMessageDialog showWithContent:content delegate:self];
}
</code>```

Forgive me if i am missing something obvious, but as this documentation reads, i assume the FBSDKMessageDialog showWithContent: method would work the same way as FBSDKShareDialog showFromViewController: which is working for me.

I am using the latest version of XCode with iOS8.

答:
This bubbled up again in an interweb search. Nowadays, there is a simple answer for the error Message dialog is not available with code 202:

Facebook's documentation:

Note: Currently the message dialog is not supported on iPads.

Body:
I am trying to set up Facebook sharing with FBSDK in my iOS app.

I have been reading the documentation here, and currently have

[FBSDKShareDialog showFromViewController:self withContent:content delegate:self];

working with a content object - FBSDKShareLinkContent.

However, upon trying to use the similar method as specified for Facebook Messenger sharing,

[FBSDKMessageDialog showWithContent:content delegate:self];

i am getting a crash. I caught the error and logged it in one of the delegate methods, and it states "The operation couldn’t be completed. (com.facebook.sdk.share error 202.)
"

I have searched for this specific error but have not found anything directly with the same error. Here is full code

FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
content.contentURL = [NSURL URLWithString:kAPPShareLink];
content.contentDescription = kAPPShareDescription;
content.contentTitle = kAPPShareTitle;

if (buttonIndex == 0) {
    // Facebook

    [FBSDKShareDialog showFromViewController:self withContent:content delegate:self];
} else if (buttonIndex == 1) {
    // Facebook Messenger

    [FBSDKMessageDialog showWithContent:content delegate:self];
}

Forgive me if i am missing something obvious, but as this documentation reads, i assume the FBSDKMessageDialog showWithContent: method would work the same way as FBSDKShareDialog showFromViewController: which is working for me.

I am using the latest version of XCode with iOS8.


问:
Change class property when set
I have the following class:

```<code>class Message {
    var content: [String]?

    init(content: [String]) {
        self.content = content
    }
}
</code>```

I want content to be an array of Strings, that are always uppercase. Even when lowercase text is set to content.
I don't seem to be able to use computed properties for this

答:
You can have an internal variable storing the actual content and a computed property visible to the outside. If the public property is set, it computes the internal (uppercased) representation.

```<code>class Message {
    private var _content: [String]?
    var content: [String]? {
        get {
            return _content
        }
        set (new) {
            if let new = new {
                _content = new.map { $0.uppercased() }
            } else {
                _content = nil
            }
        }
    }

    init(content: [String]?) {
        self.content = content
    }
}
</code>```

You can even assign content in the initializer and it will compute the upper case representation.

Title: Change class property when set

Body:
I have the following class:

class Message {
    var content: [String]?

    init(content: [String]) {
        self.content = content
    }
}

I want content to be an array of Strings, that are always uppercase. Even when lowercase text is set to content.
I don't seem to be able to use computed properties for this

Body:
You can have an internal variable storing the actual content and a computed property visible to the outside. If the public property is set, it computes the internal (uppercased) representation.

class Message {
    private var _content: [String]?
    var content: [String]? {
        get {
            return _content
        }
        set (new) {
            if let new = new {
                _content = new.map { $0.uppercased() }
            } else {
                _content = nil
            }
        }
    }

    init(content: [String]?) {
        self.content = content
    }
}

You can even assign content in the initializer and it will compute the upper case representation.


问:
Java method NotifyAll() isn't working?
I'm a little stumped. Below is pretty much a copy and paste from A simple scenario using wait() and notify() in java.

To my understanding, this Java program below should be printing yumyum.. to the screen but it isn't. I am in Eclipse for Mac OS X. Any ideas what I'm doing wrong ?

```<code>public class Main {
    public static void main(String[] args) {
        MyHouse house = new MyHouse();
        house.eatPizza();
        house.pizzaGuy();

    }
}

class MyHouse extends Thread {

    private boolean pizzaArrived = false;

    public void eatPizza() {
        synchronized (this) {
            while (!pizzaArrived) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        System.out.println("yumyum..");
    }

    public void pizzaGuy() {
        synchronized (this) {
            this.pizzaArrived = true;
            notifyAll();
        }
    }
}
</code>```

答:
Try below code working fine.

public class WaitNotify {

```<code>private static int i = 1;
private static boolean flag = false;
static Object obj = new Object();

public static void main(String[] args) {

    Thread t1 = new Thread(new Runnable(){

        @Override
        public void run() {
                while(i<10){
                    synchronized (obj) {
                        try {
                            if(i%2 == 0){
                                obj.wait();
                            }
                            System.out.println("t1 -> " + i++);
                            obj.notify();

                            Thread.currentThread().sleep(500);

                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
        }
    });

    Thread t2 = new Thread(new Runnable(){

        @Override
        public void run() {
            while(i<10){
                synchronized (obj) {
                    try {
                        if(i%2 != 0){
                            obj.wait();
                        }
                        System.out.println("t2 -> " + i++);
                        obj.notify();
                        Thread.currentThread().sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    });

    t1.start();
    t2.start();

    try {
        t1.join();
        t2.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
</code>```

}

Title: Java method NotifyAll() isn't working?

Body:
I'm a little stumped. Below is pretty much a copy and paste from A simple scenario using wait() and notify() in java.

To my understanding, this Java program below should be printing yumyum.. to the screen but it isn't. I am in Eclipse for Mac OS X. Any ideas what I'm doing wrong ?

public class Main {
    public static void main(String[] args) {
        MyHouse house = new MyHouse();
        house.eatPizza();
        house.pizzaGuy();

    }
}

class MyHouse extends Thread {

    private boolean pizzaArrived = false;

    public void eatPizza() {
        synchronized (this) {
            while (!pizzaArrived) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        System.out.println("yumyum..");
    }

    public void pizzaGuy() {
        synchronized (this) {
            this.pizzaArrived = true;
            notifyAll();
        }
    }
}

Body:
Try below code working fine.

public class WaitNotify {

private static int i = 1;
private static boolean flag = false;
static Object obj = new Object();

public static void main(String[] args) {

    Thread t1 = new Thread(new Runnable(){

        @Override
        public void run() {
                while(i<10){
                    synchronized (obj) {
                        try {
                            if(i%2 == 0){
                                obj.wait();
                            }
                            System.out.println("t1 -> " + i++);
                            obj.notify();

                            Thread.currentThread().sleep(500);

                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
        }
    });

    Thread t2 = new Thread(new Runnable(){

        @Override
        public void run() {
            while(i<10){
                synchronized (obj) {
                    try {
                        if(i%2 != 0){
                            obj.wait();
                        }
                        System.out.println("t2 -> " + i++);
                        obj.notify();
                        Thread.currentThread().sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    });

    t1.start();
    t2.start();

    try {
        t1.join();
        t2.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}


问:
how to make bot to enter a website automatically?
for example I have 10 username and password in a text file,
I want a software or bot that go to a website, enter the website and hit a button and then go to other username.</p>

答:
For example you could use wget. Most Linux distro's do have this tool.
Try:

```<code>wget --user username --password secret http://example.com/
</code>```

Body:
For example you could use wget. Most Linux distro's do have this tool.
Try:

wget --user username --password secret http://example.com/


问:
Compare two integers doesn't work correctly in Android
I have a method that have to compare an integer with an Arraylist and if the number on the integer is on the arraylist, I recieve a false. If the integer number is not on the arraylist I recieve a true.

I need this, because I'm making a quiz game that have some questions on a BBDD and I can't show the same question twice. Also this questions are in three categories: E, I and A. I have to show five E questions, then five I questions and then five A questions.

So I have to show questions without repeat them, and also 5 of each category. I make this methods but I don't know why it repeats some questions.

The only thing works correctly is the category questions. I have always 5 E questions, then 5 I questions and at least 5 A questions.

The method that told me if the questions is on the ArrayList:

```<code>private boolean checkRandom()
{
    for(int i = 0; i < listRandom.size(); i++)
    {
        if(questionPosition == listRandom.get(i))
        {
            return false;
        }
    }

    return true;
}
</code>```

I also try with "equals", but I have the same result.

The method that check if the question is in the correct category and is not showed before:

```<code>private void loadPhase() {

    if (numQuestion < 15)
    {
        r = new Random();
        questionPosition = r.nextInt(listQuestions.size());

        if(numQuestion < 5)
        {
            while(!listPhase.get(questionPosition).equals("E") && (!listPhase.get(questionPosition).equals("E")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 4 && numQuestion < 10)
        {
            while(!listPhase.get(questionPosition).equals("I") && (!listPhase.get(questionPosition).equals("I")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 9)
        {
            while(!listPhase.get(questionPosition).equals("A") && (!listPhase.get(questionPosition).equals("A")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }

        listRandom.add(questionPosition);

        header4questions.setText(listQuestions.get(questionPosition));

        answer1.setText(listAnswers.get(questionPosition * 4));
        answer2.setText(listAnswers.get((questionPosition * 4) + 1));
        answer3.setText(listAnswers.get((questionPosition * 4) + 2));
        answer4.setText(listAnswers.get((questionPosition * 4) + 3));

        numQuestion++;
    }
    else {
        Toast.makeText(getApplicationContext(), "You have finished the quiz!", Toast.LENGTH_SHORT).show();

        uploadPoints();
    }
}
</code>```

So, what I have is all the questions on the correct category, but it repeat the questions and I don't know why.

Can anyone help me?

Thanks!

答:
Replace your return as below</p>

```<code>private boolean checkRandom()
{
    for(int i = 0; i < listRandom.size(); i++)
    {
        if(questionPosition == listRandom.get(i))
        {
            return true;
        }
    }

    return false;
}
</code>```

Body:
I have a method that have to compare an integer with an Arraylist and if the number on the integer is on the arraylist, I recieve a false. If the integer number is not on the arraylist I recieve a true.

I need this, because I'm making a quiz game that have some questions on a BBDD and I can't show the same question twice. Also this questions are in three categories: E, I and A. I have to show five E questions, then five I questions and then five A questions.

So I have to show questions without repeat them, and also 5 of each category. I make this methods but I don't know why it repeats some questions.

The only thing works correctly is the category questions. I have always 5 E questions, then 5 I questions and at least 5 A questions.

The method that told me if the questions is on the ArrayList:

private boolean checkRandom()
{
    for(int i = 0; i < listRandom.size(); i++)
    {
        if(questionPosition == listRandom.get(i))
        {
            return false;
        }
    }

    return true;
}

I also try with "equals", but I have the same result.

The method that check if the question is in the correct category and is not showed before:

private void loadPhase() {

    if (numQuestion < 15)
    {
        r = new Random();
        questionPosition = r.nextInt(listQuestions.size());

        if(numQuestion < 5)
        {
            while(!listPhase.get(questionPosition).equals("E") && (!listPhase.get(questionPosition).equals("E")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 4 && numQuestion < 10)
        {
            while(!listPhase.get(questionPosition).equals("I") && (!listPhase.get(questionPosition).equals("I")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 9)
        {
            while(!listPhase.get(questionPosition).equals("A") && (!listPhase.get(questionPosition).equals("A")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }

        listRandom.add(questionPosition);

        header4questions.setText(listQuestions.get(questionPosition));

        answer1.setText(listAnswers.get(questionPosition * 4));
        answer2.setText(listAnswers.get((questionPosition * 4) + 1));
        answer3.setText(listAnswers.get((questionPosition * 4) + 2));
        answer4.setText(listAnswers.get((questionPosition * 4) + 3));

        numQuestion++;
    }
    else {
        Toast.makeText(getApplicationContext(), "You have finished the quiz!", Toast.LENGTH_SHORT).show();

        uploadPoints();
    }
}

So, what I have is all the questions on the correct category, but it repeat the questions and I don't know why.

Can anyone help me?

Thanks!

Body:
Replace your return as below

private boolean checkRandom()
{
    for(int i = 0; i < listRandom.size(); i++)
    {
        if(questionPosition == listRandom.get(i))
        {
            return true;
        }
    }

    return false;
}


问:
What causes this Android APK Upload error: "Non-upgradable APK"
I have an Android APK in the Google Play store with an Target SDK of 23.

I have released a new version (same target SDK) and Google shows me this error:

If I proceed (I learnt the hard way) then none of the current users can upgrade to this version. I had to restore the code, increment the build number and rebuild the APK to "rollback" to a usable version.

However, I cannot work out WHY google is showing me this error. Note, the "0 Supported Android Devices" is a red-herring - it is a known issue in Google Play in the last 24 hours - if you publish the APK the real number of devices is shown.

Please give me some leads on what the difference is or what causes this error:

Non-upgradable APK
WARNING
None of the users of this APK will be able to upgrade to any of the new APKs added in this release.
TIP
Ensure that all your new APKs are added to this release.

答:
I'm using VS-TACO and ran into this problem.

To slightly clarify Sanny's answer which fixed the issue for me.  Apparently, somewhere along the way the android-versionCode was calculated using this formula:

```<code>MAJOR * 100000 + MINOR * 1000 + PATCH * 10
</code>```

but now it is getting calculated using  the version Sanny shows:

```<code>MAJOR * 10000 + MINOR * 100 + PATCH
</code>```

So for example if your version was 1.3.1 android-versionCode was calculated as "103010"

now you change the version to 1.3.2 and it is calculated the new way so the version is "10302" which is less than "103010".

So to work around this issue (I guess forever if the android version keeps getting calculated the new way) you can add the version tag to your config.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<widget android-versionCode="103020" ...
</code>```

or you can go into Visual Studio and use the visual editor for config.xml, go to the "Android" section and change the "Version Code:" value.

Body:
I'm using VS-TACO and ran into this problem.

To slightly clarify Sanny's answer which fixed the issue for me.  Apparently, somewhere along the way the android-versionCode was calculated using this formula:

MAJOR * 100000 + MINOR * 1000 + PATCH * 10

but now it is getting calculated using  the version Sanny shows:

MAJOR * 10000 + MINOR * 100 + PATCH

So for example if your version was 1.3.1 android-versionCode was calculated as "103010"

now you change the version to 1.3.2 and it is calculated the new way so the version is "10302" which is less than "103010".

So to work around this issue (I guess forever if the android version keeps getting calculated the new way) you can add the version tag to your config.xml:

<?xml version="1.0" encoding="utf-8"?>
<widget android-versionCode="103020" ...

or you can go into Visual Studio and use the visual editor for config.xml, go to the "Android" section and change the "Version Code:" value.


问:
How to read successfully from a 2D texture
How can I:

Bind cudaMallocPitch float memory to a 2D texture reference

Copy some host data to the 2D array on the device

Add one to the texture reference and write to either a.) the Pitch 2D array OR b.) write to a linear memory array

Read the answer back and display it.

Below is a code that should accomplish this. Note that for NxN array sizes, my code works. For NxM where N!=M, my code bites the dust (not the correct result). If you can solve this problem I will award you 1 internets (supply limited). Maybe I'm crazy, but according to the documentation this should work (and it does work for square arrays!). The attached code should run with 'nvcc whateveryoucallit.cu -o runit'.

Help is appreciated!

```<code>#include<stdio.h>
#include<cuda.h>
#include<iostream>
#define height 16
#define width 11
#define BLOCKSIZE 16

using namespace std;

// Device Kernels

//Texture reference Declaration
texture<float,2> texRefEx;

__global__ void kernel_w_textures(float* devMPPtr, float * devMPtr, int pitch)
{
 // Thread indexes
        unsigned int idx = blockIdx.x*blockDim.x + threadIdx.x;
        unsigned int idy = blockIdx.y*blockDim.y + threadIdx.y;

 // Texutre Coordinates
 float u=(idx)/float(width);
 float v=(idy)/float(height);
 devMPtr[idy*width+idx]=devMPPtr[idy*pitch/sizeof(float)+idx];
 // Write Texture Contents to malloc array +1
 devMPtr[idy*width+idx]= tex2D(texRefEx,u,v);//+1.0f;
}
int main()
{
 // memory size
 size_t memsize=height*width;
 size_t offset;
 float * data,  // input from host
  *h_out,  // host space for output
  *devMPPtr, // malloc Pitch ptr
  *devMPtr; // malloc ptr

 size_t pitch;

 // Allocate space on the host
 data=(float *)malloc(sizeof(float)*memsize);
 h_out=(float *)malloc(sizeof(float)*memsize);

// Define data
for (int i = 0; i <  height; i++)
 for (int j=0; j < width; j++)
  data[i*width+j]=float(j);

// Define the grid
dim3 grid((int)(width/BLOCKSIZE)+1,(int)(height/BLOCKSIZE)+1), threads(BLOCKSIZE,BLOCKSIZE);

// allocate Malloc Pitch
cudaMallocPitch((void**)&devMPPtr,&pitch, width * sizeof(float), height);

// Print the pitch
printf("The pitch is %d \n",pitch/sizeof(float));

// Texture Channel Description
//cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float>();
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc(32,0,0,0,cudaChannelFormatKindFloat);

// Bind texture to pitch mem:
cudaBindTexture2D(&offset,&texRefEx,devMPPtr,&channelDesc,width,height,pitch);
cout << "My Description x is " << channelDesc.x << endl;
cout << "My Description y is " << channelDesc.y << endl;
cout << "My Description z is " << channelDesc.z << endl;
cout << "My Description w is " << channelDesc.w << endl;
cout << "My Description kind is " << channelDesc.f << endl;
cout << "Offset is " << offset << endl;

// Set mutable properties:
texRefEx.normalized=true;
texRefEx.addressMode[0]=cudaAddressModeWrap;
texRefEx.addressMode[1]=cudaAddressModeWrap;
texRefEx.filterMode= cudaFilterModePoint;

// Allocate cudaMalloc memory
cudaMalloc((void**)&devMPtr,memsize*sizeof(float));

// Read data from host to device
cudaMemcpy2D((void*)devMPPtr,pitch,(void*)data,sizeof(float)*width,
  sizeof(float)*width,height,cudaMemcpyHostToDevice);

//Read back and check this memory
cudaMemcpy2D((void*)h_out,width*sizeof(float),(void*)devMPPtr,pitch,
  sizeof(float)*width,height,cudaMemcpyDeviceToHost);

// Print the memory
 for (int i=0; i<height; i++){
  for (int j=0; j<width; j++){
   printf("%2.2f ",h_out[i*width+j]);
  }
 cout << endl;
 }

 cout << "Done" << endl;
// Memory is fine...

kernel_w_textures<<<grid,threads>>>(devMPPtr, devMPtr, pitch);

// Copy back data to host
cudaMemcpy((void*)h_out,(void*)devMPtr,width*height*sizeof(float),cudaMemcpyDeviceToHost);

// Print the Result
 cout << endl;
 for (int i=0; i<height; i++){
  for (int j=0; j<width; j++){
   printf("%2.2f ",h_out[i*width+j]);
  }
 cout << endl;
 }
 cout << "Done" << endl;

return(0);
}
</code>```

Edit October 17: So I still haven't found a solution to this issue. Nvidia is pretty silent on this seems that the world is too. I found a workaround using shared mem but if anyone has a texture solution I would be very please.

Edit Octoboer 26: Still no soltuion, but still interested in one if anyone knows.

Edit July 26: Wow it has been 9 months - and I had overlooked the correct answer the whole time. The trick was:

```<code>if ( idx < width  && idy < height){//.... code }
</code>```

As had been pointed out before. Thanks to all of those who contributed!

答:
Perhaps take a look at this thread: http://forums.nvidia.com/index.php?showtopic=186585

Another very helpful sample piece of code is currently in the NVIDIA SDK; as mentioned in the above thread on the NVIDIA forums, the simplePitchLinearTexture example works well.

Since we are using texture memory, I believe that the sizes of the 2D grid must be powers of 2 on some hardware, as also suggested in one of the answers above.

Body:
How can I:

Bind cudaMallocPitch float memory to a 2D texture reference

Copy some host data to the 2D array on the device

Add one to the texture reference and write to either a.) the Pitch 2D array OR b.) write to a linear memory array

Read the answer back and display it.

Below is a code that should accomplish this. Note that for NxN array sizes, my code works. For NxM where N!=M, my code bites the dust (not the correct result). If you can solve this problem I will award you 1 internets (supply limited). Maybe I'm crazy, but according to the documentation this should work (and it does work for square arrays!). The attached code should run with 'nvcc whateveryoucallit.cu -o runit'.

Help is appreciated!

#include<stdio.h>
#include<cuda.h>
#include<iostream>
#define height 16
#define width 11
#define BLOCKSIZE 16

using namespace std;

// Device Kernels

//Texture reference Declaration
texture<float,2> texRefEx;

__global__ void kernel_w_textures(float* devMPPtr, float * devMPtr, int pitch)
{
 // Thread indexes
        unsigned int idx = blockIdx.x*blockDim.x + threadIdx.x;
        unsigned int idy = blockIdx.y*blockDim.y + threadIdx.y;

 // Texutre Coordinates
 float u=(idx)/float(width);
 float v=(idy)/float(height);
 devMPtr[idy*width+idx]=devMPPtr[idy*pitch/sizeof(float)+idx];
 // Write Texture Contents to malloc array +1
 devMPtr[idy*width+idx]= tex2D(texRefEx,u,v);//+1.0f;
}
int main()
{
 // memory size
 size_t memsize=height*width;
 size_t offset;
 float * data,  // input from host
  *h_out,  // host space for output
  *devMPPtr, // malloc Pitch ptr
  *devMPtr; // malloc ptr

 size_t pitch;

 // Allocate space on the host
 data=(float *)malloc(sizeof(float)*memsize);
 h_out=(float *)malloc(sizeof(float)*memsize);

// Define data
for (int i = 0; i <  height; i++)
 for (int j=0; j < width; j++)
  data[i*width+j]=float(j);

// Define the grid
dim3 grid((int)(width/BLOCKSIZE)+1,(int)(height/BLOCKSIZE)+1), threads(BLOCKSIZE,BLOCKSIZE);

// allocate Malloc Pitch
cudaMallocPitch((void**)&devMPPtr,&pitch, width * sizeof(float), height);

// Print the pitch
printf("The pitch is %d \n",pitch/sizeof(float));

// Texture Channel Description
//cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float>();
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc(32,0,0,0,cudaChannelFormatKindFloat);

// Bind texture to pitch mem:
cudaBindTexture2D(&offset,&texRefEx,devMPPtr,&channelDesc,width,height,pitch);
cout << "My Description x is " << channelDesc.x << endl;
cout << "My Description y is " << channelDesc.y << endl;
cout << "My Description z is " << channelDesc.z << endl;
cout << "My Description w is " << channelDesc.w << endl;
cout << "My Description kind is " << channelDesc.f << endl;
cout << "Offset is " << offset << endl;

// Set mutable properties:
texRefEx.normalized=true;
texRefEx.addressMode[0]=cudaAddressModeWrap;
texRefEx.addressMode[1]=cudaAddressModeWrap;
texRefEx.filterMode= cudaFilterModePoint;

// Allocate cudaMalloc memory
cudaMalloc((void**)&devMPtr,memsize*sizeof(float));

// Read data from host to device
cudaMemcpy2D((void*)devMPPtr,pitch,(void*)data,sizeof(float)*width,
  sizeof(float)*width,height,cudaMemcpyHostToDevice);

//Read back and check this memory
cudaMemcpy2D((void*)h_out,width*sizeof(float),(void*)devMPPtr,pitch,
  sizeof(float)*width,height,cudaMemcpyDeviceToHost);

// Print the memory
 for (int i=0; i<height; i++){
  for (int j=0; j<width; j++){
   printf("%2.2f ",h_out[i*width+j]);
  }
 cout << endl;
 }

 cout << "Done" << endl;
// Memory is fine...

kernel_w_textures<<<grid,threads>>>(devMPPtr, devMPtr, pitch);

// Copy back data to host
cudaMemcpy((void*)h_out,(void*)devMPtr,width*height*sizeof(float),cudaMemcpyDeviceToHost);

// Print the Result
 cout << endl;
 for (int i=0; i<height; i++){
  for (int j=0; j<width; j++){
   printf("%2.2f ",h_out[i*width+j]);
  }
 cout << endl;
 }
 cout << "Done" << endl;

return(0);
}

Edit October 17: So I still haven't found a solution to this issue. Nvidia is pretty silent on this seems that the world is too. I found a workaround using shared mem but if anyone has a texture solution I would be very please.

Edit Octoboer 26: Still no soltuion, but still interested in one if anyone knows.

Edit July 26: Wow it has been 9 months - and I had overlooked the correct answer the whole time. The trick was:

if ( idx < width  && idy < height){//.... code }

As had been pointed out before. Thanks to all of those who contributed!


问:
how to adjust panel.borders in ggplot?
I have drawn a simple barplot:

```<code>mtcars$cnames = rownames(mtcars)
ggplot(mtcars[1:5,], aes(cnames, disp)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 0.5),
        panel.border = element_rect(colour = "black", fill=NA, size=5))
</code>```

and as you can see by running this example borders are going thrugh the axis.text.
How to make borders lower?

答:
Hope this is what are you looking for :   </p>

```<code>  mtcars$cnames = rownames(mtcars)
ggplot(mtcars[1:5,], aes(cnames, disp)) +
    geom_bar(stat = "identity") +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 45, hjust = 0.5),
          plot.background = element_rect(colour = "black", fill=NA, size=5))
</code>```

Title: how to adjust panel.borders in ggplot?

Body:
I have drawn a simple barplot:

mtcars$cnames = rownames(mtcars)
ggplot(mtcars[1:5,], aes(cnames, disp)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 0.5),
        panel.border = element_rect(colour = "black", fill=NA, size=5))

and as you can see by running this example borders are going thrugh the axis.text.
How to make borders lower?

Body:
Hope this is what are you looking for :

  mtcars$cnames = rownames(mtcars)
ggplot(mtcars[1:5,], aes(cnames, disp)) +
    geom_bar(stat = "identity") +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 45, hjust = 0.5),
          plot.background = element_rect(colour = "black", fill=NA, size=5))


问:
Is using __cplusplus undefined behaviour in C?
Modern C++ compilers are required by the standard to #define the macro __cplusplus.

This is often used in files that can be used by both C and C++ but the implementation differs slightly.

But in C (and C++ for that matter), the behaviour on using any double underscore in an identifier is undefined!

So therefore, if a C compiler sees something like

#ifdef __cplusplus

then is the behaviour undefined?

答:
Using such names for creating your own macros or identifiers invokes undefined behavior. C11 7.1.3 (emphasis mine):

7.1.3 Reserved identifiers

  1
  Each header declares or defines all identifiers listed in its associated subclause, and optionally
  declares or defines identifiers listed in its associated future
  library directions subclause and identifiers which are always reserved
  either for any use or for use as file scope identifiers.

  — All
  identifiers that begin with an underscore and either an uppercase
  letter or another underscore are always reserved for any use.

  ...

2 No other identifiers are reserved.
  If the program declares or defines an identifier in a context in which
  it is reserved (other than as allowed by 7.1.4), or defines a reserved
  identifier as a macro name, the behavior is undefined.

However, you are of course always free to use the macros/identifiers provided by the compiler/lib, given that they are made available in a scope you are supposed to have access to.


问:
Haskell Declare empty list, but which is actually not empty?
I'm new to Haskell and are playing around a bit. I created a recursive function with guards. See function below:

```<code>filterAge :: [Person] -> [String]
filterAge (x:xs)
 | (x:xs) == []                        = []
 | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
 | otherwise                           = [getName x] ++ filterAge xs
</code>```

I have a data set created with 10 Persons which I use in this method. When I tried this function it gave all the right people, but after that it got a Non-exhaustive patterns error:
["Lise","Jaap","Elle","Ebba"*** Exception: D:\...:(44,1)-(47,77): Non-exhaustive patterns in function filterAge

I found out that it never reaches the first guard. So I played around a bit and found out something really strange (in my opinion):

```<code>*Main> let (x:xs) = []
*Main> (x:xs) == []
False
</code>```

Now my main question is: Why does (x:xs) == [] return False?

If anyone has a better way for me of doing the function that'd be great, but it's not very important.

Thanks in advance!

EDIT

Thanks to Willem Van Onsem and Lambda.xy.x I got a quick answer to my question. This resulted in the following function which works perfectly:

```<code>filterAge :: [Person] -> [String]
filterAge []                           = []
filterAge (x:xs)
 | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
 | otherwise                           = [getName x] ++ filterAge xs
</code>```

But for the best version you'd have to check the answer of Willem Van Onsem.

答:
A list is defined as:

```<code>data [] a = [] | a : [a]
</code>```

So there are two constructors for a list: [] the empty list, and (x:xs) a constructor with one element, and a tail that can store an arbitrary number (zero or more) remaining elements.

Therefore (x:xs) is a list with at least one element: the x. The xs can be an empty list (since it has type [a]), but x has type a so that is the "head" of the list. Your let statement works with pattern matching, and since the empty list cannot match with (x:xs), it will always fail.

Another implication is that your first guard can never fire. In order to fix the issue, you should implement a separate case for the empty list. Like:

```<code>filterAge :: [Person] -> [String]
<b>filterAge []     = []</b> -- empty list case
filterAge (x:xs) -- first guard dropped
    | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
    | otherwise                           = [getName x] ++ filterAge xs</code>```

Note that we dropped the first guard in the second clause, since we know that will always fail, and thus checking this will (potentially) only cost CPU cycles.

There are still some parts we can optimize:

we call getAge twice, which is useless, we can use a where clause to optimize this;

[] ++ somelist is simply somelist: appending after an empty list results in that list; and

[element] ++ somelist is element : somelist, since now we work with the list constructor directly.

So our filterAge can be rewritten into:

```<code>filterAge :: [Person] -> [String]
filterAge []     = [] -- empty list case
filterAge (x:xs) | <b>age</b> < 30 || <b>age</b> > 40  = <b>filterAge xs</b>
                 | otherwise             = <b>getName x : filterAge xs</b>
    <b>where age = getAge x</b></code>```

Note that if you compile (or start the interpreter) with the -Wincomplete-patterns flag (warnings for incomplete patterns), Haskell will automatically warn you that your function definitions are not complete, and that there are input patterns for which you have not defined a clause.

Body:
I'm new to Haskell and are playing around a bit. I created a recursive function with guards. See function below:

filterAge :: [Person] -> [String]
filterAge (x:xs)
 | (x:xs) == []                        = []
 | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
 | otherwise                           = [getName x] ++ filterAge xs

I have a data set created with 10 Persons which I use in this method. When I tried this function it gave all the right people, but after that it got a Non-exhaustive patterns error:
["Lise","Jaap","Elle","Ebba"*** Exception: D:\...:(44,1)-(47,77): Non-exhaustive patterns in function filterAge

I found out that it never reaches the first guard. So I played around a bit and found out something really strange (in my opinion):

*Main> let (x:xs) = []
*Main> (x:xs) == []
False

Now my main question is: Why does (x:xs) == [] return False?

If anyone has a better way for me of doing the function that'd be great, but it's not very important.

Thanks in advance!

EDIT

Thanks to Willem Van Onsem and Lambda.xy.x I got a quick answer to my question. This resulted in the following function which works perfectly:

filterAge :: [Person] -> [String]
filterAge []                           = []
filterAge (x:xs)
 | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
 | otherwise                           = [getName x] ++ filterAge xs

But for the best version you'd have to check the answer of Willem Van Onsem.

Body:
A list is defined as:

data [] a = [] | a : [a]

So there are two constructors for a list: [] the empty list, and (x:xs) a constructor with one element, and a tail that can store an arbitrary number (zero or more) remaining elements.

Therefore (x:xs) is a list with at least one element: the x. The xs can be an empty list (since it has type [a]), but x has type a so that is the "head" of the list. Your let statement works with pattern matching, and since the empty list cannot match with (x:xs), it will always fail.

Another implication is that your first guard can never fire. In order to fix the issue, you should implement a separate case for the empty list. Like:

filterAge :: [Person] -> [String]
filterAge []     = [] -- empty list case
filterAge (x:xs) -- first guard dropped
    | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
    | otherwise                           = [getName x] ++ filterAge xs

Note that we dropped the first guard in the second clause, since we know that will always fail, and thus checking this will (potentially) only cost CPU cycles.

There are still some parts we can optimize:

we call getAge twice, which is useless, we can use a where clause to optimize this;

[] ++ somelist is simply somelist: appending after an empty list results in that list; and

[element] ++ somelist is element : somelist, since now we work with the list constructor directly.

So our filterAge can be rewritten into:

filterAge :: [Person] -> [String]
filterAge []     = [] -- empty list case
filterAge (x:xs) | age < 30 || age > 40  = filterAge xs
                 | otherwise             = getName x : filterAge xs
    where age = getAge x

Note that if you compile (or start the interpreter) with the -Wincomplete-patterns flag (warnings for incomplete patterns), Haskell will automatically warn you that your function definitions are not complete, and that there are input patterns for which you have not defined a clause.


问:
Google play store not showing update option for new apk
I have my app installed in my cell with version 1.0.3 ( Version code 1)  In Google Play Store, I can see my app with version 2.0.1 ( Version code 2 ), but it doesn't show me the button update ( it is showing me the button "Open")  Is it something I have to include in my app???  Is it a bug in Play Store???  Is it a configuration problem??? </p>

答:
If u install app using usb debugging mode then in playstore it will not show update when you update app in playstore.

If your previous version also downloaded from playstore then it will show update.


问:
When are canvas updates made in Microsoft Edge?
I have a JavaScript function which draws on a canvas in Microsoft Edge.  It looks a bit like this

```<code>function foo() {
    drawSomething(canvas);
    doACalculationThatTakesALongTime();
    drawSomethingElse(canvas);
    doACalculationThatTakesALongTime();
}
</code>```

foo is attached as an event handler to some event in my DOM.

The problem that I experience is that the updates to the canvas made by doACalculationThatTakesALongTime do not appear until foo completes.  Is this to be expected?  By contrast, in Firefox the updates appear immediately.

答:
A decoupling solution:

var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext("2d");

function drawSomething() {
  ctx.fillStyle = "rgba(255,0,0,0.5)";
  ctx.fillRect(0, 0, (canvas.width / 3) * 2, (canvas.height / 3) * 2);
}

function drawSomethingElse() {
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgba(0,0,255,0.5)";
  ctx.fillRect(canvas.width / 3, canvas.height / 3, (canvas.width / 3) * 2, (canvas.height / 3) * 2);
}

function doACalculationThatTakesALongTime() {
  var d = Date.now();
  while (Date.now() - d < 2 * 1000) {}
  console.log("Big calculation done");
}

function foo() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawSomething();
  setTimeout(doACalculationThatTakesALongTime, 1000);
  drawSomethingElse();
  setTimeout(doACalculationThatTakesALongTime, 1000);
}
setTimeout(foo, 1000);```
</div>
</div>
</p>

<p>Alternatively, if the order of execution is important you can chain these actions together with <code>Promises</code> while ensuring frame rendering using <code>requestAnimationFrame</code>:</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>var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext("2d");
var p = document.body.appendChild(document.createElement("p"));

function drawSomething() {
  ctx.fillStyle = "rgba(255,0,0,0.5)";
  ctx.fillRect(0, 0, (canvas.width / 3) * 2, (canvas.height / 3) * 2);
  p.innerHTML += "Drawed something<br>";
}

function drawSomethingElse() {
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgba(0,0,255,0.5)";
  ctx.fillRect(canvas.width / 3, canvas.height / 3, (canvas.width / 3) * 2, (canvas.height / 3) * 2);
  p.innerHTML += "Drawed something else<br>";
}

function doACalculationThatTakesALongTime() {
  var d = Date.now();
  while (Date.now() - d < 2 * 1000) {}
  p.innerHTML += "Big calculation done<br>";
}

function foo() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new Promise(function(resolve, reject) {
      requestAnimationFrame(function() {
        drawSomething();
        resolve();
      });
    })
    .then(function() {
      return new Promise(function(resolve, reject) {
        requestAnimationFrame(function() {
          doACalculationThatTakesALongTime();
          resolve();
        });
      });
    })
    .then(function() {
      return new Promise(function(resolve, reject) {
        requestAnimationFrame(function() {
          drawSomethingElse();
          resolve();
        });
      });
    })
    .then(function() {
      return new Promise(function(resolve, reject) {
        requestAnimationFrame(function() {
          doACalculationThatTakesALongTime();
          resolve();
        });
      });
    })
}
foo();</code>```

Body:
I have a JavaScript function which draws on a canvas in Microsoft Edge.  It looks a bit like this

function foo() {
    drawSomething(canvas);
    doACalculationThatTakesALongTime();
    drawSomethingElse(canvas);
    doACalculationThatTakesALongTime();
}

foo is attached as an event handler to some event in my DOM.

The problem that I experience is that the updates to the canvas made by doACalculationThatTakesALongTime do not appear until foo completes.  Is this to be expected?  By contrast, in Firefox the updates appear immediately.

Body:
A decoupling solution:

var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext("2d");

function drawSomething() {
  ctx.fillStyle = "rgba(255,0,0,0.5)";
  ctx.fillRect(0, 0, (canvas.width / 3) * 2, (canvas.height / 3) * 2);
}

function drawSomethingElse() {
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgba(0,0,255,0.5)";
  ctx.fillRect(canvas.width / 3, canvas.height / 3, (canvas.width / 3) * 2, (canvas.height / 3) * 2);
}

function doACalculationThatTakesALongTime() {
  var d = Date.now();
  while (Date.now() - d < 2 * 1000) {}
  console.log("Big calculation done");
}

function foo() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawSomething();
  setTimeout(doACalculationThatTakesALongTime, 1000);
  drawSomethingElse();
  setTimeout(doACalculationThatTakesALongTime, 1000);
}
setTimeout(foo, 1000);

Alternatively, if the order of execution is important you can chain these actions together with Promises while ensuring frame rendering using requestAnimationFrame:

var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext("2d");
var p = document.body.appendChild(document.createElement("p"));

function drawSomething() {
  ctx.fillStyle = "rgba(255,0,0,0.5)";
  ctx.fillRect(0, 0, (canvas.width / 3) * 2, (canvas.height / 3) * 2);
  p.innerHTML += "Drawed something<br>";
}

function drawSomethingElse() {
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgba(0,0,255,0.5)";
  ctx.fillRect(canvas.width / 3, canvas.height / 3, (canvas.width / 3) * 2, (canvas.height / 3) * 2);
  p.innerHTML += "Drawed something else<br>";
}

function doACalculationThatTakesALongTime() {
  var d = Date.now();
  while (Date.now() - d < 2 * 1000) {}
  p.innerHTML += "Big calculation done<br>";
}

function foo() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new Promise(function(resolve, reject) {
      requestAnimationFrame(function() {
        drawSomething();
        resolve();
      });
    })
    .then(function() {
      return new Promise(function(resolve, reject) {
        requestAnimationFrame(function() {
          doACalculationThatTakesALongTime();
          resolve();
        });
      });
    })
    .then(function() {
      return new Promise(function(resolve, reject) {
        requestAnimationFrame(function() {
          drawSomethingElse();
          resolve();
        });
      });
    })
    .then(function() {
      return new Promise(function(resolve, reject) {
        requestAnimationFrame(function() {
          doACalculationThatTakesALongTime();
          resolve();
        });
      });
    })
}
foo();


问:
How to inject ');
    doc.close();
}
```

<p>But using <code>document.write</code> is a really nasty way of doing it. Chrome even complains with a warning in the console: <em>[Violation] Avoid using document.write().</em></p>

<p>I've come up with a few alternative approaches, for example:</p>

```// same as above until doc.open()
const s = doc.createElement('script');
s.src = url;
doc.head.appendChild(s);
```

<p>or</p>

```const s = doc.createElement('script');
s.appendChild(doc.createTextNode('(function() { const s =
document.createElement("script"); s.src = "' + url + '";
document.body.appendChild(s); })()'));
doc.head.appendChild(s);
```

These work nicely in Chrome and Safari but not in Firefox.

I've compiled a test with several methods to load the script: https://embed.plnkr.co/l8DwUBQs7cQsi938eTOn/

Any ideas how to make this work?

答:
You can create a blob and open it

```<code>var url = 'foo'
var blob = new Blob([
  '<html><body><script src="' + url + '"></script></body></html>'
], {type: 'text/html'})
var iframeUrl = URL.createObjectURL(blob)
console.log(iframeUrl)
</code>```

...Or if you like a base64 url

You can also use the srcdoc but it isn't supported by IE/Edge

Title: How to inject <script> tag into empty iframe without document.write?

Body:
I want to load an iframe that does nothing else than load a JavaScript file from a given URL. While this would be easy by loading a simple HTML page into the iframe that only contains the ');
    doc.close();
}

But using document.write is a really nasty way of doing it. Chrome even complains with a warning in the console: [Violation] Avoid using document.write().

I've come up with a few alternative approaches, for example:

// same as above until doc.open()
const s = doc.createElement('script');
s.src = url;
doc.head.appendChild(s);

or

const s = doc.createElement('script');
s.appendChild(doc.createTextNode('(function() { const s =
document.createElement("script"); s.src = "' + url + '";
document.body.appendChild(s); })()'));
doc.head.appendChild(s);

These work nicely in Chrome and Safari but not in Firefox.

I've compiled a test with several methods to load the script: https://embed.plnkr.co/l8DwUBQs7cQsi938eTOn/

Any ideas how to make this work?

Body:
You can create a blob and open it

var url = 'foo'
var blob = new Blob([
  '<html><body><script src="' + url + '"></script></body></html>'
], {type: 'text/html'})
var iframeUrl = URL.createObjectURL(blob)
console.log(iframeUrl)

...Or if you like a base64 url

You can also use the srcdoc but it isn't supported by IE/Edge


问:
Silverlight context menu: how to determine which menu was clicked?
I have the following context menu:

```<code>                <ListBox x:Name="sectionList" Margin="56,8,15,0" FontSize="64" SelectionChanged="SectionList_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <toolkit:ContextMenuService.ContextMenu>
                                    <toolkit:ContextMenu>
                                        <toolkit:MenuItem Header="Hide this section from this list" Click="ContextMenuItem_Click" />
                                    </toolkit:ContextMenu>
                                </toolkit:ContextMenuService.ContextMenu>
                                <TextBlock Text="{Binding DisplayName}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
</code>```

As you can see, each displayed item has its own context menu. Each context menu is hooked up to the same event handler:

```<code>    private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
    {

    }
</code>```

From this method, how can I tell which context menu was clicked? I want to know what the DataContext for the corresponding DataTemplate is.

答:
If you put a breakpoint inside the event handler ContextMenuItem_Click, you will then be able to examine the properties of sender and e. You will probably find your answer there.

One way to do this is to hover over those words. Another would be to use the Immediate Window. Type in sender and a dot to get intellisense.

Body:
I have the following context menu:

                <ListBox x:Name="sectionList" Margin="56,8,15,0" FontSize="64" SelectionChanged="SectionList_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <toolkit:ContextMenuService.ContextMenu>
                                    <toolkit:ContextMenu>
                                        <toolkit:MenuItem Header="Hide this section from this list" Click="ContextMenuItem_Click" />
                                    </toolkit:ContextMenu>
                                </toolkit:ContextMenuService.ContextMenu>
                                <TextBlock Text="{Binding DisplayName}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

As you can see, each displayed item has its own context menu. Each context menu is hooked up to the same event handler:

    private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
    {

    }

From this method, how can I tell which context menu was clicked? I want to know what the DataContext for the corresponding DataTemplate is.


问:
How to define a trigger ON COMMIT in Oracle?
Is there any way in oracle database to define trigger which will be fired synchronously before COMMIT (and ROLLBACK if it throws exception) in case when specified table is changed?</p>

答:
I had a similiar problem, but option 1 was unfortunately not convenient for my case.

Another possible solution, which is also suggested by "Ask Tom", is to specify a stored procedure and simply call that procedure before executing the COMMIT.
This solution is only convenient if you have access to the code which executes the COMMIT, but for my case this was the easiest solution.


问:
Run spring boot with jdk9 using jigsaw modules
What's wrong with this application. I thought the mix of classpath jars and module jars are valid. For all jars not having an explicit module-info become an automatic module? When I delete my module-info.java it works. Because IDEA using the classpath for this case.

Java(TM) SE Runtime Environment (build 9+176)

IntelliJ IDEA 2017.1.4

module-info.java

```<code>module test {
    requires spring.boot.autoconfigure;
    requires spring.boot;
}
</code>```

App.java

```<code>package com.foo.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
</code>```

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.foo.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M2</version>
    </parent>

    <name>test</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>
</code>```

Exception in thread "main" java.lang.IllegalArgumentException: Cannot
  instantiate interface
  org.springframework.context.ApplicationContextInitializer :
  org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:439)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:418)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:409)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:266)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:247)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
    at test/com.foo.test.App.main(App.java:10) Caused by:
  java.lang.NoClassDefFoundError: java/sql/SQLException     at
  spring.beans@5.0.0.RC2/org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:145)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:435)
    ... 7 more Caused by: java.lang.ClassNotFoundException:
  java.sql.SQLException     at
  java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at
  java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 9 more

答: I assume spring.boot is an automatic module. An automatic module doesn't declare it dependences so you have to use --add-modules to ensure that any explicit modules needed are resolved. If spring.boot were an explicit module then I assume it would requires java.sql and you won't have this issue.

Body:
What's wrong with this application. I thought the mix of classpath jars and module jars are valid. For all jars not having an explicit module-info become an automatic module? When I delete my module-info.java it works. Because IDEA using the classpath for this case.

Java(TM) SE Runtime Environment (build 9+176)

IntelliJ IDEA 2017.1.4

module-info.java

module test {
    requires spring.boot.autoconfigure;
    requires spring.boot;
}

App.java

package com.foo.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.foo.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M2</version>
    </parent>

    <name>test</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

Exception in thread "main" java.lang.IllegalArgumentException: Cannot
  instantiate interface
  org.springframework.context.ApplicationContextInitializer :
  org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:439)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:418)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:409)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:266)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:247)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
    at test/com.foo.test.App.main(App.java:10) Caused by:
  java.lang.NoClassDefFoundError: java/sql/SQLException     at
  spring.beans@5.0.0.RC2/org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:145)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:435)
    ... 7 more Caused by: java.lang.ClassNotFoundException:
  java.sql.SQLException     at
  java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at
  java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 9 more