问:
What's the meaning of these two lines of PHP code?
I'm currently programming a script to login the user if the user types the right information in the Password- and Login-field on a login page. The script is working just fine, but I don't actually know what these two lines of code means and does for the overall user experience.

I'm soon going to an exam where I have to explain the meaning of the code, and it would be absolutely amazing if you guys helped me out by explaining what the two lines of code does below. This is the full script:

```<code><?php

require('db_connect.php');

if (isset($_POST['user_id']) and isset($_POST['user_pass'])) {

    $username = $_POST['user_id'];
    $password = $_POST['user_pass'];

    $query = "SELECT * FROM dataforlogin WHERE username='$username' and password='$password'";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {

        header("location: ../staudal/dashboard/index.php");

    } else {

        echo "Fail";

  }
}

?>
</code>```

The two lines of code that I'm having trouble understanding is:

```<code>$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
</code>```

What do they do and why?

答:
That's a good question because these lines are mostly wrong or useless according to the modern standards of security and application design. It never occurred to me before there could be so much wrong in just two lines of code.

mysqli_query() sends your query to MySQL server. However, it is not the way you run a mysql query with variables. A prepared statement must be used instead.

die(mysqli_error($connection)) is intended to stop the code execution if the query execution fails and reveal the mysql error (particularly, or die() does many interesting things, I have an article that explains this. However, it is not the way you report mysql errors in PHP. A single configuration option must be used instead. which will be better in so many ways, from the amount of code written to the better user experience.

mysqli_num_rows($result) tells you how many rows returned your query. An essentially useless function, you can always use the returned data instead

WHERE username='$username' and password='$password' is not the way you are checking the password in the database. A hashed password must be retrieved from the database and then checked using password_verify() function

here is how it should be

```<code>$stmt = $mysqli->prepare("SELECT * FROM dataforlogin WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result= $stmt->get_result()
$user = $result->fetch_assoc();

if ($user && password_verify($password, $user['password']))
{
    // write some info into the session
    header("location: ../staudal/dashboard/index.php");
    exit;
} else {
    echo "invalid";
}
</code>```

in the first line we are preparing the sql query with question marks placed where variables should go (so it is called a placeholder).

in the second line we are binding the actual variable to the placeholder, so it will be sent to mysql server separated from the query and there will be no way for them to interfere.

then the query gets actually executed.

then we are getting the mysqli_result variable, familiar to all users of either old mysql or new mysqli query - the actual source of data returned by the query.

then we are trying to fetch the selected row.

then we are checking two things at once,

whether our query returned any row

and if so, whether the password sent from the form is the same as one stored in the database using password_verify() function

the rest is the same as in your code save for two things

before redirecting a user you are supposed to write some information about them into the session, in order to recognize them on other pages

it is a good practice to add exit after sending the Location header.

Hope these explanations will be enough for your teachers

Seriously, this question should raise awareness about the state of PHP education. Most sources, online and offline, are teaching as though it is still PHP3 around, with only minor face-lifting in regard of deprecated functions. But the approach, which is wrong in so many ways, remains the same.

Body:
I'm currently programming a script to login the user if the user types the right information in the Password- and Login-field on a login page. The script is working just fine, but I don't actually know what these two lines of code means and does for the overall user experience.

I'm soon going to an exam where I have to explain the meaning of the code, and it would be absolutely amazing if you guys helped me out by explaining what the two lines of code does below. This is the full script:

<?php

require('db_connect.php');

if (isset($_POST['user_id']) and isset($_POST['user_pass'])) {

    $username = $_POST['user_id'];
    $password = $_POST['user_pass'];

    $query = "SELECT * FROM dataforlogin WHERE username='$username' and password='$password'";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {

        header("location: ../staudal/dashboard/index.php");

    } else {

        echo "Fail";

  }
}

?>

The two lines of code that I'm having trouble understanding is:

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);

What do they do and why?

Body:
That's a good question because these lines are mostly wrong or useless according to the modern standards of security and application design. It never occurred to me before there could be so much wrong in just two lines of code.

mysqli_query() sends your query to MySQL server. However, it is not the way you run a mysql query with variables. A prepared statement must be used instead.

die(mysqli_error($connection)) is intended to stop the code execution if the query execution fails and reveal the mysql error (particularly, or die() does many interesting things, I have an article that explains this. However, it is not the way you report mysql errors in PHP. A single configuration option must be used instead. which will be better in so many ways, from the amount of code written to the better user experience.

mysqli_num_rows($result) tells you how many rows returned your query. An essentially useless function, you can always use the returned data instead

WHERE username='$username' and password='$password' is not the way you are checking the password in the database. A hashed password must be retrieved from the database and then checked using password_verify() function

here is how it should be

$stmt = $mysqli->prepare("SELECT * FROM dataforlogin WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result= $stmt->get_result()
$user = $result->fetch_assoc();

if ($user && password_verify($password, $user['password']))
{
    // write some info into the session
    header("location: ../staudal/dashboard/index.php");
    exit;
} else {
    echo "invalid";
}

in the first line we are preparing the sql query with question marks placed where variables should go (so it is called a placeholder).

in the second line we are binding the actual variable to the placeholder, so it will be sent to mysql server separated from the query and there will be no way for them to interfere.

then the query gets actually executed.

then we are getting the mysqli_result variable, familiar to all users of either old mysql or new mysqli query - the actual source of data returned by the query.

then we are trying to fetch the selected row.

then we are checking two things at once,

whether our query returned any row

and if so, whether the password sent from the form is the same as one stored in the database using password_verify() function

the rest is the same as in your code save for two things

before redirecting a user you are supposed to write some information about them into the session, in order to recognize them on other pages

it is a good practice to add exit after sending the Location header.

Hope these explanations will be enough for your teachers

Seriously, this question should raise awareness about the state of PHP education. Most sources, online and offline, are teaching as though it is still PHP3 around, with only minor face-lifting in regard of deprecated functions. But the approach, which is wrong in so many ways, remains the same.


来源: stackexchange

问:
kubernetes timezone in POD with command and argument
I want to change timezone with command.
I know applying hostpath.

Could you know how to apply command ?

```<code>ln -snf /user/share/zoneinfor/$TZ /etc/localtime
</code>```

it works well within container. But I don't know applying with command and arguments in yaml file.

答:
In a deployment, you can do it by creating a volumeMounts in /etc/localtime and setting its values. Here is an example I have for a mariadb:</p>

```<code>apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: mariadb
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: mariadb
    spec:
      containers:
        - name: mariadb
          image: mariadb
          ports:
            - containerPort: 3306
              name: mariadb
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: password
          volumeMounts:
          - name: tz-config
            mountPath: /etc/localtime
      volumes:
      - name: tz-config
        hostPath:
           path: /usr/share/zoneinfo/Europe/Madrid
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to change timezone with command.
I know applying hostpath.

Could you know how to apply command ?

ln -snf /user/share/zoneinfor/$TZ /etc/localtime

it works well within container. But I don't know applying with command and arguments in yaml file.

Body:
In a deployment, you can do it by creating a volumeMounts in /etc/localtime and setting its values. Here is an example I have for a mariadb:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: mariadb
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: mariadb
    spec:
      containers:
        - name: mariadb
          image: mariadb
          ports:
            - containerPort: 3306
              name: mariadb
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: password
          volumeMounts:
          - name: tz-config
            mountPath: /etc/localtime
      volumes:
      - name: tz-config
        hostPath:
           path: /usr/share/zoneinfo/Europe/Madrid


问:
Interactive grid column to display full content but read only
Environment: Oracle APEX v5.1.2 / Oracle 12c

I have an interactive grid report by where I have one field that is a display only column but it actually returns an error message description that could be quite long. Since I would like to keep my IG report to one record per row, is there a means of being able to display the full contents of this field without allowing changes to the underlying column value in the database?

Some means of a tool tip or being able to drill into the field to view all info but read only.

答:
Use that column 2 times in the select statemente,

1 with substr to show in the line

2 complete that you will show it on hover (this one is a hidden column)

For Interactive Grid, go to column > Identification > Type >  HTML Expression.

Then under Settings> HTML Expression add: &COLUMN1.

It will show everything when you hover the field.

Body:
Use that column 2 times in the select statemente,

1 with substr to show in the line

2 complete that you will show it on hover (this one is a hidden column)

For Interactive Grid, go to column > Identification > Type >  HTML Expression.

Then under Settings> HTML Expression add: <span title="&COLUMN2.">&COLUMN1.</span>

It will show everything when you hover the field.


问:
Py_Initialize undefined reference
I want to add python functions in  C++ code.

I made a GUI in gtk (on the Raspberry PI) and now I want to work with a camera module which is easy to handle in python. (I want to start a video directly when I push a button.)

So I included the file Python.h

```<code>#include <python3.4m/Python.h>
#include <python3.4m/pythonrun.h>
</code>```

then I thought it should work, but when I try to compile Py_Initialize()

I get the error:

undefined reference to Py_Initialize.

I think this is strange because, when I type in, there came the selection for Py_Initialize.

答: Set the python include folder and it static lib on gcc command line and put the python dynamic lib on LD_LIBRARY_PATH. Before Py_Initialize(), do not forget to set python home with Py_SetPythonHome(). These steps must be sufficient for your code compile and run.

Title: Py_Initialize undefined reference

Body:
I want to add python functions in  C++ code.

I made a GUI in gtk (on the Raspberry PI) and now I want to work with a camera module which is easy to handle in python. (I want to start a video directly when I push a button.)

So I included the file Python.h

#include <python3.4m/Python.h>
#include <python3.4m/pythonrun.h>

then I thought it should work, but when I try to compile Py_Initialize()

I get the error:

undefined reference to Py_Initialize.

I think this is strange because, when I type in, there came the selection for Py_Initialize.


问:
Assigning a function while subsetting a data.table
Is there a specific reason why one cannot perform the following action?

```<code>v <- data.table( A = 1:2, B = vector("list", 2) )
#    A B
# 1: 1
# 2: 2

v[ A == 1, B := list( identity ) ]
# RHS of assignment is not NULL, not an an atomic vector (see ?is.atomic) and not a list column.
</code>```

Note that B is a list column. On the other hand the following is possible (though giving a warning):

```<code>v[ A == 1, B := list(2) ]
</code>```

答:
When assigning to list columns, the rule of thumb in data.table is "you always need one list() more than you would expect"

```<code>v[ A == 1, B := list(list(identity)) ]
</code>```

does what you want. Your example with the integer value worked because in this case data.table automatically coerces 2 to list(2) (but with a warning as you stated).

Body:
Is there a specific reason why one cannot perform the following action?

v <- data.table( A = 1:2, B = vector("list", 2) )
#    A B
# 1: 1
# 2: 2

v[ A == 1, B := list( identity ) ]
# RHS of assignment is not NULL, not an an atomic vector (see ?is.atomic) and not a list column.

Note that B is a list column. On the other hand the following is possible (though giving a warning):

v[ A == 1, B := list(2) ]

Body:
When assigning to list columns, the rule of thumb in data.table is "you always need one list() more than you would expect"

v[ A == 1, B := list(list(identity)) ]

does what you want. Your example with the integer value worked because in this case data.table automatically coerces 2 to list(2) (but with a warning as you stated).


问:
REST .NET Core 2.2 ~ Why Get Exception "Multipart body length limit 16384 exceeded."?
I have a .NET Core 2.2 API with a POST for a large file upload via stream.

I'm getting the exception "Multipart body length limit 16384 exceeded."

The exception appears at the line...

```<code>section = await reader.ReadNextSectionAsync();
</code>```

...at the FileStreamHelper.cs (see below).

I use postman to try the upload. My file has 10 MB.
I get this exception when I choose Body/binary.
When I choose Body/form-data instead I get the exception "Unexpected end of Stream, the content may have already been read by another component.". But I did not read the file by a different component or before. I guess binary should be right. Right?

At my Startup.cs I define

```<code>        services.Configure<FormOptions>(options =>
        {
            options.MemoryBufferThreshold = Int32.MaxValue;
            options.ValueCountLimit = 10; //default 1024
            options.ValueLengthLimit = int.MaxValue; //not recommended value
            options.MultipartBodyLengthLimit = long.MaxValue; //not recommended value
        });
</code>```

I'm using also at the Startup.cs

```<code>            app.UseWhen(context => context.Request.Path.StartsWithSegments("/File"),
            appBuilder =>
            {
                appBuilder.Run(async context =>
                {
                    context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = (long)( 2 * System.Math.Pow( 1024, 3 )); // = 2GB
                    await Task.CompletedTask;
                });
            });
</code>```

At Program.cs I use

```<code>            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = (long)(2 * System.Math.Pow(1024, 3)); // = 2 GB
            })
