问:
iOS 11 MKAnnotationView prepareForReuse dismiss the pin view in Map view
what I want to do is when I deselect an pin, the pin view change it's UI back to unselected state(e.g change color of background of the pin)

```<code>- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
   //do something;

   XLMapItemAnnotation* mapItem = [self annotationForView:view];
   [view prepareForReuse];
}
</code>```

by having this code,  when I run the app in iOS 11, if I deselect a pin, the pin disappear in the map view totally. and if I remove the prepareForReuse, everything would be fine.
and the some code if I run the app in iOS 10, everything is fine, no pin get disappeared.
can sbd give me a hint, what could be wrong?

答:
As @Tim Johnsen said, -prepareForReuse is intended for MKAnnotationView's  reuse mechanism, you should not call it yourself.

In iOS 11, MapKit introduce clustering algorithm for MKAnnotationView(But after some try, I found it cause strange behavior sometimes). In this case, MKAnnotationView.isHidden is set as true by default. So after you invoking -prepareForReuse, MKAnnotationView is hidden.

If you want to change color of the pin, just change pinTintColor property directly, or use a function to reset all properties as needed.

Body:
what I want to do is when I deselect an pin, the pin view change it's UI back to unselected state(e.g change color of background of the pin)

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
   //do something;

   XLMapItemAnnotation* mapItem = [self annotationForView:view];
   [view prepareForReuse];
}

by having this code,  when I run the app in iOS 11, if I deselect a pin, the pin disappear in the map view totally. and if I remove the prepareForReuse, everything would be fine.
and the some code if I run the app in iOS 10, everything is fine, no pin get disappeared.
can sbd give me a hint, what could be wrong?


来源: stackexchange

问:
PHP 7 with phpmyadmin gives lots of Deprecation Notices
I have Ubuntu 16.04 LTS running with PHP7 and phpmyadmin installed.
However, I get a lot of deprecation notices like:

```<code>Deprecation Notice in ./../php/php-gettext/streams.php#48
Methods with the same name as their class will not be constructors in a future version of PHP; StringReader has a deprecated constructor

Backtrace
./../php/php-gettext/gettext.inc#41: require()
./libraries/select_lang.lib.php#477: require_once(./../php/php-gettext/gettext.inc)
./libraries/common.inc.php#569: require(./libraries/select_lang.lib.php)
./index.php#12: require_once(./libraries/common.inc.php)
</code>```

Is this a problem? How can I get rid of these notices (they pop up each time a page is loaded or action is performed)?

答:
Updating the server worked for me with sudo apt-get dist-upgrade and then restarting apache.

I think that this issue is caused by not updating phpmyadmin frequently enough.

ContentLicense: CC BY-SA 3.0

Body:
I have Ubuntu 16.04 LTS running with PHP7 and phpmyadmin installed.
However, I get a lot of deprecation notices like:

Deprecation Notice in ./../php/php-gettext/streams.php#48
Methods with the same name as their class will not be constructors in a future version of PHP; StringReader has a deprecated constructor

Backtrace
./../php/php-gettext/gettext.inc#41: require()
./libraries/select_lang.lib.php#477: require_once(./../php/php-gettext/gettext.inc)
./libraries/common.inc.php#569: require(./libraries/select_lang.lib.php)
./index.php#12: require_once(./libraries/common.inc.php)

Is this a problem? How can I get rid of these notices (they pop up each time a page is loaded or action is performed)?


问:
Create link to sort columns PHP
I need to create links that allow someone to sort the data based on the column header. I was able to get a working model which sorts the data by ID either ASC or DESC. How could I create this same function for more than just the ID column?</p>

```<code><?php
    $order = (isset($_GET['sort']) && strcasecmp($_GET['sort'], 'desc') == 0) ? 'DESC' : 'ASC';
    $query = 'SELECT DISTINCT `case`, firstname, lastname FROM `cases` ORDER BY id ' . $order;
          $result = mysql_query($query);
    ?>

    <td><a href=<?php echo "'?sort=" . ($order == 'DESC' ? 'ASC' : 'DESC') . "'";?>>Case ID</a></td>
    <td>Name</td>

    <?php
    // list records
         while ($nt = mysql_fetch_assoc($result)) {
    ?>

    <td><?php echo $nt['case']; ?></td>
    <td><?php echo $nt['firstname']; ?> <?php echo $nt['lastname']; ?>
</code>```

答: You have to pass the column name or an alias (id, ...) in the URL just like the sorting direction.</p>

ContentLicense: CC BY-SA 2.5

Title: Create link to sort columns PHP

Body:
I need to create links that allow someone to sort the data based on the column header. I was able to get a working model which sorts the data by ID either ASC or DESC. How could I create this same function for more than just the ID column?

<?php
    $order = (isset($_GET['sort']) && strcasecmp($_GET['sort'], 'desc') == 0) ? 'DESC' : 'ASC';
    $query = 'SELECT DISTINCT `case`, firstname, lastname FROM `cases` ORDER BY id ' . $order;
          $result = mysql_query($query);
    ?>

    <a href=<?php echo "'?sort=" . ($order == 'DESC' ? 'ASC' : 'DESC') . "'";?>>Case ID
    Name

    <?php
    // list records
         while ($nt = mysql_fetch_assoc($result)) {
    ?>

    <?php echo $nt['case']; ?>
    <?php echo $nt['firstname']; ?> <?php echo $nt['lastname']; ?>


问:
is there a link between dstream.checkpoint(checkpointInterval) and spark.streaming.receiver.writeAheadLog.enable
As per the spark streaming documentation, dstream which are queued but not processed will be written to checkpoint directory after every checkpointInterval.

but at the same time there is a configuration spark.streaming.receiver.writeAheadLog.enable = true
which as per the spark documentation "all the data received from a receiver gets written into a write ahead log in the configuration checkpoint directory"

what is the difference in each of the options given by spark?

答:
read again the documentation on https://spark.apache.org/docs/2.2.0/streaming-programming-guide.html

"For stateful transformations that require RDD checkpointing, the default interval is a multiple of the batch interval that is at least 10 seconds. It can be set by using dstream.checkpoint(checkpointInterval). Typically, a checkpoint interval of 5 - 10 sliding intervals of a DStream is a good setting to try."

So dstream.checkpoint(checkpointInterval) works for stateful dstreams whereas  writeahead logs will work for all dstreams and it is being set at sparkcontext level.

Now based upon above 2 more Queries
1) If the writeahead logs are enabled then is the dstream.checkpoint(checkpointInterval) statement has any significance?
2) what is link of checkpointinterval with Sliding interval as mentioned in doc

"Typically, a checkpoint interval of 5 - 10 sliding intervals of a DStream is a good setting to try."


问:
excel multiple column vlookup
My table

```<code>Id  index Col1  col2  col3
a    1    smith
a    2           John
b    1    mark
b    2           kay
b    3                 Van
c    1    Par
c    2           Cap
</code>```

In the Vlookup Table

```<code>ID  Col1   Col2  Col3
a   Smith  John
b   Mark   kay   Van
c   Par    Cap
</code>```

How do I achieve by doing vlookup by id

答:
If you want to use vlookup instead of index and match, you could use a helper column:

The formula in cell 1 is:

=B2&C2

The formula in cell H2 is:

=IF(ISERROR(VLOOKUP($H2&RIGHT(I$1,1),$A$2:$C$8,RIGHT(I$1,1),0)),0,VLOOKUP($H2&RIGHT(I$1,1),$A$1:$F$8,RIGHT(I$1,1)+3,0))

To make the formula be the same in all cells in the output table, I have used the rightmost character in the column name as an index.  Hard coding this value, or adding a helper row, would make it easier to read.

Title: excel multiple column vlookup

Body:
My table

Id  index Col1  col2  col3
a    1    smith
a    2           John
b    1    mark
b    2           kay
b    3                 Van
c    1    Par
c    2           Cap

In the Vlookup Table

ID  Col1   Col2  Col3
a   Smith  John
b   Mark   kay   Van
c   Par    Cap

How do I achieve by doing vlookup by id


问:
Empty POST on Angular/PHP

I'm new to Angular 4. I've added a simple HTTP POST login & connected it to another, simple, PHP receiver which then connects to the DB to check if the credentials are correct.

Bad Code:

```<code>    login(username: string, password: string){
    var headers = new Headers();
    var creds ='http://localhost/crm/login/login.php';
    headers.append('content-type', 'application/X-www-form=urlencoded');
    return this._http.post(creds, {username: username, password: password}, {headers})
        .map((response: Response) => {
            let user = response.json();
            if(user && user.accid){
                this.isLoggedIn = true;
                this.loginType = user.accid;

                sessionStorage.setItem('accid', JSON.stringify(user.accid));
                sessionStorage.setItem('status', JSON.stringify(user.status));
                sessionStorage.setItem('username', JSON.stringify(user.user));
                sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
                return user;
            }else
                return false;

      });
}
</code>```

The issue is, if I POST, the PHP server does not read any input at all, as if I POSTed nothing.

This is how I "fixed" it, but really this isn't a fix at all. This is basically using GET, except that I format the string itself. Obviously this is a horrible walkaround since now I have to accept GET requests on the PHP body, and the request itself is literally printed out in the browser's console on login.

```<code>login(username: string, password: string){
    var headers = new Headers();
    var creds ='http://localhost/crm/login/login.php?' + 'username=' + username + '&password=' + password;
    headers.append('content-type', 'application/X-www-form=urlencoded');
    return this._http.post(creds, '', {headers})
        .map((response: Response) => {
            let user = response.json();
            if(user && user.accid){
                this.isLoggedIn = true;
                this.loginType = user.accid;

                sessionStorage.setItem('accid', JSON.stringify(user.accid));
                sessionStorage.setItem('status', JSON.stringify(user.status));
                sessionStorage.setItem('username', JSON.stringify(user.user));
                sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
                return user;
            }else
                return false;

      });
}
</code>```

PHP body

```<code><?php
require_once '../config.php';

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

$parmSir = [];
if($_GET)
    foreach($_GET as $gettie)
        $parmSir[] = $gettie;

if($_POST)
    foreach($_POST as $postie)
        $parmSir[] = $postie;

$username = isset($parmSir[0]) ? $parmSir[0] : NULL;
$password = isset($parmSir[1]) ? $parmSir[1] : NULL;

$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = sha1($password, true);
$response = [];
$query = mysqli_query($connection, "SELECT * FROM user_accounts WHERE password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);

if ($rows == 1){
    $query = mysqli_query($connection, "SELECT account_type, employee_ID FROM user_accounts WHERE username ='$username'");
    $row = $query->fetch_assoc();
    $response['status'] = 'loggedin';
    $response['accid'] = $row['account_type'];
    $response['user'] = $username;
    $response['uniqid'] = $row['employee_ID'];
}
else
    $response['status'] = 'error';
echo json_encode($response);
?>
</code>```

Not exactly sure why the PHP isn't recognizing POST/GET requests unless if I format the string in that specific manner. What am I doing wrong?

答:
The solution is to ensure the header's 'content-type' is 'application/json'. Otherwise, _POST and _GET will not read the content as required (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

