问:
How to log values which raised KeyError
Given this DataFrame, df:

```<code>     Player 1    Player 2
0    Thiem D.  Almagro N.
1  Almagro N.   Ferrer D.
2    Nadal R.    Thiem D.
</code>```

and mapping d:

```<code>d = {
    'Thiem D.': 'Dominic Thiem',
    'Nadal R.': 'Rafael Nadal',
    'Ferrer D.': 'David Ferrer',
}
</code>```

I want to rename player names and while doing so I want to keep track of elements not existing in the mapping (save to a file, or just print).

The first part of the assingment I can achieve with this line:

```<code>player_columns = ['Player 1', 'Player 2']
df[player_columns] = df[player_columns].applymap(lambda x: d.get(x, x))
</code>```

Which results in:

```<code>        Player 1       Player 2
0  Dominic Thiem     Almagro N.
1     Almagro N.   David Ferrer
2   Rafael Nadal  Dominic Thiem
</code>```

Almagro N. is not existing entry in the mapping hence why it could not be renamed. And I would like to capture this name.

I am aware I can subclass UserDict object and implement this behavoir there but I am curious if there is other way about doing it?

答:
You can create Series by stack and get all unique values by boolean indexing with boolean mask by map and isnull:

```<code>df1 = df[player_columns].stack()
print (df1)
0  Player 1      Thiem D.
   Player 2    Almagro N.
1  Player 1    Almagro N.
   Player 2     Ferrer D.
2  Player 1      Nadal R.
   Player 2      Thiem D.
dtype: object

print (df1[df1.map(d).isnull()].unique())
['Almagro N.']
</code>```

Title: How to log values which raised KeyError

Body:
Given this DataFrame, df:

     Player 1    Player 2
0    Thiem D.  Almagro N.
1  Almagro N.   Ferrer D.
2    Nadal R.    Thiem D.

and mapping d:

d = {
    'Thiem D.': 'Dominic Thiem',
    'Nadal R.': 'Rafael Nadal',
    'Ferrer D.': 'David Ferrer',
}

I want to rename player names and while doing so I want to keep track of elements not existing in the mapping (save to a file, or just print).

The first part of the assingment I can achieve with this line:

player_columns = ['Player 1', 'Player 2']
df[player_columns] = df[player_columns].applymap(lambda x: d.get(x, x))

Which results in:

        Player 1       Player 2
0  Dominic Thiem     Almagro N.
1     Almagro N.   David Ferrer
2   Rafael Nadal  Dominic Thiem

Almagro N. is not existing entry in the mapping hence why it could not be renamed. And I would like to capture this name.

I am aware I can subclass UserDict object and implement this behavoir there but I am curious if there is other way about doing it?

Body:
You can create Series by stack and get all unique values by boolean indexing with boolean mask by map and isnull:

df1 = df[player_columns].stack()
print (df1)
0  Player 1      Thiem D.
   Player 2    Almagro N.
1  Player 1    Almagro N.
   Player 2     Ferrer D.
2  Player 1      Nadal R.
   Player 2      Thiem D.
dtype: object

print (df1[df1.map(d).isnull()].unique())
['Almagro N.']


来源: stackexchange

问:
ListView text is truncated -- how do I display the entire text of an item?
Here's a picture of a System.Windows.Forms.ListView using LargeIcons

The selected item shows all it's text

e.g. The top left item shows only 11 characters of its name, it's shown fully if that's selected. How can I make it show all the text(or atleast more than 11 characters), for items that's not selected ?

答: I had this problem a while ago and solved by inserting a space after x characters and/or before a capital letter, so the text is wrapped where I wanted it to. This is somewhat a hack but it's an easy fix. You of course need to keep track of the changed you made to the text so you can reverse it if the user selects the item for further use.</p>

ContentLicense: CC BY-SA 2.5


问:
AngularJS $http POST request
When I'm making POST request with headers as content-type: application/JSON headers don't set a cookie in Request Headers. But when I change the headers as content-type: application/x-www-form-urlencoded headers set a cookie in Request Headers.
Server accepts application/JSON format.
Also, I have already given with-credentials: true on the client side.

答:
Though the code is not available, I assume that setting the path parameter of the cookie will do the trick for you. The following may help:

cookies problem in PHP and AJAX

Why is the browser not setting cookies after an AJAX request returns?

ContentLicense: CC BY-SA 3.0

Title: AngularJS $http POST request


问:
Recognize if not enough resources during timeframe
i need an idea how to solve the following problem.

Lets say i have one group with given timeframe (8:00-12:00) and i can assign resources (people) to it. Each resource can have a custom timeframe (like 9-10, 9-12,8-12 etc.) and could be assigned multiple times.

Tables

Groups

ID,
TITLE,
START_TIME,
END_TIME,
REQUIRED_PEOPLE:INTEGER

PeopleAssignments

ID,
USER_ID,
GROUP_ID,
START_TIME,
END_TIME

Now i have the rule that at any given time during the group timeframe that there have to be like like 4 people assigned. Otherwise i want to get a warning.

I am working with ruby & sql (Postgres) here.

is there an elegant way without iterating through the whole timeframe and checking if count(assignments) > REQUIRED_PEOPLE

答:
You can solve this with only SQL too (if you are interested in such answers).

Range types offers great functions and operators to calculate with.

These solutions will give you rows, when there are sub-ranges, where there is some missing people from a given group (and it will give you which sub-range it is exactly & how many people is missing from the required number).

The easy way:

You wanted to try something similar to this. You'll need to pick some interval in which the count() is based on (I picked 5 minutes):

```<code>select     g.id group_id, i start_time, i + interval '5 minutes' end_time, g.required_people - count(a.id)
from       groups g
cross join generate_series(g.start_time, g.end_time, interval '5 minutes') i
left join  people_assignments a on a.group_id = g.id
where      tsrange(a.start_time, a.end_time) && tsrange(i, i + interval '5 minutes')
group by   g.id, i
having     g.required_people - count(a.id) > 0
order by   g.id, i
</code>```

But note that you won't be able to detect missing sub-ranges, when they are less than 5 minutes. F.ex. user1 has assignment for 11:00-11:56 and user2 has one for 11:59-13:00, they will appear to be "in" the group for 11:00-13:00 (so the missing sub-range of 11:56-11:59 will go unnoticed).

