问:
Passing variables (that have space) using JavaScript window pop-up
Pop-up script:

```<code><script>
function myFunction2(url,url2) {

window.open('googleapi.php?id='+url+'&id2='+url2, "_blank", "toolbar=no,scrollbars=no,resizable=no,top=70,left=50,width=1200,height=500");
}

</script>
</code>```

PHP code:

```<code>echo "<td style='color: red;font-weight: bold;'>" . '<a style="color:
red;font-weight: bold;" href= javascript:myFunction2("'."tom
peter".'","'.$row['Account_Number'].'")>'.'Abnormal'.'</a>' . "</td>";
</code>```

Error - it's only considering "tom" - myFunction2("tom

I need to obtain myFunction2("tom peter","11234") - Can someone please help me?

答:
try this one

```<code><?php
$row['Account_Number']=12345;
$link="<a style='color: red;font-weight: bold;' href=javascript:'myFunction2(".urlencode('tom peter').",".$row['Account_Number'].")'>Abnormal</a>";
echo "<td style='color: red;font-weight: bold;'>" .$link. "</td>";
?>
</code>```

because of space in your perameter it will not pass whole perameter value so using urlencode and urldecode you get the value which will have apace

Body:
Pop-up script:

PHP code:

echo "" . ''.'Abnormal'.'' . "	";

Error - it's only considering "tom" - myFunction2("tom

I need to obtain myFunction2("tom peter","11234") - Can someone please help me?

Body:
try this one

<?php
$row['Account_Number']=12345;
$link="<a style='color: red;font-weight: bold;' href=javascript:'myFunction2(".urlencode('tom peter').",".$row['Account_Number'].")'>Abnormal</a>";
echo "<td style='color: red;font-weight: bold;'>" .$link. "</td>";
?>

because of space in your perameter it will not pass whole perameter value so using urlencode and urldecode you get the value which will have apace


来源: stackexchange

问:
retrieving number of observations with non missing values
I would like to compute the number of observations (Persons in my following example) that have non-missing values.

```<code>unbal <- data.frame(PERSON=c(rep('Frank',5),rep('Tony',5),rep('Edward',5)), YEAR=c(2001,2002,2003,2004,2005,2001,2002,2003,2004,2005,2001,2002,2003,2004,2005), Y=c(21,22,23,24,25,5,6,NA,7,8,31,32,33,34,35), X=c(1:15))
unbal

   PERSON YEAR  Y  X
1   Frank 2001 21  1
2   Frank 2002 22  2
3   Frank 2003 23  3
4   Frank 2004 24  4
5   Frank 2005 25  5
6    Tony 2001  5  6
7    Tony 2002  6  7
8    Tony 2003 NA  8
9    Tony 2004  7  9
10   Tony 2005  8 10
11 Edward 2001 31 11
12 Edward 2002 32 12
13 Edward 2003 33 13
14 Edward 2004 34 14
15 Edward 2005 35 15
</code>```

In this case will be 2, since only two persons (Frank and Edward) have all the data.

答:
We can use data.table

```<code>library(data.table)
setDT(unbal)[, .(ind = all(complete.cases(.SD))), PERSON]
</code>```

and if we need the 'PERSON', just extract it

```<code>setDT(unbal)[, .(ind = all(complete.cases(.SD))), PERSON][(ind), PERSON]
#[1] Frank  Edward
</code>```

and if we need the total number

```<code>setDT(unbal)[, .(ind = all(complete.cases(.SD))), PERSON][, sum(ind)]
#[1] 2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to compute the number of observations (Persons in my following example) that have non-missing values.

unbal <- data.frame(PERSON=c(rep('Frank',5),rep('Tony',5),rep('Edward',5)), YEAR=c(2001,2002,2003,2004,2005,2001,2002,2003,2004,2005,2001,2002,2003,2004,2005), Y=c(21,22,23,24,25,5,6,NA,7,8,31,32,33,34,35), X=c(1:15))
unbal

   PERSON YEAR  Y  X
1   Frank 2001 21  1
2   Frank 2002 22  2
3   Frank 2003 23  3
4   Frank 2004 24  4
5   Frank 2005 25  5
6    Tony 2001  5  6
7    Tony 2002  6  7
8    Tony 2003 NA  8
9    Tony 2004  7  9
10   Tony 2005  8 10
11 Edward 2001 31 11
12 Edward 2002 32 12
13 Edward 2003 33 13
14 Edward 2004 34 14
15 Edward 2005 35 15

In this case will be 2, since only two persons (Frank and Edward) have all the data.

Body:
We can use data.table

library(data.table)
setDT(unbal)[, .(ind = all(complete.cases(.SD))), PERSON]

and if we need the 'PERSON', just extract it

setDT(unbal)[, .(ind = all(complete.cases(.SD))), PERSON][(ind), PERSON]
#[1] Frank  Edward

and if we need the total number

setDT(unbal)[, .(ind = all(complete.cases(.SD))), PERSON][, sum(ind)]
#[1] 2


问:
Importing .csv file into a Oracle Forms application
I've got a question how to import a .csv file into a Oracle Forms application.
We are using Oracle Forms 11g on a Oracle 12c Database.

Now we want to import a .csv file with the Forms applicationso our customers can import this file and write the data into the database.

My plan is to create an application where the user can import a .csv file with a filechooser. The data from the .csv will be read and an output shows the user the data in this application. Then the user should be able to save it into the database through a button.

I've tried several searches but haven't found the right solution for this kind of problem. The only solutions I've found were a direct import of a .csv file into a database but not through Oracle Forms

Is it even possible to load .csv files in Oracle Forms?

If anyone has a good solution or anything else that might be helpfull i would be thankfull for that.

答: You can just use webutil to show a filechooser to select the file and upload it to the application server. If you use a shared directory between the application server and the db server you can use an external table to show the input of the file to the user. And then after the button you just insert the data from the external table in another table.</p>


问:
Is there a way to speed up Steam API update?
I'm using Steam Web API and need to check if the achievement list for a certain user and game is updated (when user gets an achievement). I am using api.ISteamUserStats.GetUserStatsForGame.

The problem is that, even though I am querying repeatedly, the list only updates to the new data after a delay of about one minute, thus rendering my app useless.

Any ideas on how to reduce this delay or maybe suggestions for a different approach?

答:
Even though your question was kind of answered in the comments, here you have some more information:

It is nearly impossible to speed up an REST API call to -not under your control- servers like in this case. You can find some advice in this SO answer.

This answer applied to the Steam API:

Make as few calls as possible (like in the post). There are simple ways to stack requests in the Steam API like request much information at once (i.e. use ISteamUser/GetPlayerSummaries/v0002/?key=SteamAPIKey&steamids=YourSteamIDs to gather information for multiple users at once and use this data instead of a new query)

Keep calls as simple as they can be. (i.e. if you just need one fact -check for one game for example- build a query for just that and don´t ask for all games and check then...)

Think about caching the data - at least for certain users or data wich can be "recycled" and updated every few days/ months. (Again inspired by the other thread)

Don´t call everything at once (if it is possible). It can be faster to load segments or just the information you want to show -for now. If you call every query at the beginning of your script, this could be slower. BUT: keep in mind #1 and that it is more efficient to make one large query instead of multiple smaller. This one depends completly on the query. It is more efficient to load a friend list in one query but it is more efficient to load the important data first and the less important data afterwards.

Furthermore -obviously- check if you got enough processing power, some ram and a good connection. Just for example: I let a hosted server make the querys and pass results to me later on.

ContentLicense: CC BY-SA 4.0


问:
Remove Duplicate ids from select query
I have the following table

```<code>ID     NAME    POINT
100    AAA     100
100    AAA     150
100    AAA     70
200    DDD     100
200    DDD     65
300    FFF     50
</code>```

I would like to delete duplicate id from this table. I would like to get below

```<code>ID     NAME    POINT
100    AAA     100
200    DDD     100
300    FFF     50
</code>```

I already used DISTINCT keyword in my select query likes this

```<code>SELECT DISTINCT ID,NAME,POINT FROM Tab ORDER BY ID;
</code>```

It is not ok. I just need one unique id per record.So How to remove duplicate ids from select query? My condition is If all records are the same then take the first record.

答:
I think the easiest option is a to group by statement. That is:

```<code>SELECT ID, NAME, POINT GROUP BY ID
</code>```

You might need to add some other logic, deepening on what POINT value you want to select (e.g. max, min etc). That is:

```<code>SELECT ID, NAME, MAX(POINT) GROUP BY ID, NAME
</code>```

Title: Remove Duplicate ids from select query

Body:
I have the following table

ID     NAME    POINT
100    AAA     100
100    AAA     150
100    AAA     70
200    DDD     100
200    DDD     65
300    FFF     50

I would like to delete duplicate id from this table. I would like to get below

ID     NAME    POINT
100    AAA     100
200    DDD     100
300    FFF     50

I already used DISTINCT keyword in my select query likes this

SELECT DISTINCT ID,NAME,POINT FROM Tab ORDER BY ID;

It is not ok. I just need one unique id per record.So How to remove duplicate ids from select query? My condition is If all records are the same then take the first record.

Body:
I think the easiest option is a to group by statement. That is:

SELECT ID, NAME, POINT GROUP BY ID

You might need to add some other logic, deepening on what POINT value you want to select (e.g. max, min etc). That is:

SELECT ID, NAME, MAX(POINT) GROUP BY ID, NAME


问:
Terraform - version differences
Why, when I run terraform -v do I get:

```<code>Terraform v0.9.6

Your version of Terraform is out of date! The latest version
is 0.9.7. You can update by downloading from www.terraform.io
</code>```

i.e. implying the latest version is 0.9.7 BUT, at the time of this post (and when I ran the terraform -v command) https://www.terraform.io/ says 0.9.8 as does brew via http://brewformulas.org/Terraform

答:
Install the required binary package (depending upon your OS) from Download page. https://github.com/hashicorp/terraform/releases

Unzip the .zip file to the bin directory as per your OS

For mac

unzip terraform_0.9.11_darwin_amd64.zip -d /usr/local/bin

Now check the terraform version:

terraform version

Terraform v0.9.1

Title: Terraform - version differences

Body:
Why, when I run terraform -v do I get:

Terraform v0.9.6

Your version of Terraform is out of date! The latest version
is 0.9.7. You can update by downloading from www.terraform.io

i.e. implying the latest version is 0.9.7 BUT, at the time of this post (and when I ran the terraform -v command) https://www.terraform.io/ says 0.9.8 as does brew via http://brewformulas.org/Terraform


问:
in Python, how to separate Local Hard Drives from Network and Floppy in Windows?
I've been looking for this info for awhile, and I have a number of ways to retrieve a list of local drives under Windows.  Here are two examples:

```<code>print win32api.GetLogicalDriveStrings().split("\x00")
</code>```

and

```<code>def getDriveLetters(self):
    self.drvs = []
    n_drives = win32api.GetLogicalDrives()
    for i in range(0,25): #check all drive letters
        j = 2**i # bitmask for each letter
        if n_drives & j > 0:
            self.drvs.append(chr(65+i)+":/")
    print self.drvs
