问:
nameerror undefined local variable or method `log_out' Did you mean? logout_url ruby on rails
So I am following the tutorial by Michael Hartl, and when I am trying to logout, I get this
"NameError in SessionsController#destroy"undefined local variable or method "log_out" for #<SessionsController:0x0000000275f290> Did you mean? logout_url

My tests and this Error only popped up after I added the last bit in my test, however, my logout function on the website did not work either.

This is my session_helper.rb:

```<code>module SessionsHelper

    # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

   # Returns the current logged-in user (if any).
  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

   # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

# Logs out the current user.
  def destroy
    session.delete(:user_id)
    @current_user = nil
  end
end
</code>```

This is my session_controller:

```<code>class SessionsController < ApplicationController
  def new
  end

  def create
    #Gets user from database in lowercase & determines if user is valid
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      # Log the user in and redirect to the user's show page.
      log_in user
      redirect_to user
    else
      # Create an error message.
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  # Logs out the current user.
  def destroy
    log_out # undefined variable Name error
    redirect_to root_url
  end
end
</code>```

My application_controller:

```<code>  class ApplicationController < ActionController::Base
    protect_from_forgery with: :exception
    include SessionsHelper #temporary session cookie, expires automatically upon browser close
  end
</code>```

My view/layouts/_header.html.erb (used for the navbar where the logout link is):

```<code><header class="navbar navbar-fixed-top navbar-inverse">
  <div class="container">
    <%= link_to image_tag("logo2.png", alt: "CourseBuddies logo"), root_path, id: "logo" %>
    <%- # link_to "sample app", '#', id: "logo" %>
    <nav>
      <ul class="nav navbar-nav navbar-right">
        <li><%= link_to "Home", root_path   %></li>
        <li><%= link_to "Reviews",   '#' %></li>
        <li><%= link_to "About us",   about_path %></li>

         <%- # LOGIN & SCROLL DOWN BAR %>
        <% if logged_in? %>
          **<li><%= link_to "Users", users_path %></li>
          <li class="dropdown">**
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
              Account <b class="caret"></b>
            </a>
            <ul class="dropdown-menu">
              **<li><%= link_to "Profile", current_user %></li>
              <li><%= link_to "Settings", '#' %></li>**
              <li class="divider"></li>
              <li>
                **<%= link_to "Log out", logout_path, method: :delete %>**
              </li>
            </ul>
          </li>
        **<% else %>
          <li><%= link_to "Log in", login_path %></li>
        <% end %>**
      </ul>
    </nav>
  </div>
</header>
</code>```

My user model:

```<code>class User < ApplicationRecord
    #before saving, make sure the email is in downcase
    before_save { self.email = email.downcase }

    validates :name,  presence: true, length: { maximum: 50 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: {case_sensitive: false}

    # Let's you safely store a hashed password_digest to DB,
    # gives you password & password_confirmation attributes,
    # an authenticate method that returns the user when pw is correct,
    # otherwise false.
    has_secure_password(validations:false)
    validates :password, presence:true, length: { minimum: 6 }

     # Returns the hash digest of the given string.
    def User.digest(string)
        cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
        BCrypt::Password.create(string, cost: cost)
    end
end
</code>```

My create-method in my Users controller:
  def create
    @user = User.new(user_params) #params[:user])#user_params)

```<code>if @user.save
  log_in @user
  flash[:success] = "Welcome to CourseBuddies!"
  redirect_to @user

else
  render 'new'
end
</code>```

end

My test/test_helper:

```<code>ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Returns true if a test user is logged in.
  def is_logged_in?
    !session[:user_id].nil?
  end
end
</code>```

And my user_login_test:

```<code>require 'test_helper'

class UsersLoginTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:michael)
  end

   # Visit the login path.
# Verify that the new sessions form renders properly.
# Post to the sessions path with an invalid params hash.
# Verify that the new sessions form gets re-rendered and that a flash message appears.
# Visit another page (such as the Home page).
# Verify that the flash message doesn’t appear on the new page.
  test "login with valid information followed by logout" do
    get login_path
    post login_path, params: { session: { email:    @user.email,
                                      password: 'password' } }
    assert is_logged_in?
    assert_redirected_to @user
    follow_redirect!
    assert_template 'users/show'
    assert_select "a[href=?]", login_path, count: 0
    assert_select "a[href=?]", logout_path
    assert_select "a[href=?]", user_path(@user)

    #AFTER ADDING THIS MY TEST FAILED

    #after logging in, we use delete to issue a DELETE request to the logout path
    #(Table 8.1) and verify that the user is logged out and redirected to the root URL
    delete logout_path
    assert_not is_logged_in?
    assert_redirected_to root_url
    follow_redirect!
    assert_select "a[href=?]", login_path
    assert_select "a[href=?]", logout_path,      count: 0
    assert_select "a[href=?]", user_path(@user), count: 0
  end
end
</code>```

And at last my routes:

```<code>Rails.application.routes.draw do

  get 'sessions/new'

  #ROOT, first page to show
  root 'pages#home'

  # maps requests for the URL/pages/home to the about us action in the Pages controller.
  # By using GET we arrange for the route to respond to a GET request.
  # With this we generate a about us action inside the Pages controller, automatically
  # get a page at the address /pages/about us
  get '/about', to: 'pages#about'
  get '/signup', to: 'users#new'
  post '/signup',  to: 'users#create' #signup route that responds to POST requests.
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

  #resources :sessions
  resources :users
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

end
</code>```

I'm sorry there is a lot of code! On the tutorial it says the test users_login_test is supposed to turn green after adding the new code, but it fails. Also, the logout does not work and gives me this error:
image of error

I will be grateful for any help!

答:
NameError in SessionsController#destroy"undefined local variable or
  method "log_out" for SessionsController:0x0000000275f290 Did you
  mean? logout_url

In the tutorial(refer to 8.3), the method name in the sessions_helper is log_out, whereas you named it as destroy, but calling it as log_out in the sessions_controller. You should change it to log_out

```<code>def log_out
  session.delete(:user_id)
  @current_user = nil
