问:
Postgres complicated query generate case statements
I have a query like this:

```<code>select date, meter,
   sum(case when period = 1 then round(value, 2)end) as period_01,
   sum(case when period = 2 then round(value, 2)end) as period_02,
   sum(case when period = 3 then round(value, 2)end) as period_03,
   sum(case when period = 4 then round(value, 2)end) as period_04,
   sum(round(kwh, 2)) as total
from table
group by date, meter
order by date, meter;
</code>```

I need a couple of things:

the total column needs to be a sum of the case statements.  Because the case statements are rounded, it is giving the wrong total.

is it possible to generate the case statement columns based off of how many periods there are for any given date?  e.g. To look like this based on how many periods for each day

```
Date - MeterId - Periods . . . - Total
2017-06-05 | meter_01 | 10 | 14 | 6 | {total} 30
2017-06-06 | meter_01 | 10 | 7  | 2 | 5 | {total} 24
```

I guess it would have to first find how many periods there are for each date then run the query but this is way beyond my knowledge level...

答:
The answer to your first question is to round() after the sum():

```<code>select date, meter,
       round(sum(case when period = 1 then value end), 2) as period_01,
       round(sum(case when period = 2 then value end), 2) as period_02,
       round(sum(case when period = 3 then value end), 2) as period_03,
       round(sum(case when period = 4 then value end), 2) as period_04
       round(sum(kwh), 2) as total
from table
group by date, meter
order by date, meter;
</code>```

The answer to your second question is essentially "not easily".  You can use dynamic SQL, crosstab() with a very complicated expression, or put the values into an array/json object.  But there is no easy way to return a variable number of columns.

Body:
I have a query like this:

select date, meter,
   sum(case when period = 1 then round(value, 2)end) as period_01,
   sum(case when period = 2 then round(value, 2)end) as period_02,
   sum(case when period = 3 then round(value, 2)end) as period_03,
   sum(case when period = 4 then round(value, 2)end) as period_04,
   sum(round(kwh, 2)) as total
from table
group by date, meter
order by date, meter;

I need a couple of things:

the total column needs to be a sum of the case statements.  Because the case statements are rounded, it is giving the wrong total.

is it possible to generate the case statement columns based off of how many periods there are for any given date?  e.g. To look like this based on how many periods for each day

Date - MeterId - Periods . . . - Total
2017-06-05 | meter_01 | 10 | 14 | 6 | {total} 30
2017-06-06 | meter_01 | 10 | 7  | 2 | 5 | {total} 24

I guess it would have to first find how many periods there are for each date then run the query but this is way beyond my knowledge level...

Body:
The answer to your first question is to round() after the sum():

select date, meter,
       round(sum(case when period = 1 then value end), 2) as period_01,
       round(sum(case when period = 2 then value end), 2) as period_02,
       round(sum(case when period = 3 then value end), 2) as period_03,
       round(sum(case when period = 4 then value end), 2) as period_04
       round(sum(kwh), 2) as total
from table
group by date, meter
order by date, meter;

The answer to your second question is essentially "not easily".  You can use dynamic SQL, crosstab() with a very complicated expression, or put the values into an array/json object.  But there is no easy way to return a variable number of columns.


来源: stackexchange

问:
RegEx to remove all \begin{gather}... \end{gather}
I have a 6,200 hundred pages book with simple stuff like:

```<code>\begin{gather}
    A>B,A=B,A<B,A\leq B,A \geq B
\end{gather}
</code>```

or a bit more complicates:

```<code>\begin{gather}
    \begin{aligned}
    (a+b)^0&=1\\
    (a+b)^1&=1a+1b\\
    (a+b)^2&=1a^2+2ab+1b^2\\
    (a+b)^3&=1a^3+3a^2b+3ab^2+1b^3\\
    \end{aligned}
\end{gather}
</code>```

I'm trying to found the RegEx to remove all \begin{gather} \end{gather} environment (it's LaTeX). The best i have found by trial and error is:

```<code>(\\begin\{gather\}*\r?\n?.*)*\r?\n?.*(\r?\n?.*\\end\{gather\})
</code>```

But it doesn't work :-(((

Any help would be appreciate.

Thx in advance

答:
This works in Notepad++:

```<code>(?s)\\begin\{gather\}.*?\\end\{gather\}
</code>```

Make sure you set the option (. matches newline)

Here is an example in Regex101 that uses the ungreedy option ".*?" and the "(?s)" s modifier: single line. Dot matches newline characters.

example

ContentLicense: CC BY-SA 3.0

Body:
I have a 6,200 hundred pages book with simple stuff like:

\begin{gather}
    A>B,A=B,A<B,A\leq B,A \geq B
\end{gather}

or a bit more complicates:

\begin{gather}
    \begin{aligned}
    (a+b)^0&=1\\
    (a+b)^1&=1a+1b\\
    (a+b)^2&=1a^2+2ab+1b^2\\
    (a+b)^3&=1a^3+3a^2b+3ab^2+1b^3\\
    \end{aligned}
\end{gather}

I'm trying to found the RegEx to remove all \begin{gather} \end{gather} environment (it's LaTeX). The best i have found by trial and error is:

(\\begin\{gather\}*\r?\n?.*)*\r?\n?.*(\r?\n?.*\\end\{gather\})

But it doesn't work :-(((

Any help would be appreciate.

Thx in advance

Body:
This works in Notepad++:

(?s)\\begin\{gather\}.*?\\end\{gather\}

Make sure you set the option (. matches newline)

Here is an example in Regex101 that uses the ungreedy option ".*?" and the "(?s)" s modifier: single line. Dot matches newline characters.

example


答:
This might work for you (GNU sed):

```<code>sed -r 's/((.*)\|[^_,]*)[_,]/\1\n\2|/;l;P;D' file
</code>```

Replace the first _ or , by the first two fields separated from the next two fields by a newline. Print the first line then repeat the process until all fields on the pattern space are accounted for.

Title: add first entry into next line and shift data after comma & underscore from previous line to the next line

Body:
Data after underscore and comma will go to next line and data from beginning to pipe add before them.

sample data:

1.2.4.0/24|24151_24409_24406
37.99.128.0/19|47794_47795,48695
37.142.128.0/17|21450,65555

expected result should be:

1.2.4.0/24|24151
1.2.4.0/24|24409
1.2.4.0/24|24406
37.99.128.0/19|47794
37.99.128.0/19|47795
37.99.128.0/19|48695
37.142.128.0/17|21450
37.142.128.0/17|65555

Is there a way to do it?

Body:
This might work for you (GNU sed):

sed -r 's/((.*)\|[^_,]*)[_,]/\1\n\2|/;l;P;D' file

Replace the first _ or , by the first two fields separated from the next two fields by a newline. Print the first line then repeat the process until all fields on the pattern space are accounted for.


问:
Append async responses in sequence swit 3
I'm generating a ticker which retrieves data from the api using dataTask and returns to the function via succsss

The function which gets the response needs to append or concatenate them in sequence, however I'm unable to get that done.

Here is what I've tried, both fail as the last print line executes before the individual ticker success call returns.

```<code>    func getTicker() {

        var tickerText = ""

        tickerText += dataRequestnew("https://api-path-here/1") { success in return "First-item: \(success)" }
        tickerText += dataRequestnew("https://api-path-here/2") { success in return " | Second-item: \(success)" }

        print(tickerText)

    }
</code>```

Or

```<code>    var tickerText = ""

    func getTicker() {

        dataRequestnew("https://api-path-here/1") { success in
            self.tickerText += "First-item: \(success)"
            print(self.tickerText)
        }
        dataRequestnew("https://api-path-here/2") { success in
            self.tickerText += " | Second-item: \(success)"
            print(self.tickerText)
        }

        print(self.tickerText)
    }
</code>```

In the second example, the individual ticker prints successfully, but not the last one, it returns the default value only.

Question

How can I make the code run in sequence or at least make sure that the last print works once all the tickerText calls are returned successfully.

Thanks.

答:
As an option, you can call the second request in first response. And only then print a result.</p>

```<code>var tickerText = ""

    func getTicker() {

        dataRequestnew("https://api-path-here/1") { success in
            self.tickerText += "First-item: \(success)"
            dataRequestnew("https://api-path-here/2") { success in
                self.tickerText += " | Second-item: \(success)"
                print(self.tickerText)
            }
        }
    }
</code>```

Body:
I'm generating a ticker which retrieves data from the api using dataTask and returns to the function via succsss

The function which gets the response needs to append or concatenate them in sequence, however I'm unable to get that done.

Here is what I've tried, both fail as the last print line executes before the individual ticker success call returns.

    func getTicker() {

        var tickerText = ""

        tickerText += dataRequestnew("https://api-path-here/1") { success in return "First-item: \(success)" }
        tickerText += dataRequestnew("https://api-path-here/2") { success in return " | Second-item: \(success)" }

        print(tickerText)

    }

Or

    var tickerText = ""

    func getTicker() {

        dataRequestnew("https://api-path-here/1") { success in
            self.tickerText += "First-item: \(success)"
            print(self.tickerText)
        }
        dataRequestnew("https://api-path-here/2") { success in
            self.tickerText += " | Second-item: \(success)"
            print(self.tickerText)
        }

        print(self.tickerText)
    }

In the second example, the individual ticker prints successfully, but not the last one, it returns the default value only.

Question

How can I make the code run in sequence or at least make sure that the last print works once all the tickerText calls are returned successfully.

Thanks.

Body:
As an option, you can call the second request in first response. And only then print a result.

var tickerText = ""

    func getTicker() {

        dataRequestnew("https://api-path-here/1") { success in
            self.tickerText += "First-item: \(success)"
            dataRequestnew("https://api-path-here/2") { success in
                self.tickerText += " | Second-item: \(success)"
                print(self.tickerText)
            }
        }
    }


问:
How do I link arraylist values to class objects? (Android)
I have a class Sale.java created in Android studio:

```<code> public class Sale {

private String Name;
private double Price;
private int quantity;

 public Sale(String Name, double Price, int quantity) {
    this.Name = Name;
    this.Price = Price;
    this.quantity = quantity;

}
 public String getName() {
     return Name;
}

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

public double getPrice() {
    return Price;
}

public void setPrice(double Price) {
    this.Price = Price;
}

public int getQuantity() {
    return quantity;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

 }
</code>```

In my mainactivity.java, I want to create an Arraylist to store each Sale object dynamically and also keep track of which Sale object belongs to which "index" from the Arraylist by using for loop in the future.

