问:
What does the jsr keyword mean?
I'm looking at some Java code, and I've noticed the following:

```<code>if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}
</code>```

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?

答: jsr 433 is not a valid Java statement. It is a VM instruction which stands for "Jump to Sub Routine" (See the VM Spec for more information). The decompiler inserted it because it didn't understand the bytecode instruction (perhaps it was obfuscated) and so couldn't decompile it into valid Java source.

Title: What does the jsr keyword mean?

Body:
I'm looking at some Java code, and I've noticed the following:

if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?


来源: stackexchange

问:
Sound Effect Won't Play (XCode/Swift)
So I am following through an old tutorial and I think with the changes in xcode and swift this code is now no longer usable, but i am not sure. Would love some help.

Declaring constant for the audio effect

```<code>let cannonSound = SKAction.playSoundFileNamed("cannon.wav", waitForCompletion: false)
</code>```

Calling the audio effect within my funtion

```<code>let hotdogSequence = SKAction.sequence([cannonSound, moveHotdog, deleteHotdog])
    hotdog.run(hotdogSequence)
</code>```

For more info I am using SpriteKit in Xcode and this code is contained within GameScene.swift file.

Update:
The error I receive is

2017-03-30 00:52:43.631 Ballpark Weiner[95999:1983181] SKAction: Error loading sound resource: "cannon.wav"

The game doesn't crash just no sound plays

答:
This message usually means that the file cannot be found in your project or might be corrupt.

You should check that the file is actually copied into your project and is spelled correctly. Its case sensitive so if the actual file is called "Cannon.wav" it will not work.

Hope this helps

ContentLicense: CC BY-SA 3.0

Title: Sound Effect Won't Play (XCode/Swift)

Body:
So I am following through an old tutorial and I think with the changes in xcode and swift this code is now no longer usable, but i am not sure. Would love some help.

Declaring constant for the audio effect

let cannonSound = SKAction.playSoundFileNamed("cannon.wav", waitForCompletion: false)

Calling the audio effect within my funtion

let hotdogSequence = SKAction.sequence([cannonSound, moveHotdog, deleteHotdog])
    hotdog.run(hotdogSequence)

For more info I am using SpriteKit in Xcode and this code is contained within GameScene.swift file.

Update:
The error I receive is

2017-03-30 00:52:43.631 Ballpark Weiner[95999:1983181] SKAction: Error loading sound resource: "cannon.wav"

The game doesn't crash just no sound plays


问:
Correct way to add fields to a model on django
I have a User model and i want to add a new field to the user, in the database and in the user form. i have looked online many differente ways to do this but i want to know what is the "correct" way to do it. Specially the correct way to create migrations.

Django Version: (1,10,0,u'final',1)

答:
Not sure if I got what you're looking for but let's say you want to add a "Status" field to your User model, and then have it in the Admin panel so you can interact with it (update, change, etc...).

in models.py - we are creating a Profile class which will be linked to a User and then a status to be added to a user:

```<code>class Profile(models.Model):
    " A profile added User """
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # so to link the profile to a user
    status = models.CharField(max_length=100, blank=True)
    # a field status

    def __str__(self):
        return self.status
</code>```

in admin.py - we are integrating the newly created Profile to the user

```<code>class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'

class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)

# And then we unregister the User class and register the two updated ones
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
</code>```

Don't forget to run /manage.py makemigrations and then /manage.py migrate to update the database.

Let me know if that answer your question.

Body:
Not sure if I got what you're looking for but let's say you want to add a "Status" field to your User model, and then have it in the Admin panel so you can interact with it (update, change, etc...).

in models.py - we are creating a Profile class which will be linked to a User and then a status to be added to a user:

class Profile(models.Model):
    " A profile added User """
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # so to link the profile to a user
    status = models.CharField(max_length=100, blank=True)
    # a field status

    def __str__(self):
        return self.status

in admin.py - we are integrating the newly created Profile to the user

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'

class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)

# And then we unregister the User class and register the two updated ones
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

Don't forget to run /manage.py makemigrations and then /manage.py migrate to update the database.

Let me know if that answer your question.


问:
Create prediction grid from dplyr piping
I'm hoping someone out there has a solution for using some form of expand.grid in piping using dplyr. I am doing some modeling where I have a few different groups (or Types below) and the groups have different ranges for x & y data. Once I run a gam on the data I am interested in creating a plot for the predictions, but I only want to predict values over the range that each value occupies, not the whole range of the data set.

I already have a working example posted below, but I'm wondering if there is a way to get around using a loop and complete my task.

Cheers

```<code>require(ggplot2)
require(dplyr)

# Create some data
df  = data.frame(Type = rep(c("A","B"), each = 100),
                 x = c(rnorm(100, 0, 1), rnorm(100, 2, 1)),
                 y = c(rnorm(100, 0, 1), rnorm(100, 2, 1)))

# and if you want to check out the data
ggplot(df,aes(x,y,col=Type)) + geom_point() + stat_ellipse()

# OK so I have no issue extracting the minimum and maximum values
# for each type
df_summ = df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y))
df_summ

# and I can create a loop and use the expand.grid function to get my
# desired output
test = NULL
for(ii in c("A","B")){
  df1 = df_summ[df_summ$Type == ii,]
  x = seq(df1$xmin, df1$xmax, length.out = 10)
  y = seq(df1$ymin, df1$ymax, length.out = 10)
  coords = expand.grid(x = x, y = y)
  coords$Type = ii
  test = rbind(test, coords)
}

ggplot(test, aes(x,y,col = Type)) + geom_point()
</code>```

But what I would really like to do is find a way to bypass the loop
and try and get the same output straight from my piping operator.
I've tried a few combinations using the do() function but to no effect,
and the one posted below is just one of many, many failed attempts

```<code>df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  do(data.frame(x = seq(xmin, xmax, length.out = 10),
                y = seq(ymin, ymax, length.out = 10)))

# this last line returns an error
# Error in is.finite(from) :
#   default method not implemented for type 'closure'
</code>```

答:
Your do() attempt was almost right. The trick is just to re-group after the summarize (which seems to drop the grouping). Also you need to make sure to grab the values from the data in the chain using .$. Try this

```<code>test <- df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  group_by(Type) %>%
  do(expand.grid(x = seq(.$xmin, .$xmax, length.out = 10),
                y = seq(.$ymin, .$ymax, length.out = 10)))
ggplot(test, aes(x,y,col = Type)) + geom_point()
</code>```

Body:
I'm hoping someone out there has a solution for using some form of expand.grid in piping using dplyr. I am doing some modeling where I have a few different groups (or Types below) and the groups have different ranges for x & y data. Once I run a gam on the data I am interested in creating a plot for the predictions, but I only want to predict values over the range that each value occupies, not the whole range of the data set.

I already have a working example posted below, but I'm wondering if there is a way to get around using a loop and complete my task.

Cheers

require(ggplot2)
require(dplyr)

# Create some data
df  = data.frame(Type = rep(c("A","B"), each = 100),
                 x = c(rnorm(100, 0, 1), rnorm(100, 2, 1)),
                 y = c(rnorm(100, 0, 1), rnorm(100, 2, 1)))

# and if you want to check out the data
ggplot(df,aes(x,y,col=Type)) + geom_point() + stat_ellipse()

# OK so I have no issue extracting the minimum and maximum values
# for each type
df_summ = df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y))
df_summ

# and I can create a loop and use the expand.grid function to get my
# desired output
test = NULL
for(ii in c("A","B")){
  df1 = df_summ[df_summ$Type == ii,]
  x = seq(df1$xmin, df1$xmax, length.out = 10)
  y = seq(df1$ymin, df1$ymax, length.out = 10)
  coords = expand.grid(x = x, y = y)
  coords$Type = ii
  test = rbind(test, coords)
}

ggplot(test, aes(x,y,col = Type)) + geom_point()

But what I would really like to do is find a way to bypass the loop
and try and get the same output straight from my piping operator.
I've tried a few combinations using the do() function but to no effect,
and the one posted below is just one of many, many failed attempts

df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  do(data.frame(x = seq(xmin, xmax, length.out = 10),
                y = seq(ymin, ymax, length.out = 10)))

# this last line returns an error
# Error in is.finite(from) :
#   default method not implemented for type 'closure'

Body:
Your do() attempt was almost right. The trick is just to re-group after the summarize (which seems to drop the grouping). Also you need to make sure to grab the values from the data in the chain using .$. Try this

test <- df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  group_by(Type) %>%
  do(expand.grid(x = seq(.$xmin, .$xmax, length.out = 10),
                y = seq(.$ymin, .$ymax, length.out = 10)))
ggplot(test, aes(x,y,col = Type)) + geom_point()


问:
How to get the values from a $.ajax using php
I'm trying to use $.ajax to send some values to a php page which then sends an email,
I can't figure out how to get the values from $.ajax in my php file,

any help would be appreciated,

```<code>$(function() {

$('form#email input[type=image]').click(function() {

    var name = $('form#email #name').val();
    var enq = $('form#email #enq').val();
    var dataString = 'name=' + name + '&enq=' + enq;

    $.ajax({
        type:'POST',
        url:'email.php',
        data:dataString,
        success:function() {
            $('form#email').fadeOut();
        }

    });
    $('form#email')[0].reset();
    return false;
 });
});
</code>```

php file

```<code>if (isset($_POST['submit_x'])) {

$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);

//echo $name,$enq;

$to = 'amirkarimian@hotmail.co.uk';
//$to = 'tutor@inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;

mail($to,$subject,$message);

if(!mail) {
    echo 'failed to send mail';
}
}
</code>```

the email doesn't get sent.
if I dont use $.ajax and submit the form normally the email get sent.

thanks

答:
You're checking for a variable you're not submitting, submit_x, you'll need to remove that outer if check.  Also, it's better to let jQuery serialize your strings properly (what if there's a & in there?) like this:

```<code>$(function() {
  $('#email input[type=image]').click(function() {
    $.ajax({
        type:'POST',
        url:'email.php',
        data: { name: $('#name').val(), enq: $('#enq').val() }
        success:function() {
            $('form#email').fadeOut();
        }
    });
    $('#email')[0].reset();
    return false;
  });
});
</code>```

Or if the <form> elements have proper name attributes (they should, for graceful degradation) , you can replace data: { name: $('#name').val(), enq: $('#enq').val() }

with data: $('#email').serialize().

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use $.ajax to send some values to a php page which then sends an email,
I can't figure out how to get the values from $.ajax in my php file,

any help would be appreciated,

$(function() {

$('form#email input[type=image]').click(function() {

    var name = $('form#email #name').val();
    var enq = $('form#email #enq').val();
    var dataString = 'name=' + name + '&enq=' + enq;

    $.ajax({
        type:'POST',
        url:'email.php',
        data:dataString,
        success:function() {
            $('form#email').fadeOut();
        }

    });
    $('form#email')[0].reset();
    return false;
 });
});

php file

if (isset($_POST['submit_x'])) {

$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);

//echo $name,$enq;

$to = 'amirkarimian@hotmail.co.uk';
//$to = 'tutor@inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;

mail($to,$subject,$message);

if(!mail) {
    echo 'failed to send mail';
}
}

