问:
Python selecting row from second dataframe based on complex criteria
I have two dataframes, one with some purchasing data, and one with a weekly calendar, e.g.

```<code>df1:
purchased_at  product_id  cost
01-01-2017    1           £10
01-01-2017    2           £8
09-01-2017    1           £10
18-01-2017    3           £12

df2:
week_no  week_start  week_end
1        31-12-2016  06-01-2017
2        07-01-2017  13-01-2017
3        14-01-2017  20-01-2017
</code>```

I want to use data from the two to add a 'week_no' column to df1, which is selected from df2 based on where the 'purchased_at' date in df1 falls between the 'week_start' and 'week_end' dates in df2, i.e.

```<code>df1:
purchased_at  product_id  cost  week_no
01-01-2017    1           £10   1
01-01-2017    2           £8    1
09-01-2017    1           £10   2
18-01-2017    3           £12   3
</code>```

I've searched but I've not been able to find an example where the data is being pulled from a second dataframe using comparisons between the two, and I've been unable to correctly apply any examples I've found, e.g.

```<code>df1.loc[(df1['purchased_at'] < df2['week_end']) &
        (df1['purchased_at'] > df2['week_start']), df2['week_no']
</code>```

was unsuccessful, with the ValueError 'can only compare identically-labeled Series objects'

Could anyone help with this problem, or I'm open to suggestions if there is a better way to achieve the same outcome.

edit to add further detail of df1

df1 full dataframe headers

```<code>purchased_at  purchase_id  product_id  product_name  transaction_id  account_number  cost
01-01-2017    1            1           A             1               AA001           £10
01-01-2017    2            2           B             1               AA001           £8
02-01-2017    3            1           A             2               AA008           £10
03-01-2017    4            3           C             3               AB040           £12
...
09-01-2017   12            1           A             10              AB102           £10
09-01-2017   13            2           B             11              AB102           £8
...
18-01-2017   20            3           C             15              AA001           £12
</code>```

So the purchase_id increases incrementally with each row, the product_id and product_name have a 1:1 relationship, the transaction_id also increases incrementally, but there can be multiple purchases within a transaction.

答:
You could just use time.strftime() to extract the week number from the date. If you want to keep counting the weeks upwards, you need to define a "zero year" as the start of your time-series and offset the week_no accordingly:

```<code>import pandas as pd

data = {'purchased_at': ['01-01-2017', '01-01-2017', '09-01-2017', '18-01-2017'], 'product_id': [1,2,1,3], 'cost':['£10', '£8', '£10', '£12']}

df = pd.DataFrame(data, columns=['purchased_at', 'product_id', 'cost'])

def getWeekNo(date, year0):
    datetime = pd.to_datetime(date, dayfirst=True)
    year = int(datetime.strftime('%Y'))
    weekNo = int(datetime.strftime('%U'))
    return weekNo + 52*(year-year0)

df['week_no'] = df.purchased_at.apply(lambda x: getWeekNo(x, 2017))
</code>```

