问:
Using Javascript to write HTML inputs which call Javascript functions
I'll give you an example of what I'm trying to do.

In Javascript:

```<code>document.innerHTML += "<input type='button' id='moveButton' value='a' onclick='webInput('a');'>"
</code>```

The problem is that the html being written has two levels of quotes, and I can't figure out how to format the second level of quotes here:

```<code>webInput('a')
</code>```

In my Javascript file, I have one function write the inputs into the HTML at the end of the function, then clicking the inputs calls the next function, until eventually the inputs are rewritten.

I know the answer probably has something to do with Escape Characters, but I was confused as to how to format them because the text is being passed back and forther between Javascript and HTML, which use different Escape Characters.

答:
If you have requirements to add this as string to the document, you need to escape quotes:

```<code>"<input type='button' id='moveButton' value='a' onclick='webInput(\"a\")'>"
</code>```

great answer with rules for escaping here: https://stackoverflow.com/a/16134942/5727598

Also, you should use innerHtml property for element in which you want to pass your string but be sure it will remove all content there;

If no requirements, create button and upend to the body:

```<code>var input = document.createElement('input');

input.type = 'button';
input.id = 'moveButton';
input.value = 'a';

button.addEventListener('click', function(){
   webInput(this.value); //if you need to pass input value as parameter
})

document.body.appendChild(input);
</code>```

Body:
I'll give you an example of what I'm trying to do.

In Javascript:

document.innerHTML += "<input type='button' id='moveButton' value='a' onclick='webInput('a');'>"

The problem is that the html being written has two levels of quotes, and I can't figure out how to format the second level of quotes here:

webInput('a')

In my Javascript file, I have one function write the inputs into the HTML at the end of the function, then clicking the inputs calls the next function, until eventually the inputs are rewritten.

I know the answer probably has something to do with Escape Characters, but I was confused as to how to format them because the text is being passed back and forther between Javascript and HTML, which use different Escape Characters.

Body:
If you have requirements to add this as string to the document, you need to escape quotes:

"<input type='button' id='moveButton' value='a' onclick='webInput(\"a\")'>"

great answer with rules for escaping here: https://stackoverflow.com/a/16134942/5727598

Also, you should use innerHtml property for element in which you want to pass your string but be sure it will remove all content there;

If no requirements, create button and upend to the body:

var input = document.createElement('input');

input.type = 'button';
input.id = 'moveButton';
input.value = 'a';

button.addEventListener('click', function(){
   webInput(this.value); //if you need to pass input value as parameter
})

document.body.appendChild(input);


来源: stackexchange

问:
Keras: ValueError while doing predictions and accuracy is zero
I wrote the following model in Keras but while doing predictions, I am encountering ValueError (stated after the code). I looked at other questions on StackOverflow but only found this one but I wasn't able to understand what the answer is saying.

I am trying to build a network which takes X as input and has a hidden of 200 neurons and finally, a sigmodial neuron to predict the output class. The objective is binary classification.

The input to the model is (n x 400) as X and (n, 1) as Y. Both X and Y are numpy arrays. The code and the error message are as follows. Also, results of the neural network are : Loss = Infinite and Accuracy = 0.0 which means something from my side is clearly wrong.

```<code>def create_baseline():
    # create model
    model = Sequential()
    model.add(Dense(200, input_dim=400, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))
    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model
</code>```

I train the model as follows:

```<code>estimator = KerasClassifier(build_fn=create_baseline, nb_epoch=5, batch_size=5, verbose=1)
estimator.fit(X, Y)
</code>```

I try to predict using the following:

```<code>estimator.predict(X[0])
</code>```

I am getting the following error:

```<code>ValueError: Error when checking : expected dense_34_input to have shape (None, 400) but got array with shape (400, 1)
</code>```

Edit 1 : The training data X has 400 features (which are learnt from word2vec for the document). Y is a label which is only 0 and 1. I read the training file into a pandas dataframe and then use dataframe.values to get X and Y as numpy array.

Edit 2: Based on the answer below, I predicted from my model as estimator.predict(train_X_vals[0].reshape(1,len(train_X_vals[0]))) and I get the following output: array([[ nan]], dtype=float32)

Edit 3: I predict values for 1000 X's from the training set and I get all these as nan.

Edit 4: I have about 250K training samples. Upon using all these samples, I am getting loss = nan and all predictions as nan.  But when I take a sample of 2000 samples, I start getting good values.

Edit 5: It seems my model can't process more than 2500 training samples. I tried increasing training size and on 3000 and more, everything becomes nan.

答:
Regarding the error that you get- when you specify the input dimension, you specify the number of columns, which is 400 in your case. However, x[0] is just a  vector, so instead of having dimensions of the form (None, 400), its dimension is (400, 1). For example, if you define

```<code>x=np.random.rand(20,400)
</code>```

The result of x[0].shape is (400L,).

So you need to reshape your x[0] accordingly, for example by doing x[0].reshape(1,len(x[0])).

ContentLicense: CC BY-SA 3.0

Body:
I wrote the following model in Keras but while doing predictions, I am encountering ValueError (stated after the code). I looked at other questions on StackOverflow but only found this one but I wasn't able to understand what the answer is saying.

I am trying to build a network which takes X as input and has a hidden of 200 neurons and finally, a sigmodial neuron to predict the output class. The objective is binary classification.

The input to the model is (n x 400) as X and (n, 1) as Y. Both X and Y are numpy arrays. The code and the error message are as follows. Also, results of the neural network are : Loss = Infinite and Accuracy = 0.0 which means something from my side is clearly wrong.

def create_baseline():
    # create model
    model = Sequential()
    model.add(Dense(200, input_dim=400, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))
    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

I train the model as follows:

estimator = KerasClassifier(build_fn=create_baseline, nb_epoch=5, batch_size=5, verbose=1)
estimator.fit(X, Y)

I try to predict using the following:

estimator.predict(X[0])

I am getting the following error:

ValueError: Error when checking : expected dense_34_input to have shape (None, 400) but got array with shape (400, 1)

Edit 1 : The training data X has 400 features (which are learnt from word2vec for the document). Y is a label which is only 0 and 1. I read the training file into a pandas dataframe and then use dataframe.values to get X and Y as numpy array.

Edit 2: Based on the answer below, I predicted from my model as estimator.predict(train_X_vals[0].reshape(1,len(train_X_vals[0]))) and I get the following output: array([[ nan]], dtype=float32)

Edit 3: I predict values for 1000 X's from the training set and I get all these as nan.

Edit 4: I have about 250K training samples. Upon using all these samples, I am getting loss = nan and all predictions as nan.  But when I take a sample of 2000 samples, I start getting good values.

Edit 5: It seems my model can't process more than 2500 training samples. I tried increasing training size and on 3000 and more, everything becomes nan.

Body:
Regarding the error that you get- when you specify the input dimension, you specify the number of columns, which is 400 in your case. However, x[0] is just a  vector, so instead of having dimensions of the form (None, 400), its dimension is (400, 1). For example, if you define

x=np.random.rand(20,400)

The result of x[0].shape is (400L,).

So you need to reshape your x[0] accordingly, for example by doing x[0].reshape(1,len(x[0])).


问:
Docker centos7 systemctl deos not work : Failed to connect D-bus
I am trying to run elasticsearch on docker.

My features like below

host system : OSX 10.12.5

docker : 17.05.0-ce

docker operating image : centos:latest

I was following this article, but it stuck with systemctl daemon-reload.

I found CentOS official respond about this D-bus bug, but when I ran docker run command it shows the message below.

[!!!!!!] Failed to mount API filesystems, freezing.

How could I solve this problem?

FYI, Here is Dockerfile what I build image

```<code>FROM centos
MAINTAINER juneyoung <juneyoung@hanmail.net>

ARG u=elastic
ARG uid=1000
ARG g=elastic
ARG gid=1000
ARG p=elastic

# add USER
RUN groupadd -g ${gid} ${g}
RUN useradd -d /home/${u} -u ${uid} -g ${g} -s /bin/bash ${u}

# systemctl settings from official Centos github
# https://github.com/docker-library/docs/tree/master/centos#systemd-integration
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]

# yum settings
RUN yum -y update
RUN yum -y install java-1.8.0-openjdk.x86_64
ENV JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-3.b12.el7_3.x86_64/jre/

# install wget
RUN yum install -y wget

# install net-tools : netstat, ifconfig
RUN yum install -y net-tools

# Elasticsearch install
ENV ELASTIC_VERSION=5.4.0
RUN rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
RUN wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-${ELASTIC_VERSION}.rpm
RUN rpm -ivh elasticsearch-${ELASTIC_VERSION}.rpm

CMD ["/usr/sbin/init"]
</code>```

and I have ran with command

docker run -ti -v /sys/fs/cgroup:/sys/fs/cgroup:ro --name=elastic2 elastic2

答:
You could follow the commands for a systemd-enabled OS if you would replace the normal systemctl command. That's how I do install elasticsearch in a centos docker container.

See "docker-systemctl-replacement" for the details.

Body:
I am trying to run elasticsearch on docker.

My features like below

host system : OSX 10.12.5

docker : 17.05.0-ce

docker operating image : centos:latest

I was following this article, but it stuck with systemctl daemon-reload.

I found CentOS official respond about this D-bus bug, but when I ran docker run command it shows the message below.

[!!!!!!] Failed to mount API filesystems, freezing.

How could I solve this problem?

FYI, Here is Dockerfile what I build image

FROM centos
MAINTAINER juneyoung <juneyoung@hanmail.net>

ARG u=elastic
ARG uid=1000
ARG g=elastic
ARG gid=1000
ARG p=elastic

# add USER
RUN groupadd -g ${gid} ${g}
RUN useradd -d /home/${u} -u ${uid} -g ${g} -s /bin/bash ${u}

# systemctl settings from official Centos github
# https://github.com/docker-library/docs/tree/master/centos#systemd-integration
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]

