问:
Rails nested resources redirection after update
Good day all, I'm pulling my hair out on this one, I've seen similar posts but none of them get me in the direction I'm trying to go.
That said, I've got a pretty complex app that's relying heavily on nested resources and name-spacing, when I save a record it saves perfectly
and redirects correctly. When I update that same record the URL changes but not as I would expect. I understand the flow from edit to update and
the set_input call pulling the params[:id], what I don't understand is why the URL is changing the parents resource to reflect the record ID.

```<code>/servers/1/features/rsyslog_inputs/12/edit"
</code>```

changes to the following after update

```<code>/servers/12/features/rsyslog_inputs/12/edit"
</code>```

LOGS

```<code>Started GET "/servers/1/features/rsyslog_inputs/12/edit" for 127.0.0.1  at 2017-12-08 12:27:55 -0600
Processing by Features::RsyslogInputsController#edit as HTML
  Parameters: {"server_id"=>"1", "id"=>"12"}
  RsyslogInput Load (0.6ms)  SELECT  "rsyslog_inputs".* FROM "rsyslog_inputs" WHERE "rsyslog_inputs"."id" = $1 LIMIT $2  [["id", 12], ["LIMIT", 1]]
  Rendering features/rsyslog_inputs/edit.html.erb within layouts/application
  Rendered shared/_error_messages.html.erb (0.4ms) [cache miss]
  Rendered features/rsyslog_inputs/_form.html.erb (4.3ms) [cache miss]
  Rendered features/rsyslog_inputs/edit.html.erb within layouts/application (6.5ms)
  Rendered layouts/_shim.html.erb (0.5ms) [cache miss]
  User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendered layouts/_navbar_top.html.erb (0.9ms) [cache miss]
  Rendered layouts/_navbar_side.html.erb (0.5ms) [cache miss]
  Completed 200 OK in 90ms (Views: 84.7ms | ActiveRecord: 1.7ms)
</code>```

Here the PATCH has modified the servers/:id to reflect the id of the rsyslog_inputs and not retained its "1" as shown above

```<code>Started PATCH "/servers/12/features/rsyslog_inputs/12" for 127.0.0.1 at 2017-12-08 12:27:58 -0600
Processing by Features::RsyslogInputsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"dFt61NcQWXoKpmScrkngT47ZxDdhzMUcCyJ5fZKrdbaOVqKfLXMVeBUj20zKKHQ8wGe4fi2QEw98cLviyO4wQw==", "rsyslog_input"=>{"inputs_interface"=>"eth04", "inputs_ip_address"=>"1.1.1.1", "inputs_input_type"=>"tcp", "inputs_port_number"=>"22", "inputs_input_name"=>"test02", "inputs_tls"=>"0"}, "commit"=>"Save Input", "appliance_id"=>"12", "id"=>"12"}
  RsyslogInput Load (0.7ms)  SELECT  "rsyslog_inputs".* FROM "rsyslog_inputs" WHERE "rsyslog_inputs"."id" = $1 LIMIT $2  [["id", 12], ["LIMIT", 1]]
  (0.6ms)  BEGIN
  Server Load (1.0ms)  SELECT  "servers".* FROM "servers" WHERE   "servers"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  SQL (1.0ms)  UPDATE "rsyslog_inputs" SET "inputs_interface" = $1, "updated_at" = $2 WHERE "rsyslog_inputs"."id" = $3  [["inputs_interface", "eth04"], ["updated_at", "2017-12-08 18:27:58.904817"], ["id", 12]]
 (0.8ms)  COMMIT

Redirected to http://localhost:3000/servers/12/features/rsyslog_inputs
Completed 302 Found in 12ms (ActiveRecord: 4.0ms)
</code>```

Controller

```<code>class Features::RsyslogInputsController < ApplicationController
  before_action :set_input, only: [:show, :edit, :update, :destroy]

  def index
    # Let's search for all inputs associated with the corresponding appliance
    @inputs = RsyslogInput.where(server_id: params[:server_id])
  end

  def create
    @input = RsyslogInput.new(input_params)
    @input.build_server
    @input.server_id = params[:server_id]
    if @input.save
      flash[:notice] = "Input was successfully saved."
      redirect_to server_features_rsyslog_inputs_path
    else
      render('new')
    end
  end

  def destroy
    if @input.destroy
      flash[:notice] = "Input was successfully destoryed."
      redirect_to server_features_rsyslog_inputs_path
    else
      flash[:alert] = "Unable to destroy #{@input.inputs_input_name}"
    end
  end

  def update

    if @input.update(input_params)
      flash[:notice] = "Input was successfully updated"
      redirect_to server_features_rsyslog_inputs_path
    else
      render('edit')
    end
  end

  def new
    @input = RsyslogInput.new
  end

  def edit; end

  def show ;end

  private

  def set_input
    @input = RsyslogInput.find(params[:id])
  end

  def input_params
    params.require(:rsyslog_input).permit(:inputs_interface,
                                  :inputs_input_type,
                                  :inputs_ip_address,
                                  :inputs_port_number,
                                  :inputs_input_name,
                                  :inputs_tls,
                                  :server_id)
  end

end
</code>```

Form

```<code><%= form_for ([:server, :features, @input]) do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
    <br/>

    <div class="form-group  clients-form-container">
      <%= f.label :inputs_interface, 'Input interface:', class: 'col-3 col-form-label' %>
      <div class="col-3">
        <%= f.text_field :inputs_interface, class: 'form-control', placeholder: 'Enter Interface: (e.g. eth0)' %>
      </div>
      <br/>

      <%= f.label :inputs_ip_address, 'Input IP Address:', class: 'col-3 col-form-label' %>
      <div class="col-3">
        <%= f.text_field :inputs_ip_address, class: 'form-control', placeholder: 'Enter IP Address:' %>
      </div>
      <br/>

      <%= f.label :inputs_input_type, 'Input type:', class: 'col-3 col-form-label' %>
      <div class="col-3">
        <%= f.text_field :inputs_input_type, class: 'form-control', placeholder: 'TCP/UDP' %>
      </div>
      <br/>

      <%= f.label :inputs_port_number, 'Input port number:', class: 'col-3 col-form-label' %>
      <div class="col-3">
        <%= f.text_field :inputs_port_number, class: 'form-control', placeholder: 'Enter Port:' %>
      </div>
      <br/>

      <%= f.label :inputs_input_name, 'Input Name:', class: 'col-3 col-form-label' %>
      <div class="col-3">
        <%= f.text_field :inputs_input_name, class: 'form-control', placeholder: 'Enter Ruleset Name)' %>
      </div>
      <br/>
      <div class="form-inline">
        <%= f.label :inputs_tls, 'Enable TLS:', class: 'col-1 col-form-label' %>
        <div class="col-3">
          <%= f.check_box :inputs_tls, class: 'form-control check-box-alignment' %>
        </div>
      </div>
    </div>

    <%= f.submit 'Save Input', class: 'btn btn-primary btn-lg' %>
    <%= link_to 'Cancel', :back, class: 'btn btn-secondary region-btn btn-lg' %>
<% end %>
<br/>
</code>```

Routes

```<code>resources :servers do
    namespace :features do
      resources :rsyslog_inputs
      resources :rsyslog, only: :index
    end
  end

  server_features_rsyslog_inputs            GET     /servers/:server_id/features/rsyslog_inputs(.:format)          features/rsyslog_inputs#index
                                            POST    /servers/:server_id/features/rsyslog_inputs(.:format)          features/rsyslog_inputs#create
 new_server_features_rsyslog_input          GET     /servers/:server_id/features/rsyslog_inputs/new(.:format)      features/rsyslog_inputs#new
edit_server_features_rsyslog_input          GET     /servers/:server_id/features/rsyslog_inputs/:id/edit(.:format) features/rsyslog_inputs#edit
     server_features_rsyslog_input          GET     /servers/:server_id/features/rsyslog_inputs/:id(.:format)      features/rsyslog_inputs#show
                                            PATCH   /servers/:server_id/features/rsyslog_inputs/:id(.:format)      features/rsyslog_inputs#update
                                            PUT     /servers/:server_id/features/rsyslog_inputs/:id(.:format)      features/rsyslog_inputs#update
                                            DELETE  /servers/:server_id/features/rsyslog_inputs/:id(.:format)      features/rsyslog_inputs#destroy
     server_features_rsyslog_index          GET     /servers/:server_id/features/rsyslog_inputs(.:format)          features/rsyslog_inputs#index
</code>```

答:
seeing your forms, controller and the requirement, i would advice that you use the route helpers and pass in the appropriate parameters there

like in your form explicitly set the form url to
server_features_rsyslog_input(server_id: params[:server_id], id: @input.id)

and in your controller too pass in the parameters explicitly

Body:
Good day all, I'm pulling my hair out on this one, I've seen similar posts but none of them get me in the direction I'm trying to go.
That said, I've got a pretty complex app that's relying heavily on nested resources and name-spacing, when I save a record it saves perfectly
and redirects correctly. When I update that same record the URL changes but not as I would expect. I understand the flow from edit to update and
the set_input call pulling the params[:id], what I don't understand is why the URL is changing the parents resource to reflect the record ID.

/servers/1/features/rsyslog_inputs/12/edit"

changes to the following after update

/servers/12/features/rsyslog_inputs/12/edit"

LOGS

Started GET "/servers/1/features/rsyslog_inputs/12/edit" for 127.0.0.1  at 2017-12-08 12:27:55 -0600
Processing by Features::RsyslogInputsController#edit as HTML
  Parameters: {"server_id"=>"1", "id"=>"12"}
  RsyslogInput Load (0.6ms)  SELECT  "rsyslog_inputs".* FROM "rsyslog_inputs" WHERE "rsyslog_inputs"."id" = $1 LIMIT $2  [["id", 12], ["LIMIT", 1]]
  Rendering features/rsyslog_inputs/edit.html.erb within layouts/application
  Rendered shared/_error_messages.html.erb (0.4ms) [cache miss]
  Rendered features/rsyslog_inputs/_form.html.erb (4.3ms) [cache miss]
  Rendered features/rsyslog_inputs/edit.html.erb within layouts/application (6.5ms)
  Rendered layouts/_shim.html.erb (0.5ms) [cache miss]
  User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendered layouts/_navbar_top.html.erb (0.9ms) [cache miss]
  Rendered layouts/_navbar_side.html.erb (0.5ms) [cache miss]
  Completed 200 OK in 90ms (Views: 84.7ms | ActiveRecord: 1.7ms)

Here the PATCH has modified the servers/:id to reflect the id of the rsyslog_inputs and not retained its "1" as shown above

