问:
Rails: Password can't be blank with has_secure_password
I am trying to follow this tutorial (Rails Tutorial by Michael Hartl) to create a valid user. Filling in the password fields still gives me the error "Password cannot be blank" and "Password has to be longer thank 6 letters". I tried creating a user through the rails console, and that worked fine. It is only when I try doing it through the website itself.

My user model looks like this:

```<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}

  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }
end
</code>```

My user_controller looks like this:

```<code>class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
#wrap_parameters :user, include: [:name, :email, :password, :password_confirmation]

def index
  @users = User.all
end

def show
  @user = User.find(params[:id])
  #debugger
end
def new
  @user = User.new
end

# GET /users/1/edit
def edit
end

#POST /users
#POST /users.json
def create
  @user = User.new(user_params) #params[:user])#user_params)

  respond_to do |format|
    if @user.save
      #flash[:success] = "Welcome to CourseBuddies!"

      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
      redirect_to @user
    else
      #render 'new'
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
  respond_to do |format|
    if @user.update(user_params)
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { render :show, status: :ok, location: @user }
    else
      format.html { render :edit }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# DELETE /users/1
# DELETE /users/1.json
def destroy
  @user.destroy
  respond_to do |format|
    format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
    format.json { head :no_content }
  end
end

private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:user).permit(:name, :email, :pasword, :password_confirmation)
  end
end
</code>```

This is my Migration file create_user:

```<code>class CreateUsers < ActiveRecord::Migration[5.0]
 def change
   create_table :users do |t|
     t.string :name
     t.string :email
     t.string :password
     t.string :password_confirmation

     t.timestamps
   end
 end
</code>```

end

I've tried different solutions found online like using "wrap_parameters" and such it doesn't seem to do anything for me.

My Gemfile looks like this:

```<code># Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'
gem 'bootstrap-sass', '3.3.7'
# make pw digest "has_secure_password" use a stateofart hash function (bcrypt)
gem 'bcrypt', '3.1.11'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18.4'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more:     https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  gem 'sqlite3', '1.3.13' #railsTuto said to get this, but already use postgresql
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'rails-controller-testing', '1.0.2'
  gem 'minitest-reporters',       '1.1.14'
  gem 'guard',                    '2.13.0'
  gem 'guard-minitest',           '2.4.4'
end

group :production do
  gem 'pg', '~>0.18.4'
  gem 'rails_12factor'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

EDIT: My FORM

```<code><%- #FIELDS FOR THE FORM %>
<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user, url: signup_path) do |f| %>

    <%- #ERROR MESSAGES %>
    <%= render 'shared/error_messages' %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <br>
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>

    <br>
    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

    <br>
    <%= f.label :password_confirmation, "Confirmation" %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>

    <br><br>
    <%= f.submit "Create my account", class: "btn btn-primary" %>
  <% end %>
</div>
</code>```

I would appreciate any kind of help or clarification. Thanks!

答:
The actual reason for the error is you mistyped password as pasword in your user_params. Fixing the typo should solve your problem.

```<code>def user_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
</code>```

Body:
I am trying to follow this tutorial (Rails Tutorial by Michael Hartl) to create a valid user. Filling in the password fields still gives me the error "Password cannot be blank" and "Password has to be longer thank 6 letters". I tried creating a user through the rails console, and that worked fine. It is only when I try doing it through the website itself.

My user model looks like this:

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}

  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }
end

My user_controller looks like this:

class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
#wrap_parameters :user, include: [:name, :email, :password, :password_confirmation]

def index
  @users = User.all
end

def show
  @user = User.find(params[:id])
  #debugger
end
def new
  @user = User.new
end

# GET /users/1/edit
def edit
end

#POST /users
#POST /users.json
def create
  @user = User.new(user_params) #params[:user])#user_params)

  respond_to do |format|
    if @user.save
      #flash[:success] = "Welcome to CourseBuddies!"

      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
      redirect_to @user
    else
      #render 'new'
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
  respond_to do |format|
    if @user.update(user_params)
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { render :show, status: :ok, location: @user }
    else
      format.html { render :edit }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# DELETE /users/1
# DELETE /users/1.json
def destroy
  @user.destroy
  respond_to do |format|
    format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
    format.json { head :no_content }
  end
end

private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:user).permit(:name, :email, :pasword, :password_confirmation)
  end
end

This is my Migration file create_user:

class CreateUsers < ActiveRecord::Migration[5.0]
 def change
   create_table :users do |t|
     t.string :name
     t.string :email
     t.string :password
     t.string :password_confirmation

     t.timestamps
   end
 end

end

I've tried different solutions found online like using "wrap_parameters" and such it doesn't seem to do anything for me.

My Gemfile looks like this:

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'
gem 'bootstrap-sass', '3.3.7'
# make pw digest "has_secure_password" use a stateofart hash function (bcrypt)
gem 'bcrypt', '3.1.11'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18.4'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more:     https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  gem 'sqlite3', '1.3.13' #railsTuto said to get this, but already use postgresql
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'rails-controller-testing', '1.0.2'
  gem 'minitest-reporters',       '1.1.14'
  gem 'guard',                    '2.13.0'
  gem 'guard-minitest',           '2.4.4'
end

group :production do
  gem 'pg', '~>0.18.4'
  gem 'rails_12factor'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

EDIT: My FORM

<%- #FIELDS FOR THE FORM %>

    <%= form_for(@user, url: signup_path) do |f| %>

    <%- #ERROR MESSAGES %>
    <%= render 'shared/error_messages' %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>

    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

    <%= f.label :password_confirmation, "Confirmation" %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>

    <%= f.submit "Create my account", class: "btn btn-primary" %>
  <% end %>

I would appreciate any kind of help or clarification. Thanks!

Body:
The actual reason for the error is you mistyped password as pasword in your user_params. Fixing the typo should solve your problem.

def user_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation)
end


来源: stackexchange

问:
How to create a IntentService to check if GoogleApiClient is not null android
In my project I'm using the "GoogleApiClient" to make locations requests each 5 seconds, the problem is, if I turn the GPS off and then reopen the App, it crushes because the mGoogleApiClient object is current null! I'm just doing a simple check on onRestart

```<code>protected void onRestart() {
    super.onRestart();
    if(mGoogleApiClient != null && mGoogleApiClient.isConnected()){
        startLocationUpdate();
    }
}
</code>```

What I want is create something that I could call every time the object mGoogleApiClient is null so it could try in background until be fine to go on! Inside of  startLocationUpdate(); I'm using this :

```<code>mlocationRequest = new LocationRequest();
    mlocationRequest.setInterval(5000);
    mlocationRequest.setFastestInterval(2000);
    mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    try{
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
    }catch (SecurityException ex){
        Toast.makeText(this, ex.toString(), Toast.LENGTH_SHORT).show();
    }
</code>```

It could be something like :

```<code>if(mGoogleApiClient != null){
   LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
  }else {
   callServiceToTryConnection();
}
</code>```

I already use IntentService with Geocoder to get the address!

答:
Check in onRestart that is GPS is enable or not by this condition</p>

```<code>if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
   //Here is your condition if GPS is not connected
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my project I'm using the "GoogleApiClient" to make locations requests each 5 seconds, the problem is, if I turn the GPS off and then reopen the App, it crushes because the mGoogleApiClient object is current null! I'm just doing a simple check on onRestart

protected void onRestart() {
    super.onRestart();
    if(mGoogleApiClient != null && mGoogleApiClient.isConnected()){
        startLocationUpdate();
    }
}

What I want is create something that I could call every time the object mGoogleApiClient is null so it could try in background until be fine to go on! Inside of  startLocationUpdate(); I'm using this :

mlocationRequest = new LocationRequest();
    mlocationRequest.setInterval(5000);
    mlocationRequest.setFastestInterval(2000);
    mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    try{
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
    }catch (SecurityException ex){
        Toast.makeText(this, ex.toString(), Toast.LENGTH_SHORT).show();
    }

It could be something like :

if(mGoogleApiClient != null){
   LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
  }else {
   callServiceToTryConnection();
}

I already use IntentService with Geocoder to get the address!

Body:
Check in onRestart that is GPS is enable or not by this condition

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
   //Here is your condition if GPS is not connected
}


问:
"WARNING:tornado.access:405" error stopping POST from both "localhost" and "file://" origins
This is a very similar problem to this question (Tornado POST 405: Method Not Allowed), but the dead simple answer for that question is still not working.  There are also many, many more similar questions in the side bar -----> which are not related to Tornado, and did not provide me with a solution.

Right now I am using Firefox on OSX.

My tornado code is as follows:

```<code>import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        self.write("Hello, world")
    get = post # <--------------

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
</code>```

If I run GET, it works fine, but if I use POST, I get the error on client side HTTP/1.1 405 Method Not Allowed and the error on server side WARNING:tornado.access:405 OPTIONS.  I have tried running the js in both a file://index.html and localhost:8000/index.html setting

My test js looks like this:

```<code>//this one returns the error
U.Ajax.post("http://localhost:8888/", "text", "data = fez hat")
.then(function(result) {
    console.log(result);
});

//this one works
U.Ajax.get("http://localhost:8888/", "text", "data = fez hat")
.then(function(result) {
    console.log(result);
});
</code>```

My ajax code looks like this, if that's any help:

```<code>//tested and functional ajax code, for ease of testing
U = {};
U.Ajax = {};
U.Ajax.send = function(getOrPost, url, dataType, data) {
    return new Promise( function(resolve, reject) {
        var request = new XMLHttpRequest();

        if(getOrPost == "GET") {
            request.responseType = dataType || "text";
            request.open("GET", url);
        }
        else {//getOrPost == "POST"
            request.open("POST", url);
            request.setRequestHeader('Content-type', dataType)
        }

        request.onload = function() {
            if (request.status >= 200 && request.status < 400) {
                console.log("ajax", request.status+" "+url, request);

                resolve(request);

            } else {
                request.onerror();
            }
        };

        request.onerror = function() {
            var err = "include src '"+url+"' does not exist";
            console.log(err)
            reject(err)
        };

        try {
            request.send(data);
        }
        catch(e) {
            var err = "NS_ERROR_DOM_BAD_URI: Access to restricted URI '"+url+"' denied";
            console.log(err)
            reject(err)
        }

    });
}

U.Ajax.get = function(url, responseType) {
    return U.Ajax.send("GET", url, responseType);
}

U.Ajax.post = function(url, contentType, data) {
    return U.Ajax.send("POST", url, contentType, data);
}
</code>```

EDIT ::  If I change the tornado code to equate GET POST and OPTION, it works, but incorrectly

```<code>class MainHandler(tornado.web.RequestHandler):
    def post(self):
        print(self.request)
    get = options = post # <--------------
</code>```

I no longer get an error, but when I print self.request it appears that my headers are set to "OPTIONS" somehow

HTTPServerRequest(protocol='http', host='localhost:8888', method='OPTIONS', uri='/', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Origin': 'null', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Access-Control-Request-Headers': 'content-type', 'Host': 'localhost:8888', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:55.0) Gecko/20100101 Firefox/55.0', 'Access-Control-Request-Method': 'POST', 'Connection': 'keep-alive'})

答:
I no longer get an error, but when I print self.request it appears that my headers are set to "OPTIONS" somehow

That would be the CORS pre-flight request.

https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request:

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood.

It is an OPTIONS request using two HTTP request headers: Access-Control-Request-Method and Access-Control-Request-Headers, and the Origin header.

A preflight request is automatically issued by a browser when needed; in normal cases, front-end developers don't need to craft such requests themselves.

For cross-domain AJAX requests, the browser first needs to check with the remote server, whether it wants to accept a request using a specific method and/or specific request headers.

That happens via an OPTIONS request. And when the server signals in the response that the actual request the client wants to make is acceptable, the client then makes that request.

Body:
This is a very similar problem to this question (Tornado POST 405: Method Not Allowed), but the dead simple answer for that question is still not working.  There are also many, many more similar questions in the side bar -----> which are not related to Tornado, and did not provide me with a solution.

Right now I am using Firefox on OSX.

My tornado code is as follows:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        self.write("Hello, world")
    get = post # <--------------

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

If I run GET, it works fine, but if I use POST, I get the error on client side HTTP/1.1 405 Method Not Allowed and the error on server side WARNING:tornado.access:405 OPTIONS.  I have tried running the js in both a file://index.html and localhost:8000/index.html setting

My test js looks like this:

//this one returns the error
U.Ajax.post("http://localhost:8888/", "text", "data = fez hat")
.then(function(result) {
    console.log(result);
});

//this one works
U.Ajax.get("http://localhost:8888/", "text", "data = fez hat")
.then(function(result) {
    console.log(result);
});

My ajax code looks like this, if that's any help:

//tested and functional ajax code, for ease of testing
U = {};
U.Ajax = {};
U.Ajax.send = function(getOrPost, url, dataType, data) {
    return new Promise( function(resolve, reject) {
        var request = new XMLHttpRequest();

        if(getOrPost == "GET") {
            request.responseType = dataType || "text";
            request.open("GET", url);
        }
        else {//getOrPost == "POST"
            request.open("POST", url);
            request.setRequestHeader('Content-type', dataType)
        }

        request.onload = function() {
            if (request.status >= 200 && request.status < 400) {
                console.log("ajax", request.status+" "+url, request);

                resolve(request);

            } else {
                request.onerror();
            }
        };

        request.onerror = function() {
            var err = "include src '"+url+"' does not exist";
            console.log(err)
            reject(err)
        };

        try {
            request.send(data);
        }
        catch(e) {
            var err = "NS_ERROR_DOM_BAD_URI: Access to restricted URI '"+url+"' denied";
            console.log(err)
            reject(err)
        }

    });
}

U.Ajax.get = function(url, responseType) {
    return U.Ajax.send("GET", url, responseType);
}

U.Ajax.post = function(url, contentType, data) {
    return U.Ajax.send("POST", url, contentType, data);
}

EDIT ::  If I change the tornado code to equate GET POST and OPTION, it works, but incorrectly

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        print(self.request)
    get = options = post # <--------------

I no longer get an error, but when I print self.request it appears that my headers are set to "OPTIONS" somehow

HTTPServerRequest(protocol='http', host='localhost:8888', method='OPTIONS', uri='/', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Origin': 'null', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Access-Control-Request-Headers': 'content-type', 'Host': 'localhost:8888', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:55.0) Gecko/20100101 Firefox/55.0', 'Access-Control-Request-Method': 'POST', 'Connection': 'keep-alive'})


问:
Webview not clearing previous page Android
I have a webView which changes its load url on a button click.
Everything is working fine except the loaded url seems to be not cleared properly.

The previous url is loaded in webview and is displayed just before the new url appears. I tried using

webView.clearView(),

webView.clearHistory(),

webView.loadUrl("about:blank"),

webView.clearCache(true)

and also tried clearing the cookies. But nothing helps clearing the webview properly.

I also tried webView.destroy(); but the webView is destroyed fully as I am nt able to load the next url.

Please help.

答:
Do you have this function in your MainActivity.java ? </p>

```<code>private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mailto:") || url.startsWith("mms:") || url.startsWith("mmsto:") || url.startsWith("market:")) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
        else {
            view.loadUrl(url);
            return true;
        }
    }
}
</code>```

Body:
Do you have this function in your MainActivity.java ?

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mailto:") || url.startsWith("mms:") || url.startsWith("mmsto:") || url.startsWith("market:")) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
        else {
            view.loadUrl(url);
            return true;
        }
    }
}


问:
Kubernetes on Oracle Linux
Can somebody give me a starting point to install Kubernetes on Oracle Linux platform. I like to start some comparison between the orchestration of docker containers.

Regards
Walter

答:
You can use this guide from Bitnami to prepare a Kubernetes cluster in Oracle Cloud: https://docs.bitnami.com/kubernetes/how-to/set-kubernetes-cluster-oracle/

The guide is meant for the Ubuntu image, but just as @sfgroups said, using kubeadm the process should be similar.

Title: Kubernetes on Oracle Linux


问:
SlidingPanel Animation
I would like to display a sliding panel in my project, from a bottom fixed div (so sliding in the top direction).

This sliding panel will be used to extend a view of an existing element.

I have some problems to make it works great (where to start sliding, respect the padding of his parents, etc, etc)

I made a Plunker of a sample project representing my problem :

In this Plunker i would like to :

open my sliding panel from the top of my div (in red). As you will notice, when you click on the button to open it, the sliding panel start his animation from the bottom of the page and go over my div (in red).

align my sliding panel with my div (in red).

So here are my questions:

How can i start my sliding animation from the top of my div (in red).

I already tried that :

```<code>.sliding-panel-wrapper {
    /* Other Css property */
    margin-bottom: /*Height of the red div*/;
    bottom: 0;
}

$("#mybtn").click(function() {
    // Increase height instead of moving it from outside of the page to inside
    $("#slidingPanel")[0].style.height= '500px'
});
</code>```

This solution works for the starting position of my panel, but i don't want the sliding panel to increase his size, but to slide .

How can i give him the exact same size / padding / margin etc etc than the div in red ( because recursively looking for padding and margin of his parent seems not to be the best solution).

Edit : I'm looking for a "generic" solution if possible, i would like to be able that my sliding panel adapt itself to the constraint that i defined above if they change (so i would like to avoid giving hard coded value in my css).

Edit 2: Summarizing my question is : How can i make a panel slide NOT from the bottom of the page, but from the Top of another div (Please see my plunker)

答:
If i'm understanding your question, you would like a sliding panel which is off page and then when a button is clicked it slides on page.

If this is the case then this will answer your question.

This is the html code which sets a div id as slide. The button has an onclick function called Slide().

```<code><div id="slide"></div>
<button onclick="Slide()">Slide</button>
</code>```