the email doesn't get sent.
if I dont use $.ajax and submit the form normally the email get sent.

thanks

Body:
You're checking for a variable you're not submitting, submit_x, you'll need to remove that outer if check.  Also, it's better to let jQuery serialize your strings properly (what if there's a & in there?) like this:

$(function() {
  $('#email input[type=image]').click(function() {
    $.ajax({
        type:'POST',
        url:'email.php',
        data: { name: $('#name').val(), enq: $('#enq').val() }
        success:function() {
            $('form#email').fadeOut();
        }
    });
    $('#email')[0].reset();
    return false;
  });
});

Or if the <form> elements have proper name attributes (they should, for graceful degradation) , you can replace data: { name: $('#name').val(), enq: $('#enq').val() }

with data: $('#email').serialize().


问:
JQuery & PHP: How to pass appended button value to jquery? Is it possible?
I am appending items (articles) to a content with some originally existing articles, each article has a button for its deleting, editing, opening. I use jquery & ajax.
I want these appended articles' buttons to be able to pass each of their values to jquery click function, as well as produce all the logic there (same way as original articles' buttons do).
Is it possible to do something that way?</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Infinite Software Blog</title>
    <meta name="viewport" content="width=device-width, scale=1.0">
    <script type="text/javascript" src="/blog/jquery/jquery-3.2.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.del_btn').click(function () {
                var clickBtnValue = $(this).val();
                var ajaxurl = '/blog/helpers/delete_post.php',
                    data = {'action': clickBtnValue};
                $.post(ajaxurl, data, function () {
                    alert("Post was successfully deleted");
                });
            });
            $('.edit_btn').click(function () {
                var clickBtnValue = $(this).val();
                console.log(clickBtnValue);
                var ajaxurl = '/blog/edit_post.php',
                    data = {'action': clickBtnValue};
                $.post(ajaxurl, data, function () {
                    window.location.assign("/blog/helpers/updatePost.php");
                });
            });
            $('.post_content_btn').click(function () {
                var clickBtnValue = $(this).val();
                var ajaxurl = '/blog/view/post.php',
                    data = {'action': clickBtnValue};
                $.post(ajaxurl, data, function () {
                    window.location.assign("/blog/post.php");
                });
            });
            $('.more_posts_btn').click(function () {
                var clickBtnValue = $(this).val();
                var ajaxurl = '/blog/helpers/show_more_posts.php',
                    data = {'action': clickBtnValue};
                $.post(ajaxurl, data, function (output) {
                    $(".content").append(output);
                });
            });
        });
    </script>
    <link rel="stylesheet" href="/blog/styles/style.css" type="text/css"/>
</head>

show_more_post.php
<?php
if (isset($_POST['action'])) {
    include($_SERVER['DOCUMENT_ROOT'] . "/blog/model/classes.php");
    $post = new posts();
    $postsToDisplay = $post->getPostsQty($_POST['action']);
    $newRecordsIndex = $_POST['action'];
    for ($i = 1; $i <= $postsToDisplay; $i++) {
        $record = $post->getPost($newRecordsIndex);
        $newRecordsIndex++;
        $elementToAdd = '<article class="topContent"><header><h2><a href="#" title="' . $record[1] . '">' .
            $record[1] . '</a></h2></header><footer><p class="post-author">Author: ' . $record[2] . '</p>' .
            '</footer><content>' . $record[6] . '</content><footer><p class="post-date">Publish date: ' .
            $record[3] . '</p>' . '<p class="post-time">Publish time: ' . $record[4] . '</p><form><button type="submit"
            title="Delete post"' . ' value="' . $record[0] . '" class="del_btn">Delete post</button><button type="submit"
            title="Edit post"' . ' value="' . $record[0] . '" class="edit_btn">Edit post</button><button type="submit"
            title="Open post in a new tab" value="' . $record[0] . '" class="post_content_btn">Open Post</button>
            </form></footer></article>';
        echo($elementToAdd);
    }
}
</code>```

答:
I will suggest you to go in a simple way, You can use live table update strategy where you can simply update the data directly from the UI and delete or add as well. Find the below code

```<code>    $(document).ready(function(){
    function load(){
    $.ajax({
        url:'db.php',
        method: 'POST',
        success:function(data){
            $("#load").html(data);
        }
    });

    };
    load();
    $(document).on('click', '.bton', function(){
        var name= $(this).data("id");
        if(confirm("Do you want to delete this row"))
        {
            $.ajax({
                url: 'delete.php',
                method: 'POST',
                data:{id:name},
                success: function(data){
                    alert(data);
                    load();
                }
            });
        }
    });

    $(document).on('click','#add', function(){
        var addName= $("#name").text();
        var addComp= $("#company").text();
        $.ajax({
            url:'insert.php',
            method:'POST',
            data: {name:addName, company:addComp},
            success:function(data){
                alert(data);
                load();
            }
        });
    });

    $(document).on('blur','.type', function(){
        var editID=$(this).data('id1');
        var editName= $(this).text();
        alert(editName);
    })
   });
</code>```

for reference click here, download file and use to understand better.

Body:
I am appending items (articles) to a content with some originally existing articles, each article has a button for its deleting, editing, opening. I use jquery & ajax.
I want these appended articles' buttons to be able to pass each of their values to jquery click function, as well as produce all the logic there (same way as original articles' buttons do).
Is it possible to do something that way?

<!DOCTYPE html>

    <title>Infinite Software Blog</title>
    <meta name="viewport" content="width=device-width, scale=1.0">

    <link rel="stylesheet" href="/blog/styles/style.css" type="text/css"/>

show_more_post.php
<?php
if (isset($_POST['action'])) {
    include($_SERVER['DOCUMENT_ROOT'] . "/blog/model/classes.php");
    $post = new posts();
    $postsToDisplay = $post->getPostsQty($_POST['action']);
    $newRecordsIndex = $_POST['action'];
    for ($i = 1; $i <= $postsToDisplay; $i++) {
        $record = $post->getPost($newRecordsIndex);
        $newRecordsIndex++;
        $elementToAdd = '

' .
            $record[1] . '

Author: ' . $record[2] . '
' .
            '<content>' . $record[6] . '</content>
Publish date: ' .
            $record[3] . '
' . '
Publish time: ' . $record[4] . '
<form><button type="submit"
            title="Delete post"' . ' value="' . $record[0] . '" class="del_btn">Delete post</button><button type="submit"
            title="Edit post"' . ' value="' . $record[0] . '" class="edit_btn">Edit post</button><button type="submit"
            title="Open post in a new tab" value="' . $record[0] . '" class="post_content_btn">Open Post</button>
            </form>
';
        echo($elementToAdd);
    }
}

Body:
I will suggest you to go in a simple way, You can use live table update strategy where you can simply update the data directly from the UI and delete or add as well. Find the below code

    $(document).ready(function(){
    function load(){
    $.ajax({
        url:'db.php',
        method: 'POST',
        success:function(data){
            $("#load").html(data);
        }
    });

    };
    load();
    $(document).on('click', '.bton', function(){
        var name= $(this).data("id");
        if(confirm("Do you want to delete this row"))
        {
            $.ajax({
                url: 'delete.php',
                method: 'POST',
                data:{id:name},
                success: function(data){
                    alert(data);
                    load();
                }
            });
        }
    });

    $(document).on('click','#add', function(){
        var addName= $("#name").text();
        var addComp= $("#company").text();
        $.ajax({
            url:'insert.php',
            method:'POST',
            data: {name:addName, company:addComp},
            success:function(data){
                alert(data);
                load();
            }
        });
    });

    $(document).on('blur','.type', function(){
        var editID=$(this).data('id1');
        var editName= $(this).text();
        alert(editName);
    })
   });

for reference click here, download file and use to understand better.


问:
Retrieving RSS posts older than those included in feed
When creating an RSS reader, you download the XML formatted document pointed to by the RSS feed link, and you can parse it manually or using the functionality in the SyndicationFeed namespace.

So if we take Scott Guthrie's blog as an example, you download the RSS feed document here, and parse it. My problem is that this document only holds 15 items, yet he has been blogging for a number of years.

Is there a standard or established way of getting the older posts not included in the RSS feed document? Or do you have to find the base address for the blog posts and then parse the pages of the site from there to get them? How do you avoid missing posts on high volume blogs?

答:
With RSS/Atom you can't query older articles.

I built a RSS archival service (https://app.pub.center). All of our data is free to use via REST. We charge money for push notifications.

PubCenter daily polls it's catalog of RSS feeds, and caches the articles. Then, you can get these articles back in a chronological order. For example:

Page 1 of The Atlantic https://pub.center/feed/02702624d8a4c825dde21af94e9169773454e0c3/articles?limit=10&page=1

Page 2 of The Atlantic https://pub.center/feed/02702624d8a4c825dde21af94e9169773454e0c3/articles?limit=10&page=2


问:
How to export table into csv file in angular 2
How to export data table on my angular application UI into a CSV file or xls spreadsheet. Looking to have a button to be displayed on top of the table clicking on which can do this export. Please advise. </p>

答:
You can take help of angular2-csv or ng-table-to-csv

https://www.npmjs.com/package/angular2-csv
https://github.com/kollavarsham/ng-table-to-csv


问:
Uncaught TypeError: Cannot read property 'getContext' of null at zoom.html:8
I am trying to create an image zoom where by if you hover over the mouse over the image let it zoom the image on the defined width. Along the line I am getting

```<code>Uncaught TypeError: Cannot read property 'getContext' of null
    at zoom.html:8