Note: the more short the interval is (what you've picked) the more precise (and slow!) the results will be.

http://rextester.com/GRC64969

The hard way:

You can accumulate the result on-the-fly with custom aggregates or recursive CTEs

```<code>with recursive r as (
    -- start with "required_people" as "missing_required_people" in the whole range
    select 0 iteration,
           id group_id,
           array[]::int[] used_assignment_ids,
           -- build a json map, where keys are the time ranges
           -- and values are the number of missing people for that range
           jsonb_build_object(tsrange(start_time, end_time), required_people) required_people_per_time_range
    from   groups
    where  required_people > 0
    and    id = 1 -- query parameter
  union all
    select r.iteration + 1,
           r.group_id,
           r.used_assignment_ids || a.assignment_id,
           d.required_people_per_time_range
    from   r
    -- join a single assignment to the previous iteration, where
    -- the assigment's time range overlaps with (at least one) time range,
    -- where there is still missing people. when there are no such time range is
    -- found in assignments, the "recursion" (which is really just a loop) stops
    cross join lateral (
      select     a.id assignment_id, tsrange(start_time, end_time) time_range
      from       people_assignments a
      cross join (select key::tsrange time_range from jsonb_each(r.required_people_per_time_range)) j
      where      a.group_id = r.group_id
      and        a.id <> ALL (r.used_assignment_ids)
      and        tsrange(start_time, end_time) && j.time_range
      limit      1
    ) a
    -- "partition" && accumulate all remaining time ranges with
    -- the one found in the previous step
    cross join lateral (
      -- accumulate "partition" results
      select jsonb_object_agg(u.time_range, u.required_people) required_people_per_time_range
      from   (select key::tsrange time_range, value::int required_people
              from   jsonb_each_text(r.required_people_per_time_range)) j
      cross join lateral (
        select u time_range, j.required_people - case when u && a.time_range then 1 else 0 end required_people
        -- "partition" the found time range with all existing ones, one-by-one
        from   unnest(case
                 when j.time_range @> a.time_range
                 then array[tsrange(lower(j.time_range), lower(a.time_range)), a.time_range, tsrange(upper(a.time_range), upper(j.time_range))]
                 when j.time_range && a.time_range
                 then array[j.time_range * a.time_range, j.time_range - a.time_range]
                 else array[j.time_range]
               end) u
        where not isempty(u)
      ) u
    ) d
),
-- select only the last iteration
l as (
  select   group_id, required_people_per_time_range
  from     r
  order by iteration desc
  limit    1
)
-- unwind the accumulated json map
select     l.group_id, lower(time_range) start_time, upper(time_range) end_time, missing_required_people
from       l
cross join lateral (
  select key::tsrange time_range, value::int missing_required_people
  from   jsonb_each_text(l.required_people_per_time_range)
) j
-- select only where there is still some missing people
-- this is optional, if you omit it you'll also see row(s) for sub-ranges where
-- there is enough people in the group (these rows will have zero,
-- or negative amount of "missing_required_people")
where      j.missing_required_people > 0
</code>```

http://rextester.com/GHPD52861

Body:
You can solve this with only SQL too (if you are interested in such answers).

Range types offers great functions and operators to calculate with.

These solutions will give you rows, when there are sub-ranges, where there is some missing people from a given group (and it will give you which sub-range it is exactly & how many people is missing from the required number).

The easy way:

You wanted to try something similar to this. You'll need to pick some interval in which the count() is based on (I picked 5 minutes):

select     g.id group_id, i start_time, i + interval '5 minutes' end_time, g.required_people - count(a.id)
from       groups g
cross join generate_series(g.start_time, g.end_time, interval '5 minutes') i
left join  people_assignments a on a.group_id = g.id
where      tsrange(a.start_time, a.end_time) && tsrange(i, i + interval '5 minutes')
group by   g.id, i
having     g.required_people - count(a.id) > 0
order by   g.id, i

But note that you won't be able to detect missing sub-ranges, when they are less than 5 minutes. F.ex. user1 has assignment for 11:00-11:56 and user2 has one for 11:59-13:00, they will appear to be "in" the group for 11:00-13:00 (so the missing sub-range of 11:56-11:59 will go unnoticed).

Note: the more short the interval is (what you've picked) the more precise (and slow!) the results will be.

http://rextester.com/GRC64969

The hard way:

You can accumulate the result on-the-fly with custom aggregates or recursive CTEs

with recursive r as (
    -- start with "required_people" as "missing_required_people" in the whole range
    select 0 iteration,
           id group_id,
           array[]::int[] used_assignment_ids,
           -- build a json map, where keys are the time ranges
           -- and values are the number of missing people for that range
           jsonb_build_object(tsrange(start_time, end_time), required_people) required_people_per_time_range
    from   groups
    where  required_people > 0
    and    id = 1 -- query parameter
  union all
    select r.iteration + 1,
           r.group_id,
           r.used_assignment_ids || a.assignment_id,
           d.required_people_per_time_range
    from   r
    -- join a single assignment to the previous iteration, where
    -- the assigment's time range overlaps with (at least one) time range,
    -- where there is still missing people. when there are no such time range is
    -- found in assignments, the "recursion" (which is really just a loop) stops
    cross join lateral (
      select     a.id assignment_id, tsrange(start_time, end_time) time_range
      from       people_assignments a
      cross join (select key::tsrange time_range from jsonb_each(r.required_people_per_time_range)) j
      where      a.group_id = r.group_id
      and        a.id <> ALL (r.used_assignment_ids)
      and        tsrange(start_time, end_time) && j.time_range
      limit      1
    ) a
    -- "partition" && accumulate all remaining time ranges with
    -- the one found in the previous step
    cross join lateral (
      -- accumulate "partition" results
      select jsonb_object_agg(u.time_range, u.required_people) required_people_per_time_range
      from   (select key::tsrange time_range, value::int required_people
              from   jsonb_each_text(r.required_people_per_time_range)) j
      cross join lateral (
        select u time_range, j.required_people - case when u && a.time_range then 1 else 0 end required_people
        -- "partition" the found time range with all existing ones, one-by-one
        from   unnest(case
                 when j.time_range @> a.time_range
                 then array[tsrange(lower(j.time_range), lower(a.time_range)), a.time_range, tsrange(upper(a.time_range), upper(j.time_range))]
                 when j.time_range && a.time_range
                 then array[j.time_range * a.time_range, j.time_range - a.time_range]
                 else array[j.time_range]
               end) u
        where not isempty(u)
      ) u
    ) d
),
-- select only the last iteration
l as (
  select   group_id, required_people_per_time_range
  from     r
  order by iteration desc
  limit    1
)
-- unwind the accumulated json map
select     l.group_id, lower(time_range) start_time, upper(time_range) end_time, missing_required_people
from       l
cross join lateral (
  select key::tsrange time_range, value::int missing_required_people
  from   jsonb_each_text(l.required_people_per_time_range)
) j
-- select only where there is still some missing people
-- this is optional, if you omit it you'll also see row(s) for sub-ranges where
-- there is enough people in the group (these rows will have zero,
-- or negative amount of "missing_required_people")
where      j.missing_required_people > 0

http://rextester.com/GHPD52861


问:
How to obtain values of parameters of get request in flask?
The answer that I found on the web is to use request.args.get. However, I cannot manage it to work. I have the following simple example:

```<code>from flask import Flask
app = Flask(__name__)

@app.route("/hello")
def hello():
    print request.args['x']
    return "Hello World!"

if __name__ == "__main__":
    app.run()
</code>```

I go to the 127.0.0.1:5000/hello?x=2 in my browser and as a result I get:

```<code>Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
</code>```

What am I doing wrong?

答:
http://localhost:5000/api/iterators/opel/next?n=5

For something like the case before

```<code>from flask import Flask, request
n = request.args.get("n")
</code>```

Can do the trick

Body:
The answer that I found on the web is to use request.args.get. However, I cannot manage it to work. I have the following simple example:

from flask import Flask
app = Flask(__name__)

@app.route("/hello")
def hello():
    print request.args['x']
    return "Hello World!"

if __name__ == "__main__":
    app.run()

I go to the 127.0.0.1:5000/hello?x=2 in my browser and as a result I get:

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

What am I doing wrong?

Body:
http://localhost:5000/api/iterators/opel/next?n=5

For something like the case before

from flask import Flask, request
n = request.args.get("n")

Can do the trick


问:
How to assign an integer value to an ArrayList of String elements?
I have an ArrayList of string elements that the user enters in the MainActivity of my application (Android Studio). It is called ArrayList<String> serviceNames. The service names can be anything like Facebook, Fitness App, Clock App etc. I want to assign an Integer value to each of these user inputs of services as I am working on a fitness function to do with Swarm Particle algorithm.

```<code>public class CustomServiceSelection implements Goodness {

    public static final int numOfServices = MainActivity.servicenames.size();
    public static final int NUM_DIMENSIONS = 2 + numOfServices;
    public static final int DATA = 0;
    public static final int WLAN = 1; //get the names of the services from the arraylist
    //then convert them into an integer for the bits/no_dimensions

    boolean alwaysOn = MainActivity.costUTILITY.contains(100.0);

    ArrayList<String> serviceNames = MainActivity.servicenames;
    ArrayList<Double> costData = MainActivity.costDATA;
    ArrayList<Double> costWlan = MainActivity.costWLAN;
    ArrayList<Double> costUtilities = MainActivity.costUTILITY;
    private double batteryCost;
    //ArrayList<Double> battery = MainActivity.costBattery;

    public CustomServiceSelection(double batteryCost, ArrayList<Double> costData, ArrayList<Double> costWlan,
                                  ArrayList<Double> costUtilities) {
        if (costUtilities == null || costUtilities.size() < 1 || costData.size() < 1 || costWlan.size() < 1) {
            throw new RuntimeException("Please add atleast 1 cost to Data, WLAN and Utility");
        }
        this.batteryCost = batteryCost; //make sure you add battery field to UI, user enters battery level
        this.costData = costData;
        this.costWlan = costWlan;
        this.costUtilities = costUtilities;
        //this.services = services;
    }

    public double getGoodness(boolean[] bits) {
        double utility = 0.0;
        double rcost = 0.0;
        ArrayList<Double> resourceCost = new ArrayList<Double>();

        for(Double i : costData){

        }

        for (int x = 0; x <= NUM_DIMENSIONS; x++) { //for each resource that is a bit
            if (bits[x] == alwaysOn) {  //if a utility cost of a service is 100, return -2000.0
                return -2000;
            }

            if (bits[DATA] && bits[WLAN]) {
                return -500;
            }
            if (!bits[DATA] || bits[WLAN]) {
                return -450; //particle goodness always returns this??
            }
            if (bits[DATA]) {
                resourceCost = costData;
            } else if (bits[WLAN]) {
                resourceCost = costWlan;
            }

            for (int i = 0; i <= NUM_DIMENSIONS; i++) { //for each service the user enters
                if (bits[i]) {
                    utility += costUtilities.get(i);
                    rcost += resourceCost.get(i);
                }
            }
            if (rcost < batteryCost) {
                return utility;
            }

        }
        return utility * 0.50;
    }
    }
</code>```

I want the num_dimensions to be 2 (WLAN and DATA) plus the number of services the user enters in the main activity. So if they enter 4 services, then 6 dimensions altogether.Then I want to assign an 'int' value to these services like this...

```<code>   public static final int Facebook = 2;
   public static final int Twitter = 3;
   public static final int ClockApp = 4;
</code>```

When that is done, I want to pass it onto the getGoodness() function which will take these values as bits in the number of dimensions, so Facebook will be the 3rd bit in the dimensions. Any help or advice would be great, I m a uni student undertaking this as a project.

EDIT: I have now implemented a hashmap in the getGoodness() function. My code now looks like this...

```<code>    public double getGoodness(boolean[] bits) {
    double utility = 0.0;
    double rcost = 0.0;
    ArrayList<Double> resourceCost = new ArrayList<Double>();

    for(int i = 2; i <= NUM_DIMENSIONS; i++) { //hashmap that stores the   service names with an int value
        for(int k = 0; k <= numOfServices; k++) {
            serviceMap.put(i, serviceNames.get(k));
        }
</code>```

I need the first 2 bits of NUM_DIMENSIONS to be WLAN and DATA. So for each service the user enters, the integer value assigned to them goes up by 1 starting at 2. So... (2, Facebook), (3, Twitter), (4, Uber) etc. Now my next problem is, passing these down to the getGoodness() function, I have an arraylist from the main UI activity that takes a utility(priority) cost from 0-100 of each service. This is called costUtilities, I want the bits that contain a utility of 80.0-100.0 (double) to return me a value of -2000 if it isn't on. If you can help with this, that would be great, if not, thank you for the help you've given so far, and wish me luck in my final year individual project on PSO :)

答:
As i told in my comment you can use java.util.hashmap for this.

```<code>HashMap<int,String> serviceMap = new HashMap<int,String>
//for adding values to a hashmap
serviceMap.put(3,"facebook");
</code>```

or if you have taken services as an arraylist serviceNames then you can put it afterwards:

```<code>HashMap<int,String> serviceMap = new HashMap<int,String>
for(String serviceName : serviceNames) {
    // you need to replace serviceIntValue with the actual int value of the service
    serviceMap.put(serviceIntValue,serviceName);
}
</code>```

Body:
I have an ArrayList of string elements that the user enters in the MainActivity of my application (Android Studio). It is called ArrayList<String> serviceNames. The service names can be anything like Facebook, Fitness App, Clock App etc. I want to assign an Integer value to each of these user inputs of services as I am working on a fitness function to do with Swarm Particle algorithm.

public class CustomServiceSelection implements Goodness {

    public static final int numOfServices = MainActivity.servicenames.size();
    public static final int NUM_DIMENSIONS = 2 + numOfServices;
    public static final int DATA = 0;
    public static final int WLAN = 1; //get the names of the services from the arraylist
    //then convert them into an integer for the bits/no_dimensions

    boolean alwaysOn = MainActivity.costUTILITY.contains(100.0);

    ArrayList<String> serviceNames = MainActivity.servicenames;
    ArrayList<Double> costData = MainActivity.costDATA;
    ArrayList<Double> costWlan = MainActivity.costWLAN;
    ArrayList<Double> costUtilities = MainActivity.costUTILITY;
    private double batteryCost;
    //ArrayList<Double> battery = MainActivity.costBattery;

    public CustomServiceSelection(double batteryCost, ArrayList<Double> costData, ArrayList<Double> costWlan,
                                  ArrayList<Double> costUtilities) {
        if (costUtilities == null || costUtilities.size() < 1 || costData.size() < 1 || costWlan.size() < 1) {
            throw new RuntimeException("Please add atleast 1 cost to Data, WLAN and Utility");
        }
        this.batteryCost = batteryCost; //make sure you add battery field to UI, user enters battery level
        this.costData = costData;
        this.costWlan = costWlan;
        this.costUtilities = costUtilities;
        //this.services = services;
    }

    public double getGoodness(boolean[] bits) {
        double utility = 0.0;
        double rcost = 0.0;
        ArrayList<Double> resourceCost = new ArrayList<Double>();

        for(Double i : costData){

        }

        for (int x = 0; x <= NUM_DIMENSIONS; x++) { //for each resource that is a bit
            if (bits[x] == alwaysOn) {  //if a utility cost of a service is 100, return -2000.0
                return -2000;
            }

            if (bits[DATA] && bits[WLAN]) {
                return -500;
            }
            if (!bits[DATA] || bits[WLAN]) {
                return -450; //particle goodness always returns this??
            }
            if (bits[DATA]) {
                resourceCost = costData;
            } else if (bits[WLAN]) {
                resourceCost = costWlan;
            }

            for (int i = 0; i <= NUM_DIMENSIONS; i++) { //for each service the user enters
                if (bits[i]) {
                    utility += costUtilities.get(i);
                    rcost += resourceCost.get(i);
                }
            }
            if (rcost < batteryCost) {
                return utility;
            }

        }
        return utility * 0.50;
    }
    }

I want the num_dimensions to be 2 (WLAN and DATA) plus the number of services the user enters in the main activity. So if they enter 4 services, then 6 dimensions altogether.Then I want to assign an 'int' value to these services like this...

   public static final int Facebook = 2;
   public static final int Twitter = 3;
   public static final int ClockApp = 4;

When that is done, I want to pass it onto the getGoodness() function which will take these values as bits in the number of dimensions, so Facebook will be the 3rd bit in the dimensions. Any help or advice would be great, I m a uni student undertaking this as a project.

EDIT: I have now implemented a hashmap in the getGoodness() function. My code now looks like this...

    public double getGoodness(boolean[] bits) {
    double utility = 0.0;
    double rcost = 0.0;
    ArrayList<Double> resourceCost = new ArrayList<Double>();

    for(int i = 2; i <= NUM_DIMENSIONS; i++) { //hashmap that stores the   service names with an int value
        for(int k = 0; k <= numOfServices; k++) {
            serviceMap.put(i, serviceNames.get(k));
        }

I need the first 2 bits of NUM_DIMENSIONS to be WLAN and DATA. So for each service the user enters, the integer value assigned to them goes up by 1 starting at 2. So... (2, Facebook), (3, Twitter), (4, Uber) etc. Now my next problem is, passing these down to the getGoodness() function, I have an arraylist from the main UI activity that takes a utility(priority) cost from 0-100 of each service. This is called costUtilities, I want the bits that contain a utility of 80.0-100.0 (double) to return me a value of -2000 if it isn't on. If you can help with this, that would be great, if not, thank you for the help you've given so far, and wish me luck in my final year individual project on PSO :)

Body:
As i told in my comment you can use java.util.hashmap for this.

HashMap<int,String> serviceMap = new HashMap<int,String>
//for adding values to a hashmap
serviceMap.put(3,"facebook");

or if you have taken services as an arraylist serviceNames then you can put it afterwards:

HashMap<int,String> serviceMap = new HashMap<int,String>
for(String serviceName : serviceNames) {
    // you need to replace serviceIntValue with the actual int value of the service
    serviceMap.put(serviceIntValue,serviceName);
}


问:
Cannot put a google maps GMSMapView in a subview of main main view?
I'm struggling with this problem!
I want to add a google maps GMSMapView into a UIView that is only a portion of the main UIView of my ViewController.

It should be simple... I created with the storyboard a UIView of the size I want and put it in the main UIView.

Snippet from Interface file:

```<code>@interface MapViewController : UIViewController <CLLocationManagerDelegate>

@property(nonatomic) IBOutlet GMSMapView *mapView;
</code>```

With the mapView linked with this UIView inside the main UIView.

What I do in the implementation:

```<code>@synthesize mapView = _mapView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.8683
                                                            longitude:151.2086
                                                                 zoom:10];
    _mapView = [GMSMapView mapWithFrame:_mapView.bounds camera:camera];
    _mapView.myLocationEnabled = YES;

}
</code>```

This should work, shouldn't it?
What I get is that my internal UIView is empty.

If I instantiate a map following google's starting guide Google Map Integration Document, it works but it assigns the map to the MAIN UIView and thats a different thing.

I tried even changing the class of my mapView in the storyboard from UIView to GMSMapView.
The map is showed in the inner view but it is initialized in a strange way making

The system throwing an error saying

"Failed to make complete frame buffer"

and slowing down a lot the loading of the view (it takes 2-3 seconds on the simulator)

The map not responding in any camera change done in the viewDidLoad method.

Any suggestions?

I read some posts here on StackOverflow but couldn't find a valid solution :(

答:
```<code>(void)viewDidLoad {
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
                                                        longitude:151.20
                                                             zoom:14];

    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
    marker.title = @"Sydney";
    marker.snippet = @"Australia";
    marker.map = self.mapContainerView;

    //set the camera for the map
    self.mapContainerView.camera = camera;

    self.mapContainerView.myLocationEnabled = YES;
}
</code>```

Body:
I'm struggling with this problem!
I want to add a google maps GMSMapView into a UIView that is only a portion of the main UIView of my ViewController.

It should be simple... I created with the storyboard a UIView of the size I want and put it in the main UIView.

Snippet from Interface file:

@interface MapViewController : UIViewController <CLLocationManagerDelegate>

@property(nonatomic) IBOutlet GMSMapView *mapView;

With the mapView linked with this UIView inside the main UIView.

What I do in the implementation:

@synthesize mapView = _mapView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.8683
                                                            longitude:151.2086
                                                                 zoom:10];
    _mapView = [GMSMapView mapWithFrame:_mapView.bounds camera:camera];
    _mapView.myLocationEnabled = YES;

}