</code>```

At my Controller I use the Attribute  [DisableRequestSizeLimit].

What could be the reason for this exception?

How to solve this problem?

All code:
Controller

```<code>[Route("api/v1/dataPicker/fileUploadStream")]
public class FileStreamUploadController : ControllerBase
{
    [HttpPost]
    [DisableRequestSizeLimit]
    [DisableFormValueModelBinding]
    public async Task<IActionResult> Upload()
    {
        var streamer = new FileStreamingHelper();
        var paths = "c:\\temp\\";
        var tempName = Guid.NewGuid().ToString("N");
        using
            (
            var stream = System.IO.File.Create($"{paths}tempName")
            )
            await streamer.StreamFile(Request, stream);
        string from = $"{paths}tempName";
        string to = $"{paths}{streamer.FileNames.FirstOrDefault() ?? tempName}";
        System.IO.File.Move(from, to);
        return Ok($"Uploaded File {paths}{streamer.FileNames.FirstOrDefault() ?? tempName}");
    }
}
</code>```

FileStreamHelper

```<code>    public async Task<FormValueProvider> StreamFile(HttpRequest request, Stream targetStream)
    {
        if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType))
        {
            throw new Exception($"Expected a multipart request, but got {request.ContentType}");
        }

        var formAccumulator = new KeyValueAccumulator();

        var boundary = MultipartRequestHelper.GetBoundary(
            MediaTypeHeaderValue.Parse(request.ContentType),
            _defaultFormOptions.MultipartBoundaryLengthLimit);
        var reader = new MultipartReader(boundary, request.Body);

        MultipartSection section;
        try
        {
            section = await reader.ReadNextSectionAsync();
        }
        catch (Exception ex)
        {
            throw;
        }
        while (section != null) ...}

    public static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit)
    {
        var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary);
        if (StringSegment.IsNullOrEmpty(boundary))
        {
            throw new InvalidDataException("Missing content-type boundary.");
        }

        if (boundary.Length > lengthLimit)
        {
            throw new InvalidDataException(
                $"Multipart boundary length limit {lengthLimit} exceeded.");
        }

        return boundary.Value;
    }
</code>```

You need more code to see? Please tell me!

Here the postman Headers...

postman Body...

答:
I had to configure postman differently..

1) Body / form-data

2) under "KEY" enter the field with your mouse, than drop down and choose "File"

3) below Value click the new Button and choose a file

4) write into the field "KEY" the word "File"

That was not easy to find out. ;-)
All the Header data wasn't important.
Now it works.

Body:
I have a .NET Core 2.2 API with a POST for a large file upload via stream.

I'm getting the exception "Multipart body length limit 16384 exceeded."

The exception appears at the line...

section = await reader.ReadNextSectionAsync();

...at the FileStreamHelper.cs (see below).

I use postman to try the upload. My file has 10 MB.
I get this exception when I choose Body/binary.
When I choose Body/form-data instead I get the exception "Unexpected end of Stream, the content may have already been read by another component.". But I did not read the file by a different component or before. I guess binary should be right. Right?

At my Startup.cs I define

        services.Configure<FormOptions>(options =>
        {
            options.MemoryBufferThreshold = Int32.MaxValue;
            options.ValueCountLimit = 10; //default 1024
            options.ValueLengthLimit = int.MaxValue; //not recommended value
            options.MultipartBodyLengthLimit = long.MaxValue; //not recommended value
        });

I'm using also at the Startup.cs

            app.UseWhen(context => context.Request.Path.StartsWithSegments("/File"),
            appBuilder =>
            {
                appBuilder.Run(async context =>
                {
                    context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = (long)( 2 * System.Math.Pow( 1024, 3 )); // = 2GB
                    await Task.CompletedTask;
                });
            });

At Program.cs I use

            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = (long)(2 * System.Math.Pow(1024, 3)); // = 2 GB
            })

At my Controller I use the Attribute  [DisableRequestSizeLimit].

What could be the reason for this exception?

How to solve this problem?

All code:
Controller

[Route("api/v1/dataPicker/fileUploadStream")]
public class FileStreamUploadController : ControllerBase
{
    [HttpPost]
    [DisableRequestSizeLimit]
    [DisableFormValueModelBinding]
    public async Task<IActionResult> Upload()
    {
        var streamer = new FileStreamingHelper();
        var paths = "c:\\temp\\";
        var tempName = Guid.NewGuid().ToString("N");
        using
            (
            var stream = System.IO.File.Create($"{paths}tempName")
            )
            await streamer.StreamFile(Request, stream);
        string from = $"{paths}tempName";
        string to = $"{paths}{streamer.FileNames.FirstOrDefault() ?? tempName}";
        System.IO.File.Move(from, to);
        return Ok($"Uploaded File {paths}{streamer.FileNames.FirstOrDefault() ?? tempName}");
    }
}

FileStreamHelper

    public async Task<FormValueProvider> StreamFile(HttpRequest request, Stream targetStream)
    {
        if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType))
        {
            throw new Exception($"Expected a multipart request, but got {request.ContentType}");
        }

        var formAccumulator = new KeyValueAccumulator();

        var boundary = MultipartRequestHelper.GetBoundary(
            MediaTypeHeaderValue.Parse(request.ContentType),
            _defaultFormOptions.MultipartBoundaryLengthLimit);
        var reader = new MultipartReader(boundary, request.Body);

        MultipartSection section;
        try
        {
            section = await reader.ReadNextSectionAsync();
        }
        catch (Exception ex)
        {
            throw;
        }
        while (section != null) ...}

    public static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit)
    {
        var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary);
        if (StringSegment.IsNullOrEmpty(boundary))
        {
            throw new InvalidDataException("Missing content-type boundary.");
        }

        if (boundary.Length > lengthLimit)
        {
            throw new InvalidDataException(
                $"Multipart boundary length limit {lengthLimit} exceeded.");
        }

        return boundary.Value;
    }

You need more code to see? Please tell me!

Here the postman Headers...

postman Body...


问:
SQL Passing Table Date for Date
Wondering how I can pass the RECEIVEDDATETIME to the statement below. What am I missing in my SQL statement?

I added an inner join to my CALENDAR table and TESTDATA table to pass the T.RECEIVEDDATETIME as the date from the original example thanks to Mark Barinstein.

This statement gets the C.WORKDATE from my tblCalendar, but I need to have the T.RECEIVEDDATETIME to pass to get my desired "DUEDATE".

I created a "tblCalendar" because I read that it was easier to reference a Calendar for true workdays...to exclude weekends and holidays and to account for leap years. Unsure if this is the best practice, but seemed straight forward to not code for exceptions. So I created the tblCalendar that includes ALL DATEs from 2017 until 2050 and holidays. The data below only represents partially January 2019 as I haven't found a way to attach a table here:

```<code>tblCalendar (partial)
DATE        NUMDAYOFWK       DAYOFWK      HOLIDAY
01/01/2019    3              Tuesday      YES
01/02/2019    4              Wednesday
01/03/2019    5              Thursday
01/04/2019    6              Friday
01/05/2019    7              Saturday
01/06/2019    1              Sunday
01/07/2019    2              Monday
01/08/2019    3              Tuesday
01/09/2019    4              Wednesday
01/10/2019    5              Thursday
01/11/2019    6              Friday
01/12/2019    7              Saturday
01/13/2019    1              Sunday
01/14/2019    2              Monday
01/15/2019    3              Tuesday
01/16/2019    4              Wednesday
01/17/2019    5              Thursday
01/18/2019    6                  Friday
01/19/2019    7              Saturday
01/20/2019    1              Sunday
01/21/2019    2              Monday       YES
</code>```

The tblTestData table holds the core data where I reference all fields needed for my reports.

```<code>tblTestData Columns (partial) - DeliveryDays would reference the 2nd parameter BusDayAdd that was noted in the previous SQL.

