问:
Running statistics on multiple lines in bash
I have multiple HTTP headers in one giant file, separated with one empty line.

```<code>Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding
</code>```

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

```<code>197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding
</code>```

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

答:
Personally, I'd use a C program, other alternatives exist as well. Here's an awk snippet which folds lines. Not perfect, but should get you started :)

```<code>$cat foo.awk
// {
    if (NF == 0)
        printf("\n");
    else
        printf("%s ", $0);
}
$ awk -f foo.awk < lots_of_data | sort | uniq -c | sort -nk1
</code>```

The last statement will take "forever", which is why a C program may be a good alternative. It depends mostly on how often you need to run the commands.

Body:
I have multiple HTTP headers in one giant file, separated with one empty line.

Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

Body:
Personally, I'd use a C program, other alternatives exist as well. Here's an awk snippet which folds lines. Not perfect, but should get you started :)

$cat foo.awk
// {
    if (NF == 0)
        printf("\n");
    else
        printf("%s ", $0);
}
$ awk -f foo.awk < lots_of_data | sort | uniq -c | sort -nk1

The last statement will take "forever", which is why a C program may be a good alternative. It depends mostly on how often you need to run the commands.


来源: stackexchange

问:
How to store uploaded file into server path using either javascript or jquery
I want to know that how can I store my uploaded file from my local system into one server path like('/newfolder/tests/') using either javascript or jquery,  Please provide me any solution for it as I'm new to this Files system.

html:

```<code>  <input type="file" id="inputfile" name="inputfile"></input>
</code>```

js:

```<code>  var path =$('input[type=file]').val().replace(/C:\\fakepath\\/i, '');
</code>```

is giving my uploaded file names only`, so that I need to store/save this variable on any server path(or any File system path),and I'm not using any database here, so that I can grab it from that path and can display it on my view page.

答:
Try This    </p>

```<code>$('#imageInput').change(function(){
var frm = new FormData();
frm.append('imageInput', input.files[0]);
$.ajax({
    method: 'POST',
    address: 'url/to/save/image',
    data: frm,
    contentType: false,
    processData: false,
    cache: false
});
</code>```

<p>});</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to know that how can I store my uploaded file from my local system into one server path like('/newfolder/tests/') using either javascript or jquery,  Please provide me any solution for it as I'm new to this Files system.

html:

  <input type="file" id="inputfile" name="inputfile"></input>

js:

  var path =$('input[type=file]').val().replace(/C:\\fakepath\\/i, '');

is giving my uploaded file names only`, so that I need to store/save this variable on any server path(or any File system path),and I'm not using any database here, so that I can grab it from that path and can display it on my view page.

Body:
Try This

$('#imageInput').change(function(){
var frm = new FormData();
frm.append('imageInput', input.files[0]);
$.ajax({
    method: 'POST',
    address: 'url/to/save/image',
    data: frm,
    contentType: false,
    processData: false,
    cache: false
});

});


问:
How to calculate weight to minimize variance?
given several vectors:

```<code>x1 = [3 4 6]
x2 = [2 8 1]
x3 = [5 5 4]
x4 = [6 2 1]
</code>```

I wanna find weight w1, w2, w3 to each item, and get the weighted sum of each vector: yi = w1*i1 + w2*i2 + w3*i3. for example, y1 = 3*w1 + 4*w2 + 6*w3
to make the variance of these values(y1, y2, y3, y4) to be minimized.

notice: w1, w2, w3 should > 0, and w1 + w2 + w3 = 1

I don't know what kind of problems it should be... and how to solve it in python or matlab?

答: You can start with building a loss function stating the variance and the constraints on w's. The mean is m = (1/4)*(y1 + y2 + y3 + y4). The variance is then (1/4)*((y1-m)^2 + (y2-m)^2 + (y3-m)^2 + (y4-m)^2) and the constraint is a*(w1+w2+w3 - 1) where a is the Lagrange multiplier. The problem looks like to me a convex optimisation with convex constraints since the loss function is quadratic with respect to target variables (w1,w2,w3) and the constraints are linear. You can look for projected gradient descent algorithms which respect to the constraints provided. Take a look to here http://www.ifp.illinois.edu/~angelia/L5_exist_optimality.pdf There are no straightforward analytic solutions to such kind of problems in general.

Body:
given several vectors:

x1 = [3 4 6]
x2 = [2 8 1]
x3 = [5 5 4]
x4 = [6 2 1]

I wanna find weight w1, w2, w3 to each item, and get the weighted sum of each vector: yi = w1*i1 + w2*i2 + w3*i3. for example, y1 = 3*w1 + 4*w2 + 6*w3
to make the variance of these values(y1, y2, y3, y4) to be minimized.

notice: w1, w2, w3 should > 0, and w1 + w2 + w3 = 1

I don't know what kind of problems it should be... and how to solve it in python or matlab?


问:
Twig Sprintf Gettext
My question refers to this Twig Extension:

https://github.com/deceze/Twig-extensions/blob/master/doc/gettext.rst

If i use this for example:

```<code><p>{{ _n('One day without accident.', '%d days without accident.', n)|format(n) }}</p>
</code>```

So how can i parse the variables to twig?

I mean %d in this example

It is the first time i need to use Sprintf.

答:
There's a typo in Wouter J's answer (which is the correct answer) it should read

foo %s'|format($valueOfThePlaceholder)

Title: Twig Sprintf Gettext

Body:
My question refers to this Twig Extension:

https://github.com/deceze/Twig-extensions/blob/master/doc/gettext.rst

If i use this for example:

{{ _n('One day without accident.', '%d days without accident.', n)|format(n) }}

So how can i parse the variables to twig?

I mean %d in this example

It is the first time i need to use Sprintf.


问:
How to get Firebase Data into a ListView?
I am doing an Android App. I have been successful in writing to Firebase, I however am having a problem reading from Firebase into a ListView. If anyone can assist in getting the data to read back into the app into the ListView, If i just have one item to try and read back it works if I try to get all three items the app fails.
I have included a picture of the Database to get an idea of the structure and my code.

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;

 import java.util.ArrayList;

 public class Admin_ViewEvent extends AppCompatActivity {

   // private TextView textViewPersons;
private ListView mListView;
private ArrayList<String> mMeetings = new ArrayList<>();
private Firebase mRef;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin__view_event);

    mRef = new Firebase("https://saica-sgb-77a4f.firebaseio.com/Meetings");
    mListView = (ListView) findViewById(R.id.ListView);
    //textViewPersons = (TextView) findViewById(R.id.textViewPersons);

    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mMeetings);
    mListView.setAdapter(arrayAdapter);

    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            for(DataSnapshot childSnapShot : dataSnapshot.getChildren()) {

                String date = (String) childSnapShot.child("address").getValue();
                String datetime = (String) childSnapShot.child("datetime").getValue();
                String name = (String) childSnapShot.child("name").getValue();

                mMeetings.add(date);
                mMeetings.add(datetime);
                mMeetings.add(name);

            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });

 }
}
</code>```

答:
Use ChildEventListener and put your this code:

 final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String(this,android.R.layout.simple_list_item_1, mMeetings);
    mListView.setAdapter(arrayAdapter);

inside the onChildAdded....

Also creat Model class to get data from firebase
public class User {public String name;public String date;public String time;// Default constructor required for calls to
// DataSnapshot.getValue(User.class)
public User() {}public User(String name, String time, String date) {this.name = name;
this.time= time;this.date=date;}

thanks it will help you..

Body:
I am doing an Android App. I have been successful in writing to Firebase, I however am having a problem reading from Firebase into a ListView. If anyone can assist in getting the data to read back into the app into the ListView, If i just have one item to try and read back it works if I try to get all three items the app fails.
I have included a picture of the Database to get an idea of the structure and my code.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;

 import java.util.ArrayList;

 public class Admin_ViewEvent extends AppCompatActivity {

   // private TextView textViewPersons;
private ListView mListView;
private ArrayList<String> mMeetings = new ArrayList<>();
private Firebase mRef;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin__view_event);

    mRef = new Firebase("https://saica-sgb-77a4f.firebaseio.com/Meetings");
    mListView = (ListView) findViewById(R.id.ListView);
    //textViewPersons = (TextView) findViewById(R.id.textViewPersons);

    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mMeetings);
    mListView.setAdapter(arrayAdapter);

    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            for(DataSnapshot childSnapShot : dataSnapshot.getChildren()) {

                String date = (String) childSnapShot.child("address").getValue();
                String datetime = (String) childSnapShot.child("datetime").getValue();
                String name = (String) childSnapShot.child("name").getValue();

                mMeetings.add(date);
                mMeetings.add(datetime);
                mMeetings.add(name);

            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });

 }
}


问:
Eloquent "whereDate" not working after Laravel 5.4 Upgrade
(sorry in advance for the long post)

I am in the process of upgrading my application from laravel 5.2 to 5.4, and have been stuck on this problem since this morning. For some reason my query to select upcoming business events with the Eloquent 'whereDate' is not returning anything, even though everything else points to the fact that it should be working!

I have a phpUnit test that won't pass to try and localize the problem. (See further below)

I have a 'Business' model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    protected $table = 'businesses';
    ..

public function businessEvents(){
    return $this->hasMany('App\BusinessEvent', 'business_id');
}
</code>```