```<code>//Arraylist for storing information about items
ArrayList<Sale> iteminfo = new ArrayList<>();
Sale scheck;

 EditText ItemName;
EditText ItemPrice;
EditText Itemqty;

 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sales);

    ItemName = (EditText) findViewById(R.id.addName);
    ItemCostPrice = (EditText) findViewById(R.id.addprice);
    ItemQty = (EditText) findViewById(R.id.addqty);

 btnSaveinfo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    double Price = Double.parseDouble(ItemPrice.getText().toString());
                double Qty =
 Double.parseDouble((ItemQty.getText().toString()));
            string Name = ItemName.getText().toString();

   scheck = new Sale(Name, Price, Qty);

 } }
</code>```

How do I code such that every time the button is clicked, an object of Sale is created which links it to ArrayList ? Have I done it right by declaring Arraylist as object type? Please help.

答:
You can just do:

iteminfo.add(scheck);

Or even without variable scheck if you don't need it for anything else:

iteminfo.add(new Sale(Name, Price, Qty));

ArrayList is simply a list of objects, so if you add 1 object it will be available by:

Sale lastAddedSale = iteminfo.get(0);

If you add another then iteminfo.get(1) will be this item, ArrayList is keeping insertion order, each time you add an object it is at the last position (to get last in the list you can iteminfo.get(iteminfo.size() - 1) if the list is not empty of course).

Also, variable names should start with lowercase, it's a convention in Java to name them like this so you don't confuse variables with class names (since they are named starting with uppercase).

Body:
I have a class Sale.java created in Android studio:

 public class Sale {

private String Name;
private double Price;
private int quantity;

 public Sale(String Name, double Price, int quantity) {
    this.Name = Name;
    this.Price = Price;
    this.quantity = quantity;

}
 public String getName() {
     return Name;
}

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

public double getPrice() {
    return Price;
}

public void setPrice(double Price) {
    this.Price = Price;
}

public int getQuantity() {
    return quantity;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

 }

In my mainactivity.java, I want to create an Arraylist to store each Sale object dynamically and also keep track of which Sale object belongs to which "index" from the Arraylist by using for loop in the future.

//Arraylist for storing information about items
ArrayList<Sale> iteminfo = new ArrayList<>();
Sale scheck;

 EditText ItemName;
EditText ItemPrice;
EditText Itemqty;

 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sales);

    ItemName = (EditText) findViewById(R.id.addName);
    ItemCostPrice = (EditText) findViewById(R.id.addprice);
    ItemQty = (EditText) findViewById(R.id.addqty);

 btnSaveinfo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    double Price = Double.parseDouble(ItemPrice.getText().toString());
                double Qty =
 Double.parseDouble((ItemQty.getText().toString()));
            string Name = ItemName.getText().toString();

   scheck = new Sale(Name, Price, Qty);

 } }

How do I code such that every time the button is clicked, an object of Sale is created which links it to ArrayList ? Have I done it right by declaring Arraylist as object type? Please help.


问:
Content type in call to web service
Please correct me if I'm wrong in defining contet type:

```<code>Content-Type: application/json; charset=utf-8
{"my_id":"975","my_a_id":"Test66","param":"4","amount":"66"}
</code>```

and

```<code>Content-Type: application/x-www-form-urlencoded
my_id=123&my_a_id=Test66&param=4&amount=66
</code>```

What other content types might be?

What content type supports RESTLet NetSuite services?

I have POST to web service:

```<code>POST https://some.netsuite.uri?deploy=1 HTTP/1.1
Authorization: NLAuth nlauth_account=3624292_SB3, nlauth_email=xduh31@gmail.com, nlauth_signature=Pass987654, nlauth_role=3
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: rest.eu1.netsuite.com
Cookie: JSESSIONID=**************************************; lastUser=1234567_SB9_1282_3; NS_ROUTING_VERSION=LAGGING; NS_VER=2017.1.0
Content-Length: 69
Expect: 100-continue

{"my_id":"975","my_a_id":"Test66","param":"4","amount":"66"}
</code>```

Is it good that in URL I have something like x-www-form-urlencoded - ?deploy=1

```<code>https://some.netsuite.uri?deploy=1
</code>```

and data is json style:

```<code>{"my_id":"975","my_a_id":"Test66","param":"4","amount":"66"}
</code>```

UPD

I got answer that I suppose should return JSON data:

```<code>HTTP/1.1 200 OK
Date: Sat, 03 Jun 2017 06:21:46 GMT
Server: Apache
Cache-Control: No-Cache
Pragma: No-Cache
Content-Length: 41
Expires: 0
Edge-Control: no-store
X-N-OperationId: 486c2d20-099d-446b-9788-4816db59a1fd
Set-Cookie: .......................; path=/
NS_RTIMER_COMPOSITE: 1688996695:706172746E6572733030312E70726F642E6475622E6E65746C65646765722E636F6D:80
P3P: CP="CAO PSAa OUR BUS PUR"
Vary: User-Agent
Content-Type: application/json; charset=utf-8

org.mozilla.javascript.Undefined@54b896b0
</code>```

But this answer not looks like JSON?

答:
You can find supported content types in NS Help Center:

RESTlets support JSON and plain text content types for input and
  output. For each RESTlet, output content type is the same as input
  content type.

You must set the content type in the HTTP Content-Type header. You can
  use the following values to specify the input/output content type for
  a RESTlet:

application/json

text/plain

If you specify a content type other than JSON or text, a 415 error is
  returned with the following message:

Invalid content type.  You can only use application/json or text/plain
  with RESTlets.

Documentation

Besides that the issue in the url mentioned by shazmodan, the script Id is missing. Below is an example of a valid restlet url:

```<code>https://rest.netsuite.com/app/site/hosting/restlet.nl?deploy=1&script=1
</code>```

You can pass additional parameters in the url:

```<code>https://rest.netsuite.com/app/site/hosting/restlet.nl?deploy=1&script=1&my_id=123&my_a_id=Test66&param=4&amount=66
</code>```

or in the request body if you are using POST and PUT methods but it needs to be a valid JSON. But the Content Type must always be application/json or text/plain.

Title: Content type in call to web service

Body:
Please correct me if I'm wrong in defining contet type:

Content-Type: application/json; charset=utf-8
{"my_id":"975","my_a_id":"Test66","param":"4","amount":"66"}

and

Content-Type: application/x-www-form-urlencoded
my_id=123&my_a_id=Test66&param=4&amount=66

What other content types might be?

What content type supports RESTLet NetSuite services?

I have POST to web service:

POST https://some.netsuite.uri?deploy=1 HTTP/1.1
Authorization: NLAuth nlauth_account=3624292_SB3, nlauth_email=xduh31@gmail.com, nlauth_signature=Pass987654, nlauth_role=3
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: rest.eu1.netsuite.com
Cookie: JSESSIONID=**************************************; lastUser=1234567_SB9_1282_3; NS_ROUTING_VERSION=LAGGING; NS_VER=2017.1.0
Content-Length: 69
Expect: 100-continue

{"my_id":"975","my_a_id":"Test66","param":"4","amount":"66"}

Is it good that in URL I have something like x-www-form-urlencoded - ?deploy=1

https://some.netsuite.uri?deploy=1

and data is json style:

{"my_id":"975","my_a_id":"Test66","param":"4","amount":"66"}

UPD

I got answer that I suppose should return JSON data:

HTTP/1.1 200 OK
Date: Sat, 03 Jun 2017 06:21:46 GMT
Server: Apache
Cache-Control: No-Cache
Pragma: No-Cache
Content-Length: 41
Expires: 0
Edge-Control: no-store
X-N-OperationId: 486c2d20-099d-446b-9788-4816db59a1fd
Set-Cookie: .......................; path=/
NS_RTIMER_COMPOSITE: 1688996695:706172746E6572733030312E70726F642E6475622E6E65746C65646765722E636F6D:80
P3P: CP="CAO PSAa OUR BUS PUR"
Vary: User-Agent
Content-Type: application/json; charset=utf-8

org.mozilla.javascript.Undefined@54b896b0

But this answer not looks like JSON?

Body:
You can find supported content types in NS Help Center:

RESTlets support JSON and plain text content types for input and
  output. For each RESTlet, output content type is the same as input
  content type.

You must set the content type in the HTTP Content-Type header. You can
  use the following values to specify the input/output content type for
  a RESTlet:

application/json

text/plain

If you specify a content type other than JSON or text, a 415 error is
  returned with the following message:

Invalid content type.  You can only use application/json or text/plain
  with RESTlets.

Documentation

Besides that the issue in the url mentioned by shazmodan, the script Id is missing. Below is an example of a valid restlet url:

https://rest.netsuite.com/app/site/hosting/restlet.nl?deploy=1&script=1

You can pass additional parameters in the url:

https://rest.netsuite.com/app/site/hosting/restlet.nl?deploy=1&script=1&my_id=123&my_a_id=Test66&param=4&amount=66

or in the request body if you are using POST and PUT methods but it needs to be a valid JSON. But the Content Type must always be application/json or text/plain.


问:
Why -bash: /usr/bin/g++: cannot execute binary file?
```<code>simpatico$ /Developer/usr/bin/g++-4.2 -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5664~89/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5664)

simpatico$ /usr/bin/g++ -v
-bash: /usr/bin/g++: cannot execute binary file
</code>```

I don't know of a command that proves that /usr/bin/g++  is an alias of /Developer/usr/bin/g++-4.2.

答: simpatico$  sudo gcc_select  gcc42</p>

ContentLicense: CC BY-SA 2.5

Body:
simpatico$ /Developer/usr/bin/g++-4.2 -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5664~89/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5664)

simpatico$ /usr/bin/g++ -v
-bash: /usr/bin/g++: cannot execute binary file

I don't know of a command that proves that /usr/bin/g++  is an alias of /Developer/usr/bin/g++-4.2.

Body: simpatico$  sudo gcc_select  gcc42


问:
How to query multiple collections in mongoose
I have two schema "Users" and "Books".

Users: _id, isActive type: boolean

Books: userid ref Users, name

I want to query Books which user's isActive is true.

I have one approach that is first query Users with isActive=true and return userid list, then query Books with userid in userid list.

Can anybody has the other better approach to query this situation? thanks.

答:
Version 3.2 introduced $lookup, which works like left outer join in aggregation pipeline.

```<code>User.aggregate([
    {
        $match: {isActive: true}
    },
    {
        $lookup: //left outer join
        {
            from: "books",
            localField: "_id",
            foreignField: "userid",
            as: "books"
        }
    },
    {
        $unwind: "$books" // convert each element of "books" array into its own document
    },
    {
        $replaceRoot: { newRoot: "$books" } // remove "books" key. Bring its content out in the root
    }

]).exec(function(err, books) {
    // books with users isActive true
})
</code>```

Note that, we used User to aggregate because we want to query isActive: true, but after processing the documents in the aggregation pipeline we get books at the end.

Body:
Version 3.2 introduced $lookup, which works like left outer join in aggregation pipeline.

