问:
How to launch a program from bash script, then close Terminal but keep the program alive
I wanted to have an icon in my desktop to start Redshift with a custom parameter which is read from the command line upon launching.

This is what I came up with:

#!/bin/bash
default_temperature=4500
echo "Default color temperature (Night) is "$default_temperature"K."
read -p "Type in the desired value: " temperature
temperature=${temperature:-$default_temperature}
nohup redshift-gtk -l "-23.9141:-147.6650" -t "6500:"$temperature &
```

<p>The above file is saved as <code>/home/redshift.sh</code>. I also created a desktop entry to launch it, with the following code:</p>

<pre class="lang-none prettyprint-override"><code>#!/usr/bin/env xdg-open
[Desktop Entry]
Name=Redshift (script)
Comment=Custom script to start Redshift with color temperature input
Exec="/home/redshift.sh"
Icon=redshift
Terminal=true
Type=Application
</code>```

(the first line was added automatically).

The expected behaviour is:

User double-clicks the desktop entry

Console opens and asks for (optional) input

Upon user pressing Enter, the script should launch the application named redshift-gtk (which is actually a Python script located at /usr/bin), with the specified arguments.

For now I don't care about checking whether the input is valid, nor if the process is already running.

An example of the (working) command would be:

redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400"
```

<p>And for the moment, I even simplified the launch script to simply this</p>

<pre class="lang-sh prettyprint-override"><code>nohup redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" &
</code>```

And even tried

nohup redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" && exit
```

But none of these closes the Terminal window, it will just keep remain open. If I close it manually, the Redshift process is killed (and this is obviosly not desired).

Tried a number of possible solutions found online, none seems to work. Didn't find anything relevant here in SO.

Just how to do it properly?

Thanks

答:
The way I would recommend doing this would be via screen. It allows you to start processes from a virtual terminal, then detach from it, exit Terminal and then come back later and reattach to it (if the session still exists). For example:

```<code>screen -d -m redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400"
</code>```

Would launch the command in "detached mode" and then you could exit Terminal. If you wanted to check on the session when returning to Terminal you could do:

```<code>screen -list
</code>```

Typical output looks something like this:

```<code>There is a screen on:
    58643..System(Detached)
1 Socket in /var/folders/qg/jxb2db8d2_57nrtq5vs0xcfw0000gn/T/.screen.
</code>```

Check the man page for screen — lots of helpful info there.

Body:
I wanted to have an icon in my desktop to start Redshift with a custom parameter which is read from the command line upon launching.

This is what I came up with:

#!/bin/bash
default_temperature=4500
echo "Default color temperature (Night) is "$default_temperature"K."
read -p "Type in the desired value: " temperature
temperature=${temperature:-$default_temperature}
nohup redshift-gtk -l "-23.9141:-147.6650" -t "6500:"$temperature &

The above file is saved as /home/redshift.sh. I also created a desktop entry to launch it, with the following code:

#!/usr/bin/env xdg-open
[Desktop Entry]
Name=Redshift (script)
Comment=Custom script to start Redshift with color temperature input
Exec="/home/redshift.sh"
Icon=redshift
Terminal=true
Type=Application

(the first line was added automatically).

The expected behaviour is:

User double-clicks the desktop entry

Console opens and asks for (optional) input

Upon user pressing Enter, the script should launch the application named redshift-gtk (which is actually a Python script located at /usr/bin), with the specified arguments.

For now I don't care about checking whether the input is valid, nor if the process is already running.

An example of the (working) command would be:

redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400"

And for the moment, I even simplified the launch script to simply this

nohup redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" &

And even tried

nohup redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" && exit

But none of these closes the Terminal window, it will just keep remain open. If I close it manually, the Redshift process is killed (and this is obviosly not desired).

Tried a number of possible solutions found online, none seems to work. Didn't find anything relevant here in SO.

Just how to do it properly?

Thanks

Body:
The way I would recommend doing this would be via screen. It allows you to start processes from a virtual terminal, then detach from it, exit Terminal and then come back later and reattach to it (if the session still exists). For example:

screen -d -m redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400"

Would launch the command in "detached mode" and then you could exit Terminal. If you wanted to check on the session when returning to Terminal you could do:

screen -list

Typical output looks something like this:

There is a screen on:
    58643..System(Detached)
1 Socket in /var/folders/qg/jxb2db8d2_57nrtq5vs0xcfw0000gn/T/.screen.

Check the man page for screen — lots of helpful info there.


来源: stackexchange

问:
Check if the word is in the db and if it is, just create the definition for it
I have a dictionary app, where word has many definitions, and definition belongs to word. This is my Word model.

```<code>class Word < ApplicationRecord

belongs_to :user
has_many :definitions, dependent: :destroy

accepts_nested_attributes_for :definitions

self.per_page = 4

end
</code>```

My words_controller

```<code>class WordsController < ApplicationController
 before_action :set_word, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user!

# GET /words
# GET /words.json

def index
 @words = Word.all.order('created_at DESC').paginate(:page =>
 params[:page])
end

# GET /words/1
# GET /words/1.json
def show
 @definitions = @word.definitions.order(cached_votes_up: :desc,
 created_at: :desc)
end

# GET /words/new
def new
 @word = Word.new
end

def all_new

 @word = Word.new
 1.times { @word.definitions.build }
 @words = Word.all

end

# GET /words/1/edit
def edit
end

# POST /words
# POST /words.json
def create

 @word = Word.find_or_create_by(word: word_params[:word]) do |word|
  word.definition.attributes = word_params[:definition_attributes]
 end

 @word.user_id = current_user.id

 @word.definitions.each  {|definition| definition.user_id =
 current_user.id }

