问:
How to get data from firebase knowing the email of user ANDROID
I am trying to get the data of my firebase database for android, knowning for example the email, but i can't do it myself.

I leave a photo for more information.

答:
Since you know the email address, you can get all users with that email address with a query. The code would be something like this:</p>

```<code>myRef.orderByChild("correo").equalTo("email@email.es").addListenerForSingleValueEvent(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            System.out.println(childSnapshot.getKey()+": "+childSnapshot.child("appellidos").getValue(String.class));
        }
</code>```

Body:
Since you know the email address, you can get all users with that email address with a query. The code would be something like this:

myRef.orderByChild("correo").equalTo("email@email.es").addListenerForSingleValueEvent(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            System.out.println(childSnapshot.getKey()+": "+childSnapshot.child("appellidos").getValue(String.class));
        }


来源: stackexchange

问:
Recursive Tree Structure - Restarting method / calling recursion inside the if(___) space
I am trying to create a recursive tree data structure for following problem: given a set of positive integers (Items with positive values), I want to divide them into a fixed number of subsets (put them in Containers or bins) so that the sum of the elements in all subsets is equal.

For simplicity purpose I have renamed all attributes.
I have a Node Class here that holds all the respective children nodes and calls their insert() function. If my success base case (All items have been distributed)  is met, all I care about is printing the current state and ending my recursive function.

Basically in each node I try to place one item into a container. If it fails (because the item (or Integer) exceeds the maximum allowed value), I want the parent node to create a new node and reattempt the thing. with its next container. If all containers have been tested, return false.

Unfortunately, I am struggling with two things. Here's the Code.

```<code>package DataStructure_Finding_Equal_Sharings_444_Prjct3;

import java.util.ArrayList;
import java.util.List;

public class Node {

    //List Holding Items still needed to be distributed
    private Items items;

    private List<Node> children;

    private List<Container> containerlist;

    private int containercount = 0;

    private Item nodeItem;

    public Node(List <Container> containerlist, Items item){
    this.Items = item;
    this.containerlist = containerlist;
    this.children = new ArrayList<>();
    }

    public boolean insert(){

        //BASECASE 1 : Combination Found
        if(items.getAllItems().isEmpty()){
            System.out.println("Combination Found:" +                 containerlist.toString());
            return true;
        }

        //BASECASE 2 : All Children Created, All Container attempted to     fill
        else if (containercount +1 ==  containerlist.size()){
            return false;
        }

        else{
            //Check If This Node has been Initiated already. If Not,     Initiate by Taking Item
            if(nodeItem == null){

                nodeItem = items.takeItem();

                //If True (GiveItem was Succesful), Item is Stored in this Node. Afterwards New Node will be created.
                if(containerlist.get(containercount).giveItem(nodeItem)){
                    Node childNode = new Node(containerlist, items);
                    children.add(childNode);

                    //If Child Returns False, Try Next Child
                    boolean test = children.get(containercount).insert(containerlist, items);
                    if( test == false){
                        containercount++;
                        insert();
                        return false;
                    }
                    //Child Returns True: Solution Found!
                    else{
                        return true;
                    }
                }
                //If False, Item did not fit in this Node, tell parent this child is dead. Put Item Item Back (This Never Happened)
                else{
                    items.returnItem(nodeItem);
                    return false;
                }
            }
            //Item was already assigned to Node, this is a revisited node
            else {
                //Create the next Node for another attempt
                Node childNode = new Node(containerlist, items);
                children.add(childNode);

                //If Child Returns False, Try Next Child
                if(childNode.insert() == false){
                    containercount++;
                    insert(); //Restart this node method with containercount                    increased, so that a new attempt can be made
                    return false; //end this attempt
                    }
                    else{
                        return true;
                    }
            }

}
</code>```

Problem One:

```<code>`Exception in thread "main" java.lang.RuntimeException: Uncompilable source code `
</code>```

- Erroneous sym type:

ultimatetalerproblem.Node.insert at   DataStructure_Finding_Equal_Sharings_444_Prjct3.Node.insert(Node.java:60[...]

Users/Library/Caches/NetBeans/8.1/executor-snippets/debug.xml:83: Java returned: 1

Is referring to this

//If Child Returns False, Try Next Child
boolean test = children.get(containercount).insert(containerlist, items)

And Problem 2:

insert();

Basically what I am attempting is to just restart the same method with the parameter containercount set to +1. However when I call insert(), I am really creating a new method, so I feel like I am not doing something right.

Any help is greatly appreciated. Thank you.

Edit: Items Class

```<code>package DataStructure_Finding_Equal_Sharings_444_Prjct3;

    import java.util.ArrayList;
    import java.util.List;

    public class Items {

private ArrayList<Item> items;
private int totalCount;
private int totalvalue;

public Items(){
    this.items = new ArrayList<>();
    this.totalCount = 0;
    this.totalvalue = 0;
}

public void addItem(int value){
    this.items.add(new Item(value));
}

public void returnitem(Item item){
    items.add(item);
}

public Coin takeItem(){
    Coin tempItem = items.get(0);
    items.remove(0);
    return tempItem;
}

public int getTotalCount(){
    return this.totalCount;
}

public int getTotalvalue(){
    return this.totalvalue;
}

public List getAllItems(){
    return items;
}

}
</code>```

Container Class:

```<code>package ultimatetalerproblem;

import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.List;

/**
 * An Container holding items.
 * <br/>
 * The number of items it can hold is not limited, but the added value of the
 * items it holds may not be higher than the given maximal size.
 */
public class Container {

/**h
 * maximal allowed added value of items.
 */
private int totalValue;
/**
 * current added value of items.
 */
private int currentSize;
/**
 * list of items in container.
 */
private List<Item> items;

/**
 * construct new container with given maximal size.
 *
 * @param totalValue
 * @param subListValue
 */

public Container(int subListValue) {
    this.totalValue = subListValue;
    this.currentSize = 0;
    this.items = new ArrayList<>();
}

/**
 * adds given item to this container, and increases the currentSize of the container by
 * value of item. If item does not fit, it will not be put in the container and
 * false will be returned.
 *
 * @param item item to put in container
 * @return true if item fit in container, false otherwise
 */

public boolean giveItem(Item item) {

    if (currentSize + item.getValue() <= totalValue) {
        items.add(item);
        currentSize += item.getValue();
        return true;
    } else {
        return false; // item didn't fit
    }
}

/**
 * removes given item from container and reduces the currentSize of the container by
 * value of item.
 *
 * @param item item to remove from container
 * @return wheter item was succesfully removed.
 */

/**
 * returns the number of items in this container (NOT the added value of the
 * items).
 *
 * @return number of items in this container
 */

public int numberOfItems() {
    return items.size();
}

public int getTotalValue(){

    return totalValue;
}

public List<Item> getitems(){

    return items;
}

@Override
public String toString() {
    String res = "";
    for (int i = 0; i < items.size(); i++) {
        res += items.get(i) + " ";
    }
    res += "    Size: " + currentSize + " (max: " + totalValue + ")";
    return res;
}
}
</code>```

答:
I found the errors below so far:

1) As i didn't have the Item class, i changed to Integer .

2) In Node constructor, should be this.items, not this.Items

You should remove Coin and use Item.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a recursive tree data structure for following problem: given a set of positive integers (Items with positive values), I want to divide them into a fixed number of subsets (put them in Containers or bins) so that the sum of the elements in all subsets is equal.

For simplicity purpose I have renamed all attributes.
I have a Node Class here that holds all the respective children nodes and calls their insert() function. If my success base case (All items have been distributed)  is met, all I care about is printing the current state and ending my recursive function.

Basically in each node I try to place one item into a container. If it fails (because the item (or Integer) exceeds the maximum allowed value), I want the parent node to create a new node and reattempt the thing. with its next container. If all containers have been tested, return false.

Unfortunately, I am struggling with two things. Here's the Code.

package DataStructure_Finding_Equal_Sharings_444_Prjct3;

import java.util.ArrayList;
import java.util.List;

public class Node {

    //List Holding Items still needed to be distributed
    private Items items;

    private List<Node> children;

    private List<Container> containerlist;

    private int containercount = 0;

    private Item nodeItem;

    public Node(List <Container> containerlist, Items item){
    this.Items = item;
    this.containerlist = containerlist;
    this.children = new ArrayList<>();
    }