end
</code>```

Body:
So I am following the tutorial by Michael Hartl, and when I am trying to logout, I get this
"NameError in SessionsController#destroy"undefined local variable or method "log_out" for #<SessionsController:0x0000000275f290> Did you mean? logout_url

My tests and this Error only popped up after I added the last bit in my test, however, my logout function on the website did not work either.

This is my session_helper.rb:

module SessionsHelper

    # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

   # Returns the current logged-in user (if any).
  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

   # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

# Logs out the current user.
  def destroy
    session.delete(:user_id)
    @current_user = nil
  end
end

This is my session_controller:

class SessionsController < ApplicationController
  def new
  end

  def create
    #Gets user from database in lowercase & determines if user is valid
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      # Log the user in and redirect to the user's show page.
      log_in user
      redirect_to user
    else
      # Create an error message.
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  # Logs out the current user.
  def destroy
    log_out # undefined variable Name error
    redirect_to root_url
  end
end

My application_controller:

  class ApplicationController < ActionController::Base
    protect_from_forgery with: :exception
    include SessionsHelper #temporary session cookie, expires automatically upon browser close
  end

My view/layouts/_header.html.erb (used for the navbar where the logout link is):

    <%= link_to image_tag("logo2.png", alt: "CourseBuddies logo"), root_path, id: "logo" %>
    <%- # link_to "sample app", '#', id: "logo" %>

<%= link_to "Home", root_path   %>

<%= link_to "Reviews",   '#' %>

<%= link_to "About us",   about_path %>

         <%- # LOGIN & SCROLL DOWN BAR %>
        <% if logged_in? %>
          **
<%= link_to "Users", users_path %>

**

              Account

              **
<%= link_to "Profile", current_user %>

<%= link_to "Settings", '#' %>
**

                **<%= link_to "Log out", logout_path, method: :delete %>**

        **<% else %>

<%= link_to "Log in", login_path %>

        <% end %>**

My user model:

class User < ApplicationRecord
    #before saving, make sure the email is in downcase
    before_save { self.email = email.downcase }

    validates :name,  presence: true, length: { maximum: 50 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: {case_sensitive: false}

    # Let's you safely store a hashed password_digest to DB,
    # gives you password & password_confirmation attributes,
    # an authenticate method that returns the user when pw is correct,
    # otherwise false.
    has_secure_password(validations:false)
    validates :password, presence:true, length: { minimum: 6 }

     # Returns the hash digest of the given string.
    def User.digest(string)
        cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
        BCrypt::Password.create(string, cost: cost)
    end
end

My create-method in my Users controller:
  def create
    @user = User.new(user_params) #params[:user])#user_params)

if @user.save
  log_in @user
  flash[:success] = "Welcome to CourseBuddies!"
  redirect_to @user

else
  render 'new'
end

end

My test/test_helper:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Returns true if a test user is logged in.
  def is_logged_in?
    !session[:user_id].nil?
  end
end

And my user_login_test:

require 'test_helper'

class UsersLoginTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:michael)
  end

   # Visit the login path.
# Verify that the new sessions form renders properly.
# Post to the sessions path with an invalid params hash.
# Verify that the new sessions form gets re-rendered and that a flash message appears.
# Visit another page (such as the Home page).
# Verify that the flash message doesn’t appear on the new page.
  test "login with valid information followed by logout" do
    get login_path
    post login_path, params: { session: { email:    @user.email,
                                      password: 'password' } }
    assert is_logged_in?
    assert_redirected_to @user
    follow_redirect!
    assert_template 'users/show'
    assert_select "a[href=?]", login_path, count: 0
    assert_select "a[href=?]", logout_path
    assert_select "a[href=?]", user_path(@user)

    #AFTER ADDING THIS MY TEST FAILED

    #after logging in, we use delete to issue a DELETE request to the logout path
    #(Table 8.1) and verify that the user is logged out and redirected to the root URL
    delete logout_path
    assert_not is_logged_in?
    assert_redirected_to root_url
    follow_redirect!
    assert_select "a[href=?]", login_path
    assert_select "a[href=?]", logout_path,      count: 0
    assert_select "a[href=?]", user_path(@user), count: 0
  end
end

And at last my routes:

Rails.application.routes.draw do

  get 'sessions/new'

  #ROOT, first page to show
  root 'pages#home'

  # maps requests for the URL/pages/home to the about us action in the Pages controller.
  # By using GET we arrange for the route to respond to a GET request.
  # With this we generate a about us action inside the Pages controller, automatically
  # get a page at the address /pages/about us
  get '/about', to: 'pages#about'
  get '/signup', to: 'users#new'
  post '/signup',  to: 'users#create' #signup route that responds to POST requests.
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

  #resources :sessions
  resources :users
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

end

I'm sorry there is a lot of code! On the tutorial it says the test users_login_test is supposed to turn green after adding the new code, but it fails. Also, the logout does not work and gives me this error:
image of error

I will be grateful for any help!

Body:
NameError in SessionsController#destroy"undefined local variable or
  method "log_out" for SessionsController:0x0000000275f290 Did you
  mean? logout_url

In the tutorial(refer to 8.3), the method name in the sessions_helper is log_out, whereas you named it as destroy, but calling it as log_out in the sessions_controller. You should change it to log_out

def log_out
  session.delete(:user_id)
  @current_user = nil
end


来源: stackexchange

问:
How to get the total number of positive, neutral and negative tweets in SQL Server?
I am a new SQL developer and I am trying to write a query that will retrieve the total number of positive, negative and neutral tweets in the database. The result should look like the following:

PositivesCount --- NeutralCount --- NegativeCount

500 ---  ---  ---  ---  --- 700 ---  ---  ---  ---  800

The schema for the tables involved in this query:

```<code>T_TweetSentiment Table: Id, TweetId, SentimentLabel, TypeId
T_Tweet Table: Id, TweetText
</code>```

The T_TweetSentiment table contains three different sentiment labels; positive, negative and neutral. I would like to retrieve the total number of positive tweets, neutral tweets and negative tweets as illustrated above. So could you please tell me how I can get the desired result?

Here's the query I have but it is not working:

```<code>SELECT  MAX(CASE WHEN ts.SentimentLabel = 'Positive' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS PositivesCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NeutralsCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Negative' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6
</code>```

答:
```<code>SELECT SUM(CASE WHEN ts.SentimentLabel = 'Positive' THEN 1 ELSE 0 END) AS PositivesCount,
       SUM(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN 1 ELSE 0 END) AS NeutralsCount,
       SUM(CASE WHEN ts.SentimentLabel = 'Negative' THEN 1 ELSE 0 END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a new SQL developer and I am trying to write a query that will retrieve the total number of positive, negative and neutral tweets in the database. The result should look like the following:

PositivesCount --- NeutralCount --- NegativeCount

500 ---  ---  ---  ---  --- 700 ---  ---  ---  ---  800

The schema for the tables involved in this query:

T_TweetSentiment Table: Id, TweetId, SentimentLabel, TypeId
T_Tweet Table: Id, TweetText

The T_TweetSentiment table contains three different sentiment labels; positive, negative and neutral. I would like to retrieve the total number of positive tweets, neutral tweets and negative tweets as illustrated above. So could you please tell me how I can get the desired result?

Here's the query I have but it is not working:

SELECT  MAX(CASE WHEN ts.SentimentLabel = 'Positive' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS PositivesCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NeutralsCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Negative' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6


问:
Unity's Google VR not viewing stereo
I want to make game to Google Cardboard using Unity. I downloaded it yesterday, so I think it's the newest version. I downloaded .unitypackage file from https://developers.google.com/vr/unity/download and followed instructions. Still I can not see Cardboard view, when I try to run it. What to do now?

Screenshot:

The scenes view should look something like this:

答: The cardboard view is only visible once you build onto a mobile device.</p>

Title: Unity's Google VR not viewing stereo


问:
How to "redefine" one char * to another char *?
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

```<code>#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}
</code>```

// output: b

How to do it?

答: Fortunately, you can't redefine string literals. Of course, the real question is: why do you want to do it?

Body:
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}

// output: b

How to do it?

ContentLicense: CC BY-SA 2.5


问:
Why do DatePart and DateName return different values for the same date?
I am trying to get the day number and name from a given date field.

But the results are confusing.

For example the following sql :

```<code>declare @date date = '20161018'

select datepart(dw, @date) as daynumber,
       datename(weekday, @date) as DayName,
       datename(weekday, 3) as DayNumber3,
       datename(weekday, 1) as DayNumber1
</code>```

it produces this result :

```<code>daynumber   DayName     DayNumber3    DayNumber1
3           Tuesday     Thursday      Tuesday
</code>```

As you can see the datepart returns 3 and when I use this datepart in the call to datename it returns Tuesday.

But when I call datepart direct with the number 3 it returns Thursday and when I call datepart direct with the number 1 it returns Tuesday

So why does datepart(dw, @date) returns 3 in stead of 1 while datename(weekday, @date) does returns the correct day name ?

For me it is important to get the number 1 in stead of 3 and still keep getting Tuesday for this date.

EDIT:

The desired output I want for '20161018' is

```<code>daynumber    DayName
1            Tuesday
</code>```

How can I get this result for the date from my example ?

答:
I think you can add 5 and mod 7 will get your results as below:</p>

```<code>Declare @date date = '20161018'

Select (datepart(dw, @date) + 5) % 7 as daynumber,
   datename(weekday, @date) as DayName,
   datename(weekday, 3) as DayNumber3,
   datename(weekday, 1) as DayNumber1
</code>```

Body:
I am trying to get the day number and name from a given date field.

But the results are confusing.

For example the following sql :

declare @date date = '20161018'

select datepart(dw, @date) as daynumber,
       datename(weekday, @date) as DayName,
       datename(weekday, 3) as DayNumber3,
       datename(weekday, 1) as DayNumber1

it produces this result :

daynumber   DayName     DayNumber3    DayNumber1
3           Tuesday     Thursday      Tuesday

As you can see the datepart returns 3 and when I use this datepart in the call to datename it returns Tuesday.

But when I call datepart direct with the number 3 it returns Thursday and when I call datepart direct with the number 1 it returns Tuesday

So why does datepart(dw, @date) returns 3 in stead of 1 while datename(weekday, @date) does returns the correct day name ?

For me it is important to get the number 1 in stead of 3 and still keep getting Tuesday for this date.

EDIT:

The desired output I want for '20161018' is

daynumber    DayName
1            Tuesday

How can I get this result for the date from my example ?

Body:
I think you can add 5 and mod 7 will get your results as below:

Declare @date date = '20161018'

Select (datepart(dw, @date) + 5) % 7 as daynumber,
   datename(weekday, @date) as DayName,
   datename(weekday, 3) as DayNumber3,
   datename(weekday, 1) as DayNumber1


答:
```<code>UPDATE mytable t1
INNER JOIN mytable t2 ON t1.Week + 1 = t2.Week
SET t2.`Diff_X` = t2.`#X` - t1.`#X`,
    t2.`Diff_Y` = t2.`#Y` - t1.`#Y`,
    t2.`Diff_Z` = t2.`#Z` - t1.`#Z`
</code>```

Title: Calculating difference between rows MySQL

Body:
I have a table like this:

+----------+-----+--------+----+---------+-----+--------+
| Week     | #X  | Diff_X | #Y | Diff_Y  | #Z  | Diff_Z |
+----------+-----+--------+----+---------+-----+--------+
| 22       | 25  | Null   | 13 | NULL    |  0  | NULL   |
| 23       | 25  | Null   | 18 | NULL    |  12 | NULL   |
| 24       | 39  | Null   | 15 | NULL    |  16 | NULL   |
+----------+-----+--------+----+---------+-----+--------+

This updates every week, so 1 row a week.

How would I proceed into calculating the difference between each value between each week? and put them in the designated column.

So the desired result should look like this:

+----------+-----+--------+----+---------+-----+--------+
| Week     | #X  | Diff_X | #Y | Diff_Y  | #Z  | Diff_Z |
+----------+-----+--------+----+---------+-----+--------+
| 22       | 25  | 0      | 13 | 0       |  2  | 0      |
| 23       | 25  | 0      | 18 | 5       |  12 | 10     |
| 24       | 39  | 14     | 15 | -3      |  16 | 4      |
+----------+-----+--------+----+---------+-----+--------+

I am totally clueless in what to do, so any kind of help would be much appreciated!


问:
Drop down menu with text
Basically, I am looking for a drop down menu and you will click an option and it displays a table. If you check out the link below, it shows the code and a working preview (kind of). Basically, the problem I have is that it only works for the first 2 options and will not work for any of the other ones. The first 2, it works perfect though. Hopefully you will see what I mean. Any help would be appreciated.

https://jsfiddle.net/ca0cb7oz/

function display(obj,id1,id2) {
txt = obj.options[obj.selectedIndex].value;
document.getElementById(id1).style.display = 'none';
document.getElementById(id2).style.display = 'none';
if ( txt.match(id1) ) {
document.getElementById(id1).style.display = 'block';
}
if ( txt.match(id2) ) {
document.getElementById(id2).style.display = 'block';
}
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 6px;
}</code>```

Start Location:

<select name="type" onchange="display(this,'Warr','CrFields','OldLivRd','Penk','Cuerd','Halt','Widn');">
<option>Please select:</option>
<option value="Warr">Warrington Interchange</option>
<option value="CrFields">Crossfields</option>
<option value="LivRd">Old Liverpool Road</option>
<option value="Penk">Penketh Road</option>
<option value="Cuerd">Cuerdley Cross</option>
<option value="Halt">Halton View</option>
<option value="Widn">Widnes Green Oaks</option>
</select>

    Destination
    Adult Single
    Adult Return
    Child Single
    Child Return

    Crossfields
    £1.80
    £3.00
    N/A
    N/A

    Old Liverpool Road In
    £1.80
    £3.00
    N/A
    N/A

    Penketh Road
    £2.30
    £4.00
    N/A
    N/A

    Curdley Cross
    £2.80
    £4.00
    N/A
    N/A

    Halton View
    £2.80
    £4.00
    N/A
    N/A

    Widnes Green Oaks
    £3.30
    £4.80
    N/A
    N/A

    Destination
    Adult Single
    Adult Return
    Child Single
    Child Return

    Crossfields
    £1.80
    £3.00
    N/A
    N/A

    Old Liverpool Road In
    £1.80
    £3.00
    N/A
    N/A

    Penketh Road
    £2.30
    £4.00
    N/A
    N/A

    Curdley Cross
    £2.80
    £4.00
    N/A
    N/A

    Halton View
    £2.80
    £4.00
    N/A
    N/A

    Widnes Green Oaks
    £3.30
    £4.80
    N/A
    N/A

    Destination
    Adult Single
    Adult Return
    Child Single
    Child Return

    Crossfields
    £1.80
    £3.00
    N/A
    N/A

    Old Liverpool Road In
    £1.80
    £3.00
    N/A
    N/A

    Penketh Road
    £2.30
    £4.00
    N/A
    N/A

    Curdley Cross
    £2.80
    £4.00
    N/A
    N/A

    Halton View
    £2.80
    £4.00
    N/A
    N/A

    Widnes Green Oaks
    £3.30
    £4.80
    N/A
    N/A

```

答:
Some
-tags are superfluous which means you might have an issue with HTML, not JavaScript.

Title: Drop down menu with text

Body:
Basically, I am looking for a drop down menu and you will click an option and it displays a table. If you check out the link below, it shows the code and a working preview (kind of). Basically, the problem I have is that it only works for the first 2 options and will not work for any of the other ones. The first 2, it works perfect though. Hopefully you will see what I mean. Any help would be appreciated.

https://jsfiddle.net/ca0cb7oz/

function display(obj,id1,id2) {
txt = obj.options[obj.selectedIndex].value;
document.getElementById(id1).style.display = 'none';
document.getElementById(id2).style.display = 'none';
if ( txt.match(id1) ) {
document.getElementById(id1).style.display = 'block';
}
if ( txt.match(id2) ) {
document.getElementById(id2).style.display = 'block';
}
}

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 6px;
}

Start Location:

<select name="type" onchange="display(this,'Warr','CrFields','OldLivRd','Penk','Cuerd','Halt','Widn');">
<option>Please select:</option>
<option value="Warr">Warrington Interchange</option>
<option value="CrFields">Crossfields</option>
<option value="LivRd">Old Liverpool Road</option>
<option value="Penk">Penketh Road</option>
<option value="Cuerd">Cuerdley Cross</option>
<option value="Halt">Halton View</option>
<option value="Widn">Widnes Green Oaks</option>
</select>

    Destination
    Adult Single
    Adult Return
    Child Single
    Child Return

    Crossfields
    £1.80
    £3.00
    N/A
    N/A

    Old Liverpool Road In
    £1.80
    £3.00
    N/A
    N/A

    Penketh Road
    £2.30
    £4.00
    N/A
    N/A

    Curdley Cross
    £2.80
    £4.00
    N/A
    N/A

    Halton View
    £2.80
    £4.00
    N/A
    N/A

    Widnes Green Oaks
    £3.30
    £4.80
    N/A
    N/A

    Destination
    Adult Single
    Adult Return
    Child Single
    Child Return

    Crossfields
    £1.80
    £3.00
    N/A
    N/A

    Old Liverpool Road In
    £1.80
    £3.00
    N/A
    N/A

    Penketh Road
    £2.30
    £4.00
    N/A
    N/A

    Curdley Cross
    £2.80
    £4.00
    N/A
    N/A

    Halton View
    £2.80
    £4.00
    N/A
    N/A

    Widnes Green Oaks
    £3.30
    £4.80
    N/A
    N/A

    Destination
    Adult Single
    Adult Return
    Child Single
    Child Return

    Crossfields
    £1.80
    £3.00
    N/A
    N/A

    Old Liverpool Road In
    £1.80
    £3.00
    N/A
    N/A

    Penketh Road
    £2.30
    £4.00
    N/A
    N/A

    Curdley Cross
    £2.80
    £4.00
    N/A
    N/A

    Halton View
    £2.80
    £4.00
    N/A
    N/A

    Widnes Green Oaks
    £3.30
    £4.80
    N/A
    N/A

Body: Some <tr/>-tags are superfluous which means you might have an issue with HTML, not JavaScript.


问:
SignInManager.ExternalLoginSignInAsync fails to log in user
In the context of ASP.NET Identity in ASP.NET Core and OAuth, I have the following snippet in a login callback:

```<code>var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
    return RedirectToAction(nameof(Login));
}

var result = await _signInManager.ExternalLoginSignInAsync(
    info.LoginProvider,
    info.ProviderKey,
    isPersistent: true);

if (result.Succeeded)
{
    // ...
</code>```

For some reason that I'm unable to determine, result always comes back with status Failed, even though I do log into the external provider correctly (evidently, since a refresh of the external page suddenly shows me as logged on).

The only information I have except that the login attempt failed, is that it is not because any of IsLockedOut, RequiresTwoFactor or IsNotAllowed, since those flags are also false on the result object.

How do I obtain more information about what went wrong?

Update:

Following suggestions by @Dmitry, I've enabled quite aggressive logging, but I still fail to find anything valuable. The only thing I get in my logs between the successful fetch of info and the subsequent failed login attempt, is the following from my db context:

2017-07-04T22:45:14.2847287+02:00 0HL633KNRMVO7 [INF] Executed DbCommand (1ms) [Parameters=[@__get_Item_0='?' (Size = 450), @__get_Item_1='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
  SELECT TOP(1) [e].[LoginProvider], [e].[ProviderKey], [e].[ProviderDisplayName], [e].[UserId]
  FROM [AspNetUserLogins] AS [e]
  WHERE ([e].[LoginProvider] = @__get_Item_0) AND ([e].[ProviderKey] = @__get_Item_1) (6438bdd5)

Executing that in MSSQL Management Studio I get an empty result set, which I suspect might be a problem, but I have no idea why, or how to fix it. Any help is much appreciated.

答:
Your Startup.cs contains Configure(...) method with something like loggerFactory.AddConsole(...) in first lines.

Logging configuration may be set in code or read from configuration file (appsettings.json) - it depends on your project.

Check you current logging config and set level to Debug. Then restart app and check console output while logging in.

Docs: Introduction to Logging in ASP.NET

Body:
In the context of ASP.NET Identity in ASP.NET Core and OAuth, I have the following snippet in a login callback:

var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
    return RedirectToAction(nameof(Login));
}

var result = await _signInManager.ExternalLoginSignInAsync(
    info.LoginProvider,
    info.ProviderKey,
    isPersistent: true);

if (result.Succeeded)
{
    // ...

For some reason that I'm unable to determine, result always comes back with status Failed, even though I do log into the external provider correctly (evidently, since a refresh of the external page suddenly shows me as logged on).

The only information I have except that the login attempt failed, is that it is not because any of IsLockedOut, RequiresTwoFactor or IsNotAllowed, since those flags are also false on the result object.

How do I obtain more information about what went wrong?

Update:

Following suggestions by @Dmitry, I've enabled quite aggressive logging, but I still fail to find anything valuable. The only thing I get in my logs between the successful fetch of info and the subsequent failed login attempt, is the following from my db context:

2017-07-04T22:45:14.2847287+02:00 0HL633KNRMVO7 [INF] Executed DbCommand (1ms) [Parameters=[@__get_Item_0='?' (Size = 450), @__get_Item_1='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
  SELECT TOP(1) [e].[LoginProvider], [e].[ProviderKey], [e].[ProviderDisplayName], [e].[UserId]
  FROM [AspNetUserLogins] AS [e]
  WHERE ([e].[LoginProvider] = @__get_Item_0) AND ([e].[ProviderKey] = @__get_Item_1) (6438bdd5)

Executing that in MSSQL Management Studio I get an empty result set, which I suspect might be a problem, but I have no idea why, or how to fix it. Any help is much appreciated.


问:
Javascript promises stuck waiting for each other
I have this code for managing dashboard which contains approximate 100 of independent checks.

Check results are received via AJAX call.

There is one initial request for each check at start. After result is received for particular check, the code recursively waits for set timeout and repeats the request again for that check again.

One promise = one check.

I am wondering why promises starts to resolve only after each one of them is pending (none of them is in timeout period). And that is even if response from server is "instantaneous", they just wait for the last promise in cycle.

```<code>const TIMEOUT = 4000;

function checkForUpdate(environment, application, check) {
    Dashboard.setCheckPending(environment, application, check);

    return Communicator.getStatus(environment, application, check)
        .then(status => {
            Dashboard.updateCheckCell(environment, application, check, status);
            Dashboard.updateEnvironmentCell(environment, application);

            setTimeout(() => {
                    return checkForUpdate(environment, application, check)
                },
                TIMEOUT
            );
        });
}

Communicator.getEnvMatrix()
    .then(data => {
        Dashboard.create(data);

        $.each(data, (environment, applications) => {
            $.each(applications, (application, checks) => {
                $.each(checks, (key, check) => {
                    checkForUpdate(environment, application, check);
                });
            });
        });
    });
</code>```

The question is also how to rewrite that so each of the checks waits just for its own result to be delivered and for set timeout.

EDIT (clarification):

Each of the 100 checks are independent, that is why I want to run AJAX for each of them as soon as I can (inside the $.each() loops).

The check is dependent only on itself. I don't want it to wait on any other check.

After the result of a check is received it has to wait for set timeout before it tries to retrieve its status again. That is why I encapsulated the recursive function within the setTimeout().

Even if I rewrite (see below) the setTimeout() as promise, the behavior stays the same unfortunately.

```<code>function delay(timeout) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);
    });
}