Started PATCH "/servers/12/features/rsyslog_inputs/12" for 127.0.0.1 at 2017-12-08 12:27:58 -0600
Processing by Features::RsyslogInputsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"dFt61NcQWXoKpmScrkngT47ZxDdhzMUcCyJ5fZKrdbaOVqKfLXMVeBUj20zKKHQ8wGe4fi2QEw98cLviyO4wQw==", "rsyslog_input"=>{"inputs_interface"=>"eth04", "inputs_ip_address"=>"1.1.1.1", "inputs_input_type"=>"tcp", "inputs_port_number"=>"22", "inputs_input_name"=>"test02", "inputs_tls"=>"0"}, "commit"=>"Save Input", "appliance_id"=>"12", "id"=>"12"}
  RsyslogInput Load (0.7ms)  SELECT  "rsyslog_inputs".* FROM "rsyslog_inputs" WHERE "rsyslog_inputs"."id" = $1 LIMIT $2  [["id", 12], ["LIMIT", 1]]
  (0.6ms)  BEGIN
  Server Load (1.0ms)  SELECT  "servers".* FROM "servers" WHERE   "servers"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  SQL (1.0ms)  UPDATE "rsyslog_inputs" SET "inputs_interface" = $1, "updated_at" = $2 WHERE "rsyslog_inputs"."id" = $3  [["inputs_interface", "eth04"], ["updated_at", "2017-12-08 18:27:58.904817"], ["id", 12]]
 (0.8ms)  COMMIT

Redirected to http://localhost:3000/servers/12/features/rsyslog_inputs
Completed 302 Found in 12ms (ActiveRecord: 4.0ms)

Controller

class Features::RsyslogInputsController < ApplicationController
  before_action :set_input, only: [:show, :edit, :update, :destroy]

  def index
    # Let's search for all inputs associated with the corresponding appliance
    @inputs = RsyslogInput.where(server_id: params[:server_id])
  end

  def create
    @input = RsyslogInput.new(input_params)
    @input.build_server
    @input.server_id = params[:server_id]
    if @input.save
      flash[:notice] = "Input was successfully saved."
      redirect_to server_features_rsyslog_inputs_path
    else
      render('new')
    end
  end

  def destroy
    if @input.destroy
      flash[:notice] = "Input was successfully destoryed."
      redirect_to server_features_rsyslog_inputs_path
    else
      flash[:alert] = "Unable to destroy #{@input.inputs_input_name}"
    end
  end

  def update

    if @input.update(input_params)
      flash[:notice] = "Input was successfully updated"
      redirect_to server_features_rsyslog_inputs_path
    else
      render('edit')
    end
  end

  def new
    @input = RsyslogInput.new
  end

  def edit; end

  def show ;end

  private

  def set_input
    @input = RsyslogInput.find(params[:id])
  end

  def input_params
    params.require(:rsyslog_input).permit(:inputs_interface,
                                  :inputs_input_type,
                                  :inputs_ip_address,
                                  :inputs_port_number,
                                  :inputs_input_name,
                                  :inputs_tls,
                                  :server_id)
  end

end

Form

<%= form_for ([:server, :features, @input]) do |f| %>
    <%= render 'shared/error_messages', object: f.object %>

      <%= f.label :inputs_interface, 'Input interface:', class: 'col-3 col-form-label' %>

        <%= f.text_field :inputs_interface, class: 'form-control', placeholder: 'Enter Interface: (e.g. eth0)' %>

      <%= f.label :inputs_ip_address, 'Input IP Address:', class: 'col-3 col-form-label' %>

        <%= f.text_field :inputs_ip_address, class: 'form-control', placeholder: 'Enter IP Address:' %>

      <%= f.label :inputs_input_type, 'Input type:', class: 'col-3 col-form-label' %>

        <%= f.text_field :inputs_input_type, class: 'form-control', placeholder: 'TCP/UDP' %>

      <%= f.label :inputs_port_number, 'Input port number:', class: 'col-3 col-form-label' %>

        <%= f.text_field :inputs_port_number, class: 'form-control', placeholder: 'Enter Port:' %>

      <%= f.label :inputs_input_name, 'Input Name:', class: 'col-3 col-form-label' %>

        <%= f.text_field :inputs_input_name, class: 'form-control', placeholder: 'Enter Ruleset Name)' %>

        <%= f.label :inputs_tls, 'Enable TLS:', class: 'col-1 col-form-label' %>

          <%= f.check_box :inputs_tls, class: 'form-control check-box-alignment' %>

    <%= f.submit 'Save Input', class: 'btn btn-primary btn-lg' %>
    <%= link_to 'Cancel', :back, class: 'btn btn-secondary region-btn btn-lg' %>
<% end %>

Routes

resources :servers do
    namespace :features do
      resources :rsyslog_inputs
      resources :rsyslog, only: :index
    end
  end

  server_features_rsyslog_inputs            GET     /servers/:server_id/features/rsyslog_inputs(.:format)          features/rsyslog_inputs#index
                                            POST    /servers/:server_id/features/rsyslog_inputs(.:format)          features/rsyslog_inputs#create
 new_server_features_rsyslog_input          GET     /servers/:server_id/features/rsyslog_inputs/new(.:format)      features/rsyslog_inputs#new
edit_server_features_rsyslog_input          GET     /servers/:server_id/features/rsyslog_inputs/:id/edit(.:format) features/rsyslog_inputs#edit
     server_features_rsyslog_input          GET     /servers/:server_id/features/rsyslog_inputs/:id(.:format)      features/rsyslog_inputs#show
                                            PATCH   /servers/:server_id/features/rsyslog_inputs/:id(.:format)      features/rsyslog_inputs#update
                                            PUT     /servers/:server_id/features/rsyslog_inputs/:id(.:format)      features/rsyslog_inputs#update
                                            DELETE  /servers/:server_id/features/rsyslog_inputs/:id(.:format)      features/rsyslog_inputs#destroy
     server_features_rsyslog_index          GET     /servers/:server_id/features/rsyslog_inputs(.:format)          features/rsyslog_inputs#index


来源: stackexchange

问:
<column> is ambiguous in column comparison between two tables
I want this postgres function to work :

```<code>CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT *
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';
</code>```

This stand alone query works just fine:

```<code>SELECT *
FROM sports.match_history
WHERE match_id NOT IN (SELECT match_id FROM sports.match_results);
</code>```

But when I put it into this function and try to run it like this:

```<code>select *
from difference_of_match_ids_in_match_history_and_match_results();
</code>```

I get this:

SQL Error [42702]: ERROR: column reference "match_id" is ambiguous

  Detail: It could refer to either a PL/pgSQL variable or a table
  column.   Where: PL/pgSQL function
  difference_of_match_ids_in_match_history_and_match_results() line 3 at
  RETURN QUERY

I've seen other questions with this same error, and they suggest naming the sub queries to specify which instance of a column you're referring to, however, those examples use joins and my query works fine outside of the function.

If I do need to name the column, how would I do so with only one sub-query?

If that isn't the issue, then I'm assuming that there's something wrong with the way I'm defining a function.

答:
As others have answerd, it's an ambiguity between the result definition and PL/pgSQL variables. The column name in a set returning function is in fact also a variable inside the function.

But you don't need PL/pgSQL for this in the first place. If you use a plain SQL function it will be more efficient and the problem will go away as well:

```<code>CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
  SELECT match_id --<< do not return * - only return one column
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
$$
LANGUAGE sql;
</code>```

Note that the language name is an identifier and should not be quoted at all.

ContentLicense: CC BY-SA 3.0

Body:
I want this postgres function to work :

CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT *
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';

This stand alone query works just fine:

SELECT *
FROM sports.match_history
WHERE match_id NOT IN (SELECT match_id FROM sports.match_results);

But when I put it into this function and try to run it like this:

select *
from difference_of_match_ids_in_match_history_and_match_results();

I get this:

SQL Error [42702]: ERROR: column reference "match_id" is ambiguous

  Detail: It could refer to either a PL/pgSQL variable or a table
  column.   Where: PL/pgSQL function
  difference_of_match_ids_in_match_history_and_match_results() line 3 at
  RETURN QUERY

I've seen other questions with this same error, and they suggest naming the sub queries to specify which instance of a column you're referring to, however, those examples use joins and my query works fine outside of the function.

If I do need to name the column, how would I do so with only one sub-query?

If that isn't the issue, then I'm assuming that there's something wrong with the way I'm defining a function.

Body:
As others have answerd, it's an ambiguity between the result definition and PL/pgSQL variables. The column name in a set returning function is in fact also a variable inside the function.

But you don't need PL/pgSQL for this in the first place. If you use a plain SQL function it will be more efficient and the problem will go away as well:

CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
  SELECT match_id --<< do not return * - only return one column
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
$$
LANGUAGE sql;

Note that the language name is an identifier and should not be quoted at all.


问:
Find single unique value in list of tuples

I have a list of key-value pairs in tuples, and it's known that one (and only one) of those tuples will contain a different value.  The keys are all different.  For example,

```<code>pairs = [
         ('John', 101991),
         ('Bob', 101991),
         ('Tom', 101997),
         ('Larry', 101991),
         ('Howard', 101991)
         ]
</code>```

I need to identify the key of the tuple with the different value.  It is not known whether this value will be larger or smaller than the others.

How can I accomplish this?

答:
I'd pick out just a list of the keys and a list of the values separately by unzipping:

```<code>keys, vals = zip(*pairs)
</code>```

Then I'd count the number of each unique value with numpy:

```<code>unique, counts = np.unique(vals, return_counts=True)
</code>```

And the value you want is the one with the smallest counts:

```<code>myminval = unique[np.argmin(counts)]
</code>```

Then you find this value in your list of keys:

```<code>keys[vals.index(myminval)]
</code>```

Body:
I have a list of key-value pairs in tuples, and it's known that one (and only one) of those tuples will contain a different value.  The keys are all different.  For example,

pairs = [
         ('John', 101991),
         ('Bob', 101991),
         ('Tom', 101997),
         ('Larry', 101991),
         ('Howard', 101991)
         ]

I need to identify the key of the tuple with the different value.  It is not known whether this value will be larger or smaller than the others.

How can I accomplish this?

Body:
I'd pick out just a list of the keys and a list of the values separately by unzipping:

keys, vals = zip(*pairs)

Then I'd count the number of each unique value with numpy:

unique, counts = np.unique(vals, return_counts=True)

And the value you want is the one with the smallest counts:

myminval = unique[np.argmin(counts)]

Then you find this value in your list of keys:

keys[vals.index(myminval)]


问:
how can i get avatar (profile picture) of email id in gmail addon
I want to read a particular thread of email and get its email ids, in to,from,cc.
also I want to get their profile pictures and name to display in the addon.

I tried to get using metadata but was not able to get it

Note : I am able to get the email ids.
but for some I am not getting the names.
I am not able to get profile pictures for all

