问:
querying the graph api with curl
I want to check how to handle the access_token. So, I use curl to perform the following queries:

```<code>curl -X POST https://graph.facebook.com/oauth/access_token -d "client_id=<appId>&client_secret=<secret>&grant_type=client_credentials&redirect_uri="
</code>```

It returns a value for access_token.

Then, I'd like to get the list of my friends:

```<code>curl -X POST https://graph.facebook.com/me/friends -d "access_token=<token>"
</code>```

It returns this error:

```<code>{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
</code>```

Any hints ?

答:
The easy way is to use graph API explorer, go there and get and acces token with your facebook developer account:

Generate a Basic User Access Token

When you get to building your own app, you'll need to learn about
  access tokens and how to generate them using Facebook Login, but for
  now, we can get one really quickly through the Graph API Explorer:

```<code>Click on the Get Token button in the top right of the Explorer.
Choose the option Get User Access Token.
In the following dialog don't check any boxes, just click the blue Get Access Token button.
You'll see a Facebook Login Dialog, click **OK" here to proceed.
</code>```

You can use the graph api explorer as curl, but if you want to try it with a real curl the sintaxis is as follows for last api v2.8:

```<code>curl -i -H 'Authorization: Bearer YOUR_ACCES_TOKEN' -XGET 'https://graph.facebook.com/v2.8/me'
</code>```

in my case:

```<code>toni@MBP-de-Antonio  ~  curl -i -H 'Authorization: Bearer MY-ACCES_TOKEN' -XGET 'https://graph.facebook.com/v2.8/me'
HTTP/1.1 200 OK
x-app-usage: {"call_count":2,"total_cputime":3,"total_time":3}
Expires: Sat, 01 Jan 2000 00:00:00 GMT
x-fb-trace-id: BnLv25AHTjq
facebook-api-version: v2.8
Content-Type: application/json; charset=UTF-8
x-fb-rev: 2929740
Cache-Control: private, no-cache, no-store, must-revalidate
Pragma: no-cache
ETag: "39875e94193dcd62dcbbf583fc0008c110820a6c"
Access-Control-Allow-Origin: *
X-FB-Debug: fvO9W8Bfl+BihEy/3aZyzOiMrXOkrbK8q1I3Xk2wYnI7sSujZNC6vQzR4RoTWK7K3Hx6EdzoE2kZ/aWhsXe4OA==
Date: Sat, 01 Apr 2017 06:55:52 GMT
Connection: keep-alive
Content-Length: 61

{"name":"Antonio Juan Querol Giner","id":"10204458008519686"}%
</code>```

Title: querying the graph api with curl

Body:
I want to check how to handle the access_token. So, I use curl to perform the following queries:

curl -X POST https://graph.facebook.com/oauth/access_token -d "client_id=<appId>&client_secret=<secret>&grant_type=client_credentials&redirect_uri="

It returns a value for access_token.

Then, I'd like to get the list of my friends:

curl -X POST https://graph.facebook.com/me/friends -d "access_token=<token>"

It returns this error:

{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}

Any hints ?

Body:
The easy way is to use graph API explorer, go there and get and acces token with your facebook developer account:

Generate a Basic User Access Token

When you get to building your own app, you'll need to learn about
  access tokens and how to generate them using Facebook Login, but for
  now, we can get one really quickly through the Graph API Explorer:

Click on the Get Token button in the top right of the Explorer.
Choose the option Get User Access Token.
In the following dialog don't check any boxes, just click the blue Get Access Token button.
You'll see a Facebook Login Dialog, click **OK" here to proceed.

You can use the graph api explorer as curl, but if you want to try it with a real curl the sintaxis is as follows for last api v2.8:

curl -i -H 'Authorization: Bearer YOUR_ACCES_TOKEN' -XGET 'https://graph.facebook.com/v2.8/me'

in my case:

toni@MBP-de-Antonio  ~  curl -i -H 'Authorization: Bearer MY-ACCES_TOKEN' -XGET 'https://graph.facebook.com/v2.8/me'
HTTP/1.1 200 OK
x-app-usage: {"call_count":2,"total_cputime":3,"total_time":3}
Expires: Sat, 01 Jan 2000 00:00:00 GMT
x-fb-trace-id: BnLv25AHTjq
facebook-api-version: v2.8
Content-Type: application/json; charset=UTF-8
x-fb-rev: 2929740
Cache-Control: private, no-cache, no-store, must-revalidate
Pragma: no-cache
ETag: "39875e94193dcd62dcbbf583fc0008c110820a6c"
Access-Control-Allow-Origin: *
X-FB-Debug: fvO9W8Bfl+BihEy/3aZyzOiMrXOkrbK8q1I3Xk2wYnI7sSujZNC6vQzR4RoTWK7K3Hx6EdzoE2kZ/aWhsXe4OA==
Date: Sat, 01 Apr 2017 06:55:52 GMT
Connection: keep-alive
Content-Length: 61

{"name":"Antonio Juan Querol Giner","id":"10204458008519686"}%


来源: stackexchange

问:
Obtaining data from jqgrid on mouseover
I'm trying to do a mouseover for the jquery and when the mouse is hovered over a certain row I can get the id from that row and populate information and display an image.  However, I have been having the hardest time trying to do so.

Here is what I want to happen

Just like in the onSelectRow where I obtain the data using the following code

```<code>var ret = $('#list').jqGrid('getRowData', Id);
</code>```

I want to use when I do a mouseover.  However, I don't see a way of doing this.  I tried the following under gridComplete

```<code>gridComplete: function() {'.jqgrow').mouseover(function(e) {
 var rowId = $('.jqgrow').parent(tr:first).attr('id');
 alert("You rolled over " + rowId.Id);
});
}
</code>```

but it only gave me the ide number of the row of that table inside the jqgrid and I need the data from that row instead.

For instance, in my data I have Id, FirstName, LastName, FullName, Title, SortID

I would like to present a picture on the right side of my HTML page when hovered over certain rows by passing the Id to the HTML page, and querying through an array.  If I can some how get the actual Id that's within my dataset I can do the rest.

Any help would be lovely.

I have given the entire code of my jqGrid at the bottom for reference.

```<code>jQuery("#list").jqGrid({
url: '/Providers/DynamicGridData/',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'LastName', 'FirstName', 'FullName', 'Title', 'Url', 'SortId'],
colModel: [
{ name: 'Id', index: 'Id', width: 30, align: 'left', hidden: true },
{ name: 'LastName', index: 'LastName', width: 30, align: 'left', hidden: true },
{ name: 'FirstName', index: 'FirstName', width: 30, align: 'left', hidden: true },
{ name: 'FullName', index: 'FullName', width: 100, align: 'left' },
/*{ name: 'FirstName', index: 'FirstName', width: 100, align: 'left' },*/
{name: 'Title', index: 'Title', width: 200, align: 'left' },
{ name: 'Url', index: 'Url', width: 30, align: 'left', hidden: true },
{ name: 'SortId', index: 'SortId', width: 30, align: 'left', hidden: true}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
scrollOffset: 0,
width: '425',
altRows: 'true',
altClass: 'ui-priority-secondary',
autowidth: 'true',
height: '300',
altRows: 'true',
altClass: 'ui-priority-secondary',
viewrecords: true,
caption: 'Clinical Providers',
onSelectRow: function() {
var Id = $("#list").jqGrid('getGridParam', 'selrow');
if (Id) {
var ret = $('#list').jqGrid('getRowData', Id);
var url = ret.Url;
url.split(' ').join('');
//alert("id=" + ret.Id + "FullName=" + ret.FullName + "...");
window.location = "/" + url;
}
else { alert("Please select a row"); }
},
gridComplete: function() {
$('.jqgrow').mouseover(function(e) {
var rowId = $('.jqgrow').
alert("You rolled over " + rowId.Id);
});
}
});
</code>```

答:
I'm trying this code and it works fine:</p>

```<code>gridComplete: function() {
    $('.jqgrow').mouseover(function(e) {
        var rowId = $(this).attr('id');
        alert('You rolled over ' + rowId);
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Obtaining data from jqgrid on mouseover

Body:
I'm trying to do a mouseover for the jquery and when the mouse is hovered over a certain row I can get the id from that row and populate information and display an image.  However, I have been having the hardest time trying to do so.

Here is what I want to happen

Just like in the onSelectRow where I obtain the data using the following code

var ret = $('#list').jqGrid('getRowData', Id);

I want to use when I do a mouseover.  However, I don't see a way of doing this.  I tried the following under gridComplete

gridComplete: function() {'.jqgrow').mouseover(function(e) {
 var rowId = $('.jqgrow').parent(tr:first).attr('id');
 alert("You rolled over " + rowId.Id);
});
}

but it only gave me the ide number of the row of that table inside the jqgrid and I need the data from that row instead.

For instance, in my data I have Id, FirstName, LastName, FullName, Title, SortID

I would like to present a picture on the right side of my HTML page when hovered over certain rows by passing the Id to the HTML page, and querying through an array.  If I can some how get the actual Id that's within my dataset I can do the rest.

Any help would be lovely.

I have given the entire code of my jqGrid at the bottom for reference.

jQuery("#list").jqGrid({
url: '/Providers/DynamicGridData/',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'LastName', 'FirstName', 'FullName', 'Title', 'Url', 'SortId'],
colModel: [
{ name: 'Id', index: 'Id', width: 30, align: 'left', hidden: true },
{ name: 'LastName', index: 'LastName', width: 30, align: 'left', hidden: true },
{ name: 'FirstName', index: 'FirstName', width: 30, align: 'left', hidden: true },
{ name: 'FullName', index: 'FullName', width: 100, align: 'left' },
/*{ name: 'FirstName', index: 'FirstName', width: 100, align: 'left' },*/
{name: 'Title', index: 'Title', width: 200, align: 'left' },
{ name: 'Url', index: 'Url', width: 30, align: 'left', hidden: true },
{ name: 'SortId', index: 'SortId', width: 30, align: 'left', hidden: true}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
scrollOffset: 0,
width: '425',
altRows: 'true',
altClass: 'ui-priority-secondary',
autowidth: 'true',
height: '300',
altRows: 'true',
altClass: 'ui-priority-secondary',
viewrecords: true,
caption: 'Clinical Providers',
onSelectRow: function() {
var Id = $("#list").jqGrid('getGridParam', 'selrow');
if (Id) {
var ret = $('#list').jqGrid('getRowData', Id);
var url = ret.Url;
url.split(' ').join('');
//alert("id=" + ret.Id + "FullName=" + ret.FullName + "...");
window.location = "/" + url;
}
else { alert("Please select a row"); }
},
gridComplete: function() {
$('.jqgrow').mouseover(function(e) {
var rowId = $('.jqgrow').
alert("You rolled over " + rowId.Id);
});
}
});

Body:
I'm trying this code and it works fine:

gridComplete: function() {
    $('.jqgrow').mouseover(function(e) {
        var rowId = $(this).attr('id');
        alert('You rolled over ' + rowId);
    });
}


问:
JNR UnsatisfiedLinkError
This question might be related to this and a ton other UnsatisfiedLinkError questions.

I'm trying to run the following code.

```<code>import jnr.ffi.LibraryLoader;
import jnr.ffi.types.pid_t;