function checkForUpdate(environment, application, check) {
    Dashboard.setCheckPending(environment, application, check);

    let promise = Communicator.getStatus(environment, application, check).promise();

    return promise
        .then(status => {
            Dashboard.updateCheckCell(environment, application, check, status);
            Dashboard.updateEnvironmentCell(environment, application);

            return delay(TIMEOUT).then(() => {
                return checkForUpdate(environment, application, check);
            });
        });
}
</code>```

答:
Your code runs $.each() synchronously.  That means it is going to call every checkForUpdate() before anything else can run.  Since standards-conforming promises are always resolved asynchronously (on some future tick), that means that every single request here will get started before ANY promise can run its .then() handler.  That's how promises work.   Only once the $.each() loop is done can the Javascript interpreter start to process the .then() handlers of resolved promises.

Also, it is unclear why you are trying to do a return checkForUpdate(environment, application, check) inside the setTimeout().  The return there does nothing.  It's just returning to the setTimeout() callback which does nothing.  The parent function has long since already returned so this is not chaining the next checkForUpdate() to the previous promise chain.  If you wanted to chain them together, then you need to make a delay with a promise and return that promise like is shown in these references:

using setTimeout on promise chain

Delays between promises in promise chain

Delay chained promise

The unexpected thing is that even if all 100 requests are sent immediately after page loads, they are being resolved just few at a time and (roughly) in the order they've been sent. Roughly means 3, 2, 5, 1, 8, .... But I'd expect something like 3, 89, 12, 76, 21, 94, .... There seems to be some limit on how many promises can be run concurrently and in what order.

Another thing that will influence your ajax calls is that each browser has a limit on how many concurrent ajax calls it will allow to the same host.  If you exceed that limit, it will queue them and not run subsequent ones until some earlier ones finish.  Each browser sets its own limit and they've changed over time so I don't know exactly what the current limits are, but they are lowish. I know Chrome used to be something like 6 at at time to the same host.  So, that will also affect the exact order that things complete.

When you hit this limit, Ajax calls will be sent in the order they were called by your code.  So, if the limit was 6 per host, then your first 6 would be sent and the 7th request would only be sent when one of the first 6 finished and so on.  That still doesn't guarantee a finish order, but it does affect the ability for a later request to finish before an earlier request.

Body:
I have this code for managing dashboard which contains approximate 100 of independent checks.

Check results are received via AJAX call.

There is one initial request for each check at start. After result is received for particular check, the code recursively waits for set timeout and repeats the request again for that check again.

One promise = one check.

I am wondering why promises starts to resolve only after each one of them is pending (none of them is in timeout period). And that is even if response from server is "instantaneous", they just wait for the last promise in cycle.

const TIMEOUT = 4000;

function checkForUpdate(environment, application, check) {
    Dashboard.setCheckPending(environment, application, check);

    return Communicator.getStatus(environment, application, check)
        .then(status => {
            Dashboard.updateCheckCell(environment, application, check, status);
            Dashboard.updateEnvironmentCell(environment, application);

            setTimeout(() => {
                    return checkForUpdate(environment, application, check)
                },
                TIMEOUT
            );
        });
}

Communicator.getEnvMatrix()
    .then(data => {
        Dashboard.create(data);

        $.each(data, (environment, applications) => {
            $.each(applications, (application, checks) => {
                $.each(checks, (key, check) => {
                    checkForUpdate(environment, application, check);
                });
            });
        });
    });

The question is also how to rewrite that so each of the checks waits just for its own result to be delivered and for set timeout.

EDIT (clarification):

Each of the 100 checks are independent, that is why I want to run AJAX for each of them as soon as I can (inside the $.each() loops).

The check is dependent only on itself. I don't want it to wait on any other check.

After the result of a check is received it has to wait for set timeout before it tries to retrieve its status again. That is why I encapsulated the recursive function within the setTimeout().

Even if I rewrite (see below) the setTimeout() as promise, the behavior stays the same unfortunately.

function delay(timeout) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);
    });
}

function checkForUpdate(environment, application, check) {
    Dashboard.setCheckPending(environment, application, check);

    let promise = Communicator.getStatus(environment, application, check).promise();

    return promise
        .then(status => {
            Dashboard.updateCheckCell(environment, application, check, status);
            Dashboard.updateEnvironmentCell(environment, application);

            return delay(TIMEOUT).then(() => {
                return checkForUpdate(environment, application, check);
            });
        });
}


问:
How can I open pdf file from document directory Swift 3
I have the pdf Stored in Document Directory and I want to open this pdf file</p>

```<code>let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