Other posts have recommended to use $HTTP_RAW_POST_DATA (now deprecated, replaced with php://input which I now use).

Here is how it now looks like:

```<code>    login(username: string, password: string){
    var headers = new Headers();
    var creds ='http://localhost/crm/login/login.php';
    headers.append('content-type', 'application/json');
    return this._http.post(creds, {username: username, password: password}, {headers})
        .map((response: Response) => {
            let user = response.json();
            if(user && user.accid){
                this.isLoggedIn = true;
                this.loginType = user.accid;

                sessionStorage.setItem('accid', JSON.stringify(user.accid));
                sessionStorage.setItem('status', JSON.stringify(user.status));
                sessionStorage.setItem('username', JSON.stringify(user.user));
                sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
                return user;
            }else if(user.status == "error"){
                return false;
            }else
                return false;

      });
}
</code>```

And the .PHP:

```<code><?php
require_once '../config.php';
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
    throw new Exception('Request method must be POST!');
}

$input = json_decode(trim(file_get_contents('php://input')),true);

$username = $input['username'];
$password = $input['password'];

$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = sha1($password, true);
$response = [];
$query = mysqli_query($connection, "SELECT * FROM user_accounts WHERE password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);

if ($rows == 1){
    $query = mysqli_query($connection, "SELECT account_type, employee_ID FROM user_accounts WHERE username ='$username'");
    $row = $query->fetch_assoc();
    $response['status'] = 'loggedin';
    $response['accid'] = $row['account_type'];
    $response['user'] = $username;
    $response['uniqid'] = $row['employee_ID'];
}
else
    $response['status'] = 'error';
echo json_encode($response);
?>
</code>```

Title: Empty POST on Angular/PHP

Body:
I'm new to Angular 4. I've added a simple HTTP POST login & connected it to another, simple, PHP receiver which then connects to the DB to check if the credentials are correct.

Bad Code:

    login(username: string, password: string){
    var headers = new Headers();
    var creds ='http://localhost/crm/login/login.php';
    headers.append('content-type', 'application/X-www-form=urlencoded');
    return this._http.post(creds, {username: username, password: password}, {headers})
        .map((response: Response) => {
            let user = response.json();
            if(user && user.accid){
                this.isLoggedIn = true;
                this.loginType = user.accid;

                sessionStorage.setItem('accid', JSON.stringify(user.accid));
                sessionStorage.setItem('status', JSON.stringify(user.status));
                sessionStorage.setItem('username', JSON.stringify(user.user));
                sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
                return user;
            }else
                return false;

      });
}

The issue is, if I POST, the PHP server does not read any input at all, as if I POSTed nothing.

This is how I "fixed" it, but really this isn't a fix at all. This is basically using GET, except that I format the string itself. Obviously this is a horrible walkaround since now I have to accept GET requests on the PHP body, and the request itself is literally printed out in the browser's console on login.

login(username: string, password: string){
    var headers = new Headers();
    var creds ='http://localhost/crm/login/login.php?' + 'username=' + username + '&password=' + password;
    headers.append('content-type', 'application/X-www-form=urlencoded');
    return this._http.post(creds, '', {headers})
        .map((response: Response) => {
            let user = response.json();
            if(user && user.accid){
                this.isLoggedIn = true;
                this.loginType = user.accid;

                sessionStorage.setItem('accid', JSON.stringify(user.accid));
                sessionStorage.setItem('status', JSON.stringify(user.status));
                sessionStorage.setItem('username', JSON.stringify(user.user));
                sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
                return user;
            }else
                return false;

      });
}

PHP body

<?php
require_once '../config.php';

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

$parmSir = [];
if($_GET)
    foreach($_GET as $gettie)
        $parmSir[] = $gettie;

if($_POST)
    foreach($_POST as $postie)
        $parmSir[] = $postie;

$username = isset($parmSir[0]) ? $parmSir[0] : NULL;
$password = isset($parmSir[1]) ? $parmSir[1] : NULL;

$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = sha1($password, true);
$response = [];
$query = mysqli_query($connection, "SELECT * FROM user_accounts WHERE password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);

if ($rows == 1){
    $query = mysqli_query($connection, "SELECT account_type, employee_ID FROM user_accounts WHERE username ='$username'");
    $row = $query->fetch_assoc();
    $response['status'] = 'loggedin';
    $response['accid'] = $row['account_type'];
    $response['user'] = $username;
    $response['uniqid'] = $row['employee_ID'];
}
else
    $response['status'] = 'error';
echo json_encode($response);
?>

Not exactly sure why the PHP isn't recognizing POST/GET requests unless if I format the string in that specific manner. What am I doing wrong?

Body:
The solution is to ensure the header's 'content-type' is 'application/json'. Otherwise, _POST and _GET will not read the content as required (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type).

Other posts have recommended to use $HTTP_RAW_POST_DATA (now deprecated, replaced with php://input which I now use).

Here is how it now looks like:

    login(username: string, password: string){
    var headers = new Headers();
    var creds ='http://localhost/crm/login/login.php';
    headers.append('content-type', 'application/json');
    return this._http.post(creds, {username: username, password: password}, {headers})
        .map((response: Response) => {
            let user = response.json();
            if(user && user.accid){
                this.isLoggedIn = true;
                this.loginType = user.accid;

                sessionStorage.setItem('accid', JSON.stringify(user.accid));
                sessionStorage.setItem('status', JSON.stringify(user.status));
                sessionStorage.setItem('username', JSON.stringify(user.user));
                sessionStorage.setItem('uniqid', JSON.stringify(user.uniqid));
                return user;
            }else if(user.status == "error"){
                return false;
            }else
                return false;

      });
}

And the .PHP:

<?php
require_once '../config.php';
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
    throw new Exception('Request method must be POST!');
}

$input = json_decode(trim(file_get_contents('php://input')),true);

$username = $input['username'];
$password = $input['password'];

$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = sha1($password, true);
$response = [];
$query = mysqli_query($connection, "SELECT * FROM user_accounts WHERE password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);

if ($rows == 1){
    $query = mysqli_query($connection, "SELECT account_type, employee_ID FROM user_accounts WHERE username ='$username'");
    $row = $query->fetch_assoc();
    $response['status'] = 'loggedin';
    $response['accid'] = $row['account_type'];
    $response['user'] = $username;
    $response['uniqid'] = $row['employee_ID'];
}
else
    $response['status'] = 'error';
echo json_encode($response);
?>

ContentLicense: CC BY-SA 4.0


问:
VSTS-hosted build agents refuse to run due to false capability error
We are using VSTS to build a typical ASP.NET MVC web application. It had previously been working on hosted build agents, and they currently work on local agents.

We are trying to get them to use hosted Visual Studio 2017 build agents, so we don't rely on developers' laptops, and even bought additional build minutes. However, when I try to queue a build against the hosted Visual Studio 2017 agent queue, I get the following error:

No registered agents found in the selected queue with the following
  capabilities: azureps, npm, yarn, node.js, msbuild, visualstudio,
  vstest, sqlpackage

These hosted agents should have all of those and when I look in the capabilities of the agent queue, it appears to have everything yet it still will not build. If I tell it to queue anyway, the build fails, saying:

No registered agents found in the selected queue with the following
  capabilities: azureps, npm, yarn, node.js, msbuild, visualstudio,
  vstest, sqlpackage. Use a different queue. More
  information.

The build works great against our local agent queue running on our laptops. What could be blocking the hosted agents?

答:
We had the yarn task in the build, but not the yarn installer. The hosted agents don't have yarn.

The build still demands yarn, but putting the yarn installer task before the yarn task seems to make it work.


问:
Excel Vba bold some text on a string
i need some help with excel.

I have a cell that get value by macro with code:

```<code>Range("A1").Value = "This Year we are having our guest " &Guest_name &" who is currently " &Guest_age &"years old, spending holidays with us"
</code>```

So i'm just wondering how can I get the Guest_name and Guest_age to be bold.

Thanks

答:
Here is one version of the answer. Using Characters to instruct vba where to start and end.

```<code>Sub test()

Dim guest_name, guest_name_len As Integer
Dim guest_age, guest_age_len As Integer

guest_name = "tester"
guest_name_len = Len(guest_name)
guest_age = "999"
guest_age_len = Len(guest_age)
Debug.Print guest_name_len & " / " & guest_age_len

Range("A1").Value = "This Year we are having our guest " & guest_name & " who is currently " & guest_age & "years old, spending holidays with us"

With Range("A1").Characters(Start:=35, Length:=guest_name_len).Font '35 characters counted (this year....)
.FontStyle = "bold"
End With
With Range("A1").Characters(Start:=35 + guest_name_len + 18, Length:=guest_age_len).Font '18 characters counted (who is... years old)
.FontStyle = "bold"
End With

End Sub
</code>```

Title: Excel Vba bold some text on a string

Body:
i need some help with excel.

I have a cell that get value by macro with code:

Range("A1").Value = "This Year we are having our guest " &Guest_name &" who is currently " &Guest_age &"years old, spending holidays with us"

So i'm just wondering how can I get the Guest_name and Guest_age to be bold.

Thanks

Body:
Here is one version of the answer. Using Characters to instruct vba where to start and end.

Sub test()

Dim guest_name, guest_name_len As Integer
Dim guest_age, guest_age_len As Integer

guest_name = "tester"
guest_name_len = Len(guest_name)
guest_age = "999"
guest_age_len = Len(guest_age)
Debug.Print guest_name_len & " / " & guest_age_len

Range("A1").Value = "This Year we are having our guest " & guest_name & " who is currently " & guest_age & "years old, spending holidays with us"

With Range("A1").Characters(Start:=35, Length:=guest_name_len).Font '35 characters counted (this year....)
.FontStyle = "bold"
End With
With Range("A1").Characters(Start:=35 + guest_name_len + 18, Length:=guest_age_len).Font '18 characters counted (who is... years old)
.FontStyle = "bold"
End With

End Sub


问:
Does argparse (python) support mutually exclusive groups of arguments?
If I have the arguments '-a', '-b', '-c', '-d', with the add_mutually_exclusive_group() function my program will have to use just one of them. Is there a way to combine that, so that the program will accept only either '-a 999 -b 999' or '-c 999 -d 999'?

Edit: adding a simple program for more clarity:

```<code>>>> parser = argparse.ArgumentParser()
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('-a')
>>> group.add_argument('-b')
>>> group.add_argument('-c')
>>> group.add_argument('-d')
</code>```

Then only ./app.py -a | ./app.py -b | ./app.py -c | ./app.py -d can be called. Is it possible to have argparse group the exclusion groups, so that only ./app.py -a .. -b .. | ./app.py -c .. -d .. be called?

答:
EDIT: Never mind. Because argparse makes the horrible choice of having to create an option when invoking group.add_argument. That wouldn't be my design choice. If you're desperate for this feature, you can try doing it with ConflictsOptionParser:

```<code># exclusivegroups.py
import conflictsparse

parser = conflictsparse.ConflictsOptionParser()
a_opt = parser.add_option('-a')
b_opt = parser.add_option('-b')
c_opt = parser.add_option('-c')
d_opt = parser.add_option('-d')

import itertools
compatible_opts1 = (a_opt, b_opt)
compatible_opts2 = (c_opt, d_opt)
exclusives = itertools.product(compatible_opts1, compatible_opts2)
for exclusive_grp in exclusives:
    parser.register_conflict(exclusive_grp)

opts, args = parser.parse_args()
print "opts: ", opts
print "args: ", args
</code>```

Thus when we invoke it, we can see we get the desired effect.

```<code>$ python exclusivegroups.py -a 1 -b 2
opts:  {'a': '1', 'c': None, 'b': '2', 'd': None}
args:  []
$ python exclusivegroups.py -c 3 -d 2
opts:  {'a': None, 'c': '3', 'b': None, 'd': '2'}
args:  []
$ python exclusivegroups.py -a 1 -b 2 -c 3
Usage: exclusivegroups.py [options]

exclusivegroups.py: error: -b, -c are incompatible options.
</code>```

The warning message doesn't inform you that both '-a' and '-b' are incompatible with '-c', however a more appropriate error message could be crafted. Older, wrong answer below.

OLDER EDIT: [This edit is wrong, although wouldn't it be just a perfect world if argparse worked this way?] My previous answer actually was incorrect, you should be able to do this with argparse by specifying one group per mutually exclusive options. We can even use itertools to generalize the process. And make it so we don't have to type out all the combinations explicitly:

```<code>import itertools
compatible_opts1 = ('-a', '-b')
compatible_opts2 = ('-c', '-d')
exclusives = itertools.product(compatible_opts1, compatible_opts2)
for exclusive_grp in exclusives:
    group = parser.add_mutually_exclusive_group()
    group.add_argument(exclusive_grp[0])
    group.add_argument(exclusive_grp[1])
</code>```

Body:
If I have the arguments '-a', '-b', '-c', '-d', with the add_mutually_exclusive_group() function my program will have to use just one of them. Is there a way to combine that, so that the program will accept only either '-a 999 -b 999' or '-c 999 -d 999'?

Edit: adding a simple program for more clarity:

>>> parser = argparse.ArgumentParser()
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('-a')
>>> group.add_argument('-b')
>>> group.add_argument('-c')
>>> group.add_argument('-d')

Then only ./app.py -a | ./app.py -b | ./app.py -c | ./app.py -d can be called. Is it possible to have argparse group the exclusion groups, so that only ./app.py -a .. -b .. | ./app.py -c .. -d .. be called?

Body:
EDIT: Never mind. Because argparse makes the horrible choice of having to create an option when invoking group.add_argument. That wouldn't be my design choice. If you're desperate for this feature, you can try doing it with ConflictsOptionParser:

# exclusivegroups.py
import conflictsparse

parser = conflictsparse.ConflictsOptionParser()
a_opt = parser.add_option('-a')
b_opt = parser.add_option('-b')
c_opt = parser.add_option('-c')
d_opt = parser.add_option('-d')

import itertools
compatible_opts1 = (a_opt, b_opt)
compatible_opts2 = (c_opt, d_opt)
exclusives = itertools.product(compatible_opts1, compatible_opts2)
for exclusive_grp in exclusives:
    parser.register_conflict(exclusive_grp)

opts, args = parser.parse_args()
print "opts: ", opts
print "args: ", args

Thus when we invoke it, we can see we get the desired effect.

$ python exclusivegroups.py -a 1 -b 2
opts:  {'a': '1', 'c': None, 'b': '2', 'd': None}
args:  []
$ python exclusivegroups.py -c 3 -d 2
opts:  {'a': None, 'c': '3', 'b': None, 'd': '2'}
args:  []
$ python exclusivegroups.py -a 1 -b 2 -c 3
Usage: exclusivegroups.py [options]

exclusivegroups.py: error: -b, -c are incompatible options.

The warning message doesn't inform you that both '-a' and '-b' are incompatible with '-c', however a more appropriate error message could be crafted. Older, wrong answer below.

OLDER EDIT: [This edit is wrong, although wouldn't it be just a perfect world if argparse worked this way?] My previous answer actually was incorrect, you should be able to do this with argparse by specifying one group per mutually exclusive options. We can even use itertools to generalize the process. And make it so we don't have to type out all the combinations explicitly:

import itertools
compatible_opts1 = ('-a', '-b')
compatible_opts2 = ('-c', '-d')
exclusives = itertools.product(compatible_opts1, compatible_opts2)
for exclusive_grp in exclusives:
    group = parser.add_mutually_exclusive_group()
    group.add_argument(exclusive_grp[0])
    group.add_argument(exclusive_grp[1])


问:
Parse a substring in Python using regular expression
I am trying to parse a substring using re.

From the string present in variable s,I would like to split the string present till the first !(the string stored in s has two !) and store it as a substring.From this substring(stored in variable result), I wish to parse another substring.

Here is the code,

```<code>import re
s='ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081#kmValueMaximum*#!'

Data={}

result = re.search('%s(.*)%s' % ('ec', '!'), s).group(1)
print result
ecNumber = re.search('%s(.*)%s' % ('Number*', '#kmValue*'), result).group(1)
Data["ecNumber"]=ecNumber
print Data
</code>```

The value corresponding to each tag present in the substring(example:ecNumber)  is stored in between * and # (example: *2.4.1.11#).I attempted to parse the value stored for the tag ecNumber in the first substring.
The output I obtain is

```<code>result='Number*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081#kmValueMaximum*#'
{'ecNumber': '*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081'}
</code>```

The desired output is

```<code>result= 'ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#'
{'ecNumber': '2.4.1.11'}
</code>```

I would like to store each tag and its corresponding value.For example,

```<code>{'ecNumber': '2.4.1.11','kmValue':'0.021','kmValueMaximum':'1.25'}
</code>```

答:
Despite you are asking a solution with regular expression, I would say it's much easier to use direct string operations for this problem, since the source string is well formatted.

For infomation before the first i:

```<code>print dict([i.split('*') for i in s.split('!', 1)[0].split('#') if i])
</code>```

For all information in s:

```<code>print [dict([i.split('*') for i in j.split('#') if i]) for j in s.split('!') if j]
</code>```

Body:
I am trying to parse a substring using re.

From the string present in variable s,I would like to split the string present till the first !(the string stored in s has two !) and store it as a substring.From this substring(stored in variable result), I wish to parse another substring.

Here is the code,

import re
s='ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081#kmValueMaximum*#!'

Data={}

result = re.search('%s(.*)%s' % ('ec', '!'), s).group(1)
print result
ecNumber = re.search('%s(.*)%s' % ('Number*', '#kmValue*'), result).group(1)
Data["ecNumber"]=ecNumber
print Data

The value corresponding to each tag present in the substring(example:ecNumber)  is stored in between * and # (example: *2.4.1.11#).I attempted to parse the value stored for the tag ecNumber in the first substring.
The output I obtain is

result='Number*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081#kmValueMaximum*#'
{'ecNumber': '*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#!ecNumber*2.3.1.11#kmValue*0.081'}

The desired output is

result= 'ecNumber*2.4.1.11#kmValue*0.57#kmValueMaximum*1.25#'
{'ecNumber': '2.4.1.11'}

I would like to store each tag and its corresponding value.For example,

{'ecNumber': '2.4.1.11','kmValue':'0.021','kmValueMaximum':'1.25'}

Body:
Despite you are asking a solution with regular expression, I would say it's much easier to use direct string operations for this problem, since the source string is well formatted.

For infomation before the first i:

print dict([i.split('*') for i in s.split('!', 1)[0].split('#') if i])

For all information in s:

print [dict([i.split('*') for i in j.split('#') if i]) for j in s.split('!') if j]


问:
How to lock one activities orientation,then have another on top which is free to rotate?
I am developing an app for Android where I use the front camera as a mirror and have controls on top to do various functions. Now I was wondering how I can get the MainActivity to stay locked as 'portrait' and have another activity on top (which has all the buttons and has a transparent background) to have freedom to rotate?

Thanks

答:
So you have two activites, one for which orientation is fixed and another one is free to rotate.
For the activity for which orientation is to be fixed, add this line in its activity tag in Manifest.xml :

```<code><activity
        android:name=".MyPreferencesActivity"
        android:screenOrientation="landscape"/>
</code>```

And by default the other activity is free to rotate.Mark the answer as verified if it works.

The above way is static (defined in xml).Ii  it doesn't work, try this programmatical(can be changed during runtime) method also:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

public void onButtonPressed(Uri uri) {getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);}
</code>```

Body:
So you have two activites, one for which orientation is fixed and another one is free to rotate.
For the activity for which orientation is to be fixed, add this line in its activity tag in Manifest.xml :

<activity
        android:name=".MyPreferencesActivity"
        android:screenOrientation="landscape"/>

And by default the other activity is free to rotate.Mark the answer as verified if it works.

The above way is static (defined in xml).Ii  it doesn't work, try this programmatical(can be changed during runtime) method also:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

public void onButtonPressed(Uri uri) {getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);}


问:
React-native scroll to top with pull to refresh iOS
I have a react-native app, that I want to scroll to top when the FlatList is refreshing in iOS. I can scroll to the top of the FlaList by using:

```<code>this.componentRef.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
</code>```

Now, the list has Pull-to-refresh on, so I would like to scroll above the refreshing indicator in iOS.

I tried:

```<code>this.componentRef.FlatList.scrollToOffset({x: 0, y: -20, animated: true});
</code>```

and declaring the RefreshControl with a ref  as refreshcontrol (using callback ref declaration):

```<code>this.componentRef.FlatList.refreshcontrol.scrollToOffset({x: 0, y: 0, animated: true});
</code>```

and

```<code>this.componentRef.refreshcontrol.scrollToOffset({x: 0, y: 0, animated: true});
</code>```

But none work. Is anyone aware of a way I can scroll above the refreshing indicator, if its on? This only happens in iOS as Android's refreshing indicator works differently.

UPDATE:

As scrollToOffset is not available for the RefrehControl component, it won;t work. Which brings me back to how can I scroll above a RefreshControl in a FlatList. My last attempt:

```<code>this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
</code>```

Still scrolls to the beginning of the list, yet the "RefreshControl" is visually hidden.

I also tried adding an empty ScrollView above and scrolling to it, because it is empty, it did not work. Any ideas?

UPDATE 2

To clarify, this is how everything is called (simplified):

_scrollAndRefresh method in Main.js:

```<code>  _scrollAndRefresh = () => {
     this.setState({
       loading: true
     }, () => {
       this.CustomFlatList._scrollToTop();
     });
  }
</code>```

Rendering the component in Main.js:

```<code>  <CustomFlatList ref={(ref) => {
      this.CustomFlatList = ref}}
    onRefresh={this._handleRefresh} loading={this.state.loading}/>
</code>```

_handleRefresh method in Main.js:

```<code>  _handleRefresh = () => {
    this.setState({
      loading: true
    }, () => {
      // REFRESH ACTION
    })
  };
</code>```

_scrollToTop method CustomFlatList.js:

```<code>  _scrollToTop = () => {
    if (Platform.OS === 'ios' && this.props.loading) {
      this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
    }
    else {
      this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
    }
  }
</code>```

And FlatList CustomFlatList.js:

```<code><FlatList
  ref={(ref) => { this.FlatList = ref; }}
  refreshControl={<RefreshControl
            refreshing={this.props.loading}
            onRefresh={this.props.onRefresh}
        />}
/>
</code>```

答:
Since <RefreshControl /> detect refresh behavior from gesture, <FlatList /> scroll method has no effect on it; And you are just attempt to hack it.

Suggest to do it this way. You still scroll to top and shows refresh, and more directly:

constructor(props) {
  super(props);
  this.state = {
    refreshing: false,
  }
}

/// scroll to top, and show refresh at the same time
scrollToTopAndRefresh() {
  this.componentRef.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
  this.setState({
    refreshing: true,
  }, () => {
    this.refresh();
  });
}

refresh() {
  /// put your refresh logic here
}

componentRef = {};
render() {
  return (
    <FlatList ref={ (ref) => this.componentRef.FlatList = ref }
      refreshControl={
        <RefreshControl
          refreshing={this.state.refreshing}
          onRefresh={() => this.refresh()}
        />
      }
    />
  );
}
```

<h2>Update 2:</h2>

<p>I made a simple workable code for your needs.</p>

<pre class="lang-js prettyprint-override"><code>import React, { Component } from 'react';
import {
    Image,
    View,
    FlatList,
    Text,
    StyleSheet,
    Button,
    RefreshControl,
} from 'react-native';

export class App extends Component {
    constructor(props) {
        super(props);
        this.scrollToTopAndRefresh = this.scrollToTopAndRefresh.bind(this);
        this.doRefresh = this.doRefresh.bind(this);
        this.state = {
            refreshing: false,
        }
    }

    scrollToTopAndRefresh() {
        this.flatlistref.scrollToOffset({y: 0, animated: true});
        this.setState({refreshing: true}, this.doRefresh);
    }

    doRefresh() {
        /// do refresh work here /////
        //////////////////////////////
        setTimeout( () => this.setState({refreshing: false}), 1000);
    }

    flatlistref = null;
    render() {
        return (
            <View style={{flex: 1}}>
                <FlatList
                    ref={(ref) => this.flatlistref = ref}
                    data={Array(30).fill(1)}
                    renderItem={() => <Text style={styles.line}>This is one line.</Text>}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={this.doRefresh}
                        />
                    }
                />
                <Button title='Scroll To Top' onPress={this.scrollToTopAndRefresh} />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    line: {
        height: 50,
        paddingTop: 17,
        textAlign: 'center',
        backgroundColor: 'orange',
        borderWidth: 1,
        borderColor: 'purple',
    }
});
</code>```

Result:

Body:
I have a react-native app, that I want to scroll to top when the FlatList is refreshing in iOS. I can scroll to the top of the FlaList by using:

this.componentRef.FlatList.scrollToOffset({x: 0, y: 0, animated: true});

Now, the list has Pull-to-refresh on, so I would like to scroll above the refreshing indicator in iOS.

I tried:

this.componentRef.FlatList.scrollToOffset({x: 0, y: -20, animated: true});

and declaring the RefreshControl with a ref  as refreshcontrol (using callback ref declaration):

this.componentRef.FlatList.refreshcontrol.scrollToOffset({x: 0, y: 0, animated: true});

and

this.componentRef.refreshcontrol.scrollToOffset({x: 0, y: 0, animated: true});

But none work. Is anyone aware of a way I can scroll above the refreshing indicator, if its on? This only happens in iOS as Android's refreshing indicator works differently.

UPDATE:

As scrollToOffset is not available for the RefrehControl component, it won;t work. Which brings me back to how can I scroll above a RefreshControl in a FlatList. My last attempt:

this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});

Still scrolls to the beginning of the list, yet the "RefreshControl" is visually hidden.

I also tried adding an empty ScrollView above and scrolling to it, because it is empty, it did not work. Any ideas?

UPDATE 2

To clarify, this is how everything is called (simplified):

_scrollAndRefresh method in Main.js:

  _scrollAndRefresh = () => {
     this.setState({
       loading: true
     }, () => {
       this.CustomFlatList._scrollToTop();
     });
  }

Rendering the component in Main.js:

  <CustomFlatList ref={(ref) => {
      this.CustomFlatList = ref}}
    onRefresh={this._handleRefresh} loading={this.state.loading}/>

_handleRefresh method in Main.js:

  _handleRefresh = () => {
    this.setState({
      loading: true
    }, () => {
      // REFRESH ACTION
    })
  };

_scrollToTop method CustomFlatList.js:

  _scrollToTop = () => {
    if (Platform.OS === 'ios' && this.props.loading) {
      this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
    }
    else {
      this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
    }
  }

And FlatList CustomFlatList.js:

<FlatList
  ref={(ref) => { this.FlatList = ref; }}
  refreshControl={<RefreshControl
            refreshing={this.props.loading}
            onRefresh={this.props.onRefresh}
        />}
/>

Body:
Since <RefreshControl /> detect refresh behavior from gesture, <FlatList /> scroll method has no effect on it; And you are just attempt to hack it.

Suggest to do it this way. You still scroll to top and shows refresh, and more directly:

constructor(props) {
  super(props);
  this.state = {
    refreshing: false,
  }
}

/// scroll to top, and show refresh at the same time
scrollToTopAndRefresh() {
  this.componentRef.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
  this.setState({
    refreshing: true,
  }, () => {
    this.refresh();
  });
}

refresh() {
  /// put your refresh logic here
}

componentRef = {};
render() {
  return (
    <FlatList ref={ (ref) => this.componentRef.FlatList = ref }
      refreshControl={
        <RefreshControl
          refreshing={this.state.refreshing}
          onRefresh={() => this.refresh()}
        />
      }
    />
  );
}

Update 2:

I made a simple workable code for your needs.

import React, { Component } from 'react';
import {
    Image,
    View,
    FlatList,
    Text,
    StyleSheet,
    Button,
    RefreshControl,
} from 'react-native';

export class App extends Component {
    constructor(props) {
        super(props);
        this.scrollToTopAndRefresh = this.scrollToTopAndRefresh.bind(this);
        this.doRefresh = this.doRefresh.bind(this);
        this.state = {
            refreshing: false,
        }
    }

    scrollToTopAndRefresh() {
        this.flatlistref.scrollToOffset({y: 0, animated: true});
        this.setState({refreshing: true}, this.doRefresh);
    }

    doRefresh() {
        /// do refresh work here /////
        //////////////////////////////
        setTimeout( () => this.setState({refreshing: false}), 1000);
    }

    flatlistref = null;
    render() {
        return (
            <View style={{flex: 1}}>
                <FlatList
                    ref={(ref) => this.flatlistref = ref}
                    data={Array(30).fill(1)}
                    renderItem={() => <Text style={styles.line}>This is one line.</Text>}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={this.doRefresh}
                        />
                    }
                />
                <Button title='Scroll To Top' onPress={this.scrollToTopAndRefresh} />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    line: {
        height: 50,
        paddingTop: 17,
        textAlign: 'center',
        backgroundColor: 'orange',
        borderWidth: 1,
        borderColor: 'purple',
    }
});

Result:


问:
Search and get all child nodes of XML node base on attribute id
I have a sample XML like this:

```<code><doc>
    <customer id="1">
      <first>
        <fullname>John Doe 1</fullname>
        <contact>011-1111111</contact>
        <title>Lorem</title>
      </first>
      <second>
        <fullname>John Doe 2</fullname>
        <contact>012-2222222</contact>
        <title>Lorem</title>
      </second>
    </customer>
</doc>
</code>```

My question is how can I get all the child node inside first and second based on the customer id. So far this is what i have tried but i have no idea how to continue it.

```<code> XDocument doc = XDocument.Load("sampleXML.xml");
 var controls = from str in doc.Elements("customer")
                           where str.Attribute("id").Value == 1
                           select str;
</code>```

If I am able to get the data, how can i display the result? By using foreach loop? Sorry if this is a stupid question, but I am quite new to c# and linq.

答:
You can use xpath for finding the element with attribute value.

Here is an example

```<code>    string xml= "your xml string";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    var nodes = doc.SelectSingleNode("/doc/customer[@id='1']").ChildNodes;
</code>```

Body:
I have a sample XML like this:

<doc>
    <customer id="1">
      <first>
        <fullname>John Doe 1</fullname>
        <contact>011-1111111</contact>
        <title>Lorem</title>
      </first>
      <second>
        <fullname>John Doe 2</fullname>
        <contact>012-2222222</contact>
        <title>Lorem</title>
      </second>
    </customer>
</doc>

My question is how can I get all the child node inside first and second based on the customer id. So far this is what i have tried but i have no idea how to continue it.

 XDocument doc = XDocument.Load("sampleXML.xml");
 var controls = from str in doc.Elements("customer")
                           where str.Attribute("id").Value == 1
                           select str;

If I am able to get the data, how can i display the result? By using foreach loop? Sorry if this is a stupid question, but I am quite new to c# and linq.

Body:
You can use xpath for finding the element with attribute value.

Here is an example

    string xml= "your xml string";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    var nodes = doc.SelectSingleNode("/doc/customer[@id='1']").ChildNodes;


问:
CMake - Build error with forward declaration
I'm a C++ beginner, so I'm building a budget app (creative, right?) for practice. I'm using CMake for the build process. I've forward declared one class in another and I only have std::shared_ptrs to the incomplete class, but I still get incomplete type errors. Is this an issue with CMake attempting to build one class before the other? If that's the case, is there a way to specify to CMake that Category needs to be built before Transaction? Or is there something I'm missing about forward declaration?

```<code>-- Configuring done
-- Generating done
-- Build files have been written to: /hdd/lfs/projects/budget/build
make[1]: Entering directory '/hdd/lfs/projects/budget/build'
make[2]: Entering directory '/hdd/lfs/projects/budget/build'
make[3]: Entering directory '/hdd/lfs/projects/budget/build'
make[3]: Leaving directory '/hdd/lfs/projects/budget/build'
make[3]: Entering directory '/hdd/lfs/projects/budget/build'
[ 16%] Building CXX object CMakeFiles/budget.dir/src/Transaction.cpp.o
/hdd/lfs/projects/budget/src/Transaction.cpp: In constructor ‘Transaction::Transaction(double, std::shared_ptr<Category>)’:
/hdd/lfs/projects/budget/src/Transaction.cpp:11:12: error: invalid use of incomplete type ‘class Category’
   _category->addTransaction(*this);
            ^
In file included from /hdd/lfs/projects/budget/src/Transaction.cpp:3:0:
/hdd/lfs/projects/budget/include/Transaction.h:10:7: note: forward declaration of ‘class Category’
 class Category;
       ^
/hdd/lfs/projects/budget/src/Transaction.cpp: In constructor ‘Transaction::Transaction(double, std::__cxx11::string, std::shared_ptr<Category>)’:
/hdd/lfs/projects/budget/src/Transaction.cpp:21:12: error: invalid use of incomplete type ‘class Category’
   _category->addTransaction(*this);
            ^
In file included from /hdd/lfs/projects/budget/src/Transaction.cpp:3:0:
/hdd/lfs/projects/budget/include/Transaction.h:10:7: note: forward declaration of ‘class Category’
 class Category;
       ^
/hdd/lfs/projects/budget/src/Transaction.cpp: In destructor ‘Transaction::~Transaction()’:
/hdd/lfs/projects/budget/src/Transaction.cpp:26:12: error: invalid use of incomplete type ‘class Category’
   _category->deleteTransaction(*this);
            ^
In file included from /hdd/lfs/projects/budget/src/Transaction.cpp:3:0:
/hdd/lfs/projects/budget/include/Transaction.h:10:7: note: forward declaration of ‘class Category’
 class Category;
       ^
CMakeFiles/budget.dir/build.make:158: recipe for target 'CMakeFiles/budget.dir/src/Transaction.cpp.o' failed
make[3]: *** [CMakeFiles/budget.dir/src/Transaction.cpp.o] Error 1
make[3]: Leaving directory '/hdd/lfs/projects/budget/build'
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/budget.dir/all' failed
make[2]: *** [CMakeFiles/budget.dir/all] Error 2
make[2]: Leaving directory '/hdd/lfs/projects/budget/build'
Makefile:83: recipe for target 'all' failed
make[1]: *** [all] Error 2
make[1]: Leaving directory '/hdd/lfs/projects/budget/build'
makefile:2: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

Category.h

```<code>#pragma once

#include <string>
#include <list>

#include "Transaction.h"

class Category
{
  private:
    std::string _name;
    double _budget;
    double _balance;
    std::list<Transaction> _transactions;

    void calculateBalance();

  public:
    Category() =delete;

    Category(std::string name)
      : _name(name), _budget(0), _balance(0)
    {}

    std::string name() const;
    void setName(std::string name);

    double budget() const;
    void setBudget(double budget);

    double balance() const;

    void addTransaction(Transaction& transaction);

    void deleteTransaction(Transaction& transaction);

    std::ostream& display(std::ostream& out) const;

    bool operator==(const Category& right) const;

    bool operator!=(const Category& right) const;

    friend std::ostream& operator<<(std::ostream& out, const Category& c)
    {
      return c.display(out);
    }
};
</code>```

Transaction.h

```<code>#pragma once

#include <iostream>
#include <memory>

#include "boost/date_time/gregorian/gregorian.hpp"

#include "DisplayHelpers.h"

class Category;

class Transaction
{
  private:
    std::string _description;
    double _amount;
    boost::gregorian::date _date;
    std::shared_ptr<Category> _category;

  public:
    Transaction() = delete;

    Transaction(double amount, std::shared_ptr<Category> category);

    Transaction(double amount, std::string description,
                std::shared_ptr<Category> category);

    ~Transaction();

    void setDescription(std::string description);
    std::string getDescription() const;

    void setAmount(double amount);
    double getAmount() const;

    boost::gregorian::date getDate() const;

    void setCategory(std::shared_ptr<Category> c);
    std::shared_ptr<Category> getCategory() const;

    bool operator==(const Transaction& other) const;
    bool operator<(const Transaction& other) const;

    std::ostream&  display(std::ostream& out) const;

    friend std::ostream& operator<<(std::ostream& out, const Transaction& t)
    {
      return t.display(out);
    }
};
</code>```

Transaction.cpp

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

Transaction::Transaction(double amount, std::shared_ptr<Category> category)
  : _amount(amount),
    _date(boost::gregorian::day_clock::local_day()),
    _description("Transaction"),
    _category(category)
{
  _category->addTransaction(*this);
}

Transaction::Transaction(double amount, std::string description,
            std::shared_ptr<Category> category)
  : _amount(amount),
    _date(boost::gregorian::day_clock::local_day()),
    _description(description),
    _category(category)
{
  _category->addTransaction(*this);
}

Transaction::~Transaction()
{
  _category->deleteTransaction(*this);
}

void Transaction::setDescription(std::string description)
{
  _description = description;
}

std::string Transaction::getDescription() const
{
  return _description;
}

void Transaction::setAmount(double amount) {_amount = amount;}
double Transaction::getAmount() const {return _amount;}

void Transaction::setCategory(std::shared_ptr<Category> category)
{
  _category = category;
}
std::shared_ptr<Category> Transaction::getCategory() const
{
  return _category;
}

std::ostream&  Transaction::display(std::ostream& out=std::cout) const
{
  std::string amountString = DisplayHelpers::monify(_amount);

  out << std::setw(14) << std::left << "Description: " << _description << "\n";
  out << std::setw(13) << std::left << "Amount: " << amountString << "\n";
  out << std::setw(14) << std::left << "Date: " << _date << "\n";

  return out;
}

bool Transaction::operator==(const Transaction& other) const
{
  return (_description == other._description &&
          _amount == other._amount &&
          _date == other._date &&
          _category == other._category);
}

bool Transaction::operator<(const Transaction& other) const
{
    bool returnStatus = false;
    if (_date > other._date)
    {
        returnStatus = false;
    }
    else
        {
          if (_amount < other._amount)
          {
            returnStatus = true;
          }
    }
    return returnStatus;
}
</code>```

答: Your Transaction.cpp file includes only Transaction.h which does not contain a definition of Category.   Therefore in the context of  Transaction.cpp the compiler can not allow you to access members of any object of type Category.   Include Category.h in Transaction.cpp to fix your problem.

Body:
I'm a C++ beginner, so I'm building a budget app (creative, right?) for practice. I'm using CMake for the build process. I've forward declared one class in another and I only have std::shared_ptrs to the incomplete class, but I still get incomplete type errors. Is this an issue with CMake attempting to build one class before the other? If that's the case, is there a way to specify to CMake that Category needs to be built before Transaction? Or is there something I'm missing about forward declaration?

-- Configuring done
-- Generating done
-- Build files have been written to: /hdd/lfs/projects/budget/build
make[1]: Entering directory '/hdd/lfs/projects/budget/build'
make[2]: Entering directory '/hdd/lfs/projects/budget/build'
make[3]: Entering directory '/hdd/lfs/projects/budget/build'
make[3]: Leaving directory '/hdd/lfs/projects/budget/build'
make[3]: Entering directory '/hdd/lfs/projects/budget/build'
[ 16%] Building CXX object CMakeFiles/budget.dir/src/Transaction.cpp.o
/hdd/lfs/projects/budget/src/Transaction.cpp: In constructor ‘Transaction::Transaction(double, std::shared_ptr<Category>)’:
/hdd/lfs/projects/budget/src/Transaction.cpp:11:12: error: invalid use of incomplete type ‘class Category’
   _category->addTransaction(*this);
            ^
In file included from /hdd/lfs/projects/budget/src/Transaction.cpp:3:0:
/hdd/lfs/projects/budget/include/Transaction.h:10:7: note: forward declaration of ‘class Category’
 class Category;
       ^
/hdd/lfs/projects/budget/src/Transaction.cpp: In constructor ‘Transaction::Transaction(double, std::__cxx11::string, std::shared_ptr<Category>)’:
/hdd/lfs/projects/budget/src/Transaction.cpp:21:12: error: invalid use of incomplete type ‘class Category’
   _category->addTransaction(*this);
            ^
In file included from /hdd/lfs/projects/budget/src/Transaction.cpp:3:0:
/hdd/lfs/projects/budget/include/Transaction.h:10:7: note: forward declaration of ‘class Category’
 class Category;
       ^
/hdd/lfs/projects/budget/src/Transaction.cpp: In destructor ‘Transaction::~Transaction()’:
/hdd/lfs/projects/budget/src/Transaction.cpp:26:12: error: invalid use of incomplete type ‘class Category’
   _category->deleteTransaction(*this);
            ^
In file included from /hdd/lfs/projects/budget/src/Transaction.cpp:3:0:
/hdd/lfs/projects/budget/include/Transaction.h:10:7: note: forward declaration of ‘class Category’
 class Category;
       ^
CMakeFiles/budget.dir/build.make:158: recipe for target 'CMakeFiles/budget.dir/src/Transaction.cpp.o' failed
make[3]: *** [CMakeFiles/budget.dir/src/Transaction.cpp.o] Error 1
make[3]: Leaving directory '/hdd/lfs/projects/budget/build'
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/budget.dir/all' failed
make[2]: *** [CMakeFiles/budget.dir/all] Error 2
make[2]: Leaving directory '/hdd/lfs/projects/budget/build'
Makefile:83: recipe for target 'all' failed
make[1]: *** [all] Error 2
make[1]: Leaving directory '/hdd/lfs/projects/budget/build'
makefile:2: recipe for target 'all' failed
make: *** [all] Error 2

Category.h

#pragma once

#include <string>
#include <list>

#include "Transaction.h"

class Category
{
  private:
    std::string _name;
    double _budget;
    double _balance;
    std::list<Transaction> _transactions;

    void calculateBalance();

  public:
    Category() =delete;

    Category(std::string name)
      : _name(name), _budget(0), _balance(0)
    {}

    std::string name() const;
    void setName(std::string name);

    double budget() const;
    void setBudget(double budget);

    double balance() const;

    void addTransaction(Transaction& transaction);

    void deleteTransaction(Transaction& transaction);

    std::ostream& display(std::ostream& out) const;

    bool operator==(const Category& right) const;

    bool operator!=(const Category& right) const;

    friend std::ostream& operator<<(std::ostream& out, const Category& c)
    {
      return c.display(out);
    }
};

Transaction.h

#pragma once

#include <iostream>
#include <memory>

#include "boost/date_time/gregorian/gregorian.hpp"

#include "DisplayHelpers.h"

class Category;

class Transaction
{
  private:
    std::string _description;
    double _amount;
    boost::gregorian::date _date;
    std::shared_ptr<Category> _category;

  public:
    Transaction() = delete;

    Transaction(double amount, std::shared_ptr<Category> category);

    Transaction(double amount, std::string description,
                std::shared_ptr<Category> category);

    ~Transaction();

    void setDescription(std::string description);
    std::string getDescription() const;

    void setAmount(double amount);
    double getAmount() const;

    boost::gregorian::date getDate() const;

    void setCategory(std::shared_ptr<Category> c);
    std::shared_ptr<Category> getCategory() const;

    bool operator==(const Transaction& other) const;
    bool operator<(const Transaction& other) const;

    std::ostream&  display(std::ostream& out) const;

    friend std::ostream& operator<<(std::ostream& out, const Transaction& t)
    {
      return t.display(out);
    }
};

Transaction.cpp

#include "Transaction.h"

Transaction::Transaction(double amount, std::shared_ptr<Category> category)
  : _amount(amount),
    _date(boost::gregorian::day_clock::local_day()),
    _description("Transaction"),
    _category(category)
{
  _category->addTransaction(*this);
}

Transaction::Transaction(double amount, std::string description,
            std::shared_ptr<Category> category)
  : _amount(amount),
    _date(boost::gregorian::day_clock::local_day()),
    _description(description),
    _category(category)
{
  _category->addTransaction(*this);
}

Transaction::~Transaction()
{
  _category->deleteTransaction(*this);
}

void Transaction::setDescription(std::string description)
{
  _description = description;
}

std::string Transaction::getDescription() const
{
  return _description;
}

void Transaction::setAmount(double amount) {_amount = amount;}
double Transaction::getAmount() const {return _amount;}

void Transaction::setCategory(std::shared_ptr<Category> category)
{
  _category = category;
}
std::shared_ptr<Category> Transaction::getCategory() const
{
  return _category;
}

std::ostream&  Transaction::display(std::ostream& out=std::cout) const
{
  std::string amountString = DisplayHelpers::monify(_amount);

  out << std::setw(14) << std::left << "Description: " << _description << "\n";
  out << std::setw(13) << std::left << "Amount: " << amountString << "\n";
  out << std::setw(14) << std::left << "Date: " << _date << "\n";

  return out;
}

bool Transaction::operator==(const Transaction& other) const
{
  return (_description == other._description &&
          _amount == other._amount &&
          _date == other._date &&
          _category == other._category);
}

bool Transaction::operator<(const Transaction& other) const
{
    bool returnStatus = false;
    if (_date > other._date)
    {
        returnStatus = false;
    }
    else
        {
          if (_amount < other._amount)
          {
            returnStatus = true;
          }
    }
    return returnStatus;
}


问:
SQL condition: (A=B AND C LIKE %D%) OR (A LIKE %B% AND C=D)
I've got a table of first names and last names.

I'm trying to make a jQuery instant search on an input, in order to find very quickly and precisely a person in a huge list of people.

When the first word is entered in the input, it might be the first name or the last name.

I do this : SELECT * FROM myTable WHERE firstName LIKE %content% OR lastName LIKE %content%

When two words are entered, it might be:
* the full firstname and a bit of the lastname
* the full lastname and a bit of the firstame

So I tried this query : SELECT * FROM myTable WHERE (firstName = content1 AND lastName LIKE %content2%) OR ( lastName = content1 AND firstName LIKE %content2%)

Unfortunately parenthesis seems to do nothing, and the query is not interpreted this way, I've got a lot of results, basically produced by the two LIKE %% condition

Anyone had deal with this before and could give me a hand?

Thanx

答:
When two words are entered, it might
  be: * the full firstname and a bit of
  the lastname * the full lastname and a
  bit of the firstame

If it is ALL of (exact match) the first or last name, then the = test seems correct.  Just in case it is an error in the PHP part, this is how it should look like.

```<code>$qry = '
SELECT * FROM myTable
WHERE (firstName = content1 AND lastName LIKE '%".mysql_real_escape_string(content2)."%')
   OR ( lastName = content1 AND firstName LIKE '%".mysql_real_escape_string(content2)."%')';
</code>```

If it is a bit of both, then you need the wildcard twice

```<code>$qry = '
SELECT * FROM myTable
WHERE (firstName LIKE '%".mysql_real_escape_string(content1)."%' AND lastName LIKE '%".mysql_real_escape_string(content2)."%')
   OR ( lastName LIKE '%".mysql_real_escape_string(content1)."%' AND firstName LIKE '%".mysql_real_escape_string(content2)."%')';
</code>```

Body:
When two words are entered, it might
  be: * the full firstname and a bit of
  the lastname * the full lastname and a
  bit of the firstame

If it is ALL of (exact match) the first or last name, then the = test seems correct.  Just in case it is an error in the PHP part, this is how it should look like.

$qry = '
SELECT * FROM myTable
WHERE (firstName = content1 AND lastName LIKE '%".mysql_real_escape_string(content2)."%')
   OR ( lastName = content1 AND firstName LIKE '%".mysql_real_escape_string(content2)."%')';

If it is a bit of both, then you need the wildcard twice

$qry = '
SELECT * FROM myTable
WHERE (firstName LIKE '%".mysql_real_escape_string(content1)."%' AND lastName LIKE '%".mysql_real_escape_string(content2)."%')
   OR ( lastName LIKE '%".mysql_real_escape_string(content1)."%' AND firstName LIKE '%".mysql_real_escape_string(content2)."%')';


问:
Excel VBA - use the if and countif to clear(not delete) the duplicate cell expect the first item
I have two workbooks. one is report.xls, another one is AT.xlsm.

In report.xls, there has the sheet called "Service".

In AT.xlsm, there has the sheet called "Worksheet".

Thanks for the help of @mooseman, it can use the VBA to copy the column B,C,F,J,E,D expect first row of report to the column A,C,D,E,F,H of AT.

After copy the data from the report to AT, i want to remove the duplicate cell(just clear the content of the cell) expect the first item that use the VBA. I know that use the if and countif can work out.

Would you please tell me how to use the if and countif in the VBA to remove the duplicate cell(just clear the content of the cell) expect the first item ?

Thank you very much.

```<code> Sub add_click()

Dim sDirectory As String
Dim sFilename As String
Dim sheet As Worksheet
Dim total As Integer
Dim lastRow As Long
Dim sImportFile As String
Dim totalactive As Integer
Dim readsheetName As String
Dim destsheetName As String

readsheetName = "Service"
destsheetName = "Worksheet"

addWSn = 0
Application.ScreenUpdating = False
Application.DisplayAlerts = False
sDirectory = ActiveWorkbook.Path
sFilename = sDirectory + "\*.xl??"

sImportFile = Application.GetOpenFilename(FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open report")
If sImportFile = "False" Then
    MsgBox ("No File")
    Exit Sub
End If

'set destination workbook and worksheet
Set wb2 = ThisWorkbook
Set wsw = wb2.Sheets(destsheetName)
lastRow = wsw.Cells(wsw.Rows.Count, "D").End(xlUp).Row
lastRow = lastRow + 2
Set wb = Workbooks.Open(sImportFile)
Set wss = wb.Sheets(readsheetName)

wss.Range(wss.Cells(2, 2), wss.Cells(wss.Range("B" & wss.Rows.Count).End(xlUp).Row, 2)).Copy
wsw.Cells(lastRow, 1).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 3), wss.Cells(wss.Range("C" & wss.Rows.Count).End(xlUp).Row, 3)).Copy
wsw.Cells(lastRow, 3).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 6), wss.Cells(wss.Range("F" & wss.Rows.Count).End(xlUp).Row, 6)).Copy
wsw.Cells(lastRow, 4).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 10), wss.Cells(wss.Range("J" & wss.Rows.Count).End(xlUp).Row, 10)).Copy
wsw.Cells(lastRow, 5).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 5), wss.Cells(wss.Range("E" & wss.Rows.Count).End(xlUp).Row, 5)).Copy
wsw.Cells(lastRow, 6).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 4), wss.Cells(wss.Range("D" & wss.Rows.Count).End(xlUp).Row, 4)).Copy
wsw.Cells(lastRow, 8).PasteSpecial Paste:=xlPasteValues