</code>```

What I can't seem to find is a way to separate the floppies (A:), usb drives (G:), CD drives (E:), and network drives (P:) from the Local hard drives (C:, D:)

If they all were assigned the same letters it would be easy, but I'm writing this script to monitor local hard disk space across a network of computers with different configurations.

Any help would be appreciated! Thanks.

答:
You can try the win32 GetDriveType function.</p>

```<code>import win32file
>>> win32file.GetDriveType("C:/") == win32file.DRIVE_FIXED ##hardrive
True
>>> win32file.GetDriveType("Z:/") == win32file.DRIVE_FIXED ##network
False
>>> win32file.GetDriveType("D:/") == win32file.DRIVE_FIXED ##cd-rom
False
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've been looking for this info for awhile, and I have a number of ways to retrieve a list of local drives under Windows.  Here are two examples:

print win32api.GetLogicalDriveStrings().split("\x00")

and

def getDriveLetters(self):
    self.drvs = []
    n_drives = win32api.GetLogicalDrives()
    for i in range(0,25): #check all drive letters
        j = 2**i # bitmask for each letter
        if n_drives & j > 0:
            self.drvs.append(chr(65+i)+":/")
    print self.drvs

What I can't seem to find is a way to separate the floppies (A:), usb drives (G:), CD drives (E:), and network drives (P:) from the Local hard drives (C:, D:)

If they all were assigned the same letters it would be easy, but I'm writing this script to monitor local hard disk space across a network of computers with different configurations.

Any help would be appreciated! Thanks.

Body:
You can try the win32 GetDriveType function.

import win32file
>>> win32file.GetDriveType("C:/") == win32file.DRIVE_FIXED ##hardrive
True
>>> win32file.GetDriveType("Z:/") == win32file.DRIVE_FIXED ##network
False
>>> win32file.GetDriveType("D:/") == win32file.DRIVE_FIXED ##cd-rom
False


问:
Data is only loading on reload?
Im getting data from factory. after request im defining some properties.

```<code>http.get( 'app/propertyType/get.php').then(function (response)
             {

            if (response.data) {
                var data = response.data;

                dataFactory.propertyTypes = angular.extend({
                    asArray: data
                }
                });
            }
        });
 getPropertyTypes: function () {
                return this.propertyTypes;
            }
</code>```

Thats how im getting in controller..

```<code>       $scope.propertyTypes = DataFactory.getPropertyTypes();
        $scope.$watch(function () {
            return DataFactory.getPropertyTypes();
        }, function (newValue) {
            if (newValue) {
                $scope.propertyTypes = newValue;
            }
        });
</code>```

so it needs a reload to successfully load data..how to solve this problem? whenever i change the route it should be already loaded in page.

答:
If you're using ui.router module, to load smth before entering the route you can use resolve block in the state definition.
Ex:

```<code>$stateProvider.state('state1', {
    controller:'controller',
    templateUrl:'url',
    resolve: function(DataFactory){
        DataFactory.getPropertyTypes();
    }
})
</code>```

Also to make this work you should return promise object from DataFactory.getPropertyTypes()

EDIT: U can also use resolve in ngRoute routes definition. Here you can read details on how to do that.

Title: Data is only loading on reload?

Body:
Im getting data from factory. after request im defining some properties.

http.get( 'app/propertyType/get.php').then(function (response)
             {

            if (response.data) {
                var data = response.data;

                dataFactory.propertyTypes = angular.extend({
                    asArray: data
                }
                });
            }
        });
 getPropertyTypes: function () {
                return this.propertyTypes;
            }

Thats how im getting in controller..

       $scope.propertyTypes = DataFactory.getPropertyTypes();
        $scope.$watch(function () {
            return DataFactory.getPropertyTypes();
        }, function (newValue) {
            if (newValue) {
                $scope.propertyTypes = newValue;
            }
        });

so it needs a reload to successfully load data..how to solve this problem? whenever i change the route it should be already loaded in page.

Body:
If you're using ui.router module, to load smth before entering the route you can use resolve block in the state definition.
Ex:

$stateProvider.state('state1', {
    controller:'controller',
    templateUrl:'url',
    resolve: function(DataFactory){
        DataFactory.getPropertyTypes();
    }
})

Also to make this work you should return promise object from DataFactory.getPropertyTypes()

EDIT: U can also use resolve in ngRoute routes definition. Here you can read details on how to do that.


问:
How to add an onclick method on dynamically created button using jquery
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

```<code>'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '
</code>```

but it leaves me an error saying the test function isn't defined.

here's my whole code:

```<code>$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

        for (var i = 0; i < items.length; i++) {

            //test();
            $('#myTable').append('<tr><td>' + items[i].unitId + '</td><td>'+
             items[i].pcName +'</td><td>'+ items[i].user + '</td><td>'+
             items[i].department+'</td><td>'+items[i].location+ '</td><td>'+
             items[i].dateAssigned + '</td><td>' + items[i].status +'</td><td>' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '</td></tr>');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});
</code>```

答:
Add the class attribute to the dynamically added button and add the onclick jquery function to the buttons. Use this code.

History

use the jquery function like this

$(document).on("click", ".btn-history", function(){
  alert ('test');
});

or

$('#table-id').on("click", ".btn-history", function(){
  alert ('test');
});

Body:
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '

but it leaves me an error saying the test function isn't defined.

here's my whole code:

$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

        for (var i = 0; i < items.length; i++) {

            //test();
            $('#myTable').append('
' + items[i].unitId + '	'+
             items[i].pcName +'	'+ items[i].user + '	'+
             items[i].department+'	'+items[i].location+ '	'+
             items[i].dateAssigned + '	' + items[i].status +'	' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '
');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});


问:
react router 4 - Nested Switch not work as expected
App.js

```<code><ConnectedRouter history={history}>
    <Switch>
        <Route path="/dashboard" name="Layout" component={Layout} />
        <Route exact path="/login" name="Login" component={Login} />
        <Redirect from="/" to="/dashboard" />
        <Route component={NoMatch}/>
    </Switch>
</ConnectedRouter>
</code>```

Layout.js

```<code><Switch>
    <Route path="/" name="Dashboard" component={Dashboard} />
    <Route path="/components/a" component={ComponentA} />
    <Route path="/components/b" component={ComponentB} />
</Switch>
</code>```

Problems:

problem#1 navigate to '/dashboard/components/a' or '/dashboard/components/b' not display component a or b as expected

problem#2 navigate to wrong path always redirect to '/dashboard' not display NoMatch component

UPDATE:
changing Redirect to

    <Route exact path='/' render={() => <Redirect to='/dashboard' />} />

can fix the problem #2 but problem #1 remains

答:
You may need to change your Route path to have a /dashboard param as well when you are tyring to navigate to /dashboard/componenets/a or /dashboard/componenets/b

```<code><Switch>
    <Route exact path="/dashboard" name="Dashboard" component={Dashboard} />
    <Route path="/dashboard/components/a" component={ComponentA} />
    <Route path="/dashboard/components/b" component={ComponentB} />
</Switch>
</code>```

Body:
App.js

<ConnectedRouter history={history}>
    <Switch>
        <Route path="/dashboard" name="Layout" component={Layout} />
        <Route exact path="/login" name="Login" component={Login} />
        <Redirect from="/" to="/dashboard" />
        <Route component={NoMatch}/>
    </Switch>
</ConnectedRouter>

Layout.js

<Switch>
    <Route path="/" name="Dashboard" component={Dashboard} />
    <Route path="/components/a" component={ComponentA} />
    <Route path="/components/b" component={ComponentB} />
</Switch>

Problems:

problem#1 navigate to '/dashboard/components/a' or '/dashboard/components/b' not display component a or b as expected

problem#2 navigate to wrong path always redirect to '/dashboard' not display NoMatch component

UPDATE:
changing Redirect to

    <Route exact path='/' render={() => <Redirect to='/dashboard' />} />

can fix the problem #2 but problem #1 remains

Body:
You may need to change your Route path to have a /dashboard param as well when you are tyring to navigate to /dashboard/componenets/a or /dashboard/componenets/b

<Switch>
    <Route exact path="/dashboard" name="Dashboard" component={Dashboard} />
    <Route path="/dashboard/components/a" component={ComponentA} />
    <Route path="/dashboard/components/b" component={ComponentB} />
</Switch>


问:
How to find the common elements of 2 cell arrays that contain randperm elements?
I have two cell arrays which may not be of the same size. Elements of cell arrays is randperm of an integer number. randperm data Type is double array. How can I find common elements of two cell arrays?

For example:

```<code>Q1 = {[1 2 3 4], [3 2 4 1], [4 2 1 3]}
Q2 = {[2 4 3 1], [1 2 3 4], [1 2 4 3]}
</code>```

As I said elements of cell arrays are randperm. I want the output of above example be "Element-1 of Q1 i.e. [1 2 3 4] since it is also present in Q2.
Note: Cell Arrays may have different number of columns...

答:
Vertically concatenate the matrices inside the cell arrays and use intersect with the 'rows' flag. i.e.

```<code>Q1={[1 2 3 4], [3 2 4 1], [4 2 1 3]};
Q2={[2 4 3 1], [1 2 3 4], [1 2 4 3]};
Qout = intersect(vertcat(Q1{:}), vertcat(Q2{:}), 'rows');

%>> Qout
%Qout =
%     1     2     3     4
</code>```

Body:
I have two cell arrays which may not be of the same size. Elements of cell arrays is randperm of an integer number. randperm data Type is double array. How can I find common elements of two cell arrays?

For example:

Q1 = {[1 2 3 4], [3 2 4 1], [4 2 1 3]}
Q2 = {[2 4 3 1], [1 2 3 4], [1 2 4 3]}

As I said elements of cell arrays are randperm. I want the output of above example be "Element-1 of Q1 i.e. [1 2 3 4] since it is also present in Q2.
Note: Cell Arrays may have different number of columns...

Body:
Vertically concatenate the matrices inside the cell arrays and use intersect with the 'rows' flag. i.e.

Q1={[1 2 3 4], [3 2 4 1], [4 2 1 3]};
Q2={[2 4 3 1], [1 2 3 4], [1 2 4 3]};
Qout = intersect(vertcat(Q1{:}), vertcat(Q2{:}), 'rows');

%>> Qout
%Qout =
%     1     2     3     4


问:
Is HIPE with RabbitMQ production ready?
does anyone enabled HIPE on RabbitMQ on production servers, if yes, did you face any problems beside the Rabbimq start-up time ,</p>

答:
HIPE has become more stable over the years and recent versions. Now I use it in production without any segmentation fault and an important performance boost. I am using the latest version:

RabbitMQ 3.6.10, Erlang 19.2.1

You can turn it on safely, but better use the last version you can.

Title: Is HIPE with RabbitMQ production ready?


答:
You can try that:</p>

```<code>length(unique(unbal$PERSON[!unbal$PERSON%in%unbal[!complete.cases(unbal),1]]))
# [1] 2
</code>```

Title: retrieving number of observations with non missing values

Body:
You can try that:

length(unique(unbal$PERSON[!unbal$PERSON%in%unbal[!complete.cases(unbal),1]]))
# [1] 2


问:
Numpy: Multiplying a matrix with a 3d tensor -- Suggestion
I have a matrix P with shape MxN and a 3d tensor T with shape KxNxR. I want to multiply P with every NxR matrix in T, resulting in a KxMxR 3d tensor.

P.dot(T).transpose(1,0,2) gives the desired result. Is there a nicer solution (i.e. getting rid of transpose) to this problem? This must be quite a common operation, so I assume, others have found different approaches, e.g. using tensordot (which I tried but failed to get the desired result). Opinions/Views would be highly appreciated!

答:
```<code>scipy.tensordot(P, T, axes=[1,1]).swapaxes(0,1)
</code>```


问:
Is it possible to mock the builtin len() function in Python 3.6?
Is it possible to mock the builtin len() function in Python 3.6?

I have a class which defines a simple method whic is dependent upon the len() function as follows:

```<code>class MyLenFunc(object):
    def is_longer_than_three_characters(self, some_string):
        return len(some_string) > 3
</code>```

I am trying to write a unit test for this method, but I am unable to mock out the len() function without errors being produced.
Here's what I have so far:

```<code>import unittest
from unittest.mock import patch
import my_len_func

class TestMyLenFunc(unittest.TestCase):

    @patch('builtins.len')
    def test_len_function_is_called(self, mock_len):
        # Arrange
        test_string = 'four'

        # Act
        test_object = my_len_func.MyLenFunc()
        test_object.is_longer_than_three_characters(test_string)

        # Assert
        self.assertEqual(1, mock_len.call_count)

if __name__ == '__main__':
    unittest.main()
</code>```

I found another SO question/answer here which suggests that it is not possible to mock out builtin functions because they are immutable.  However, I found a couple more websites here and here which suggest otherwise.  My attempt at the unit test class above is taken directly from the latter of these websites (and yes, I've tried the other techniques mentioned there. All end with the same error).

The error I'm getting is rather long to post the full thing, so I'll snip out the repeating parts of it (you'll see that it's recursive from the final part of the error message).  The error text is as follows:

```<code>ERROR: test_len_function_is_called (__main__.TestMyLenFunc)
----------------------------------------------------------------------
Traceback (most recent call last):
    File "C:\Python36\Lib\unittest\mock.py", line 1179, in patched
        return func(*args, **keywargs)
    File "C:/Python/scratchpad/my_len_func_tests.py", line 16, in test_len_function_is_called
        test_object.is_longer_than_three_characters(test_string)
    File "C:\Python\scratchpad\my_len_func.py", line 3, in is_longer_than_three_characters
        return len(some_string) > 3
    File "C:\Python36\Lib\unittest\mock.py", line 939, in __call__
        return _mock_self._mock_call(*args, **kwargs)
    File "C:\Python36\Lib\unittest\mock.py", line 949, in _mock_call
        _call = _Call((args, kwargs), two=True)
    File "C:\Python36\Lib\unittest\mock.py", line 1972, in __new__
        _len = len(value)
    ...
    (Repeat errors from lines 939, 949, and 1972 another 95 times!)
    ...
    File "C:\Python36\Lib\unittest\mock.py", line 939, in __call__
        return _mock_self._mock_call(*args, **kwargs)
    File "C:\Python36\Lib\unittest\mock.py", line 944, in _mock_call
        self.called = True RecursionError: maximum recursion depth exceeded while calling a Python object

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (errors=1)
</code>```

Many thanks in advance.

答:
Don't patch builtins.len; now code in the mock library breaks, because it needs the function to operate as normal! Patch the globals of the module-under-test:

```<code>@patch('my_len_func.len')
</code>```

This adds the global len to your module, and the len(some_string) in the MyLenFunc().is_longer_than_three_characters() method will find that one rather than the built-in function.

However, I must say that testing if len() is called feels like the wrong thing to test. You want to check if the method is producing the right results for the given inputs, basic operations like len() are just small building blocks towards that goal and are usually not tested that extent.

Body:
Is it possible to mock the builtin len() function in Python 3.6?

I have a class which defines a simple method whic is dependent upon the len() function as follows:

class MyLenFunc(object):
    def is_longer_than_three_characters(self, some_string):
        return len(some_string) > 3

I am trying to write a unit test for this method, but I am unable to mock out the len() function without errors being produced.
Here's what I have so far:

import unittest
from unittest.mock import patch
import my_len_func

class TestMyLenFunc(unittest.TestCase):

    @patch('builtins.len')
    def test_len_function_is_called(self, mock_len):
        # Arrange
        test_string = 'four'

        # Act
        test_object = my_len_func.MyLenFunc()
        test_object.is_longer_than_three_characters(test_string)

        # Assert
        self.assertEqual(1, mock_len.call_count)

if __name__ == '__main__':
    unittest.main()

I found another SO question/answer here which suggests that it is not possible to mock out builtin functions because they are immutable.  However, I found a couple more websites here and here which suggest otherwise.  My attempt at the unit test class above is taken directly from the latter of these websites (and yes, I've tried the other techniques mentioned there. All end with the same error).

The error I'm getting is rather long to post the full thing, so I'll snip out the repeating parts of it (you'll see that it's recursive from the final part of the error message).  The error text is as follows:

ERROR: test_len_function_is_called (__main__.TestMyLenFunc)
----------------------------------------------------------------------
Traceback (most recent call last):
    File "C:\Python36\Lib\unittest\mock.py", line 1179, in patched
        return func(*args, **keywargs)
    File "C:/Python/scratchpad/my_len_func_tests.py", line 16, in test_len_function_is_called
        test_object.is_longer_than_three_characters(test_string)
    File "C:\Python\scratchpad\my_len_func.py", line 3, in is_longer_than_three_characters
        return len(some_string) > 3
    File "C:\Python36\Lib\unittest\mock.py", line 939, in __call__
        return _mock_self._mock_call(*args, **kwargs)
    File "C:\Python36\Lib\unittest\mock.py", line 949, in _mock_call
        _call = _Call((args, kwargs), two=True)
    File "C:\Python36\Lib\unittest\mock.py", line 1972, in __new__
        _len = len(value)
    ...
    (Repeat errors from lines 939, 949, and 1972 another 95 times!)
    ...
    File "C:\Python36\Lib\unittest\mock.py", line 939, in __call__
        return _mock_self._mock_call(*args, **kwargs)
    File "C:\Python36\Lib\unittest\mock.py", line 944, in _mock_call
        self.called = True RecursionError: maximum recursion depth exceeded while calling a Python object

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (errors=1)

Many thanks in advance.

Body:
Don't patch builtins.len; now code in the mock library breaks, because it needs the function to operate as normal! Patch the globals of the module-under-test:

@patch('my_len_func.len')

This adds the global len to your module, and the len(some_string) in the MyLenFunc().is_longer_than_three_characters() method will find that one rather than the built-in function.

However, I must say that testing if len() is called feels like the wrong thing to test. You want to check if the method is producing the right results for the given inputs, basic operations like len() are just small building blocks towards that goal and are usually not tested that extent.


问:
"Safe" TO_NUMBER()
```<code>SELECT TO_NUMBER('*') FROM DUAL
</code>```

This obviously gives me an exception:

ORA-01722: invalid number

Is there a way to "skip" it and get 0 or NULL instead?

The whole issue: I have NVARCHAR2 field, which contains numbers and not almost ;-) (like *) and I need to select the biggest number from the column.

Yes, I know it is a terrible design, but this is what I need now... :-S

UPD:

For myself I've solved this issue with

```<code>COALESCE(TO_NUMBER(REGEXP_SUBSTR(field, '^\d+')), 0)
</code>```

答:
Fitting the original question and rather old skool</p>

```<code>select a, decode(trim(translate(b,'0123456789.',' ')),null,to_number(b),0)  from
(
    select '1' a, 'not a number' b from dual
    union
    select '2' a, '1234' b from dual
)
</code>```

Title: "Safe" TO_NUMBER()

Body:
SELECT TO_NUMBER('*') FROM DUAL

This obviously gives me an exception:

ORA-01722: invalid number

Is there a way to "skip" it and get 0 or NULL instead?

The whole issue: I have NVARCHAR2 field, which contains numbers and not almost ;-) (like *) and I need to select the biggest number from the column.

Yes, I know it is a terrible design, but this is what I need now... :-S

UPD:

For myself I've solved this issue with

COALESCE(TO_NUMBER(REGEXP_SUBSTR(field, '^\d+')), 0)

Body:
Fitting the original question and rather old skool

select a, decode(trim(translate(b,'0123456789.',' ')),null,to_number(b),0)  from
(
    select '1' a, 'not a number' b from dual
    union
    select '2' a, '1234' b from dual
)


问:
Highlight multiple fields on validate javascript
I want when textfields empty it will highlight it. Following is my code its only highlight one field at one time. If both fields empty it will highlight one field.

```<code><script>
function ValidateForm(){

    var summary=document.getElementById("<%=summary.ClientID%>");
    if (summary.value == "" && txtTest.value == "") {
        summary.style.backgroundColor = "Yellow";
        return false;
    }
    var txtTest = document.getElementById("<%=txtTest.ClientID%>");
    if (txtTest.value == "" ) {

        txtTest.style.backgroundColor = "Yellow";
        return false;
    }

   return true;

}
</script>
</code>```

Please help me to solve this problem. I don't want to use default validators.

答:
An alternative approach if your form is more complex maybe to separate the validation and highlighting.

// onKeyUp
function k(e) {
 this.style.background = (this.value) ? "none" : "#0f0";
}
window.onload = function() {
  var t = ["in1","in2","in3"];
  var i, max = t.length;
  var d;
  for(i=0;i<max;i++) {
    d = document.getElementById(t[i]);
    d.style.background="#0f0";
    d.addEventListener("keyup",k,false);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="in1" name="in1" placeholder="Input 1"/><br />
<input type="text" id="in2" name="in2" placeholder="Input 2"/><br />
<input type="text" id="in3" name="in3" placeholder="Input 3"/><br /></code>```

Body:
I want when textfields empty it will highlight it. Following is my code its only highlight one field at one time. If both fields empty it will highlight one field.

Please help me to solve this problem. I don't want to use default validators.

Body:
An alternative approach if your form is more complex maybe to separate the validation and highlighting.

// onKeyUp
function k(e) {
 this.style.background = (this.value) ? "none" : "#0f0";
}
window.onload = function() {
  var t = ["in1","in2","in3"];
  var i, max = t.length;
  var d;
  for(i=0;i<max;i++) {
    d = document.getElementById(t[i]);
    d.style.background="#0f0";
    d.addEventListener("keyup",k,false);
  }
}

<input type="text" id="in1" name="in1" placeholder="Input 1"/><br />
<input type="text" id="in2" name="in2" placeholder="Input 2"/><br />
<input type="text" id="in3" name="in3" placeholder="Input 3"/><br />


问:
iOS - View order when creating a constraint
When creating a constraint (programmatically or from interface builder) does it matter the order of the views? Does it matter which is the first item and which is the second item ?</p>

答:
Yes, it does, because the constant value is added to the second item to determine the value of the first item.

So, if you have label2.leading = label1.trailing + 45 then you get something like:

But if you have label1.trailing = label2.leading + 45 you get:

because the trailing edge of label1 now needs to be 45 away from the leading edge of label2, which means that label2 is on top of label1

If I say label1.trailing = label2.leading + -45 then I will have the same as in the first instance:

You would have similar issues with top/bottom constraint items too.

If you select Reverse first and second items in Interface Builder, then it will switch the sign of the constant for you.  If you are doing it programatically then you need to account for this yourself.


问:
Specify the dimensions of a Tkinter text box in pixels
How would I specify the dimensions of a Tkinter text box using pixels? I am not trying to change the font size, I am using this to help me scale it to the size of the window.</p>

答:
This helped me a lot:

You can also use the height and width options to explicitly set the
  size. If you display text in the button, these options define the size
  of the button in text units. If you display bitmaps or images instead,
  they define the size in pixels (or other screen units). You can
  specify the size in pixels even for text buttons, but that requires
  some magic. Here’s one way to do it (there are others):

f = Frame(master, height=32, width=32) f.pack_propagate(0) # don't
  shrink f.pack()

b = Button(f, text="Sure!") b.pack(fill=BOTH, expand=1)

Source: http://effbot.org/tkinterbook/button.htm


问:
File not readable from documents folder
I am creating a binary file using few c libraries and saving the file in documents folder of app in iOS. But when i try to read it its not reading. I am using the following code to read. </p>

```<code>let fileData = try NSData(contentsOfFile: filePath, options: NSData.ReadingOptions.mappedIfSafe) as Data
</code>```

<p>But this goes always into catch block. </p>

答:
You must retrieve your Document folder first and then get the content of document.

```<code>func readDocument(file:String) -> NSData{
        var vreturn:NSData
        if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true){
            let dir = dirs[0] //documents directory
            let path = dir.stringByAppendingString(file);
            //reading
            vreturn = (try? NSData(contentsOfFile: path)) ?? NSData()
        }
        return vreturn
    }
</code>```

I'm using this to get String content but it seems to work the same way using NSData. Simple way to read local file using Swift?

Title: File not readable from documents folder

Body:
I am creating a binary file using few c libraries and saving the file in documents folder of app in iOS. But when i try to read it its not reading. I am using the following code to read.

let fileData = try NSData(contentsOfFile: filePath, options: NSData.ReadingOptions.mappedIfSafe) as Data

But this goes always into catch block.

Body:
You must retrieve your Document folder first and then get the content of document.

func readDocument(file:String) -> NSData{
        var vreturn:NSData
        if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true){
            let dir = dirs[0] //documents directory
            let path = dir.stringByAppendingString(file);
            //reading
            vreturn = (try? NSData(contentsOfFile: path)) ?? NSData()
        }
        return vreturn
    }

I'm using this to get String content but it seems to work the same way using NSData. Simple way to read local file using Swift?


问:
Is there a "nice" way to advance a pointer to a struct by one byte?
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

```<code>#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}
</code>```

The compiler reports an error on the "nice" part:

```<code>% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^
</code>```

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

Body:
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}

The compiler reports an error on the "nice" part:

% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

Body:
How about:

ps = (s_t*) (1 + (uint8_t*) ps);


问:
How do I encode HTTP GET query strings in Perl?
This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

```<code>use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);
</code>```

答:
URI::Escape does what you want.</p>

```<code>use URI::Escape;

sub escape_hash {
    my %hash = @_;
    my @pairs;
    for my $key (keys %hash) {
        push @pairs, join "=", map { uri_escape($_) } $key, $hash{$key};
    }
    return join "&", @pairs;
}
</code>```

OwnerDisplayName: cdleary

Body:
This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);

LastEditorDisplayName: cdleary

Body:
URI::Escape does what you want.

use URI::Escape;

sub escape_hash {
    my %hash = @_;
    my @pairs;
    for my $key (keys %hash) {
        push @pairs, join "=", map { uri_escape($_) } $key, $hash{$key};
    }
    return join "&", @pairs;
}

OwnerDisplayName: Leon Timmermans

LastEditorDisplayName: Leon Timmermans


问:
Prettifying a conversion from m(metres) to feet(') and inches ('')
I'm creating table for defining an individual's BMI. The chart (as yet) doesn't take input (because I want to make the thing work stand-alone, first), but it does show (on parallel axes) the height in both metres and feet/inches.

In order to do this I'm defining the metres' start point and range and then converting the defined metres variables into feet/inches, to do which I've come up with (please don't laugh...) the following:

```<code><?php
        $m; // height in m

        $hInInches = ($m*3.2808399)*12;

        $hInImp = explode(".",$hInInches);

        $hInFt = $hInImp[0];

        $hInInches = substr(12*$hInImp[1],0,2);
?>
</code>```

I was wondering if anyone has any prettier, more economical, more accurate means by which this could be done, since this is being run inside of a for () loop to generate x numbers of rows (defined elswhere), and I'd like (if possible) to reduce the load...

答:
```<code>     <?php echo metersToFeetInches(3); //call function    ?>

     <?php
        function metersToFeetInches($meters, $echo = true)
        {
            $m = $meters;
            $valInFeet = $m*3.2808399;
            $valFeet = (int)$valInFeet;
            $valInches = round(($valInFeet-$valFeet)*12);
            $data = $valFeet."′".$valInches."″";
            if($echo == true)
            {
                return $data;
            } else {
                return $data;
            }
        }
        ?>
</code>```

output : 9′10″

Body:
I'm creating table for defining an individual's BMI. The chart (as yet) doesn't take input (because I want to make the thing work stand-alone, first), but it does show (on parallel axes) the height in both metres and feet/inches.

In order to do this I'm defining the metres' start point and range and then converting the defined metres variables into feet/inches, to do which I've come up with (please don't laugh...) the following:

<?php
        $m; // height in m

        $hInInches = ($m*3.2808399)*12;

        $hInImp = explode(".",$hInInches);

        $hInFt = $hInImp[0];

        $hInInches = substr(12*$hInImp[1],0,2);
?>

I was wondering if anyone has any prettier, more economical, more accurate means by which this could be done, since this is being run inside of a for () loop to generate x numbers of rows (defined elswhere), and I'd like (if possible) to reduce the load...

Body:
     <?php echo metersToFeetInches(3); //call function    ?>

     <?php
        function metersToFeetInches($meters, $echo = true)
        {
            $m = $meters;
            $valInFeet = $m*3.2808399;
            $valFeet = (int)$valInFeet;
            $valInches = round(($valInFeet-$valFeet)*12);
            $data = $valFeet."&prime;".$valInches."&Prime;";
            if($echo == true)
            {
                return $data;
            } else {
                return $data;
            }
        }
        ?>

output : 9′10″


问:
Removing duplicate integers from Array in C++
Here is my array: Arr[8] = {24, 30, 30, 32, 32, 36, 36, 36};

I am trying to eliminate the duplicate numbers from Arr using C++. Any suggestions? Thank you!

答:
```<code>sort( vec.begin(), vec.end() );
vec.erase( unique( vec.begin(), vec.end() ), vec.end() );
</code>```


问:
Window.close() is working in chrome but not in firefox
I have written a javascript function to pass the value from child window to parent window and in the child window on clicking the close button I am calling the below function which closes the window on chrome. but the same function is not working in firefox. kindly let me know what can I do to close the child window in Firefox.</p>

```<code>function SetName() {
        if (window.opener != null && !window.opener.closed) {
            var txtName = window.opener.document.getElementById("txtName");
            txtName.value = jq('#sizemsg').html();
        }
        window.close();
    }
</code>```

答: I believe you should try self.window.close(), as chrome autoamtically checks for window type child/parent, but Firefox strictly follows rules ..</p>

Body:
I have written a javascript function to pass the value from child window to parent window and in the child window on clicking the close button I am calling the below function which closes the window on chrome. but the same function is not working in firefox. kindly let me know what can I do to close the child window in Firefox.

function SetName() {
        if (window.opener != null && !window.opener.closed) {
            var txtName = window.opener.document.getElementById("txtName");
            txtName.value = jq('#sizemsg').html();
        }
        window.close();
    }


问:
Failed to load extension from popup box while running selenium scripts
I get the following popup box when I try to run my selenium script in java:

```<code>Failed to load extension from:
C:\Users\xyz\AppData\Local\Temp\scoped_dir20432_5430\internal. Loading of unpacked extensions is disabled by the administrator.
</code>```

I have tried chromeoption arguments I have found in other pages. But none seems to work.

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
public class testClass {

     public static String driverPath = "D:/Selenium/Chrome Driver latest/chromedriver.exe";
     public static WebDriver driver;

public static void main(String args[]) {
    System.setProperty("webdriver.chrome.driver", driverPath);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("--enable-automation");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    options.addArguments("disable-extensions");

    driver = new ChromeDriver(options);
    driver.navigate().to("http://google.com");
    driver.quit();
}
}
</code>```

I am forced to handle that popup manually. How do I get rid of it ?

答:
I had the same problem and I finally found a working answer in another thread.
Loading of unpacked extensions is disabled by the administrator

The following line did the trickt for me

```<code>options.setExperimentalOption("useAutomationExtension", false);
</code>```

There are some trade-offs mentioned in the link, like window resizing operations with the Chrome automation extension aren't possible anymore. Anyway, starting with the start-maximized argument still worked fine in my code.

```<code>options.addArguments("start-maximized");
</code>```

Body:
I get the following popup box when I try to run my selenium script in java:

Failed to load extension from:
C:\Users\xyz\AppData\Local\Temp\scoped_dir20432_5430\internal. Loading of unpacked extensions is disabled by the administrator.

I have tried chromeoption arguments I have found in other pages. But none seems to work.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
public class testClass {

     public static String driverPath = "D:/Selenium/Chrome Driver latest/chromedriver.exe";
     public static WebDriver driver;

public static void main(String args[]) {
    System.setProperty("webdriver.chrome.driver", driverPath);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("--enable-automation");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    options.addArguments("disable-extensions");

    driver = new ChromeDriver(options);
    driver.navigate().to("http://google.com");
    driver.quit();
}
}

I am forced to handle that popup manually. How do I get rid of it ?

Body:
I had the same problem and I finally found a working answer in another thread.
Loading of unpacked extensions is disabled by the administrator

The following line did the trickt for me

options.setExperimentalOption("useAutomationExtension", false);

There are some trade-offs mentioned in the link, like window resizing operations with the Chrome automation extension aren't possible anymore. Anyway, starting with the start-maximized argument still worked fine in my code.

options.addArguments("start-maximized");


问:
Adding one ui file into another
Suppose i have designer files with there respective classes say form.ui , form.h , form.cpp and myclass.ui , myclass.h , myclass,cpp . Now what i want is 2 different things .
Now i have a widget and a layout in the myclass.ui file and i now using addLayout function i add the form.ui file into it . Now i want it so that whole of the form.ui file content should come into small layout space by self adjusting . But that is not happening . So how could i achieve that

答:
Example of QUiLoader:

```<code>// your main widget
MyClass *myclass = new MyClass();

// to generate a widget with a .ui file
QUiLoader loader;
QFile file("form.ui");
file.open(QFile::ReadOnly);
QWidget *myForm = loader.load(&file, this);
file.close();

// insert the widget in your main container
myclass->layout()->addWidget(myForm);
</code>```

Title: Adding one ui file into another

Body:
Example of QUiLoader:

// your main widget
MyClass *myclass = new MyClass();

// to generate a widget with a .ui file
QUiLoader loader;
QFile file("form.ui");
file.open(QFile::ReadOnly);
QWidget *myForm = loader.load(&file, this);
file.close();

// insert the widget in your main container
myclass->layout()->addWidget(myForm);


问:
why a pointer to List can also point to Node?
I am a primer to c programming and reading c primer: 5th edition. What confuse me is why  plist  as a pointer to  List can also point to Node?

sorry, I did not paste function ListItemCount to the code block. In this function, Node * pnode = *plist;,  Does that mean plist was converted as a ponter point to Node ?  If so, why does the program need to convert to a pointer to node instead of assigning  plist->head to pnode(a pointer to Node)?

```<code>typedef struct film {
    char title[TSIZE];
    int rating;
} Item;

typedef struct node{
    Item item;
    // typical usage
    struct node * next;
} Node;

/*
* Note: to manage a linked list, we need  a pointer to its beginning,
* and we've used typedef to make List the name for a pointer of this
* type.
*/
typedef struct list{
    // should point to linked list Node
    Node * head;

    int size;
} List;

// TODO why  `plist`  as a pointer to  List can also point to Node?
/* returns number of nodes */
unsigned int ListItemCount(const List * plist)
{
    unsigned int count = 0;
    Node * pnode = *plist; /* set to start of list */
    while (pnode != NULL)
    {
        ++count;
        pnode = pnode->next; /* set to next node */
    }
    return count;
}
</code>```

答:
So you know that this doesn't work.

How should it work?

```<code>Node * pnode = *plist;
</code>```

This was intended to get the first node. It actually tries to assign the list type as the first node. To make it work, we need to get the head node out of that.

```<code>Node * pnode = (*plist).head;
</code>```

This now actually returns a Node*
To write this more succinctly:

```<code>Node * pnode = plist->head;
</code>```

Body:
I am a primer to c programming and reading c primer: 5th edition. What confuse me is why  plist  as a pointer to  List can also point to Node?

sorry, I did not paste function ListItemCount to the code block. In this function, Node * pnode = *plist;,  Does that mean plist was converted as a ponter point to Node ?  If so, why does the program need to convert to a pointer to node instead of assigning  plist->head to pnode(a pointer to Node)?

typedef struct film {
    char title[TSIZE];
    int rating;
} Item;

typedef struct node{
    Item item;
    // typical usage
    struct node * next;
} Node;

/*
* Note: to manage a linked list, we need  a pointer to its beginning,
* and we've used typedef to make List the name for a pointer of this
* type.
*/
typedef struct list{
    // should point to linked list Node
    Node * head;

    int size;
} List;

// TODO why  `plist`  as a pointer to  List can also point to Node?
/* returns number of nodes */
unsigned int ListItemCount(const List * plist)
{
    unsigned int count = 0;
    Node * pnode = *plist; /* set to start of list */
    while (pnode != NULL)
    {
        ++count;
        pnode = pnode->next; /* set to next node */
    }
    return count;
}

Body:
So you know that this doesn't work.

How should it work?

Node * pnode = *plist;

This was intended to get the first node. It actually tries to assign the list type as the first node. To make it work, we need to get the head node out of that.

Node * pnode = (*plist).head;

This now actually returns a Node*
To write this more succinctly:

Node * pnode = plist->head;


问:
How to get default Android Home screen package and activity name
I know that we can get Package and Activity names by using "adb shell dumpsys window windows" and get values from mFocusedApp.

But when i just connect my device and trying to get package and activity names, for that i am getting
appPackage as com.google.android.googlequicksearchbox
appActivity as com.google.android.launcher.GEL

But these values doesnt seemed to be right. When use the above in Appium tool, the tool is malfunctioned.

Can someone tell me how to get these package or activity name?

答:
The adb shell command to show the default launcher activity in Android 7.0+ without having to bring the launcher app to the front is:

```<code>adb shell cmd shortcut get-default-launcher
</code>```

Also com.google.android.googlequicksearchbox/com.google.android.launcher.GEL is a legitimate activity. So whatever malfunction you experienced - take it to the Appium developers.

Body:
The adb shell command to show the default launcher activity in Android 7.0+ without having to bring the launcher app to the front is:

adb shell cmd shortcut get-default-launcher

Also com.google.android.googlequicksearchbox/com.google.android.launcher.GEL is a legitimate activity. So whatever malfunction you experienced - take it to the Appium developers.


问:
Prefix for testing methods in Unit: "test" vs "should"
It is a common practice to prefix the tests method names in JUnit with "test". But in the last few years, some people changed this to the prefix "should".

If I want to test the customer creation in a database, I would normally name the method "testCustomerCreation". However, some people would name "shouldCreateCustomer".

This is a lot of personal taste when I am the only person in the project or when everyone else in the project agrees with me. But when/where this is not the case, some divergences or inconsistent mixes starts to shows up.

I readed somewhere an article of a guy that named his methods like "testShouldCreateCustomer", and for this reason he decided to drop the "test" prefix. But in fact he wasn't prefixing with "test", he was using "testShould" and changed to "should". Obviously, this did not convinced me.

I am personally strongly inclined to stick to "test" prefix because the methods names normally starts with verbs in the infinitive form ("get", "set", "add", "remove", "clear", "send", "receive", "open", "close", "read", "write", "create", "list", "pop", "print", etc, so is "test"). So, prefixing a method name with "should" makes it sound really very strange for me, looks wrong.

So, what is the real good reason to use "should" instead of "test"? What are the great advantages and disadvantages?

答: In the original JUnit, test methods had to begin test. A lot of frameworks for other languages copied this convention. Even though it's no longer the case in JUnit, and even though other frameworks may be different, I think most programmers are still pretty familiar with methods named e.g. testX as being unit tests, so I think it's good to stick to the test convention for that reason.


问:
How to populate selectOneMenu list with values from 1 to 31
I need to create a selectOneMenu list for the day of birth. I need something like this:

```<code>for(int i=1;i<32;i++)
system.out.println(i);
</code>```

How can I achieve this?

答:
Without backing bean: </p>

```<code><h:selectOneMenu value="#{...}"  >
    <c:forEach var="i" begin="1" end="31">
        <f:selectItem itemLabel="#{i}" itemValue="#{i}" />
    </c:forEach>
</h:selectOneMenu>
</code>```

Body:
I need to create a selectOneMenu list for the day of birth. I need something like this:

for(int i=1;i<32;i++)
system.out.println(i);

How can I achieve this?

Body:
Without backing bean:

<h:selectOneMenu value="#{...}"  >
    <c:forEach var="i" begin="1" end="31">
        <f:selectItem itemLabel="#{i}" itemValue="#{i}" />
    </c:forEach>
</h:selectOneMenu>


问:
Jenkins environment different to interactive logon - why?
Using Jenkins 2.46.2 on Windows Server 2012 R2.

I have pipeline script that runs:

bat 'env'

I'm interested in environment variable: PSModulePath

This is output as

PSModulePath=C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\

in my console output. However, if I run this logged on as the Jenkins account on the Jenkins server, I get a different result:

PSModulePath=C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\;C:\Program File
s (x86)\Microsoft SQL Server\140\Tools\PowerShell\Modules\;C:\Program Files\Wind
owsPowerShell\Modules

Why is that? I can't load some modules in a Jenkins job because they can't be found.

答: I worked around this by explicitly adding the path as an environment variable to Jenkins, but I don't know why I had to do that. Anyway it works now.</p>


问:
Groovy-JSONSlurper: Transform JSON map into a key=value pair
I have a JSON object, which we assume to be flat (no nesting) and a map. How can I transform this into a single string of key=value pairs, delimited by tab using JSONSlurper in Groovy?</p>

答:
For example like that:</p>

```<code>StringBuilder keyStr = new StringBuilder()
def json = new JsonSlurper().parseText(jsonString)
json.each{keyStr.append(it.key).append("=").append(it.value).append("\t")}
someMap.put(strKey, someValue)
</code>```

Body:
For example like that:

StringBuilder keyStr = new StringBuilder()
def json = new JsonSlurper().parseText(jsonString)
json.each{keyStr.append(it.key).append("=").append(it.value).append("\t")}
someMap.put(strKey, someValue)


问:
ERR_TOO_MANY_REDIRECTS in PHP
My logout.php file is like this. Is there any mistake in my code

logout.php

```<code><?php
session_start();
session_destroy();
header('Location:index.php');
exit;
?>
</code>```

Here is my index.php file. If I am set $_SESSION['s_activId'] then it is working properly but when I am trying to put condition if $_SESSION['s_activId'] is not set at that time I want to pass header on index page sometimes it works sometimes it does not work.

```<code><?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    header("Location:index.php");
}
else
{
  $wrong = '';
  if(isset($_POST['submit']))
  {
    $checkLogin = "SELECT userName,password,userType
                     FROM user
                    WHERE BINARY userName = '".$_POST['userName']."'
                      AND BINARY password = '".$_REQUEST['password']."'";
    $checkLoginresult = mysql_query($checkLogin);
    if($userLoginRow = mysql_fetch_array($checkLoginresult))
    {
      $_SESSION['s_activId']   = $userLoginRow['userName'];
      $_SESSION['s_password']  = $userLoginRow['password'];
      $_SESSION['hg_userType'] = $userLoginRow['userType'];

     if(!$_SESSION['s_urlRedirectDir'])
      {
        header("Location:index.php");
      }
      else
      {
        header("Location:reminder.php");
      }
    }
    else
    {
      $wrong = "UserId And Password Is Not Valid";
    }
  }
}
include("bottom.php");
$smarty->assign('wrong',$wrong);
$smarty->display("index.tpl");
?>
</code>```

答:
Dont redirect index.php to index.php. you having redirects loop. Also
  if you have code below that also can fire add die in if because after
  redirect code below still executes.  I didnt read your code, maybe
  there isnt problems with this but after

```<code>header("Location: lalala"); always add die(); or exit();
</code>```

Title: ERR_TOO_MANY_REDIRECTS in PHP

Body:
My logout.php file is like this. Is there any mistake in my code

logout.php

<?php
session_start();
session_destroy();
header('Location:index.php');
exit;
?>

Here is my index.php file. If I am set $_SESSION['s_activId'] then it is working properly but when I am trying to put condition if $_SESSION['s_activId'] is not set at that time I want to pass header on index page sometimes it works sometimes it does not work.

<?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    header("Location:index.php");
}
else
{
  $wrong = '';
  if(isset($_POST['submit']))
  {
    $checkLogin = "SELECT userName,password,userType
                     FROM user
                    WHERE BINARY userName = '".$_POST['userName']."'
                      AND BINARY password = '".$_REQUEST['password']."'";
    $checkLoginresult = mysql_query($checkLogin);
    if($userLoginRow = mysql_fetch_array($checkLoginresult))
    {
      $_SESSION['s_activId']   = $userLoginRow['userName'];
      $_SESSION['s_password']  = $userLoginRow['password'];
      $_SESSION['hg_userType'] = $userLoginRow['userType'];

     if(!$_SESSION['s_urlRedirectDir'])
      {
        header("Location:index.php");
      }
      else
      {
        header("Location:reminder.php");
      }
    }
    else
    {
      $wrong = "UserId And Password Is Not Valid";
    }
  }
}
include("bottom.php");
$smarty->assign('wrong',$wrong);
$smarty->display("index.tpl");
?>

Body:
Dont redirect index.php to index.php. you having redirects loop. Also
  if you have code below that also can fire add die in if because after
  redirect code below still executes.  I didnt read your code, maybe
  there isnt problems with this but after

header("Location: lalala"); always add die(); or exit();


问:
How can i execute external script or function which generate random mail in mail field in the protractor script
The protractor script is just login form but I want in the field where is email to have a function which generates random mail or use an external script which generates random mail :

browser.driver.findElement(by.id('fullname')).sendKeys('LQLQLQLQ');
    browser.sleep(5000);

browser.driver.findElement(by.id('mobile')).sendKeys('899999888');
    browser.sleep(5000);

```<code>getRandomEmail = function () {
var strValues = "abcdefghijk123456789";
var strEmail = "";
for (var i = 0; i < strValues.length; i++) {
    strEmail = strEmail + strValues.charAt(Math.round(strValues.length * Math.random()));
}
return strEmail + "@mymail.test";
};
browser.driver.findElement(by.id('email')).executeScript('getRandomEmail');
</code>```

答:
This function will return an email address ending in '@mymail.test' of a length specified.

```<code>var randomEmail = function (emailLength) {
        var possible = 'abcdefghijklmnopqrstuvwxyz0123456789';
        function pickRandom() {
            return possible[Math.floor(Math.random() * possible.length)];
        };
        var strEmail = Array.apply(null, Array(emailLength)).map(pickRandom).join('');
        return strEmail + '@mymail.test';
    };
</code>```

You can then just call it like this:

```<code>element(by.id('fullname')).sendKeys('LQLQLQLQ');
element(by.id('mobile')).sendKeys('899999888');
element(by.id('email')).sendKeys(randomEmail(10));
</code>```

Note that you shouldn't need to use browser.sleep() at all.

Body:
The protractor script is just login form but I want in the field where is email to have a function which generates random mail or use an external script which generates random mail :

browser.driver.findElement(by.id('fullname')).sendKeys('LQLQLQLQ');
    browser.sleep(5000);

browser.driver.findElement(by.id('mobile')).sendKeys('899999888');
    browser.sleep(5000);

getRandomEmail = function () {
var strValues = "abcdefghijk123456789";
var strEmail = "";
for (var i = 0; i < strValues.length; i++) {
    strEmail = strEmail + strValues.charAt(Math.round(strValues.length * Math.random()));
}
return strEmail + "@mymail.test";
};
browser.driver.findElement(by.id('email')).executeScript('getRandomEmail');

Body:
This function will return an email address ending in '@mymail.test' of a length specified.

var randomEmail = function (emailLength) {
        var possible = 'abcdefghijklmnopqrstuvwxyz0123456789';
        function pickRandom() {
            return possible[Math.floor(Math.random() * possible.length)];
        };
        var strEmail = Array.apply(null, Array(emailLength)).map(pickRandom).join('');
        return strEmail + '@mymail.test';
    };

You can then just call it like this:

element(by.id('fullname')).sendKeys('LQLQLQLQ');
element(by.id('mobile')).sendKeys('899999888');
element(by.id('email')).sendKeys(randomEmail(10));

Note that you shouldn't need to use browser.sleep() at all.


问:
Nginx serve images from multiple static directories under one alias
I am making transition from apache to nginx, and i can not get the alias to serve images. Reading nginx documentation, diving in google and what not have not yielded any acceptable results for me ;(

The images is located C:/xampp/htdocs/content/XYZ/thumbn/image.jpg

the XYZ part is dynamic and changes.

Nginx is set up to serve content from  root C:/nginx/public_html/domain.dev/

In the apache i had simply made Alias /CDN "C:\xampp\htdocs\content"

So that way when ever i request www.domain.dev/CDN/XYZ/thumbn/image.jpg i would get the image from the alias directory.

So im trying to replicate the same in nginx

```<code>location /CDN {
alias C:/xampp/htdocs/content;
autoindex on; # just there to see if it works.
}
</code>```

Unfortunately when i access the image www.domain.dev/CDN/XYZ/thumbn/image.jpg i get 404. In the Nginx logs i see following record :

```<code>2017/07/04 16:43:32 [error] 10532#6488: *4 CreateFile() "C:/nginx/public_html/domain.dev/CDN/XYZ/thumbn/two.jpg" failed (3: The system cannot find the path specified), client: 127.0.0.1, server: www.domain.dev, request: "GET /CDN/XYZ/thumbn/two.jpg HTTP/1.1", host: "www.domain.dev"
</code>```

it is how ever listing the directory contents.

Now if i change the location block to this

```<code>    location ^~ /CDN/ {
        alias C:/xampp/htdocs/content/;
    }
</code>```

I get the same error in log, only way i managed to get it working (but not in the way i need) was when i use this location block

```<code>    location ^~ /CDN/ {
        alias C:/xampp/htdocs/content/XYZ/thumbn/;
    }
</code>```

Then it is showing the image, but the url for the image is different and not valid for my project.

Now the question: how do i serve only images from multiple static directories under same alias?
the images are located in following structure

```<code>C:/xampp/htdocs/content/one/thumbn/image.jpg
C:/xampp/htdocs/content/two/thumbn/cats.jpg
C:/xampp/htdocs/content/three/thumbn/dogs.jpg
C:/xampp/htdocs/content/another_random_direcotry/thumbn/random.jpg
</code>```

And they should be accessed by URL as follows

```<code>www.domain.dev/CDN/one/thumbn/image.jpg
www.domain.dev/CDN/two/thumbn/cats.jpg
www.domain.dev/CDN/three/thumbn/dogs.jpg
www.domain.dev/CDN/another_random_direcotry/thumbn/random.jpg
</code>```

Is this even possible with Nginx? so how do i achieve this? Is regex required in this occasion?

full config file here

答:
The problem was caused by

```<code>    location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 7d;
    }
</code>```

When i comment out this location directive i can access the images from alias directory.

This how ever removes expiration header for images and with this enabled i can not access the images.

Body:
I am making transition from apache to nginx, and i can not get the alias to serve images. Reading nginx documentation, diving in google and what not have not yielded any acceptable results for me ;(

The images is located C:/xampp/htdocs/content/XYZ/thumbn/image.jpg

the XYZ part is dynamic and changes.

Nginx is set up to serve content from  root C:/nginx/public_html/domain.dev/

In the apache i had simply made Alias /CDN "C:\xampp\htdocs\content"

So that way when ever i request www.domain.dev/CDN/XYZ/thumbn/image.jpg i would get the image from the alias directory.

So im trying to replicate the same in nginx

location /CDN {
alias C:/xampp/htdocs/content;
autoindex on; # just there to see if it works.
}

Unfortunately when i access the image www.domain.dev/CDN/XYZ/thumbn/image.jpg i get 404. In the Nginx logs i see following record :

2017/07/04 16:43:32 [error] 10532#6488: *4 CreateFile() "C:/nginx/public_html/domain.dev/CDN/XYZ/thumbn/two.jpg" failed (3: The system cannot find the path specified), client: 127.0.0.1, server: www.domain.dev, request: "GET /CDN/XYZ/thumbn/two.jpg HTTP/1.1", host: "www.domain.dev"

it is how ever listing the directory contents.

Now if i change the location block to this

    location ^~ /CDN/ {
        alias C:/xampp/htdocs/content/;
    }

I get the same error in log, only way i managed to get it working (but not in the way i need) was when i use this location block

    location ^~ /CDN/ {
        alias C:/xampp/htdocs/content/XYZ/thumbn/;
    }

Then it is showing the image, but the url for the image is different and not valid for my project.

Now the question: how do i serve only images from multiple static directories under same alias?
the images are located in following structure

C:/xampp/htdocs/content/one/thumbn/image.jpg
C:/xampp/htdocs/content/two/thumbn/cats.jpg
C:/xampp/htdocs/content/three/thumbn/dogs.jpg
C:/xampp/htdocs/content/another_random_direcotry/thumbn/random.jpg

And they should be accessed by URL as follows

www.domain.dev/CDN/one/thumbn/image.jpg
www.domain.dev/CDN/two/thumbn/cats.jpg
www.domain.dev/CDN/three/thumbn/dogs.jpg
www.domain.dev/CDN/another_random_direcotry/thumbn/random.jpg

Is this even possible with Nginx? so how do i achieve this? Is regex required in this occasion?

full config file here

Body:
The problem was caused by

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 7d;
    }

When i comment out this location directive i can access the images from alias directory.

This how ever removes expiration header for images and with this enabled i can not access the images.


问:
Query Join Condition
I Have two tables named account and assignedgroup. In account table there are two columns named ID and sourceaccount and In assignedgroup I have two columns named ID and assignedgroup.

I want to select ID by joining account and assignedgroup tables. I did something like this:

```<code>select a.ID
from account a
  left outer join assignedgroup b
   on a.sourceaccount = b.assignedgorup
</code>```

But I get Null as output the reason being that The values in sourceaccount are like this

sourceaccount:

```<code>sample
sample
</code>```

and whereas the values in assignedgroup are like this

assignedgroup:

```<code>sample-L1
sample-P-L1
</code>```

Can anyone help me on how to join these two tables?

I want to get all the ID's whenever there is a sample value in both sourceaccount and assignedgroup.

It is comparing sample with sample-L1 since those are not equal it is returning null but I want the ID even if it has values like that. I mean if somepart of the column values matches then also I want those values to be displayed

答:
Since the actual data within those two tables does not actually match, you cannot join those rows in those tables unless you start making some rather broad assumptions about the nature of the data in those tables. For example, this might work:

```<code>SELECT a.ID
 from Account a
  left outer join AssignedGroup b
   on a.sourceaccount = left(b.assignedgroup, 6)
</code>```

or, more generically,

```<code>SELECT a.ID
 from Account a
  left outer join AssignedGroup b
   on a.sourceaccount = left(b.assignedgroup, len(a.sourceaccount))
</code>```

However, this is truly horrible code, logic, and database design, and I would only use this while tyring to troubleshoot and/or fix messed-up data.

Title: Query Join Condition

Body:
I Have two tables named account and assignedgroup. In account table there are two columns named ID and sourceaccount and In assignedgroup I have two columns named ID and assignedgroup.

I want to select ID by joining account and assignedgroup tables. I did something like this:

select a.ID
from account a
  left outer join assignedgroup b
   on a.sourceaccount = b.assignedgorup

But I get Null as output the reason being that The values in sourceaccount are like this

sourceaccount:

sample
sample

and whereas the values in assignedgroup are like this

assignedgroup:

sample-L1
sample-P-L1

Can anyone help me on how to join these two tables?

I want to get all the ID's whenever there is a sample value in both sourceaccount and assignedgroup.

It is comparing sample with sample-L1 since those are not equal it is returning null but I want the ID even if it has values like that. I mean if somepart of the column values matches then also I want those values to be displayed

Body:
Since the actual data within those two tables does not actually match, you cannot join those rows in those tables unless you start making some rather broad assumptions about the nature of the data in those tables. For example, this might work:

SELECT a.ID
 from Account a
  left outer join AssignedGroup b
   on a.sourceaccount = left(b.assignedgroup, 6)

or, more generically,

SELECT a.ID
 from Account a
  left outer join AssignedGroup b
   on a.sourceaccount = left(b.assignedgroup, len(a.sourceaccount))

However, this is truly horrible code, logic, and database design, and I would only use this while tyring to troubleshoot and/or fix messed-up data.


问:
$_GET Parameter already exist, replace parameter
I have a question im busy with a filter inside of wordpress. Now i have problem i try to explain.

If a visitor select a "single merk" url gonna be ?merk=Brand1 and than option 2 is select "Soort" than the url is gonna be "?merk=Brand1&soort=Soort1" that works.

But if you have select both, than want to change only ?merk=Brand2 than the url is "?merk=Brand2&soort=Soort1&merk=brand1" how can i make it if you switch between the "merk" that "Brand1" replaced to "Brand2".

Here is the code:

```<code>            foreach ( $allemerken as $merksingle ) { ?>
                <?php if(isset($_GET['merk']) && $_GET['merk'] == $merksingle->slug){?>
                <a href="<?php echo $current_url; ?>" class="filter_merklink active"><i class="fa fa-times" aria-hidden="true"></i> <?php echo $merksingle->name; ?></a>
                <?php }else{ ?>
                <a href="<?php echo $current_url; ?>?merk=<?php echo $merksingle->slug;?><?php if(isset($_GET['soort']) && $_GET['soort'] != ''){ echo '&'.$_SERVER['QUERY_STRING'];} ?>" class="filter_merklink"><?php echo $merksingle->name; ?></a>
                <?php }?>
            <?php }?>
            <p class="mt-30"><strong>Soort:</strong></p>
            <?php
            $soorten = get_terms('warmtepompcategorie');
//            echo '```'.print_r($allemerken,true).'```';
            foreach ( $soorten as $soort ) { ?>
                <?php if(isset($_GET['soort']) && $_GET['soort'] == $soort->slug){?>
                " class="filter_merklink active"><i class="fa fa-times" aria-hidden="true"></i> <?php echo $soort->name; ?>
                <?php }else{ ?>
                ?soort=<?php echo $soort->slug;?><?php if(isset($_GET['merk']) && $_GET['merk'] != ''){ echo '&'.$_SERVER['QUERY_STRING'];} ?>" class="filter_merklink"><?php echo $soort->name; ?>
                <?php }?>
            <?php }?>
</code>```

Ps. sorry for my bad English, but hope someone can help me out!

答:
I have made a function.
And i did it like this:</p>

```<code>function replace_get($newname,$newvalue){
    $oldvars = $_GET;
    $varsnew = $newname.'='.$newvalue;
    foreach($oldvars as $name=> $value){
        if($name != $newname){
            $varsnew .= '&'.$name.'='.$value;
        }
    }
    return $varsnew;
}
</code>```

Body:
I have a question im busy with a filter inside of wordpress. Now i have problem i try to explain.

If a visitor select a "single merk" url gonna be ?merk=Brand1 and than option 2 is select "Soort" than the url is gonna be "?merk=Brand1&soort=Soort1" that works.

But if you have select both, than want to change only ?merk=Brand2 than the url is "?merk=Brand2&soort=Soort1&merk=brand1" how can i make it if you switch between the "merk" that "Brand1" replaced to "Brand2".

Here is the code:

            foreach ( $allemerken as $merksingle ) { ?>
                <?php if(isset($_GET['merk']) && $_GET['merk'] == $merksingle->slug){?>
                <a href="<?php echo $current_url; ?>" class="filter_merklink active"> <?php echo $merksingle->name; ?>
                <?php }else{ ?>
                <a href="<?php echo $current_url; ?>?merk=<?php echo $merksingle->slug;?><?php if(isset($_GET['soort']) && $_GET['soort'] != ''){ echo '&'.$_SERVER['QUERY_STRING'];} ?>" class="filter_merklink"><?php echo $merksingle->name; ?>
                <?php }?>
            <?php }?>

Soort:

            <?php
            $soorten = get_terms('warmtepompcategorie');
//            echo '
'.print_r($allemerken,true).'
';
            foreach ( $soorten as $soort ) { ?>
                <?php if(isset($_GET['soort']) && $_GET['soort'] == $soort->slug){?>
                <a href="<?php echo $current_url; ?>" class="filter_merklink active"> <?php echo $soort->name; ?>
                <?php }else{ ?>
                <a href="<?php echo $current_url; ?>?soort=<?php echo $soort->slug;?><?php if(isset($_GET['merk']) && $_GET['merk'] != ''){ echo '&'.$_SERVER['QUERY_STRING'];} ?>" class="filter_merklink"><?php echo $soort->name; ?>
                <?php }?>
            <?php }?>

Ps. sorry for my bad English, but hope someone can help me out!

Body:
I have made a function.
And i did it like this:

function replace_get($newname,$newvalue){
    $oldvars = $_GET;
    $varsnew = $newname.'='.$newvalue;
    foreach($oldvars as $name=> $value){
        if($name != $newname){
            $varsnew .= '&'.$name.'='.$value;
        }
    }
    return $varsnew;
}


问:
Regex replace any number of matches at the start of the line
I have text with this structure:

```<code>1.  Text1
2.  Text 2. It has a number with a dot.
3.  1.   Text31
</code>```

I want to get this text:

```<code># Text1
# Text 2. It has a number with a dot. (notice that this number did not get replaced)
## Text31
</code>```

I tried doing the following but it does not work

```<code>var pattern = @"^(\s*\d+\.\s*)+";
var replaced = Regex.Replace(str, pattern, "#", RegexOptions.Multiline);
</code>```

Basically, it should start matching at the start of every line and replace every matched group with # symbol. Currently, if more than one group is matched, everything is replaced by a single # symbol. Pattern I am using is probably incorrect, can anyone come up with a solution?

答:
You may use

```<code>(?:\G|^)\s*\d+\.
</code>```

It matches the start of string or the end of the previous successful match or start of a line, and then zero or more whitespaces, one or more digits and a dot.

Details

(?:\G|^) - start of string or end of the previous match (\G) or the start of a line (^)

\s* - zero or more whitespaces if you want to only match horizontal whitespaces to avoid overflowing to the next lie(s) replace with [\s-[\r\n]]* or [\p{Zs}\t]*)

\d+ - one or more digits (to match only ASCII digits, replace with [0-9]+ or pass the RegexOptions.ECMAScript option to the Regex constructor)

\. - a dot.

The RegexOptions.Multiline option must be passed to the Regex constructor to make ^ match the start of a line. Or add an inline version of the anchor, (?m), at the start of the pattern.

For more details about \G anchor, see Continuing at The End of The Previous Match.

See the RegexStorm demo.

Body:
I have text with this structure:

1.  Text1
2.  Text 2. It has a number with a dot.
3.  1.   Text31

I want to get this text:

# Text1
# Text 2. It has a number with a dot. (notice that this number did not get replaced)
## Text31

I tried doing the following but it does not work

var pattern = @"^(\s*\d+\.\s*)+";
var replaced = Regex.Replace(str, pattern, "#", RegexOptions.Multiline);

Basically, it should start matching at the start of every line and replace every matched group with # symbol. Currently, if more than one group is matched, everything is replaced by a single # symbol. Pattern I am using is probably incorrect, can anyone come up with a solution?

Body:
You may use

(?:\G|^)\s*\d+\.

It matches the start of string or the end of the previous successful match or start of a line, and then zero or more whitespaces, one or more digits and a dot.

Details

(?:\G|^) - start of string or end of the previous match (\G) or the start of a line (^)

\s* - zero or more whitespaces if you want to only match horizontal whitespaces to avoid overflowing to the next lie(s) replace with [\s-[\r\n]]* or [\p{Zs}\t]*)