Make sure the div has a position of fixed and then set the bottom attribute to whatever you require.

```<code>#slide{
position:fixed;
bottom:-52%;
background-color:red;
width:100px;
height:500px;
right:0;
transition:1s;
}
</code>```

This javascript is called when you click the Slide button. If the div is off screen then it will "slide" onto screen and if the div is on screen then it will "slide" slide off screen. But make sure you set your values to suit your needs because these values may not work for your solution.

```<code>var a = false;
    function Slide() {
        if (a) {
            $('#slide').css('bottom', '-52%');
            a = false;
        }
        else {
            $('#slide').css('bottom', '0%');
            a = true;
        }

    }
</code>```

Any questions, just ask.

Title: SlidingPanel Animation

Body:
I would like to display a sliding panel in my project, from a bottom fixed div (so sliding in the top direction).

This sliding panel will be used to extend a view of an existing element.

I have some problems to make it works great (where to start sliding, respect the padding of his parents, etc, etc)

I made a Plunker of a sample project representing my problem :

In this Plunker i would like to :

open my sliding panel from the top of my div (in red). As you will notice, when you click on the button to open it, the sliding panel start his animation from the bottom of the page and go over my div (in red).

align my sliding panel with my div (in red).

So here are my questions:

How can i start my sliding animation from the top of my div (in red).

I already tried that :

.sliding-panel-wrapper {
    /* Other Css property */
    margin-bottom: /*Height of the red div*/;
    bottom: 0;
}

$("#mybtn").click(function() {
    // Increase height instead of moving it from outside of the page to inside
    $("#slidingPanel")[0].style.height= '500px'
});

This solution works for the starting position of my panel, but i don't want the sliding panel to increase his size, but to slide .

How can i give him the exact same size / padding / margin etc etc than the div in red ( because recursively looking for padding and margin of his parent seems not to be the best solution).

Edit : I'm looking for a "generic" solution if possible, i would like to be able that my sliding panel adapt itself to the constraint that i defined above if they change (so i would like to avoid giving hard coded value in my css).

Edit 2: Summarizing my question is : How can i make a panel slide NOT from the bottom of the page, but from the Top of another div (Please see my plunker)

Body:
If i'm understanding your question, you would like a sliding panel which is off page and then when a button is clicked it slides on page.

If this is the case then this will answer your question.

This is the html code which sets a div id as slide. The button has an onclick function called Slide().

<div id="slide"></div>
<button onclick="Slide()">Slide</button>

Make sure the div has a position of fixed and then set the bottom attribute to whatever you require.

#slide{
position:fixed;
bottom:-52%;
background-color:red;
width:100px;
height:500px;
right:0;
transition:1s;
}

This javascript is called when you click the Slide button. If the div is off screen then it will "slide" onto screen and if the div is on screen then it will "slide" slide off screen. But make sure you set your values to suit your needs because these values may not work for your solution.

var a = false;
    function Slide() {
        if (a) {
            $('#slide').css('bottom', '-52%');
            a = false;
        }
        else {
            $('#slide').css('bottom', '0%');
            a = true;
        }

    }

Any questions, just ask.


问:
send data from action method to appear in modal dialog
Im using asp.net mvc with jqueryui

I have placed the default logon htlm (that comes with a new created mvc project) and placed it in a jquery modal dialog. login seems to work okay. However Im not sure how I'm meant to handle errors. I'd like it to just show up in the modal dialog...,

The modal dialog is fine when it errors if for example a required field is missing, (it shows up in the dialog)

but the LogOn action method returns View(model); if there are any errors with the authenticating the credential entered( user/password are invalid)

how can i make it so that these erros get rendered within the dialog too?

答:
Add the errors to your Model and then read those values out in the view.  </p>

```<code>  public class LoginModel
  {
      public string ErrorMessage { get; set; }
  }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Add the errors to your Model and then read those values out in the view.

  public class LoginModel
  {
      public string ErrorMessage { get; set; }
  }


问:
Get List<Guid> from object C#
I have function GetChildren, which returns all the child nodes, in a structure as they need to be in treeview.

```<code> public static object GetChildrenNodes(IEnumerable<NodeDto> aNodes, Guid aNodeGuid)
    {
        var childrens = from childrenNode in aNodes
                        where (childrenNode.NodeParentGuid == aNodeGuid)
                        select new
                        {
                            id = childrenNode.NodeGuid,
                            text = childrenNode.Label,
                            nodes = (aNodes.Count(x => x.NodeParentGuid == childrenNode.NodeGuid) > 0) ? GetChildrenNodes(aNodes, childrenNode.NodeGuid) : null
                        };

        return childrens;
    }
</code>```

This function must remain as is, because TreeView requires that kind of object to build itself.

I would like to use the same function to get the guids of nodes to delete, so i have:

```<code> object nodesList = GetChildrenNodes(nodeList, aNodeGuid);
</code>```

The thing is i want to get List<Guid> guids from  "id"s of object nodesList, so i please for your help.

答:
The proper way to do this is to define a TreeNode class and use that instead of the anonymous class... if you really want you can then do a .Select after calling this method.

That said if you insist - You could try casting to dynamic? Then casting the Id property... although this makes me cringe and you should really just define a TreeNode class and use that instead of an anonymous class...

```<code>List<Guid> guids = new List<Guid>();
for (var node in nodeList){
    guids.Add((Guid)(node as dynamic).Id);
}
</code>```

Title: Get List<Guid> from object C#

Body:
I have function GetChildren, which returns all the child nodes, in a structure as they need to be in treeview.

 public static object GetChildrenNodes(IEnumerable<NodeDto> aNodes, Guid aNodeGuid)
    {
        var childrens = from childrenNode in aNodes
                        where (childrenNode.NodeParentGuid == aNodeGuid)
                        select new
                        {
                            id = childrenNode.NodeGuid,
                            text = childrenNode.Label,
                            nodes = (aNodes.Count(x => x.NodeParentGuid == childrenNode.NodeGuid) > 0) ? GetChildrenNodes(aNodes, childrenNode.NodeGuid) : null
                        };

        return childrens;
    }

This function must remain as is, because TreeView requires that kind of object to build itself.

I would like to use the same function to get the guids of nodes to delete, so i have:

 object nodesList = GetChildrenNodes(nodeList, aNodeGuid);

The thing is i want to get List<Guid> guids from  "id"s of object nodesList, so i please for your help.

Body:
The proper way to do this is to define a TreeNode class and use that instead of the anonymous class... if you really want you can then do a .Select after calling this method.

That said if you insist - You could try casting to dynamic? Then casting the Id property... although this makes me cringe and you should really just define a TreeNode class and use that instead of an anonymous class...

List<Guid> guids = new List<Guid>();
for (var node in nodeList){
    guids.Add((Guid)(node as dynamic).Id);
}


问:
How to make only some columns editable in a Vaadin Grid?
Vaadin Grid allows to be defined as editable with

```<code>grid.setEditorEnabled(true);
</code>```

This makes all visible columns editable. However I don't want the user to edit an specific column, but seems like the editable is an all or nothing.

The next best solution I have found is to define an editor field with a disabled editor, which almost does the trick but the user is still able to select the text and move the cursor (but the field is not editable anymore).

```<code>Grid.Column nameColumn = grid.getColumn("fullName");
nameColumn.setHeaderCaption("Full Name");
nameColumn.setEditorField(getNoEditableTextField());

...

private Field<?> getNoEditableTextField() {
    TextField noEditableTextFiled = new TextField();
    noEditableTextFiled.setEnabled(false);
    return noEditableTextFiled;
}
</code>```

I believe Label cannot be used because it's not a Field.

Is there a better option to achieve this?

edit: as aakath said, there is a way of achieving this not enabling the column to be edited, but in doing so the cell value disappears when you edit the row, which is not desirable.

答:
I had the same problem and didn't want that clicking on id column opens editor. I solved it with adding an ItemClickListener as below. It works fine for me.

```<code>grid.addItemClickListener((ItemClickListener<GridBean>) event -> grid.getEditor().setEnabled(!event.getColumn().getCaption().equals("Id")));
</code>```

Also byc clicking on specific columns Grid is not editable any more.

Body:
Vaadin Grid allows to be defined as editable with

grid.setEditorEnabled(true);

This makes all visible columns editable. However I don't want the user to edit an specific column, but seems like the editable is an all or nothing.

The next best solution I have found is to define an editor field with a disabled editor, which almost does the trick but the user is still able to select the text and move the cursor (but the field is not editable anymore).

Grid.Column nameColumn = grid.getColumn("fullName");
nameColumn.setHeaderCaption("Full Name");
nameColumn.setEditorField(getNoEditableTextField());

...

private Field<?> getNoEditableTextField() {
    TextField noEditableTextFiled = new TextField();
    noEditableTextFiled.setEnabled(false);
    return noEditableTextFiled;
}

I believe Label cannot be used because it's not a Field.

Is there a better option to achieve this?

edit: as aakath said, there is a way of achieving this not enabling the column to be edited, but in doing so the cell value disappears when you edit the row, which is not desirable.

Body:
I had the same problem and didn't want that clicking on id column opens editor. I solved it with adding an ItemClickListener as below. It works fine for me.

grid.addItemClickListener((ItemClickListener<GridBean>) event -> grid.getEditor().setEnabled(!event.getColumn().getCaption().equals("Id")));

Also byc clicking on specific columns Grid is not editable any more.


问:
How to remove Empty Rows from a list in Python 3.5
```<code>apple
mango
banana