ID                  RECEIVEDDATE       DeliveryDays     Address
T-20190116-255      01/16/2019          2             1234 Address
T-20190117-255      01/17/2019          2             3657 Address
T-20190118-222      01/18/2019          2             9999 Address
T-20190119-255      01/19/2019          2
T-20190120-255      01/20/2019
T-20190121-255      01/21/2019
T-20190303-1        03/03/2019
</code>```

The Desired end results would look like the following taking into account the RECEIVEDDATETIME in my tblTestData and reference the tblCalendar table to exclude weekends and holidays to give the correct due date.

```<code>ID              RECEIVEDDATE            DeliveryDays    DueDate    Address
T-20190116-255  1/16/2019                2             1/18/2019     1234 Address
T-20190117-255  1/17/2019   2   1/22/2019   3657 Address
T-20190118-222  1/18/2019   2   1/23/2019   9999 Address
T-20190119-255  1/19/2019   2   1/23/2019   10000 Address
T-20190120-255  1/20/2019   2   1/23/2019   10001 Address
T-20190121-255  1/21/2019   2   1/23/2019   10002 Address
T-20190121-256  1/22/2019   2   1/24/2019   10003 Address
T-20190303-1    3/3/2019    3   3/6/2019    10004 Address
T-20190121-257  3/15/2019   7   3/26/2019   10005 Address
</code>```

I have tried various statements by rewriting the code to wrap the SQL string to pass the table "RECEIVEDDATETIME", but each time the "DUEDATE" comes back {NULL}.

```<code>SELECT T.ID, VARCHAR_format(T.RECEIVEDDATETIME, 'MM/DD/YYYY') RECDATE,

(select VARCHAR_FORMAT(WORKDATE,'MM/DD/YYYY') DUEDATE

from

(Select
WORKDATE, T.RECEIVEDDATETIME,
sum(case when C.HOLIDAY='YES' or C.NUMDAYOFWK in (7,1) then 0 else 1 end) over  (order by C.WORKDATE) BUSDAYADD

from tblCALENDAR C

--ADDED INNER JOIN TO GET T.RECEIVEDDATETIME TO FEED AUTOMATICALLY FROM TESTDATA TABLE

INNER JOIN TESTDATA T
      ON
VARCHAR_FORMAT(C.WORKDATE, 'MM/DD/YYYY') = VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')

where C.WORKDATE > VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')) -- 1-st PARAMETER TO CAPTURE RECEIVEDDATETIME

WHERE BUSDAYADD = ? -- 2-nd parameter to add the number of days needed to be added to RECEIVEDDATETIME

order by WORKDATE --3rd Parameter
fetch first 1 row only)

FROM TESTDATA T
WHERE ID = 'T-20190303-1'
</code>```

When I run the SQL, I get {NULL} for my results for DUEDATE:

```<code>ID              RECDATE     DUEDATE
T-20190303-1    03/03/2019  {NULL}
</code>```

The results should be:

```<code> ID             RECDATE     DUEDATE
 T-20190303-1   03/03/2019  03/05/2019
</code>```

Any help is appreciated.

Title: SQL Passing Table Date for Date

Body:
Wondering how I can pass the RECEIVEDDATETIME to the statement below. What am I missing in my SQL statement?

I added an inner join to my CALENDAR table and TESTDATA table to pass the T.RECEIVEDDATETIME as the date from the original example thanks to Mark Barinstein.

This statement gets the C.WORKDATE from my tblCalendar, but I need to have the T.RECEIVEDDATETIME to pass to get my desired "DUEDATE".

I created a "tblCalendar" because I read that it was easier to reference a Calendar for true workdays...to exclude weekends and holidays and to account for leap years. Unsure if this is the best practice, but seemed straight forward to not code for exceptions. So I created the tblCalendar that includes ALL DATEs from 2017 until 2050 and holidays. The data below only represents partially January 2019 as I haven't found a way to attach a table here:

tblCalendar (partial)
DATE        NUMDAYOFWK       DAYOFWK      HOLIDAY
01/01/2019    3              Tuesday      YES
01/02/2019    4              Wednesday
01/03/2019    5              Thursday
01/04/2019    6              Friday
01/05/2019    7              Saturday
01/06/2019    1              Sunday
01/07/2019    2              Monday
01/08/2019    3              Tuesday
01/09/2019    4              Wednesday
01/10/2019    5              Thursday
01/11/2019    6              Friday
01/12/2019    7              Saturday
01/13/2019    1              Sunday
01/14/2019    2              Monday
01/15/2019    3              Tuesday
01/16/2019    4              Wednesday
01/17/2019    5              Thursday
01/18/2019    6                  Friday
01/19/2019    7              Saturday
01/20/2019    1              Sunday
01/21/2019    2              Monday       YES

The tblTestData table holds the core data where I reference all fields needed for my reports.

tblTestData Columns (partial) - DeliveryDays would reference the 2nd parameter BusDayAdd that was noted in the previous SQL.

ID                  RECEIVEDDATE       DeliveryDays     Address
T-20190116-255      01/16/2019          2             1234 Address
T-20190117-255      01/17/2019          2             3657 Address
T-20190118-222      01/18/2019          2             9999 Address
T-20190119-255      01/19/2019          2
T-20190120-255      01/20/2019
T-20190121-255      01/21/2019
T-20190303-1        03/03/2019

The Desired end results would look like the following taking into account the RECEIVEDDATETIME in my tblTestData and reference the tblCalendar table to exclude weekends and holidays to give the correct due date.

ID              RECEIVEDDATE            DeliveryDays    DueDate    Address
T-20190116-255  1/16/2019                2             1/18/2019     1234 Address
T-20190117-255  1/17/2019   2   1/22/2019   3657 Address
T-20190118-222  1/18/2019   2   1/23/2019   9999 Address
T-20190119-255  1/19/2019   2   1/23/2019   10000 Address
T-20190120-255  1/20/2019   2   1/23/2019   10001 Address
T-20190121-255  1/21/2019   2   1/23/2019   10002 Address
T-20190121-256  1/22/2019   2   1/24/2019   10003 Address
T-20190303-1    3/3/2019    3   3/6/2019    10004 Address
T-20190121-257  3/15/2019   7   3/26/2019   10005 Address

I have tried various statements by rewriting the code to wrap the SQL string to pass the table "RECEIVEDDATETIME", but each time the "DUEDATE" comes back {NULL}.

SELECT T.ID, VARCHAR_format(T.RECEIVEDDATETIME, 'MM/DD/YYYY') RECDATE,

(select VARCHAR_FORMAT(WORKDATE,'MM/DD/YYYY') DUEDATE

from

(Select
WORKDATE, T.RECEIVEDDATETIME,
sum(case when C.HOLIDAY='YES' or C.NUMDAYOFWK in (7,1) then 0 else 1 end) over  (order by C.WORKDATE) BUSDAYADD

from tblCALENDAR C

--ADDED INNER JOIN TO GET T.RECEIVEDDATETIME TO FEED AUTOMATICALLY FROM TESTDATA TABLE

INNER JOIN TESTDATA T
      ON
VARCHAR_FORMAT(C.WORKDATE, 'MM/DD/YYYY') = VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')

where C.WORKDATE > VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')) -- 1-st PARAMETER TO CAPTURE RECEIVEDDATETIME

WHERE BUSDAYADD = ? -- 2-nd parameter to add the number of days needed to be added to RECEIVEDDATETIME

order by WORKDATE --3rd Parameter
fetch first 1 row only)

FROM TESTDATA T
WHERE ID = 'T-20190303-1'

When I run the SQL, I get {NULL} for my results for DUEDATE:

ID              RECDATE     DUEDATE
T-20190303-1    03/03/2019  {NULL}

The results should be:

 ID             RECDATE     DUEDATE
 T-20190303-1   03/03/2019  03/05/2019

Any help is appreciated.

Body:
You provided inconsistent data in both tables: your calendar ends too early for all records in the tblTestData table except the 1-st one.

Let me provide absolutely the same query, which I already sent earlier to your another question.

with tblCalendar (DATE, HOLIDAY) as (values
  (date(to_date('01/16/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/17/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/18/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/19/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/20/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/21/2019', 'MM/DD/YYYY')), 'YES')

, (date(to_date('01/22/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/23/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/24/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/25/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/26/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/27/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/28/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/29/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/30/2019', 'MM/DD/YYYY')), '')
, (date(to_date('01/31/2019', 'MM/DD/YYYY')), '')
, (date(to_date('02/01/2019', 'MM/DD/YYYY')), '')
, (date(to_date('02/02/2019', 'MM/DD/YYYY')), '')
, (date(to_date('02/03/2019', 'MM/DD/YYYY')), '')
, (date(to_date('02/04/2019', 'MM/DD/YYYY')), '')
, (date(to_date('02/05/2019', 'MM/DD/YYYY')), '')

)
, tblTestData (ID, RECEIVEDDATE, DeliveryDays) as (values
  ('T-20190116-255', date(to_date('01/16/2019', 'MM/DD/YYYY')), 2)
, ('T-20190117-255', date(to_date('01/17/2019', 'MM/DD/YYYY')), 2)
, ('T-20190118-222', date(to_date('01/18/2019', 'MM/DD/YYYY')), 2)
, ('T-20190119-255', date(to_date('01/19/2019', 'MM/DD/YYYY')), 2)
, ('T-20190120-255', date(to_date('01/20/2019', 'MM/DD/YYYY')), 2)
, ('T-20190121-255', date(to_date('01/21/2019', 'MM/DD/YYYY')), 2)
, ('T-20190121-256', date(to_date('01/22/2019', 'MM/DD/YYYY')), 2)
, ('T-20190303-1'  , date(to_date('01/23/2019', 'MM/DD/YYYY')), 3)
, ('T-20190121-257', date(to_date('01/24/2019', 'MM/DD/YYYY')), 7)
)
select m.*, t.date as DUEDATE
--, dayofweek(date) as DAYOFWK, dayname(date) as DAY
from tblTestData m
, table
(
  select date
  from table
  (
    select
      date
    , sum(case when HOLIDAY='YES' or dayofweek(date) in (7,1) then 0 else 1 end) over (order by date) as dn_
    from tblCalendar t
    where t.date > m.RECEIVEDDATE
  )
  where dn_ = m.DeliveryDays
  fetch first 1 row only
) t;

The result is:

ID              RECEIVEDDATE DAYS   DUEDATE
--------------  ------------ ----   ----------
T-20190116-255    2019-01-16    2   2019-01-18
T-20190117-255    2019-01-17    2   2019-01-22
T-20190118-222    2019-01-18    2   2019-01-23
T-20190119-255    2019-01-19    2   2019-01-23
T-20190120-255    2019-01-20    2   2019-01-23
T-20190121-255    2019-01-21    2   2019-01-23
T-20190121-256    2019-01-22    2   2019-01-24
T-20190303-1      2019-01-23    3   2019-01-28
T-20190121-257    2019-01-24    7   2019-02-04


问:
Cannot get last child of div
I am trying to get the last child of a
 but I am failing. Here is the code that I use for it but it always returns undefined.

```<code>$('#output:last-child').attr('class');
</code>```

What is wrong? How can I fix it?

This is supposed to be the last element:

```<code><div class='hisout ${hisclass}'><p class="he">` + message + '</p></div>
</code>```

答:
Use the child combinator selector:
$('#output > :last-child').attr('class');

Edit: Added example

#output > :last-child {
  height: 20px;
  width: 20px;
  background: red;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output">
  <div>....</div>
  <div>....</div>
  <div>....</div>
</div></code>```

Title: Cannot get last child of div

Body:
I am trying to get the last child of a
 but I am failing. Here is the code that I use for it but it always returns undefined.

$('#output:last-child').attr('class');

What is wrong? How can I fix it?

This is supposed to be the last element:

` + message + '

Body:
Use the child combinator selector:
$('#output > :last-child').attr('class');

Edit: Added example

#output > :last-child {
  height: 20px;
  width: 20px;
  background: red;
  border: 1px solid green;
}