wsw.Range(wsw.Cells(lastRow, 6), wsw.Cells(wsw.Range("F" & wsw.Rows.Count).End(xlUp).Row, 6)).Replace What:="[S]", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
wsw.Columns("E:K").HorizontalAlignment = xlRight

'close excel file
Workbooks.Open (sImportFile)
ActiveWorkbook.Close SaveChanges:=False
End Sub
</code>```

Updated:
@ Maldred
The result is partly worked, it can some clear the content of some duplicate.

答:
You might find it's easier (and quicker) to remove the duplicates before you copy the data to the new sheet. If you read it into an array, changed all dupes to Empty and then wrote the array to the worksheet, you wouldn't need that second task of emptying cells:

```<code>'Additonal declarations
Dim data As Variant, readCols As Variant, destCols As Variant
Dim exists As Boolean
Dim i As Long, r As Long
Dim uniques As Collection

'... your code to initialise worksheets, etc.

lastRow = wsw.Cells(wsw.Rows.Count, "D").End(xlUp).Offset(2).Row

'Define column maps
readCols = Array("B", "C", "F", "J", "E", "D")
destCols = Array("A", "C", "D", "E", "F", "H")

For i = LBound(readCols) To UBound(readCols)
    'Read the data.
    With wss
        data = .Range(.Cells(2, readCols(i)), .Cells(.Rows.Count, readCols(i)).End(xlUp)).Value2
    End With

    'Check for duplicates.
    Set uniques = New Collection
    For r = 1 To UBound(data, 1)
        exists = False: On Error Resume Next
        exists = uniques(CStr(data(r, 1))): On Error GoTo 0
        If exists Then
            'Reomve the duplicate.
            data(r, 1) = Empty
        Else
            'Keep it - it's a first instance.
            uniques.Add True, CStr(data(r, 1))
        End If
    Next

    'Write the data
    wsw.Cells(lastRow, destCols(i)).Resize(UBound(data, 1), 1).Value = data