so i need a way by which i can get profile picture and name of all email ids

答:
It’s only possible to get your own profile picture
as you do not have permission to access someone else’s.  So if you’re deploying an
addon, the user will be able to see their own
profile pic.

As far as getting the name, not quite sure what you mean.  The full name of a contact?  The name of the the person sending you the email?

To get the name of someone that’s sent you an email that’s not one of your contacts, it’s not possible.  For a contact that emails you, it’s quite simple.  Here is the reference for the ContactsApp:  first grab the contact by the email address, and then on the contact object, there is a method to get the fullName.

https://developers.google.com/apps-script/reference/contacts/contacts-app


问:
Time::Piece (localtime/gmtime) calculation vs bash date
Have this bash script:

```<code>future="${1:-Dec 08 2017 22:00:00}"
t1=$(date -j -f "%b %d %Y %H:%M:%S" "$future" +%s)  #using OS X
t0=$(date +%s)

echo "Current: $(date)"
echo "Future : $future"
echo "Diff   : $(( $t1 - $t0 )) secs"
</code>```

It prints:

```<code>Current: pi   8. december 2017 21:25:25 CET
Future : Dec 08 2017 22:00:00
Diff   : 2075 secs
</code>```

The result (diff) is correct.

Now trying to do the same using perl:

```<code>use strict;
use warnings;
use feature 'say';

use Time::Piece;

my $format = '%b %d %Y %H:%M:%S';

my $future = shift // 'Dec 08 2017 22:00:00';
say "Future: $future";

say "localtime: ", scalar localtime();
say "gmtime   : ", scalar gmtime();

my $tf = Time::Piece->strptime($future, $format);
say 'localtime-diff : ', $tf-localtime();
say 'gmtime-diff    : ', $tf-gmtime();
</code>```

it prints

```<code>Future: Dec 08 2017 22:00:00
localtime: Fri Dec  8 21:27:45 2017  #correct
gmtime   : Fri Dec  8 20:27:45 2017  #correct
localtime-diff : 5535 #incorrect (expecting 3600 secs less)
gmtime-diff    : 5535 #ok
</code>```

What is wrong? Mean, why it prints the same diff for the localtime and gmtime but the scalar localtime and scalar gmtime prints different (and correct) strings?

EDIT: So, the main question is: how to get the same result as in bash using perl?

答:
Both localtime() and gmtime() return an object that represents now.

You are doing:

```<code>2017-12-08T22:00:00+00:00 - 2017-12-08T21:25:25+01:00   # $tf-localtime()
2017-12-08T22:00:00+00:00 - 2017-12-08T20:25:25+00:00   # $tf-gmtime()
</code>```

It looks like you want to do

```<code>2017-12-08T22:00:00+01:00 - 2017-12-08T21:25:25+01:00
</code>```

Using Time::Piece:

```<code>use Time::Piece qw( localtime );

my $future_str = 'Dec 08 2017 23:00:00';

my $format = '%b %d %Y %H:%M:%S';

my $future_dt = localtime->strptime($future_str, $format);
say $future_dt - localtime();  # 2241 (instead of 5841)
</code>```

Using DateTime:

```<code>use DateTime::Format::Strptime qw( );

my $future_str = 'Dec 08 2017 23:00:00';

my $format = DateTime::Format::Strptime->new(
   pattern   => '%b %d %Y %H:%M:%S',
   locale    => 'en',
   time_zone => 'local',
   on_error  => 'croak',
);

my $future_dt = $format->parse_datetime($future_str);
say $future_dt->epoch - time();  # 2241 (instead of 5841)
</code>```

Body:
Have this bash script:

future="${1:-Dec 08 2017 22:00:00}"
t1=$(date -j -f "%b %d %Y %H:%M:%S" "$future" +%s)  #using OS X
t0=$(date +%s)

echo "Current: $(date)"
echo "Future : $future"
echo "Diff   : $(( $t1 - $t0 )) secs"

It prints:

Current: pi   8. december 2017 21:25:25 CET
Future : Dec 08 2017 22:00:00
Diff   : 2075 secs

The result (diff) is correct.

Now trying to do the same using perl:

use strict;
use warnings;
use feature 'say';

use Time::Piece;

my $format = '%b %d %Y %H:%M:%S';

my $future = shift // 'Dec 08 2017 22:00:00';
say "Future: $future";

say "localtime: ", scalar localtime();
say "gmtime   : ", scalar gmtime();

my $tf = Time::Piece->strptime($future, $format);
say 'localtime-diff : ', $tf-localtime();
say 'gmtime-diff    : ', $tf-gmtime();

it prints

Future: Dec 08 2017 22:00:00
localtime: Fri Dec  8 21:27:45 2017  #correct
gmtime   : Fri Dec  8 20:27:45 2017  #correct
localtime-diff : 5535 #incorrect (expecting 3600 secs less)
gmtime-diff    : 5535 #ok

What is wrong? Mean, why it prints the same diff for the localtime and gmtime but the scalar localtime and scalar gmtime prints different (and correct) strings?

EDIT: So, the main question is: how to get the same result as in bash using perl?

Body:
Both localtime() and gmtime() return an object that represents now.

You are doing:

2017-12-08T22:00:00+00:00 - 2017-12-08T21:25:25+01:00   # $tf-localtime()
2017-12-08T22:00:00+00:00 - 2017-12-08T20:25:25+00:00   # $tf-gmtime()

It looks like you want to do

2017-12-08T22:00:00+01:00 - 2017-12-08T21:25:25+01:00

Using Time::Piece:

use Time::Piece qw( localtime );

my $future_str = 'Dec 08 2017 23:00:00';

my $format = '%b %d %Y %H:%M:%S';

my $future_dt = localtime->strptime($future_str, $format);
say $future_dt - localtime();  # 2241 (instead of 5841)

Using DateTime:

use DateTime::Format::Strptime qw( );

my $future_str = 'Dec 08 2017 23:00:00';

my $format = DateTime::Format::Strptime->new(
   pattern   => '%b %d %Y %H:%M:%S',
   locale    => 'en',
   time_zone => 'local',
   on_error  => 'croak',
);

my $future_dt = $format->parse_datetime($future_str);
say $future_dt->epoch - time();  # 2241 (instead of 5841)


问:
add columns that are not in dataframe but present in another index
Assume I have a dataframe with several named columns

```<code>df = pd.DataFrame({'foo': [1, 2], 'bar': [3, 4]})
</code>```

I also have some index of names:

```<code>all_columns = pd.Index(['foo', 'baz', 'bar', 'quux'])
</code>```

What I want is to add empty columns to df with column names from all_columns that are not present in df yet. So the desired output is:

```<code>   bar  foo  baz  quux
0    3    1  NaN   NaN
1    4    2  NaN   NaN
</code>```

I'd like to do it in method-chaining style, preserving original dataframe, so I'm looking for something like:

```<code>df.some_magick_column_appender(all_columns)
</code>```

答:
By using reindex

```<code>df.reindex(columns=['foo', 'baz', 'bar', 'quux'])
Out[659]:
   foo  baz  bar  quux
0    1  NaN    3   NaN
1    2  NaN    4   NaN
</code>```

Body:
Assume I have a dataframe with several named columns

df = pd.DataFrame({'foo': [1, 2], 'bar': [3, 4]})

I also have some index of names:

all_columns = pd.Index(['foo', 'baz', 'bar', 'quux'])

What I want is to add empty columns to df with column names from all_columns that are not present in df yet. So the desired output is:

   bar  foo  baz  quux
0    3    1  NaN   NaN
1    4    2  NaN   NaN

I'd like to do it in method-chaining style, preserving original dataframe, so I'm looking for something like:

df.some_magick_column_appender(all_columns)

Body:
By using reindex

df.reindex(columns=['foo', 'baz', 'bar', 'quux'])
Out[659]:
   foo  baz  bar  quux
0    1  NaN    3   NaN
1    2  NaN    4   NaN


问:
mirror prime generator python
I am currently enrolled in a Python programming course and last week we got a homework problem which was to Develop a program to generate all prime numbers less or equal to n whose mirror is also prime, I can't see where I am going wrong, please help!

```<code>import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
        for d in range (3, int(math.sqrt(n))+1, 2):
            if n%d==0:
                answer=False
            # End if
        # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if

def mirror_prime_generator(n):
    for i in range(3, n+1):
        print (mirror_prime(i))
</code>```

I am expecting to get a list of all prime numbers whose mirror is also prime less or equal to n

The result i get when i put mirror_prime_generator(n) into the shell, it justs prints none however many times n is, so if n is 23 it will print none 23 times

答:
This is my code in the end after editing, it now does what I want it to do, thanks everyone for the help</p>

```<code>import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
    for d in range (3, int(math.sqrt(n))+1, 2):
        if n%d==0:
            answer=False
        # End if

    # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if
    # Test even numbers
    if n != 2 and n%2==0:
        mirror_answer= False
    # End if

    # Test if there is a proper odd divisor
    for d in range (3, int(math.sqrt(mirror_n))+1, 2):
        if mirror_n%d==0:
            mirror_answer=False
        # End if

        # End for

    if answer and mirror_answer==True:
        return n, mirror_n

def mirror_prime_generator(n):
    for i in range(3, n+1):
        if mirror_prime(i):
            print(i)
</code>```

Title: mirror prime generator python

Body:
I am currently enrolled in a Python programming course and last week we got a homework problem which was to Develop a program to generate all prime numbers less or equal to n whose mirror is also prime, I can't see where I am going wrong, please help!

import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
        for d in range (3, int(math.sqrt(n))+1, 2):
            if n%d==0:
                answer=False
            # End if
        # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if

def mirror_prime_generator(n):
    for i in range(3, n+1):
        print (mirror_prime(i))

I am expecting to get a list of all prime numbers whose mirror is also prime less or equal to n

The result i get when i put mirror_prime_generator(n) into the shell, it justs prints none however many times n is, so if n is 23 it will print none 23 times

Body:
This is my code in the end after editing, it now does what I want it to do, thanks everyone for the help

import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
    for d in range (3, int(math.sqrt(n))+1, 2):
        if n%d==0:
            answer=False
        # End if

    # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if
    # Test even numbers
    if n != 2 and n%2==0:
        mirror_answer= False
    # End if

    # Test if there is a proper odd divisor
    for d in range (3, int(math.sqrt(mirror_n))+1, 2):
        if mirror_n%d==0:
            mirror_answer=False
        # End if

        # End for

    if answer and mirror_answer==True:
        return n, mirror_n

def mirror_prime_generator(n):
    for i in range(3, n+1):
        if mirror_prime(i):
            print(i)


问:
bar chart not displaying
my bar chart is not displaying on my web page..help me on how to make it visible by setting the barchat.visible...thats where am getting the error.</p>