This should work, shouldn't it?
What I get is that my internal UIView is empty.

If I instantiate a map following google's starting guide Google Map Integration Document, it works but it assigns the map to the MAIN UIView and thats a different thing.

I tried even changing the class of my mapView in the storyboard from UIView to GMSMapView.
The map is showed in the inner view but it is initialized in a strange way making

The system throwing an error saying

"Failed to make complete frame buffer"

and slowing down a lot the loading of the view (it takes 2-3 seconds on the simulator)

The map not responding in any camera change done in the viewDidLoad method.

Any suggestions?

I read some posts here on StackOverflow but couldn't find a valid solution :(


问:
Creating markers with onClickListener that opens AlertDialog dynamically
I'm trying to add markers to the map dynamically, getting the data from JSON, and that part is working, I can add multiple marker in multiple places, but when I click on the marker I want that a alert dialog opens, this alert dialog must contain some information regarding that marker, but right now the information I have is always the same, it's like if the the creation of the alert dialog is not in the same cycle that creates the marker.

See my code:

```<code>final JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++)
{
    JSONObject jsonObject = array.getJSONObject(i);
    final String Designacao = jsonObject.getString("Designacao");
    String Coord_LAT = jsonObject.getString("Coord_LAT");
    String Coord_LONG = jsonObject.getString("Coord_LONG");
    final String Morada = jsonObject.getString("Morada");

    final HashMap<String, String> oportunidades = new HashMap<>();

    oportunidades.put("Designacao", Designacao);
    oportunidades.put("Coord_LAT", Coord_LAT);
    oportunidades.put("Coord_LONG", Coord_LONG);
    oportunidades.put("Morada", Morada);

    double lat1 = Double.parseDouble(Coord_LAT);
    double lng1 = Double.parseDouble(Coord_LONG);

    mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            new AlertDialog.Builder(MapsActivity.this)
                    .setTitle(Designacao)
                    .setMessage("Endereço: " + Morada + "\n" + "Telefone: " )
                    .setPositiveButton("Ir", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            new GetDirecoes().execute();//Enviar as coordenadas
                            mBottomSheetBehavior.setPeekHeight(250);
                        }
                    })
                    .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .show();
            return false;
        }
    });
    listaOportunidades.add(oportunidades);
}
</code>```

答:
You are reassigning GoogleMap.OnMapClickListener on the GoogleMap object in every iteration of the loop. So, the listener will have the information of the last object in the JSON array. Make sure to only set OnMapClickListener one time.

A solution for this would be to add your extra data to the marker and the extract that in the listener.

```<code>Marker marker = new MarkerOptions().position(new LatLng(lat1, lng1));
marker.setTag(extraInfo)
</code>```

And then in the listener

```<code>public boolean onMarkerClick(Marker marker) {
  ExtraInfo info = (ExtraInfo)marker.getTag();
}
</code>```

Body:
I'm trying to add markers to the map dynamically, getting the data from JSON, and that part is working, I can add multiple marker in multiple places, but when I click on the marker I want that a alert dialog opens, this alert dialog must contain some information regarding that marker, but right now the information I have is always the same, it's like if the the creation of the alert dialog is not in the same cycle that creates the marker.

See my code:

final JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++)
{
    JSONObject jsonObject = array.getJSONObject(i);
    final String Designacao = jsonObject.getString("Designacao");
    String Coord_LAT = jsonObject.getString("Coord_LAT");
    String Coord_LONG = jsonObject.getString("Coord_LONG");
    final String Morada = jsonObject.getString("Morada");

    final HashMap<String, String> oportunidades = new HashMap<>();

    oportunidades.put("Designacao", Designacao);
    oportunidades.put("Coord_LAT", Coord_LAT);
    oportunidades.put("Coord_LONG", Coord_LONG);
    oportunidades.put("Morada", Morada);

    double lat1 = Double.parseDouble(Coord_LAT);
    double lng1 = Double.parseDouble(Coord_LONG);

    mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            new AlertDialog.Builder(MapsActivity.this)
                    .setTitle(Designacao)
                    .setMessage("Endereço: " + Morada + "\n" + "Telefone: " )
                    .setPositiveButton("Ir", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            new GetDirecoes().execute();//Enviar as coordenadas
                            mBottomSheetBehavior.setPeekHeight(250);
                        }
                    })
                    .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .show();
            return false;
        }
    });
    listaOportunidades.add(oportunidades);
}

Body:
You are reassigning GoogleMap.OnMapClickListener on the GoogleMap object in every iteration of the loop. So, the listener will have the information of the last object in the JSON array. Make sure to only set OnMapClickListener one time.