\d+ - one or more digits (to match only ASCII digits, replace with [0-9]+ or pass the RegexOptions.ECMAScript option to the Regex constructor)

\. - a dot.

The RegexOptions.Multiline option must be passed to the Regex constructor to make ^ match the start of a line. Or add an inline version of the anchor, (?m), at the start of the pattern.

For more details about \G anchor, see Continuing at The End of The Previous Match.

See the RegexStorm demo.


问:
Condition on rows content of dataframe in Spark scala
I have the following dataframe:

```<code>+--------+---------+------+
|  value1| value2  |value3|
+--------+---------+------+
|   a    |  2      |   3  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   c    |  3      |   4  |
+--------+---------+------+
</code>```

I would like to put the result of value2/value3 of the rows when value1=b, then add it for all the rows (even the rows that do not belong to b) in a new field with name of "result". It means that another column must be added to the dataframe. For example for all the rows, the result of 5/4 (I choose it since, it is for b) should be added to dataframe. I know that, I should use this code:

```<code> val dataframe_new = Dataframe.withColumn("result", $"value1" / $"value2")
 Dataframe.show()
</code>```

However how can I put the condition in such a way that, it added it to all rows. The output should be like below:

```<code>+---+---+---+------+
| v1| v2| v3|result|
+---+---+---+------+
|  a|  2|  3|  1.25|
|  b|  5|  4|  1.25|
|  b|  5|  4|  1.25|
|  c|  3|  4|  1.25|
+---+---+---+------+
</code>```