<div id="output">
  <div>....</div>
  <div>....</div>
  <div>....</div>
</div>


问:
CakePHP: get user info in models
I'm moving some of my find code inside models.

Previously in my controller I had

```<code>$this->Book->Review->find('first', array(
    'conditions' => array(
        'Review.book_id' => $id,
        'Review.user_id' => $this->Auth->user('id')
    )
));
</code>```

so in my Review model I put something like

```<code>function own($id) {
    $this->contain();
    $review = $this->find('first', array(
        'conditions' => array(
            'Review.book_id' => $id,
            'Review.user_id' => AuthComponent::user('id')
        )
    ));
    return $review;
}
</code>```

So I'm calling AuthComponent statically from the Model. I know I can do this for the method AuthComponent::password(), which is useful for validation. But I'm getting errors using the method AuthComponent::user(), in particular

Fatal error: Call to a member function
  check() on a non-object in
  /var/www/MathOnline/cake/libs/controller/components/auth.php
  on line 663

Is there a way to get the info about the currently logged user from a model?

答:
Create a new function in the "app_model.php" ("AppModel.php" in CakePHP 2.x), so it will be available at all models within our application:

```<code>function getCurrentUser() {
  // for CakePHP 1.x:
  App::import('Component','Session');
  $Session = new SessionComponent();

  // for CakePHP 2.x:
  App::uses('CakeSession', 'Model/Datasource');
  $Session = new CakeSession();

  $user = $Session->read('Auth.User');

  return $user;
}
</code>```

in the model:

```<code>$user = $this->getCurrentUser();
$user_id = $user['id'];
$username = $user['username'];
</code>```

ContentLicense: CC BY-SA 2.5

Title: CakePHP: get user info in models

Body:
I'm moving some of my find code inside models.

Previously in my controller I had

$this->Book->Review->find('first', array(
    'conditions' => array(
        'Review.book_id' => $id,
        'Review.user_id' => $this->Auth->user('id')
    )
));

so in my Review model I put something like

function own($id) {
    $this->contain();
    $review = $this->find('first', array(
        'conditions' => array(
            'Review.book_id' => $id,
            'Review.user_id' => AuthComponent::user('id')
        )
    ));
    return $review;
}

So I'm calling AuthComponent statically from the Model. I know I can do this for the method AuthComponent::password(), which is useful for validation. But I'm getting errors using the method AuthComponent::user(), in particular

Fatal error: Call to a member function
  check() on a non-object in
  /var/www/MathOnline/cake/libs/controller/components/auth.php
  on line 663

Is there a way to get the info about the currently logged user from a model?

Body:
Create a new function in the "app_model.php" ("AppModel.php" in CakePHP 2.x), so it will be available at all models within our application:

function getCurrentUser() {
  // for CakePHP 1.x:
  App::import('Component','Session');
  $Session = new SessionComponent();

  // for CakePHP 2.x:
  App::uses('CakeSession', 'Model/Datasource');
  $Session = new CakeSession();

  $user = $Session->read('Auth.User');

  return $user;
}

in the model:

$user = $this->getCurrentUser();
$user_id = $user['id'];
$username = $user['username'];

ContentLicense: CC BY-SA 3.0


问:
Waiting query result
I can't succeed into waiting an sql query result

This is what my Code looks like