</code>```

in my html file. This is a snippet of the html file I am having the challenge with

```<code>var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    iw, ih;
</code>```

In the body of the html file I have this snippet

```<code><canvas width="310" height="305" id="canvas">Sorry, no canvas available</canvas>
<a id="download" download="download.jpg">Download as image</a>
</code>```

here is a plunk demo I have made

```<code>http://plnkr.co/edit/0G93qmVeUWby0SRIp5Br
</code>```

Please what could be wrong?

答:
You're attempting to access an element in the DOM before it's loaded. Compare these two examples:

<canvas id="canvas"></canvas>```
</div>
</div>
</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-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas>
<script>
console.log(document.getElementById('canvas'));
</script></code>```

As you may have picked up, the solution is to run your script after the page is loaded, i.e. at the bottom of the .

Body:
I am trying to create an image zoom where by if you hover over the mouse over the image let it zoom the image on the defined width. Along the line I am getting

Uncaught TypeError: Cannot read property 'getContext' of null
    at zoom.html:8

in my html file. This is a snippet of the html file I am having the challenge with

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    iw, ih;

In the body of the html file I have this snippet

<canvas width="310" height="305" id="canvas">Sorry, no canvas available</canvas>
Download as image

here is a plunk demo I have made

http://plnkr.co/edit/0G93qmVeUWby0SRIp5Br

Please what could be wrong?

Body:
You're attempting to access an element in the DOM before it's loaded. Compare these two examples:

<script>
console.log(document.getElementById('canvas'));
</script>
<canvas id="canvas"></canvas>

<canvas id="canvas"></canvas>
<script>
console.log(document.getElementById('canvas'));
</script>

As you may have picked up, the solution is to run your script after the page is loaded, i.e. at the bottom of the <body>.


问:
How can I format currency depending on decimal value?
I am using NSDecimalNumber to format currency and want the following inputs and outputs:

9.99 --> 9.99
10 --> 10
10.00 --> 10
9.90 --> 9.90
9.9 --> 9.90
0 --> 0
0.01 --> 0.01
20 --> 20
10.01 --> 10.01

How can I do this in Swift.

EDIT: Essentially if there are cents (i.e. cents > 0) then display the cents. Otherwise, don't.

答:
(Answering here, as a closed question was re-directed to this one...)

Perhaps the most straightforward route, particularly since this is tagged "Swift", is to determine if it's a whole number or not:

```<code>if value.truncatingRemainder(dividingBy: 1) == 0 {
    // it's a whole number,
    // so format WITHOUT decimal places, e.g. $12
} else {
    // it's a fraction,
    // so format WITH decimal places, e.g. $12.25
}
</code>```

the added benefit is avoiding issues with locales and currency formats... no search/replace of ".00" when you're in Germany, for example, where the format is ",00"

Body:
(Answering here, as a closed question was re-directed to this one...)

Perhaps the most straightforward route, particularly since this is tagged "Swift", is to determine if it's a whole number or not:

if value.truncatingRemainder(dividingBy: 1) == 0 {
    // it's a whole number,
    // so format WITHOUT decimal places, e.g. $12
} else {
    // it's a fraction,
    // so format WITH decimal places, e.g. $12.25
}

the added benefit is avoiding issues with locales and currency formats... no search/replace of ".00" when you're in Germany, for example, where the format is ",00"


问:
The columns in 'table' do not match an existing primary key or unique constraint
Consider two database tables, tbl_One & tbl_Two.

tbl_One's primary keys are: A, B & E columns

tbl_Two's primary keys are: B & C.

I don't want any values in table tbl_Two column B that do not exist in table tbl_One column B.

Ideally, I want column B to be foreign key, but when I try to create this I get the following error message:

The columns in table 'tbl_One' do not match an existing primary key
  or UNIQUE constraint.

How can I achieve this?

答: If you want a foreign key for field B in table B, remove field A, E 's primary key, create the relation then reset the primary keys back to those two fields.</p>


答: try sending 'submit_x' to php :)</p>

Title: How to get the values from a $.ajax using php

Body: try sending 'submit_x' to php :)


问:
PHP Get Time From X Percentage of Total Time
I don't know if this will make sense but I would like to get the time from percentage of a value, I have the following as an input example:

```<code>mypercentage = 50;
mytime = "00:59:59"
</code>```

As you can see, my time is 60 minutes (1 hour) and 50% of that is 30 minutes therefore from the 2 above inputs I would like to get the following output
(50 % of an hour):

```<code>00:30:00
</code>```

答:
Thank you all who responded, I found this solution to work:</p>

```<code>            $mypercentage = 50;
            $mytime = '00:59:59';

            $totaltime = date('H:i:s', strtotime($mytime));

            $seconds = strtotime("1970-01-01 $totaltime UTC");

            $per_seconds = ($mypercentage / 100) * $seconds;

            $time_from_percentage = gmdate("H:i:s", $per_seconds);
            echo $time_from_percentage;
</code>```

Body:
I don't know if this will make sense but I would like to get the time from percentage of a value, I have the following as an input example:

mypercentage = 50;
mytime = "00:59:59"

As you can see, my time is 60 minutes (1 hour) and 50% of that is 30 minutes therefore from the 2 above inputs I would like to get the following output
(50 % of an hour):

00:30:00

Body:
Thank you all who responded, I found this solution to work:

            $mypercentage = 50;
            $mytime = '00:59:59';

            $totaltime = date('H:i:s', strtotime($mytime));

            $seconds = strtotime("1970-01-01 $totaltime UTC");

            $per_seconds = ($mypercentage / 100) * $seconds;

            $time_from_percentage = gmdate("H:i:s", $per_seconds);
            echo $time_from_percentage;


问:
Windows Batch: replace %20 to space
I am writing a custom pluggable protocol handler, which is basically the following batch script:

```<code>@ECHO off
SET "FullPath=%~1"
explorer.exe "%FullPath%"
</code>```

However if Windows Explorer passes a UNC with spaces it comes to the script with %20 instead of space:

\Groups\Group%20Micro\

instead of

\Groups\Group Micro\

Can you help me to figure out a batch script snippet replacing "%20" to " " or "\ " in the string please?

So far I found Replace Percent with Bang in String, but it requires somehow to replace % with %%, which is a separate task.

Thank you very much.

答:
Eventually many thanks to Windows batch script url decoding I worked out desired snippet:</p>

```<code>@ECHO off

SET "FullPath=%~1"
REM ECHO %FullPath% & PAUSE

SETLOCAL ENABLEDELAYEDEXPANSION

SET FullPath=%FullPath:smb:=%
SET FullPath=%FullPath:/=\%
SET FullPath=!FullPath:%%20= !

REM ECHO %FullPath% & PAUSE

explorer.exe "%FullPath%"
</code>```

Title: Windows Batch: replace %20 to space

Body:
I am writing a custom pluggable protocol handler, which is basically the following batch script:

@ECHO off
SET "FullPath=%~1"
explorer.exe "%FullPath%"

However if Windows Explorer passes a UNC with spaces it comes to the script with %20 instead of space:

\Groups\Group%20Micro\

instead of

\Groups\Group Micro\

Can you help me to figure out a batch script snippet replacing "%20" to " " or "\ " in the string please?

So far I found Replace Percent with Bang in String, but it requires somehow to replace % with %%, which is a separate task.

Thank you very much.

Body:
Eventually many thanks to Windows batch script url decoding I worked out desired snippet:

@ECHO off

SET "FullPath=%~1"
REM ECHO %FullPath% & PAUSE

SETLOCAL ENABLEDELAYEDEXPANSION

SET FullPath=%FullPath:smb:=%
SET FullPath=%FullPath:/=\%
SET FullPath=!FullPath:%%20= !

REM ECHO %FullPath% & PAUSE

explorer.exe "%FullPath%"


问:
WooCommerce costum meta_key
I would like to add a custom meta_key value to each WooCommerce product It will be the Discount rate :

```<code>_discount_rate = ((_sale_price-_regular_price_)/(_regular_price)*100)
</code>```

I'm trying to figure out how to add a filter to WooCommerce function woocommerce_process_product_meta Something like:

```<code>add_filter('woocommerce_process_product_meta', 'mytheme_product_save_discountrate');

function mytheme_product_save_discountrate($post_id) {

    if (get_post_meta($post_id, "_sale_price")) {

        $regular_price = get_post_meta($post_id, "_regular_price");
        $sale_price = get_post_meta($post_id, "_sale_price");

        $discount_rate = ($sale_price - $regular_price) / $regular_price * 100);

        update_post_meta($post_id, '_discount_rate', $discount_rate);
    }
}
</code>```

I'm just not sure how I can retrieve the regular and sale prices?

答:
WooCommerce has an inbuilt methods to get the price
  get_regular_price() and get_sale_price().

Here is the code:

```<code>add_action('woocommerce_process_product_meta', 'mytheme_product_save_discountrate', 999); //<-- check the priority

function mytheme_product_save_discountrate($post_id) {

    $_product = wc_get_product($post_id);
    $regular_price = $_product->get_regular_price();
    $sale_price = $_product->get_sale_price();
//    $_product->get_price();

    if (!empty($sale_price)) {
        $discount_rate = (($sale_price - $regular_price) / ($regular_price)) * 100; //replace it with your own logic
        update_post_meta($post_id, '_discount_rate', $discount_rate);
    }
}
</code>```

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin PHP files.

Code is tested and works.

Hope this helps!

Title: WooCommerce costum meta_key

Body:
I would like to add a custom meta_key value to each WooCommerce product It will be the Discount rate :

_discount_rate = ((_sale_price-_regular_price_)/(_regular_price)*100)

I'm trying to figure out how to add a filter to WooCommerce function woocommerce_process_product_meta Something like:

add_filter('woocommerce_process_product_meta', 'mytheme_product_save_discountrate');

function mytheme_product_save_discountrate($post_id) {

    if (get_post_meta($post_id, "_sale_price")) {

        $regular_price = get_post_meta($post_id, "_regular_price");
        $sale_price = get_post_meta($post_id, "_sale_price");

        $discount_rate = ($sale_price - $regular_price) / $regular_price * 100);

        update_post_meta($post_id, '_discount_rate', $discount_rate);
    }
}

I'm just not sure how I can retrieve the regular and sale prices?

Body:
WooCommerce has an inbuilt methods to get the price
  get_regular_price() and get_sale_price().

Here is the code:

add_action('woocommerce_process_product_meta', 'mytheme_product_save_discountrate', 999); //<-- check the priority

function mytheme_product_save_discountrate($post_id) {

    $_product = wc_get_product($post_id);
    $regular_price = $_product->get_regular_price();
    $sale_price = $_product->get_sale_price();
//    $_product->get_price();

    if (!empty($sale_price)) {
        $discount_rate = (($sale_price - $regular_price) / ($regular_price)) * 100; //replace it with your own logic
        update_post_meta($post_id, '_discount_rate', $discount_rate);
    }
}

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin PHP files.

Code is tested and works.

Hope this helps!


问:
mousePos As Point = Control.MousePosition not accepted after Imports AForge
When trying to run   Error when: imports AForge </p>

<p>^^ 2 screenshots
 Well I hope to get a fix as I don't understand error. </p>

```<code>Private Sub Form1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove

    If e.Button = MouseButtons.Left Then
        Dim mousePos As Point = Control.MousePosition
        mousePos.Offset(mouse_offset.X, mouse_offset.Y)
        Location = mousePos

    End If