Here, I use pd.to_dateime() to convert the datestring from df into a datetime-object. strftime('%Y') returns the year and strftime('%U') the week (with the first week of a year starting on it's first Sunday. If weeks should start on Monday, use '%W' instead).

This way, you don't need to maintain a seperate DataFrame only for week numbers.

Body:
I have two dataframes, one with some purchasing data, and one with a weekly calendar, e.g.

df1:
purchased_at  product_id  cost
01-01-2017    1           £10
01-01-2017    2           £8
09-01-2017    1           £10
18-01-2017    3           £12

df2:
week_no  week_start  week_end
1        31-12-2016  06-01-2017
2        07-01-2017  13-01-2017
3        14-01-2017  20-01-2017

I want to use data from the two to add a 'week_no' column to df1, which is selected from df2 based on where the 'purchased_at' date in df1 falls between the 'week_start' and 'week_end' dates in df2, i.e.

df1:
purchased_at  product_id  cost  week_no
01-01-2017    1           £10   1
01-01-2017    2           £8    1
09-01-2017    1           £10   2
18-01-2017    3           £12   3

I've searched but I've not been able to find an example where the data is being pulled from a second dataframe using comparisons between the two, and I've been unable to correctly apply any examples I've found, e.g.

df1.loc[(df1['purchased_at'] < df2['week_end']) &
        (df1['purchased_at'] > df2['week_start']), df2['week_no']

was unsuccessful, with the ValueError 'can only compare identically-labeled Series objects'

Could anyone help with this problem, or I'm open to suggestions if there is a better way to achieve the same outcome.

edit to add further detail of df1

df1 full dataframe headers

purchased_at  purchase_id  product_id  product_name  transaction_id  account_number  cost
01-01-2017    1            1           A             1               AA001           £10
01-01-2017    2            2           B             1               AA001           £8
02-01-2017    3            1           A             2               AA008           £10
03-01-2017    4            3           C             3               AB040           £12
...
09-01-2017   12            1           A             10              AB102           £10
09-01-2017   13            2           B             11              AB102           £8
...
18-01-2017   20            3           C             15              AA001           £12

So the purchase_id increases incrementally with each row, the product_id and product_name have a 1:1 relationship, the transaction_id also increases incrementally, but there can be multiple purchases within a transaction.

Body:
You could just use time.strftime() to extract the week number from the date. If you want to keep counting the weeks upwards, you need to define a "zero year" as the start of your time-series and offset the week_no accordingly:

import pandas as pd

data = {'purchased_at': ['01-01-2017', '01-01-2017', '09-01-2017', '18-01-2017'], 'product_id': [1,2,1,3], 'cost':['£10', '£8', '£10', '£12']}

df = pd.DataFrame(data, columns=['purchased_at', 'product_id', 'cost'])

def getWeekNo(date, year0):
    datetime = pd.to_datetime(date, dayfirst=True)
    year = int(datetime.strftime('%Y'))
    weekNo = int(datetime.strftime('%U'))
    return weekNo + 52*(year-year0)

df['week_no'] = df.purchased_at.apply(lambda x: getWeekNo(x, 2017))

Here, I use pd.to_dateime() to convert the datestring from df into a datetime-object. strftime('%Y') returns the year and strftime('%U') the week (with the first week of a year starting on it's first Sunday. If weeks should start on Monday, use '%W' instead).

This way, you don't need to maintain a seperate DataFrame only for week numbers.


来源: stackexchange

问:
How to retrieve entity names in CRM 2016
In our solution, we are building HTTP/ODATA requests dynamically.

For example, we will build a URL that looks like this:

```<code>[http://org....api/v8.1/]accounts(00000000-0000-0000-0000-000000000001)/primarycontactid?$select=fullname
</code>```

How do we dynamically get a list of all the entities such as 'accounts'?

In 2011, we would simply execute against LeadSet/AccountSet/etcSet, what is the strategy in 2016?

答:
1.To get all the entities available in your crm:

```<code>https://<your org name>.crm.dynamics.com/api/data/v8.2/
</code>```

2.To get all the records metadata information (Retrieve Multiple Records):

```<code>https://<your org name>.crm.dynamics.com/api/data/v8.2/accounts?
</code>```

3.To get the specific record email address information (Retrieve Single Record). What ever we chose the attributes in the select clause, we can get those attributes information in the result:

```<code>https://<your org name>.crm.dynamics.com/api/data/v8.2/accounts?$select=emailaddress1&$filter=accountid eq <GUID goes here>
</code>```

4.To get entire metadata information in the CRM:

```<code>https://<your org name>.crm.dynamics.com/api/data/v8.2/EntityDefinitions
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In our solution, we are building HTTP/ODATA requests dynamically.

For example, we will build a URL that looks like this:

[http://org....api/v8.1/]accounts(00000000-0000-0000-0000-000000000001)/primarycontactid?$select=fullname

How do we dynamically get a list of all the entities such as 'accounts'?

In 2011, we would simply execute against LeadSet/AccountSet/etcSet, what is the strategy in 2016?

Body:
1.To get all the entities available in your crm:

https://<your org name>.crm.dynamics.com/api/data/v8.2/

2.To get all the records metadata information (Retrieve Multiple Records):

https://<your org name>.crm.dynamics.com/api/data/v8.2/accounts?

3.To get the specific record email address information (Retrieve Single Record). What ever we chose the attributes in the select clause, we can get those attributes information in the result:

https://<your org name>.crm.dynamics.com/api/data/v8.2/accounts?$select=emailaddress1&$filter=accountid eq <GUID goes here>

4.To get entire metadata information in the CRM:

https://<your org name>.crm.dynamics.com/api/data/v8.2/EntityDefinitions


问:
Disable last checkbox multiple choice required
Scenario :

I have a vote page, you have to select 3 of 4 candidates from the list.

Needs :

I need to make the last checkbox disabled after checking 3 of them (4).

Code :

HTML

```<code><input class="cb" type="checkbox" name="condidate" value="1" onchange="cbChange(this)" />
<input class="cb" type="checkbox" name="condidate" value="2" onchange="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="3" onchange="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="4" onchange="cbChange(this)"/>
</code>```

JS

```<code>function cbChange(obj) {
    var cbs = document.getElementsByClassName("cb");
    for (var i = 0; i < cbs.length - 3; i++) {
        cbs[i].disabled = true;
    }
    obj.disabled = false;
}
</code>```

Question :

How Can I make the last choice disabled after selecting the 3 others.

答:
you need to call cbChange on click event of checkboxes.

function cbChange(obj) {
    var cbs = document.getElementsByClassName("cb");
    var checkCount = 0;
    for (var i = 0; i < cbs.length; i++) {
        if (cbs[i].checked === true)
  checkCount++;
        cbs[i].disabled = false;
    }
    if (checkCount >= 3){
     for (var i = 0; i < cbs.length; i++) {
  if (cbs[i].checked === false)
   cbs[i].disabled = true;
     }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <input class="cb" type="checkbox" name="condidate" value="1" onclick="cbChange(this)"/>
    <input class="cb" type="checkbox" name="condidate" value="2" onclick="cbChange(this)"/>
    <input class="cb" type="checkbox" name="condidate" value="3" onclick="cbChange(this)"/>
    <input class="cb" type="checkbox" name="condidate" value="4" onclick="cbChange(this)"/>

 </code>```

Body:
Scenario :

I have a vote page, you have to select 3 of 4 candidates from the list.

Needs :

I need to make the last checkbox disabled after checking 3 of them (4).

Code :

HTML

<input class="cb" type="checkbox" name="condidate" value="1" onchange="cbChange(this)" />
<input class="cb" type="checkbox" name="condidate" value="2" onchange="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="3" onchange="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="4" onchange="cbChange(this)"/>

JS

function cbChange(obj) {
    var cbs = document.getElementsByClassName("cb");
    for (var i = 0; i < cbs.length - 3; i++) {
        cbs[i].disabled = true;
    }
    obj.disabled = false;
}

Question :

How Can I make the last choice disabled after selecting the 3 others.

Body:
you need to call cbChange on click event of checkboxes.

function cbChange(obj) {
    var cbs = document.getElementsByClassName("cb");
    var checkCount = 0;
    for (var i = 0; i < cbs.length; i++) {
        if (cbs[i].checked === true)
  checkCount++;
        cbs[i].disabled = false;
    }
    if (checkCount >= 3){
     for (var i = 0; i < cbs.length; i++) {
  if (cbs[i].checked === false)
   cbs[i].disabled = true;
     }
    }
}

    <input class="cb" type="checkbox" name="condidate" value="1" onclick="cbChange(this)"/>
    <input class="cb" type="checkbox" name="condidate" value="2" onclick="cbChange(this)"/>
    <input class="cb" type="checkbox" name="condidate" value="3" onclick="cbChange(this)"/>
    <input class="cb" type="checkbox" name="condidate" value="4" onclick="cbChange(this)"/>


问:
while loop result at table, sends first row when submit form in php
1.fetch user data and display in tabular fashion

```<code>                  <?php
                      while($row=mysqli_fetch_assoc($rResultSet))
                     {
                   ?>

                  <td><?php echo $row['id']?></td>
                  <td><?php echo $row['name']?></td>
                  <td><?php echo $row['user_role']?></td>
                  <td><?php echo $row['start_date']?></td>
                  <td>

                  <form id='euser' action='edituser.php' method='post'>
                  <input type="hidden" name="id" value="<?php echo $row['id']?>">
                  <input type="hidden" name="type" value="edituser">

                  <a  href="javascript: document.getElementById('euser').submit();">Edit</i></a>|
                 </form>
                 <?php
                 }
                 ?>
</code>```

result of this code

2.when click on Edit link every time first id which 16 throw by form

i need , when press link  edit at id 17 then id 17 thrown by form

答:
Try below if it help :</p>

```<code><?php
    while($row=mysqli_fetch_assoc($rResultSet))
{
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['user_role'];?></td>
<td><?php echo $row['start_date'];?></td>
<td>

    <form id='<?php echo $row['id'];?>' action='edituser.php' method='post'>
        <input type="hidden" name="id" value="<?php echo $row['id'];?>">
        <input type="hidden" name="type" value="edituser">

        <a  href="javascript: document.getElementById('<?php echo $row['id'];?>').submit();">Edit</a>|
    </form>
</td>
</tr>
 <?php
   }
 ?>
</code>```

Body:
1.fetch user data and display in tabular fashion

                  <?php
                      while($row=mysqli_fetch_assoc($rResultSet))
                     {
                   ?>

                  <?php echo $row['id']?>
                  <?php echo $row['name']?>
                  <?php echo $row['user_role']?>
                  <?php echo $row['start_date']?>

                  <form id='euser' action='edituser.php' method='post'>
                  <input type="hidden" name="id" value="<?php echo $row['id']?>">
                  <input type="hidden" name="type" value="edituser">

                  Edit|
                 </form>
                 <?php
                 }
                 ?>

result of this code

2.when click on Edit link every time first id which 16 throw by form

i need , when press link  edit at id 17 then id 17 thrown by form

Body:
Try below if it help :

<?php
    while($row=mysqli_fetch_assoc($rResultSet))
{
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['user_role'];?></td>
<td><?php echo $row['start_date'];?></td>
<td>

    <form id='<?php echo $row['id'];?>' action='edituser.php' method='post'>
        <input type="hidden" name="id" value="<?php echo $row['id'];?>">
        <input type="hidden" name="type" value="edituser">

        <a  href="javascript: document.getElementById('<?php echo $row['id'];?>').submit();">Edit</a>|
    </form>
</td>
</tr>
 <?php
   }
 ?>


答: When one of the checkboxes has changed, count the number that are unchecked.  If there is only one, you can disable it; otherwise, if one is disabled, it must be re-enabled.</p>

Title: Disable last checkbox multiple choice required


问:
I want to compare date of duration of leaves with the current date in odoo python
Here is the program which i wrote and inherited from hr.holidays
that if the selected date is before the current date then it should provide an error message.
Code-

```<code>from datetime import date

if self.date_from <= date.today():
            print 'You cannot select the previous date'
</code>```

But it gives the error-

```<code>TypeError: can't compare datetime.date to bool
</code>```

Thanks

答:
Hello Ujjwal Singh Baghel,

Try this below code,

```<code>#!/usr/bin/python
import datetime
i = datetime.datetime.now()

print ("Current date & time = %s" % i)

if self.date_from <= str(i):
            print 'You cannot select the previous date'
</code>```

OR

```<code>from datetime import date
if self.date_from <= str(date.today()):
            print 'You cannot select the previous date'
</code>```

For example

```<code>from datetime import date
if "10/07/2017" <= str(date.today()):
            print 'You cannot select the previous date'
</code>```

Out put:

You cannot select the previous date

I hope my answer is helpful.
If any query so comments, please.

Body:
Here is the program which i wrote and inherited from hr.holidays
that if the selected date is before the current date then it should provide an error message.
Code-

from datetime import date

if self.date_from <= date.today():
            print 'You cannot select the previous date'

But it gives the error-

TypeError: can't compare datetime.date to bool

Thanks

Body:
Hello Ujjwal Singh Baghel,

Try this below code,

#!/usr/bin/python
import datetime
i = datetime.datetime.now()

print ("Current date & time = %s" % i)

if self.date_from <= str(i):
            print 'You cannot select the previous date'

OR

from datetime import date
if self.date_from <= str(date.today()):
            print 'You cannot select the previous date'

For example

from datetime import date
if "10/07/2017" <= str(date.today()):
            print 'You cannot select the previous date'

Out put:

You cannot select the previous date

I hope my answer is helpful.
If any query so comments, please.


问:
Reacting to orientation changes without .faceUp and .faceDown
I have a UIView that appears/disappears with an animation when the device is in portrait/landscape mode.

I am doing it like this:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationChanged), name: Notification.Name.UIDeviceOrientationDidChange, object: nil)
}

func deviceOrientationChanged() {
        switch UIDevice.current.orientation {
        case .portrait:
            //appear
        case .landscapeLeft, .landscapeRight:
            //disappear
        case default:
            //appear; here lies the problem
        }
    }