# yum settings
RUN yum -y update
RUN yum -y install java-1.8.0-openjdk.x86_64
ENV JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-3.b12.el7_3.x86_64/jre/

# install wget
RUN yum install -y wget

# install net-tools : netstat, ifconfig
RUN yum install -y net-tools

# Elasticsearch install
ENV ELASTIC_VERSION=5.4.0
RUN rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
RUN wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-${ELASTIC_VERSION}.rpm
RUN rpm -ivh elasticsearch-${ELASTIC_VERSION}.rpm

CMD ["/usr/sbin/init"]

and I have ran with command

docker run -ti -v /sys/fs/cgroup:/sys/fs/cgroup:ro --name=elastic2 elastic2


问:
Rails: (Devise) Two different methods for new users?
I have a Rails 3 app with authentication setup using Devise with the registerable module enabled.

I want to have new users who sign up using our outside register form to use the full Devise registerable module, which is happening now.

However, I also want the admin user to be able to create new users directly, bypassing (I think) Devise's registerable module.

With registerable disabled, my standard UsersController works as I want it to for the admin user, just like any other Rail scaffold. However, now new users can't register on their own.

With registerable enabled, my standard UsersController is never called for the new user action (calling Devise::RegistrationsController instead), and my CRUD actions don't seem to work at all (I get dumped back onto my root page with no new user created and no flash message). Here's the log from the request:

```<code>Started POST "/users" for 127.0.0.1 at 2010-12-20 11:49:31 -0500
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"18697r4syNNWHfMTkDCwcDYphjos+68rPFsaYKVjo8Y=", "user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "role"=>"manager"}, "commit"=>"Create User"}
SQL (0.9ms)   ...

User Load (0.6ms)  SELECT "users".* FROM "users" WHERE ("users"."id" = 2) LIMIT 1
SQL (0.9ms)   ...

Redirected to http://test-app.local/ Completed 302 Found in 192ms
</code>```

... but I am able to register new users through the outside form.

How can I get both of these methods to work together, such that my admin user can manually create new users and guest users can register on their own?

I have my Users controller setup for standard CRUD:

```<code>class UsersController < ApplicationController
  load_and_authorize_resource

  def index
    @users = User.where("id NOT IN (?)", current_user.id) # don't display the current user in the users list; go to account management to edit current user details
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:notice] = "#{ @user.email } created."
      redirect_to users_path
    else
      render :action => 'new'
    end
  end

  def edit
  end

  def update
    params[:user].delete(:password) if params[:user][:password].blank?
    params[:user].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank?
    if @user.update_attributes(params[:user])
      flash[:notice] = "Successfully updated User."
      redirect_to users_path
    else
      render :action => 'edit'
    end
  end

  def delete
  end

  def destroy
    redirect_to users_path and return if params[:cancel]
    if @user.destroy
      flash[:notice] = "#{ @user.email } deleted."
      redirect_to users_path
    end
  end

end
</code>```

And my routes setup as follows:

```<code>TestApp::Application.routes.draw do

  devise_for :users

  devise_scope :user do
    get "/login", :to => "devise/sessions#new", :as => :new_user_session
    get "/logout", :to => "devise/sessions#destroy", :as => :destroy_user_session
  end

  resources :users do
    get :delete, :on => :member
  end

  authenticate :user do
    root :to => "application#index"
  end
  root :to => "devise/session#new"

end
</code>```

答:
You should create a separate controller to manage your users. I always create administrator users and give them a special namespace to work in. Let me illustrate that:

config/routes.rb

```<code>devise :users # Allow users to register here

namespace :admin do
  resources :users # Have the admin manage them here.
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a Rails 3 app with authentication setup using Devise with the registerable module enabled.

I want to have new users who sign up using our outside register form to use the full Devise registerable module, which is happening now.

However, I also want the admin user to be able to create new users directly, bypassing (I think) Devise's registerable module.

With registerable disabled, my standard UsersController works as I want it to for the admin user, just like any other Rail scaffold. However, now new users can't register on their own.

With registerable enabled, my standard UsersController is never called for the new user action (calling Devise::RegistrationsController instead), and my CRUD actions don't seem to work at all (I get dumped back onto my root page with no new user created and no flash message). Here's the log from the request:

Started POST "/users" for 127.0.0.1 at 2010-12-20 11:49:31 -0500
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"18697r4syNNWHfMTkDCwcDYphjos+68rPFsaYKVjo8Y=", "user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "role"=>"manager"}, "commit"=>"Create User"}
SQL (0.9ms)   ...

User Load (0.6ms)  SELECT "users".* FROM "users" WHERE ("users"."id" = 2) LIMIT 1
SQL (0.9ms)   ...

Redirected to http://test-app.local/ Completed 302 Found in 192ms

... but I am able to register new users through the outside form.

How can I get both of these methods to work together, such that my admin user can manually create new users and guest users can register on their own?

I have my Users controller setup for standard CRUD:

class UsersController < ApplicationController
  load_and_authorize_resource

  def index
    @users = User.where("id NOT IN (?)", current_user.id) # don't display the current user in the users list; go to account management to edit current user details
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:notice] = "#{ @user.email } created."
      redirect_to users_path
    else
      render :action => 'new'
    end
  end

  def edit
  end

  def update
    params[:user].delete(:password) if params[:user][:password].blank?
    params[:user].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank?
    if @user.update_attributes(params[:user])
      flash[:notice] = "Successfully updated User."
      redirect_to users_path
    else
      render :action => 'edit'
    end
  end

  def delete
  end

  def destroy
    redirect_to users_path and return if params[:cancel]
    if @user.destroy
      flash[:notice] = "#{ @user.email } deleted."
      redirect_to users_path
    end
  end

end

And my routes setup as follows:

TestApp::Application.routes.draw do

  devise_for :users

  devise_scope :user do
    get "/login", :to => "devise/sessions#new", :as => :new_user_session
    get "/logout", :to => "devise/sessions#destroy", :as => :destroy_user_session
  end

  resources :users do
    get :delete, :on => :member
  end

  authenticate :user do
    root :to => "application#index"
  end
  root :to => "devise/session#new"

end

Body:
You should create a separate controller to manage your users. I always create administrator users and give them a special namespace to work in. Let me illustrate that:

config/routes.rb

devise :users # Allow users to register here

namespace :admin do
  resources :users # Have the admin manage them here.
end


问:
cell.imageview.image not showing image on table
I am getting image URL from firebase but when trying to show on table i am not able to see one.Code is below.I am saving images in firebase from

UIImagePickerController()

```<code> public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

        let cell = tableView.dequeueReusableCell(withIdentifier: "allUsers", for: indexPath) as! allUserCell
        cell.textLabel?.text = allUserData[indexPath.row].name
        cell.detailTextLabel?.text = allUserData[indexPath.row].email

        if let image = allUserData[indexPath.row].image  {
        let url = NSURL(string: image)
        let request = URLRequest(url:url! as URL)

        URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
            if error != nil{
                print(error as Any)
                return
            }
            DispatchQueue.main.async {
                if let image = UIImage(data: data!) {
                    print(image)
                    cell.imageView?.image = image
                }
            }

        }).resume()

    }
        return cell
}
}
</code>```

The print(image) line gives me following-:

```<code>UIImage: 0x60800009b3f0>, {746, 498}
</code>```

custom Cell Class.

```<code>class allUserCell:UITableViewCell{
    override init(style:UITableViewCellStyle,reuseIdentifier:String?) {
        super.init(style:.subtitle,reuseIdentifier:reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

答:
add an extension

```<code>extension UIImageView{

    func setImageFromURl(stringImageUrl url: String){

        if let url = NSURL(string: url) {
            if let data = NSData(contentsOfURL: url) {
                self.image = UIImage(data: data)
            }
        }
    }
}
</code>```

then use
cell.imageView.setImageFromURl((stringImageUrl: imgURL)) // provide your Image url in the parameter as String

hope this will help you . All the best

Body:
I am getting image URL from firebase but when trying to show on table i am not able to see one.Code is below.I am saving images in firebase from

UIImagePickerController()

 public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

        let cell = tableView.dequeueReusableCell(withIdentifier: "allUsers", for: indexPath) as! allUserCell
        cell.textLabel?.text = allUserData[indexPath.row].name
        cell.detailTextLabel?.text = allUserData[indexPath.row].email

        if let image = allUserData[indexPath.row].image  {
        let url = NSURL(string: image)
        let request = URLRequest(url:url! as URL)

        URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
            if error != nil{
                print(error as Any)
                return
            }
            DispatchQueue.main.async {
                if let image = UIImage(data: data!) {
                    print(image)
                    cell.imageView?.image = image
                }
            }

        }).resume()

    }
        return cell
}
}

The print(image) line gives me following-:

UIImage: 0x60800009b3f0>, {746, 498}

custom Cell Class.