let path = documentsURL.appendingPathComponent("myFile.pdf")
</code>```

答:
You can open you pdf file using QLPreviewController import QuickLook into your controller</p>

```<code>import QuickLook

func openQlPreview() {
        let previoew = QLPreviewController.init()
        previoew.dataSource = self
        previoew.delegate = self
        self.present(previoew, animated: true, completion: nil)
    }

extension UIViewController : QLPreviewControllerDelegate , QLPreviewControllerDataSource{

    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }

    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
         //  pass your document url here
        return path as QLPreviewItem
    }

    func previewController(_ controller: QLPreviewController, shouldOpen url: URL, for item: QLPreviewItem) -> Bool {
        return true
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the pdf Stored in Document Directory and I want to open this pdf file

let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

let path = documentsURL.appendingPathComponent("myFile.pdf")

Body:
You can open you pdf file using QLPreviewController import QuickLook into your controller

import QuickLook

func openQlPreview() {
        let previoew = QLPreviewController.init()
        previoew.dataSource = self
        previoew.delegate = self
        self.present(previoew, animated: true, completion: nil)
    }

extension UIViewController : QLPreviewControllerDelegate , QLPreviewControllerDataSource{

    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }

    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
         //  pass your document url here
        return path as QLPreviewItem
    }

    func previewController(_ controller: QLPreviewController, shouldOpen url: URL, for item: QLPreviewItem) -> Bool {
        return true
    }

}


