问:
Combine my two MySQL queries
This is erp.orders:

```<code>userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01
</code>```

This is prod.referral_order_delivered

```<code>user_id
1
2
1
1
1
</code>```

I need to combine two requests.

This request :

```<code>SELECT DISTINCT
    erp.orders.userid, COUNT(erp.orders.userid) as countorders
FROM
    erp.orders
WHERE
    erp.orders.userid IN (SELECT erp.orders.userid
                          FROM erp.orders, prod.referral_order_delivered
                          WHERE erp.orders.userid = prod.referral_order_delivered.user_id
                            AND erp.orders.paidat::date >= '2017-06-07'
                            AND erp.orders.paidat::date <= '2017-07-07')
GROUP BY
    erp.orders.userid;
</code>```

This returns this result:

```<code>userId  countorders
1           2
2           4
</code>```

And this request:

```<code>SELECT
    prod.referral_order_delivered.user_id,
    COUNT(prod.referral_order_delivered.user_id) AS countreferral
FROM
    prod.referral_order_delivered
WHERE
    prod.referral_order_delivered.user_id IN (SELECT DISTINCT erp.orders.userid
                                              FROM erp.orders
                                              INNER JOIN prod.referral_order_delivered ON erp.orders.userid = prod.referral_order_delivered.user_id
                                              WHERE erp.orders.paidat >= '2017-06-07'
                                                AND erp.orders.paidat <= '2017-07-07')
GROUP BY
    prod.referral_order_delivered.user_id
</code>```

which returns this result:

```<code>user_id    countreferral
1          4
2          1
</code>```

Now I want to combine these requests to get this result:

```<code>userId  countorders countreferral
1       2           4
2       4           1
</code>```

Note that user_id and userId is the same thing. So it doesn't matter if this is user_id or userId which appears.

You can test the solution here.

答:
Consider joining the two aggregate queries as derived tables. First, convert the IN clause queries (both of which are equivalent with former using implicit join and latter with explicit join) to JOIN clauses. Then, run same aggregations with outer query joining both and selecting columns.

```<code>SELECT agg1.userid, agg1.countorders, agg2.countreferral
FROM
   (SELECT j.userid, COUNT(j.userid) as countorders
    FROM
        (SELECT DISTINCT erp.orders.userid
         FROM erp.orders
         INNER JOIN prod.referral_order_delivered
             ON erp.orders.userid = prod.referral_order_delivered.user_id
         WHERE erp.orders.paidat >= '2017-06-07'
           AND erp.orders.paidat <= '2017-07-07') j

    INNER JOIN erp.orders e ON j.userid = e.userid
    GROUP BY j.userid) agg1

INNER JOIN
   (SELECT j.userid, COUNT(j.userid) as countreferral
    FROM
        (SELECT DISTINCT erp.orders.userid
         FROM erp.orders
         INNER JOIN prod.referral_order_delivered
             ON erp.orders.userid = prod.referral_order_delivered.user_id
         WHERE erp.orders.paidat >= '2017-06-07'
           AND erp.orders.paidat <= '2017-07-07') j

    INNER JOIN prod.referral_order_delivered p ON j.userid = p.user_id
    GROUP BY j.userid) agg2

ON agg1.userid = agg2.userid
</code>```

Even save the nested inner query used in the source of both aggregates as a view.

```<code>SELECT agg1.userid, agg1.countorders, agg2.countreferral
FROM
   (SELECT v.userid, COUNT(j.userid) as countorders
    FROM myview v
    INNER JOIN erp.orders e ON v.userid = e.userid
    GROUP BY v.userid) agg1

INNER JOIN
   (SELECT v.userid, COUNT(j.userid) as countreferral
    FROM myview v
    INNER JOIN prod.referral_order_delivered p ON v.userid = p.user_id
    GROUP BY v.userid) agg2

ON agg1.userid = agg2.userid
</code>```

In other RDBMS's like Postgres unlike MySQL you could use CTE's WITH() to avoid repetition. See rextester demo forked from your initial setup.

Title: Combine my two MySQL queries

Body:
This is erp.orders:

userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01

This is prod.referral_order_delivered

user_id
1
2
1
1
1

I need to combine two requests.

This request :

SELECT DISTINCT
    erp.orders.userid, COUNT(erp.orders.userid) as countorders
FROM
    erp.orders
WHERE
    erp.orders.userid IN (SELECT erp.orders.userid
                          FROM erp.orders, prod.referral_order_delivered
                          WHERE erp.orders.userid = prod.referral_order_delivered.user_id
                            AND erp.orders.paidat::date >= '2017-06-07'
                            AND erp.orders.paidat::date <= '2017-07-07')
GROUP BY
    erp.orders.userid;

This returns this result:

userId  countorders
1           2
2           4

And this request:

SELECT
    prod.referral_order_delivered.user_id,
    COUNT(prod.referral_order_delivered.user_id) AS countreferral
FROM
    prod.referral_order_delivered
WHERE
    prod.referral_order_delivered.user_id IN (SELECT DISTINCT erp.orders.userid
                                              FROM erp.orders
                                              INNER JOIN prod.referral_order_delivered ON erp.orders.userid = prod.referral_order_delivered.user_id
                                              WHERE erp.orders.paidat >= '2017-06-07'
                                                AND erp.orders.paidat <= '2017-07-07')
GROUP BY
    prod.referral_order_delivered.user_id

which returns this result:

user_id    countreferral
1          4
2          1

Now I want to combine these requests to get this result:

userId  countorders countreferral
1       2           4
2       4           1

Note that user_id and userId is the same thing. So it doesn't matter if this is user_id or userId which appears.

You can test the solution here.

Body:
Consider joining the two aggregate queries as derived tables. First, convert the IN clause queries (both of which are equivalent with former using implicit join and latter with explicit join) to JOIN clauses. Then, run same aggregations with outer query joining both and selecting columns.

SELECT agg1.userid, agg1.countorders, agg2.countreferral
FROM
   (SELECT j.userid, COUNT(j.userid) as countorders
    FROM
        (SELECT DISTINCT erp.orders.userid
         FROM erp.orders
         INNER JOIN prod.referral_order_delivered
             ON erp.orders.userid = prod.referral_order_delivered.user_id
         WHERE erp.orders.paidat >= '2017-06-07'
           AND erp.orders.paidat <= '2017-07-07') j

    INNER JOIN erp.orders e ON j.userid = e.userid
    GROUP BY j.userid) agg1

INNER JOIN
   (SELECT j.userid, COUNT(j.userid) as countreferral
    FROM
        (SELECT DISTINCT erp.orders.userid
         FROM erp.orders
         INNER JOIN prod.referral_order_delivered
             ON erp.orders.userid = prod.referral_order_delivered.user_id
         WHERE erp.orders.paidat >= '2017-06-07'
           AND erp.orders.paidat <= '2017-07-07') j

    INNER JOIN prod.referral_order_delivered p ON j.userid = p.user_id
    GROUP BY j.userid) agg2

ON agg1.userid = agg2.userid

Even save the nested inner query used in the source of both aggregates as a view.

SELECT agg1.userid, agg1.countorders, agg2.countreferral
FROM
   (SELECT v.userid, COUNT(j.userid) as countorders
    FROM myview v
    INNER JOIN erp.orders e ON v.userid = e.userid
    GROUP BY v.userid) agg1

INNER JOIN
   (SELECT v.userid, COUNT(j.userid) as countreferral
    FROM myview v
    INNER JOIN prod.referral_order_delivered p ON v.userid = p.user_id
    GROUP BY v.userid) agg2

ON agg1.userid = agg2.userid

In other RDBMS's like Postgres unlike MySQL you could use CTE's WITH() to avoid repetition. See rextester demo forked from your initial setup.


来源: stackexchange

问:
csv empty strings handling and values appending
With a csv of ~50 rows (stars) and ~30 columns (name, magnitudes and distance), that has some empty string values (''), I am trying to do two things in which all the help so far hasn't been useful. (1) I need to parse empty strings as 0.0, so I can (2) append each row in a list of lists (what I called s).

In other words:
- s is a list of stars (each one has all its parameters)
- d is a particular parameter for all the stars (distance), which I obtain correctly.

Big issue is with s. My try:

```<code>with open('stars.csv', 'r') as mycsv:
    csv_stars = csv.reader(mycsv)
    next(csv_stars) #skip header
    stars = list(csv_stars)
    s = [] # star
    d = [] # distances
    for row in stars:
        row[row==''] = '0'
        s.append(float(row)) #stars
        d.append(arcsec*AU*float(row[30]))
</code>```

I can't think of a better syntax, and so I get the error

s.append(float(row)) # stars
  TypeError: float() argument must be a string or a number

From s I would obtain later the magnitudes for all the stars, separately. But first things first...

答:
@cwasdwa Please look at below code. it will give you an idea. I am sure there might be better way. This solution is based on what I have understood from your code.</p>

```<code>with open('stars.csv', 'r') as mycsv:
csv_stars = csv.reader(mycsv)
next(csv_stars) #skip header
stars = list(csv_stars)
s = [] # star
d = [] # distances
for row in stars:
    newRow = [] #create new row array to convert all '' to 0.0
    for x in row:
        if x =='':
            newRow.append(0.0)
        else:
            newRow.append(x)
    s.append(newRow) #stars

    if row[30] == '':
        value = 0.0
    else:
        value = row[30]
    d.append(arcsec*AU*float(value))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
With a csv of ~50 rows (stars) and ~30 columns (name, magnitudes and distance), that has some empty string values (''), I am trying to do two things in which all the help so far hasn't been useful. (1) I need to parse empty strings as 0.0, so I can (2) append each row in a list of lists (what I called s).

In other words:
- s is a list of stars (each one has all its parameters)
- d is a particular parameter for all the stars (distance), which I obtain correctly.

Big issue is with s. My try:

with open('stars.csv', 'r') as mycsv:
    csv_stars = csv.reader(mycsv)
    next(csv_stars) #skip header
    stars = list(csv_stars)
    s = [] # star
    d = [] # distances
    for row in stars:
        row[row==''] = '0'
        s.append(float(row)) #stars
        d.append(arcsec*AU*float(row[30]))

I can't think of a better syntax, and so I get the error

s.append(float(row)) # stars
  TypeError: float() argument must be a string or a number

From s I would obtain later the magnitudes for all the stars, separately. But first things first...

Body:
@cwasdwa Please look at below code. it will give you an idea. I am sure there might be better way. This solution is based on what I have understood from your code.

with open('stars.csv', 'r') as mycsv:
csv_stars = csv.reader(mycsv)
next(csv_stars) #skip header
stars = list(csv_stars)
s = [] # star
d = [] # distances
for row in stars:
    newRow = [] #create new row array to convert all '' to 0.0
    for x in row:
        if x =='':
            newRow.append(0.0)
        else:
            newRow.append(x)
    s.append(newRow) #stars

    if row[30] == '':
        value = 0.0
    else:
        value = row[30]
    d.append(arcsec*AU*float(value))


问:
Retrieving JSON Values Not Working - JavaScript/jQuery
Below is the code that I am using to retrieve a certain font name from the API (which contains a list of fonts available).

The problem is that I am only able to retrieve the first 20 values. By changing the 19 to any number after that, the family value is not retrieved.

```<code>$.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=***", function(result){
        $.each(result, function(i, field){
           $("div").append([field][0][19]['family']);
        });
    });
