问:
How to hide hierarchy grid toolbar custom button in kendo grid?
Here is my hierarchy grid toolbar.

I put new button in toolbar and that id is CustomButton.

I want to hide that button onclick but when ajax call is success.

I tried $("#CustomButton").remove(); And Also $("#CustomButton").hide(); This code through my button is not hide.

How to hide that button?

```<code>toolbar: [{ name: "create", text: "@T("Admin.Common.AddNewRecord")" },{ name: "add_user", template: '<a class="k-button" id="CustomButton" onclick="oleuminvoiceDocketSubmit()">Send invoice to customer</a>'}],

//Custom Toolbar Button Click
function oleuminvoiceDocketSubmit()
{
        $.ajax({
            dataType: "json",
            type: "POST",
            url: "@(Url.Action("Abc", "Def"))",
            data: {
                'id':InvoiceId,
                'selectedid':selectedIds,
                'method':'Ground'
            },
            success: function (response) {

            },
          });
}
</code>```

答:
```<code>$(document).ready(function () {
     // after grid initialization
     $("#CustomButton").kendoButton().data("kendoButton");
}
</code>```

And in the success function of the ajax call use: $("#customButton").hide();

Body:
Here is my hierarchy grid toolbar.

I put new button in toolbar and that id is CustomButton.

I want to hide that button onclick but when ajax call is success.

I tried $("#CustomButton").remove(); And Also $("#CustomButton").hide(); This code through my button is not hide.

How to hide that button?

toolbar: [{ name: "create", text: "@T("Admin.Common.AddNewRecord")" },{ name: "add_user", template: 'Send invoice to customer'}],

//Custom Toolbar Button Click
function oleuminvoiceDocketSubmit()
{
        $.ajax({
            dataType: "json",
            type: "POST",
            url: "@(Url.Action("Abc", "Def"))",
            data: {
                'id':InvoiceId,
                'selectedid':selectedIds,
                'method':'Ground'
            },
            success: function (response) {

            },
          });
}

