问:
Right click without Actions in Selenium 3.x in Firefox browser
How to right click an element without using Actions object. I get exception while using Actions in Selenium3 in FireFox  with GeckoDriver.
I have used the following code to set the GeckoDriver property.</p>

```<code>System.setProperty("webdriver.gecko.driver", new File("lib/geckodriver").getAbsolutePath());
</code>```

答:
Try using Robot class to right click on WebElement:

```<code>Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_ENTER);
</code>```

and to set the system properties for gecko driver you can use the below line :

System.setProperty("webdriver.gecko.driver",
                            path of your geckodriver.exe");

Body:
How to right click an element without using Actions object. I get exception while using Actions in Selenium3 in FireFox  with GeckoDriver.
I have used the following code to set the GeckoDriver property.

System.setProperty("webdriver.gecko.driver", new File("lib/geckodriver").getAbsolutePath());

Body:
Try using Robot class to right click on WebElement:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_ENTER);

and to set the system properties for gecko driver you can use the below line :

System.setProperty("webdriver.gecko.driver",
                            path of your geckodriver.exe");


来源: stackexchange

问:
Getting a Rails App to Work with Git Pages to Create a Personal Blog
I created a git page -> https://github.com/username/username.github.io.git

I then created a workspace in Cloud9-IDE and cloned https://github.com/username/username.github.io.git

Then I installed Rails from the terminal gem install rails -v 5.0.1
and create a new Rails app rails _5.0.1_ new blog, I created a 'Hello World' home page and confirmed that it was working locally with Rails Server.

I then committed the changes and pushed successfully to GitHub, the commits are visible in the repo.

```<code>git add -A
git commit -m "message"
git push
</code>```

However, when visiting https://username.github.io I do not see anything other than username.github.io from the README at the top of the page.

答:
I'm afraid not. Rails is a dynamic system, meaning that the pages are generated from templates combined with data. Github Pages only servers static HTML, so even if you put static content into Rails, you would not be able to run the scripts that serve it.

If you really need Rails, use Heroku free plan.

ContentLicense: CC BY-SA 3.0

Body:
I created a git page -> https://github.com/username/username.github.io.git

I then created a workspace in Cloud9-IDE and cloned https://github.com/username/username.github.io.git

Then I installed Rails from the terminal gem install rails -v 5.0.1
and create a new Rails app rails _5.0.1_ new blog, I created a 'Hello World' home page and confirmed that it was working locally with Rails Server.

I then committed the changes and pushed successfully to GitHub, the commits are visible in the repo.

git add -A
git commit -m "message"
git push

However, when visiting https://username.github.io I do not see anything other than username.github.io from the README at the top of the page.


问:
SQL giving me headache - multiple joins
First I'll explain my scenario. Here's the 2 general tables in use:

Accounts:

LegacyID = The identifer of the
account

InvoiceAccount = An account can have
multiple subaccounts in the same
table. This    field is the LegacyID
of its parent account

Customer = There can be two different
types of accounts, and they can share
ID's - so this column differentiates
between the 2. For the purposes of my
SQL I always want it to be true rather
than false

AllocatedUser = The username of the
person who needs to see this
deliveries. This is only populated on
the parent account, so I need to link
back to get this for the subaccounts

Deliveries:

LegacyID = The deliveries identifier

Customer = The LegacyID of the account
related to the delivery (can be a
subaccount)

OnHold = A flag which for the purposes
of my query needs to be 'true'

Now that's explained, basically I need an SQL which returns any deliveries that are 'OnHold', but only for deliveries for accounts that are allocated the logged in user. The query for selecting the AllocatedUser if the delivery links to a parent account was simple, but I'm having issues with returning rows if the delivery is linked to a subaccount - it's simply not returning any. Here is the SQL below:

```<code>SELECT     Deliveries_1.LegacyID, Deliveries_1.TripDate, Deliveries_1.OnHoldReason, Account_2.AllocatedUser
FROM         Deliveries AS Deliveries_1 INNER JOIN
                      Account AS Account_1 ON Deliveries_1.Customer = Account_1.InvoiceAccount INNER JOIN
                      Account AS Account_2 ON Account_1.InvoiceAccount = Account_2.LegacyID
WHERE     (Deliveries_1.OnHold = @OnHold) AND (Account_2.Customer = 'True') AND (Account_2.AllocatedUser = @AllocatedUser)
</code>```

My mind is frazzled from trying to work out why it don't work at the moment - I'd really appreciate any advice.

Thanks!

答:
First comment is that you should build the joins in steps if you are having issues.

Second comment is that in the query you posted there is unnecessary join - you are not filtering nor selecting nor joining on anything specific from table aliased as Account_1.

Maybe that is an indication of what you are doing wrong. Otherwise, the query looks(!) ok (assuming that all the joins are correct; your descriptions are not exact - for example for Accounts.Customer you say that 'For the purposes of my SQL I always want it to be true rather than false' - well the Customer is not true/false field is it? What do you mean? There are other such inconsistencies...)

Some sample data and a sample of the result could shed some more light.

ContentLicense: CC BY-SA 2.5

Title: SQL giving me headache - multiple joins

Body:
First I'll explain my scenario. Here's the 2 general tables in use:

Accounts:

LegacyID = The identifer of the
account

InvoiceAccount = An account can have
multiple subaccounts in the same
table. This    field is the LegacyID
of its parent account

Customer = There can be two different
types of accounts, and they can share
ID's - so this column differentiates
between the 2. For the purposes of my
SQL I always want it to be true rather
than false

AllocatedUser = The username of the
person who needs to see this
deliveries. This is only populated on
the parent account, so I need to link
back to get this for the subaccounts

Deliveries:

LegacyID = The deliveries identifier

Customer = The LegacyID of the account
related to the delivery (can be a
subaccount)

OnHold = A flag which for the purposes
of my query needs to be 'true'

Now that's explained, basically I need an SQL which returns any deliveries that are 'OnHold', but only for deliveries for accounts that are allocated the logged in user. The query for selecting the AllocatedUser if the delivery links to a parent account was simple, but I'm having issues with returning rows if the delivery is linked to a subaccount - it's simply not returning any. Here is the SQL below:

SELECT     Deliveries_1.LegacyID, Deliveries_1.TripDate, Deliveries_1.OnHoldReason, Account_2.AllocatedUser
FROM         Deliveries AS Deliveries_1 INNER JOIN
                      Account AS Account_1 ON Deliveries_1.Customer = Account_1.InvoiceAccount INNER JOIN
                      Account AS Account_2 ON Account_1.InvoiceAccount = Account_2.LegacyID
WHERE     (Deliveries_1.OnHold = @OnHold) AND (Account_2.Customer = 'True') AND (Account_2.AllocatedUser = @AllocatedUser)

My mind is frazzled from trying to work out why it don't work at the moment - I'd really appreciate any advice.

Thanks!


问:
lambda in list comprehension error
I am doing the following:

```<code>ll = [-8, -4, 0, 4, 8]
[lambda x: x**2 for x in ll]
</code>```

and getting following error:

```<code>[<function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>]
</code>```

What could be the problem? I know desired result can be achieved by below code but I want to understand why lambda is not working in list comprehension?

```<code>[x**2 for x in ll]
</code>```

答:
You don't make clear what you expected instead, but I'm suggesting this:</p>

```<code>ll = [-8, -4, 0, 4, 8]
f = lambda x: x**2
print([f(x) for x in ll])
</code>```

Title: lambda in list comprehension error

Body:
I am doing the following:

ll = [-8, -4, 0, 4, 8]
[lambda x: x**2 for x in ll]

and getting following error:

[<function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>]

What could be the problem? I know desired result can be achieved by below code but I want to understand why lambda is not working in list comprehension?

[x**2 for x in ll]

Body:
You don't make clear what you expected instead, but I'm suggesting this:

ll = [-8, -4, 0, 4, 8]
f = lambda x: x**2
print([f(x) for x in ll])


问:
ECONRESET socket hungup
I have a function that triggers on firebase database onWrite. The function body use two google cloud apis (DNS and Storage).

While the function is running and working as expected (mostly), the issue is that the Socket hang up more often than I'd like. (50%~ of times)

My questions are:
Is it similar to what the rest of the testers have experienced? Is it a well known issue that is outstanding or expected behavior?

the example code is as follows:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {credentials} = functions.config().auth;
credentials.private_key = credentials.private_key.replace(/\\n/g, '\n');
const config = Object.assign({}, functions.config().firebase, {credentials});
admin.initializeApp(config);
const gcs = require('@google-cloud/storage')({credentials});
const dns = require('@google-cloud/dns')({credentials});
const zoneName = 'applambda';
const zone = dns.zone(zoneName);

exports.createDeleteDNSAndStorage = functions.database.ref('/apps/{uid}/{appid}/name')
.onWrite(event => {
    // Only edit data when it is first created.
    const {uid, appid} = event.params;
    const name = event.data.val();
    const dbRef = admin.database().ref(`/apps/${uid}/${appid}`);

    if (event.data.previous.exists()) {
        console.log(`already exists ${uid}/${appid}`);
        return;
    }
    // Exit when the data is deleted.
    if (!event.data.exists()) {
        console.log(`data is being deleted ${uid}/${appid}`);
        return;
    }

    const url = `${name}.${zoneName}.com`;
    console.log(`data: ${uid}/${appid}/${name}\nsetting up: ${url}`);

    setupDNS({url, dbRef});
    setupStorage({url, dbRef});
    return;
});

function setupDNS({url, dbRef}) {

    // Create an NS record.
    let cnameRecord = zone.record('cname', {
        name: `${url}.`,
        data: 'c.storage.googleapis.com.',
        ttl: 3000
    });

    zone.addRecords(cnameRecord).then(function() {
        console.log(`done setting up zonerecord for ${url}`);
        dbRef.update({dns: url}).then(res => console.log(res)).catch(err => console.log(err));
    }).catch(function(err) {
        console.error(`error setting up zonerecord for ${url}`);
        console.error(err);
    });
}

function setupStorage({url, dbRef}) {
    console.log(`setting up storage bucket for ${url}`);

    gcs.createBucket(url, {
        website: {
            mainPageSuffix: `https://${url}`,
            notFoundPage: `https://${url}/404.html`
        }
    }).then(function(res) {
        let bucket = res[0];
        console.log(`created bucket ${url}, setting it as public`);
        dbRef.update({storage: url}).then(function() {
            console.log(`done setting up bucket for ${url}`);
        }).catch(function(err) {
            console.error(`db update for storage failed ${url}`);
            console.error(err);
        });
        bucket.makePublic().then(function() {
            console.log(`bucket set as public for ${url}`);
        }).catch(function(err) {
            console.error(`setting public for storage failed ${url}`);
            console.error(err);
        });
    }).catch(function(err) {
        console.error(`creating bucket failed ${url}`);
        console.error(err);
    });
}
</code>```

答:
I'm thinking your function needs to return a promise so that all the other async work has time to complete before the function shuts down.  As it's shown now, your functions simply returns immediately without waiting for the work to complete.

I don't know the cloud APIs you're using very well, but I'd guess that you should make your setupDns() and setupStorage() return the promises from the async work that they're doing, then return Promise.all() passing those two promises to let Cloud Functions know it should wait until all that work is complete before cleaning up the container that's running the function.

Title: ECONRESET socket hungup

Body:
I have a function that triggers on firebase database onWrite. The function body use two google cloud apis (DNS and Storage).

While the function is running and working as expected (mostly), the issue is that the Socket hang up more often than I'd like. (50%~ of times)

My questions are:
Is it similar to what the rest of the testers have experienced? Is it a well known issue that is outstanding or expected behavior?

the example code is as follows:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {credentials} = functions.config().auth;
credentials.private_key = credentials.private_key.replace(/\\n/g, '\n');
const config = Object.assign({}, functions.config().firebase, {credentials});
admin.initializeApp(config);
const gcs = require('@google-cloud/storage')({credentials});
const dns = require('@google-cloud/dns')({credentials});
const zoneName = 'applambda';
const zone = dns.zone(zoneName);

exports.createDeleteDNSAndStorage = functions.database.ref('/apps/{uid}/{appid}/name')
.onWrite(event => {
    // Only edit data when it is first created.
    const {uid, appid} = event.params;
    const name = event.data.val();
    const dbRef = admin.database().ref(`/apps/${uid}/${appid}`);

    if (event.data.previous.exists()) {
        console.log(`already exists ${uid}/${appid}`);
        return;
    }
    // Exit when the data is deleted.
    if (!event.data.exists()) {
        console.log(`data is being deleted ${uid}/${appid}`);
        return;
    }

    const url = `${name}.${zoneName}.com`;
    console.log(`data: ${uid}/${appid}/${name}\nsetting up: ${url}`);

    setupDNS({url, dbRef});
    setupStorage({url, dbRef});
    return;
});

function setupDNS({url, dbRef}) {

    // Create an NS record.
    let cnameRecord = zone.record('cname', {
        name: `${url}.`,
        data: 'c.storage.googleapis.com.',
        ttl: 3000
    });

    zone.addRecords(cnameRecord).then(function() {
        console.log(`done setting up zonerecord for ${url}`);
        dbRef.update({dns: url}).then(res => console.log(res)).catch(err => console.log(err));
    }).catch(function(err) {
        console.error(`error setting up zonerecord for ${url}`);
        console.error(err);
    });
}

function setupStorage({url, dbRef}) {
    console.log(`setting up storage bucket for ${url}`);

    gcs.createBucket(url, {
        website: {
            mainPageSuffix: `https://${url}`,
            notFoundPage: `https://${url}/404.html`
        }
    }).then(function(res) {
        let bucket = res[0];
        console.log(`created bucket ${url}, setting it as public`);
        dbRef.update({storage: url}).then(function() {
            console.log(`done setting up bucket for ${url}`);
        }).catch(function(err) {
            console.error(`db update for storage failed ${url}`);
            console.error(err);
        });
        bucket.makePublic().then(function() {
            console.log(`bucket set as public for ${url}`);
        }).catch(function(err) {
            console.error(`setting public for storage failed ${url}`);
            console.error(err);
        });
    }).catch(function(err) {
        console.error(`creating bucket failed ${url}`);
        console.error(err);
    });
}