End Sub
</code>```

答:
It is probably a namespace collision where AForge also has a Point type.  Fully qualify the reference.

Dim mousePos As System.Drawing.Point = Control.MousePosition

Body:
When trying to run   Error when: imports AForge

^^ 2 screenshots
 Well I hope to get a fix as I don't understand error.

Private Sub Form1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove

    If e.Button = MouseButtons.Left Then
        Dim mousePos As Point = Control.MousePosition
        mousePos.Offset(mouse_offset.X, mouse_offset.Y)
        Location = mousePos

    End If
End Sub


问:
Sql left join with 2 columns
I have a problem with left join i have 2 tables. Table A:

```<code>Itemid InventlocationID
10001    200
10001    301
10001    302
</code>```

And table B

```<code>ItemId InventLocationID ItemOption
10001    200               A
10001    301               B
</code>```

I want to get the following result

```<code>Itemid InventlocationID ItemOption
10001    200                A
10001    301                B
10001    302               null
</code>```

I use left join:

```<code>SELECT a.itemid,a.inventlocationid,b.ItemOption
FROM  a
left  join b
on (a.ItemID = b.ITEMID and a.InventLocationid = b.INVENTLOCATIONID)
</code>```

and the result i get is:

```<code>Itemid InventlocationID Itemoption
10001    200                A
10001    301                B
</code>```

Any ideas how can i achieve the result i want?
Edit : tables a and b have more records

答:
This typically happens when you have a WHERE clause that references a column in the LEFT JOIN.  They key point is to use only columns from the first table -- not the one that is LEFT/OUTER joined.

You could still use ans ISNULL() or an OR (col == null) if you needed to.

(giving you an answer instead of a comment)

Title: Sql left join with 2 columns

Body:
I have a problem with left join i have 2 tables. Table A:

Itemid InventlocationID
10001    200
10001    301
10001    302

And table B

ItemId InventLocationID ItemOption
10001    200               A
10001    301               B

I want to get the following result

Itemid InventlocationID ItemOption
10001    200                A
10001    301                B
10001    302               null

I use left join:

SELECT a.itemid,a.inventlocationid,b.ItemOption
FROM  a
left  join b
on (a.ItemID = b.ITEMID and a.InventLocationid = b.INVENTLOCATIONID)

and the result i get is:

Itemid InventlocationID Itemoption
10001    200                A
10001    301                B

Any ideas how can i achieve the result i want?
Edit : tables a and b have more records


问:
pdfbox.util.ImageIOUtil.writeImage issue

There is an issue with PDFbox going on here.

```<code>java.lang.NullPointerException
    at org.apache.pdfbox.util.ImageIOUtil.writeImage(ImageIOUtil.java:197)
    at org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg.createImageStream(PDJpeg.java:190)
    at org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg.<init>(PDJpeg.java:150)
</code>```

Our current setup is 2 servers with 2 JVMs for each server running over Websphere 8.5 and Java 6.

When we restart the JVMs the issue seems to be resolved, but after few hours we get the same exception.

The application is using PDFBox v1.8.8

Here is a piece of the code:

```<code>ImageIO.setUseCache(false);
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage convertedFile = tiffToBufferedImageJAI(file);
PDXObjectImage img = new PDJpeg(document, convertedFile);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawXObject(img, 0, 0, 550, 800);
contentStream.close();

document.save(baos);
document.close();
baos.flush();

return baos.toByteArray();
</code>```

答:
The problem was that the ImageWriter below was registered but would not start correctly:

com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriterSpi

So, when ImageWriterIterator.next() was called, spi.createWriterInstance() was throwing a silent IOException and a null was being returned:

```<code>public ImageWriter next() {
        ImageWriterSpi spi = null;
        try {
                spi = (ImageWriterSpi)iter.next();
                return spi.createWriterInstance();
        } catch (IOException e) {
                // Deregister the spi in this case, but only as a writerSpi
                theRegistry.deregisterServiceProvider(spi, ImageWriterSpi.class);
        }
        return null;
}
</code>```

The reason why spi.createWriterInstance() was failing was:

```<code>java.lang.NoClassDefFoundError: com/sun/medialib/codec/jpeg/Encoder
</code>```

Adding -Dcom.sun.media.jai.disableMediaLib=true to the JVM startup made the offending ImageWriter not to be registered anymore.

Body:
There is an issue with PDFbox going on here.

java.lang.NullPointerException
    at org.apache.pdfbox.util.ImageIOUtil.writeImage(ImageIOUtil.java:197)
    at org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg.createImageStream(PDJpeg.java:190)
    at org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg.<init>(PDJpeg.java:150)

Our current setup is 2 servers with 2 JVMs for each server running over Websphere 8.5 and Java 6.

When we restart the JVMs the issue seems to be resolved, but after few hours we get the same exception.

The application is using PDFBox v1.8.8

Here is a piece of the code:

ImageIO.setUseCache(false);
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage convertedFile = tiffToBufferedImageJAI(file);
PDXObjectImage img = new PDJpeg(document, convertedFile);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawXObject(img, 0, 0, 550, 800);
contentStream.close();

document.save(baos);
document.close();
baos.flush();

return baos.toByteArray();

Body:
The problem was that the ImageWriter below was registered but would not start correctly:

com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriterSpi

So, when ImageWriterIterator.next() was called, spi.createWriterInstance() was throwing a silent IOException and a null was being returned:

public ImageWriter next() {
        ImageWriterSpi spi = null;
        try {
                spi = (ImageWriterSpi)iter.next();
                return spi.createWriterInstance();
        } catch (IOException e) {
                // Deregister the spi in this case, but only as a writerSpi
                theRegistry.deregisterServiceProvider(spi, ImageWriterSpi.class);
        }
        return null;
}

The reason why spi.createWriterInstance() was failing was:

java.lang.NoClassDefFoundError: com/sun/medialib/codec/jpeg/Encoder

Adding -Dcom.sun.media.jai.disableMediaLib=true to the JVM startup made the offending ImageWriter not to be registered anymore.


问:
Lodash template return function says data undefined
I am working on a code gen tool, and I am using Lodash to template the output files.  When I try running the resultant function from _.template(XXX) I get

"AppData" (the name of the template variable) is not defined.

I have tried to call temp below with and without the AppData variable and both give me

"ReferenceError: AppData is not defined"

```<code>templates.forEach((template) => {
      let temp = _.template(template, { AppData: AppData });
      output = temp(AppData);
    });
</code>```

This is the AppData object:

```<code>let AppData = { clientId: clientId,
                appId: applicationId,
                intents: ['Testing1',
                          'Testing2',
                          'Testing3',
                          'Testing4'
                         ]};
</code>```

Here is one of the 3 templates:

```<code><% _.each(AppData.intents, function( intent ){ %>
<transition event="<%=intent%>" target="<%=intent%>">
<state id="<%=intent%>">
<onentry>
<assign location="href_answer" expr="tfs.getKBAPIUrl(DNIS, environment, '<%=intent%>')"/>
<assign location="reason" expr="'<%=intent%>'"/>
<script><![CDATA[presentAnswer(href_answer,reason);]]></script>
</onentry>
  </state>
<% }) %>
</code>```

Stack is not letting me post the output, but it's the function representing the finished template.

答:
After much head smashing, I realized a simple issue.

I was passing the object incorrectly, and the templates were looking for the wrong thing.  In the templates I removed my AppData. object notation and updated the code to look like this.  The templates picked up the values correctly.

```<code>templates.forEach((template) => {
  let temp = _.template(template);
  output += temp(AppData);
});
</code>```

A bit of a rookie mistake, first time using Lodash.

Body:
I am working on a code gen tool, and I am using Lodash to template the output files.  When I try running the resultant function from _.template(XXX) I get

"AppData" (the name of the template variable) is not defined.

I have tried to call temp below with and without the AppData variable and both give me

"ReferenceError: AppData is not defined"

templates.forEach((template) => {
      let temp = _.template(template, { AppData: AppData });
      output = temp(AppData);
    });

This is the AppData object:

let AppData = { clientId: clientId,
                appId: applicationId,
                intents: ['Testing1',
                          'Testing2',
                          'Testing3',
                          'Testing4'
                         ]};

Here is one of the 3 templates:

<% _.each(AppData.intents, function( intent ){ %>
<transition event="<%=intent%>" target="<%=intent%>">
<state id="<%=intent%>">
<onentry>
<assign location="href_answer" expr="tfs.getKBAPIUrl(DNIS, environment, '<%=intent%>')"/>
<assign location="reason" expr="'<%=intent%>'"/>

</onentry>
  </state>
<% }) %>

Stack is not letting me post the output, but it's the function representing the finished template.

Body:
After much head smashing, I realized a simple issue.

I was passing the object incorrectly, and the templates were looking for the wrong thing.  In the templates I removed my AppData. object notation and updated the code to look like this.  The templates picked up the values correctly.

templates.forEach((template) => {
  let temp = _.template(template);
  output += temp(AppData);
});

A bit of a rookie mistake, first time using Lodash.


问:
Specific output pattern of array in java
I've figured out how to create an array in which the output look like this:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

if the user enters a 4 indicating a 4x4 array.
My question is how could I manipulate this code in a way that it would out put the array in this order

1 2 3 4

8 7 6 5

9 10 11 12

16 15 14 13

where every other row is "backwards"

`import java.util.Scanner;
import java.util.Arrays;
import java.util.Arrays;