Body:
$(document).ready(function () {
     // after grid initialization
     $("#CustomButton").kendoButton().data("kendoButton");
}

And in the success function of the ajax call use: $("#customButton").hide();


来源: stackexchange

问:
Settype integer changing the value in php
I have a field in my database called time. It contains UNIX timestamp. However the data type is a string and in php the date function expects an integer.

So i tried parsing the string to an integer but the value changes.

```<code>    $time = $value['time'];
    echo "Time string is $time<br/>";

    settype($time,'integer');
    echo "time intenger is".$time."<br/>";
</code>```

This is the output i get

Time string is 1499327190163

time intenger is2147483647

What am i doing wrong here? Or is there a better way to convert timestamp to a date? Thanks

EDIT : I just read the manual on settype and it said Maximum value for "int" is PHP_INT_MAX. Perhaps this could be my issue, would it be alright to change this, or should there be any security related concern in changing the max integer value?

答:
This is because the range (upper limit of) of integer is:

```<code>2147483647
</code>```

In layman terms,  a cup can't hold water of a bucket.

32-bit builds of PHP:

```<code>Integers can be from -2,147,483,648 to 2,147,483,647 (~ ± 2 billion)
</code>```

64-bit builds of PHP:

```<code>Integers can be from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (~ ± 9 quintillion)
</code>```

Check this answer

ContentLicense: CC BY-SA 3.0

Body:
I have a field in my database called time. It contains UNIX timestamp. However the data type is a string and in php the date function expects an integer.

So i tried parsing the string to an integer but the value changes.

    $time = $value['time'];
    echo "Time string is $time
";

    settype($time,'integer');
    echo "time intenger is".$time."
";

This is the output i get

Time string is 1499327190163

time intenger is2147483647

What am i doing wrong here? Or is there a better way to convert timestamp to a date? Thanks

EDIT : I just read the manual on settype and it said Maximum value for "int" is PHP_INT_MAX. Perhaps this could be my issue, would it be alright to change this, or should there be any security related concern in changing the max integer value?

Body:
This is because the range (upper limit of) of integer is:

2147483647

In layman terms,  a cup can't hold water of a bucket.

32-bit builds of PHP:

Integers can be from -2,147,483,648 to 2,147,483,647 (~ ± 2 billion)

64-bit builds of PHP:

Integers can be from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (~ ± 9 quintillion)

Check this answer


问:
Extract a function name inside a macro
In C, we often have to run such code

```<code>if (! somefun(x, y, z)) {
    perror("somefun")
}
</code>```

Is it possible to create a macro which, used as follows:

```<code>#define chkerr ...
chkerr(somefun(x, y, z));
</code>```

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

```<code>chkerr(somefun, x, y, z)
</code>```

答:
It's not possible to extract just the function name. The C processor sees the literals you pass as single tokens, which can't be manipulated. Your only options are to print the function with arguments like Aconcague suggests or pass the name as a separate parameter:

```<code>#define chkErr(FUNCTION_NAME, FUNCTION_CALL) \
if(!FUNCTION_CALL) \
{ \
    perror(#FUNCTION_NAME); \
}

chkErr(someFunction, someFunction(10, 12));
</code>```

Title: Extract a function name inside a macro

Body:
In C, we often have to run such code

if (! somefun(x, y, z)) {
    perror("somefun")
}

Is it possible to create a macro which, used as follows:

#define chkerr ...
chkerr(somefun(x, y, z));

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

chkerr(somefun, x, y, z)

Body:
It's not possible to extract just the function name. The C processor sees the literals you pass as single tokens, which can't be manipulated. Your only options are to print the function with arguments like Aconcague suggests or pass the name as a separate parameter:

#define chkErr(FUNCTION_NAME, FUNCTION_CALL) \
if(!FUNCTION_CALL) \
{ \
    perror(#FUNCTION_NAME); \
}

chkErr(someFunction, someFunction(10, 12));


问:
What are the implications of Image.cache?
The Image Qt Quick component has a cache property. The documentation on that property, however, is very scant. In particular, it does not say what the cache is used for, and when images are loaded from the cache.

Can you tell me the implications of setting Image.cache to either true or false?

I'm asking because I'm tempted to save a lot of memory by setting cache: false on all my Images.

The docs do say this:

Images are cached and shared internally, so if several Image items have the same source, only one copy of the image will be loaded.

But does this mean that cache: true only has a point when several Image items have the same source? And does it mean that cache: false results in no gain whatsoever?

Note: In my tests with ~1000 images mem usage dropped from 247MB to 237MB when I disabled cache. And this app has a lot of other things in it too. So I'm happy with this win. But my questions stand.

答:
The difference you have is in the margin of error. QML is very careless with memory management. Make sure the behavior is consistent before you write it off as a gain.

What the doc actually says about Image.cache is:

Specifies whether the image should be cached. The default value is
  true. Setting cache to false is useful when dealing with large images,
  to make sure that they aren't cached at the expense of small 'ui
  element' images.

Which I assume is that the image will be kept in (presumably) GPU RAM whereas non-cached images are transferred there on demand. As far as I know, all Images, visible or not, will take up system RAM, which has always been odd to me, since having an image that is solely for the purpose of visualizing on a GPU backend can actually omit the copy in RAM and only keep the image in VRAM.

The doc entry you quote looks like it concerns the scenegraph, that caching is implicit, which only makes sense, because there is no reason storing the same data twice, it will refcount each image url so that if it is used multiple times it will resolve to the same single packet of data. Image.cache has nothing to do with that cache.

At any rate, I'd say the only viable solution to make sizable gains is to do lazy loading. Using vectors won't save you much, since the images are internally cached rasterized. Using more compressed images will reduce the binary size, but they are still cached decoded in memory.

If your images are stuff like grayscale icon stencils, they render tremendously well to signed distance field representation. In my project I managed to reduce 83 MB worth of such icons to 1.25 MB of SDFs with no loss of quality, in fact with the SDFs I was able to enlarge the GUI even more without getting jagged edges. And the shader to render an SDF into a raster of the appropriate size is only a tad more complex than a flat color shader, so performance differences are negligible, but since this happens on the fly I also get the same amount of memory saved from both RAM and VRAM.


问:
How to change password masking character in Xamarin forms - Entry
I've currently faced a rather simple issue which eventually put me to a dead end. I am building an application that uses Xamarin Forms and want to change a masking character when user enters password from a bullet to an asterisk.

For entering password I'm using Entry control in Portable lib project in my content page (in VS2017 professional):

```<code><Entry x:Name="Entry_Password" Placeholder="Password" IsPassword="True" />
</code>```

I know that I probably should create a custom Renderer in Android project for this one, but would really appreciate how to do it for this specific purpose.

答:
An easyier way to do this would be to use a Converter to swap every letter in an asterisk and than when you request the value it is plain.

This is an interesting post that could help you with your problem: https://forums.xamarin.com/discussion/52354/is-there-a-way-to-partially-mask-an-entry-field-in-xamarin

It's imported to use oneway and not twoway!

Good luck

Body:
I've currently faced a rather simple issue which eventually put me to a dead end. I am building an application that uses Xamarin Forms and want to change a masking character when user enters password from a bullet to an asterisk.

For entering password I'm using Entry control in Portable lib project in my content page (in VS2017 professional):

<Entry x:Name="Entry_Password" Placeholder="Password" IsPassword="True" />

I know that I probably should create a custom Renderer in Android project for this one, but would really appreciate how to do it for this specific purpose.


问:
Save undo stack during macro run
I am wondering if there is a way to save ability to undo actions after macro has been run.
I do not care about results of macro - just need to undo actions that were done by user before macro.

Background:
I have a macro on the worksheet_change event that logs who and when made the change on this worksheet. I do not want it to restrict user's ability to undo his/her actions.

答:
This one is a bit old now but in case anyone is still trying to get this to work - I just tried setting the undo stack to be able undo the formatting on a column that a macro had reformatted and noticed that by doing that the full undo command worked (before I added this bit the undo was unavailable) - does not matter what the custom undo code contains (in my case I had not even created the routine yet), the application undo works perfectly

Application.OnUndo "Undo Amount Format", "sUndo_Col2"

Title: Save undo stack during macro run


问:
Active record column names convert to Array of hash
I am using ruby on rails 5 .. I want get active record column names in array of hash Format..
e.g

```<code>Customer.column_names
=> ["id", "key", "name", "domain_name", "description"]
</code>```

Now i want to convert this array to like

```<code> [{"name"=>"id"}, {"name"=>"key"}, {"name"=>"name"}, {"name"=>"domain_name"}, {"name"=>"description"}]
</code>```

Can anyone help me with this??

答:
You can use map to turn the elements into hashes:

```<code>result = Customer.column_names.map { |column| {"name" => column} }
#=> [{"name"=>"id"}, {"name"=>"key"}, {"name"=>"name"}, {"name"=>"domain_name"}, {"name"=>"description"}]
</code>```

Body:
I am using ruby on rails 5 .. I want get active record column names in array of hash Format..
e.g

Customer.column_names
=> ["id", "key", "name", "domain_name", "description"]

Now i want to convert this array to like

 [{"name"=>"id"}, {"name"=>"key"}, {"name"=>"name"}, {"name"=>"domain_name"}, {"name"=>"description"}]

Can anyone help me with this??

Body:
You can use map to turn the elements into hashes:

result = Customer.column_names.map { |column| {"name" => column} }
#=> [{"name"=>"id"}, {"name"=>"key"}, {"name"=>"name"}, {"name"=>"domain_name"}, {"name"=>"description"}]


问:
How to convert NSstring to Nsdate
I am getting response from service that

```<code>"created_at" = "Thu Jul 06 07:26:23 +0000 2017";
</code>```

i want to convert the string  into Nsdate  format
i do not know how to do it

答:
Use this code

(source::http://nsdateformatter.com)

```<code>NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"EEE MMM dd hh:mm:ss Z yyyy"];
    NSDate *date = [dateFormat dateFromString:[NSString stringWithFormat:@"Thu Jul 06 07:26:23 +0000 2017"]];
    NSLog(@"date is %@ ",date);
</code>```

Title: How to convert NSstring to Nsdate

Body:
I am getting response from service that

"created_at" = "Thu Jul 06 07:26:23 +0000 2017";

i want to convert the string  into Nsdate  format
i do not know how to do it

Body:
Use this code

(source::http://nsdateformatter.com)

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"EEE MMM dd hh:mm:ss Z yyyy"];
    NSDate *date = [dateFormat dateFromString:[NSString stringWithFormat:@"Thu Jul 06 07:26:23 +0000 2017"]];
    NSLog(@"date is %@ ",date);


问:
Karaf bundles not loaded from .kar on deploy
I have a Karaf application with three bundles in a .kar file, specified by a features.xml.

When I deploy the compiled .kar (using maven plug-in) on the target VM, the main bundle loads and updates in Karaf, but it appears that a dependent bundle (add-on capabilities), is not extracted and deployed - Karaf tries to get the bundle from the /system/ repository instead of the .kar.

Deployment works on my Dev machine, by I suspect the dependent bundle is being pulled from the local Maven repo which is up to date due to the build process.

Currently to work around this on the target machine I have to copy my local repo to the [karaf.root]/system/ folder in order for all bundles to get updated when the .kar is hot-deployed.

Does anyone know how to configure the features .xml so bundles are pulled out of the .kar instead of [initially] from the /system folder?
My features.xml file is;

```<code><features name="${project.artifactId}-${project.version}"
xmlns="http://karaf.apache.org/xmlns/features/v1.3.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.3.0 http://karaf.apache.org/xmlns/features/v1.3.0">

<feature name="${project.artifactId}" install="auto" version="${project.version}"
    description="${project.description}">
    <bundle dependency="true">mvn:com.google.code.gson/gson/${gson.version}</bundle>
    <bundle>mvn:uk.co.company.product/product-common-api/${project.version}</bundle>
    <bundle>mvn:uk.co.company.product/product-core-services/${project.version}</bundle>
    <bundle>mvn:uk.co.company.product/product-scenario-exporter/${project.version}</bundle>

<feature prerequisite="true">camel-jetty</feature>
<feature prerequisite="true">webconsole</feature>
</feature>
</code>```

I've checked and the required bundles (i.e. common-api) is included within the compiled kar file's repository folder.

答:
You simply use a mvn url for the bundle you need. The content of the kar will be one source for such dependencies. I assume that you have an error in your kar. Can you post your kar file here (maybe slimmed down to neutral content)?

What is the file structure inside your kar?  It should contains a directory repository and inside should be subdirectories and jars like in a maven repository. Only then will the mvn url be resolved.

Body:
I have a Karaf application with three bundles in a .kar file, specified by a features.xml.

When I deploy the compiled .kar (using maven plug-in) on the target VM, the main bundle loads and updates in Karaf, but it appears that a dependent bundle (add-on capabilities), is not extracted and deployed - Karaf tries to get the bundle from the /system/ repository instead of the .kar.

Deployment works on my Dev machine, by I suspect the dependent bundle is being pulled from the local Maven repo which is up to date due to the build process.

Currently to work around this on the target machine I have to copy my local repo to the [karaf.root]/system/ folder in order for all bundles to get updated when the .kar is hot-deployed.

Does anyone know how to configure the features .xml so bundles are pulled out of the .kar instead of [initially] from the /system folder?
My features.xml file is;

<features name="${project.artifactId}-${project.version}"
xmlns="http://karaf.apache.org/xmlns/features/v1.3.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.3.0 http://karaf.apache.org/xmlns/features/v1.3.0">

<feature name="${project.artifactId}" install="auto" version="${project.version}"
    description="${project.description}">
    <bundle dependency="true">mvn:com.google.code.gson/gson/${gson.version}</bundle>
    <bundle>mvn:uk.co.company.product/product-common-api/${project.version}</bundle>
    <bundle>mvn:uk.co.company.product/product-core-services/${project.version}</bundle>
    <bundle>mvn:uk.co.company.product/product-scenario-exporter/${project.version}</bundle>

<feature prerequisite="true">camel-jetty</feature>
<feature prerequisite="true">webconsole</feature>
</feature>

I've checked and the required bundles (i.e. common-api) is included within the compiled kar file's repository folder.


问:
Adding comments to article in Rails 5 (deeply nested resources)
I have a Rails app that has three main models: Qn, Ans, and Comments. I've been doing okay with 1-level-deep nested resources, but these three resources are nested deeply (Comments is shallowly nested) and they are all displayed in one single view, which makes it very confusing.

In a url like: http://localhost:3000/questions/2, the user can see all @question.answers displayed using a loop. In each of those answers, the user can see the answer.comments displayed using a loop. Below each answer, the user can also submit a new comment.

But after attempting several times to implement a 1) loop displaying all comments and 2) form for new comment, I always get some error along the lines of:

```<code>undefined method `model_name' for {:url=>"/questions/4/answers/2/comments/new"}:Hash
</code>```

So I tried to pass in params @commentable instead of the answer, or point to the specific controller and action and so on, but none of these methods worked. I am guessing that I have an issue with my controllers to begin with, but I cannot seem to figure out what.

routes.rb (top ommited)

```<code># Resources
resources :sessions
resources :users
resources :bookmarks # to be implemented later

resources :questions do
  resources :answers do
    resources :comments, shallow: true
  end
end
</code>```

Question model

```<code>class Question < ApplicationRecord
  has_many :answers
  has_many :bookmarks #later
end
</code>```

Answer model:

```<code>class Answer < ApplicationRecord
  belongs_to :question
  has_many :comments, as: :commentable

  has_many :likes, as: :likeable
  validates :answercontent, length: {minimum: 50}
end
</code>```

Comment model:

```<code>class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end
</code>```

The show.html.erb (of QuestionsController)

```<code><% @question.answers.each do |answer| %>
// ommited
<!-- Comments -->
<% answer.comments.each do |comment| %>
   <%= comment.content %>
   <br>
<% end %>

<!-- Submit new comment -->
<%= form_for(url: new_question_answer_comment_path, comment: {answer_id: answer.id, question_id: @question.id}) do |f| %>
   <%= f.text_area :content %>
   <%= f.submit "Submit" %>
<% end %>
<% end %>
</code>```

QuestionsController (new, create, destroy ommited for brevity)

```<code>class QuestionsController < ApplicationController
def index
    @questions = Question.all
end

def show
    @question = Question.find(params[:id])
    @answers = Answer.all

    # Delete only appears when num_ans is 0
    @deletable = (current_user== User.find(@question.user_id)) && (@question.answers.all.size==0)

end

private
  def question_params
    params.require(:question).permit(:picture_url, :country, :educational_level, :topic)
  end

end
</code>```

AnswersController (edit, update, destroy ommited for brevity)

```<code>class AnswersController < ApplicationController

def create
    @question = Question.find(params[:question_id])
    @answer = @question.answers.create(answer_params)
    @answer.question_id = @question.id
    @answer.user_id = current_user.id

    if @answer.save
        redirect_to @question
    else
        render :new
    end
end

private
  def answer_params
    params.require(:answer).permit(:user_id, :question_id, :answercontent)
  end
end
</code>```

CommentsController

```<code>class CommentsController < ApplicationController
before_filter: load_commentable

def index
  @commentable = Answer.find(params[:answer_id])
  @comments = @commentable.comments
end

def new
   @comment = @commentable.comments.new
end

def create
  @comment = @commentable.comments.new(params[:comment])
    if @comment.save
     redirect_to @commentable
  else
    render :new
  end
end

# From RailsCast ep.154
private
def load_commentable
  resource, id = request.path.split('/')[1,2]
  @commentable = resource.singularize.classify.constantize.find(id)
end
end
</code>```

The routes
are quite messy right now so I will just post where the comments are:

```<code> question_answer_comments GET    /questions/:question_id/answers/:answer_id/comments(.:format)     comments#index
                        POST   /questions/:question_id/answers/:answer_id/comments(.:format)     comments#create
new_question_answer_comment GET    /questions/:question_id/answers/:answer_id/comments/new(.:format) comments#new
           edit_comment GET    /comments/:id/edit(.:format)                                      comments#edit
                comment GET    /comments/:id(.:format)                                           comments#show
                        PATCH  /comments/:id(.:format)                                           comments#update
                        PUT    /comments/:id(.:format)                                           comments#update
                        DELETE /comments/:id(.:format)                                           comments#destroy
</code>```

Thanks in advance for the help.

Update:

To give you more info on what solutions I attempted:
1. Passing in two params like:

```<code># Resources
resources :sessions
resources :users
resources :bookmarks # to be implemented later

resources :questions do
  resources :answers do
    resources :comments, shallow: true
  end
end
</code>```0

Gave me:

```<code># Resources
resources :sessions
resources :users
resources :bookmarks # to be implemented later

resources :questions do
  resources :answers do
    resources :comments, shallow: true
  end
end
</code>```1

Using @commentable (which is basically the answer) gives me an error saying that 'the id in @commentable.id doesn't exist as @commentable is nil'.

So I think the problem is that answer or @commentable is nil. But I specified it in the loop and in the controller too. So what else may I try?

答:
form_for expects record as first argument, in your case it should be a comment instance. Also <s>new_question_answer_comment_path expects values for question_id and answer_id keys</s>, as you are creating a new comment, the route should be question_answer_comments not new_question_answer_comment so your form_for should be

```<code><%= form_for Comment.new,url: question_answer_comments_path(@question,answer) do |f| %>
  <%= f.text_area :content %>
  <%= f.submit "Submit" %>
<% end %>
</code>```

or just

```<code><%= form_for [Comment.new,@question,answer] do |f| %>
  <%= f.text_area :content %>
  <%= f.submit "Submit" %>
<% end %>
</code>```

Body:
I have a Rails app that has three main models: Qn, Ans, and Comments. I've been doing okay with 1-level-deep nested resources, but these three resources are nested deeply (Comments is shallowly nested) and they are all displayed in one single view, which makes it very confusing.

In a url like: http://localhost:3000/questions/2, the user can see all @question.answers displayed using a loop. In each of those answers, the user can see the answer.comments displayed using a loop. Below each answer, the user can also submit a new comment.

But after attempting several times to implement a 1) loop displaying all comments and 2) form for new comment, I always get some error along the lines of:

undefined method `model_name' for {:url=>"/questions/4/answers/2/comments/new"}:Hash

So I tried to pass in params @commentable instead of the answer, or point to the specific controller and action and so on, but none of these methods worked. I am guessing that I have an issue with my controllers to begin with, but I cannot seem to figure out what.

routes.rb (top ommited)

# Resources
resources :sessions
resources :users
resources :bookmarks # to be implemented later

resources :questions do
  resources :answers do
    resources :comments, shallow: true
  end
end

Question model

class Question < ApplicationRecord
  has_many :answers
  has_many :bookmarks #later
end

Answer model:

class Answer < ApplicationRecord
  belongs_to :question
  has_many :comments, as: :commentable

  has_many :likes, as: :likeable
  validates :answercontent, length: {minimum: 50}
end

Comment model:

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

The show.html.erb (of QuestionsController)

<% @question.answers.each do |answer| %>
// ommited

<% answer.comments.each do |comment| %>
   <%= comment.content %>

<% end %>

<%= form_for(url: new_question_answer_comment_path, comment: {answer_id: answer.id, question_id: @question.id}) do |f| %>
   <%= f.text_area :content %>
   <%= f.submit "Submit" %>
<% end %>
<% end %>

QuestionsController (new, create, destroy ommited for brevity)

class QuestionsController < ApplicationController
def index
    @questions = Question.all
end

def show
    @question = Question.find(params[:id])
    @answers = Answer.all

    # Delete only appears when num_ans is 0
    @deletable = (current_user== User.find(@question.user_id)) && (@question.answers.all.size==0)

end

private
  def question_params
    params.require(:question).permit(:picture_url, :country, :educational_level, :topic)
  end

end

AnswersController (edit, update, destroy ommited for brevity)

class AnswersController < ApplicationController

def create
    @question = Question.find(params[:question_id])
    @answer = @question.answers.create(answer_params)
    @answer.question_id = @question.id
    @answer.user_id = current_user.id

    if @answer.save
        redirect_to @question
    else
        render :new
    end
end

private
  def answer_params
    params.require(:answer).permit(:user_id, :question_id, :answercontent)
  end
end

CommentsController

class CommentsController < ApplicationController
before_filter: load_commentable

def index
  @commentable = Answer.find(params[:answer_id])
  @comments = @commentable.comments
end

def new
   @comment = @commentable.comments.new
end

def create
  @comment = @commentable.comments.new(params[:comment])
    if @comment.save
     redirect_to @commentable
  else
    render :new
  end
end

# From RailsCast ep.154
private
def load_commentable
  resource, id = request.path.split('/')[1,2]
  @commentable = resource.singularize.classify.constantize.find(id)
end
end

The routes
are quite messy right now so I will just post where the comments are:

 question_answer_comments GET    /questions/:question_id/answers/:answer_id/comments(.:format)     comments#index
                        POST   /questions/:question_id/answers/:answer_id/comments(.:format)     comments#create
new_question_answer_comment GET    /questions/:question_id/answers/:answer_id/comments/new(.:format) comments#new
           edit_comment GET    /comments/:id/edit(.:format)                                      comments#edit
                comment GET    /comments/:id(.:format)                                           comments#show
                        PATCH  /comments/:id(.:format)                                           comments#update
                        PUT    /comments/:id(.:format)                                           comments#update
                        DELETE /comments/:id(.:format)                                           comments#destroy

Thanks in advance for the help.

Update:

To give you more info on what solutions I attempted:
1. Passing in two params like:

<%= form_for([answer, @comment], url: new_question_answer_comment_path(answer.id, @question.id)) do |f| %>

Gave me:

First argument in form cannot contain nil or be empty

Using @commentable (which is basically the answer) gives me an error saying that 'the id in @commentable.id doesn't exist as @commentable is nil'.

So I think the problem is that answer or @commentable is nil. But I specified it in the loop and in the controller too. So what else may I try?

Body:
form_for expects record as first argument, in your case it should be a comment instance. Also <s>new_question_answer_comment_path expects values for question_id and answer_id keys</s>, as you are creating a new comment, the route should be question_answer_comments not new_question_answer_comment so your form_for should be

<%= form_for Comment.new,url: question_answer_comments_path(@question,answer) do |f| %>
  <%= f.text_area :content %>
  <%= f.submit "Submit" %>
<% end %>

or just

<%= form_for [Comment.new,@question,answer] do |f| %>
  <%= f.text_area :content %>
  <%= f.submit "Submit" %>
<% end %>


问:
nearby notification and turning Bluetooth OFF-ON
After getting a Nearby notification if I swipe away the notification, in order to get the same notification again I need to force the mobile phone to scan for the beacons again. Can turning OFF the Bluetooth and turning it ON again will work ? Does this Bluetooth OFF-ON can initiate the scanning of the beacons ?

It does seem to work. But the behavior is hard to understand and predict. After turning the Bluetooth ON again, sometimes the mobile detects all of the beacons within a minutes and shows all the notifications, sometime the mobile detect only one beacon and sometimes mobiles does not show any Nearby notification again.

How does turning Bluetooth OFF-ON affects the scanning the beacons ?
Thanks.

答:
We generally interpret swiping away as an indicator of temporary disinterest in a notification, so there's some backoff behavior that tries to prevent a beacon from spamming users with unwanted notifications.

It may help us to understand what you're trying to achieve, and we can suggest alternative ways. For instance, Notifications has a developer mode which changes the way we show notifications in cases where you're debugging or trying things out.


问:
angular 2 filter BehaviorSubject
i try to filter a BehaviorSubject in Angular 2. The commissions object in the service will get data via a http request. But because it's instanced with "null" there is an error at the filter code line.

The error:

Cannot read property '0' of null

at .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)