Can you help me? Thanks in advance.

Body:
I have the following dataframe:

+--------+---------+------+
|  value1| value2  |value3|
+--------+---------+------+
|   a    |  2      |   3  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   c    |  3      |   4  |
+--------+---------+------+

I would like to put the result of value2/value3 of the rows when value1=b, then add it for all the rows (even the rows that do not belong to b) in a new field with name of "result". It means that another column must be added to the dataframe. For example for all the rows, the result of 5/4 (I choose it since, it is for b) should be added to dataframe. I know that, I should use this code:

 val dataframe_new = Dataframe.withColumn("result", $"value1" / $"value2")
 Dataframe.show()

However how can I put the condition in such a way that, it added it to all rows. The output should be like below:

+---+---+---+------+
| v1| v2| v3|result|
+---+---+---+------+
|  a|  2|  3|  1.25|
|  b|  5|  4|  1.25|
|  b|  5|  4|  1.25|
|  c|  3|  4|  1.25|
+---+---+---+------+

Can you help me? Thanks in advance.

Body:
You just need to use when :

scala> val df = Seq(("a",2,3),("b",5,4),("b",5,4),("c",3,4)).toDF("v1","v2","v3")
df: org.apache.spark.sql.DataFrame = [v1: string, v2: int ... 1 more field]