tea

coffee
</code>```

Can someone please suggest a python code to remove the empty rows in this case after banana/tea/coffee so the actual result should be as below without any empty rows in between and after the end of lists

```<code>apple
mango
banana
tea
coffee
</code>```

答:
You may also use list comprehension:</p>

```<code>>>> test_list = ['apple','mango','banana','','tea','','coffee']
>>> test_list = [item for item in test_list if item]
>>> test_list
>>> ['apple', 'mango', 'banana', 'tea', 'coffee']
</code>```

Body:
apple
mango
banana

tea

coffee

Can someone please suggest a python code to remove the empty rows in this case after banana/tea/coffee so the actual result should be as below without any empty rows in between and after the end of lists

apple
mango
banana
tea
coffee

Body:
You may also use list comprehension:

>>> test_list = ['apple','mango','banana','','tea','','coffee']
>>> test_list = [item for item in test_list if item]
>>> test_list
>>> ['apple', 'mango', 'banana', 'tea', 'coffee']


问:
IIS bottleneck?
I have 3 machines - one which is IIS, one with a database and one from which I test the efficiency of my application - which means:
Using The Grinder I run 1000 instances of my application (hosted on the IIS and operating with the database on the machine with SQL Server). And using perfmon I observe that there really are 1000 requests.

BUT the problem is that connecting to this application (IIS) from another computer is very slow. I suppose there is some bottleneck on the IIS side but I cannot find it - CPU usage is less than 10%.

I think I changed every option in the IIS Manager and machine.config and web.config files - nothing seems to have any effect.

答:
First thing is you need to confirm if you have a slowness issue while browsing the site

Check the IIS logs and look for the time-taken field. If the time taken is more than 10 seconds then it is considered as a Slowness.

The slowness might be because of several reasons. It might be because of the Network or might be because something in your code might be causing it.

I suggest you to capture a Network trace using Netmon or WireShark in case if its a Network related.

If its not Network you can collect a Process dump using Debug diag 2 update 2 tool.

You can check the below link to collect the dumps and check them and try to find out if there is any slowness:

https://msdn.microsoft.com/en-us/library/ff420662.aspx

Title: IIS bottleneck?


问:
:app:transformClassWithDexFor Debug failed error in react native
Issues during running react native app.

It shows following error:

:app:transformClassWithDexFor Debug failed error in react native

Please give solution to fix it.
Thanks

答:
Remove both build folder in /android and /android/app
and build again with react-native run-android


问:
How to Get Array Inside stdClass
I am trying to decode with json
http://digitsolutions4u.com/apps_services/statuslist.php?catid=1
like this

```<code><?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "```";
print_r($data);
echo "```";
?>
</code>```

i want to get all "statusdesc" Values after decode.
I am getting results something like this

```<code>stdClass Object
(
    [posts] => Array
        (
            [0] => stdClass Object
                (
                    [statusid] => 1329
                    [statusdesc] => love86.jpg
                )
)
)
</code>```

i just want to list out all statusdesc available on the page like
love86.jpg
love87.jpg
love88.jpg
and so on. Anyone can provide me solution(code)  for this? I have tried several threads, but no success.

答:
All you need to do is tell json_decode() that you want it to convert the JSON String to all arrays and not as the JSONString intended an object

```<code><?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);

$data = json_decode($json, true);
// the change ..  ..  ..   ^^^^

echo "```";
print_r($data);
echo "```";
foreach ($json['posts'] as $post) {
    echo $post['statusdesc'] . '<br>';
}
?>
</code>```

However is is simpler tp deal with it as it is and do

```<code><?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);

$data = json_decode($json);

//echo "```";
//print_r($data);
//echo "```";

foreach ($json->posts as $post) {
    echo $post->statusdesc . '<br>';
}
?>
</code>```

Title: How to Get Array Inside stdClass

Body:
I am trying to decode with json
http://digitsolutions4u.com/apps_services/statuslist.php?catid=1
like this

<?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "
";
print_r($data);
echo "
";
?>

i want to get all "statusdesc" Values after decode.
I am getting results something like this

stdClass Object
(
    [posts] => Array
        (
            [0] => stdClass Object
                (
                    [statusid] => 1329
                    [statusdesc] => love86.jpg
                )
)
)

i just want to list out all statusdesc available on the page like
love86.jpg
love87.jpg
love88.jpg
and so on. Anyone can provide me solution(code)  for this? I have tried several threads, but no success.

Body:
All you need to do is tell json_decode() that you want it to convert the JSON String to all arrays and not as the JSONString intended an object

<?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);

$data = json_decode($json, true);
// the change ..  ..  ..   ^^^^

echo "<pre>";
print_r($data);
echo "</pre>";
foreach ($json['posts'] as $post) {
    echo $post['statusdesc'] . '<br>';
}
?>

However is is simpler tp deal with it as it is and do

<?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);

$data = json_decode($json);

//echo "<pre>";
//print_r($data);
//echo "</pre>";

foreach ($json->posts as $post) {
    echo $post->statusdesc . '<br>';
}
?>


问:
need else arguments appear only once no matter how much string that are inputted in the loop
```<code>#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    string input = " ";
    cout << "Do you wanted to input : " << endl << "a. String" << endl
         << "b. Integer" << endl;
    while (input != "A" || input != "a" || input != "B" || input != "b")
    {
        cin >> setw(1) >> input;
        if (input == "A" || input == "a")
        {
            cout << "String" << endl; break;
        }
        else if (input == "B" || input == "b")
        {
            cout << "int" << endl;
            break;
        }
        else
        {
            cout << "Please input only the given option." << endl;
        }
    }
}
</code>```

<p>So, I'm currently using the code like the one i posted up there, my problem is that when i trigger the else arguments by inputting more than 1 string at a time like using the words 'how much' will result in else argument appear twice and if i input 'c d e' it will appear thrice when i only wanted it only appear once no matter how much string that are inputted. I know it probably had something to do with my loop that i missed but i just don't know what is it. Is there a resolve for this ? I'm so grateful for your kind help. Thank you very much </p>

答:
Instead of a while loop, you could use a do while loop. Actually, you used a break after each successful branch. Thus, you could even use a for (;;) loop (an endless loop where condition is always true).

Demonstration:

```<code>$ cat >test-input.cc <<EOF
> #include <iostream>
> #include <string>
>
> using namespace std;
>
> int main()
> {
>   cout
>     << "Please, choose an option:" << endl
>     << "a. String" << endl
>     << "b. int" << endl;
>   for (;;) {
>     string input; getline(cin, input);
>     if (input == "a" || input == "A") {
>       cout << "String" << endl;
>       break;
>     }
>     if (input == "b" || input == "B") {
>       cout << "int" << endl;
>       break;
>     }
>     cout << "Please, choose one of the options." << endl;
>   }
>   cout << "Well done." << endl;
>   return 0;
> }
> EOF

$ g++ -std=c++11 -o test-input test-input.cc

$ ./test-input.exe
Please, choose an option:
a. String
b. int
abc
Please, choose one of the options.

Please, choose one of the options.
a
String
Well done.

$ ./test-input.exe
Please, choose an option:
a. String
b. int
b
int
Well done.