    public boolean insert(){

        //BASECASE 1 : Combination Found
        if(items.getAllItems().isEmpty()){
            System.out.println("Combination Found:" +                 containerlist.toString());
            return true;
        }

        //BASECASE 2 : All Children Created, All Container attempted to     fill
        else if (containercount +1 ==  containerlist.size()){
            return false;
        }

        else{
            //Check If This Node has been Initiated already. If Not,     Initiate by Taking Item
            if(nodeItem == null){

                nodeItem = items.takeItem();

                //If True (GiveItem was Succesful), Item is Stored in this Node. Afterwards New Node will be created.
                if(containerlist.get(containercount).giveItem(nodeItem)){
                    Node childNode = new Node(containerlist, items);
                    children.add(childNode);

                    //If Child Returns False, Try Next Child
                    boolean test = children.get(containercount).insert(containerlist, items);
                    if( test == false){
                        containercount++;
                        insert();
                        return false;
                    }
                    //Child Returns True: Solution Found!
                    else{
                        return true;
                    }
                }
                //If False, Item did not fit in this Node, tell parent this child is dead. Put Item Item Back (This Never Happened)
                else{
                    items.returnItem(nodeItem);
                    return false;
                }
            }
            //Item was already assigned to Node, this is a revisited node
            else {
                //Create the next Node for another attempt
                Node childNode = new Node(containerlist, items);
                children.add(childNode);

                //If Child Returns False, Try Next Child
                if(childNode.insert() == false){
                    containercount++;
                    insert(); //Restart this node method with containercount                    increased, so that a new attempt can be made
                    return false; //end this attempt
                    }
                    else{
                        return true;
                    }
            }

}

Problem One:

`Exception in thread "main" java.lang.RuntimeException: Uncompilable source code `

- Erroneous sym type:

ultimatetalerproblem.Node.insert at   DataStructure_Finding_Equal_Sharings_444_Prjct3.Node.insert(Node.java:60[...]

Users/Library/Caches/NetBeans/8.1/executor-snippets/debug.xml:83: Java returned: 1

Is referring to this

//If Child Returns False, Try Next Child
boolean test = children.get(containercount).insert(containerlist, items)

And Problem 2:

insert();

Basically what I am attempting is to just restart the same method with the parameter containercount set to +1. However when I call insert(), I am really creating a new method, so I feel like I am not doing something right.

Any help is greatly appreciated. Thank you.

Edit: Items Class

package DataStructure_Finding_Equal_Sharings_444_Prjct3;

    import java.util.ArrayList;
    import java.util.List;

    public class Items {

private ArrayList<Item> items;
private int totalCount;
private int totalvalue;

public Items(){
    this.items = new ArrayList<>();
    this.totalCount = 0;
    this.totalvalue = 0;
}

public void addItem(int value){
    this.items.add(new Item(value));
}

public void returnitem(Item item){
    items.add(item);
}

public Coin takeItem(){
    Coin tempItem = items.get(0);
    items.remove(0);
    return tempItem;
}

public int getTotalCount(){
    return this.totalCount;
}

public int getTotalvalue(){
    return this.totalvalue;
}

public List getAllItems(){
    return items;
}

}

Container Class:

package ultimatetalerproblem;

import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.List;

/**
 * An Container holding items.
 *

 * The number of items it can hold is not limited, but the added value of the
 * items it holds may not be higher than the given maximal size.
 */
public class Container {

/**h
 * maximal allowed added value of items.
 */
private int totalValue;
/**
 * current added value of items.
 */
private int currentSize;
/**
 * list of items in container.
 */
private List<Item> items;

/**
 * construct new container with given maximal size.
 *
 * @param totalValue
 * @param subListValue
 */

public Container(int subListValue) {
    this.totalValue = subListValue;
    this.currentSize = 0;
    this.items = new ArrayList<>();
}

/**
 * adds given item to this container, and increases the currentSize of the container by
 * value of item. If item does not fit, it will not be put in the container and
 * false will be returned.
 *
 * @param item item to put in container
 * @return true if item fit in container, false otherwise
 */

public boolean giveItem(Item item) {

    if (currentSize + item.getValue() <= totalValue) {
        items.add(item);
        currentSize += item.getValue();
        return true;
    } else {
        return false; // item didn't fit
    }
}

/**
 * removes given item from container and reduces the currentSize of the container by
 * value of item.
 *
 * @param item item to remove from container
 * @return wheter item was succesfully removed.
 */

/**
 * returns the number of items in this container (NOT the added value of the
 * items).
 *
 * @return number of items in this container
 */

public int numberOfItems() {
    return items.size();
}

public int getTotalValue(){

    return totalValue;
}

public List<Item> getitems(){

    return items;
}

@Override
public String toString() {
    String res = "";
    for (int i = 0; i < items.size(); i++) {
        res += items.get(i) + " ";
    }
    res += "    Size: " + currentSize + " (max: " + totalValue + ")";
    return res;
}
}


问:
I'm new to QBasic and coding in general and I'm making a guessing game that just wont work
I'm new to QBasic and coding in general and I'm making a guessing game that just won't work.
I have to make a guessing game that does not use GOTO or Do statements, and gives the user 5 chances. Here's the code:

```<code>chances%=1
dim guess as integer
dim answer as string
randomize timer
rndnum=INT(RND*100+1)

'makinng a title
color 5
locate 12,32
print "welcome to My guessing game."
Print "think of a number between 1 and 100."

color 12
Input "enter you guess:  ",guess
while chances%<4
if guess >rndnum then
  print "wrong, too high"
elseif guess <rndnum then
   print "wrong, too low"
elseif guess=rndnum then
 print "your guessed the number!"
end if
wend
chances%=chances%+1

color 14
Print "you took "; chances%;"to guess the number"

color 3
Input would you like to play again (yes/no)?", answer
wend

if answer = "yes" then
?

else
  print "have a good day"
end if
end
</code>```

答:
You could use WHILE...WEND to run a loop until chances becomes 0.Here is what I mean:

```<code>....(rest of code)
chances = 5
WHILE chances > 0
    ....
    if guess > rndnum then
       print "wrong, too high"
       chances = chances - 1
    elseif guess < rndnum then
       print "wrong, too low"
       chances = chances -1
     ....
WEND
</code>```

Body:
I'm new to QBasic and coding in general and I'm making a guessing game that just won't work.
I have to make a guessing game that does not use GOTO or Do statements, and gives the user 5 chances. Here's the code:

chances%=1
dim guess as integer
dim answer as string
randomize timer
rndnum=INT(RND*100+1)

'makinng a title
color 5
locate 12,32
print "welcome to My guessing game."
Print "think of a number between 1 and 100."

color 12
Input "enter you guess:  ",guess
while chances%<4
if guess >rndnum then
  print "wrong, too high"
elseif guess <rndnum then
   print "wrong, too low"
elseif guess=rndnum then
 print "your guessed the number!"
end if
wend
chances%=chances%+1

color 14
Print "you took "; chances%;"to guess the number"

color 3
Input would you like to play again (yes/no)?", answer
wend

if answer = "yes" then
?

else
  print "have a good day"
end if
end

Body:
You could use WHILE...WEND to run a loop until chances becomes 0.Here is what I mean:

....(rest of code)
chances = 5
WHILE chances > 0
    ....
    if guess > rndnum then
       print "wrong, too high"
       chances = chances - 1
    elseif guess < rndnum then
       print "wrong, too low"
       chances = chances -1
     ....
WEND


问:
Is now the time to start designing for 1280px wide screens instead of 1024px?
Need opinions on this, what do you guys think? A good idea or not so good idea.

I could do a seperate css style but not sure whether to drop 1024 for sure.

答:
Hmmm

I know that 76% have over 1024 resolution (January 2010 browser display stats - w3schools.com), but 20% still use 1024 x 768.

Designing a site around 1280 will annoy people with a smaller rez, and having to scroll horizontal to view content is not good, users will just leave and go elsewhere if they have to constantly horizontal scroll.

It's going to depend on your target audience though. Also think about how popular portable devices are becoming now, such as the iPhone, iPad...? How will a site designed for 1280 preform on those?

Of course you could always create specific mobile type sites for smaller screen size portable devices.

For now I still stick with the 960 width grid system :)

ContentLicense: CC BY-SA 2.5


问:
Minitest for get request with params
I'm having trouble with one of my tests, even though the controller is working perfectly.

So, I have a form to change the VIP status of an user.

```<code><%= form_tag("/activate/#{@user.id}", method: :get, class: "form-inline space-bottom") do |f| %>
    <%= hidden_field_tag :vip, false %>
    <%= check_box_tag :vip, type:"checkbox" %>
    <%= date_field_tag(:vip_expiration_date, @user.vip_expiration_date) %>
    <button type="submit">
        Change
    </button>
</code>```

This form sends to this route:

```<code>get  '/activate/:id',           to: 'users#activate_vip'
</code>```

and gets to this controller action:

```<code>def activate_vip
  @user = User.find(params[:id])
  if @user.update_attributes(activate_vip_params)
    flash[:success] = "VIP status updated"
    redirect_to @user
  else
    render show
  end
end
</code>```

also:

```<code>def activate_vip_params
  params.permit(:vip_expiration_date, :vip)
end
</code>```

And this action works just fine, no problems, so I wanted to make a test for it using minitest:

```<code>  test "Admin should be able to change vip status" do
    log_in_as(@user)
    get "/activate/#{@other_user.id}", params: {:vip => true}
    assert @other_user.vip
  end
</code>```

I was sure this test would simply pass, but I'm getting the error "Expected false to be truthy."

My intuition said it's related to how I pass the parameters, so I tried several variations on params: but all without success. Can someone help me on this one?

I'm using gem 'minitest', '~> 5.10', '!= 5.10.2' and rails 5

EDIT:

Changed the code so I could "require" the user.

```<code>    <%= form_for @user, url: "/activate/#{@user.id}", class: "form-inline" do |f| %>
    <%= hidden_field_tag :vip, false %>
    <%= f.check_box :vip, type:"checkbox" %>
    <%= f.date_field :vip_expiration_date %>
    <%= f.submit "Change" %>
    <% end %>
</code>```

and the controller

```<code>def activate_vip_params
  params.require(:user).permit(:vip_expiration_date, :vip)
end
</code>```

and the test:

```<code>test "Admin should be able to change vip status" do
  log_in_as(@user)
  patch "/activate/#{@other_user.id}", user: { vip: true }
  assert @other_user.vip
end
</code>```

Still no success. The controller works but can't make the test.

------ EDIT ------

Nevermind. It was a stupid mistake.

I just had to add "vip:false" in the fixture for @other_user do initialise the variable.

答:
You don't have to use 'params', you need to write permitted parameter name. For ex in your controller

```<code>def address_params
  params.require(:address).permit(:street_address_1)
end
</code>```

Then in test case you can do

```<code>    test "Admin should be able to change vip status" do
      log_in_as(@user)
      get "/activate/#{@other_user.id}", address: { street_address_1: "1223 4th floor"}
     assert @other_user.vip
    end
</code>```

Title: Minitest for get request with params

Body:
I'm having trouble with one of my tests, even though the controller is working perfectly.

So, I have a form to change the VIP status of an user.

<%= form_tag("/activate/#{@user.id}", method: :get, class: "form-inline space-bottom") do |f| %>
    <%= hidden_field_tag :vip, false %>
    <%= check_box_tag :vip, type:"checkbox" %>
    <%= date_field_tag(:vip_expiration_date, @user.vip_expiration_date) %>
    <button type="submit">
        Change
    </button>

This form sends to this route:

get  '/activate/:id',           to: 'users#activate_vip'

and gets to this controller action:

def activate_vip
  @user = User.find(params[:id])
  if @user.update_attributes(activate_vip_params)
    flash[:success] = "VIP status updated"
    redirect_to @user
  else
    render show
  end
end

also:

def activate_vip_params
  params.permit(:vip_expiration_date, :vip)
end

And this action works just fine, no problems, so I wanted to make a test for it using minitest:

  test "Admin should be able to change vip status" do
    log_in_as(@user)
    get "/activate/#{@other_user.id}", params: {:vip => true}
    assert @other_user.vip
  end

I was sure this test would simply pass, but I'm getting the error "Expected false to be truthy."

My intuition said it's related to how I pass the parameters, so I tried several variations on params: but all without success. Can someone help me on this one?

I'm using gem 'minitest', '~> 5.10', '!= 5.10.2' and rails 5

EDIT:

Changed the code so I could "require" the user.

    <%= form_for @user, url: "/activate/#{@user.id}", class: "form-inline" do |f| %>
    <%= hidden_field_tag :vip, false %>
    <%= f.check_box :vip, type:"checkbox" %>
    <%= f.date_field :vip_expiration_date %>
    <%= f.submit "Change" %>
    <% end %>

and the controller

def activate_vip_params
  params.require(:user).permit(:vip_expiration_date, :vip)
end

and the test:

test "Admin should be able to change vip status" do
  log_in_as(@user)
  patch "/activate/#{@other_user.id}", user: { vip: true }
  assert @other_user.vip
end

Still no success. The controller works but can't make the test.

------ EDIT ------

Nevermind. It was a stupid mistake.

I just had to add "vip:false" in the fixture for @other_user do initialise the variable.

Body:
You don't have to use 'params', you need to write permitted parameter name. For ex in your controller

def address_params
  params.require(:address).permit(:street_address_1)
end

Then in test case you can do

    test "Admin should be able to change vip status" do
      log_in_as(@user)
      get "/activate/#{@other_user.id}", address: { street_address_1: "1223 4th floor"}
     assert @other_user.vip
    end


问:
How to hide JavaScripts in wordpress
I have inserted my javascripts in the header.php file, but I noticed the whole code can be stolen by simply lookin at the source from within any single post or homepage...

May you suggest me a simple way to hide my javascripts in wordpress somehow to prevent being copied/stolen?

答: You can minify and uglyfy your code, so it will be hard to read it</p>

Title: How to hide JavaScripts in wordpress


问:
Unix shell script find out which directory the script file resides?
Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script file resides?</p>

答:
That should do the trick:

```<code>echo `pwd`/`dirname $0`
</code>```

It might look ugly depending on how it was invoked and the cwd but should get you where you need to go (or you can tweak the string if you care how it looks).

OwnerDisplayName: goodwill

Body:
That should do the trick:

echo `pwd`/`dirname $0`

It might look ugly depending on how it was invoked and the cwd but should get you where you need to go (or you can tweak the string if you care how it looks).

OwnerDisplayName: foo


问:
How to share data between separate classes in Java
What is the best way to share data between separate classes in Java? I have a bunch of variables that are used by different classes in separate files in different ways.
Let me try to illustrate a simplified version of my problem:

This was my code before:

```<code>public class Top_Level_Class(){
    int x, y;

    // gets user input which changes x, y;
    public void main(){
       int p, q, r, s;
       // compute p, q, r, s
       doA(p,q,r);
       doB(q,r,s);
    }

    public void doA(int p, int q, int r){
       // do something that requires x,y and p, q, r
    }

    public void doB(int q, int r, int s){
       // does something else that requires x, y and q, r, s
    }
}
</code>```

Now it looks something like this:

```<code>public class Top_Level_Class(){
    int x, y;
    SomeClass1a a = new SomeClass1a();
    SomeClass1a b = new SomeClass1b();
    // gets user input which changes x, y;
    public void main(){
       int p, q, r, s;
       // compute p, q, r, s
       a.doA(p,q,r);
       b.doB(q,r,s);
    }

public class SomeClass1a() {  // in its own separate file
    public void doA(int p, int q, int r){
       // do something that requires x,y and p, q, r
    }
}

public class SomeClass1b() {  // in its own separate file
    public void doB(int q, int r, int s){
       // does something else that requires x, y and q, r, s
    }
}
</code>```

So anyway, should I pass x and y each time (where x,y are variables stored in the helper class func) ?

```<code> a.set(x,y);
 a.doA(p,q,r);
</code>```

My idea was to have a special container class where x and y are held. The top level class would have an instance of the container class and change x,y  using the set methods.

```<code>// in the top level class:
Container c = new Container(x,y);
a.setContainer(c);
b.setContainer(c);
</code>```

My helper classes would also have an instance of the container and it would point to the same instance as in the top level. That way they access the same x,y as in the top level.

I would like to know if I should

Use the container class

Load x,y each time into the subclasses

?? Some better method ??

答:
I guess the answer to your question is the Design Pattern called Singleton.
It basically allows you to get and exploits the same (and unique) instance of a class whenever you want in your system.

This is its implementation (please forgive possible syntax errors, I did not compile it):

```<code>class Container{

  //eventually provides setters and getters
  public float x;
  public float y;
  //------------

  private static Container instance = null;
  private void Container(){

  }
  public static Container getInstance(){
    if(instance==null){
       instance = new Container();
      }
      return instance;
  }
}
</code>```

then if elsewhere in your code you import the Container you can write for example

```<code>Container.getInstance().x = 3;
temp = Container.getInstance().x;
</code>```

and you will affect the attributes of the unique container instance you have in your system

In many cases it is however better to use the Dependency Injection pattern as it reduces the coupling between different components.

Body:
What is the best way to share data between separate classes in Java? I have a bunch of variables that are used by different classes in separate files in different ways.
Let me try to illustrate a simplified version of my problem:

This was my code before:

public class Top_Level_Class(){
    int x, y;

    // gets user input which changes x, y;
    public void main(){
       int p, q, r, s;
       // compute p, q, r, s
       doA(p,q,r);
       doB(q,r,s);
    }

    public void doA(int p, int q, int r){
       // do something that requires x,y and p, q, r
    }

    public void doB(int q, int r, int s){
       // does something else that requires x, y and q, r, s
    }
}

Now it looks something like this:

public class Top_Level_Class(){
    int x, y;
    SomeClass1a a = new SomeClass1a();
    SomeClass1a b = new SomeClass1b();
    // gets user input which changes x, y;
    public void main(){
       int p, q, r, s;
       // compute p, q, r, s
       a.doA(p,q,r);
       b.doB(q,r,s);
    }

public class SomeClass1a() {  // in its own separate file
    public void doA(int p, int q, int r){
       // do something that requires x,y and p, q, r
    }
}

public class SomeClass1b() {  // in its own separate file
    public void doB(int q, int r, int s){
       // does something else that requires x, y and q, r, s
    }
}

So anyway, should I pass x and y each time (where x,y are variables stored in the helper class func) ?

 a.set(x,y);
 a.doA(p,q,r);

My idea was to have a special container class where x and y are held. The top level class would have an instance of the container class and change x,y  using the set methods.

// in the top level class:
Container c = new Container(x,y);
a.setContainer(c);
b.setContainer(c);

My helper classes would also have an instance of the container and it would point to the same instance as in the top level. That way they access the same x,y as in the top level.

I would like to know if I should

Use the container class

Load x,y each time into the subclasses

?? Some better method ??

Body:
I guess the answer to your question is the Design Pattern called Singleton.
It basically allows you to get and exploits the same (and unique) instance of a class whenever you want in your system.

This is its implementation (please forgive possible syntax errors, I did not compile it):

class Container{

  //eventually provides setters and getters
  public float x;
  public float y;
  //------------

  private static Container instance = null;
  private void Container(){

  }
  public static Container getInstance(){
    if(instance==null){
       instance = new Container();
      }
      return instance;
  }
}

then if elsewhere in your code you import the Container you can write for example

Container.getInstance().x = 3;
temp = Container.getInstance().x;

and you will affect the attributes of the unique container instance you have in your system

In many cases it is however better to use the Dependency Injection pattern as it reduces the coupling between different components.


问:
create a table without hardcode in html
I want to create a ten row five column table which has only two rows filled in it and also first cell of every row has a checkbox. I want to write entire table code in script of jquery but not define it as hardcode  data  in html page. I want it as an array instead of individual variables for each row.

```<code>$(document).ready(function() {
var table = [

{
  check: '<label><input type="checkbox" class="case" /><span></span>
  </label>',
  name: 'XYZ',
  score: '<div class="score">34</div>',
},
{
  check: '<label><input type="checkbox" class="case" /><span></span>
  </label>',
  name: 'XYZ',
  score: '<div class="score">34</div>',
},
{
  check: '<label><input type="checkbox" class="case" /><span></span>
  </label>',
  name: 'XYZ',
  score: '<div class="score">34</div>',
},

 $.each(table, function(index, obj)
 {
var row = '<tr>';
row += '<td>' + obj.check + '</td>';
row += '<td>' + obj.name + '</td>';
row += '<td>' + obj.score + '</td>';
row += '<td>' + obj.mail + '</td>';
row += '<td>' + obj.other + '</td>';
$('tbody').append(row);
});
</code>```

I dont want to declare objects every time. I want to use an array for defining "name, score, mail, other" and then push related items into that array variables

答:
Replace the loop by folowing code

```<code>  $.each(table, function(index, obj)
     {
       var row = '<tr>';
       var keys = Object.keys(obj);
       $.each(keys, function(index, val){
         row += '<td>' + obj[val] + '</td>';
      });
      row += '</tr>';
      $('tbody').append(row);
    });
</code>```

here you can see how an object could be iterated to get all the key-values,so you wouldn't need to explicitly write obj.name, obj.type etc.

Title: create a table without hardcode in html

Body:
I want to create a ten row five column table which has only two rows filled in it and also first cell of every row has a checkbox. I want to write entire table code in script of jquery but not define it as hardcode  data  in html page. I want it as an array instead of individual variables for each row.

$(document).ready(function() {
var table = [

{
  check: '<input type="checkbox" class="case" />
  ',
  name: 'XYZ',
  score: '
34
',
},
{
  check: '<input type="checkbox" class="case" />
  ',
  name: 'XYZ',
  score: '
34
',
},
{
  check: '<input type="checkbox" class="case" />
  ',
  name: 'XYZ',
  score: '
34
',
},

 $.each(table, function(index, obj)
 {
var row = '
';
row += '' + obj.check + '	';
row += '' + obj.name + '	';
row += '' + obj.score + '	';
row += '' + obj.mail + '	';
row += '' + obj.other + '	';
$('tbody').append(row);
});

I dont want to declare objects every time. I want to use an array for defining "name, score, mail, other" and then push related items into that array variables

Body:
Replace the loop by folowing code

  $.each(table, function(index, obj)
     {
       var row = '<tr>';
       var keys = Object.keys(obj);
       $.each(keys, function(index, val){
         row += '<td>' + obj[val] + '</td>';
      });
      row += '</tr>';
      $('tbody').append(row);
    });

here you can see how an object could be iterated to get all the key-values,so you wouldn't need to explicitly write obj.name, obj.type etc.


问:
Find extra space / new line after a closing ?> (php tag)
So I have a space/new line after a closing ?> (php tag) that is breaking my application.

How can I find it easily I have 1000 of files and 100000 lines of code in this app.

Ideally im after some regex combined with find grep to run on a unix box.

答:
This is possible with regular grep

```<code>grep -Pz '\?>[\s]+$' -Rl
</code>```

Will search for all files starting from the current directory and list all that have a ?> followed by white space at the end of the file.

-P Interpret the pattern as a Perl-compatible regular expression (PCRE).

-z Treats the input file as one long line - this is in part what makes it work

[\s]+ matches at least one white space - including newlines

If you want to match PHP files only:

```<code>find -name '*.php' | xargs grep -Pz '\?>[\s]+$' -l
</code>```

To search for white space at the beginning of the file before

```<code>find -name '*.php' | xargs grep -Pz '^[\s]+<\?' -l
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is possible with regular grep

grep -Pz '\?>[\s]+$' -Rl

Will search for all files starting from the current directory and list all that have a ?> followed by white space at the end of the file.

-P Interpret the pattern as a Perl-compatible regular expression (PCRE).

-z Treats the input file as one long line - this is in part what makes it work

[\s]+ matches at least one white space - including newlines

If you want to match PHP files only:

find -name '*.php' | xargs grep -Pz '\?>[\s]+$' -l

To search for white space at the beginning of the file before

find -name '*.php' | xargs grep -Pz '^[\s]+<\?' -l


问:
linq nested query conditional order by
I have a parent query with sub query return child ,
what i need to sort child query according to one property in parent.
here is sudo code:

```<code>from menu in db.Menus
                     orderby menu.Order
                     select new
                     {
                         Title= menu.Title,
                         OrderNumber = menu.Order,
                         data = (from menuItem in menu.Items
                                  let g = Guid.NewGuid()
                                  orderby g
                                 select new
                                 {
                                     id = worker.ID,
                                     Title = worker.JobTitle
                                  })
                                 .Take(4)

                     };
</code>```

that works ok,But what i need to sort some menu in random(NewGuid) and sort others with their item priority some thing like it:

```<code>  let g = Guid.NewGuid()
orderby menu.ISRandom ? g: menuItem.Order
</code>```

But it give error about mismatch guid and int.What's the soloution?
second:How can i replace take(4) with take(menu.size)?
thank's

答:
You can solve the ordering problem by adding ToString():

```<code>let g = Guid.NewGuid().ToString()
orderbymenu.ISRandom ? g : menuItem.Order.ToString()
</code>```

Using Take(someProperty) isn't allowed in an EF LINQ query. This is because the take is translated into a TOP(x) clause, which can't possibly refer to a column in the SQL result. You can only do this afterwards, after pulling the results into memory without Take (or taking some reasonable fixed maximum).

Title: linq nested query conditional order by

Body:
I have a parent query with sub query return child ,
what i need to sort child query according to one property in parent.
here is sudo code:

from menu in db.Menus
                     orderby menu.Order
                     select new
                     {
                         Title= menu.Title,
                         OrderNumber = menu.Order,
                         data = (from menuItem in menu.Items
                                  let g = Guid.NewGuid()
                                  orderby g
                                 select new
                                 {
                                     id = worker.ID,
                                     Title = worker.JobTitle
                                  })
                                 .Take(4)

                     };

that works ok,But what i need to sort some menu in random(NewGuid) and sort others with their item priority some thing like it:

  let g = Guid.NewGuid()
orderby menu.ISRandom ? g: menuItem.Order

But it give error about mismatch guid and int.What's the soloution?
second:How can i replace take(4) with take(menu.size)?
thank's

Body:
You can solve the ordering problem by adding ToString():

let g = Guid.NewGuid().ToString()
orderbymenu.ISRandom ? g : menuItem.Order.ToString()

Using Take(someProperty) isn't allowed in an EF LINQ query. This is because the take is translated into a TOP(x) clause, which can't possibly refer to a column in the SQL result. You can only do this afterwards, after pulling the results into memory without Take (or taking some reasonable fixed maximum).


问:
Could not migrate and how to set mysql DB using Django python
I am beginner of Django python. When I am running into this python manage.py migrate I am getting the following error.

```<code>Unknown command: 'migrate'
Type 'manage.py help' for usage.
</code>```

Here also I am trying to create one crud application with MYSQL database which is present inside localhost means I need to connect to my localhost database .I need to also know how to connect it inside the settings.py file with all credentials. My settings.py file is given below.

settings.py:

```<code>"""
Django settings for mysite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#=0(1b4%2y!3(hs%_4v&_*(-j#c#8__s6^=1+b0eqrar7810h+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'
</code>```

Please help me to resolve the above issue and connect to DB.

答:
First of all, if you have data you want to migrate execute this command:

```<code>python manage.py dumpdata > datadump.json
</code>```

Next step: change database configuration to MySql:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your-db-name',
        'USER': 'your-username',
        'PASSWORD': 'your-password',
        'HOST': 'localhost',
        'PORT': '',
    },
}
</code>```

Then execute:

```<code>python manage.py makemigrations
python manage.py migrate
</code>```

To restore the data type:

```<code>python manage.py loaddata datadump.json
</code>```

Body:
I am beginner of Django python. When I am running into this python manage.py migrate I am getting the following error.

Unknown command: 'migrate'
Type 'manage.py help' for usage.

Here also I am trying to create one crud application with MYSQL database which is present inside localhost means I need to connect to my localhost database .I need to also know how to connect it inside the settings.py file with all credentials. My settings.py file is given below.

settings.py:

"""
Django settings for mysite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#=0(1b4%2y!3(hs%_4v&_*(-j#c#8__s6^=1+b0eqrar7810h+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

Please help me to resolve the above issue and connect to DB.

Body:
First of all, if you have data you want to migrate execute this command:

python manage.py dumpdata > datadump.json

Next step: change database configuration to MySql:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your-db-name',
        'USER': 'your-username',
        'PASSWORD': 'your-password',
        'HOST': 'localhost',
        'PORT': '',
    },
}

Then execute:

python manage.py makemigrations
python manage.py migrate

To restore the data type:

python manage.py loaddata datadump.json


问:
TextBox.text value not updated when page is not refreshed
I have a textBox (tbAdresse) which doesn't have any value. Then I do this in javascript :

```<code> origin = document.getElementById("tbAdresse").value;
        if (origin == "")
            origin = <%=this.GetFormatStringCoordonnees("Paris")%>;
        else
            origin = <%=this.GetFormatStringCoordonnees(tbAdresse.Text)%>;
</code>```

In this code, on first Load origin equals to "" which is correct. When I write "something" in tbAdresse origin = "something" too so its ok. But in the else statement, tbAdresse.Text seems to always be equal to "".

I'm never refreshing the page while doing this and I think it's the reason why it's not working but I really don't get why. Can I update tbAdresse.Text to its actual value without refreshing the page ?

答:
Do you not mean to do this:

```<code> origin = document.getElementById("tbAdresse").value;
        if (origin == "")
            origin = <%=this.GetFormatStringCoordonnees("Paris")%>;
        else
            origin = <%=this.GetFormatStringCoordonnees(origin)%>;
</code>```

If not, please post some more details on what your the elements and functions actually are.

Body:
I have a textBox (tbAdresse) which doesn't have any value. Then I do this in javascript :

 origin = document.getElementById("tbAdresse").value;
        if (origin == "")
            origin = <%=this.GetFormatStringCoordonnees("Paris")%>;
        else
            origin = <%=this.GetFormatStringCoordonnees(tbAdresse.Text)%>;

In this code, on first Load origin equals to "" which is correct. When I write "something" in tbAdresse origin = "something" too so its ok. But in the else statement, tbAdresse.Text seems to always be equal to "".

I'm never refreshing the page while doing this and I think it's the reason why it's not working but I really don't get why. Can I update tbAdresse.Text to its actual value without refreshing the page ?

Body:
Do you not mean to do this:

 origin = document.getElementById("tbAdresse").value;
        if (origin == "")
            origin = <%=this.GetFormatStringCoordonnees("Paris")%>;
        else
            origin = <%=this.GetFormatStringCoordonnees(origin)%>;

If not, please post some more details on what your the elements and functions actually are.


问:
JS arguments.forEach is not a function
So this code works perfectly

```<code>var arr = [1, 2, 3, 4];
arr.forEach(function (el) {
    console.log(el);
})
</code>```

But if i try to do this:

```<code>function printArgsInfo() {
    arguments.forEach(function (el) {
        console.log(el);
    });
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
</code>```

arguments.forEach is not a function

Even though arguments is an array and if Itry to do this with a for in loop it still works.

答:
Per the MDN Docs:

The arguments object is an Array-like object corresponding to the arguments passed to a function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

So, it is not a true array and does not share the Array object's prototype -- which is where the forEach method is defined.

Interestingly, also from the MDN docs:

You can also use the Array.from() method or the spread operator to convert arguments to a real Array

```<code>var args = Array.from(arguments);
</code>```

So, here is a working example with your code:

```<code>function printArgsInfo() {
    var args = Array.from(arguments);

    args.forEach(function (el) {
        console.log(el);
    });
}

printArgsInfo(2, 3, 2.5, -110.5564, false);
</code>```

Title: JS arguments.forEach is not a function

Body:
So this code works perfectly

var arr = [1, 2, 3, 4];
arr.forEach(function (el) {
    console.log(el);
})

But if i try to do this:

function printArgsInfo() {
    arguments.forEach(function (el) {
        console.log(el);
    });
}
printArgsInfo(2, 3, 2.5, -110.5564, false);

arguments.forEach is not a function

Even though arguments is an array and if Itry to do this with a for in loop it still works.

Body:
Per the MDN Docs:

The arguments object is an Array-like object corresponding to the arguments passed to a function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

So, it is not a true array and does not share the Array object's prototype -- which is where the forEach method is defined.

Interestingly, also from the MDN docs:

You can also use the Array.from() method or the spread operator to convert arguments to a real Array

var args = Array.from(arguments);

So, here is a working example with your code:

function printArgsInfo() {
    var args = Array.from(arguments);

    args.forEach(function (el) {
        console.log(el);
    });
}

printArgsInfo(2, 3, 2.5, -110.5564, false);


问:
Capturing keystrokes in a panel in java
I want to capture keystrokes when the focus in on a panel in java. What should i do?

I am using Netbeans as the IDE. I tried adding keyTyped event but it doesnot work.

Here goes my code

```<code>import com.lanadmin.Interface.ClientInterface;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.rmi.Naming;
import java.util.logging.Level;

public class RemoteViewer extends javax.swing.JInternalFrame {

    public RemoteViewer() {
        initComponents();
        rdpanel.setFocusable(true);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        rdpanel = new javax.swing.JPanel();
        setFocusable(true);

        rdpanel.setToolTipText("Remote Desktop");
        rdpanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                rdpanelMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                rdpanelMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                rdpanelMouseReleased(evt);
            }
        });
        rdpanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                rdpanelMouseMoved(evt);
            }
        });
        rdpanel.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                rdpanelFocusGained(evt);
            }
        });
        rdpanel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                rdpanelKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                rdpanelKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                rdpanelKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout rdpanelLayout = new javax.swing.GroupLayout(rdpanel);
        rdpanel.setLayout(rdpanelLayout);
        rdpanelLayout.setHorizontalGroup(
            rdpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 679, Short.MAX_VALUE)
        );
        rdpanelLayout.setVerticalGroup(
            rdpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 626, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rdpanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rdpanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>
    private void rdpanelMouseMoved(java.awt.event.MouseEvent evt) {
        double xScale = Toolkit.getDefaultToolkit().getScreenSize().getWidth() / rdpanel.getWidth();
        double yScale = Toolkit.getDefaultToolkit().getScreenSize().getHeight() / rdpanel.getHeight();
        try {
            String current = Login.handler.currentClientAddress.getHostAddress();
            ClientInterface client = (ClientInterface) Naming.lookup("rmi://" + current + "/lan");
            client.mousemove((int) (evt.getX() * xScale), (int) (evt.getY() * yScale));
        } catch (Exception ex) {
            Log2File.logger.log(Level.SEVERE, null, ex);
            Log2File.fileHandler.flush();
        }
    }
    private void rdpanelKeyPressed(java.awt.event.KeyEvent evt) {
        System.out.println("keypressed");
    }
    private void rdpanelKeyTyped(java.awt.event.KeyEvent evt) {
        System.out.println("aaa");
    }
    private void rdpanelKeyReleased(java.awt.event.KeyEvent evt) {
        System.out.println("keyreleased");
    }
   private void rdpanelFocusGained(java.awt.event.FocusEvent evt) {
        rdpanel.addKeyListener(new java.awt.event.KeyAdapter() {
           @Override
            public void keyPressed(java.awt.event.KeyEvent evt) {
                rdpanelKeyPressed(evt);
            }
            @Override
            public void keyReleased(java.awt.event.KeyEvent evt) {
                rdpanelKeyReleased(evt);
            }
            @Override
            public void keyTyped(java.awt.event.KeyEvent evt) {
                rdpanelKeyTyped(evt);
            }
        });
    }
    public javax.swing.JPanel rdpanel;
}
</code>```

答:
Actually, what you want is a KeyboardManager to install a KeyEventPostProcessor, or even an alternate dispatch for various components.  I had the same issues in a NB app as you did.

Here's the article I used: (developer.com)

I did this to capture enter key events from any control in a panel (to initiate "OK" button behavior automatically):

```<code>    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    manager.addKeyEventPostProcessor(new EnterKeyListener());
</code>```

And the listener:

```<code>    class EnterKeyListener implements KeyEventPostProcessor {

    @Override
    public boolean postProcessKeyEvent(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            //Activate the refresh button:
            fireSearch();
            return true;    //halt further processing
        }
        return false;
    }
}
</code>```

Title: Capturing keystrokes in a panel in java

Body:
I want to capture keystrokes when the focus in on a panel in java. What should i do?

I am using Netbeans as the IDE. I tried adding keyTyped event but it doesnot work.

Here goes my code

import com.lanadmin.Interface.ClientInterface;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.rmi.Naming;
import java.util.logging.Level;

public class RemoteViewer extends javax.swing.JInternalFrame {

    public RemoteViewer() {
        initComponents();
        rdpanel.setFocusable(true);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        rdpanel = new javax.swing.JPanel();
        setFocusable(true);

        rdpanel.setToolTipText("Remote Desktop");
        rdpanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                rdpanelMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                rdpanelMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                rdpanelMouseReleased(evt);
            }
        });
        rdpanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                rdpanelMouseMoved(evt);
            }
        });
        rdpanel.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                rdpanelFocusGained(evt);
            }
        });
        rdpanel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                rdpanelKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                rdpanelKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                rdpanelKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout rdpanelLayout = new javax.swing.GroupLayout(rdpanel);
        rdpanel.setLayout(rdpanelLayout);
        rdpanelLayout.setHorizontalGroup(
            rdpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 679, Short.MAX_VALUE)
        );
        rdpanelLayout.setVerticalGroup(
            rdpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 626, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rdpanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rdpanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>
    private void rdpanelMouseMoved(java.awt.event.MouseEvent evt) {
        double xScale = Toolkit.getDefaultToolkit().getScreenSize().getWidth() / rdpanel.getWidth();
        double yScale = Toolkit.getDefaultToolkit().getScreenSize().getHeight() / rdpanel.getHeight();
        try {
            String current = Login.handler.currentClientAddress.getHostAddress();
            ClientInterface client = (ClientInterface) Naming.lookup("rmi://" + current + "/lan");
            client.mousemove((int) (evt.getX() * xScale), (int) (evt.getY() * yScale));
        } catch (Exception ex) {
            Log2File.logger.log(Level.SEVERE, null, ex);
            Log2File.fileHandler.flush();
        }
    }
    private void rdpanelKeyPressed(java.awt.event.KeyEvent evt) {
        System.out.println("keypressed");
    }
    private void rdpanelKeyTyped(java.awt.event.KeyEvent evt) {
        System.out.println("aaa");
    }
    private void rdpanelKeyReleased(java.awt.event.KeyEvent evt) {
        System.out.println("keyreleased");
    }
   private void rdpanelFocusGained(java.awt.event.FocusEvent evt) {
        rdpanel.addKeyListener(new java.awt.event.KeyAdapter() {
           @Override
            public void keyPressed(java.awt.event.KeyEvent evt) {
                rdpanelKeyPressed(evt);
            }
            @Override
            public void keyReleased(java.awt.event.KeyEvent evt) {
                rdpanelKeyReleased(evt);
            }
            @Override
            public void keyTyped(java.awt.event.KeyEvent evt) {
                rdpanelKeyTyped(evt);
            }
        });
    }
    public javax.swing.JPanel rdpanel;
}