问:
C++ map customize comparator
I defined a map to count the number of strings while sorting the strings by their length:

```<code>struct cmp {
    bool operator()(const string& a, const string& b) {
        return a.size() > b.size();
    }
};

int main() {
    map<string, int, cmp> mp;
    mp["aaa"] = 1;
    mp["bbb"] = 2;
    cout << mp["aaa"];
}
</code>```

I'm confused as the output is 2. How should I achieve my goal?

答:
Because of the way your comparator is defined, strings "aaa" and "bbb" are considered equal. Your map has one item, not two. First you assigned 1 to that item, then you assigned 2.

To solve the problem, define your comparator as follows:

```<code>struct cmp {
    bool operator()(const string& a, const string& b) {
        return a.size() == b.size() ? a > b : a.size() > b.size();
    }
};
</code>```

That way, the strings will be considered equal only if they actually are equal, not only when their sizes match, but the string length will still have priority for sorting.

Title: C++ map customize comparator

Body:
I defined a map to count the number of strings while sorting the strings by their length:

struct cmp {
    bool operator()(const string& a, const string& b) {
        return a.size() > b.size();
    }
};

int main() {
    map<string, int, cmp> mp;
    mp["aaa"] = 1;
    mp["bbb"] = 2;
    cout << mp["aaa"];
}

I'm confused as the output is 2. How should I achieve my goal?

Body:
Because of the way your comparator is defined, strings "aaa" and "bbb" are considered equal. Your map has one item, not two. First you assigned 1 to that item, then you assigned 2.

To solve the problem, define your comparator as follows:

struct cmp {
    bool operator()(const string& a, const string& b) {
        return a.size() == b.size() ? a > b : a.size() > b.size();
    }
};

That way, the strings will be considered equal only if they actually are equal, not only when their sizes match, but the string length will still have priority for sorting.


答:
In order to get the square of numbers in your list, you don't need the lambda expression. You should just do:

```<code>>>> [x**2 for x in ll]
[64, 16, 0, 16, 64]
</code>```

In your usage, it is not an error. You are seeing the reference to lambda functions in your list (because you are not calling the function). In order to make it work, you may do:

```<code>>>> ll = [-8, -4, 0, 4, 8]
>>> f = lambda x: x**2
>>> [f(x) for x in ll]
[64, 16, 0, 16, 64]
</code>```

which is equivalent to:

```<code>>>> [(lambda x: x**2)(x) for x in ll]
[64, 16, 0, 16, 64]
</code>```

Note: Lambda is not at all needed here

Title: lambda in list comprehension error

Body:
In order to get the square of numbers in your list, you don't need the lambda expression. You should just do:

>>> [x**2 for x in ll]
[64, 16, 0, 16, 64]

In your usage, it is not an error. You are seeing the reference to lambda functions in your list (because you are not calling the function). In order to make it work, you may do:

>>> ll = [-8, -4, 0, 4, 8]
>>> f = lambda x: x**2
>>> [f(x) for x in ll]
[64, 16, 0, 16, 64]

which is equivalent to:

>>> [(lambda x: x**2)(x) for x in ll]
[64, 16, 0, 16, 64]

Note: Lambda is not at all needed here


问:
Python: invalid syntax error while using es2csv
This is the query I am trying to use in order to connect to elasticsearch, which is in (172.21.150.230) in order to pull out information in a csv format:

es2csv  -u  http://xxx.xx.xxx.xxx:5601/ -f  _all    -d  doc -i  test2   -r  -q  '{"query": {"match": {"NAME": "xxx"}}}' -o  database.csv

However, I get SyntaxError: invalid syntax

Thanks

答:
Which version are you using?
This error raised when your json query is not valid or when you forget to add -r argument. </p>


问:
Convert sub-hourly data to hourly and round up time in R
I have a very big dataframe in R, containing weather data with the following format.

```<code>                 valid temp
    1 17/08/2014 00:20   14
    2 17/08/2014 00:50   14
    3 17/08/2014 01:20   13.5
    4 17/08/2014 01:50   13
    5 17/08/2014 02:20   12
    6 17/08/2014 02:50   10
</code>```

I would like to convert these sub-hourly data to hourly, like the following.

```<code>                    valid tmpc
    1 2014-08-17 00:00:00   14
    2 2014-08-17 01:00:00   13.75
    3 2014-08-17 02:00:00   12.5
</code>```

The class of df$valid is 'factor'. I have tried first converting them to Date through POSIXct, but it gives only NA values. I have also tried changing the system locale and still I get NAs.

答:
We can do this in base R by converting to POSIXlt, set the minute to 0, convert it back to POSIXct and aggregate to get the mean of 'temp'

```<code>df1$valid <- strptime(df1$valid, "%d/%m/%Y %H:%M")
df1$valid$min <- 0
df1$valid <- as.POSIXct(df1$valid)
aggregate(temp~valid, df1, FUN = mean)
</code>```

Body:
I have a very big dataframe in R, containing weather data with the following format.

                 valid temp
    1 17/08/2014 00:20   14
    2 17/08/2014 00:50   14
    3 17/08/2014 01:20   13.5
    4 17/08/2014 01:50   13
    5 17/08/2014 02:20   12
    6 17/08/2014 02:50   10

I would like to convert these sub-hourly data to hourly, like the following.

                    valid tmpc
    1 2014-08-17 00:00:00   14
    2 2014-08-17 01:00:00   13.75
    3 2014-08-17 02:00:00   12.5

The class of df$valid is 'factor'. I have tried first converting them to Date through POSIXct, but it gives only NA values. I have also tried changing the system locale and still I get NAs.

Body:
We can do this in base R by converting to POSIXlt, set the minute to 0, convert it back to POSIXct and aggregate to get the mean of 'temp'

df1$valid <- strptime(df1$valid, "%d/%m/%Y %H:%M")
df1$valid$min <- 0
df1$valid <- as.POSIXct(df1$valid)
aggregate(temp~valid, df1, FUN = mean)