A solution for this would be to add your extra data to the marker and the extract that in the listener.

Marker marker = new MarkerOptions().position(new LatLng(lat1, lng1));
marker.setTag(extraInfo)

And then in the listener

public boolean onMarkerClick(Marker marker) {
  ExtraInfo info = (ExtraInfo)marker.getTag();
}


问:
C# - Custom TabControl Class Memory Leak onHover
```<code>#region CustomTabControl - Leak

public class cTabControl : TabControl
{

    #region Remove Padding
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x1300 + 40)
        {
            lparamrect rc = (lparamrect)m.GetLParam(typeof(lparamrect));
            rc.Left -= 4;
            rc.Right += 4;
            rc.Top -= 2;
            rc.Bottom += 4;
            Marshal.StructureToPtr(rc, m.LParam, true);
        }
        base.WndProc(ref m);
    }
    internal struct lparamrect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
    #endregion

    //Variables;
    private Rectangle Rect;
    private int _OverIndex = -1;
    private int OverIndex
    {
        get { return _OverIndex; }
        set
        {
            _OverIndex = value;
            Invalidate();
        }
    }

    //Default Settings;
    public cTabControl()
    {
        DoubleBuffered = true;
        Alignment = TabAlignment.Left;
        SizeMode = TabSizeMode.Fixed;
        ItemSize = new Size(30, 32);
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);
    }

    protected override void OnControlAdded(ControlEventArgs e)
    {
        base.OnControlAdded(e);
        e.Control.BackColor = Settings.Default.TabBackgroundColor;
        e.Control.ForeColor = ColorFromHex("#FFFFFF");
        e.Control.Font = new Font("Kozuka Gothic Pro B", 9);
    }

    protected override void OnPaint(PaintEventArgs e)
    {

        //Set the Graphics Variable;
        Graphics G = e.Graphics;

        //Raise the Paint event;
        base.OnPaint(e);

        //Dynamically Darken the Parent's Color slightly;
        Color DarkParentColor = default(Color);
        if (ColorContrast(Parent.BackColor) == Color.White)
        {
            DarkParentColor = ControlPaint.Light(ControlPaint.Dark(Parent.BackColor, (float)0.01), (float)1.2);
        }
        else
        {
            DarkParentColor = ControlPaint.Light(ControlPaint.Dark(Parent.BackColor, (float)0.1), (float)0.35);
        }

        //Set the Tab's Background Color to the Darkened Parent's Color;
        G.Clear(DarkParentColor);

        //For Each Tab;
        for (int i = 0; i <= TabPages.Count - 1; i++)
        {

            if ((string)TabPages[i].Tag != "Hidden")
            {

                // Get the Tab's Rectangle Sizing
                Rect = GetTabRect(i);
                float x = Convert.ToSingle((Rect.X + (Rect.Height - 10)) - (Rect.Height / 2));
                float y = Convert.ToSingle((Rect.Y + (Rect.Height - 10)) - (Rect.Height / 2));

                // If the user is hovering over the tab
                if (!(OverIndex == -1))
                {
                    using (SolidBrush sb = new SolidBrush(Color.FromArgb(9, Color.Black)))
                    {
                        //Draw the Hover Background;
                        G.FillRectangle(sb, new Rectangle(GetTabRect(OverIndex).X, GetTabRect(OverIndex).Y, GetTabRect(OverIndex).Width, GetTabRect(OverIndex).Height));
                    }
                }
                else
                {
                    using (SolidBrush sb = new SolidBrush(DarkParentColor))
                    {
                        // Set the Background Color to the Darkened Parent's Color
                        G.FillRectangle(sb, new Rectangle(Rect.X, Rect.Y, Rect.Width + 6, Rect.Height));
                    }
                }

                // If its the selected tab
                if (SelectedIndex == i)
                {
                    using (SolidBrush sb = new SolidBrush(Settings.Default.HighlightColor), sb2 = new SolidBrush(Color.FromArgb(30, Color.Black)))
                    {
                        // Set the Selected Indicator to the Highlight Color
                        G.FillRectangle(sb, new Rectangle(Rect.X, Rect.Y, 2, Rect.Height));
                        //Draw the Hover Background;
                        G.FillRectangle(sb2, new Rectangle(Rect.X, Rect.Y, Rect.Width, Rect.Height));
                    }
                }

                //Set Render Quality;
                G.TextRenderingHint = TextRenderingHint.AntiAlias;

                if ((!ReferenceEquals(Tag, "TextOnly")))
                {
                    if (!(SelectedIndex == i))
                    {
                        using (Graphics gfx = Graphics.FromImage(new Bitmap(GetTabIcon(i).Width, GetTabIcon(i).Height)))
                        {
                            ColorMatrix matrix = new ColorMatrix();
                            matrix.Matrix33 = (float)0.5;
                            ImageAttributes attributes = new ImageAttributes();
                            attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            G.DrawImage(GetTabIcon(i), new Rectangle(Convert.ToInt32(x), Convert.ToInt32(y), 20, 20), 0, 0, GetTabIcon(i).Width, GetTabIcon(i).Height, GraphicsUnit.Pixel, attributes);
                        }
                    }
                    else if (SelectedIndex == i)
                    {
                        using (Image ti = GetTabIcon(i))
                        {
                            G.DrawImage(ti, new Rectangle(Convert.ToInt32(x) + 1, Convert.ToInt32(y), 20, 20));
                        }
                    }
                }
                else
                {
                    dynamic TabProperties = TabPages[i];
                    StringFormat sf = new StringFormat();
                    sf.LineAlignment = StringAlignment.Center;
                    using (Font f = new Font(LoadFont(Resources.Roboto_Medium), 10f))
                    using (SolidBrush sb = new SolidBrush(TabProperties.ForeColor))
                    {
                        G.DrawString(TabProperties.Text, f, sb, x + 2, Convert.ToSingle(Rect.Y + (Rect.Height / 2)), sf);
                    }
                }

            }

        }

    }

    protected override void OnSelecting(TabControlCancelEventArgs e)
    {
        base.OnSelecting(e);

        if ((e.TabPage != null))
        {
            if (!string.IsNullOrEmpty(Convert.ToString(e.TabPage.Tag)))
            {
                e.Cancel = true;
            }
            else
            {
                OverIndex = -1;
            }
        }

    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);

        for (int I = 0; I <= TabPages.Count - 1; I++)
        {
            if (GetTabRect(I).Contains(e.Location) & string.IsNullOrEmpty(Convert.ToString(TabPages[I].Tag)))
            {
                OverIndex = I;
                break; // TODO: might not be correct. Was : Exit For
            }
            else
            {
                OverIndex = -1;
            }
        }

    }

    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        OverIndex = -1;
    }

}

#endregion
</code>```

I have this custom tab control class that is more modern and is left aligned rather than top aligned. It works, but there's a huge memory leak issue with it. I'm using MouseMove to be able to get the mouse location and then cross match it with the tabs, but even if I leave my mouse still or move in more to the middle of the tab for example, it will obviously execute millions of times, this then causes huge spikes in memory usage.

Is there any way around this?

Process Memory Diagnostic

答: cache the mouse-coordinates after the for-loop in your OnMouseMove. then, before the for-loop, check the cached coodinates against the current coordinates. if their difference is lower then a treshold of your choice, exit the function. using this approach will execute your logic only on major changes to the mouse-position.</p>

Body:
#region CustomTabControl - Leak

public class cTabControl : TabControl
{