$
</code>```

Notes:

I replaced cin << by getline() as suggested by Some programmer dude (which I would prefer also).

There is no else as each "successful" if ends with a break (and thus following statements are not reached in this case). This you can imagine like an "implicit else".

Body:
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    string input = " ";
    cout << "Do you wanted to input : " << endl << "a. String" << endl
         << "b. Integer" << endl;
    while (input != "A" || input != "a" || input != "B" || input != "b")
    {
        cin >> setw(1) >> input;
        if (input == "A" || input == "a")
        {
            cout << "String" << endl; break;
        }
        else if (input == "B" || input == "b")
        {
            cout << "int" << endl;
            break;
        }
        else
        {
            cout << "Please input only the given option." << endl;
        }
    }
}

So, I'm currently using the code like the one i posted up there, my problem is that when i trigger the else arguments by inputting more than 1 string at a time like using the words 'how much' will result in else argument appear twice and if i input 'c d e' it will appear thrice when i only wanted it only appear once no matter how much string that are inputted. I know it probably had something to do with my loop that i missed but i just don't know what is it. Is there a resolve for this ? I'm so grateful for your kind help. Thank you very much

Body:
Instead of a while loop, you could use a do while loop. Actually, you used a break after each successful branch. Thus, you could even use a for (;;) loop (an endless loop where condition is always true).

Demonstration:

$ cat >test-input.cc <<EOF
> #include <iostream>
> #include <string>
>
> using namespace std;
>
> int main()
> {
>   cout
>     << "Please, choose an option:" << endl
>     << "a. String" << endl
>     << "b. int" << endl;
>   for (;;) {
>     string input; getline(cin, input);
>     if (input == "a" || input == "A") {
>       cout << "String" << endl;
>       break;
>     }
>     if (input == "b" || input == "B") {
>       cout << "int" << endl;
>       break;
>     }
>     cout << "Please, choose one of the options." << endl;
>   }
>   cout << "Well done." << endl;
>   return 0;
> }
> EOF

$ g++ -std=c++11 -o test-input test-input.cc

$ ./test-input.exe
Please, choose an option:
a. String
b. int
abc
Please, choose one of the options.

Please, choose one of the options.
a
String
Well done.

$ ./test-input.exe
Please, choose an option:
a. String
b. int
b
int
Well done.

$

Notes:

I replaced cin << by getline() as suggested by Some programmer dude (which I would prefer also).

There is no else as each "successful" if ends with a break (and thus following statements are not reached in this case). This you can imagine like an "implicit else".


问:
How to calculate Tangent and Binormal?
Talking about bump mapping, specular highlight and these kind of things in OpenGL Shading Language (GLSL)

I have:

An array of vertices (e.g. {0.2,0.5,0.1, 0.2,0.4,0.5, ...})

An array of normals (e.g. {0.0,0.0,1.0, 0.0,1.0,0.0, ...})

The position of a point light in world space (e.g. {0.0,1.0,-5.0})

The position of the viewer in world space (e.g. {0.0,0.0,0.0}) (assume the viewer is in the center of the world)

Now, how can I calculate the Binormal and Tangent for each vertex? I mean, what is the formula to calculate the Binormals, what I have to use based on those informations? And about the tangent?

I'll construct the TBN Matrix anyway, so if you know a formula to construct the matrix directly based on those informations will be nice!

Oh, yeh, I have the texture coordinates too, if needed.
And as I'm talking about GLSL, would be nice a per-vertex solution, I mean, one which doesn't need to access more than one vertex information at a time.

---- Update -----

I found this solution:

```
vec3 tangent;
vec3 binormal;

vec3 c1 = cross(a_normal, vec3(0.0, 0.0, 1.0));
vec3 c2 = cross(a_normal, vec3(0.0, 1.0, 0.0));

if (length(c1)>length(c2))
{
    tangent = c1;
}
else
{
    tangent = c2;
}

tangent = normalize(tangent);

binormal = cross(v_nglNormal, tangent);
binormal = normalize(binormal);
```

But I don't know if it is 100% correct.

答:
Based on the answer from kvark, I would like to add more thoughts.

If you are in need of an orthonormalized tangent space matrix you have to do some work any way.
Even if you add tangent and binormal attributes, they will be interpolated during the shader stages
and at the end they are neither normalized nor they are normal to each another.

Let's assume that we have a normalized normalvector n, and we have the tangent t and the binormalb or we can calculate them from the derivations as follows:

```<code>// derivations of the fragment position
vec3 pos_dx = dFdx( fragPos );
vec3 pos_dy = dFdy( fragPos );
// derivations of the texture coordinate
vec2 texC_dx = dFdx( texCoord );
vec2 texC_dy = dFdy( texCoord );
// tangent vector and binormal vector
vec3 t = texC_dy.y * pos_dx - texC_dx.y * pos_dy;
vec3 b = texC_dx.x * pos_dy - texC_dy.x * pos_dx;
</code>```

Of course an orthonormalized tangent space matrix can be calcualted by using the cross product,
but this would only work for right-hand systems. If a matrix was mirrored (left-hand system) it will turn to a right hand system:

```<code>t = cross( cross( n, t ), t ); // orthonormalization of the tangent vector
b = cross( n, t );             // orthonormalization of the binormal vector
                               //   may invert the binormal vector
mat3 tbn = mat3( normalize(t), normalize(b), n );
</code>```

In the code snippet above the binormal vector is reversed if the tangent space is a left-handed system.
To avoid this, the hard way must be gone:

```<code>t = cross( cross( n, t ), t ); // orthonormalization of the tangent vector
b = cross( b, cross( b, n ) ); // orthonormalization of the binormal vectors to the normal vector
b = cross( cross( t, b ), t ); // orthonormalization of the binormal vectors to the tangent vector
mat3 tbn = mat3( normalize(t), normalize(b), n );
</code>```

A common way to orthogonalize any matrix is the Gram–Schmidt process:

```<code>t = t - n * dot( t, n ); // orthonormalization ot the tangent vectors
b = b - n * dot( b, n ); // orthonormalization of the binormal vectors to the normal vector
b = b - t * dot( b, t ); // orthonormalization of the binormal vectors to the tangent vector
mat3 tbn = mat3( normalize(t), normalize(b), n );
</code>```

Another possibility is to use the determinant of the 2*2 matrix, which results from the derivations of the texture coordinates texC_dx, texC_dy, to take the direction of the binormal vector into account. The idea is that the determinant of a orthogonal matrix is 1 and the determined one of a orthogonal mirror matrix -1.

The determinant can eihter be calcualted by the GLSL function determinant( mat2( texC_dx, texC_dy )
or it can be calcualated by it formula texC_dx.x * texC_dy.y - texC_dy.x * texC_dx.y.

For the calculation of the orthonormalized tangent space matrix, the binormal vector is no longer required and the calculation of the unit vector
(normalize) of the binormal vector can be evaded.

```<code>float texDet = texC_dx.x * texC_dy.y - texC_dy.x * texC_dx.y;
vec3 t = texC_dy.y * pos_dx - texC_dx.y * pos_dy;
t      = normalize( t - n * dot( t, n ) );
vec3 b = cross( n, t );                      // b is normlized because n and t are orthonormalized unit vectors
mat3 tbn = mat3( t, sign( texDet ) * b, n ); // take in account the direction of the binormal vector
</code>```

Title: How to calculate Tangent and Binormal?

Body:
Talking about bump mapping, specular highlight and these kind of things in OpenGL Shading Language (GLSL)

I have:

An array of vertices (e.g. {0.2,0.5,0.1, 0.2,0.4,0.5, ...})

An array of normals (e.g. {0.0,0.0,1.0, 0.0,1.0,0.0, ...})

The position of a point light in world space (e.g. {0.0,1.0,-5.0})

The position of the viewer in world space (e.g. {0.0,0.0,0.0}) (assume the viewer is in the center of the world)

Now, how can I calculate the Binormal and Tangent for each vertex? I mean, what is the formula to calculate the Binormals, what I have to use based on those informations? And about the tangent?

I'll construct the TBN Matrix anyway, so if you know a formula to construct the matrix directly based on those informations will be nice!

Oh, yeh, I have the texture coordinates too, if needed.
And as I'm talking about GLSL, would be nice a per-vertex solution, I mean, one which doesn't need to access more than one vertex information at a time.

---- Update -----

I found this solution:

vec3 tangent;
vec3 binormal;

vec3 c1 = cross(a_normal, vec3(0.0, 0.0, 1.0));
vec3 c2 = cross(a_normal, vec3(0.0, 1.0, 0.0));

if (length(c1)>length(c2))
{
    tangent = c1;
}
else
{
    tangent = c2;
}

tangent = normalize(tangent);

binormal = cross(v_nglNormal, tangent);
binormal = normalize(binormal);

But I don't know if it is 100% correct.

Body:
Based on the answer from kvark, I would like to add more thoughts.

If you are in need of an orthonormalized tangent space matrix you have to do some work any way.
Even if you add tangent and binormal attributes, they will be interpolated during the shader stages
and at the end they are neither normalized nor they are normal to each another.

Let's assume that we have a normalized normalvector n, and we have the tangent t and the binormalb or we can calculate them from the derivations as follows:

// derivations of the fragment position
vec3 pos_dx = dFdx( fragPos );
vec3 pos_dy = dFdy( fragPos );
// derivations of the texture coordinate
vec2 texC_dx = dFdx( texCoord );
vec2 texC_dy = dFdy( texCoord );
// tangent vector and binormal vector
vec3 t = texC_dy.y * pos_dx - texC_dx.y * pos_dy;
vec3 b = texC_dx.x * pos_dy - texC_dy.x * pos_dx;

Of course an orthonormalized tangent space matrix can be calcualted by using the cross product,
but this would only work for right-hand systems. If a matrix was mirrored (left-hand system) it will turn to a right hand system:

t = cross( cross( n, t ), t ); // orthonormalization of the tangent vector
b = cross( n, t );             // orthonormalization of the binormal vector
                               //   may invert the binormal vector
mat3 tbn = mat3( normalize(t), normalize(b), n );

In the code snippet above the binormal vector is reversed if the tangent space is a left-handed system.
To avoid this, the hard way must be gone:

t = cross( cross( n, t ), t ); // orthonormalization of the tangent vector
b = cross( b, cross( b, n ) ); // orthonormalization of the binormal vectors to the normal vector
b = cross( cross( t, b ), t ); // orthonormalization of the binormal vectors to the tangent vector
mat3 tbn = mat3( normalize(t), normalize(b), n );

A common way to orthogonalize any matrix is the Gram–Schmidt process:

t = t - n * dot( t, n ); // orthonormalization ot the tangent vectors
b = b - n * dot( b, n ); // orthonormalization of the binormal vectors to the normal vector
b = b - t * dot( b, t ); // orthonormalization of the binormal vectors to the tangent vector
mat3 tbn = mat3( normalize(t), normalize(b), n );

Another possibility is to use the determinant of the 2*2 matrix, which results from the derivations of the texture coordinates texC_dx, texC_dy, to take the direction of the binormal vector into account. The idea is that the determinant of a orthogonal matrix is 1 and the determined one of a orthogonal mirror matrix -1.

The determinant can eihter be calcualted by the GLSL function determinant( mat2( texC_dx, texC_dy )
or it can be calcualated by it formula texC_dx.x * texC_dy.y - texC_dy.x * texC_dx.y.

For the calculation of the orthonormalized tangent space matrix, the binormal vector is no longer required and the calculation of the unit vector
(normalize) of the binormal vector can be evaded.

float texDet = texC_dx.x * texC_dy.y - texC_dy.x * texC_dx.y;
vec3 t = texC_dy.y * pos_dx - texC_dx.y * pos_dy;
t      = normalize( t - n * dot( t, n ) );
vec3 b = cross( n, t );                      // b is normlized because n and t are orthonormalized unit vectors
mat3 tbn = mat3( t, sign( texDet ) * b, n ); // take in account the direction of the binormal vector


问:
getter method throwing StackOverflowError
I am trying to use data binding in the Android. But end up getting the StackOverflow error.

loginViewModel.kt

```<code>class loginViewModel(): BaseObservable() {

    @Bindable
    var errorEmail:String?=null
        get() {
            if (userEmailAddress.isNullOrBlank())
                return "Please Enter the Email Address"
            else if (!isValidEmail(userEmailAddress))
                return "Enter Valid Email Id."
            else
                return null
        }

    var userEmailAddress:String= String()
        set(userEmailAddress){
            field=userEmailAddress
            notifyPropertyChanged(R.id.email_address)
            /*to check Email for validation on every character inserted by user*/
            notifyPropertyChanged(BR.errorEmail)

        }
        get() {
        return userEmailAddress
    }

}
</code>```

Error log:

```<code>07-04 13:54:15.435 6865-6865/com.example.itstym.reminder D/AndroidRuntime: Shutting down VM
07-04 13:54:15.513 6865-6865/com.example.itstym.reminder E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.itstym.reminder, PID: 6865
                                                                           java.lang.StackOverflowError: stack size 8MB
                                                                               at com.example.itstym.reminder.loginViewModel.getUserEmailAddress(loginViewModel.kt:49)
                                                                               at com.example.itstym.reminder.loginViewModel.getUserEmailAddress(loginViewModel.kt:49)