</code>```

The issue are .faceDown and .faceUp. I want to ignore the orientation changes to these orientation and have nothing change.
Putting them in the default: of the switch results in uneccessarily repeated animations when the device is put back into portrait.

I am sure I could hack together a solution. But I find the simplicity of the problem frustrating.

Is there a property that only informs about changes to .portrait, .landscapeRight, .landscapeLeft and .portraitUpsideDown?

答:
Yes interfaceOrientation has been deprecated, now you should use statusBarOrientation or traits and related methods to detect the current orientation or the changes in orientation.

I'd like to point you to this post, device orientation will not consider the eventual orientation lock that the user can set in the options.

While statusBarOrientation seems to be deprecated is apparently only on the setter as stated here from an Apple employee.

How could you present a landscape view controller in a portrait application? this is just one of the possible example:

```<code>// ApplicationDelegate overridden method
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if topController() is FullGraphViewController {
            return .all
        }  else {
            return .portrait
        }
    }
</code>```

Basically I say that when a FullGraphViewController is presented it can be displayed in all possible orientations.

```<code>// FullgraphViewController overridden methods
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if landActive {
            return [UIInterfaceOrientationMask.allButUpsideDown]
        }
        return [UIInterfaceOrientationMask.portrait]
    }

    override var shouldAutorotate: Bool {
        return true
    }

    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
</code>```

Here I'm saying that view should be presented in portrait this will lead to a nice orientation animation, the view can rotate and if landscape flag is active it can rotate in all orientation except upside-down.

To intercept orientation changes you can:

Use device orientation changes, but only to trigger the presentation of the landscape view controller

Use the traits variation callback to trigger the presentation, but your app is like mine and you have pick only portrait orientation in general settings you will not receive any of those call callbacks

Inside the orientation changes callback from the vc where you want to present the landscape interface, you can present your landscape view controller:

```<code>func orientationChanged(_ notification: Notification) {
    let orientation = UIDevice.current.orientation
    if UIDeviceOrientationIsValidInterfaceOrientation(orientation) && UIDeviceOrientationIsLandscape(orientation) {
        let vc = storyboard!.instantiateViewController(withIdentifier: Constants.ViewControllerIdentifiers.LandscapeFullGraphViewController) as! FullGraphViewController
        vc.title = navigatorViewController?.navigationBarView.barTitle
        vc.instrumentInfo = instrumentInfo
        vc.modalTransitionStyle = .crossDissolve
        present(vc, animated: true) {
            vc.landActive = true
        }
    }
}
</code>```

The landActive is a property of the FullGraphViewController that when is set asks the rotation from port to landscape to begin.

```<code>var landActive = true {
        didSet(old) {
            UIViewController.attemptRotationToDeviceOrientation()
            view.setNeedsLayout()
            view.layoutIfNeeded()
        }
    }
</code>```

Please note the function UIDeviceOrientationIsValidInterfaceOrientation, that is very important and discharges faceup and facedown.

Body:
I have a UIView that appears/disappears with an animation when the device is in portrait/landscape mode.

I am doing it like this:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationChanged), name: Notification.Name.UIDeviceOrientationDidChange, object: nil)
}

func deviceOrientationChanged() {
        switch UIDevice.current.orientation {
        case .portrait:
            //appear
        case .landscapeLeft, .landscapeRight:
            //disappear
        case default:
            //appear; here lies the problem
        }
    }

The issue are .faceDown and .faceUp. I want to ignore the orientation changes to these orientation and have nothing change.
Putting them in the default: of the switch results in uneccessarily repeated animations when the device is put back into portrait.

I am sure I could hack together a solution. But I find the simplicity of the problem frustrating.

Is there a property that only informs about changes to .portrait, .landscapeRight, .landscapeLeft and .portraitUpsideDown?

Body:
Yes interfaceOrientation has been deprecated, now you should use statusBarOrientation or traits and related methods to detect the current orientation or the changes in orientation.

I'd like to point you to this post, device orientation will not consider the eventual orientation lock that the user can set in the options.

While statusBarOrientation seems to be deprecated is apparently only on the setter as stated here from an Apple employee.

How could you present a landscape view controller in a portrait application? this is just one of the possible example:

// ApplicationDelegate overridden method
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if topController() is FullGraphViewController {
            return .all
        }  else {
            return .portrait
        }
    }

Basically I say that when a FullGraphViewController is presented it can be displayed in all possible orientations.

// FullgraphViewController overridden methods
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if landActive {
            return [UIInterfaceOrientationMask.allButUpsideDown]
        }
        return [UIInterfaceOrientationMask.portrait]
    }

    override var shouldAutorotate: Bool {
        return true
    }

    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }

Here I'm saying that view should be presented in portrait this will lead to a nice orientation animation, the view can rotate and if landscape flag is active it can rotate in all orientation except upside-down.

To intercept orientation changes you can:

Use device orientation changes, but only to trigger the presentation of the landscape view controller

Use the traits variation callback to trigger the presentation, but your app is like mine and you have pick only portrait orientation in general settings you will not receive any of those call callbacks

Inside the orientation changes callback from the vc where you want to present the landscape interface, you can present your landscape view controller:

func orientationChanged(_ notification: Notification) {
    let orientation = UIDevice.current.orientation
    if UIDeviceOrientationIsValidInterfaceOrientation(orientation) && UIDeviceOrientationIsLandscape(orientation) {
        let vc = storyboard!.instantiateViewController(withIdentifier: Constants.ViewControllerIdentifiers.LandscapeFullGraphViewController) as! FullGraphViewController
        vc.title = navigatorViewController?.navigationBarView.barTitle
        vc.instrumentInfo = instrumentInfo
        vc.modalTransitionStyle = .crossDissolve
        present(vc, animated: true) {
            vc.landActive = true
        }
    }
}

The landActive is a property of the FullGraphViewController that when is set asks the rotation from port to landscape to begin.

var landActive = true {
        didSet(old) {
            UIViewController.attemptRotationToDeviceOrientation()
            view.setNeedsLayout()
            view.layoutIfNeeded()
        }
    }

Please note the function UIDeviceOrientationIsValidInterfaceOrientation, that is very important and discharges faceup and facedown.


问:
Adding UITableView on top of UIView
I want to add UITableView on top of UIView. Here's an image  of what exactly i want to do.
Sample code link/tutorial is appreciated.
Thanks

答: Is the image you've provided from a website? It looks very much like a combo box in a standard HTML file.</p>

ContentLicense: CC BY-SA 2.5

Title: Adding UITableView on top of UIView


问:
Getting error in sqlite like query in ionic1
I am using sqlite select query to retrieve the name from a list in which I have used the following select query with like but it gives me an error as NaN can anyone tell me what's wrong in this query.

```<code>var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE ' % '' + name + '' % ' ORDER BY name COLLATE NOCASE ASC';
</code>```

Error:

getAllSearchQuery:  SELECT DISTINCT * FROM phonebookNaNViNaN

答:
```<code>var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE \'%' + name + '%\' ORDER BY name COLLATE NOCASE ASC';
</code>```

because name is string, so need add ' or ", if your code is using ', so you need add a slash (\)

Body:
I am using sqlite select query to retrieve the name from a list in which I have used the following select query with like but it gives me an error as NaN can anyone tell me what's wrong in this query.

var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE ' % '' + name + '' % ' ORDER BY name COLLATE NOCASE ASC';

Error:

getAllSearchQuery:  SELECT DISTINCT * FROM phonebookNaNViNaN

Body:
var query = 'SELECT DISTINCT * FROM ' + tblName + ' WHERE name LIKE \'%' + name + '%\' ORDER BY name COLLATE NOCASE ASC';

because name is string, so need add ' or ", if your code is using ', so you need add a slash (\)


问:
How to concatenate QuerySets from a list of QuerySet
I come across this syntax on stackoverflow

```<code>from itertools import chain
result_list = list(chain(page_list, article_list, post_list))
</code>```

I need to concatenate a bunch of QuerySets with something like this:

```<code>    prjExpList = list(chain(lvl for lvl in prjlvl))
    prjEnvList = list(chain(env for env in prjEnv))
</code>```

This gives me an error of

```<code>AttributeError: 'QuerySet' object has no attribute '_meta'
</code>```

My goal is to concatenate a bunch of QuerySets that's stored inside a list prjlvl and prjEnv
How do I do that?

答:
Are the QuerySets of the same model? You can just do

```<code>combined_queryset = queryset_1 | queryset_2 | queryset_3
</code>```

To chain them together into one QuerySet. This means you can still do things with the QuerySet in the ORM, which is a big help.

Body:
I come across this syntax on stackoverflow

from itertools import chain
result_list = list(chain(page_list, article_list, post_list))

I need to concatenate a bunch of QuerySets with something like this:

    prjExpList = list(chain(lvl for lvl in prjlvl))
    prjEnvList = list(chain(env for env in prjEnv))

This gives me an error of

AttributeError: 'QuerySet' object has no attribute '_meta'

My goal is to concatenate a bunch of QuerySets that's stored inside a list prjlvl and prjEnv
How do I do that?

Body:
Are the QuerySets of the same model? You can just do

combined_queryset = queryset_1 | queryset_2 | queryset_3

To chain them together into one QuerySet. This means you can still do things with the QuerySet in the ORM, which is a big help.


答:
The problem is because of form's id attribute, it has to be unique for each row. Right now you're assigning the same id value euser for each row. For maintaining the uniqueness of id value, what you can do is, append the $row['id'] with euser for each table row. Also, you forgot to encapsulate each table row in
...
. So your code should be like this:

```<code><?php
    while($row=mysqli_fetch_assoc($rResultSet)){
    ?>
        <tr>
            <td><?php echo $row['id']?></td>
            <td><?php echo $row['name']?></td>
            <td><?php echo $row['user_role']?></td>
            <td><?php echo $row['start_date']?></td>
            <td>

            <form id='euser<?php echo $row['id']?>' action='edituser.php' method='post'>
                <input type="hidden" name="id" value="<?php echo $row['id']?>">
                <input type="hidden" name="type" value="edituser">

                <a  href="javascript: document.getElementById('euser<?php echo $row['id']?>').submit();">Edit</i></a>|
            </form>
        <tr>
    <?php
    }