    #region Remove Padding
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x1300 + 40)
        {
            lparamrect rc = (lparamrect)m.GetLParam(typeof(lparamrect));
            rc.Left -= 4;
            rc.Right += 4;
            rc.Top -= 2;
            rc.Bottom += 4;
            Marshal.StructureToPtr(rc, m.LParam, true);
        }
        base.WndProc(ref m);
    }
    internal struct lparamrect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
    #endregion

    //Variables;
    private Rectangle Rect;
    private int _OverIndex = -1;
    private int OverIndex
    {
        get { return _OverIndex; }
        set
        {
            _OverIndex = value;
            Invalidate();
        }
    }

    //Default Settings;
    public cTabControl()
    {
        DoubleBuffered = true;
        Alignment = TabAlignment.Left;
        SizeMode = TabSizeMode.Fixed;
        ItemSize = new Size(30, 32);
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);
    }

    protected override void OnControlAdded(ControlEventArgs e)
    {
        base.OnControlAdded(e);
        e.Control.BackColor = Settings.Default.TabBackgroundColor;
        e.Control.ForeColor = ColorFromHex("#FFFFFF");
        e.Control.Font = new Font("Kozuka Gothic Pro B", 9);
    }

    protected override void OnPaint(PaintEventArgs e)
    {

        //Set the Graphics Variable;
        Graphics G = e.Graphics;

        //Raise the Paint event;
        base.OnPaint(e);

        //Dynamically Darken the Parent's Color slightly;
        Color DarkParentColor = default(Color);
        if (ColorContrast(Parent.BackColor) == Color.White)
        {
            DarkParentColor = ControlPaint.Light(ControlPaint.Dark(Parent.BackColor, (float)0.01), (float)1.2);
        }
        else
        {
            DarkParentColor = ControlPaint.Light(ControlPaint.Dark(Parent.BackColor, (float)0.1), (float)0.35);
        }

        //Set the Tab's Background Color to the Darkened Parent's Color;
        G.Clear(DarkParentColor);

        //For Each Tab;
        for (int i = 0; i <= TabPages.Count - 1; i++)
        {

            if ((string)TabPages[i].Tag != "Hidden")
            {

                // Get the Tab's Rectangle Sizing
                Rect = GetTabRect(i);
                float x = Convert.ToSingle((Rect.X + (Rect.Height - 10)) - (Rect.Height / 2));
                float y = Convert.ToSingle((Rect.Y + (Rect.Height - 10)) - (Rect.Height / 2));

                // If the user is hovering over the tab
                if (!(OverIndex == -1))
                {
                    using (SolidBrush sb = new SolidBrush(Color.FromArgb(9, Color.Black)))
                    {
                        //Draw the Hover Background;
                        G.FillRectangle(sb, new Rectangle(GetTabRect(OverIndex).X, GetTabRect(OverIndex).Y, GetTabRect(OverIndex).Width, GetTabRect(OverIndex).Height));
                    }
                }
                else
                {
                    using (SolidBrush sb = new SolidBrush(DarkParentColor))
                    {
                        // Set the Background Color to the Darkened Parent's Color
                        G.FillRectangle(sb, new Rectangle(Rect.X, Rect.Y, Rect.Width + 6, Rect.Height));
                    }
                }

                // If its the selected tab
                if (SelectedIndex == i)
                {
                    using (SolidBrush sb = new SolidBrush(Settings.Default.HighlightColor), sb2 = new SolidBrush(Color.FromArgb(30, Color.Black)))
                    {
                        // Set the Selected Indicator to the Highlight Color
                        G.FillRectangle(sb, new Rectangle(Rect.X, Rect.Y, 2, Rect.Height));
                        //Draw the Hover Background;
                        G.FillRectangle(sb2, new Rectangle(Rect.X, Rect.Y, Rect.Width, Rect.Height));
                    }
                }

                //Set Render Quality;
                G.TextRenderingHint = TextRenderingHint.AntiAlias;

                if ((!ReferenceEquals(Tag, "TextOnly")))
                {
                    if (!(SelectedIndex == i))
                    {
                        using (Graphics gfx = Graphics.FromImage(new Bitmap(GetTabIcon(i).Width, GetTabIcon(i).Height)))
                        {
                            ColorMatrix matrix = new ColorMatrix();
                            matrix.Matrix33 = (float)0.5;
                            ImageAttributes attributes = new ImageAttributes();
                            attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            G.DrawImage(GetTabIcon(i), new Rectangle(Convert.ToInt32(x), Convert.ToInt32(y), 20, 20), 0, 0, GetTabIcon(i).Width, GetTabIcon(i).Height, GraphicsUnit.Pixel, attributes);
                        }
                    }
                    else if (SelectedIndex == i)
                    {
                        using (Image ti = GetTabIcon(i))
                        {
                            G.DrawImage(ti, new Rectangle(Convert.ToInt32(x) + 1, Convert.ToInt32(y), 20, 20));
                        }
                    }
                }
                else
                {
                    dynamic TabProperties = TabPages[i];
                    StringFormat sf = new StringFormat();
                    sf.LineAlignment = StringAlignment.Center;
                    using (Font f = new Font(LoadFont(Resources.Roboto_Medium), 10f))
                    using (SolidBrush sb = new SolidBrush(TabProperties.ForeColor))
                    {
                        G.DrawString(TabProperties.Text, f, sb, x + 2, Convert.ToSingle(Rect.Y + (Rect.Height / 2)), sf);
                    }
                }

            }

        }

    }

    protected override void OnSelecting(TabControlCancelEventArgs e)
    {
        base.OnSelecting(e);

        if ((e.TabPage != null))
        {
            if (!string.IsNullOrEmpty(Convert.ToString(e.TabPage.Tag)))
            {
                e.Cancel = true;
            }
            else
            {
                OverIndex = -1;
            }
        }

    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);

        for (int I = 0; I <= TabPages.Count - 1; I++)
        {
            if (GetTabRect(I).Contains(e.Location) & string.IsNullOrEmpty(Convert.ToString(TabPages[I].Tag)))
            {
                OverIndex = I;
                break; // TODO: might not be correct. Was : Exit For
            }
            else
            {
                OverIndex = -1;
            }
        }

    }

    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        OverIndex = -1;
    }

}

#endregion

I have this custom tab control class that is more modern and is left aligned rather than top aligned. It works, but there's a huge memory leak issue with it. I'm using MouseMove to be able to get the mouse location and then cross match it with the tabs, but even if I leave my mouse still or move in more to the middle of the tab for example, it will obviously execute millions of times, this then causes huge spikes in memory usage.

Is there any way around this?

Process Memory Diagnostic


问:
Dynamodb: Querying tables with secondary index
I am using the gem aws-sdk-ruby to query a table which looks something like this:

```<code>hk (Hashkey)  |  guid(Rangekey)  |  Timestamp (Secondary Range index)  |  other attributes
aaaa          |  50              |  2013-02-04T12:33:00Z               |
aaaa          |  244             |  2013-04-22T04:54:00Z               |
aaaa          |  342             |  2013-05-18T06:52:00Z               |
bbbb          |  243             |  2013-06-21T13:17:00Z               |
</code>```

What I am trying to do is get all 'aaaa' rows that were created after a certain date.
Ex:

```<code>AWS.config(access_key_id: 'xxx', secret_access_key: 'xxx', :dynamo_db => { :api_version => '2012-08-10' })
client = AWS::DynamoDB::Client.new
client.query(
{
  table_name: 'table',
  select: 'ALL_ATTRIBUTES',
  key_conditions: {
    'hk' => {
      comparison_operator: 'EQ',
      attribute_value_list: [
        {'s' => 'aaaa'}
      ]
    },
    'timestamp' => {
      comparison_operator: 'GE',
      attribute_value_list: [
        {'s' => Time.now.utc.iso8601}
      ]
    }
  }
})
</code>```

When i run the code above i get this:

```<code>Query condition missed key schema element guid (AWS::DynamoDB::Errors::ValidationException)
</code>```

Running the query with hashKey and RangeKey works but when i replace the rangeKey with a secondary range index it fails telling me that the rangeKey is required.

If i then add the range key (Which makes no sense) i get the following error instead:

```<code>Conditions can be of length 1 or 2 only (AWS::DynamoDB::Errors::ValidationException)
</code>```

Anyone know what might be happening?

答:
You can use "scan" instead "query"
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property

I can emphatize that scan in slower than query, scan is not recomended for huge amount data retrieve.

I did this with the next schema

DB Schema
Where
Primary partition key id (String)

```<code>  //JavaScript EXAMPLE-1
var params = {
        TableName : 'users',
        FilterExpression : 'isActive = :isActive',
        ExpressionAttributeValues : {':isActive' : true}
    };

        dynamoDBClient.scan(params, function(err, data){
            if(err){
                return console.error(err);
            }
            console.log(data.Items);

        });
</code>```

I hope help you.

Regards.

Body:
I am using the gem aws-sdk-ruby to query a table which looks something like this:

hk (Hashkey)  |  guid(Rangekey)  |  Timestamp (Secondary Range index)  |  other attributes
aaaa          |  50              |  2013-02-04T12:33:00Z               |
aaaa          |  244             |  2013-04-22T04:54:00Z               |
aaaa          |  342             |  2013-05-18T06:52:00Z               |
bbbb          |  243             |  2013-06-21T13:17:00Z               |

What I am trying to do is get all 'aaaa' rows that were created after a certain date.
Ex:

AWS.config(access_key_id: 'xxx', secret_access_key: 'xxx', :dynamo_db => { :api_version => '2012-08-10' })
client = AWS::DynamoDB::Client.new
client.query(
{
  table_name: 'table',
  select: 'ALL_ATTRIBUTES',
  key_conditions: {
    'hk' => {
      comparison_operator: 'EQ',
      attribute_value_list: [
        {'s' => 'aaaa'}
      ]
    },
    'timestamp' => {
      comparison_operator: 'GE',
      attribute_value_list: [
        {'s' => Time.now.utc.iso8601}
      ]
    }
  }
})

When i run the code above i get this:

Query condition missed key schema element guid (AWS::DynamoDB::Errors::ValidationException)

Running the query with hashKey and RangeKey works but when i replace the rangeKey with a secondary range index it fails telling me that the rangeKey is required.

If i then add the range key (Which makes no sense) i get the following error instead:

Conditions can be of length 1 or 2 only (AWS::DynamoDB::Errors::ValidationException)

Anyone know what might be happening?

Body:
You can use "scan" instead "query"
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property

I can emphatize that scan in slower than query, scan is not recomended for huge amount data retrieve.

I did this with the next schema

DB Schema
Where
Primary partition key id (String)

  //JavaScript EXAMPLE-1
var params = {
        TableName : 'users',
        FilterExpression : 'isActive = :isActive',
        ExpressionAttributeValues : {':isActive' : true}
    };

        dynamoDBClient.scan(params, function(err, data){
            if(err){
                return console.error(err);
            }
            console.log(data.Items);

        });

I hope help you.

Regards.


问:
C - Genetic Algorithm for N Queens
I'm trying to figure our how to use the Genetic Algorithm to solve N queens.

Here is the program:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 8
#define POP 8

int answers[SIZE] = {5,3,1,7,4,6,0,2};

int getRand(int mod){
    if (mod==0) return 0;
    else return random()%mod;
}

void printArray(int array[]){
    int i;
    for(i=0; i<SIZE-1; i++) printf("(%i,%i),",i,array[i]);
    printf("(%i,%i)",SIZE-1,array[SIZE-1]);
    printf("\n");
}

int getWeight(int array[]){
    int weight = 28;
    int queen;
    for(queen=0;queen<SIZE;queen++){    //for each queen
        int nextqueen;
        for(nextqueen=queen+1;nextqueen<SIZE;nextqueen++){        //for each of the other queens (nextqueen = queen to avoid counting pairs twice)
            if(array[queen] == array[nextqueen] || abs(queen-nextqueen)==abs(array[queen]-array[nextqueen])){   //if conflict
                weight--;
            }
        }
    }
    return weight;
}

void geneticAlgorithm(){
    int population[POP][SIZE];
    int children[POP][SIZE];
    int weightProb[224] = {};
    int wpl = 0; //weightProb[] length
    float mutProb = 0.2; //higher prob yields faster times. works decently anyways. bug: prob = 0
    int done = 0;
    int i;
    for(i=0;i<POP;i++) for(int j=0;j<SIZE;j++) population[i][j] = getRand(SIZE);
    while(done == 0){
        for(i=0;i<POP;i++){
            if(getWeight(children[i]) == 28){
                printf("solution: ");
                printArray(children[i]);
                done = 1;
            }
        }

        for(i=0;i<wpl;i++) weightProb[i] = (int)NULL; //clear weightprob
        wpl=0;

        //weighted probability distribution
        for(i=0;i<POP;i++){
            int w = getWeight(population[i]);
            for(int j=0;j<w;j++){
                weightProb[wpl] = i; //fill array with member number w times
                wpl++;
            }
        }

        //reproduce
        for(i=0;i<POP;i+=2){
            int par1 = weightProb[getRand(wpl)];
            int par2 = weightProb[getRand(wpl)];
            int split = getRand(SIZE);
            //crossover
            for(int j=0;j<split;j++){
                children[i][j] = population[par1][j];
                children[i+1][j] = population[par2][j];
            }
            for(int j=split;j<SIZE;j++){
                children[i][j] = population[par2][j];
                children[i+1][j] = population[par1][j];
            }
            //mutation
            if(getRand(1000000)<=mutProb*1000000){
                int child=getRand(2);
                if(child == 0) children[i][getRand(SIZE)] = getRand(SIZE);
                else children[i+1][getRand(SIZE)] = getRand(SIZE);
            }
        }
        for(i=0;i<POP;i++) for(int j=0;j<SIZE;j++) population[i][j] = children[i][j];
        wpl = 0;
    }
}