Here ist the code:

commissionService:

```<code>public commissions: Subject<Commission[]> = new BehaviorSubject<Commission[]>(null);
</code>```

in the component:

```<code>  ngOnInit() {
    this.commissionService.commissions
        .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)
        .subscribe(data => {console.log(data); })
  }
</code>```

Is it possible at all that this filter will work if I change the this.commissionid? Thanks!

答:
now i found a solutions, thanks for you help, here the complete code:</p>

```<code>  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.commissionid = params.commissionid;
      if (this.commissionid) { this.init_obj(this.commissionid); }
    });

  }

  init_obj(id) {
    this.commissionService.commissions
        .map(function(data) {
          if (data) { return data.find(commission => commission._id === id); }
        })
        .subscribe(data => {
          if (data) { this.commission = data; }
        })

  }
</code>```

Title: angular 2 filter BehaviorSubject

Body:
i try to filter a BehaviorSubject in Angular 2. The commissions object in the service will get data via a http request. But because it's instanced with "null" there is an error at the filter code line.

The error:

Cannot read property '0' of null

at .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)

Here ist the code:

commissionService:

public commissions: Subject<Commission[]> = new BehaviorSubject<Commission[]>(null);

in the component:

  ngOnInit() {
    this.commissionService.commissions
        .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)
        .subscribe(data => {console.log(data); })
  }

Is it possible at all that this filter will work if I change the this.commissionid? Thanks!

Body:
now i found a solutions, thanks for you help, here the complete code:

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.commissionid = params.commissionid;
      if (this.commissionid) { this.init_obj(this.commissionid); }
    });

  }

  init_obj(id) {
    this.commissionService.commissions
        .map(function(data) {
          if (data) { return data.find(commission => commission._id === id); }
        })
        .subscribe(data => {
          if (data) { this.commission = data; }
        })

  }


问:
TextInput OnChange in React native
Please help me. I have a TextInput, my problem is when I type the numeric value, that value going to multiply with some number. When I type 1000, this will get saved to state as 1000, but it saves to store as 100. The results differ.

```<code> <TextInput
  onChangeText={this.handle_bill_Amount}
  style={styles.input}
  placeholder="Amount"
  value={this.state.Amount}
  keyboardType = 'numeric'
  enablesReturnKeyAutomatically={true}
  placeholderTextColor = "#824242"
  underlineColorAndroid="transparent">
 </TextInput>

  handle_bill_Amount = Amount => {
  this.setState({ Amount})
  let billamt = this.state.Amount;
  console.log(billamt);
  }

 constructor(props) {
    super(props);
    this.state = {
    Amount: '',
    }
    this.handle_bill_Amount = this.handle_bill_Amount.bind(this);
}
</code>```

Guys help me please!

答:
I think results are not different, it's just your console.log which confuses you. It will print out 100 instead of 1000 because your are doing console log inside the function which is setting the new state. Try to do it somewhere else, e.g. in componentWillReceiveProps, or componentWillUpdate and you'll see it's ok.

Hope this helps.

Title: TextInput OnChange in React native