</code>```

Here is an example fiddle:

https://jsfiddle.net/tLhea2eo/2/

答:
All the fonts are in the array result.items which has length of 82

$.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=***", function(result) {

  $.each(result.items, function(i, item) {
    $("ul").append('
' + item.family + '
');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul></code>```

Body:
Below is the code that I am using to retrieve a certain font name from the API (which contains a list of fonts available).

The problem is that I am only able to retrieve the first 20 values. By changing the 19 to any number after that, the family value is not retrieved.

$.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=***", function(result){
        $.each(result, function(i, field){
           $("div").append([field][0][19]['family']);
        });
    });

Here is an example fiddle:

https://jsfiddle.net/tLhea2eo/2/

Body:
All the fonts are in the array result.items which has length of 82

$.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=***", function(result) {

  $.each(result.items, function(i, item) {
    $("ul").append('<li>' + item.family + '</li>');
  });
});

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


问:
Passing two php variables to another page from a link
Ok so I'm building a simple question/answer site and this is a loop that outputs all the questions asked previously in link form.  I'm trying to concat two variables to the next page url so I can get them and work with them there but it will only allow one?  I've tried everything but not working?  See the only comment section of my code for the crux of the issue.  Thank you.</p>

```<code><?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;

$conn = mysqli_connect($servername, $username, $password, $dbname,
$port);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'> Log out </a><br>
<a href='ask.php'> Ask a question</a><br>
<br />
<br />";

echo "Answer another users question: <br><br />";

$sql = "SELECT q_id,question, username FROM questions";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

while($row = mysqli_fetch_array($result))
{

$q_id = $row['q_id'];
$question = $row['question'];
$username = $row['username'];

//right here I need to add(concat) the second variable $username
//I need to get both on the next page url but not allowing me to

echo ('<a href="totalqs.php?q_id=' . $q_id .'   " >' . $question .
'</a>'  . '<br>');
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>
</code>```

答:
Get requests can pass multiple variables for example: {host}?var1=val1&var2=val2&var2=val3

You could echo out a link with a get request in it:

```<code>echo ('<a href="totalqs.php?q_id=' . $q_id .'&username='. $username .'" >' . $question .'</a>'  . '<br>');
</code>```

And then, you could use $_GET to retrieve these vars in totalqs.php. Like:

```<code>$_GET['username']
</code>```

would give you the value of the username.

Body:
Ok so I'm building a simple question/answer site and this is a loop that outputs all the questions asked previously in link form.  I'm trying to concat two variables to the next page url so I can get them and work with them there but it will only allow one?  I've tried everything but not working?  See the only comment section of my code for the crux of the issue.  Thank you.

<?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;

$conn = mysqli_connect($servername, $username, $password, $dbname,
$port);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo " Log out

 Ask a question

";

echo "Answer another users question:

";

$sql = "SELECT q_id,question, username FROM questions";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