User.aggregate([
    {
        $match: {isActive: true}
    },
    {
        $lookup: //left outer join
        {
            from: "books",
            localField: "_id",
            foreignField: "userid",
            as: "books"
        }
    },
    {
        $unwind: "$books" // convert each element of "books" array into its own document
    },
    {
        $replaceRoot: { newRoot: "$books" } // remove "books" key. Bring its content out in the root
    }

]).exec(function(err, books) {
    // books with users isActive true
})

Note that, we used User to aggregate because we want to query isActive: true, but after processing the documents in the aggregation pipeline we get books at the end.


问:
Python: parse JSON in loop
I have a function that pick-ups Country,City,Latitude,Longitude from a database and search on Yelp API for particular business.

And everything works fine:

```<code>def get_movietheaters_for(country, city, latitude, longitude):
    connection2 = pyodbc.connect('DRIVER={SQL Server};'
                                 'SERVER=ASPIRES3;'
                                 'DATABASE=worldcitiespop;'
                                 'UID=sqlninja;'
                                 'PWD=sqlninja')
    cursor2 = connection2.cursor()
    # Call Yelp API to pull business data
    # (Yelp v3 API: https://nz.yelp.com/developers/documentation/v3)
    url = 'https://api.yelp.com/v3/businesses/search'
    params = {'cc': country,
              'location': city,
              'cll': "%s,%s" % (latitude, longitude),
              'categories': args.category,
              'limit': args.limit}
    response = requests.get(url = url, headers = headers, params=params)
    # if response.status_code == 200:
    response_data = response.json()

    sqlStatement = "INSERT INTO VistaYelp (ID, Name, City, Zip_code, Country, State, Address1, Address2, Address3, Latitude, Longitude, Phone, Yelp_URL, Review_Count, Rating) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" # Query
    # Here we go to store JSON elements for SQL

    for SQL_element in response_data['businesses']:
        SQL_ID = SQL_element['id']
        SQL_Name = SQL_element['name']
        SQL_City = SQL_element['location']['city']
        SQL_Zip_code = SQL_element['location']['zip_code']
        SQL_Country = SQL_element['location']['country']
        SQL_State = SQL_element['location']['state']
        SQL_Address1 = SQL_element['location']['address1']
        SQL_Address2 = SQL_element['location']['address2']
        SQL_Address3 = SQL_element['location']['address3']
        SQL_Latitude = SQL_element['coordinates']['latitude']
        SQL_Longitude = SQL_element['coordinates']['longitude']
        SQL_Phone = SQL_element['phone']
        SQL_YelpURL = SQL_element['url']
        SQL_Review = SQL_element['review_count']
        SQL_Rating = SQL_element['rating']

        if args.do == 'show':
            print (SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,
                SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone)
        elif args.do == 'save':
            cursor2.execute(sqlStatement, SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone,SQL_YelpURL,SQL_Review,SQL_Rating)
            connection2.commit()

    if args.do == 'show':
        print ('\nTotal Cinemas found: ' , len(response_data['businesses']),' for Latitude and Longitude ', latitude, longitude)
    elif args.do == 'save':
        print ('\nTotal Cinemas found and saved in database: ' , len(response_data['businesses']),' for', latitude, longitude)
</code>```

Problem start when the script search for a town that doesn't exists or is not in the Yelp database, so JSON call returns me:

```<code>{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}
</code>```

and the script dies in terrible pain (my pain actually):

And it make sense to me, Python is saying:

```<code>    for SQL_element in response_data['businesses']:
KeyError: 'businesses'
</code>```

Which translated means:"Hey dude, you know 'businesses' JSON element, there is no such element in the response, so I don't know what to do, so I stop here."

How can I structure something like: keep doing your job and if response_data['error']['code'] == 'LOCATION_NOT_FOUND': do nothing?

答:
After
    response_data = response.json()

Verify if response_data Has a businesses key

```<code>If `businesses` in response_data.keys():
    # Do the code
</code>```

Title: Python: parse JSON in loop

Body:
I have a function that pick-ups Country,City,Latitude,Longitude from a database and search on Yelp API for particular business.

And everything works fine:

def get_movietheaters_for(country, city, latitude, longitude):
    connection2 = pyodbc.connect('DRIVER={SQL Server};'
                                 'SERVER=ASPIRES3;'
                                 'DATABASE=worldcitiespop;'
                                 'UID=sqlninja;'
                                 'PWD=sqlninja')
    cursor2 = connection2.cursor()
    # Call Yelp API to pull business data
    # (Yelp v3 API: https://nz.yelp.com/developers/documentation/v3)
    url = 'https://api.yelp.com/v3/businesses/search'
    params = {'cc': country,
              'location': city,
              'cll': "%s,%s" % (latitude, longitude),
              'categories': args.category,
              'limit': args.limit}
    response = requests.get(url = url, headers = headers, params=params)
    # if response.status_code == 200:
    response_data = response.json()

    sqlStatement = "INSERT INTO VistaYelp (ID, Name, City, Zip_code, Country, State, Address1, Address2, Address3, Latitude, Longitude, Phone, Yelp_URL, Review_Count, Rating) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" # Query
    # Here we go to store JSON elements for SQL

    for SQL_element in response_data['businesses']:
        SQL_ID = SQL_element['id']
        SQL_Name = SQL_element['name']
        SQL_City = SQL_element['location']['city']
        SQL_Zip_code = SQL_element['location']['zip_code']
        SQL_Country = SQL_element['location']['country']
        SQL_State = SQL_element['location']['state']
        SQL_Address1 = SQL_element['location']['address1']
        SQL_Address2 = SQL_element['location']['address2']
        SQL_Address3 = SQL_element['location']['address3']
        SQL_Latitude = SQL_element['coordinates']['latitude']
        SQL_Longitude = SQL_element['coordinates']['longitude']
        SQL_Phone = SQL_element['phone']
        SQL_YelpURL = SQL_element['url']
        SQL_Review = SQL_element['review_count']
        SQL_Rating = SQL_element['rating']

        if args.do == 'show':
            print (SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,
                SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone)
        elif args.do == 'save':
            cursor2.execute(sqlStatement, SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone,SQL_YelpURL,SQL_Review,SQL_Rating)
            connection2.commit()

    if args.do == 'show':
        print ('\nTotal Cinemas found: ' , len(response_data['businesses']),' for Latitude and Longitude ', latitude, longitude)
    elif args.do == 'save':
        print ('\nTotal Cinemas found and saved in database: ' , len(response_data['businesses']),' for', latitude, longitude)

Problem start when the script search for a town that doesn't exists or is not in the Yelp database, so JSON call returns me:

{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}

and the script dies in terrible pain (my pain actually):

And it make sense to me, Python is saying:

    for SQL_element in response_data['businesses']:
KeyError: 'businesses'

Which translated means:"Hey dude, you know 'businesses' JSON element, there is no such element in the response, so I don't know what to do, so I stop here."

How can I structure something like: keep doing your job and if response_data['error']['code'] == 'LOCATION_NOT_FOUND': do nothing?

Body:
After
    response_data = response.json()

Verify if response_data Has a businesses key

If `businesses` in response_data.keys():
    # Do the code


问:
Find a character in a list of words
I am trying to find a specific character in a list of words and then print all the words that match. for example, I have a list of 6 words. I would like to find a way to select all the words with a ('.') (fullstop) in them and transfer them to another list.

Example:

```<code>List ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
</code>```

I would like it to find Charlie and its position in the list

I mostly just need the if statement for it
Thanks in advance!

This is what I have so far

```<code>sent = str(input('enter sentance '))
words = sent.split()
print (words)
</code>```

答:
you can try this (for python 2.7)</p>

```<code>sent = raw_input('enter sentance ')

lista = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']

res = [i for i in lista if (sent in i)][0]

print(str(res) + "is at index " + str(lista.index(res)))
</code>```

Title: Find a character in a list of words

Body:
I am trying to find a specific character in a list of words and then print all the words that match. for example, I have a list of 6 words. I would like to find a way to select all the words with a ('.') (fullstop) in them and transfer them to another list.

Example:

List ['alpha', 'bravo', 'charlie.', 'delta', 'echo']

I would like it to find Charlie and its position in the list

I mostly just need the if statement for it
Thanks in advance!

This is what I have so far

sent = str(input('enter sentance '))
words = sent.split()
print (words)

Body:
you can try this (for python 2.7)

sent = raw_input('enter sentance ')

lista = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']

res = [i for i in lista if (sent in i)][0]

print(str(res) + "is at index " + str(lista.index(res)))


问:
error: expected initializer before '*' token
```<code>#include <iostream>

using namespace std;

int** add(int** first, int** second);
int addAllElems(int** matrix);
int addAllElems(int** matrix);
void display(int** matrix);

int main()
{
    int first** = {{5,7,4}, {3,9,2}, {7,3,6}};
    int second** = {{3,7,2}, {6,2,6}, {3,5,8}};

    cout << "The first matrix is:" << endl;
    display(first);
    cout << endl;

    cout << "The second matrix is:" << endl;
    display(second);
    cout << endl;

    cout << "The sum of the two matrices is:" << endl;
    display(add(first, second));
    cout << endl;

    cout << "The sum of all elements of the first matrix is: "
        << addAllElems(first) << endl;
    cout << endl;

    return 0;
}

int** add(int** first, int** second) {
    int[][] sum = new int[3][3];
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            sum[i][j] = first[i][j] + second[i][j];
        }
    }
    return sum;
}

int addAllElems(int** matrix) {
    int sumOfElems = 0;
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            sumOfElems += matrix[i][j];
        }
    }
    return sumOfElems;
}

void display(int** matrix) {
    cout << "[" << endl;
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            cout << matrix[i][j] << ", ";
        }
        cout << endl;
    }
    cout << "]" << endl;
}
</code>```

Who can fix this code?

I'm getting this error when compiling it:

```<code> In function 'int main()':
12:14: error: expected initializer before '*' token
63:1: error: expected '}' at end of input
</code>```

I think the problem is from my array declaration.
I think the problem is from my array declaration.
I think the problem is from my array declaration.
I think the problem is from my array declaration.

答:
First the stars need to be directly to the right of a type:

```<code>int** first;
</code>```

Then you need to initialize it differently:

```<code>int** first = new int*[3];
    for (int i = 0; i < 3; i++)
    {
        first[i] = new int[3];
    }
    first[0][0] = 5;
    first[0][7] = 7;
    // ...
</code>```

Body:
#include <iostream>

using namespace std;

int** add(int** first, int** second);
int addAllElems(int** matrix);
int addAllElems(int** matrix);
void display(int** matrix);

int main()
{
    int first** = {{5,7,4}, {3,9,2}, {7,3,6}};
    int second** = {{3,7,2}, {6,2,6}, {3,5,8}};

    cout << "The first matrix is:" << endl;
    display(first);
    cout << endl;

    cout << "The second matrix is:" << endl;
    display(second);
    cout << endl;

    cout << "The sum of the two matrices is:" << endl;
    display(add(first, second));
    cout << endl;

    cout << "The sum of all elements of the first matrix is: "
        << addAllElems(first) << endl;
    cout << endl;

    return 0;
}