</code>```

I know StackOverflow error occurs when there is any recursive call but I am not able to figure out how to solve this error?

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <data class="ActivityMainBinding">
        <variable
            name="login"
            type="com.example.itstym.reminder.loginViewModel" />
    </data>

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.itstym.reminder.MainActivity">

    <EditText
        app:error="@{login.errorEmail}"
        android:text="@{login.userEmailAddress}"
        android:hint="Email Address"
        android:id="@+id/email_address"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="24dp"/>

</layout>
</code>```

答:
You're recursively calling the getter. You should write

```<code>get() = field
</code>```

instead of

```<code>get() {
    return userEmailAddress
}
</code>```

The field identifier is used in the accessors of the property to provide access to the backing field, while referring to userEmailAddress ends up calling getUserEmailAddress() method which leads to infinite loop and StackOverflowError.

Body:
I am trying to use data binding in the Android. But end up getting the StackOverflow error.

loginViewModel.kt

class loginViewModel(): BaseObservable() {

    @Bindable
    var errorEmail:String?=null
        get() {
            if (userEmailAddress.isNullOrBlank())
                return "Please Enter the Email Address"
            else if (!isValidEmail(userEmailAddress))
                return "Enter Valid Email Id."
            else
                return null
        }

    var userEmailAddress:String= String()
        set(userEmailAddress){
            field=userEmailAddress
            notifyPropertyChanged(R.id.email_address)
            /*to check Email for validation on every character inserted by user*/
            notifyPropertyChanged(BR.errorEmail)

        }
        get() {
        return userEmailAddress
    }

}

Error log:

07-04 13:54:15.435 6865-6865/com.example.itstym.reminder D/AndroidRuntime: Shutting down VM
07-04 13:54:15.513 6865-6865/com.example.itstym.reminder E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.itstym.reminder, PID: 6865
                                                                           java.lang.StackOverflowError: stack size 8MB
                                                                               at com.example.itstym.reminder.loginViewModel.getUserEmailAddress(loginViewModel.kt:49)
                                                                               at com.example.itstym.reminder.loginViewModel.getUserEmailAddress(loginViewModel.kt:49)

I know StackOverflow error occurs when there is any recursive call but I am not able to figure out how to solve this error?

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <data class="ActivityMainBinding">
        <variable
            name="login"
            type="com.example.itstym.reminder.loginViewModel" />
    </data>

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.itstym.reminder.MainActivity">

    <EditText
        app:error="@{login.errorEmail}"
        android:text="@{login.userEmailAddress}"
        android:hint="Email Address"
        android:id="@+id/email_address"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="24dp"/>

</layout>

Body:
You're recursively calling the getter. You should write

get() = field

instead of

get() {
    return userEmailAddress
}

The field identifier is used in the accessors of the property to provide access to the backing field, while referring to userEmailAddress ends up calling getUserEmailAddress() method which leads to infinite loop and StackOverflowError.


问:
explain these how the conditional operator helps in counting the negative and positive numbers in an array?
my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown.
explain these code please!</p>

```<code>int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();
</code>```

答:
The ternary operator used as an expression statement evaluates like an if statement:

```<code>num[i] < 0 ? neg++ : (pos++);
</code>```

is equivalent to

```<code>if (num[i] < 0)
    neg++;
else
    pos++;
</code>```

This kind of coding is not considered good style, and there are other issues in the code fragment posted:

the return value of scanf() should be checked to avoid undefined behavior if the input cannot be converted to an int.

the loop index should be compared to the array size with i < 5 instead of using the <= operator and a close but different constant.

output lines should be terminated with newline, not initiated with one.

getch() is a non standard function.  Its purpose is to force a pause before the program exits. Fixing shortcomings of the environment inside the program is a sad workaround. Opening a terminal window to execute programs is a better alternative: it allows the programmer to observe all program output including any extra runtime messages occurring upon program termination.

Body:
my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown.
explain these code please!

int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();

Body:
The ternary operator used as an expression statement evaluates like an if statement:

num[i] < 0 ? neg++ : (pos++);

is equivalent to

if (num[i] < 0)
    neg++;
else
    pos++;

This kind of coding is not considered good style, and there are other issues in the code fragment posted:

the return value of scanf() should be checked to avoid undefined behavior if the input cannot be converted to an int.

the loop index should be compared to the array size with i < 5 instead of using the <= operator and a close but different constant.

output lines should be terminated with newline, not initiated with one.

getch() is a non standard function.  Its purpose is to force a pause before the program exits. Fixing shortcomings of the environment inside the program is a sad workaround. Opening a terminal window to execute programs is a better alternative: it allows the programmer to observe all program output including any extra runtime messages occurring upon program termination.


问:
Java - Object runs an external process: how to stop it?
I have a Java class. Its constructor calls ProcessBuilder class to run an external problem (the complete class code provided below, I think there is nothing important in it for my question, but I give it just to illustrate and make my question less abstract).

My code works well, however, when everything is done, it doesn't stop. It seems logical to me, because the external process is still running. So I find the way how to stop it. As my class just starts it, I think there is no "link" between the class instance and the running external process, so if I destroy this object, the external process will still run. My question is: how can I kill that external process?

I'm sorry for a stupid question, it has to be answered somewhere, but I can't find it.

Thank you very much for your time!