int main(int argc, const char * argv[]){
    srandom((unsigned int)time(NULL));  //seed random
    geneticAlgorithm();
    return 0;
}
</code>```

The program runs and compiles properly but doesn't produce the results I'm after. I'm wanting to display the x,y co-ordinates of each queen and simply print them out on output. However instead I'm getting random garbage on output and I cant figure out why.

Current output example:

```<code>(0,0) (1,3248234234) (2,0) (3,-3248236736) (4,57435727) (5,234743567) (6, 23498348) (7,23487234)
</code>```

Desired output example (a solution to the N queen problem):

```<code>(3,4) (7,2) (0,3) (4,6) (6,5) (1,7) (5,1) (2,0)
</code>```

答:
Not sure if this is the cause of your specific issue, but it is a problem:

```<code>for(i=0;i<POP;i++) for(int j=0;j<SIZE;j++) population[i][j] = getRand(SIZE);
while(done == 0){
    for(i=0;i<POP;i++){
        if(getWeight(children[i]) == 28){
            printf("solution: ");
            printArray(children[i]);
            done = 1;
        }
    }
</code>```

The above is the initialisation of the population and the beginning of the loop. On the first time through, the children array contains uninitialised data.

Given the rest of the algorithm, you need to be checking the weight of the elements of population (and printing an element from population) if it is a winner, not children.

Title: C - Genetic Algorithm for N Queens

Body:
I'm trying to figure our how to use the Genetic Algorithm to solve N queens.

Here is the program:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 8
#define POP 8

int answers[SIZE] = {5,3,1,7,4,6,0,2};

int getRand(int mod){
    if (mod==0) return 0;
    else return random()%mod;
}

void printArray(int array[]){
    int i;
    for(i=0; i<SIZE-1; i++) printf("(%i,%i),",i,array[i]);
    printf("(%i,%i)",SIZE-1,array[SIZE-1]);
    printf("\n");
}

int getWeight(int array[]){
    int weight = 28;
    int queen;
    for(queen=0;queen<SIZE;queen++){    //for each queen
        int nextqueen;
        for(nextqueen=queen+1;nextqueen<SIZE;nextqueen++){        //for each of the other queens (nextqueen = queen to avoid counting pairs twice)
            if(array[queen] == array[nextqueen] || abs(queen-nextqueen)==abs(array[queen]-array[nextqueen])){   //if conflict
                weight--;
            }
        }
    }
    return weight;
}

void geneticAlgorithm(){
    int population[POP][SIZE];
    int children[POP][SIZE];
    int weightProb[224] = {};
    int wpl = 0; //weightProb[] length
    float mutProb = 0.2; //higher prob yields faster times. works decently anyways. bug: prob = 0
    int done = 0;
    int i;
    for(i=0;i<POP;i++) for(int j=0;j<SIZE;j++) population[i][j] = getRand(SIZE);
    while(done == 0){
        for(i=0;i<POP;i++){
            if(getWeight(children[i]) == 28){
                printf("solution: ");
                printArray(children[i]);
                done = 1;
            }
        }

        for(i=0;i<wpl;i++) weightProb[i] = (int)NULL; //clear weightprob
        wpl=0;

        //weighted probability distribution
        for(i=0;i<POP;i++){
            int w = getWeight(population[i]);
            for(int j=0;j<w;j++){
                weightProb[wpl] = i; //fill array with member number w times
                wpl++;
            }
        }

        //reproduce
        for(i=0;i<POP;i+=2){
            int par1 = weightProb[getRand(wpl)];
            int par2 = weightProb[getRand(wpl)];
            int split = getRand(SIZE);
            //crossover
            for(int j=0;j<split;j++){
                children[i][j] = population[par1][j];
                children[i+1][j] = population[par2][j];
            }
            for(int j=split;j<SIZE;j++){
                children[i][j] = population[par2][j];
                children[i+1][j] = population[par1][j];
            }
            //mutation
            if(getRand(1000000)<=mutProb*1000000){
                int child=getRand(2);
                if(child == 0) children[i][getRand(SIZE)] = getRand(SIZE);
                else children[i+1][getRand(SIZE)] = getRand(SIZE);
            }
        }
        for(i=0;i<POP;i++) for(int j=0;j<SIZE;j++) population[i][j] = children[i][j];
        wpl = 0;
    }
}

int main(int argc, const char * argv[]){
    srandom((unsigned int)time(NULL));  //seed random
    geneticAlgorithm();
    return 0;
}

The program runs and compiles properly but doesn't produce the results I'm after. I'm wanting to display the x,y co-ordinates of each queen and simply print them out on output. However instead I'm getting random garbage on output and I cant figure out why.

Current output example:

(0,0) (1,3248234234) (2,0) (3,-3248236736) (4,57435727) (5,234743567) (6, 23498348) (7,23487234)

Desired output example (a solution to the N queen problem):

(3,4) (7,2) (0,3) (4,6) (6,5) (1,7) (5,1) (2,0)

Body:
Not sure if this is the cause of your specific issue, but it is a problem:

for(i=0;i<POP;i++) for(int j=0;j<SIZE;j++) population[i][j] = getRand(SIZE);
while(done == 0){
    for(i=0;i<POP;i++){
        if(getWeight(children[i]) == 28){
            printf("solution: ");
            printArray(children[i]);
            done = 1;
        }
    }

The above is the initialisation of the population and the beginning of the loop. On the first time through, the children array contains uninitialised data.

Given the rest of the algorithm, you need to be checking the weight of the elements of population (and printing an element from population) if it is a winner, not children.


问:
What is the concept behind R.java?
In android R.java is used to provide access to resources defined in XML files.
To access the resource we need to invoke findViewById() method passing in the id of the resource to be fetched.

This is similar to Spring where beans are defined in a XML context and are fetched by using application context. context.getBean("beanId")

This provides loose coupling since the beans are defined externally and could be changed without making modifications to the code.

This has me confused. Though what Android does looks similar to spring, what advantage does it offer?

What is the point of having an intermediate R.java anyway? Couldn't we just acquire resources directly from XML by use of a resource
  reader/application context. e.g. findViewById("resourceId")

There isn't any loose coupling. Since references in R.java get auto-generated how could one delete a resource and put in a new one?

What design pattern does it follow(if there is one)?

Wouldn't it be better to have resources injected using IOC (like Roboguice)? Why did then google decide to give us such
  a wierd way of working with resources?

Pardon my ignorance. I'm a newbie Java developer trying too many things at once. :-)
Thanks for all the feedback.

答: It also contains access to resources - such as id, drawables, layouts, strings, arrays, and basically anything you can declare in resources.</p>

Title: What is the concept behind R.java?


问:
Element to point toward another element
I need to make four rectangles and an arrow at the center that points toward the rectange that is hovered. See https://jsfiddle.net/Lvmf67rm/1/

```<code>$(document).ready(function(){
  $('.quarter:nth-child(1)').mouseenter(function(){
    $('.pointer').css('transform','rotate(-45deg)');
  });
  $('.quarter:nth-child(2)').mouseenter(function(){
    $('.pointer').css('transform','rotate(45deg)');
  });
  $('.quarter:nth-child(3)').mouseenter(function(){
    $('.pointer').css('transform','rotate(-135deg)');
  });
  $('.quarter:nth-child(4)').mouseenter(function(){
    $('.pointer').css('transform','rotate(135deg)');
  });
});
</code>```

There are two issues with what I've made:

If there would be an element before or somewhere in-between the rectangle divs - the arrow would point in the wrong direction (this is because "nth-child()" selects the children regardless of class)

When hovering between 3rd and the 4th rectangles the arrow doesn't go straight to the next block but goes through the first and second first (quite obvious why this happens).

But how to make it right? I'm quite a noob with javascript so this is the best I could do and I ask for your guidance.

P.S. Sorry if I didn't explain it very good, english is not my native.

P.P.S. Sorry, I forgot to mention I can't edit HTML.

答:
Regarding adding elements before or somewhere in-between the rectangle divs, here are some possible solutions:

Best option: Just don't do it.  Add other elements outside the container and use CSS positioning to position.

Use :nth-of-type instead of :nth-child

Instead of :nth-child use classes q1, q2...

Regarding arrow direction: See how using -225deg in q4 changes the behaviour:

```<code>  $('.quarter:nth-child(4)').mouseenter(function(){
      console.log($('.pointer').css('transform'));  // get prev value
      $('.pointer').css('transform','rotate(-225deg)'); // instead of 135deg
  });
</code>```

You can check the previous value to change the degrees dynamically, selecting the best option of the 2 candidates (where the absolute value of previous degrees - new degrees is minimal, adding or subtracting 360 degrees).

Title: Element to point toward another element

Body:
I need to make four rectangles and an arrow at the center that points toward the rectange that is hovered. See https://jsfiddle.net/Lvmf67rm/1/

$(document).ready(function(){
  $('.quarter:nth-child(1)').mouseenter(function(){
    $('.pointer').css('transform','rotate(-45deg)');
  });
  $('.quarter:nth-child(2)').mouseenter(function(){
    $('.pointer').css('transform','rotate(45deg)');
  });
  $('.quarter:nth-child(3)').mouseenter(function(){
    $('.pointer').css('transform','rotate(-135deg)');
  });
  $('.quarter:nth-child(4)').mouseenter(function(){
    $('.pointer').css('transform','rotate(135deg)');
  });
});

There are two issues with what I've made:

If there would be an element before or somewhere in-between the rectangle divs - the arrow would point in the wrong direction (this is because "nth-child()" selects the children regardless of class)

When hovering between 3rd and the 4th rectangles the arrow doesn't go straight to the next block but goes through the first and second first (quite obvious why this happens).

But how to make it right? I'm quite a noob with javascript so this is the best I could do and I ask for your guidance.

P.S. Sorry if I didn't explain it very good, english is not my native.

P.P.S. Sorry, I forgot to mention I can't edit HTML.

Body:
Regarding adding elements before or somewhere in-between the rectangle divs, here are some possible solutions:

Best option: Just don't do it.  Add other elements outside the container and use CSS positioning to position.

Use :nth-of-type instead of :nth-child

Instead of :nth-child use classes q1, q2...

Regarding arrow direction: See how using -225deg in q4 changes the behaviour:

  $('.quarter:nth-child(4)').mouseenter(function(){
      console.log($('.pointer').css('transform'));  // get prev value
      $('.pointer').css('transform','rotate(-225deg)'); // instead of 135deg
  });

You can check the previous value to change the degrees dynamically, selecting the best option of the 2 candidates (where the absolute value of previous degrees - new degrees is minimal, adding or subtracting 360 degrees).


问:
Select either a file or folder from the same dialog in .NET
Is there an "easy" way to select either a file OR a folder from the same dialog?

In many apps I create I allow for both files or folders as input.
Until now i always end up creating a switch to toggle between file or folder selection dialogs or stick with drag-and-drop functionality only.

Since this seems such a basic thing i would imagine this has been created before, but googling does not result in much information. So it looks like i would need to start from scratch and create a custom selection Dialog, but I rather not introduce any problems by reinventing the wheel for such a trivial task.

Anybody any tips or existing solutions?

To keep the UI consistent it would be nice if it is possible to extend the OpenFileDialog (or the FolderBrowserDialog).

答:
Based on the above tips I found some working code that uses the standard Folder Browser dialog at the following location: http://topic.csdn.net/t/20020703/05/845468.html

The Class for the extended Folder Browser Dialog

```<code>Imports System
Imports System.Text
Imports System.Windows.Forms
Imports System.Runtime.InteropServices

Public Class DirectoryDialog
    Public Structure BROWSEINFO
        Public hWndOwner As IntPtr
        Public pIDLRoot As Integer
        Public pszDisplayName As String
        Public lpszTitle As String
        Public ulFlags As Integer
        Public lpfnCallback As Integer
        Public lParam As Integer
        Public iImage As Integer
    End Structure

    Const MAX_PATH As Integer = 260

    Public Enum BrowseForTypes As Integer
        Computers = 4096
        Directories = 1
        FilesAndDirectories = 16384
        FileSystemAncestors = 8
    End Enum

    Declare Function CoTaskMemFree Lib "ole32" Alias "CoTaskMemFree" (ByVal hMem As IntPtr) As Integer
    Declare Function lstrcat Lib "kernel32" Alias "lstrcat" (ByVal lpString1 As String, ByVal lpString2 As String) As IntPtr
    Declare Function SHBrowseForFolder Lib "shell32" Alias "SHBrowseForFolder" (ByRef lpbi As BROWSEINFO) As IntPtr
    Declare Function SHGetPathFromIDList Lib "shell32" Alias "SHGetPathFromIDList" (ByVal pidList As IntPtr, ByVal lpBuffer As StringBuilder) As Integer
    Protected Function RunDialog(ByVal hWndOwner As IntPtr) As Boolean

        Dim udtBI As BROWSEINFO = New BROWSEINFO()
        Dim lpIDList As IntPtr
        Dim hTitle As GCHandle = GCHandle.Alloc(Title, GCHandleType.Pinned)
        udtBI.hWndOwner = hWndOwner
        udtBI.lpszTitle = Title
        udtBI.ulFlags = BrowseFor
        Dim buffer As StringBuilder = New StringBuilder(MAX_PATH)
        buffer.Length = MAX_PATH
        udtBI.pszDisplayName = buffer.ToString()
        lpIDList = SHBrowseForFolder(udtBI)
        hTitle.Free()
        If lpIDList.ToInt64() <> 0 Then
            If BrowseFor = BrowseForTypes.Computers Then
                m_Selected = udtBI.pszDisplayName.Trim()
            Else
                Dim path As StringBuilder = New StringBuilder(MAX_PATH)
                SHGetPathFromIDList(lpIDList, path)
                m_Selected = path.ToString()
            End If
            CoTaskMemFree(lpIDList)
        Else
            Return False
        End If
        Return True
    End Function

    Public Function ShowDialog() As DialogResult
        Return ShowDialog(Nothing)
    End Function

    Public Function ShowDialog(ByVal owner As IWin32Window) As DialogResult
        Dim handle As IntPtr
        If Not owner Is Nothing Then
            handle = owner.Handle
        Else
            handle = IntPtr.Zero
        End If
        If RunDialog(handle) Then
            Return DialogResult.OK
        Else
            Return DialogResult.Cancel
        End If
    End Function

    Public Property Title() As String
        Get
            Return m_Title
        End Get
        Set(ByVal Value As String)
            If Value Is DBNull.Value Then
                Throw New ArgumentNullException()
            End If
            m_Title = Value
        End Set
    End Property

    Public ReadOnly Property Selected() As String
        Get
            Return m_Selected
        End Get
    End Property

    Public Property BrowseFor() As BrowseForTypes
        Get
            Return m_BrowseFor
        End Get
        Set(ByVal Value As BrowseForTypes)
            m_BrowseFor = Value
        End Set
    End Property

    Private m_BrowseFor As BrowseForTypes = BrowseForTypes.Directories
    Private m_Title As String = ""
    Private m_Selected As String = ""

    Public Sub New()
    End Sub
End Class
</code>```

The code to implement the extended dialog

```<code>Sub Button1Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim frmd As DirectoryDialog = New DirectoryDialog()
    ' frmd.BrowseFor = DirectoryDialog.BrowseForTypes.Directories
    ' frmd.BrowseFor = DirectoryDialog.BrowseForTypes.Computers
    frmd.BrowseFor = DirectoryDialog.BrowseForTypes.FilesAndDirectories
    frmd.Title = "Select a file or a folder"
    If frmd.ShowDialog(Me) = DialogResult.OK Then
        MsgBox(frmd.Selected)
    End If
End Sub
</code>```

OwnerDisplayName: barry

LastEditorDisplayName: barry

Body:
Based on the above tips I found some working code that uses the standard Folder Browser dialog at the following location: http://topic.csdn.net/t/20020703/05/845468.html

The Class for the extended Folder Browser Dialog

Imports System
Imports System.Text
Imports System.Windows.Forms
Imports System.Runtime.InteropServices

Public Class DirectoryDialog
    Public Structure BROWSEINFO
        Public hWndOwner As IntPtr
        Public pIDLRoot As Integer
        Public pszDisplayName As String
        Public lpszTitle As String
        Public ulFlags As Integer
        Public lpfnCallback As Integer
        Public lParam As Integer
        Public iImage As Integer
    End Structure

    Const MAX_PATH As Integer = 260

    Public Enum BrowseForTypes As Integer
        Computers = 4096
        Directories = 1
        FilesAndDirectories = 16384
        FileSystemAncestors = 8
    End Enum

    Declare Function CoTaskMemFree Lib "ole32" Alias "CoTaskMemFree" (ByVal hMem As IntPtr) As Integer
    Declare Function lstrcat Lib "kernel32" Alias "lstrcat" (ByVal lpString1 As String, ByVal lpString2 As String) As IntPtr
    Declare Function SHBrowseForFolder Lib "shell32" Alias "SHBrowseForFolder" (ByRef lpbi As BROWSEINFO) As IntPtr
    Declare Function SHGetPathFromIDList Lib "shell32" Alias "SHGetPathFromIDList" (ByVal pidList As IntPtr, ByVal lpBuffer As StringBuilder) As Integer
    Protected Function RunDialog(ByVal hWndOwner As IntPtr) As Boolean

        Dim udtBI As BROWSEINFO = New BROWSEINFO()
        Dim lpIDList As IntPtr
        Dim hTitle As GCHandle = GCHandle.Alloc(Title, GCHandleType.Pinned)
        udtBI.hWndOwner = hWndOwner
        udtBI.lpszTitle = Title
        udtBI.ulFlags = BrowseFor
        Dim buffer As StringBuilder = New StringBuilder(MAX_PATH)
        buffer.Length = MAX_PATH
        udtBI.pszDisplayName = buffer.ToString()
        lpIDList = SHBrowseForFolder(udtBI)
        hTitle.Free()
        If lpIDList.ToInt64() <> 0 Then
            If BrowseFor = BrowseForTypes.Computers Then
                m_Selected = udtBI.pszDisplayName.Trim()
            Else
                Dim path As StringBuilder = New StringBuilder(MAX_PATH)
                SHGetPathFromIDList(lpIDList, path)
                m_Selected = path.ToString()
            End If
            CoTaskMemFree(lpIDList)
        Else
            Return False
        End If
        Return True
    End Function

    Public Function ShowDialog() As DialogResult
        Return ShowDialog(Nothing)
    End Function

    Public Function ShowDialog(ByVal owner As IWin32Window) As DialogResult
        Dim handle As IntPtr
        If Not owner Is Nothing Then
            handle = owner.Handle
        Else
            handle = IntPtr.Zero
        End If
        If RunDialog(handle) Then
            Return DialogResult.OK
        Else
            Return DialogResult.Cancel
        End If
    End Function

    Public Property Title() As String
        Get
            Return m_Title
        End Get
        Set(ByVal Value As String)
            If Value Is DBNull.Value Then
                Throw New ArgumentNullException()
            End If
            m_Title = Value
        End Set
    End Property

    Public ReadOnly Property Selected() As String
        Get
            Return m_Selected
        End Get
    End Property

    Public Property BrowseFor() As BrowseForTypes
        Get
            Return m_BrowseFor
        End Get
        Set(ByVal Value As BrowseForTypes)
            m_BrowseFor = Value
        End Set
    End Property

    Private m_BrowseFor As BrowseForTypes = BrowseForTypes.Directories
    Private m_Title As String = ""
    Private m_Selected As String = ""

    Public Sub New()
    End Sub
End Class

The code to implement the extended dialog

Sub Button1Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim frmd As DirectoryDialog = New DirectoryDialog()
    ' frmd.BrowseFor = DirectoryDialog.BrowseForTypes.Directories
    ' frmd.BrowseFor = DirectoryDialog.BrowseForTypes.Computers
    frmd.BrowseFor = DirectoryDialog.BrowseForTypes.FilesAndDirectories
    frmd.Title = "Select a file or a folder"
    If frmd.ShowDialog(Me) = DialogResult.OK Then
        MsgBox(frmd.Selected)
    End If
End Sub


问:
whats is the best way of getting the name of the controller action that i am currently in
i have a number of asp.net-mvc controller actions that look like this:

```<code> public ActionResult Home()
 {
      return View(new MyViewModel("Home"));
 }

 public ActionResult Architecture()
 {
      return View(new MyViewModel("Architecture"));
 }
</code>```

is there anyway to get the name of the method that i am in to avoid having to hard code the string "Home" or "Architecture" ??

答:
Sure:</p>

```<code>var action = RouteData.Values["action"];
</code>```

Body:
i have a number of asp.net-mvc controller actions that look like this:

 public ActionResult Home()
 {
      return View(new MyViewModel("Home"));
 }

 public ActionResult Architecture()
 {
      return View(new MyViewModel("Architecture"));
 }

is there anyway to get the name of the method that i am in to avoid having to hard code the string "Home" or "Architecture" ??

Body:
Sure:

var action = RouteData.Values["action"];


问:
Can I run/emulate my Ionic app on my own device?
Is it possible to emulate/run my ionic app on my own device (iOS) without using an Ionic view?
If so, how can I do it? Can I do it with android too?

I'm developing on windows btw.

答:
First of all if you need develop for iOS then you need to do it in iMac. Read the link below:

http://ionicframework.com/docs/guide/testing.html

https://ionicframework.com/docs/v2/cli/emulate/


问:
How do you get the current page URL in jQuery Mobile 1.4.5?
Please don't mark this as a duplicate. I have tried all the methods suggested on StackOverflow and none of them work. They all give me the URL of the referring page, not the current page. Or they don't work at all. Even window.location.href returns the referring page URL, not the current page URL. I'm using jQuery Mobile 1.4.5.

For example say I was on page1.php and I clicked a link to page1.php?getvar=42. Page 1 looks like this:

```<code><!doctype html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
</head>
<body><div data-role="page" data-dom-cache="false">
<a href="page1.php?getvar=42">Click Here</a>
<?php if ($_GET['getvar']=='42'): ?>
<script>
console.log(window.location.href);
console.log(document.location.href);
console.log($.mobile.activePage.data('url'));
</script>
<?php endif ?>
</div></body></html>
</code>```

When I click the link in the above page and I look at what it says in the console. I get:

```<code>http://hostname/page1.php
http://hostname/page1.php
/page1.php
</code>```

I've also tried wrapping these calls to console.log() in a jQuery $(document).ready() function with no change in the result.

```<code><script>
$(function() {
    console.log(window.location.href);
    console.log(document.location.href);
    console.log($.mobile.activePage.data('url'));
});
</script>
</code>```

As you can see none of these are the complete URL. The same is true when linking to a different file. So it doesn't just affect pages with GET variables on the URL. I am expecting to see /page1.php?getvar=42

I've found topics on Stack Overflow that ask this same question but none of the answers are working for me. Perhaps they are using a different version of jQuery Mobile. I'm using jQuery 1.4.5 as you can see.

So far the only solution that I have found is to turn off ajax loading of pages in jQuery mobile by putting data-ajax="false" on a parent container. But there must be a better way.

(By the way, the reason I need this is so that I can reload the current page. But currently all attempts to reload the current page just take me back to the referring page. And this is why.)

答:
Try the following function. I used this peace of code in my project and it did well.</p>

```<code>  var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
  };