socket.on('new', async function(information) {
  console.log("check no offer en cours");
  var checkOffer = "SELECT COUNT(*) as total FROM app__offer WHERE status_id = 1 AND profile_id = " + user.idUser;
  doInsert = false;
  con.query(checkOffer, function(err, result) {
    if (err) throw err;
    console.log(result[0].total);
    if (result[0].total == 0) {
      console.log("can insert");
      doInsert = true;
    }
  }).then(function() {
    console.log(doInsert);
    if (doInsert) {
      console.log("create offer");
      var sql = "INSERT INTO app__offer (createdAt,updatedAt, startAt, programmed, startLatitude, startLongitude, commune_id, point_id, status_id,device,profile_id) " +
        "VALUES ('" + todayDateTime + "','" + todayDateTime + "','" + todayDateTime + "'," + false + "," + user.latitude + "," + user.longitude + "," + user.idCommuneDestination + "," + user.idPoint + "," + 1 + "," + 'device' + "," + user.idUser + ")";
      console.log(sql);
      con.query(sql, function(err, result) {
        if (err) throw err;
        socket.emit('new', result);
      });
    } else {
      console.log("Cet user a déjà une offre en cours");
    }
  });
```

Issue is the doInsert Log is executed before the canInsert Log.

答:
I think that con.query() accept the callback and is also "thennable" returning a Promise.

In most cases if the callback is provided, that will be the handler of the result and it wont be passed to the Promise.

So

```<code>con.query(query, () => {
    // this code is executed when the query ends
}).then(() => {
    // this code is executed when the promise attached to .then() is resolved
    // in this case con.query() is instant resolved cause a callback parameter is given
})
</code>```

The solution is to put all in the callback OR all in the promise chain.

Title: Waiting query result

Body:
I can't succeed into waiting an sql query result

This is what my Code looks like

socket.on('new', async function(information) {
  console.log("check no offer en cours");
  var checkOffer = "SELECT COUNT(*) as total FROM app__offer WHERE status_id = 1 AND profile_id = " + user.idUser;
  doInsert = false;
  con.query(checkOffer, function(err, result) {
    if (err) throw err;
    console.log(result[0].total);
    if (result[0].total == 0) {
      console.log("can insert");
      doInsert = true;
    }
  }).then(function() {
    console.log(doInsert);
    if (doInsert) {
      console.log("create offer");
      var sql = "INSERT INTO app__offer (createdAt,updatedAt, startAt, programmed, startLatitude, startLongitude, commune_id, point_id, status_id,device,profile_id) " +
        "VALUES ('" + todayDateTime + "','" + todayDateTime + "','" + todayDateTime + "'," + false + "," + user.latitude + "," + user.longitude + "," + user.idCommuneDestination + "," + user.idPoint + "," + 1 + "," + 'device' + "," + user.idUser + ")";
      console.log(sql);
      con.query(sql, function(err, result) {
        if (err) throw err;
        socket.emit('new', result);
      });
    } else {
      console.log("Cet user a déjà une offre en cours");
    }
  });

Issue is the doInsert Log is executed before the canInsert Log.

Body:
I think that con.query() accept the callback and is also "thennable" returning a Promise.

In most cases if the callback is provided, that will be the handler of the result and it wont be passed to the Promise.

So

con.query(query, () => {
    // this code is executed when the query ends
}).then(() => {
    // this code is executed when the promise attached to .then() is resolved
    // in this case con.query() is instant resolved cause a callback parameter is given
})

The solution is to put all in the callback OR all in the promise chain.


问:
Issue sending/Receiving vector of double over TCP socket (missing data)
I am trying to send data from a vector over a TCP socket.
I'm working with a vector that I fill with values from 0 to 4999, and then send it to the socket.

Client side, I'm receiving the data into a vector, then I copy its data to another vector until I received all the data from the server.

The issue I'm facing is that when I receive my data, sometimes I will get all of it, and sometimes I will only receive the correct data from 0 to 1625 and then I get trash data until the end (please see the image below). I even received for example from 0 to 2600 correct data, then from 2601 to 3500 it's trash and finally from 3501 to 4999 it's correct again.

 (left column is line number and right column is the data).

This is the server side :

vector<double> values2;
for(int i=0; i<5000; i++)
    values2.push_back(i);
skt.sendmsg(&values2[0], values2.size()*sizeof(double));
```

<p>The function sendmsg :</p>

<pre class="lang-cpp prettyprint-override"><code>void Socket::sendmsg(const void *buf, size_t len){

    int bytes=-1;

    bytes = send(m_csock, buf, len, MSG_CONFIRM);

    cout << "Bytes sent: " << bytes << endl;

}
</code>```

Client side :

vector<double> final;
vector<double> msgrcvd(4096);

do{

    bytes += recv(sock, &msgrcvd[0], msgrcvd.size()*sizeof(double), 0);
    cout << "Bytes received: " << bytes << endl;

    //Get rid of the trailing zeros
    while(!msgrcvd.empty() && msgrcvd[msgrcvd.size() - 1] == 0){
        msgrcvd.pop_back();

    }

    //Insert buffer content into final vector
    final.insert(final.end(), msgrcvd.begin(), msgrcvd.end());

}while(bytes < sizeof(double)*5000);

//Write the received data in a txt file

for(int i=0; i<final.size(); i++)
    myfile << final[i] << endl;

myfile.close();

```

The outputs of the bytes are correct, the server outputs 40 000 when sending the data and the client also outputs 40 000 when receiving the data.

Removing the trailing zeros and then inserting the content of the buffer into a new vector is not very efficient, but I don't think it's the issue. If you have any clues on how to make it more efficient, it would be great!

I don't really know if the issue is when I send the data or when I receive it, and also I don't really get why sometimes (rarely), I get all the data.

答:
TL/DR:
Never-ever send raw data via a network socket and expect them properly received/unpacked on other side.

Detailed answer:
Network is built on top of various protocols, and this is for a reason. Once you send something, there is no warranty you counterparty is on the same OS and same software version. There is no standard how primitive types should be coded on byte level. There is no restriction how much intermittent nodes could be involved into the data delivery, and each of your send() may traverse via different routes. So, you have to formalize the way you send the data, then other party can be sure what is proper way to retrieve them from the socket.

Simplest solution: use a header before your data. So, you plan to send 5000 doubles? Then send a DWORD first, which contains 40000 inside (5k elements, 8 bytes each -> 40k) and push all your 5k doubles right after that. Then, your counterparty should read 4 bytes from the socket first, interpret it as DWORD and understand how much bytes should come then.

Next step: you may want to send not only doubles, but ints and strings as well. That way, you have to expand your header so it can indicate

Total size of further data (so called payload size)

Kind of the data (array of doubles, string, single int etc)

Advanced solution:
Take a look on ready-to-go solutions:

ProtoBuf https://developers.google.com/protocol-buffers/docs/cpptutorial

Boost.Serialization https://www.boost.org/doc/libs/1_67_0/libs/serialization/doc/index.html

Apache Thrift https://thrift.apache.org

YAS https://github.com/niXman/yas

Happy coding!

Body:
I am trying to send data from a vector over a TCP socket.
I'm working with a vector that I fill with values from 0 to 4999, and then send it to the socket.

Client side, I'm receiving the data into a vector, then I copy its data to another vector until I received all the data from the server.

The issue I'm facing is that when I receive my data, sometimes I will get all of it, and sometimes I will only receive the correct data from 0 to 1625 and then I get trash data until the end (please see the image below). I even received for example from 0 to 2600 correct data, then from 2601 to 3500 it's trash and finally from 3501 to 4999 it's correct again.

 (left column is line number and right column is the data).

This is the server side :

vector<double> values2;
for(int i=0; i<5000; i++)
    values2.push_back(i);
skt.sendmsg(&values2[0], values2.size()*sizeof(double));

The function sendmsg :

void Socket::sendmsg(const void *buf, size_t len){

    int bytes=-1;

    bytes = send(m_csock, buf, len, MSG_CONFIRM);

    cout << "Bytes sent: " << bytes << endl;

}

Client side :

vector<double> final;
vector<double> msgrcvd(4096);

do{

    bytes += recv(sock, &msgrcvd[0], msgrcvd.size()*sizeof(double), 0);
    cout << "Bytes received: " << bytes << endl;

    //Get rid of the trailing zeros
    while(!msgrcvd.empty() && msgrcvd[msgrcvd.size() - 1] == 0){
        msgrcvd.pop_back();

    }

    //Insert buffer content into final vector
    final.insert(final.end(), msgrcvd.begin(), msgrcvd.end());

}while(bytes < sizeof(double)*5000);

//Write the received data in a txt file

for(int i=0; i<final.size(); i++)
    myfile << final[i] << endl;

myfile.close();

The outputs of the bytes are correct, the server outputs 40 000 when sending the data and the client also outputs 40 000 when receiving the data.

Removing the trailing zeros and then inserting the content of the buffer into a new vector is not very efficient, but I don't think it's the issue. If you have any clues on how to make it more efficient, it would be great!

I don't really know if the issue is when I send the data or when I receive it, and also I don't really get why sometimes (rarely), I get all the data.


问:
Subtracting months in Java
I am using two string variables to store two different dates. The dates are being stored in this format(May 28, 2019) and I need to find a difference in months.I am not able to figure if I need to first convert these dates to another format before doing the subtraction.

I am using getText() to get these dates from the following location
//span[@class='expiry_date']

答:
The simplest approach is to use ChronoUnit#between method:

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMMM dd, yyyy", Locale.US );
LocalDate d1 = LocalDate.parse( "May 28, 2019", formatter );
LocalDate d2 = LocalDate.parse( "September 02, 2020", formatter );

long diff = ChronoUnit.MONTHS.between( d1, d2 );   // 15 full months
</code>```

Title: Subtracting months in Java

Body:
The simplest approach is to use ChronoUnit#between method:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMMM dd, yyyy", Locale.US );
LocalDate d1 = LocalDate.parse( "May 28, 2019", formatter );
LocalDate d2 = LocalDate.parse( "September 02, 2020", formatter );

long diff = ChronoUnit.MONTHS.between( d1, d2 );   // 15 full months


问:
php preg_match_all find gettext language strings in a string
Hello

So i am trying to find multi gettext language string in a string in php.

Like so:

```<code>$test = "
    sadsssss_('test1');

    sdfsd _('test2');
";
preg_match_all("/_('(.*?)')/s", $test, $matches);
echo '```';
print_r($matches);
echo '```';
</code>```

This example dont work, but then again i dont know much about patterns.

Tried googling it, was unable to find a pattern i could use.

Thanks.

答:
Your original expression is just fine, we just might want to add a m flag:

```<code>\('(.+?)'\)
</code>```

Test

```<code>$re = '/\(\'(.+?)\'\)/m';
$str = '    sadsssss_(\'test1\');

    sdfsd _(\'test2\');
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

foreach ($matches as $key => $value) {
    echo $value[1] . "\n";
}
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Body:
Hello

So i am trying to find multi gettext language string in a string in php.

Like so:

$test = "
    sadsssss_('test1');

    sdfsd _('test2');
";
preg_match_all("/_('(.*?)')/s", $test, $matches);
echo '
';
print_r($matches);
echo '
';

This example dont work, but then again i dont know much about patterns.

Tried googling it, was unable to find a pattern i could use.

Thanks.

Body:
Your original expression is just fine, we just might want to add a m flag:

\('(.+?)'\)

Test

$re = '/\(\'(.+?)\'\)/m';
$str = '    sadsssss_(\'test1\');

    sdfsd _(\'test2\');
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

foreach ($matches as $key => $value) {
    echo $value[1] . "\n";
}

DEMO

RegEx Circuit

jex.im visualizes regular expressions:


问:
How to test if a category already exists? PrestaShop
I get the category from other database web service and I put them on PrestaShop when I refresh the file to add categories I wanna make sure if the category id exists, if exist I wanna update the category.</p>

```<code>$XMLRQString = '<?xml version="1.0" encoding="utf-8"?>'.
    '<x:Winmax4GetFamiliesRQ xmlns:x="urn:Winmax4GetFamiliesRQ">'.
    '</x:Winmax4GetFamiliesRQ >';

$return = $client->GetFamilies($Params);
$XMLRSString = new SimpleXMLElement($return->GetFamiliesResult);
if ($XMLRSString->Code > 0)
    echo '</br>Error: '.$XMLRSString->Code." ".$XMLRSString->Message;
else{

        foreach ($XMLRSString->Families->Family as $family)
        {

            $category = new Category();

            $category->id = $family->Code;

            $category->force_id = true;

            $category->is_root_category = false;

            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

            $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

            $category->add();

        }
    }
</code>```

答:
This would work:

```<code>$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$home = (int)Configuration::get('PS_HOME_CATEGORY');
$category = new Category((int)$family->Code);
$category->is_root_category = false;
$category->name = array($default_lang => $family->Designation);
$category->link_rewrite = array($default_lang => $family->Code);
$category->id_parent = $home;
$category->save();
</code>```

Also, you can always check if an object is valid using the Validate::isLoadedObject() static method.

Body:
I get the category from other database web service and I put them on PrestaShop when I refresh the file to add categories I wanna make sure if the category id exists, if exist I wanna update the category.

$XMLRQString = '<?xml version="1.0" encoding="utf-8"?>'.
    '<x:Winmax4GetFamiliesRQ xmlns:x="urn:Winmax4GetFamiliesRQ">'.
    '</x:Winmax4GetFamiliesRQ >';

$return = $client->GetFamilies($Params);
$XMLRSString = new SimpleXMLElement($return->GetFamiliesResult);
if ($XMLRSString->Code > 0)
    echo '
Error: '.$XMLRSString->Code." ".$XMLRSString->Message;
else{

        foreach ($XMLRSString->Families->Family as $family)
        {

            $category = new Category();

            $category->id = $family->Code;

            $category->force_id = true;

            $category->is_root_category = false;

            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

            $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

            $category->add();

        }
    }

Body:
This would work:

$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$home = (int)Configuration::get('PS_HOME_CATEGORY');
$category = new Category((int)$family->Code);
$category->is_root_category = false;
$category->name = array($default_lang => $family->Designation);
$category->link_rewrite = array($default_lang => $family->Code);
$category->id_parent = $home;
$category->save();

Also, you can always check if an object is valid using the Validate::isLoadedObject() static method.


问:
Why can't a nullable int be implicitly conversion to an int ? Technical reason or design choice?
In C#, there is no implicit conversion from the int? type to the int type.

I have defined the following implicit operator

```<code>namespace System
{
    public partial struct Int32
    {
        public static implicit operator Int32(int? v)
        {
            return (Int32)(v ?? 0);
        }
    }
}
</code>```

Which allows me to compile the following code

```<code>int? nullableInt = 0;
Int32 regularInt = nullableInt;
</code>```

but if I define regularInt as an int instead of Int32 I get the following error

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

I expected int and Int32 to be interchangeable but the C# language clearly hasn't been built with this functionality in mind.

Is there a technical reason behind the impossibility of defining this operation, is it a decision made to prevent potential code smell ?

I'm aware that defining such an implicit operator could result in some very unexpected behavior, as the conversion from a null value to a 0 integer doesn't make sense in every situation. This question is more about "why can't it be done" than "why doing it is a really  bad idea"

答:
As documented here, implicit type conversions are only possible, as long as the conversion is save.

Example from before

```<code>// Implicit conversion. A long can
// hold any value an int can hold, and more!
int num = 2147483647;
long bigNum = num;
</code>```

In your case, int or Int32 may be savely converted to int? but not vice-versa.

The same applies to type-hierarchy

```<code>class A {}

class B : A {}

class C : A {}

A var1 = new A(); // Compiles
A var2 = new B(); // Compiles (implicit cast)
B var3 = new B(); // Compiles

// need for explicit cast because instance2 can could also be A or C
B var4 = (B) instance2;

// Throws InvalidCastException
C var5 = (C) instance2;
</code>```

Body:
In C#, there is no implicit conversion from the int? type to the int type.

I have defined the following implicit operator

namespace System
{
    public partial struct Int32
    {
        public static implicit operator Int32(int? v)
        {
            return (Int32)(v ?? 0);
        }
    }
}

Which allows me to compile the following code

int? nullableInt = 0;
Int32 regularInt = nullableInt;

but if I define regularInt as an int instead of Int32 I get the following error

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

I expected int and Int32 to be interchangeable but the C# language clearly hasn't been built with this functionality in mind.

Is there a technical reason behind the impossibility of defining this operation, is it a decision made to prevent potential code smell ?

I'm aware that defining such an implicit operator could result in some very unexpected behavior, as the conversion from a null value to a 0 integer doesn't make sense in every situation. This question is more about "why can't it be done" than "why doing it is a really  bad idea"

Body:
As documented here, implicit type conversions are only possible, as long as the conversion is save.

Example from before

// Implicit conversion. A long can
// hold any value an int can hold, and more!
int num = 2147483647;
long bigNum = num;

In your case, int or Int32 may be savely converted to int? but not vice-versa.

The same applies to type-hierarchy

class A {}

class B : A {}

class C : A {}

A var1 = new A(); // Compiles
A var2 = new B(); // Compiles (implicit cast)
B var3 = new B(); // Compiles

// need for explicit cast because instance2 can could also be A or C
B var4 = (B) instance2;

// Throws InvalidCastException
C var5 = (C) instance2;


问:
Make optional property in the formgroup
I am trying to create a formgroup with optional property. imageName should be optional.

Component

```<code>this.formbuilder.group({
      details:[''],
      date:[''],
      imageName : ['']
    })
</code>```

答:
Try with generating a formGroup like this

formGroup: FormGroup;

this.formGroup = new FormGroup({
      details: new FormControl(null, [Validators.required]),
      date: new FormControl(null, [Validators.required]),
      imageName: new FormControl(null)
    });
```

<p>And in your HTML, you can set each input with <code>formControlName</code></p>

<pre class="lang-html prettyprint-override"><code><input type="text" formControlName="details">
</code>```

Title: Make optional property in the formgroup

Body:
I am trying to create a formgroup with optional property. imageName should be optional.

Component

this.formbuilder.group({
      details:[''],
      date:[''],
      imageName : ['']
    })

Body:
Try with generating a formGroup like this

formGroup: FormGroup;

this.formGroup = new FormGroup({
      details: new FormControl(null, [Validators.required]),
      date: new FormControl(null, [Validators.required]),
      imageName: new FormControl(null)
    });

And in your HTML, you can set each input with formControlName

<input type="text" formControlName="details">


问:
php address request
i have this request method:

```<code>if (!$_REQUEST['0'])  {
    echo "Address missing...";
    die();
} else {
    code
    code etc.
}
</code>```

And address is: http://localhost/api.php?0=address

If I open: api.php?0=0 I should get another error which says address doesn't correct. But I get Address missing... In my opinion something wrong with:

```<code>if (!$_REQUEST['0'])
</code>```

Any ideas?

答:
```<code>  if (empty ($_REQUEST['0']))
  {
      echo "Address doesn't provided...";
      die();
  } else {
     code
     code etc.
</code>```

Title: php address request

Body:
i have this request method:

if (!$_REQUEST['0'])  {
    echo "Address missing...";
    die();
} else {
    code
    code etc.
}

And address is: http://localhost/api.php?0=address

If I open: api.php?0=0 I should get another error which says address doesn't correct. But I get Address missing... In my opinion something wrong with:

if (!$_REQUEST['0'])

Any ideas?


问:
Python: 'ValueError: too many values to unpack (expected 2)' for a username password system
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

```<code>database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse
</code>```

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

答: Check all the lines in your file.txt file. There might be a case where the occurrence of ":" is more than one. Since, you are unpacking the list into two variables. If there are more than two values in the resulting list on line 4, i.e. line.strip().split(":"), it will raise an exception.

Body:
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked


问:
After configuring for docker, minikube doesn't run anymore
I user minikube on windows. It was working perfectly, but my "docker-for-desktop" wasn't.

After running the command BCDEDIT /Set {current} hypervisorlaunchtype auto my Docker app started to work but everytime I try to start my minikube VM it shows me an error about "VBOX_VERRR_VMW_NO_VMX".

When i run the BCDEDIT /Set {current} hypervisorlaunchtype off minikube works again, but DOcker doesn't. And I docker working for build the docker images, and the minikube for hosting them.

Someone can help me ?

答:
Did you follow official guides for Docker for Windows and Minikube? I wrote some answers about particular scenarios with Windows, Docker for Windows and minikube. Try reading this answer or this. They should be enough to solve the problems.

If you still have issues try to describe what steps you have made that led you to the error.


问:
Cause: buildOutput.apkData must not be null
My android application using Kotlin is throwing this exception when I try to Run 'app' in the emulator o in my cellphone. When I build my project it runs well, with no errors.

I am using:

SDK 28 (Android 9.0 (Pie))

Gradle 5.1.1

Gradle Plugin 3.5.0-alpha03

Kotlin 1.3.10

Java 1.8.0_151

OSX 10.13.2

```<code>    org.gradle.internal.exceptions.LocationAwareException: buildOutput.apkData must not be null
        at org.gradle.initialization.exception.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:99)
        at org.gradle.initialization.exception.DefaultExceptionAnalyser.collectFailures(DefaultExceptionAnalyser.java:65)
        at org.gradle.initialization.exception.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:39)
        at org.gradle.initialization.exception.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:29)
        at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:194)
        at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:141)
        ...
    Caused by: java.lang.IllegalStateException: buildOutput.apkData must not be null
        at com.android.build.gradle.internal.ide.EarlySyncBuildOutput$Companion$load$2.invoke(EarlySyncBuildOutput.kt:103)
        at com.android.build.gradle.internal.ide.EarlySyncBuildOutput$Companion$load$2.invoke(EarlySyncBuildOutput.kt:67)
        at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:174)
        at kotlin.sequences.SequencesKt___SequencesKt.toCollection(_Sequences.kt:691)
        at kotlin.sequences.SequencesKt___SequencesKt.toMutableList(_Sequences.kt:721)
        at kotlin.sequences.SequencesKt___SequencesKt.toList(_Sequences.kt:712)
        ...
</code>```

答: I was using Android Studio 3.5 beta 2 and I was having the exact same error but only on my release build. After trying every other solution I found, the only way I was able to compile again was to go back to Android Studio 3.4.</p>

Body:
My android application using Kotlin is throwing this exception when I try to Run 'app' in the emulator o in my cellphone. When I build my project it runs well, with no errors.

I am using:

SDK 28 (Android 9.0 (Pie))

Gradle 5.1.1

Gradle Plugin 3.5.0-alpha03

Kotlin 1.3.10

Java 1.8.0_151

OSX 10.13.2

    org.gradle.internal.exceptions.LocationAwareException: buildOutput.apkData must not be null
        at org.gradle.initialization.exception.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:99)
        at org.gradle.initialization.exception.DefaultExceptionAnalyser.collectFailures(DefaultExceptionAnalyser.java:65)
        at org.gradle.initialization.exception.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:39)
        at org.gradle.initialization.exception.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:29)
        at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:194)
        at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:141)
        ...
    Caused by: java.lang.IllegalStateException: buildOutput.apkData must not be null
        at com.android.build.gradle.internal.ide.EarlySyncBuildOutput$Companion$load$2.invoke(EarlySyncBuildOutput.kt:103)
        at com.android.build.gradle.internal.ide.EarlySyncBuildOutput$Companion$load$2.invoke(EarlySyncBuildOutput.kt:67)
        at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:174)
        at kotlin.sequences.SequencesKt___SequencesKt.toCollection(_Sequences.kt:691)
        at kotlin.sequences.SequencesKt___SequencesKt.toMutableList(_Sequences.kt:721)
        at kotlin.sequences.SequencesKt___SequencesKt.toList(_Sequences.kt:712)
        ...