Body:
Actually, what you want is a KeyboardManager to install a KeyEventPostProcessor, or even an alternate dispatch for various components.  I had the same issues in a NB app as you did.

Here's the article I used: (developer.com)

I did this to capture enter key events from any control in a panel (to initiate "OK" button behavior automatically):

    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    manager.addKeyEventPostProcessor(new EnterKeyListener());

And the listener:

    class EnterKeyListener implements KeyEventPostProcessor {

    @Override
    public boolean postProcessKeyEvent(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            //Activate the refresh button:
            fireSearch();
            return true;    //halt further processing
        }
        return false;
    }
}


问:
Custom Marker Overlap issue
I have displayed custom markers on the map. Some of them are overlapped each other.
so, for that i have created one logic to display infowindows seperate on each marker click.

Here is my Example : http://jsfiddle.net/u758rqpa/20/

Here you can see that when click on marker map is zooming.

but , i want that when i clicked on overlapped marker then it should be zoom not on one seperate marker click.

so, is there any way to find out that the markers are overlapped ?

so, i can stop zooming when marker is seperate.

```<code>        google.maps.event.addListener(marker, 'click', (function (marker, x, content) {
        return function () {
            var zoomLevel = map.getZoom();
            if (zoomLevel != 15)
                map.setZoom(zoomLevel + 1)

            infowindow.close();
            infowindow.setOptions({
                content: content,
                pixelOffset: new google.maps.Size(0, 20)
            })
            infowindow.open(map, this);
        }
    })(marker, x, content));
</code>```