public class Question2 {

```<code>public static void main(String[] args) {

//Title
    System.out.println("[----------------------]");
    System.out.println("[     Array Pattern    ]");
    System.out.println("[----------------------]");
    System.out.println("");
//declare scanner
    Scanner keyboard = new Scanner (System.in);

//Prompt user to enter a digit greater than or equal to 3
    System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");

//read user input
    int num = keyboard.nextInt();

//place constraints on int num so that if it is less than 3, the program does not execute
    while(num<3 )
    {
        System.out.println("Lets's try this again....");
        System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
        num = keyboard.nextInt();
    }

    //2D array with number of rows and columns entered by user
    int[][] array = new int [num][num];
    int inc=1;
    for(int i=0;i<array.length;i++)
        for(int j=0;j<array.length;j++)
              {
                 array[i][j]=inc;
                 inc++;
              }

    //replace all square brackets in array display & format into order

            //replace all commas in array display

    String a = Arrays.toString(array);
    a = Arrays.deepToString(array).replace("], [", "\n").replaceAll("[\\[\\],]", "");
    System.out.println(a);`
</code>```

答:
What you could do is reverse the order of the for loop on every other line, so that it decrements instead:

```<code>for(int i=0;i<array.length;i++)
{
    if(i%2 == 0){
        for(int j=0;j<array.length;j++)
        {
            array[i][j]=inc;
            inc++;
        }
    }
    else{
        for(int j=num-1;j>=0;j--)
        {
            array[i][j]=inc;
            inc++;
        }
    }
}
</code>```

I don't really know how to format the columns the way you wrote the code (with Arrays.deepToString) but if you instead loop through it manually you could pad the string:

```<code>String [][]stringConvertedTable= new String[num][num];