Body:
Please help me. I have a TextInput, my problem is when I type the numeric value, that value going to multiply with some number. When I type 1000, this will get saved to state as 1000, but it saves to store as 100. The results differ.

 <TextInput
  onChangeText={this.handle_bill_Amount}
  style={styles.input}
  placeholder="Amount"
  value={this.state.Amount}
  keyboardType = 'numeric'
  enablesReturnKeyAutomatically={true}
  placeholderTextColor = "#824242"
  underlineColorAndroid="transparent">
 </TextInput>

  handle_bill_Amount = Amount => {
  this.setState({ Amount})
  let billamt = this.state.Amount;
  console.log(billamt);
  }

 constructor(props) {
    super(props);
    this.state = {
    Amount: '',
    }
    this.handle_bill_Amount = this.handle_bill_Amount.bind(this);
}

Guys help me please!


问:
Bazel cc_library dependency on other cc_library when each compile with a different crosstool
I have a code generator tool that generates C/C++ code. This code generator tool is compiled with crosstool1. The generated C/C++ code needs to be compiled with crosstool2.

So the actions are:

Using Crosstool1 compile 'code_generator'.

Execute 'code_generator' and generate 'generated_code.cpp'

Using Crosstool2 compile 'generated_code.cpp'

Is it possible to make a cc_library() determine the crosstool to use? I saw that Skylark rules now allow a 'toolchains' parameter which I'm not sure how this is used, also I do not want to do the heavy lifting of C/C++ compiling bare bone with Skylark.

Is there an example of using a proper Host Crosstool and Target Crosstool except for the Tenserflow example? I get a headache each time I read it :D

答:
Assume //crosstool1:toolchain is a label for cc_toolchain_suite rule describing first crosstool, //crosstool2:toolchain is a label for cc_toolchain_suite for second crosstool, and the build file for the project is:

```<code>cc_binary(
    name = "generator",
    srcs = [ "main.cc" ],
)

genrule(
    name = "generate",
    outs = ["generated.cc"],
    cmd = "$(location :generator) > $@",
    tools = [":generator"],
)

cc_binary(
    name = "generated",
    srcs = [ "generated.cc" ],
)
</code>```

Then running:

```<code>bazel build --host_crosstool_top=//crosstool1:toolchain --crosstool_top=//crosstool2:toolchain :generated
</code>```

will do exactly what you describe, it will use crosstool1 to build :generator, and crosstool2 to build generated. Genrules use host configuration by default, so all should just work.

Body:
Assume //crosstool1:toolchain is a label for cc_toolchain_suite rule describing first crosstool, //crosstool2:toolchain is a label for cc_toolchain_suite for second crosstool, and the build file for the project is:

cc_binary(
    name = "generator",
    srcs = [ "main.cc" ],
)

genrule(
    name = "generate",
    outs = ["generated.cc"],
    cmd = "$(location :generator) > $@",
    tools = [":generator"],
)

cc_binary(
    name = "generated",
    srcs = [ "generated.cc" ],
)

Then running:

bazel build --host_crosstool_top=//crosstool1:toolchain --crosstool_top=//crosstool2:toolchain :generated

will do exactly what you describe, it will use crosstool1 to build :generator, and crosstool2 to build generated. Genrules use host configuration by default, so all should just work.


问:
The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation
i tried to install pod on ios project but getting this errors
diff: /Podfile.lock: No such file or directory
diff: /Manifest.lock: No such file or directory
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation .
please suggest me something.</p>

答: Delete your podfile.lock file and try running pod install again. </p>


问:
Vue.Js - data not updating
I am very new to Vue.Js so please forgive me for this newbie question. I have a result variable in my data() method, and when I try to update the result variable using this.result = result, in the browser, the original variable remains the same. I don'; know what I am doing wrong. I have googled for a few hours and found no answer. As always, any help is greatly appreciated. I don't know why my data isn't updating. here is my code;

play.js

```<code>    Vue.component('game', {
        template: '#game-template',

        data: function () {
            return {
                ready: null,
                result: 0
            }
        },
        props: ['gameid'],

        methods: {
            loadGame: function () {
                this.$http.get('../api/games/ready/' + this.gameid).then(function (response) {
                    if (response.body === '1') {
                        // process coinflip upon ready game
                        var result = Math.floor((Math.random() * 2) + 1);
                        this.result = result;
                        console.log(this.result);

                    }

                }.bind(this));
            }
        },

        ready: function () {
            this.loadGame();

            setInterval(function () {
                this.loadGame();
            }.bind(this), 5000);
        }
    });

new Vue({
    el: '#app'
});
</code>```

View:

```<code>extends('layouts.app')

@section('content')

    <div id="app">
        <game v-bind:gameid="{{$gameid}}"></game>
    </div>

    <template id="game-template">
        <div>
            <strong>Result:</strong> @{{ result }}

        </div>
    </template>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.js"></script>

    <script src="../js/play.js"></script>

    @endsection
</code>```

答:
```<code>1 == true //true
1 === true // false
</code>```

I think the problem may lies in the fact that HTTP returns true, not 1.

Title: Vue.Js - data not updating

Body:
I am very new to Vue.Js so please forgive me for this newbie question. I have a result variable in my data() method, and when I try to update the result variable using this.result = result, in the browser, the original variable remains the same. I don'; know what I am doing wrong. I have googled for a few hours and found no answer. As always, any help is greatly appreciated. I don't know why my data isn't updating. here is my code;

play.js

    Vue.component('game', {
        template: '#game-template',

        data: function () {
            return {
                ready: null,
                result: 0
            }
        },
        props: ['gameid'],

        methods: {
            loadGame: function () {
                this.$http.get('../api/games/ready/' + this.gameid).then(function (response) {
                    if (response.body === '1') {
                        // process coinflip upon ready game
                        var result = Math.floor((Math.random() * 2) + 1);
                        this.result = result;
                        console.log(this.result);

                    }

                }.bind(this));
            }
        },

        ready: function () {
            this.loadGame();

            setInterval(function () {
                this.loadGame();
            }.bind(this), 5000);
        }
    });

new Vue({
    el: '#app'
});

View:

extends('layouts.app')

@section('content')

        <game v-bind:gameid="{{$gameid}}"></game>

    <template id="game-template">

            Result: @{{ result }}

    </template>

    @endsection

Body:
1 == true //true
1 === true // false

I think the problem may lies in the fact that HTTP returns true, not 1.


问:
What are the best practices to encrypt passwords stored in MySql using PhP?
I am seeking advice on how to securely store passwords in MySQL using PHP.

Overlooking the limitations of PHP itself, I want to know more about salting, hashing, and encrypting these bad boys.

Obviously people will continue to use weak passwords unless forced to do otherwise, but it's how I am storing them that is important to me. My user's passwords are far more important to me than the database itself, and as such I want to keep them in such a way that it will be painstaking and monotonous for any script kiddie trying reverse. Obviously with due diligence just about anything can be defeated, but I wouldn't mind making this particularly bothersome.

There are two scenarios we are looking at.

The kiddie has a complete copy of the database.

The kiddie has a complete copy of the PHP used to craft the password, and the database.

Any and all advice on this topic is graciously appreciated.

答: Taking advice from here, for added fun you can dynamically change your salt as well. For example, use different salts for usernames of different length, use the user's registration date as the salt. This makes it that even if someone DOES get to your database, they can't just re-generate the hash, they have to calculate a hash table for each salt that you used.</p>

ContentLicense: CC BY-SA 2.5


问:
Using psql how do I list extensions installed in a database?
How do I list all extensions that are already installed in a database or schema from psql?

See also

Finding a list of available extensions that PostgreSQL ships with

答:
Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions.

See pg_available_extensions and pg_available_extension_versions.

ContentLicense: CC BY-SA 4.0


问:
Android Java - have button change tab
I recently started coding and have been following tutorials. I'm trying to learn how to use a tab activity right now and followed a tutorial to do it by swiping pages. Here's what I've come up with

```<code>public class MainActivity extends FragmentActivity {

ViewPager pager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn1 = (Button) findViewById(R.id.btn1);
    Button btn2 = (Button) findViewById(R.id.btn2);
    pager = (ViewPager) findViewById(R.id.viewPager);

    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}

public void onClickBtn1(View v) {
    //when clicked, take to Main2Activity.java
}

public void onClickBtn2(View v) {
    //when clicked, take to Main3Activity.java

}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pos) {
        switch(pos) {

            case 0: return Main2Activity.newInstance("FirstFragment, Instance 1");
            case 1: return Main3Activity.newInstance("SecondFragment, Instance 1");
            case 2: return Main4Activity.newInstance("ThirdFragment, Instance 1");
            default: return Main4Activity.newInstance("ThirdFragment, Default");
        }
    }

    @Override
    public int getCount() {
        return 3;
    }
}
}
</code>```

Can someone please explain to me what's going on in the MyPageAdapter class please?

Also, is it possible that instead of swiping pages that I use a button? For instance, onClickBtn1 will take me to Main2Activity and onClickBtn2 will take me to Main3Activity. I'd like to continue using the tabs instead of creating a new intent.

Thanks in advance!

答:
if you want to use tabs, you could use 4 fragments in an activity and manage them with ViewPager, by this you can go from one to another by clicking on the tabs and swipe left and right

```<code>    private void initPager() {
    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    mAdapter = new MyPagerAdapter(getSupportFragmentManager());

    mAdapter.addFragment(firstFragment.newInstance(), getString(R.string.first_fragment_Title));
    mAdapter.addFragment(secondFragment.newInstance(), getString(R.string.second_fragment_title));
    pager.setAdapter(mAdapter);

    TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
    tabs.setupWithViewPager(pager);
    TextView firstFragmentTabTitle = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, null);
    firstFragmentTabTitle.setText(mAdapter.getPageTitle(0).toString());
    TextView secondFragmentTabTitle = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, null);
    secondFragmentTabTitle.setText(mAdapter.getPageTitle(1).toString());

    tabs.getTabAt(0).setCustomView(firstFragmentTabTitle);
    tabs.getTabAt(1).setCustomView(secondFragmentTabTitle);
    pager.setCurrentItem(mAdapter.getCount());
}
</code>```

and the main activity XML add view pager and tab layout like this :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".fragments.BankCounterFragment">

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutDirection="ltr"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:contentInsetEnd="16dp"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start|center_vertical"
            android:gravity="center|start"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"/>
    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:layoutDirection="ltr"
        app:tabGravity="fill"
        app:tabIndicatorColor="@android:color/white"
        app:tabIndicatorHeight="3dp"
        app:tabMode="fixed"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>