Title: Custom Marker Overlap issue

Body:
I have displayed custom markers on the map. Some of them are overlapped each other.
so, for that i have created one logic to display infowindows seperate on each marker click.

Here is my Example : http://jsfiddle.net/u758rqpa/20/

Here you can see that when click on marker map is zooming.

but , i want that when i clicked on overlapped marker then it should be zoom not on one seperate marker click.

so, is there any way to find out that the markers are overlapped ?

so, i can stop zooming when marker is seperate.

        google.maps.event.addListener(marker, 'click', (function (marker, x, content) {
        return function () {
            var zoomLevel = map.getZoom();
            if (zoomLevel != 15)
                map.setZoom(zoomLevel + 1)

            infowindow.close();
            infowindow.setOptions({
                content: content,
                pixelOffset: new google.maps.Size(0, 20)
            })
            infowindow.open(map, this);
        }
    })(marker, x, content));

Body:
There is easy way for this, Marker Clusterer

Check this fiddle of yours.

More Examples Here

var markerCluster = new MarkerClusterer(map, markersArray, {imagePath:'https://googlemaps.github.io/js-marker-clusterer/images/m'});

  function initialize() {
      var mapOptions = {
          zoom: 7,
          draggableCursor: 'default',
          draggingCursor: 'pointer',
          visualRefresh: true,
          scaleControl: true,
          scaleControlOptions: {
              position: google.maps.ControlPosition.TOP_CENTER
          },
          streetViewControl: false,
          maxZoom: 17,
          minZoom: 4,
          center: new google.maps.LatLng(40.73761121, -73.8186132),
      };
      map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

      var infowindow = new google.maps.InfoWindow();

      var color = ['red', 'blue', 'yellow','pink', 'black','green','pink','gray','red', 'blue', 'yellow', 'black', 'gray'];

      var markerA = [
          ['BQ04998A_A', '-73.8186132', '40.73761121', '30'],
          ['BQ04280A_B', '-73.97947631', '40.64278852', '130'],
          ['BQ04673A_B', '-73.90797053', '40.63474517', '150'],
          ['LI12404B_A', '-73.72630945', '40.65964026', '30'],
          ['BQ04401A_C', '-73.78156774', '40.6451916', '250'],
          ['BQ06011B_B','-73.79849804','40.66775732','145'],
          ['BQ06176B_B','-73.86074985','40.75626901','140'],
          ['LI12869A_B','-73.59015092','40.6796578','150'],
          ['LI13123C_C','-73.1161812','40.90960403','303'],
          ['NY01114B_A','-73.99099681','40.75596539','340'],
          ['BQ04567E_A','-73.82849995','40.75500521','30'],
          ['LI12031A_A','-73.70109864','40.75319817','30'],
          ['LI12089B_A','-73.58183184','40.65620728','60'],
          ['BQ04072F_C','-73.8900656','40.7466413','290'],
          ['BQ04113A_B','-73.8933153','40.68161187','150']
      ];
      var marker;
      var mkrs = [];
      for (var i = 0; i < markerA.length; i++) {

          marker = new google.maps.Marker({
              position: new google.maps.LatLng(markerA[i][2], markerA[i][1]),
              map: map,
              icon: {
                  path: 'm 32.460621,0.112468 -32.372233,-0.022 0,-0.088 L 0,0.090468 l 22.91468,22.9147 c 0.02205,-0.022 0.04437,-0.044 0.06629,-0.066 6.300656,-6.3007 9.451842,-14.5699 9.47965,-22.8263 z',

                  fillColor: color[i],
                  fillOpacity: 1,
                  strokeColor: '',
                  strokeWeight: 0,
                  rotation: 280 + markerA[i][3],
                  anchor: new google.maps.Point(0, 0)
              }
          });

          mkrs.push(marker);

          google.maps.event.addListener(marker, 'click', (function (marker, i, content) {
              return function () {
                 var zoomLevel = map.getZoom();
            if (zoomLevel != 15)
                map.setZoom(zoomLevel + 1)

            infowindow.close();
            infowindow.setOptions({
                content: content,
                pixelOffset: new google.maps.Size(0, 20)
            })
            infowindow.open(map, this);
              }
          })(marker, i, content));
      }

            var markerCluster = new MarkerClusterer(map, mkrs, {imagePath: 'https://googlemaps.github.io/js-marker-clusterer/images/m'});
       var content = markerA[i][0];
  }

  google.maps.event.addDomListener(window, 'load', initialize);