while($row = mysqli_fetch_array($result))
{

$q_id = $row['q_id'];
$question = $row['question'];
$username = $row['username'];

//right here I need to add(concat) the second variable $username
//I need to get both on the next page url but not allowing me to

echo ('' . $question .
''  . '
');
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

Body:
Get requests can pass multiple variables for example: {host}?var1=val1&var2=val2&var2=val3

You could echo out a link with a get request in it:

echo ('<a href="totalqs.php?q_id=' . $q_id .'&username='. $username .'" >' . $question .'</a>'  . '<br>');

And then, you could use $_GET to retrieve these vars in totalqs.php. Like:

$_GET['username']

would give you the value of the username.


问:
Meteor app , If we add a new cordova plugin , do we have to resubmit the app or will meter hotcode push take care of it?
So our app is already submitted and approved in apple and google play stores , I have a need to launch app from a link and thinking of using url scheme cordova plugin to launch the app from a link ,question is if I add this cordova plugin and build the app , do i need to resubmit the app to the stores or will the hot code push take care of this ?From my understanding , any new cordova plugin requires a new app build and submission to the app stores . If this is the case , then users will have to upgrade the app in their devices which i want to avoid at the present stage.

Appreciate all your answers.
Thanks

答:
Indeed, any change in Cordova plugins (actually anything that is not simply loaded like a web page) will require an update in the app and play store.

Hot Code Push can only handle JS, HTML, CSS and assets in the public folder. This is also a constraint from the App Store policy, which allows bypassing a new approval only for what is processed by JavaScript Core.


问:
Linq query to select only common items in two lists
I have to lists:

```<code>Dim ListA as List (of MyClass)
Dim ListB as List (of MyClass)
</code>```

MyClass includes fields A, B , C, D

I want to derive a list that includes only common items based on comparison only of field A.   .Intersect returns 0 count list even when there are common records (probably because MyClass doesn't implement compare method).  Also, Is there a way to do this in VB.Net?

答:
Consider using Linq Join on the common properties</p>

```<code>Dim ListA As List (Of SomeClass)
Dim ListB As List (Of SomeClass)
'...
'Assuming both lists are initialized and populated
Dim ListC As List (Of SomeClass) = (From itemA In ListA
                                    Join itemB In ListB
                                    On itemA.A Equals itemB.A
                                    Select itemA).ToList()
</code>```

Body:
I have to lists:

Dim ListA as List (of MyClass)
Dim ListB as List (of MyClass)

MyClass includes fields A, B , C, D

I want to derive a list that includes only common items based on comparison only of field A.   .Intersect returns 0 count list even when there are common records (probably because MyClass doesn't implement compare method).  Also, Is there a way to do this in VB.Net?

Body:
Consider using Linq Join on the common properties

Dim ListA As List (Of SomeClass)
Dim ListB As List (Of SomeClass)
'...
'Assuming both lists are initialized and populated
Dim ListC As List (Of SomeClass) = (From itemA In ListA
                                    Join itemB In ListB
                                    On itemA.A Equals itemB.A
                                    Select itemA).ToList()


答:
It looks like you're doing HTTP GET so instead of trying to concat 2 strings, why not just have something like

```<code>totalqs.php?q_id=$q_id&question=$question&username=$username
</code>```

Then in the totalqs.php, you'll do something like

```<code>$q_id = $_GET['q_id'];
$question = $_GET['question'];
$username = $_GET['username'];
</code>```

This is assuming you have access to totalqs.php.

Title: Passing two php variables to another page from a link

Body:
It looks like you're doing HTTP GET so instead of trying to concat 2 strings, why not just have something like

totalqs.php?q_id=$q_id&question=$question&username=$username

Then in the totalqs.php, you'll do something like

$q_id = $_GET['q_id'];
$question = $_GET['question'];
$username = $_GET['username'];

This is assuming you have access to totalqs.php.


答:
You can send to variables by adding the & and then continuing to add values.

Example

```<code>example.php?one=value&second=value
</code>```

In your case

```<code>totalqs.php?q_id=$q_id&username=$username
</code>```

Body:
You can send to variables by adding the & and then continuing to add values.

Example

example.php?one=value&second=value

In your case

totalqs.php?q_id=$q_id&username=$username


问:
Custom infoWindow Google Maps IOS
I customized a infoWindow, but this shows a infowindow default in the background. Is there a way to hide the infoWindow background? or that I'm doing wrong.

The code is:

```<code>func mapView(mapView: GMSMapView!, markerInfoContents marker: GMSMarker!) -> UIView! {
        if let infoView = UIView.viewFromNibName("MarkerInfoView") as? MarkerInfoView {
            infoView.lblTitle.text =  "Title" //marker.title
            infoView.lblDescription.text = "Description"
            infoView.lblDescription.numberOfLines = 0
            infoView.lblDescription.lineBreakMode = NSLineBreakMode.ByWordWrapping
            infoView.lblDescription.sizeToFit()
            return infoView
        } else {
            return nil
        }
    }
</code>```

答: in your nib file, where you do custom look for your info window, set top nib view background color to clear color

Title: Custom infoWindow Google Maps IOS

Body:
I customized a infoWindow, but this shows a infowindow default in the background. Is there a way to hide the infoWindow background? or that I'm doing wrong.

The code is:

func mapView(mapView: GMSMapView!, markerInfoContents marker: GMSMarker!) -> UIView! {
        if let infoView = UIView.viewFromNibName("MarkerInfoView") as? MarkerInfoView {
            infoView.lblTitle.text =  "Title" //marker.title
            infoView.lblDescription.text = "Description"
            infoView.lblDescription.numberOfLines = 0
            infoView.lblDescription.lineBreakMode = NSLineBreakMode.ByWordWrapping
            infoView.lblDescription.sizeToFit()
            return infoView
        } else {
            return nil
        }
    }


问:
Delphi how to do SearchReplace in a component property in all the files of a project?
I need to do a SearchReplace in all my forms (all the dfm) for changing all the occurences of ':' to ';' in all the TQuery.Strings (of type TStrings).

How can I accomplish this? I'd like to do it at desing time: I would like that my dfm contain ";", not do a runtime substitution.

答: Try e.g. CnPack, what is huge set of useful addons. In this pack it's called Property Corrector.</p>

ContentLicense: CC BY-SA 2.5


问:
Why can a Rust struct be defined without a semicolon?
I'm learning Rust and the chapter for structs gives an example of a struct without a ; at the end. It compiles but I have no idea why this is allowed.

```<code>fn main() {
    struct User {
        username: String,
        email: String,
        sign_in_count: u64,
        active: bool,
    }
}
</code>```

... same question goes for functions, actually.

答:
As Shepmaster said in the comment, the "reason" is that Rust defines so. Here I will explain the rules behind it.

Basically you can omit ; when it ends with }. This will answer your question.

However, there are a number of exceptions to the rule:

When {} appears indirectly

The rule above doesn't apply when {} appears indirectly, like

```<code>use std::io::{self, Read, Write}; // Here }; appears
</code>```

or

```<code>let x = if cond {
    1
} else {
    2
}; // Here }; appears
</code>```

In this case, {} isn't a direct part of use/let. So in this case you need ;.

Items

Items are things which you can also place outside of functions. That is, one of extern crate, use, mod, struct, enum, union, type, trait, impl, fn, static, const, extern, and macros.

You can place items either outside of functions or in a function. However, There is a difference between them:

If it appears outside of functions, you have to omit ; when unnecessary.

If it appears in a function, you can also place ; there. This is basically because the ; itself is an empty statement.

Example:

```<code>struct A {} // You can't place ; here
fn main() {
    struct B {} // You can omit ; here
    struct C {}; // You can also place ; here
}
</code>```

The last expression

You have to omit ; if

It is the last statement in the block,

it is an expression (items and let aren't expressions), and

you want to return the value from the expression.

Example:

```<code>fn f() -> i32 {
    let x = 1;
    x + x // You want to return x + x, so you can't place `;` here
}
</code>```

Block expressions

if, if let, match, loop, while, while let, for, unsafe, and bare {} ends with }, so you can omit ; after them. However, there is a slight effect if you place ; here.

Example:

```<code>fn f(x: i32) -> i32 {
    if x < 10 {
        10
    } else {
        20
    }; // If you remove ; here, then you will see a compile error.
    42
}
</code>```

In most cases, you don't have to place ; here; instead you may have to place ; in the blocks.

```<code>fn f(x: i32) -> i32 {
    if x < 10 {
        10;
    } else {
        20;
    }
    42
}
</code>```

Statement macros

In statement positions, you can write three different kinds of macros:

some_macro!()/some_macro![]: this isn't in fact a statement macro; instead, this is a mere expression macro. It can't expand to items or let.

some_macro!{}: this expands to zero or more statements.

some_macro!();/some_macro![];/some_macro!{};: this also expands to zero or more statements; however, there is a very minor difference: ; is added to the last expanded statement.

Body:
I'm learning Rust and the chapter for structs gives an example of a struct without a ; at the end. It compiles but I have no idea why this is allowed.

fn main() {
    struct User {
        username: String,
        email: String,
        sign_in_count: u64,
        active: bool,
    }
}

... same question goes for functions, actually.

Body:
As Shepmaster said in the comment, the "reason" is that Rust defines so. Here I will explain the rules behind it.

Basically you can omit ; when it ends with }. This will answer your question.

However, there are a number of exceptions to the rule:

When {} appears indirectly

The rule above doesn't apply when {} appears indirectly, like

use std::io::{self, Read, Write}; // Here }; appears

or

let x = if cond {
    1
} else {
    2
}; // Here }; appears

In this case, {} isn't a direct part of use/let. So in this case you need ;.

Items

Items are things which you can also place outside of functions. That is, one of extern crate, use, mod, struct, enum, union, type, trait, impl, fn, static, const, extern, and macros.

You can place items either outside of functions or in a function. However, There is a difference between them:

If it appears outside of functions, you have to omit ; when unnecessary.

If it appears in a function, you can also place ; there. This is basically because the ; itself is an empty statement.

Example:

struct A {} // You can't place ; here
fn main() {
    struct B {} // You can omit ; here
    struct C {}; // You can also place ; here
}

The last expression

You have to omit ; if

It is the last statement in the block,

it is an expression (items and let aren't expressions), and

you want to return the value from the expression.

Example:

fn f() -> i32 {
    let x = 1;
    x + x // You want to return x + x, so you can't place `;` here
}

Block expressions

if, if let, match, loop, while, while let, for, unsafe, and bare {} ends with }, so you can omit ; after them. However, there is a slight effect if you place ; here.

Example:

fn f(x: i32) -> i32 {
    if x < 10 {
        10
    } else {
        20
    }; // If you remove ; here, then you will see a compile error.
    42
}

In most cases, you don't have to place ; here; instead you may have to place ; in the blocks.

fn f(x: i32) -> i32 {
    if x < 10 {
        10;
    } else {
        20;
    }
    42
}

Statement macros

In statement positions, you can write three different kinds of macros:

some_macro!()/some_macro![]: this isn't in fact a statement macro; instead, this is a mere expression macro. It can't expand to items or let.

some_macro!{}: this expands to zero or more statements.

some_macro!();/some_macro![];/some_macro!{};: this also expands to zero or more statements; however, there is a very minor difference: ; is added to the last expanded statement.


问:
Measuring the blocking part of Garbage Collection time
Java's garbage collector (GC) does not always stop the main thread. It may block all threads, or just run in parallel without pausing the other threads.

I can measure the total garbage collection time either by using
 garbageCollectorMXBean.getCollectionTime(); at the end of the program, or by running the VM with -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -verbose:gc.

However, I want to measure the portion of GCs during which the main thread is blocked (i.e. paused), so that I can measure the exact time that the main thread has been running. Is it possible to measure it?

答: Use -XX:+PrintGCApplicationStoppedTime and/or -XX:+PrintGCApplicationConcurrentTime


问:
Do executables built with CodeBlocks + GCC run on any Windows?
When building with Visual C++, I noticed that a simple executable helloworld.exe (displaying a WinAPI MessageBox) can be shipped to any computer using Windows XP, Vista, 7, 8, 10, and will run without any third-party dll or redistribuable packages.

Now that I'm moving to CodeBlocks + GCC, will the same be true? i.e. will a simple executable displaying a WinAPI MessageBox be able to run on all Win XP, Vista, 7, 8, 10 without any other packages needed, specific to GCC ?

答:
A way I have used before to make sure everything was linked properly, is to statically link by passing the -static flag when compiling.
in g++ that would be like this: g++ hello.cpp -o hello.exe -static.
That should take care of it. This way you only need the binary without the libstdc++6.dll. So if you can pass linker flags in code::blocks do it.


问:
d3 v4 - have value on left side of single horizontal bar chart
below is the code for a horizontal bar chart in its current form. I would like to move the value to the left side of the bar chart. I tried .attr("text-anchor", "start") but it didn't work. Any help is appreciated, and hopefully you can provide some comments to help explain some of the principles in formatting labels/values. Thanks!

```<code>var data = [{
    "xAxis": "72.1"
    }];
    var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 80
    },
    width = 500 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;
    var y = d3.scaleBand()
    .range([height, 0])
    .padding(0.4);
    var x = d3.scaleLinear()
    .range([0, width])
    .domain([0, 100]);
    var svg = d3.select(".barChartContainer").append("svg")
    .attr("width", 500)
    .attr("height", 200)
    .append("g")
    .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");
    y.domain(data.map(function(d) {
    return d.yAxis;
    }));
    var backgroundBar = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    .attr("class", "barBackground")
    .attr("y", function(d) {
    return y(d.yAxis);
    })
    .attr("height", y.bandwidth())
    .attr("width", function(d) {
    return x(100);
    });
    var bar = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    .attr("class", "bar")
    .attr("y", function(d) {
    return y(d.yAxis);
    })
    .attr("width", function(d) {
    return x(d.xAxis);
    });
    var labels = svg.selectAll(null)
    .data(data)
    .enter()
    .append("text")
    var values = svg.selectAll(null)
    .data(data)
    .enter()
    .append("text")
    .attr("y", function(d) {
    return y(d.yAxis) + y.bandwidth() / 2;
    })
    .attr("x", 10)
    .text(function(d) {
    return +d.xAxis
    })
    .attr("x", function(d) {
    return x(d.xAxis) + 10;
    });
</code>```

Current bar chart

What I would like

答:
Change the last line:

```<code>.attr("x", function(d) {
        return x(d.xAxis) + 10;
        });
</code>```

And replace with:

```<code>.attr("x", x(-10));
</code>```

Body:
below is the code for a horizontal bar chart in its current form. I would like to move the value to the left side of the bar chart. I tried .attr("text-anchor", "start") but it didn't work. Any help is appreciated, and hopefully you can provide some comments to help explain some of the principles in formatting labels/values. Thanks!

var data = [{
    "xAxis": "72.1"
    }];
    var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 80
    },
    width = 500 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;
    var y = d3.scaleBand()
    .range([height, 0])
    .padding(0.4);
    var x = d3.scaleLinear()
    .range([0, width])
    .domain([0, 100]);
    var svg = d3.select(".barChartContainer").append("svg")
    .attr("width", 500)
    .attr("height", 200)
    .append("g")
    .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");
    y.domain(data.map(function(d) {
    return d.yAxis;
    }));
    var backgroundBar = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    .attr("class", "barBackground")
    .attr("y", function(d) {
    return y(d.yAxis);
    })
    .attr("height", y.bandwidth())
    .attr("width", function(d) {
    return x(100);
    });
    var bar = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    .attr("class", "bar")
    .attr("y", function(d) {
    return y(d.yAxis);
    })
    .attr("width", function(d) {
    return x(d.xAxis);
    });
    var labels = svg.selectAll(null)
    .data(data)
    .enter()
    .append("text")
    var values = svg.selectAll(null)
    .data(data)
    .enter()
    .append("text")
    .attr("y", function(d) {
    return y(d.yAxis) + y.bandwidth() / 2;
    })
    .attr("x", 10)
    .text(function(d) {
    return +d.xAxis
    })
    .attr("x", function(d) {
    return x(d.xAxis) + 10;
    });

Current bar chart

What I would like

Body:
Change the last line:

.attr("x", function(d) {
        return x(d.xAxis) + 10;
        });

And replace with:

.attr("x", x(-10));


问:
How do I create a nested dictionary under a key that is yet to exist?
I have an empty array.

I want to assign a value like this: array[key][subkey] = 'value'

This produces a KeyError as array[key] does not exist yet.

What do I do? I tried the following...

```<code>array['key'] = None
array['key']['subkey'] = 'value'
</code>```

TypeError: 'NoneType' object does not support item assignment

I tried:

```<code>array['key'] = []
array['key']['subkey'] = 'value'
</code>```

TypeError: list indices must be integers, not str

I tried:

```<code>array['key'] = ['subkey']
array['key']['subkey'] = 'value'
</code>```

TypeError: list indices must be integers, not str

So what do I do?

答:
You could use a nested defaultdict like this, goes arbitrarily deep automatically:

```<code>>>> from collections import defaultdict
>>> def ndd():
        return defaultdict(ndd)

>>> array = ndd()
>>> array['key']['subkey']['subsubkey'] = 'value'
>>> array
defaultdict(<function ndd at 0x041AC270>,
            {'key': defaultdict(<function ndd at 0x041AC270>,
                                {'subkey': defaultdict(<function ndd at 0x041AC270>,
                                                       {'subsubkey': 'value'})})})
</code>```

(I indented the output for readability.)

Originally saw that from severb.

Body:
I have an empty array.

I want to assign a value like this: array[key][subkey] = 'value'

This produces a KeyError as array[key] does not exist yet.

What do I do? I tried the following...

array['key'] = None
array['key']['subkey'] = 'value'

TypeError: 'NoneType' object does not support item assignment

I tried:

array['key'] = []
array['key']['subkey'] = 'value'

TypeError: list indices must be integers, not str

I tried:

array['key'] = ['subkey']
array['key']['subkey'] = 'value'

TypeError: list indices must be integers, not str

So what do I do?

Body:
You could use a nested defaultdict like this, goes arbitrarily deep automatically:

>>> from collections import defaultdict
>>> def ndd():
        return defaultdict(ndd)

>>> array = ndd()
>>> array['key']['subkey']['subsubkey'] = 'value'
>>> array
defaultdict(<function ndd at 0x041AC270>,
            {'key': defaultdict(<function ndd at 0x041AC270>,
                                {'subkey': defaultdict(<function ndd at 0x041AC270>,
                                                       {'subsubkey': 'value'})})})

(I indented the output for readability.)

Originally saw that from severb.


问:
Marshalling two similar json fields to the same java field
I have a sample dummy JSON response that looks like :

```<code>    {
        "id": 1,
        "teacher_name": "Foo",
        "teacher_address": "123 Main St.",
        "teacher_phone_num": 1234567891,
        "student_name": "Bar",
        "student_address": "546 Main St.",
        "student_phone_num": 9184248576
    }
</code>```

The above is a silly example, but it helps illustrate the issue I am having trying to de-serialize the above into a Java class called "Employee" using Jackson:

```<code>public class Employee {
    String name;
    String address;
    String phoneNumber;
}
</code>```

The issue is that the JSON has two different prepends so I cannot annotate each field in Employee and have the object mapper map teacher_name and student_name to the name field in an Employee object. Is there a way in Jackson to specify two differently named nodes to map to the same Java field?

答:
I think you need to write code to do the mapping whether you use annotation or not.

Simple is the best.
If you read the json as JsonNode it should be trivial to code the assignments.

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class Q44094751 {

   public static void main(String[] args) throws IOException {
      String json = "{\"id\": 1," +
            "\"teacher_name\": \"Foo\", \"teacher_address\": \"123 Main St.\", \"teacher_phone_num\": 1234567891," +
            "\"student_name\": \"Bar\", \"student_address\": \"546 Main St.\", \"student_phone_num\": 9184248576" +
         "}";
      ObjectMapper mapper = new ObjectMapper();
      // Read
      JsonNode node = mapper.readValue( json, JsonNode.class);
      Employee teacher = new Employee(),
               student = new Employee();
      teacher.name = node.get( "teacher_name" ).toString();
      teacher.address = node.get( "teacher_address" ).toString();
      teacher.phoneNumber = node.get( "teacher_phone_num" ).toString();
      student.name = node.get( "student_name" ).toString();
      student.address = node.get( "student_address" ).toString();
      student.phoneNumber = node.get( "student_phone_num" ).toString();
      // Check
      mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
      System.out.println( mapper.writeValueAsString( teacher ) );
   }

   public static class Employee {
      String name;
      String address;
      String phoneNumber;
   }
}
```

Given a "silly example", the answer that may looks silly.
  For example if you have a hundred properties, a loop with reflection should work better.

If you have requirement(s) that is not reflected in the example,
  please edit your question to better describe the actual problem(s) you are facing.

Body:
I have a sample dummy JSON response that looks like :

    {
        "id": 1,
        "teacher_name": "Foo",
        "teacher_address": "123 Main St.",
        "teacher_phone_num": 1234567891,
        "student_name": "Bar",
        "student_address": "546 Main St.",
        "student_phone_num": 9184248576
    }

The above is a silly example, but it helps illustrate the issue I am having trying to de-serialize the above into a Java class called "Employee" using Jackson:

public class Employee {
    String name;
    String address;
    String phoneNumber;
}

The issue is that the JSON has two different prepends so I cannot annotate each field in Employee and have the object mapper map teacher_name and student_name to the name field in an Employee object. Is there a way in Jackson to specify two differently named nodes to map to the same Java field?

Body:
I think you need to write code to do the mapping whether you use annotation or not.

Simple is the best.
If you read the json as JsonNode it should be trivial to code the assignments.

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class Q44094751 {

   public static void main(String[] args) throws IOException {
      String json = "{\"id\": 1," +
            "\"teacher_name\": \"Foo\", \"teacher_address\": \"123 Main St.\", \"teacher_phone_num\": 1234567891," +
            "\"student_name\": \"Bar\", \"student_address\": \"546 Main St.\", \"student_phone_num\": 9184248576" +
         "}";
      ObjectMapper mapper = new ObjectMapper();
      // Read
      JsonNode node = mapper.readValue( json, JsonNode.class);
      Employee teacher = new Employee(),
               student = new Employee();
      teacher.name = node.get( "teacher_name" ).toString();
      teacher.address = node.get( "teacher_address" ).toString();
      teacher.phoneNumber = node.get( "teacher_phone_num" ).toString();
      student.name = node.get( "student_name" ).toString();
      student.address = node.get( "student_address" ).toString();
      student.phoneNumber = node.get( "student_phone_num" ).toString();
      // Check
      mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
      System.out.println( mapper.writeValueAsString( teacher ) );
   }

   public static class Employee {
      String name;
      String address;
      String phoneNumber;
   }
}

Given a "silly example", the answer that may looks silly.
  For example if you have a hundred properties, a loop with reflection should work better.

If you have requirement(s) that is not reflected in the example,
  please edit your question to better describe the actual problem(s) you are facing.


问:
Python: How to create a unique file name?
I have a python web form with two options - File upload and textarea. I need to take the values from each and pass them to another command-line program. I can easily pass the file name with file upload options, but I am not sure how to pass the value of the textarea.

I think what I need to do is:

Generate a unique file name

Create a temporary file with that name in the working directory

Save the values passed from textarea into the temporary file

Execute the commandline program from inside my python module and pass it the name of the temporary file

I am not sure how to generate a unique file name. Can anybody give me some tips on how to generate a unique file name? Any algorithms, suggestions, and lines of code are appreciated.

Thanks for your concern

答:
The uuid module would be a good choice, I prefer to use uuid.uuid4().hex as random filename because it will return a hex string without dashes.

```<code>import uuid
filename = uuid.uuid4().hex
</code>```

The outputs should like this:

```<code>>>> import uuid
>>> uuid.uuid()
UUID('20818854-3564-415c-9edc-9262fbb54c82')
>>> str(uuid.uuid4())
'f705a69a-8e98-442b-bd2e-9de010132dc4'
>>> uuid.uuid4().hex
'5ad02dfb08a04d889e3aa9545985e304'  # <-- this one
</code>```

Body:
The uuid module would be a good choice, I prefer to use uuid.uuid4().hex as random filename because it will return a hex string without dashes.

import uuid
filename = uuid.uuid4().hex

The outputs should like this:

>>> import uuid
>>> uuid.uuid()
UUID('20818854-3564-415c-9edc-9262fbb54c82')
>>> str(uuid.uuid4())
'f705a69a-8e98-442b-bd2e-9de010132dc4'
>>> uuid.uuid4().hex
'5ad02dfb08a04d889e3aa9545985e304'  # <-- this one


问:
ng-bootstrap not working in angular 4
I am new with angular 4, I am trying to configure bootstrap.
I installed ng-bootstrap:

https://ng-bootstrap.github.io/#/getting-started

I did all like on the page, but I don't see the bootstrap on my page.
Here is my code:

src/app/app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    AppComponent
  ],
imports: [
   BrowserModule,
   FormsModule,  // add  this
   NgbModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

src/app/app.component.html

```<code><div class="container">

<h1 class="text-primary">{{title}} </h1>

<h2 class="text-primary">My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
   </li>
</ul>

<div class="alert alert-success" role="alert">
 <strong>Well done!</strong> You successfully read this important alert
   message.
</div>

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
  <label>name: </label>
  <input [(ngModel)]="selectedHero.name" placeholder="name"/>
</div>
</code>```

I tried also some code in the index.html, but it does not work,

for this line I am expecting to see some color:

```<code><h1 class="text-primary">{{title}} </h1>
</code>```

I don't find any reference of bootstrap when I check the header of the html.
Any help, please?
Thanks

答:
I don't see any ng-bootstrap component in your code! I think you are looking for bootstrap css, which is also a prerequisite for ng-bootstrap.

Add these lines in index.html between the  tag:

```<code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</code>```

Title: ng-bootstrap not working in angular 4

Body:
I am new with angular 4, I am trying to configure bootstrap.
I installed ng-bootstrap:

https://ng-bootstrap.github.io/#/getting-started

I did all like on the page, but I don't see the bootstrap on my page.
Here is my code:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    AppComponent
  ],
imports: [
   BrowserModule,
   FormsModule,  // add  this
   NgbModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

src/app/app.component.html

{{title}}

My Heroes

    {{hero.id}} {{hero.name}}

 Well done! You successfully read this important alert
   message.

{{selectedHero.name}} details!

id: {{selectedHero.id}}

  name:
  <input [(ngModel)]="selectedHero.name" placeholder="name"/>

I tried also some code in the index.html, but it does not work,

for this line I am expecting to see some color:

{{title}}

I don't find any reference of bootstrap when I check the header of the html.
Any help, please?
Thanks

Body:
I don't see any ng-bootstrap component in your code! I think you are looking for bootstrap css, which is also a prerequisite for ng-bootstrap.

Add these lines in index.html between the <head></head> tag:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


问:
Creating a branch from issue in GitLab
I've just started using GitLab, and have created a set of issues, in order to keep an overview of what needs to be done for my application. I was wondering if it was possible to create a branch from these issues, such that the branch and issues are linked, similar as in jira and Stash from atlassian?</p>

答:
On the Issue screen, you see a green button labeled "Create merge request", with a down-arrow to its right.

That's not a button, that's a drop down list of buttons.

Click on the down arrow

Choose "Create branch"

Click on "Create branch"

A branch is created from the issue number, plus the title of the branch

For example, my issue #2, with title "Test repoSearch with no repos"
will have a branch called:

2-test-reposearch-with-no-repos

Notice that it changes case to all-lower-case

Title: Creating a branch from issue in GitLab

ContentLicense: CC BY-SA 4.0


问:
Incorrect Syntax near '=' (not an issue with "similiar" characters)
I know that this probably has been answered before, but I have rewritten this single line 10 times it still won't work. I have assured myself that this is written properly, yet it won't work.

This is my last resort. Here's a screenshot:

答:
For security reasons, and for the exact reason you are asking, you should not be setting raw T-SQL in theCommandText property of your SqlCommand.

In your case, your string likely has ' characters in it that are breaking your query making the syntax invalid.

Instead, you CommandText should be initialized with Parameters, for example:

```<code>findItForMe.CommandText = "SELECT Name, LicenseType, till FROM myTable WHERE SomeColumn = @SomeParameter"
</code>```

Then in your findItForMe command add the Parameters.

```<code>findItForMe.Parameters.AddWithValue("@SomeParameter", Somevalue)
</code>```

Building your findItForMe SqlCommand this way will fix your errors and prevent malicious actors from perform SQL injection hacks against your application.

A full example:

```<code>string name = "Jacob's Ladder";
string commandText = "SELECT Name, LicenseType, till FROM myTable WHERE Name = @Name";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand findItForMe = new SqlCommand(commandText, connection);

    // Use AddWithValue to assign name
    // The parameterized query will escape your strings and keep you safe from hackers.
    command.Parameters.AddWithValue("@name", name);

    try
    {
        connection.Open();
        SqlDataReader dr = command.ExecuteReader();
        while (dr.Read())
        {
            // do something here
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
</code>```

Body:
For security reasons, and for the exact reason you are asking, you should not be setting raw T-SQL in theCommandText property of your SqlCommand.

In your case, your string likely has ' characters in it that are breaking your query making the syntax invalid.

Instead, you CommandText should be initialized with Parameters, for example:

findItForMe.CommandText = "SELECT Name, LicenseType, till FROM myTable WHERE SomeColumn = @SomeParameter"

Then in your findItForMe command add the Parameters.

findItForMe.Parameters.AddWithValue("@SomeParameter", Somevalue)

Building your findItForMe SqlCommand this way will fix your errors and prevent malicious actors from perform SQL injection hacks against your application.

A full example:

string name = "Jacob's Ladder";
string commandText = "SELECT Name, LicenseType, till FROM myTable WHERE Name = @Name";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand findItForMe = new SqlCommand(commandText, connection);

    // Use AddWithValue to assign name
    // The parameterized query will escape your strings and keep you safe from hackers.
    command.Parameters.AddWithValue("@name", name);

    try
    {
        connection.Open();
        SqlDataReader dr = command.ExecuteReader();
        while (dr.Read())
        {
            // do something here
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}


答:
Option 1: You can actually convert multiple documents with just one execution of Open/Libre Office.. without a loop.  Just use a wildcard, eg:

```<code>    "C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to DBF mydir\*.csv
</code>```

Option 2: I assume that Windows has a limit on the number of files you can pass in that way.. not sure what that limit is.. but if you exceed that limit, you can use this python program I wrote to do this just a few days ago.. as part of a project I am still working on.  In my case I am converting .doc to .odt, and obviously my directories aren't the same as yours.  But it would be quite easy for you to adjust this to your needs...  One thing I wanted to do with mine is to check for the existence of the converted file and skip it if it exists.. so that if a few new files are added it can be run again to convert them without redoing them all...

The docpath should be set to the location of your files, and soffice to the pathname of your Calc exe.. and if you leave things the way I have them, that's where the program puts the converted files too.. and checks for their existence.  Also, I walk the path looking for input files.. so if for whatever reason you have your files in different subdirectories, it will find them and put the conversion in the same directory.

```<code>import os, sys, re, subprocess

docpath = 'doc'
soffice = 'C:\Program Files\LibreOffice 5\program\soffice.exe'

convert = '"%s" --headless --convert-to odt --outdir "%s" "%s"'

def plog(fmt = '', *args):
    sys.stdout.write(fmt % args)
    sys.stdout.flush()

def log(fmt = '', *args):
    plog((fmt + '\n'), *args)

def convert():
    odtfiles = []
    for subdir, dirs, files in os.walk(docpath):
        for file in files:
            if not file.endswith('.doc'):
                continue
            docfile = os.path.join(subdir, file)
            odtfile = re.sub(r"\.doc$", ".odt", docfile)
            plog("%s -> %s: " % (docfile, odtfile))
            if not os.path.isfile(odtfile):
                 plog('Converting.. ')
                 subprocess.check_output(convert % (soffice, docpath, docfile), shell=True)
            log('OK.')
            odtfiles.append(odtfile)
        return odtfiles

odtfiles = convert()
</code>```

Just install Python27.. and set the convert string to have the correct settings for your conversion.  Along with a few other changes that should be pretty easy.. but if you need help, ask in comments.

Title: Run an LibreOffice Command-Line Script through a loop

Body:
I have been able to successfully run the below code on an individual file, but I would like to find a way to have it run so that it loops through all the files shown in a directory. I believe that loops are possible within CMD.exe, but I am not having any success. Any help would be greatly appreciated.

"C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to DBF --infilter="csv:44,34,76,1,1/2/2/2/3/2/4/2/5/2/6/2/7/2/8/2/9/2/10/2/11/2/12/2/13/2/14/2/15/2/16/2/17/2/18/2/19/2/20/2/21/2/22/2/23/2/24/2/25/2/26/2/27/2/28/2/29/2/30/2/31/2/32/2/33/2/34/2/35/2/36/2/37/2/38/2/39/2/40/2/41/2/42/2/43/2/44/2/45/2/46/2/47/2/48/2/49/2/50/2/51/2/52/2/53/2/54/2/55/2/56/2/57/2/58/2/59/2/60/2/61/2/62/2/63/2/64/2/65/2/66/2/67/2/68/2/69/2/70/2/71/2/72/2/73/2/74/2/75/2/76/2/77/2/78/2/79/2/80/2/81/2/82/2/83/2/84/2/85/2/86/2/87/2/88/2/89/2/90/2/91/2/92/2/93/2/94/2/95/2/96/2/97/2/98/2/99/2/100/2/101/2/102/2/103/2/104/2/105/2/106/2/107/2/108/2/109/2/110/2/111/2/112/2/113/2/114/2/115/2/116/2/117/2/118/2/119/2/120/2/121/2/122/2/123/2/124/2/125/2/126/2/127/2/128/2/129/2/130/2/131/2/132/2/133/2/134/2/135/2/136/2,0,false,false" C:\Users\jdavidson\Desktop\DBFCONVERT\57826001_JQSAMPLE.csv --outdir C:\Users\jdavidson\desktop\complete

If you have any ideas for how I might be able to achieve this it be a huge help. I am working to build this as part of a larger workflow and make it repeatable.

UPDATE

I was able to iterate(Loop) through all of the files in my directory by creating a batch file and placing it within the directory that I am going to be using for converting moving forward

for /r %%i in (*.csv) do "C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to DBF --infilter="csv:44,34,76,1,1/2/2/2/3/2/4/2/5/2/6/2/7/2/8/2/9/2/10/2/11/2/12/2/13/2/14/2/15/2/16/2/17/2/18/2/19/2/20/2/21/2/22/2/23/2/24/2/25/2/26/2/27/2/28/2/29/2/30/2/31/2/32/2/33/2/34/2/35/2/36/2/37/2/38/2/39/2/40/2/41/2/42/2/43/2/44/2/45/2/46/2/47/2/48/2/49/2/50/2/51/2/52/2/53/2/54/2/55/2/56/2/57/2/58/2/59/2/60/2/61/2/62/2/63/2/64/2/65/2/66/2/67/2/68/2/69/2/70/2/71/2/72/2/73/2/74/2/75/2/76/2/77/2/78/2/79/2/80/2/81/2/82/2/83/2/84/2/85/2/86/2/87/2/88/2/89/2/90/2/91/2/92/2/93/2/94/2/95/2/96/2/97/2/98/2/99/2/100/2/101/2/102/2/103/2/104/2/105/2/106/2/107/2/108/2/109/2/110/2/111/2/112/2/113/2/114/2/115/2/116/2/117/2/118/2/119/2/120/2/121/2/122/2/123/2/124/2/125/2/126/2/127/2/128/2/129/2/130/2/131/2/132/2/133/2/134/2/135/2/136/2,0,false,false" C:\Users\jdavidson\Desktop\DBFCONVERT\57826001_JQSAMPLE.csv --outdir C:\Users\jdavidson\desktop\complete %%i

Note that I used a for Loop to achieve what I wanted.

for /r %%i in ('list directory if command not being run in specific directory already; you can also but * for all files in directory or *.ext for the extension of only certain files) do 'add in command %%i

Body:
Option 1: You can actually convert multiple documents with just one execution of Open/Libre Office.. without a loop.  Just use a wildcard, eg:

    "C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to DBF mydir\*.csv

Option 2: I assume that Windows has a limit on the number of files you can pass in that way.. not sure what that limit is.. but if you exceed that limit, you can use this python program I wrote to do this just a few days ago.. as part of a project I am still working on.  In my case I am converting .doc to .odt, and obviously my directories aren't the same as yours.  But it would be quite easy for you to adjust this to your needs...  One thing I wanted to do with mine is to check for the existence of the converted file and skip it if it exists.. so that if a few new files are added it can be run again to convert them without redoing them all...

The docpath should be set to the location of your files, and soffice to the pathname of your Calc exe.. and if you leave things the way I have them, that's where the program puts the converted files too.. and checks for their existence.  Also, I walk the path looking for input files.. so if for whatever reason you have your files in different subdirectories, it will find them and put the conversion in the same directory.

import os, sys, re, subprocess

docpath = 'doc'
soffice = 'C:\Program Files\LibreOffice 5\program\soffice.exe'

convert = '"%s" --headless --convert-to odt --outdir "%s" "%s"'

def plog(fmt = '', *args):
    sys.stdout.write(fmt % args)
    sys.stdout.flush()

def log(fmt = '', *args):
    plog((fmt + '\n'), *args)

def convert():
    odtfiles = []
    for subdir, dirs, files in os.walk(docpath):
        for file in files:
            if not file.endswith('.doc'):
                continue
            docfile = os.path.join(subdir, file)
            odtfile = re.sub(r"\.doc$", ".odt", docfile)
            plog("%s -> %s: " % (docfile, odtfile))
            if not os.path.isfile(odtfile):
                 plog('Converting.. ')
                 subprocess.check_output(convert % (soffice, docpath, docfile), shell=True)
            log('OK.')
            odtfiles.append(odtfile)
        return odtfiles

odtfiles = convert()

Just install Python27.. and set the convert string to have the correct settings for your conversion.  Along with a few other changes that should be pretty easy.. but if you need help, ask in comments.


问:
Laravel - How to restrict certain functionality based on user authentication?
Laravel newbie here (obviously :D ). I've set up a new model & controller for a model named Pages.

Every User has many Pages.

Each Page has a single User.

I've created the following functioning controller actions (& views):

```<code>PagesController::index
PagesController::create
PagesController::store
PagesController::show
PagesController::edit
PagesController::delete
</code>```

So you can edit a Page by going to url.dev/pages/{id}/edit.

The problem is, you can access all of these routes regardless of your session status. So random users can edit any given Page. Which, obviously, is terrible.

Can anyone point me in the direction of what I should read up on, to limit the ability to access my model's controller actions based on whether or not the user is logged in (and if it's the correct user, at all)?

答:
You´re looking for middleware..
You can read more here  </p>

```<code>public function __construct()
{
    $this->middleware('auth')->only('index');

    $this->middleware('admin')->except('store');
}
</code>```

Body:
Laravel newbie here (obviously :D ). I've set up a new model & controller for a model named Pages.

Every User has many Pages.

Each Page has a single User.

I've created the following functioning controller actions (& views):

PagesController::index
PagesController::create
PagesController::store
PagesController::show
PagesController::edit
PagesController::delete

So you can edit a Page by going to url.dev/pages/{id}/edit.

The problem is, you can access all of these routes regardless of your session status. So random users can edit any given Page. Which, obviously, is terrible.

Can anyone point me in the direction of what I should read up on, to limit the ability to access my model's controller actions based on whether or not the user is logged in (and if it's the correct user, at all)?

Body:
You´re looking for middleware..
You can read more here

public function __construct()
{
    $this->middleware('auth')->only('index');

    $this->middleware('admin')->except('store');
}


答:
To force a specific route to be only accessible by authenticated users you can specify middleware auth in the controller constructor, like so:

```<code>public function __construct()
{
    $this->middleware('auth');
}
</code>```

Also you can restrict which methods you want auth to be applied to in the controller, using the only or except parameters. Using only you could do:

```<code>public function __construct()
{
    $this->middleware('auth', ['only' => ['create', 'store', 'edit', 'delete']]);
}
</code>```

Title: Laravel - How to restrict certain functionality based on user authentication?

Body:
To force a specific route to be only accessible by authenticated users you can specify middleware auth in the controller constructor, like so:

public function __construct()
{
    $this->middleware('auth');
}

Also you can restrict which methods you want auth to be applied to in the controller, using the only or except parameters. Using only you could do:

public function __construct()
{
    $this->middleware('auth', ['only' => ['create', 'store', 'edit', 'delete']]);
}


问:
Can I use Existing Certificate, private key, public key for my hyperledger fabric user rather than creating new from CA or cryptogen?
I am working on Hyperledger fabric 1.0 beta release. So far I have noticed that if a transaction is done on a peer using Node sdk, it internally sends a call to CA to get crypto material for new user(Cert, private key, public key). If I already have a user certificate, private key, public key, how can I use them to send request to peers instead of using crypto material provided by CA.
I have noticed that Cryptogen utility also generates crypto artifacts for users. How can I use those artifacts to make a transaction on peer instead of making a call to CA first?</p>

答: Please refer to the e2e_cli example in fabric project, by using the script generateArtifacts.sh, you will get the certificate files and genesis block. When you start you node server, you read the certificate directly from the existing file instead of getting them from CA server, actually you don't need to run the CA server.</p>


问:
How to move all contents of Directory (not including Parent) to another directory Groovy
I have a groovy script which takes a 2 zip files, unzips them, then processes them.

The problem I have is when I go to unzip the zip files, each unzipped file produces a subfolder then the content of the unzip file not the content itself.

Example:

Currently this happens when I unzip

content-1232.zip -> /content-1232/content/<all content here>

What I want is

content-1232.zip -> /content-1232/<all_content>

or

Put  into a new directory

content-1232.zip -> /new_directory/<all_content>

I tried this but to no avail:

```<code>Path basePath = Paths.get(output.getAbsolutePath())
Path srcPath = Paths.get(pdfContent.getAbsolutePath())
Path targetPath = basePath

Files.move(srcPath, targetPath.resolve(basePath.relativize(srcPath)))
</code>```

Seems like a very simple thing to do but I'm not have any luck. How can I accomplish this in groovy? Any help will be appreciated

Edit:

```<code>static void main(String[] args) {
    logger.info("Beginning unpacking of content...")

    def output = new File("/Users/Haddad/Desktop/workspace/c")
    def pdfContent = new File("/Users/Haddad/Desktop/workspace/c/pdf-content")

    // Look for test1 and test2 production content zip file, ensure there's only 1 and unzip
    List appZip = FileUtil.discoverFiles(output, true, "test1-production-content-.*\\.zip")
    List compliZip = FileUtil.discoverFiles(output,true,"test2-production-content-.*\\.zip")

    assert appZip.size() == 1, "Did not find expected number of test1 content zip, actual size is: " + appZip.size()
    assert compliZip.size() == 1, "Did not find expected number of test2 content zip, actual size is " + appZip.size()

    def outputAppZip = new File(output.getAbsolutePath()+"/"+appZip.get(0).getName()+"-intermediate");
    def outputCompliZip = new File(output.getAbsolutePath()+"/"+compliZip.get(0).getName()+"-intermediate");

    ZipUtil.unzipToDisk(appZip.get(0), outputAppZip )
    ZipUtil.unzipToDisk(compliZip.get(0), outputCompliZip )

    // move it to pdf content
    List applicationContent = FileUtil.discoverDirectories(output, "one-production-content-.*-intermediate", true)
    assert applicationContent.size() == 1, "Did not find expected number of test1 contents " + applicationContent.size()

    def success = FileUtil.copy(applicationContent.get(0), pdfContent)
    assert success, "Could not copy tt content"

    // move pdf content
    List complianceContent = FileUtil.discoverDirectories(output, "two-production-content-.*-intermediate", true)
    assert complianceContent.size() == 1, "Did not find expected number of test2 contents " + complianceContent.size()
    success = FileUtil.copy(complianceContent.get(0), pdfContent)
    assert success, "Could not copy pdf content"

    // rename to not be unsupported
    List unsupportedDirs = FileUtil.discoverDirectories(pdfContent, "_unsupported_.*", true)
    for (File file : unsupportedDirs) {
        file.renameTo(new File(file.getParentFile(), file.getName().replace("_unsupported_", "")))
    }

    logger.info("Completed!")
}
</code>```

答:
How about this?

Input:

```<code>test.zip
--- test
------ test.txt
</code>```

Output:

```<code><someFolder>
--- test.txt
</code>```

Code:

```<code>public class Main {

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        Path input = main.getInputPath(args);
        Path output = main.getOutputPath(args);

        main.extract(input, output);
        main.flatten(output);
    }

    private final Path getInputPath(String[] args) {
        if (args.length < 1) {
            throw new IllegalArgumentException("Usage: Main <inputFile> [<outputDirectory>]");
        }

        Path input = Paths.get(args[0]);

        if (!isRegularFile(input)) {
            throw new IllegalArgumentException(String.format("%s is not a file.", input.toFile().getAbsolutePath()));
        }

        return input;
    }

    private final Path getOutputPath(String[] args) throws IOException {
        return args.length < 2 ? Files.createTempDirectory(null) :
                Files.createDirectories(Paths.get(args[1]));
    }

    private final void extract(Path input, Path output) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input.toFile()))) {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                String fileName = ze.getName();

                if (fileName.contains("__MACOSX")) {
                    continue;
                }

                File file = new File(output.toFile(), fileName);

                if (ze.isDirectory()) {
                    Files.createDirectories(file.toPath());
                    continue;
                }

                System.out.println("Extracting: " + file.getAbsolutePath());

                try (FileOutputStream fos = new FileOutputStream(file, true)) {
                    byte[] buffer = new byte[4096];
                    for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                        fos.write(buffer, 0, len);
                    }
                }
            }
        }
    }

    private final void flatten(Path output) throws IOException {
        List<Path> children = Files.list(output)
                .collect(toList());

        if (children.size() == 1) {
            Path path = children.get(0);
            Files.list(path)
                    .forEach(f -> {
                        try {
                            System.out.printf("Moving %s to %s.\n", f.toFile().getAbsolutePath(),
                                    output.toFile().getAbsolutePath());
                            Files.move(f, Paths.get(output.toFile().getAbsolutePath(), f.toFile().getName()));
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });

            Files.delete(path);
        }
    }
}
</code>```

Body:
I have a groovy script which takes a 2 zip files, unzips them, then processes them.

The problem I have is when I go to unzip the zip files, each unzipped file produces a subfolder then the content of the unzip file not the content itself.

Example:

Currently this happens when I unzip

content-1232.zip -> /content-1232/content/<all content here>

What I want is

content-1232.zip -> /content-1232/<all_content>

or

Put  into a new directory

content-1232.zip -> /new_directory/<all_content>

I tried this but to no avail:

Path basePath = Paths.get(output.getAbsolutePath())
Path srcPath = Paths.get(pdfContent.getAbsolutePath())
Path targetPath = basePath

Files.move(srcPath, targetPath.resolve(basePath.relativize(srcPath)))

Seems like a very simple thing to do but I'm not have any luck. How can I accomplish this in groovy? Any help will be appreciated

Edit:

static void main(String[] args) {
    logger.info("Beginning unpacking of content...")

    def output = new File("/Users/Haddad/Desktop/workspace/c")
    def pdfContent = new File("/Users/Haddad/Desktop/workspace/c/pdf-content")

    // Look for test1 and test2 production content zip file, ensure there's only 1 and unzip
    List appZip = FileUtil.discoverFiles(output, true, "test1-production-content-.*\\.zip")
    List compliZip = FileUtil.discoverFiles(output,true,"test2-production-content-.*\\.zip")

    assert appZip.size() == 1, "Did not find expected number of test1 content zip, actual size is: " + appZip.size()
    assert compliZip.size() == 1, "Did not find expected number of test2 content zip, actual size is " + appZip.size()

    def outputAppZip = new File(output.getAbsolutePath()+"/"+appZip.get(0).getName()+"-intermediate");
    def outputCompliZip = new File(output.getAbsolutePath()+"/"+compliZip.get(0).getName()+"-intermediate");

    ZipUtil.unzipToDisk(appZip.get(0), outputAppZip )
    ZipUtil.unzipToDisk(compliZip.get(0), outputCompliZip )

    // move it to pdf content
    List applicationContent = FileUtil.discoverDirectories(output, "one-production-content-.*-intermediate", true)
    assert applicationContent.size() == 1, "Did not find expected number of test1 contents " + applicationContent.size()

    def success = FileUtil.copy(applicationContent.get(0), pdfContent)
    assert success, "Could not copy tt content"

    // move pdf content
    List complianceContent = FileUtil.discoverDirectories(output, "two-production-content-.*-intermediate", true)
    assert complianceContent.size() == 1, "Did not find expected number of test2 contents " + complianceContent.size()
    success = FileUtil.copy(complianceContent.get(0), pdfContent)
    assert success, "Could not copy pdf content"

    // rename to not be unsupported
    List unsupportedDirs = FileUtil.discoverDirectories(pdfContent, "_unsupported_.*", true)
    for (File file : unsupportedDirs) {
        file.renameTo(new File(file.getParentFile(), file.getName().replace("_unsupported_", "")))
    }

    logger.info("Completed!")
}

Body:
How about this?

Input:

test.zip
--- test
------ test.txt

Output:

<someFolder>
--- test.txt

Code:

public class Main {

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        Path input = main.getInputPath(args);
        Path output = main.getOutputPath(args);

        main.extract(input, output);
        main.flatten(output);
    }

    private final Path getInputPath(String[] args) {
        if (args.length < 1) {
            throw new IllegalArgumentException("Usage: Main <inputFile> [<outputDirectory>]");
        }

        Path input = Paths.get(args[0]);

        if (!isRegularFile(input)) {
            throw new IllegalArgumentException(String.format("%s is not a file.", input.toFile().getAbsolutePath()));
        }

        return input;
    }

    private final Path getOutputPath(String[] args) throws IOException {
        return args.length < 2 ? Files.createTempDirectory(null) :
                Files.createDirectories(Paths.get(args[1]));
    }

    private final void extract(Path input, Path output) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input.toFile()))) {
            for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
                String fileName = ze.getName();

                if (fileName.contains("__MACOSX")) {
                    continue;
                }

                File file = new File(output.toFile(), fileName);

                if (ze.isDirectory()) {
                    Files.createDirectories(file.toPath());
                    continue;
                }

                System.out.println("Extracting: " + file.getAbsolutePath());

                try (FileOutputStream fos = new FileOutputStream(file, true)) {
                    byte[] buffer = new byte[4096];
                    for (int len = zis.read(buffer); len > 0; len = zis.read(buffer)) {
                        fos.write(buffer, 0, len);
                    }
                }
            }
        }
    }

    private final void flatten(Path output) throws IOException {
        List<Path> children = Files.list(output)
                .collect(toList());

        if (children.size() == 1) {
            Path path = children.get(0);
            Files.list(path)
                    .forEach(f -> {
                        try {
                            System.out.printf("Moving %s to %s.\n", f.toFile().getAbsolutePath(),
                                    output.toFile().getAbsolutePath());
                            Files.move(f, Paths.get(output.toFile().getAbsolutePath(), f.toFile().getName()));
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });

            Files.delete(path);
        }
    }
}


问:
Creating Spring Framework task programmatically?
I need to create task on the fly in my app. How can I do that? I can get scheduler with @autowired annotation, but scheduler takes Runnable objects. I need to give Spring objects, so that my tasks can use @autowired annotation too.

```<code>@Autowired private TaskScheduler taskScheduler;
</code>```

答:
You just need to wrap your target object in a Runnable, and submit that:

```<code>private Target target;  // this is a Spring bean of some kind
@Autowired private TaskScheduler taskScheduler;