respond_to do |format|
  if Word.where(word: word_params[:word]).present?
    format.html { redirect_to root_path, notice: 'Word already exists.'
}
  elsif @word.save
    format.html { redirect_to root_path, notice: 'Word was successfully
created.' }
    format.json { render :show, status: :created, location: @word }
  else
    format.html { render :new }
    format.json { render json: @word.errors, status:
:unprocessable_entity }
  end
end
end

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

# DELETE /words/1
# DELETE /words/1.json
def destroy
@word.destroy
respond_to do |format|
  format.html { redirect_to words_url, notice: 'Word was successfully
destroyed.' }
  format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_word
  @word = Word.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white
list through.
def word_params
  params.require(:word).permit(:word, definitions_attributes:
[:definition, :URL])
end
end
</code>```

How do I rewrite this code to have it check whether the word exists. If it doesn’t, create word or word and definition (this part works); if it does, create only the definition to existing word (this part doesn’t work). I ran the Rails.logger.debug and it seems like the block doesn’t even execute. Obviously, find_or_create_by isn't the right method to use here.

```<code>This is my form
<%= form_for @word do |form| %>

<% if word.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(word.errors.count, "error") %> prohibited this word
from being saved:</h2>

  <ul>
  <% word.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
</div>
<% end %>

<div class="form-group upper-margin">
 <%= form.text_field :word, id: :word_word, class: "form-control",
 placeholder: "Word" %>
</div>

<%= form.fields_for :definitions do |definition| %>

 <div class="form-group">

  <button type="button" id="ShiftButton" class="btn btn-secondary form-
control" >I don't know the definition!</button>

  <%= definition.text_field :definition, class: "form-control
definition", placeholder: "Definition", id: "chartdiv"%>

 </div>

<% end %>

<div class="form-group">
 <%= form.submit class: "btn btn-secondary form-control" %>
</div>

<% end %>
</code>```

答:
```<code>@word = Word.find_or_create_by(word_params[:word])
@word.definitions.create(word_params[:definitions_attributes])
</code>```

Though you may end up with duplicate definitions since you really define no way to make a definition "unique"

ContentLicense: CC BY-SA 3.0

Body:
I have a dictionary app, where word has many definitions, and definition belongs to word. This is my Word model.

class Word < ApplicationRecord

belongs_to :user
has_many :definitions, dependent: :destroy

accepts_nested_attributes_for :definitions

self.per_page = 4

end

My words_controller

class WordsController < ApplicationController
 before_action :set_word, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user!

# GET /words
# GET /words.json

def index
 @words = Word.all.order('created_at DESC').paginate(:page =>
 params[:page])
end

# GET /words/1
# GET /words/1.json
def show
 @definitions = @word.definitions.order(cached_votes_up: :desc,
 created_at: :desc)
end

# GET /words/new
def new
 @word = Word.new
end

def all_new

 @word = Word.new
 1.times { @word.definitions.build }
 @words = Word.all

end

# GET /words/1/edit
def edit
end

# POST /words
# POST /words.json
def create

 @word = Word.find_or_create_by(word: word_params[:word]) do |word|
  word.definition.attributes = word_params[:definition_attributes]
 end

 @word.user_id = current_user.id

 @word.definitions.each  {|definition| definition.user_id =
 current_user.id }

respond_to do |format|
  if Word.where(word: word_params[:word]).present?
    format.html { redirect_to root_path, notice: 'Word already exists.'
}
  elsif @word.save
    format.html { redirect_to root_path, notice: 'Word was successfully
created.' }
    format.json { render :show, status: :created, location: @word }
  else
    format.html { render :new }
    format.json { render json: @word.errors, status:
:unprocessable_entity }
  end
end
end

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

# DELETE /words/1
# DELETE /words/1.json
def destroy
@word.destroy
respond_to do |format|
  format.html { redirect_to words_url, notice: 'Word was successfully
destroyed.' }
  format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_word
  @word = Word.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white
list through.
def word_params
  params.require(:word).permit(:word, definitions_attributes:
[:definition, :URL])
end
end

How do I rewrite this code to have it check whether the word exists. If it doesn’t, create word or word and definition (this part works); if it does, create only the definition to existing word (this part doesn’t work). I ran the Rails.logger.debug and it seems like the block doesn’t even execute. Obviously, find_or_create_by isn't the right method to use here.

This is my form
<%= form_for @word do |form| %>

<% if word.errors.any? %>

<%= pluralize(word.errors.count, "error") %> prohibited this word
from being saved:

  <% word.errors.full_messages.each do |message| %>

<%= message %>

  <% end %>

<% end %>

 <%= form.text_field :word, id: :word_word, class: "form-control",
 placeholder: "Word" %>

<%= form.fields_for :definitions do |definition| %>

  <button type="button" id="ShiftButton" class="btn btn-secondary form-
control" >I don't know the definition!</button>

  <%= definition.text_field :definition, class: "form-control
definition", placeholder: "Definition", id: "chartdiv"%>

<% end %>

 <%= form.submit class: "btn btn-secondary form-control" %>

<% end %>

Body:
@word = Word.find_or_create_by(word_params[:word])
@word.definitions.create(word_params[:definitions_attributes])

Though you may end up with duplicate definitions since you really define no way to make a definition "unique"


问:
Zipfile Method doesn't works
I create a zip file with rockyou password and I tried to extractall files. But I got some issues. Doesn't matter how password I put in extractall always I will get:

```<code>('Bad password for file', <zipfile.ZipInfo object at 0x7f7928d14dc8>)
</code>```

Code:

```<code>import zipfile

zfile = zipfile.ZipFile("./rockyou.zip")

pss = b"rockyou"

try:
    zfile.extractall(pwd = pss)

except RuntimeError as e:
    print(e)
    zfile.close()
</code>```

If I pass a string I got another issue:

```<code>TypeError: pwd: expected bytes, got <class 'str'>
</code>```

And I tried too:

```<code>pss = str.encode("rockyou")
</code>```

And:

```<code>pss = bytes(str.encode("rockyou"))
</code>```

And:

```<code>pss = bytes("rockyou".encode("UTF-8"))
</code>```

答:
I've been following the violent python book and in Chapter one you make a mini script to unlock a encrypted zip file. what worked for me was to add a b so the string would be in bytes:

```<code>import zipfile
zFile = zipfile.ZipFile("evil.zip")
zFile.extractall(pwd=b'secret') #this is what i'm talking about
</code>```

ContentLicense: CC BY-SA 4.0

Title: Zipfile Method doesn't works

Body:
I create a zip file with rockyou password and I tried to extractall files. But I got some issues. Doesn't matter how password I put in extractall always I will get:

('Bad password for file', <zipfile.ZipInfo object at 0x7f7928d14dc8>)

Code:

import zipfile

zfile = zipfile.ZipFile("./rockyou.zip")

pss = b"rockyou"

try:
    zfile.extractall(pwd = pss)

except RuntimeError as e:
    print(e)
    zfile.close()

If I pass a string I got another issue:

TypeError: pwd: expected bytes, got <class 'str'>

And I tried too:

pss = str.encode("rockyou")

And:

pss = bytes(str.encode("rockyou"))

And:

pss = bytes("rockyou".encode("UTF-8"))

Body:
I've been following the violent python book and in Chapter one you make a mini script to unlock a encrypted zip file. what worked for me was to add a b so the string would be in bytes:

import zipfile
zFile = zipfile.ZipFile("evil.zip")
zFile.extractall(pwd=b'secret') #this is what i'm talking about


问:
C++ - stat(), access() not working under gnu gcc
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

```<code>#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

I have also tried the access version:

```<code>#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

Neither of them find my folder (which is right there in the same directory as the program).  These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps.  I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory.  The updated, working program is as follows:

```<code>#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.

答: Check your PWD when you running your program. This problem is not caused by compiler. You DevCpp may set a working directory for your program automatically. </p>

Body:
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

I have also tried the access version:

#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

Neither of them find my folder (which is right there in the same directory as the program).  These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps.  I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory.  The updated, working program is as follows:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.

ContentLicense: CC BY-SA 2.5


问:
Rails 5.1.: destroy records in "has_many: through" association with restriction
I have classic has_many: through relationship:

```<code>class UserGroup < ApplicationRecord
  has_many :user_groups_users
  has_many :users, through: :user_groups_users
end

class UserGroupsUser < ApplicationRecord
  belongs_to :user_group
  belongs_to :user
end

class User < ApplicationRecord
  has_many :user_groups_users
  has_many :user_groups, through: :user_groups_users
end
</code>```

and in order to destroy UserGroup record, I need to destroy appropriate records in UserGroupsUser, which both is part of a gem. Otherwise I will get back error that there are Users tied to UserGroups and I cannot destroy particular UserGroup.

At the moment in my Controller I have this:

```<code>  def destroy
    @user_group = UserGroup.find(params[:id])
    UserGroupsUser.where(user_group_id: @user_group).destroy_all
    respond_to do |format|
    if @user_group.destroy
      format.js { flash.now[:notice] = "User group #{@user_group.name} deleted!" }
      format.html { redirect_to user_groups_url }
      format.json { head :no_content }
    else
      format.js { flash[:danger] = "User group #{@user_group.name} cannot be deleted because
                                   #{@user_group.users.size} users belong to it" }
    end
    end
  end
</code>```

however when I click Delete button in View, it destroys a record before I accept that in my modal window. How do I make it do destroy action, after accept in view, please? As I undestand it would require that after accept, it would firs destroy records in through models and then UserGroup.

My "Delete" action in View is quite regular:

```<code><%= link_to 'Delete', user_group, method: :delete, remote: true,
data: { confirm: "Do you confirm deleting #{user_group.name}?" }, class: 'btn-danger btn btn-xs' %>
</code>```

答:
To simplify the whole thing, you could just add a before_destroy callback to your UserGroup. It'll only execute when you run @user_group.destroy

```<code>class UserGroup < ApplicationRecord
  has_many :user_groups_users
  has_many :users, through: :user_groups_users

  before_destroy do
    user_groups_users.destroy_all
  end
end
</code>```

Read ActiveRecord Callbacks

Body:
I have classic has_many: through relationship:

class UserGroup < ApplicationRecord
  has_many :user_groups_users
  has_many :users, through: :user_groups_users
end

class UserGroupsUser < ApplicationRecord
  belongs_to :user_group
  belongs_to :user
end

class User < ApplicationRecord
  has_many :user_groups_users
  has_many :user_groups, through: :user_groups_users
end

and in order to destroy UserGroup record, I need to destroy appropriate records in UserGroupsUser, which both is part of a gem. Otherwise I will get back error that there are Users tied to UserGroups and I cannot destroy particular UserGroup.

At the moment in my Controller I have this:

  def destroy
    @user_group = UserGroup.find(params[:id])
    UserGroupsUser.where(user_group_id: @user_group).destroy_all
    respond_to do |format|
    if @user_group.destroy
      format.js { flash.now[:notice] = "User group #{@user_group.name} deleted!" }
      format.html { redirect_to user_groups_url }
      format.json { head :no_content }
    else
      format.js { flash[:danger] = "User group #{@user_group.name} cannot be deleted because
                                   #{@user_group.users.size} users belong to it" }
    end
    end
  end

however when I click Delete button in View, it destroys a record before I accept that in my modal window. How do I make it do destroy action, after accept in view, please? As I undestand it would require that after accept, it would firs destroy records in through models and then UserGroup.

My "Delete" action in View is quite regular:

<%= link_to 'Delete', user_group, method: :delete, remote: true,
data: { confirm: "Do you confirm deleting #{user_group.name}?" }, class: 'btn-danger btn btn-xs' %>

Body:
To simplify the whole thing, you could just add a before_destroy callback to your UserGroup. It'll only execute when you run @user_group.destroy

class UserGroup < ApplicationRecord
  has_many :user_groups_users
  has_many :users, through: :user_groups_users

  before_destroy do
    user_groups_users.destroy_all
  end
end

Read ActiveRecord Callbacks


问:
unique_ptr trouble? (VS 2015)
I’ve just copied some code from here http://en.cppreference.com/w/cpp/language/pimpl, added <memory> and main.cpp, corrected std::experimental::propagate_const<std::unique_ptr<impl>>. Visual Studio 2015.

```<code>// widget.h
#include <memory>

class widget
{
    // public members
private:
    struct impl;
    std::unique_ptr<impl> pImpl;
};
</code>```

.

```<code>// widget.cpp
#include "widget.h"

struct widget::impl {
    // implementation details
};
</code>```

widget.cpp is compiled fine, but main.cpp is not.

```<code>#include "widget.h"

int main()
{
    widget w;
}
</code>```

Error messages.

```<code>1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1193): error C2027: use of undefined type 'widget::impl'
1>  e:\***\***\***\widget.h(8): note: see declaration of 'widget::impl'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1192): note: while compiling class template member function 'void std::default_delete<_Ty>::operator ()(_Ty *) noexcept const'
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1397): note: see reference to function template instantiation 'void std::default_delete<_Ty>::operator ()(_Ty *) noexcept const' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1227): note: see reference to class template instantiation 'std::default_delete<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1236): note: see reference to class template instantiation 'std::_Get_deleter_pointer_type<_Ty,std::default_delete<_Ty>>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1279): note: see reference to class template instantiation 'std::_Unique_ptr_base<_Ty,_Dx>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl,
1>              _Dx=std::default_delete<widget::impl>
1>          ]
1>  e:\***\***\***\***.h(10): note: see reference to class template instantiation 'std::unique_ptr<widget::impl,std::default_delete<_Ty>>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1194): error C2338: can't delete an incomplete type
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1195): warning C4150: deletion of pointer to incomplete type 'widget::impl'; no destructor called
1>  e:\***\***\***\widget.h(8): note: see declaration of 'widget::impl'
</code>```

答:
The problem is that std::unique_ptr has a deleter associated with it. When no deleter is specified it defaults to std::default_delete.

And what does it do? It calls delete on it, which requires destructor to be defined at that point. And that requires a definition there.

Title: unique_ptr trouble? (VS 2015)

Body:
I’ve just copied some code from here http://en.cppreference.com/w/cpp/language/pimpl, added <memory> and main.cpp, corrected std::experimental::propagate_const<std::unique_ptr<impl>>. Visual Studio 2015.

// widget.h
#include <memory>

class widget
{
    // public members
private:
    struct impl;
    std::unique_ptr<impl> pImpl;
};

.

// widget.cpp
#include "widget.h"

struct widget::impl {
    // implementation details
};

widget.cpp is compiled fine, but main.cpp is not.

#include "widget.h"

int main()
{
    widget w;
}

Error messages.

1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1193): error C2027: use of undefined type 'widget::impl'
1>  e:\***\***\***\widget.h(8): note: see declaration of 'widget::impl'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1192): note: while compiling class template member function 'void std::default_delete<_Ty>::operator ()(_Ty *) noexcept const'
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1397): note: see reference to function template instantiation 'void std::default_delete<_Ty>::operator ()(_Ty *) noexcept const' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1227): note: see reference to class template instantiation 'std::default_delete<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1236): note: see reference to class template instantiation 'std::_Get_deleter_pointer_type<_Ty,std::default_delete<_Ty>>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1279): note: see reference to class template instantiation 'std::_Unique_ptr_base<_Ty,_Dx>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl,
1>              _Dx=std::default_delete<widget::impl>
1>          ]
1>  e:\***\***\***\***.h(10): note: see reference to class template instantiation 'std::unique_ptr<widget::impl,std::default_delete<_Ty>>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1194): error C2338: can't delete an incomplete type
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1195): warning C4150: deletion of pointer to incomplete type 'widget::impl'; no destructor called
1>  e:\***\***\***\widget.h(8): note: see declaration of 'widget::impl'