```<code>public static class OptimizerMOEA extends ExternalProblem {

    public static final String SEPARATOR = "\\s+"; //a space
    public static final float LOWER_BOUND = 0.0;
    public static final float UPPER_BOUND = 275000000*3;
    public static final String CPP_EXE_NAME = "optimizer_moea";

    public OptimizerMOEA() throws IOException{
        super(CPP_EXE_NAME);
    }

    public OptimizerMOEA(String path) throws IOException{
        super(path);
    }

    @Override
    public String getName() {
        return "OptimizerMOEA";
    }

    @Override
    public int getNumberOfVariables() {
        //!!! TODO: pass this value from C++ function to this class
       return 6890;
    }

    @Override
    public int getNumberOfObjectives() {
       return 2;
    }

    @Override
    public int getNumberOfConstraints() {
        return 0;
    }

    @Override
    public Solution newSolution() {
        Solution solution = new Solution(getNumberOfVariables(),
        getNumberOfObjectives());

        for (int i = 0; i < getNumberOfVariables(); i++) {
            solution.setVariable(i, new RealVariable(LOWER_BOUND, UPPER_BOUND));
        }

        return solution;
    }

}//EOF OptimizerMOEA class
</code>```

EDIT:

This is the constructor from the parent class I use:

```<code>/**
 * Constructs an external problem using {@code new
 * ProcessBuilder(command).start()}.  If the command contains arguments,
 * the arguments should be passed in as separate strings, such as
 * ```
 *   new ExternalProblem("command", "arg1", "arg2");
 * ```
 *
 * @param command a specified system command
 * @throws IOException if an I/O error occured
 */
public ExternalProblem(String... command) throws IOException {
    this(new ProcessBuilder(command).start());
}
</code>```

And these are the others constructors. My Java class communicates with the external process via standard I/O. So the constructors using socket are given just for completeness.

Maybe using the constructor with a process in parameter would be a solution. In this case, I'm still interested if there is a way to solve the problem with the first constructor (just because I don't see it, find it an interesting question and am wondering in which case this constructor could be useful and why).

```<code>/**
 * Constructs an external problem that connects to a remote process via
 * sockets.  The remote process should be instantiated and already
 * listening to the designated port number prior to invoking this
 * constructor.
 *
 * @param host the host name of the remote system; or {@code null} to use
 *        the local host
 * @param port the port number
 * @throws UnknownHostException if the IP address of the specified host
 *         could not be determined
 * @throws IOException if an I/O error occurred
 */
public ExternalProblem(String host, int port) throws IOException,
UnknownHostException {
    this(new Socket(host, port));
}

/**
 * Constructs an external problem that connects to a remote process via
 * sockets.  The remote process should be instantiated and already
 * listening to the designated port number prior to invoking this
 * constructor.
 *
 * @param address the IP address of the remote system
 * @param port the port number
 * @throws IOException if an I/O error occurred
 */
public ExternalProblem(InetAddress address, int port) throws IOException {
    this(new Socket(address, port));
}

/**
 * Constructs an external problem using the specified socket.
 *
 * @param socket the socket used to send solutions to be evaluated
 * @throws IOException if an I/O error occurred
 */
ExternalProblem(Socket socket) throws IOException {
    this(socket.getInputStream(), socket.getOutputStream());
}

/**
 * Constructs an external problem using the specified process.
 *
 * @param process the process used to evaluate solutions
 */
ExternalProblem(Process process) {
    this(process.getInputStream(), process.getOutputStream());
    RedirectStream.redirect(process.getErrorStream(), System.err);
}

/**
 * Constructs an external problem using the specified input and output
 * streams.
 *
 * @param input the input stream
 * @param output the output stream
 */
ExternalProblem(InputStream input, OutputStream output) {
    super();
    reader = new BufferedReader(new InputStreamReader(input));
    writer = new BufferedWriter(new OutputStreamWriter(output));
}
</code>```

答:
This:

```<code>new ProcessBuilder(command).start();
</code>```

returns a Process object, and if you hold a reference to it, you can call Process.destroy() at a later time (this SO answer details the destroy() implementation)

Body:
I have a Java class. Its constructor calls ProcessBuilder class to run an external problem (the complete class code provided below, I think there is nothing important in it for my question, but I give it just to illustrate and make my question less abstract).

My code works well, however, when everything is done, it doesn't stop. It seems logical to me, because the external process is still running. So I find the way how to stop it. As my class just starts it, I think there is no "link" between the class instance and the running external process, so if I destroy this object, the external process will still run. My question is: how can I kill that external process?

I'm sorry for a stupid question, it has to be answered somewhere, but I can't find it.

Thank you very much for your time!

public static class OptimizerMOEA extends ExternalProblem {

    public static final String SEPARATOR = "\\s+"; //a space
    public static final float LOWER_BOUND = 0.0;
    public static final float UPPER_BOUND = 275000000*3;
    public static final String CPP_EXE_NAME = "optimizer_moea";

    public OptimizerMOEA() throws IOException{
        super(CPP_EXE_NAME);
    }

    public OptimizerMOEA(String path) throws IOException{
        super(path);
    }

    @Override
    public String getName() {
        return "OptimizerMOEA";
    }

    @Override
    public int getNumberOfVariables() {
        //!!! TODO: pass this value from C++ function to this class
       return 6890;
    }

    @Override
    public int getNumberOfObjectives() {
       return 2;
    }

    @Override
    public int getNumberOfConstraints() {
        return 0;
    }

    @Override
    public Solution newSolution() {
        Solution solution = new Solution(getNumberOfVariables(),
        getNumberOfObjectives());

        for (int i = 0; i < getNumberOfVariables(); i++) {
            solution.setVariable(i, new RealVariable(LOWER_BOUND, UPPER_BOUND));
        }

        return solution;
    }

}//EOF OptimizerMOEA class

EDIT:

This is the constructor from the parent class I use:

/**
 * Constructs an external problem using {@code new
 * ProcessBuilder(command).start()}.  If the command contains arguments,
 * the arguments should be passed in as separate strings, such as
 *

 *   new ExternalProblem("command", "arg1", "arg2");
 *

 *
 * @param command a specified system command
 * @throws IOException if an I/O error occured
 */
public ExternalProblem(String... command) throws IOException {
    this(new ProcessBuilder(command).start());
}

And these are the others constructors. My Java class communicates with the external process via standard I/O. So the constructors using socket are given just for completeness.

Maybe using the constructor with a process in parameter would be a solution. In this case, I'm still interested if there is a way to solve the problem with the first constructor (just because I don't see it, find it an interesting question and am wondering in which case this constructor could be useful and why).

/**
 * Constructs an external problem that connects to a remote process via
 * sockets.  The remote process should be instantiated and already
 * listening to the designated port number prior to invoking this
 * constructor.
 *
 * @param host the host name of the remote system; or {@code null} to use
 *        the local host
 * @param port the port number
 * @throws UnknownHostException if the IP address of the specified host
 *         could not be determined
 * @throws IOException if an I/O error occurred
 */
public ExternalProblem(String host, int port) throws IOException,
UnknownHostException {
    this(new Socket(host, port));
}

/**
 * Constructs an external problem that connects to a remote process via
 * sockets.  The remote process should be instantiated and already
 * listening to the designated port number prior to invoking this
 * constructor.
 *
 * @param address the IP address of the remote system
 * @param port the port number
 * @throws IOException if an I/O error occurred
 */
public ExternalProblem(InetAddress address, int port) throws IOException {
    this(new Socket(address, port));
}

/**
 * Constructs an external problem using the specified socket.
 *
 * @param socket the socket used to send solutions to be evaluated
 * @throws IOException if an I/O error occurred
 */
ExternalProblem(Socket socket) throws IOException {
    this(socket.getInputStream(), socket.getOutputStream());
}

/**
 * Constructs an external problem using the specified process.
 *
 * @param process the process used to evaluate solutions
 */
ExternalProblem(Process process) {
    this(process.getInputStream(), process.getOutputStream());
    RedirectStream.redirect(process.getErrorStream(), System.err);
}

/**
 * Constructs an external problem using the specified input and output
 * streams.
 *
 * @param input the input stream
 * @param output the output stream
 */
ExternalProblem(InputStream input, OutputStream output) {
    super();
    reader = new BufferedReader(new InputStreamReader(input));
    writer = new BufferedWriter(new OutputStreamWriter(output));
}

Body:
This:

new ProcessBuilder(command).start();

returns a Process object, and if you hold a reference to it, you can call Process.destroy() at a later time (this SO answer details the destroy() implementation)


问:
SharpArchitecture / Fluent NHibernate
Does DomainSignature attribute create unique constrain in DB?

Does Fluent NHibernate 1.1.0.685 supports NaturalId correctly?

答:
Domain signature doesn't create constraints in DB.

Yes Fluent NH supports Natural ID by

```<code>map.NaturalId()
      .Property(x => x.Name)
      .Property(x => x.NickName);
</code>```

syntax

Title: SharpArchitecture / Fluent NHibernate

Body:
Domain signature doesn't create constraints in DB.

Yes Fluent NH supports Natural ID by

map.NaturalId()
      .Property(x => x.Name)
      .Property(x => x.NickName);

syntax


问:
clojure "look-and say" sequence
Working on some 2015 AoC problems to learn clojure... The below was quick enough for the 40th iteration, but crawls to a halt much after that.  I compared to a few other peoples solutions and it's not immediately obvious to me why this is so slow.  I tried to use recur believing it to be about as efficient as a loop (and to avoid stack consumption).  One thing I'm not 100% clear on is if there is a sigifnicant difference between just using recur, versus using loop recur.  I tested it both ways and saw no difference.