public void scheduleSomething() {
    Runnable task = new Runnable() {
       public void run() {
          target.doTheWork();
       }
    };
    taskScheduler.scheduleWithFixedDelay(task, delay);
}
</code>```

Body:
I need to create task on the fly in my app. How can I do that? I can get scheduler with @autowired annotation, but scheduler takes Runnable objects. I need to give Spring objects, so that my tasks can use @autowired annotation too.

@Autowired private TaskScheduler taskScheduler;

Body:
You just need to wrap your target object in a Runnable, and submit that:

private Target target;  // this is a Spring bean of some kind
@Autowired private TaskScheduler taskScheduler;

public void scheduleSomething() {
    Runnable task = new Runnable() {
       public void run() {
          target.doTheWork();
       }
    };
    taskScheduler.scheduleWithFixedDelay(task, delay);
}


问:
Is it possible to anchor an element to a centered element?
Is it possible to anchor a textarea to an image that is centered in the middle of the page, so that it doesn't move out of the image when the screen size changes?

Example on jsfiddle: https://jsfiddle.net/rxg7t2ca/1/

.container {
  width: 60%;
  margin: 0 auto;
  /* border: 2px solid blue; */
}

#cat {
  display: block;
  margin: 0 auto;
}

.box1 {
  position: relative;
  top: -250px;
  left: 30px;
  width: 100px;
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img src="http://i.imgur.com/a2Wd9D2.jpg" height=300px id="cat" />
  <textarea class="box1"> This is a text box </textarea>

</div></code>```