int** add(int** first, int** second) {
    int[][] sum = new int[3][3];
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            sum[i][j] = first[i][j] + second[i][j];
        }
    }
    return sum;
}

int addAllElems(int** matrix) {
    int sumOfElems = 0;
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            sumOfElems += matrix[i][j];
        }
    }
    return sumOfElems;
}

void display(int** matrix) {
    cout << "[" << endl;
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            cout << matrix[i][j] << ", ";
        }
        cout << endl;
    }
    cout << "]" << endl;
}

Who can fix this code?

I'm getting this error when compiling it:

 In function 'int main()':
12:14: error: expected initializer before '*' token
63:1: error: expected '}' at end of input

I think the problem is from my array declaration.
I think the problem is from my array declaration.
I think the problem is from my array declaration.
I think the problem is from my array declaration.

Body:
First the stars need to be directly to the right of a type:

int** first;

Then you need to initialize it differently:

int** first = new int*[3];
    for (int i = 0; i < 3; i++)
    {
        first[i] = new int[3];
    }
    first[0][0] = 5;
    first[0][7] = 7;
    // ...


问:
I'm trying to limit the number of displayed numbers in ng-repeat in html
Angular novice and working through a fibonacci sequence app. I would like to only ng-repeat/display the current number in the sequence instead of having all of the numbers stack up in the html page. Should I use a directive instead or is limitTo the solution to dynamically display only one number each time the button is clicked? I looked for other answers, but none really fit my problem. Thanks for any help!

Here is my code so far:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fibonacci</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">

</head>
<body ng-app="fib" ng-controller="nextFibCtrl">

<h2 ng-repeat="result in results track by $index" | "limitTo: 1"> {{ result }}
</h2>

<div>
<button type="button" class="reset" ng-click="clear()">RESET</button>
<button type="button" class="next" ng-click="nextNum()">NEXT FIB</button>
</div>

<script src =
 "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.js" >
</script>
<script src="script.js"></script>
</body>
</html>
</code>```

My script file:

```<code> var app = angular.module('fib', []);

 app.controller('nextFibCtrl', function($scope,){

 $scope.results = [0, 1];

 $scope.nextNum = function(){

     $scope.currentInt = $scope.results.length -1;

     $scope.nextInt = $scope.results[$scope.currentInt] +

     $scope.results[$scope.currentInt -1];

     $scope.results.push($scope.nextInt);

  }

      $scope.clear = function(){

      $scope.results = [0, 1];

  }

  });
</code>```

答:
You don't need ng-repeat. Just initialise and reference nextInt:

```<code><h2>{{nextInt}}
</h2>
</code>```

In your script:

```<code>$scope.nextInt = 1;
</code>```

Or alternatively, just:

```<code><h2>{{results[results.length - 1]}}</h2>
</code>```

Body:
Angular novice and working through a fibonacci sequence app. I would like to only ng-repeat/display the current number in the sequence instead of having all of the numbers stack up in the html page. Should I use a directive instead or is limitTo the solution to dynamically display only one number each time the button is clicked? I looked for other answers, but none really fit my problem. Thanks for any help!

Here is my code so far:

<!DOCTYPE html>

<meta charset="utf-8">
<title>Fibonacci</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">

 {{ result }}

<button type="button" class="reset" ng-click="clear()">RESET</button>
<button type="button" class="next" ng-click="nextNum()">NEXT FIB</button>

My script file:

 var app = angular.module('fib', []);

 app.controller('nextFibCtrl', function($scope,){

 $scope.results = [0, 1];

 $scope.nextNum = function(){

     $scope.currentInt = $scope.results.length -1;

     $scope.nextInt = $scope.results[$scope.currentInt] +

     $scope.results[$scope.currentInt -1];

     $scope.results.push($scope.nextInt);

  }

      $scope.clear = function(){

      $scope.results = [0, 1];

  }

  });

Body:
You don't need ng-repeat. Just initialise and reference nextInt:

<h2>{{nextInt}}
</h2>

In your script:

$scope.nextInt = 1;

Or alternatively, just:

<h2>{{results[results.length - 1]}}</h2>


问:
WCF in WP7 The client and service bindings may be mismatched
I create and tested a WCF service locally and of course it works fine.  I published to a shared hosting site and browsed to the wsdl and appears to be fine.  But when I make a call in WP7 code to the service I get an error with a useless error message.  After enabling includeExceptionDetailInFaults and WCF tracing the error reads. "System.ServiceModel.ProtocolException: Content Type application/soap+xml; charset=utf-8 was sent to a service expecting text/xml; charset=utf-8.  The client and service bindings may be mismatched."

Here are parts of the web.config ...

```<code><behaviors>
  <serviceBehaviors>
    <behavior name="SL_SeeYaThere_WCF.Web.SeeYaThereWCFBehavior">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug httpHelpPageEnabled ="true" includeExceptionDetailInFaults="true"  />
    </behavior>
    <!—- other services… -->
  </serviceBehaviors>
</behaviors>

<bindings>
   <basicHttpBinding>
     <!—- there is not a binding for this service should there be? -->
     <!—- other services… -->
   </basicHttpBinding>
</bindings>
</code>```

< services>

    < service behaviorConfiguration="SL_SeeYaThere_WCF.Web.SeeYaThereWCFBehavior" name="SL_SeeYaThere_WCF.Web.SeeYaThereWCF">

     < endpoint address="" binding="basicHttpBinding" contract="SL_SeeYaThere_WCF.Web.ISeeYaThereWCF" />

     < endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

    < /service>

    < !—- other services… -->

  < /services>

^^ appoligize about the format. editor would not display markup correctly.

This is my first experience with WFC and it hasn’t been enjoyable.  What am I doing wrong?

Thanks for your help.

答:
Ok found the problem.  In the WP7 app there  is a ServicesReferences.clientConfig file that has the client bindings.  There were two end points for the WCF service one for Localhost and one for the shared hosted address.  It must have happened when I 'configure service reference' from the local host to shared host site.

I changed the local host adderss to shared hosted addresss and it works.

Body:
I create and tested a WCF service locally and of course it works fine.  I published to a shared hosting site and browsed to the wsdl and appears to be fine.  But when I make a call in WP7 code to the service I get an error with a useless error message.  After enabling includeExceptionDetailInFaults and WCF tracing the error reads. "System.ServiceModel.ProtocolException: Content Type application/soap+xml; charset=utf-8 was sent to a service expecting text/xml; charset=utf-8.  The client and service bindings may be mismatched."

Here are parts of the web.config ...

<behaviors>
  <serviceBehaviors>
    <behavior name="SL_SeeYaThere_WCF.Web.SeeYaThereWCFBehavior">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug httpHelpPageEnabled ="true" includeExceptionDetailInFaults="true"  />
    </behavior>
    <!—- other services… -->
  </serviceBehaviors>
</behaviors>

<bindings>
   <basicHttpBinding>
     <!—- there is not a binding for this service should there be? -->
     <!—- other services… -->
   </basicHttpBinding>
</bindings>

< services>

    < service behaviorConfiguration="SL_SeeYaThere_WCF.Web.SeeYaThereWCFBehavior" name="SL_SeeYaThere_WCF.Web.SeeYaThereWCF">

     < endpoint address="" binding="basicHttpBinding" contract="SL_SeeYaThere_WCF.Web.ISeeYaThereWCF" />

     < endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

    < /service>

    < !—- other services… -->

  < /services>

^^ appoligize about the format. editor would not display markup correctly.

This is my first experience with WFC and it hasn’t been enjoyable.  What am I doing wrong?

Thanks for your help.


答:
```<code>if 'businesses' in response_data:
   for SQL_element in response_data['businesses']:
       …
</code>```

Title: Python: parse JSON in loop


问:
find the closest next hour
how can I find the next closest hour in php

so for example if current time is 4:15 the next hour will be 5, etc

```<code>$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
echo $date->format( 'H:i:s' );
</code>```

gives me the time from the string and I want to expand on that and get the next closest hour

答:
Here we go:</p>

```<code><?php
    echo date("H:00",strtotime($date. " + 1hour "));
?>
</code>```

Title: find the closest next hour

Body:
how can I find the next closest hour in php

so for example if current time is 4:15 the next hour will be 5, etc

$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
echo $date->format( 'H:i:s' );

gives me the time from the string and I want to expand on that and get the next closest hour

Body:
Here we go:

<?php
    echo date("H:00",strtotime($date. " + 1hour "));
?>

ContentLicense: CC BY-SA 4.0


问:
Wait for a coroutine to finish before moving on with the function C# Unity
I was working on making a unit move through a grid in Unity2d. I got the movement to work without problems.
I would want the function MovePlayer to wait until the coroutine is finished before moving on, so the program will wait until the player has finished the movement before issuing more orders.

Here is my code:
public class Player : MonoBehaviour {

```<code>public Vector3 position;
private Vector3 targetPosition;

private float speed;

void Awake ()
{
    speed = 2.0f;
    position = gameObject.transform.position;
    targetPosition = position;
    GameManager.instance.AddPlayerToList(this);                     //Register this player with our instance of GameManager by adding it to a list of Player objects.
}

//Function that moves the player, takes a list of nodes as path
public void MovePlayer(List<Node> path)
{
    StartCoroutine(SmoothMovement(path));
    //Next step should wait until SmoothMovement is finished
}