问:
Composer install laravel every-time when I create new project
Each and everytime I want to create new project through this command

composer laravel/laravel_project project_name

composer starts to install everything form scratch .

Did I do anything wrong ?

Also, If I copy the framework from another project  that's the same as installing through the above command , right? [copying everything before doing anything to that directory]

答:
Also, If I copy the framework from another project that's the same as installing through the above command , right?

Yes, but I won't recommend it because the app key will be copied too so both projects will generate the same hashes. This can be good if the 2 apps should have access to the same database tables, but in most cases they should not.

If you use the compose command, compose will download all packages and won't cache them. A better approach would be the use of the laravel installer: composer global require "laravel/installer". It caches the packages you need for a project so it will be installed faster.


问:
How to/best practice on how to differentiate between serialised objects stored within JSON format?
Suppose that I serialise two different objects and save them to a directory.

Problem: Upon application start up, parsing the JSON files are not a problem - since GSON is employed, I can write my own serialisers and  deserialisers for both of the JSON files for their respective objects to be constructed.

But the problem is, how can I differentiate between the numerous JSON files in terms of what they store within them, so I can apply the correct deserialiser to it.

Thank you, best.

答:
Consider standardizing your JSON structure to include document type. You can even store the target object type in that field. Good practice is to include document version number as well. Example below shows two different versions of the 'account' document and a transaction document. All three can be stored in, say, the same Couchbase bucket. The way to differentiate between different documents would be to look at the "doc_type" field and the document version (if required). From the GSON serializer selection standpoint, you can look at at the "doc_type" in a switch/if-else statement or store the target object type in place of "account" or "transaction" and then, at the expense of performance, dynamically parse JSON to POJO.

```<code>{
  "doc_type": "account",
  "doc_ver": 1,
  "content": {
    "accnt_no": "12321645645484",
    "name": "Name or alias",
    "email": "Email address",
    "password": "Password in raw format",
    "exp_date": "06/10/2017"
  }
}

{
  "doc_type": "account",
  "doc_ver": 2,
  "content": {
    "accnt_no": "12321645645484",
    "name": "customer name",
    "email": "customer email",
    "password": "pass",
    "timezone": "customer timezone",
    "ip": "IP address",
    "spoken_languages": [ "EN", "RU" ],
    "exp_date": "06/10/2017"
  }
}

{
  "doc_type": "transaction",
  "doc_ver": 1,
  "content": {
    "accnt_no": "12321645645484",
    "tran_date": "06/04/2017",
    "tran_time":  "09:15:84.953"
  }
}
</code>```

Hope this helps.

Body:
Consider standardizing your JSON structure to include document type. You can even store the target object type in that field. Good practice is to include document version number as well. Example below shows two different versions of the 'account' document and a transaction document. All three can be stored in, say, the same Couchbase bucket. The way to differentiate between different documents would be to look at the "doc_type" field and the document version (if required). From the GSON serializer selection standpoint, you can look at at the "doc_type" in a switch/if-else statement or store the target object type in place of "account" or "transaction" and then, at the expense of performance, dynamically parse JSON to POJO.

{
  "doc_type": "account",
  "doc_ver": 1,
  "content": {
    "accnt_no": "12321645645484",
    "name": "Name or alias",
    "email": "Email address",
    "password": "Password in raw format",
    "exp_date": "06/10/2017"
  }
}

{
  "doc_type": "account",
  "doc_ver": 2,
  "content": {
    "accnt_no": "12321645645484",
    "name": "customer name",
    "email": "customer email",
    "password": "pass",
    "timezone": "customer timezone",
    "ip": "IP address",
    "spoken_languages": [ "EN", "RU" ],
    "exp_date": "06/10/2017"
  }
}

{
  "doc_type": "transaction",
  "doc_ver": 1,
  "content": {
    "accnt_no": "12321645645484",
    "tran_date": "06/04/2017",
    "tran_time":  "09:15:84.953"
  }
}

Hope this helps.


问:
Sorted a Python dictionary by changing a key, now when I try to iterate through it, it iterates through the changed key
I have a dictionary of Arrays in Python such that

```<code>dictionary={a:[1,2,3,4],b:[2,3,4,8],c:[3,5,6,5]}
</code>```

and so on and so on

I've already sorted the dictionary so that it is now sorted by the fourth item of every array so the order goes b,c,a

```<code>dictionary=sorted(dictionary.values(),key=itemgetter(3),reverse=True)
</code>```

The problem is, when I try to iterate through the keys, it shoots out the key as the array itself.

```<code>for key in dictionary:
    print(key)
</code>```

prints out [2,3,4,8], however, I want it to iterate through b,c,a in that order.

Is there an easy way to do this?