```<code>public void BindGrid()
{
    string query = "select Customer, COUNT([Total Amount]) [Total Amount] from CustomerDebts group by Customer";
    DataTable dt = GetData(query);

    string[] x = new string[dt.Rows.Count];
    decimal[] y = new decimal[dt.Rows.Count];
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        x[i] = dt.Rows[i][0].ToString();
        y[i] = Convert.ToInt32(dt.Rows[i][1]);
    }
    BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
    BarChart1.CategoriesAxis = string.Join(",", x);
     if (x.Length > 3)
    {
        BarChart1.ChartWidth = (x.Length * 150).ToString();
    }
    BarChart1.Visible;
}

private static DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = TraceBizCommon.Configuration.ConfigSettings.ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
        return dt;
    }
}
</code>```

答:
BarChart.Visible is a property that needs an assignment, such as;

```<code>BarChart.Visible = true;
</code>```

Take a look at the example here: https://www.aspsnippets.com/Articles/ASPNet-AJAX-Bar-Chart-Control-Populate-from-Database-example.aspx

Further information on the Chart class can be seen here: https://msdn.microsoft.com/en-us/library/system.web.ui.datavisualization.charting.chart(v=vs.110).aspx

Title: bar chart not displaying

Body:
my bar chart is not displaying on my web page..help me on how to make it visible by setting the barchat.visible...thats where am getting the error.

public void BindGrid()
{
    string query = "select Customer, COUNT([Total Amount]) [Total Amount] from CustomerDebts group by Customer";
    DataTable dt = GetData(query);

    string[] x = new string[dt.Rows.Count];
    decimal[] y = new decimal[dt.Rows.Count];
    for (int i = 0; i
 3)
    {
        BarChart1.ChartWidth = (x.Length * 150).ToString();
    }
    BarChart1.Visible;
}

private static DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = TraceBizCommon.Configuration.ConfigSettings.ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
        return dt;
    }
}

Body:
BarChart.Visible is a property that needs an assignment, such as;

BarChart.Visible = true;

Take a look at the example here: https://www.aspsnippets.com/Articles/ASPNet-AJAX-Bar-Chart-Control-Populate-from-Database-example.aspx

Further information on the Chart class can be seen here: https://msdn.microsoft.com/en-us/library/system.web.ui.datavisualization.charting.chart(v=vs.110).aspx


问:
Combining Text from a table into a blob
In my code I have a blob of data that I am separating out into a table to make it look more presentable. This is working fine and it's pretty awesome.

However, I'm having an issue putting the data back together so I can store it back as that unsightly blob because I cannot change any of the backend.

I've tried just a simple concatenation, but it's printing the classes in separate rows when they need to be bunched back together. Any ideas?

```<code><table class="table" id="DataTables_Table_5">
  <thead style="display:none;">
    <tr role="row">
      <th name="date" scope="col" class="sorting_disabled commentDate" rowspan="1" colspan="1" style="width: 0px;">Invalid date</th>
      <th name="user" scope="col" class="sorting_disabled commentUser" rowspan="1" colspan="1" style="width: 0px;">UserName</th>
      <th name="comment" scope="col" class="sorting_disabled commentComment" rowspan="1" colspan="1" style="width: 0px;">Comment</th>
    </tr>
  </thead>
  <tbody>
    <tr role="row" class="odd">
      <td class=" commentDate">Fr 01 12, 2017</td>
      <td class=" commentUser">Demo</td>
      <td class=" commentComment">skvbgskjhbgswdjefv</td>
    </tr>
    <tr role="row" class="even">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMO</td>
      <td class=" commentComment">This issvgswrgwrgwrgwrg</td>
    </tr>
    <tr role="row" class="odd">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMOoooo</td>
      <td class=" commentComment">Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. </td>
    </tr>
    <tr role="row" class="even">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMO DEMO</td>
      <td class=" commentComment">This is a short comment after the super long comment</td>
    </tr>
  </tbody>
</table>
</code>```

and the js I have tried looks like this

```<code>$(".commentDate").text()+ '\n' + $(".commentUser").text() + '\n\n' + $(".commentComment").text()+ '\n\n'
</code>```

https://www.bootply.com/8sDFSzV22Y

答:
You need to read each row and then read each cell of each row to concatenate.

var rows = document.querySelectorAll( '#DataTables_Table_5 tr' );
var lines = [];

// Read each row
for ( var i = 0; i < rows.length; ++i ) {
  var r = rows[ i ];
  // Read each cell
  var cells = [].slice.call( r.querySelectorAll( 'td, th' ) )
    .map( function( c ) { return c.innerText } );
  // Collect concatenated cells
  lines.push( cells.join( ',' ) );
}

console.log( lines.join( '\n\n' ) );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table" id="DataTables_Table_5">
  <thead style="display:none;">
    <tr role="row">
      <th name="date" scope="col" class="sorting_disabled commentDate" rowspan="1" colspan="1" style="width: 0px;">Invalid date</th>
      <th name="user" scope="col" class="sorting_disabled commentUser" rowspan="1" colspan="1" style="width: 0px;">UserName</th>
      <th name="comment" scope="col" class="sorting_disabled commentComment" rowspan="1" colspan="1" style="width: 0px;">Comment</th>
    </tr>
  </thead>
  <tbody>
    <tr role="row" class="odd">
      <td class=" commentDate">Fr 01 12, 2017</td>
      <td class=" commentUser">Demo</td>
      <td class=" commentComment">skvbgskjhbgswdjefv</td>
    </tr>
    <tr role="row" class="even">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMO</td>
      <td class=" commentComment">This issvgswrgwrgwrgwrg</td>
    </tr>
    <tr role="row" class="odd">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMOoooo</td>
      <td class=" commentComment">Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. </td>
    </tr>
    <tr role="row" class="even">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMO DEMO</td>
      <td class=" commentComment">This is a short comment after the super long comment</td>
    </tr>
  </tbody>
</table></code>```

Title: Combining Text from a table into a blob

Body:
In my code I have a blob of data that I am separating out into a table to make it look more presentable. This is working fine and it's pretty awesome.

However, I'm having an issue putting the data back together so I can store it back as that unsightly blob because I cannot change any of the backend.

I've tried just a simple concatenation, but it's printing the classes in separate rows when they need to be bunched back together. Any ideas?

      Invalid date
      UserName
      Comment

      Fr 01 12, 2017
      Demo
      skvbgskjhbgswdjefv

      Mo 04 12, 2017
      DEMO
      This issvgswrgwrgwrgwrg

      Mo 04 12, 2017
      DEMOoooo
      Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome.

      Mo 04 12, 2017
      DEMO DEMO
      This is a short comment after the super long comment

and the js I have tried looks like this

$(".commentDate").text()+ '\n' + $(".commentUser").text() + '\n\n' + $(".commentComment").text()+ '\n\n'

https://www.bootply.com/8sDFSzV22Y

Body:
You need to read each row and then read each cell of each row to concatenate.

var rows = document.querySelectorAll( '#DataTables_Table_5 tr' );
var lines = [];

// Read each row
for ( var i = 0; i < rows.length; ++i ) {
  var r = rows[ i ];
  // Read each cell
  var cells = [].slice.call( r.querySelectorAll( 'td, th' ) )
    .map( function( c ) { return c.innerText } );
  // Collect concatenated cells
  lines.push( cells.join( ',' ) );
}

console.log( lines.join( '\n\n' ) );

<table class="table" id="DataTables_Table_5">
  <thead style="display:none;">
    <tr role="row">
      <th name="date" scope="col" class="sorting_disabled commentDate" rowspan="1" colspan="1" style="width: 0px;">Invalid date</th>
      <th name="user" scope="col" class="sorting_disabled commentUser" rowspan="1" colspan="1" style="width: 0px;">UserName</th>
      <th name="comment" scope="col" class="sorting_disabled commentComment" rowspan="1" colspan="1" style="width: 0px;">Comment</th>
    </tr>
  </thead>
  <tbody>
    <tr role="row" class="odd">
      <td class=" commentDate">Fr 01 12, 2017</td>
      <td class=" commentUser">Demo</td>
      <td class=" commentComment">skvbgskjhbgswdjefv</td>
    </tr>
    <tr role="row" class="even">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMO</td>
      <td class=" commentComment">This issvgswrgwrgwrgwrg</td>
    </tr>
    <tr role="row" class="odd">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMOoooo</td>
      <td class=" commentComment">Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. Super long. Super aewsome. </td>
    </tr>
    <tr role="row" class="even">
      <td class=" commentDate">Mo 04 12, 2017</td>
      <td class=" commentUser">DEMO DEMO</td>
      <td class=" commentComment">This is a short comment after the super long comment</td>
    </tr>
  </tbody>
</table>


问:
Laravel dusk + docker-compose + selenium + firefox: Undefined index ELEMENT
I have docker-compose with 3 images - webserver, db and selenium.

I up it then exec into webserver and run php artisan dusk.

My app is a simple https page that returns Welcome in a few div.
But I got ErrorException: Undefined index: ELEMENT.

Selenium image: selenium/standalone-firefox.

```<code>test:
...
$this->browse(function (Browser $browser) use ($user) {
  $browser
    ->visit('/home')
    ->assertSee('Welcome');
});