</code>```

Body:
Please don't mark this as a duplicate. I have tried all the methods suggested on StackOverflow and none of them work. They all give me the URL of the referring page, not the current page. Or they don't work at all. Even window.location.href returns the referring page URL, not the current page URL. I'm using jQuery Mobile 1.4.5.

For example say I was on page1.php and I clicked a link to page1.php?getvar=42. Page 1 looks like this:

<!doctype html>

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">

Click Here
<?php if ($_GET['getvar']=='42'): ?>

<?php endif ?>

When I click the link in the above page and I look at what it says in the console. I get:

http://hostname/page1.php
http://hostname/page1.php
/page1.php

I've also tried wrapping these calls to console.log() in a jQuery $(document).ready() function with no change in the result.

As you can see none of these are the complete URL. The same is true when linking to a different file. So it doesn't just affect pages with GET variables on the URL. I am expecting to see /page1.php?getvar=42

I've found topics on Stack Overflow that ask this same question but none of the answers are working for me. Perhaps they are using a different version of jQuery Mobile. I'm using jQuery 1.4.5 as you can see.

So far the only solution that I have found is to turn off ajax loading of pages in jQuery mobile by putting data-ajax="false" on a parent container. But there must be a better way.

(By the way, the reason I need this is so that I can reload the current page. But currently all attempts to reload the current page just take me back to the referring page. And this is why.)

Body:
Try the following function. I used this peace of code in my project and it did well.

  var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
  };


问:
Subprocess call to execute a complex command
I need to start the following command in my linux shell.

```<code>./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system "cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"
</code>```

However, using subprocess.call(), the parentheses and quotes don't match correctly.

Escaping double quotes does not help.

```<code>subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"\")
</code>```

Command is executed wrong.

答:
It looks like the error may be in your quote escaping - you have the command as:

```<code>subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"\")
</code>```

But maybe it should be:

```<code>subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')\"")
</code>```

Not how the escape slash on the last double quote is moved to the actual double quote that balances inside the string.

You may also find that you need to escape the backslashes inside of the string too:

```<code>subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\\Users\\ladmin\\Desktop\\successshibani456.csv')\"")
</code>```

Body:
I need to start the following command in my linux shell.

./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system "cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"

However, using subprocess.call(), the parentheses and quotes don't match correctly.

Escaping double quotes does not help.

subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"\")

Command is executed wrong.

Body:
It looks like the error may be in your quote escaping - you have the command as:

subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')"\")

But maybe it should be:

subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\Users\ladmin\Desktop\successshibani456.csv')\"")

Not how the escape slash on the last double quote is moved to the actual double quote that balances inside the string.

You may also find that you need to escape the backslashes inside of the string too:

subprocess.call("./bin/winexe -U ladmin //135.249.24.214  --interactive=0 --system \"cmd.exe /c powershell -c (new-object System.Net.WebClient).DownloadFile('http://135.249.21.229/fr_query/base64.tcl','C:\\Users\\ladmin\\Desktop\\successshibani456.csv')\"")


问:
How to Serialize Tree Structure Data From Database to JSON
I have data in a data store which represents a tree structure. Following code represents how it can be described in a simple DataTable in C#.

```<code>using System.Data;