As well as a 'BusinessEvent' model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BusinessEvent extends Model
{
  protected $table = 'business_events';
  protected $fillable = ['business_id', ..., 'start_date', 'end_date'];

  public function business(){
      return $this->belongsTo('App\Business', 'business_id');
  }
...
</code>```

Both of which I make dummy versions of in my test. The dummy 'business' works for other tests, but I introduced the following dummy 'business_event' for this test case:

```<code>protected function createMockBusinessEventWithUpcomingDateTime($businessId){
  $faker = Faker::create();

  $businessEvent = BusinessEvent::create([
      'business_id'   => $businessId,
      'name'          => $faker->name,
      'description'   => $faker->text,
      'start_date'    => date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s")."+30 minutes")),
      'end_date'      => date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s")."+1 hour +30 minutes"))
  ]);

  ...

  $business = Business::find($businessId);
  if($business){
    $businessEvent->business()->associate($business);
  }

  return $businessEvent;
}
</code>```

Now here is the actual test function:

```<code>public function testGetUpcomingN(){

    $this->businessEvent  = $this->createMockBusinessEventWithUpcomingDateTime($this->business->id);

    $response = $this->json('GET', '/api/v1/business/'.$this->business->id.'/events/upcoming/2');

    $this->outp($response->content());

    $this->outp("Testing Assertions");
    $this->assertEquals(200, $response->status());
    $this->assertEquals($this->business->businessEvents()->first()->id, $this->businessEvent->id);
}
</code>```

The test doesn't fail, which means that the event is correctly being associated with the business, and no matter how I query the api endpoint (HttpRequester, Logging result, returned value in test, production...) it always returns an empty array!

The following function is what is called in the controller (also verified!):

```<code>public function upcomingN($businessId, $n){
    Log::info('Get upcoming '.$n.' recorded events for business with id: '.$businessId);
    $business = Business::find($businessId);
    if (is_null($business)){
        Log::warning('No business exists with given id. Exiting.');
        return response('No Content.', 204);
    }

    $currentDate = date('Y-m-d H:i:s');

    $greaterThan = $business->businessEvents()->first()->end_date >= $currentDate;
    Log::info("Greater THAN:", [$greaterThan]);

    $events = $business->businessEvents()->whereDate('end_date', '>=', $currentDate)->take($n)->get();

    if (!is_null($events)){
        Log::info('Got upcoming N recorded events for business with id: '.$businessId, (array) $events);
        return response()->json($events);
    }

    return response('No Content.', 204);
}
</code>```

As you can see, I even tried logging the "$greaterThan" boolean that should test the exact same thing that "whereDate" does, and it evaluates to true! I have tried Carbon::parse()-ing, setting the locale, and now I am pretty much out of ideas.

The old function that worked in 5.2:

```<code>public function upcomingN($businessId, $n){
   Log::info('Get upcoming N recorded events for business with id: '.$businessId);
$business = Business::find($businessId);
if (is_null($business)){
    Log::warning('No business exists with given id. Exiting.');
        return response('No Content.', 204);
    }

    $currentDate = date('Y-m-d H:i:s');
    $events = $business->businessEvents()->whereDate('start_date', '>=', $currentDate)->take($n)->get();

     if (!is_null($events)){
         Log::info('Got upcoming N recorded events for business with id: '.$businessId, (array) $events);
         return response()->json($events);
     }

    return response('No Content.', 204);
}
</code>```

One thing I did have to change during the upgrade was setting the mysql-db to non-strict, because Laravel was complaining about a lack of default values. However, I've checked the db and the test entries are correctly populated.

Any help would be greatly appreciated!

答:
Thanks so much to Omisakin Oluwatobi, the solution was in fact using an Eloquent 'where' instead of 'whereDate', as 'whereDate' only compares the dates and not the date times (which, in hindsight seems obvious).

I find it a bit confusing that the 'whereDate' function exists if you can achieve the same result with 'where' using the same amount of code.

I can verify (unit-tested) that the following final solution works for selecting future datetimes and ignoring past ones:

```<code>public function upcomingN($businessId, $n){
    Log::info('Get upcoming '.$n.' recorded events for business with id: '.$businessId);
    $business = Business::find($businessId);

    if (is_null($business)){
        Log::warning('No business exists with given id. Exiting.');
        return response('No Content.', 204);
    }

    $currentDate = date('Y-m-d H:i:s');
    $events = $business->businessEvents()->where('end_date', '>=', $currentDate)->take($n)->get();

    if (!is_null($events)){
        Log::info('Got upcoming N recorded events for business with id: '.$businessId, (array) $events);
        return response()->json($events);
    }

    return response('No Content.', 204);
}
</code>```

Body:
(sorry in advance for the long post)

I am in the process of upgrading my application from laravel 5.2 to 5.4, and have been stuck on this problem since this morning. For some reason my query to select upcoming business events with the Eloquent 'whereDate' is not returning anything, even though everything else points to the fact that it should be working!

I have a phpUnit test that won't pass to try and localize the problem. (See further below)

I have a 'Business' model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    protected $table = 'businesses';
    ..

public function businessEvents(){
    return $this->hasMany('App\BusinessEvent', 'business_id');
}

As well as a 'BusinessEvent' model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BusinessEvent extends Model
{
  protected $table = 'business_events';
  protected $fillable = ['business_id', ..., 'start_date', 'end_date'];

  public function business(){
      return $this->belongsTo('App\Business', 'business_id');
  }
...

Both of which I make dummy versions of in my test. The dummy 'business' works for other tests, but I introduced the following dummy 'business_event' for this test case:

protected function createMockBusinessEventWithUpcomingDateTime($businessId){
  $faker = Faker::create();

  $businessEvent = BusinessEvent::create([
      'business_id'   => $businessId,
      'name'          => $faker->name,
      'description'   => $faker->text,
      'start_date'    => date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s")."+30 minutes")),
      'end_date'      => date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s")."+1 hour +30 minutes"))
  ]);

  ...

  $business = Business::find($businessId);
  if($business){
    $businessEvent->business()->associate($business);
  }

  return $businessEvent;
}

Now here is the actual test function:

public function testGetUpcomingN(){

    $this->businessEvent  = $this->createMockBusinessEventWithUpcomingDateTime($this->business->id);

    $response = $this->json('GET', '/api/v1/business/'.$this->business->id.'/events/upcoming/2');

    $this->outp($response->content());

    $this->outp("Testing Assertions");
    $this->assertEquals(200, $response->status());
    $this->assertEquals($this->business->businessEvents()->first()->id, $this->businessEvent->id);
}

The test doesn't fail, which means that the event is correctly being associated with the business, and no matter how I query the api endpoint (HttpRequester, Logging result, returned value in test, production...) it always returns an empty array!

The following function is what is called in the controller (also verified!):

public function upcomingN($businessId, $n){
    Log::info('Get upcoming '.$n.' recorded events for business with id: '.$businessId);
    $business = Business::find($businessId);
    if (is_null($business)){
        Log::warning('No business exists with given id. Exiting.');
        return response('No Content.', 204);
    }

    $currentDate = date('Y-m-d H:i:s');

    $greaterThan = $business->businessEvents()->first()->end_date >= $currentDate;
    Log::info("Greater THAN:", [$greaterThan]);

    $events = $business->businessEvents()->whereDate('end_date', '>=', $currentDate)->take($n)->get();

    if (!is_null($events)){
        Log::info('Got upcoming N recorded events for business with id: '.$businessId, (array) $events);
        return response()->json($events);
    }

    return response('No Content.', 204);
}

As you can see, I even tried logging the "$greaterThan" boolean that should test the exact same thing that "whereDate" does, and it evaluates to true! I have tried Carbon::parse()-ing, setting the locale, and now I am pretty much out of ideas.

The old function that worked in 5.2:

public function upcomingN($businessId, $n){
   Log::info('Get upcoming N recorded events for business with id: '.$businessId);
$business = Business::find($businessId);
if (is_null($business)){
    Log::warning('No business exists with given id. Exiting.');
        return response('No Content.', 204);
    }

    $currentDate = date('Y-m-d H:i:s');
    $events = $business->businessEvents()->whereDate('start_date', '>=', $currentDate)->take($n)->get();

     if (!is_null($events)){
         Log::info('Got upcoming N recorded events for business with id: '.$businessId, (array) $events);
         return response()->json($events);
     }

    return response('No Content.', 204);
}

One thing I did have to change during the upgrade was setting the mysql-db to non-strict, because Laravel was complaining about a lack of default values. However, I've checked the db and the test entries are correctly populated.

Any help would be greatly appreciated!

Body:
Thanks so much to Omisakin Oluwatobi, the solution was in fact using an Eloquent 'where' instead of 'whereDate', as 'whereDate' only compares the dates and not the date times (which, in hindsight seems obvious).

I find it a bit confusing that the 'whereDate' function exists if you can achieve the same result with 'where' using the same amount of code.

I can verify (unit-tested) that the following final solution works for selecting future datetimes and ignoring past ones:

public function upcomingN($businessId, $n){
    Log::info('Get upcoming '.$n.' recorded events for business with id: '.$businessId);
    $business = Business::find($businessId);

    if (is_null($business)){
        Log::warning('No business exists with given id. Exiting.');
        return response('No Content.', 204);
    }

    $currentDate = date('Y-m-d H:i:s');
    $events = $business->businessEvents()->where('end_date', '>=', $currentDate)->take($n)->get();

    if (!is_null($events)){
        Log::info('Got upcoming N recorded events for business with id: '.$businessId, (array) $events);
        return response()->json($events);
    }

    return response('No Content.', 204);
}


问:
Problem aligning divs next to each other?
I want this design:

```<code>DIV1: auto-size DIV2: 160px
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
</code>```

How do I solve this problem? I've tried stuff like floating left & right, but I just can't get them on the same line.

I want the div 2 to always be there, and the div1 to have a max-width of 40em, but resize to allow the div 2 to show at all times if its necessary.

My code:

```<code><style="text/css">
#mainbulk {
    padding: 1.5em 2% 1.5em .5em;
}
#ads {
    width: 7.5em;
    float: left;
    display: table-cell;