class allUserCell:UITableViewCell{
    override init(style:UITableViewCellStyle,reuseIdentifier:String?) {
        super.init(style:.subtitle,reuseIdentifier:reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Body:
add an extension

extension UIImageView{

    func setImageFromURl(stringImageUrl url: String){

        if let url = NSURL(string: url) {
            if let data = NSData(contentsOfURL: url) {
                self.image = UIImage(data: data)
            }
        }
    }
}

then use
cell.imageView.setImageFromURl((stringImageUrl: imgURL)) // provide your Image url in the parameter as String

hope this will help you . All the best


问:
Gradle build takes too long while creating a new project
Everytime I create a new project, gradle build takes too long to finish for about 20 to 25 minutes. It is usually on "Gradle: Resolve dependencies ':app_debugAndroidTestxxx'" but when running my program it doesn't take that long only when creating a new project.

Here is the screenshot.

答: If you have Internet connection, try to create a new Android Studio project in offline mode. Because some dependencies might be take time to install from internet. So in offline mode, it pick downloaded dependencies from cache. </p>


问:
What does "Break outside Loop" mean?
Beginner!

I am trying to make a program that reads in X whole numbers and outputs (1) the sum of all positive numbers, (2) the sum of all negative numbers, and (3) the sum of all positive and negative numbers. The user can enter the X numbers in any different order every time, and can repeat the program if desired.

In order to add the repeat function I have added "break" to the loop. However when I try to run it it shows an error that says "break outside loop". I am unsure what this error means and how I can go about fixing it.

```<code>while True:
    many = int(input("How many numbers would you like to enter:"))
    Sum = 0
    sumNeg = 0
    for i in range(0,many,1):
        num = float(input("Please enter number" +str(i+1)+":"))
        Sum = Sum + num
        if num < 0:
            sumNeg = sumNeg + num
    print('Sum =',Sum)
    print('sumNeg =', sumNeg)
repeat =input("Would you like to repeat? (Y/N):")
if repeat != 'Y':
    break
</code>```

答:
The break statement is outside the loop because it's parent if statement is outside the loop.</p>

```<code>while True:
    many = int(input("How many numbers would you like to enter:"))
    Sum = 0
    sumNeg = 0
    for i in range(0,many,1):
        num = float(input("Please enter number" +str(i+1)+":"))
        Sum = Sum + num
        if num < 0:
            sumNeg = sumNeg + num
    print('Sum =',Sum)
    print('sumNeg =', sumNeg)
    repeat =input("Would you like to repeat? (Y/N):")
    if repeat != 'Y':
        break
</code>```

Title: What does "Break outside Loop" mean?

Body:
Beginner!

I am trying to make a program that reads in X whole numbers and outputs (1) the sum of all positive numbers, (2) the sum of all negative numbers, and (3) the sum of all positive and negative numbers. The user can enter the X numbers in any different order every time, and can repeat the program if desired.

In order to add the repeat function I have added "break" to the loop. However when I try to run it it shows an error that says "break outside loop". I am unsure what this error means and how I can go about fixing it.

while True:
    many = int(input("How many numbers would you like to enter:"))
    Sum = 0
    sumNeg = 0
    for i in range(0,many,1):
        num = float(input("Please enter number" +str(i+1)+":"))
        Sum = Sum + num
        if num < 0:
            sumNeg = sumNeg + num
    print('Sum =',Sum)
    print('sumNeg =', sumNeg)
repeat =input("Would you like to repeat? (Y/N):")
if repeat != 'Y':
    break

Body:
The break statement is outside the loop because it's parent if statement is outside the loop.

while True:
    many = int(input("How many numbers would you like to enter:"))
    Sum = 0
    sumNeg = 0
    for i in range(0,many,1):
        num = float(input("Please enter number" +str(i+1)+":"))
        Sum = Sum + num
        if num < 0:
            sumNeg = sumNeg + num
    print('Sum =',Sum)
    print('sumNeg =', sumNeg)
    repeat =input("Would you like to repeat? (Y/N):")
    if repeat != 'Y':
        break


问:
Thread.stop() - deprecated
Why is Thread.stop() deprecated in Java? On their website, I see the following:

Why is Thread.stop deprecated?

Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.

I don't understand what they mean by "monitors". Regardless, my question is if Thread.stop() should not be called then how should a Java thread be stopped?

答:
From https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html:

Most uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized
  ).

Title: Thread.stop() - deprecated

ContentLicense: CC BY-SA 4.0


问:
How to programatically chain two js functions?
I'm trying to solve how I can to chain several js functions (two in this case). I have one javascript function to save() an another for saveAndPrint(). I need to chain the call because I need the id generated in save() to forward it for printing in the second one. Probably I just could use only one function to do both things but I'd like to learn how to do this. At the moment I just getting an 'undefined' because second function starts before the first one finishes.
Here is the code:

```<code>$scope.save = function () {
    var receipt = {
        documentType: 'RCI',
        expirationDate: new moment().format('YYYY-MM-DD'),
        person: {id: $scope.financeDocuments[0].person.id},
        payments: getPayments(),
        promotions: [],
        creationDate: new moment().format('YYYY-MM-DD'),
        compensatedDocuments: getDocumentsToPay()
    };

    financeDocumentService.save(receipt, function (response) {
        receipt = response;
        $uibModalInstance.close(response);
    }).$promise.then(function (data) {
        return receipt;
    });
};

$scope.saveAndPrint = function() {
    var document = $scope.save();
        $window.location.href = "#/finance/receipt_show/"+document.id;
};
</code>```

Thanks a lot!

答:
First return the promise:

```<code>$scope.save = function () {
    var receipt = {
        documentType: 'RCI',
        expirationDate: new moment().format('YYYY-MM-DD'),
        person: {id: $scope.financeDocuments[0].person.id},
        payments: getPayments(),
        promotions: [],
        creationDate: new moment().format('YYYY-MM-DD'),
        compensatedDocuments: getDocumentsToPay()
    };

    //RETURN the promise
    ͟r͟e͟t͟u͟r͟n͟  financeDocumentService.save(receipt, function (response) {
        receipt = response;
        $uibModalInstance.close(response);
    }).$promise.then(function (data) {
        return receipt;
    });
};
</code>```

Then chain from the promise:

```<code>$scope.saveAndPrint = function() {
    var promise = $scope.save();
    promise.then(function(receipt) {
        $window.location.href = "#/finance/receipt_show/"+document.id;
    });
};
</code>```

For more information,

AngularJS $q Service API Reference - Chaining Promises

You`re Missing the Point of Promises

Body:
I'm trying to solve how I can to chain several js functions (two in this case). I have one javascript function to save() an another for saveAndPrint(). I need to chain the call because I need the id generated in save() to forward it for printing in the second one. Probably I just could use only one function to do both things but I'd like to learn how to do this. At the moment I just getting an 'undefined' because second function starts before the first one finishes.
Here is the code:

$scope.save = function () {
    var receipt = {
        documentType: 'RCI',
        expirationDate: new moment().format('YYYY-MM-DD'),
        person: {id: $scope.financeDocuments[0].person.id},
        payments: getPayments(),
        promotions: [],
        creationDate: new moment().format('YYYY-MM-DD'),
        compensatedDocuments: getDocumentsToPay()
    };

    financeDocumentService.save(receipt, function (response) {
        receipt = response;
        $uibModalInstance.close(response);
    }).$promise.then(function (data) {
        return receipt;
    });
};

$scope.saveAndPrint = function() {
    var document = $scope.save();
        $window.location.href = "#/finance/receipt_show/"+document.id;
};

Thanks a lot!

Body:
First return the promise:

$scope.save = function () {
    var receipt = {
        documentType: 'RCI',
        expirationDate: new moment().format('YYYY-MM-DD'),
        person: {id: $scope.financeDocuments[0].person.id},
        payments: getPayments(),
        promotions: [],
        creationDate: new moment().format('YYYY-MM-DD'),
        compensatedDocuments: getDocumentsToPay()
    };

    //RETURN the promise
    ͟r͟e͟t͟u͟r͟n͟  financeDocumentService.save(receipt, function (response) {
        receipt = response;
        $uibModalInstance.close(response);
    }).$promise.then(function (data) {
        return receipt;
    });
};

Then chain from the promise:

$scope.saveAndPrint = function() {
    var promise = $scope.save();
    promise.then(function(receipt) {
        $window.location.href = "#/finance/receipt_show/"+document.id;
    });
};

For more information,

AngularJS $q Service API Reference - Chaining Promises

You`re Missing the Point of Promises


问:
How to deploy a Maven web application to a local-installed Glassfish?
How one can deploy a maven web application to a locally instaled glassfish server using only maven plugins?

In other words, if I have a maven project with packaging=war, it is possible to deploy to a locally installed glassfish using a command like "mvn clean package some-plugin:goal-deploy"?

答: You need to specify a version of the plugin. Maven version 3 gives me some warnings about this issue.</p>


问:
Scilab plotting functions with if
I have a problen in scilab
How can I plot functions containing if and < like

```<code>function y = alpha(t)
   if (t < 227.8) then
       y = 0.75;
   elseif (t < 300) then
       y = 2.8 - 0.009 .* t;
   else
       y = 0.1;
   end
endfunction
</code>```

and

```<code>function [r]=minus_alpha(t)
    r = 1 - alpha(t)
endfunction
</code>```

When I use

```<code>x = linspace(0,300)
plot(x, alpha(x))
</code>```

I got the error message

```<code>WARNING: Transposing row vector X to get compatible dimensions
plot2d: falsche Größe für Eingangsargument: inkompatible Größen.
Error 999 : in plot2d called by plot
</code>```

Sorry for german mix. Thank you.

答:
If you check the output of your alpha(x), you will see that it is just a scalar (not a vector). I guess you wanted something like this, so it's necessary to iterate through t to compute each value of y based on the value of t:

```<code>clc;
clear;
function y = alpha(t)
    for i=1:size(t,"*")
        if t(i) < 227.8 then
            y(i) = 0.75;
        elseif t(i) < 300 then
            y(i) = 2.8 - 0.009 * t(i);
        else
            y(i) = 0.1;
        end
    end
endfunction

x = linspace(0,300);
plot2d(x,alpha(x));
</code>```

If you find the answer useful, please do not forget to accept it, so others will see that your problem is solved.

Title: Scilab plotting functions with if

Body:
I have a problen in scilab
How can I plot functions containing if and < like

function y = alpha(t)
   if (t < 227.8) then
       y = 0.75;
   elseif (t < 300) then
       y = 2.8 - 0.009 .* t;
   else
       y = 0.1;
   end
endfunction

and

function [r]=minus_alpha(t)
    r = 1 - alpha(t)
endfunction

When I use

x = linspace(0,300)
plot(x, alpha(x))

I got the error message

WARNING: Transposing row vector X to get compatible dimensions
plot2d: falsche Größe für Eingangsargument: inkompatible Größen.
Error 999 : in plot2d called by plot

Sorry for german mix. Thank you.

Body:
If you check the output of your alpha(x), you will see that it is just a scalar (not a vector). I guess you wanted something like this, so it's necessary to iterate through t to compute each value of y based on the value of t:

clc;
clear;
function y = alpha(t)
    for i=1:size(t,"*")
        if t(i) < 227.8 then
            y(i) = 0.75;
        elseif t(i) < 300 then
            y(i) = 2.8 - 0.009 * t(i);
        else
            y(i) = 0.1;
        end
    end
endfunction

x = linspace(0,300);
plot2d(x,alpha(x));

If you find the answer useful, please do not forget to accept it, so others will see that your problem is solved.


问:
Issue tracker for web agency workflow
We're looking into implementing an issue tracker for our web agency. The problem is that most issue trackers seem to revolve around the assumption that an issue is a bug, whereas in a web agency environment, a lot of the issues (request, or whatever you want to call them) are about changes and additions to a current web site.

It also seems to me that a lot of issue trackers assume that you're working on one main software project, and uses that project as the focus of the tracker. A good issue tracker for a web agency would be one which puts each separate client and their issues at the heart of the system, making it easy for them to track and report issues.

Does anyone know of a good issue tracker for the web agency workflow? What are other people using?

答:
Have you had a look at fixx at all? Obviously, being the developer of fixx, I will want to plug it but I know from first-hand experience that a lot of our customers are web agencies who work in a service-oriented environment and need to track more than just "software development" projects.

With fixx, you can define custom issue types (for example "change request" or "Copy changes") and track work against that type.

Unfortunately, fixx still does suffer from the "project-centric" view but a lot of our customers work around this by defining a project per client/website. So, if you were doing web/maintenance on stackoverflow.com, you would have a project called "stackoverflow.com maintenance" and would assign all your users from that company to that specific project. From there, using notifications and filters, it would be very easy for clients to keep track of progress on their specific issues.

Title: Issue tracker for web agency workflow


问:
parametrize and running a single test in pytest
How can I run a single test out of a set configured with parametrize?
Let's say I have the following test method:

```<code>@pytest.mark.parametrize(PARAMETERS_LIST, PARAMETERS_VALUES)
def test_my_feature(self, param1, param2, param3):
    """
    test doc
    """
    if param1 == 'value':
        assert True
    else:
        print 'not value'
        assert False
</code>```

I have 3 parameters, and I generate a list of 15 different possible values for them, to test the function on.

How can I run just one of them? except for the obvious way - giving a single value instead of 15.

答:
You can specify the tests to run by using the -k flag for filtering tests that match a string expression. When using parametrize, pytest names each test case with the following convention:

test_name['-' separated test inputs]

for example

```<code>test_name[First_test_value-Second_test_value-N_test_value]
</code>```

Selecting an specific test to run is a matter of putting all the above together for example

```<code>pytest -k 'my_test[value_1-value_2]'
</code>```

or

```<code>pytest -k my_test\[value_1-value_2\]
</code>```

You need to escape the square brackets.

Body:
How can I run a single test out of a set configured with parametrize?
Let's say I have the following test method:

@pytest.mark.parametrize(PARAMETERS_LIST, PARAMETERS_VALUES)
def test_my_feature(self, param1, param2, param3):
    """
    test doc
    """
    if param1 == 'value':
        assert True
    else:
        print 'not value'
        assert False

I have 3 parameters, and I generate a list of 15 different possible values for them, to test the function on.

How can I run just one of them? except for the obvious way - giving a single value instead of 15.

Body:
You can specify the tests to run by using the -k flag for filtering tests that match a string expression. When using parametrize, pytest names each test case with the following convention:

test_name['-' separated test inputs]

for example

test_name[First_test_value-Second_test_value-N_test_value]

Selecting an specific test to run is a matter of putting all the above together for example

pytest -k 'my_test[value_1-value_2]'

or

pytest -k my_test\[value_1-value_2\]

You need to escape the square brackets.


问:
Dataset_factory importerror: Tensorflow fine-tuning a pre-trained model from an existing checkpoint on custom data
I am working on retraining a a pre-trained (inception v1) model on a small custom dataset based on the instructions of the tensorflow github page

Creating the dataset:

```<code>python build_image_data.py
--train_directory="${TRAIN_DIR}"
--validation_directory="${VALIDATION_DIR}"
--output_directory="${OUTPUT_DIRECTORY}"
--labels_file="${LABELS_FILE}"
--train_shards=128
--validation_shards=24
--num_threads=8
</code>```

Fine-tuning (https://github.com/tensorflow/models/tree/master/slim#Pretrained - Fine-tuning a model from an existing checkpoint section):

```<code>python train_image_classifier.py
--train_dir="${TRAIN_DIR}"
--dataset_dir="${DATASET_DIR}"
--dataset_name=objects
--dataset_split_name=train
--model_name=inception_v1
--checkpoint_path="${CHECKPOINT_PATH}"
</code>```

And I got the following error message:

File "train_image_classifier.py", line 23, in  from datasets import dataset_factory - ImportError: no module named 'datasets'

I tried to add dataset_factory to python path but it did not work and I cannot find any solution to solve this issue. What to do in this case?

答: First of all, make shure that you have the latest version of the code https://github.com/tensorflow/models/tree/master/slim . Check, that datasets folder exists. You also may try to add datasets (not dataset_factory.py) folder to PYTHONPATH environment variable.</p>

Body:
I am working on retraining a a pre-trained (inception v1) model on a small custom dataset based on the instructions of the tensorflow github page

Creating the dataset:

python build_image_data.py
--train_directory="${TRAIN_DIR}"
--validation_directory="${VALIDATION_DIR}"
--output_directory="${OUTPUT_DIRECTORY}"
--labels_file="${LABELS_FILE}"
--train_shards=128
--validation_shards=24
--num_threads=8

Fine-tuning (https://github.com/tensorflow/models/tree/master/slim#Pretrained - Fine-tuning a model from an existing checkpoint section):

python train_image_classifier.py
--train_dir="${TRAIN_DIR}"
--dataset_dir="${DATASET_DIR}"
--dataset_name=objects
--dataset_split_name=train
--model_name=inception_v1
--checkpoint_path="${CHECKPOINT_PATH}"

And I got the following error message:

File "train_image_classifier.py", line 23, in  from datasets import dataset_factory - ImportError: no module named 'datasets'

I tried to add dataset_factory to python path but it did not work and I cannot find any solution to solve this issue. What to do in this case?


问:
docusign embedded email notification
I will create a embedded envelope with 2 recipient in sequential order. How to notify the second user that the first user has signed the document and now he can do the digital signature. Does docusign has any such kind of feature </p>

答:
If both your recipients are embedded, then once the first recipient takes an action, DocuSign redirects to the the returnUrl you specify with a Recipient action.  Based on the recipient action returned you can take the next steps in your workflow. If you get the signing_complete action then you can load the next recipient.

From Documentation

There are numerous actions the embedded recipient might take:

cancel - the recipient decides to finish later

decline - the recipient declines signing

exception - a processing error occurs during the signing session

fax_pending - if the recipient choses to print, sign and fax back

id_check_failed - if authentication was added to the document, this is when the recipient fails

session_timeout - the signing session times out when recipient goes idle

signing_complete - the recipient completed signing

ttl_expired - the token was not used within the timeout period or the token was already accessed

viewing_complete - a recipient that does not need to sign completes the viewing ceremony

If your second recipient is a remote recipient then DocuSign will automatically notify the second recipient after the first recipient finishes signing.

Title: docusign embedded email notification


问:
AngularJS double value in table
I have problem with when I want print a table, I have a double value. This is my print on page:

A 2.14 2.14 B 4.57 C 6.00 6.00 D 3.43 E 3.86 F 3.29

```<code><tr ng-repeat="item in liveCurrency">
    <td> {{item.currency}}</td>
    <td class="min-price" ng-show="isMin(item.price)">{{item.price}}</td>
    <td class="max-price" ng-show="isMax(item.price)">{{item.price}}</td>
    <td>{{item.price}}</td>
</tr>
</code>```

Which condition I have to set to overcome duplicate values? tnx for help

答:
The value is double printed because you have the {{item.price}}	 that will show every time and the ng-show directive that will be right at least once.

```<code><tr ng-repeat="item in liveCurrency">
    <td> {{item.currency}}</td>
    <td class="min-price" ng-show="isMin(item.price)">{{item.price}}</td>
    <td class="max-price" ng-show="isMax(item.price)">{{item.price}}</td>
    <!-- <td>{{item.price}}</td> -->
</tr>
</code>```

If none of the show conditions are true, display your last .

```<code><td ng-if="!isMin(item.price) && !isMax(item.price)>{{item.price}}</td>
</code>```

Title: AngularJS double value in table

Body:
I have problem with when I want print a table, I have a double value. This is my print on page:

A 2.14 2.14 B 4.57 C 6.00 6.00 D 3.43 E 3.86 F 3.29

     {{item.currency}}
    {{item.price}}
    {{item.price}}
    {{item.price}}

Which condition I have to set to overcome duplicate values? tnx for help

Body:
The value is double printed because you have the <td>{{item.price}}</td> that will show every time and the ng-show directive that will be right at least once.

<tr ng-repeat="item in liveCurrency">
    <td> {{item.currency}}</td>
    <td class="min-price" ng-show="isMin(item.price)">{{item.price}}</td>
    <td class="max-price" ng-show="isMax(item.price)">{{item.price}}</td>
    <!-- <td>{{item.price}}</td> -->
</tr>

If none of the show conditions are true, display your last <td>.

<td ng-if="!isMin(item.price) && !isMax(item.price)>{{item.price}}</td>


问:
execute Linux multiline command via PHP
in putty i paste these lines and it works

```<code>cd /usr/local/vpnserver/
./vpncmd
1

Hub VPN
UserGet 34
</code>```

but when it try to do this in php with exec or shell_exec

```<code><?php

$x = exec('cd /usr/local/vpnserver/;./vpncmd;1;;;Hub VPN;UserGet 34');
echo $x;

?>
</code>```

it doesn't work for me because after ./vpncmd it asks question to choose 1 2 3

I have to enter 1 and then again 2 enter and I reach my position to connect with vpn hub and can view my vpn users details.

but i can't do this in php.
how it will work in php

答:
; can only be used to separate commands, it doesn't work for input to the commands. If you want to supply input to a command, use a here-doc.

```<code>$x = exec('cd /usr/local/vpnserver/;./vpncmd <<EOF
1

Hub VPN
UserGet 34
EOF');
</code>```

Title: execute Linux multiline command via PHP

Body:
in putty i paste these lines and it works

cd /usr/local/vpnserver/
./vpncmd
1

Hub VPN
UserGet 34

but when it try to do this in php with exec or shell_exec

<?php

$x = exec('cd /usr/local/vpnserver/;./vpncmd;1;;;Hub VPN;UserGet 34');
echo $x;

?>

it doesn't work for me because after ./vpncmd it asks question to choose 1 2 3

I have to enter 1 and then again 2 enter and I reach my position to connect with vpn hub and can view my vpn users details.

but i can't do this in php.
how it will work in php

Body:
; can only be used to separate commands, it doesn't work for input to the commands. If you want to supply input to a command, use a here-doc.

$x = exec('cd /usr/local/vpnserver/;./vpncmd <<EOF
1

Hub VPN
UserGet 34
EOF');


问:
Uncheck checkbox on text input & clear text input when checkbox is checked
I have a search bar and check box as so:

```<code><input type="text" placeholder="Search..." (keyup)="onKey()" [(ngModel)]="input">
<input type="checkbox" (click)="clearSearch()" [(ngModel)]="checkbox">View All
</code>```

Whenever anyone types into the search bar I want the checkbox to become unchecked.
Likewise, whenever anyone checks the checkbox, I want the search bar to be cleared.

I've tried the following:

```<code>export class App {
 checkbox = ['checked']
 clearSearch() {
 this.input = '';
};
onKey() {
 checkbox = ['unchecked']
}
</code>```

But it obviously doesn't quite work.

Here is a plunker with the above code: https://plnkr.co/edit/uAYxswpoz18jlRUqAMn5?p=preview

Which is the best way to achieve this functionality?

Thanks!

答:
In your function make this.checkbox to be false.

```<code> <input type="checkbox" (click)="clearSearch()" [(ngModel)]="checkbox">View All
</code>```

your function

```<code> onKey() {
     this.checkbox = false;
  }
</code>```

DEMO

Body:
I have a search bar and check box as so:

<input type="text" placeholder="Search..." (keyup)="onKey()" [(ngModel)]="input">
<input type="checkbox" (click)="clearSearch()" [(ngModel)]="checkbox">View All

Whenever anyone types into the search bar I want the checkbox to become unchecked.
Likewise, whenever anyone checks the checkbox, I want the search bar to be cleared.

I've tried the following:

export class App {
 checkbox = ['checked']
 clearSearch() {
 this.input = '';
};
onKey() {
 checkbox = ['unchecked']
}

But it obviously doesn't quite work.

Here is a plunker with the above code: https://plnkr.co/edit/uAYxswpoz18jlRUqAMn5?p=preview

Which is the best way to achieve this functionality?

Thanks!

Body:
In your function make this.checkbox to be false.

 <input type="checkbox" (click)="clearSearch()" [(ngModel)]="checkbox">View All

your function

 onKey() {
     this.checkbox = false;
  }

DEMO


问:
How does KNearestNeighborMatching.Match work
I've reviewed the documentation for this method here: http://accord-framework.net/docs/html/M_Accord_Imaging_KNearestNeighborMatching_1_Match_1.htm

The description is rather brief: "Matches two sets of feature points." I've tried it a couple of times, first by using the result of SURFing the same image twice and, second, by SURFing two different images. The first test returned, what I expected, a little less matching points that the points found by SURF. The second got me scratching my head, I got more points than the largest number of points found by SURF. So, obviously, I don't know what to expect from this method. Can anyone give me a more detailed description of what I can expect?

What I am trying to do is to determine how similar two images of different sizes are. You can see a previous, related question I made here: Accord.NET Comparing two images to determine similarity

答:
The method uses a k-Nearest Neighbor classification algorithm to learn a mapping between the descriptors in one image and a vector of integer indices indicating their position. From the source code of the KNearestNeighborMatch class, you can see:

```<code>/// <summary>
///   Creates a nearest neighbor algorithm with the feature points as
///   inputs and their respective indices a the corresponding output.
/// </summary>
///
protected virtual IMulticlassScoreClassifier<T> CreateNeighbors(T[] features)
{
    int[] outputs = Vector.Range(0, features.Length);

    // Create a k-Nearest Neighbor classifier to classify points
    // in the second image to nearest points in the first image
    return new KNearestNeighbors<T>(K, Distance).Learn(features, outputs);
}
</code>```

The point of building this classifier is that now you can pass any descriptor to it, even of those who were not in the original image, and it will give you the index of the descriptor in the original image that is the more closest to it. So in practice, you can use this classifier to obtain the best matches between the feature points from two different images.

Regarding the observation about the number of points returned by the function, this is explained in lines 144-154:

```<code> // We should build the classifiers with the highest number
 // of training points. Thus, if we have more points in the
 // second image than in the first, we'll have to swap them

 if (points2.Length > points1.Length)
 {
     var aux = points1;
     points1 = points2;
     points2 = aux;
     swap = true;
 }
</code>```

So as you can see, the method will use as the "anchor" image the image that has the largest number of SURF descriptors. This is needed so no feature point in the image with smaller number of descriptor is left unclassified.

Answering the original question about how to compute a measure of compatibility between two images, a possibility is to consider the total number of point matches, the sum of best scores between the two images, the minimum (worst) score, the best score, or a combination of these (maybe following something along the lines of the Hausdorff distance).

Body:
The method uses a k-Nearest Neighbor classification algorithm to learn a mapping between the descriptors in one image and a vector of integer indices indicating their position. From the source code of the KNearestNeighborMatch class, you can see:

/// <summary>
///   Creates a nearest neighbor algorithm with the feature points as
///   inputs and their respective indices a the corresponding output.
/// </summary>
///
protected virtual IMulticlassScoreClassifier<T> CreateNeighbors(T[] features)
{
    int[] outputs = Vector.Range(0, features.Length);

    // Create a k-Nearest Neighbor classifier to classify points
    // in the second image to nearest points in the first image
    return new KNearestNeighbors<T>(K, Distance).Learn(features, outputs);
}

The point of building this classifier is that now you can pass any descriptor to it, even of those who were not in the original image, and it will give you the index of the descriptor in the original image that is the more closest to it. So in practice, you can use this classifier to obtain the best matches between the feature points from two different images.

Regarding the observation about the number of points returned by the function, this is explained in lines 144-154:

 // We should build the classifiers with the highest number
 // of training points. Thus, if we have more points in the
 // second image than in the first, we'll have to swap them

 if (points2.Length > points1.Length)
 {
     var aux = points1;
     points1 = points2;
     points2 = aux;
     swap = true;
 }

So as you can see, the method will use as the "anchor" image the image that has the largest number of SURF descriptors. This is needed so no feature point in the image with smaller number of descriptor is left unclassified.

Answering the original question about how to compute a measure of compatibility between two images, a possibility is to consider the total number of point matches, the sum of best scores between the two images, the minimum (worst) score, the best score, or a combination of these (maybe following something along the lines of the Hausdorff distance).


问:
CMake's find packages finds nonexisting python library
FindPythonLibs.cmake is somehow finding Python versions that don't exist/were uninstalled.

When I run find_package(PythonLibs 3 REQUIRED) CMake properly finds my Python3.6 installation and adds its include path, but then I get the error

No rule to make target 'C:/Users/ultim/Anaconda2/libs/python27.lib', needed by 'minotaur-cpp.exe'.  Stop.

This directory doesn't exist, and I recently uninstalled Anaconda and the python that came with it. I've looked through my environment variables and registry, but find no reference to this location.

Would anyone know where there might still be a reference to this location?

答:
Since the "REQUIRED" option to find_package() is not working, you can be explicit about which Python library using CMake options with cache variables:

cmake -DPYTHON_INCLUDE_DIR=C:\Python36\include -DPYTHON_LIBRARY=C:\Python36\libs\python36.lib ..


问:
What would cause an algorithm to have O(log n) complexity?
My knowledge of big-O is limited, and when log terms show up in the equation it throws me off even more.

Can someone maybe explain to me in simple terms what a O(log n) algorithm is? Where does the logarithm come from?

This specifically came up when I was trying to solve this midterm practice question:

Let X(1..n) and Y(1..n) contain two lists of integers, each sorted in nondecreasing order. Give an O(log n)-time algorithm to find the median (or the nth smallest integer) of all 2n combined elements.  For ex, X = (4, 5, 7, 8, 9) and Y = (3, 5, 8, 9, 10), then 7 is the median of the combined list (3, 4, 5, 5, 7, 8, 8, 9, 9, 10). [Hint: use concepts of binary search]

答: We call the time complexity O(log n), when the solution is based on iterations over n, where the work done in each iteration is a fraction of the previous iteration, as the algorithm works towards the solution. </p>


问:
Rating Stars in R shiny app
I am trying to add some elements to my shiny app to make it look better.
Therefore, I am using the new shiny.semantic package which allows to add semantic UI elements in an easy way.
One finds examples for shiny semantic elements here:
http://demo.appsilondatascience.com/shiny.semantic/components/

I wanted to add a rating stars UI with the following code:

```<code>library(shiny)
#devtools::install_github("Appsilon/shiny.semantic")
library(shiny.semantic)

ui <- function() {
  shinyUI(
    semanticPage(
      title = "My page",
      suppressDependencies("bootstrap"),
      div(class = "ui star rating")
    )
  )
}

server <- shinyServer(function(input, output) {
})

shinyApp(ui = ui(), server = server)
</code>```

Unfortunately, the rating stars are not appearing in the app. Is there another way to add such rating stars to shiny apps?

答:
You need to initialize with Javascript code

ui.R:

```<code>library(shiny)
library(shiny.semantic)

shinyUI(semanticPage(
  shinyjs::useShinyjs(),
  div(class = "ui star rating")
))
</code>```

server.R:

```<code>library(shiny)
library(shinyjs)
jsCode <- "
$('.ui.rating')
  .rating({
    initialRating: 3,
    maxRating: 5
  })
;
"

shinyServer(function(input, output) {
  runjs(jsCode)
})
</code>```

Title: Rating Stars in R shiny app

Body:
I am trying to add some elements to my shiny app to make it look better.
Therefore, I am using the new shiny.semantic package which allows to add semantic UI elements in an easy way.
One finds examples for shiny semantic elements here:
http://demo.appsilondatascience.com/shiny.semantic/components/

I wanted to add a rating stars UI with the following code:

library(shiny)
#devtools::install_github("Appsilon/shiny.semantic")
library(shiny.semantic)

ui <- function() {
  shinyUI(
    semanticPage(
      title = "My page",
      suppressDependencies("bootstrap"),
      div(class = "ui star rating")
    )
  )
}

server <- shinyServer(function(input, output) {
})

shinyApp(ui = ui(), server = server)

Unfortunately, the rating stars are not appearing in the app. Is there another way to add such rating stars to shiny apps?

Body:
You need to initialize with Javascript code

ui.R:

library(shiny)
library(shiny.semantic)

shinyUI(semanticPage(
  shinyjs::useShinyjs(),
  div(class = "ui star rating")
))

server.R:

library(shiny)
library(shinyjs)
jsCode <- "
$('.ui.rating')
  .rating({
    initialRating: 3,
    maxRating: 5
  })
;
"

shinyServer(function(input, output) {
  runjs(jsCode)
})


问:
Accessing non-static images in Django?
I don't want to store images in static for this Django project because the user will be able to change them from the admin panel.

My code looks like:

```<code><div class="col-md-3 col-sm-4 col-xs-6">
<img class="img-responsive" src="/galleryimg/first.jpg"/>
</div>
</code>```

Where /galleryimg/ is a folder in the root directory of the project, and "first.jpg" is the file that I want to serve.

However, this does not load. How can I get it to load?

答:
Use a django media url

In your setting.py file

```<code>MEDIA_URL = "/Media/"
MEDIA_PATH = "Media"
</code>```

In your urls.py file

```<code>from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [

]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
</code>```

Now create a Media folder in your root directory and then create galleryimg folder in Media folder.

Now use the following url in your template

```<code><div class="col-md-3 col-sm-4 col-xs-6">
<img class="img-responsive" src="/Media/galleryimg/first.jpg"/>
</div>
</code>```

Hope this helps you

Title: Accessing non-static images in Django?

Body:
I don't want to store images in static for this Django project because the user will be able to change them from the admin panel.

My code looks like:

Where /galleryimg/ is a folder in the root directory of the project, and "first.jpg" is the file that I want to serve.

However, this does not load. How can I get it to load?

Body:
Use a django media url

In your setting.py file

MEDIA_URL = "/Media/"
MEDIA_PATH = "Media"

In your urls.py file

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [

]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Now create a Media folder in your root directory and then create galleryimg folder in Media folder.

Now use the following url in your template

<div class="col-md-3 col-sm-4 col-xs-6">
<img class="img-responsive" src="/Media/galleryimg/first.jpg"/>
</div>

Hope this helps you


问:
how to communicate between labview and DM software
Hello，I need to use DM software to analyse a txt file and get numbers.Each number was send to a Labview software which controls the moving stage. Then Labview tells it's done then DM will take picture and save the files. So how can this be done？I found few samples with the DM script.Please give a direction.Thanks</p>

答:
There are not a lot of 'outward' or 'inward' communcition possibilities in current DigitalMicrograph and some options are only available in later GMS versions.
I also don't know the options Labview has, so you will need to find out what works and what doesn't. Suggestions are:

If you are using GMS 2.3 or later, you can use the command LaunchExternalProcess() to start any routine from within DigitalMicrograph the same way you would do from the command prompt.

If Labview allows to trigger some functionality by being called with parameters from the command prompt, this might be the easiest option. The DM-script will continue either when the launched process is finished, or after a specified time-out.

If you are using GMS 3.1 or later, you can do the oposite and have an outside program call DigitalMicrograph.exe with a command line parameter to trigger the start of a DM-script.

Essentially, this is the reverse of the first suggestion. Labview would need to "call" DigitalMicrograph whenever it wants the next action performed. I do not know Labview enough to judge if this is a possibility or not.

There are script commands for serial communication via the COM port (RS232) provided your installation has the SerialControl.dll in the plugin-folder.

If Labview supports this, you may be able to establish the inter-program communication using this. The serial communication script calls are not officially supported, but the commands are rather self-explanatory:

```<code>Number SPOpen( Number port, Number baud, Number stop, Number parity, Number data )
Number SPOpen( String prefix )
void SPClose( Number serialPortL )
Number SPSendString( Number serialPortL, String string )
Number SPSendHex( Number serialPortL, String string )
void SPFlushInput( Number serialPortL )
Number SPGetPendingBytes( Number serialPortL )
Number SPGetTime(  )
String SPReceiveString( Number serialPortL, Number maxLength, NumberVariable actual )
String SPReceiveHexString( Number serialPortL, Number maxLength, NumberVariable actual )
void SPSetRTS( Number serialPortL, Boolean on )
void SPSetDTR( Number serialPortL, Boolean on )
</code>```

You can also establish 'communication' with a workaround as suggested by Gelliant in his answer. A DM-script can 'monitor' a specific folder on the harddrive and trigger some action whenever a (specific) file in this folder gets created or modified.

If Labview is capable of something similiar, this "write-to-disk" and "watch-for-change" method can be used to have two programs work in synchronization with each other.

If Labview does not support this directly, you may be able to achieve a similar "hacked" synchronisation by using a 3rd party 'scripting' language for the general system. I've personally used a software called AutoIt in the past to synchronize otherwise incompatible software to controll hardware.

If you know C++ programming, you may get the "Software Development Kit (SDK)" for DigitalMicrograph and create your own Labview-communication plugin for DigitalMicrograph.

This option is of course the most versatile, as you're only limited by what you can achieve by your own C++ code. The disadvantage is, that you might need to recompile the plugin-DLL for different versions of DigitalMicrograph.

Body:
There are not a lot of 'outward' or 'inward' communcition possibilities in current DigitalMicrograph and some options are only available in later GMS versions.
I also don't know the options Labview has, so you will need to find out what works and what doesn't. Suggestions are:

If you are using GMS 2.3 or later, you can use the command LaunchExternalProcess() to start any routine from within DigitalMicrograph the same way you would do from the command prompt.

If Labview allows to trigger some functionality by being called with parameters from the command prompt, this might be the easiest option. The DM-script will continue either when the launched process is finished, or after a specified time-out.

If you are using GMS 3.1 or later, you can do the oposite and have an outside program call DigitalMicrograph.exe with a command line parameter to trigger the start of a DM-script.

Essentially, this is the reverse of the first suggestion. Labview would need to "call" DigitalMicrograph whenever it wants the next action performed. I do not know Labview enough to judge if this is a possibility or not.

There are script commands for serial communication via the COM port (RS232) provided your installation has the SerialControl.dll in the plugin-folder.

If Labview supports this, you may be able to establish the inter-program communication using this. The serial communication script calls are not officially supported, but the commands are rather self-explanatory:

Number SPOpen( Number port, Number baud, Number stop, Number parity, Number data )
Number SPOpen( String prefix )
void SPClose( Number serialPortL )
Number SPSendString( Number serialPortL, String string )
Number SPSendHex( Number serialPortL, String string )
void SPFlushInput( Number serialPortL )
Number SPGetPendingBytes( Number serialPortL )
Number SPGetTime(  )
String SPReceiveString( Number serialPortL, Number maxLength, NumberVariable actual )
String SPReceiveHexString( Number serialPortL, Number maxLength, NumberVariable actual )
void SPSetRTS( Number serialPortL, Boolean on )
void SPSetDTR( Number serialPortL, Boolean on )

You can also establish 'communication' with a workaround as suggested by Gelliant in his answer. A DM-script can 'monitor' a specific folder on the harddrive and trigger some action whenever a (specific) file in this folder gets created or modified.

If Labview is capable of something similiar, this "write-to-disk" and "watch-for-change" method can be used to have two programs work in synchronization with each other.

If Labview does not support this directly, you may be able to achieve a similar "hacked" synchronisation by using a 3rd party 'scripting' language for the general system. I've personally used a software called AutoIt in the past to synchronize otherwise incompatible software to controll hardware.

If you know C++ programming, you may get the "Software Development Kit (SDK)" for DigitalMicrograph and create your own Labview-communication plugin for DigitalMicrograph.

This option is of course the most versatile, as you're only limited by what you can achieve by your own C++ code. The disadvantage is, that you might need to recompile the plugin-DLL for different versions of DigitalMicrograph.


问:
Wrapper for template callback?

Immediate callback

Consider the following example:

```<code>template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    callback(42);
}

int main()
{
    call_me_back([](const int & value)
    {
        std :: cout << value << std :: endl;
    });
}
</code>```

Here I provide call_me_back with a lambda that accepts an int. call_me_back calls callback after some long calculation, and callback prints it out. Easy as cake.

Now, say that depending on the execution, call_me_back needs to call callback either with an int or with some other type. We can edit the previous example to

```<code>template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    if(rand() % 2)
        callback(42);
    else
        callback("Kill all the humans.");
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}
</code>```

So far so good. Now callback can do all sorts of tricks and handle value depending on its type.

Delayed callback

Now, back to the first example. Say that call_me_back is not ready to immediately call callback with an int. What it can do, however, is to store the callback somewhere, and then call it later.

For example:

```<code>std :: function <void(const int &)> the_callback;

template <typename lambda> void call_me_back(const lambda & callback)
{
    the_callback = callback;
}

void ready_to_answer()
{
    the_callback(42);
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}
</code>```

Now, instead of immediately calling callback, call_me_back stores callback in an std :: function <void(const int &)> object (I know, it's in the global scope, bear with me). Many things can then happen and at some point someone can call ready_to_answer, which retrieves the previously stored callback and calls it. For example, ready_to_answer can be called by another thread, but there is a whole lot of reasons why one would need a paradigm like this, where the callback can be stored and called later.

The problem

What if I wanted to implement the second example, but with a delayed callback?. I don't seem to be able to get my head around this.

I can imagine that std :: function is implemented with a virtual call operator that accepts some specific type. The std :: function then wraps a pointer / reference to a template wrapper class that stores the actual lambda and implements the call operator by forwarding its argument to the lambda it's storing. Nice and easy. But I can't have template virtual methods!

I have tried coming up with all sorts of solutions, but I couldn't find anything that could reasonably work. Is this really impossible to do? Is it impossible to have some externally provided lambda that accepts a const auto & argument stored somewhere, and then call it later?

答:
You could implement a class template that stores the lambda for you.

```<code>#include<iostream>

template<typename L>
struct Telephone
{
    L l;

    Telephone(L l) : l{std::move(l)} {}

    template<typename... Args>
    decltype(auto) ready_to_answer(Args&&... args)
    {
        return l(std::forward<Args>(args)...);
    }
};

template<typename L>
auto call_me_back(L&& l)
{
    return Telephone<std::decay_t<L>>(std::forward<L>(l));
}

int main()
{
    auto telephone = call_me_back([](auto x){ std::cout << x << std::endl; });
    telephone.ready_to_answer(42);
    telephone.ready_to_answer("Kill all the humans.");
}
</code>```

This has the downside that Telephone is templated on a lambda and will be a different type for each lambda.

If you know beforehand what the function signatures looks like, you could have Telephone inherit from a common base class and have virtual non-template methods.

Slap on some automatic construction and management of Telephone and you basically implemented another std::function but with custom signatures

```<code>struct Phone
{
    // all Telephone<L> inherits from Phone and have these methods

    virtual void ready_to_answer(int) = 0;
    virtual void ready_to_answer(const char*) = 0;
};

struct Spouse
{
    std::unique_ptr<Phone> phone;

    template<typename L>
    Spouse(L&& l) : phone{ new Telephone<std::decay_t<L>>{std::forward<L>(l)} } {}

    void ready_to_answer(int i) { phone->ready_to_answer(i); }
    void ready_to_answer(const char* str) { phone->ready_to_answer(str); }
};
</code>```

EDIT: I went ahead and implemented a buffed up version of std::function which accepts any number of signatures, so you could write

```<code>function<void (int), void (std::string)> callback =
    [](auto x){std::cout << x << std::endl;};

callback(42);
callback("Kill all humans!");
</code>```

Live

Suffice to say the implementation is not trivial and there is just a bit too much to explain here.

Title: Wrapper for template callback?

Body:
Immediate callback

Consider the following example:

template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    callback(42);
}

int main()
{
    call_me_back([](const int & value)
    {
        std :: cout << value << std :: endl;
    });
}

Here I provide call_me_back with a lambda that accepts an int. call_me_back calls callback after some long calculation, and callback prints it out. Easy as cake.

Now, say that depending on the execution, call_me_back needs to call callback either with an int or with some other type. We can edit the previous example to

template <typename lambda> void call_me_back(const lambda & callback)
{
    // Very complicated calculation to find the meaning of everything

    if(rand() % 2)
        callback(42);
    else
        callback("Kill all the humans.");
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}

So far so good. Now callback can do all sorts of tricks and handle value depending on its type.

Delayed callback

Now, back to the first example. Say that call_me_back is not ready to immediately call callback with an int. What it can do, however, is to store the callback somewhere, and then call it later.

For example:

std :: function <void(const int &)> the_callback;

template <typename lambda> void call_me_back(const lambda & callback)
{
    the_callback = callback;
}

void ready_to_answer()
{
    the_callback(42);
}

int main()
{
    call_me_back([](const auto & value)
    {
        std :: cout << value << std :: endl;
    });
}

Now, instead of immediately calling callback, call_me_back stores callback in an std :: function <void(const int &)> object (I know, it's in the global scope, bear with me). Many things can then happen and at some point someone can call ready_to_answer, which retrieves the previously stored callback and calls it. For example, ready_to_answer can be called by another thread, but there is a whole lot of reasons why one would need a paradigm like this, where the callback can be stored and called later.

The problem

What if I wanted to implement the second example, but with a delayed callback?. I don't seem to be able to get my head around this.

I can imagine that std :: function is implemented with a virtual call operator that accepts some specific type. The std :: function then wraps a pointer / reference to a template wrapper class that stores the actual lambda and implements the call operator by forwarding its argument to the lambda it's storing. Nice and easy. But I can't have template virtual methods!

I have tried coming up with all sorts of solutions, but I couldn't find anything that could reasonably work. Is this really impossible to do? Is it impossible to have some externally provided lambda that accepts a const auto & argument stored somewhere, and then call it later?

Body:
You could implement a class template that stores the lambda for you.

#include<iostream>

template<typename L>
struct Telephone
{
    L l;

    Telephone(L l) : l{std::move(l)} {}

    template<typename... Args>
    decltype(auto) ready_to_answer(Args&&... args)
    {
        return l(std::forward<Args>(args)...);
    }
};

template<typename L>
auto call_me_back(L&& l)
{
    return Telephone<std::decay_t<L>>(std::forward<L>(l));
}

int main()
{
    auto telephone = call_me_back([](auto x){ std::cout << x << std::endl; });
    telephone.ready_to_answer(42);
    telephone.ready_to_answer("Kill all the humans.");
}

This has the downside that Telephone is templated on a lambda and will be a different type for each lambda.

If you know beforehand what the function signatures looks like, you could have Telephone inherit from a common base class and have virtual non-template methods.

Slap on some automatic construction and management of Telephone and you basically implemented another std::function but with custom signatures

struct Phone
{
    // all Telephone<L> inherits from Phone and have these methods

    virtual void ready_to_answer(int) = 0;
    virtual void ready_to_answer(const char*) = 0;
};

struct Spouse
{
    std::unique_ptr<Phone> phone;

    template<typename L>
    Spouse(L&& l) : phone{ new Telephone<std::decay_t<L>>{std::forward<L>(l)} } {}

    void ready_to_answer(int i) { phone->ready_to_answer(i); }
    void ready_to_answer(const char* str) { phone->ready_to_answer(str); }
};

EDIT: I went ahead and implemented a buffed up version of std::function which accepts any number of signatures, so you could write

function<void (int), void (std::string)> callback =
    [](auto x){std::cout << x << std::endl;};

callback(42);
callback("Kill all humans!");

Live

Suffice to say the implementation is not trivial and there is just a bit too much to explain here.


问:
How to create real time order book since Poloniex exchange WAMP Api sequence number is not correlating with the sequence number got from the REST Api?
I am using C# WAMP client to connect to the Poloniex exchange to get the real time Market data.AS per the documentation provided by the exchange in order to create a real time order book we have to first get the snapshot of the order book through REST api provided by them and extract the sequence number from it and then connect to the WAMP server to get the streaming data and update the order book snapshot.

I have problem in updating the snapshot order book received through rest api since the sequence number which I received through the REST api is nearly 400k record ahead of the sequence number received through WAMP.

Is there any other way which I could get the real time Streaming data from the POloniex exchange or am I missing anything?

答:
I have the same problem. Seems they have some bug. What I have noticed is that there are different sequences sent in normal update messages and in "heartbeat" messages (the ones without payload). The documentation states that a heartbeat message should repeat the last normal message sequence number. But it differs. However it corresponds to a number returned by REST API. So seems that "works" for heartbeat messages and wrong for normal ones. Looks pretty much as a bug.

Here is also some related question.

UPD: Also checked "newTrade" events with trade history returned by the REST API. Trade IDs in WAMP are significantly lower than actual ones in a snapshot. Seems the events published via push API are outdated by several hours and that is the explanation of all this behaviour. So the push API is unusable now.

And finally, seems that current way to go is using their pure WebSocket API which is used by web-interface. It is located at wss://api2.poloniex.com. The only problem is lack of documentation. One way is reverse engineering the traffic of the web-interface. Some poor pieces of information although can be found in code snippets like this or in discussion here.


问:
Setting the selected attribute on a select list using jQuery
I have the following HTML:

```<code><select id="dropdown">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>
</code>```

I have the string "B" so I want to set the selected attribute on it so it will be:

```<code><select id="dropdown">
    <option>A</option>
    <option selected="selected">B</option>
    <option>C</option>
</select>
</code>```

How would I do this in jQuery?

答:
```<code><select id="cars">
<option value='volvo'>volvo</option>
<option value='bmw'>bmw</option>
<option value='fiat'>fiat</option>
</select>

var make = "fiat";

$("#cars option[value='" + make + "']").attr("selected","selected");
</code>```

Body:
I have the following HTML:

<select id="dropdown">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

I have the string "B" so I want to set the selected attribute on it so it will be:

<select id="dropdown">
    <option>A</option>
    <option selected="selected">B</option>
    <option>C</option>
</select>

How would I do this in jQuery?


问:
sql join with nullable data
I have a posts and users table, and I want that the following code will return a table with a post_count column, if a user has 0 posts it should still say 0, however the code below does not return all the users, only those have have posts.

```<code>SELECT users.*, COUNT(posts.id) post_count
FROM `posts`
JOIN  `users` ON `posts`.`user_id` = `users`.`id`
GROUP BY(posts.user_id)
ORDER BY `users`.`id`
</code>```

答:
In sql you need to use a left join for this:

```<code>SELECT users.*, COUNT(posts.user_id) post_count
FROM users
LEFT JOIN  posts ON posts.user_id = users.id
GROUP BY(users.id)
ORDER BY users.id
</code>```

A left join will include all items in the user table and only the records in the posts table that exist.

Title: sql join with nullable data

Body:
I have a posts and users table, and I want that the following code will return a table with a post_count column, if a user has 0 posts it should still say 0, however the code below does not return all the users, only those have have posts.

SELECT users.*, COUNT(posts.id) post_count
FROM `posts`
JOIN  `users` ON `posts`.`user_id` = `users`.`id`
GROUP BY(posts.user_id)
ORDER BY `users`.`id`

Body:
In sql you need to use a left join for this:

SELECT users.*, COUNT(posts.user_id) post_count
FROM users
LEFT JOIN  posts ON posts.user_id = users.id
GROUP BY(users.id)
ORDER BY users.id

A left join will include all items in the user table and only the records in the posts table that exist.


问:
AppIcon will showed twice on device with Android App
When i install my android application on the device, the AppIcon will appear twice.

This means: there are two separate app-icons. Both icons launch the same app version. If I remove one app-icon, the other disappears also. If i reinstall them, it appears twice again.

How can i avoid this?

This is my AndroidManifest.xml:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.******"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <application
      android:name=".MainApplication"
      android:allowBackup="true"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:theme="@style/AppTheme">

        <meta-data android:name="com.bugsnag.android.API_KEY"
             android:value="524b0194108e90ae383189e509746766"/>

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

        <activity
            android:name=".SplashActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>
</code>```

答:
It's because of the intent-filter. Only one activity should have

```<code><intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</code>```

Any activity having this intent filter will be shown in the launcher.

Body:
When i install my android application on the device, the AppIcon will appear twice.

This means: there are two separate app-icons. Both icons launch the same app version. If I remove one app-icon, the other disappears also. If i reinstall them, it appears twice again.

How can i avoid this?

This is my AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.******"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <application
      android:name=".MainApplication"
      android:allowBackup="true"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:theme="@style/AppTheme">

        <meta-data android:name="com.bugsnag.android.API_KEY"
             android:value="524b0194108e90ae383189e509746766"/>

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

        <activity
            android:name=".SplashActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Body:
It's because of the intent-filter. Only one activity should have

<intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Any activity having this intent filter will be shown in the launcher.


问:
Text alignment changes on exporting d3js chart svg as png using html2canvas
I've created circle pack chart using D3js version 3 and following is the snapshot of the chart.

I'm trying to export it using html2canvas using following code:

```<code>html2canvas(document.getElementById("chart"), {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  }
});
</code>```

Here, chart is the id of div element that holds the chart svg which I'm trying to export as png. The above code works fine and successfully returns the png image but the alignment and font setting of the text which is inside the svg changes as in following snapshot.

Can anyone please suggest me how can I export chart image as png with the same text settings.

Please also note that I've used the following js files for this.

d3.v3.js

html2canvas.js

html2canvas.svg.js

Thanks in advance.

Bhagyesh

答: You're probably setting styles in css which htm2canvas doesn't have access to and therefore doesn't apply. If you set everything as attributes of the svg instead, it should work.</p>

Body:
I've created circle pack chart using D3js version 3 and following is the snapshot of the chart.

I'm trying to export it using html2canvas using following code:

html2canvas(document.getElementById("chart"), {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  }
});

Here, chart is the id of div element that holds the chart svg which I'm trying to export as png. The above code works fine and successfully returns the png image but the alignment and font setting of the text which is inside the svg changes as in following snapshot.

Can anyone please suggest me how can I export chart image as png with the same text settings.

Please also note that I've used the following js files for this.

d3.v3.js

html2canvas.js

html2canvas.svg.js

Thanks in advance.

Bhagyesh


答:
You were almost there. First of all, I advice You to use boolean values for checkboxes data models. Array evaluates to true so checkbox is still checked. If you reference instance properties, You should reference them by using word this. So the method onKey() should be :

```<code>onKey() {
 this.checkbox = false
}
</code>```

plunker

Title: Uncheck checkbox on text input & clear text input when checkbox is checked

Body:
You were almost there. First of all, I advice You to use boolean values for checkboxes data models. Array evaluates to true so checkbox is still checked. If you reference instance properties, You should reference them by using word this. So the method onKey() should be :

onKey() {
 this.checkbox = false
}

plunker


问:
Offline XML Validation with Java
I need to figure out how to validate my XML files with schema's offline. After looking around for a couple of days, what I was able to find was basically that I needed to have an internal reference to the schema. I needed to find them, download them, and change the reference to a local system path. What I was unable to find was exactly how to do that. Where and how can I change the reference to point internally instead of externally? What is the best way to download the schemas?</p>

答:
There are three ways you could do this. What they all have in common is that you need a local copy of the schema document(s). I'm assuming that the instance documents currently use xsi:schemaLocation and/or xsi:noNamespaceSchemaLocation to point to a location holding the schema document(s) on the web.

(a) Modify your instance documents to refer to the local copy of the schema documents. This is usually inconvenient.

(b) Redirect the references so that a request for a remote file is redirected to a local file. The way to set this up depends on which schema validator you are using and how you are invoking it.

(c) Tell the schema processor to ignore the values of xsi:schemaLocation and xsi:noNamespaceSchemaLocation, and to validate instead against a schema that you supply using your schema processor's invocation API. Again the details depend on which schema processor you are using.

My preferred approach is (c): if only because when you are validating a source document, then by definition you don't fully trust it - so why should you trust it to contain a correct xsi:schemaLocation attribute?

Title: Offline XML Validation with Java


问:
How can I Cut and Paste PivotTable?
I have a PevoteTable in data source worksheet, So I want move that PivotTable in appropriate situation.

What is a PivotTable Range for using code Sheets("SheetName").Range("PivotTableRange").Cut or what is the better method?

答:
You can use the TableRange2 object of the PivotTable, see step-by-step code below:

```<code>Dim Sht As Worksheet
Dim PvtTbl As PivotTable
Dim PvtRng As Range

' set the Sheet object where the Pivot Table lies
Set Sht = Worksheets("SheetName")

' set the Pivot-Table object
Set PvtTbl = Sht.PivotTables("PivotTableName")

' set the Pivot-Table range you want to copy
Set PvtRng = PvtTbl.TableRange2

' copy the Range
PvtRng.Copy
</code>```

Title: How can I Cut and Paste PivotTable?

Body:
You can use the TableRange2 object of the PivotTable, see step-by-step code below:

Dim Sht As Worksheet
Dim PvtTbl As PivotTable
Dim PvtRng As Range

' set the Sheet object where the Pivot Table lies
Set Sht = Worksheets("SheetName")

' set the Pivot-Table object
Set PvtTbl = Sht.PivotTables("PivotTableName")

' set the Pivot-Table range you want to copy
Set PvtRng = PvtTbl.TableRange2

' copy the Range
PvtRng.Copy


问:
Converting UTC to EST in Swift
I have a string of text in my application that conveys a time and the date, such as let time = "2017-07-09T09:17:08+00:00". I want to take this string, which is in UTC, and convert it to a string that presents the time in EST. For my example, the resulting string would be 2017-07-09T05:17:08+00:00. How can this be done?

I've tried using

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone.current
let date = dateFormatter.date(from:time!)!
</code>```

but printing the date gives me the same time in UTC.

答:
All you need to do is to use a DateFormatter to convert your Date object into a String. By default, the date will be formatted to local time.

```<code>// First, get a Date from the String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:time!)!

// Now, get a new string from the Date in the proper format for the user's locale
dateFormatter.dateFormat = nil
dateFormatter.dateStyle = .long // set as desired
dateFormatter.timeStyle = .medium // set as desired
let local = dateFormatter.string(from: date)
</code>```

Note that there is no need to set any timezone for either set of code in this case.

Title: Converting UTC to EST in Swift

Body:
I have a string of text in my application that conveys a time and the date, such as let time = "2017-07-09T09:17:08+00:00". I want to take this string, which is in UTC, and convert it to a string that presents the time in EST. For my example, the resulting string would be 2017-07-09T05:17:08+00:00. How can this be done?

I've tried using

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone.current
let date = dateFormatter.date(from:time!)!

but printing the date gives me the same time in UTC.

Body:
All you need to do is to use a DateFormatter to convert your Date object into a String. By default, the date will be formatted to local time.

// First, get a Date from the String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:time!)!

// Now, get a new string from the Date in the proper format for the user's locale
dateFormatter.dateFormat = nil
dateFormatter.dateStyle = .long // set as desired
dateFormatter.timeStyle = .medium // set as desired
let local = dateFormatter.string(from: date)

Note that there is no need to set any timezone for either set of code in this case.


问:
jQuery animation if load() returns something different
```<code>setInterval(function() {
                var prevTopArticle = $("#toparticles table:first").html();
                  $("#toparticles").load("myurloffeed.com/topfeed", function()
                   {
                       alternateBG();
                       var newTopArticle = $("#toparticles table:first").html();
                            if (prevTopArticle!=newTopArticle)
                                {
                                     $("#toparticles table:first").effect("highlight", {color:"#faffc4"}, 2000);
                                }
                  });
                }, 8000);
</code>```

So it sets the current first table item to a variable, loads the toparticles div with the tables off the url, and if they are different it will perform the highlight effect, however it does the highlight effect anyway, completely unsure why it isn't working.

答: For some reason one of the articles was outputting a twitter link and the other wasn't, thought the feeds were the same. Figured it out using console.log of the two variables.</p>

Body:
setInterval(function() {
                var prevTopArticle = $("#toparticles table:first").html();
                  $("#toparticles").load("myurloffeed.com/topfeed", function()
                   {
                       alternateBG();
                       var newTopArticle = $("#toparticles table:first").html();
                            if (prevTopArticle!=newTopArticle)
                                {
                                     $("#toparticles table:first").effect("highlight", {color:"#faffc4"}, 2000);
                                }
                  });
                }, 8000);

So it sets the current first table item to a variable, loads the toparticles div with the tables off the url, and if they are different it will perform the highlight effect, however it does the highlight effect anyway, completely unsure why it isn't working.