答:
Sorted is a builtin function that takes an iterable like a list (array) or dictionary or any other such type and returns a list (array) as output.
(Refer here: Builtin Function - sorted()

You cannot sort a dictionary itself and store it as dictionary by itself is unordered (It does not remember the order of its keys).

In order to store a dictionary along with its order use the ordereddict datatype in python. (Refer here for Ordereddict)

For sorting an ordered dict you refer this stackoverflow question.

(For more information on sorting a dictionary Refer this question.)

Body:
I have a dictionary of Arrays in Python such that

dictionary={a:[1,2,3,4],b:[2,3,4,8],c:[3,5,6,5]}

and so on and so on

I've already sorted the dictionary so that it is now sorted by the fourth item of every array so the order goes b,c,a

dictionary=sorted(dictionary.values(),key=itemgetter(3),reverse=True)

The problem is, when I try to iterate through the keys, it shoots out the key as the array itself.

for key in dictionary:
    print(key)

prints out [2,3,4,8], however, I want it to iterate through b,c,a in that order.

Is there an easy way to do this?


问:
Spring MVC Resource not found 404
I am getting 404 response not found when I try to call a RESTful Web Service from AngularJS. Following is the code sample :

WebAppConfiguration.java

```<code>public class WebAppConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
       InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
       viewResolver.setViewClass(JstlView.class);
       viewResolver.setPrefix("/WEB-INF/");
       viewResolver.setSuffix(".html");
       registry.viewResolver(viewResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/app/**").addResourceLocations("/app/");
    }
}
</code>```

WebAppInitializer.java

```<code>public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebBeanConfig.class);
        ctx.setServletContext(servletContext);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);
        servlet.addMapping("/");
        servlet.setAsyncSupported(true);
        servlet.setLoadOnStartup(1);
    }
}
</code>```

WebBeanConfig.java

```<code>@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.rvc.releaseSessionDemo")
public class WebBeanConfig {
}
</code>```

SessionController.java

```<code>@RestController
@RequestMapping("/session")
public class SessionController {
   @Autowired
   private ISessionService sessionService;

   @RequestMapping(value = "/releaseSession", method = RequestMethod.POST,  produces = MediaType.APPLICATION_JSON_VALUE)
   public ResponseEntity<Boolean> releaseSession(@RequestBody String sessionId) throws Exception {
       Boolean response = sessionService.releaseSession(sessionId());
       return new ResponseEntity<Boolean>(response, HttpStatus.OK);
   }
}
</code>```

session.service.js

```<code>angular.module('session', []).factory('sessionService', ['$http', '$q', sessionService]);

function sessionService($http, $q) {
   return {
      releaseSession : releaseSession
   }

function releaseSession(sessionId) {
    var deferred = $q.defer();
    var req = {sessionId : sessionId};
    $http.post('session/releaseSession', req).then(function(response) {
        deferred.resolve(response.data);
    }, function(errorResponse) {
        deferred.reject(errorResponse);
    });
    return deferred.promise;
  }
}
</code>```

答:
I would myself like to answer the question.

The problem was the servlet mapping i.e. "/" which works only in case of XML based configuration. If we are using Annotation based configuration, then servlet mapping should be "/*" in the initializer class.

servlet.addMapping("/*");

Title: Spring MVC Resource not found 404

Body:
I am getting 404 response not found when I try to call a RESTful Web Service from AngularJS. Following is the code sample :

WebAppConfiguration.java

public class WebAppConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
       InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
       viewResolver.setViewClass(JstlView.class);
       viewResolver.setPrefix("/WEB-INF/");
       viewResolver.setSuffix(".html");
       registry.viewResolver(viewResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/app/**").addResourceLocations("/app/");
    }
}

WebAppInitializer.java

public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebBeanConfig.class);
        ctx.setServletContext(servletContext);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);
        servlet.addMapping("/");
        servlet.setAsyncSupported(true);
        servlet.setLoadOnStartup(1);
    }
}

WebBeanConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.rvc.releaseSessionDemo")
public class WebBeanConfig {
}

SessionController.java

@RestController
@RequestMapping("/session")
public class SessionController {
   @Autowired
   private ISessionService sessionService;

   @RequestMapping(value = "/releaseSession", method = RequestMethod.POST,  produces = MediaType.APPLICATION_JSON_VALUE)
   public ResponseEntity<Boolean> releaseSession(@RequestBody String sessionId) throws Exception {
       Boolean response = sessionService.releaseSession(sessionId());
       return new ResponseEntity<Boolean>(response, HttpStatus.OK);
   }
}

session.service.js

angular.module('session', []).factory('sessionService', ['$http', '$q', sessionService]);

function sessionService($http, $q) {
   return {
      releaseSession : releaseSession
   }

function releaseSession(sessionId) {
    var deferred = $q.defer();
    var req = {sessionId : sessionId};
    $http.post('session/releaseSession', req).then(function(response) {
        deferred.resolve(response.data);
    }, function(errorResponse) {
        deferred.reject(errorResponse);
    });
    return deferred.promise;
  }
}


问:
WriteFile String Byte Length causes crash
Problem

I have been trying all sorts of byte counts trying to get WriteFile to work. The problem is it immediately crashes after writing to the file. All the text is in the file but yet the "A program has crashed, send to Microsoft??" Error Dialog pops up.

When commenting out invoke WriteFile and everything below it, the program runs fine and does not crash. However when I just uncomment WriteFile and leave all the code below it commented out it again rears it's ugly head. The code is below and if anybody can see something that I missed it is much appreciated :-)

Byte Lengths I have tried.

I have tried byte lengths of 23, 24 (string length + null), 25 (Maybe I forgot a byte), and also just using SIZEOF WriteText and all of them failed :-(.

Code

```<code>.386
.model flat,stdcall
option casemap:none ; Case Sensitive

; Windows
include \masm32\include\windows.inc

; Kernel32
include \masm32\include\kernel32.inc
includelib \masm32\lib\kernel32.lib

.data
FilePath         db "C:\test.txt",0
WriteText        db "This is some test text."

.code
start:

; Edit a file

invoke CreateFile, addr FilePath, GENERIC_WRITE, FILE_SHARE_WRITE or FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL
push eax ; save the file handle

; This works other than the crashing, any number less then 23
; and the file has some of the text clipped
; any larger and NUL is appended until the byte count is matched.
invoke WriteFile, eax, addr WriteText, 23, NULL, NULL

pop eax
push eax

invoke CloseHandle, eax

invoke ExitProcess, 0
end start
</code>```

答:
According to the documentation for the WriteFile function:

lpNumberOfBytesWritten [out, optional]

  [...]

  This parameter can be NULL only when the lpOverlapped parameter is not NULL.

You have both lpNumberOfBytesWritten and lpOverlapped as NULL. Pass addr some_writable_variable as lpNumberOfBytesWritten and it should work.

Body:
Problem

I have been trying all sorts of byte counts trying to get WriteFile to work. The problem is it immediately crashes after writing to the file. All the text is in the file but yet the "A program has crashed, send to Microsoft??" Error Dialog pops up.

When commenting out invoke WriteFile and everything below it, the program runs fine and does not crash. However when I just uncomment WriteFile and leave all the code below it commented out it again rears it's ugly head. The code is below and if anybody can see something that I missed it is much appreciated :-)

Byte Lengths I have tried.

I have tried byte lengths of 23, 24 (string length + null), 25 (Maybe I forgot a byte), and also just using SIZEOF WriteText and all of them failed :-(.

Code

.386
.model flat,stdcall
option casemap:none ; Case Sensitive

; Windows
include \masm32\include\windows.inc

; Kernel32
include \masm32\include\kernel32.inc
includelib \masm32\lib\kernel32.lib

.data
FilePath         db "C:\test.txt",0
WriteText        db "This is some test text."

.code
start:

; Edit a file

invoke CreateFile, addr FilePath, GENERIC_WRITE, FILE_SHARE_WRITE or FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL
push eax ; save the file handle

; This works other than the crashing, any number less then 23
; and the file has some of the text clipped
; any larger and NUL is appended until the byte count is matched.
invoke WriteFile, eax, addr WriteText, 23, NULL, NULL

pop eax
push eax

invoke CloseHandle, eax

invoke ExitProcess, 0
end start


问:
Unable to change UILabel in a method after calling different method in different class
I am trying to update a UILabel with data retrieved from a different class, so in ViewDidLoad, I am calling a method in that different class, then in that class, calling a method in the ViewController to update the UILabel. Here is a simplified version of the code I'm trying to run:

```<code>import UIKit

  class ViewController: UIViewController {

    @IBOutlet var label: UILabel!
    override func viewDidLoad() {
    super.viewDidLoad()
    test().runTest()
}

func print() {
    label.text = "test123"
}

}
</code>```

and the other class:

```<code>import UIKit

class test: UIView {

    func runTest() {
        ViewController().print()
    }
}
</code>```

I keep getting an error message printed in the console saying: "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)"

And an error on the "label.text = "test123" saying: "Thread 1: EXC_Bad_Instruction(code=EXC_(386_INVOP, subcode = 0x0)"

Thanks in advance for your help.

答:
Your problem is that you are running the function on a new instance of your view controller rather, you should be running it on the already created instance. For instance, if your view is a child of your view controller you can do this, in your class test replace edit your function test to be this.

```<code>func runTest() {
    if let vc = self.parent as? ViewController{
        vc.print()
    }
}
</code>```

This should run the function on the already created instance of your view controller.

Body:
I am trying to update a UILabel with data retrieved from a different class, so in ViewDidLoad, I am calling a method in that different class, then in that class, calling a method in the ViewController to update the UILabel. Here is a simplified version of the code I'm trying to run:

import UIKit

  class ViewController: UIViewController {

    @IBOutlet var label: UILabel!
    override func viewDidLoad() {
    super.viewDidLoad()
    test().runTest()
}

func print() {
    label.text = "test123"
}

}

and the other class:

import UIKit

class test: UIView {

    func runTest() {
        ViewController().print()
    }
}

I keep getting an error message printed in the console saying: "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)"

And an error on the "label.text = "test123" saying: "Thread 1: EXC_Bad_Instruction(code=EXC_(386_INVOP, subcode = 0x0)"

Thanks in advance for your help.

Body:
Your problem is that you are running the function on a new instance of your view controller rather, you should be running it on the already created instance. For instance, if your view is a child of your view controller you can do this, in your class test replace edit your function test to be this.

func runTest() {
    if let vc = self.parent as? ViewController{
        vc.print()
    }
}

This should run the function on the already created instance of your view controller.


问:
What is the use case for a Fragment with no UI?
The Android Developer guide has a decent section on the use of Fragments.  One way to use Fragments is without a UI.  There are a few references to using this as a means of background processing, but what advantages do Fragments bring to this area?  Where would I choose to use a Fragment over Threads, AsyncTasks, Handlers, etc. for background processing?</p>

答:
These are also called Headless Fragments.
You can read more here


问:
How can I create iterators of a filtered vector?
Suppose I have a vector named spot_deals of SpotDeal that is a class:

```<code>class SpotDeal
{
public:
    int deal_id_; // primary key, and vector is sorted by id
    string ccy_pair_; // ccy pair, e.g. GBPUSD, AUDUSD
    double amount_;
}
</code>```

Say I need to pass two subset of spot_deals to a function foo for some computation. I could make copies, however, that would cost memory and time. Actually foo only needs iterators of deals. So can I make 2 iterators of vector<SpotDeal>, namely it1 and it2 and pass them to foo?

The two subset of spot_deals could be filtered by ccy_pair_, e.g. deals of GBPUSD and AUDUSD, or by other conditions. So I'm looking for a way to define an iterator defined by a vector and a lambda function (could equivalently be a functor though).

Is there a way to write a helper function make_filtered_iterator so that I can have something like below?

```<code>auto it1 = make_filtered_iterator(spot_deals, filter_lambda1);
auto it2 = make_filtered_iterator(spot_deals, filter_lambda2);
foo(it1, it2);
</code>```

答:
Yes, it would be possible to create an iterator type.   However, I suspect your question is an example of an XY problem (https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - you want to find a way to operate differently on two subsets of a vector (X), have decided the solution must involve implementing a special-purpose iterator (Y), and have asked how to do Y rather than X.    I am going to provide an option to do X without needing to do Y.

I suggest it would be easier to use standard algorithm std::stable_partition() to separate the container into two ranges.

```<code> auto false_partition = std::stable_partition(your_vector.begin(), your_vector.end(), your_filter);
</code>```

The begin() and end() iterators of the vector do not change (i.e. are not invalidated), but the elements between them are reorganised into two ranges, such that the elements for which your_filter returns true precedes the set of elements for which your_filter returns false. false_partition is therefore simultaneously the "past the end" iterator for the first range, and the beginning of the second range.    The order of elements in each range is the same as in the original vector.

These can be used as follows

```<code> //   a loop to operates on the elements for which your_filter returned true

 for (auto i = your_vector.begin(); i != false_partition; ++i)
 {
      // do whatever
 }

 //   a loop to operates on the elements for which your_filter returned false

 for (auto i = false_partition; i != your_vector.end(); ++i)
 {
      // do whatever
 }
</code>```

Before C++11, the auto keyword can be replaced with appropriate iterator types (e.g. std::vector<int>::iterator or std::vector<int>::const_iterator, depending on whether you want the elements to be changed using the iterators).

Body:
Suppose I have a vector named spot_deals of SpotDeal that is a class:

class SpotDeal
{
public:
    int deal_id_; // primary key, and vector is sorted by id
    string ccy_pair_; // ccy pair, e.g. GBPUSD, AUDUSD
    double amount_;
}

Say I need to pass two subset of spot_deals to a function foo for some computation. I could make copies, however, that would cost memory and time. Actually foo only needs iterators of deals. So can I make 2 iterators of vector<SpotDeal>, namely it1 and it2 and pass them to foo?

The two subset of spot_deals could be filtered by ccy_pair_, e.g. deals of GBPUSD and AUDUSD, or by other conditions. So I'm looking for a way to define an iterator defined by a vector and a lambda function (could equivalently be a functor though).

Is there a way to write a helper function make_filtered_iterator so that I can have something like below?

auto it1 = make_filtered_iterator(spot_deals, filter_lambda1);
auto it2 = make_filtered_iterator(spot_deals, filter_lambda2);
foo(it1, it2);

Body:
Yes, it would be possible to create an iterator type.   However, I suspect your question is an example of an XY problem (https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - you want to find a way to operate differently on two subsets of a vector (X), have decided the solution must involve implementing a special-purpose iterator (Y), and have asked how to do Y rather than X.    I am going to provide an option to do X without needing to do Y.

I suggest it would be easier to use standard algorithm std::stable_partition() to separate the container into two ranges.

 auto false_partition = std::stable_partition(your_vector.begin(), your_vector.end(), your_filter);

The begin() and end() iterators of the vector do not change (i.e. are not invalidated), but the elements between them are reorganised into two ranges, such that the elements for which your_filter returns true precedes the set of elements for which your_filter returns false. false_partition is therefore simultaneously the "past the end" iterator for the first range, and the beginning of the second range.    The order of elements in each range is the same as in the original vector.

These can be used as follows

 //   a loop to operates on the elements for which your_filter returned true

 for (auto i = your_vector.begin(); i != false_partition; ++i)
 {
      // do whatever
 }

 //   a loop to operates on the elements for which your_filter returned false

 for (auto i = false_partition; i != your_vector.end(); ++i)
 {
      // do whatever
 }

Before C++11, the auto keyword can be replaced with appropriate iterator types (e.g. std::vector<int>::iterator or std::vector<int>::const_iterator, depending on whether you want the elements to be changed using the iterators).


问:
Do .Net Collection Classes Use .Equals() on contained members to evaluate .Contains()?
The subject pretty much says it all.

Does a collection class use an (overridden) .Equals() method to determine if the collection class .Contains() an element or not?  Or does it use reference equality or some other method?

I would like the collection class to ignore a single field on contained members when determining if the collection .Contains() an element or not.

答: According to these articles, unless your object implements IEquatable, Object.Equals is used.


问:
Using pointer to channel
Is it good practice to use pointer to channel? For example I read the data concurrently and pass those data map[string]sting using channel  and process this channel inside getSameValues().

```<code>func getSameValues(results *chan map[string]string) []string {
    var datas = make([]map[string]string, len(*results))
    i := 0
    for values := range *results {
        datas[i] = values
        i++
    }
}
</code>```

The reason I do this is because the chan map[string]string there will be around millions of data inside the map and it will be more than one map.

So I think it would be a good approach if I can pass pointer to the function so that it will not copy the data to save some resource of memory.

I didn't find a good practice in effective go. So I'm kinda doubt about my approach here.

答:
It is poor practice to use pointers to channels, maps, functions, interfaces, or slices for efficiency.

Values of these types have a small fixed size independent of the length or capacity of the value. An internal pointer references the variable size data.

Channels, maps, and functions are the same size as a pointer. Therefore, the runtime cost of copying a value of these types is identical to copying a pointer to the value.

Interfaces are two × the size of a pointer, and slices are three × the size of a pointer. The cost of copying a value of these types is higher than copying a pointer. That extra copying cost is often lower or equal to the cost of dereferencing the pointer.

Title: Using pointer to channel

Body:
Is it good practice to use pointer to channel? For example I read the data concurrently and pass those data map[string]sting using channel  and process this channel inside getSameValues().

func getSameValues(results *chan map[string]string) []string {
    var datas = make([]map[string]string, len(*results))
    i := 0
    for values := range *results {
        datas[i] = values
        i++
    }
}

The reason I do this is because the chan map[string]string there will be around millions of data inside the map and it will be more than one map.

So I think it would be a good approach if I can pass pointer to the function so that it will not copy the data to save some resource of memory.

I didn't find a good practice in effective go. So I'm kinda doubt about my approach here.


问:
angular display ng-repeat only after clicking a button
I have a controller that runs with the page load. I would like to change it, so only after clicking a button the function will called and the results will be displayed.

HTML:

```<code><div ng-controller="MyController">Files on server: {{ mydata }}
</div>

<ul ng-controller="MyController as controller">
    <li ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
</code>```

JS:

```<code>app.controller('MyController', function($http) {
var vm = this;
vm.mydata = [];

$http.get('list')
    .then(function(result) {
      console.log(result);
      vm.mydata = result.data;
     });
});
</code>```

答:
It´s better to make only one call to the server, so you could get the data from the beginning.

You could toggle the visibility instead of making an api call.

```<code><ul ng-controller="MyController as controller">
    <a href="#" ng-click="controller.display == !controller.display">
      Toggle Info
    </a>
    <li ng-if="controller.display" ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>
</code>```

And decelerate the display as:

```<code>vm.display = false;
</code>```

Why the negation?

With that the a tag will toggle the visibility of the li elements.

Body:
I have a controller that runs with the page load. I would like to change it, so only after clicking a button the function will called and the results will be displayed.

HTML:

Files on server: {{ mydata }}

{{ data }}

JS:

app.controller('MyController', function($http) {
var vm = this;
vm.mydata = [];

$http.get('list')
    .then(function(result) {
      console.log(result);
      vm.mydata = result.data;
     });
});

Body:
It´s better to make only one call to the server, so you could get the data from the beginning.

You could toggle the visibility instead of making an api call.

<ul ng-controller="MyController as controller">
    <a href="#" ng-click="controller.display == !controller.display">
      Toggle Info
    </a>
    <li ng-if="controller.display" ng-repeat="data in controller.mydata">{{ data }}</li>
</ul>

And decelerate the display as:

vm.display = false;

Why the negation?

With that the a tag will toggle the visibility of the li elements.


问:
Springboot - Thymeleaf tries to resolve files it should not
Hi I am currently working on a web project that uses thymeleaf and also JSF (its a legacy system and we can only slowly migrate to thymeleaf thats why JSF is still there and cannot be removed from one day to another since this is a lot of work). Thymeleaf is configured to resolve the views in the webapp directory that lie under the directory "thymeleaf". This works perfectly if I deploy the application directly on a tomcat server. Also pages from other directories then the "thymeleaf" directory are also resolved by the JSF framework.

I added some integration tests in JUnit that are using SpringBoot. Inside these tests I got the problem that thymeleaf now is trying to resolve any page in any directory. JSF is completely ignored and I got a whole bunch of JUnit tests failing because of that. Is there any point why thymeleaf ignores its configuration and wants to resolve all files?
Here is my complete thymeleaf configuration, and as I said this works perfectly if I deploy it on a standalone tomcat.

```<code>private ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
  this.applicationContext = applicationContext;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
  String imagesPattern = "/images/**";
  String imagesLocation = basePath() + "resources/images/";
  registry.addResourceHandler(imagesPattern).addResourceLocations(imagesLocation);
  log.info("added resourceHandler (pathPattern: '{}'), (resourceLocation: '{}')",
           imagesPattern,
           imagesLocation);

  String cssPattern = "/css/**";
  String cssLocation = basePath() + "resources/css/";
  registry.addResourceHandler(cssPattern).addResourceLocations(cssLocation);
  log.info("added resourceHandler (pathPattern: '{}'), (resourceLocation: '{}')", cssPattern, cssLocation);
}

@Bean(name = "basepath")
public String basePath()
{
  String basepath = "";

  File file = new File(Optional.ofNullable(System.getenv("THYMELEAF_APP_RESOURCES"))
                               .orElse("thymeleaf-resources/"));
  if (file.exists())
  {
    basepath = "file:" + file.getAbsolutePath();
  }
  if (!basepath.endsWith("/"))
  {
    basepath += "/";
  }
  log.info("basepath: {}", basepath);
  return basepath;
}

@Bean
@Description("Thymeleaf View Resolver")
public ThymeleafViewResolver viewResolver(String basePath)
{
  log.info("setting up Thymeleaf view resolver");
  ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
  viewResolver.setTemplateEngine(templateEngine(basePath));
  viewResolver.setCharacterEncoding("UTF-8");
  viewResolver.setCache(true);
  return viewResolver;
}

public SpringTemplateEngine templateEngine(String basePath)
{
  log.info("setting up Thymeleaf template engine.");
  SpringTemplateEngine templateEngine = new SpringTemplateEngine();
  templateEngine.setTemplateResolver(templateResolver(basePath));
  templateEngine.setEnableSpringELCompiler(true);
  return templateEngine;
}

private ITemplateResolver templateResolver(String basePath)
{
  log.info("setting up Thymeleaf template resolver");
  SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
  resolver.setApplicationContext(applicationContext);
  resolver.setPrefix(basePath + "thymeleaf/views/");
  resolver.setSuffix(".html");
  resolver.setTemplateMode(TemplateMode.HTML);
  resolver.setCacheable(false);
  return resolver;
}

@Bean
public IMessageResolver thymeleafMessageSource(MessageSource messageSource)
{
  SpringMessageResolver springMessageResolver = new SpringMessageResolver();
  springMessageResolver.setMessageSource(messageSource);
  return springMessageResolver;
}
</code>```

EDIT

I just found that the problem seems to lie much deeper. Having the dependencies of thymeleaf added into my pom.xml seems to be enough for spring boot to load it into the context... I just deleted my ThymeleafConfig class for testing purposes and still thymeleaf tries to resolve the JSF pages... (yes I did maven clean before executing the test)

EDIT 2

I read it now and tried to exclude the ThymeleafAutoConfiguration class but it does not help. My configurations are still overridden. Here is my configuration for this so far. (And yes this is the ONLY EnableAutoConfiguration annotation in the whole project)

```<code>    @Configuration
    @EnableAutoConfiguration(exclude = {ThymeleafAutoConfiguration.class})
    @Import({WebAppConfig.class, ThymeleafConfig.class})
    public class SpringBootInitializer extends SpringBootServletInitializer
</code>```

and my ThymeleafConfig class is already added above.

答:
Having the dependencies of thymeleaf added into my pom.xml seems to be enough for spring boot to load it into the context...

If this has surprised you then I would recommend spending some time to take a step back and read about how Spring Boot works and, in particular, it's auto-configuration feature. This section of the reference documentation is a good place to start.

In short, Spring Boot adopts a convention over configuration approach. If a dependency is on the classpath, Spring Boot assumes that you want to use it, and configures it with sensible defaults. This is what it's doing with Thymeleaf. You can disable this auto-configuration for a specific dependency using the excludes attribute on @SpringBootApplication:

```<code>@SpringBootApplication(exclude={ThymeleafAutoConfiguration.class})
public class ExampleApplication {

}
</code>```

You can also use the spring.autoconfigure.exclude property to provide a comma-separated list of auto-configuration classes to exclude. Each entry in the list should be the fully-qualified name of an auto-configuration class. You could use this property with @TestPropertySource to disable auto-configuration on a test-by-test basis.

Body:
Hi I am currently working on a web project that uses thymeleaf and also JSF (its a legacy system and we can only slowly migrate to thymeleaf thats why JSF is still there and cannot be removed from one day to another since this is a lot of work). Thymeleaf is configured to resolve the views in the webapp directory that lie under the directory "thymeleaf". This works perfectly if I deploy the application directly on a tomcat server. Also pages from other directories then the "thymeleaf" directory are also resolved by the JSF framework.

I added some integration tests in JUnit that are using SpringBoot. Inside these tests I got the problem that thymeleaf now is trying to resolve any page in any directory. JSF is completely ignored and I got a whole bunch of JUnit tests failing because of that. Is there any point why thymeleaf ignores its configuration and wants to resolve all files?
Here is my complete thymeleaf configuration, and as I said this works perfectly if I deploy it on a standalone tomcat.

private ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
  this.applicationContext = applicationContext;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
  String imagesPattern = "/images/**";
  String imagesLocation = basePath() + "resources/images/";
  registry.addResourceHandler(imagesPattern).addResourceLocations(imagesLocation);
  log.info("added resourceHandler (pathPattern: '{}'), (resourceLocation: '{}')",
           imagesPattern,
           imagesLocation);

  String cssPattern = "/css/**";
  String cssLocation = basePath() + "resources/css/";
  registry.addResourceHandler(cssPattern).addResourceLocations(cssLocation);
  log.info("added resourceHandler (pathPattern: '{}'), (resourceLocation: '{}')", cssPattern, cssLocation);
}

@Bean(name = "basepath")
public String basePath()
{
  String basepath = "";

  File file = new File(Optional.ofNullable(System.getenv("THYMELEAF_APP_RESOURCES"))
                               .orElse("thymeleaf-resources/"));
  if (file.exists())
  {
    basepath = "file:" + file.getAbsolutePath();
  }
  if (!basepath.endsWith("/"))
  {
    basepath += "/";
  }
  log.info("basepath: {}", basepath);
  return basepath;
}

@Bean
@Description("Thymeleaf View Resolver")
public ThymeleafViewResolver viewResolver(String basePath)
{
  log.info("setting up Thymeleaf view resolver");
  ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
  viewResolver.setTemplateEngine(templateEngine(basePath));
  viewResolver.setCharacterEncoding("UTF-8");
  viewResolver.setCache(true);
  return viewResolver;
}

public SpringTemplateEngine templateEngine(String basePath)
{
  log.info("setting up Thymeleaf template engine.");
  SpringTemplateEngine templateEngine = new SpringTemplateEngine();
  templateEngine.setTemplateResolver(templateResolver(basePath));
  templateEngine.setEnableSpringELCompiler(true);
  return templateEngine;
}

private ITemplateResolver templateResolver(String basePath)
{
  log.info("setting up Thymeleaf template resolver");
  SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
  resolver.setApplicationContext(applicationContext);
  resolver.setPrefix(basePath + "thymeleaf/views/");
  resolver.setSuffix(".html");
  resolver.setTemplateMode(TemplateMode.HTML);
  resolver.setCacheable(false);
  return resolver;
}

@Bean
public IMessageResolver thymeleafMessageSource(MessageSource messageSource)
{
  SpringMessageResolver springMessageResolver = new SpringMessageResolver();
  springMessageResolver.setMessageSource(messageSource);
  return springMessageResolver;
}

EDIT

I just found that the problem seems to lie much deeper. Having the dependencies of thymeleaf added into my pom.xml seems to be enough for spring boot to load it into the context... I just deleted my ThymeleafConfig class for testing purposes and still thymeleaf tries to resolve the JSF pages... (yes I did maven clean before executing the test)

EDIT 2

I read it now and tried to exclude the ThymeleafAutoConfiguration class but it does not help. My configurations are still overridden. Here is my configuration for this so far. (And yes this is the ONLY EnableAutoConfiguration annotation in the whole project)

    @Configuration
    @EnableAutoConfiguration(exclude = {ThymeleafAutoConfiguration.class})
    @Import({WebAppConfig.class, ThymeleafConfig.class})
    public class SpringBootInitializer extends SpringBootServletInitializer

and my ThymeleafConfig class is already added above.

Body:
Having the dependencies of thymeleaf added into my pom.xml seems to be enough for spring boot to load it into the context...

If this has surprised you then I would recommend spending some time to take a step back and read about how Spring Boot works and, in particular, it's auto-configuration feature. This section of the reference documentation is a good place to start.

In short, Spring Boot adopts a convention over configuration approach. If a dependency is on the classpath, Spring Boot assumes that you want to use it, and configures it with sensible defaults. This is what it's doing with Thymeleaf. You can disable this auto-configuration for a specific dependency using the excludes attribute on @SpringBootApplication:

@SpringBootApplication(exclude={ThymeleafAutoConfiguration.class})
public class ExampleApplication {

}

You can also use the spring.autoconfigure.exclude property to provide a comma-separated list of auto-configuration classes to exclude. Each entry in the list should be the fully-qualified name of an auto-configuration class. You could use this property with @TestPropertySource to disable auto-configuration on a test-by-test basis.


问:
Vertically align text to top within a UILabel
I have a UILabel with space for two lines of text. Sometimes, when the text is too short, this text is displayed in the vertical center of the label.

How do I vertically align the text to always be at the top of the UILabel?

答:
I took the suggestions here and created a view which can wrap a UILabel and will size it and set the number of lines so that it is top aligned. Simply put a UILabel as a subview:</p>

```<code>@interface TopAlignedLabelContainer : UIView
{
}

@end

@implementation TopAlignedLabelContainer

- (void)layoutSubviews
{
    CGRect bounds = self.bounds;

    for (UILabel *label in [self subviews])
    {
        if ([label isKindOfClass:[UILabel class]])
        {
            CGSize fontSize = [label.text sizeWithFont:label.font];

            CGSize textSize = [label.text sizeWithFont:label.font
                                     constrainedToSize:bounds.size
                                         lineBreakMode:label.lineBreakMode];

            label.numberOfLines = textSize.height / fontSize.height;

            label.frame = CGRectMake(0, 0, textSize.width,
                 fontSize.height * label.numberOfLines);
        }
    }
}

@end
</code>```

Body:
I took the suggestions here and created a view which can wrap a UILabel and will size it and set the number of lines so that it is top aligned. Simply put a UILabel as a subview:

@interface TopAlignedLabelContainer : UIView
{
}

@end

@implementation TopAlignedLabelContainer

- (void)layoutSubviews
{
    CGRect bounds = self.bounds;

    for (UILabel *label in [self subviews])
    {
        if ([label isKindOfClass:[UILabel class]])
        {
            CGSize fontSize = [label.text sizeWithFont:label.font];

            CGSize textSize = [label.text sizeWithFont:label.font
                                     constrainedToSize:bounds.size
                                         lineBreakMode:label.lineBreakMode];

            label.numberOfLines = textSize.height / fontSize.height;

            label.frame = CGRectMake(0, 0, textSize.width,
                 fontSize.height * label.numberOfLines);
        }
    }
}

@end


问:
Net Send command in Windows 10 Home Edition
How would I send a message, for example, to all the hosts on my LAN ? In windows XP, one would use net send: net send * Hello Wold !

How is that possible in Windows 10 ? I can see that they removed this command, so is there an equivalent ?

Moreover, if I try to use msg.exe as an alternative, I get the error-message:

msg is not recognized as an internal or external command, operable
  program or batch file.

答:
This was already removed in Vista, but you can use msg.exe instead:</p>
```<code>msg.exe /server:brad-dc-01 console "Your machine needs to be rebooted."
</code>```

Body:
This was already removed in Vista, but you can use msg.exe instead:

msg.exe /server:brad-dc-01 console "Your machine needs to be rebooted."


问:
pulling a random item from multiple arrays
I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

```<code>var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}
</code>```

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.

答: Why don't you use a 2-d array instead of 12 single arrays. Then it will be very easy.</p>

Body:
I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.


问:
Keeping one table or multiple table for similar type of data which one is best while considering high performance
I am designing DATABASE for a Sales and Purchase application like ERP and using MYSQL as RDBMS, I have doubt on creating table for sales and purchase entities to go with single table for each module(Sale/Purchase) or multiple tables for each entities(Sales order, Sale invoice, Sale return, Purchase order, Purchase invoice, Purchase return) in longer run. Below is my use case.

My application will have Sale Order, Sale Delivery, Sale Invoice, Sale Return and Credit Note and same entity for Purchase module also and all these entity may be enter linked in there module. Like Sale Order can be converted into Sale Delivery or Sale Order and Sale Delivery can be converted into Sale Invoice. So there need to maintain reference b/w each entity of a module.

Now, I am little confuse to keep all this in one table for each module say "sale_entity" and "purchase_entity" having entity type Or should I create separate table for each entity type say sale_order, sale_invoice, sale_return, purchase_order, purchase_invoice, purchase_return etc.

Below is what running in my mind for both the cases:

Single Table: I really want to keep this in single table for each module but I am worry about performance in longer run, It will increase the table size quickly and may slow down the performance.

Multiple table: It will be difficult to manage, maintain relationships and fetching data in reports for all entity types of records at once, requires union and all.

My understanding is that large size of table performs slower than the small size of table, Please correct if I am wrong.

Please put some light on it, and suggest me how should I proceed.

Thank You

答:
Use separate tables.

I agree with the notion that you will have similar data in both tables but there is more to a Sales Order header and Sales Orderline than just the design of the table.

The concept of a sales order is very different logically than say the concept of a purchase order.

On it's most basic level one is directly related to a debtor account and one to a creditor account.

Both also have very different procedures when it comes to stock movements.  E.g. One is goods inwards, which has a whole set of concepts like costing associated.  Whereas the other is a goods outwards which has associated delivery information such as couriers, cost of delivery, etc.

I am assuming if you are trying to replicate an ERP then you will also have to have some sort of manufacturing works orders tables, which when considered together with a sales order and purchase order, interact very differently with stock transactions and stock locations.  When you consider the differences between 1. receiving goods to a location during putaway, to 2. consuming raw materials receieved and generating new output items to different stock locations, to 3. sales orders for items that are generated from a works order and not part of the goods inwards receiving process, then you start to see that trying to dump all that logic into a single table would be complete madness.

You also need to consider the affects of having a single table in terms of programmability.  What happens when you need to lock the table for a transaction?  You have now locked all users from all data related to orders incl. Sales orders, purchase orders, and works orders.

So, in short, you need to separate the data with the logic.

I have never seen an ERP database that has a single table for all order types, or all stock transactions, or all debitor transactions, etc.

Anyone who says different is a bluffer of monumental proportions.

If in doubt remember that RELATIONAL database systems were designed so that you could separate data across multiple tables reducing the issues associated with single table designs, like performance, table locking, separation of logic (stored procedures, triggers, etc).  Use sales order header numbers (or equivelant) as the relational key.   Its a far tidier design principle.


问:
How to set props use refs in React js
who knows how change props in my component use refs in react js ?

```<code><MyComponent
  ref={'input1'}
  name={'input1'}
  label={interestsName}
  disabled={ false}
  onChange={this.myFunction}/>
</code>```

after onChange i call function with

```<code>myFunction =()=>{console.log(this.rews[input1].props.disable);}
</code>```

May I change props use refs without use state? Because I have many '15' components such as this component. Thanks.

答:
You cannot change props from child class, for more please refer to link.

For your functionality use you can use state to change value on the change event. And one more thing you should keep the logic of changing component properties should remain inside a component. This will help us to maintain different states for different components.

```<code>class MyComponent extends React.Component {
  constructor(props) {
    this.state = {
     disable: props.disabled
    };
  }

  myFunction() {
    console.log(this.state);
  }
}
</code>```

You can iterate over the above component and it can be used for 15 times and different states can be managed for every element

Title: How to set props use refs in React js

Body:
who knows how change props in my component use refs in react js ?

<MyComponent
  ref={'input1'}
  name={'input1'}
  label={interestsName}
  disabled={ false}
  onChange={this.myFunction}/>

after onChange i call function with

myFunction =()=>{console.log(this.rews[input1].props.disable);}

May I change props use refs without use state? Because I have many '15' components such as this component. Thanks.

Body:
You cannot change props from child class, for more please refer to link.

For your functionality use you can use state to change value on the change event. And one more thing you should keep the logic of changing component properties should remain inside a component. This will help us to maintain different states for different components.

class MyComponent extends React.Component {
  constructor(props) {
    this.state = {
     disable: props.disabled
    };
  }

  myFunction() {
    console.log(this.state);
  }
}

You can iterate over the above component and it can be used for 15 times and different states can be managed for every element


问:
1 big Google Cloud SQL instance, 2 small Google Cloud SQL instances or 1 medium + 1 replica?
I've started to use Google Cloud SQL and I need to improve my IOPS and network speed. I've seen that this it's only possible improving the type of machine and/or improving the size of disk. And this is my question. In my case, I need to migrate 2 MySQL databases (from 2 different projects) and I don't know what is better: 1 big instance with 2 databases? 2 small instances with the database in each instance? or 1 regular instance + 1 read replica instance?

Thank you in advance!

答:
The answer is usual "It depends".

If you're not concerned with data isolation issues, a single instance would be more efficient and easier to manage.

If you split data between instances, you're also capping performance per database. This can be a non-issue if your datasets are similar and process the same amount of requests.

Read replicas could be a solution to scale IOPS if your application workload is heavily skewed towards reads.

Also, independent of which option you will choose, consider HA-setup.


问:
PHP exec command to write to server
So  I have a bash script I want to run in php that has arguments but at the moment I cant even get PHP to write to the machine. As a basic test I tried the touch command to no success. I'm new to PHP so any help would be great. I don't understand whats wrong here.
I've tried:</p>

```<code><?php
shell_exec('touch /var/www/html/test.txt');
?>

<?php
exec('touch /var/www/html/test.txt');
?>

<?php
system('touch /var/www/html/test.txt');
?>

<?php
passthru('touch /var/www/html/test.txt');
?>
</code>```

答:
Difficult to answer this without more information. But, normally touch should create a new file. The most common reason is lack of permissions.

Normally, webserver runs with user www-data. Check and see if permissions are not set for that user.

You can simply run the command

```<code>addgroup www-data
</code>```

That will error out if www-data has right permissions. Otherwise, things might just start working. Also restart apache after this for safety purposes.

```<code>/etc/init.d/apache2 restart
</code>```

Alternatively, in the system command add a 2nd variable like this.

```<code>system('touch /var/www/html/test.txt', $retval);
</code>```

$retval will contain the status of the error. Will help you debug.

You can also run a tail on the apache error log like this.

```<code>tail -f /var/log/apache2/error.log
</code>```

It should throw errors , if there is a problem.

Title: PHP exec command to write to server

Body:
So  I have a bash script I want to run in php that has arguments but at the moment I cant even get PHP to write to the machine. As a basic test I tried the touch command to no success. I'm new to PHP so any help would be great. I don't understand whats wrong here.
I've tried:

<?php
shell_exec('touch /var/www/html/test.txt');
?>

<?php
exec('touch /var/www/html/test.txt');
?>

<?php
system('touch /var/www/html/test.txt');
?>

<?php
passthru('touch /var/www/html/test.txt');
?>

Body:
Difficult to answer this without more information. But, normally touch should create a new file. The most common reason is lack of permissions.

Normally, webserver runs with user www-data. Check and see if permissions are not set for that user.

You can simply run the command

addgroup www-data

That will error out if www-data has right permissions. Otherwise, things might just start working. Also restart apache after this for safety purposes.

/etc/init.d/apache2 restart

Alternatively, in the system command add a 2nd variable like this.

system('touch /var/www/html/test.txt', $retval);

$retval will contain the status of the error. Will help you debug.

You can also run a tail on the apache error log like this.

tail -f /var/log/apache2/error.log

It should throw errors , if there is a problem.


问:
print " ".join(tsOutput) ^ SyntaxError: invalid syntax
i am getting error in

print "".join(tsOutput)

is it due to syntax are different in python 2.x and 3.x versions?

答:
You should add parenthesis to your print statement

print("".join(tsOutput)) should work


问:
adb devices list empty -- Snow Leopard
I'm running into an issue with the android SDK where it doesn't recognize devices plugged in via usb:

```<code>$adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
$adb devices
List of devices attached
</code>```

(list is empty, other sdk tools don't recognize the devices either)

According to the SDK documentation, on Mac OS X, this should "just work". (Setting up a Device for Development)

It's worked for me in the past, but seems to have just stopped. Is there an OS X solution to this problem? (On other operating systems presumably you have to fiddle with USB drivers)

Have tried:

Power cycling machine and device

Switching USB ports Unplugging all

USB except for the sole (non-split)

cable to the device Multiple cables

答:
Note that the setting for "USB Debugging" on the devices seems to unset under certain conditions. In my case this is what happened... So if you come across this for OS X, hopefully that is your issue, otherwise perhaps try the steps above. To enable USB Debugging:

Settings --> Applications --> Development --> USB Debugging.

Title: adb devices list empty -- Snow Leopard

Body:
I'm running into an issue with the android SDK where it doesn't recognize devices plugged in via usb:

$adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
$adb devices
List of devices attached

(list is empty, other sdk tools don't recognize the devices either)

According to the SDK documentation, on Mac OS X, this should "just work". (Setting up a Device for Development)

It's worked for me in the past, but seems to have just stopped. Is there an OS X solution to this problem? (On other operating systems presumably you have to fiddle with USB drivers)

Have tried:

Power cycling machine and device

Switching USB ports Unplugging all

USB except for the sole (non-split)

cable to the device Multiple cables


问:
how to read terminal input in node.js?
I want to do some local node test before push the code to server.

how can I read terminal input as a input for my js script?
    readline or something

答:
For commandline app you can use nicl. you can make call to your chat module or websocket or whatever based on your logic.

```<code>var nicl = require("nicl");

function main() {
    nicl.printLine("Hello, what is your name?");
    var name = nicl.readLine();
    //call to websocket or any chat module
    nicl.printLine("Great to meet you, " + name + "!");

    process.exit(0);
}

nicl.run(main);
</code>```

Title: how to read terminal input in node.js?

Body:
For commandline app you can use nicl. you can make call to your chat module or websocket or whatever based on your logic.

var nicl = require("nicl");

function main() {
    nicl.printLine("Hello, what is your name?");
    var name = nicl.readLine();
    //call to websocket or any chat module
    nicl.printLine("Great to meet you, " + name + "!");

    process.exit(0);
}

nicl.run(main);


答:
I'm going to go out on a limb and say you must be using python 3. In that case, this must be written as print("".join(tsOutput))

This is because print is a function in python 3, and needs standard function syntax. (In python 2 it was built more tightly into the core language and was an exception to the regular syntax in that it required no parentheses)

Title: print " ".join(tsOutput) ^ SyntaxError: invalid syntax

Body:
i am getting error in

print "".join(tsOutput)

is it due to syntax are different in python 2.x and 3.x versions?


问:
How I can change Firefox tab color with a new WebExtensions add-on?
I want to make a new WebExtensions add-on to change the color of my tab but I didn't find anything applicable. tabs.insertCss() can be used only to change CSS inside tab content, but can not style the tab bar

答:
Short answer: You can't do so right now.

Longer: An API is being worked on which will allow some limited changes to the browser UI, which might include what you desire. The API, browser.theme.update(), currently exists in Nightly (Firefox 55). It used to be behind a preference, but is now enabled by default. This API does not permit you to insert arbitrary CSS. You will only be able to change the things specifically included in the API. Inserting arbitrary CSS is something that explicitly won't be permitted.

See:

Blog post announcement: Improving Themes in Firefox

Beginning of a thread on dev-addons

Continuing that dev-addons thread a month later

Main tracking bug for all feature development related the new theming API


问:
What is std::__detail::_Map_base in perf report?
A significant portion of my program's runtime is being dedicated to std::__detail::_Map_base and I have no idea what that is referring to.

I searched around a bit on the internet, and it appears to be a struct of some sort, but I don't see how it's taking up time, let alone almost a fifth of it.  What should I look for to reduce this time?

答:
I smell an EECS 281 Project here

For reference when I was an IA for this class, I got a lot of questions about this.  This just means that a lot of your time has been spent in the internal methods of the map type.  Try and cut down on expensive copies and repeated find operations.  If you are accessing the map over and over again like the following code

```<code>if (m[key].something) {
    use(m[key]);
    cout << m[key];
}
</code>```

try and change it to

```<code>auto& value = m[key];
if (value.something) {
    use(value);
    cout << value;
}
</code>```

This will help you go from 3 expensive find operations to just 1.  You can imagine how this can be helpful when you access a map lots of times in a loop.

Also take a look at Can the use of C++11's 'auto' improve performance? and make sure you are not making mistakes like that.

Body:
I smell an EECS 281 Project here

For reference when I was an IA for this class, I got a lot of questions about this.  This just means that a lot of your time has been spent in the internal methods of the map type.  Try and cut down on expensive copies and repeated find operations.  If you are accessing the map over and over again like the following code

if (m[key].something) {
    use(m[key]);
    cout << m[key];
}

try and change it to

auto& value = m[key];
if (value.something) {
    use(value);
    cout << value;
}

This will help you go from 3 expensive find operations to just 1.  You can imagine how this can be helpful when you access a map lots of times in a loop.

Also take a look at Can the use of C++11's 'auto' improve performance? and make sure you are not making mistakes like that.


问:
Most efficient way to select point with the most surrounding points
N.B: there's a major edit at the bottom of the question - check it out

Question

Say I have a set of points:

I want to find the point with the most points surrounding it, within radius  (ie a circle) or within  (ie a square) of the point for 2 dimensions. I'll refer to it as the densest point function.

For the diagrams in this question, I'll represent the surrounding region as circles. In the image above, the middle point's surrounding region is shown in green. This middle point has the most surrounding points of all the points within radius  and would be returned by the densest point function.

What I've tried

A viable way to solve this problem would be to use a range searching solution; this answer explains further and that it has " worst-case time". Using this, I could get the number of points surrounding each point and choose the point with largest surrounding point count.

However, if the points were extremely densely packed (in the order of a million), as such:

then each of these million points () would need to have a range search performed. The worst-case time , where  is the number of points returned in the range, is true for the following point tree types:

kd-trees of two dimensions (which are actually slightly worse, at ),

2d-range trees,

Quadtrees, which have a worst-case time of

So, for a group of  points within radius  of all points within the group, it gives complexity of  for each point. This yields over a trillion operations!

Any ideas on a more efficient, precise way of achieving this, so that I could find the point with the most surrounding points for a group of points, and in a reasonable time (preferably  or less)?

EDIT

Turns out that the method above is correct! I just need help implementing it.

(Semi-)Solution

If I use a 2d-range tree:

A range reporting query costs , for  returned points,

For a range tree with fractional cascading (also known as layered range trees) the complexity is ,

For 2 dimensions, that is ,

Furthermore, if I perform a range counting query (i.e., I do not report each point), then it costs .

I'd perform this on every point - yielding the  complexity I desired!

Problem

However, I cannot figure out how to write the code for a counting query for a 2d layered range tree.

I've found a great resource (from page 113 onwards) about range trees, including 2d-range tree psuedocode. But I can't figure out how to introduce fractional cascading, nor how to correctly implement the counting query so that it is of O(log n) complexity.

I've also found two range tree implementations here and here in Java, and one in C++ here, although I'm not sure this uses fractional cascading as it states above the countInRange method that

It returns the number of such points in worst case
      * O(log(n)^d) time. It can also return the points that are in the rectangle in worst case
      * O(log(n)^d + k) time where k is the number of points that lie in the rectangle.

which suggests to me it does not apply fractional cascading.

Refined question

To answer the question above therefore, all I need to know is if there are any libraries with 2d-range trees with fractional cascading that have a range counting query of complexity  so I don't go reinventing any wheels, or can you help me to write/modify the resources above to perform a query of that complexity?

Also not complaining if you can provide me with any other methods to achieve a range counting query of 2d points in  in any other way!

答:
I would start by creating something like a https://en.wikipedia.org/wiki/K-d_tree, where you have a tree with points at the leaves and each node information about its descendants. At each node I would keep a count of the number of descendants, and a bounding box enclosing those descendants.

Now for each point I would recursively search the tree. At each node I visit, either all of the bounding box is within R of the current point, all of the bounding box is more than R away from the current point, or some of it is inside R and some outside R. In the first case I can use the count of the number of descendants of the current node to increase the count of points within R of the current point and return up one level of the recursion. In the second case I can simply return up one level of the recursion without incrementing anything. It is only in the intermediate case that I need to continue recursing down the tree.

So I can work out for each point the number of neighbours within R without checking every other point, and pick the point with the highest count.

If the points are spread out evenly then I think you will end up constructing a k-d tree where the lower levels are close to a regular grid, and I think if the grid is of size A x A then in the worst case R is large enough so that its boundary is a circle that intersects O(A) low level cells, so I think that if you have O(n) points you could expect this to cost about O(n * sqrt(n)).


问:
SubSonic 3 Visual Studio Add-in
I'm look for a subsonic 3.0 Add-in tools for visual studio like what was provided for Subsonic 2.
Any alternative tools. I find using the T4 templates annoying. </p>

<p>thanks. </p>

答:
Click on the project that contains the SubSonic templates, then click on the button at the top of Solution Explorer that that says Transform Text Templates, then wait. Use your output window to verify that SubSonic has refreshed all templates.

That's all there is to it.

Title: SubSonic 3 Visual Studio Add-in

Body:
I'm look for a subsonic 3.0 Add-in tools for visual studio like what was provided for Subsonic 2.
Any alternative tools. I find using the T4 templates annoying.

thanks.


问:
How to build cast app which enable to cast media to non Android TV
I would like to develop an app which enable to cast medias like audio, images & videos but cast should work without chromecast. It should directly cast to Smart TV. It should be similar to AllCast app. As I am new with Adroid Cast SDK. So any help with example will help me lot to get started.

I gone through the googlecodelabs sample application but it won't show cast icon. As I think it won't find my Samsung Smart TV.

Please help me to start

答: Google Cast SDK only supports casting to Cast devices, such as Chromecast, Cast for Audio, Android TV, etc. Smart TV's such as Samsung TVs are not Cast devices, and as such, the Cast SDK won't help you with that. To expand support to other devices outside of Cast devices, you need to integrate their SDK's with your app (that should include discovery of such devices); after doing that, you can extend the Cast dialog (the dialog that opens up when you click on the cast icon)to "show" such devices but when you select such devices from that dialog, it is the other SDK that handles streaming to those devices. If you select a Cast device from the dialog, then Cast SDK will handle the casting.</p>