问:
Ansible pip module: name package and umask 0022 Fatal error: invalid literal for int() with base 8: '18' umask must be an octal integer
ansible/ansible-playbook version: 2.1.2.0

I have the following action in my playbook:

```<code>- name: Install cli (as well)
  pip:
    name: "{{ mycompany_pip_pkg }}"
    umask: 0022
</code>```

Why am I getting the following fatal error message even though I followed the docs for Ansible pip module: http://docs.ansible.com/ansible/pip_module.html

Error:

```<code>TASK [company.company-ansible : Install cli (as well)] ****************
fatal: [localhost]: FAILED! => {"changed": false, "details": "invalid literal for int() with base 8: '18'", "failed": true, "msg": "umask must be an octal integer"}
</code>```

Ansible pip Docs says:

The system umask to apply before installing the pip package. This
  is useful, for example, when installing on systems that have a very
  restrictive umask by default (e.g., 0077) and you want to pip install
  packages which are to be used by all users. Note that this requires
  you to specify desired umask mode in octal, with a leading 0 (e.g.,
  0077).

http://programtalk.com/vs2/python/749/ansible-modules-core/packaging/language/pip.py/ shows the following code:

```<code>if umask and not isinstance(umask, int):
    try:
        umask = int(umask, 8)
    except Exception:
        module.fail_json(msg="umask must be an octal integer",
                         details=to_native(sys.exc_info()[1]))
</code>```