scala> df.withColumn("result", when($"v1" === "b" , ($"v2"/$"v3"))).show
+---+---+---+------+
| v1| v2| v3|result|
+---+---+---+------+
|  a|  2|  3|  null|
|  b|  5|  4|  1.25|
|  b|  5|  4|  1.25|
|  c|  3|  4|  null|
+---+---+---+------+

You can embed multiple when as followed :

scala> df.withColumn("result", when($"v1" === "b" , ($"v2"/$"v3")).
     |    otherwise(when($"v1" === "a", $"v3"/$"v2"))).show
+---+---+---+------+
| v1| v2| v3|result|
+---+---+---+------+
|  a|  2|  3|   1.5|
|  b|  5|  4|  1.25|
|  b|  5|  4|  1.25|
|  c|  3|  4|  null|
+---+---+---+------+

EDIT: It seems that you need something else where the condition for v1 has always the same values v2 and v3 which allows us doing the following :

With Spark 2+ :

scala> val res = df.filter($"v1" === lit("b")).distinct.select($"v2"/$"v3").as[Double].head
res: Double = 1.25

Before Spark <2 :

scala> val res = df.filter($"v1" === lit("b")).distinct.withColumn("result",$"v2"/$"v3").rdd.map(_.getAs[Double]("result")).collect()(0)
res: Double = 1.25