    for(int i=0; i<num; i++) {
        for(int j=0; j<num; j++) {
            stringConvertedTable[i][j]= Integer.toString(array[i][j]);
            System.out.print(stringConvertedTable[i][j] + "\t");
        }
        System.out.println("");
    }
</code>```

It's not the most elegant way to do it though...

Body:
I've figured out how to create an array in which the output look like this:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

if the user enters a 4 indicating a 4x4 array.
My question is how could I manipulate this code in a way that it would out put the array in this order

1 2 3 4

8 7 6 5

9 10 11 12

16 15 14 13

where every other row is "backwards"

`import java.util.Scanner;
import java.util.Arrays;
import java.util.Arrays;

public class Question2 {

public static void main(String[] args) {

//Title
    System.out.println("[----------------------]");
    System.out.println("[     Array Pattern    ]");
    System.out.println("[----------------------]");
    System.out.println("");
//declare scanner
    Scanner keyboard = new Scanner (System.in);

//Prompt user to enter a digit greater than or equal to 3
    System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");

//read user input
    int num = keyboard.nextInt();

//place constraints on int num so that if it is less than 3, the program does not execute
    while(num<3 )
    {
        System.out.println("Lets's try this again....");
        System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
        num = keyboard.nextInt();
    }

    //2D array with number of rows and columns entered by user
    int[][] array = new int [num][num];
    int inc=1;
    for(int i=0;i<array.length;i++)
        for(int j=0;j<array.length;j++)
              {
                 array[i][j]=inc;
                 inc++;
              }

    //replace all square brackets in array display & format into order

            //replace all commas in array display

    String a = Arrays.toString(array);
    a = Arrays.deepToString(array).replace("], [", "\n").replaceAll("[\\[\\],]", "");
    System.out.println(a);`

Body:
What you could do is reverse the order of the for loop on every other line, so that it decrements instead:

for(int i=0;i<array.length;i++)
{
    if(i%2 == 0){
        for(int j=0;j<array.length;j++)
        {
            array[i][j]=inc;
            inc++;
        }
    }
    else{
        for(int j=num-1;j>=0;j--)
        {
            array[i][j]=inc;
            inc++;
        }
    }
}

I don't really know how to format the columns the way you wrote the code (with Arrays.deepToString) but if you instead loop through it manually you could pad the string:

String [][]stringConvertedTable= new String[num][num];

    for(int i=0; i<num; i++) {
        for(int j=0; j<num; j++) {
            stringConvertedTable[i][j]= Integer.toString(array[i][j]);
            System.out.print(stringConvertedTable[i][j] + "\t");
        }
        System.out.println("");
    }

It's not the most elegant way to do it though...


问:
Is there a way I can write my PHP code for WordPress a bit more optimized? Right now I feel like there could be a better way
So I am writing a template file for WordPress and I feel like I am using too many echo tabs. Just wanted to see if there is something that is better and easier that I am not doing right now. </p>

```<code><h1>Responsive grid layout</h1>
      <dl class="gridtab-1">

        <?php
            $args = array( 'post_type' => 'product', 'posts_per_page' => 5 );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();
              echo '<dt>', the_post_thumbnail('medium'), '</dt>';
              echo '<dd class="entry-content">';

              echo '<div class="bdanzer-container">',
                        '<div class="bdanzer-left">';

                            echo '<p>', the_post_thumbnail('large'), '</p>';

                        echo '</div>';

                echo '<div class="bdanzer-right">';
                    echo '<h1>', the_title() , '</h1>';
                    echo '<p>',the_content(),'</p>';
                echo '</div>';

                echo '<p>', the_category(), '</p>';

              echo '</div>';
              echo '</dd>';

            endwhile;
        ?>

        </dl>
</code>```

答:
Your code should be something like this:

```<code><h1>Responsive grid layout</h1>
<dl class="gridtab-1">
<?php
    $args = array( 'post_type' => 'product', 'posts_per_page' => 5 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
?>
    <dt><?php the_post_thumbnail('medium'); ?></dt>
    <dd class="entry-content">
        <div class="bdanzer-container">
            <div class="bdanzer-left">
                <p><?php the_post_thumbnail('large'); ?></p>
            </div>
            <div class="bdanzer-right">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
            </div>
            <p><?php the_category(); ?></p>
        </div>
    </dd>
<?php endwhile; ?>
</dl>
</code>```

Just close the php tag and start using plain html, use php only when is needed.

Body:
So I am writing a template file for WordPress and I feel like I am using too many echo tabs. Just wanted to see if there is something that is better and easier that I am not doing right now.

Responsive grid layout

        <?php
            $args = array( 'post_type' => 'product', 'posts_per_page' => 5 );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();
              echo '
', the_post_thumbnail('medium'), '
';
              echo '
';

              echo '
',
                        '
';

                            echo '
', the_post_thumbnail('large'), '
';

                        echo '
';

                echo '
';
                    echo '
', the_title() , '
';
                    echo '
',the_content(),'
';
                echo '
';

                echo '
', the_category(), '
';

              echo '
';
              echo '
';

            endwhile;
        ?>

Body:
Your code should be something like this:

<h1>Responsive grid layout</h1>
<dl class="gridtab-1">
<?php
    $args = array( 'post_type' => 'product', 'posts_per_page' => 5 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
?>
    <dt><?php the_post_thumbnail('medium'); ?></dt>
    <dd class="entry-content">
        <div class="bdanzer-container">
            <div class="bdanzer-left">
                <p><?php the_post_thumbnail('large'); ?></p>
            </div>
            <div class="bdanzer-right">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
            </div>
            <p><?php the_category(); ?></p>
        </div>
    </dd>
<?php endwhile; ?>
</dl>

Just close the php tag and start using plain html, use php only when is needed.


问:
Call intent with decimal points in an USSD code
In my android app, I want to dial an ussd code something like -- *123*1*0.5# -- the code i'm using is like this

Intent callIntent = new Intent(Intent.ACTION_DIAL);
   callIntent.setData(Uri.parse("tel:" + Uri.encode( "*123*1*"+"0.5"+"#")));

And i know that's working cause i Log it, and i got the right expresion, but when the dialer of the phone opens, it erase the dot and show me this.
*123*1*05#  - YOU CAN SEE THE DOT IS MISSING.

The first it's not an encoding problem , in fact the dot is one of the unreserved characters that UTF-8 leaves untouch.

A probable solution to this problem might be answer #2 of this post... How to send a USSD code containing decimal floating point (.)? wich is overwrite the intent for NEW_OUTGOING_CALL but i tried and didn't work. Does anyone has a solution for this.

Remember the problem it's not about the encoding, is about changing the number that the dial Intent is getting.

答: Dot is not a valid character in a tel: scheme intent. It's usually used to separate groups of digits in a phonenumber and I suspect it's stripped out by the dialer before sending as dtmf, even if it's an allowed alphanumeric character for USSD.


问:
Kentico 9 tild not being resolved for files
I have a custom page Type that lets the user select uploaded files (pdf, docx, xlxs). I've noticed that the tilde (~) is not being resolved when i look at the rendered page. I've checked the Output Filter in settings, but the settings here are default. What am I missing?

Here's a snippet from my transformation

```<code><%# IfEmpty(Eval("File"),"n/a","<a href=" + Eval("File") +" target='blank'><span class='fa fa-download'></span></a>")%>
</code>```

答: I think i solved this. In my custom page, I have a File Field, which is using the URL selector form control. With the Control Settings, I unchecked Use Relative URL. It seems to be working.</p>

Body:
I have a custom page Type that lets the user select uploaded files (pdf, docx, xlxs). I've noticed that the tilde (~) is not being resolved when i look at the rendered page. I've checked the Output Filter in settings, but the settings here are default. What am I missing?

Here's a snippet from my transformation

<%# IfEmpty(Eval("File"),"n/a","")%>


问:
How does Google Reader get every item in an RSS feed?
Slashdot's RSS feed is http://rss.slashdot.org/Slashdot/slashdot. If I download the XML file directly, I only get a few of the posts from today. However, if I subscribe to the feed in Google Reader, and keep scrolling down in their "infinite scroll" interface, it seems like I can get an arbitrary number of Slashdot posts from the past - maybe I can get every Slashdot post ever?

How does Google Reader retrieve an unlimited number of posts from an RSS feed?

How can I do the same?

答:
I built a RSS archival service that does what you're talking about (https://app.pub.center). All of the RSS is free to use via REST. If you want push notifications you have to switch to a paid plan.

PubCenter daily polls it's catalog of RSS feeds, and caches the articles. Then, you can get these articles back in a chronological order. For example:

Page 1 of The Atlantic https://pub.center/feed/02702624d8a4c825dde21af94e9169773454e0c3/articles?limit=10&page=1

Page 2 of The Atlantic https://pub.center/feed/02702624d8a4c825dde21af94e9169773454e0c3/articles?limit=10&page=2

OwnerDisplayName: Horace Loeb


问:
How to extract text between matching strings including match strings and lines
I am working on python to extract certain string between match strings. These strings are generated from a list which is again generated dynamically by a separate python function. The list I am working on looks like this:-

```<code>sample_list = ['line1 this line a first line',
        'line1 this line is also considered as line one...',
        'line1 this line is the first line',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 this contain other strings',
        'line1 this may contain other strings as well',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 what the heck is it...'
        ]
</code>```

The output I want is similar to this:-

```<code>line1 this line is the first line
line2 this line is second line to be included in output
line3 this should also be included in output
line1 this may contain other strings as well
line2 this line is second line to be included in output
line3 this should also be included in output
</code>```

As you can see, I want to extract the text/lines which are starting as line1 and ending with line3 (up to line ending). The final output includes both the matching words (ie. line1 and line3).

The code I have tried is:-

```<code># Convert list to string first
list_to_str = '\n'.join(sample_list)
# Get desired output
print(re.findall('\nline1(.*?)\nline2(.*?)\nline3($)', list_to_str, re.DOTALL))
</code>```

This is what I am getting as an output ():-

```<code>[]
</code>```

Any help is appreciated.

Edit1:-
I have done some work and found this nearest solution:-

```<code>matches = (re.findall(r"^line1(.*)\nline2(.*)\nline3(.*)$", list_to_str, re.MULTILINE))

for match in matches:
    print('\n'.join(match))
</code>```

It gives me this output:-

```<code> this line is the first line
 this line is second line to be included in output
 this is the third and it should also be included in output
 this may contain other strings as well
 this line is second line to be included in output...
 this is the third should also be included in output
</code>```

The output is almost correct but it does not include the match text.

答:
This may not be the sharpest way (you may want to use regular expressions), but does output what you want:

```<code>sample_list = ['line1 this line a first line',
        'line1 this line is also considered as line one...',
        'line1 this line is the first line',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 this contain other strings',
        'line1 this may contain other strings as well',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 what the heck is it...'
        ]
output = []
text = str
line1 = ""
line2 = ""
line3 = ""
prevStart = ""
for text in sample_list:
    if prevStart == "":
        if text.startswith("line1"):
            prevStart = "line1"
            line1 = text
    elif prevStart == "line1":
        if text.startswith("line2"):
            prevStart ="line2"
            line2 = text
        elif text.startswith("line1"):
            line1 = text
            prevStart = "line1"
        else:
            prevStart = ""
    elif prevStart == "line2":
        if text.startswith("line3"):
            prevStart = ""
            line3 = text
        else:
            prevStart = ""
    if line1 != "" and line2 != "" and line3 != "":
        output.append(line1)
        output.append(line2)
        output.append(line3)
        line1 = ""
        line2 = ""
        line3 = ""

for line in output:
    print line
</code>```

Output for this code is:

```<code>line1 this line is the first line
line2 this line is second line to be included in output
line3 this should also be included in output
line1 this may contain other strings as well
line2 this line is second line to be included in output
line3 this should also be included in output
</code>```

Body:
I am working on python to extract certain string between match strings. These strings are generated from a list which is again generated dynamically by a separate python function. The list I am working on looks like this:-

sample_list = ['line1 this line a first line',
        'line1 this line is also considered as line one...',
        'line1 this line is the first line',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 this contain other strings',
        'line1 this may contain other strings as well',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 what the heck is it...'
        ]

The output I want is similar to this:-

line1 this line is the first line
line2 this line is second line to be included in output
line3 this should also be included in output
line1 this may contain other strings as well
line2 this line is second line to be included in output
line3 this should also be included in output

As you can see, I want to extract the text/lines which are starting as line1 and ending with line3 (up to line ending). The final output includes both the matching words (ie. line1 and line3).

The code I have tried is:-

# Convert list to string first
list_to_str = '\n'.join(sample_list)
# Get desired output
print(re.findall('\nline1(.*?)\nline2(.*?)\nline3($)', list_to_str, re.DOTALL))

This is what I am getting as an output ():-

[]

Any help is appreciated.

Edit1:-
I have done some work and found this nearest solution:-

matches = (re.findall(r"^line1(.*)\nline2(.*)\nline3(.*)$", list_to_str, re.MULTILINE))

for match in matches:
    print('\n'.join(match))

It gives me this output:-

 this line is the first line
 this line is second line to be included in output
 this is the third and it should also be included in output
 this may contain other strings as well
 this line is second line to be included in output...
 this is the third should also be included in output

The output is almost correct but it does not include the match text.

Body:
This may not be the sharpest way (you may want to use regular expressions), but does output what you want:

sample_list = ['line1 this line a first line',
        'line1 this line is also considered as line one...',
        'line1 this line is the first line',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 this contain other strings',
        'line1 this may contain other strings as well',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 what the heck is it...'
        ]
output = []
text = str
line1 = ""
line2 = ""
line3 = ""
prevStart = ""
for text in sample_list:
    if prevStart == "":
        if text.startswith("line1"):
            prevStart = "line1"
            line1 = text
    elif prevStart == "line1":
        if text.startswith("line2"):
            prevStart ="line2"
            line2 = text
        elif text.startswith("line1"):
            line1 = text
            prevStart = "line1"
        else:
            prevStart = ""
    elif prevStart == "line2":
        if text.startswith("line3"):
            prevStart = ""
            line3 = text
        else:
            prevStart = ""
    if line1 != "" and line2 != "" and line3 != "":
        output.append(line1)
        output.append(line2)
        output.append(line3)
        line1 = ""
        line2 = ""
        line3 = ""

for line in output:
    print line

Output for this code is:

line1 this line is the first line
line2 this line is second line to be included in output
line3 this should also be included in output
line1 this may contain other strings as well
line2 this line is second line to be included in output
line3 this should also be included in output


问:
how to redirect and seprate out the server response in php curl
i am working with cURL and got the API response in xml but browser in printing a single line whcih contain the url and a transaction id .any one can help me to seprate both and to load the url with out printing it ?</p>

答: Use string functions (preg_replace, str_replace) to parse value you need.


问:
Is it normal for COM RWC's created in STA thread to disconnect from the underlying COM object on thread termination?
First off, I want to make it clear that this is not a question on how to release COM objects under .Net.  It is a question about trying to understand an unexpected COM object release that is probably due to normal COM behavior, but I am unable to find a definitive explanation for the observed behavior and would appreciate a confirmation of the inferences that I am making based on some quotations presented later on.

I have noticed that when working with Excel via COM-Interop that the Excel instance will completely terminate, as one would hope, when the interop references are created in a secondary thread with the Apartmentstate set to ApartmentState.STA.   This occurs without taking any action to clear the reference count on the runtime callable wrappers (RCW's) either by explicitly calling for their release using Marshal.ReleaseCOMObject or by invoking the garbage collector (GC)  to clean up the objects in order for Excel to completely shutdown.  For those not familiar with working with Excel Interop, please be advised that it well known for not shutting down after being told to quit until all .Net COM references have been released.

My first thought was that GC had automatically run on thread completion. To see if this was true, I used Visual Studio's "Performance and Diagnostics" tool to monitor memory usage.

The above graphic, I first run the method that interacts with Excel on the UI thread and then on  a MTA thread.  It can be observed that the Excel process did not terminate until the GC was run to free the COM references.  Note that a GC marker is placed on the profiling chart.  Then I run the method twice on a STA thread.  It can be observed that the Excel process terminates without any additional action required and the Profiling chart indicates that the GC did not run after the thread that Excel was launched from had exited.  Also, if I attempt to access a reference created in the STA thread after it has terminated, a "COM object that has been separated from its underlying RCW cannot be used." exception is thrown.

At this point I thought that release of the Excel process was in some way related to the reclamation of the thread used to create the objects.  I ran the program executing the Excel method twice on a STA thread and recorded the results shown below.  It can be seen that all thread instances as well as the COM objects are listed as being alive throughout the life of the test.

In researching a COM object's lifetime, I found the following statement in Larry Osterman's blog entry "What are these “Threading Models” and why do I care?" that seems to explain why the .Net RCW's are disconnected from the underlying COM object.

A COM object’s lifetime is limited to the lifetime of the apartment that creates the object.  So if you create an object in an STA, then destroy the apartment (by calling CoUninitialize), all objects created in this apartment will be destroyed.

This statement implies that the STA COM apartment that is the controlling mechanism.  However, the only thing that I have found indicating the impact of Apartment lifetime on .Net objects is the following quotation from Chris Brumme's blog post "Apartments and Pumping in the CLR".

Our COM Interop layer ensures that we almost only ever call COM objects in the correct apartment and context. The one place where we violate COM rules is when the COM object’s apartment or context has been torn down. In that case, we will still call IUnknown::Release on the pUnk to try to recover its resources, even though this is strictly illegal.

So finally to my question:   Is what I have observed the result of the STA apartment  that was created for thread being destroyed when the thread execution ends and thus allowing the Excel process to terminate because there are no longer any objects holding references to it?

I originally stated that this is not a question on how to release COM objects in .Net.  However, I would appreciate any insights into possible negative effects of using this technique to do so.  It has worked without fail, but I am hesitant to use it when documented techniques are readily implemented.

The code presented below, is what I used to investigate this behavior.

```<code>Imports System
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Threading
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Imports System.Diagnostics

Public Class frmComRelease : Inherits Form
    Private launchedExcelProcesses As New System.Collections.Concurrent.ConcurrentDictionary(Of Process, ApartmentState) ' requires Proj Ref: System.ServiceModel.dll
    Private btnRunUI As Button
    Private btnRunMTA As Button
    Private btnRunSTA As Button
    Private btnRunGC As Button
    Private btnTryToAccessExcelReference As Button
    Private excelReference As Object
    Private processStatus As TextBox
    Private chkBxGrabReference As CheckBox
    Private grabReference As Boolean
    Private key As New Object

    Public Sub New()
        MyBase.New()
        Font = New Drawing.Font(Font.FontFamily, 12, Font.Style, Drawing.GraphicsUnit.Pixel)
        Width = 400 : Height = 350

        btnRunUI = AddButton("Run Excel On UI Thead", Nothing, AddressOf btnRunUI_Click)
        btnRunMTA = AddButton("Run Excel On MTA Thead", btnRunUI, AddressOf btnRunMTA_Click)
        btnRunSTA = AddButton("Run Excel On STA Thead", btnRunMTA, AddressOf btnRunSTA_Click)
        btnTryToAccessExcelReference = AddButton("Access Last Excel Reference", btnRunSTA, AddressOf btnTryToAccessExcelReference_Click)
        btnRunGC = AddButton("Run GC to free UI or MTA started Excel Process", btnTryToAccessExcelReference, AddressOf btnRunGC_Click)
        processStatus = New TextBox With {.Multiline = True, .Location = New System.Drawing.Point(5, btnRunGC.Bottom + 10), .Width = Me.ClientSize.Width - 10, .Anchor = AnchorStyles.Bottom Or AnchorStyles.Left Or AnchorStyles.Right Or AnchorStyles.Top, .ReadOnly = True, .ScrollBars = ScrollBars.Vertical}
        processStatus.Height = ClientSize.Height - processStatus.Top - 5
        Controls.Add(processStatus)
        chkBxGrabReference = New CheckBox() With {.Text = "Hold Excel Reference", .AutoCheck = True, .Location = New System.Drawing.Point(10 + btnRunMTA.Width, 5), .TextAlign = System.Drawing.ContentAlignment.MiddleLeft, .AutoSize = True}
        AddHandler chkBxGrabReference.CheckedChanged, AddressOf chkBxGrabReference_CheckedChanged
        Controls.Add(chkBxGrabReference)
        StartPosition = FormStartPosition.Manual
        Location = New Drawing.Point(500, 100)
    End Sub

    Private Sub chkBxGrabReference_CheckedChanged(sender As Object, e As EventArgs)
        SyncLock key
            grabReference = chkBxGrabReference.Checked
        End SyncLock
    End Sub

    Private Function AddButton(text As String, relativeTo As Control, clickHandler As EventHandler) As Button
        Dim btn As New Button() With {.Text = text, .Location = New System.Drawing.Point(5, If(relativeTo Is Nothing, 5, relativeTo.Bottom + 5)), .TextAlign = System.Drawing.ContentAlignment.MiddleLeft, .AutoSize = True}
        AddHandler btn.Click, clickHandler
        Controls.Add(btn)
        Return btn
    End Function

    Protected Overrides Sub OnClosed(e As EventArgs)
        MyBase.OnClosed(e)
        For Each p As Process In Me.launchedExcelProcesses.Keys
            p.Dispose()
        Next
    End Sub

    Private Sub btnTryToAccessExcelReference_Click(sender As Object, e As EventArgs)
        SyncLock key
            If excelReference IsNot Nothing Then
                Dim ptr As IntPtr
                Dim msg As String
                Try
                    ptr = Marshal.GetIUnknownForObject(excelReference)
                    Marshal.Release(ptr)
                    msg = "Sucessfully accessed reference"
                Catch ex As Exception
                    msg = ex.Message
                End Try
                excelReference = Nothing
                MessageBox.Show(msg)
            End If
        End SyncLock
    End Sub

    Private Sub btnRunUI_Click(sender As Object, e As EventArgs)
        ExcelWork()
    End Sub

    Private Sub btnRunMTA_Click(sender As Object, e As EventArgs)
        Dim t As New Thread(AddressOf ExcelWork)
        t.SetApartmentState(ApartmentState.MTA)
        t.Start()
    End Sub

    Private Sub btnRunSTA_Click(sender As Object, e As EventArgs)
        Dim t As New Thread(AddressOf ExcelWork)
        t.SetApartmentState(ApartmentState.STA)
        t.Start()
    End Sub

    Private Sub btnRunGC_Click(sender As Object, e As EventArgs)
        excelReference = Nothing
        Do
            GC.Collect()
            GC.WaitForPendingFinalizers()
        Loop While System.Runtime.InteropServices.Marshal.AreComObjectsAvailableForCleanup
    End Sub

    Private Sub ExcelWork()
        Dim app As Excel.Application = New Excel.Application()
        app.Visible = True
        PositionExcel(app)
        SyncLock key
            If grabReference Then excelReference = app
        End SyncLock

        Dim processId As Int32
        Dim threadID As Int32 = GetWindowThreadProcessId(app.Hwnd, processId)
        Dim proc As Process = Process.GetProcessById(processId)
        proc.EnableRaisingEvents = True
        Dim state As ApartmentState = Thread.CurrentThread.GetApartmentState()
        launchedExcelProcesses.TryAdd(proc, state)
        UpdateStatus(GetProcessStatusMessage(proc))
        AddHandler proc.Exited, AddressOf Process_Exited
        Dim wb As Excel.Workbook = app.Workbooks.Add()
        For Each cell As Excel.Range In DirectCast(wb.Worksheets.Item(1), Excel.Worksheet).Range("A1:H10")
            cell.Value2 = 10
        Next

        wb.Close(False)
        app.Quit()
        UpdateStatus(String.Format("Exiting {0} thread of Excel process [{1}]", state, proc.Id))
    End Sub

    Private Sub PositionExcel(app As Excel.Application)
        Dim r As System.Drawing.Rectangle = Me.Bounds
        ' Excel position/size measured in pts
        Dim pxTopt As Double
        Using g As Drawing.Graphics = CreateGraphics()
            pxTopt = 72.0 / g.DpiX
        End Using
        app.WindowState = Excel.XlWindowState.xlNormal
        app.Top = r.Top * pxTopt
        app.Left = (r.Right) * pxTopt
        app.Width = r.Width * pxTopt
        app.Height = r.Height * pxTopt
    End Sub

    Private Function GetProcessStatusMessage(process As Process) As String
        Dim state As ApartmentState
        launchedExcelProcesses.TryGetValue(process, state)
        Return String.Format("{3} - Excel process [{0}] {1} at {2}", process.Id, If(process.HasExited, "ended", "started"), If(process.HasExited, process.ExitTime, process.StartTime), state)
    End Function

    Private Sub UpdateStatus(msg As String)
        Invoke(New Action(Of String)(AddressOf processStatus.AppendText), msg & Environment.NewLine)
    End Sub

    Private Sub Process_Exited(sender As Object, e As EventArgs)
        Dim proc As Process = DirectCast(sender, Process)
        UpdateStatus(GetProcessStatusMessage(proc))
        Dim state As ApartmentState
        launchedExcelProcesses.TryRemove(proc, state)
        proc.Dispose()
        proc = Nothing
    End Sub

    <DllImport("user32.dll", SetLastError:=True)>
    Private Shared Function GetWindowThreadProcessId(ByVal hwnd As Int32, ByRef lpdwProcessId As Int32) As Int32
    End Function
End Class
</code>```

Edit: Additional info that may be of relevance:

Don Box; May 1997, Microsoft Systems Journal, Q&A ActiveX/COM

...By their nature, all objects live in a process. For an
  out-of-process server, this process is created dynamically by the
  Service Control Manager (SCM), based on the server’s implementation of
  main/WinMain. For outofproc servers, the server implementor is in
  complete control of when the process shuts down. The standard
  implementation of a server’s WinMain is to have the main thread of the
  process wait around until no objects have outstanding clients to
  service. This guarantees that the object’s "home" will remain alive as
  long as it is needed.

答:
I can't find an official source saying that CoUninitialize is called by .NET. However, I have found a few things. Below are some "stack traces" from the .NET Core source code. I was unable to find the corresponding .NET Framework source, but I expect it's not too much different than this. These aren't the only paths through this code, and these aren't all the cases where COM is initialized and uninitialized, but this should be enough to demonstrate that the CLR is designed to manage the COM framework implicitly.

CLR startup and shutdown

GetCLRRuntimeHost

CoreHost2::CreateObject

CoreHost2::Start

CorRuntimeHostBase::Start

InitializeEE

EnsureEEStarted

EEStartup

EEStartupHelper

SetupThread

Thread::PrepareApartmentAndContext

Thread::SetApartment

CoInitializeEx

CoreHost2::UnloadAppDomain

EEShutDown

EEShutDownProcForSTAThread

EEShutDownHelper

Thread::CoUninitialize

Thread::BaseCoUninitialize

CoUninitialize

Thread pool threads

ThreadpoolMgr::WorkerThreadStart

CoInitializeEx

CoUninitialize

IOCP threads

ThreadpoolMgr::CompletionPortThreadStart

CoInitializeEx

CoUninitialize

Here's something interesting to note. Thread:PrepareApartmentAndContext also registers an IInitializeSpy object. That object watches for the apartment to be shut down and calls ReleaseRCWsInCaches. That method is also called from a few other places. Somewhere down these rabbit holes, you'll find all the information you seek.

Body:
First off, I want to make it clear that this is not a question on how to release COM objects under .Net.  It is a question about trying to understand an unexpected COM object release that is probably due to normal COM behavior, but I am unable to find a definitive explanation for the observed behavior and would appreciate a confirmation of the inferences that I am making based on some quotations presented later on.

I have noticed that when working with Excel via COM-Interop that the Excel instance will completely terminate, as one would hope, when the interop references are created in a secondary thread with the Apartmentstate set to ApartmentState.STA.   This occurs without taking any action to clear the reference count on the runtime callable wrappers (RCW's) either by explicitly calling for their release using Marshal.ReleaseCOMObject or by invoking the garbage collector (GC)  to clean up the objects in order for Excel to completely shutdown.  For those not familiar with working with Excel Interop, please be advised that it well known for not shutting down after being told to quit until all .Net COM references have been released.

My first thought was that GC had automatically run on thread completion. To see if this was true, I used Visual Studio's "Performance and Diagnostics" tool to monitor memory usage.

The above graphic, I first run the method that interacts with Excel on the UI thread and then on  a MTA thread.  It can be observed that the Excel process did not terminate until the GC was run to free the COM references.  Note that a GC marker is placed on the profiling chart.  Then I run the method twice on a STA thread.  It can be observed that the Excel process terminates without any additional action required and the Profiling chart indicates that the GC did not run after the thread that Excel was launched from had exited.  Also, if I attempt to access a reference created in the STA thread after it has terminated, a "COM object that has been separated from its underlying RCW cannot be used." exception is thrown.

At this point I thought that release of the Excel process was in some way related to the reclamation of the thread used to create the objects.  I ran the program executing the Excel method twice on a STA thread and recorded the results shown below.  It can be seen that all thread instances as well as the COM objects are listed as being alive throughout the life of the test.

In researching a COM object's lifetime, I found the following statement in Larry Osterman's blog entry "What are these “Threading Models” and why do I care?" that seems to explain why the .Net RCW's are disconnected from the underlying COM object.

A COM object’s lifetime is limited to the lifetime of the apartment that creates the object.  So if you create an object in an STA, then destroy the apartment (by calling CoUninitialize), all objects created in this apartment will be destroyed.

This statement implies that the STA COM apartment that is the controlling mechanism.  However, the only thing that I have found indicating the impact of Apartment lifetime on .Net objects is the following quotation from Chris Brumme's blog post "Apartments and Pumping in the CLR".

Our COM Interop layer ensures that we almost only ever call COM objects in the correct apartment and context. The one place where we violate COM rules is when the COM object’s apartment or context has been torn down. In that case, we will still call IUnknown::Release on the pUnk to try to recover its resources, even though this is strictly illegal.

So finally to my question:   Is what I have observed the result of the STA apartment  that was created for thread being destroyed when the thread execution ends and thus allowing the Excel process to terminate because there are no longer any objects holding references to it?

I originally stated that this is not a question on how to release COM objects in .Net.  However, I would appreciate any insights into possible negative effects of using this technique to do so.  It has worked without fail, but I am hesitant to use it when documented techniques are readily implemented.

The code presented below, is what I used to investigate this behavior.

Imports System
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Threading
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Imports System.Diagnostics

Public Class frmComRelease : Inherits Form
    Private launchedExcelProcesses As New System.Collections.Concurrent.ConcurrentDictionary(Of Process, ApartmentState) ' requires Proj Ref: System.ServiceModel.dll
    Private btnRunUI As Button
    Private btnRunMTA As Button
    Private btnRunSTA As Button
    Private btnRunGC As Button
    Private btnTryToAccessExcelReference As Button
    Private excelReference As Object
    Private processStatus As TextBox
    Private chkBxGrabReference As CheckBox
    Private grabReference As Boolean
    Private key As New Object

    Public Sub New()
        MyBase.New()
        Font = New Drawing.Font(Font.FontFamily, 12, Font.Style, Drawing.GraphicsUnit.Pixel)
        Width = 400 : Height = 350

        btnRunUI = AddButton("Run Excel On UI Thead", Nothing, AddressOf btnRunUI_Click)
        btnRunMTA = AddButton("Run Excel On MTA Thead", btnRunUI, AddressOf btnRunMTA_Click)
        btnRunSTA = AddButton("Run Excel On STA Thead", btnRunMTA, AddressOf btnRunSTA_Click)
        btnTryToAccessExcelReference = AddButton("Access Last Excel Reference", btnRunSTA, AddressOf btnTryToAccessExcelReference_Click)
        btnRunGC = AddButton("Run GC to free UI or MTA started Excel Process", btnTryToAccessExcelReference, AddressOf btnRunGC_Click)
        processStatus = New TextBox With {.Multiline = True, .Location = New System.Drawing.Point(5, btnRunGC.Bottom + 10), .Width = Me.ClientSize.Width - 10, .Anchor = AnchorStyles.Bottom Or AnchorStyles.Left Or AnchorStyles.Right Or AnchorStyles.Top, .ReadOnly = True, .ScrollBars = ScrollBars.Vertical}
        processStatus.Height = ClientSize.Height - processStatus.Top - 5
        Controls.Add(processStatus)
        chkBxGrabReference = New CheckBox() With {.Text = "Hold Excel Reference", .AutoCheck = True, .Location = New System.Drawing.Point(10 + btnRunMTA.Width, 5), .TextAlign = System.Drawing.ContentAlignment.MiddleLeft, .AutoSize = True}
        AddHandler chkBxGrabReference.CheckedChanged, AddressOf chkBxGrabReference_CheckedChanged
        Controls.Add(chkBxGrabReference)
        StartPosition = FormStartPosition.Manual
        Location = New Drawing.Point(500, 100)
    End Sub

    Private Sub chkBxGrabReference_CheckedChanged(sender As Object, e As EventArgs)
        SyncLock key
            grabReference = chkBxGrabReference.Checked
        End SyncLock
    End Sub

    Private Function AddButton(text As String, relativeTo As Control, clickHandler As EventHandler) As Button
        Dim btn As New Button() With {.Text = text, .Location = New System.Drawing.Point(5, If(relativeTo Is Nothing, 5, relativeTo.Bottom + 5)), .TextAlign = System.Drawing.ContentAlignment.MiddleLeft, .AutoSize = True}
        AddHandler btn.Click, clickHandler
        Controls.Add(btn)
        Return btn
    End Function

    Protected Overrides Sub OnClosed(e As EventArgs)
        MyBase.OnClosed(e)
        For Each p As Process In Me.launchedExcelProcesses.Keys
            p.Dispose()
        Next
    End Sub

    Private Sub btnTryToAccessExcelReference_Click(sender As Object, e As EventArgs)
        SyncLock key
            If excelReference IsNot Nothing Then
                Dim ptr As IntPtr
                Dim msg As String
                Try
                    ptr = Marshal.GetIUnknownForObject(excelReference)
                    Marshal.Release(ptr)
                    msg = "Sucessfully accessed reference"
                Catch ex As Exception
                    msg = ex.Message
                End Try
                excelReference = Nothing
                MessageBox.Show(msg)
            End If
        End SyncLock
    End Sub

    Private Sub btnRunUI_Click(sender As Object, e As EventArgs)
        ExcelWork()
    End Sub

    Private Sub btnRunMTA_Click(sender As Object, e As EventArgs)
        Dim t As New Thread(AddressOf ExcelWork)
        t.SetApartmentState(ApartmentState.MTA)
        t.Start()
    End Sub

    Private Sub btnRunSTA_Click(sender As Object, e As EventArgs)
        Dim t As New Thread(AddressOf ExcelWork)
        t.SetApartmentState(ApartmentState.STA)
        t.Start()
    End Sub

    Private Sub btnRunGC_Click(sender As Object, e As EventArgs)
        excelReference = Nothing
        Do
            GC.Collect()
            GC.WaitForPendingFinalizers()
        Loop While System.Runtime.InteropServices.Marshal.AreComObjectsAvailableForCleanup
    End Sub

    Private Sub ExcelWork()
        Dim app As Excel.Application = New Excel.Application()
        app.Visible = True
        PositionExcel(app)
        SyncLock key
            If grabReference Then excelReference = app
        End SyncLock

        Dim processId As Int32
        Dim threadID As Int32 = GetWindowThreadProcessId(app.Hwnd, processId)
        Dim proc As Process = Process.GetProcessById(processId)
        proc.EnableRaisingEvents = True
        Dim state As ApartmentState = Thread.CurrentThread.GetApartmentState()
        launchedExcelProcesses.TryAdd(proc, state)
        UpdateStatus(GetProcessStatusMessage(proc))
        AddHandler proc.Exited, AddressOf Process_Exited
        Dim wb As Excel.Workbook = app.Workbooks.Add()
        For Each cell As Excel.Range In DirectCast(wb.Worksheets.Item(1), Excel.Worksheet).Range("A1:H10")
            cell.Value2 = 10
        Next

        wb.Close(False)
        app.Quit()
        UpdateStatus(String.Format("Exiting {0} thread of Excel process [{1}]", state, proc.Id))
    End Sub

    Private Sub PositionExcel(app As Excel.Application)
        Dim r As System.Drawing.Rectangle = Me.Bounds
        ' Excel position/size measured in pts
        Dim pxTopt As Double
        Using g As Drawing.Graphics = CreateGraphics()
            pxTopt = 72.0 / g.DpiX
        End Using
        app.WindowState = Excel.XlWindowState.xlNormal
        app.Top = r.Top * pxTopt
        app.Left = (r.Right) * pxTopt
        app.Width = r.Width * pxTopt
        app.Height = r.Height * pxTopt
    End Sub

    Private Function GetProcessStatusMessage(process As Process) As String
        Dim state As ApartmentState
        launchedExcelProcesses.TryGetValue(process, state)
        Return String.Format("{3} - Excel process [{0}] {1} at {2}", process.Id, If(process.HasExited, "ended", "started"), If(process.HasExited, process.ExitTime, process.StartTime), state)
    End Function

    Private Sub UpdateStatus(msg As String)
        Invoke(New Action(Of String)(AddressOf processStatus.AppendText), msg & Environment.NewLine)
    End Sub

    Private Sub Process_Exited(sender As Object, e As EventArgs)
        Dim proc As Process = DirectCast(sender, Process)
        UpdateStatus(GetProcessStatusMessage(proc))
        Dim state As ApartmentState
        launchedExcelProcesses.TryRemove(proc, state)
        proc.Dispose()
        proc = Nothing
    End Sub

    <DllImport("user32.dll", SetLastError:=True)>
    Private Shared Function GetWindowThreadProcessId(ByVal hwnd As Int32, ByRef lpdwProcessId As Int32) As Int32
    End Function
End Class

Edit: Additional info that may be of relevance:

Don Box; May 1997, Microsoft Systems Journal, Q&A ActiveX/COM

...By their nature, all objects live in a process. For an
  out-of-process server, this process is created dynamically by the
  Service Control Manager (SCM), based on the server’s implementation of
  main/WinMain. For outofproc servers, the server implementor is in
  complete control of when the process shuts down. The standard
  implementation of a server’s WinMain is to have the main thread of the
  process wait around until no objects have outstanding clients to
  service. This guarantees that the object’s "home" will remain alive as
  long as it is needed.

ContentLicense: CC BY-SA 4.0


问:
.slideDown() not working on absolute positioned div
https://jsfiddle.net/8mfho6ns/

Can someone tell me why the .slideDown() does not show the effect when displaying the .cart-dropdown div?  I am assuming it's due to the absolute position, as it works if I remove that.

Is it possible to use .slideDown on an absolute positioned element?

答: Use min-height instead height.  Height is required for effect.


问:
How to get input values to save to variable in Laravel
Kind of confused about how to capture values as an when they are saved to DB. This is laravel 5.4

In the app\Http\Controllers\Auth, I want to capture the input values that are being saved to the DB.

```<code>protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged.

    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

     $name = $data['name'];

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.
}
</code>```

The reason why I want to capture is because I want to send a curl request with the captured input data to a third party application as soon as a user is created.

Thank you.

答:
Instead of returning created User instance do this:

```<code>$user = User::create([
    'name' => $data['name'],
    'username' => $data['username'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
]);

// Do stuff here
$name = $user->name;

return $user;
</code>```

Body:
Kind of confused about how to capture values as an when they are saved to DB. This is laravel 5.4

In the app\Http\Controllers\Auth, I want to capture the input values that are being saved to the DB.

protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged.

    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

     $name = $data['name'];

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.
}

The reason why I want to capture is because I want to send a curl request with the captured input data to a third party application as soon as a user is created.

Thank you.

Body:
Instead of returning created User instance do this:

$user = User::create([
    'name' => $data['name'],
    'username' => $data['username'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
]);

// Do stuff here
$name = $user->name;

return $user;