DuskTestCase.php
...
protected function driver() {
  return RemoteWebDriver::create(
    'http://selenium:4444/wd/hub', DesiredCapabilities::firefox()->setCapability(
      'acceptInsecureCerts', true
    )
  );
}
</code>```

答:
This is due to an incompatibility between the geckodriver and Selenium:

https://github.com/facebook/php-webdriver/issues/492

For Firefox and Selenium you need to add enablePassThrough=false to the Selenium capabilities.

Something like:

```<code>protected function driver() {
  return RemoteWebDriver::create(
    'http://selenium:4444/wd/hub', DesiredCapabilities::firefox()
        ->setCapability('acceptInsecureCerts', true)
        ->setCapability('enablePassThrough', false)
  );
}
</code>```

should probably do the trick.

Body:
I have docker-compose with 3 images - webserver, db and selenium.

I up it then exec into webserver and run php artisan dusk.

My app is a simple https page that returns Welcome in a few div.
But I got ErrorException: Undefined index: ELEMENT.

Selenium image: selenium/standalone-firefox.

test:
...
$this->browse(function (Browser $browser) use ($user) {
  $browser
    ->visit('/home')
    ->assertSee('Welcome');
});

DuskTestCase.php
...
protected function driver() {
  return RemoteWebDriver::create(
    'http://selenium:4444/wd/hub', DesiredCapabilities::firefox()->setCapability(
      'acceptInsecureCerts', true
    )
  );
}

Body:
This is due to an incompatibility between the geckodriver and Selenium:

https://github.com/facebook/php-webdriver/issues/492

For Firefox and Selenium you need to add enablePassThrough=false to the Selenium capabilities.

Something like:

protected function driver() {
  return RemoteWebDriver::create(
    'http://selenium:4444/wd/hub', DesiredCapabilities::firefox()
        ->setCapability('acceptInsecureCerts', true)
        ->setCapability('enablePassThrough', false)
  );
}

should probably do the trick.


问:
What does Spark recover the data from a failed node?
Suppose we have an RDD, which is being used multiple times. So to save the computations again and again, we persisted this RDD using the rdd.persist() method.

So when we are persisting this RDD, the nodes computing the RDD will be storing their partitions.

So now suppose, the node containing this persisted partition of RDD fails, then what will happen? How will spark recover the lost data? Is there any replication mechanism? Or some other mechanism?

答:
I think the best way I was able to understand how Spark is resilient was when someone told me that I should not think of RDDs as big, distributed arrays of data.

Instead I should picture them as a container that had instructions on what steps to take to convert data from data source and take one step at a time until a result was produced.

Now if you really care about losing data when persisting, then you can specify that you want to replicate your cached data.

For this, you need to select storage level. So instead of normally using this:

```<code>MEMORY_ONLY - Store RDD as deserialized Java objects in the JVM. If the RDD does not fit in memory, some partitions will not be cached and will be recomputed on the fly each time they're needed. This is the default level.
MEMORY_AND_DISK - Store RDD as deserialized Java objects in the JVM. If the RDD does not fit in memory, store the partitions that don't fit on disk, and read them from there when they're needed.
</code>```

You can specify that you want your persisted data replcated

```<code>MEMORY_ONLY_2, MEMORY_AND_DISK_2, etc. -    Same as the levels above, but replicate each partition on two cluster nodes.
</code>```

So if the node fails, you will not have to recompute the data.

Check storage levels here: http://spark.apache.org/docs/latest/rdd-programming-guide.html#rdd-persistence

Body:
I think the best way I was able to understand how Spark is resilient was when someone told me that I should not think of RDDs as big, distributed arrays of data.

Instead I should picture them as a container that had instructions on what steps to take to convert data from data source and take one step at a time until a result was produced.

Now if you really care about losing data when persisting, then you can specify that you want to replicate your cached data.

For this, you need to select storage level. So instead of normally using this:

MEMORY_ONLY - Store RDD as deserialized Java objects in the JVM. If the RDD does not fit in memory, some partitions will not be cached and will be recomputed on the fly each time they're needed. This is the default level.
MEMORY_AND_DISK - Store RDD as deserialized Java objects in the JVM. If the RDD does not fit in memory, store the partitions that don't fit on disk, and read them from there when they're needed.

You can specify that you want your persisted data replcated

MEMORY_ONLY_2, MEMORY_AND_DISK_2, etc. -    Same as the levels above, but replicate each partition on two cluster nodes.

So if the node fails, you will not have to recompute the data.

Check storage levels here: http://spark.apache.org/docs/latest/rdd-programming-guide.html#rdd-persistence


问:
How to convert specific algorithm with streams
The task is to return String with sum of every letter. The input is also a String.

For example

```<code>input: dasamdw
output: s1d2a2m1w1
</code>```

I came out with a simple quick algorithm:

```<code>private String method(String input) {
    Map<String, Integer> integerMap = new HashMap<>();
    for( char c : input.toCharArray()) {
        String key = String.valueOf(c);
        if(integerMap.containsKey(key)) {
            integerMap.put(key, integerMap.get(key) + 1);
        } else {
            integerMap.put(key, 1);
        }
    }

    StringBuilder sb = new StringBuilder();
    for(Map.Entry<String, Integer> e : integerMap.entrySet()) {
        sb.append(e.getKey());
        sb.append(e.getValue());
    }
    return sb.toString();
}
</code>```

But I really would like to use streams for that, someting like:

```<code>private String method(String input) {
    Map<Character, Integer> collect =
        input.chars().
        mapToObj(i -> (char)i).collect(Collectors.groupingBy(Function.identity(), Collectors.counting() ));

    return collect.entrySet()
                    .stream()
                    .map(entry -> entry.getKey() + "" + entry.getValue())
                    .collect(Collectors.joining(""));
}
</code>```

But I can't figure out the right groupingBy part...

答:
as Collectors.counting() returns Long, you'll need to change the map target type from:

```<code>Map<Character, Integer> collect
</code>```

to

```<code>Map<Character, Long> collect
</code>```

That aside, you can combine your groupingBy and joining
 collectors by using Collectors.collectingAndThen i.e:

```<code>return Arrays.stream(input.split(""))
             .collect(
                 collectingAndThen(groupingBy(identity(), counting()),
                         e -> e.entrySet()
                               .stream()
                               .map(entry -> entry.getKey() + entry.getValue())
                               .collect(joining())));
</code>```

make sure to use the imports:

```<code>import static java.util.stream.Collectors.*;
import static java.util.function.Function.*;
</code>```

Body:
The task is to return String with sum of every letter. The input is also a String.

For example

input: dasamdw
output: s1d2a2m1w1

I came out with a simple quick algorithm:

private String method(String input) {
    Map<String, Integer> integerMap = new HashMap<>();
    for( char c : input.toCharArray()) {
        String key = String.valueOf(c);
        if(integerMap.containsKey(key)) {
            integerMap.put(key, integerMap.get(key) + 1);
        } else {
            integerMap.put(key, 1);
        }
    }

    StringBuilder sb = new StringBuilder();
    for(Map.Entry<String, Integer> e : integerMap.entrySet()) {
        sb.append(e.getKey());
        sb.append(e.getValue());
    }
    return sb.toString();
}

But I really would like to use streams for that, someting like:

private String method(String input) {
    Map<Character, Integer> collect =
        input.chars().
        mapToObj(i -> (char)i).collect(Collectors.groupingBy(Function.identity(), Collectors.counting() ));

    return collect.entrySet()
                    .stream()
                    .map(entry -> entry.getKey() + "" + entry.getValue())
                    .collect(Collectors.joining(""));
}

But I can't figure out the right groupingBy part...

Body:
as Collectors.counting() returns Long, you'll need to change the map target type from:

Map<Character, Integer> collect

to

Map<Character, Long> collect

That aside, you can combine your groupingBy and joining
 collectors by using Collectors.collectingAndThen i.e:

return Arrays.stream(input.split(""))
             .collect(
                 collectingAndThen(groupingBy(identity(), counting()),
                         e -> e.entrySet()
                               .stream()
                               .map(entry -> entry.getKey() + entry.getValue())
                               .collect(joining())));

make sure to use the imports:

import static java.util.stream.Collectors.*;
import static java.util.function.Function.*;


问:
Tactics with variable arity
Say I want to have a tactic to clear multiple hypothesis at once, to do something like clear_multiple H1, H2, H3.. I tried to do that using pairs, like the following:

```<code>Ltac clear_multiple arg :=
match arg with
| (?f, ?s) => clear s; clear_multiple f
| ?f => clear f
end.
</code>```

But then, the problem is that I have to place parenthesis to have a Prod:

```<code>Variable A: Prop.

Goal A -> A -> A -> True.
intros.
clear_multiple (H, H0, H1).
</code>```

My question is, how to do that without using Prods ?

I checked this question, but it is not exactly what I want, since the number of arguments I want is not known.

答:
You might like to know that the clear tactic can take multiple arguments, so you do not need to define a new tactic: you can just write clear H H0 H1.

Of course, you might want to define such n-ary tactics for other tasks.  Coq has a tactic notation mechanism that supports such definitions.  Unfortunately, they are not too powerful: you can only pass a list of arguments of a certain kind to a tactic that expects multiple arguments (like clear); I don't think it can give you a list that you can iterate on programmatically.

Title: Tactics with variable arity

Body:
Say I want to have a tactic to clear multiple hypothesis at once, to do something like clear_multiple H1, H2, H3.. I tried to do that using pairs, like the following:

Ltac clear_multiple arg :=
match arg with
| (?f, ?s) => clear s; clear_multiple f
| ?f => clear f
end.

But then, the problem is that I have to place parenthesis to have a Prod:

Variable A: Prop.

Goal A -> A -> A -> True.
intros.
clear_multiple (H, H0, H1).

My question is, how to do that without using Prods ?

I checked this question, but it is not exactly what I want, since the number of arguments I want is not known.


问:
How to limit Jenkins concurrent multibranch pipeline builds across branches?
Does anybody have an idea how to limit concurrent builds with a declarative pipeline set up in a multibranch job across branches?

Anytime we set an agent for a stage, a new executor will be allocated. This leads to deadlocks e.g. when you have builds triggered concurrently for as many branches as you have executors. Not setting an agent leads to the stage chosing an executor randomly, which isn't acceptable as certain stages need to run on certain agents...

The classic approaches don't work:

Throttle Concurrent Builds Plugin doesn't work with multibranch

Setting properties([disableConcurrentBuilds()]) just limits concurrency per branch

the lock step needs agent none in the pipeline root to prevent allocating executors, but this hinders our global post block to execute suff as it needs an agent and apparently one cannot set an agent for the post block

答:
This question is a bit old and I'm not sure that the solution existed at the time, but if you set an agent on each stage, then it should not deadlock unless you have a dependency on another build that uses an agent.  Doing the below part will also execute the post block on the same node as the agent specified in the respective stage.
I've also added another pipeline post section at the end that you might need if you have to run the post block for the entire pipeline and need to have it run on the same agent used in a previous stage.  Hope this helps!</p>

```<code>def agentNameStage2 = null
pipeline {
    agent none
    stages {
        stage("Stage 1") {
            agent { label "somelabel" }
            steps {
                println getContext(hudson.model.Node)
            }
        }
        stage("Stage 2") {
            agent { label "anotherlabel" }
            steps {
                script {
                    def agentStage2 = getContext(hudson.model.Node)
                    println agentStage2

                    // Either use this hack or add whitelist hudson.model.Node getNodeName and use agentStage2.nodeName
                    //agentNameStage2 = agentStage2.nodeName // <-- Best method that needs whitelisting or to run as trusted
                    agentNameStage2 = agentStage2.toString().replaceAll('.*?\\[', '').replaceAll('\\]$', '')
                }
            }
            post {
                always {
                    // Running on an agent with "anotherlabel"
                   println getContext(hudson.model.Node)
                }
            }
        }
    }

    post {
        always {
            script {
                if(agentNameStage2) {
                    // Note this doesn't guarantee the same workspace as was used in the above Stage 2 section
                    node (agentNameStage2) {
                        println "Pipeline post is running on: " + getContext(hudson.model.Node)
                    }
                } else {
                    // Handle else case
                }
            }
        }
    }
}
</code>```

Body:
This question is a bit old and I'm not sure that the solution existed at the time, but if you set an agent on each stage, then it should not deadlock unless you have a dependency on another build that uses an agent.  Doing the below part will also execute the post block on the same node as the agent specified in the respective stage.
I've also added another pipeline post section at the end that you might need if you have to run the post block for the entire pipeline and need to have it run on the same agent used in a previous stage.  Hope this helps!

def agentNameStage2 = null
pipeline {
    agent none
    stages {
        stage("Stage 1") {
            agent { label "somelabel" }
            steps {
                println getContext(hudson.model.Node)
            }
        }
        stage("Stage 2") {
            agent { label "anotherlabel" }
            steps {
                script {
                    def agentStage2 = getContext(hudson.model.Node)
                    println agentStage2

                    // Either use this hack or add whitelist hudson.model.Node getNodeName and use agentStage2.nodeName
                    //agentNameStage2 = agentStage2.nodeName // <-- Best method that needs whitelisting or to run as trusted
                    agentNameStage2 = agentStage2.toString().replaceAll('.*?\\[', '').replaceAll('\\]$', '')
                }
            }
            post {
                always {
                    // Running on an agent with "anotherlabel"
                   println getContext(hudson.model.Node)
                }
            }
        }
    }

    post {
        always {
            script {
                if(agentNameStage2) {
                    // Note this doesn't guarantee the same workspace as was used in the above Stage 2 section
                    node (agentNameStage2) {
                        println "Pipeline post is running on: " + getContext(hudson.model.Node)
                    }
                } else {
                    // Handle else case
                }
            }
        }
    }
}


问:
Neo4j cypher - filter out child nodes
Imagine the following graph:

The goal is to query for all connecting nodes between two entities ("Main" and "Other" in this case), but filter out mutual descendants. In other words, I would like the result set to only contain a and b, but not c, because C is a descendant of B, which is already included in the result set.

答:
If I correctly understand the condition of the problem, then you need to find such child nodes, to which exactly one way to get from the original nodes:</p>

```<code>MATCH p = (Main:Node {id: 'main'})
          -[:child*]->(T:Node)<-[:child*]-
          (Other:Node {id: 'other'})