问:
Where i can check the main standards for making android user interfaces?
i need a link where i can read and understand the main standards to follow where making android user interfaces

i can't find it on google

thanks

答: I would imagine that a lot (but obviously not all by any means) of Apple's iOS human interface guidelines may be transferable to Android HI design. Might be worth a read.</p>


问:
Response content types in swagger, .net core api
I had some problems to render my api response as xml in swagger, finally I got it to render in the correct format, application/xml with my first action below, but it still says I can only render it as application/json.

I tried to remove application/json from Produces attribute, but still shows only application/json.

Any ideas why its behaving in this way?

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddMvcOptions(o => o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()));
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.RoutePrefix = "";
    });
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey" });
        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
            { "Bearer", Enumerable.Empty<string>() },
        });
    });
}
</code>```

And action:

```<code>[Produces("application/json", "application/xml")]
public ContentResult GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return Content(result, "application/xml", Encoding.UTF8);
}
</code>```

Same result with:

```<code>[Produces("application/json", "application/xml")]
public IActionResult GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return Content(result, "application/xml", Encoding.UTF8);
}
</code>```

Results in:

When clicking excecute I get the result in the correct XML-format though.

While this:

```<code>[Produces("application/json", "application/xml")]
public string GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return result;
}
</code>```

Or this:

```<code>[Produces("application/json", "application/xml")]
public List<Address> GetByAddreses()
{
    string result = _soapApi.GetResults();
    return result;
}
</code>```

Results in:

I am not able to return a list of parsed objects due to different data-structure returned for different parameters. So at this point I only receive raw soap xml-data and have to parse/deserialize it. But to actually be able to see the raw response I also need to show it as Content from string with content-type application/xml. And it gives me a nice output like (even though it still says only application/json is possible):

To summarize it:

I did not get it work with response content-type showing the correct content-type (in "Response Content Type" -filter) when a string was parsed to its actual format like below. Even though this results in the correct output for application/xml that was the most important (see screenshot above);

```<code>[Produces("application/json", "application/xml")]
public ContentResult GetByAddress(string address)
{
    return Content("<xml>...</xml>", "application/xml", Encoding.UTF8);
}
</code>```

答:
I am testing a web api application developed with asp.net core2.2.

I installed the Microsoft.AspNetCore.Mvc.Formatters.Xml nuget package.

Then I updated the ConfigureServices method within the Startup.cs by adding.

services.AddMvc().AddXmlSerializerFormatters();
```