PS: The following syntax WORKS! but why the above one is not working?

```<code>- name: Install cli (as well)
  pip: name="{{ mycompany_pip_pkg }}" umask=0022
</code>```

UPDATE:

Question:

1) Why in Ansible pip module, when name property's value contains an  invalid package name, then this module is failing for umask property's value (which is correct in my case)?

答:
Just enclose the umask value in quotes.

Doesn't work:

```<code>  pip:
    name:
      - pika
      - argparse
    umask: 0022
</code>```

Does work:

```<code>  pip:
    name:
      - pika
      - argparse
    umask: "0022"
</code>```

The same problem used to occur with "file" module until it got fixed with https://github.com/ansible/ansible/issues/9196. As others pointed out, using key=value syntax works as well.

Body:
ansible/ansible-playbook version: 2.1.2.0

I have the following action in my playbook:

- name: Install cli (as well)
  pip:
    name: "{{ mycompany_pip_pkg }}"
    umask: 0022

Why am I getting the following fatal error message even though I followed the docs for Ansible pip module: http://docs.ansible.com/ansible/pip_module.html

Error:

TASK [company.company-ansible : Install cli (as well)] ****************
fatal: [localhost]: FAILED! => {"changed": false, "details": "invalid literal for int() with base 8: '18'", "failed": true, "msg": "umask must be an octal integer"}

Ansible pip Docs says:

The system umask to apply before installing the pip package. This
  is useful, for example, when installing on systems that have a very
  restrictive umask by default (e.g., 0077) and you want to pip install
  packages which are to be used by all users. Note that this requires
  you to specify desired umask mode in octal, with a leading 0 (e.g.,
  0077).