?>
</code>```

Title: while loop result at table, sends first row when submit form in php

Body:
The problem is because of form's id attribute, it has to be unique for each row. Right now you're assigning the same id value euser for each row. For maintaining the uniqueness of id value, what you can do is, append the $row['id'] with euser for each table row. Also, you forgot to encapsulate each table row in <tr>...</tr>. So your code should be like this:

<?php
    while($row=mysqli_fetch_assoc($rResultSet)){
    ?>
        <tr>
            <td><?php echo $row['id']?></td>
            <td><?php echo $row['name']?></td>
            <td><?php echo $row['user_role']?></td>
            <td><?php echo $row['start_date']?></td>
            <td>

            <form id='euser<?php echo $row['id']?>' action='edituser.php' method='post'>
                <input type="hidden" name="id" value="<?php echo $row['id']?>">
                <input type="hidden" name="type" value="edituser">

                <a  href="javascript: document.getElementById('euser<?php echo $row['id']?>').submit();">Edit</i></a>|
            </form>
        <tr>
    <?php
    }
?>


问:
Dividing workload on several threads
I was wondering if anyone knows about a good article which describes dividing workload on to several Threads? Preferebly it would be written for C# but it's really the concept I'm after, so it's not an issue if it's written for a different, similar, language.

I have a problem where I would have to divide a large amount of computing into several threads and then Sum the generated data after one iteration completes (so I would need to know that all threads have finished) and then start a new iteration, supplying all the threads with the data generated in the last iteration (the data would be modified before the end of each iteration).

I hope this makes sense, and is possible. Either way I would appreciate some advice on how to tackle the problem of computing large amounts of data divided on to several threads (so I can use more than one processor's core).

Thank you for your answers!

答:
Paint.NET does this quite well (for image processing) and the source code to older versions of might still be freely available somewhere.

For more information, please move over to my question regarding a white paper by the author I once saw about this subject. When I wanted to show that article it to a co-worker recently I (that is: Google) was not able to find this any more, hence the question.

OwnerDisplayName: Rekreativc

Title: Dividing workload on several threads

OwnerDisplayName: peSHIr

LastEditorDisplayName: peSHIr


问:
expected `;' before "pennies"? C++ Debugging (Code Completed)
Can anyone tell me why I get an error on my last cout?

```<code>#include <iostream>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <conio.h>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int main()
{
 cout << "How many pennies do you have?\n";
 int pennies;
 cin >> pennies;
 double total_pen;
 total_pen = (0.01 * pennies);
           if (pennies >= 1)
           {
                       string penn = " pennies.";
           }else
           {
                       string penn = " penny.";
 } cout << "How many nickles do you have?\n";
 int nickles;
 cin >> nickles;
 double total_nic;
 total_nic = (0.05 * nickles);
           if (nickles >= 1)
           {
                       string five = " nickels.";
           }else
           {
                       string five = " nickel.";
 } cout << "How many dimes do you have?\n";
 int dimes;
 cin >> dimes;
 double total_dim;
 total_dim = (0.10 * dimes);
           if (dimes >= 1)
           {
                     string ten = " dimes.";
           }else
           {
                     string ten = " dime.";
 } cout << "How many quarters do you have?\n";
 int quarters;
 cin >> quarters;
 double total_qua;
 total_qua = (0.25 * quarters);
           if (quarters >= 1)
           {
                        string twentyfive = " quarters.";
           }else
           {
                        string twentyfive = " quarter.";
 } cout << "How many half-dollars do you have?\n";
 int half_dollars;
 cin >> half_dollars;
 double total_dol;
 total_dol = (0.50 * half_dollars);
           if (half_dollars >= 1)
           {
                        string fifty = " half dollars.";
           }else
           {
                        string fifty = " half dollar.";
           }
string saying = "You have ";
cout << saying pennies penn << "\n" << saying nickles five << "\n" << saying dimes ten << "\n" << saying quarters twentyfive << "\n" << saying half_dollars fifty << "\n";
keep_window_open()
return 0;
}
</code>```

答:
You're missing the << between the strings and the numbers. It should read:

```<code>cout << saying << pennies << penn << ...
</code>```

Body:
Can anyone tell me why I get an error on my last cout?

#include <iostream>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <conio.h>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int main()
{
 cout << "How many pennies do you have?\n";
 int pennies;
 cin >> pennies;
 double total_pen;
 total_pen = (0.01 * pennies);
           if (pennies >= 1)
           {
                       string penn = " pennies.";
           }else
           {
                       string penn = " penny.";
 } cout << "How many nickles do you have?\n";
 int nickles;
 cin >> nickles;
 double total_nic;
 total_nic = (0.05 * nickles);
           if (nickles >= 1)
           {
                       string five = " nickels.";
           }else
           {
                       string five = " nickel.";
 } cout << "How many dimes do you have?\n";
 int dimes;
 cin >> dimes;
 double total_dim;
 total_dim = (0.10 * dimes);
           if (dimes >= 1)
           {
                     string ten = " dimes.";
           }else
           {
                     string ten = " dime.";
 } cout << "How many quarters do you have?\n";
 int quarters;
 cin >> quarters;
 double total_qua;
 total_qua = (0.25 * quarters);
           if (quarters >= 1)
           {
                        string twentyfive = " quarters.";
           }else
           {
                        string twentyfive = " quarter.";
 } cout << "How many half-dollars do you have?\n";
 int half_dollars;
 cin >> half_dollars;
 double total_dol;
 total_dol = (0.50 * half_dollars);
           if (half_dollars >= 1)
           {
                        string fifty = " half dollars.";
           }else
           {
                        string fifty = " half dollar.";
           }
string saying = "You have ";
cout << saying pennies penn << "\n" << saying nickles five << "\n" << saying dimes ten << "\n" << saying quarters twentyfive << "\n" << saying half_dollars fifty << "\n";
keep_window_open()
return 0;
}

Body:
You're missing the << between the strings and the numbers. It should read:

cout << saying << pennies << penn << ...


问:
Error when I install samtools for python on windows
I am trying to install pysam and pybedtools modules on python 3.4. But I got an Error:

```<code>Collecting pysam
  Using cached pysam-0.9.0.tar.gz
    Complete output from command python setup.py egg_info:
    '.' is not recognized as an internal or external command,
    operable program or batch file.
    # pysam: htslib mode is shared
    # pysam: htslib configure options: None
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\ikirov.CLO\AppData\Local\Temp\pip-build-_me_xeme\pysam\setup.py", line 212, in <module>
        sys.abiflags)]
    AttributeError: 'module' object has no attribute 'abiflags'
</code>```

Could you please help me with it?

答:
Hi I got the same error last year during one of my class.

As I know back then, pysam simply won't work with python3 + windows environment.
See this: https://github.com/pysam-developers/pysam/issues/353 looks like it is still unsolved now.

For my homework, I just used this http://bow.codeplex.com/

And my suggestion, just try to use linux or get a python2. Yes I know the scientific field is the slowest for the 2->3 transition. It sucks.

Body:
I am trying to install pysam and pybedtools modules on python 3.4. But I got an Error:

Collecting pysam
  Using cached pysam-0.9.0.tar.gz
    Complete output from command python setup.py egg_info:
    '.' is not recognized as an internal or external command,
    operable program or batch file.
    # pysam: htslib mode is shared
    # pysam: htslib configure options: None
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\ikirov.CLO\AppData\Local\Temp\pip-build-_me_xeme\pysam\setup.py", line 212, in <module>
        sys.abiflags)]
    AttributeError: 'module' object has no attribute 'abiflags'

Could you please help me with it?


问:
Non-recursive add function in a binary tree using c++
I am writing an Add function to add nodes to a binary tree non recursively.
I have run into the problem of only being able to produce one level deep binary tree. I debugged it and I know where the problem is but can't figure out how to fix it. Maybe fresh pair of eyes will see something i dont...
The problem is that my temp node is being reset to the root value every new function call and hence, adding nodes linearly.
Anyways, here is the function:

```<code>   void BinaryTreeNonRec::add(int num){
        treeNode *temp, *parent;

        if (root==NULL) {
            root = new treeNode;
            root->data=num;
            root->left=0;
            root->right=0;
            temp=root;
            printf("value is root \n");
        } else {
            temp=root;
            while (temp!=NULL) {
                if (num <= temp->data){
                    parent = temp;
                    temp=temp->left;
                    //root =temp;
                    printf("value is to the left \n");
                } else {
                    parent =temp;
                    temp=temp->right;
                    //root=temp;
                    printf("value is to the right \n");
                }
            }
            parent = new treeNode;
            parent->data=num;
            parent->left=NULL;
            parent->right=NULL;
            temp=parent;
        }
}
</code>```

Thanks for any kind of help.

答:
Algo

if root == null  Create new node assign to Root

Keep iterating based on comparison with rootNode until reach any leaf Node

check if num <= parent(leaf) Insert into left ELSE insert into right

Code

```<code>private void insertItrInBST(int num){
    Node temp = root,parent = root;

    if(root == null){
        root = getNewNode(num);
    }else{
        temp = root;

        while(temp != null){
            if(num <= root.data){
                parent = temp;
                temp = temp.left;
            }else{
                parent = temp;
                temp = temp.right;
            }
        }
        Node newNode = getNewNode(num);
        if(num <= parent.data){
            parent.left = newNode;
        }else{
            parent.right = newNode;
        }
    }
}
</code>```

Body:
I am writing an Add function to add nodes to a binary tree non recursively.
I have run into the problem of only being able to produce one level deep binary tree. I debugged it and I know where the problem is but can't figure out how to fix it. Maybe fresh pair of eyes will see something i dont...
The problem is that my temp node is being reset to the root value every new function call and hence, adding nodes linearly.
Anyways, here is the function:

   void BinaryTreeNonRec::add(int num){
        treeNode *temp, *parent;

        if (root==NULL) {
            root = new treeNode;
            root->data=num;
            root->left=0;
            root->right=0;
            temp=root;
            printf("value is root \n");
        } else {
            temp=root;
            while (temp!=NULL) {
                if (num <= temp->data){
                    parent = temp;
                    temp=temp->left;
                    //root =temp;
                    printf("value is to the left \n");
                } else {
                    parent =temp;
                    temp=temp->right;
                    //root=temp;
                    printf("value is to the right \n");
                }
            }
            parent = new treeNode;
            parent->data=num;
            parent->left=NULL;
            parent->right=NULL;
            temp=parent;
        }
}

Thanks for any kind of help.

Body:
Algo

if root == null  Create new node assign to Root

Keep iterating based on comparison with rootNode until reach any leaf Node

check if num <= parent(leaf) Insert into left ELSE insert into right

Code

private void insertItrInBST(int num){
    Node temp = root,parent = root;

    if(root == null){
        root = getNewNode(num);
    }else{
        temp = root;

        while(temp != null){
            if(num <= root.data){
                parent = temp;
                temp = temp.left;
            }else{
                parent = temp;
                temp = temp.right;
            }
        }
        Node newNode = getNewNode(num);
        if(num <= parent.data){
            parent.left = newNode;
        }else{
            parent.right = newNode;
        }
    }
}


问:
How to push down main menu while expanding nested menu using Flex CSS?
I have two level menu (main and nested). The menu appears as Flex column on small screen size but when I hover on the main menu the sub menu appears top of the main menu. How can I push down the main menu to make require room for sub menu while expanding?

#main-menu ul {
    display: flex;
    flex-direction: row;
    background-color: #F2F3F4;
    padding: 0;
}
#main-menu ul li {
    position: relative;
    flex: 1 0 auto;
    text-align: left;
}
#main-menu li ul {
    display: none;
    width: 100%;
    position: absolute;
}
#main-menu ul ul {
    left: 0;
    top: 10;
}
#main-menu ul li:hover ul,
#main-menu li ul li:hover ul {
    display: flex;
    flex-direction: column;
}
#main-menu ul a {
    display: block;
    padding: 10px;
}
#main-menu ul a:hover {
    background-color: #B2BABB;
}
@media only screen and (max-width: 768px) {
    #main-menu ul {
        flex-direction: column;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav id="main-menu">
<ul>
    <li>Item 1
        <ul id="sub-menu">
            <li>Item 1.1</li>
            <li>Item 1.2</li>
            <li>Item 1.3</li>
        </ul>
    </li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>
</nav></code>```

答:
That overlap is caused by the inner ul being set to position: absolute, which simply mean, the ul is taken out of flow and doesn't affect any other elements.

```<code>#main-menu li ul {
    display: none;
    width: 100%;
    position: absolute;              /*  this needs to be changed  */
}
</code>```

Simply add a new rule in the media query, that override the previous setting on smaller screens

```<code>@media only screen and (max-width: 768px) {
    #main-menu ul {
        flex-direction: column;
    }
    #main-menu li ul {                         /*  added  */
        position: relative;
    }
}
</code>```

Stack snippet

#main-menu ul {
    display: flex;
    flex-direction: row;
    background-color: #F2F3F4;
    padding: 0;
}
#main-menu ul li {
    position: relative;
    flex: 1 0 auto;
    text-align: left;
}
#main-menu li ul {
    display: none;
    position: absolute;
    left: 0;
    top: 100%;
    width: 100%;
}
#main-menu ul li:hover ul,
#main-menu li ul li:hover ul {
    display: flex;
    flex-direction: column;
}
#main-menu ul a {
    display: block;
    padding: 10px;
}
#main-menu ul a:hover {
    background-color: #B2BABB;
}
@media only screen and (max-width: 768px) {
    #main-menu ul {
        flex-direction: column;
    }
    #main-menu li ul {
        position: relative;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav id="main-menu">
<ul>
    <li>Item 1
        <ul id="sub-menu">
            <li>Item 1.1</li>
            <li>Item 1.2</li>
            <li>Item 1.3</li>
        </ul>
    </li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>
</nav></code>```

You also had these 2 rules,

```<code>#main-menu li ul {
    display: none;
    width: 100%;
    position: absolute;
}
#main-menu ul ul {
    left: 0;
    top: 10;                   /*  invalid value, needs a unit (if not a "0")  */
}
</code>```

which I merged into 1 and corrected the top: 10 property/value.

```<code>#main-menu li ul {
    display: none;
    position: absolute;
    left: 0;
    top: 100%;                 /*  changed so it start at the bottom of its parent  */
    width: 100%;
}
</code>```

Body:
I have two level menu (main and nested). The menu appears as Flex column on small screen size but when I hover on the main menu the sub menu appears top of the main menu. How can I push down the main menu to make require room for sub menu while expanding?

#main-menu ul {
    display: flex;
    flex-direction: row;
    background-color: #F2F3F4;
    padding: 0;
}
#main-menu ul li {
    position: relative;
    flex: 1 0 auto;
    text-align: left;
}
#main-menu li ul {
    display: none;
    width: 100%;
    position: absolute;
}
#main-menu ul ul {
    left: 0;
    top: 10;
}
#main-menu ul li:hover ul,
#main-menu li ul li:hover ul {
    display: flex;
    flex-direction: column;
}
#main-menu ul a {
    display: block;
    padding: 10px;
}
#main-menu ul a:hover {
    background-color: #B2BABB;
}
@media only screen and (max-width: 768px) {
    #main-menu ul {
        flex-direction: column;
    }
}

Item 1

Item 1.1

Item 1.2

Item 1.3

Item 2

Item 3

Item 4

Body:
That overlap is caused by the inner ul being set to position: absolute, which simply mean, the ul is taken out of flow and doesn't affect any other elements.

#main-menu li ul {
    display: none;
    width: 100%;
    position: absolute;              /*  this needs to be changed  */
}

Simply add a new rule in the media query, that override the previous setting on smaller screens

@media only screen and (max-width: 768px) {
    #main-menu ul {
        flex-direction: column;
    }
    #main-menu li ul {                         /*  added  */
        position: relative;
    }
}

Stack snippet

#main-menu ul {
    display: flex;
    flex-direction: row;
    background-color: #F2F3F4;
    padding: 0;
}
#main-menu ul li {
    position: relative;
    flex: 1 0 auto;
    text-align: left;
}
#main-menu li ul {
    display: none;
    position: absolute;
    left: 0;
    top: 100%;
    width: 100%;
}
#main-menu ul li:hover ul,
#main-menu li ul li:hover ul {
    display: flex;
    flex-direction: column;
}
#main-menu ul a {
    display: block;
    padding: 10px;
}
#main-menu ul a:hover {
    background-color: #B2BABB;
}
@media only screen and (max-width: 768px) {
    #main-menu ul {
        flex-direction: column;
    }
    #main-menu li ul {
        position: relative;
    }
}