padding: 0 0 0 2em;
}
#textcontent {
    width: 70%;
    float: left;
    display: table-cell;
}
</style>
</code>```

and

```<code><div id="mainbulk">
    <div id="textcontent">
        <p>This is the most amazing site in the world. It has a very nice design, and is perfect for everything. If there's something that this site can't do, then nothing can do it, but I'd suggest to try all of this site's features before complaining.</p>
    </div>
    <div id="ads" align="right">
    ads would, hypothetically, be placed here if this were actually an actual website.
    </div>
</div>
</code>```

I'm encountering this problem:

http://www.screencast-o-matic.com/watch/c6lrXsXyQ

答:
Not really sure what you're after, but you can try what I've done here. You should only use an id on a unique element in a document, so if you want more than one, re-assign them as classes. display: table-cell; is not needed here.

HTML:

```<code><div class="mainbulk">
    <div class="ads">
    ads would, hypothetically, be placed here if this were actually an actual website.
    </div>
    <div class="textcontent">

        <p>This is the most amazing site in the world. It has a very nice design, and is perfect for everything. If there's something that this site can't do, then nothing can do it, but I'd suggest to try all of this site's features before complaining.</p>
    </div>

</div>
</code>```

CSS:

```<code>.mainbulk {
    padding: 1.5em 2% 1.5em .5em;
    border: 1px solid #000;
}
.ads {
    width: 7.5em;
    float:right;
    text-align: right;
    border: 1px dotted #f00;
}
.textcontent {
    max-width: 40em;
    float: right;
    border: 1px dotted #00f;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want this design:

DIV1: auto-size DIV2: 160px
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo

How do I solve this problem? I've tried stuff like floating left & right, but I just can't get them on the same line.

I want the div 2 to always be there, and the div1 to have a max-width of 40em, but resize to allow the div 2 to show at all times if its necessary.

My code:

and

This is the most amazing site in the world. It has a very nice design, and is perfect for everything. If there's something that this site can't do, then nothing can do it, but I'd suggest to try all of this site's features before complaining.

    ads would, hypothetically, be placed here if this were actually an actual website.

I'm encountering this problem:

http://www.screencast-o-matic.com/watch/c6lrXsXyQ

Body:
Not really sure what you're after, but you can try what I've done here. You should only use an id on a unique element in a document, so if you want more than one, re-assign them as classes. display: table-cell; is not needed here.

HTML:

<div class="mainbulk">
    <div class="ads">
    ads would, hypothetically, be placed here if this were actually an actual website.
    </div>
    <div class="textcontent">

        <p>This is the most amazing site in the world. It has a very nice design, and is perfect for everything. If there's something that this site can't do, then nothing can do it, but I'd suggest to try all of this site's features before complaining.</p>
    </div>

</div>

CSS:

.mainbulk {
    padding: 1.5em 2% 1.5em .5em;
    border: 1px solid #000;
}
.ads {
    width: 7.5em;
    float:right;
    text-align: right;
    border: 1px dotted #f00;
}
.textcontent {
    max-width: 40em;
    float: right;
    border: 1px dotted #00f;
}


问:
Android Webview not triggering a href download file
I have added the Download Manager , but it is not triggering the download event , can any body help . When user goes to webview download option and click a link to download a file nothing happens. I have gone through many of the post in stackoverflow but nothing works for me.

```<code> public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    // boolean thread_running = true;
    private static final String TAG = "MainActivity";
    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.setWebViewClient(new MyAppWebViewClient(this));

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        webSettings.setDomStorageEnabled(true);

        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());
        /**
         * Check Internet status button click event
         * */
        isInternetPresent = cd.isConnectingToInternet();
        // check for Internet status
        if (isInternetPresent) {
            // Internet Connection is Present
            // make HTTP requests
            mWebView.loadUrl("http://url");
        } else {
            // Internet connection is not present
            // Ask user to connect to Internet
            //showAlertDialog(MainActivity.this, "No Internet Connection",
            //"You don't have internet connection.", false);
            Toast.makeText(this, "No Internet connection, Please SwitchOn Connection", Toast.LENGTH_LONG).show();
            finish();
        }

    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    public class MyAppWebViewClient extends WebViewClient {

        private Context context;

        public MyAppWebViewClient(Context context) {
            this.context = context;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (!cd.isConnectingToInternet()) {

                //internet is not present
                Toast.makeText(getApplicationContext(), "Internet Stopped Working", Toast.LENGTH_SHORT).show();
                finish();
            }

            if(url.contains(".JPG")){

                DownloadManager mdDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));
                File destinationFile = new File(Environment.getExternalStorageDirectory(),getFileName(url));
                request.setDescription("Downloading ...");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationUri(Uri.fromFile(destinationFile));
                mdDownloadManager.enqueue(request);

                return true;

            }

            view.loadUrl(url);
            return true;
        }

        public String getFileName(String url) {
            String filenameWithoutExtension = "";
            filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
                    + ".jpg");
            return filenameWithoutExtension;
        }

    }
    }
</code>```

Can someone help me out here? The page loads without issue but the link to a image file in the HTML page is not working...

I am getting this following error when click on link

```<code> Writing exception to parcel
                                                                java.lang.SecurityException: No permission to write to /storage/emulated/0/1499148267411.jpg: Neither user 10109 nor current process has android.permission.WRITE_EXTERNAL_STORAGE.
                                                                    at android.app.ContextImpl.enforce(ContextImpl.java:1438)
                                                                    at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1470)
                                                                    at com.android.providers.downloads.DownloadProvider.checkFileUriDestination(DownloadProvider.java:724)
                                                                    at com.android.providers.downloads.DownloadProvider.insert(DownloadProvider.java:558)
                                                                    at android.content.ContentProvider$Transport.insert(ContentProvider.java:263)
                                                                    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)
                                                                    at android.os.Binder.execTransact(Binder.java:453)
</code>```

答:
Finally after searching lot and reading here about permission in Marshmallow API 23 >= , we need to give permission in run time . I solved my problem with this code ,

Oncreate method in MainActivity

```<code>   int permissionCheck = ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        //requesting permission
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    } else {
        Log.i(TAG , "Permission Granted");
    }
</code>```

and Overriding this Method

```<code>@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        //you have the permission now.
            Log.i(TAG , "Permission Already Granted");
    }

}
</code>```

Body:
I have added the Download Manager , but it is not triggering the download event , can any body help . When user goes to webview download option and click a link to download a file nothing happens. I have gone through many of the post in stackoverflow but nothing works for me.

 public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    // boolean thread_running = true;
    private static final String TAG = "MainActivity";
    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.setWebViewClient(new MyAppWebViewClient(this));

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        webSettings.setDomStorageEnabled(true);

        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());
        /**
         * Check Internet status button click event
         * */
        isInternetPresent = cd.isConnectingToInternet();
        // check for Internet status
        if (isInternetPresent) {
            // Internet Connection is Present
            // make HTTP requests
            mWebView.loadUrl("http://url");
        } else {
            // Internet connection is not present
            // Ask user to connect to Internet
            //showAlertDialog(MainActivity.this, "No Internet Connection",
            //"You don't have internet connection.", false);
            Toast.makeText(this, "No Internet connection, Please SwitchOn Connection", Toast.LENGTH_LONG).show();
            finish();
        }

    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    public class MyAppWebViewClient extends WebViewClient {

        private Context context;

        public MyAppWebViewClient(Context context) {
            this.context = context;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (!cd.isConnectingToInternet()) {

                //internet is not present
                Toast.makeText(getApplicationContext(), "Internet Stopped Working", Toast.LENGTH_SHORT).show();
                finish();
            }

            if(url.contains(".JPG")){

                DownloadManager mdDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));
                File destinationFile = new File(Environment.getExternalStorageDirectory(),getFileName(url));
                request.setDescription("Downloading ...");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationUri(Uri.fromFile(destinationFile));
                mdDownloadManager.enqueue(request);

                return true;

            }

            view.loadUrl(url);
            return true;
        }

        public String getFileName(String url) {
            String filenameWithoutExtension = "";
            filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
                    + ".jpg");
            return filenameWithoutExtension;
        }

    }
    }