WITH T,
     collect(p) as pw WHERE size(pw) = 1
RETURN T
</code>```

Title: Neo4j cypher - filter out child nodes

Body:
If I correctly understand the condition of the problem, then you need to find such child nodes, to which exactly one way to get from the original nodes:

MATCH p = (Main:Node {id: 'main'})
          -[:child*]->(T:Node)<-[:child*]-
          (Other:Node {id: 'other'})
WITH T,
     collect(p) as pw WHERE size(pw) = 1
RETURN T


问:
Not getting expected pixel height when testing with Nightwatch
First of all, in case anybody asks for my machine info:

CentOS 7

kmod-nvidia Graphics drivers (dedicated GPU)

I have a webpage that I am testing with Nightwatch, and one of the criteria is making sure a background image's height is the height that is is supposed to be.

To summarize the problem I'm having:  I need to verify that the background image (or containing div) is height: calc(90vh - 200). I have either been getting greatly differing values, slightly different, or unknown/null values. Firefox is the only browser to have actually been spot on.

Below is some data that I have collected in my trouble shooting, and it is laid out as follows:

Rendering Browser: Which browser Nightwatch uses to render the page to test

Window.innerHeight: The viewport that the height attribute uses to calculate the expected height

Computed Value: What the height should be (innerHeight x 0.9 - 200)

Test Expected: The expected value in the Nightwatch test.

The test: client.verify.cssProperty("div.Background", "height", data.value.height);

Data is the variable where I have put my computed (expected) height from a client.execute() function.

Test Actual: The actual rendered value reported by nightwatch.

NIghtwatch's default browser (PhantomJS)

vp = 1080

Computed (height) = 772

Expected = 772

Actual = 600

Chrome

vp = 967

computed = 670.3

Expected = 670.300000001

Actual = 670.297

Firefox

vp = 945

Computed = 650.5

Expected = 650.5

Actual = 650.5

We also have our implementation of Nightwatch spin off a custom hosted port separate from selenium.  I have seen this value to be different from the above, but I just checked today as I'm writting this (on my local chrome browser), and It was behaving the same as PhantomJS, although with some variances.

Additionally, in the client.execute() function, I also attempted to retrieve this information from the DOM itself, but whenever I try any iteration of an element height, it gives me "unknown".

Here is an example of some code I'm using for various things in my above explanation:

```<code>client.resizeWindow(1920, 1080);
client.waitForElementVisible("background", 3000); // passes
client.execute(function(){ return window.innerHeight; }, [], (result) => {
  console.log("viewport:" + JSON.stringify(result.value));
}
client.getElementSize("div.background", (elementSize) => { //outputs wrong value
   console.log("elementSize: " + elementSize.value.height);
});

client.execute(function() {
  var data = {};
  var el = document.getElementsByClassName("background").clientHeight; //insert any height function here
  data.height = ((0.9 * window.innerHeight) - 200); //this is what it should be
  data.elementHeight = "height: " + el + "px";
  return data;
}, [], (data) => {
  console.log("computed Height: " + data.value.height);
  console.log("element height: " + data.value.elementHeight); //this gives "unknown"

  client.verify.cssProperty("div.background", height, data.value.height);
})
</code>```

Additionally, I have been having some problems with my graphics driver recently, and thought this might be the issue, but I have since ruled this out today.

Thanks in advance for any feedback, or thoughts on this!

答:
I found out that the minute differences in chrome are probably within a margin of error in whatever calculation algorithm they use (correct me if I'm wrong).  Otherwise I realized my major issue was with the Phantom.js browser that Nightwatch.js uses.

More specifically I noticed when making a mock html page in plunker, that the calc function had some issues with divs with a background image of which calc was setting the height to. If I removed the calc() function, then the image loaded once again.

Ex. Html:

```<code><html>
  <head>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="doTheThing"></div>
  </body>
</html>
</code>```

Ex. Css:

```<code>.doTheThing: {
  background-image: url('insertRandomImageUrlHere');
  height: calc(90vh - 200); //didn't work.  Image didn't load
  height: 90vh; //worked, image loaded.
}
</code>```

Scratching my head at this odd behavior I thought about it some more and looked specifically into the rendering browser Phantom.js with this regard and I came across this issue here: https://github.com/ariya/phantomjs/issues/13547

By the looks of it, it is entirely possible that calc() is being computed incorrectly by Phantom.js and this is causing the difference in pixels.  (also note, that the 600px in the above tests in my original post would be because there is a min-height of 600 set, so the computed value would've been less than 600.)

I believe this solves this issue, however I believe it warrants another question specifically to phantom.js to see if the situation has updated.  I'll also update my answer if I find otherwise conflicting conclusions to this answer.

I'll note my new question bellow once it's made.

Phantomjs browser incorrectly computing css calc() function in Nightwatch tests

Body:
First of all, in case anybody asks for my machine info:

CentOS 7

kmod-nvidia Graphics drivers (dedicated GPU)

I have a webpage that I am testing with Nightwatch, and one of the criteria is making sure a background image's height is the height that is is supposed to be.

To summarize the problem I'm having:  I need to verify that the background image (or containing div) is height: calc(90vh - 200). I have either been getting greatly differing values, slightly different, or unknown/null values. Firefox is the only browser to have actually been spot on.

Below is some data that I have collected in my trouble shooting, and it is laid out as follows:

Rendering Browser: Which browser Nightwatch uses to render the page to test

Window.innerHeight: The viewport that the height attribute uses to calculate the expected height

Computed Value: What the height should be (innerHeight x 0.9 - 200)

Test Expected: The expected value in the Nightwatch test.

The test: client.verify.cssProperty("div.Background", "height", data.value.height);

Data is the variable where I have put my computed (expected) height from a client.execute() function.

Test Actual: The actual rendered value reported by nightwatch.

NIghtwatch's default browser (PhantomJS)

vp = 1080

Computed (height) = 772

Expected = 772

Actual = 600

Chrome

vp = 967

computed = 670.3

Expected = 670.300000001

Actual = 670.297

Firefox

vp = 945

Computed = 650.5

Expected = 650.5

Actual = 650.5

We also have our implementation of Nightwatch spin off a custom hosted port separate from selenium.  I have seen this value to be different from the above, but I just checked today as I'm writting this (on my local chrome browser), and It was behaving the same as PhantomJS, although with some variances.

Additionally, in the client.execute() function, I also attempted to retrieve this information from the DOM itself, but whenever I try any iteration of an element height, it gives me "unknown".

Here is an example of some code I'm using for various things in my above explanation:

client.resizeWindow(1920, 1080);
client.waitForElementVisible("background", 3000); // passes
client.execute(function(){ return window.innerHeight; }, [], (result) => {
  console.log("viewport:" + JSON.stringify(result.value));
}
client.getElementSize("div.background", (elementSize) => { //outputs wrong value
   console.log("elementSize: " + elementSize.value.height);
});

client.execute(function() {
  var data = {};
  var el = document.getElementsByClassName("background").clientHeight; //insert any height function here
  data.height = ((0.9 * window.innerHeight) - 200); //this is what it should be
  data.elementHeight = "height: " + el + "px";
  return data;
}, [], (data) => {
  console.log("computed Height: " + data.value.height);
  console.log("element height: " + data.value.elementHeight); //this gives "unknown"

  client.verify.cssProperty("div.background", height, data.value.height);
})

Additionally, I have been having some problems with my graphics driver recently, and thought this might be the issue, but I have since ruled this out today.

Thanks in advance for any feedback, or thoughts on this!

Body:
I found out that the minute differences in chrome are probably within a margin of error in whatever calculation algorithm they use (correct me if I'm wrong).  Otherwise I realized my major issue was with the Phantom.js browser that Nightwatch.js uses.

More specifically I noticed when making a mock html page in plunker, that the calc function had some issues with divs with a background image of which calc was setting the height to. If I removed the calc() function, then the image loaded once again.

Ex. Html:

<html>
  <head>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="doTheThing"></div>
  </body>
</html>

Ex. Css:

.doTheThing: {
  background-image: url('insertRandomImageUrlHere');
  height: calc(90vh - 200); //didn't work.  Image didn't load
  height: 90vh; //worked, image loaded.
}

Scratching my head at this odd behavior I thought about it some more and looked specifically into the rendering browser Phantom.js with this regard and I came across this issue here: https://github.com/ariya/phantomjs/issues/13547

By the looks of it, it is entirely possible that calc() is being computed incorrectly by Phantom.js and this is causing the difference in pixels.  (also note, that the 600px in the above tests in my original post would be because there is a min-height of 600 set, so the computed value would've been less than 600.)

I believe this solves this issue, however I believe it warrants another question specifically to phantom.js to see if the situation has updated.  I'll also update my answer if I find otherwise conflicting conclusions to this answer.

I'll note my new question bellow once it's made.

Phantomjs browser incorrectly computing css calc() function in Nightwatch tests


问:
get the key while using firebase on ionic3
I'm using firebase on my ionic project. You can see my dataset on firebase with the following image.

I want to get the $key to update the specific data. How can i get it?

You can check my code how to get datas from firebase.

```<code>getPaymentsFromArchive() {
    const userid = this.authData.showUser().uid;
    let profileData: any[] = [];

this.angularFireDatabase.list(`/users/${userid}/userPayments/${this.selectedYears}/${this.selectedMonths}/userSubscriptions`).subscribe(data => {
        profileData = data;
      });
}
</code>```

I want to get $key: "-L-hLB5VKoYRxKEvlNYj"

答:
If you want all the keys in userSubscriptions this should work.

```<code>this.angularFireDatabase.list('/users/${userid}/userPayments/${this.selectedYears}/${this.selectedMonths}/userSubscriptions').subscribe(data => {
    profileData = data;
    profileData.map(item => {
       console.log(item.$key);
    })
});
</code>```

Body:
I'm using firebase on my ionic project. You can see my dataset on firebase with the following image.

I want to get the $key to update the specific data. How can i get it?

You can check my code how to get datas from firebase.

getPaymentsFromArchive() {
    const userid = this.authData.showUser().uid;
    let profileData: any[] = [];

this.angularFireDatabase.list(`/users/${userid}/userPayments/${this.selectedYears}/${this.selectedMonths}/userSubscriptions`).subscribe(data => {
        profileData = data;
      });
}

I want to get $key: "-L-hLB5VKoYRxKEvlNYj"

Body:
If you want all the keys in userSubscriptions this should work.

this.angularFireDatabase.list('/users/${userid}/userPayments/${this.selectedYears}/${this.selectedMonths}/userSubscriptions').subscribe(data => {
    profileData = data;
    profileData.map(item => {
       console.log(item.$key);
    })
});


问:
Azure Logic Apps - Dropbox Connector Filesize Limit
I have a very simple Logic App which lists files in a Dropbox folder, then copies them to an Azure Blob container.  Works great!  However, when a file is larger than 50MB (like 100MB in this example), I get the following error:

```<code>{
  "status": 413,
  "message": "The file contains 100.514 megabytes which exceeds the maximum 50 megabytes.\r\nclientRequestId: <someid>",
  "source": "dropbox-cus.azconn-cus.p.azurewebsites.net"
}
</code>```

That limit does not appear to exist on either Dropbox or Blob Storage.  Is there a way to make that connector limit larger?

答:
I'm relaying the information from another answer, which does not directly target same exact technologies, but is definitely related to Logic Apps.

Logic App have maximum message size limits, and seems like you are hitting one of them.

So, if you need to use logic apps, you would need to have smaller messages.

Source: MSDN Forum

Maybe you can contact support and ask them to increase your limits.

Body:
I have a very simple Logic App which lists files in a Dropbox folder, then copies them to an Azure Blob container.  Works great!  However, when a file is larger than 50MB (like 100MB in this example), I get the following error:

{
  "status": 413,
  "message": "The file contains 100.514 megabytes which exceeds the maximum 50 megabytes.\r\nclientRequestId: <someid>",
  "source": "dropbox-cus.azconn-cus.p.azurewebsites.net"
}

That limit does not appear to exist on either Dropbox or Blob Storage.  Is there a way to make that connector limit larger?


问:
Obtaining Raw Facebook Cookie Contents iPhone
I wanted to use Facebook to authenticate my iPhone client with my Google App Engine web server. The way I figured doing this would be the following:

Log in with facebook on the iPhone

Obtain the Facebook cookie (signed with my app's Secret Id)

Have the iPhone client send the cookie to my server

Verify the signature on the cookie from the server side (which also know's the app's Secret Id)

I have successfully done thiswith a javascript client that and a JSON RPC tool running on app engine, but I can' seem to get the raw Facebook cookie contents on the iPhone using the Facebook SDK (https://github.com/facebook/facebook-ios-sdk). Using their sample code, I've set up a simple log in with Facebook iPhone client. If you look at Facebook.m it reads cookies as NSHttpCookie, but it lacks the information I am seeing from my javascript client.

I am not seeing this information:
access_token=
expires=
secret=
session_key=
sig=

I can at least obtain the access token, the other way to authenticate on my server, would be to accept the users access token and then make a request to facebook's graph api on the server side to verify that the access token is indeed for who the user claims to be user.

Any ideas on how to get the entire cookie on the iPhone?

答:
What you need to do is read up on NSHTTPCookieStorage and NSHTTPCookie.  Documentation here and here.

Here is some sample code on iterating through the cookies that your app has access to read/write:

```<code>for(NSHTTPCookie* cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
    // read and write from the CookieStorage
}
</code>```

As the documentation points out, keep in mind that you only have access to your cookies and not any other app's, including Safari.app.

ContentLicense: CC BY-SA 2.5

Body:
What you need to do is read up on NSHTTPCookieStorage and NSHTTPCookie.  Documentation here and here.

Here is some sample code on iterating through the cookies that your app has access to read/write:

for(NSHTTPCookie* cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
    // read and write from the CookieStorage
}

As the documentation points out, keep in mind that you only have access to your cookies and not any other app's, including Safari.app.


问:
What is the difference between statically typed and dynamically typed languages?
What does it mean when we say a language is dynamically typed versus statically typed?</p>

答:
Compiled vs. Interpreted

"When source code is translated"

Source Code: Original code (usually typed by a human into a computer)

Translation: Converting source code into something a computer can read (i.e. machine code)

Run-Time: Period when program is executing commands (after compilation, if compiled)

Compiled Language: Code translated before run-time

Interpreted Language: Code translated on the fly, during execution

Typing

"When types are checked"

5 + '3' is an example of a type error in strongly typed languages such as Go and Python, because they don't allow for "type coercion" -> the ability for a value to change type in certain contexts such as merging two types. Weakly typed languages, such as JavaScript, won't throw a type error (results in '53').

Static: Types checked before run-time

Dynamic: Types checked on the fly, during execution

The definitions of "Static & Compiled" and "Dynamic & Interpreted" are quite similar...but remember it's "when types are checked" vs. "when source code is translated".

You'll get the same type errors irrespective of whether the language is compiled or interpreted! You need to separate these terms conceptually.

Python Example

Dynamic, Interpreted

```<code>def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

silly(2)
</code>```

Because Python is both interpreted and dynamically typed, it only translates and type-checks code it's executing on. The else block never executes, so 5 + '3' is never even looked at!

What if it was statically typed?

A type error would be thrown before the code is even run. It still performs type-checking before run-time even though it is interpreted.

What if it was compiled?

The else block would be translated/looked at before run-time, but because it's dynamically typed it wouldn't throw an error! Dynamically typed languages don't check types until execution, and that line never executes.

Go Example

Static, Compiled

```<code>package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}
</code>```

The types are checked before running (static) and the type error is immediately caught! The types would still be checked before run-time if it was interpreted, having the same result. If it was dynamic, it wouldn't throw any errors even though the code would be looked at during compilation.

Performance

A compiled language will have better performance at run-time if it's statically typed (vs. dynamically); knowledge of types allows for machine code optimization.

Statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running).

Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to "interpret"/translate it on the fly.

Note that both compiled and statically typed languages will have a delay before running for translation and type-checking, respectively.

More Differences

Static typing catches errors early, instead of finding them during execution (especially useful for long programs). It's more "strict" in that it won't allow for type errors anywhere in your program and often prevents variables from changing types, which further defends against unintended errors.

```<code>num = 2
num = '3' // ERROR
</code>```

Dynamic typing is more flexible, which some appreciate. It typically allows for variables to change types, which can result in unexpected errors.

ContentLicense: CC BY-SA 4.0

Body:
Compiled vs. Interpreted

"When source code is translated"

Source Code: Original code (usually typed by a human into a computer)

Translation: Converting source code into something a computer can read (i.e. machine code)

Run-Time: Period when program is executing commands (after compilation, if compiled)

Compiled Language: Code translated before run-time

Interpreted Language: Code translated on the fly, during execution

Typing

"When types are checked"

5 + '3' is an example of a type error in strongly typed languages such as Go and Python, because they don't allow for "type coercion" -> the ability for a value to change type in certain contexts such as merging two types. Weakly typed languages, such as JavaScript, won't throw a type error (results in '53').

Static: Types checked before run-time

Dynamic: Types checked on the fly, during execution

The definitions of "Static & Compiled" and "Dynamic & Interpreted" are quite similar...but remember it's "when types are checked" vs. "when source code is translated".

You'll get the same type errors irrespective of whether the language is compiled or interpreted! You need to separate these terms conceptually.

Python Example

Dynamic, Interpreted

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

silly(2)

Because Python is both interpreted and dynamically typed, it only translates and type-checks code it's executing on. The else block never executes, so 5 + '3' is never even looked at!

What if it was statically typed?

A type error would be thrown before the code is even run. It still performs type-checking before run-time even though it is interpreted.

What if it was compiled?

The else block would be translated/looked at before run-time, but because it's dynamically typed it wouldn't throw an error! Dynamically typed languages don't check types until execution, and that line never executes.

Go Example

Static, Compiled

package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}

The types are checked before running (static) and the type error is immediately caught! The types would still be checked before run-time if it was interpreted, having the same result. If it was dynamic, it wouldn't throw any errors even though the code would be looked at during compilation.

Performance

A compiled language will have better performance at run-time if it's statically typed (vs. dynamically); knowledge of types allows for machine code optimization.

Statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running).

Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to "interpret"/translate it on the fly.

Note that both compiled and statically typed languages will have a delay before running for translation and type-checking, respectively.

More Differences

Static typing catches errors early, instead of finding them during execution (especially useful for long programs). It's more "strict" in that it won't allow for type errors anywhere in your program and often prevents variables from changing types, which further defends against unintended errors.

num = 2
num = '3' // ERROR

Dynamic typing is more flexible, which some appreciate. It typically allows for variables to change types, which can result in unexpected errors.


问:
primefaces dialog is not working
This is my dialog.

```<code><p:dialog closeOnEscape="true" resizable="false"
            header="Confirmation" widgetVar="groupconfirmation">
            <center>
                Do you want to remove this Pin Priority group?<br /> <br />
                <p:commandButton value="Yes" oncomplete="groupconfirmation.hide()"
                    actionListener="#{pinProrityHandler.deletePinPriorityGroup}"
                    update="pinprioritygroup" />

                <p:commandButton value="No"
                    actionListener="#{platformGroupHandler.onGroupReset}"
                    oncomplete="groupconfirmation.hide()" update="pinprioritygroup" />
            </center>