namespace DemoConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable treeData = new DataTable();
            treeData.Clear();
            treeData.Columns.Add("NodeId", typeof(int));
            treeData.Columns.Add("ParentNodeId", typeof(int));
            treeData.Columns.Add("Data", typeof(string));
            treeData.Columns.Add("AbsolutePath", typeof(string));

            DataRow record1 = treeData.NewRow();
            record1["NodeId"] = 1;
            record1["ParentNodeId"] = 0;
            record1["Data"] = "Dairy";
            record1["AbsolutePath"] = "/Dairy/";
            treeData.Rows.Add(record1);

            DataRow record2 = treeData.NewRow();
            record2["NodeId"] = 2;
            record2["ParentNodeId"] = 1;
            record2["Data"] = "Yoghurt";
            record2["AbsolutePath"] = "/Dairy/Yoghurt";
            treeData.Rows.Add(record2);

            DataRow record3 = treeData.NewRow();
            record3["NodeId"] = 3;
            record3["ParentNodeId"] = 1;
            record3["Data"] = "Cheese";
            record3["AbsolutePath"] = "/Dairy/Cheese";
            treeData.Rows.Add(record3);

            DataRow record4 = treeData.NewRow();
            record4["NodeId"] = 4;
            record4["ParentNodeId"] = 2;
            record4["Data"] = "Flavored";
            record4["AbsolutePath"] = "/Dairy/Yoghurt/Flavored";
            treeData.Rows.Add(record4);
        }
    }
}
</code>```

I need to serialize the data into the following structure.

```<code>{
  "TreeData": {
    "NodeId" : "1",
    "Data" : "Dairy",
    "Children": [
      {
        "NodeId": "2",
        "Data": "Yohurt",
        "Children": [
          {
              "NodeId": "4",
              "Data": "Flavored",
              "Children": []
          }
        ]
      },
      {
        "NodeId": "3",
        "Data": "Cheese",
        "Children": []
      }
    ]
  }
}
</code>```

How do i go about achieving this?

答:
```<code>you need to make custom recursive function with Serialization Class
which will append Children till you get leaf node.
Below is example for that. please use your logic to append JsonString
var appendJsonString;

Private string PassParentId(int Id)
{
      var childnodecount=0;
      childnodecount=getchildnode(Id);
     while(childnodecount>0)
     {
       getchilddata=getchildnode(Id);
       childnodecount=getchilddata.count();
       appendJsonString = getchilddata();
    }
    return appendJsonString;
}
</code>```

Body:
I have data in a data store which represents a tree structure. Following code represents how it can be described in a simple DataTable in C#.

using System.Data;

namespace DemoConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable treeData = new DataTable();
            treeData.Clear();
            treeData.Columns.Add("NodeId", typeof(int));
            treeData.Columns.Add("ParentNodeId", typeof(int));
            treeData.Columns.Add("Data", typeof(string));
            treeData.Columns.Add("AbsolutePath", typeof(string));

            DataRow record1 = treeData.NewRow();
            record1["NodeId"] = 1;
            record1["ParentNodeId"] = 0;
            record1["Data"] = "Dairy";
            record1["AbsolutePath"] = "/Dairy/";
            treeData.Rows.Add(record1);

            DataRow record2 = treeData.NewRow();
            record2["NodeId"] = 2;
            record2["ParentNodeId"] = 1;
            record2["Data"] = "Yoghurt";
            record2["AbsolutePath"] = "/Dairy/Yoghurt";
            treeData.Rows.Add(record2);

            DataRow record3 = treeData.NewRow();
            record3["NodeId"] = 3;
            record3["ParentNodeId"] = 1;
            record3["Data"] = "Cheese";
            record3["AbsolutePath"] = "/Dairy/Cheese";
            treeData.Rows.Add(record3);

            DataRow record4 = treeData.NewRow();
            record4["NodeId"] = 4;
            record4["ParentNodeId"] = 2;
            record4["Data"] = "Flavored";
            record4["AbsolutePath"] = "/Dairy/Yoghurt/Flavored";
            treeData.Rows.Add(record4);
        }
    }
}

I need to serialize the data into the following structure.

{
  "TreeData": {
    "NodeId" : "1",
    "Data" : "Dairy",
    "Children": [
      {
        "NodeId": "2",
        "Data": "Yohurt",
        "Children": [
          {
              "NodeId": "4",
              "Data": "Flavored",
              "Children": []
          }
        ]
      },
      {
        "NodeId": "3",
        "Data": "Cheese",
        "Children": []
      }
    ]
  }
}

How do i go about achieving this?