<nav id="main-menu">
<ul>
    <li><a href="#">Item 1</a>
        <ul id="sub-menu">
            <li><a href="#">Item 1.1</a></li>
            <li><a href="#">Item 1.2</a></li>
            <li><a href="#">Item 1.3</a></li>
        </ul>
    </li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a></li>
    <li><a href="#">Item 4</a></li>
</ul>
</nav>

You also had these 2 rules,

#main-menu li ul {
    display: none;
    width: 100%;
    position: absolute;
}
#main-menu ul ul {
    left: 0;
    top: 10;                   /*  invalid value, needs a unit (if not a "0")  */
}

which I merged into 1 and corrected the top: 10 property/value.

#main-menu li ul {
    display: none;
    position: absolute;
    left: 0;
    top: 100%;                 /*  changed so it start at the bottom of its parent  */
    width: 100%;
}


问:
Adjust Height of Map in Divi
Was hoping to increase the height of the google map module in Divi but my CSS code is not working and do not understand why.  I am pasting the following code within Advanced > Custom CSS > Main Element of the Map Module

```<code>.et_pb_map {
     height: 440px;
}
</code>```

Any suggestions would be very useful!

答:
Try to add padding instead of an explicit increase of height.

```<code>#map ,#map .et_pb_map {padding-bottom: 56.25%}
</code>```

You might have to adjust the selector. Usually #map is enough though.

and adjust the padding percentage to modify the aspect ratio. This is responsive.

The reason why this might work is because padding creates more space for the background - map in the case of this iframe - to be painted thus expanding it.
Read more on this here

Working demo on JSFiddle

Title: Adjust Height of Map in Divi

Body:
Was hoping to increase the height of the google map module in Divi but my CSS code is not working and do not understand why.  I am pasting the following code within Advanced > Custom CSS > Main Element of the Map Module

.et_pb_map {
     height: 440px;
}

Any suggestions would be very useful!

Body:
Try to add padding instead of an explicit increase of height.

#map ,#map .et_pb_map {padding-bottom: 56.25%}

You might have to adjust the selector. Usually #map is enough though.

and adjust the padding percentage to modify the aspect ratio. This is responsive.

The reason why this might work is because padding creates more space for the background - map in the case of this iframe - to be painted thus expanding it.
Read more on this here

Working demo on JSFiddle


问:
Mapping multiple test classes to the same file for autotest
I'm using standalone autotest in my projects along with minitest. In one of my projects, I have a single file (validation.rb) that validates a document to different internal format levels. (A Level 2 document has more features than a Level 1 document.)

Testing the validation for a particular level requires repeatedly loading in a known-valid document, subtly mutating it in broken way, and then ensuring that it is broken. In short:

```<code>class TestValidation < MiniTest::Unit::TestCase
  def setup
    @l1 = Document.load( L1DOC )
  end
  def test_valid
    assert @l1.valid_level_1?
  end
  def test_unbalanced_data
    @l1.instance_eval{ @tracks[0].data.pop }
    refute @l1.valid_level_1?, "Validation must ensure that all tracks have the same amount of data"
  end
  # many more tests for level 1 here
end
</code>```

The problem is that autotest (as far as I can tell) knows which tests to run based on the name of the test classes. TestValidation will have its tests automatically run when validation.rb is changed.

Without autotest, I would have named the above class TestL1Validation, and created a new class TestL2Validation that loaded a different document. Doing this breaks autotest, however, unless I break out my validation into l1validation.rb and l2validation.rb.

How can I name my files or tests, or set up my tests, so that autotest will run multiple test classes when a single source file changes?

答:
You can add custom mappings for autotest. Here's one way of doing it:
Create autotest directory at the same level as lib and test directories.

Add autotest/discover.rb:

```<code>$LOAD_PATH.unshift File.expand_path('../', File.dirname(__FILE__))
Autotest.add_discovery { "my_rules" }
</code>```

Add autotest/my_rules.rb:

```<code>require 'autotest'

class Autotest::My_rules < Autotest
  def initialize
    super

    add_mapping(%r%^lib/valid.rb$%, true) { |filename, _|
      files_matching %r%^test/test_.*\.rb$%
    }
  end
end
</code>```

This will add a custom mapping: whenever lib/valid.rb files has changed, re-run all test_*.rb files in test directory.

Body:
I'm using standalone autotest in my projects along with minitest. In one of my projects, I have a single file (validation.rb) that validates a document to different internal format levels. (A Level 2 document has more features than a Level 1 document.)

Testing the validation for a particular level requires repeatedly loading in a known-valid document, subtly mutating it in broken way, and then ensuring that it is broken. In short:

class TestValidation < MiniTest::Unit::TestCase
  def setup
    @l1 = Document.load( L1DOC )
  end
  def test_valid
    assert @l1.valid_level_1?
  end
  def test_unbalanced_data
    @l1.instance_eval{ @tracks[0].data.pop }
    refute @l1.valid_level_1?, "Validation must ensure that all tracks have the same amount of data"
  end
  # many more tests for level 1 here
end

The problem is that autotest (as far as I can tell) knows which tests to run based on the name of the test classes. TestValidation will have its tests automatically run when validation.rb is changed.

Without autotest, I would have named the above class TestL1Validation, and created a new class TestL2Validation that loaded a different document. Doing this breaks autotest, however, unless I break out my validation into l1validation.rb and l2validation.rb.

How can I name my files or tests, or set up my tests, so that autotest will run multiple test classes when a single source file changes?

Body:
You can add custom mappings for autotest. Here's one way of doing it:
Create autotest directory at the same level as lib and test directories.

Add autotest/discover.rb:

$LOAD_PATH.unshift File.expand_path('../', File.dirname(__FILE__))
Autotest.add_discovery { "my_rules" }

Add autotest/my_rules.rb:

require 'autotest'

class Autotest::My_rules < Autotest
  def initialize
    super

    add_mapping(%r%^lib/valid.rb$%, true) { |filename, _|
      files_matching %r%^test/test_.*\.rb$%
    }
  end
end

This will add a custom mapping: whenever lib/valid.rb files has changed, re-run all test_*.rb files in test directory.


问:
getClass().getClassLoader() is null, why?
I've got some code that calls..

```<code>x = getClass().getClassLoader();
</code>```

This returns null though.

When I start the same code not from Eclipse, but the command line, it returns a classloader.

I can hack the code to do this...

```<code>if (getClass().getClassLoader() == null)
{
 x = ClassLoader.getSystemClassLoader().getSystemResourceAsStream( loadedPropFileName );
}
</code>```