private IEnumerator SmoothMovement(List<Node> path)
{
    float step = speed * Time.deltaTime;

    for (int i = 0; i < path.Count; i++)
    {
        targetPosition = new Vector3(path[i].coordinatesX, path[i].coordinatesY, 0f);

        float sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;

        while (sqrRemainingDistance > float.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
            sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;
            yield return null;
        }

        position = transform.position;
    }

}
</code>```

答:
You can not wait for a coroutine in a function in the main thread, otherwise your game will freeze until your function ends.

Why don't you call your next step at the end of your coroutine?

```<code>private IEnumerator SmoothMovement(List<Node> path)
{
    float step = speed * Time.deltaTime;

    for (int i = 0; i < path.Count; i++)
    {
        targetPosition = new Vector3(path[i].coordinatesX, path[i].coordinatesY, 0f);

        float sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;

        while (sqrRemainingDistance > float.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
            sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;
            yield return null;
        }

        position = transform.position;
    }
    //Next Step
}
</code>```

Body:
I was working on making a unit move through a grid in Unity2d. I got the movement to work without problems.
I would want the function MovePlayer to wait until the coroutine is finished before moving on, so the program will wait until the player has finished the movement before issuing more orders.

Here is my code:
public class Player : MonoBehaviour {

public Vector3 position;
private Vector3 targetPosition;

private float speed;

void Awake ()
{
    speed = 2.0f;
    position = gameObject.transform.position;
    targetPosition = position;
    GameManager.instance.AddPlayerToList(this);                     //Register this player with our instance of GameManager by adding it to a list of Player objects.
}

//Function that moves the player, takes a list of nodes as path
public void MovePlayer(List<Node> path)
{
    StartCoroutine(SmoothMovement(path));
    //Next step should wait until SmoothMovement is finished
}

private IEnumerator SmoothMovement(List<Node> path)
{
    float step = speed * Time.deltaTime;

    for (int i = 0; i < path.Count; i++)
    {
        targetPosition = new Vector3(path[i].coordinatesX, path[i].coordinatesY, 0f);

        float sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;

        while (sqrRemainingDistance > float.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
            sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;
            yield return null;
        }

        position = transform.position;
    }

}

Body:
You can not wait for a coroutine in a function in the main thread, otherwise your game will freeze until your function ends.

Why don't you call your next step at the end of your coroutine?

private IEnumerator SmoothMovement(List<Node> path)
{
    float step = speed * Time.deltaTime;

    for (int i = 0; i < path.Count; i++)
    {
        targetPosition = new Vector3(path[i].coordinatesX, path[i].coordinatesY, 0f);

        float sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;

        while (sqrRemainingDistance > float.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
            sqrRemainingDistance = (transform.position - targetPosition).sqrMagnitude;
            yield return null;
        }

        position = transform.position;
    }
    //Next Step
}


问:
Adding Boost Library to a C++ project in OS X Eclipse
I am have been attempting to get a C++ project setup using boost file system library using eclipse. I followed these directions to install boost on my system. The directions where pretty much

download

extract

run bootstrap.sh

run ./bjam architecture=combined

That seemed to go fine, no errors. I then fired up eclipse and created a new test project called test with a single file called test.cpp. The code in it is:

```<code>#include <stdio.h>
#include <boost/filesystem.hpp>

int main() {
    boost::filesystem::path path("/Users/schoen"); // random pathname
    bool result = boost::filesystem::is_directory(path);
    printf("Path is a directory : %d\n", result);
    return 0;
}
</code>```

This is just something simple to make sure it is all set up correctly. Of course I tried to compile at this point and it failed. Did some googling and found this site. It said to add the boost library to the linker by going to project properties and adding "boost_filesystem". I tried this, and well it didn't work.

Can someone point me in the right direction or give me a hint to how to set up Boost in an Eclipse project?

I am new to C++ and Eclipse, and most my experience is in Java with Netbeans. So I am pretty lost at the moment.

UPDATE

I just wanted to update on what I have tried based on the answers given.

Based on Alex's suggestion I added boost_system and boost_filesystem to the linker list. I was still getting the same compiler errors.

Following the suggestion from rve I added the path to the boost libraries to the Library search path. When this did not work. I cleared out the linker list and tried it with just the library search path. This also did not work.

I then cleared the Library search path. I then manually edited the command on the linker window to be 'g++ -L/Users/jacobschoen/Library/boost_1_45_0/stage/lib -lboost -lboost_filesystem'. This also did not work.

In all of these I tried setting the path to boost to be '/Users/jacobschoen/Library/boost_1_45_0' and '/Users/jacobschoen/Library/boost_1_45_0/stage/lib'. Neither worked.

As requested the comiler error for the above code is:

```<code>**** Build of configuration Debug for project test ****

make all
Building file: ../src/test.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/test.d" -MT"src/test.d" -o"src/test.o" "../src/test.cpp"
../src/test.cpp:10:32: warning: boost/filesystem.hpp: No such file or directory
../src/test.cpp: In function 'int main()':
../src/test.cpp:13: error: 'boost' has not been declared
../src/test.cpp:13: error: expected `;' before 'path'
../src/test.cpp:14: error: 'boost' has not been declared
../src/test.cpp:14: error: 'path' was not declared in this scope
make: *** [src/test.o] Error 1
</code>```

If any one has any further suggestions I am still trying.

Second Update
On a suggestion by rholmes I added an include library along with the linker list and library search path. So now the compile error is:

```<code>**** Build of configuration Debug for project test ****

make all
Building target: test
Invoking: MacOS X C++ Linker
g++ -L/Users/jacobschoen/Library/boost_1_45_0 -o "test"  ./src/test.o   -lboost_system -lboost_filesystem
ld: library not found for -lboost_system
collect2: ld returned 1 exit status
make: *** [test] Error 1
</code>```

Any ideas?

答:
I had recently uninstalled the boost rpm and installed Boost like how you did. I had no problems running Boost programs in Eclipse. I didn't add any extra parameters. Just installed boost and ran Boost programs. It works fine.

Tried your program in the vi editor. Commented out everything in main

```<code>#include <cstdio>
#include <boost/filesystem.hpp>

int main() {
    /*boost::filesystem::path path("/Users/schoen"); // random pathname
    bool result = boost::filesystem::is_directory(path);
    printf("Path is a directory : %d\n", result);*/
    return 0;
}
</code>```

and it still gave this error:

```<code>/tmp/cc7TAIYS.o: In function `__static_initialization_and_destruction_0(int, int)':
test.cpp:(.text+0x29): undefined reference to `boost::system::get_system_category()'
test.cpp:(.text+0x35): undefined reference to `boost::system::get_generic_category()'
test.cpp:(.text+0x41): undefined reference to `boost::system::get_generic_category()'
test.cpp:(.text+0x4d): undefined reference to `boost::system::get_generic_category()'
test.cpp:(.text+0x59): undefined reference to `boost::system::get_system_category()'
collect2: ld returned 1 exit status
</code>```

I'm puzzled. Boost programs work on my system, but your program's header files itself are giving a problem. I doubt it's a problem with Eclipse. It has to be something else.

Body:
I am have been attempting to get a C++ project setup using boost file system library using eclipse. I followed these directions to install boost on my system. The directions where pretty much

download

extract

run bootstrap.sh

run ./bjam architecture=combined

That seemed to go fine, no errors. I then fired up eclipse and created a new test project called test with a single file called test.cpp. The code in it is:

#include <stdio.h>
#include <boost/filesystem.hpp>

int main() {
    boost::filesystem::path path("/Users/schoen"); // random pathname
    bool result = boost::filesystem::is_directory(path);
    printf("Path is a directory : %d\n", result);
    return 0;
}

This is just something simple to make sure it is all set up correctly. Of course I tried to compile at this point and it failed. Did some googling and found this site. It said to add the boost library to the linker by going to project properties and adding "boost_filesystem". I tried this, and well it didn't work.

Can someone point me in the right direction or give me a hint to how to set up Boost in an Eclipse project?

I am new to C++ and Eclipse, and most my experience is in Java with Netbeans. So I am pretty lost at the moment.

UPDATE

I just wanted to update on what I have tried based on the answers given.

Based on Alex's suggestion I added boost_system and boost_filesystem to the linker list. I was still getting the same compiler errors.

Following the suggestion from rve I added the path to the boost libraries to the Library search path. When this did not work. I cleared out the linker list and tried it with just the library search path. This also did not work.

I then cleared the Library search path. I then manually edited the command on the linker window to be 'g++ -L/Users/jacobschoen/Library/boost_1_45_0/stage/lib -lboost -lboost_filesystem'. This also did not work.

In all of these I tried setting the path to boost to be '/Users/jacobschoen/Library/boost_1_45_0' and '/Users/jacobschoen/Library/boost_1_45_0/stage/lib'. Neither worked.

As requested the comiler error for the above code is:

**** Build of configuration Debug for project test ****

make all
Building file: ../src/test.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/test.d" -MT"src/test.d" -o"src/test.o" "../src/test.cpp"
../src/test.cpp:10:32: warning: boost/filesystem.hpp: No such file or directory
../src/test.cpp: In function 'int main()':
../src/test.cpp:13: error: 'boost' has not been declared
../src/test.cpp:13: error: expected `;' before 'path'
../src/test.cpp:14: error: 'boost' has not been declared
../src/test.cpp:14: error: 'path' was not declared in this scope
make: *** [src/test.o] Error 1

If any one has any further suggestions I am still trying.

Second Update
On a suggestion by rholmes I added an include library along with the linker list and library search path. So now the compile error is:

**** Build of configuration Debug for project test ****

make all
Building target: test
Invoking: MacOS X C++ Linker
g++ -L/Users/jacobschoen/Library/boost_1_45_0 -o "test"  ./src/test.o   -lboost_system -lboost_filesystem
ld: library not found for -lboost_system
collect2: ld returned 1 exit status
make: *** [test] Error 1

Any ideas?

Body:
I had recently uninstalled the boost rpm and installed Boost like how you did. I had no problems running Boost programs in Eclipse. I didn't add any extra parameters. Just installed boost and ran Boost programs. It works fine.

Tried your program in the vi editor. Commented out everything in main

#include <cstdio>
#include <boost/filesystem.hpp>

int main() {
    /*boost::filesystem::path path("/Users/schoen"); // random pathname
    bool result = boost::filesystem::is_directory(path);
    printf("Path is a directory : %d\n", result);*/
    return 0;
}

and it still gave this error:

/tmp/cc7TAIYS.o: In function `__static_initialization_and_destruction_0(int, int)':
test.cpp:(.text+0x29): undefined reference to `boost::system::get_system_category()'
test.cpp:(.text+0x35): undefined reference to `boost::system::get_generic_category()'
test.cpp:(.text+0x41): undefined reference to `boost::system::get_generic_category()'
test.cpp:(.text+0x4d): undefined reference to `boost::system::get_generic_category()'
test.cpp:(.text+0x59): undefined reference to `boost::system::get_system_category()'
collect2: ld returned 1 exit status

I'm puzzled. Boost programs work on my system, but your program's header files itself are giving a problem. I doubt it's a problem with Eclipse. It has to be something else.


问:
css percentage based background
How can I show a div with some text (which fills the div completely in width) and then show a background color which is only 40%, without obstructing the text.

The following is problematic because the text is within the inner div. I want it in the outer div so to speak.

This is a much longer text and takes up a lot of space

```

答:
You can use gradiant background .

```<code>background:linear-gradient(90deg, #EAFEE2 40%, #FFFFFF 50%)
</code>```

check this link for More information: CSS: Set a background color which is 50% of the width of the window

Title: css percentage based background

Body:
You can use gradiant background .