And my web api swagger is working as I needed with the dropdown showing both (json and xml) and resulting the expected format.
If you need more information please visit: https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

Body:
I had some problems to render my api response as xml in swagger, finally I got it to render in the correct format, application/xml with my first action below, but it still says I can only render it as application/json.

I tried to remove application/json from Produces attribute, but still shows only application/json.

Any ideas why its behaving in this way?

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddMvcOptions(o => o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()));
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.RoutePrefix = "";
    });
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey" });
        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
            { "Bearer", Enumerable.Empty<string>() },
        });
    });
}

And action:

[Produces("application/json", "application/xml")]
public ContentResult GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return Content(result, "application/xml", Encoding.UTF8);
}

Same result with:

[Produces("application/json", "application/xml")]
public IActionResult GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return Content(result, "application/xml", Encoding.UTF8);
}

Results in:

When clicking excecute I get the result in the correct XML-format though.

While this:

[Produces("application/json", "application/xml")]
public string GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return result;
}

Or this:

[Produces("application/json", "application/xml")]
public List<Address> GetByAddreses()
{
    string result = _soapApi.GetResults();
    return result;
}

Results in:

I am not able to return a list of parsed objects due to different data-structure returned for different parameters. So at this point I only receive raw soap xml-data and have to parse/deserialize it. But to actually be able to see the raw response I also need to show it as Content from string with content-type application/xml. And it gives me a nice output like (even though it still says only application/json is possible):

To summarize it:

I did not get it work with response content-type showing the correct content-type (in "Response Content Type" -filter) when a string was parsed to its actual format like below. Even though this results in the correct output for application/xml that was the most important (see screenshot above);

[Produces("application/json", "application/xml")]
public ContentResult GetByAddress(string address)
{
    return Content("<xml>...</xml>", "application/xml", Encoding.UTF8);
}

Body:
I am testing a web api application developed with asp.net core2.2.

I installed the Microsoft.AspNetCore.Mvc.Formatters.Xml nuget package.

Then I updated the ConfigureServices method within the Startup.cs by adding.

services.AddMvc().AddXmlSerializerFormatters();

And my web api swagger is working as I needed with the dropdown showing both (json and xml) and resulting the expected format.
If you need more information please visit: https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1


问:
HTML CSS How to stop a table cell from expanding
I have a table which is built with the contents coming from a returned dataset.  What I want to do is stop a 'description' cell from expanding over 280px wide, no matter what the content length (its s string).  I have tried:

```<code><td align="left" valign="top" style="overflow:hidden;" nowrap="nowrap" width="280px" >
</code>```

But this doesn't seem to work.  I don't want it to wrap, nor do I want anything over 280px to be displayed.

答:
To post Chris Dutrow's comment here as answer:

```<code>style="table-layout:fixed;"
</code>```

in the style of the table itself is what worked for me. Thanks Chris!

Full example:

```<code><table width="55" height="55" border="0" cellspacing="0" cellpadding="0" style="border-radius:50%; border:0px solid #000000;table-layout:fixed" align="center" bgcolor="#152b47">
  <tbody>
    <td style="color:#ffffff;font-family:TW-Averta-Regular,Averta,Helvetica,Arial;font-size:11px;overflow:hidden;width:55px;text-align:center;valign:top;whitespace:nowrap;">

     Your table content here

    </td>
  </tbody>
</table>
</code>```

Body:
I have a table which is built with the contents coming from a returned dataset.  What I want to do is stop a 'description' cell from expanding over 280px wide, no matter what the content length (its s string).  I have tried:

But this doesn't seem to work.  I don't want it to wrap, nor do I want anything over 280px to be displayed.

Body:
To post Chris Dutrow's comment here as answer:

style="table-layout:fixed;"

in the style of the table itself is what worked for me. Thanks Chris!

Full example:

<table width="55" height="55" border="0" cellspacing="0" cellpadding="0" style="border-radius:50%; border:0px solid #000000;table-layout:fixed" align="center" bgcolor="#152b47">
  <tbody>
    <td style="color:#ffffff;font-family:TW-Averta-Regular,Averta,Helvetica,Arial;font-size:11px;overflow:hidden;width:55px;text-align:center;valign:top;whitespace:nowrap;">

     Your table content here

    </td>
  </tbody>
</table>


问:
print the unique values in every column in a pandas dataframe
I have a dataframe (df) and want to print the unique values from each column in the dataframe.

I need to substitute the variable (i) [column name] into the print statement

```<code>column_list = df.columns.values.tolist()
for column_name in column_list:
    print(df."[column_name]".unique()
</code>```

Update

When I use this: I get "Unexpected EOF Parsing" with no extra details.

```<code>column_list = sorted_data.columns.values.tolist()
for column_name in column_list:
      print(sorted_data[column_name].unique()
</code>```

What is the difference between your syntax YS-L (above) and the below:

```<code>for column_name in sorted_data:
      print(column_name)
      s = sorted_data[column_name].unique()
      for i in s:
        print(str(i))
</code>```

答:
The code below could provide you a list of unique values for each field, I find it very useful when you want to take a deeper look at the data frame:

```<code>for col in list(df):
    print(col)
    print(df[col].unique())
</code>```

You can also sort the unique values if you want them to be sorted:

```<code>import numpy as np
for col in list(df):
    print(col)
    print(np.sort(df[col].unique()))
</code>```

Body:
I have a dataframe (df) and want to print the unique values from each column in the dataframe.

I need to substitute the variable (i) [column name] into the print statement