scala> df.withColumn("v4", lit(res)).show
+---+---+---+----+
| v1| v2| v3|  v4|
+---+---+---+----+
|  a|  2|  3|1.25|
|  b|  5|  4|1.25|
|  b|  5|  4|1.25|
|  c|  3|  4|1.25|
+---+---+---+----+


问:
Querying collection created by an app in another Meteor js app
I have 2 apps that query the same db, they both created diff collections on a db. App A at myapp:3000 created a collection comments while app B at myapp:3300 created courses at its end in the same db (school). both servers are running, how do I query the a collection created by app A in app B?

My reason for asking this question is that, as a newbie, it is easy for me to query new collection created in an app by using it global variable. Let's say I created

```<code>UsesList = new Mongo.Collection('useslist');
</code>```

it is possible for me to publish it this way:

```<code>Meteor.publish('UsesList', function () {
        if (!this.userId) {
            return false;
            throw new Meteor.Error('Not authorized');
        } else {
            return UsesList.find();
        }
    });
</code>```

I wouldn't have access to this variable, and I think accessing the database directly to query the collection might be unethical.

答:
No problem in "creating" the same collection in two different applications.

The collection identity is determined by the name string you provide to the collection constructor, and the identity of the database itself, of course.

You can assign them to whatever variable identifier you want, and they may be different between the applications.