</p:dialog>
</code>```

And this is my java code:

```<code>  try {
        RequestContext.getCurrentInstance().execute("groupconfirmation.show()");
    } catch (Exception e) {
        logger.error("Error {}", e);
    }
</code>```

I don't know why my code is not working.

I am new to primeface.

答:
For Primefaces <= 3.x

```<code>RequestContext context = RequestContext.getCurrentInstance();
context.execute("groupconfirmation.show();");
</code>```

For Primefaces >= 4.x

```<code>RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('groupconfirmation').show();")
</code>```

Title: primefaces dialog is not working

Body:
This is my dialog.

                Do you want to remove this Pin Priority group?

And this is my java code:

  try {
        RequestContext.getCurrentInstance().execute("groupconfirmation.show()");
    } catch (Exception e) {
        logger.error("Error {}", e);
    }

I don't know why my code is not working.

I am new to primeface.

Body:
For Primefaces <= 3.x

RequestContext context = RequestContext.getCurrentInstance();
context.execute("groupconfirmation.show();");

For Primefaces >= 4.x

RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('groupconfirmation').show();")


问:
ActiveAdmin. Add `back` button to previous page
How to add a button in Active Admin that behaves similar to the browser's back button.

Thanks.

答:
This is a working solution i'm currently using :</p>

```<code>ActiveAdmin.register User do
  action_item 'Back', only: :index do
    link_to('Back', :back)
  end