</code>```

Title: Android Java - have button change tab

Body:
I recently started coding and have been following tutorials. I'm trying to learn how to use a tab activity right now and followed a tutorial to do it by swiping pages. Here's what I've come up with

public class MainActivity extends FragmentActivity {

ViewPager pager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn1 = (Button) findViewById(R.id.btn1);
    Button btn2 = (Button) findViewById(R.id.btn2);
    pager = (ViewPager) findViewById(R.id.viewPager);

    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}

public void onClickBtn1(View v) {
    //when clicked, take to Main2Activity.java
}

public void onClickBtn2(View v) {
    //when clicked, take to Main3Activity.java

}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pos) {
        switch(pos) {

            case 0: return Main2Activity.newInstance("FirstFragment, Instance 1");
            case 1: return Main3Activity.newInstance("SecondFragment, Instance 1");
            case 2: return Main4Activity.newInstance("ThirdFragment, Instance 1");
            default: return Main4Activity.newInstance("ThirdFragment, Default");
        }
    }

    @Override
    public int getCount() {
        return 3;
    }
}
}

Can someone please explain to me what's going on in the MyPageAdapter class please?

Also, is it possible that instead of swiping pages that I use a button? For instance, onClickBtn1 will take me to Main2Activity and onClickBtn2 will take me to Main3Activity. I'd like to continue using the tabs instead of creating a new intent.

Thanks in advance!

Body:
if you want to use tabs, you could use 4 fragments in an activity and manage them with ViewPager, by this you can go from one to another by clicking on the tabs and swipe left and right

    private void initPager() {
    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    mAdapter = new MyPagerAdapter(getSupportFragmentManager());

    mAdapter.addFragment(firstFragment.newInstance(), getString(R.string.first_fragment_Title));
    mAdapter.addFragment(secondFragment.newInstance(), getString(R.string.second_fragment_title));
    pager.setAdapter(mAdapter);

    TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
    tabs.setupWithViewPager(pager);
    TextView firstFragmentTabTitle = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, null);
    firstFragmentTabTitle.setText(mAdapter.getPageTitle(0).toString());
    TextView secondFragmentTabTitle = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, null);
    secondFragmentTabTitle.setText(mAdapter.getPageTitle(1).toString());

    tabs.getTabAt(0).setCustomView(firstFragmentTabTitle);
    tabs.getTabAt(1).setCustomView(secondFragmentTabTitle);
    pager.setCurrentItem(mAdapter.getCount());
}

and the main activity XML add view pager and tab layout like this :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".fragments.BankCounterFragment">

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutDirection="ltr"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:contentInsetEnd="16dp"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start|center_vertical"
            android:gravity="center|start"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"/>
    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:layoutDirection="ltr"
        app:tabGravity="fill"
        app:tabIndicatorColor="@android:color/white"
        app:tabIndicatorHeight="3dp"
        app:tabMode="fixed"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>


问:
Mouseover, mouseEnter
I have a FAQ and Question page. And if a user hover with his mouse over a question, then the answer will be shown.

But if you will now hover over a question all the answers are shown. what not has to be. Only the answere of the selected question has to be visible.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>A One Page Faq</title>
    <link href="Content/site.css" rel="stylesheet">
    <script src="Scripts/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.answer').hide();
            var $answer = $(this).next('.answer');
            $('.main h2').mouseover(function () {
                $('.answer').show();
                $answer.slideDown();
                $(this).addClass('close');
            });
            $('.main h2').mouseout(function () {
                $('.answer').hide();
                $answer.fadeOut();
                 $(this).removeClass('close');
            });

        }); // end ready
    </script>
</head>
<body>
    <div class="wrapper">
        <div class="content">
            <div class="main">
                <h1>A One Page FAQ</h1>
                <div class="faq">
                    <h2>I've heard that JavaScript is the long-lost fountain of youth. Is this true?</h2>
                    <div class="answer">
                        <p>Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)</p>
                    </div>
                </div>
                <div class="faq">
                    <h2>Can JavaScript really solve all of my problems?</h2>
                    <div class="answer">
                        <p>Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.</p>
                    </div>
                </div>
                <div class="faq">
                    <h2>Is there nothing JavaScript <em>can’t</em> do?</h2>
                    <div class="answer">
                        <p>Why, no there isn’t! It’s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that’s one smart programming language!</p>
                    </div>
                </div>
            </div>
        </div>
        <footer>
            <p>JavaScript & jQuery: The Missing Manual, 3rd Edition, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
        </footer>
    </div>
</body>
</html>
</code>```

Thank you

If I do it like this:

```<code> $(document).ready(function () {
            $('.answer').hide();
            var $answer = $(this).next('.answer');

            $('.main h2').mouseover(function (e) {
                $('.answer').hide();//Hide All Other Answers
                $(e).closest('.answer').show();//Show Closest Answer To Question
            });

            $('.main h2').mouseout(function (e) {
                $('.answer').hide();
            });
</code>```

nothing happens

答:
this happens because you use class selector which actually select all elements has this class $('.answer').show();

you need to change your code to select the closest answer to the question and show it to be like

```<code>            $('.main h2').mouseover(function (e) {
               $('.answer').hide();//Hide All Other Answers
               $(e).closest('.answer').show();//Show Closest Answer To Question

            });
</code>```

and for Mouse Out

```<code>$('.main h2').mouseout(function (e) {
   $('.answer').hide();
});
</code>```

Title: Mouseover, mouseEnter

Body:
I have a FAQ and Question page. And if a user hover with his mouse over a question, then the answer will be shown.

But if you will now hover over a question all the answers are shown. what not has to be. Only the answere of the selected question has to be visible.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>A One Page Faq</title>
    <link href="Content/site.css" rel="stylesheet">

A One Page FAQ

I've heard that JavaScript is the long-lost fountain of youth. Is this true?

Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)

Can JavaScript really solve all of my problems?

Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.

Is there nothing JavaScript can’t do?

Why, no there isn’t! It’s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that’s one smart programming language!

JavaScript & jQuery: The Missing Manual, 3rd Edition, by David McFarland. Published by O'Reilly Media, Inc.

Thank you

If I do it like this:

 $(document).ready(function () {
            $('.answer').hide();
            var $answer = $(this).next('.answer');

            $('.main h2').mouseover(function (e) {
                $('.answer').hide();//Hide All Other Answers
                $(e).closest('.answer').show();//Show Closest Answer To Question
            });

            $('.main h2').mouseout(function (e) {
                $('.answer').hide();
            });

nothing happens

Body:
this happens because you use class selector which actually select all elements has this class $('.answer').show();

you need to change your code to select the closest answer to the question and show it to be like

            $('.main h2').mouseover(function (e) {
               $('.answer').hide();//Hide All Other Answers
               $(e).closest('.answer').show();//Show Closest Answer To Question

            });

and for Mouse Out

$('.main h2').mouseout(function (e) {
   $('.answer').hide();
});


答:
Replace this

```<code> $('.main h2').mouseover(function () {
     $('.answer').show();
     $answer.slideDown();
     $(this).addClass('close');
 });
 $('.main h2').mouseout(function () {
     $('.answer').hide();
     $answer.fadeOut();
     $(this).removeClass('close');
 });
</code>```

With

```<code>$('.main h2').mouseover(function () {
   $(this).siblings('.answer').show();
   $(this).siblings('.answer').slideDown();
   $(this).addClass('close');
});
$('.main h2').mouseout(function () {
   $(this).siblings('.answer').hide();
   $(this).siblings('.answer').fadeOut();
   $(this).removeClass('close');
});
</code>```

it will helps you.

Title: Mouseover, mouseEnter

Body:
Replace this

 $('.main h2').mouseover(function () {
     $('.answer').show();
     $answer.slideDown();
     $(this).addClass('close');
 });
 $('.main h2').mouseout(function () {
     $('.answer').hide();
     $answer.fadeOut();
     $(this).removeClass('close');
 });

With

$('.main h2').mouseover(function () {
   $(this).siblings('.answer').show();
   $(this).siblings('.answer').slideDown();
   $(this).addClass('close');
});
$('.main h2').mouseout(function () {
   $(this).siblings('.answer').hide();
   $(this).siblings('.answer').fadeOut();
   $(this).removeClass('close');
});

it will helps you.


问:
Npm ERR! Missing Script: Start when deploying to heroku
I do have a procfile:

```<code>web: node server.js
</code>```

here's my package.json:

```<code>{
"name": "easyrtc_server_example",
"version": "0.1.6",
"author": "Priologic Software Inc. info@priologic.com (http://priologic.com/)",
"description" : "Simple EasyRTC server example which includes EasyRTC, Express, and Socket.io",
"main":"server.js",
"private": true,

"scripts": {
"start": "node server.js"
},

"dependencies" : {
"express": "^4.10.7",
"serve-static": "^1.8.0",
"socket.io": "^1.4.5",
"bcryptjs": "",
"body-parser": "",
"connect-flash": "",
"cookie-parser": "^1.4.1",
"express-handlebars": "",
"express-messages": "",
"express-session": "",
"express-validator": "",
"mongodb": "",
"mongoose": "",
"passport": "",
"passport-http": "",
"passport-local": ""
},

"license": "BSD2",

"engines": {
"node": ">=0.8"
}
}
</code>```

Here's my npm-error log.

0 info it worked if it ends with ok

1 verbose cli [ 'C:\Program Files\nodejs\node.exe',

1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',

1 verbose cli 'start' ]

2 info using npm@3.10.10

3 info using node@v6.10.2

4 verbose stack Error: missing script: start

4 verbose stack at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:151:19)

4 verbose stack at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:61:5

4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:356:5

4 verbose stack at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:320:45)

4 verbose stack at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:354:3)

4 verbose stack at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:124:5)

4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:243:12

4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:78:16

4 verbose stack at tryToString (fs.js:456:3)

4 verbose stack at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:443:12)

5 verbose cwd C:\Users\Nette\Desktop\pektos_1

6 error Windows_NT 6.3.9600

7 error argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "start"

8 error node v6.10.2

9 error npm v3.10.10

10 error missing script: start

11 error If you need help, you may report this error at:

11 error https://github.com/npm/npm/issues

12 verbose exit [ 1, true ]