background:linear-gradient(90deg, #EAFEE2 40%, #FFFFFF 50%)

check this link for More information: CSS: Set a background color which is 50% of the width of the window


问:
Using Extract Text Plugin with Webpack
I'm trying to learn how to use Extract Text Plugin and I found this example:

```<code>var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry:  './src',
  output: {
    path: 'build',
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.js/,
        loader: 'babel',
        include: __dirname + '/src',
      },
      {
        test: /\.css/,
        loader: ExtractTextPlugin.extract("css")
      }
    ],
  },
  plugins: [
    new ExtractTextPlugin("styles.css")
  ]
};
</code>```

Why is the "css" used as a loader ? I tried to look at the docs but still can't understand this.

Thank you all in advance for your helps.

答:
The extractTextPlugin can work with sass, less postcss etc so its asking plugin to only look for css. thats why you are using css there.

```<code>extractCSS.extract([ 'css-loader', 'postcss-loader' ])

extractLESS.extract([ 'css-loader', 'less-loader' ])
</code>```

Title: Using Extract Text Plugin with Webpack

Body:
I'm trying to learn how to use Extract Text Plugin and I found this example:

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry:  './src',
  output: {
    path: 'build',
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.js/,
        loader: 'babel',
        include: __dirname + '/src',
      },
      {
        test: /\.css/,
        loader: ExtractTextPlugin.extract("css")
      }
    ],
  },
  plugins: [
    new ExtractTextPlugin("styles.css")
  ]
};

Why is the "css" used as a loader ? I tried to look at the docs but still can't understand this.

Thank you all in advance for your helps.

Body:
The extractTextPlugin can work with sass, less postcss etc so its asking plugin to only look for css. thats why you are using css there.

extractCSS.extract([ 'css-loader', 'postcss-loader' ])

extractLESS.extract([ 'css-loader', 'less-loader' ])


问:
R histogram, find range of x-values by y-value (frequencies)
I have a list of values. With that I am actually not plotting a histogram, but returning a list of breaks and counts:

```<code>hist(loc$position, breaks=100000, plot=F)
</code>```

Now I am trying to get the range of x-values, that are taken together into one bin. I am only interested in the bin with the maximum frequency. I therefore create

```<code>x <- hist(loc$position, breaks=100000, plot=F)
</code>```

Now I am using that to return the middle of the bin as x-values with the max. frequency:

```<code>x$mids[which.max(list_histo$counts)]
</code>```

But how do I get the full range of that one bin?

答:
```<code>hist_data <- hist(loc$position, breaks=100000, plot=F)

c(hist_data$breaks[which.max(hist_data$counts)],
  hist_data$breaks[which.max(hist_data$counts)+1])
</code>```

This way you will get a vector with the begin and end values of the bin with most elements.

Body:
I have a list of values. With that I am actually not plotting a histogram, but returning a list of breaks and counts:

hist(loc$position, breaks=100000, plot=F)

Now I am trying to get the range of x-values, that are taken together into one bin. I am only interested in the bin with the maximum frequency. I therefore create

x <- hist(loc$position, breaks=100000, plot=F)

Now I am using that to return the middle of the bin as x-values with the max. frequency:

x$mids[which.max(list_histo$counts)]

But how do I get the full range of that one bin?

Body:
hist_data <- hist(loc$position, breaks=100000, plot=F)

c(hist_data$breaks[which.max(hist_data$counts)],
  hist_data$breaks[which.max(hist_data$counts)+1])

This way you will get a vector with the begin and end values of the bin with most elements.


问:
How to get first and last day of the current week in JavaScript
I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?

答:
The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.</p>

```<code>    let startOfWeek = moment().startOf("isoWeek").toDate();
    let endOfWeek = moment().endOf("isoWeek").toDate();
</code>```

Body:
The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.

    let startOfWeek = moment().startOf("isoWeek").toDate();
    let endOfWeek = moment().endOf("isoWeek").toDate();


问:
angularjs nvd3 dispatch chart event won't trigger $onChanges()
How do I get angularjs nvd3 dispatch.elementMouseover to trigger $onChanges() in a child component

.

.

Parent Component Controller (StatsComponent)

```<code>class StatsController {

  constructor( $q, PlayerService, PointService ) {
    'ngInject';
    this.$q = $q;
    this.PlayerService = PlayerService;
    this.PointService = PointService;
  }

  $onInit() {

    const P_players = this.PlayerService.getAllPlayer();
    const P_points = this.PointService.getPointLeader();

    this.pointChartOptions = this.setChartOptions();

    this.$q.all([ P_players, P_points ])
      .then(payload => {
        this.pointLeadersVM = this.getLeadersVM(payload[0], payload[1]);
        this.selectedPointLeader = this.pointLeadersVM[0];
        this.pointData = this.getPointData(payload[1]);
        this.setPointChartMouseOver(this.pointLeadersVM);
      });
  }

  setChartOptions() {
    return {
      chart: {
        type: 'multiBarHorizontalChart',
        height: 300,
        x: function (d) { return d.label; },
        y: function (d) { return d.value; },
        duration: 500,
        multibar: {
          dispatch: {
            elementMouseover: function (e) { /* see setPointChartMouseOver method */ }
          }
        },
      }
    }
  }

  setPointChartMouseOver(pointLeaders) {
    this.pointChartOptions.chart.multibar.dispatch.elementMouseover = function(e) { this.selectedPointLeader = pointLeaders[e.index]; };
  }

  getLeadersVM(players, leaders) {
    // get leaders vm code ...
  }

  getPointData(leaders) {
    // chart data code ...
  }

}

export default StatsController;
</code>```

.

.

Parent Component HTML (StatsComponent)

```<code><leader selectedleader="vm.selectedPointLeader"></leader>
<nvd3 options="vm.pointChartOptions" data="vm.pointData"></nvd3>
</code>```

.

.

Child Component (LeaderComponent)

```<code>import controller from './leader.component.controller';
import template from './leader.component.html';
import './leader.component.styl';

const LeaderComponent = {
  bindings: {
    selectedleader: '<'
  },
  template,
  controller,
  controllerAs: 'vm'
}

export default LeaderComponent;
</code>```

.

.

Child Component Controller (LeaderComponent)

```<code>class LeaderComponent {

  $onChanges() {
    console.log('from child component ', this.selectedleader);
  }
}

export default LeaderComponent;
</code>```

答:
Owwww, figured it out!!!

Inject $scope and then call $scope.$apply(). Must also use arrow function.

.

.

Parent Component Controller (StatsComponent)

```<code>class StatsController {

  constructor( $q, $scope, PlayerService, PointService ) {
    'ngInject';
    this.$q = $q;
    this.$scope = $scope;
    this.PlayerService = PlayerService;
    this.PointService = PointService;
  }

  // this.$scope.$apply(fn) passing function arg into $apply()

  setPointChartMouseOver(pointLeaders) {
    this.pointChartOptions.chart.multibar.dispatch.elementMouseover = (e) => {
      this.$scope.$apply(() => this.selectedPointLeader = pointLeaders[e.index]);
    };
  }

  // OR this.$scope.$apply() without passing function arg into $apply()

  setPointChartMouseOver(pointLeaders) {
    this.pointChartOptions.chart.multibar.dispatch.elementMouseover = (e) => {
      this.selectedPointLeader = pointLeaders[e.index];
      this.$scope.$apply();
    };
  }
</code>```

article on $apply()
https://www.sitepoint.com/understanding-angulars-apply-digest/

Body:
How do I get angularjs nvd3 dispatch.elementMouseover to trigger $onChanges() in a child component

.

.

Parent Component Controller (StatsComponent)

class StatsController {

  constructor( $q, PlayerService, PointService ) {
    'ngInject';
    this.$q = $q;
    this.PlayerService = PlayerService;
    this.PointService = PointService;
  }

  $onInit() {

    const P_players = this.PlayerService.getAllPlayer();
    const P_points = this.PointService.getPointLeader();

    this.pointChartOptions = this.setChartOptions();

    this.$q.all([ P_players, P_points ])
      .then(payload => {
        this.pointLeadersVM = this.getLeadersVM(payload[0], payload[1]);
        this.selectedPointLeader = this.pointLeadersVM[0];
        this.pointData = this.getPointData(payload[1]);
        this.setPointChartMouseOver(this.pointLeadersVM);
      });
  }

  setChartOptions() {
    return {
      chart: {
        type: 'multiBarHorizontalChart',
        height: 300,
        x: function (d) { return d.label; },
        y: function (d) { return d.value; },
        duration: 500,
        multibar: {
          dispatch: {
            elementMouseover: function (e) { /* see setPointChartMouseOver method */ }
          }
        },
      }
    }
  }

  setPointChartMouseOver(pointLeaders) {
    this.pointChartOptions.chart.multibar.dispatch.elementMouseover = function(e) { this.selectedPointLeader = pointLeaders[e.index]; };
  }

  getLeadersVM(players, leaders) {
    // get leaders vm code ...
  }

  getPointData(leaders) {
    // chart data code ...
  }

}

export default StatsController;

.

.

Parent Component HTML (StatsComponent)

<leader selectedleader="vm.selectedPointLeader"></leader>
<nvd3 options="vm.pointChartOptions" data="vm.pointData"></nvd3>

.

.

Child Component (LeaderComponent)

import controller from './leader.component.controller';
import template from './leader.component.html';
import './leader.component.styl';

const LeaderComponent = {
  bindings: {
    selectedleader: '<'
  },
  template,
  controller,
  controllerAs: 'vm'
}

export default LeaderComponent;

.

.

Child Component Controller (LeaderComponent)

class LeaderComponent {

  $onChanges() {
    console.log('from child component ', this.selectedleader);
  }
}

export default LeaderComponent;

Body:
Owwww, figured it out!!!

Inject $scope and then call $scope.$apply(). Must also use arrow function.

.

.

Parent Component Controller (StatsComponent)

class StatsController {

  constructor( $q, $scope, PlayerService, PointService ) {
    'ngInject';
    this.$q = $q;
    this.$scope = $scope;
    this.PlayerService = PlayerService;
    this.PointService = PointService;
  }

  // this.$scope.$apply(fn) passing function arg into $apply()

  setPointChartMouseOver(pointLeaders) {
    this.pointChartOptions.chart.multibar.dispatch.elementMouseover = (e) => {
      this.$scope.$apply(() => this.selectedPointLeader = pointLeaders[e.index]);
    };
  }

  // OR this.$scope.$apply() without passing function arg into $apply()