Can someone help me out here? The page loads without issue but the link to a image file in the HTML page is not working...

I am getting this following error when click on link

 Writing exception to parcel
                                                                java.lang.SecurityException: No permission to write to /storage/emulated/0/1499148267411.jpg: Neither user 10109 nor current process has android.permission.WRITE_EXTERNAL_STORAGE.
                                                                    at android.app.ContextImpl.enforce(ContextImpl.java:1438)
                                                                    at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1470)
                                                                    at com.android.providers.downloads.DownloadProvider.checkFileUriDestination(DownloadProvider.java:724)
                                                                    at com.android.providers.downloads.DownloadProvider.insert(DownloadProvider.java:558)
                                                                    at android.content.ContentProvider$Transport.insert(ContentProvider.java:263)
                                                                    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)
                                                                    at android.os.Binder.execTransact(Binder.java:453)

Body:
Finally after searching lot and reading here about permission in Marshmallow API 23 >= , we need to give permission in run time . I solved my problem with this code ,

Oncreate method in MainActivity

   int permissionCheck = ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        //requesting permission
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    } else {
        Log.i(TAG , "Permission Granted");
    }

and Overriding this Method

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        //you have the permission now.
            Log.i(TAG , "Permission Already Granted");
    }

}


问:
Get value of unlimited textfield in array
How to get value from unlimited input[type="text] in array

Children.js

```<code>import React, { Component } from 'react';

export default class Children extends Component {

    render() {
        return(
            <div id={"children-"+this.props.number}>
                <div className="form-group">
                    <input type="text" placeholder="Name" className="fullWidth"/>
                </div>
                <div className="form-group">
                    <input type="text" placeholder="Age" className="fullWidth"/>
                </div>
            </div>
        )
    }

}
</code>```

Parent.js

```<code>import React, { Component } from 'react';
import Children from './Children.js'
import RaisedButton from 'material-ui/RaisedButton';

export default class NewProduct extends Component {
    constructor(props) {
        super(props);
        this.state = {
            numOfChildren: 0,
        }
    }

    onAddChildren () {
        this.setState({
            numOfChildren: this.state.numOfChildren + 1
        });
    }

    render() {
        const children = [];
        for (var i = 0; i < this.state.numOfChildren; i += 1) {
            children.push(<Children
                                number={i}
                                key={i}
                            />);
        }

        return (
            <div className="form">
                <div className="tab-content">
                    {children}
                    <RaisedButton
                        label="Add Children"
                        onTouchTap={this.onAddChildren.bind(this)}
                    />
                </div>
            </div>
        );
    }
}
</code>```

The results must be like this :
value-A-1 : "value A 1", value-B-1 : "value B 1"
value-A-2 : "value A 2", value-B-2 : "value B 2"
value-A-3 : "value A 3", value-B-3 : "value B 3"

So the array will be like this:

```<code>[
    {
        "id" : 1,
        "value-A" : "value A 1",
        "value-B" : "value B 1"
    }
    {
        "id" : 2,
        "value-A" : "value A 2",
        "value-B" : "value B 2"
    }
    {
        "id" : 3,
        "value-A" : "value A 3",
        "value-B" : "value B 3"
    }
]
</code>```

I'm really appreciate if you can help me. Thanks.

答:
Add a field to state for hold your input results in the constructor

```<code>this.state = {
 numOfChildren: 0,
 data:[]
}
</code>```

Add an onChange function to Parent class which push the results to the state

```<code>onChange(index,key,value){
 let data=this.state.data;
 data[index][key]=value;
 this.setState({data:data});
}
</code>```

Pass onChange as a callback to the Child

```<code>for (var i = 0; i < this.state.numOfChildren; i += 1) {
     children.push(<Children onChange={this.onChange}
                                number={i}
                                key={i}
                            />);
}
</code>```

In Children call onChange callback with the number and the value name and value

```<code>import React, { Component } from 'react';

export default class Children extends Component {

    render() {
        return(
            <div id={"children-"+this.props.number}>
                <div className="form-group">
                    <input type="text" placeholder="Name" className="fullWidth" onChange={(e)=>this.props.onChange(this.props.number,"value-A",e.target.value)}/>
                </div>
                <div className="form-group">
                    <input type="text" placeholder="Age" className="fullWidth" onChange={(e)=>this.props.onChange(this.props.number,"value-B",e.target.value)}/>
                </div>
            </div>
        )
    }

}
</code>```

Body:
How to get value from unlimited input[type="text] in array

Children.js

import React, { Component } from 'react';

export default class Children extends Component {

    render() {
        return(

                    <input type="text" placeholder="Name" className="fullWidth"/>

                    <input type="text" placeholder="Age" className="fullWidth"/>

        )
    }

}

Parent.js

import React, { Component } from 'react';
import Children from './Children.js'
import RaisedButton from 'material-ui/RaisedButton';

export default class NewProduct extends Component {
    constructor(props) {
        super(props);
        this.state = {
            numOfChildren: 0,
        }
    }

    onAddChildren () {
        this.setState({
            numOfChildren: this.state.numOfChildren + 1
        });
    }

    render() {
        const children = [];
        for (var i = 0; i < this.state.numOfChildren; i += 1) {
            children.push(<Children
                                number={i}
                                key={i}
                            />);
        }

        return (

                    {children}
                    <RaisedButton
                        label="Add Children"
                        onTouchTap={this.onAddChildren.bind(this)}
                    />

        );
    }
}

The results must be like this :
value-A-1 : "value A 1", value-B-1 : "value B 1"
value-A-2 : "value A 2", value-B-2 : "value B 2"
value-A-3 : "value A 3", value-B-3 : "value B 3"

So the array will be like this:

[
    {
        "id" : 1,
        "value-A" : "value A 1",
        "value-B" : "value B 1"
    }
    {
        "id" : 2,
        "value-A" : "value A 2",
        "value-B" : "value B 2"
    }
    {
        "id" : 3,
        "value-A" : "value A 3",
        "value-B" : "value B 3"
    }
]

I'm really appreciate if you can help me. Thanks.

Body:
Add a field to state for hold your input results in the constructor

this.state = {
 numOfChildren: 0,
 data:[]
}

Add an onChange function to Parent class which push the results to the state

onChange(index,key,value){
 let data=this.state.data;
 data[index][key]=value;
 this.setState({data:data});
}

Pass onChange as a callback to the Child

for (var i = 0; i < this.state.numOfChildren; i += 1) {
     children.push(<Children onChange={this.onChange}
                                number={i}
                                key={i}
                            />);
}

In Children call onChange callback with the number and the value name and value

import React, { Component } from 'react';

export default class Children extends Component {

    render() {
        return(
            <div id={"children-"+this.props.number}>
                <div className="form-group">
                    <input type="text" placeholder="Name" className="fullWidth" onChange={(e)=>this.props.onChange(this.props.number,"value-A",e.target.value)}/>
                </div>
                <div className="form-group">
                    <input type="text" placeholder="Age" className="fullWidth" onChange={(e)=>this.props.onChange(this.props.number,"value-B",e.target.value)}/>
                </div>
            </div>
        )
    }

}


问:
how to vectorize the args of a function in R?
I have a list in R and I'm trying to rename the list members from a character array. For instance:

```<code>mylist <- list(c('a','b','c'),c('d','e'),'f')
headers <- c('heading1','heading2','heading3')
</code>```

And I can rename the list members like this:

```<code>names(mylist) <- c(headers[1],
                   headers[2],
                   headers[3])
</code>```

But when my list is 100s of members long, this code is horrible to write. I've tried using a for-loop as well as vectorized notation but nothing works. Apologies for what is doubtless a duplicate question but I've searched a lot of false leads in trying to google it

答:
With the sprintf-function it is as easy as:

```<code>names(mylist) <- sprintf("%s%s", "heading", 1:length(mylist))
</code>```

The result:

```<code>> mylist
$heading1
[1] "a" "b" "c"

$heading2
[1] "d" "e"

$heading3
[1] "f"
</code>```

Body:
I have a list in R and I'm trying to rename the list members from a character array. For instance:

mylist <- list(c('a','b','c'),c('d','e'),'f')
headers <- c('heading1','heading2','heading3')

And I can rename the list members like this:

names(mylist) <- c(headers[1],
                   headers[2],
                   headers[3])

But when my list is 100s of members long, this code is horrible to write. I've tried using a for-loop as well as vectorized notation but nothing works. Apologies for what is doubtless a duplicate question but I've searched a lot of false leads in trying to google it

Body:
With the sprintf-function it is as easy as:

names(mylist) <- sprintf("%s%s", "heading", 1:length(mylist))

The result:

> mylist
$heading1
[1] "a" "b" "c"

$heading2
[1] "d" "e"

$heading3
[1] "f"


问:
How to define where libs are loaded from
I am trying to compile omniORB on AIX 6.1 with gcc 4.2.0.

The initialization does not work as it is picking up the non pthreaded library.

If I set LIBPATH to /opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/ omniNames will not work, as the streams interface gives an exception.

Setting the LIBPATH to /opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/pthread seems to work, but other non pthreaded programs will pick up the pthreaded lib which may cause problems...

The link looks like this:

```<code>g++ -o omniNames -O2 -Wall -Wno-unused -fexceptions -Wl,-brtl -Wl,-blibpath:/lib:/usr/lib:/opt/dbx/omniORB-4/lib -L../../../lib -L../../../../lib omniNames.o NamingContext_i.o log.o omniNamesWin.o -lomniORB4-ar -lomnithread34 -lpthreads
</code>```

How do I resolve this ??

Note that I have tried to change libpath using configure arguments but without success.

答:
Launching via a wrapper script which set LIBPATH correctly is probably the easiest.

Then there is the RUNPATH/RPATH feature of ELF which allows to embded a search path for dynamic libraries in the executable; but I don't know if AIX implement it.  It it does and is set with the same argument as for Linux and Solaris, -Wl,--enable-new-dtags -Wl,-R$(RUNPATH) for DT_RUNPATH, -Wl,--disable-new-dtags -Wl,-R$(RPATH) for DT_RPATH; you may want to test also simply -Wl,-R$(RPATH) (which will probably set the DT_RPATH).

Body:
I am trying to compile omniORB on AIX 6.1 with gcc 4.2.0.

The initialization does not work as it is picking up the non pthreaded library.

If I set LIBPATH to /opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/ omniNames will not work, as the streams interface gives an exception.

Setting the LIBPATH to /opt/freeware/lib/gcc/powerpc-ibm-aix6.1.0.0/4.2.0/pthread seems to work, but other non pthreaded programs will pick up the pthreaded lib which may cause problems...

The link looks like this:

g++ -o omniNames -O2 -Wall -Wno-unused -fexceptions -Wl,-brtl -Wl,-blibpath:/lib:/usr/lib:/opt/dbx/omniORB-4/lib -L../../../lib -L../../../../lib omniNames.o NamingContext_i.o log.o omniNamesWin.o -lomniORB4-ar -lomnithread34 -lpthreads

How do I resolve this ??

Note that I have tried to change libpath using configure arguments but without success.


答:
You can go with this approach:

Children.js

```<code>import React, { Component } from 'react';

export default class Children extends Component {
    render() {
        return(
            <div id={"children-"+this.props.number}>
                <div className="form-group">
                    <input type="text" placeholder="Name" className="fullWidth" onChange={({target: {value}}) => this.props.onNameChange(value)}/>
                </div>
                <div className="form-group">
                    <input type="text" placeholder="Age" className="fullWidth" onChange={({target: {value}}) => this.props.onAgeChange(value)}/>
                </div>
            </div>
        )
    }
}

Children.defaultProps = {
    onNameChange: () => null,
    onValueChange: () => null,
}
</code>```

Parent.js

```<code>import React, { Component } from 'react';
import Children from './Children.js'
import RaisedButton from 'material-ui/RaisedButton';

export default class NewProduct extends Component {
    constructor(props) {
        super(props);
        this.state = {
            numOfChildren: 0,
        }
        this.result = [];
    }

    onAddChildren () {
        this.setState({
            numOfChildren: this.state.numOfChildren + 1
        });
    }

    render() {
        const children = [];
        for (var i = 0; i < this.state.numOfChildren; i += 1) {
            this.result[i] = {name: '', age: '', id: i + 1);
            const index = i;
            children.push(<Children
                                number={i}
                                key={i}
                                onNameChange={value => this.result[index].name = value}
                                onAgeChange={value => this.result[index].name = value}
                            />);
        }

        return (
            <div className="form">
                <div className="tab-content">
                    {children}
                    <RaisedButton
                        label="Add Children"
                        onTouchTap={this.onAddChildren.bind(this)}
                    />
                </div>
            </div>
        );
    }
}
</code>```

this.result will store something like the array you described.

I didn't check the above code but it should give you the idea.

Title: Get value of unlimited textfield in array

Body:
You can go with this approach:

Children.js

import React, { Component } from 'react';

export default class Children extends Component {
    render() {
        return(
            <div id={"children-"+this.props.number}>
                <div className="form-group">
                    <input type="text" placeholder="Name" className="fullWidth" onChange={({target: {value}}) => this.props.onNameChange(value)}/>
                </div>
                <div className="form-group">
                    <input type="text" placeholder="Age" className="fullWidth" onChange={({target: {value}}) => this.props.onAgeChange(value)}/>
                </div>
            </div>
        )
    }
}

Children.defaultProps = {
    onNameChange: () => null,
    onValueChange: () => null,
}

Parent.js

import React, { Component } from 'react';
import Children from './Children.js'
import RaisedButton from 'material-ui/RaisedButton';

export default class NewProduct extends Component {
    constructor(props) {
        super(props);
        this.state = {
            numOfChildren: 0,
        }
        this.result = [];
    }

    onAddChildren () {
        this.setState({
            numOfChildren: this.state.numOfChildren + 1
        });
    }

    render() {
        const children = [];
        for (var i = 0; i < this.state.numOfChildren; i += 1) {
            this.result[i] = {name: '', age: '', id: i + 1);
            const index = i;
            children.push(<Children
                                number={i}
                                key={i}
                                onNameChange={value => this.result[index].name = value}
                                onAgeChange={value => this.result[index].name = value}
                            />);
        }

        return (
            <div className="form">
                <div className="tab-content">
                    {children}
                    <RaisedButton
                        label="Add Children"
                        onTouchTap={this.onAddChildren.bind(this)}
                    />
                </div>
            </div>
        );
    }
}

this.result will store something like the array you described.

I didn't check the above code but it should give you the idea.


问:
Issues with userdefaults usage swift 3
I just started learning Swift so the level of this question may be obvious enough for you, however, I simply can't understand what to do.

I "created" a simple app which allows you to add logs of your day. Each cell stores the time you added, a custom icon that changes depending on the time, and, the log text itself (simple text).

Everything works fine. But, as I didn't know about the "Userdefaults" stuff, the clock resets every time I kill the app.

I read many articles about Userdefaults but I have no idea what to do to keep saving my data even when I kill the app.

Here's what I tried to do:

```<code>class ToDoItem: NSObject, NSCoding {

var title: String
var date: String
var type: String!

public init(title: String, date: String, type: String) {

    self.title = title
    self.date = date
    self.type = type

}

required init?(coder aDecoder: NSCoder)
{
    // Try to unserialize the "title" variable
    if let title = aDecoder.decodeObject(forKey: "title") as? String
    {
        self.title = title
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .none
        dateFormatter.timeStyle = .short
        self.date = dateFormatter.string(from: Date())

        let hour = NSCalendar.current.component(.hour, from: Date())
        var tempType = ""
        switch hour {
        case 5..<9: tempType = "morning_1"
        case 6..<12: tempType = "morning_2"
        case 12: tempType = "noon_1"
        case 13..<16: tempType = "afternoon_1"
        case 16..<20: tempType = "dusk_1"
        case 20..<23: tempType = "evening_1"
        case 23..<00: tempType = "midnight_1"
        default: tempType = "morning_1"

        }

        self.type = tempType

    }

    else
    {
        // There were no objects encoded with the key "title",
        // so that's an error.
        return nil
    }

    let userDefaults = UserDefaults.standard
    userDefaults.set(true, forKey: "title")

}

func encode(with aCoder: NSCoder)
{
    // Store the objects into the coder object
    aCoder.encode(self.title, forKey: "title")

    let defaults = UserDefaults.standard
    defaults.set(false, forKey: "title")

}
</code>```

}

```<code>extension Collection where Iterator.Element == ToDoItem
{
    // Builds the persistence URL. This is a location inside
    // the "Application Support" directory for the App.
    private static func persistencePath() -> URL?
    {
        let url = try? FileManager.default.url(
            for: .applicationSupportDirectory,
            in: .userDomainMask,
            appropriateFor: nil,
            create: true)

        return url?.appendingPathComponent("todoitems.bin")
    }

    // Write the array to persistence
    func writeToPersistence() throws
    {
        if let url = Self.persistencePath(), let array = self as? NSArray
        {
            let data = NSKeyedArchiver.archivedData(withRootObject: array)
            try data.write(to: url)
        }
        else
        {
            throw NSError(domain: "com.example.MyToDo", code: 10, userInfo: nil)
        }
    }

    // Read the array from persistence
    static func readFromPersistence() throws -> [ToDoItem]
    {
        if let url = persistencePath(), let data = (try Data(contentsOf: url) as Data?)
        {
            if let array = NSKeyedUnarchiver.unarchiveObject(with: data) as? [ToDoItem]
            {
                return array
            }
            else
            {
                throw NSError(domain: "com.example.MyToDo", code: 11, userInfo: nil)
            }
        }
        else
        {
            throw NSError(domain: "com.example.MyToDo", code: 12, userInfo: nil)
        }
    }
}
</code>```

can anyone help me or at least point what I have to do? thank you!

答:
You're using NSKeyedArchiver and NSKeyedUnarchiver which is a different mechanism than UserDefaults. Both are perfectly valid, but you have to pick one, they don't work together.

Here you are archiving and unarchiving an array of ToDoItem. For this to work, ToDoItem needs to be archivable, meaning it must implement the NSCoding protocol, which is:

```<code>public protocol NSCoding {
    public func encode(with aCoder: NSCoder)
    public init?(coder aDecoder: NSCoder) // NS_DESIGNATED_INITIALIZER
}
</code>```

All the properties that you want to save must be added to/extracted from the NSCoder object. Here is an example:

```<code>class ToDoItem: NSObject, NSCoding
{
    var title: String
    var date: Date

    required init?(coder aDecoder: NSCoder)
    {
        guard let title = aDecoder.decodeObject(forKey: "title") as? String else {
            return nil
        }
        guard let date = aDecoder.decodeObject(forKey: "date") as? Date else {
            return nil
        }
        self.title = title
        self.date = date
    }

    func encode(with aCoder: NSCoder)
    {
        aCoder.encode(self.title, forKey: "title")
        aCoder.encode(self.date, forKey: "date")
    }
}
</code>```

Title: Issues with userdefaults usage swift 3

Body:
I just started learning Swift so the level of this question may be obvious enough for you, however, I simply can't understand what to do.

I "created" a simple app which allows you to add logs of your day. Each cell stores the time you added, a custom icon that changes depending on the time, and, the log text itself (simple text).

Everything works fine. But, as I didn't know about the "Userdefaults" stuff, the clock resets every time I kill the app.

I read many articles about Userdefaults but I have no idea what to do to keep saving my data even when I kill the app.

Here's what I tried to do:

class ToDoItem: NSObject, NSCoding {

var title: String
var date: String
var type: String!

public init(title: String, date: String, type: String) {

    self.title = title
    self.date = date
    self.type = type

}

required init?(coder aDecoder: NSCoder)
{
    // Try to unserialize the "title" variable
    if let title = aDecoder.decodeObject(forKey: "title") as? String
    {
        self.title = title
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .none
        dateFormatter.timeStyle = .short
        self.date = dateFormatter.string(from: Date())

        let hour = NSCalendar.current.component(.hour, from: Date())
        var tempType = ""
        switch hour {
        case 5..<9: tempType = "morning_1"
        case 6..<12: tempType = "morning_2"
        case 12: tempType = "noon_1"
        case 13..<16: tempType = "afternoon_1"
        case 16..<20: tempType = "dusk_1"
        case 20..<23: tempType = "evening_1"
        case 23..<00: tempType = "midnight_1"
        default: tempType = "morning_1"

        }

        self.type = tempType

    }

    else
    {
        // There were no objects encoded with the key "title",
        // so that's an error.
        return nil
    }

    let userDefaults = UserDefaults.standard
    userDefaults.set(true, forKey: "title")

}

func encode(with aCoder: NSCoder)
{
    // Store the objects into the coder object
    aCoder.encode(self.title, forKey: "title")

    let defaults = UserDefaults.standard
    defaults.set(false, forKey: "title")

}

}

extension Collection where Iterator.Element == ToDoItem
{
    // Builds the persistence URL. This is a location inside
    // the "Application Support" directory for the App.
    private static func persistencePath() -> URL?
    {
        let url = try? FileManager.default.url(
            for: .applicationSupportDirectory,
            in: .userDomainMask,
            appropriateFor: nil,
            create: true)

        return url?.appendingPathComponent("todoitems.bin")
    }

    // Write the array to persistence
    func writeToPersistence() throws
    {
        if let url = Self.persistencePath(), let array = self as? NSArray
        {
            let data = NSKeyedArchiver.archivedData(withRootObject: array)
            try data.write(to: url)
        }
        else
        {
            throw NSError(domain: "com.example.MyToDo", code: 10, userInfo: nil)
        }
    }

    // Read the array from persistence
    static func readFromPersistence() throws -> [ToDoItem]
    {
        if let url = persistencePath(), let data = (try Data(contentsOf: url) as Data?)
        {
            if let array = NSKeyedUnarchiver.unarchiveObject(with: data) as? [ToDoItem]
            {
                return array
            }
            else
            {
                throw NSError(domain: "com.example.MyToDo", code: 11, userInfo: nil)
            }
        }
        else
        {
            throw NSError(domain: "com.example.MyToDo", code: 12, userInfo: nil)
        }
    }
}

can anyone help me or at least point what I have to do? thank you!

Body:
You're using NSKeyedArchiver and NSKeyedUnarchiver which is a different mechanism than UserDefaults. Both are perfectly valid, but you have to pick one, they don't work together.

Here you are archiving and unarchiving an array of ToDoItem. For this to work, ToDoItem needs to be archivable, meaning it must implement the NSCoding protocol, which is:

public protocol NSCoding {
    public func encode(with aCoder: NSCoder)
    public init?(coder aDecoder: NSCoder) // NS_DESIGNATED_INITIALIZER
}

All the properties that you want to save must be added to/extracted from the NSCoder object. Here is an example:

class ToDoItem: NSObject, NSCoding
{
    var title: String
    var date: Date

    required init?(coder aDecoder: NSCoder)
    {
        guard let title = aDecoder.decodeObject(forKey: "title") as? String else {
            return nil
        }
        guard let date = aDecoder.decodeObject(forKey: "date") as? Date else {
            return nil
        }
        self.title = title
        self.date = date
    }

    func encode(with aCoder: NSCoder)
    {
        aCoder.encode(self.title, forKey: "title")
        aCoder.encode(self.date, forKey: "date")
    }
}


问:
How to write something in the Output tab in Visual Studio Code
How can I respond to my program in the Output tab of Visual Studio Code?

I am using the Code Runner extension. Here is a picture of what I want (lower part, near "Ausgabe"):

答:
The Output panel doesn't support input. That's one of the reasons why they switched from Output panel to Terminal in version 2 of the Tasks API.

It seems the Code Runner extension supports running in the Terminal as well:

"code-runner.runInTerminal": true
```

ContentLicense: CC BY-SA 4.0


问:
Identifying text using NLP
I'm trying to find the courses in the below line of text using some NLP technique.

```<code>from nltk import word_tokenize, pos_tag, ne_chunk
sentence = "SDGI is offering courses like Electronics,Mechatronics, Physics,Mechanical Engineering"
print ne_chunk(pos_tag(word_tokenize(sentence)))
</code>```

Out put of this is

```<code>(S
  (ORGANIZATION SDGI/NNP)
  is/VBZ
  offering/VBG
  courses/NNS
  like/IN
  Electronics/NNS
  ,/,
  Mechatronics/NNS
  ,/,
  (PERSON Physics/NNPS)
  ,/,
  (PERSON Mechanical/NNP Engineering/NNP))
</code>```

Is there any way I can extract the courses from this line?

In my real project I will be getting so many documents from which I need to get the course names.

Any help is appreciated!

答:
Extract all the Nouns from a given text.

Create a Bag of Words feature set and train the set for courses with labeled data.

It seems the courses mostly precede or succeed a comma(,). A bigram or trigram approach could give accurate results.

Title: Identifying text using NLP

Body:
I'm trying to find the courses in the below line of text using some NLP technique.

from nltk import word_tokenize, pos_tag, ne_chunk
sentence = "SDGI is offering courses like Electronics,Mechatronics, Physics,Mechanical Engineering"
print ne_chunk(pos_tag(word_tokenize(sentence)))

Out put of this is

(S
  (ORGANIZATION SDGI/NNP)
  is/VBZ
  offering/VBG
  courses/NNS
  like/IN
  Electronics/NNS
  ,/,
  Mechatronics/NNS
  ,/,
  (PERSON Physics/NNPS)
  ,/,
  (PERSON Mechanical/NNP Engineering/NNP))

Is there any way I can extract the courses from this line?

In my real project I will be getting so many documents from which I need to get the course names.

Any help is appreciated!


问:
PHP can't read my html inside a file
I have a template class that I can echo out files through it.
I give the address of my file to template class and echo it out.
I have 4 files named: index, topic, topics, register and all of them are doing perfect but topic.php is empty.here is my code for example for the register inside a register controller file.what should I do? thank you.</p>

```<code><?php
$template = new template('templates/register.php');//include the template
//display template
echo $template;
</code>```

答:
It looks like you are trying to echo an object and not a string.

Does it work with this template function?

```<code>/**
 * Render template
 *
 * @param string $fileName
 * @param array $data
 * @return mixed
 */
function render($fileName, $data = array())
{
    ob_start();
    extract($data);
    require $fileName;
    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}
</code>```

Usage

```<code>$template = render('templates/register.php');
echo $template;
</code>```

Title: PHP can't read my html inside a file

Body:
I have a template class that I can echo out files through it.
I give the address of my file to template class and echo it out.
I have 4 files named: index, topic, topics, register and all of them are doing perfect but topic.php is empty.here is my code for example for the register inside a register controller file.what should I do? thank you.

<?php
$template = new template('templates/register.php');//include the template
//display template
echo $template;

Body:
It looks like you are trying to echo an object and not a string.

Does it work with this template function?

/**
 * Render template
 *
 * @param string $fileName
 * @param array $data
 * @return mixed
 */
function render($fileName, $data = array())
{
    ob_start();
    extract($data);
    require $fileName;
    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}

Usage

$template = render('templates/register.php');
echo $template;


问:
NASM ASM not being compiled properly?
I am following a tutorial and learning x64 Intel Syntax Assembly and I have this code sample that suppose to compile without issues but I am getting errors, so I cannot get started.

Code sample:

```<code>.code
ASM_Debug proc
    mov rax, 55
    ret
ASM_Debug endp
end
</code>```

I am using NASM assembly compiler, using MinGW (G++) code compiler, if I compile using inline assembly using x64 Intel Syntax MASM I don't get any errors.

Could someone tell me what do I need to do?, what is the correct NASM command line to compile this code so I could get started learning. Thanks

My current command line is: nasm.exe -f elf64 Foo.asm -o Foo.o

PS: I am NOT using Visual Studio IDE for development, I don't want to hear anything about it.

PS2: I am developing/working on/for Windows OS, NOT Linux.

Compilation errors:

```<code>CoreASM.asm:1: warning: label alone on a line without a colon might be in error [-w+orphan-labels]
CoreASM.asm:1: error: attempt to define a local label before any non-local labels
CoreASM.asm:2: error: parser: instruction expected
CoreASM.asm:5: error: symbol `ASM_Debug' redefined
CoreASM.asm:5: error: parser: instruction expected
CoreASM.asm:6: warning: label alone on a line without a colon might be in error [-w+orphan-labels]
</code>```

答:
The code you've written is in MASM syntax, which NASM doesn't support. You can tell because of the PROC/ENDP keywords, which are only in MASM (and TASM, which is mostly syntax-compatible with MASM).

So, this is MASM syntax:

```<code>.code
ASM_Debug proc
    mov rax, 55
    ret
ASM_Debug endp
end
</code>```

And this is the same code translated to NASM syntax:

```<code>SECTION .text

ASM_Debug:
    mov rax, 55
    ret
</code>```

Notice, in particular, that:

The .code directive has been replaced by SECTION .text.

The PROC/ENDP keywords have been eliminated, and a simple label is used to name the procedure. Procedures don't repeat their names at the end.

There is no END directive at the end of the code file.

You can find multiple guides to syntactical differences between MASM and NASM online. Here is a blog post by Dara Hazeghi that looks pretty comprehensive.

Your command line for running NASM is also wrong because it's trying to build a Linux-format binary (elf64 format). (You can build these in NASM on Windows, of course, but you won't be able to run them.) For 64-bit Windows, you want win64. So, it would be:

```<code>nasm.exe -f win64 Foo.asm -o Foo.obj
</code>```

(Note that .obj is conventional for object files on Windows, not .o, although you can use either. The entire -o switch is actually optional; if you omit it, NASM will automatically name the object file with the standard extension and the same name as our input source file.)

But, if you're trying to learn how to program in assembly, you really need to find a tutorial that uses syntax identical to what your assembler expects. If you want to use NASM as your assembler, then find a tutorial that also uses NASM. Or, if you want to use the MASM tutorial, then use MASM as your assembler. Version 8 of MASM can be downloaded here for non-commercial use; it isn't the newest version, but it's perfectly suitable for learning. However, that's the 32-bit version. If you want to assemble 64-bit code, you'll need the x86-64 version, with the filename ml64.exe. I don't know anywhere you can download this separately, but it is included with the Windows SDK. At least, I know it was included with the Windows 7 SDK; I'm not sure if it's still there in the latest Windows 10 SDKs, but I think so.

Title: NASM ASM not being compiled properly?

Body:
I am following a tutorial and learning x64 Intel Syntax Assembly and I have this code sample that suppose to compile without issues but I am getting errors, so I cannot get started.

Code sample:

.code
ASM_Debug proc
    mov rax, 55
    ret
ASM_Debug endp
end