问:
Tensorboard error after installing via pip
I have recently attempted to install tensorboard via pip as detailed in the README.md. The installation was deemed successful however when I try to run tensorboard after the installation, I keep on receiving an import/undefined symbol error as seen below.

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/tensorboard/tensorboard.py", line 32, in <module>
    from tensorflow.python.summary import event_file_inspector as efi
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/summary/event_file_inspector.py", line 122, in <module>
    from tensorflow.python.platform import gfile
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/platform/gfile.py", line 22, in <module>
    from tensorflow.python.lib.io.file_io import copy as Copy
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/lib/io/file_io.py", line 27, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: /usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/_pywrap_tensorflow.so: undefined symbol: PyBytes_AsStringAndSize
</code>```

Have I missed something in the installation process?

What can I do to fix this?

Thanks!

答:
above error is reported because Tensorboard is installed using pip3(python 3) and TF env is set to python2.7.

use pip2 install tensorboard

now tensorboard and tf env both set to python2

Body:
I have recently attempted to install tensorboard via pip as detailed in the README.md. The installation was deemed successful however when I try to run tensorboard after the installation, I keep on receiving an import/undefined symbol error as seen below.

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/tensorboard/tensorboard.py", line 32, in <module>
    from tensorflow.python.summary import event_file_inspector as efi
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/summary/event_file_inspector.py", line 122, in <module>
    from tensorflow.python.platform import gfile
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/platform/gfile.py", line 22, in <module>
    from tensorflow.python.lib.io.file_io import copy as Copy
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/lib/io/file_io.py", line 27, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: /usr/local/lib/python3.5/dist-packages/tensorboard/tensorboard.runfiles/org_tensorflow/tensorflow/python/_pywrap_tensorflow.so: undefined symbol: PyBytes_AsStringAndSize

Have I missed something in the installation process?

What can I do to fix this?

Thanks!


问:
Find largest adjacent product in array (JavaScript)
I'm trying to understand the following solution for finding the largest adjacent product in any given array.

Example:

```<code> For inputArray = [3, 6, -2, -5, 7, 3], the output should be
 adjacentElementsProduct(inputArray) = 21.

 7 and 3 produce the largest product.
</code>```

Possible solution in JS:

```<code>function adjacentElementsProduct(arr) {
  return Math.max(...arr.slice(1).map((x,i)=>[x*arr[i]]))
  }
</code>```

I am having a hard time understanding two things:

What do the three dots exactly do and how does this get passed into the function? Is there any way to write this in a more understandable way? I know that is the "spread syntax" feature in ES6, but still don't understand completely.

Why do we insert "1" as argument to slice? My first though was to input "0", because we want to start at the start, then loop through everything, and see which adjacent product is the largest.

I'd appreciate any advice, links and explanations.

Thanks.

Cheers!

答:
You may simply do as follows;

function getNeigboringMaxProduct([x,...xs], r = -Infinity){
  var p = x * xs[0];
  return xs.length ? getNeigboringMaxProduct(xs, p > r ? p : r)
                   : r;
}

var arr = [3, 6, -2, -5, 7, 3],
    res = getNeigboringMaxProduct(arr);
console.log(res);```

Body:
I'm trying to understand the following solution for finding the largest adjacent product in any given array.

Example:

 For inputArray = [3, 6, -2, -5, 7, 3], the output should be
 adjacentElementsProduct(inputArray) = 21.

 7 and 3 produce the largest product.

Possible solution in JS:

function adjacentElementsProduct(arr) {
  return Math.max(...arr.slice(1).map((x,i)=>[x*arr[i]]))
  }

I am having a hard time understanding two things:

What do the three dots exactly do and how does this get passed into the function? Is there any way to write this in a more understandable way? I know that is the "spread syntax" feature in ES6, but still don't understand completely.

Why do we insert "1" as argument to slice? My first though was to input "0", because we want to start at the start, then loop through everything, and see which adjacent product is the largest.

I'd appreciate any advice, links and explanations.

Thanks.

Cheers!


问:
Spring Integration Wrong Host Header
We've been experiencing this weird problem with the request Host header being set as the application's URL. This results to the external system to not handle our requests.

Here's the DEBUG log of apache of the Spring Integration application hosted on localhost:8082. Don't mind the content for now but the Content-Type will be a problem subsequently:

```<code>org.apache.http.wire - http-outgoing-0 >> "POST /health HTTP/1.1[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Accept: */*[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "cookie: PHPSESSID=ost897ibh0j7rovf2rudr33c22[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "host: localhost:8082[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "connection: keep-alive[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Cache-Control: no-cache[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/xml[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "accept-encoding: gzip, deflate[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "user-agent: PostmanRuntime/6.1.6[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Length: 4[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "test"
org.apache.http.wire - http-outgoing-0 << "HTTP/1.1 200 OK[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "Content-Type: application/json[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "Transfer-Encoding: chunked[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "Server: Jetty(9.2.z-SNAPSHOT)[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "27[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "{"success":true,"message":"Service up"}"
org.apache.http.headers - http-outgoing-0 << HTTP/1.1 200 OK
org.apache.http.headers - http-outgoing-0 << Content-Type: application/json
org.apache.http.headers - http-outgoing-0 << Transfer-Encoding: chunked
org.apache.http.headers - http-outgoing-0 << Server: Jetty(9.2.z-SNAPSHOT)
org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "0[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
</code>```

and here's the request done with curl:

```<code>curl -v -X POST http://localhost:9292/health
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9292 (#0)
> POST /health HTTP/1.1
> Host: localhost:9292
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Transfer-Encoding: chunked
< Server: Jetty(9.2.z-SNAPSHOT)
</code>```

So with Spring Integration
org.apache.http.wire - http-outgoing-0 >> "host: localhost:8082[\r][\n]"

and with curl
> Host: localhost:9292

We can easily solve the host problem in Spring Integration by setting the header mapper of the outgate:
handler.setHeaderMapper(new DefaultHttpHeaderMapper());

```<code>org.apache.http.wire - http-outgoing-0 >> "POST /health HTTP/1.1[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Accept: application/json, application/*+json[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Type: text/plain;charset=UTF-8[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Length: 4[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Host: localhost:9292[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_112)[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "test"
</code>```

So we were able to solve the problem with the Host header, unfortunately, it seems that the Content-Type set through an enricher has been ignored and has been set to text/plain instead of application/xml.

What seems to be the problem here? I'm assuming this has to do with just using a basic DefaultHttpHeaderMapper.

Here's the flow configuration snippet:

```<code>public class BasicIntegrationConfig {

    @Bean
    public MessageChannel basicRequestChannel() {
        return MessageChannels.publishSubscribe().get();
    }

    @Bean
    public MessageChannel basicResponseChannel() {
        return MessageChannels.publishSubscribe().get();
    }

    @Bean
    public MessagingGatewaySupport basicInGate() {
        HttpRequestHandlingMessagingGateway handler = new HttpRequestHandlingMessagingGateway();

        RequestMapping mapping = new RequestMapping();
        mapping.setPathPatterns("api/v1/basic");
        mapping.setMethods(HttpMethod.GET);
        mapping.setProduces(MediaType.APPLICATION_JSON_UTF8_VALUE);
        handler.setRequestMapping(mapping);

        handler.setRequestChannel(basicRequestChannel());
        handler.setReplyChannel(basicResponseChannel());

        return handler;
    }

    @Bean
    public MessageHandler basicOutGate() {
        HttpRequestExecutingMessageHandler handler =
                new HttpRequestExecutingMessageHandler("http://localhost:9292/health");
        handler.setHttpMethod(HttpMethod.POST);
        handler.setExpectedResponseType(BaseResponse.class);
        handler.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        handler.setHeaderMapper(new DefaultHttpHeaderMapper());
        return handler;
    }

    @Bean
    public IntegrationFlow basicFlow() {
        return (IntegrationFlowDefinition<?> f) -> f
                .channel(basicRequestChannel())
                .log("basic")
                .handle((GenericHandler<Object>) (o, map) -> "test")
                .enrichHeaders(e -> e.header(MessageHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE, true))
                .log("basic")
                .handle(basicOutGate())
                .log("basic")
                .enrichHeaders(e -> e.header(MessageHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE, true))
                .channel(basicResponseChannel());
    }
}
</code>```