both are compiled and run with the same JVM. (I'm 99.99% sure).

Anyone have any ideas why the first would return null for the classloader?

Edit:

My question is does "Anyone have any ideas why the same class would return null when started via Eclipse and a class loader when loaded from the command line."

Thanks for the advice that the Bootstap loader must be loading the class in Eclipse. I've no idea why this happens though.

答:
"This method will return null in such implementations if this class was loaded by the bootstrap class loader." - JavaDoc at getClassLoader()

The null class loader is reserved for system classes for security purposes and can only be used if Class.forName(String name, boolean initialize, ClassLoader loader). If a class has a null ClassLoader, most security checks are not made.

Body:
I've got some code that calls..

x = getClass().getClassLoader();

This returns null though.

When I start the same code not from Eclipse, but the command line, it returns a classloader.

I can hack the code to do this...

if (getClass().getClassLoader() == null)
{
 x = ClassLoader.getSystemClassLoader().getSystemResourceAsStream( loadedPropFileName );
}

both are compiled and run with the same JVM. (I'm 99.99% sure).

Anyone have any ideas why the first would return null for the classloader?

Edit:

My question is does "Anyone have any ideas why the same class would return null when started via Eclipse and a class loader when loaded from the command line."

Thanks for the advice that the Bootstap loader must be loading the class in Eclipse. I've no idea why this happens though.


问:
http proxy heroku login enotfound: getaddrinfoo enotfound api.heroku.com:443
I have just installed heroku and I am using powershell to login but i keep getting this message:

```<code>enotfound: getaddrinfoo enotfound api.heroku.com api.heroku.com:443
</code>```

any idea?

答:
You can refer to solution provided in

heroku issue

Body:
I have just installed heroku and I am using powershell to login but i keep getting this message:

enotfound: getaddrinfoo enotfound api.heroku.com api.heroku.com:443

any idea?


问:
Calculate the max and the min difference between two adjacent numbers
Having a matrix A like:

```<code>     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   14   17   20   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28
</code>```

I want to calculate the max and the min difference between two adjacent numbers in all rows.
And then filter to limit only rows where adjacent numbers min is less between 4 and 7 and max is between 6 an 12
The output should return no row.

For the following matrix:

```<code>     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   16   17   28   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28
</code>```

the result should be row 1

Body:
Having a matrix A like:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   14   17   20   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28

I want to calculate the max and the min difference between two adjacent numbers in all rows.
And then filter to limit only rows where adjacent numbers min is less between 4 and 7 and max is between 6 an 12
The output should return no row.

For the following matrix:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   16   17   28   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28

the result should be row 1

Body:
You could approach this as follows:

d <- abs(apply(m, 1, diff))

m[apply(d, 2, min) %in% 4:7 & apply(d, 2, max) %in% 6:12,]

which gives:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   21   15   22   13   23   17
[2,]   27   18   13   25   16   11

Used data:

set.seed(2)
m <- matrix(sample(11:28, 54, TRUE), nrow = 9)


问:
Login to Microsoft SQL Server Error: 18456
I am getting this error while trying to connect to the SQL Server.

Microsoft SQL Server Error: 18456

Can anybody tell me what the error code means?

答:
First go to start bar then search local services
Then click on "view local services"
Then it will open service window then go to SQL Server(MSSQLSERVER) right click on it and click on stop and then again right click on it and click start. Now you can able to login and put your user name as 'sa' and password is your won password.</p>


问:
Send data from Widget Configuration to viewsFactory Android
Upon adding a new widget a configuration activity popups which inflates a listview of names from database and when i select the name from the config activity it pass the position to Appwidget provider

```<code> static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        final CharSequence recipeId = IngredientConfiguration.loadTitlePref(context, appWidgetId);

        String recipeIdInt = recipeId.toString();

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.ingredient_widget);

        Intent intent = new Intent(context, ListViewService.class);
        remoteViews.setRemoteAdapter(R.id.widget_listview, intent);

        remoteViews.setEmptyView(R.id.widget_listview, R.id.empty_view);

        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
    }
</code>```

i created the remoteviewservice factory which inflates listview from database with cursor with position 0.

i want to get the info from config activity and use that value in remoteviewfactory and inflate the listview with unique value

答:
Just add your parameters to adapter intent. Check out a simple example.

```<code>Intent intent = new Intent(context, ExampleRemoteService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
intent.putExtra("group", group);
intent.putExtra("week", week);
intent.putExtra("day", day);
remoteViews.setRemoteAdapter(R.id.example, intent);
</code>```

In ExampleRemoteService in method onGetViewFactory you can get this intent and transfer to ExampleViewsFactory.

```<code>@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
    return (new ExampleViewsFactory(this.getApplicationContext(),
            intent));
}
</code>```

In ExampleViewsFactory take all intent's data and in OnCreate just load your list depends on this parameters.

```<code>private String group;
private int widgetId;
private int week;
private int day;
private List<ExampleModel> data = new ArrayList<>();

public ExampleViewsFactory(Context context, Intent adapter) {
    this.group = adapter.getStringExtra("group");
    this.day = adapter.getIntExtra("day", 0);
    this.week = adapter.getIntExtra("week", 0);
    this.widgetId = adapter.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID);
}

@Override
public void onCreate() {
    this.data = exampleRepository.getDataByWeekAndDay(group, week, day);
}
</code>```

Now you need only to make a remoteviews for all items.

Body:
Upon adding a new widget a configuration activity popups which inflates a listview of names from database and when i select the name from the config activity it pass the position to Appwidget provider

 static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        final CharSequence recipeId = IngredientConfiguration.loadTitlePref(context, appWidgetId);

        String recipeIdInt = recipeId.toString();

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.ingredient_widget);

        Intent intent = new Intent(context, ListViewService.class);
        remoteViews.setRemoteAdapter(R.id.widget_listview, intent);

        remoteViews.setEmptyView(R.id.widget_listview, R.id.empty_view);

        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
    }

i created the remoteviewservice factory which inflates listview from database with cursor with position 0.

i want to get the info from config activity and use that value in remoteviewfactory and inflate the listview with unique value

Body:
Just add your parameters to adapter intent. Check out a simple example.

Intent intent = new Intent(context, ExampleRemoteService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
intent.putExtra("group", group);
intent.putExtra("week", week);
intent.putExtra("day", day);
remoteViews.setRemoteAdapter(R.id.example, intent);

In ExampleRemoteService in method onGetViewFactory you can get this intent and transfer to ExampleViewsFactory.

@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
    return (new ExampleViewsFactory(this.getApplicationContext(),
            intent));
}

In ExampleViewsFactory take all intent's data and in OnCreate just load your list depends on this parameters.

private String group;
private int widgetId;
private int week;
private int day;
private List<ExampleModel> data = new ArrayList<>();

public ExampleViewsFactory(Context context, Intent adapter) {
    this.group = adapter.getStringExtra("group");
    this.day = adapter.getIntExtra("day", 0);
    this.week = adapter.getIntExtra("week", 0);
    this.widgetId = adapter.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID);
}

@Override
public void onCreate() {
    this.data = exampleRepository.getDataByWeekAndDay(group, week, day);
}

Now you need only to make a remoteviews for all items.


问:
Run code at midnight everyday
I want to update status at midnight everyday. but timer is by interval. how can I set the interval by day</p>

```<code>var timer = Timer()

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

// called every time interval from the timer
func timerAction() {

}
</code>```

答:
No timer needed. Observe the notification

```<code>static let NSCalendarDayChanged: NSNotification.Name
</code>```

Posted whenever the calendar day of the system changes, as determined by the system calendar, locale, and time zone. This notification does not provide an object.

If the the device is asleep when the day changes, this notification will be posted on wakeup. Only one notification will be posted on wakeup if the device has been asleep for multiple days.

```<code>NotificationCenter.default.addObserver(self, selector:#selector(calendarDayDidChange), name:.NSCalendarDayChanged, object:nil)

...

func calendarDayDidChange()
{
    print("day did change")
}
</code>```

Or with the closure based API

```<code>NotificationCenter.default.addObserver(forName: .NSCalendarDayChanged, object: nil, queue: .main) { _ in
   print("day did change")
}
</code>```

Or with Combine

```<code>var subscription : AnyCancellable?

subscription = NotificationCenter.default.publisher(for: .NSCalendarDayChanged)
    .sink { _ in print("day did change") }
</code>```

Or with async/await (Swift 5.5+)

```<code>Task {
    for await _ in NotificationCenter.default.notifications(named: .NSCalendarDayChanged) {
        print("day did change")
    }
}
</code>```

Title: Run code at midnight everyday

Body:
I want to update status at midnight everyday. but timer is by interval. how can I set the interval by day

var timer = Timer()

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

// called every time interval from the timer
func timerAction() {

}

Body:
No timer needed. Observe the notification

static let NSCalendarDayChanged: NSNotification.Name

Posted whenever the calendar day of the system changes, as determined by the system calendar, locale, and time zone. This notification does not provide an object.

If the the device is asleep when the day changes, this notification will be posted on wakeup. Only one notification will be posted on wakeup if the device has been asleep for multiple days.