```<code>(def data "3113322113")

(defn encode-string [data results count]
   (let [prev (first data)
         curr (second data)]
     (cond (empty? data) results
           (not= prev curr)
           (recur (rest data) (str results count prev) 1)
           :else (recur (rest data) results (inc count)))))

(count
 (nth (iterate #(encode-string % "" 1) data) 40 #_50))
</code>```

An example of a solution I benchmarked against is Bruce Hauman's, which is really nice:

```<code>(defn count-encode [x]
  (apply str
         (mapcat
          (juxt count first)
          (partition-by identity x))))
</code>```

I realize in my solution I am iterating over very large strings repeatedly, but I don't see how Bruce's is so much faster since although he is not explicitly iterating, partition is probably iterating behind the scenes.

答:
Your version is computing something like

```<code>(str "11" (str "22" (str "31" ...)))
</code>```

which is building up a brand-new String object for every two characters. Since this involves iterating over every character in the input and output strings at each step, your operation is quadratic in the length of the string.

The solution you're comparing to is different: it builds up a lazy sequence of integers, which is a linear-time process. Then, it does something like

```<code>(apply str [1 1 2 2 3 1])
</code>```

which is the same as

```<code>(str 1 1 2 2 3 1 ...)
</code>```

and str, when called with multiple arguments, uses a StringBuilder to efficiently build up the result incrementally, an optimization that is not available if you demand a full-fledged String object at every intermediate step. As a result, the whole process is linear-time, rather than quadratic.

Title: clojure "look-and say" sequence

Body:
Working on some 2015 AoC problems to learn clojure... The below was quick enough for the 40th iteration, but crawls to a halt much after that.  I compared to a few other peoples solutions and it's not immediately obvious to me why this is so slow.  I tried to use recur believing it to be about as efficient as a loop (and to avoid stack consumption).  One thing I'm not 100% clear on is if there is a sigifnicant difference between just using recur, versus using loop recur.  I tested it both ways and saw no difference.

(def data "3113322113")

(defn encode-string [data results count]
   (let [prev (first data)
         curr (second data)]
     (cond (empty? data) results
           (not= prev curr)
           (recur (rest data) (str results count prev) 1)
           :else (recur (rest data) results (inc count)))))

(count
 (nth (iterate #(encode-string % "" 1) data) 40 #_50))

An example of a solution I benchmarked against is Bruce Hauman's, which is really nice:

(defn count-encode [x]
  (apply str
         (mapcat
          (juxt count first)
          (partition-by identity x))))

I realize in my solution I am iterating over very large strings repeatedly, but I don't see how Bruce's is so much faster since although he is not explicitly iterating, partition is probably iterating behind the scenes.

Body:
Your version is computing something like

(str "11" (str "22" (str "31" ...)))

which is building up a brand-new String object for every two characters. Since this involves iterating over every character in the input and output strings at each step, your operation is quadratic in the length of the string.

The solution you're comparing to is different: it builds up a lazy sequence of integers, which is a linear-time process. Then, it does something like

(apply str [1 1 2 2 3 1])

which is the same as

(str 1 1 2 2 3 1 ...)

and str, when called with multiple arguments, uses a StringBuilder to efficiently build up the result incrementally, an optimization that is not available if you demand a full-fledged String object at every intermediate step. As a result, the whole process is linear-time, rather than quadratic.


答:
By default json_decode decodes it to an object instead of an associative array. You just access the members of that object via the arrow (->) notation. To get each post you can use foreach to loop through them.

```<code>foreach ($data->posts as $post) {
  echo $post->statusdesc;
}
</code>```

Title: How to Get Array Inside stdClass

Body:
By default json_decode decodes it to an object instead of an associative array. You just access the members of that object via the arrow (->) notation. To get each post you can use foreach to loop through them.

foreach ($data->posts as $post) {
  echo $post->statusdesc;
}


问:
Get my selected data from a list ionic 2
I have a list of items,I need to get the selected data once i click on it
Here is my list:</p>

```<code><ion-content class="outer-content" no-border-top>
    <ion-list lines (click)="openSubCat($event,category)">
      <ion-list-header>
        Shop For
      </ion-list-header>
      <ion-item>
        <ion-icon name="man" item-left></ion-icon>
         Men
        <ion-icon item-right ></ion-icon>
        </ion-item>
       <ion-item menuClose>
       <ion-icon name="woman" item-left></ion-icon>
         Women
        <ion-icon  item-right></ion-icon>
      </ion-item>
      <ion-item>
        <ion-icon name="baby" item-left></ion-icon>
          Kids
        <ion-icon  item-right></ion-icon>
      </ion-item>
     </ion-list>
</ion-content>`
</code>```

答:
You can use the hashbang in a similar way to how you would use ${''} for id in jquery.

```<code> <ion-item #menItem (click)="itemClicked(menuItem)>
  ....
 </ion-item>
</code>```

Then in your console.log will give you the properties of the ion-item. That can work well for inputs but not so much structural tags.

```<code>itemClicked(item){
   console.log(item);
}
</code>```

I think there is a better way to go about what you are trying to achieve though. It might be better to create your list in the code as an object literal and then pass to the view to use in a *ngFor . This makes your code compact yet complex and your view concise and neat.

So in your page component

```<code>categoryArray: Array<any> = [];
....
ionViewDidEnter(){
   this.categoryArray = [{
      value:'Men',
      icon: 'man',
      view:'viewToGoTo'
   },{
      value:'Woman',
      icon: 'woman',
      view:'viewToGoTo'
   },{
      value:'Kids',
      icon: 'baby',
      view:'viewToGoTo'
   }];
}
</code>```

Then in the view you can write a neat *ngFor

```<code><ion-item *ngFor="let item of categoryArray; let idx=index (click)="openSubCat(item)">
    <ion-icon [name]="item.icon" item-left></ion-icon>
      {{ item.value }}
    <ion-icon item-right ></ion-icon>
</ion-item>
</code>```

your click event will then pass

```<code>Object {value: "Men", icon: "man", view: "viewToGoTo"}
</code>```

That way in the click event you get a neat package of the properties that you require to be passed, and can be easily updated and edited. Or you can target a specific value with and idx, which makes it more versatile if complexity is added to the project. As well as adding the coolness in *ngFor like pipes and filters

```<code> (click)="openSubCat(item.view,idx)"
</code>```

You could then also make the categoryArray into an interface that can then be used throughout your code base.

Body:
I have a list of items,I need to get the selected data once i click on it
Here is my list:

<ion-content class="outer-content" no-border-top>
    <ion-list lines (click)="openSubCat($event,category)">
      <ion-list-header>
        Shop For
      </ion-list-header>
      <ion-item>
        <ion-icon name="man" item-left></ion-icon>
         Men
        <ion-icon item-right ></ion-icon>
        </ion-item>
       <ion-item menuClose>
       <ion-icon name="woman" item-left></ion-icon>
         Women
        <ion-icon  item-right></ion-icon>
      </ion-item>
      <ion-item>
        <ion-icon name="baby" item-left></ion-icon>
          Kids
        <ion-icon  item-right></ion-icon>
      </ion-item>
     </ion-list>
</ion-content>`

Body:
You can use the hashbang in a similar way to how you would use ${''} for id in jquery.

 <ion-item #menItem (click)="itemClicked(menuItem)>
  ....
 </ion-item>

Then in your console.log will give you the properties of the ion-item. That can work well for inputs but not so much structural tags.

itemClicked(item){
   console.log(item);
}

I think there is a better way to go about what you are trying to achieve though. It might be better to create your list in the code as an object literal and then pass to the view to use in a *ngFor . This makes your code compact yet complex and your view concise and neat.

So in your page component

categoryArray: Array<any> = [];
....
ionViewDidEnter(){
   this.categoryArray = [{
      value:'Men',
      icon: 'man',
      view:'viewToGoTo'
   },{
      value:'Woman',
      icon: 'woman',
      view:'viewToGoTo'
   },{
      value:'Kids',
      icon: 'baby',
      view:'viewToGoTo'
   }];
}

Then in the view you can write a neat *ngFor

<ion-item *ngFor="let item of categoryArray; let idx=index (click)="openSubCat(item)">
    <ion-icon [name]="item.icon" item-left></ion-icon>
      {{ item.value }}
    <ion-icon item-right ></ion-icon>
</ion-item>

your click event will then pass

Object {value: "Men", icon: "man", view: "viewToGoTo"}

That way in the click event you get a neat package of the properties that you require to be passed, and can be easily updated and edited. Or you can target a specific value with and idx, which makes it more versatile if complexity is added to the project. As well as adding the coolness in *ngFor like pipes and filters

 (click)="openSubCat(item.view,idx)"

You could then also make the categoryArray into an interface that can then be used throughout your code base.