I am using NASM assembly compiler, using MinGW (G++) code compiler, if I compile using inline assembly using x64 Intel Syntax MASM I don't get any errors.

Could someone tell me what do I need to do?, what is the correct NASM command line to compile this code so I could get started learning. Thanks

My current command line is: nasm.exe -f elf64 Foo.asm -o Foo.o

PS: I am NOT using Visual Studio IDE for development, I don't want to hear anything about it.

PS2: I am developing/working on/for Windows OS, NOT Linux.

Compilation errors:

CoreASM.asm:1: warning: label alone on a line without a colon might be in error [-w+orphan-labels]
CoreASM.asm:1: error: attempt to define a local label before any non-local labels
CoreASM.asm:2: error: parser: instruction expected
CoreASM.asm:5: error: symbol `ASM_Debug' redefined
CoreASM.asm:5: error: parser: instruction expected
CoreASM.asm:6: warning: label alone on a line without a colon might be in error [-w+orphan-labels]

Body:
The code you've written is in MASM syntax, which NASM doesn't support. You can tell because of the PROC/ENDP keywords, which are only in MASM (and TASM, which is mostly syntax-compatible with MASM).

So, this is MASM syntax:

.code
ASM_Debug proc
    mov rax, 55
    ret
ASM_Debug endp
end

And this is the same code translated to NASM syntax:

SECTION .text

ASM_Debug:
    mov rax, 55
    ret

Notice, in particular, that:

The .code directive has been replaced by SECTION .text.

The PROC/ENDP keywords have been eliminated, and a simple label is used to name the procedure. Procedures don't repeat their names at the end.

There is no END directive at the end of the code file.

You can find multiple guides to syntactical differences between MASM and NASM online. Here is a blog post by Dara Hazeghi that looks pretty comprehensive.

Your command line for running NASM is also wrong because it's trying to build a Linux-format binary (elf64 format). (You can build these in NASM on Windows, of course, but you won't be able to run them.) For 64-bit Windows, you want win64. So, it would be:

nasm.exe -f win64 Foo.asm -o Foo.obj

(Note that .obj is conventional for object files on Windows, not .o, although you can use either. The entire -o switch is actually optional; if you omit it, NASM will automatically name the object file with the standard extension and the same name as our input source file.)

But, if you're trying to learn how to program in assembly, you really need to find a tutorial that uses syntax identical to what your assembler expects. If you want to use NASM as your assembler, then find a tutorial that also uses NASM. Or, if you want to use the MASM tutorial, then use MASM as your assembler. Version 8 of MASM can be downloaded here for non-commercial use; it isn't the newest version, but it's perfectly suitable for learning. However, that's the 32-bit version. If you want to assemble 64-bit code, you'll need the x86-64 version, with the filename ml64.exe. I don't know anywhere you can download this separately, but it is included with the Windows SDK. At least, I know it was included with the Windows 7 SDK; I'm not sure if it's still there in the latest Windows 10 SDKs, but I think so.


问:
How does & bit operator work here?
In Java Collection classes, I have noticed very often codes like below

```<code>  //ArrayDeque
    public E pollFirst() {
    int h = head;
    @SuppressWarnings("unchecked")
    E result = (E) elements[h];
    // Element is null if deque empty
    if (result == null)
        return null;
    elements[h] = null;     // Must null out slot
    head = (h + 1) & (elements.length - 1);
    return result;
}
</code>```

What does head = (h + 1) & (elements.length - 1); do ?
   Why is & operator used here and what purpose does it serve.

My Question is not how & works, but what's its use here.

Can anyone explain it ?

答: It is a shortcut for (h + 1) % elements.length that only works if elements.length is a power of two. On some older hardware this may have run slightly faster, although I doubt this is still the case on a modern CPU.

Title: How does & bit operator work here?

Body:
In Java Collection classes, I have noticed very often codes like below

  //ArrayDeque
    public E pollFirst() {
    int h = head;
    @SuppressWarnings("unchecked")
    E result = (E) elements[h];
    // Element is null if deque empty
    if (result == null)
        return null;
    elements[h] = null;     // Must null out slot
    head = (h + 1) & (elements.length - 1);
    return result;
}

What does head = (h + 1) & (elements.length - 1); do ?
   Why is & operator used here and what purpose does it serve.

My Question is not how & works, but what's its use here.

Can anyone explain it ?


问:
Disable hamburger to back arrow animation on Toolbar
It's very easy to implement Toolbar with hamburger to back arrow animation. In my opinion this animation is pointless because as per material design spec navigation drawer covers the Toolbar when opened. My question is how to properly disable this animation and show either hamburger or back arrow using getSupportActionBar().setDisplayHomeAsUpEnabled(true);

This is how I did it, but it looks like a dirty hack:

```<code>mDrawerToggle.setDrawerIndicatorEnabled(false);