end
</code>```

Body:
This is a working solution i'm currently using :

ActiveAdmin.register User do
  action_item 'Back', only: :index do
    link_to('Back', :back)
  end
end


问:
Jupyter Notebook show public IP at startup

I am running a public jupyter notebook on an AWS ec2 instance. When starting the jupyter notebook, how can I get the notebook to give me the public IP address of the instance instead of "localhost"?

```<code>https://[PUBLIC_IP_ADDRESS]:8888/?token=[token]
</code>```

instead of:

```<code>https://localhost:8888/?token=[token]
</code>```

Thank you!

答:
You cannot, or at least not easily, because the externally visible IP may not be the internally visible IP, and the machine you are on, likely does not know this. And that's generic of any network/network enabled application.

For example my current ip in  my network is (using ifconfig) 10.168.1.63, but my current global ip is 77.200.16.xxx. My router knows that when it sees an external connection to port 80 from the internet, then it should forward to my machine where the notebook is running. But my machine has no clue about that.

You need to get your public IP from AWS itself.

Body:
I am running a public jupyter notebook on an AWS ec2 instance. When starting the jupyter notebook, how can I get the notebook to give me the public IP address of the instance instead of "localhost"?

https://[PUBLIC_IP_ADDRESS]:8888/?token=[token]

instead of:

https://localhost:8888/?token=[token]

Thank you!


问:
Transforming a nested data frame with varying number of elements
I have a data frame with a column of nested data frames with 1 or 2 columns and n rows. It looks like df in the sample below:

```<code>'data.frame':   3 obs. of  2 variables:
 $ vector:List of 3
  ..$ : chr "p1"
  ..$ : chr "p2"
  ..$ : chr "p3"
 $ lists :List of 3
  ..$ :'data.frame':    2 obs. of  2 variables:
  .. ..$ n1: Factor w/ 2 levels "a","b": 1 2
  .. ..$ n2: Factor w/ 2 levels "1","2": 1 2
  ..$ :'data.frame':    1 obs. of  1 variable:
  .. ..$ n1: Factor w/ 1 level "d": 1
  ..$ :'data.frame':    1 obs. of  2 variables:
  .. ..$ n1: Factor w/ 1 level "e": 1
  .. ..$ n2: Factor w/ 1 level "3": 1
</code>```

df can be recreated like this :

```<code>v <- c("p1", "p2", "p3")
l <- list(data.frame(n1 = c("a", "b"), n2 = c("1", "2")), data.frame(n1 = "d"), data.frame(n1 = "e", n2 = "3"))
df <- as.data.frame(cbind(v, l))
</code>```

I'd like to transform it to a data frame that looks like that:

```<code>[v] [n1] [n2]

p1  a  1

p1  b  2

p2  d  NA

p3  e  3
</code>```

n1 and n2 are in seperate columns

if the data frame in row i has n rows, the vector element of row i should be repeated n times

if there is no content in n1 or n2, there should be a NA

I've tried using tidyr::unnest but got the following error

```<code> unnest(df)
Error: All nested columns must have the same number of elements.
</code>```

Does anyone has a better idea how to transform the dataframe in the desired format?

答:
Using purrr::pmap_df, within each row of df, we combine v and l into a single data frame and then combine all of the data frames into a single data frame.

```<code>library(tidyverse)

pmap_df(df, function(v,l) {
  data.frame(v,l)
})
</code>```

```<code>   v n1   n2
1 p1  a    1
2 p1  b    2
3 p2  d <NA>
4 p3  e    3
</code>```

Body:
I have a data frame with a column of nested data frames with 1 or 2 columns and n rows. It looks like df in the sample below:

'data.frame':   3 obs. of  2 variables:
 $ vector:List of 3
  ..$ : chr "p1"
  ..$ : chr "p2"
  ..$ : chr "p3"
 $ lists :List of 3
  ..$ :'data.frame':    2 obs. of  2 variables:
  .. ..$ n1: Factor w/ 2 levels "a","b": 1 2
  .. ..$ n2: Factor w/ 2 levels "1","2": 1 2
  ..$ :'data.frame':    1 obs. of  1 variable:
  .. ..$ n1: Factor w/ 1 level "d": 1
  ..$ :'data.frame':    1 obs. of  2 variables:
  .. ..$ n1: Factor w/ 1 level "e": 1
  .. ..$ n2: Factor w/ 1 level "3": 1

df can be recreated like this :

v <- c("p1", "p2", "p3")
l <- list(data.frame(n1 = c("a", "b"), n2 = c("1", "2")), data.frame(n1 = "d"), data.frame(n1 = "e", n2 = "3"))
df <- as.data.frame(cbind(v, l))

I'd like to transform it to a data frame that looks like that:

[v] [n1] [n2]

p1  a  1

p1  b  2

p2  d  NA

p3  e  3

n1 and n2 are in seperate columns

if the data frame in row i has n rows, the vector element of row i should be repeated n times

if there is no content in n1 or n2, there should be a NA

I've tried using tidyr::unnest but got the following error

 unnest(df)
Error: All nested columns must have the same number of elements.

Does anyone has a better idea how to transform the dataframe in the desired format?

Body:
Using purrr::pmap_df, within each row of df, we combine v and l into a single data frame and then combine all of the data frames into a single data frame.

library(tidyverse)

pmap_df(df, function(v,l) {
  data.frame(v,l)
})

   v n1   n2
1 p1  a    1
2 p1  b    2
3 p2  d <NA>
4 p3  e    3


问:
Issues writing doubles to files, writing nothing
I seem to be missing something when it comes to writing doubles to text files, when I check the file, just blank space is present. When I read from the file and print with System.out.println(); it just prints nothing... What's going wrong here? Do I need to do some converting?</p>

```<code>import java.io.*;
import javax.swing.JOptionPane;

public class ReadCalcAveragePrint  {

    double firstNum;
    double secondNum;
    double average;

    public void readFile() {

        try {
            File f = new File("numbers.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String one = br.readLine();
            String two = br.readLine();
            firstNum = Double.parseDouble(one);
            secondNum = Double.parseDouble(two);

            average = (firstNum + secondNum) / 2;
            JOptionPane.showMessageDialog(null, average, "title", JOptionPane.PLAIN_MESSAGE);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    public void writeFile() {
        try {
            File f = new File("result.txt");
            FileOutputStream fos = new FileOutputStream(f);
            DataOutputStream dos = new DataOutputStream(fos);
            dos.writeDouble(average);
            dos.flush();
            fos.close();
            System.out.println("Printed.");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);

        }
    }

    public void readResult() {

        try {
            File f = new File("result.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String one = br.readLine();
            System.out.println(one);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    public static void main(String[] args) {

        new ReadCalcAveragePrint().readFile();
        new ReadCalcAveragePrint().writeFile();
        new ReadCalcAveragePrint().readResult();
    }
}
</code>```

答:
In the main you are creating 3 different objects, only the first is going to contain the numbers you read from the file.

You should just create and reuse one object:

```<code>public static void main(String[] args) {
    ReadCalcAveragePrint obj = new ReadCalcAveragePrint();
    obj.readFile();
    obj.writeFile();
    obj.readResult();
}
</code>```

Also you are writing the result file using DataOutputStream which is meant to write the data in binary form. If you just want to save the result as text you should use FileWriter instead:

```<code>File f = new File("result.txt");
FileWriter fw = new FileWriter(f);
fw.write(String.valueOf(average));
fw.close();
</code>```

Body:
I seem to be missing something when it comes to writing doubles to text files, when I check the file, just blank space is present. When I read from the file and print with System.out.println(); it just prints nothing... What's going wrong here? Do I need to do some converting?

import java.io.*;
import javax.swing.JOptionPane;

public class ReadCalcAveragePrint  {

    double firstNum;
    double secondNum;
    double average;

    public void readFile() {

        try {
            File f = new File("numbers.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String one = br.readLine();
            String two = br.readLine();
            firstNum = Double.parseDouble(one);
            secondNum = Double.parseDouble(two);

            average = (firstNum + secondNum) / 2;
            JOptionPane.showMessageDialog(null, average, "title", JOptionPane.PLAIN_MESSAGE);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    public void writeFile() {
        try {
            File f = new File("result.txt");
            FileOutputStream fos = new FileOutputStream(f);
            DataOutputStream dos = new DataOutputStream(fos);
            dos.writeDouble(average);
            dos.flush();
            fos.close();
            System.out.println("Printed.");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);

        }
    }

    public void readResult() {

        try {
            File f = new File("result.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String one = br.readLine();
            System.out.println(one);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    public static void main(String[] args) {

        new ReadCalcAveragePrint().readFile();
        new ReadCalcAveragePrint().writeFile();
        new ReadCalcAveragePrint().readResult();
    }
}

Body:
In the main you are creating 3 different objects, only the first is going to contain the numbers you read from the file.

You should just create and reuse one object:

public static void main(String[] args) {
    ReadCalcAveragePrint obj = new ReadCalcAveragePrint();
    obj.readFile();
    obj.writeFile();
    obj.readResult();
}

Also you are writing the result file using DataOutputStream which is meant to write the data in binary form. If you just want to save the result as text you should use FileWriter instead:

File f = new File("result.txt");
FileWriter fw = new FileWriter(f);
fw.write(String.valueOf(average));
fw.close();