  setPointChartMouseOver(pointLeaders) {
    this.pointChartOptions.chart.multibar.dispatch.elementMouseover = (e) => {
      this.selectedPointLeader = pointLeaders[e.index];
      this.$scope.$apply();
    };
  }

article on $apply()
https://www.sitepoint.com/understanding-angulars-apply-digest/


问:
Syntax error: PHP brackets issue for IF and FOREACH?
```<code><?php if (count($errors) > 0): ?>
  <div class="error">
     <?php foreach ($errors as $error) ?>
     <p><?php echo $error; ?></p>
  <?php endforeach ?>
  </div>
<?php endif ?>
</code>```

My apologies if this is obvious to some of you more experienced PHP developers, but my code has the following errors;

ForEach must uses braces

Unexpected endforeach after string

I know that these { braces should inserted somewhere, but I'm not sure where and in what order? Also, what do I need to do after the string in question?

Any help would be much appreciated. Thanks.

答:
If you're using alternative syntax, you need to add a colon : after the foreach

```<code>foreach ($errors as $error):
                          ^^^
</code>```

Alternatively, you can use brackets {} (which I personally find easier to read):

```<code><?php foreach ($errors as $error) { ?>
     <p><?php echo $error; ?></p>
<?php } ?>
</code>```

And there's no reason to go in and out of PHP like that, you might as well do it all in one go, using double-quotes we can still pass variables by value, so we don't need to concat your HTML to the $error variable either.

```<code><?php foreach ($errors as $error):
    echo "<p>$error</p>";
endforeach; ?>
</code>```

http://php.net/manual/en/control-structures.alternative-syntax.php

Body:
<?php if (count($errors) > 0): ?>

     <?php foreach ($errors as $error) ?>

<?php echo $error; ?>

  <?php endforeach ?>

<?php endif ?>

My apologies if this is obvious to some of you more experienced PHP developers, but my code has the following errors;

ForEach must uses braces

Unexpected endforeach after string

I know that these { braces should inserted somewhere, but I'm not sure where and in what order? Also, what do I need to do after the string in question?

Any help would be much appreciated. Thanks.

Body:
If you're using alternative syntax, you need to add a colon : after the foreach

foreach ($errors as $error):
                          ^^^

Alternatively, you can use brackets {} (which I personally find easier to read):

<?php foreach ($errors as $error) { ?>
     <p><?php echo $error; ?></p>
<?php } ?>

And there's no reason to go in and out of PHP like that, you might as well do it all in one go, using double-quotes we can still pass variables by value, so we don't need to concat your HTML to the $error variable either.

<?php foreach ($errors as $error):
    echo "<p>$error</p>";
endforeach; ?>

http://php.net/manual/en/control-structures.alternative-syntax.php


问:
The simplest way for creating 2D matrix in loop
I would like to know how to create matrix from vector in loop in the simplest possible way. I have for cycle which contains conditions (so i don't know the final shape of the matrix) under which I want to append a vector to matrix (it should be empty at the beginning). I would like to do something like:

```<code>import numpy as np

for i in range(100):
   vector=np.random.random(10)
   condition=np.random.choice([True, False])
   if (condition):
      matrix[i,:]=vector
</code>```

In matlab this is super easy (the written example (in matlab syntax ofc) works perfectly). However python has much more (at least for me) complicated system with arrays and lists. So, if anybody knows the simplest and most correct way how to do this in python, please give an example. Thanks a lot!

答:
You could make matrix a python list and then use .append() to add vector. Then after your loop call np.array(matrix)

```<code>import numpy as np

matrix_as_list = []

for i in range(100):
   vector=np.random.random(10)
   condition=np.random.choice([True, False])
   if (condition):
      matrix_as_list.append(vector)

matrix = np.array(matrix_as_list)
</code>```

I'm not sure about Python, but in MATLAB it would be faster to actually initialise your matrix to be a 100-by-10 matrix and then delete the unnecessary rows afterwards rather than growing the matrix in a loop. Of course, fastest would be to just vectorize the solution to not use a loop at all.

Body:
I would like to know how to create matrix from vector in loop in the simplest possible way. I have for cycle which contains conditions (so i don't know the final shape of the matrix) under which I want to append a vector to matrix (it should be empty at the beginning). I would like to do something like:

import numpy as np

for i in range(100):
   vector=np.random.random(10)
   condition=np.random.choice([True, False])
   if (condition):
      matrix[i,:]=vector

In matlab this is super easy (the written example (in matlab syntax ofc) works perfectly). However python has much more (at least for me) complicated system with arrays and lists. So, if anybody knows the simplest and most correct way how to do this in python, please give an example. Thanks a lot!

Body:
You could make matrix a python list and then use .append() to add vector. Then after your loop call np.array(matrix)

import numpy as np

matrix_as_list = []

for i in range(100):
   vector=np.random.random(10)
   condition=np.random.choice([True, False])
   if (condition):
      matrix_as_list.append(vector)

matrix = np.array(matrix_as_list)

I'm not sure about Python, but in MATLAB it would be faster to actually initialise your matrix to be a 100-by-10 matrix and then delete the unnecessary rows afterwards rather than growing the matrix in a loop. Of course, fastest would be to just vectorize the solution to not use a loop at all.


问:
removing default document from current URL
I use the following code to get the URL of current page.

```<code>thispage ="http://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("URL") & "?" & Request.Querystring
</code>```

I want to check if user has typed the default document (index.asp) at the end of URL and remove it (by redirecting to the clean URL without default document in address bar).

But this code always contains the default document even when if not typed in address bar e.g. the code above returns http://example.com/index.asp when I have http://example.com in address bar.

How do I edit the above code to distinguish those URLs?

答:
It's a complicated task in an environment where you don't know what the applicable default document is but I think it's always index.asp in your case.

If so, you can do it with something like the following.

```<code>defaultFile = "/index.asp" ' leading slash is mandatory
reqUrl = Request.ServerVariables("URL")
reqQS = Request.ServerVariables("QUERY_STRING")

'put a leading question mark if there's a query
If reqQS <> "" Then
    reqQS = "?" & reqQS
End If

'check if URL ends with "/index.asp" (case-insensitive comparison should be made)
If StrComp(Right(reqUrl, Len(defaultFile)), defaultFile, vbTextCompare) = 0 Then
    ' remove from reqUrl by preserving leading slash
    reqUrl = Left(reqUrl, Len(reqUrl) - Len(defaultFile) + 1)
End If

thispage = "http://" & Request.ServerVariables("SERVER_NAME") & reqUrl & reqQS
</code>```

Body:
I use the following code to get the URL of current page.

thispage ="http://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("URL") & "?" & Request.Querystring

I want to check if user has typed the default document (index.asp) at the end of URL and remove it (by redirecting to the clean URL without default document in address bar).

But this code always contains the default document even when if not typed in address bar e.g. the code above returns http://example.com/index.asp when I have http://example.com in address bar.

How do I edit the above code to distinguish those URLs?

Body:
It's a complicated task in an environment where you don't know what the applicable default document is but I think it's always index.asp in your case.

If so, you can do it with something like the following.

defaultFile = "/index.asp" ' leading slash is mandatory
reqUrl = Request.ServerVariables("URL")
reqQS = Request.ServerVariables("QUERY_STRING")

'put a leading question mark if there's a query
If reqQS <> "" Then
    reqQS = "?" & reqQS
End If

'check if URL ends with "/index.asp" (case-insensitive comparison should be made)
If StrComp(Right(reqUrl, Len(defaultFile)), defaultFile, vbTextCompare) = 0 Then
    ' remove from reqUrl by preserving leading slash
    reqUrl = Left(reqUrl, Len(reqUrl) - Len(defaultFile) + 1)
End If

thispage = "http://" & Request.ServerVariables("SERVER_NAME") & reqUrl & reqQS


问:
Displaying a to a List from a private void method
I just started developing in Winforms and I'm developing a simple recipe app that allows the user to create a recipe, submit all the details about the recipe, those details will be passed back to a ListBox on the Main form so the user can access that recipe again later. My problem is right now is when I'm finished setting up the recipe to submit, I don't know how to transfer the information back to the ListBox to be stored. I know this has to be a simple answer and I appreciate the help.

Main form code:

```<code>public partial class Main : Form
{
    // Creat the recipeList here and make it public
    public static List<Recipe> recipeList = new List<Recipe>();

    public Main()
    {
        InitializeComponent();
    }

    private void newRecipeButton_Click(object sender, EventArgs e)
    {
        // When the new recipe button is clicked, create a new AddNewRecipeForm object that passed the recipeList.
        var newForm = new AddNewRecipeForm(recipeList);
        newForm.Show();
    }

    private void recipeListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        // List the New Recipe in the listbox.
    }
}
</code>```

Second form code:

```<code>public partial class AddNewRecipeForm : Form
{
    // Create a private recipeList
    private List<Recipe> recipeList = new List<Recipe>();

    // Once AddNewRecipe is create, it uses the recipeList as the parameters.
    public AddNewRecipeForm(List<Recipe> recipeList)
    {
        InitializeComponent();
    }

    private void submitRecipeButton_Click(object sender, EventArgs e)
    {
        // Create a newRecipe object.
        Recipe newRecipe = new Recipe();

        // Add each entry made in the textboxes to newRecipe object.
        newRecipe.Name = nameTextBox.Text;
        newRecipe.Time = Convert.ToInt32(timeTextBox.Text);
        newRecipe.Servings = Convert.ToInt32(servingsTextBox.Text);
        newRecipe.Directions = directionsTextBox.Text;
        newRecipe.Ingredients = ingredientsTextBox.Text;

        // Add the newRecipe object to the recipeList.
        recipeList.Add(newRecipe);

        // Close the window.
        this.Close();
    }
}
</code>```

答:
Use a  BindingList instead of a list. Whenever you add items to it, it will notify your lisbox and the listbox will update itself. Make sure you import using System.ComponentModel;:

```<code>private BindingList<Recipe> recipeList = new BindingList<Recipe>();
</code>```

Set the DataSource of the ListBox to the recipeList like this:

```<code>this.recipeListBox.DataSource = items;
// Instruct the listbox to display the Name or any property
this.recipeListBox.DisplayMember = "Name";
// Optionally instruct the listbox that the ValueMember is Name
// If you use SelectedValue, it will return the value from this property
this.recipeListBox.ValueMember = "Name";
</code>```

Body:
I just started developing in Winforms and I'm developing a simple recipe app that allows the user to create a recipe, submit all the details about the recipe, those details will be passed back to a ListBox on the Main form so the user can access that recipe again later. My problem is right now is when I'm finished setting up the recipe to submit, I don't know how to transfer the information back to the ListBox to be stored. I know this has to be a simple answer and I appreciate the help.

Main form code:

public partial class Main : Form
{
    // Creat the recipeList here and make it public
    public static List<Recipe> recipeList = new List<Recipe>();

    public Main()
    {
        InitializeComponent();
    }

    private void newRecipeButton_Click(object sender, EventArgs e)
    {
        // When the new recipe button is clicked, create a new AddNewRecipeForm object that passed the recipeList.
        var newForm = new AddNewRecipeForm(recipeList);
        newForm.Show();
    }

    private void recipeListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        // List the New Recipe in the listbox.
    }
}

Second form code:

public partial class AddNewRecipeForm : Form
{
    // Create a private recipeList
    private List<Recipe> recipeList = new List<Recipe>();

    // Once AddNewRecipe is create, it uses the recipeList as the parameters.
    public AddNewRecipeForm(List<Recipe> recipeList)
    {
        InitializeComponent();
    }

    private void submitRecipeButton_Click(object sender, EventArgs e)
    {
        // Create a newRecipe object.
        Recipe newRecipe = new Recipe();

        // Add each entry made in the textboxes to newRecipe object.
        newRecipe.Name = nameTextBox.Text;
        newRecipe.Time = Convert.ToInt32(timeTextBox.Text);
        newRecipe.Servings = Convert.ToInt32(servingsTextBox.Text);
        newRecipe.Directions = directionsTextBox.Text;
        newRecipe.Ingredients = ingredientsTextBox.Text;

        // Add the newRecipe object to the recipeList.
        recipeList.Add(newRecipe);

        // Close the window.
        this.Close();
    }
}

Body:
Use a  BindingList instead of a list. Whenever you add items to it, it will notify your lisbox and the listbox will update itself. Make sure you import using System.ComponentModel;:

private BindingList<Recipe> recipeList = new BindingList<Recipe>();

Set the DataSource of the ListBox to the recipeList like this:

this.recipeListBox.DataSource = items;
// Instruct the listbox to display the Name or any property
this.recipeListBox.DisplayMember = "Name";
// Optionally instruct the listbox that the ValueMember is Name
// If you use SelectedValue, it will return the value from this property
this.recipeListBox.ValueMember = "Name";


问:
Java Generic Inheritance / Generic Comparable
Say that I have a function that does things with a list of shapes.  I can define a few useful classes:

```<code>public abstract class Shape implements Comparable<Shape> { }

public abstract class FourSidedShapes extends Shape { }

public class Rectangle extends FourSidedShapes{
   ...
   @Override
   public int compareTo(Shape o) {
    return 0;
   }
}

public class Square extends FourSidedShapes {... }
</code>```

I have a helper container:

```<code>//Implements doubly-linked sorted list
public class SortedLinkedListNode<T extends Shape> {
   public SortedLinkedListNode<T> add(T e) { }
   public <E extends Shape> T get(E target) { }
   ...
}
</code>```

I would like to do something like this:TreeSet<FourSidedShapes> myshapes;

If I do that, I have two problems.  First, I want to keep the SortedLinkedList helper collection as generic as possible.  So I would like to write the implementation assuming that it will hold Shape or some subclass of shape (including objects that have not been considered / implemented such as circles / triangles, etc.  But if I do that, then I have to implement public int compareTo(Shape o) for both rectangle and square even though I really only want to implement public int compareTo(FourSidedShapes o) because I'm really only storing subclasses of FourSidedShapes in my collection.  So my question is, how do I modify my SortedLinkedListNode so that it extends a compareTo that is no lower than the base class that it is storing?  For example, if I am storing shapes, then it expects shapes to implement Comparable<Shapes>.  If I'm storing FourSidedShapes, then it expects FourSidedShapes to implement Comparable<FourSidedShapes>.  I suspect that the right answer involves making the parameter of Comparable generic, but I'm not sure what that look like.  For example, something like

```<code>public class ShapeComparable<T extends Comparable<T>> {
   public abstract int compareTo(T other);
}
</code>```

答:
I am not completely clear on your question but I am assuming that you are asking how to make Rectangle or FourSidedShapes implement Comparable<FourSidedShapes>.
Here is the code showing how to do that:

```<code>public abstract class Shape< T extends Shape<T> > implements Comparable<T> { }

public abstract class FourSidedShapes extends Shape<FourSidedShapes> {

    @Override
    public int compareTo(FourSidedShapes o) {
        return 0;
    }
}

public class Rectangle extends FourSidedShapes{

    @Override
    public int compareTo(FourSidedShapes o) {
        return 0;
    }

}

public class Square extends FourSidedShapes{

    @Override
    public int compareTo(FourSidedShapes o) {
        return 0;
    }

}
</code>```

Body:
Say that I have a function that does things with a list of shapes.  I can define a few useful classes:

public abstract class Shape implements Comparable<Shape> { }

public abstract class FourSidedShapes extends Shape { }

public class Rectangle extends FourSidedShapes{
   ...
   @Override
   public int compareTo(Shape o) {
    return 0;
   }
}

public class Square extends FourSidedShapes {... }

I have a helper container:

//Implements doubly-linked sorted list
public class SortedLinkedListNode<T extends Shape> {
   public SortedLinkedListNode<T> add(T e) { }
   public <E extends Shape> T get(E target) { }
   ...
}

I would like to do something like this:TreeSet<FourSidedShapes> myshapes;

If I do that, I have two problems.  First, I want to keep the SortedLinkedList helper collection as generic as possible.  So I would like to write the implementation assuming that it will hold Shape or some subclass of shape (including objects that have not been considered / implemented such as circles / triangles, etc.  But if I do that, then I have to implement public int compareTo(Shape o) for both rectangle and square even though I really only want to implement public int compareTo(FourSidedShapes o) because I'm really only storing subclasses of FourSidedShapes in my collection.  So my question is, how do I modify my SortedLinkedListNode so that it extends a compareTo that is no lower than the base class that it is storing?  For example, if I am storing shapes, then it expects shapes to implement Comparable<Shapes>.  If I'm storing FourSidedShapes, then it expects FourSidedShapes to implement Comparable<FourSidedShapes>.  I suspect that the right answer involves making the parameter of Comparable generic, but I'm not sure what that look like.  For example, something like

public class ShapeComparable<T extends Comparable<T>> {
   public abstract int compareTo(T other);
}

Body:
I am not completely clear on your question but I am assuming that you are asking how to make Rectangle or FourSidedShapes implement Comparable<FourSidedShapes>.
Here is the code showing how to do that:

public abstract class Shape< T extends Shape<T> > implements Comparable<T> { }

public abstract class FourSidedShapes extends Shape<FourSidedShapes> {

    @Override
    public int compareTo(FourSidedShapes o) {
        return 0;
    }
}

public class Rectangle extends FourSidedShapes{

    @Override
    public int compareTo(FourSidedShapes o) {
        return 0;
    }

}

public class Square extends FourSidedShapes{

    @Override
    public int compareTo(FourSidedShapes o) {
        return 0;
    }

}


问:
Deleting specific record from Access database on button click
I have a string that contains 9 characters, for example LON052012 (from London 23.05.2012. - day.month.year.). I want to delete all records from table in Access where all cities start with first three letters from that string and have those months and year (05.2007.).

This is the function:

```<code>private void button2_Click(object sender, EventArgs e)
    {
        if (textBox1.Text != "")
        {
            try
            {
                string sTown, s1, s2;
                sTown = textBox1.Text.Substring(0, 3);
                s1 = textBox1.Text.Substring(3, 2);
                s2 = textBox1.Text.Substring(5);

                string sDelete = "DELETE * FROM Country WHERE Town LIKE @p1 and month(TownDate) = @p2 and year(TownDate) = @p3";
                OleDbCommand komDelete = new OleDbCommand(sDelete, connection);
                komDelete.Parameters.AddWithValue("@p1", sTown + "*");
                komDelete.Parameters.AddWithValue("@p2", s1);
                komDelete.Parameters.AddWithValue("@p3", s2);
                connection.Open();
                komDelete.ExecuteNonQuery();
                MessageBox.Show("Deleted");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                connection.Close();
            }
        }
        else
        {
            MessageBox.Show("TextBox is empty!");
        }
    }
</code>```

This is how table Country looks like (CountryID, Town, TownDate):

It always says that the record is deleted even if it's not.

答:
For UPDATE, INSERT, and DELETE statements, the return value of ExecuteNonQuery is the number of rows affected by the command.

So, modify your code as:

```<code>  var n= komDelete.ExecuteNonQuery();
  if (n >0 )
   {
            MessageBox.Show("Deleted");
   }
</code>```

Edit

The problems in the query  are:

The parameter data type s1 , s2 which they are string , and they
should be passed as integer.

Using * and it should be % (access use
%, see my comment)

so, you have to modify the code to be:

```<code>        var p1 = sTown + "%"; // not *
        komDelete.Parameters.AddWithValue("@p1", p1);
        var p2 = int.Parse(s1); //convert to numeric data type
        var p3 = int.Parse(s2);
        komDelete.Parameters.AddWithValue("@p2", p2);
        komDelete.Parameters.AddWithValue("@p3", p3);

      var n= komDelete.ExecuteNonQuery();
     if (n >0 )
     {
            MessageBox.Show("Deleted");
     }
</code>```

I tested that code with access 2007 and 2007 Office System Driver: Data Connectivity Components and it's working fine and deleted the row.

Body:
I have a string that contains 9 characters, for example LON052012 (from London 23.05.2012. - day.month.year.). I want to delete all records from table in Access where all cities start with first three letters from that string and have those months and year (05.2007.).

This is the function:

private void button2_Click(object sender, EventArgs e)
    {
        if (textBox1.Text != "")
        {
            try
            {
                string sTown, s1, s2;
                sTown = textBox1.Text.Substring(0, 3);
                s1 = textBox1.Text.Substring(3, 2);
                s2 = textBox1.Text.Substring(5);

                string sDelete = "DELETE * FROM Country WHERE Town LIKE @p1 and month(TownDate) = @p2 and year(TownDate) = @p3";
                OleDbCommand komDelete = new OleDbCommand(sDelete, connection);
                komDelete.Parameters.AddWithValue("@p1", sTown + "*");
                komDelete.Parameters.AddWithValue("@p2", s1);
                komDelete.Parameters.AddWithValue("@p3", s2);
                connection.Open();
                komDelete.ExecuteNonQuery();
                MessageBox.Show("Deleted");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                connection.Close();
            }
        }
        else
        {
            MessageBox.Show("TextBox is empty!");
        }
    }

This is how table Country looks like (CountryID, Town, TownDate):

It always says that the record is deleted even if it's not.

Body:
For UPDATE, INSERT, and DELETE statements, the return value of ExecuteNonQuery is the number of rows affected by the command.

So, modify your code as:

  var n= komDelete.ExecuteNonQuery();
  if (n >0 )
   {
            MessageBox.Show("Deleted");
   }

Edit

The problems in the query  are:

The parameter data type s1 , s2 which they are string , and they
should be passed as integer.

Using * and it should be % (access use
%, see my comment)

so, you have to modify the code to be:

        var p1 = sTown + "%"; // not *
        komDelete.Parameters.AddWithValue("@p1", p1);
        var p2 = int.Parse(s1); //convert to numeric data type
        var p3 = int.Parse(s2);
        komDelete.Parameters.AddWithValue("@p2", p2);
        komDelete.Parameters.AddWithValue("@p3", p3);

      var n= komDelete.ExecuteNonQuery();
     if (n >0 )
     {
            MessageBox.Show("Deleted");
     }

I tested that code with access 2007 and 2007 Office System Driver: Data Connectivity Components and it's working fine and deleted the row.