if (showHomeAsUp) {
    mDrawerToggle.setHomeAsUpIndicator(R.drawable.lib_ic_arrow_back_light);
    mDrawerToggle.setToolbarNavigationClickListener(view -> finish());
} else {
    mDrawerToggle.setHomeAsUpIndicator(R.drawable.lib_ic_menu_light);
    mDrawerToggle.setToolbarNavigationClickListener(view -> toggleDrawer());
}
</code>```

Any clues how this should be properly implemented to use just setDisplayHomeAsUpEnabled to switch between hamburger and back arrow icons?

答:
Now there is dedicated method to disable the animation: toggle.setDrawerSlideAnimationEnabled(false)

Here's a snippet I use:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    [...]

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    toggle.setDrawerSlideAnimationEnabled(false);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
}
</code>```

Body:
It's very easy to implement Toolbar with hamburger to back arrow animation. In my opinion this animation is pointless because as per material design spec navigation drawer covers the Toolbar when opened. My question is how to properly disable this animation and show either hamburger or back arrow using getSupportActionBar().setDisplayHomeAsUpEnabled(true);

This is how I did it, but it looks like a dirty hack:

mDrawerToggle.setDrawerIndicatorEnabled(false);

if (showHomeAsUp) {
    mDrawerToggle.setHomeAsUpIndicator(R.drawable.lib_ic_arrow_back_light);
    mDrawerToggle.setToolbarNavigationClickListener(view -> finish());
} else {
    mDrawerToggle.setHomeAsUpIndicator(R.drawable.lib_ic_menu_light);
    mDrawerToggle.setToolbarNavigationClickListener(view -> toggleDrawer());
}