help me guys please :(

答:
maybe it's very late but if someone encounter this kind of problem like mine here's what i did on my procfile

```<code>worker: node server.js
</code>```

thats what i did.

Body:
I do have a procfile:

web: node server.js

here's my package.json:

{
"name": "easyrtc_server_example",
"version": "0.1.6",
"author": "Priologic Software Inc. info@priologic.com (http://priologic.com/)",
"description" : "Simple EasyRTC server example which includes EasyRTC, Express, and Socket.io",
"main":"server.js",
"private": true,

"scripts": {
"start": "node server.js"
},

"dependencies" : {
"express": "^4.10.7",
"serve-static": "^1.8.0",
"socket.io": "^1.4.5",
"bcryptjs": "",
"body-parser": "",
"connect-flash": "",
"cookie-parser": "^1.4.1",
"express-handlebars": "",
"express-messages": "",
"express-session": "",
"express-validator": "",
"mongodb": "",
"mongoose": "",
"passport": "",
"passport-http": "",
"passport-local": ""
},

"license": "BSD2",

"engines": {
"node": ">=0.8"
}
}

Here's my npm-error log.

0 info it worked if it ends with ok

1 verbose cli [ 'C:\Program Files\nodejs\node.exe',

1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',

1 verbose cli 'start' ]

2 info using npm@3.10.10

3 info using node@v6.10.2

4 verbose stack Error: missing script: start

4 verbose stack at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:151:19)

4 verbose stack at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:61:5

4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:356:5

4 verbose stack at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:320:45)

4 verbose stack at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:354:3)

4 verbose stack at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:124:5)

4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:243:12

4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:78:16

4 verbose stack at tryToString (fs.js:456:3)

4 verbose stack at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:443:12)

5 verbose cwd C:\Users\Nette\Desktop\pektos_1

6 error Windows_NT 6.3.9600

7 error argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "start"

8 error node v6.10.2

9 error npm v3.10.10

10 error missing script: start

11 error If you need help, you may report this error at:

11 error https://github.com/npm/npm/issues

12 verbose exit [ 1, true ]

help me guys please :(

Body:
maybe it's very late but if someone encounter this kind of problem like mine here's what i did on my procfile

worker: node server.js

thats what i did.


问:
How to set object list to Vaadin 8 combobox
I want to integrate list of complex objects to a Vaadin combobox. I tried it as follows and that shows only garbage values (toString() values). But I want to know how to set the specific attribute which should show in the drop down.

Below class objects should be rendered in the combobox.

```<code>public class TestExecution {
private String name;
private String startingTime;
private String endingTime;
private String status;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getStartingTime() {
    return startingTime;
}

public void setStartingTime(String startingTime) {
    this.startingTime = startingTime;
}

public String getEndingTime() {
    return endingTime;
}

public void setEndingTime(String endingTime) {
    this.endingTime = endingTime;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}
</code>```

}

Note: I can't override the toString() method as I will be using it for other purposes.

答:
Firstly, you can give the type of the combo box as follows when creating it.

```<code>private ComboBox<TestExecution> comboExecution = new ComboBox<>("Select Execution");
</code>```

Then you can specify the logic to render the caption of the items of the dropdown by setting a ItemCaptionGenerator.

```<code>comboExecution.setItemCaptionGenerator(new ItemCaptionGenerator<TestExecution>() {
        @Override
        public String apply(TestExecution execution) {
            return execution.getName();
        }
    });
</code>```

You can simplify the code using lamda expressions as follows.

```<code>comboExecution.setItemCaptionGenerator(execution -> execution.getName());
</code>```

Body:
I want to integrate list of complex objects to a Vaadin combobox. I tried it as follows and that shows only garbage values (toString() values). But I want to know how to set the specific attribute which should show in the drop down.

Below class objects should be rendered in the combobox.

public class TestExecution {
private String name;
private String startingTime;
private String endingTime;
private String status;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getStartingTime() {
    return startingTime;
}

public void setStartingTime(String startingTime) {
    this.startingTime = startingTime;
}

public String getEndingTime() {
    return endingTime;
}

public void setEndingTime(String endingTime) {
    this.endingTime = endingTime;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

}

Note: I can't override the toString() method as I will be using it for other purposes.

Body:
Firstly, you can give the type of the combo box as follows when creating it.

private ComboBox<TestExecution> comboExecution = new ComboBox<>("Select Execution");

Then you can specify the logic to render the caption of the items of the dropdown by setting a ItemCaptionGenerator.

comboExecution.setItemCaptionGenerator(new ItemCaptionGenerator<TestExecution>() {
        @Override
        public String apply(TestExecution execution) {
            return execution.getName();
        }
    });

You can simplify the code using lamda expressions as follows.

comboExecution.setItemCaptionGenerator(execution -> execution.getName());


问:
JSON extract subtree as string in android
I have the following json structure:

```<code> "interpretation": {
        "ComplexSearchRequest": {
            "BoostLanguage": 0,
            "Clauses": {
                "MustClauses": [
                    {
                        "Match": {
                            "Attribute": "Channel",
                            "Operator": "None",
                            "Value": "n twenty four c h"
                        }
                    }
                ],
                "MustNotClauses": []
            },
            "FilterLanguages": [],
            "ItemFilters": [],
            "MaxResults": 10
        },
        "GraphManagerRequestId": "baf28b69-0806-4725-9fb4-1d2acd1944ea",
        "GraphManagerRequestLanguage": "de",
        "Type": "Search"
    },
</code>```

How do I extract the entire node "Clauses" and convert it as string? The output should be:

```<code>"Clauses": {
                "MustClauses": [
                    {
                        "Match": {
                            "Attribute": "Channel",
                            "Operator": "None",
                            "Value": "n twenty four c h"
                        }
                    }
                ],
                "MustNotClauses": []
            },
</code>```

An optimal solution is needed.

For simple parsing I use JsonReader.

答:
Let's say you have JSONObject with name interpretation, then following is the simple way to get Clauses:</p>

```<code>JSONObject complexSearchRequest = interpretation.getJSONObject("ComplexSearchRequest");
JSONObject clauses = complexSearchRequest.getJSONObject("Clauses");
Log.d("clauses",clauses.toString());
</code>```

Body:
I have the following json structure:

 "interpretation": {
        "ComplexSearchRequest": {
            "BoostLanguage": 0,
            "Clauses": {
                "MustClauses": [
                    {
                        "Match": {
                            "Attribute": "Channel",
                            "Operator": "None",
                            "Value": "n twenty four c h"
                        }
                    }
                ],
                "MustNotClauses": []
            },
            "FilterLanguages": [],
            "ItemFilters": [],
            "MaxResults": 10
        },
        "GraphManagerRequestId": "baf28b69-0806-4725-9fb4-1d2acd1944ea",
        "GraphManagerRequestLanguage": "de",
        "Type": "Search"
    },

How do I extract the entire node "Clauses" and convert it as string? The output should be:

"Clauses": {
                "MustClauses": [
                    {
                        "Match": {
                            "Attribute": "Channel",
                            "Operator": "None",
                            "Value": "n twenty four c h"
                        }
                    }
                ],
                "MustNotClauses": []
            },

An optimal solution is needed.

For simple parsing I use JsonReader.

Body:
Let's say you have JSONObject with name interpretation, then following is the simple way to get Clauses:

JSONObject complexSearchRequest = interpretation.getJSONObject("ComplexSearchRequest");
JSONObject clauses = complexSearchRequest.getJSONObject("Clauses");
Log.d("clauses",clauses.toString());


问:
VBA editor auto-deletes spaces at the ends of lines
Is there a way to convince the VBA editor in Excel to stop auto-formatting lines to remove the space at the end when I pause in my typing for a quarter second?</p>

答: In Excel 2010, toggling Design Mode button on the Developer Ribbon Tab solves the problem for me.


问:
timeout when running report in Acumatica ERP system
I have a problem when I'm running customized report,
I used this query View to generate the report: https://drive.google.com/open?id=0B0Aenr4I_Yz9RWRSN0RtaXhoSG8

After Executing finished, report doesn't work and show the timeout error.

and then I tried to trace this query in the system, and get this query:

```<code>    SELECT vTranPeriodMultiCury.[BatchNbr], vTranPeriodMultiCury.[RefNbr], vTranPeriodMultiCury.[InvoiceNbr], vTranPeriodMultiCury.[JobOrderNbr], vTranPeriodMultiCury.[Customer_Vendor_ID], vTranPeriodMultiCury.[SourceCredit], vTranPeriodMultiCury.[SourceDebit], vTranPeriodMultiCury.[BaseCredit], vTranPeriodMultiCury.[BaseDebit], vTranPeriodMultiCury.[Module], vTranPeriodMultiCury.[TranDate], vTranPeriodMultiCury.[TranType], vTranPeriodMultiCury.[Customer_Vendor_CD], vTranPeriodMultiCury.[Customer_Vendor_Name], vTranPeriodMultiCury.[TranDesc], vTranPeriodMultiCury.[Curyid], vTranPeriodMultiCury.[CuryRate], vTranPeriodMultiCury.[FinPeriodID], vTranPeriodMultiCury.[AccountCD], vTranPeriodMultiCury.[AccountDesc], vTranPeriodMultiCury.[BaseBegBalSummary], vTranPeriodMultiCury.[BaseEndBalSummary], vTranPeriodMultiCury.[SourceBegBalSummary], vTranPeriodMultiCury.[SourceEndBalSummary], vTranPeriodMultiCury.[BaseBegBalIDR], vTranPeriodMultiCury.[BaseEndBalIDR], vTranPeriodMultiCury.[SourceBegBalIDR], vTranPeriodMultiCury.[SourceEndBalIDR], vTranPeriodMultiCury.[BaseBegBalJPY], vTranPeriodMultiCury.[BaseEndBalJPY], vTranPeriodMultiCury.[SourceBegBalJPY], vTranPeriodMultiCury.[SourceEndBalJPY], vTranPeriodMultiCury.[BaseBegBalUSD], vTranPeriodMultiCury.[BaseEndBalUSD], vTranPeriodMultiCury.[SourceBegBalUSD], vTranPeriodMultiCury.[SourceEndBalUSD], Account.[AccountCD], Account.[Type], Account.[NoteID], NULL, NULL, NULL, Batch.[Module], Batch.[BatchNbr], Batch.[CuryInfoID], Batch.[NoteID], NULL, NULL, NULL FROM vTranPeriodMultiCury vTranPeriodMultiCury LEFT JOIN Account Account ON (Account.CompanyID = 2) AND [Account].[DeletedDatabaseRecord] = 0 AND (vTranPeriodMultiCury.[AccountID] = Account.[AccountID]) LEFT JOIN Batch Batch ON (Batch.CompanyID = 2) AND [Batch].[DeletedDatabaseRecord] = 0 AND (vTranPeriodMultiCury.[BatchNbr] = Batch.[BatchNbr]) WHERE (vTranPeriodMultiCury.CompanyID = 2) AND (vTranPeriodMultiCury.BranchID IS NULL OR vTranPeriodMultiCury.BranchID IN (1, 2, 3)) AND (((vTranPeriodMultiCury.[AccountCD] >= NULL OR NULL IS NULL ) AND (vTranPeriodMultiCury.[AccountCD] <= NULL OR NULL IS NULL ) AND (vTranPeriodMultiCury.[FinPeriodID] = '052017' OR '052017' IS NULL ))) ORDER BY vTranPeriodMultiCury.[AccountCD]  ASC, vTranPeriodMultiCury.[Curyid]  ASC, vTranPeriodMultiCury.[FinPeriodID]  ASC, vTranPeriodMultiCury.[TranDate]  ASC, vTranPeriodMultiCury.[BatchNbr]  ASC OPTION(OPTIMIZE FOR UNKNOWN)
</code>```

My question is in which part of web.config should be possible to change the timeout of executing sql query of report designer ?

答:
Probably you should increase this executionTimeOut in Location->system.web->httpRuntime in web.config:

```<code><httpRuntime executionTimeout="300" requestValidationMode="2.0" maxRequestLength="1048576" />
</code>```

Also try to execute the Following SQL Query on your SQL Server for your Acumatica ERP's database:

```<code>use YOUR_DATABASE_NAME
go
exec sp_configure 'remote query timeout (s)',6000
RECONFIGURE WITH OVERRIDE;
</code>```

Body:
I have a problem when I'm running customized report,
I used this query View to generate the report: https://drive.google.com/open?id=0B0Aenr4I_Yz9RWRSN0RtaXhoSG8

After Executing finished, report doesn't work and show the timeout error.

and then I tried to trace this query in the system, and get this query:

    SELECT vTranPeriodMultiCury.[BatchNbr], vTranPeriodMultiCury.[RefNbr], vTranPeriodMultiCury.[InvoiceNbr], vTranPeriodMultiCury.[JobOrderNbr], vTranPeriodMultiCury.[Customer_Vendor_ID], vTranPeriodMultiCury.[SourceCredit], vTranPeriodMultiCury.[SourceDebit], vTranPeriodMultiCury.[BaseCredit], vTranPeriodMultiCury.[BaseDebit], vTranPeriodMultiCury.[Module], vTranPeriodMultiCury.[TranDate], vTranPeriodMultiCury.[TranType], vTranPeriodMultiCury.[Customer_Vendor_CD], vTranPeriodMultiCury.[Customer_Vendor_Name], vTranPeriodMultiCury.[TranDesc], vTranPeriodMultiCury.[Curyid], vTranPeriodMultiCury.[CuryRate], vTranPeriodMultiCury.[FinPeriodID], vTranPeriodMultiCury.[AccountCD], vTranPeriodMultiCury.[AccountDesc], vTranPeriodMultiCury.[BaseBegBalSummary], vTranPeriodMultiCury.[BaseEndBalSummary], vTranPeriodMultiCury.[SourceBegBalSummary], vTranPeriodMultiCury.[SourceEndBalSummary], vTranPeriodMultiCury.[BaseBegBalIDR], vTranPeriodMultiCury.[BaseEndBalIDR], vTranPeriodMultiCury.[SourceBegBalIDR], vTranPeriodMultiCury.[SourceEndBalIDR], vTranPeriodMultiCury.[BaseBegBalJPY], vTranPeriodMultiCury.[BaseEndBalJPY], vTranPeriodMultiCury.[SourceBegBalJPY], vTranPeriodMultiCury.[SourceEndBalJPY], vTranPeriodMultiCury.[BaseBegBalUSD], vTranPeriodMultiCury.[BaseEndBalUSD], vTranPeriodMultiCury.[SourceBegBalUSD], vTranPeriodMultiCury.[SourceEndBalUSD], Account.[AccountCD], Account.[Type], Account.[NoteID], NULL, NULL, NULL, Batch.[Module], Batch.[BatchNbr], Batch.[CuryInfoID], Batch.[NoteID], NULL, NULL, NULL FROM vTranPeriodMultiCury vTranPeriodMultiCury LEFT JOIN Account Account ON (Account.CompanyID = 2) AND [Account].[DeletedDatabaseRecord] = 0 AND (vTranPeriodMultiCury.[AccountID] = Account.[AccountID]) LEFT JOIN Batch Batch ON (Batch.CompanyID = 2) AND [Batch].[DeletedDatabaseRecord] = 0 AND (vTranPeriodMultiCury.[BatchNbr] = Batch.[BatchNbr]) WHERE (vTranPeriodMultiCury.CompanyID = 2) AND (vTranPeriodMultiCury.BranchID IS NULL OR vTranPeriodMultiCury.BranchID IN (1, 2, 3)) AND (((vTranPeriodMultiCury.[AccountCD] >= NULL OR NULL IS NULL ) AND (vTranPeriodMultiCury.[AccountCD] <= NULL OR NULL IS NULL ) AND (vTranPeriodMultiCury.[FinPeriodID] = '052017' OR '052017' IS NULL ))) ORDER BY vTranPeriodMultiCury.[AccountCD]  ASC, vTranPeriodMultiCury.[Curyid]  ASC, vTranPeriodMultiCury.[FinPeriodID]  ASC, vTranPeriodMultiCury.[TranDate]  ASC, vTranPeriodMultiCury.[BatchNbr]  ASC OPTION(OPTIMIZE FOR UNKNOWN)

My question is in which part of web.config should be possible to change the timeout of executing sql query of report designer ?

Body:
Probably you should increase this executionTimeOut in Location->system.web->httpRuntime in web.config:

<httpRuntime executionTimeout="300" requestValidationMode="2.0" maxRequestLength="1048576" />

Also try to execute the Following SQL Query on your SQL Server for your Acumatica ERP's database:

use YOUR_DATABASE_NAME
go
exec sp_configure 'remote query timeout (s)',6000
RECONFIGURE WITH OVERRIDE;


问:
How do I get visual studio 2017 to see my phone, a Samsung Galaxy J1 (2016)?
I am new to app development, though an experienced software developer.

I have developed a small app in Visual Studio community (free) 2017 with Xamarin,
and run it successfully in the emulator. I do not know how to deploy it to the phone.

I tried to follow the instructions in
https://developer.xamarin.com/guides/android/getting_started/installation/set_up_device_for_development/
including setting development mode on the phone, but I could not find the drivers
for the phone listed on the Samsung website. Instead I connected the phone to the PC by USB, and
updated the drivers by Windows seasrching on the internet.

When I load my project into Visual Studio 2017, it does not see the phone.

Can someone please advise what I need to do to make this work correctly?

答: I have solved this problem by upgrading to Windows 10. This may not have been necessary, but deploying to the phone now works.</p>


问:
Cannot Access Data Retrieved from Observable [Angular 2, Typescript]
I'm getting a promise error whenever I reference a variable that is fed data from an observable. Example.

I have my class Stat defined in the component:

```<code>export class Stats {
  name: string;
  percentage: number;
  constructor(n: string, p: number) {
    this.name = n;
    this.percentage = p;
  }
}
</code>```

Now this is where its getting messy, I want data over from Http to populate my array so I'm doing this

```<code>export class StatsComponent {

  public stat1: Stats[] = [];

  constructor(private _httpService: HttpService, private _http: Http) {
     this._httpService.getParams("myURL").subscribe(S => {
       this.stat1 = S;
    });
  }
</code>```

getParams() fetches data for me with an observable like so

```<code>getParams(url: string): Observable<Stats[]>{
return this._http.get(url)
       .map(res =><Stats[]>res.json());
    }
</code>```

In stat.component.ts, I have this array that I want the data to populate it. Sorry stat2 doesn't exist, its just a concept on how I want to populate the data so I'm assuming I'll declare stat2[] in the same way I declare stat1[]

```<code>  public lineChartData: Array<any> = [
    { data: [this.stat1[0].data, this.stat2[0].data], label: 'Data 1' },
    { data: [this.stat1[1].data, this.stat2[1].data], label: 'Data 2' },
    { data: [this.stat1[2].data, this.stat2[2].data], label: 'Data 3' }
  ];
</code>```

Whenever I reference any of my local variable that received data from the observable in the constructor, they throw a Promise Error. How can I use data outside the scope of my .subscribe (in the constructor).

答:
You can move the assignment within the subscribe like this:

```<code>  lineChartData: Array<any>;

  constructor(private _httpService: HttpService, private _http: Http) {
     this._httpService.getParams("myURL").subscribe(S => {
       this.stat1 = S;
       this.lineChartData = [
          { data: [this.stat1[0].data, this.stat2[0].data], label: 'Data 1' },
          { data: [this.stat1[1].data, this.stat2[1].data], label: 'Data 2' },
          { data: [this.stat1[2].data, this.stat2[2].data], label: 'Data 3' }
       ];
    });
</code>```

A few things:

1) It is highly recommended that async operations (such as getting data) are NOT in the constructor. Consider instead using the ngOnInit method.

2) I'm not sure where stat2 is coming from ... so not sure this will work as is.

Body:
I'm getting a promise error whenever I reference a variable that is fed data from an observable. Example.

I have my class Stat defined in the component:

export class Stats {
  name: string;
  percentage: number;
  constructor(n: string, p: number) {
    this.name = n;
    this.percentage = p;
  }
}

Now this is where its getting messy, I want data over from Http to populate my array so I'm doing this

export class StatsComponent {

  public stat1: Stats[] = [];

  constructor(private _httpService: HttpService, private _http: Http) {
     this._httpService.getParams("myURL").subscribe(S => {
       this.stat1 = S;
    });
  }

getParams() fetches data for me with an observable like so

getParams(url: string): Observable<Stats[]>{
return this._http.get(url)
       .map(res =><Stats[]>res.json());
    }

In stat.component.ts, I have this array that I want the data to populate it. Sorry stat2 doesn't exist, its just a concept on how I want to populate the data so I'm assuming I'll declare stat2[] in the same way I declare stat1[]