答:
Use</p>

```<code>DefaultHttpHeaderMapper mapper = DefaultHttpHeaderMapper.outboundMapper();
mapper.setExcludedOutboundStandardRequestHeaderNames(new String[] { "Host" });
handler.setHeaderMapper(mapper);
</code>```

Title: Spring Integration Wrong Host Header

Body:
We've been experiencing this weird problem with the request Host header being set as the application's URL. This results to the external system to not handle our requests.

Here's the DEBUG log of apache of the Spring Integration application hosted on localhost:8082. Don't mind the content for now but the Content-Type will be a problem subsequently:

org.apache.http.wire - http-outgoing-0 >> "POST /health HTTP/1.1[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Accept: */*[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "cookie: PHPSESSID=ost897ibh0j7rovf2rudr33c22[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "host: localhost:8082[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "connection: keep-alive[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Cache-Control: no-cache[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/xml[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "accept-encoding: gzip, deflate[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "user-agent: PostmanRuntime/6.1.6[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Length: 4[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "test"
org.apache.http.wire - http-outgoing-0 << "HTTP/1.1 200 OK[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "Content-Type: application/json[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "Transfer-Encoding: chunked[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "Server: Jetty(9.2.z-SNAPSHOT)[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "27[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "{"success":true,"message":"Service up"}"
org.apache.http.headers - http-outgoing-0 << HTTP/1.1 200 OK
org.apache.http.headers - http-outgoing-0 << Content-Type: application/json
org.apache.http.headers - http-outgoing-0 << Transfer-Encoding: chunked
org.apache.http.headers - http-outgoing-0 << Server: Jetty(9.2.z-SNAPSHOT)
org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "0[\r][\n]"
org.apache.http.wire - http-outgoing-0 << "[\r][\n]"

and here's the request done with curl:

curl -v -X POST http://localhost:9292/health
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9292 (#0)
> POST /health HTTP/1.1
> Host: localhost:9292
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Transfer-Encoding: chunked
< Server: Jetty(9.2.z-SNAPSHOT)

So with Spring Integration
org.apache.http.wire - http-outgoing-0 >> "host: localhost:8082[\r][\n]"

and with curl
> Host: localhost:9292

We can easily solve the host problem in Spring Integration by setting the header mapper of the outgate:
handler.setHeaderMapper(new DefaultHttpHeaderMapper());

org.apache.http.wire - http-outgoing-0 >> "POST /health HTTP/1.1[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Accept: application/json, application/*+json[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Type: text/plain;charset=UTF-8[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Length: 4[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Host: localhost:9292[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_112)[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
org.apache.http.wire - http-outgoing-0 >> "test"

So we were able to solve the problem with the Host header, unfortunately, it seems that the Content-Type set through an enricher has been ignored and has been set to text/plain instead of application/xml.

What seems to be the problem here? I'm assuming this has to do with just using a basic DefaultHttpHeaderMapper.

Here's the flow configuration snippet:

public class BasicIntegrationConfig {

    @Bean
    public MessageChannel basicRequestChannel() {
        return MessageChannels.publishSubscribe().get();
    }

    @Bean
    public MessageChannel basicResponseChannel() {
        return MessageChannels.publishSubscribe().get();
    }

    @Bean
    public MessagingGatewaySupport basicInGate() {
        HttpRequestHandlingMessagingGateway handler = new HttpRequestHandlingMessagingGateway();

        RequestMapping mapping = new RequestMapping();
        mapping.setPathPatterns("api/v1/basic");
        mapping.setMethods(HttpMethod.GET);
        mapping.setProduces(MediaType.APPLICATION_JSON_UTF8_VALUE);
        handler.setRequestMapping(mapping);

        handler.setRequestChannel(basicRequestChannel());
        handler.setReplyChannel(basicResponseChannel());

        return handler;
    }

    @Bean
    public MessageHandler basicOutGate() {
        HttpRequestExecutingMessageHandler handler =
                new HttpRequestExecutingMessageHandler("http://localhost:9292/health");
        handler.setHttpMethod(HttpMethod.POST);
        handler.setExpectedResponseType(BaseResponse.class);
        handler.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        handler.setHeaderMapper(new DefaultHttpHeaderMapper());
        return handler;
    }

    @Bean
    public IntegrationFlow basicFlow() {
        return (IntegrationFlowDefinition<?> f) -> f
                .channel(basicRequestChannel())
                .log("basic")
                .handle((GenericHandler<Object>) (o, map) -> "test")
                .enrichHeaders(e -> e.header(MessageHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE, true))
                .log("basic")
                .handle(basicOutGate())
                .log("basic")
                .enrichHeaders(e -> e.header(MessageHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE, true))
                .channel(basicResponseChannel());
    }
}

Body:
Use

DefaultHttpHeaderMapper mapper = DefaultHttpHeaderMapper.outboundMapper();
mapper.setExcludedOutboundStandardRequestHeaderNames(new String[] { "Host" });
handler.setHeaderMapper(mapper);


问:
How to handle (i.e. log) errors in restify
In our restify app, when we pass an error to next, a generic 500 error is returned, which is all just fine. However, I need to also log the details of the error somewhere so that I know what happened.

Previously, I worked on an express application, and a centralized error-handling middleware gave us the ability to do any arbitrary code when receiving errors, like logging.

What's the "restify way" to centralizing the logging of error details? I do not want to sprinkle logging statements throughout the entire app.

答:
An alternative to listening to 'after' is listening to 'restifyError':

```<code>server.on('restifyError', (req, res, err, cb) => {
  req.log.error(err)
  return cb();
});
</code>```

Body:
An alternative to listening to 'after' is listening to 'restifyError':

server.on('restifyError', (req, res, err, cb) => {
  req.log.error(err)
  return cb();
});


问:
Get button click from reusable cell in collection view (xib file)
I have created reusable cell with include a button in a XIB for a collection.

I can change the text of labels and buttons in the collection view but i can't get on click event.

I have tried below options:

a.   This in UICollectionViewCell :  Not working

```<code>class cellVC: UICollectionViewCell {
    @IBOutlet weak var sampleLabel: UILabel!
    @IBOutlet weak var buttonClicked: UIButton!

    @IBAction func buttonTest(_ sender: Any) {
        print("dsfsdf   111111")
    }
}
</code>```

b. I have also tried : Not working

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{

    let cell : cellVC = collectionView.dequeueReusableCell(withReuseIdentifier: "cellVC", for: indexPath) as! cellVC
    cell.sampleLabel. = "sample text"
    cell.buttonClicked.tag = indexPath.row
    cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)

    cell.buttonClicked.backgroundColor = UIColor.cyan
    return cell
}

func masterAction(_ sender: UIButton) {
    print ("button click")
}
</code>```

As both solutions are not working, how do i achieve this.

Thanks

答:
Places To Check

There are several potential points of failure here, because what you're doing seems to look right. I have a sample Xcode project which has this working. (See it on GitHub.)

You can double check these things, to make sure everything is set up correctly:

Your collection view's data source and delegate are wired up

Your button and sample label have their outlet's connected correctly

Your storyboard has the appropriate class and identifier set up

Your selector is named correctly

It seems, based on what you've posted here that all of the above conditions are true, so let's talk a little more about what you're trying to do and see how all the pieces fit.

Why these Things Seem Ok

If the data source and delegate were incorrectly set up, you wouldn't see your cells.

If your outlets were incorrectly wired, you'd end up with crashes, because IBOutlets are force-unwrapped by default. (And that's how your posted code works.)

Your storyboard seems to be set up correctly because, again, your cells wouldn't appear without the right set up.

An incorrectly named selector wouldn't even compile.

Implications of Cells and Recycling

In general, this is a tricky problem to solve, because of the way UICollectionView is designed. (The same applies to UITableView.)

Your button is inside of a re-usable collection view cell, which means that you not only have to handle taps, but you need to know which index path in your data set the button is currently referring to.

Further, views that are placed inside an instance of UICollectionViewCell are actually inside the collection view cell's contentView, which makes it just a little more work to handle.

Finally, if your cells scroll on and offscreen, then you may end up attaching the action to your button multiple times as the cell is recycled. So, you need to account for that as well.

An Implementation Example

Let's work with a very simple custom cell, that has a single button in it:

The code for the button looks like this:

```<code>import UIKit

class CustomCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var updateButton: UIButton!
}
</code>```

Really simple. Notice the IBOutlet. That needs to be wired up in interface builder as well.

The last thing we need to do is set up the cell's reuse identifier so that we can access it in code. With the cell selected in Interface Builder, add an identifier to the cell:

Ok, that's all you need to do with the cell. We're ready to implement the view controller. In the view controller, we're going to set up a few things:

A label to show that our button inside the cell was tapped

An outlet for our collection view, so we can get the index path of the cell that contains the button. (If you're using a UICollectionViewController instead of aUIViewController, this won't be necessary.)

Some code to show our custom cell.

Some code to handle the button tap.

Let's start with the IBOutlets:

```<code>class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var lastTappedLabel: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
</code>```

We need to wire those up in Interface builder. While you're at it, also connect the collection view's data source and delegate to be the "File's Owner" if they aren't connected already. (Again, if you're using a UICollectionViewController instead of aUIViewController, this won't be necessary.)

Next, let's implement some code to show our custom cell, using UICollectionViewDataSource. We need to show at least one section and at least one cell:

```<code>// MARK: - UICollectionViewDataSource

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 36
}
</code>```

When we dequeue the cell, we want to force downcast our dequeued cell to the custom cell class we defined earlier. Then we can access the update button to add an action to it.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "com.mosheberman.samples.cell", for: indexPath) as! CustomCollectionViewCell

    cell.updateButton.addTarget(self, action: #selector(updateLabel(_:)), for: .touchUpInside)

    return cell
}
</code>```

Now we need to implement the method for accessing the index path of the cell:

```<code>// MARK: - Updating the Label

@objc func updateLabel(_ sender:UIButton)
{
    print("\(sender) tapped. Update label called.")

    guard let button = sender as? UIButton else
    {
        print("Sender isn't a button. Returning.")
        return
    }

    guard let contentView = button.superview else
    {
        print("Button isn't inside a contentView. Returning.")
        return
    }

    guard let cell = contentView.superview as? UICollectionViewCell else
    {
        print("View's superview isn't a UICollectionViewCell instance. Returning.")
        return
    }

    guard let collectionView = self.collectionView else
    {
        print("Our collection view isn't wired up. Returning.")
        return
    }

    guard let indexPathForCell = collectionView.indexPath(for: cell) else
    {
        print("The cell doesn't correspond to an index path. Maybe it's not a child of this collection view?")
        return
    }

    self.lastTappedLabel.text = "Tapped button at \(indexPathForCell.item), \(indexPathForCell.section)"
}
</code>```

This method handles all of the checks you need to handle the tap and determine which item was actually tapped.

We need to ensure the sender is actually a UIButton instance. Not critical, but if we don't at least ensure it's a UIView, we won't be able to get the superview.

Once we have that, ensure the button is inside a superview, which we assume to be the contentView.

Check for the superview of the content view, and we'll have the cell itself.

At this point we can ask the collection view (which we have a reference to, because of the outlet set up above) for the index path to the cell.

Once we have an index path, we can update our label or do something with the data backing the cell.

Notes

While testing this I see that you may not actually need to remove the target-action anymore - UIKit seems to do the right thing now and only calls your method once.

The code we wrote here is available on GitHub.

Edit:

@DonMag pointed out that you're using a nib instead of a storyboard, which I overlooked initially. So, here's the process for getting it all set up with nibs:

We can use the same cell class as above, but we need to add a separate nib for it, because the view controller nib doesn't support cell prototypes.

We need to register the nib separately, for the same reason. Including a cell prototype in the storyboard does this automatically. When working with nibs, you don't get this for free.

We need to set up the view controller in the nib.

Almost all of the other code can be moved over from the storyboard version.

Let's start by making a new nib for the CustomCollectionViewCell. Using the "Empty" template, make a new nib called "CustomCollectionViewCell.xib." The name doesn't have to match the class, but it's going to be used later on, so to follow convention, let's call it that.

In the new nib, drag out a collection view cell from the palette on the bottom right, and then add the label to it. Set the custom class to CustomViewControllerCell (or whatever yours is called) and connect the label to the outlet.

Next, let's make a new View Controller. We probably can re-use the initial one, but so that we don't register two cells for the same identifier, let's stick to a new UIViewController subclass. To get the nib, check "Also create XIB file."

Inside the new nib-based view controller, we want the same outlets as we had before. We also want the same UICollectionViewDataSource implementation. There's one thing that's different here: we need to register the cell.

To do so, let's add a method called registerCollectionViewCell() which we'll call from viewDidLoad. Here's what it looks like:

```<code>// MARK: - Setting Up The Collection View Cell

func registerCollectionViewCell()
{
    guard let collectionView = self.collectionView else
    {
        print("We don't have a reference to the collection view.")
        return
    }

    let nib = UINib(nibName: "CustomCollectionViewCell", bundle: Bundle.main)

    collectionView.register(nib, forCellWithReuseIdentifier: "com.mosheberman.samples.cell")
}
</code>```

Our viewDidLoad() method looks like this now:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    self.registerCollectionViewCell()

    // Do any additional setup after loading the view.
}
</code>```

Inside the nib, lay out the label and collection view as we did before. Wire up the outlets and the collection view data source, and delegate, and we should be done!

A couple of other things:

In my demo project, I needed to also present the nib-based version of the view controller. I did that in the app delegate by replacing whatever the app's main storyboard loaded in application(_:didFinishLaunchingWithOptions:)

Your storyboard nib should have the File's Owner left to the default value of NSObject. The cell should have a custom class matching whatever class you want to load.

Body:
I have created reusable cell with include a button in a XIB for a collection.

I can change the text of labels and buttons in the collection view but i can't get on click event.

I have tried below options:

a.   This in UICollectionViewCell :  Not working

class cellVC: UICollectionViewCell {
    @IBOutlet weak var sampleLabel: UILabel!
    @IBOutlet weak var buttonClicked: UIButton!

    @IBAction func buttonTest(_ sender: Any) {
        print("dsfsdf   111111")
    }
}

b. I have also tried : Not working

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{

    let cell : cellVC = collectionView.dequeueReusableCell(withReuseIdentifier: "cellVC", for: indexPath) as! cellVC
    cell.sampleLabel. = "sample text"
    cell.buttonClicked.tag = indexPath.row
    cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)

    cell.buttonClicked.backgroundColor = UIColor.cyan
    return cell
}

func masterAction(_ sender: UIButton) {
    print ("button click")
}

As both solutions are not working, how do i achieve this.

Thanks

Body:
Places To Check

There are several potential points of failure here, because what you're doing seems to look right. I have a sample Xcode project which has this working. (See it on GitHub.)

You can double check these things, to make sure everything is set up correctly:

Your collection view's data source and delegate are wired up

Your button and sample label have their outlet's connected correctly

Your storyboard has the appropriate class and identifier set up

Your selector is named correctly

It seems, based on what you've posted here that all of the above conditions are true, so let's talk a little more about what you're trying to do and see how all the pieces fit.

Why these Things Seem Ok

If the data source and delegate were incorrectly set up, you wouldn't see your cells.

If your outlets were incorrectly wired, you'd end up with crashes, because IBOutlets are force-unwrapped by default. (And that's how your posted code works.)

Your storyboard seems to be set up correctly because, again, your cells wouldn't appear without the right set up.

An incorrectly named selector wouldn't even compile.

Implications of Cells and Recycling

In general, this is a tricky problem to solve, because of the way UICollectionView is designed. (The same applies to UITableView.)

Your button is inside of a re-usable collection view cell, which means that you not only have to handle taps, but you need to know which index path in your data set the button is currently referring to.

Further, views that are placed inside an instance of UICollectionViewCell are actually inside the collection view cell's contentView, which makes it just a little more work to handle.

Finally, if your cells scroll on and offscreen, then you may end up attaching the action to your button multiple times as the cell is recycled. So, you need to account for that as well.

An Implementation Example

Let's work with a very simple custom cell, that has a single button in it:

The code for the button looks like this:

import UIKit

class CustomCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var updateButton: UIButton!
}

Really simple. Notice the IBOutlet. That needs to be wired up in interface builder as well.

The last thing we need to do is set up the cell's reuse identifier so that we can access it in code. With the cell selected in Interface Builder, add an identifier to the cell:

Ok, that's all you need to do with the cell. We're ready to implement the view controller. In the view controller, we're going to set up a few things:

A label to show that our button inside the cell was tapped

An outlet for our collection view, so we can get the index path of the cell that contains the button. (If you're using a UICollectionViewController instead of aUIViewController, this won't be necessary.)

Some code to show our custom cell.

Some code to handle the button tap.

Let's start with the IBOutlets:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var lastTappedLabel: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!

We need to wire those up in Interface builder. While you're at it, also connect the collection view's data source and delegate to be the "File's Owner" if they aren't connected already. (Again, if you're using a UICollectionViewController instead of aUIViewController, this won't be necessary.)

Next, let's implement some code to show our custom cell, using UICollectionViewDataSource. We need to show at least one section and at least one cell:

// MARK: - UICollectionViewDataSource

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 36
}

When we dequeue the cell, we want to force downcast our dequeued cell to the custom cell class we defined earlier. Then we can access the update button to add an action to it.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "com.mosheberman.samples.cell", for: indexPath) as! CustomCollectionViewCell

    cell.updateButton.addTarget(self, action: #selector(updateLabel(_:)), for: .touchUpInside)

    return cell
}

Now we need to implement the method for accessing the index path of the cell:

// MARK: - Updating the Label

@objc func updateLabel(_ sender:UIButton)
{
    print("\(sender) tapped. Update label called.")

    guard let button = sender as? UIButton else
    {
        print("Sender isn't a button. Returning.")
        return
    }

    guard let contentView = button.superview else
    {
        print("Button isn't inside a contentView. Returning.")
        return
    }

    guard let cell = contentView.superview as? UICollectionViewCell else
    {
        print("View's superview isn't a UICollectionViewCell instance. Returning.")
        return
    }

    guard let collectionView = self.collectionView else
    {
        print("Our collection view isn't wired up. Returning.")
        return
    }

    guard let indexPathForCell = collectionView.indexPath(for: cell) else
    {
        print("The cell doesn't correspond to an index path. Maybe it's not a child of this collection view?")
        return
    }

    self.lastTappedLabel.text = "Tapped button at \(indexPathForCell.item), \(indexPathForCell.section)"
}

This method handles all of the checks you need to handle the tap and determine which item was actually tapped.

We need to ensure the sender is actually a UIButton instance. Not critical, but if we don't at least ensure it's a UIView, we won't be able to get the superview.

Once we have that, ensure the button is inside a superview, which we assume to be the contentView.

Check for the superview of the content view, and we'll have the cell itself.

At this point we can ask the collection view (which we have a reference to, because of the outlet set up above) for the index path to the cell.

Once we have an index path, we can update our label or do something with the data backing the cell.

Notes

While testing this I see that you may not actually need to remove the target-action anymore - UIKit seems to do the right thing now and only calls your method once.

The code we wrote here is available on GitHub.

Edit:

@DonMag pointed out that you're using a nib instead of a storyboard, which I overlooked initially. So, here's the process for getting it all set up with nibs:

We can use the same cell class as above, but we need to add a separate nib for it, because the view controller nib doesn't support cell prototypes.

We need to register the nib separately, for the same reason. Including a cell prototype in the storyboard does this automatically. When working with nibs, you don't get this for free.

We need to set up the view controller in the nib.

Almost all of the other code can be moved over from the storyboard version.

Let's start by making a new nib for the CustomCollectionViewCell. Using the "Empty" template, make a new nib called "CustomCollectionViewCell.xib." The name doesn't have to match the class, but it's going to be used later on, so to follow convention, let's call it that.

In the new nib, drag out a collection view cell from the palette on the bottom right, and then add the label to it. Set the custom class to CustomViewControllerCell (or whatever yours is called) and connect the label to the outlet.

Next, let's make a new View Controller. We probably can re-use the initial one, but so that we don't register two cells for the same identifier, let's stick to a new UIViewController subclass. To get the nib, check "Also create XIB file."

Inside the new nib-based view controller, we want the same outlets as we had before. We also want the same UICollectionViewDataSource implementation. There's one thing that's different here: we need to register the cell.

To do so, let's add a method called registerCollectionViewCell() which we'll call from viewDidLoad. Here's what it looks like:

// MARK: - Setting Up The Collection View Cell

func registerCollectionViewCell()
{
    guard let collectionView = self.collectionView else
    {
        print("We don't have a reference to the collection view.")
        return
    }

    let nib = UINib(nibName: "CustomCollectionViewCell", bundle: Bundle.main)

    collectionView.register(nib, forCellWithReuseIdentifier: "com.mosheberman.samples.cell")
}

Our viewDidLoad() method looks like this now:

override func viewDidLoad() {
    super.viewDidLoad()

    self.registerCollectionViewCell()

    // Do any additional setup after loading the view.
}

Inside the nib, lay out the label and collection view as we did before. Wire up the outlets and the collection view data source, and delegate, and we should be done!

A couple of other things:

In my demo project, I needed to also present the nib-based version of the view controller. I did that in the app delegate by replacing whatever the app's main storyboard loaded in application(_:didFinishLaunchingWithOptions:)

Your storyboard nib should have the File's Owner left to the default value of NSObject. The cell should have a custom class matching whatever class you want to load.


问:
Add key and value to an existing Object in Angular Dynamically
I want to add a value to an existing Object in Angular , I am getting the object from a service call and before saving it to local storage i want to save the time stamp .

I am using Object.assign for the same

The problem is that user is a typed with an Interface and if i add any property to it says that the property is not defined in interface and the interface class is not written by me its by Firebase User info . i donot want to edit that interface or add to it . I want to create a new one property dynamically.

Like Reflection in Java and also adding dynamic Value to object in Javascript.

This is what i have tried

```<code>this.afAuth.authState.subscribe((data) => {
  console.log("Here");
  if (data) {
    const value = Object.assign(data,{TimeStamp : new Date().getTime()}); // this assign is not working even having obj in variable dosent help
    console.log("Value"+JSON.stringify(value));
    localStorage.setItem("user", JSON.stringify(value));
    this.user = data;
    this.service.fetchData(this.user.uid).subscribe((res) => {
      this.comments = res;
    });
  } else {
    this.comments = null;
  }
});
</code>```

Any Help Thanks in Advance

答:
You can extend the Firebase User interface and add the Timestamp, then use your extended interface in place of the default one.

```<code>interface MyUser extends User {
    timeStamp: any;
}
</code>```

Then you can add the timeStamp to the data object like this:

```<code> data.timestamp = {TimeStamp : new Date().getTime()}
 console.log("data",data);
</code>```

You don't need to use Object.assign, you can just add a value for a key directly on the object.

You'll want to specify the correct type for the timeStamp in your interface, if you're carrying the value as a string, make that a string, but any is a safe place to start.

Make sure to make your local user variable is typed to your extended interface.

```<code>public user: MyUser;

this.afAuth.authState.subscribe((data) => {
  console.log("Here");
  if (data) {
    data.timestamp = {TimeStamp : new Date().getTime()}
    console.log("data: "+JSON.stringify(data));
    localStorage.setItem("user", JSON.stringify(data));
    this.user = data;
    this.service.fetchData(this.user.uid).subscribe((res) => {
      this.comments = res;
    });
  } else {
    this.comments = null;
  }
});
</code>```

Body:
I want to add a value to an existing Object in Angular , I am getting the object from a service call and before saving it to local storage i want to save the time stamp .

I am using Object.assign for the same

The problem is that user is a typed with an Interface and if i add any property to it says that the property is not defined in interface and the interface class is not written by me its by Firebase User info . i donot want to edit that interface or add to it . I want to create a new one property dynamically.

Like Reflection in Java and also adding dynamic Value to object in Javascript.

This is what i have tried

this.afAuth.authState.subscribe((data) => {
  console.log("Here");
  if (data) {
    const value = Object.assign(data,{TimeStamp : new Date().getTime()}); // this assign is not working even having obj in variable dosent help
    console.log("Value"+JSON.stringify(value));
    localStorage.setItem("user", JSON.stringify(value));
    this.user = data;
    this.service.fetchData(this.user.uid).subscribe((res) => {
      this.comments = res;
    });
  } else {
    this.comments = null;
  }
});

Any Help Thanks in Advance

Body:
You can extend the Firebase User interface and add the Timestamp, then use your extended interface in place of the default one.

interface MyUser extends User {
    timeStamp: any;
}

Then you can add the timeStamp to the data object like this:

 data.timestamp = {TimeStamp : new Date().getTime()}
 console.log("data",data);

You don't need to use Object.assign, you can just add a value for a key directly on the object.

You'll want to specify the correct type for the timeStamp in your interface, if you're carrying the value as a string, make that a string, but any is a safe place to start.

Make sure to make your local user variable is typed to your extended interface.

public user: MyUser;

this.afAuth.authState.subscribe((data) => {
  console.log("Here");
  if (data) {
    data.timestamp = {TimeStamp : new Date().getTime()}
    console.log("data: "+JSON.stringify(data));
    localStorage.setItem("user", JSON.stringify(data));
    this.user = data;
    this.service.fetchData(this.user.uid).subscribe((res) => {
      this.comments = res;
    });
  } else {
    this.comments = null;
  }
});


答: Macro names must be identifiers, and thus cannot contain the character ".

Title: How to "redefine" one char * to another char *?

Body:
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}

// output: b

How to do it?