答:
.container {
  position: relative;
  width: 60%;
  margin: 0 auto;
  border: 2px solid blue;
}

#cat {
  width: 100%;
  object-fit: cover;                 /* 1 */
  vertical-align: bottom;            /* 2 */
}

.box1 {
  position: absolute;                /* 3 */
  top: 50%;                          /* 3 */
  left: 50%;                         /* 3 */
  transform: translate(-50%, -50%);  /* 3 */
  width: 100px;
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img src="http://i.imgur.com/a2Wd9D2.jpg" height=300px id="cat" />
  <textarea class="box1"> This is a text box </textarea>
</div></code>```

Explanations:

Why isn't object-fit working in flexbox?

Mystery white space underneath image tag

Element will not stay centered, especially when re-sizing screen

Body:
Is it possible to anchor a textarea to an image that is centered in the middle of the page, so that it doesn't move out of the image when the screen size changes?

Example on jsfiddle: https://jsfiddle.net/rxg7t2ca/1/

.container {
  width: 60%;
  margin: 0 auto;
  /* border: 2px solid blue; */
}

#cat {
  display: block;
  margin: 0 auto;
}

.box1 {
  position: relative;
  top: -250px;
  left: 30px;
  width: 100px;
  height: 100px;
}

  <textarea class="box1"> This is a text box </textarea>

Body:
.container {
  position: relative;
  width: 60%;
  margin: 0 auto;
  border: 2px solid blue;
}

#cat {
  width: 100%;
  object-fit: cover;                 /* 1 */
  vertical-align: bottom;            /* 2 */
}

.box1 {
  position: absolute;                /* 3 */
  top: 50%;                          /* 3 */
  left: 50%;                         /* 3 */
  transform: translate(-50%, -50%);  /* 3 */
  width: 100px;
  height: 100px;
}

<div class="container">
  <img src="http://i.imgur.com/a2Wd9D2.jpg" height=300px id="cat" />
  <textarea class="box1"> This is a text box </textarea>
</div>

Explanations:

Why isn't object-fit working in flexbox?

Mystery white space underneath image tag

Element will not stay centered, especially when re-sizing screen


问:
Passing two php variables to another page from a link
Ok so I'm building a simple question/answer site and this is a loop that outputs all the questions asked previously in link form.  I'm trying to concat two variables to the next page url so I can get them and work with them there but it will only allow one?  I've tried everything but not working?  See the only comment section of my code for the crux of the issue.  Thank you.</p>

```<code><?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;

$conn = mysqli_connect($servername, $username, $password, $dbname,
$port);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'> Log out </a><br>
<a href='ask.php'> Ask a question</a><br>
<br />
<br />";

echo "Answer another users question: <br><br />";

$sql = "SELECT q_id,question, username FROM questions";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

while($row = mysqli_fetch_array($result))
{

$q_id = $row['q_id'];
$question = $row['question'];
$username = $row['username'];

//right here I need to add(concat) the second variable $username
//I need to get both on the next page url but not allowing me to

echo ('<a href="totalqs.php?q_id=' . $q_id .'   " >' . $question .
'</a>'  . '<br>');
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>
</code>```

答:
Use this code in your echo statement. This concatenates your second value $username with name user:

```<code>echo '<a href="totalqs.php?q_id='.$q_id.'&user='.$username.'">'.$question.'</a><br />';
</code>```

Note that you do not need parentheses in your echo statement. You need to properly concatenate your string (you need to learn more about concatenation). In the next page, you can access q_id and user as

```<code>$id = $_GET['q_id'];
$username = $_GET['user'];
</code>```

Body:
Ok so I'm building a simple question/answer site and this is a loop that outputs all the questions asked previously in link form.  I'm trying to concat two variables to the next page url so I can get them and work with them there but it will only allow one?  I've tried everything but not working?  See the only comment section of my code for the crux of the issue.  Thank you.

<?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;

$conn = mysqli_connect($servername, $username, $password, $dbname,
$port);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo " Log out

 Ask a question

";

echo "Answer another users question:

";

$sql = "SELECT q_id,question, username FROM questions";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

while($row = mysqli_fetch_array($result))
{

$q_id = $row['q_id'];
$question = $row['question'];
$username = $row['username'];

//right here I need to add(concat) the second variable $username
//I need to get both on the next page url but not allowing me to

echo ('' . $question .
''  . '
');
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

Body:
Use this code in your echo statement. This concatenates your second value $username with name user:

echo '<a href="totalqs.php?q_id='.$q_id.'&user='.$username.'">'.$question.'</a><br />';

Note that you do not need parentheses in your echo statement. You need to properly concatenate your string (you need to learn more about concatenation). In the next page, you can access q_id and user as

$id = $_GET['q_id'];
$username = $_GET['user'];


问:
What are the exact downsides of copy=False in DataFrame.merge()?
I am a bit confused about the argument copy in DataFrame.merge() after a co-worker asked me about that.

The docstring of DataFrame.merge() states:

```<code>copy : boolean, default True
    If False, do not copy data unnecessarily
</code>```

The pandas documentation states:

copy: Always copy data (default True) from the passed DataFrame objects, even when reindexing is not necessary. Cannot be avoided in many cases but may improve performance / memory usage. The cases where copying can be avoided are somewhat pathological but this option is provided nonetheless.

The docstring kind of implies that copying the data is not necessary and might be skipped nearly always. The documention on the other hand says, that copying data can't be avoided in many cases.

My questions are:

What are those cases?

What are the downsides?

答:
Disclaimer: I'm not very experienced with pandas and this is the first time I dug into its source, so I can't guarantee that I'm not missing something in my below assessment.

The relevant bits of code have been recently refactored. I'll discuss the subject in terms of the current stable version 0.20, but I don't suspect functional changes compared to earlier versions.

The investigation starts with the source of merge in pandas/core/reshape/merge.py (formerly pandas/tools/merge.py). Ignoring some doc-aware decorators:

```<code>def merge(left, right, how='inner', on=None, left_on=None, right_on=None,
          left_index=False, right_index=False, sort=False,
          suffixes=('_x', '_y'), copy=True, indicator=False):
    op = _MergeOperation(left, right, how=how, on=on, left_on=left_on,
                         right_on=right_on, left_index=left_index,
                         right_index=right_index, sort=sort, suffixes=suffixes,
                         copy=copy, indicator=indicator)
    return op.get_result()
</code>```

Calling merge will pass on the copy parameter to the constructor of class _MergeOperation, then calls its get_result() method. The first few lines with context:

```<code># TODO: transformations??
# TODO: only copy DataFrames when modification necessary
class _MergeOperation(object):
    [...]
</code>```

Now that second comment is highly suspicious. Moving on, the copy kwarg is bound to an eponymous instance attribute, which only seems to reappear once within the class:

```<code>result_data = concatenate_block_managers(
    [(ldata, lindexers), (rdata, rindexers)],
    axes=[llabels.append(rlabels), join_index],
    concat_axis=0, copy=self.copy)
</code>```

We can then track down the concatenate_block_managers function in pandas/core/internals.py that just passes on the copy kwarg to concatenate_join_units.

We reached the final resting place of the original copy keyword argument in concatenate_join_units:

```<code>if len(to_concat) == 1:
    # Only one block, nothing to concatenate.
    concat_values = to_concat[0]
    if copy and concat_values.base is not None:
        concat_values = concat_values.copy()
else:
    concat_values = _concat._concat_compat(to_concat, axis=concat_axis)
</code>```

As you can see, the only thing that copy does is rebind a copy of concat_values here to the same name in the special case of concatenation when there's really nothing to concatenate.

Now, at this point my lack of pandas knowledge starts to show, because I'm not really sure what exactly is going on this deep inside the call stack. But the above hot-potato scheme with the copy keyword argument ending in that no-op-like branch of a concatenation function is perfectly consistent with the "TODO" comment above, the documentation quoted in the question:

copy: Always copy data (default True) from the passed DataFrame objects, even when reindexing is not necessary. Cannot be avoided in many cases but may improve performance / memory usage. The cases where copying can be avoided are somewhat pathological but this option is provided nonetheless.

(emphasis mine), and the related discussion on an old issue:

IIRC I think the copy parameter only matters here is its a trivial merge and you actually do want it copied (kind I like a reindex with the same index)

Based on these hints I suspect that in the very vast majority of real use cases copying is inevitable, and the copy keyword argument is never used. However, since for the small number of exceptions skipping a copy step might improve performance (without leading to any performance impact whatsoever for the majority of use cases in the mean time), the choice was implemented.

I suspect that the rationale is something like this: the upside of not doing a copy unless necessary (which is only possible in a very special few cases) is that the code avoids some memory allocations and copies in this case, but not returning a copy in a very special few cases might lead to unexpected surprises if one doesn't expect that mutating the return value of merge could in any way affect the original dataframe. So the default value of the copy keyword argument is True, thus the user only doesn't get a copy from merge if they explicitly volunteer for this (but even then they'll still likely end up with a copy).

Body:
I am a bit confused about the argument copy in DataFrame.merge() after a co-worker asked me about that.

The docstring of DataFrame.merge() states:

copy : boolean, default True
    If False, do not copy data unnecessarily

The pandas documentation states:

copy: Always copy data (default True) from the passed DataFrame objects, even when reindexing is not necessary. Cannot be avoided in many cases but may improve performance / memory usage. The cases where copying can be avoided are somewhat pathological but this option is provided nonetheless.

The docstring kind of implies that copying the data is not necessary and might be skipped nearly always. The documention on the other hand says, that copying data can't be avoided in many cases.

My questions are:

What are those cases?

What are the downsides?

Body:
Disclaimer: I'm not very experienced with pandas and this is the first time I dug into its source, so I can't guarantee that I'm not missing something in my below assessment.

The relevant bits of code have been recently refactored. I'll discuss the subject in terms of the current stable version 0.20, but I don't suspect functional changes compared to earlier versions.

The investigation starts with the source of merge in pandas/core/reshape/merge.py (formerly pandas/tools/merge.py). Ignoring some doc-aware decorators:

def merge(left, right, how='inner', on=None, left_on=None, right_on=None,
          left_index=False, right_index=False, sort=False,
          suffixes=('_x', '_y'), copy=True, indicator=False):
    op = _MergeOperation(left, right, how=how, on=on, left_on=left_on,
                         right_on=right_on, left_index=left_index,
                         right_index=right_index, sort=sort, suffixes=suffixes,
                         copy=copy, indicator=indicator)
    return op.get_result()

Calling merge will pass on the copy parameter to the constructor of class _MergeOperation, then calls its get_result() method. The first few lines with context:

# TODO: transformations??
# TODO: only copy DataFrames when modification necessary
class _MergeOperation(object):
    [...]

Now that second comment is highly suspicious. Moving on, the copy kwarg is bound to an eponymous instance attribute, which only seems to reappear once within the class:

result_data = concatenate_block_managers(
    [(ldata, lindexers), (rdata, rindexers)],
    axes=[llabels.append(rlabels), join_index],
    concat_axis=0, copy=self.copy)

We can then track down the concatenate_block_managers function in pandas/core/internals.py that just passes on the copy kwarg to concatenate_join_units.

We reached the final resting place of the original copy keyword argument in concatenate_join_units:

if len(to_concat) == 1:
    # Only one block, nothing to concatenate.
    concat_values = to_concat[0]
    if copy and concat_values.base is not None:
        concat_values = concat_values.copy()
else:
    concat_values = _concat._concat_compat(to_concat, axis=concat_axis)

As you can see, the only thing that copy does is rebind a copy of concat_values here to the same name in the special case of concatenation when there's really nothing to concatenate.

Now, at this point my lack of pandas knowledge starts to show, because I'm not really sure what exactly is going on this deep inside the call stack. But the above hot-potato scheme with the copy keyword argument ending in that no-op-like branch of a concatenation function is perfectly consistent with the "TODO" comment above, the documentation quoted in the question:

copy: Always copy data (default True) from the passed DataFrame objects, even when reindexing is not necessary. Cannot be avoided in many cases but may improve performance / memory usage. The cases where copying can be avoided are somewhat pathological but this option is provided nonetheless.

(emphasis mine), and the related discussion on an old issue:

IIRC I think the copy parameter only matters here is its a trivial merge and you actually do want it copied (kind I like a reindex with the same index)

Based on these hints I suspect that in the very vast majority of real use cases copying is inevitable, and the copy keyword argument is never used. However, since for the small number of exceptions skipping a copy step might improve performance (without leading to any performance impact whatsoever for the majority of use cases in the mean time), the choice was implemented.

I suspect that the rationale is something like this: the upside of not doing a copy unless necessary (which is only possible in a very special few cases) is that the code avoids some memory allocations and copies in this case, but not returning a copy in a very special few cases might lead to unexpected surprises if one doesn't expect that mutating the return value of merge could in any way affect the original dataframe. So the default value of the copy keyword argument is True, thus the user only doesn't get a copy from merge if they explicitly volunteer for this (but even then they'll still likely end up with a copy).