问:
survey php mysql counter
I am working on a small php/mysql survey.
I have all my questions/answers/cateogries stored in a mysql db.
I also have my categories stored in an array in my php script.
categories array=("Person","A Mom","A Student","Somebody",etc)
each category have 4 questions and 4 answers.
there are 8 categories. a user answers the survey by moving from category 1, to the next category etc...

here is a sql query that i have hard coded the category 2, so that i can display the 4 questions that is associated with category 2:
select a., b. from category a, questions b where a.id = b.id and a.id='2'

my question is, i will like to make the number "2" dynamic. dynamic here means, when the user click on the "NEXT" button, i would like to the new sql query to be like this:

select a., b. from category a, questions b where a.id = b.id and a.id='3'

clicking on next button again goes to:
select a., b. from category a, questions b where a.id = b.id and a.id='4'
etc...

below is a code snippet:

```<code> <?php
    $categories = array ("Person","A Mom","A Student","Somebody");

    $sql="select a.*, b.* from category a, questions b where a.id = b.id and a.id='2'";
    $result=mysql_query($sql,$db_connection);
    if (!$result)
    {
   die('Error: ' . mysql_error());
    }
 ?>
  <tr>
    <td height="32" colspan="5" bgcolor="#ECA4DD"><b><?php echo $result['name'];?></b></td></tr>
  <tr>
  <tr>
    <td colspan="5" class="content_2"><?php echo $result['description'];?></td>
  </tr>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

     <?php
    while ($row = mysql_fetch_assoc($result))
    {

 ?>

   <tr>
    <td class="content_2"><?php echo "Question1"; ?></td>
    <td align="center" valign="middle"><input type="radio" name="q1" id="s1" value="<?php echo $row['q1']; ?>"/> Rare </td>
    <td align="center" valign="middle"><input type="radio" name="q1" id="s1" value="<?php echo $row['q1']; ?>"/> Sometimes</td>
    <td align="center" valign="middle"><input type="radio" name="q1" id="s1" value="<?php echo $row['q1']; ?>"/> True</td>
    <td align="center" valign="middle"><input type="radio" name="q1" id="s1" value="<?php echo $row['q1']; ?>"/> Always</td>
  </tr>
  <tr>
       <td height="108"></td>
       <td align="center" valign="middle"> </td>
       <td align="center" valign="middle"> </td>
       <td colspan="2" align="right" valign="middle"><input type="submit" name="save" value="NextButton"/>
       </td>
      </tr>

   <?php
   mysql_free_result($result);
   }
  ?>

 </form>
</code>```

答:
In your form you need to indicate either which step you're currently on or which the next step is.  This way you can increment it to move you through the form.

So, in your form, put in a hidden variable like this:

```<code><input type='hidden' name='thisCategoryID' value='2'>
</code>```

Then, in your PHP code, you can do this:

```<code>// If there was a category ID posted, set some variables and increment it to load the next section
if(isset($_POST['thisCategoryID]) && is_numeric($_POST['thisCategoryID']) {
    $currentCategoryID = $_POST['thisCategoryID'];
    $nextCategoryID = $currentCategoryID + 1;
} else {
    // There's something wrong with your input, show an appropriate error
}

// Now run your query with the updated Category ID
$sql="select a.*, b.* from category a, questions b where a.id = b.id and a.id='{$nextCategoryID}'";
$result=mysql_query($sql,$db_connection);
if (!$result) {
    die('Error: '.mysql_error());
}
</code>```

I could have done a little more to prevent against SQL injection in the above query, in this example I'm just making sure you have a numeric value.

Title: survey php mysql counter

Body:
I am working on a small php/mysql survey.
I have all my questions/answers/cateogries stored in a mysql db.
I also have my categories stored in an array in my php script.
categories array=("Person","A Mom","A Student","Somebody",etc)
each category have 4 questions and 4 answers.
there are 8 categories. a user answers the survey by moving from category 1, to the next category etc...

here is a sql query that i have hard coded the category 2, so that i can display the 4 questions that is associated with category 2:
select a., b. from category a, questions b where a.id = b.id and a.id='2'

my question is, i will like to make the number "2" dynamic. dynamic here means, when the user click on the "NEXT" button, i would like to the new sql query to be like this:

select a., b. from category a, questions b where a.id = b.id and a.id='3'

clicking on next button again goes to:
select a., b. from category a, questions b where a.id = b.id and a.id='4'
etc...

below is a code snippet:

 <?php
    $categories = array ("Person","A Mom","A Student","Somebody");

    $sql="select a.*, b.* from category a, questions b where a.id = b.id and a.id='2'";
    $result=mysql_query($sql,$db_connection);
    if (!$result)
    {
   die('Error: ' . mysql_error());
    }
 ?>

    <?php echo $result['name'];?>

    <?php echo $result['description'];?>

  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

     <?php
    while ($row = mysql_fetch_assoc($result))
    {

 ?>

    <?php echo "Question1"; ?>
    <input type="radio" name="q1" id="s1" value="<?php echo $row['q1']; ?>"/> Rare
    <input type="radio" name="q1" id="s1" value="<?php echo $row['q1']; ?>"/> Sometimes
    <input type="radio" name="q1" id="s1" value="<?php echo $row['q1']; ?>"/> True
    <input type="radio" name="q1" id="s1" value="<?php echo $row['q1']; ?>"/> Always

       <input type="submit" name="save" value="NextButton"/>

   <?php
   mysql_free_result($result);
   }
  ?>

 </form>

Body:
In your form you need to indicate either which step you're currently on or which the next step is.  This way you can increment it to move you through the form.

So, in your form, put in a hidden variable like this:

<input type='hidden' name='thisCategoryID' value='2'>

Then, in your PHP code, you can do this:

// If there was a category ID posted, set some variables and increment it to load the next section
if(isset($_POST['thisCategoryID]) && is_numeric($_POST['thisCategoryID']) {
    $currentCategoryID = $_POST['thisCategoryID'];
    $nextCategoryID = $currentCategoryID + 1;
} else {
    // There's something wrong with your input, show an appropriate error
}

// Now run your query with the updated Category ID
$sql="select a.*, b.* from category a, questions b where a.id = b.id and a.id='{$nextCategoryID}'";
$result=mysql_query($sql,$db_connection);
if (!$result) {
    die('Error: '.mysql_error());
}

I could have done a little more to prevent against SQL injection in the above query, in this example I'm just making sure you have a numeric value.


问:
What is the openssl -new option for?
If I create a selfsigned certificate I can omit or include the -new option with no obvious difference.
Assume I have a private key in the file privkey.pem.

```<code>openssl req -x509 -key privkey.pem -out selfcertnonew.pem

openssl req -new -x509 -key privkey.pem -out selfcertwithnew.pem
</code>```

What is the difference between the certificates in the files selfcertnonew.pem and selfcertwithnew.pem

答:
Looking at the openssl source code, the '-x509' option implies the '-new' option.

Reference:

https://github.com/openssl/openssl/blob/master/apps/req.c ... line 293.

Title: What is the openssl -new option for?

Body:
If I create a selfsigned certificate I can omit or include the -new option with no obvious difference.
Assume I have a private key in the file privkey.pem.

openssl req -x509 -key privkey.pem -out selfcertnonew.pem

openssl req -new -x509 -key privkey.pem -out selfcertwithnew.pem

What is the difference between the certificates in the files selfcertnonew.pem and selfcertwithnew.pem


问:
Regex in Python: How to match a word pattern, if not preceded by another word of variable length?
I would like reconstruct full names from photo captions using Regex in Python, by appending last name back to the first name in patterns "FirstName1 and FirstName2 LastName". We can rely on names starting with capital letter.

For example,

'John and Albert McDonald' becomes 'John McDonald' and 'Albert McDonald'

'Stephen Stewart, John and Albert Diamond' becomes 'John Diamond' and 'Albert Diamond'

I would need to avoid matching patterns like this: 'Jay Smith and Albert Diamond' and generate a non-existent name 'Smith Diamond'

The photo captions may or may not have more words before this pattern, for example, 'It was a great day hanging out with John and Stephen Diamond.'

This is the code I have so far:

```<code>s = 'John and Albert McDonald'
so = re.search('([A-Z][a-z\-]+)\sand\s([A-Z][a-z\-]+\s[A-Z][a-z\-]+(?:[A-Z][a-z]+)?)', s)
if so:
    print so.group(1) + ' ' + so.group(2).split()[1]
    print so.group(2)
</code>```

This returns 'John McDonald' and 'Albert McDonald', but 'Jay Smith and Albert Diamond' will result in a non-existent name 'Smith Diamond'.

An idea would be to check whether the pattern is preceded by a capitalized word, something like (?<![A-Z][a-z\-]+)\s([A-Z][a-z\-]+)\sand\s([A-Z][a-z\-]+\s[A-Z][a-z\-]+(?:[A-Z][a-z]+)?) but unfortunately negative lookbehind only works if we know the exact length of the preceding word, which I don't.

Could you please let me know how I can correct my regex epression? Or is there a better way to do what I want? Thanks!

答:
As you can rely on names starting with a capital letter, then you could do something like:

```<code>((?:[A-Z]\w+\s+)+)and\s+((?:[A-Z]\w+(?:\s+|\b))+)
</code>```

Live preview

Swapping out your current pattern, with this pattern should work with your current Python code. You do need to strip() the captured results though.

Which for your examples and current code would yield:

```<code>Input
First print
Second print

John and Albert McDonald
John McDonald
Albert McDonald

Stephen Stewart, John and Albert Diamond
John Diamond
Albert Diamond

It was a great day hanging out with John and Stephen Diamond.
John Diamond
Stephen Diamond
</code>```

Body:
I would like reconstruct full names from photo captions using Regex in Python, by appending last name back to the first name in patterns "FirstName1 and FirstName2 LastName". We can rely on names starting with capital letter.

For example,

'John and Albert McDonald' becomes 'John McDonald' and 'Albert McDonald'

'Stephen Stewart, John and Albert Diamond' becomes 'John Diamond' and 'Albert Diamond'

I would need to avoid matching patterns like this: 'Jay Smith and Albert Diamond' and generate a non-existent name 'Smith Diamond'

The photo captions may or may not have more words before this pattern, for example, 'It was a great day hanging out with John and Stephen Diamond.'

This is the code I have so far:

s = 'John and Albert McDonald'
so = re.search('([A-Z][a-z\-]+)\sand\s([A-Z][a-z\-]+\s[A-Z][a-z\-]+(?:[A-Z][a-z]+)?)', s)
if so:
    print so.group(1) + ' ' + so.group(2).split()[1]
    print so.group(2)

This returns 'John McDonald' and 'Albert McDonald', but 'Jay Smith and Albert Diamond' will result in a non-existent name 'Smith Diamond'.

An idea would be to check whether the pattern is preceded by a capitalized word, something like (?<![A-Z][a-z\-]+)\s([A-Z][a-z\-]+)\sand\s([A-Z][a-z\-]+\s[A-Z][a-z\-]+(?:[A-Z][a-z]+)?) but unfortunately negative lookbehind only works if we know the exact length of the preceding word, which I don't.

Could you please let me know how I can correct my regex epression? Or is there a better way to do what I want? Thanks!

Body:
As you can rely on names starting with a capital letter, then you could do something like:

((?:[A-Z]\w+\s+)+)and\s+((?:[A-Z]\w+(?:\s+|\b))+)

Live preview

Swapping out your current pattern, with this pattern should work with your current Python code. You do need to strip() the captured results though.

Which for your examples and current code would yield:

Input
First print
Second print

John and Albert McDonald
John McDonald
Albert McDonald

Stephen Stewart, John and Albert Diamond
John Diamond
Albert Diamond

It was a great day hanging out with John and Stephen Diamond.
John Diamond
Stephen Diamond


问:
PHP AJAX script not working properly on all conditions
I have a script where I want to process form data using ajax. The script is returning the success message but not the error message. Have a look at the scripts below.

AJAX Script

```<code>$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val()
        };
    $.ajax({
            type: "POST",
            dataType : "json",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#submit").hide();
                $("#loading").show();
                $(".message").hide();
      },
            success: function(json){
                setTimeout(function(){
                    $(".message").html(json.status).fadeIn();
                    $('#mywallet').html('$' + json.deduct);
                    $("#submit").show();
                    $("#loading").hide();
                },3000);
            }
        });
        return false;
    });
});
</code>```

PHP Script

```<code><?php
session_start();
include'config/db.php';
$msg = null;
$sessionid = (!empty($_SESSION['login']))?$_SESSION['login']:null;

$wp = $pdo->prepare("SELECT set_cointoss_wp, set_cointoss_prob FROM settings");
$wp-> execute();
$sp = $wp->fetch();
    $percent = $sp['set_cointoss_wp'];
    $probablity = $sp['set_cointoss_prob'];

$bal = $pdo->prepare("SELECT mb_acbal, mb_wallet FROM mem_balance WHERE mb_id = :mem");
$bal-> bindValue(':mem', $sessionid);
$bal-> execute();
$bf = $bal->fetch();
    $balance = $bf['mb_acbal'];
    $wallet = $bf['mb_wallet'];

$coin   = (!empty($_POST['flip']))?$_POST['flip']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;

if($_POST){
        if($wallet < $amount){
            $msg = "<div class='message-error'>Sorry buddy! You have insufficient balance. Please <a href=''>recharge</a> your wallet.</div>";
        }else{
            $deduct = $wallet-$amount;
            $prob = rand(1, 10);

            //set new wallet balance after bet amount deduction
            $stmt = $pdo->prepare("UPDATE mem_balance SET mb_wallet = :bal WHERE mb_user = :user");
            $stmt-> bindValue(':bal', $deduct);
            $stmt-> bindValue(':user', $sessionid);
            $stmt-> execute();

        if($coin == ''){
          $msg = "<div class='message-error'>Sorry buddy! Fields cannot be left empty.</div>";
        }else{
          if($coin == "head"){
                    if($prob <= $probablity){
                        $result = 1;
                    }else{
                      $result = 2;
                    }
            if($result == 1){
              // win
                        $wa = $amount*$percent;
                        $win_amount = $wa/100;
                        $final_cash = $win_amount+$balance;

                        // update database with winning amount
                        $stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
                        $stmt-> bindValue(':bal', $final_cash);
                        $stmt-> bindValue(':user', $sessionid);
                        $stmt-> execute();

              $msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
            }else{
              // loose
              $msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
            }
          }else{
                    if($prob <= $probablity){
                        $result = 2;
                    }else{
                      $result = 1;
                    }
            if($result == 1){
              // loose
              $msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
            }else{
              // win
                        $wa = $amount*$percent;
                        $win_amount = $wa/100;
                        $final_cash = $win_amount+$balance;

                        // update database with winning amount
                        $stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
                        $stmt-> bindValue(':bal', $final_cash);
                        $stmt-> bindValue(':user', $sessionid);
                        $stmt-> execute();

              $msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
            }
          }
        }
        }
        echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>
</code>```

Here in the scripts above, when if($wallet < $amount) condition is false and else condition is executed, the scripts works fine and returns
 as required. But, if if($wallet < $amount) condition is true then its not returning
 and the loading image keeps on moving (as if waiting for the response) but does not receives any response in return. I am stuck since a few days on this but not being able to find any solution for the same. Please help.

答:
I am not sure but I think in your php script $deduct has been declared inside the else block.

so when the script executes and if ($wallet < $amount) condition evaluates to true, then the else part is skipped and you directly return this:-

```<code>return  echo json_encode(array(
        'status' => $msg,
        'deduct' => $deduct
    ));
</code>```

so it might be the case that $deduct is not recognized. try executing by declaring the $deduct before the if block.

Body:
I have a script where I want to process form data using ajax. The script is returning the success message but not the error message. Have a look at the scripts below.

AJAX Script

$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val()
        };
    $.ajax({
            type: "POST",
            dataType : "json",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#submit").hide();
                $("#loading").show();
                $(".message").hide();
      },
            success: function(json){
                setTimeout(function(){
                    $(".message").html(json.status).fadeIn();
                    $('#mywallet').html('$' + json.deduct);
                    $("#submit").show();
                    $("#loading").hide();
                },3000);
            }
        });
        return false;
    });
});

PHP Script

<?php
session_start();
include'config/db.php';
$msg = null;
$sessionid = (!empty($_SESSION['login']))?$_SESSION['login']:null;

$wp = $pdo->prepare("SELECT set_cointoss_wp, set_cointoss_prob FROM settings");
$wp-> execute();
$sp = $wp->fetch();
    $percent = $sp['set_cointoss_wp'];
    $probablity = $sp['set_cointoss_prob'];

$bal = $pdo->prepare("SELECT mb_acbal, mb_wallet FROM mem_balance WHERE mb_id = :mem");
$bal-> bindValue(':mem', $sessionid);
$bal-> execute();
$bf = $bal->fetch();
    $balance = $bf['mb_acbal'];
    $wallet = $bf['mb_wallet'];

$coin   = (!empty($_POST['flip']))?$_POST['flip']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;

if($_POST){
        if($wallet < $amount){
            $msg = "
Sorry buddy! You have insufficient balance. Please recharge your wallet.
";
        }else{
            $deduct = $wallet-$amount;
            $prob = rand(1, 10);

            //set new wallet balance after bet amount deduction
            $stmt = $pdo->prepare("UPDATE mem_balance SET mb_wallet = :bal WHERE mb_user = :user");
            $stmt-> bindValue(':bal', $deduct);
            $stmt-> bindValue(':user', $sessionid);
            $stmt-> execute();

        if($coin == ''){
          $msg = "
Sorry buddy! Fields cannot be left empty.
";
        }else{
          if($coin == "head"){
                    if($prob <= $probablity){
                        $result = 1;
                    }else{
                      $result = 2;
                    }
            if($result == 1){
              // win
                        $wa = $amount*$percent;
                        $win_amount = $wa/100;
                        $final_cash = $win_amount+$balance;

                        // update database with winning amount
                        $stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
                        $stmt-> bindValue(':bal', $final_cash);
                        $stmt-> bindValue(':user', $sessionid);
                        $stmt-> execute();

              $msg = "
Congratulations buddy! You won... $".$win_amount." has been credited to your account.
";
            }else{
              // loose
              $msg = "
Sorry buddy! You lost... But do not loose hope. Try your luck again :)
";
            }
          }else{
                    if($prob <= $probablity){
                        $result = 2;
                    }else{
                      $result = 1;
                    }
            if($result == 1){
              // loose
              $msg = "
Sorry buddy! You lost... But do not loose hope. Try your luck again :)
";
            }else{
              // win
                        $wa = $amount*$percent;
                        $win_amount = $wa/100;
                        $final_cash = $win_amount+$balance;

                        // update database with winning amount
                        $stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
                        $stmt-> bindValue(':bal', $final_cash);
                        $stmt-> bindValue(':user', $sessionid);
                        $stmt-> execute();

              $msg = "
Congratulations buddy! You won... $".$win_amount." has been credited to your account.
";
            }
          }
        }
        }
        echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>

Here in the scripts above, when if($wallet < $amount) condition is false and else condition is executed, the scripts works fine and returns
 as required. But, if if($wallet < $amount) condition is true then its not returning
 and the loading image keeps on moving (as if waiting for the response) but does not receives any response in return. I am stuck since a few days on this but not being able to find any solution for the same. Please help.

Body:
I am not sure but I think in your php script $deduct has been declared inside the else block.

so when the script executes and if ($wallet < $amount) condition evaluates to true, then the else part is skipped and you directly return this:-

return  echo json_encode(array(
        'status' => $msg,
        'deduct' => $deduct
    ));

so it might be the case that $deduct is not recognized. try executing by declaring the $deduct before the if block.


问:
Implementing an AddAtIndex method in a LinkedList
currently, I am working on implementing an AddAtIndex method and for the most part it seems to be working fine. However, my method is not passing my JUnit test and I can't seem to understand why. Thus, I have chosen to show the code I have done thus far:

```<code>**
     * Add an element to the list at the specified index
     * @param The index where the element should be added
     * @param element The element to add
     */
    public void add(int index, E element ) //Method should be O(1) time.
    {
        // TODO: Implement this method
        if (index < 0) {
            System.out.println("Can't add an element at a negative index.");
        }
        int i = 0;
        LLNode<E> currentNode = head.next;
        while ( i < size ) {
            if ( i == index ) {
                LLNode<E> newNode = new LLNode<E>(element);
                LLNode<E> tempNode = new LLNode<E>(currentNode.data);

                currentNode.next = tempNode;
                currentNode.data = newNode.data;

                newNode.prev = currentNode.prev;
                newNode.next = tempNode;
                tempNode.prev = newNode;
                size++;
            }
            currentNode = currentNode.next;
            i++;
        }

    }
</code>```

My thought process behind the code is that the method creates a new Node, then it replaces the data at the specified index of the linked list. However, the data at the node it is replacing is stored in a temporary node which is incremented in position to the next node after the new node. I am about 80% confident in my implementation though the code looks a bit sloppy. I have created a driver to demonstrate the implementation. The drivers code is as follows:

```<code>public class LinkedListDriver {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyLinkedList<String> nameList = new MyLinkedList<String>();
        nameList.add("Hamadi");
        nameList.add("Ballo");
        nameList.add(1, "Salisu");
        nameList.add(2, "Galo");
        System.out.println(nameList.toString());
        System.out.println(nameList.size());
        nameList.set(2, "Abdullahi");
        System.out.println(nameList.toString());
        nameList.remove(1);
        System.out.println(nameList.toString());
        MyLinkedList<Integer> list1 = new MyLinkedList<Integer>();
        list1.add(65);
        list1.add(21);
        list1.add(42);
        System.out.println(list1.toString());
        list1.remove(0);
        System.out.println(list1.toString());
    }

}
</code>```

The Output from the driver is as follows:

```<code>List: Hamadi, Salisu, Galo, Ballo,
4
Replacing Galo with Abdullahi
List: Hamadi, Salisu, Abdullahi, Ballo,
Removing Salisu from the list
List: Hamadi, Abdullahi, Ballo,
List: 65, 21, 42,
Removing 65 from the list
List: 21, 42,
</code>```

The unit test fails however with the following error:

It fails at the AssertEquals method:

```<code>shortList.add(2, "E");
        shortList.add(3, "F");
        **assertEquals("AddAtIndex: at position 2 ", "E", shortList.get(2)); //fails here**
        assertEquals("AddAtIndex: at position 3 ", "F", shortList.get(3));
        assertEquals("AddAtIndex: List size is ", 6, shortList.size());
</code>```

I would like to know what I'm doing wrong. I have this literally completely figured out, though I know that there is something a bit off about my AddAtindex method. Thanks!

答:
I used head and tail as sentinel nodes. Created a new node to be added in the list.</p>

```<code>public boolean add(E element) {
        // create new element
        LLNode<E> variable = new LLNode(element);
        variable.next = null;
        variable.prev = null;

        // if element is null, throw exception
        if (element == null) {
            // return false;
            throw new NullPointerException("Element is null");
        } else {
            // get the value stored in tail.prev in variable temp.
            variable.prev = tail.prev;
            variable.next = tail;
            // now modify the tail node prev and new node next
            tail.prev = variable;

            // get prev node next link changed
            variable.prev.next = variable;

            // update size
            if (head.next.next != tail) {
                size++;
            }
            return true;
        }
    }
</code>```

Body:
currently, I am working on implementing an AddAtIndex method and for the most part it seems to be working fine. However, my method is not passing my JUnit test and I can't seem to understand why. Thus, I have chosen to show the code I have done thus far:

**
     * Add an element to the list at the specified index
     * @param The index where the element should be added
     * @param element The element to add
     */
    public void add(int index, E element ) //Method should be O(1) time.
    {
        // TODO: Implement this method
        if (index < 0) {
            System.out.println("Can't add an element at a negative index.");
        }
        int i = 0;
        LLNode<E> currentNode = head.next;
        while ( i < size ) {
            if ( i == index ) {
                LLNode<E> newNode = new LLNode<E>(element);
                LLNode<E> tempNode = new LLNode<E>(currentNode.data);

                currentNode.next = tempNode;
                currentNode.data = newNode.data;

                newNode.prev = currentNode.prev;
                newNode.next = tempNode;
                tempNode.prev = newNode;
                size++;
            }
            currentNode = currentNode.next;
            i++;
        }

    }

My thought process behind the code is that the method creates a new Node, then it replaces the data at the specified index of the linked list. However, the data at the node it is replacing is stored in a temporary node which is incremented in position to the next node after the new node. I am about 80% confident in my implementation though the code looks a bit sloppy. I have created a driver to demonstrate the implementation. The drivers code is as follows:

public class LinkedListDriver {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyLinkedList<String> nameList = new MyLinkedList<String>();
        nameList.add("Hamadi");
        nameList.add("Ballo");
        nameList.add(1, "Salisu");
        nameList.add(2, "Galo");
        System.out.println(nameList.toString());
        System.out.println(nameList.size());
        nameList.set(2, "Abdullahi");
        System.out.println(nameList.toString());
        nameList.remove(1);
        System.out.println(nameList.toString());
        MyLinkedList<Integer> list1 = new MyLinkedList<Integer>();
        list1.add(65);
        list1.add(21);
        list1.add(42);
        System.out.println(list1.toString());
        list1.remove(0);
        System.out.println(list1.toString());
    }

}

The Output from the driver is as follows:

List: Hamadi, Salisu, Galo, Ballo,
4
Replacing Galo with Abdullahi
List: Hamadi, Salisu, Abdullahi, Ballo,
Removing Salisu from the list
List: Hamadi, Abdullahi, Ballo,
List: 65, 21, 42,
Removing 65 from the list
List: 21, 42,

The unit test fails however with the following error:

It fails at the AssertEquals method:

shortList.add(2, "E");
        shortList.add(3, "F");
        **assertEquals("AddAtIndex: at position 2 ", "E", shortList.get(2)); //fails here**
        assertEquals("AddAtIndex: at position 3 ", "F", shortList.get(3));
        assertEquals("AddAtIndex: List size is ", 6, shortList.size());

I would like to know what I'm doing wrong. I have this literally completely figured out, though I know that there is something a bit off about my AddAtindex method. Thanks!

Body:
I used head and tail as sentinel nodes. Created a new node to be added in the list.

public boolean add(E element) {
        // create new element
        LLNode<E> variable = new LLNode(element);
        variable.next = null;
        variable.prev = null;

        // if element is null, throw exception
        if (element == null) {
            // return false;
            throw new NullPointerException("Element is null");
        } else {
            // get the value stored in tail.prev in variable temp.
            variable.prev = tail.prev;
            variable.next = tail;
            // now modify the tail node prev and new node next
            tail.prev = variable;

            // get prev node next link changed
            variable.prev.next = variable;

            // update size
            if (head.next.next != tail) {
                size++;
            }
            return true;
        }
    }


问:
Java: array initialize in shorthand cannot assign to an object
```<code>Integer i1 = 1;
Integer i2 = 2;

Number arr1[] = {i1, i2};
</code>```

as we already know, {i1, i2} is shorthand for new Number[]{i1, i2}

but when declare in this way:

```<code>Object o = {i1, i2};   //error
</code>```

I got a compile error:
Type mismatch: cannot convert from Integer[] to Object

On the other hand,

```<code>Object arr1 = new Number[]{i1, i2};
</code>```

Isn't it means, that the array can be convert to Object.

And if I write in this way:

```<code>Number arr2[] = {i1, i2};
Object obj = arr2;
</code>```

It's also okay.

So, the problem i want to consult is, why did I got the compile error.
Or the eclipse gave me an mistake error message ,for '{i1, i2}' in the expression 'Object o = {i1, i2};' is not an array?

答: Shorthand array initializers are only valid when initializing an array. Number arr1[] = {i1, i2}; declares and initializes an array of Number. Object o just declares a single object, not an array. You could write Object o = new Number[] { i1, i2 }; (e.g., not shorthand) and it would work.

Body:
Integer i1 = 1;
Integer i2 = 2;

Number arr1[] = {i1, i2};

as we already know, {i1, i2} is shorthand for new Number[]{i1, i2}

but when declare in this way:

Object o = {i1, i2};   //error

I got a compile error:
Type mismatch: cannot convert from Integer[] to Object

On the other hand,

Object arr1 = new Number[]{i1, i2};

Isn't it means, that the array can be convert to Object.

And if I write in this way:

Number arr2[] = {i1, i2};
Object obj = arr2;

It's also okay.

So, the problem i want to consult is, why did I got the compile error.
Or the eclipse gave me an mistake error message ,for '{i1, i2}' in the expression 'Object o = {i1, i2};' is not an array?


问:
Combine 2 lists in python such that elements at the corresponding index are together
I have two lists like:

```<code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
</code>```

I would like to combine them to get:

```<code>l = [1, 4, 2, 5, 3, 6]
</code>```

How can I do this without using loops?

答:
You can use itertools and zip:

Code:

```<code>import itertools as it
list(it.chain(*zip(listone, listtwo)))
</code>```

Test Code:

```<code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
print(list(it.chain(*zip(listone, listtwo))))
</code>```

Results:

```<code>[1, 4, 2, 5, 3, 6]
</code>```

Body:
I have two lists like:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

I would like to combine them to get:

l = [1, 4, 2, 5, 3, 6]

How can I do this without using loops?

Body:
You can use itertools and zip:

Code:

import itertools as it
list(it.chain(*zip(listone, listtwo)))

Test Code:

listone = [1, 2, 3]
listtwo = [4, 5, 6]
print(list(it.chain(*zip(listone, listtwo))))

Results:

[1, 4, 2, 5, 3, 6]


问:
Something wrong in c++ code
Please what wrong in this code:

```<code>#include <iostream>
#include <vector>

unsigned __int32 ConvertToChars(std::vector<int> container, char** pChars)
{
    *pChars = (char*)&container[0];

    return container.size() * sizeof(int);
}

void ConvertToIntegers(char* chars, short size, std::vector<int>& container)
{
    int count = size / sizeof(int);

    int* pIntegers = (int*)chars;

    for(int i=0; i < count; ++i)
    {
        container.push_back(*(pIntegers++));
    }
}

void Print(const std::vector<int>& container)
{
    for(int i=0; i < container.size(); ++i)
    {
        std::cout << container[i] << std::endl;
    }
}

void main()
{
    std::vector<int> vec1;

    vec1.push_back(1);
    vec1.push_back(2);
    vec1.push_back(3);

    char* buffer = 0;

    short bufferSize = ConvertToChars(vec1, &buffer);

    std::vector<int> vec2;

    ConvertToIntegers(buffer, bufferSize, vec2);

    Print(vec2);

    char c;

    std::cin >> c;
}
</code>```

function Print prints values:

-572662307

-842150451

-572662307

Thank you!!!

答: You're copying the container when you pass it to ConvertToChars, then taking a pointer to one of its elements, then seeing the copy go out of scope, which invalidates your pointer.

Title: Something wrong in c++ code

Body:
Please what wrong in this code:

#include <iostream>
#include <vector>

unsigned __int32 ConvertToChars(std::vector<int> container, char** pChars)
{
    *pChars = (char*)&container[0];

    return container.size() * sizeof(int);
}

void ConvertToIntegers(char* chars, short size, std::vector<int>& container)
{
    int count = size / sizeof(int);

    int* pIntegers = (int*)chars;

    for(int i=0; i < count; ++i)
    {
        container.push_back(*(pIntegers++));
    }
}

void Print(const std::vector<int>& container)
{
    for(int i=0; i < container.size(); ++i)
    {
        std::cout << container[i] << std::endl;
    }
}

void main()
{
    std::vector<int> vec1;

    vec1.push_back(1);
    vec1.push_back(2);
    vec1.push_back(3);

    char* buffer = 0;

    short bufferSize = ConvertToChars(vec1, &buffer);

    std::vector<int> vec2;

    ConvertToIntegers(buffer, bufferSize, vec2);

    Print(vec2);

    char c;

    std::cin >> c;
}

function Print prints values:

-572662307

-842150451

-572662307

Thank you!!!


问:
adding a before event to either an IDictionary or class
Is it possible to create an event before an item is added or updated to an IDictionary?

```<code>public static IDictionary<string, Aircraft> aircraftList = new Dictionary<string, Aircraft>();
</code>```

and I use it like this

```<code>MainForm.aircraftList[acNumber].FlightStatus = strFlying;
</code>```

What I want to do is not to update the value if the new value is null, empty string or an int == 0

Aircraft is a class with lots of values which are a mix of strings int's and doubles...

or is there a way of doing this type of action within the class?

currently I'm doing this everywhere I assign a value via an if statement, I assume there is a better way?

答:
I have to be honest with you, I'm a bit confused as to what you are requesting... However, I've noticed a couple of issues with your example code which could be causing the problem you're experiencing?

First off, IDictionary is a collection object interface, and yet you are treating it as an array, which to me is a tad suspicious.

Secondly, Aircraft is a class and yet you are not initialising it when setting a value to FlightStatus.

So what you should be doing is either:

```<code>aircraftList.Add(strKey, new Aircraft() {FlightStatus = strFlying});
</code>```

or

```<code>Aircraft ac = new Aircraft();

// set the ac values
ac.FlightStatus = strFlying;

aircraftList.Add(strKey, ac);
</code>```

You can add conditional statement before adding the object to the dictionary.

Finally, what do you mean when asking about adding a before event? If you follow dotNET's example you could add your own OnBeforeEvent method/Invoke() within Add() method declaration.

Body:
Is it possible to create an event before an item is added or updated to an IDictionary?

public static IDictionary<string, Aircraft> aircraftList = new Dictionary<string, Aircraft>();

and I use it like this

MainForm.aircraftList[acNumber].FlightStatus = strFlying;

What I want to do is not to update the value if the new value is null, empty string or an int == 0

Aircraft is a class with lots of values which are a mix of strings int's and doubles...

or is there a way of doing this type of action within the class?

currently I'm doing this everywhere I assign a value via an if statement, I assume there is a better way?

Body:
I have to be honest with you, I'm a bit confused as to what you are requesting... However, I've noticed a couple of issues with your example code which could be causing the problem you're experiencing?

First off, IDictionary is a collection object interface, and yet you are treating it as an array, which to me is a tad suspicious.

Secondly, Aircraft is a class and yet you are not initialising it when setting a value to FlightStatus.

So what you should be doing is either:

aircraftList.Add(strKey, new Aircraft() {FlightStatus = strFlying});

or

Aircraft ac = new Aircraft();

// set the ac values
ac.FlightStatus = strFlying;

aircraftList.Add(strKey, ac);

You can add conditional statement before adding the object to the dictionary.

Finally, what do you mean when asking about adding a before event? If you follow dotNET's example you could add your own OnBeforeEvent method/Invoke() within Add() method declaration.


问:
Make background-page visible in Google Chrome extension
I have a background-page in my Google Chrome extension, and this page is naturally invisible. Is there anyway to make this hidden page visible, say in a popup when a browser action icon is clicked? Then hide it again with another click.

答:
In your extensions' popup page, add a piece of JS that utilities chrome.runtime.getBackgroundPage(callback). Give the  element of your background page an id, and use window.getElementById("myBackgroundPageHTMLElementId")

For Example, your callback could look like this:

```<code>document.getElementById("myPopupHTMLElementId").outerHTML = backgroundWindow.getElementById("myBackgroundPageHTMLElementId").outerHTML
</code>```

After this JS script completes, the HTML element of your popup page will be ENTIRELY replaced with the background page (until you reload it)! This means all attributes, even on the HTML element are set to the background page's version.

Hope this helps!

Body:
In your extensions' popup page, add a piece of JS that utilities chrome.runtime.getBackgroundPage(callback). Give the <html> element of your background page an id, and use window.getElementById("myBackgroundPageHTMLElementId")

For Example, your callback could look like this:

document.getElementById("myPopupHTMLElementId").outerHTML = backgroundWindow.getElementById("myBackgroundPageHTMLElementId").outerHTML

After this JS script completes, the HTML element of your popup page will be ENTIRELY replaced with the background page (until you reload it)! This means all attributes, even on the HTML element are set to the background page's version.

Hope this helps!


问:
Compression to Improve Hard Disk Write Performance
On a modern system can local hard disk write speeds be improved by compressing the output stream?

This question derives from a case I'm working with where a program serially generates and dumps around 1-2GB of text logging data to a raw text file on the hard disk and I think it is IO bound. Would I expect to be able to decrease runtimes by compressing the data before it goes to disk or would the overhead of compression eat up any gain I could get? Would having an idle second core affect this?

I know this would be affected by how much CPU is being used to generate the data so rules of thumb on how much idle CPU time would be needed would be good.

I recall a video talk where someone used compression to improve read speeds for a database but IIRC compressing is a lot more CPU intensive than decompressing.

答:
CPUs have grown faster at a faster rate than hard drive access. Even back in the 80's a many compressed files could be read off the disk and uncompressed in less time than it took to read the original (uncompressed) file.  That will not have changed.

Generally though, these days the compression/de-compression is handled at a lower level than you would be writing, for example in a database I/O layer.

As to the usefulness of a second core only counts if the system will be also doing a significant number of other things - and your program would have to be multi-threaded to take advantage of the additional CPU.

OwnerDisplayName: BCS

LastEditorDisplayName: BCS

OwnerDisplayName: Topbit


问:
cycling star-field animation
I made this star-field animation in javascript. I'm just not sure the best way to make it cycle the same animation from the other side. I like to get the stars to scroll across from one side of the canvas to the other.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x += stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas"></canvas></code>```

答:
To reverse

```<code>stars[i].x -= stars[i].v;
</code>```

You could loop forever and when i==1999, multiply v with -1 and set i to 0 again

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x -= stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas"></canvas></code>```

Title: cycling star-field animation

Body:
I made this star-field animation in javascript. I'm just not sure the best way to make it cycle the same animation from the other side. I like to get the stars to scroll across from one side of the canvas to the other.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x += stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();

<canvas id="myCanvas"></canvas>

Body:
To reverse

stars[i].x -= stars[i].v;

You could loop forever and when i==1999, multiply v with -1 and set i to 0 again

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x -= stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();

<canvas id="myCanvas"></canvas>


问:
bootstrap disabling collapse/toggleable on navbar
How can I make my navbar not collapse/toggle when the window is resized? I tried adding

```<code>.collapse{
   display: inline-block;
 }
</code>```

to my css. With this, when the window is resized, the nav bar elements end up stacking. I'm also using bootstrap 4 alpha 6

here's my code for the navbar: http://www.bootply.com/mHeWTUSxAM

答:
```<code>how i did it is by giving .btn.btn-navbar{display:none;}
and by giving .nav-collapse{height:auto}
it worked like this but i believe it is not best solution
referenced to bootstrap 4 documentation you should look into that "Responsive behaviors
</code>```

Navbars can utilize .navbar-toggler, .navbar-collapse, and .navbar-toggleable-* classes to change when their content collapses behind a button. In combination with other utilities, you can easily choose when to show or hide particular elements."

Body:
How can I make my navbar not collapse/toggle when the window is resized? I tried adding

.collapse{
   display: inline-block;
 }

to my css. With this, when the window is resized, the nav bar elements end up stacking. I'm also using bootstrap 4 alpha 6

here's my code for the navbar: http://www.bootply.com/mHeWTUSxAM

Body:
how i did it is by giving .btn.btn-navbar{display:none;}
and by giving .nav-collapse{height:auto}
it worked like this but i believe it is not best solution
referenced to bootstrap 4 documentation you should look into that "Responsive behaviors

Navbars can utilize .navbar-toggler, .navbar-collapse, and .navbar-toggleable-* classes to change when their content collapses behind a button. In combination with other utilities, you can easily choose when to show or hide particular elements."