column_list = df.columns.values.tolist()
for column_name in column_list:
    print(df."[column_name]".unique()

Update

When I use this: I get "Unexpected EOF Parsing" with no extra details.

column_list = sorted_data.columns.values.tolist()
for column_name in column_list:
      print(sorted_data[column_name].unique()

What is the difference between your syntax YS-L (above) and the below:

for column_name in sorted_data:
      print(column_name)
      s = sorted_data[column_name].unique()
      for i in s:
        print(str(i))

Body:
The code below could provide you a list of unique values for each field, I find it very useful when you want to take a deeper look at the data frame:

for col in list(df):
    print(col)
    print(df[col].unique())

You can also sort the unique values if you want them to be sorted:

import numpy as np
for col in list(df):
    print(col)
    print(np.sort(df[col].unique()))


问:
How to write a column name with dot (".") in the SELECT clause?
I'm trying to write a column name using "." with no success

sample:

```<code>SELECT PrmTable.Value = MAX(Value)
FROM TempTable
</code>```

or

```<code>SELECT MAX(Value) AS PrmTable.Value
FROM TempTable
</code>```

Any idea ?

答:
I would not recommend you use field names which always require you to enclose the name in brackets, it becomes a pain.

Also the period is used in SQL Server to denote schema and database name separators. Using your field name the full name for a field becomes:

```<code>[DatabaseName].[SchemaName].[TableName].[FieldName.WithPeriod]
</code>```

That just looks odd and would probably confuse other DBAs. Use an underscore to separate words in your field names, it's a much more common style:

```<code>[DatabaseName].[SchemaName].[TableName].[FieldName_WithUnderscore]
</code>```

Body:
I'm trying to write a column name using "." with no success

sample:

SELECT PrmTable.Value = MAX(Value)
FROM TempTable

or

SELECT MAX(Value) AS PrmTable.Value
FROM TempTable

Any idea ?

Body:
I would not recommend you use field names which always require you to enclose the name in brackets, it becomes a pain.

Also the period is used in SQL Server to denote schema and database name separators. Using your field name the full name for a field becomes:

[DatabaseName].[SchemaName].[TableName].[FieldName.WithPeriod]

That just looks odd and would probably confuse other DBAs. Use an underscore to separate words in your field names, it's a much more common style:

[DatabaseName].[SchemaName].[TableName].[FieldName_WithUnderscore]


问:
Check is the structure is empty (python)
I use a special class of objects and some method which returns me structures such as:

```<code>{'items': [{'_from': 12,
            'bla': 3713,
            'ff': 0.0,
            'd': 45755,
            'fdef': 1536},
           {'_from': None,
            'bla': 3712,
            'ff': 0.0,
            'd': 45838,
            'fdef': 1536}]}
</code>```

Sometimes this structure is empty and then I get the following;

```<code>{'items': []}
</code>```

How can I check in my program if the returning structure is empty? It has no such attributes as length. It seems that I can access single elements of the structure only via the Loop (so nothing like structure['items']['bla'] is possible):

```<code>for k in myStructure.items:
         idd=k.bla
</code>```

How can I perform such a check in an elegant way?

答:
Empty lists evaluate to False when used in an if-statement.

```<code>if myStructure.items:
    for k in myStructure.items:
         idd=k.bla
</code>```

Example:

```<code>>>> if []:
    print('here')

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

Body:
I use a special class of objects and some method which returns me structures such as:

{'items': [{'_from': 12,
            'bla': 3713,
            'ff': 0.0,
            'd': 45755,
            'fdef': 1536},
           {'_from': None,
            'bla': 3712,
            'ff': 0.0,
            'd': 45838,
            'fdef': 1536}]}

Sometimes this structure is empty and then I get the following;

{'items': []}

How can I check in my program if the returning structure is empty? It has no such attributes as length. It seems that I can access single elements of the structure only via the Loop (so nothing like structure['items']['bla'] is possible):

for k in myStructure.items:
         idd=k.bla

How can I perform such a check in an elegant way?

Body:
Empty lists evaluate to False when used in an if-statement.

if myStructure.items:
    for k in myStructure.items:
         idd=k.bla

Example:

>>> if []:
    print('here')

>>>
>>>


问:
Minimalist cocoa app does not appear in dock
As part of a broader project, I am implementing my own window management for a Cocoa app. I'm using the "objective c++" flag when compiling because much of the codebase is in c++.

I have put some stub code in my main.cpp to get a window to open but the window icon is not going in the applications dock and isn't raising itself to the front of the window stack.

I have this bit in my main.cpp :

main.cpp

    TestAppDelegate* appDel = [TestAppDelegate alloc];
    [NSApp setDelegate:appDel];

    NSApplication* app = [NSApplication sharedApplication];

    app.delegate = appDel;
    [app run];

    return NSApplicationMain(argc, argv);
```

<p>And my AppDelegate object looks like this </p>

<p>test.h</p>

<pre class="lang-c prettyprint-override"><code>@interface TestAppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate> {

NSWindow * win;

}
@end
</code>```

test.cpp

#include "test.h"

@implementation TestAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application

    NSRect rect;
    rect.origin.x = 0;
    rect.origin.y = 0;
    rect.size.width = 500;
    rect.size.height = 500;

    unsigned int style = (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable);

    NSWindow* win = [[NSWindow alloc] initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:FALSE];

    NSButton* butan = [NSButton buttonWithTitle:@"SomeText" target:nil action:nil];
    butan.frame = NSMakeRect(20, 20, 100, 30);
    butan.title = [NSString stringWithUTF8String:"Things"];
    [win.contentView addSubview:butan];
    [win makeKeyAndOrderFront:nil];

}

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender {
    return YES;
}

@end
```

It's a bunch of useless test code for now but the window opens up although it appears behind the Xcode editor. The button is responsive to clicks and the window is not frozen since I can move it around freely.

My problem is that the window doesn't seem "active". It's not in the dock, I can't "command+tab+ to reach it and when I click on it and give it focus the top-left buttons don't light up like the other applications.

What am I forgetting here ?

As a reference, I am looking at the source of SDL, which my project mainly use except for this little experiment. If I start a graphical window with SDL, which uses Cocoa as its driver. I will see the window on the dock and it will be more "active" than my little window.

答:
Since your program is not a bundled app, you'll need to configure its "activation policy" to make it show up in the Dock and Command-Tab switcher:

```<code>[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
</code>```

You'll also want to activate it on launch:

```<code>[NSApp activateIgnoringOtherApps:YES];
</code>```

Body:
As part of a broader project, I am implementing my own window management for a Cocoa app. I'm using the "objective c++" flag when compiling because much of the codebase is in c++.

I have put some stub code in my main.cpp to get a window to open but the window icon is not going in the applications dock and isn't raising itself to the front of the window stack.

I have this bit in my main.cpp :

main.cpp

    TestAppDelegate* appDel = [TestAppDelegate alloc];
    [NSApp setDelegate:appDel];

    NSApplication* app = [NSApplication sharedApplication];

    app.delegate = appDel;
    [app run];

    return NSApplicationMain(argc, argv);

And my AppDelegate object looks like this

test.h

@interface TestAppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate> {

NSWindow * win;

}
@end

test.cpp

#include "test.h"

@implementation TestAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application

    NSRect rect;
    rect.origin.x = 0;
    rect.origin.y = 0;
    rect.size.width = 500;
    rect.size.height = 500;

    unsigned int style = (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable);

    NSWindow* win = [[NSWindow alloc] initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:FALSE];

    NSButton* butan = [NSButton buttonWithTitle:@"SomeText" target:nil action:nil];
    butan.frame = NSMakeRect(20, 20, 100, 30);
    butan.title = [NSString stringWithUTF8String:"Things"];
    [win.contentView addSubview:butan];
    [win makeKeyAndOrderFront:nil];

}

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender {
    return YES;
}

@end

It's a bunch of useless test code for now but the window opens up although it appears behind the Xcode editor. The button is responsive to clicks and the window is not frozen since I can move it around freely.

My problem is that the window doesn't seem "active". It's not in the dock, I can't "command+tab+ to reach it and when I click on it and give it focus the top-left buttons don't light up like the other applications.

What am I forgetting here ?

As a reference, I am looking at the source of SDL, which my project mainly use except for this little experiment. If I start a graphical window with SDL, which uses Cocoa as its driver. I will see the window on the dock and it will be more "active" than my little window.

Body:
Since your program is not a bundled app, you'll need to configure its "activation policy" to make it show up in the Dock and Command-Tab switcher:

[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];

You'll also want to activate it on launch:

[NSApp activateIgnoringOtherApps:YES];


问:
Recoding specific column values using reference list
My dataframe looks like this

```<code>data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))
</code>```

And I have a reference list that looks like this -

```<code>ref=list(Male=1,Female=2)
</code>```

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

```<code>do.call(dplyr::recode, c(list(data), ref))
</code>```

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

答:
Surprisingly, that one works as well:</p>

```<code>data$Gender <- ref[as.character(data$Gender)]

#> data
#    ID Gender
# 1   1      1
# 2   2      2
# 3   3      2
# 4   4      2
# 5   5      1
# 6   6      2
# 7   7      1
# 8   8      1
# 9   9      2
# 10 10      2
</code>```

Body:
My dataframe looks like this

data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))

And I have a reference list that looks like this -

ref=list(Male=1,Female=2)

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

do.call(dplyr::recode, c(list(data), ref))

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

Body:
Surprisingly, that one works as well:

data$Gender <- ref[as.character(data$Gender)]

#> data
#    ID Gender
# 1   1      1
# 2   2      2
# 3   3      2
# 4   4      2
# 5   5      1
# 6   6      2
# 7   7      1
# 8   8      1
# 9   9      2
# 10 10      2


问:
Temporaries problem in C++
I have this piece of code that prints the content of a directory using Boost.Filesystem:

```<code>class Shell {
private:
    const string& command;
    const path& firstPath;
    const path& secondPath;
public:
    // constructor
    Shell(const string& _command, const path& _firstPath, const path& _secondPath = path()): command(_command), firstPath(_firstPath), secondPath(_secondPath) {}

    //destructor
    ~Shell() {}

    //execute commands
    void executeCommand()
    {
        if(command.compare("ls"))
        {
            ls();
        }
    }

    void ls()
    {
        if(exists(firstPath))
        {
            vector<path> vecPath;

            copy(directory_iterator(firstPath), directory_iterator(), back_inserter(vecPath));
            sort(vecPath.begin(), vecPath.end());
            for(vector<path>::iterator it = vecPath.begin(); it != vecPath.end(); ++it)
            {
                cout << *it << endl;
            }
        }
    }
};

int main(int argc, char** argv)
{
    path Path = "c:\\workspace";
    Shell shell("ls", Path); // GOOD
    // Shell shell("ls", "c:\\workspace");  BAD creates temporary !!
    shell.executeCommand();
}
</code>```

If I send my second argument direclty as a const char* I know that it will create a temporary and my constructor argument will only be visible in the constructor, then its lost, because of the reference to temporary.

My question is, why isnt the same thing happening to the first argument, the string, because I am sending him also as a const char* directly, but the value isnt lost outside of the constructor ?

答:
```<code>Shell shell("ls", Path); // BAD - just happens to work as you expected.
</code>```

Undefined Behavior - Anything can happen, including acting like you expect. The memory allocated by the temporary just happened to not be overwritten in your case.

Title: Temporaries problem in C++

Body:
I have this piece of code that prints the content of a directory using Boost.Filesystem:

class Shell {
private:
    const string& command;
    const path& firstPath;
    const path& secondPath;
public:
    // constructor
    Shell(const string& _command, const path& _firstPath, const path& _secondPath = path()): command(_command), firstPath(_firstPath), secondPath(_secondPath) {}

    //destructor
    ~Shell() {}

    //execute commands
    void executeCommand()
    {
        if(command.compare("ls"))
        {
            ls();
        }
    }

    void ls()
    {
        if(exists(firstPath))
        {
            vector<path> vecPath;

            copy(directory_iterator(firstPath), directory_iterator(), back_inserter(vecPath));
            sort(vecPath.begin(), vecPath.end());
            for(vector<path>::iterator it = vecPath.begin(); it != vecPath.end(); ++it)
            {
                cout << *it << endl;
            }
        }
    }
};

int main(int argc, char** argv)
{
    path Path = "c:\\workspace";
    Shell shell("ls", Path); // GOOD
    // Shell shell("ls", "c:\\workspace");  BAD creates temporary !!
    shell.executeCommand();
}

If I send my second argument direclty as a const char* I know that it will create a temporary and my constructor argument will only be visible in the constructor, then its lost, because of the reference to temporary.

My question is, why isnt the same thing happening to the first argument, the string, because I am sending him also as a const char* directly, but the value isnt lost outside of the constructor ?

Body:
Shell shell("ls", Path); // BAD - just happens to work as you expected.

Undefined Behavior - Anything can happen, including acting like you expect. The memory allocated by the temporary just happened to not be overwritten in your case.


答:
Because the default value of int is 0 but int? by default has a null value which is not a valid int value and will result to an exception.

For instance,
int x; // declaration result to 0
int? x; // declaration results to null (not valid int value)

Title: Why can't a nullable int be implicitly conversion to an int ? Technical reason or design choice?

Body:
In C#, there is no implicit conversion from the int? type to the int type.

I have defined the following implicit operator

namespace System
{
    public partial struct Int32
    {
        public static implicit operator Int32(int? v)
        {
            return (Int32)(v ?? 0);
        }
    }
}

Which allows me to compile the following code

int? nullableInt = 0;
Int32 regularInt = nullableInt;

but if I define regularInt as an int instead of Int32 I get the following error

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

I expected int and Int32 to be interchangeable but the C# language clearly hasn't been built with this functionality in mind.

Is there a technical reason behind the impossibility of defining this operation, is it a decision made to prevent potential code smell ?

I'm aware that defining such an implicit operator could result in some very unexpected behavior, as the conversion from a null value to a 0 integer doesn't make sense in every situation. This question is more about "why can't it be done" than "why doing it is a really  bad idea"