Any clues how this should be properly implemented to use just setDisplayHomeAsUpEnabled to switch between hamburger and back arrow icons?

Body:
Now there is dedicated method to disable the animation: toggle.setDrawerSlideAnimationEnabled(false)

Here's a snippet I use:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    [...]

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    toggle.setDrawerSlideAnimationEnabled(false);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
}


问:
matplotlib with Qt5Agg backend returns empty ticklabels
In the following code snippet, I want to append a percentage sign to all Y axis tick labels of a plot:

```<code>import matplotlib as mpl
import pandas as pd
from matplotlib import pyplot as plt
print mpl.__version__, mpl.get_backend()

df = pd.DataFrame({'a': [10, 40], 'b': [20, 30]})
ax = df.plot(kind='bar', title='Plot of Percentage')
plt.draw()
ax.set_yticklabels([x.get_text() + '%' for x in ax.get_yticklabels()])
ax.get_figure().savefig('test.png', bbox_inches='tight')
</code>```

In python 2.7.13 + matplotlib 1.5.3, using backend Qt5Agg, ax.get_yticklabels() returns a list of empty Text objects, resulting in the following output image:

The above code snippet works correctly under python 2.6.9 + matplotlib 1.4.2 + Qt4Agg backend and under python 2.6.6 + matplotlib 1.3.1 + TkAgg backend.

Possibly related to: https://github.com/matplotlib/matplotlib/issues/6103/

答:
The ticklabels are not actually filled until the canvas is completely drawn. Since the ticklabels are determined by a matplotlib.ticker.***Formatter, the best solution is of course not trying to change the ticklabels themselves but to use a convenient Formatter.

Here a FuncFormatter seems a good choice.

```<code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker

df = pd.DataFrame({'a': [10, 40], 'b': [20, 30]})
ax = df.plot(kind='bar', title='Plot of Percentage')

func = lambda x, pos: "{} %".format(x)
ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(func))
plt.show()
</code>```

There is no need to draw anything and this solution is also independent on backends.

Body:
In the following code snippet, I want to append a percentage sign to all Y axis tick labels of a plot:

import matplotlib as mpl
import pandas as pd
from matplotlib import pyplot as plt
print mpl.__version__, mpl.get_backend()

df = pd.DataFrame({'a': [10, 40], 'b': [20, 30]})
ax = df.plot(kind='bar', title='Plot of Percentage')
plt.draw()
ax.set_yticklabels([x.get_text() + '%' for x in ax.get_yticklabels()])
ax.get_figure().savefig('test.png', bbox_inches='tight')

In python 2.7.13 + matplotlib 1.5.3, using backend Qt5Agg, ax.get_yticklabels() returns a list of empty Text objects, resulting in the following output image:

The above code snippet works correctly under python 2.6.9 + matplotlib 1.4.2 + Qt4Agg backend and under python 2.6.6 + matplotlib 1.3.1 + TkAgg backend.

Possibly related to: https://github.com/matplotlib/matplotlib/issues/6103/

Body:
The ticklabels are not actually filled until the canvas is completely drawn. Since the ticklabels are determined by a matplotlib.ticker.***Formatter, the best solution is of course not trying to change the ticklabels themselves but to use a convenient Formatter.

Here a FuncFormatter seems a good choice.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker

df = pd.DataFrame({'a': [10, 40], 'b': [20, 30]})
ax = df.plot(kind='bar', title='Plot of Percentage')

func = lambda x, pos: "{} %".format(x)
ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(func))
plt.show()

There is no need to draw anything and this solution is also independent on backends.