问:
Get Array of Input fields values and append itinto the associated textarea
I have some input field dynamically generated inside form. I am trying to read the value of hidden input and append to to the end of text area

```<code>   .<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="VAlue 1 value 123" />
    <textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area 1 or 1 </textarea>

    <input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="VAlue value 123" />
    <textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">test desc</textarea>
</code>```

and Here is the js  code, but it's not working,

```<code>var values = [];

$("input[name='formtype[loans][][description]']").each(function() {
    values.push($(this).val());
});
alert(values);
</code>```

答:
Your selector "input[name='formtype[loans][][description]']" won't match any elements, because the [] in the middle will not match to the [0] or [1] (etc.) in the middle of the actual element name attributes.

For the HTML shown you could use the attribute starts with selector [name^=value]:

```<code>$('input[name^="formtype[loans]"]').each(function() {
</code>```

If each textarea will always immediately follow its associated hidden input then within the .each() loop that iterates over the inputs you can say $(this).next() to get the textarea.

If the textareas might be elsewhere in the DOM then you could find them by selecting by the name attribute based on the name of the current input:

```<code>$('textarea[name="' + this.name.replace("comment", "description") + '"')
</code>```

Demonstrated in context:

$('input[name^="formtype[loans]"]').each(function() {
  var val = this.value
  // add input's value to end of associated textarea's existing value:
  $('textarea[name="' + this.name.replace("comment", "description") + '"')
    .val(function(i, v) { return v + ' ' + val })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="Hidden value 0" />
<textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area A</textarea>

<input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="Hidden value 1" />
<textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">Text Area B</textarea></code>```

If you want to simply replace the textarea's current value rather than adding to the end of it then you can simplify the above to:

```<code>$('input[name^="formtype[loans]"]').each(function() {
  $('textarea[name="' + this.name.replace("comment", "description") + '"')
    .val(this.value)
})
</code>```

Body:
I have some input field dynamically generated inside form. I am trying to read the value of hidden input and append to to the end of text area

   .<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="VAlue 1 value 123" />
    <textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area 1 or 1 </textarea>

    <input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="VAlue value 123" />
    <textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">test desc</textarea>

and Here is the js  code, but it's not working,

var values = [];

$("input[name='formtype[loans][][description]']").each(function() {
    values.push($(this).val());
});
alert(values);

Body:
Your selector "input[name='formtype[loans][][description]']" won't match any elements, because the [] in the middle will not match to the [0] or [1] (etc.) in the middle of the actual element name attributes.

For the HTML shown you could use the attribute starts with selector [name^=value]:

$('input[name^="formtype[loans]"]').each(function() {

If each textarea will always immediately follow its associated hidden input then within the .each() loop that iterates over the inputs you can say $(this).next() to get the textarea.

If the textareas might be elsewhere in the DOM then you could find them by selecting by the name attribute based on the name of the current input:

$('textarea[name="' + this.name.replace("comment", "description") + '"')

Demonstrated in context:

$('input[name^="formtype[loans]"]').each(function() {
  var val = this.value
  // add input's value to end of associated textarea's existing value:
  $('textarea[name="' + this.name.replace("comment", "description") + '"')
    .val(function(i, v) { return v + ' ' + val })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="Hidden value 0" />
<textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area A</textarea>

<input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="Hidden value 1" />
<textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">Text Area B</textarea>

If you want to simply replace the textarea's current value rather than adding to the end of it then you can simplify the above to:

$('input[name^="formtype[loans]"]').each(function() {
  $('textarea[name="' + this.name.replace("comment", "description") + '"')
    .val(this.value)
})


问:
How to represent translation and scaling as a matrix?
I'm trying to implement the normalized 8-point algorithm to estimate the fundamental matrix. One step is to normalize the points such that they have center (0,0) and mean distance of sqrt(2). I know how to translate and scale the points to do so, but how do I represent the steps as a matrix to use at a later step?

My current function transforms the points as below, but I also need to figure out what the transformation matrix is:

```<code>%% Normalize points to have center (0,0) and mean distance sqrt(2)
function [pts1, T] = normalizePoints(pts)
    Xs = pts(:,1);
    Ys = pts(:,2);

    %% Compute old center and translate
    Xc = mean(Xs);
    Yc = mean(Ys);
    Xs = Xs - Xc;
    Ys = Ys - Yc;

    %% Compute mean distance and scale
    Ds = sqrt(Xs .^ 2 + Ys .^ 2);
    meanD = mean(Ds);
    scale = sqrt(2) / meanD;

    pts1 = [Xs .* scale, Ys .* scale];
    T = ... % How do I represent the previous operations as T?
end
</code>```

答:
use Homogeneous coordinates:

```<code>T = [3;5];
% Normalize points to have center (0,0) and mean distance sqrt(2)
pts = rand(10,2);
Xs = pts(:,1);
Ys = pts(:,2);

% Compute old center and translate
Xc = mean(Xs);
Yc = mean(Ys);
Xs = Xs - Xc;
Ys = Ys - Yc;

% Compute mean distance and scale
Ds = sqrt(Xs .^ 2 + Ys .^ 2);
meanD = mean(Ds);
scale = sqrt(2) / meanD;

% composing transformation matrix
H = eye(3);
H([1,5]) = H([1,5])*scale;
H(1:2,3) = T(:);
% making homogenous coordinates (add ones as z values)
ptsHomo = [pts';ones(1,size(pts,1))];
% apply transform
ptsRes = H*ptsHomo;
ptsRes = bsxfun(@rdivide,ptsRes(1:2,:),ptsRes(3,:))';

subplot(121);
plot(pts(:,1),pts(:,2),'o');
title('original points')

subplot(122);
plot(ptsRes(:,1),ptsRes(:,2),'o');
title('transformed points')
</code>```

Body:
I'm trying to implement the normalized 8-point algorithm to estimate the fundamental matrix. One step is to normalize the points such that they have center (0,0) and mean distance of sqrt(2). I know how to translate and scale the points to do so, but how do I represent the steps as a matrix to use at a later step?

My current function transforms the points as below, but I also need to figure out what the transformation matrix is:

%% Normalize points to have center (0,0) and mean distance sqrt(2)
function [pts1, T] = normalizePoints(pts)
    Xs = pts(:,1);
    Ys = pts(:,2);

    %% Compute old center and translate
    Xc = mean(Xs);
    Yc = mean(Ys);
    Xs = Xs - Xc;
    Ys = Ys - Yc;

    %% Compute mean distance and scale
    Ds = sqrt(Xs .^ 2 + Ys .^ 2);
    meanD = mean(Ds);
    scale = sqrt(2) / meanD;

    pts1 = [Xs .* scale, Ys .* scale];
    T = ... % How do I represent the previous operations as T?
end

Body:
use Homogeneous coordinates:

T = [3;5];
% Normalize points to have center (0,0) and mean distance sqrt(2)
pts = rand(10,2);
Xs = pts(:,1);
Ys = pts(:,2);

% Compute old center and translate
Xc = mean(Xs);
Yc = mean(Ys);
Xs = Xs - Xc;
Ys = Ys - Yc;

% Compute mean distance and scale
Ds = sqrt(Xs .^ 2 + Ys .^ 2);
meanD = mean(Ds);
scale = sqrt(2) / meanD;

% composing transformation matrix
H = eye(3);
H([1,5]) = H([1,5])*scale;
H(1:2,3) = T(:);
% making homogenous coordinates (add ones as z values)
ptsHomo = [pts';ones(1,size(pts,1))];
% apply transform
ptsRes = H*ptsHomo;
ptsRes = bsxfun(@rdivide,ptsRes(1:2,:),ptsRes(3,:))';

subplot(121);
plot(pts(:,1),pts(:,2),'o');
title('original points')

subplot(122);
plot(ptsRes(:,1),ptsRes(:,2),'o');
title('transformed points')


问:
ionic2 InAppBrowser (Ionic native) loaderror not working
If there is a network connection but if internet is not working . example There is a wifi connection but wifi doesn't have internet connection than the browser observable should fire "loaderror" event.

Code:

```<code>import { Component } from '@angular/core';
import { Platform,AlertController,LoadingController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Network } from '@ionic-native/network';
import { HomePage } from '../pages/home/home';
import { InAppBrowser } from '@ionic-native/in-app-browser';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  public rootPage:any = HomePage;

  constructor(private platform: Platform,private statusBar: StatusBar,private splashScreen: SplashScreen, private network: Network, private alertCtrl: AlertController, private iab: InAppBrowser, private loadingCtrl: LoadingController) {

platform.ready().then(() => {
  // Okay, so the platform is ready and our plugins are available.
  // Here you can do any higher level native things you might need.

   let alert = this.alertCtrl.create({
            title: "Network Problem",
            subTitle: 'Internet is not connected' ,
            buttons: [
                {
                    text: 'Close', handler: () => {
                        this.platform.exitApp();
                    }
                }
            ]
        });
        const loading = this.loadingCtrl.create();
        if(this.network.type !== 'none') {
            loading.present();
            const browser = this.iab.create('http://www.google.com','_blank','location=no,clearsessioncache=yes');
            browser.on("loaderror").subscribe(() => {
                loading.dismiss();
                this.iab.create('http://192.168.2.222/users/dashboard','_blank','location=no,clearsesioncache=yes');
            });
            const sub = browser.on('loadstart').subscribe(() => {
                loading.dismiss();
                sub.unsubscribe();
            },
                err => { loading.dismiss(); console.log('error') ; alert.present()},
                () => { loading.dismiss(); console.log('success') });
        }

        /// check connectivity automatically .

        let connectSubscription = network.onConnect().subscribe(() => {
                loading.present();
                const browser = this.iab.create('http://www.google.com','_blank','location=no,clearsesioncache=yes');
                browser.on("loaderror").subscribe(() => {
                    loading.dismiss();
                    this.iab.create('http://192.168.2.222/users/dashboard','_blank','location=no,clearsesioncache=yes');
                });
        });
        let disconnectSubscription = network.onDisconnect().subscribe(() => {
                const browser = this.iab.create("error.html",'_blank','location=no');
        });

    statusBar.styleDefault();
    splashScreen.hide();
    });
 }
}
</code>```

But it always load google page, even after the clearsessioncache and internet disconnection it always get loaded. I tested this both on android and Desktop.

答:
You can try as shown below.

Note: Hence it has a certain delay you have to use loader as shown below.

```<code> goToWebPage() {
    const loading = this.loadingCtrl.create();//use loader
    loading.present();
    const browser = this.iab.create('http://www.google.com');
    const sub = browser.on('loadstart').subscribe(() => {
       loading.dismiss();
       sub.unsubscribe();
    },
      err => {  loading.dismiss();console.log('error'); },
      () => { loading.dismiss();console.log('success') });
  }
</code>```

Body:
If there is a network connection but if internet is not working . example There is a wifi connection but wifi doesn't have internet connection than the browser observable should fire "loaderror" event.

Code:

import { Component } from '@angular/core';
import { Platform,AlertController,LoadingController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Network } from '@ionic-native/network';
import { HomePage } from '../pages/home/home';
import { InAppBrowser } from '@ionic-native/in-app-browser';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  public rootPage:any = HomePage;

  constructor(private platform: Platform,private statusBar: StatusBar,private splashScreen: SplashScreen, private network: Network, private alertCtrl: AlertController, private iab: InAppBrowser, private loadingCtrl: LoadingController) {

platform.ready().then(() => {
  // Okay, so the platform is ready and our plugins are available.
  // Here you can do any higher level native things you might need.

   let alert = this.alertCtrl.create({
            title: "Network Problem",
            subTitle: 'Internet is not connected' ,
            buttons: [
                {
                    text: 'Close', handler: () => {
                        this.platform.exitApp();
                    }
                }
            ]
        });
        const loading = this.loadingCtrl.create();
        if(this.network.type !== 'none') {
            loading.present();
            const browser = this.iab.create('http://www.google.com','_blank','location=no,clearsessioncache=yes');
            browser.on("loaderror").subscribe(() => {
                loading.dismiss();
                this.iab.create('http://192.168.2.222/users/dashboard','_blank','location=no,clearsesioncache=yes');
            });
            const sub = browser.on('loadstart').subscribe(() => {
                loading.dismiss();
                sub.unsubscribe();
            },
                err => { loading.dismiss(); console.log('error') ; alert.present()},
                () => { loading.dismiss(); console.log('success') });
        }

        /// check connectivity automatically .

        let connectSubscription = network.onConnect().subscribe(() => {
                loading.present();
                const browser = this.iab.create('http://www.google.com','_blank','location=no,clearsesioncache=yes');
                browser.on("loaderror").subscribe(() => {
                    loading.dismiss();
                    this.iab.create('http://192.168.2.222/users/dashboard','_blank','location=no,clearsesioncache=yes');
                });
        });
        let disconnectSubscription = network.onDisconnect().subscribe(() => {
                const browser = this.iab.create("error.html",'_blank','location=no');
        });

    statusBar.styleDefault();
    splashScreen.hide();
    });
 }
}

But it always load google page, even after the clearsessioncache and internet disconnection it always get loaded. I tested this both on android and Desktop.

Body:
You can try as shown below.

Note: Hence it has a certain delay you have to use loader as shown below.

 goToWebPage() {
    const loading = this.loadingCtrl.create();//use loader
    loading.present();
    const browser = this.iab.create('http://www.google.com');
    const sub = browser.on('loadstart').subscribe(() => {
       loading.dismiss();
       sub.unsubscribe();
    },
      err => {  loading.dismiss();console.log('error'); },
      () => { loading.dismiss();console.log('success') });
  }


问:
lambda in list comprehension error
I am doing the following:

```<code>ll = [-8, -4, 0, 4, 8]
[lambda x: x**2 for x in ll]
</code>```

and getting following error:

```<code>[<function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>]
</code>```

What could be the problem? I know desired result can be achieved by below code but I want to understand why lambda is not working in list comprehension?

```<code>[x**2 for x in ll]
</code>```

答:
You forgot to invoke the lambda.  Here's a way to do it in line:

```<code>ll = [-8, -4, 0, 4, 8]
print([(lambda x: x**2)(x) for x in ll])
</code>```

Title: lambda in list comprehension error

Body:
I am doing the following:

ll = [-8, -4, 0, 4, 8]
[lambda x: x**2 for x in ll]

and getting following error:

[<function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>,
 <function __main__.<listcomp>.<lambda>>]

What could be the problem? I know desired result can be achieved by below code but I want to understand why lambda is not working in list comprehension?

[x**2 for x in ll]

Body:
You forgot to invoke the lambda.  Here's a way to do it in line:

ll = [-8, -4, 0, 4, 8]
print([(lambda x: x**2)(x) for x in ll])


问:
Create subdomain in microsoft azure
I want to create a sub-domain in Microsoft Azure cloud account where i can put a blog for my website.

For example if my domain is example.com where i have hosted by main website file but i want to create a sub-domain like blog.example.com where i can put a blog for my website.

What i have tried so is like this. I have created 2 different app resource . i have hosted my main website content in one app in other i have put my blog file code.

I can access my main website but can't access the blog by using blog.example.com. I have tried to use the custom sub-domain but it not working.

答:
You'll also need to add a CNAME record pointing to your blog app's default domain name.

Then navigate to your app service via the Azure portal, and add your subdomain as the app's hostname.

Title: Create subdomain in microsoft azure


问:
order a row by column name of other data frame and match in length
For example you have this data frame :

```<code>dd <- data.frame(b = c("cpg1", "cpg2", "cpg3", "cpg4"),
                  x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
                 z = c(1, 1, 1, 2))
dd
     b x y z
1 cpg1 A 8 1
2 cpg2 D 3 1
3 cpg3 A 9 1
4 cpg4 C 9 2
</code>```

I want to order the column names (b,x,y,z) by a row in another data frame which is:

```<code>d <- data.frame(pos = c("x", "z", "b"),
                 g = c("A", "D", "A"), h = c(8, 3, 9))
d
  pos g h
1   x A 8
2   z D 3
3   b A 9
</code>```

So I want to order the column name of dd with the row d$pos and dd also needs to have the same number in the row d$pos.

I tried with order and match but it did not give me the need result. My dataset is quite large, so something automtic would be ideal.

Thanks a lot for your help!

答:
We can do a match and then order the columns

```<code>i1 <- match(d$pos, names(dd), nomatch = 0)
dd[i1]
#  x z    b
#1 A 1 cpg1
#2 D 1 cpg2
#3 A 1 cpg3
#4 C 2 cpg4
</code>```

Or if we want only the columns based on the 'd$pos'

```<code>dd[as.character(d$pos)]
#  x z    b
#1 A 1 cpg1
#2 D 1 cpg2
#3 A 1 cpg3
#4 C 2 cpg4
</code>```

Body:
For example you have this data frame :

dd <- data.frame(b = c("cpg1", "cpg2", "cpg3", "cpg4"),
                  x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
                 z = c(1, 1, 1, 2))
dd
     b x y z
1 cpg1 A 8 1
2 cpg2 D 3 1
3 cpg3 A 9 1
4 cpg4 C 9 2

I want to order the column names (b,x,y,z) by a row in another data frame which is:

d <- data.frame(pos = c("x", "z", "b"),
                 g = c("A", "D", "A"), h = c(8, 3, 9))
d
  pos g h
1   x A 8
2   z D 3
3   b A 9

So I want to order the column name of dd with the row d$pos and dd also needs to have the same number in the row d$pos.

I tried with order and match but it did not give me the need result. My dataset is quite large, so something automtic would be ideal.

Thanks a lot for your help!

Body:
We can do a match and then order the columns

i1 <- match(d$pos, names(dd), nomatch = 0)
dd[i1]
#  x z    b
#1 A 1 cpg1
#2 D 1 cpg2
#3 A 1 cpg3
#4 C 2 cpg4

Or if we want only the columns based on the 'd$pos'

dd[as.character(d$pos)]
#  x z    b
#1 A 1 cpg1
#2 D 1 cpg2
#3 A 1 cpg3
#4 C 2 cpg4


问:
Why text input field disappearing (html , php)?
------------code 1 ------------

```<code><!DOCTYPE html>
<html>
<body>
    <form action="#" method="POST">
        <input type ="text" value="default text" name="someName">
        <input type ="submit" value ="Submit" >
    </form>
    <?php echo "Entered data is -->".$_POST["someName"]; ?>
</body>
</html>
</code>```

----------------- code 2 ------------------

```<code><?php
echo $htmlDoc = <<< HTML
<html>
<body>
    <input type="button" value="Add Input Field"  onClick="addField();">
    <p id="addHere"></p>
</body>
</html>
HTML;

echo ' Entered Data is as :  '.$_POST["someName"];
?>
<script>
    function addField()
    {
        document.getElementById("addHere").innerHTML
        ='<form action="#" method="POST">'+
         '<input type ="text" value="default text" name="someName">'+
         '<input type ="submit" value ="Submit" >'+
         '</form>';
   }
</script>
</code>```

code1 works fine
but in code2 after submit text input field disappears why? how to retain it and retain value entered in it?

答:
that's because your form is not by default part of your DOM document.

you are appending your form using Javascript into your DOM document using a specific event onClick="addField();".

and while Form Submission is a process that sends a POST/GET data to the server -Server Side Process- then the server return back with some data -refreshes the page-, so all your DOM changes will be forgotten or restarted so to speak after this submit .

So, to work around this, you may set your form as a part of your DOM document, and control the viability by javascript.

Body:
------------code 1 ------------

<!DOCTYPE html>

    <form action="#" method="POST">
        <input type ="text" value="default text" name="someName">
        <input type ="submit" value ="Submit" >
    </form>
    <?php echo "Entered data is -->".$_POST["someName"]; ?>

----------------- code 2 ------------------

<?php
echo $htmlDoc = <<< HTML

    <input type="button" value="Add Input Field"  onClick="addField();">

HTML;

echo ' Entered Data is as :  '.$_POST["someName"];
?>

code1 works fine
but in code2 after submit text input field disappears why? how to retain it and retain value entered in it?