/**
 * Gets the process ID of the current process, and that of its parent.
*/
public class Getpid {
    public interface LibC  {
        public @pid_t long getpid();
        public @pid_t long getppid();
    }

    public static void main(String[] args) {
        LibC libc = (LibC) LibraryLoader.create(LibC.class).load("c");

        System.out.println("pid=" + libc.getpid() + " parent pid=" + libc.getppid());
    }
}
</code>```

The code compiles correctly but refuses to run,

(compilation step)

```<code>javac -cp /usr/share/java/jnr-ffi.jar:. Getpid.java
</code>```

(running step)

```<code>java -cp /usr/share/java/jnr-ffi.jar:. Getpid
</code>```

While running I get this error.

答:
You need to install objective-web's asm.jar

and jjfi.jar

add those to your classpath and voila!

Compile with this:

```<code>javac -cp /usr/share/java/jnr-ffi.jar:.:/usr/lib/java/jffi.jar:/usr/lib/java/jffi-native.jar:/usr/share/java/objectweb-asm/asm.jar Getpid.java
</code>```

and run with this:

```<code>java -cp /usr/share/java/jnr-ffi.jar:.:/usr/lib/java/jffi.jar:/usr/lib/java/jffi-native.jar:/usr/share/java/objectweb-asm/asm.jar Getpid
</code>```

Title: JNR UnsatisfiedLinkError

Body:
This question might be related to this and a ton other UnsatisfiedLinkError questions.

I'm trying to run the following code.

import jnr.ffi.LibraryLoader;
import jnr.ffi.types.pid_t;

/**
 * Gets the process ID of the current process, and that of its parent.
*/
public class Getpid {
    public interface LibC  {
        public @pid_t long getpid();
        public @pid_t long getppid();
    }

    public static void main(String[] args) {
        LibC libc = (LibC) LibraryLoader.create(LibC.class).load("c");

        System.out.println("pid=" + libc.getpid() + " parent pid=" + libc.getppid());
    }
}

The code compiles correctly but refuses to run,

(compilation step)

javac -cp /usr/share/java/jnr-ffi.jar:. Getpid.java

(running step)

java -cp /usr/share/java/jnr-ffi.jar:. Getpid

While running I get this error.

Body:
You need to install objective-web's asm.jar

and jjfi.jar

add those to your classpath and voila!

Compile with this:

javac -cp /usr/share/java/jnr-ffi.jar:.:/usr/lib/java/jffi.jar:/usr/lib/java/jffi-native.jar:/usr/share/java/objectweb-asm/asm.jar Getpid.java

and run with this:

java -cp /usr/share/java/jnr-ffi.jar:.:/usr/lib/java/jffi.jar:/usr/lib/java/jffi-native.jar:/usr/share/java/objectweb-asm/asm.jar Getpid


问:
What is the use of ("*") in jquery
I am reading jQuery, i don't know why use <code>("*")</code> please explain it's helpful </p>

```<code><script>
    $(document).ready(function(){
        $("button").click(function(){
            $("*").hide();
        });
    });
</script>
</code>```

答:
* is a selector in jquery which select everything without any condition including html, head and body.

Here is an example explaining its usage.

$(document).ready(function(){
    $("button").click(function(){
        $("*").hide();
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Hello text
</div>
<button>Click Me to Hide everything</button></code>```

* selector can be used with elements that it selects all child elements within the specified element. without any condition