I would, however, recommend you to start using ES6 modules and reduce global namespace pollution. Start using the best practices when you are learning, so you won't have to unlearn the bad ones later.

So, provided both apps are connected to the same DB:

```<code>// same in app 1 and app 2
import { Mongo } from 'meteor/mongo';
export const UsesList = new Mongo.Collection('user_list');

// and importing it
import { UserList } from '../path/to/other/file';
</code>```

Body:
I have 2 apps that query the same db, they both created diff collections on a db. App A at myapp:3000 created a collection comments while app B at myapp:3300 created courses at its end in the same db (school). both servers are running, how do I query the a collection created by app A in app B?

My reason for asking this question is that, as a newbie, it is easy for me to query new collection created in an app by using it global variable. Let's say I created

UsesList = new Mongo.Collection('useslist');

it is possible for me to publish it this way:

Meteor.publish('UsesList', function () {
        if (!this.userId) {
            return false;
            throw new Meteor.Error('Not authorized');
        } else {
            return UsesList.find();
        }
    });

I wouldn't have access to this variable, and I think accessing the database directly to query the collection might be unethical.

Body:
No problem in "creating" the same collection in two different applications.

The collection identity is determined by the name string you provide to the collection constructor, and the identity of the database itself, of course.

You can assign them to whatever variable identifier you want, and they may be different between the applications.

I would, however, recommend you to start using ES6 modules and reduce global namespace pollution. Start using the best practices when you are learning, so you won't have to unlearn the bad ones later.

So, provided both apps are connected to the same DB:

// same in app 1 and app 2
import { Mongo } from 'meteor/mongo';
export const UsesList = new Mongo.Collection('user_list');

// and importing it
import { UserList } from '../path/to/other/file';


答:
If your data never has two lines near each other containing 1 column:</p>

```<code>awk '{if(NF==1 && NR!=1){printf("\n%s",$0)} else{printf("%s",$0)}}' file
</code>```

Title: Sort block of numbers into columns

Body:
i have a file with alot of data written out of a simulation:

  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.93071889E-02
  0.14952319E-13  0.55746201E-11  0.89816722E-11  0.46833532E-11  0.14964636E-13
 -0.92995325E-47  0.79969902E-46  0.00000000E+00 -0.21442451-105 -0.86924526E-93
  0.00000000E+00 -0.85777333E-93  0.48179949-102  0.00000000E+00
  0.18614378E-01
  0.12050471E-12  0.44928328E-10  0.72404536E-10  0.37744496E-10  0.12066634E-12
  0.25848493E-36 -0.13804858E-35  0.56376226E-83  0.20648121E-74 -0.89608567E-66
 -0.20861629E-76 -0.87854256E-66 -0.23574755E-73 -0.73275846E-82

Desired Output is: Each Block of Data written in its own column and the column starts with the "header" of each block, which is the first number. For example the last block should look like this:

0.18614378E-01 0.12050471E-12  0.44928328E-10  0.72404536E-10 0.37744496E-10  0.12066634E-12 0.25848493E-36 -0.13804858E-35  0.56376226E-83 0.20648121E-74 -0.89608567E-66 -0.20861629E-76 -0.87854256E-66 -0.23574755E-73 -0.73275846E-82

I thought about using AWK with FS=' ', but i don’t know how to tell my bash script to stop after reading 15 numbers and how to save those 15 numbers and output them into a separate file (using printf maybe?)

Thanks!

Body:
If your data never has two lines near each other containing 1 column:

awk '{if(NF==1 && NR!=1){printf("\n%s",$0)} else{printf("%s",$0)}}' file


问:
How to bend a div in CSS
I need some help with some css I am playing around.
How can I bend a div with css to achieve something like in the image below.
I need to blue filled divs which are curved.

答:
A similar effect can be achieved using two divs and CSS:

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

#c {
  height: 110px;
  overflow: hidden;
}
#b {
  height: 150px;
  width: 150px;
  border: 30px solid blue;
  border-radius: 50%;
  margin-top: -50px;
  margin-left: -150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="c">
  <div id="b"></div>
</div></code>```

Title: How to bend a div in CSS

Body:
A similar effect can be achieved using two divs and CSS:

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

#c {
  height: 110px;
  overflow: hidden;
}
#b {
  height: 150px;
  width: 150px;
  border: 30px solid blue;
  border-radius: 50%;
  margin-top: -50px;
  margin-left: -150px;
}

<div id="c">
  <div id="b"></div>
</div>


问:
Rails multiple exceptions handler with "exceptions_app" per route namespace
is there any solution how to handle Rails exceptions per route namespace with defined direction config.exceptions_app ?

I have versioned interface eg /api/v1, /api/v2. Every namespace uses different JSON/XML/HTML response structure.

Global definition is nice, but i need something more dynamic.

RESOLVE:

config.exceptions_app takes closure/lambda block. In that block i could create simple case statement like this:

```<code>config.exceptions_app = lambda do |env|
  case env['REQUEST_PATH']
  when %r{^(\/api\/v1)}
    Api::V1::ExceptionsController.action(:show).call(env)
  when %r{^(\/api\/v2)}
    Api::V2::ExceptionsController.action(:show).call(env)
  when %r{^(\/cms\/)}
    Cms::ExceptionsController.action(:show).call(env)
  end
end
</code>```

答: Have you looked into rescue_from? It allows you to catch all exceptions (of a given type) inside the controllers and render them how you wish</p>

Body:
is there any solution how to handle Rails exceptions per route namespace with defined direction config.exceptions_app ?

I have versioned interface eg /api/v1, /api/v2. Every namespace uses different JSON/XML/HTML response structure.

Global definition is nice, but i need something more dynamic.

RESOLVE:

config.exceptions_app takes closure/lambda block. In that block i could create simple case statement like this:

config.exceptions_app = lambda do |env|
  case env['REQUEST_PATH']
  when %r{^(\/api\/v1)}
    Api::V1::ExceptionsController.action(:show).call(env)
  when %r{^(\/api\/v2)}
    Api::V2::ExceptionsController.action(:show).call(env)
  when %r{^(\/cms\/)}
    Cms::ExceptionsController.action(:show).call(env)
  end
end