Next
</code>```

Body:
I have two workbooks. one is report.xls, another one is AT.xlsm.

In report.xls, there has the sheet called "Service".

In AT.xlsm, there has the sheet called "Worksheet".

Thanks for the help of @mooseman, it can use the VBA to copy the column B,C,F,J,E,D expect first row of report to the column A,C,D,E,F,H of AT.

After copy the data from the report to AT, i want to remove the duplicate cell(just clear the content of the cell) expect the first item that use the VBA. I know that use the if and countif can work out.

Would you please tell me how to use the if and countif in the VBA to remove the duplicate cell(just clear the content of the cell) expect the first item ?

Thank you very much.

 Sub add_click()

Dim sDirectory As String
Dim sFilename As String
Dim sheet As Worksheet
Dim total As Integer
Dim lastRow As Long
Dim sImportFile As String
Dim totalactive As Integer
Dim readsheetName As String
Dim destsheetName As String

readsheetName = "Service"
destsheetName = "Worksheet"

addWSn = 0
Application.ScreenUpdating = False
Application.DisplayAlerts = False
sDirectory = ActiveWorkbook.Path
sFilename = sDirectory + "\*.xl??"

sImportFile = Application.GetOpenFilename(FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open report")
If sImportFile = "False" Then
    MsgBox ("No File")
    Exit Sub
End If

'set destination workbook and worksheet
Set wb2 = ThisWorkbook
Set wsw = wb2.Sheets(destsheetName)
lastRow = wsw.Cells(wsw.Rows.Count, "D").End(xlUp).Row
lastRow = lastRow + 2
Set wb = Workbooks.Open(sImportFile)
Set wss = wb.Sheets(readsheetName)

wss.Range(wss.Cells(2, 2), wss.Cells(wss.Range("B" & wss.Rows.Count).End(xlUp).Row, 2)).Copy
wsw.Cells(lastRow, 1).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 3), wss.Cells(wss.Range("C" & wss.Rows.Count).End(xlUp).Row, 3)).Copy
wsw.Cells(lastRow, 3).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 6), wss.Cells(wss.Range("F" & wss.Rows.Count).End(xlUp).Row, 6)).Copy
wsw.Cells(lastRow, 4).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 10), wss.Cells(wss.Range("J" & wss.Rows.Count).End(xlUp).Row, 10)).Copy
wsw.Cells(lastRow, 5).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 5), wss.Cells(wss.Range("E" & wss.Rows.Count).End(xlUp).Row, 5)).Copy
wsw.Cells(lastRow, 6).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 4), wss.Cells(wss.Range("D" & wss.Rows.Count).End(xlUp).Row, 4)).Copy
wsw.Cells(lastRow, 8).PasteSpecial Paste:=xlPasteValues

wsw.Range(wsw.Cells(lastRow, 6), wsw.Cells(wsw.Range("F" & wsw.Rows.Count).End(xlUp).Row, 6)).Replace What:="[S]", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
wsw.Columns("E:K").HorizontalAlignment = xlRight

'close excel file
Workbooks.Open (sImportFile)
ActiveWorkbook.Close SaveChanges:=False
End Sub

Updated:
@ Maldred
The result is partly worked, it can some clear the content of some duplicate.

Body:
You might find it's easier (and quicker) to remove the duplicates before you copy the data to the new sheet. If you read it into an array, changed all dupes to Empty and then wrote the array to the worksheet, you wouldn't need that second task of emptying cells:

'Additonal declarations
Dim data As Variant, readCols As Variant, destCols As Variant
Dim exists As Boolean
Dim i As Long, r As Long
Dim uniques As Collection

'... your code to initialise worksheets, etc.

lastRow = wsw.Cells(wsw.Rows.Count, "D").End(xlUp).Offset(2).Row

'Define column maps
readCols = Array("B", "C", "F", "J", "E", "D")
destCols = Array("A", "C", "D", "E", "F", "H")

For i = LBound(readCols) To UBound(readCols)
    'Read the data.
    With wss
        data = .Range(.Cells(2, readCols(i)), .Cells(.Rows.Count, readCols(i)).End(xlUp)).Value2
    End With

    'Check for duplicates.
    Set uniques = New Collection
    For r = 1 To UBound(data, 1)
        exists = False: On Error Resume Next
        exists = uniques(CStr(data(r, 1))): On Error GoTo 0
        If exists Then
            'Reomve the duplicate.
            data(r, 1) = Empty
        Else
            'Keep it - it's a first instance.
            uniques.Add True, CStr(data(r, 1))
        End If
    Next

    'Write the data
    wsw.Cells(lastRow, destCols(i)).Resize(UBound(data, 1), 1).Value = data

Next


问:
Regex to FAX Numbers from string
I'm tring to find fax number from below regex but it does not work with Fax: (91-44) 7781 1234 or FAX: +91 44 7781 1234 / 2828 1111

```<code>(?<=FAX[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)|(?<=F[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)
</code>```

答:
To match the given numbers you could use:</p>

```<code>"(?i)fax\\s*\\:\\s*\\+?[/\\(\\d\\)\\s-]+\\d"
</code>```

Title: Regex to FAX Numbers from string

Body:
I'm tring to find fax number from below regex but it does not work with Fax: (91-44) 7781 1234 or FAX: +91 44 7781 1234 / 2828 1111

(?<=FAX[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)|(?<=F[:\\s])([+\\d\\s]+\\S)(?=\\s\\D)

Body:
To match the given numbers you could use:

"(?i)fax\\s*\\:\\s*\\+?[/\\(\\d\\)\\s-]+\\d"


问:
Operator '==' cannot be applied to operands of type 'byte[]' and 'string'
I'm making a program with a login page and this error came up when coding it: Operator == cannot be applied to operands of type byte[] and string

Im not sure where to go with it or how to handle it. This is my section with the error:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(textBox1.Text))
    {
        MessageBox.Show("Please Enter your username.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        textBox1.Focus();
        return;
    }
    try
    {
        using (DataEntities test = new DataEntities())
        {
            var query = from o in test.Users
                        where o.Username == textBox1.Text && o.Password == textBox2.Text
                        select o;
            if(query.SingleOrDefault() != null)
            {
                MessageBox.Show("You have been successfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //Add your code process login here
            }
            else
            {
                MessageBox.Show("Your username or password is incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
</code>```

Thanks in advance!

答:
if your username and password fields are byte arrays you could convert them to string before doing the comparison:

Encoding.ASCII.GetString(o.Username) == textBox1.Text

Body:
I'm making a program with a login page and this error came up when coding it: Operator == cannot be applied to operands of type byte[] and string

Im not sure where to go with it or how to handle it. This is my section with the error:

private void button1_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(textBox1.Text))
    {
        MessageBox.Show("Please Enter your username.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        textBox1.Focus();
        return;
    }
    try
    {
        using (DataEntities test = new DataEntities())
        {
            var query = from o in test.Users
                        where o.Username == textBox1.Text && o.Password == textBox2.Text
                        select o;
            if(query.SingleOrDefault() != null)
            {
                MessageBox.Show("You have been successfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //Add your code process login here
            }
            else
            {
                MessageBox.Show("Your username or password is incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Thanks in advance!


问:
jquery selector doesn't work when html is replaced!
Please, help me with following problem:

```<code><!-- this is the visible code -->
<div id="divid">{some default content}<img class="img" src="GoNextArrow.jpg" alt=""></div>

<!-- this is a hidden list of contents -->
<div style="display: none;">
    <div id="divid1">{some content 1}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid2">{some content 2}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid3">{some content 3}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid4">{some content 4}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid5">{some content 5}<img class="img" src="GoNextArrow.jpg" alt=""></div>
</div>

<!-- this is an jquery script which replace the #divid with any of divid1-divid5 -->
$('#divid').hide().html(elem.html()).fadeIn();
<!-- elem is a variable, divid1 to divid5, e.g. var elem = $j('#divid'+id);  -->

<!-- I need a rollover effect, I made it so: -->
$('img.img').hover(function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
}, function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});
</code>```

This works well for the first div divid, but doesn't for divid1-divid5 when these are loaded instead of divid.
Where is my mistake??

Thanks!

答:
You might look into using replaceWith():

```<code>$('#divid').hide().replaceWith( elem.fadeIn() );
</code>```

If you've already bound functions to events on elem, those should persist even after you've swapped elem for another element on the page.

Example: http://jsfiddle.net/redler/eLD9A/

Body:
Please, help me with following problem:

{some default content}

{some content 1}

{some content 2}

{some content 3}

{some content 4}

{some content 5}

$('#divid').hide().html(elem.html()).fadeIn();

$('img.img').hover(function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
}, function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});

This works well for the first div divid, but doesn't for divid1-divid5 when these are loaded instead of divid.
Where is my mistake??

Thanks!

Body:
You might look into using replaceWith():

$('#divid').hide().replaceWith( elem.fadeIn() );

If you've already bound functions to events on elem, those should persist even after you've swapped elem for another element on the page.

Example: http://jsfiddle.net/redler/eLD9A/


问:
Setting a TextBox's .Text to "" or String.Empty does not show up in the GUI. Do I have to force a GUI update?
Code is running on main thread.
Code is:

```<code>OutputBox.Text = String.Empty; //have tried ""
var auto = new AutoGram(PrefixBox.Text, (int)SeedNum.Value,
     CharsBox.Text.ToCharArray(), SuffixBox.Text); //Just something for my program.
OutputBox.Text = auto.Execute(); //Again shouldn't be relevant.
</code>```

This code runs on click of a "Run" button. I want the outputbox to be cleared upon this button's click and then filled in when the code executes.
I have placed breakpoints everywhere and the text setting does show up as edited in visual studio, but not in the application's GUI. Thanks so much.

答:
A few things to consider:

if auto.Execute() takes 'forever' to complete, then you may want to have an Application.DoEvents() statement after you set the output box text to string.Empty to allow the OS an opportunity to update the GUI while your code is executing. You may also want to consider running the function in a backgroundWorker.

Set the return value from auto.Execute() to a string variable, then put a breakpoint when you assign the string variable to the OutputBox to evaluate the string when it is returned.  There are sequences that can exist that will cause the string to not display.  One example would be "\0whatever"

For example:

```<code>string foo = "whatever";
string bar = "\0whatever";
OutputBox.Text = foo;  \\\\ displays whatever
OutputBox.Text = bar;  \\\\ displays nothing.
</code>```

This is because \0 is being interpreted as end of string.

Body:
Code is running on main thread.
Code is:

OutputBox.Text = String.Empty; //have tried ""
var auto = new AutoGram(PrefixBox.Text, (int)SeedNum.Value,
     CharsBox.Text.ToCharArray(), SuffixBox.Text); //Just something for my program.
OutputBox.Text = auto.Execute(); //Again shouldn't be relevant.

This code runs on click of a "Run" button. I want the outputbox to be cleared upon this button's click and then filled in when the code executes.
I have placed breakpoints everywhere and the text setting does show up as edited in visual studio, but not in the application's GUI. Thanks so much.

Body:
A few things to consider:

if auto.Execute() takes 'forever' to complete, then you may want to have an Application.DoEvents() statement after you set the output box text to string.Empty to allow the OS an opportunity to update the GUI while your code is executing. You may also want to consider running the function in a backgroundWorker.

Set the return value from auto.Execute() to a string variable, then put a breakpoint when you assign the string variable to the OutputBox to evaluate the string when it is returned.  There are sequences that can exist that will cause the string to not display.  One example would be "\0whatever"

For example:

string foo = "whatever";
string bar = "\0whatever";
OutputBox.Text = foo;  \\\\ displays whatever
OutputBox.Text = bar;  \\\\ displays nothing.

This is because \0 is being interpreted as end of string.


问:
select box auto select
I want to create auto select box using jQuery or JavaScript.I have four select box. If I choose one select box from every select box, I want to choose auto select for other select box. Now, my design is depending on first select box. How can I do that ? Please help me.

html

```<code><select name="select1" id="select1">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>

<select name="select2" id="select2">
    <option value="1">Banana</option>
    <option value="1">Apple</option>
    <option value="1">Orange</option>
    <option value="2">Wolf</option>
    <option value="2">Fox</option>
    <option value="2">Bear</option>
    <option value="3">Eagle</option>
    <option value="3">Hawk</option>
    <option value="4">BWM<option>
</select>

<select name="select3" id="select3">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>
</code>```

javascript

```<code>var $select1 = $( '#select1' ),
    $select2 = $( '#select2' ),
    $select3 = $( '#select3' ),
    $select4 = $( '#select4' ),
$option2 = $select2.find( 'option' ),
$option3 = $select3.find( 'option' ),
$option4 = $select4.find( 'option' );
$select1.on( 'change', function() {
$select2.html( $option2.filter( '[value="' + this.value + '"]' ) ),
$select3.html( $option3.filter( '[value="' + this.value + '"]' ) ),
$select4.html( $option4.filter( '[value="' + this.value + '"]' ) );
} ).trigger( 'change' );
</code>```

答:
you need to store your values in arrays and according to your first dropdown selection you need to assign respected array values to seccont dropdown

I cant understand what is dropdown2 and dropdown3?

```<code>var $select1 = $( '#select1' ),
    $select2 = $( '#select2' ),
    $select3 = $( '#select3' ),
    $select4 = $( '#select4' ),
$option2 = $select2.find( 'option' ),
$option3 = $select3.find( 'option' ),
$option4 = $select4.find( 'option' );

var objectTypeValues = ['Fruit','Animal','Bird','Car'];
var fruiteValues = ['Banana','Apple','Orange',''];
var carValues = ['BWM'];
var animalValues = ['Wolf','Fox','Bear'];
var birdValues = ['Eagle','Hawk'];

$select1.on( 'change', function() {
  var valuesTobeBind = null;
  console.log(this.value);
  switch(this.value){
    case 'Fruit':
      valuesTobeBind = fruiteValues;
        break;
      case 'Animal':
      valuesTobeBind = animalValues;
        break;
      case 'Bird':
      valuesTobeBind = birdValues;
        break;
      case 'Car':
      valuesTobeBind = carValues;
        break;
  }

  $select2.html('');
  var selecthtml;
  for (var i = 0; i<=valuesTobeBind.length; i++){
    selecthtml+='<option value="'+  valuesTobeBind[i]+'">'+  valuesTobeBind[i]+'</option>';
  }
  $select2.html(selecthtml);

});
</code>```

Please ignore select3 and select4 from my code

Title: select box auto select

Body:
I want to create auto select box using jQuery or JavaScript.I have four select box. If I choose one select box from every select box, I want to choose auto select for other select box. Now, my design is depending on first select box. How can I do that ? Please help me.

html

<select name="select1" id="select1">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>

<select name="select2" id="select2">
    <option value="1">Banana</option>
    <option value="1">Apple</option>
    <option value="1">Orange</option>
    <option value="2">Wolf</option>
    <option value="2">Fox</option>
    <option value="2">Bear</option>
    <option value="3">Eagle</option>
    <option value="3">Hawk</option>
    <option value="4">BWM<option>
</select>

<select name="select3" id="select3">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>

javascript

var $select1 = $( '#select1' ),
    $select2 = $( '#select2' ),
    $select3 = $( '#select3' ),
    $select4 = $( '#select4' ),
$option2 = $select2.find( 'option' ),
$option3 = $select3.find( 'option' ),
$option4 = $select4.find( 'option' );
$select1.on( 'change', function() {
$select2.html( $option2.filter( '[value="' + this.value + '"]' ) ),
$select3.html( $option3.filter( '[value="' + this.value + '"]' ) ),
$select4.html( $option4.filter( '[value="' + this.value + '"]' ) );
} ).trigger( 'change' );

Body:
you need to store your values in arrays and according to your first dropdown selection you need to assign respected array values to seccont dropdown

I cant understand what is dropdown2 and dropdown3?

var $select1 = $( '#select1' ),
    $select2 = $( '#select2' ),
    $select3 = $( '#select3' ),
    $select4 = $( '#select4' ),
$option2 = $select2.find( 'option' ),
$option3 = $select3.find( 'option' ),
$option4 = $select4.find( 'option' );

var objectTypeValues = ['Fruit','Animal','Bird','Car'];
var fruiteValues = ['Banana','Apple','Orange',''];
var carValues = ['BWM'];
var animalValues = ['Wolf','Fox','Bear'];
var birdValues = ['Eagle','Hawk'];

$select1.on( 'change', function() {
  var valuesTobeBind = null;
  console.log(this.value);
  switch(this.value){
    case 'Fruit':
      valuesTobeBind = fruiteValues;
        break;
      case 'Animal':
      valuesTobeBind = animalValues;
        break;
      case 'Bird':
      valuesTobeBind = birdValues;
        break;
      case 'Car':
      valuesTobeBind = carValues;
        break;
  }

  $select2.html('');
  var selecthtml;
  for (var i = 0; i<=valuesTobeBind.length; i++){
    selecthtml+='<option value="'+  valuesTobeBind[i]+'">'+  valuesTobeBind[i]+'</option>';
  }
  $select2.html(selecthtml);

});

Please ignore select3 and select4 from my code


问:
NSString drawInRect with 2 different font style
I have this following text coming from server. i need to change the font style depending on the result before sending out to the printer from device.

1.
Driver
Id #123445
Verified

2.
Driver
Id #123445
UNVERIFIED

if text has UNVERIFIED i need to bold that unverified text part.

currently i do following to create image

```<code>   CGRect text10Rect = CGRectMake(DateTextRect.origin.x, CGRectGetMaxY(DateTextRect) + 40, DateTextRect.size.width, CGRectGetHeight(frame) - CGRectGetMaxY(DateTextRect) + 20 - 10);
        [strokeColor setFill];
 [stringFromServer drawInRect: text10Rect withFont: smallFont lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentLeft];
</code>```

i was thinking checking if it has UNVERIFIED then apply bold font to it. but couldnt figure out good way to do that.

答:
I endedup doing following method.</p>

```<code>if([stringFromServer containsString:@"UNVERIFIED"]){
            stringFromServer = [firstBlock stringByReplacingOccurrencesOfString:@"UNVERIFIED" withString:@""];

            CGRect text10Rect = CGRectMake(DateTextRect.origin.x, CGRectGetMaxY(DateTextRect) + 40, DateTextRect.size.width, CGRectGetHeight(frame) - CGRectGetMaxY(DateTextRect) + 20 - 10);
            [strokeColor setFill];
            [stringFromServer drawInRect: text10Rect withFont: smallFont lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentLeft];

            CGRect text11Rect = CGRectMake(DateTextRect.origin.x, CGRectGetMaxY(DateTextRect) + 130, DateTextRect.size.width, CGRectGetHeight(frame) - CGRectGetMaxY(DateTextRect) + 20 - 10);
            [strokeColor setFill];
            [@"UNVERIFIED" drawInRect: text11Rect withFont: smallFontBold lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentLeft];

        }else{
            CGRect text10Rect = CGRectMake(DateTextRect.origin.x, CGRectGetMaxY(DateTextRect) + 40, DateTextRect.size.width, CGRectGetHeight(frame) - CGRectGetMaxY(DateTextRect) + 20 - 10);
            [strokeColor setFill];
            [stringFromServer drawInRect: text10Rect withFont: smallFont lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentLeft];
        }
</code>```

Body:
I have this following text coming from server. i need to change the font style depending on the result before sending out to the printer from device.

1.
Driver
Id #123445
Verified

2.
Driver
Id #123445
UNVERIFIED

if text has UNVERIFIED i need to bold that unverified text part.

currently i do following to create image

   CGRect text10Rect = CGRectMake(DateTextRect.origin.x, CGRectGetMaxY(DateTextRect) + 40, DateTextRect.size.width, CGRectGetHeight(frame) - CGRectGetMaxY(DateTextRect) + 20 - 10);
        [strokeColor setFill];
 [stringFromServer drawInRect: text10Rect withFont: smallFont lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentLeft];

i was thinking checking if it has UNVERIFIED then apply bold font to it. but couldnt figure out good way to do that.

Body:
I endedup doing following method.

if([stringFromServer containsString:@"UNVERIFIED"]){
            stringFromServer = [firstBlock stringByReplacingOccurrencesOfString:@"UNVERIFIED" withString:@""];

            CGRect text10Rect = CGRectMake(DateTextRect.origin.x, CGRectGetMaxY(DateTextRect) + 40, DateTextRect.size.width, CGRectGetHeight(frame) - CGRectGetMaxY(DateTextRect) + 20 - 10);
            [strokeColor setFill];
            [stringFromServer drawInRect: text10Rect withFont: smallFont lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentLeft];

            CGRect text11Rect = CGRectMake(DateTextRect.origin.x, CGRectGetMaxY(DateTextRect) + 130, DateTextRect.size.width, CGRectGetHeight(frame) - CGRectGetMaxY(DateTextRect) + 20 - 10);
            [strokeColor setFill];
            [@"UNVERIFIED" drawInRect: text11Rect withFont: smallFontBold lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentLeft];

        }else{
            CGRect text10Rect = CGRectMake(DateTextRect.origin.x, CGRectGetMaxY(DateTextRect) + 40, DateTextRect.size.width, CGRectGetHeight(frame) - CGRectGetMaxY(DateTextRect) + 20 - 10);
            [strokeColor setFill];
            [stringFromServer drawInRect: text10Rect withFont: smallFont lineBreakMode: NSLineBreakByWordWrapping alignment: NSTextAlignmentLeft];
        }


问:
Pythonic way of sum of dot product of two list of lists
How can this be done elegantly (Pythonic way)

You have two matrices A and B represented each by a list of lists.

You would like to calculate the overall sum over the matrix of element-wise product of A and B.

sample code:

```<code>sum = 0
nrows = len(A)
ncols = len(A[0])
for i in range(nrows):
    for j in range(ncols):
        sum += A[i][j]*B[i][j]

# interested finally in the value of sum
# return sum
</code>```

for example if

A=[[1,2,3],[3,4,5]]

and

B=[[3,2,2],[1,1,1]]

the result is :

1*3 + 2*2 + 3*2 + 3*1 + 4*1 + 5*1 = 25

答:
If the matrices are always 2D, you could do

```<code>sum(sum(a * b for a, b in zip(*rows)) for rows in zip(A, B))
</code>```

IDEOne Link

Body:
How can this be done elegantly (Pythonic way)

You have two matrices A and B represented each by a list of lists.

You would like to calculate the overall sum over the matrix of element-wise product of A and B.

sample code:

sum = 0
nrows = len(A)
ncols = len(A[0])
for i in range(nrows):
    for j in range(ncols):
        sum += A[i][j]*B[i][j]

# interested finally in the value of sum
# return sum

for example if

A=[[1,2,3],[3,4,5]]

and

B=[[3,2,2],[1,1,1]]

the result is :

1*3 + 2*2 + 3*2 + 3*1 + 4*1 + 5*1 = 25

Body:
If the matrices are always 2D, you could do

sum(sum(a * b for a, b in zip(*rows)) for rows in zip(A, B))

IDEOne Link


问:
Why the group do not shows its users(it contains the test02) in user_set?
I have a user test02, and you can see there is 售后组 group in its groups:

```<code>{
        "id": 3,
        "account": null,
        "last_login": null,
        "username": "test02",
        ...
        "is_admin": false,
        "is_staff": false,
        "is_superuser": false,
        "status": "1",
        "groups": [
            {
                "id": 3,
                "name": "售后组",
                "permissions": [
                    13
                ]
            }
        ],
        "user_permissions": []
    }
</code>```

But when I use group.user_set to check the group's users, it shows None.

```<code>try:
    group = Group.objects.get(pk=group_id)  # there I get `售后组 group`
    users = group.user_set

    for user in users:
        message = Message.objects.create(
            title = title,
            content = content,
            create_user = create_user,

        )
        message.save()
        message.receive_user.add(user)

except Exception as e:
    raise e
</code>```

Why the 售后组 group do not shows its users(it contains the test02)?

答:
Instead of:

```<code>users = group.user_set
</code>```

Try:

```<code>users = group.user_set.all()
</code>```

Body:
I have a user test02, and you can see there is 售后组 group in its groups:

{
        "id": 3,
        "account": null,
        "last_login": null,
        "username": "test02",
        ...
        "is_admin": false,
        "is_staff": false,
        "is_superuser": false,
        "status": "1",
        "groups": [
            {
                "id": 3,
                "name": "售后组",
                "permissions": [
                    13
                ]
            }
        ],
        "user_permissions": []
    }

But when I use group.user_set to check the group's users, it shows None.

try:
    group = Group.objects.get(pk=group_id)  # there I get `售后组 group`
    users = group.user_set

    for user in users:
        message = Message.objects.create(
            title = title,
            content = content,
            create_user = create_user,

        )
        message.save()
        message.receive_user.add(user)

except Exception as e:
    raise e

Why the 售后组 group do not shows its users(it contains the test02)?

Body:
Instead of:

users = group.user_set

Try:

users = group.user_set.all()