http://programtalk.com/vs2/python/749/ansible-modules-core/packaging/language/pip.py/ shows the following code:

if umask and not isinstance(umask, int):
    try:
        umask = int(umask, 8)
    except Exception:
        module.fail_json(msg="umask must be an octal integer",
                         details=to_native(sys.exc_info()[1]))

PS: The following syntax WORKS! but why the above one is not working?

- name: Install cli (as well)
  pip: name="{{ mycompany_pip_pkg }}" umask=0022

UPDATE:

Question:

1) Why in Ansible pip module, when name property's value contains an  invalid package name, then this module is failing for umask property's value (which is correct in my case)?

Body:
Just enclose the umask value in quotes.

Doesn't work:

  pip:
    name:
      - pika
      - argparse
    umask: 0022

Does work:

  pip:
    name:
      - pika
      - argparse
    umask: "0022"

The same problem used to occur with "file" module until it got fixed with https://github.com/ansible/ansible/issues/9196. As others pointed out, using key=value syntax works as well.


问:
How to access package references within a Task for dotnet build
Is it possible to use package references like Microsoft.CodeAnalysis within a Microsoft Build Task running with dotnet build?

I'm using netstandard1.5 for the task library and the following package references:

```<code><PackageReference Include="Microsoft.Build" Version="15.3.0-preview-000117-01" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="15.3.0-preview-000117-01" />
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="2.2.0" />
</code>```

The consuming project is a netcoreapp1.1. The task fails with an

The "MyTask" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.CodeAnalysis, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

exception.

When trying to load the package reference via AssemblyLoadContext.Default.LoadFromAssemblyPath I get

Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

without any additional information. This does not work when running in a .net core console application either. I tried a second (simpler) package, which can be loaded via LoadFromAssemblyPath in a .net core console application, but still it does not work when running as dotnet build Task.

Both assemblies can be loaded when running in classical net4.6 with Assembly.LoadFile in a console application and when running as Task though.

答: Unfortunately task dlls cannot reference any packages - they are loaded into the running msbuild instance and will only be able to reference the dlls that are available to the hosting msbuild instance. Any other DLLs could be loaded via AssemblyLoadContext in .net core or AppDomain.Load() in .net framework. No dependency resolution is performed for the task's dll file, this also means that there may be conflicts with already loaded dlls, different parts of msbuild or other tasks. In .NET Framework MSBuild, tasks can be isolated to their own AppDomains, but this mechanism is not available on .NET Core.

Body:
Is it possible to use package references like Microsoft.CodeAnalysis within a Microsoft Build Task running with dotnet build?

I'm using netstandard1.5 for the task library and the following package references:

<PackageReference Include="Microsoft.Build" Version="15.3.0-preview-000117-01" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="15.3.0-preview-000117-01" />
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="2.2.0" />

The consuming project is a netcoreapp1.1. The task fails with an

The "MyTask" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.CodeAnalysis, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

exception.

When trying to load the package reference via AssemblyLoadContext.Default.LoadFromAssemblyPath I get

Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

without any additional information. This does not work when running in a .net core console application either. I tried a second (simpler) package, which can be loaded via LoadFromAssemblyPath in a .net core console application, but still it does not work when running as dotnet build Task.

Both assemblies can be loaded when running in classical net4.6 with Assembly.LoadFile in a console application and when running as Task though.


问:
Application object in ASP.NET
I was reading a article saying " the first time a user request a page that resides in an application's directory, ASP.NET initializes the application. During that process, ASP.NET creates an application object, application state object and a cache object.

My questions are:

Let's say I have many users request a page from the application, how many application state objects are created by the application? just one or many? will new application state object be created for every new user? or all users share the same objects?