$(document).ready(function(){
    $("button").click(function(){
        $("div *").toggle();
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
border:0.5px solid red;
}</code>```

Hello text

  Here is a link

<button>Click Me to Hide/ Show elements inside the div</button>```

Title: What is the use of ("*") in jquery

Body: I am reading jQuery, i don't know why use ("*") please explain it's helpful

Body:
* is a selector in jquery which select everything without any condition including html, head and body.

Here is an example explaining its usage.

$(document).ready(function(){
    $("button").click(function(){
        $("*").hide();
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Hello text
</div>
<button>Click Me to Hide everything</button>

* selector can be used with elements that it selects all child elements within the specified element. without any condition

$(document).ready(function(){
    $("button").click(function(){
        $("div *").toggle();
    });
});

div{
border:0.5px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p>Hello text</p>
  <a>Here is a link </a>
</div>

<button>Click Me to Hide/ Show elements inside the div</button>


问:
How to create TCPDF HTML table with variable row paddings
I'm trying to create an HTML table in TCPDF, with few rows having grater space between rows (padding), and others having smaller padding.

```<code>$html = '<table border="0" cellpadding="6">
        <tr>
            <td style="width="52%">' . lang('ticket_name') . '</td>
            <td style="width="18%">' . lang('ticket_price') . '</td>
            <td style="width="12%">' . lang('quantity') . '</td>
            <td style="width="18%">' . lang('total') . '</td>
        </tr>
    <tr>
            <td style="padding: 10px">' . $item['name'] . '</td>
            <td style="padding: 10px">' . $item['unit_price'] . '</td>
            <td style="padding: 10px">' . $item['quantity'] . '</td>
            <td style="padding: 10px">' . $item['row_total'] . '</td>
        </tr>
        <tr>
            <td style="text-align:right" colspan="3">' . lang('price_basis') . ': </td>
            <td>' . $totals['total_before_tax'] . '</td>
        </tr>
            <tr>
            <td style="text-align:right" colspan="3">' . 'Ukupni popust' . ': </td>
            <td>' . $totals['total_discount'] . '</td>
        </tr>
            <tr>
            <td style="text-align:right" colspan="3">' . 'Sveukupno' . ': </td>
            <td>' . $totals['grand_total'] . '</td>
        </tr>
    </table>';
$pdf->writeHTML($html, $linebreak = true, $fill = false, $reseth = true, $cell = false, $align = '');
</code>```

As you can see, I have a cellpadding attribute in the table tag, which is working fine, but I want to have a different padding in the second row.
Padding style obviously isn't working on 'td' nor on 'tr' tags.

I know it can be done with two separate tables with different cellpaddings, but it seems pretty wrong. There must be another way.

答:
TCPDF doesn't support all CSS attributes, for example TCPDF doesn't support padding and margin attributes.
You can simulate paddings by inner table:

```<code><tr>
 <td>
  <table><tr>
   <td style="width:10px;"></td>
   <td>' . $item['name'] . '</td>
   <td style="width:10px;"></td>
  </tr></table>
 </td>
</tr>
</code>```

Or you can use different tables with different cellpadding for each row:

```<code><table border="0" cellpadding="6">
 <tr>
  <td>' . lang('ticket_name') . '</td>
  <td>' . lang('ticket_price') . '</td>
  <td>' . lang('quantity') . '</td>
  <td>' . lang('total') . '</td>
 </tr>
</table>
<table border="0" cellpadding="5">
 <tr>
  <td>' . $item['name'] . '</td>
  <td>' . $item['unit_price'] . '</td>
  <td>' . $item['quantity'] . '</td>
  <td>' . $item['row_total'] . '</td>
 </tr>
</table>
</code>```

Body:
I'm trying to create an HTML table in TCPDF, with few rows having grater space between rows (padding), and others having smaller padding.

$html = '

            ' . lang('ticket_name') . '
            ' . lang('ticket_price') . '
            ' . lang('quantity') . '
            ' . lang('total') . '

            ' . $item['name'] . '
            ' . $item['unit_price'] . '
            ' . $item['quantity'] . '
            ' . $item['row_total'] . '

            ' . lang('price_basis') . ':
            ' . $totals['total_before_tax'] . '

            ' . 'Ukupni popust' . ':
            ' . $totals['total_discount'] . '

            ' . 'Sveukupno' . ':
            ' . $totals['grand_total'] . '

';
$pdf->writeHTML($html, $linebreak = true, $fill = false, $reseth = true, $cell = false, $align = '');

As you can see, I have a cellpadding attribute in the table tag, which is working fine, but I want to have a different padding in the second row.
Padding style obviously isn't working on 'td' nor on 'tr' tags.

I know it can be done with two separate tables with different cellpaddings, but it seems pretty wrong. There must be another way.

Body:
TCPDF doesn't support all CSS attributes, for example TCPDF doesn't support padding and margin attributes.
You can simulate paddings by inner table:

<tr>
 <td>
  <table><tr>
   <td style="width:10px;"></td>
   <td>' . $item['name'] . '</td>
   <td style="width:10px;"></td>
  </tr></table>
 </td>
</tr>

Or you can use different tables with different cellpadding for each row:

<table border="0" cellpadding="6">
 <tr>
  <td>' . lang('ticket_name') . '</td>
  <td>' . lang('ticket_price') . '</td>
  <td>' . lang('quantity') . '</td>
  <td>' . lang('total') . '</td>
 </tr>
</table>
<table border="0" cellpadding="5">
 <tr>
  <td>' . $item['name'] . '</td>
  <td>' . $item['unit_price'] . '</td>
  <td>' . $item['quantity'] . '</td>
  <td>' . $item['row_total'] . '</td>
 </tr>
</table>


问:
How to manage fragments in backstack?
I am trying to manage fragments in a very simple way. I have created a utility class that's adding fragments to the backstack and when we press the back button, the previous fragment shows up. I am OK with that. But, when I am trying to clear out all the fragments, and show up the root fragment, I am not able to do so properly. Following is my utility class:

```<code>public class FragmentUtil {
private FragmentUtil() {
}

public static void animatedReplace(FragmentActivity activity, int containerId, Fragment fragment, Bundle args, boolean addToBackStack){
    FragmentTransaction transaction=activity.getSupportFragmentManager().beginTransaction();
    fragment.setArguments(args);
    if(addToBackStack){
        transaction.addToBackStack(fragment.getClass().getName());
    }
    transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_to_left,R.anim.slide_from_left,R.anim.slide_to_right);
    transaction.replace(containerId,fragment);
    transaction.commit();
}

public static void clearBackStackToHome(FragmentActivity activity){
    FragmentManager manager = activity.getSupportFragmentManager();
    manager.popBackStack(DashboardFragment.class.getName(),FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
</code>```

When I want to another fragment I just pass "true" for addToStack in animatedReplace method. When I want to clear the backstack I pass "false" and call the clearBackStackToHome method. Can anybody help me what I am doing wrong?

答:
Try this:

in your Utility class:

```<code>public void clearBackStack() {
    FragmentManager manager = activity.getSupportFragmentManager();
    if (manager.getBackStackEntryCount() > 0) {
        FragmentManager.BackStackEntry first = manager
                .getBackStackEntryAt(0);
        manager.popBackStack(first.getId(),
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
}
</code>```

make sure in your root/first fragment animatedReplace() you pass boolean addToBackStack = false .

so that it will not be cleared.

EDIT

To use it in OnBackPressed() overwrite onBackPressed() in your activity and add the following code:

```<code> @Override
    public void onBackPressed() {
        FragmentManager fm = getSupportFragmentManager();
        if (fm.getBackStackEntryCount() > 0) {
             FragmentManager.BackStackEntry first = fm
                    .getBackStackEntryAt(0);
            fm.popBackStack(first.getId(),
                    FragmentManager.POP_BACK_STACK_INCLUSIVE);
            Log.i("MainActivity", "popping backstack");
        } else {
             super.onBackPressed();
        }
    }
</code>```

Title: How to manage fragments in backstack?

Body:
I am trying to manage fragments in a very simple way. I have created a utility class that's adding fragments to the backstack and when we press the back button, the previous fragment shows up. I am OK with that. But, when I am trying to clear out all the fragments, and show up the root fragment, I am not able to do so properly. Following is my utility class:

public class FragmentUtil {
private FragmentUtil() {
}

public static void animatedReplace(FragmentActivity activity, int containerId, Fragment fragment, Bundle args, boolean addToBackStack){
    FragmentTransaction transaction=activity.getSupportFragmentManager().beginTransaction();
    fragment.setArguments(args);
    if(addToBackStack){
        transaction.addToBackStack(fragment.getClass().getName());
    }
    transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_to_left,R.anim.slide_from_left,R.anim.slide_to_right);
    transaction.replace(containerId,fragment);
    transaction.commit();
}

public static void clearBackStackToHome(FragmentActivity activity){
    FragmentManager manager = activity.getSupportFragmentManager();
    manager.popBackStack(DashboardFragment.class.getName(),FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}

When I want to another fragment I just pass "true" for addToStack in animatedReplace method. When I want to clear the backstack I pass "false" and call the clearBackStackToHome method. Can anybody help me what I am doing wrong?

Body:
Try this:

in your Utility class:

public void clearBackStack() {
    FragmentManager manager = activity.getSupportFragmentManager();
    if (manager.getBackStackEntryCount() > 0) {
        FragmentManager.BackStackEntry first = manager
                .getBackStackEntryAt(0);
        manager.popBackStack(first.getId(),
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
}

make sure in your root/first fragment animatedReplace() you pass boolean addToBackStack = false .

so that it will not be cleared.

EDIT

To use it in OnBackPressed() overwrite onBackPressed() in your activity and add the following code:

 @Override
    public void onBackPressed() {
        FragmentManager fm = getSupportFragmentManager();
        if (fm.getBackStackEntryCount() > 0) {
             FragmentManager.BackStackEntry first = fm
                    .getBackStackEntryAt(0);
            fm.popBackStack(first.getId(),
                    FragmentManager.POP_BACK_STACK_INCLUSIVE);
            Log.i("MainActivity", "popping backstack");
        } else {
             super.onBackPressed();
        }
    }


问:
Objective-C Programming: Will Learning C and/or Smalltalk Help?
Objective-C is an object-oriented programming language that adds Smalltalk-style messaging to the C programming language. I understand that learning Smalltalk might be good in the same way that learning Lisp is good for one's knowledge, but I want to know if learning Smalltalk-specific concepts will help me to understand Objective-C more completely, given Smalltalk's role in its "origin story". If so, what specifically?

Assuming that one already knows C programming, what can we learn from Smalltalk? Obviously, there's a lot of concepts in Objective-C that just aren't in C (ie. messaging, interfaces, protocols, dynamic typing, delegation, reflection; it's object-oriented!) but are derived from Smalltalk.

Edit: I've added the C programming language to the question, as the general consensus is that learning C is a better use of one's time than learning Smalltalk (when it comes to programming in Objective-C).

答:
Disclaimer: I don't know Smalltalk.

I'm sure your Obj-C skills would benefit from learning Smalltalk, but in my opinion, your time would be much better spent learning C. As someone who learned Obj-C before delving into C, the concepts taken from Smalltalk are easy to pick up, the concepts taken from C are much more difficult.

ContentLicense: CC BY-SA 2.5


问:
Libgdx error on Android when taking screen shot
I created a game that has a button that will take a screen shot when clicked.

```<code>    ChangeListener changeListener = new ChangeListener() {

                    //take screenshot and share
                    if(actor.equals(shareBtn)){
                        byte[] pixels = ScreenUtils.getFrameBufferPixels(0, 0, Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), true);
                        Pixmap pixmap = new Pixmap(Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), Pixmap.Format.RGBA8888);
                        BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);
                        PixmapIO.writePNG(Gdx.files.external("screenShot.png"), pixmap);
                        pixmap.dispose();
                    }

 };
</code>```

When I run the game on pc there's no problem but when I run it on android I get this error (my phone has an external sd card).

```<code>com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: screenShot.png (External)

Caused by: java.io.FileNotFoundException: /storage/emulated/0/screenShot.png: open failed: EACCES (Permission denied)
</code>```

答:
Make sure you have added permission to write external storage in your manifest file, if you are targeting Android SDK<23 else take permission at run-time.</p>

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

Body:
I created a game that has a button that will take a screen shot when clicked.

    ChangeListener changeListener = new ChangeListener() {

                    //take screenshot and share
                    if(actor.equals(shareBtn)){
                        byte[] pixels = ScreenUtils.getFrameBufferPixels(0, 0, Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), true);
                        Pixmap pixmap = new Pixmap(Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), Pixmap.Format.RGBA8888);
                        BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);
                        PixmapIO.writePNG(Gdx.files.external("screenShot.png"), pixmap);
                        pixmap.dispose();
                    }

 };

When I run the game on pc there's no problem but when I run it on android I get this error (my phone has an external sd card).

com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: screenShot.png (External)

Caused by: java.io.FileNotFoundException: /storage/emulated/0/screenShot.png: open failed: EACCES (Permission denied)

Body:
Make sure you have added permission to write external storage in your manifest file, if you are targeting Android SDK<23 else take permission at run-time.

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


问:
How to do point-wise categorical crossentropy loss in Keras?
I have a network that produces a 4D output tensor where the value at each position in spatial dimensions (~pixel) is to be interpreted as the class probabilities for that position.  In other words, the output is (num_batches, height, width, num_classes).  I have labels of the same size where the real class is coded as one-hot.  I would like to calculate the categorical-crossentropy loss using this.

Problem #1: The K.softmax function expects a 2D tensor (num_batches, num_classes)

Problem #2: I'm not sure how the losses from each position should be combined.  Is it correct to reshape the tensor to (num_batches * height * width, num_classes) and then calling K.categorical_crossentropy on that?  Or rather, call K.categorical_crossentropy(num_batches, num_classes) height*width times and average the results?

答:
Found this issue to confirm my intuition.

In short : the softmax will take 2D or 3D inputs. If they are 3D keras will assume a shape like this (samples, timedimension, numclasses) and apply the softmax on the last one.  For some weird reasons, it doesnt do that for 4D tensors.

Solution : reshape your output to a sequence of pixels

```<code>reshaped_output = Reshape((height*width, num_classes))(output_tensor)
</code>```

Then apply your softmax

```<code>new_output = Activation('softmax')(reshaped_output)
</code>```

And then either you reshape your target tensors to 2D or you just reshape that last layer into (width, height, num_classes).

Otherwise, something I would try if I wasn't on my phone right now is to use a TimeDistributed(Activation('softmax')). But no idea if that would work... will try later

I hope this helps :-)

Body:
Found this issue to confirm my intuition.

In short : the softmax will take 2D or 3D inputs. If they are 3D keras will assume a shape like this (samples, timedimension, numclasses) and apply the softmax on the last one.  For some weird reasons, it doesnt do that for 4D tensors.

Solution : reshape your output to a sequence of pixels

reshaped_output = Reshape((height*width, num_classes))(output_tensor)

Then apply your softmax

new_output = Activation('softmax')(reshaped_output)

And then either you reshape your target tensors to 2D or you just reshape that last layer into (width, height, num_classes).

Otherwise, something I would try if I wasn't on my phone right now is to use a TimeDistributed(Activation('softmax')). But no idea if that would work... will try later

I hope this helps :-)

ContentLicense: CC BY-SA 4.0


问:
did facebook oauth/authorize get deprecated?
I have been authenticating user against facebook using an api call like

https://graph.facebook.com/oauth/authorize?client_id=715408518535970&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth%2Fecho&scope=email%2Cread_stream

this would redirect and there would be an access_token query parameter.
Now during the redirect, there is only a query parameter called code.

Has this method of authenticating been deprecated?

答:
Yes it is deprecated.
https://developers.facebook.com/docs/apps/changelog

[Oauth Access Token] Format - The response format of https://www.facebook.com/v2.3/oauth/access_token returned when you exchange a code for an access_token now return valid JSON instead of being URL encoded. The new format of this response is {"access_token": {TOKEN}, "token_type":{TYPE}, "expires_in":{TIME}}. We made this update to be compliant with section 5.1 of RFC 6749.


问:
How to generate auto increment ID and do not set to default when a program is closed and opened again in java?
I am generating the auto increment number as the code below.

```<code>public class CoachRegForm extends javax.swing.JFrame {

/**
 * Creates new form CoachRegForm
 */
   private static int counter = 10000;
    final private int coachId;

public CoachRegForm() {
    initComponents();
     coachId = counter++;
     String staffIDInString=new Integer(coachId).toString();
     CoachRegFormIDShowLab.setText(staffIDInString);
}
</code>```

It works within the system, but when I close the program and run again, it goes back to the default which is 10000.

Is there any method to carry the last number saved by the program to the next time I open the program?

答:
A good way to store some field value is Preferences: http://www.vogella.com/tutorials/JavaPreferences/article.html
You might also consider using an AtomicInteger to prevent problems with concurrency (within ONE multithreaded instance of your program) in future.

```<code>package preferences;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.prefs.Preferences;

public class PrefsAutoinc {
    private Preferences prefs;
    private static final String AI_SETTING_ID = "autoincrement";

    public void testPrefs() {
        prefs = Preferences.userRoot().node(this.getClass().getName());

        AtomicInteger autoinc = new AtomicInteger(prefs.getInt(AI_SETTING_ID, 0));

        System.out.println("last saved value: " + autoinc);

        System.out.println("next: " + autoinc.incrementAndGet());
        System.out.println("next: " + autoinc.incrementAndGet());

        prefs.putInt(AI_SETTING_ID, autoinc.get());
    }

    public static void main(String[] args) {
        PrefsAutoinc test = new PrefsAutoinc();
        test.testPrefs();
    }
}
</code>```

Of course if your program uses a database in any other way, then storing autoincrement value in database would be a better choice, as @javaguy suggests.

However, if you plan to run multiple instances of your application at the same time and the uniqueness of id is a must, then using centralized db storage is the only choice. Because each instance would increment it's own copy of variable and then save it in preferences, some values would be lost.

Body:
I am generating the auto increment number as the code below.

public class CoachRegForm extends javax.swing.JFrame {

/**
 * Creates new form CoachRegForm
 */
   private static int counter = 10000;
    final private int coachId;

public CoachRegForm() {
    initComponents();
     coachId = counter++;
     String staffIDInString=new Integer(coachId).toString();
     CoachRegFormIDShowLab.setText(staffIDInString);
}

It works within the system, but when I close the program and run again, it goes back to the default which is 10000.

Is there any method to carry the last number saved by the program to the next time I open the program?

Body:
A good way to store some field value is Preferences: http://www.vogella.com/tutorials/JavaPreferences/article.html
You might also consider using an AtomicInteger to prevent problems with concurrency (within ONE multithreaded instance of your program) in future.

package preferences;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.prefs.Preferences;

public class PrefsAutoinc {
    private Preferences prefs;
    private static final String AI_SETTING_ID = "autoincrement";

    public void testPrefs() {
        prefs = Preferences.userRoot().node(this.getClass().getName());

        AtomicInteger autoinc = new AtomicInteger(prefs.getInt(AI_SETTING_ID, 0));

        System.out.println("last saved value: " + autoinc);

        System.out.println("next: " + autoinc.incrementAndGet());
        System.out.println("next: " + autoinc.incrementAndGet());

        prefs.putInt(AI_SETTING_ID, autoinc.get());
    }

    public static void main(String[] args) {
        PrefsAutoinc test = new PrefsAutoinc();
        test.testPrefs();
    }
}

Of course if your program uses a database in any other way, then storing autoincrement value in database would be a better choice, as @javaguy suggests.

However, if you plan to run multiple instances of your application at the same time and the uniqueness of id is a must, then using centralized db storage is the only choice. Because each instance would increment it's own copy of variable and then save it in preferences, some values would be lost.


问:
How to programmatically logon to a URL, keep the session, and browse around to different pages
I am working on small Java project to programmatically connect to a website with username/password, after login, browse to different links on the site to download some data. First, I need to connect to the website with username/password,
second, while I keep the session open, go to other links to download data.

How do I do this in Java?

Any help will be highly appreciated!

答:
Investigate with your browser how the web page submits the username/pass data? HTTP Form POST, Ajax, etc..? Use a plugin like Firebug to see network traffic.

You can use  URLConnection to create HTTP requests. You will neet to simulate a username/pass login and remember the cookie for use in consequent HTTP requests to simulate a session. Here are some examples: send HTTP POST request, get a cookie, send a cookie.


问:
data format in tensorflow for word2vec
I am using word2vec module of TF. I would like to read a data file which consists of multiple lines. Each line is made of multiple words. Each word in one line could be either source or target word.

I followed the tutorial, but I didn't find the so-called example to read customized data in

For the case of Skip-Gram modeling, we've actually already done this for you as an example in tensorflow/models/embedding/word2vec.py.

Should I change the code in word2vec_kernel.cc or use tf.TextLineReader. If so, how? Thanks!

答:
If the different lines of your input file represent different contexts then tensorflow/models/embedding/word2vec.py won't work for you as it wraps each line into a single giant sentence. You will need to rewrite the customer operator kernel here:

https://github.com/tensorflow/models/blob/master/tutorials/embedding/word2vec_kernels.cc

Below is an example of one of the functions that needs to change:

```<code>void NextExample(int *label, int *example) {
    while (true) {
        if (label_pos_ >= label_limit_) {
            ++total_words_processed_;
            ++sentence_index_;
            // check if we hit the end of the sentence
            if (sentence_index_ >= sentence_size_) {
                sentence_index_ = 0;
                ++corpus_idx_;
                // check if we hit the end of the corpus
                if (corpus_idx_ >= nrows_) {
                    ++current_epoch_;
                    corpus_idx_ = 0;
                }
                sentence_ = corpus_[corpus_idx_];

            }
            label_pos_ = std::max<int>(0, sentence_index_ - window_size_);
            label_limit_ =
                    std::min<int>(sentence_.size(), sentence_index_ + window_size_ + 1);
        }
        if (sentence_index_ != label_pos_) // add constraint that tokens are different
            break;
        ++label_pos_;
    }
    *example = sentence_[sentence_index_];
    *label = sentence_[label_pos_++];
}
</code>```

Title: data format in tensorflow for word2vec

Body:
If the different lines of your input file represent different contexts then tensorflow/models/embedding/word2vec.py won't work for you as it wraps each line into a single giant sentence. You will need to rewrite the customer operator kernel here:

https://github.com/tensorflow/models/blob/master/tutorials/embedding/word2vec_kernels.cc

Below is an example of one of the functions that needs to change:

void NextExample(int *label, int *example) {
    while (true) {
        if (label_pos_ >= label_limit_) {
            ++total_words_processed_;
            ++sentence_index_;
            // check if we hit the end of the sentence
            if (sentence_index_ >= sentence_size_) {
                sentence_index_ = 0;
                ++corpus_idx_;
                // check if we hit the end of the corpus
                if (corpus_idx_ >= nrows_) {
                    ++current_epoch_;
                    corpus_idx_ = 0;
                }
                sentence_ = corpus_[corpus_idx_];

            }
            label_pos_ = std::max<int>(0, sentence_index_ - window_size_);
            label_limit_ =
                    std::min<int>(sentence_.size(), sentence_index_ + window_size_ + 1);
        }
        if (sentence_index_ != label_pos_) // add constraint that tokens are different
            break;
        ++label_pos_;
    }
    *example = sentence_[sentence_index_];
    *label = sentence_[label_pos_++];
}


问:
VueJS with vue-router how to redirect to a server route
I am trying to redirect a user clicking logout link to the server rendered logout page. But as it stands with code below I just get redirected to the default path.

I have a server route set-up in flask as the following:

```<code>@app.route('/logout')
def logout():
    logout_user()
    return render_template('login.html')
</code>```

In vue I want to redirect the route so that I am directed to the server route.

```<code><template>
<a v-on:click="logout">Logout</a>
</template>
<script>
  export default {
    name: SomePage.vue
  },
  methods: {
    logout () {
      this.$router.replace('/logout')
      // I also tried .go('/logout')
    }
  }
 </script>
</code>```

Then do I need to set up a route in my router?

```<code>export default new Router {
  routes: {
     {
     path: '/'
     component: Default
     children: [
       {
       path: '/logout'
       // no component added here - is it needed?
       }
     ]
  }
}
</code>```

As I have already redirected to /logout, I am not sure how adding a component for this route would help as I just want to go to the base /logout and get the .html page returned by the server. Any ideas?

答:
Manipulating the window location via $router methods doesn't cause the browser to perform a full page reload, which is what you want in this case. You'll need to set the window location manually:

```<code>window.location.replace('/logout')
</code>```

Body:
I am trying to redirect a user clicking logout link to the server rendered logout page. But as it stands with code below I just get redirected to the default path.

I have a server route set-up in flask as the following:

@app.route('/logout')
def logout():
    logout_user()
    return render_template('login.html')

In vue I want to redirect the route so that I am directed to the server route.

<template>
Logout
</template>

Then do I need to set up a route in my router?

export default new Router {
  routes: {
     {
     path: '/'
     component: Default
     children: [
       {
       path: '/logout'
       // no component added here - is it needed?
       }
     ]
  }
}

As I have already redirected to /logout, I am not sure how adding a component for this route would help as I just want to go to the base /logout and get the .html page returned by the server. Any ideas?

Body:
Manipulating the window location via $router methods doesn't cause the browser to perform a full page reload, which is what you want in this case. You'll need to set the window location manually:

window.location.replace('/logout')


问:
JQuery Checking and Unchecking Checkboxes validations
I have some checkboxes in which one is select all and other child checkboxes are there

this is my html

```<code><label> Select All </label>
<input type="checkbox" name="all" checked="" id="parent">
<label> Child 1 </label>
<input type="checkbox" name="child" checked="" id="child">
<label> Child 2 </label>
<input type="checkbox" name="child" checked="" id="child">
</code>```

This is my JQuery Script of checking and unchecking

```<code> $('#parent').on('change', function () {
    $('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('change', function () {
$('#parent').prop('checked', false);
 $('.child').not(this).prop('checked', false);
$(this).prop('checked',true);
});
</code>```

The select all works fine but the ('.child') on change the parent is unchecked and the child remains checked, i cant uncheck

I need a way to for once any child is checked the parent should be unchecked along with all other child elements but also I should be able to select multiple children

答:
I think when you are de-selecting the child checkbox again the first function is excuting and making the parent as selected. so you can try this:</p>

```<code>$('#parent').on('change', function () {
    if($(this).is(":checked")){
        $('.child').prop('checked', $(this).prop('checked'));
    }else{
        $(this).prop('checked', false);
    }
});
</code>```

Body:
I have some checkboxes in which one is select all and other child checkboxes are there

this is my html

 Select All
<input type="checkbox" name="all" checked="" id="parent">
 Child 1
<input type="checkbox" name="child" checked="" id="child">
 Child 2
<input type="checkbox" name="child" checked="" id="child">

This is my JQuery Script of checking and unchecking

 $('#parent').on('change', function () {
    $('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('change', function () {
$('#parent').prop('checked', false);
 $('.child').not(this).prop('checked', false);
$(this).prop('checked',true);
});

The select all works fine but the ('.child') on change the parent is unchecked and the child remains checked, i cant uncheck

I need a way to for once any child is checked the parent should be unchecked along with all other child elements but also I should be able to select multiple children

Body:
I think when you are de-selecting the child checkbox again the first function is excuting and making the parent as selected. so you can try this:

$('#parent').on('change', function () {
    if($(this).is(":checked")){
        $('.child').prop('checked', $(this).prop('checked'));
    }else{
        $(this).prop('checked', false);
    }
});


问:
Facebook oauth reply with improperly formatted URL parameter
I am trying to authenticate my Facebook app against a user.

My application provides the following for starting the oauth authorization process:

https://graph.facebook.com/oauth/authorize?state=abc&response_type=code&client_id=292634984182123&redirect_uri=http://dev.foo.com:12020/app/c-rex/authorize-facebook-action/&scope=publish_pages,email&type=user_agent

Then the browser redirects to Facebook, asks for the permissions and redirects to the given redirection URL but with improper URL parameters:

http://dev.foo.com:12020/app/c-rex/authorize-facebook-action/?#state=abc&access_token=wqeqeqBAJmOBc25oYf64IaJBO8Y7k0pOgfo3q3PzoystyqvGPFeve5F8RxZCWtAVUyZB14YaWaZC4escFL69UxcZCHZBI2riqx88rUdKFx7riLPY83D1uY1Qtf9LJfZBuC1nv7sJH1BmIOXV0ZAP94jiaXV5M5tNU99lucTAZDZD&expires_in=6078

As you can see the query string is empty and instead the query strings after the '#' as URL fragment. It looks pretty weird...The URL would be correct if it would not contain the hashmark. Since fragment is irrelevant for the server I can not pick up the fragment from the URL inside my code.

Is this a Facebook bug?

答:
https://developers.facebook.com/docs/apps/changelog

[Oauth Access Token] Format - The response format of https://www.facebook.com/v2.3/oauth/access_token returned when you exchange a code for an access_token now return valid JSON instead of being URL encoded. The new format of this response is {"access_token": {TOKEN}, "token_type":{TYPE}, "expires_in":{TIME}}. We made this update to be compliant with section 5.1 of RFC 6749.


问:
How to name a thread?
How can I name this Thread?

```<code>    override val t: Thread = Thread {
        try {
            transmit()
        } catch (e: Exception) {
            println("Transmitter throws exception: $e")
        }
    }
</code>```

答:
You can create a named thread using the thread function from stdlib:

```<code>fun thread(
    start: Boolean = true,
    isDaemon: Boolean = false,
    contextClassLoader: ClassLoader? = null,
    name: String? = null,
    priority: Int = -1,
    block: () -> Unit
): Thread
</code>```

Just change your code:

```<code>override val t: Thread = thread(name = "transmitter thread") {
        try {
            transmit()
        } catch (e: Exception) {
            println("Transmitter throws exception: $e")
        }
    }
</code>```

In order to set the thread's name from within the thread, you can't use Thread's constructor that receives Runnable. You need to subclass the Thread class using the object expression:

```<code>val thread = object : Thread() {
  override fun run() {
       name = "thread with random name: ${Math.random()}"
  }
}
</code>```

Title: How to name a thread?

Body:
How can I name this Thread?

    override val t: Thread = Thread {
        try {
            transmit()
        } catch (e: Exception) {
            println("Transmitter throws exception: $e")
        }
    }

Body:
You can create a named thread using the thread function from stdlib:

fun thread(
    start: Boolean = true,
    isDaemon: Boolean = false,
    contextClassLoader: ClassLoader? = null,
    name: String? = null,
    priority: Int = -1,
    block: () -> Unit
): Thread

Just change your code:

override val t: Thread = thread(name = "transmitter thread") {
        try {
            transmit()
        } catch (e: Exception) {
            println("Transmitter throws exception: $e")
        }
    }

In order to set the thread's name from within the thread, you can't use Thread's constructor that receives Runnable. You need to subclass the Thread class using the object expression:

val thread = object : Thread() {
  override fun run() {
       name = "thread with random name: ${Math.random()}"
  }
}


问:
How to specify pod to node affinity in kubernetes
How can I configure a specific pod to run on a multi-node kubernetes cluster so that it would restrict the containers of the POD to a subset of the nodes.

E.g. let's say I have A, B, C three nodes running mu kubernetes cluster.

How to limit a Pod to run its containers only on A & B, and not on C?

答:
Firstly, you need to add label to nodes. You can refer to Nebril's answer of how to add label.

Then I recommend you to use the node affinity feature to constrain pods to nodes with particular labels. Here is an example.

```<code>apiVersion: v1
kind: Pod
metadata:
  name: with-node-affinity
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: node_type
            operator: In
            values:
            - foo
  containers:
  - name: with-node-affinity
    image: gcr.io/google_containers/pause:2.0
</code>```

Compared to nodeSelector, the affinity/anti-affinity feature greatly expands the types of constraints you can express.

For more detailed information about node affinity, you can refer to the following link: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/

Body:
Firstly, you need to add label to nodes. You can refer to Nebril's answer of how to add label.

Then I recommend you to use the node affinity feature to constrain pods to nodes with particular labels. Here is an example.

apiVersion: v1
kind: Pod
metadata:
  name: with-node-affinity
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: node_type
            operator: In
            values:
            - foo
  containers:
  - name: with-node-affinity
    image: gcr.io/google_containers/pause:2.0

Compared to nodeSelector, the affinity/anti-affinity feature greatly expands the types of constraints you can express.

For more detailed information about node affinity, you can refer to the following link: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/


问:
Get itunes link for app before submitting
I read in another post that you can submit the app without the binary but I based on what I have seen this is no longer possible. It seems you cannot submit without the binary and the binary is submitted through the application loader. Is there any other known way to get the itunes/app store link to my app before I submit the binary?</p>

答:
Once you create application in iTunes for submission under App Information tab click in View on App Store you will get app link.

Option 2: (In new update this is no longer available) you can create as below

```<code>https://itunes.apple.com/in/app/your-appname/id123456?mt=8
</code>```

Note : Just replace app name and numbers after /id with your app-id in above link

Body:
Once you create application in iTunes for submission under App Information tab click in View on App Store you will get app link.

Option 2: (In new update this is no longer available) you can create as below

https://itunes.apple.com/in/app/your-appname/id123456?mt=8

Note : Just replace app name and numbers after /id with your app-id in above link


问:
python object returned without \n and \t
How do I get a python object that is returned to acknowledge /n and /t in a string object that I have created?

I cannot use print and need to have my function assign a returned string object to output, and when I enter the output, it will print out as I want it to be.

Currently my output is this:

```<code>>>> output = function(input_data)
>>> output
'1\t2\t100\nALL\t100\n2\t1\t20\nALL\t20\nALL\t1\t20\n2\t100\nALL\t120\n'
</code>```

But I want it to be this:

```<code>>>> output = function(input_data)
>>> output
1   2   100
ALL 100
2   1   20
ALL 20
ALL 1   20
2   100
ALL 120
</code>```

答:
Despite the fact that both of your outputs are the same object, the only difference is that print(output) prints the __str__ method of output, which is usually more user-friendly. And typing just output prints the __repr__ method of output, which sometimes refers as the "raw" output.

However, there is a work around with this by creating a custom object, subclass of str, like this:

```<code>>>> class cusstr(str):
    def __repr__(self):
        return self.__str__()
>>> output = function(input_data) # your function...
>>> output = cusstr(output)
>>> output
1   2   100
ALL 100
2   1   20
ALL 20
ALL 1   20
2   100
ALL 120
</code>```

This object overrides the default __repr__ and make it return it's __str__ instead.

Body:
How do I get a python object that is returned to acknowledge /n and /t in a string object that I have created?

I cannot use print and need to have my function assign a returned string object to output, and when I enter the output, it will print out as I want it to be.

Currently my output is this:

>>> output = function(input_data)
>>> output
'1\t2\t100\nALL\t100\n2\t1\t20\nALL\t20\nALL\t1\t20\n2\t100\nALL\t120\n'

But I want it to be this:

>>> output = function(input_data)
>>> output
1   2   100
ALL 100
2   1   20
ALL 20
ALL 1   20
2   100
ALL 120

Body:
Despite the fact that both of your outputs are the same object, the only difference is that print(output) prints the __str__ method of output, which is usually more user-friendly. And typing just output prints the __repr__ method of output, which sometimes refers as the "raw" output.

However, there is a work around with this by creating a custom object, subclass of str, like this:

>>> class cusstr(str):
    def __repr__(self):
        return self.__str__()
>>> output = function(input_data) # your function...
>>> output = cusstr(output)
>>> output
1   2   100
ALL 100
2   1   20
ALL 20
ALL 1   20
2   100
ALL 120

This object overrides the default __repr__ and make it return it's __str__ instead.


答:
Check out the Apache HTTPClient, it can do all this for you.

Edit: Apache HTTPClient has authentication and cookie handling features included, which will save you a lot of work doing this yourself.

Title: How to programmatically logon to a URL, keep the session, and browse around to different pages

Body:
I am working on small Java project to programmatically connect to a website with username/password, after login, browse to different links on the site to download some data. First, I need to connect to the website with username/password,
second, while I keep the session open, go to other links to download data.

How do I do this in Java?

Any help will be highly appreciated!


问:
How to get a distribution app when using xcodebuild -exportArchive (Xcode8.3, Auto Signing)?
After update Xcode8.3, the options '-exportSigningIdentity', '-exportProvisioningProfile' and '-exportFormat' are removed from  'xcodebuild -exportArchive'.

When i try to get a distribution app, i get the error below:
 xcodebuild: error: invalid option '-exportProvisioningProfile'.

So how can i get distribution MyApp.ipa from MyApp.xcarchive, when the project has set Automatic Signing Enabled?

Automatic Signing

答:
Just replace this parameter :

-exportProvisioningProfile "MyProvisioningProfile"

with:

PROVISIONING_PROFILE_SPECIFIER="MyProvisioningProfile"

Hope it helps.


答:
You can use Thread's constructor, although due to how its arguments are ordered, you'll have to do this:</p>

```<code>override val t: Thread = Thread({
    try {
        transmit()
    } catch (e: Exception) {
        println("Transmitter throws exception: $e")
    }}, "Your name here")
}
</code>```

Title: How to name a thread?

Body:
You can use Thread's constructor, although due to how its arguments are ordered, you'll have to do this:

override val t: Thread = Thread({
    try {
        transmit()
    } catch (e: Exception) {
        println("Transmitter throws exception: $e")
    }}, "Your name here")
}


问:
ipython notebook clear all code
All I want to do is try some new codes in ipython notebook and I don't want to save it every time as its done automatically. Instead what I want is clear all the codes of ipython notebook along with reset of variables.

I want to do some coding and clear everything and start coding another set of codes without going to new python portion and without saving the current code.

Any shortcuts will be appreciated.

Note: I want to clear every cells code one time. All I want is an interface which appears when i create new python file, but I don't want to save my current code.

答: You can type dd to remove current selected cell. And if you continously press dd you can clean the screen.</p>

Title: ipython notebook clear all code


问:
JavaFX Event Handling Mystery - Code removed and events still handled?
I'm pretty experienced in OOP languages like Java and C#. Never messed with FX until now and started toying around with handling events out of boredom at the office.

My FX application is all written in one class. I imported the packages i wanted, including these two:

```<code>import javafx.event.ActionEvent;
import javafx.event.EventHandler;
</code>```

I implemented EventHandler interface with the type ActionEvent on my Main class declaration like so..

```<code>public class Main extends Application implements EventHandler<ActionEvent>
</code>```

I wrote an anonymous inner class on a button object to handle a click event like so..

```<code>btnButton.setOnAction(new EventHandler<ActionEvent>(){
        public void handle(ActionEvent event) {
            System.out.println("I got clicked");
        }
});
</code>```

It obviously worked like it should but then I ran an experiment. I deleted the two imports from above. I removed the "implements" part of the Main class declaration. This leaves my application without any reference to event handling. I then went back to my button object and wrote the event handler as a lambda expression like so...

```<code>btnButton.setOnAction(e -> System.out.println("I got touched"));
</code>```

And guess what? IT STILL WORKED!!! This is impossible.. Can someone explain how this still works after removing the required code for handling events? It's kind of funny and it's blowing my mind.

Thanks in advance for replies!

-KeplerIO

答:
You did not remove the required code for event handling:

```<code>public class Main extends Application implements EventHandler<ActionEvent>
</code>```

implementing EventHandler<ActionEvent> with the Main class was never required, since you were using a anonymus class as event handler anyways, instead of

```<code>btnButton.setOnAction(this);
</code>```

(Assuming this references the Main instance here)

Also one of the benefits of lambdas is that you can leave out the parameter types as long as the java compiler is still able to determine the interface you're implementing (and thereby the signature of the method) unambiguously.

In this case the setOnAction method is not overloaded and the java compiler can be sure the parameter is of type EventHandler<ActionEvent> and the signature of the method to implement is

```<code>public void handle(ActionEvent event)
</code>```

Therefore

```<code>btnButton.setOnAction((ActionEvent e) -> System.out.println("I got touched"));
</code>```

and even

```<code>btnButton.setOnAction(e -> System.out.println("I got touched"));
</code>```

"satisfies" the compiler.

This would be different, if the setOnAction method was overloaded Button

```<code>public void setOnAction(Consumer<Integer> x) { ... }
</code>```

In this case the compiler would need additional information to determine the method to use:

```<code>btnButton.setOnAction((Integer a) -> System.out.println("something"));
btnButton.setOnAction((ActionEvent a) -> System.out.println("something"));
btnButton.setOnAction((Consumer<Integer>) a -> System.out.println("something"));
btnButton.setOnAction((EventHandler<ActionEvent>) a -> System.out.println("something"));
</code>```

If you're interested in looking this up in the specification, here are the relevant sections:

JLS: 15. Expressions

             12. Method Invocation Expressions

                    Compile-Time Step 2: Determine Method Signature

                          5. Choosing the Most Specific Method

JLS: 15. Expressions

              27. Lambda Expressions

Body:
I'm pretty experienced in OOP languages like Java and C#. Never messed with FX until now and started toying around with handling events out of boredom at the office.

My FX application is all written in one class. I imported the packages i wanted, including these two:

import javafx.event.ActionEvent;
import javafx.event.EventHandler;

I implemented EventHandler interface with the type ActionEvent on my Main class declaration like so..

public class Main extends Application implements EventHandler<ActionEvent>

I wrote an anonymous inner class on a button object to handle a click event like so..

btnButton.setOnAction(new EventHandler<ActionEvent>(){
        public void handle(ActionEvent event) {
            System.out.println("I got clicked");
        }
});

It obviously worked like it should but then I ran an experiment. I deleted the two imports from above. I removed the "implements" part of the Main class declaration. This leaves my application without any reference to event handling. I then went back to my button object and wrote the event handler as a lambda expression like so...

btnButton.setOnAction(e -> System.out.println("I got touched"));

And guess what? IT STILL WORKED!!! This is impossible.. Can someone explain how this still works after removing the required code for handling events? It's kind of funny and it's blowing my mind.

Thanks in advance for replies!

-KeplerIO

Body:
You did not remove the required code for event handling:

public class Main extends Application implements EventHandler<ActionEvent>

implementing EventHandler<ActionEvent> with the Main class was never required, since you were using a anonymus class as event handler anyways, instead of

btnButton.setOnAction(this);

(Assuming this references the Main instance here)

Also one of the benefits of lambdas is that you can leave out the parameter types as long as the java compiler is still able to determine the interface you're implementing (and thereby the signature of the method) unambiguously.

In this case the setOnAction method is not overloaded and the java compiler can be sure the parameter is of type EventHandler<ActionEvent> and the signature of the method to implement is

public void handle(ActionEvent event)

Therefore

btnButton.setOnAction((ActionEvent e) -> System.out.println("I got touched"));

and even

btnButton.setOnAction(e -> System.out.println("I got touched"));

"satisfies" the compiler.

This would be different, if the setOnAction method was overloaded Button

public void setOnAction(Consumer<Integer> x) { ... }

In this case the compiler would need additional information to determine the method to use:

btnButton.setOnAction((Integer a) -> System.out.println("something"));
btnButton.setOnAction((ActionEvent a) -> System.out.println("something"));
btnButton.setOnAction((Consumer<Integer>) a -> System.out.println("something"));
btnButton.setOnAction((EventHandler<ActionEvent>) a -> System.out.println("something"));

If you're interested in looking this up in the specification, here are the relevant sections:

JLS: 15. Expressions

             12. Method Invocation Expressions

                    Compile-Time Step 2: Determine Method Signature

                          5. Choosing the Most Specific Method

JLS: 15. Expressions

              27. Lambda Expressions


问:
StaggeredGridLayoutManager and moving items
I have created a very simple project, displaying 28 images with StaggeredGridLayoutManager by recyclerview. but as I scroll the recyclerview it moves items for example from left to right or swap the column of left and right.

codes:

```<code>import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;

public class MainActivity extends Activity {

    String mImageDir;
    private RecyclerView mRecyclerView;
    private StaggeredGridLayoutManager mLayoutManager;

    MyRecyclerAdapter myRecyclerAdapter;
    List<ImageModel> mImageList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView)findViewById(R.id.recyclerview_rootview);
        mLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        mLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(false);
        mImageList = new ArrayList<ImageModel>();
        for (int i = 1; i < 29 ; i++) {
            ImageModel img = new ImageModel();
            img.setTitle("Image No " + i);
            int drawableResourceId = this.getResources().getIdentifier("image"+String.valueOf(i), "drawable", this.getPackageName());
            img.setResId(drawableResourceId);
            mImageList.add(img);

        }
        myRecyclerAdapter = new MyRecyclerAdapter(MainActivity.this,mImageList);
        mRecyclerView.setAdapter(myRecyclerAdapter);

    }

}
</code>```

And the adapter:

```<code>public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {

    private List<ImageModel> mItems;
    Context mContext;

    public MyRecyclerAdapter(Context context,List<ImageModel> objects) {
        mContext = context;
        mItems = objects;

    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        public  ImageView mImageView;
        public  TextView mTextView;
        public View rootView;
        public ViewHolder(View itemView) {
            super(itemView);
            rootView = itemView;
            mImageView =(ImageView)itemView.findViewById(R.id.image);
            mTextView =(TextView)itemView.findViewById(R.id.title);
        }
    }

    @Override
    public int getItemCount() {

        return mItems.size();
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        ImageModel item = mItems.get(position);
        Picasso.with(mContext).load(item.getResId()).into(holder.mImageView);
        holder.mTextView.setText(item.getTitle());
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
        LayoutInflater inflater =
                (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View convertView = inflater.inflate(R.layout.item, parent, false);
        return new ViewHolder(convertView);

    }

}
</code>```

and a sample moving item:

http://i.imgur.com/FUapm2K.gif?1

if you play (scroll up and down) you can discover more interesting animation :-)

How to prevent that and having stable layout like an ordinary listview?

Edit

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    ImageModel item = mItems.get(position);
    RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams)holder.mImageView.getLayoutParams();
    float ratio = item.getHeight()/item.getWidth();
    rlp.height = (int)(rlp.width * ratio);
    holder.mImageView.setLayoutParams(rlp);
    Picasso.with(mContext).load(item.getResId()).into(holder.mImageView);
    holder.mTextView.setText(item.getTitle());
}
</code>```

答:
Maybe this is a more efficient way:

```<code>mBrandRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if(newState == RecyclerView.SCROLL_STATE_IDLE){
                mBrandRecyclerView.invalidateItemDecorations();
            }
        }
    });
</code>```

For more information:
https://github.com/ibosong/CommonItemDecoration

Body:
I have created a very simple project, displaying 28 images with StaggeredGridLayoutManager by recyclerview. but as I scroll the recyclerview it moves items for example from left to right or swap the column of left and right.

codes:

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;

public class MainActivity extends Activity {

    String mImageDir;
    private RecyclerView mRecyclerView;
    private StaggeredGridLayoutManager mLayoutManager;

    MyRecyclerAdapter myRecyclerAdapter;
    List<ImageModel> mImageList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView)findViewById(R.id.recyclerview_rootview);
        mLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        mLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(false);
        mImageList = new ArrayList<ImageModel>();
        for (int i = 1; i < 29 ; i++) {
            ImageModel img = new ImageModel();
            img.setTitle("Image No " + i);
            int drawableResourceId = this.getResources().getIdentifier("image"+String.valueOf(i), "drawable", this.getPackageName());
            img.setResId(drawableResourceId);
            mImageList.add(img);

        }
        myRecyclerAdapter = new MyRecyclerAdapter(MainActivity.this,mImageList);
        mRecyclerView.setAdapter(myRecyclerAdapter);

    }

}

And the adapter:

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {

    private List<ImageModel> mItems;
    Context mContext;

    public MyRecyclerAdapter(Context context,List<ImageModel> objects) {
        mContext = context;
        mItems = objects;

    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        public  ImageView mImageView;
        public  TextView mTextView;
        public View rootView;
        public ViewHolder(View itemView) {
            super(itemView);
            rootView = itemView;
            mImageView =(ImageView)itemView.findViewById(R.id.image);
            mTextView =(TextView)itemView.findViewById(R.id.title);
        }
    }

    @Override
    public int getItemCount() {

        return mItems.size();
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        ImageModel item = mItems.get(position);
        Picasso.with(mContext).load(item.getResId()).into(holder.mImageView);
        holder.mTextView.setText(item.getTitle());
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
        LayoutInflater inflater =
                (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View convertView = inflater.inflate(R.layout.item, parent, false);
        return new ViewHolder(convertView);

    }

}

and a sample moving item:

http://i.imgur.com/FUapm2K.gif?1

if you play (scroll up and down) you can discover more interesting animation :-)

How to prevent that and having stable layout like an ordinary listview?

Edit

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    ImageModel item = mItems.get(position);
    RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams)holder.mImageView.getLayoutParams();
    float ratio = item.getHeight()/item.getWidth();
    rlp.height = (int)(rlp.width * ratio);
    holder.mImageView.setLayoutParams(rlp);
    Picasso.with(mContext).load(item.getResId()).into(holder.mImageView);
    holder.mTextView.setText(item.getTitle());
}

Body:
Maybe this is a more efficient way:

mBrandRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if(newState == RecyclerView.SCROLL_STATE_IDLE){
                mBrandRecyclerView.invalidateItemDecorations();
            }
        }
    });

For more information:
https://github.com/ibosong/CommonItemDecoration


问:
Error: Reference to non-static member function must be called (2)
I have a piece of code like this

```<code>class A {
public:

typedef int (A::*AFn)(int);
std::map<std::string, AFn> fm_;

A() {
    fm_.insert("fn1", fn);
}

int fn(int a) {
    return a;
}

};
</code>```

I get a compile time error saying error: reference to non-static member function must be called
fm_.insert("fn1", fn);

Why does this happen and how do I correct it?

答:
Since fn is a non-static member function, a lone fn is not a valid expression. The only thing you can do with non-qualified fn in this context is call it: fn(something). This is what the compiler is telling you.

If you want to obtain a pointer to member function A::fn, you have to explcitly use operator & and supply a qualified member name: &A::fn.

Body:
I have a piece of code like this

class A {
public:

typedef int (A::*AFn)(int);
std::map<std::string, AFn> fm_;

A() {
    fm_.insert("fn1", fn);
}

int fn(int a) {
    return a;
}

};

I get a compile time error saying error: reference to non-static member function must be called
fm_.insert("fn1", fn);

Why does this happen and how do I correct it?


问:
Shift planning with Linear Programming
The Modeling and Solving Linear Programming with R book has a nice example on planning shifts in Sec 3.7. I am unable to solve it with R. Also, I am not clear with the solution provided in the book.

Problem

A company has a emergency center which is working 24 hours a day. In
the table below, is detailed the minimal needs of employees for each of the
six shifts of four hours in which the day is divided.

```<code>     Shift    Employees
00:00 - 04:00    5
04:00 - 08:00    7
08:00 - 12:00   18
12:00 - 16:00   12
16:00 - 20:00   15
20:00 - 00:00   10
</code>```

R solution

I used the following to solve the above.

```<code>library(lpSolve)
obj.fun <- c(1,1,1,1,1,1)
constr <- c(1,1,0,0,0,0,
            0,1,1,0,0,0,
            0,0,1,1,0,0,
            0,0,0,1,1,0,
            0,0,0,0,1,1,
            1,0,0,0,0,1)
constr.dir <- rep(">=",6)
constr.val <-c (12,25,30,27,25,15)
day.shift <- lp("min",obj.fun,constr,constr.dir,constr.val,compute.sens = TRUE)
</code>```

And, I get the following result.

```<code>> day.shift$objval
[1] 1.666667
> day.shift$solution
[1] 0.000000 1.666667 0.000000 0.000000 0.000000 0.000000
</code>```

This is nowhere close to the numerical solution mentioned in the book.

Numerical solution

The total number of solutions required as per the numerical solution is 38. However, since the problem stated that, there is a defined minimum number of employees in every period, how can this solution be valid?

s1 5
s2 6
s3 12
s4 0
s5 15
s6 0

Title: Shift planning with Linear Programming

Body:
The Modeling and Solving Linear Programming with R book has a nice example on planning shifts in Sec 3.7. I am unable to solve it with R. Also, I am not clear with the solution provided in the book.

Problem

A company has a emergency center which is working 24 hours a day. In
the table below, is detailed the minimal needs of employees for each of the
six shifts of four hours in which the day is divided.

     Shift    Employees
00:00 - 04:00    5
04:00 - 08:00    7
08:00 - 12:00   18
12:00 - 16:00   12
16:00 - 20:00   15
20:00 - 00:00   10

R solution

I used the following to solve the above.

library(lpSolve)
obj.fun <- c(1,1,1,1,1,1)
constr <- c(1,1,0,0,0,0,
            0,1,1,0,0,0,
            0,0,1,1,0,0,
            0,0,0,1,1,0,
            0,0,0,0,1,1,
            1,0,0,0,0,1)
constr.dir <- rep(">=",6)
constr.val <-c (12,25,30,27,25,15)
day.shift <- lp("min",obj.fun,constr,constr.dir,constr.val,compute.sens = TRUE)

And, I get the following result.

> day.shift$objval
[1] 1.666667
> day.shift$solution
[1] 0.000000 1.666667 0.000000 0.000000 0.000000 0.000000

This is nowhere close to the numerical solution mentioned in the book.

Numerical solution

The total number of solutions required as per the numerical solution is 38. However, since the problem stated that, there is a defined minimum number of employees in every period, how can this solution be valid?

s1 5
s2 6
s3 12
s4 0
s5 15
s6 0

Body:
Your mistake is at the point where you initialize the variable constr, because you don't define it as a matrix. Second fault is your matrix itself. Just look at my example.

I was wondering why you didn't stick to the example in the book because I wanted to check my solution. Mine is based on that.

library(lpSolve)
obj.fun <- c(1,1,1,1,1,1)
constr <- matrix(c(1,0,0,0,0,1,
        1,1,0,0,0,0,
        0,1,1,0,0,0,
        0,0,1,1,0,0,
        0,0,0,1,1,0,
        0,0,0,0,1,1), ncol = 6, byrow = TRUE)
constr.dir <- rep(">=",6)
constr.val <-c (5,7,18,12,15,10)
day.shift <- lp("min",obj.fun,constr,constr.dir,constr.val,compute.sens = TRUE)

day.shift$objval
# [1] 38
day.shift$solution
# [1]  5 11  7  5 10  0

EDIT based on your question in the comments:

This is the distribution of the shifts on the periods:

shift | 0-4 | 4-8 | 8-12 | 12-16 | 16-20 | 20-24
---------------------------------------------------
20-4  | 5   | 5   |      |       |       |
0-8   |     | 11  | 11   |       |       |
4-12  |     |     | 7    | 7     |       |
8-16  |     |     |      | 5     | 5     |
12-20 |     |     |      |       | 10    | 10
18-24 |     |     |      |       |       |
----------------------------------------------------
sum   | 5   | 16  | 18   | 12    | 15    | 10
----------------------------------------------------
need  | 5   | 7   | 18   | 12    | 15    | 10
---------------------------------------------------


问:
How to play audio?
I am making a game with HTML5 and JavaScript.

How could I play game audio via JavaScript?

Title: How to play audio?

Body: new Audio('./file.mp3').play()


问:
Pager error in Kendo Grid(Nan-Nan of 1 items)
I am trying to create a Kendo grid with a list of student details. On click of the add button, the pager shows "Nan-Nan of 1 items".

@(Html.Kendo().Grid<Student.Models.StudentDetails>()
  .Name("StudentDetailsGrid")
  .Pageable()
  .HtmlAttributes(new { id="StudentDetailsGrid"})
  .Columns(col =>
    {
      col.Bound(a => a.FirstName).Title("Name");
      col.Bound(a => a.LastName).Hidden()
      col.Bound(a => a.StudentID).Hidden();
      col.Command(a => { a.Destroy(); a.Edit(); }).Title("");
    }
  )
  .ToolBar(toolbar => toolbar
    .Create()
    .Text("Add")
    .HtmlAttributes(new {@id="btnCreateStudent"})
  )
  .Editable(editable => editable.Mode(GridEditMode.InLine))
  .Scrollable(scrol => scrol.Enabled(true))
  .DataSource(source => source
    .Ajax()
    .PageSize(5)
    .Model(a => {a.Id(b => b.StudentID);})
    .Read(read => read.Action()
    .Create(create => create.Action())
    .Destroy(destroy => destroy.Action())
    .Update(update => update.Action())
  )
  .Events(even => even
    .Save("SaveDetails")
    .Edit("ChangeNoOfStudent")
    .DataBound("StudentValidate")
  )
)
```
<p>on Document.ready function :</p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
  $.ajax({
    url: '../Student/GetStudentDetails?StudentId=' + Data.StudentId,
    type: 'POST',
    contentType: 'application/json',
    dataType: 'json',
    success: function (data) {

    if (data.length > 0) {
        var studentdetail = new kendo.data.DataSource({
            data: data,
            pageSize: 5
        });
        $("#StudentDetailsGrid").data("kendoGrid").setDataSource(studentdetail);
    }
</code>```

I have added the page size, but I can still see the "Nan-Nan of 1 items".

Can you please help?

答:
Add pageSize:5 inside of dataSource:{} as,

dataSource: {
  pageSize: 5
}
```

If you put pageSize: 5 outside of dataSource:{} you will get that error "Nan-Nan".

Body:
I am trying to create a Kendo grid with a list of student details. On click of the add button, the pager shows "Nan-Nan of 1 items".

@(Html.Kendo().Grid<Student.Models.StudentDetails>()
  .Name("StudentDetailsGrid")
  .Pageable()
  .HtmlAttributes(new { id="StudentDetailsGrid"})
  .Columns(col =>
    {
      col.Bound(a => a.FirstName).Title("Name");
      col.Bound(a => a.LastName).Hidden()
      col.Bound(a => a.StudentID).Hidden();
      col.Command(a => { a.Destroy(); a.Edit(); }).Title("");
    }
  )
  .ToolBar(toolbar => toolbar
    .Create()
    .Text("Add")
    .HtmlAttributes(new {@id="btnCreateStudent"})
  )
  .Editable(editable => editable.Mode(GridEditMode.InLine))
  .Scrollable(scrol => scrol.Enabled(true))
  .DataSource(source => source
    .Ajax()
    .PageSize(5)
    .Model(a => {a.Id(b => b.StudentID);})
    .Read(read => read.Action()
    .Create(create => create.Action())
    .Destroy(destroy => destroy.Action())
    .Update(update => update.Action())
  )
  .Events(even => even
    .Save("SaveDetails")
    .Edit("ChangeNoOfStudent")
    .DataBound("StudentValidate")
  )
)

on Document.ready function :

$(document).ready(function () {
  $.ajax({
    url: '../Student/GetStudentDetails?StudentId=' + Data.StudentId,
    type: 'POST',
    contentType: 'application/json',
    dataType: 'json',
    success: function (data) {

    if (data.length > 0) {
        var studentdetail = new kendo.data.DataSource({
            data: data,
            pageSize: 5
        });
        $("#StudentDetailsGrid").data("kendoGrid").setDataSource(studentdetail);
    }

I have added the page size, but I can still see the "Nan-Nan of 1 items".

Can you please help?

Body:
Add pageSize:5 inside of dataSource:{} as,

dataSource: {
  pageSize: 5
}

If you put pageSize: 5 outside of dataSource:{} you will get that error "Nan-Nan".


问:
push key generated in firebase not equal one being retrieved android
I am trying to retrieve the push key that is being generated when i am sign up and creating a new user in my android app. But the key being retrieved is not the same as the one that was created.How is this possible? This is my code.How do i correct it?</p>

```<code> firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        //checking if success
                        if(task.isSuccessful()){

                              id = firebaseAuth.getCurrentUser().getUid();
                             key = databaseReference1.child(sexs).push().getKey();
                            Log.d("User key", key);
                            User user = new User(username, halls, levels, downloadUrl, id, key );

                            databaseReference1.child(sexs).push().setValue(user);
</code>```

答:
You are getting a different key because you are calling push() again

```<code>databaseReference1.child(sexs).push().setValue(user);
</code>```

Instead you should do the following:

```<code>databaseReference1.child(sexs).child(key).setValue(user);
</code>```

This will store the user under the key which you generated and stored in the 'key' variable

Body:
I am trying to retrieve the push key that is being generated when i am sign up and creating a new user in my android app. But the key being retrieved is not the same as the one that was created.How is this possible? This is my code.How do i correct it?

 firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        //checking if success
                        if(task.isSuccessful()){

                              id = firebaseAuth.getCurrentUser().getUid();
                             key = databaseReference1.child(sexs).push().getKey();
                            Log.d("User key", key);
                            User user = new User(username, halls, levels, downloadUrl, id, key );

                            databaseReference1.child(sexs).push().setValue(user);

Body:
You are getting a different key because you are calling push() again

databaseReference1.child(sexs).push().setValue(user);

Instead you should do the following:

databaseReference1.child(sexs).child(key).setValue(user);

This will store the user under the key which you generated and stored in the 'key' variable


问:
Can't return array from php function to ajax request
I have a javascript file in which I am doing an ajax request to foo.php
in order to get an array of mysql results.
Here is my javascript file.

```<code>//foo.js
$(document).ready(function(){
    $.ajax({
        url:"foo.php",
        type:"POST",
        data:{
            action:"test",
            remail:"foo"
        },
        success:function(data){
            var messages = data;
            console.log("Ext req");
            try{
                console.log(JSON.parse(data));
            }catch(e){
                console.log(data);
            }
        },
        failure:function(){

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

In order to receive my array of results from php I do the following:

```<code>//foo.php
<?php
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $query = "select * from message where seen";
                $ar = [];
                $res = mysqli_query($con,$query);
                while($row = mysqli_fetch_array($res)){
                    $ar[] = $row;

                }
               echo json_encode($ar);
            break;
        }
    }
?>
</code>```

This returns an array of objects to my ajax request which then I can handle according to my needs.
However if I try to move the php code inside the switch statement into a function and return the encoded result of the function I only get an empty array as response.
Here is how I am trying to do it:

```<code><?php
    function test(){
        $query = "select * from message where seen";
        $ar = [];
        $res = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($res)){
            $ar[] = $row;
        }
        return $ar;
    }
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $result = test();
               echo json_encode($result);
            break;
        }
    }
?>
</code>```

Any ideas why this happening?

UPDATE

$con is a variable that comes from another file which I include

答:
Let us talk about the problems you have:

You pass a failure function to $.ajax. You surely wanted to use error instead of failure. See here.

You have a messages variable initialized, but unused inside success. Get rid of it.

You check for isset($_POST), but that will always be true. You wanted to check isset($_POST["action"]) instead, or you wanted to check whether it is a POST request.

$con is not available inside the function. You will need to either initialize it inside the function or pass it to it and use it as a parameter.

Body:
I have a javascript file in which I am doing an ajax request to foo.php
in order to get an array of mysql results.
Here is my javascript file.

//foo.js
$(document).ready(function(){
    $.ajax({
        url:"foo.php",
        type:"POST",
        data:{
            action:"test",
            remail:"foo"
        },
        success:function(data){
            var messages = data;
            console.log("Ext req");
            try{
                console.log(JSON.parse(data));
            }catch(e){
                console.log(data);
            }
        },
        failure:function(){

        }
    })
});

In order to receive my array of results from php I do the following:

//foo.php
<?php
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $query = "select * from message where seen";
                $ar = [];
                $res = mysqli_query($con,$query);
                while($row = mysqli_fetch_array($res)){
                    $ar[] = $row;

                }
               echo json_encode($ar);
            break;
        }
    }
?>

This returns an array of objects to my ajax request which then I can handle according to my needs.
However if I try to move the php code inside the switch statement into a function and return the encoded result of the function I only get an empty array as response.
Here is how I am trying to do it:

<?php
    function test(){
        $query = "select * from message where seen";
        $ar = [];
        $res = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($res)){
            $ar[] = $row;
        }
        return $ar;
    }
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $result = test();
               echo json_encode($result);
            break;
        }
    }
?>

Any ideas why this happening?

UPDATE

$con is a variable that comes from another file which I include


问:
Run a command in a shell and keep running the command when you close the session
I am using Putty to connect to a remote server. What I want to know is if there is any way to write my commands and allow them to keep running after I close the session with Putty. The reason for this is that I do not want to keep the computer ON all the time. Is there any way to do this?.

Update with the solution

For my question as it is presented the best solution is use one of the commands provided such as nohup, because you do not have to install any additional software. But if you are in the same problem use screen, install it and use it. It is amazing.

I have selected the answer of Norman Ramsey as favourite because propose several solutions using commands and screen. But please check the other answers specially the one of PEZ, then you get an insight of what screen is able todo.

答:
```<code>./command & disown
</code>```

OwnerDisplayName: Eduardo

LastEditorDisplayName: Eduardo

Body: ./command & disown

OwnerDisplayName: Nick Stinemates


问:
Strategy for auto encoding text inputs?
To prevent my application from crashing with the error "A potentially dangerous Request.Form value was detected...", I just turned page validation off. I want to revisit this and solve it correctly.

Is there a good strategy for this? If people are entering '<' and '>', I think the only way to save their data is to encode it via Javacript. I have tried catching it in the code-behind, but it becomes too late. I am thinking of inheriting the textbox and auto encode/decode the input with client scripts. I also have to think of all the angle brackets that are already saved in my database.

Any suggestions or experience with this?

答:
It's best to think of the built-in page validation as a safety device that isn't applicable to all cases. There are more than a few times when it is completely impossible to do something with it turned on. In these cases we turn it off, and deal with the validation ourselves.

The most obvious case is that sometimes we actually do want to send big chunks of HTML to the server. Of course, doing so still has to be made secure, but "oh, that looks like a big chunk of HTML! throw a security exception!" obviously isn't the correct way to do that.

So, in these cases it's perfectly sensible to turn off page-validation and add your own server-side. It does mean that you have to think about just how this input will be used with a bit more scrutiny than before. Follow through the path of every datum input (not just those where you expect to see characters like <, and ensure that either it will never be sent back to the client unescaped, or that it is thoroughly inspected to guarantee safety.

Title: Strategy for auto encoding text inputs?


问:
How to access method from view inside a Xamarin Forms custom renderer?
I have the following code:

```<code>public partial class PhrasesFrameRendererClass : Frame
{
    .....
    void getRandomWords() {
       // more code here that involves getting random numbers
       // and updating a grid's bindingcontext
    }
}
</code>```

In my custom renderer I want to be able to call the getRandomWords on swipe left gesture like below:

```<code>public class PhraseFrameCustomRenderer : FrameRenderer
{
   UISwipeGestureRecognizer leftSwipeGestureRecognizer;
   protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
   {
       base.OnElementChanged(e);
       leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
       leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
       leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
       leftSwipeGestureRecognizer.AddTarget((obj) =>
       {
          // Call getRandomWords() here
       });
   }
}
</code>```

Is this possible? Any ideas on how this could be done?

答:
```<code> base.OnElementChanged(e);
   leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
   leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
   leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
   leftSwipeGestureRecognizer.AddTarget((obj) =>
   {
      // Call getRandomWords() here
      var frame = Element as PhrasesFrameRendererClass ;
      if(frame!=null){
           frame.getRandomWords();
      }
   });
</code>```

Body:
I have the following code:

public partial class PhrasesFrameRendererClass : Frame
{
    .....
    void getRandomWords() {
       // more code here that involves getting random numbers
       // and updating a grid's bindingcontext
    }
}

In my custom renderer I want to be able to call the getRandomWords on swipe left gesture like below:

public class PhraseFrameCustomRenderer : FrameRenderer
{
   UISwipeGestureRecognizer leftSwipeGestureRecognizer;
   protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
   {
       base.OnElementChanged(e);
       leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
       leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
       leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
       leftSwipeGestureRecognizer.AddTarget((obj) =>
       {
          // Call getRandomWords() here
       });
   }
}

Is this possible? Any ideas on how this could be done?


问:
Uipath offline packages install
How do you add the Microsoft word activities to a uipath installation that is offline? V8

I have tried downloading it on an online pc then copying it across to the program files. No joy.

答:
Installing the packages from "\Program Files (x86)\UiPath Studio\Packages" is one way. You can also configure other sources for .nupkg installation.

Click on 'Manage Packages'. Right click on left side of window and select 'Configure Sources'.

Click on Add (+) and select the folder where .nupkg are stored.

Give the name for the source. Then you can access all .nupkg in that folder.

Title: Uipath offline packages install