NotificationCenter.default.addObserver(self, selector:#selector(calendarDayDidChange), name:.NSCalendarDayChanged, object:nil)

...

func calendarDayDidChange()
{
    print("day did change")
}

Or with the closure based API

NotificationCenter.default.addObserver(forName: .NSCalendarDayChanged, object: nil, queue: .main) { _ in
   print("day did change")
}

Or with Combine

var subscription : AnyCancellable?

subscription = NotificationCenter.default.publisher(for: .NSCalendarDayChanged)
    .sink { _ in print("day did change") }

Or with async/await (Swift 5.5+)

Task {
    for await _ in NotificationCenter.default.notifications(named: .NSCalendarDayChanged) {
        print("day did change")
    }
}

ContentLicense: CC BY-SA 4.0


问:
Program skips to end after first input
hey guys so I have a pizza program that gathers weight name and size using a structure and allocates the memory dynamically. My problem comes after the user inputs a number for the diameter. My code looks like this

```<code>#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;

int main()
{
  struct pizza
  {
    char name[15];
    float diameter;
    int weight;
  };
  pizza *user= new pizza{};

  cout << "Hello please enter some information about your pizza" << endl;
  cout << endl << "Diameter: ";

  cin >> user->diameter;
  cout << "company name: ";
  cin.get(user->name,15);
  cout << endl << "Weight: ";
  cin >> user->weight;

  cout << "here is the information that we have assembled about your pizza company" << endl;
  cout << "Company name: "<< user->name <<e ndl;
  cout << "diameter: " << user->diameter << endl;
  cout << "weight: " << user->weight << endl;
  return 0;
}
</code>```

when I run the program it looks like this
Hello please enter some information about your pizza

Diameter: 40
company name:
Weight: here is the information that we have assembled about your pizza company
Company name:
diameter: 40
weight: 0

答:
what appears is that you haven't used the code for clearing the buffer.

What is buffer?

Temporary storage area is called buffer. All standard input and output devices contain input and output buffer. In standard C/C++, streams are buffered, for example in case of standard input,when we press the key on keyboard,it isn’t send to your program, rather it is buffered by operating system till the time is allotted to the program.

How does it effect Programming?
On various occasions you may need to clear the unwanted buffer so as to get the next input in the desired container and not in the buffer of previous variable.

```<code>cin.clear();
fflush(stdin);
</code>```

This is the code you need to add in your program.

```<code>int main()
{
struct pizza
{
 char name[15];
 float diameter;
 int weight;

 };

 pizza*user= new pizza{
 };
 cout<<"Hello please enter some information about your pizza"<<endl;
 cout<<endl<<"Diameter: ";

 cin>>user->diameter;
 cout<<"company name: ";
 cin.clear();    //for clearing the input buffer
fflush(stdin);

cin.get(user->name,15);

cout<<endl<<"Weight: ";
cin.clear();
fflush(stdin);

cin>>user->weight;

cout<<"here is the information that we have assembled about your pizza
company"<<endl;
cout<<"Company name: "<<user->name<<endl;
cout<<"diameter: " <<user->diameter<<endl;
cout<<"weight: "<<user->weight<<endl;
return 0;

}
</code>```

after encountering“cin” statement, we require to input a character array or a string , we require to clear the input buffer or else the desired input is occupied by buffer of previous variable, not by the desired container.On pressing “Enter” (carriage return) on output screen after the first input , as the buffer of previous variable was the space for new container(as we did’nt clear it) , the program skips the following input of container.

Title: Program skips to end after first input

Body:
hey guys so I have a pizza program that gathers weight name and size using a structure and allocates the memory dynamically. My problem comes after the user inputs a number for the diameter. My code looks like this

#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;

int main()
{
  struct pizza
  {
    char name[15];
    float diameter;
    int weight;
  };
  pizza *user= new pizza{};

  cout << "Hello please enter some information about your pizza" << endl;
  cout << endl << "Diameter: ";

  cin >> user->diameter;
  cout << "company name: ";
  cin.get(user->name,15);
  cout << endl << "Weight: ";
  cin >> user->weight;

  cout << "here is the information that we have assembled about your pizza company" << endl;
  cout << "Company name: "<< user->name <<e ndl;
  cout << "diameter: " << user->diameter << endl;
  cout << "weight: " << user->weight << endl;
  return 0;
}

when I run the program it looks like this
Hello please enter some information about your pizza

Diameter: 40
company name:
Weight: here is the information that we have assembled about your pizza company
Company name:
diameter: 40
weight: 0

Body:
what appears is that you haven't used the code for clearing the buffer.

What is buffer?

Temporary storage area is called buffer. All standard input and output devices contain input and output buffer. In standard C/C++, streams are buffered, for example in case of standard input,when we press the key on keyboard,it isn’t send to your program, rather it is buffered by operating system till the time is allotted to the program.

How does it effect Programming?
On various occasions you may need to clear the unwanted buffer so as to get the next input in the desired container and not in the buffer of previous variable.

cin.clear();
fflush(stdin);

This is the code you need to add in your program.

int main()
{
struct pizza
{
 char name[15];
 float diameter;
 int weight;

 };

 pizza*user= new pizza{
 };
 cout<<"Hello please enter some information about your pizza"<<endl;
 cout<<endl<<"Diameter: ";

 cin>>user->diameter;
 cout<<"company name: ";
 cin.clear();    //for clearing the input buffer
fflush(stdin);

cin.get(user->name,15);

cout<<endl<<"Weight: ";
cin.clear();
fflush(stdin);

cin>>user->weight;

cout<<"here is the information that we have assembled about your pizza
company"<<endl;
cout<<"Company name: "<<user->name<<endl;
cout<<"diameter: " <<user->diameter<<endl;
cout<<"weight: "<<user->weight<<endl;
return 0;

}

after encountering“cin” statement, we require to input a character array or a string , we require to clear the input buffer or else the desired input is occupied by buffer of previous variable, not by the desired container.On pressing “Enter” (carriage return) on output screen after the first input , as the buffer of previous variable was the space for new container(as we did’nt clear it) , the program skips the following input of container.


问:
Replacing a sequence in a string with its match index
In PHP, If I am replacing "a" in a string "a b a b a b c", how do I get it to replace with the index of the match (i.e. "1 b 2 b 3 b c")?</p>

答:
use preg_replace_callback instead.

PHP 5.3.0 example (not tested):

```<code>$i = 0;
preg_replace_callback("/a/", function( $match ) {
    global $i;
    return ++$i;
}, "a b a b a b c");
</code>```

Body:
use preg_replace_callback instead.

PHP 5.3.0 example (not tested):

$i = 0;
preg_replace_callback("/a/", function( $match ) {
    global $i;
    return ++$i;
}, "a b a b a b c");


问:
Turbo C++ : while(fin) vs while(!fin.eof())
I was told that I should be using while(fin) instead of while(!fin.eof()) when reading a file.

What exactly is the difference?

Edit: I do know that while(fin) actually checks the stream object and that when it becomes NULL, the loop breaks and it covers eof and fail flags.
But my course teacher says that fin.eof() is better so I need to understand the fundamental operation that's going on here.

Which one is the right practice?

Note: This is not a duplicate, I need assistance in Turbo C++ and with binary files.
I'm basically trying to read a file using a class object.

答:
First of all I am assuming fin is your fstream object. In which case your teacher would not have told you to use while(fin.eof()) for reading from file. She would have told to use while(!fin.eof()).

Let me explain. eof() is a member of the fstream class which returns a true or false value depending on whether the End Of File (eof) of the file you are reading has been reached. Thus while eof() function returns 0 it means the end of file has not been reached and loop continues to execute, but when eof() returns 1 the end of the file has been reached and the loop exits.

while(fin) loop is entered because fin actually returns the value of an error flag variable inside the class object fin whose value is set to 0 when any function like read or write or open fails. Thus the loop works as long as the read function inside the loop works.

Personally I would not suggest either of them.
I would suggest

//assume a class abc.

```<code>abc ob;

While(fin.read((char*)&ob, sizeof(ob)))
{}
</code>```

Or

```<code>While(fin.getline(parameters))
{}
</code>```

This loop reads the file record inside the loop condition and if nothing was read due to the end of file being reached, the loop is exited.

The problem with while(!fin.eof()) is that it returns 1 if the end of file has been reached. End of file is actually a character that is put at the end of the file. So when the read function inside the loop reads this character and sets a variable eof to 1. All the function actually does is return this value.

Thus works fine when you are reading lines in words but when you are reading successive records of a class from a file, this method will fail.
Consider

```<code>clas abc
{}a;

Fstream fin("file");

While(!fin.eof())

{
  fin.read((char*)&a,sizeof(a));

  a.display();  // display is a member function which displays the info }
</code>```

Thus displays the last record twice. This is because the end of file character is the character after the last byte of the last record. When the last is read the file pointer is at the eof byte but hasn't read it yet. So it will enter the loop again but this time the eof char is read but the read function fails. The values already in the variable a, that is the previous records will be displayed again.

Body:
First of all I am assuming fin is your fstream object. In which case your teacher would not have told you to use while(fin.eof()) for reading from file. She would have told to use while(!fin.eof()).

Let me explain. eof() is a member of the fstream class which returns a true or false value depending on whether the End Of File (eof) of the file you are reading has been reached. Thus while eof() function returns 0 it means the end of file has not been reached and loop continues to execute, but when eof() returns 1 the end of the file has been reached and the loop exits.

while(fin) loop is entered because fin actually returns the value of an error flag variable inside the class object fin whose value is set to 0 when any function like read or write or open fails. Thus the loop works as long as the read function inside the loop works.

Personally I would not suggest either of them.
I would suggest

//assume a class abc.

abc ob;

While(fin.read((char*)&ob, sizeof(ob)))
{}

Or

While(fin.getline(parameters))
{}

This loop reads the file record inside the loop condition and if nothing was read due to the end of file being reached, the loop is exited.

The problem with while(!fin.eof()) is that it returns 1 if the end of file has been reached. End of file is actually a character that is put at the end of the file. So when the read function inside the loop reads this character and sets a variable eof to 1. All the function actually does is return this value.

Thus works fine when you are reading lines in words but when you are reading successive records of a class from a file, this method will fail.
Consider

clas abc
{}a;

Fstream fin("file");

While(!fin.eof())

{
  fin.read((char*)&a,sizeof(a));

  a.display();  // display is a member function which displays the info }

Thus displays the last record twice. This is because the end of file character is the character after the last byte of the last record. When the last is read the file pointer is at the eof byte but hasn't read it yet. So it will enter the loop again but this time the eof char is read but the read function fails. The values already in the variable a, that is the previous records will be displayed again.