If there is only one application object created, how can the application know which Session belongs to which users? For examples, Michael requests a page, nd setting Session["name']= "Michael", Sarah also requests a page and setting Session["name']= "Sarah", so how can the application what's the value of Session["name']?

答:
For Sessions, see How the session work in asp.net? . In short - it identifies the session via a cookie.

For Application / Application State, there is one object. See https://msdn.microsoft.com/en-us/library/ms178594.aspx for more details.

Title: Application object in ASP.NET


问:
CakePHP find condition for a query between two dates
I have a start and an end date in my database and a $date variable from a form field. I am now trying to query all the rows where $date is either = start/end date in the db, or ANY date between those two.

It's kind of the opposite of what is described in the docs of how daysAsSql works. I can't figure out how to get it to work. The following line does not work as a find condition in the controller:

```<code>'? BETWEEN ? AND ?' => array($date, 'Item.date_start', 'Item.date_end'),
</code>```

Any help is greatly appreciated. This is driving me crazy.

Here is the complete Query and corresponding SQL:

```<code>$conditions = array(
            'conditions' => array(
            'and' => array(
                '? BETWEEN ? AND ?' => array($date, 'Item.date_start', 'Item.date_end'),
                'Item.title LIKE' => "%$title%",
                'Item.status_id =' => '1'
                )));

        $this->set('items', $this->Item->find('all', $conditions));

WHERE (('2012-10-06' BETWEEN 'Item.date_start' AND 'Item.date_end') AND (`Item`.`title` LIKE '%%') AND (`Item`.`status_id` = 1))
</code>```

答:
Here is CakePHP BETWEEN query example.

I'm defining my arrays as variables, and then using those variables in my CakePHP find function call:

```<code>// just return these two fields
$fields = array('uri', 'page_views');

// use this "between" range
$conditions = array('Event.date BETWEEN ? and ?' => array($start_date, $end_date));

// run the "select between" query
$results = $this->Event->find('all',
         array('fields'=>$fields,
               'conditions'=>$conditions));
</code>```

Ref from

Body:
I have a start and an end date in my database and a $date variable from a form field. I am now trying to query all the rows where $date is either = start/end date in the db, or ANY date between those two.

It's kind of the opposite of what is described in the docs of how daysAsSql works. I can't figure out how to get it to work. The following line does not work as a find condition in the controller:

'? BETWEEN ? AND ?' => array($date, 'Item.date_start', 'Item.date_end'),

Any help is greatly appreciated. This is driving me crazy.

Here is the complete Query and corresponding SQL:

$conditions = array(
            'conditions' => array(
            'and' => array(
                '? BETWEEN ? AND ?' => array($date, 'Item.date_start', 'Item.date_end'),
                'Item.title LIKE' => "%$title%",
                'Item.status_id =' => '1'
                )));

        $this->set('items', $this->Item->find('all', $conditions));

WHERE (('2012-10-06' BETWEEN 'Item.date_start' AND 'Item.date_end') AND (`Item`.`title` LIKE '%%') AND (`Item`.`status_id` = 1))

Body:
Here is CakePHP BETWEEN query example.

I'm defining my arrays as variables, and then using those variables in my CakePHP find function call:

// just return these two fields
$fields = array('uri', 'page_views');

// use this "between" range
$conditions = array('Event.date BETWEEN ? and ?' => array($start_date, $end_date));

// run the "select between" query
$results = $this->Event->find('all',
         array('fields'=>$fields,
               'conditions'=>$conditions));

Ref from


问:
JS onclick() not called at all in IE
I've created a drop-down menu with HTML and JS. When I run it in Chrome it works great, but it doesn't work in IE. The onclick() function doesn't seem to be called at all.

The options tags within the select tag look like this:

```<code><option value="?id=3" onclick="hideDropDown();return false;">Option 3</option>
</code>```

but hideDropDown() never gets run in IE (I've checked using an alert() within the function).

The same for:

```<code><option value="?id=2" onclick="alert('hi'); return false;">Option 2</option>
</code>```

clicking on 'Option 2' in this case does not bring up an alert.

I've read a lot online about onclick() not working in IE, but none of the answers I've seen have worked for me. Does anybody have any suggestions?

答:
It seems that there're issues with onclick events in <option> tags. One of the alternatives would be placing an onchange event into the parent <select> tag:

```<code><select onchange="check(this.value)">
  <option value="1">one</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
</code>```

Then check() function is executed every time an option is selected (clicked):

```<code>function check(value) {
  alert(value);
}
</code>```

Also, you could look at the option's value to run certain code only for it:

```<code>function check(value) {
  if (value === 2) {
    alert("You clicked two!");
  }
}
</code>```

Working example

https://codepen.io/anon/pen/jwbvbR

Title: JS onclick() not called at all in IE

Body:
I've created a drop-down menu with HTML and JS. When I run it in Chrome it works great, but it doesn't work in IE. The onclick() function doesn't seem to be called at all.

The options tags within the select tag look like this:

<option value="?id=3" onclick="hideDropDown();return false;">Option 3</option>

but hideDropDown() never gets run in IE (I've checked using an alert() within the function).

The same for:

<option value="?id=2" onclick="alert('hi'); return false;">Option 2</option>

clicking on 'Option 2' in this case does not bring up an alert.

I've read a lot online about onclick() not working in IE, but none of the answers I've seen have worked for me. Does anybody have any suggestions?

Body:
It seems that there're issues with onclick events in <option> tags. One of the alternatives would be placing an onchange event into the parent <select> tag:

<select onchange="check(this.value)">
  <option value="1">one</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>

Then check() function is executed every time an option is selected (clicked):

function check(value) {
  alert(value);
}

Also, you could look at the option's value to run certain code only for it:

function check(value) {
  if (value === 2) {
    alert("You clicked two!");
  }
}

Working example

https://codepen.io/anon/pen/jwbvbR


问:
Fetch Firebase data from app to website?
I have built an iphone app that writes data to firebase. That works fine. Now I want to display that data on a  website. I am totally new to programming, and had to learn swift from scratch.

So  my question is; is there a easy way to display the data on the webpage? It dont have to look  good as long as the data is displayed. I'm not sure if I'm able to learn another codelanguage just yet  ☺

答:
You may use the Firebase JS SDK
https://firebase.google.com/docs/database/web/start

use Nodejs to generate static HTML

or

use Express as the website framework, dynamically generate the pages


答:
There is just one Application object per application, which is shared by all users. The Session object is not shared between sessions (and thus users).

The Session state is not part of the Application context. ASP.NET knows which session belongs to who (based on session cookies for example).

Title: Application object in ASP.NET

Body:
I was reading a article saying " the first time a user request a page that resides in an application's directory, ASP.NET initializes the application. During that process, ASP.NET creates an application object, application state object and a cache object.

My questions are:

Let's say I have many users request a page from the application, how many application state objects are created by the application? just one or many? will new application state object be created for every new user? or all users share the same objects?

If there is only one application object created, how can the application know which Session belongs to which users? For examples, Michael requests a page, nd setting Session["name']= "Michael", Sarah also requests a page and setting Session["name']= "Sarah", so how can the application what's the value of Session["name']?


问:
How to rename Key for QMap?
I have this QMap<int, myDB> myTable like this

```<code>(1, {something0})
(3, {something1})
(5, {something2})
(8, {something3})
</code>```

How can I change Key for myTable with first key begin from 0?

```<code>(0, {something0})
(1, {something1})
(2, {something2})
(3, {something3})
</code>```

答:
You can not change the key directly in the original map, instead create an other map, assign the values to the other map with reorganized key, then use QMap::swap to replace the original map items. The snippets will look like

```<code>//Make sure myDB is assignable
QMap<int, myDB> other;
QList<int> keys = myTable.uniqueKeys();
for (int k = 0; k < keys.length(); k++) {
    int key = keys[k];

    //We're using insertMulti in case
    //we have multiple values associated to single key
    QList<myDB> values = myTable.values(key);
    for (int j = 0; j < values.length(); j++) {
        other.insertMulti(k, values.at(j));
    }
}
myTable.swap(other);
</code>```

Title: How to rename Key for QMap?

Body:
I have this QMap<int, myDB> myTable like this

(1, {something0})
(3, {something1})
(5, {something2})
(8, {something3})

How can I change Key for myTable with first key begin from 0?

(0, {something0})
(1, {something1})
(2, {something2})
(3, {something3})

Body:
You can not change the key directly in the original map, instead create an other map, assign the values to the other map with reorganized key, then use QMap::swap to replace the original map items. The snippets will look like

//Make sure myDB is assignable
QMap<int, myDB> other;
QList<int> keys = myTable.uniqueKeys();
for (int k = 0; k < keys.length(); k++) {
    int key = keys[k];

    //We're using insertMulti in case
    //we have multiple values associated to single key
    QList<myDB> values = myTable.values(key);
    for (int j = 0; j < values.length(); j++) {
        other.insertMulti(k, values.at(j));
    }
}
myTable.swap(other);


Title: How to add groupBy().count() to the source DataFrame?

Body:
I have the following dataframe:

+---------------+--------------+--------------+-----+
|        column0|       column1|       column2|label|
+---------------+--------------+--------------+-----+
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
+---------------+--------------+--------------+-----+

I want to apply groupBy and count on it and make the following result:

+--------------+--------------+-----+
|       column1|       column2|count|
+--------------+--------------+-----+
|10.0.0.2.54880| 10.0.0.3.5001|   19|
| 10.0.0.3.5001|10.0.0.2.54880|   10|
+--------------+--------------+-----+

I know that I have to use this:

dataFrame_Train.groupBy("column1", "column2").count().show()

However the problem is that I need to add "count" column as a permanent column to my dataframe.
In the above case, if I use dataFrame_Train.show() after the groupBy, I see the first dataframe without "count" column. This code:

dataFrame_Train.groupBy("column1", "column2").count().show()
`dataFrame_Train.show()`

Can you help me to add groupBy("column1", "column2").count() to the dataframe? (Since I need to use "count" column for training the data in future) Thanks.

Body:
We will use the same data that you have presented in csv format.

Let's read those data :

scala> val df = spark.read.format("csv").load("data.txt").toDF("column0","column1","column2","label")
// df: org.apache.spark.sql.DataFrame = [column0: string, column1: string ... 2 more fields]

We can now perform our group by aggregations :

scala> val df2 = df.groupBy("column1","column2").count
df2: org.apache.spark.sql.DataFrame = [column1: string, column2: string ... 1 more field]

All we need to do is an equi-join on the same columns you performed the group by key on :

scala> val df3 = df.join(df2, Seq("column1","column2"))
df3: org.apache.spark.sql.DataFrame = [column1: string, column2: string ... 3 more fields]

Et voilà !

scala> df3.show
+--------------+--------------+---------------+-----+-----+
|       column1|       column2|        column0|label|count|
+--------------+--------------+---------------+-----+-----+
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604899|    2|   13|
| 10.0.0.3.5001|10.0.0.2.54880|05:49:56.604908|    2|    7|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604900|    2|   13|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604899|    2|   13|
| 10.0.0.3.5001|10.0.0.2.54880|05:49:56.604908|    2|    7|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604900|    2|   13|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604899|    2|   13|
| 10.0.0.3.5001|10.0.0.2.54880|05:49:56.604908|    2|    7|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604900|    2|   13|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604899|    2|   13|
| 10.0.0.3.5001|10.0.0.2.54880|05:49:56.604908|    2|    7|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604900|    2|   13|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604899|    2|   13|
| 10.0.0.3.5001|10.0.0.2.54880|05:49:56.604908|    2|    7|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604900|    2|   13|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604899|    2|   13|
| 10.0.0.3.5001|10.0.0.2.54880|05:49:56.604908|    2|    7|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604900|    2|   13|
|10.0.0.2.54880| 10.0.0.3.5001|05:49:56.604899|    2|   13|
| 10.0.0.3.5001|10.0.0.2.54880|05:49:56.604908|    2|    7|
+--------------+--------------+---------------+-----+-----+


问:
ASP.NET MVC Custom controller not working
I have a Project called Project.Web which contains a folder Mvc which includes a base controller called BaseController.cs.

```<code>namespace ProsecVHIPHelper.Web.Mvc
{
    /// <summary>
    /// A base controller for all controllers
    /// </summary>
    public abstract class BaseController : Controller
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="applicationContext"></param>
        protected BaseController(ApplicationContext applicationContext)
        {
            if (applicationContext == null) throw new ArgumentNullException("applicationContext");
            ApplicationContext = applicationContext;
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        protected BaseController() : this(ApplicationContext.Current) { }

        /// <summary>
        /// The application context
        /// </summary>
        public ApplicationContext ApplicationContext
        {
            get;
            private set;
        }

        /// <summary>
        /// Get the services singleton
        /// </summary>
        public ServiceContext Services
        {
            get { return ApplicationContext.Services; }
        }
    }
}
</code>```

This base controller will be used by all of my other controllers.

In my second project called Project.Web.UI I have a route config like:

```<code>public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Ftp", action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { "Project.Web.Mvc" }
            );
        }
    }
</code>```

Where I include the base controller namespace.

But when I create new controllers using my base controller I always get a 404 not found exception.

When I use the default Controller class then it works.

First my controllers where located in the Project.Web project in a folder called Controllers. When I add this namespace also in the route config it doesn't work.

Then I moved these controllers ( not the base controller ) to my other project Project.Web.UI, but still no luck.

The Project.Web project is a class library and the Project.Web.UI is a web project.

Any ideas?

答:
Ok I have found the solution. The problem was that I have added the System.Web.Mvc using the add reference. But this had a different version from the System.Web.Mvc in my web project.

After removing this reference and added a reference to the dll in the web project, everything worked like a charm!

Body:
I have a Project called Project.Web which contains a folder Mvc which includes a base controller called BaseController.cs.

namespace ProsecVHIPHelper.Web.Mvc
{
    ///
    /// A base controller for all controllers
    ///
    public abstract class BaseController : Controller
    {
        ///
        /// Constructor
        ///
        /// <param name="applicationContext"></param>
        protected BaseController(ApplicationContext applicationContext)
        {
            if (applicationContext == null) throw new ArgumentNullException("applicationContext");
            ApplicationContext = applicationContext;
        }

        ///
        /// Default constructor
        ///
        protected BaseController() : this(ApplicationContext.Current) { }

        ///
        /// The application context
        ///
        public ApplicationContext ApplicationContext
        {
            get;
            private set;
        }

        ///
        /// Get the services singleton
        ///
        public ServiceContext Services
        {
            get { return ApplicationContext.Services; }
        }
    }
}

This base controller will be used by all of my other controllers.

In my second project called Project.Web.UI I have a route config like:

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Ftp", action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { "Project.Web.Mvc" }
            );
        }
    }

Where I include the base controller namespace.

But when I create new controllers using my base controller I always get a 404 not found exception.

When I use the default Controller class then it works.

First my controllers where located in the Project.Web project in a folder called Controllers. When I add this namespace also in the route config it doesn't work.

Then I moved these controllers ( not the base controller ) to my other project Project.Web.UI, but still no luck.

The Project.Web project is a class library and the Project.Web.UI is a web project.

Any ideas?