  public lineChartData: Array<any> = [
    { data: [this.stat1[0].data, this.stat2[0].data], label: 'Data 1' },
    { data: [this.stat1[1].data, this.stat2[1].data], label: 'Data 2' },
    { data: [this.stat1[2].data, this.stat2[2].data], label: 'Data 3' }
  ];

Whenever I reference any of my local variable that received data from the observable in the constructor, they throw a Promise Error. How can I use data outside the scope of my .subscribe (in the constructor).

Body:
You can move the assignment within the subscribe like this:

  lineChartData: Array<any>;

  constructor(private _httpService: HttpService, private _http: Http) {
     this._httpService.getParams("myURL").subscribe(S => {
       this.stat1 = S;
       this.lineChartData = [
          { data: [this.stat1[0].data, this.stat2[0].data], label: 'Data 1' },
          { data: [this.stat1[1].data, this.stat2[1].data], label: 'Data 2' },
          { data: [this.stat1[2].data, this.stat2[2].data], label: 'Data 3' }
       ];
    });

A few things:

1) It is highly recommended that async operations (such as getting data) are NOT in the constructor. Consider instead using the ngOnInit method.

2) I'm not sure where stat2 is coming from ... so not sure this will work as is.


问:
How do I get some value in the IntervalIndex ?
The variable 'lvl' is IntervalIndex type like following this.

```<code>lvl = IntervalIndex([(1.418, 1.69], (1.69, 6.696], (6.696, 7.217], (7.217, 7.845], (7.845, 10.11] ... (17.648, 18.199], (18.199, 19.315], (19.315, 20.16], (20.16, 22.471], (22.471, 25.009]]
          closed='right',
          dtype='interval[float64]')
</code>```

Now I've try to append some index value like this:

```<code>for each in val_list:
    for k in range(len(lvl)):
        lower_val = float(lvl[k][1:-1].split(',')[0])
        upper_val = float(lvl[k][1:-1].split(',')[-1])
        if each >=lower_val and each <= upper_val:
            some_var_index.append(k)
</code>```

But, error raise to me... :

```<code>{TypeError}'pandas._libs.interval.Interval' object is not subscriptable
</code>```

How do I this?
Thank you

答:
Object being not subscriptable means it does not behave like ordinary list, but you doing it twice here:

```<code>lower_val = float(lvl[k][1:-1].split(',')[0])
upper_val = float(lvl[k][1:-1].split(',')[-1])
</code>```

with second square bracket [1:-1]. Instead those two lines use this one:

```<code>lower_val, upper_val = lvl[k].left, lvl[k].right
</code>```

and you should be good.

Body:
The variable 'lvl' is IntervalIndex type like following this.

lvl = IntervalIndex([(1.418, 1.69], (1.69, 6.696], (6.696, 7.217], (7.217, 7.845], (7.845, 10.11] ... (17.648, 18.199], (18.199, 19.315], (19.315, 20.16], (20.16, 22.471], (22.471, 25.009]]
          closed='right',
          dtype='interval[float64]')

Now I've try to append some index value like this:

for each in val_list:
    for k in range(len(lvl)):
        lower_val = float(lvl[k][1:-1].split(',')[0])
        upper_val = float(lvl[k][1:-1].split(',')[-1])
        if each >=lower_val and each <= upper_val:
            some_var_index.append(k)

But, error raise to me... :

{TypeError}'pandas._libs.interval.Interval' object is not subscriptable

How do I this?
Thank you

Body:
Object being not subscriptable means it does not behave like ordinary list, but you doing it twice here:

lower_val = float(lvl[k][1:-1].split(',')[0])
upper_val = float(lvl[k][1:-1].split(',')[-1])

with second square bracket [1:-1]. Instead those two lines use this one:

lower_val, upper_val = lvl[k].left, lvl[k].right

and you should be good.


问:
How can I make Tab-key navigation work with popups?
I'm struggling with making a navigation keyboard-accessible, so that the user can Tab through the links. The problem is with popups that will be shown next to a menu item once it is focused or hovered. Here's a minimal working example:

a.help {
    /* don't show help until explicitly triggered */
    display: none;
}
li:hover + a.help, a:focus + a.help {
    /* show help button when user is about to interact with the original button */
    display: inline;
}
a.help:focus, a.help:hover, a.help:active {
    /* don't hide help button while user interacts with it */
    display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Actions</h3>
<ul>
    <li>Edit (Help)</li>
    <li>Delete (Help)</li>
    <li>Back</li>
</ul></code>```

In Firefox 45, when Focus is on "Edit" and its "(Help)" is visible, the next Tab will not focus anything, but the "(Help)" vanishes. The next Tab will then move to "Delete".

In Chrome 49, it's even worse. When focus is on "Edit", the next Tab will not focus anything, and in fact restart the navigation at the page's first link upon the next Tab.

Is there any way that I can make this work while retaining the general style and document structure?

答:
You can use negative tabindex attribute in order to move element out of Tab scope:

Actions

Edit (Help)

Delete (Help)

Back

```

tabindex=-1

When tabindex is set to a negative integer like -1, it becomes
  programmatically focusable but it isn’t included in the tab order. In
  other words, it can’t be reached by someone using the tab key to
  navigate through content, but it can be focused on with scripting.

Read more about tabindex

Body:
I'm struggling with making a navigation keyboard-accessible, so that the user can Tab through the links. The problem is with popups that will be shown next to a menu item once it is focused or hovered. Here's a minimal working example:

a.help {
    /* don't show help until explicitly triggered */
    display: none;
}
li:hover + a.help, a:focus + a.help {
    /* show help button when user is about to interact with the original button */
    display: inline;
}
a.help:focus, a.help:hover, a.help:active {
    /* don't hide help button while user interacts with it */
    display: inline;
}

Actions

Edit (Help)

Delete (Help)

Back

In Firefox 45, when Focus is on "Edit" and its "(Help)" is visible, the next Tab will not focus anything, but the "(Help)" vanishes. The next Tab will then move to "Delete".

In Chrome 49, it's even worse. When focus is on "Edit", the next Tab will not focus anything, and in fact restart the navigation at the page's first link upon the next Tab.

Is there any way that I can make this work while retaining the general style and document structure?

Body:
You can use negative tabindex attribute in order to move element out of Tab scope:

<h3>Actions</h3>
<ul>
    <li><a href="#" tabindex="1">Edit</a> <a tabindex="-1" href="#">(Help)</a></li>
    <li><a href="#" tabindex="2">Delete</a> <a tabindex="-1" href="#">(Help)</a></li>
    <li><a href="#" tabindex="3">Back</a></li>
</ul>

tabindex=-1

When tabindex is set to a negative integer like -1, it becomes
  programmatically focusable but it isn’t included in the tab order. In
  other words, it can’t be reached by someone using the tab key to
  navigate through content, but it can be focused on with scripting.

Read more about tabindex


问:
Python - Strip line at either one point or another in the same string
I want to save a phrase that´s between a start and a end point.

The start is start = '->'. The problem is that it can have two different end points (depending on which string I get) end = ':\' or end1 ='[Channel].

So I'm trying to split the string at both ends ':\' and '[channel]' in the same loop. I tried using or, split, strip, striplines and others, but nothing does the trick

How  my code looks now (not working)

```<code>        if line.startswith('->'):
                start = '-> '  # take string from
                end = ':\ ' #either end at this character
                end1 = '[Channel]' # or this character
                data.append(line[line.find(start) + 3:line.find(end or end1)].strip())
</code>```

example on how the file with the strings looks

```<code>SEND TEST:
-> 3C 53 25 25 :\TCM_APP_33\MO\NO
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
SEND TEST:
-> 35 32 5V 25 :\ KCM_APP_31\TEST\FIX
-> 3N 21 24 23 [Channel]
SEND TEST:
-> 12 3F 56 7D :\BCM_APP_31\TRY
-> 3N 21 24 23 [Channel]
</code>```

Basically I want to extract the numbers

答:
```<code>data="""
-> 123456 :\\
123 123
other data ...
-> 12 3F 56 7D :\\
-> 3C 53 25 25 :\\
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
-> 35 32 5V 25 :\\
-> 3N 21 24 23 [Channel]
other data ...
123 123
-> hello [Channel]"""

numbers= [''.join(_.split()[1:-1]) for _ in data.split("\n") if _.startswith('->') and _.count(' ') == 5]
print (numbers)
</code>```

Output

```<code>['123F567D', '3C532525', '3212H23G', '4334524B', '4C334524', '35325V25', '3N212423']
</code>```

Split all lines, keep only lines beginning by -> and with 5 spaces, split the spaces, don't keep the first and last result, merge the rest.

Body:
I want to save a phrase that´s between a start and a end point.

The start is start = '->'. The problem is that it can have two different end points (depending on which string I get) end = ':\' or end1 ='[Channel].

So I'm trying to split the string at both ends ':\' and '[channel]' in the same loop. I tried using or, split, strip, striplines and others, but nothing does the trick

How  my code looks now (not working)

        if line.startswith('->'):
                start = '-> '  # take string from
                end = ':\ ' #either end at this character
                end1 = '[Channel]' # or this character
                data.append(line[line.find(start) + 3:line.find(end or end1)].strip())

example on how the file with the strings looks

SEND TEST:
-> 3C 53 25 25 :\TCM_APP_33\MO\NO
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
SEND TEST:
-> 35 32 5V 25 :\ KCM_APP_31\TEST\FIX
-> 3N 21 24 23 [Channel]
SEND TEST:
-> 12 3F 56 7D :\BCM_APP_31\TRY
-> 3N 21 24 23 [Channel]

Basically I want to extract the numbers

Body:
data="""
-> 123456 :\\
123 123
other data ...
-> 12 3F 56 7D :\\
-> 3C 53 25 25 :\\
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
-> 35 32 5V 25 :\\
-> 3N 21 24 23 [Channel]
other data ...
123 123
-> hello [Channel]"""

numbers= [''.join(_.split()[1:-1]) for _ in data.split("\n") if _.startswith('->') and _.count(' ') == 5]
print (numbers)

Output

['123F567D', '3C532525', '3212H23G', '4334524B', '4C334524', '35325V25', '3N212423']

Split all lines, keep only lines beginning by -> and with 5 spaces, split the spaces, don't keep the first and last result, merge the rest.