问:
php mysql select not working on field "name"
I know it's strange but I have a select that returns null if the field named name is used. If I remove it then it works, and I already changed the data in the table. If I make a direct query to mysql it works. There might be something in the contents but I can't see anything strange.

Any suggestion that could help me investigate is welcome :(

```<code>class go {
   function Query($sql){

       $results = $this->db->query($sql);

       if (mysqli_num_rows($results)<1){
           throw new Exception('No Results');
       }

       $out = array();

       while ($r = $results->fetch_object()){
           $out[] = $r;
       }

       return json_encode($out);

       $out = null;
    }
}

$client = new go;

//not working
$sql = "select name from books limit 10";
$sql = "select name,description from books limit 10";
$sql = "select * from books limit 10";

// works!
$sql = "select description from books limit 10";

$data = $client->Query( $sql );
</code>```

UPDATE

I found that the problem comes out due to some latin accented characters like ó ñ é

答:
Update

Try setting the charset when initialising the connection to your mySQL server usg set_charset() method. I use the following charset:

```<code>$this->db->set_charset('utf8mb4');
</code>```

This may resolve your issue.

Body:
I know it's strange but I have a select that returns null if the field named name is used. If I remove it then it works, and I already changed the data in the table. If I make a direct query to mysql it works. There might be something in the contents but I can't see anything strange.

Any suggestion that could help me investigate is welcome :(

class go {
   function Query($sql){

       $results = $this->db->query($sql);

       if (mysqli_num_rows($results)<1){
           throw new Exception('No Results');
       }

       $out = array();

       while ($r = $results->fetch_object()){
           $out[] = $r;
       }

       return json_encode($out);

       $out = null;
    }
}

$client = new go;

//not working
$sql = "select name from books limit 10";
$sql = "select name,description from books limit 10";
$sql = "select * from books limit 10";

// works!
$sql = "select description from books limit 10";

$data = $client->Query( $sql );

UPDATE

I found that the problem comes out due to some latin accented characters like ó ñ é

Body:
Update

Try setting the charset when initialising the connection to your mySQL server usg set_charset() method. I use the following charset:

$this->db->set_charset('utf8mb4');

This may resolve your issue.


来源: stackexchange

问:
Remove specific cookie from session python requests
Remove specific cookie from session python requests.

Only found

```<code>s.cookies.clear()
</code>```

Would like to ONLY remove a specific cookie. e.g. s.cookies['basketid']

答:
Let's say you are creating this session:

import requests
s = requests.session()
r = s.get('http://httpbin.org/cookies/set', params={'foo': 'bar', 'baz': 'but'})
```

<p>Inspecting the cookie shows:</p>

<pre class="lang-py prettyprint-override"><code>s.cookies.keys()
</code>```

>> ['baz', 'foo']
```

<p>Now, let's remove <code>foo</code> from the cookie:</p>

<pre class="lang-py prettyprint-override"><code>s.cookies.pop('foo', None)
</code>```

This shows:

s.cookies.keys()
```

<pre class="lang-py prettyprint-override"><code>>> ['baz']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Remove specific cookie from session python requests.

Only found

s.cookies.clear()

Would like to ONLY remove a specific cookie. e.g. s.cookies['basketid']

Body:
Let's say you are creating this session:

import requests
s = requests.session()
r = s.get('http://httpbin.org/cookies/set', params={'foo': 'bar', 'baz': 'but'})

Inspecting the cookie shows:

s.cookies.keys()

>> ['baz', 'foo']

Now, let's remove foo from the cookie:

s.cookies.pop('foo', None)

This shows:

s.cookies.keys()

>> ['baz']


问:
How to hash particular column in csv file | linux |
I have a scenario

where i want to hash some columns of csv file

how to do that with below data

```<code>ID|NAME|CITY|AGE
1|AB1|BBC|12
2|AB2|FGD|17
3|AB3|ASD|18
4|AB4|SDF|19
5|AB5|ASC|22
</code>```

The Column name NAME | AGE should get hashed with random values

like below output

```<code>ID|NAME|CITY|AGE
1|68b329da9111314099c7d8ad5cb9c940|BBC|77bAD9da9893er34099c7d8ad5cb9c940
2|69b32fga9893e34099c7d8ad5cb9c940|FGD|68bAD9da989yue34099c7d8ad5cb9c940
3|46b329da9893e3403453d8ad5cb9c940|ASD|60bfgD9da9893e34099c7d8ad5cb9c940
4|50Cd29da9893e34099c7d8ad5cb9c940|SDF|67bAD9da98973e34099c7d8ad5cb9c940
5|67bAD9da9893e34099c7d8ad5cb9c940|ASC|67bAD9da11893e34099c7d8ad5cb9c940
</code>```

When i tested this code below code gives me same value for the column 'NAME'  it should give  randomized values

```<code>awk '{
    tmp="echo " $2 " | openssl md5 | cut -f2 -d\" \""
tmp | getline cksum
close(tmp)
$2=cksum
print
}' < sample.csv
</code>```

output :

```<code> 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
</code>```

答:
You have to specify | as input and output field separators. Otherwise $2 is not what you expect, but an empty string.

```<code>awk -F '|' -v "OFS=|" 'FNR==1 { print; next } {
    tmp="echo " $2 " | openssl md5 | cut -f2 -d\" \""
tmp | getline cksum
close(tmp)
$2=cksum
print
}' sample.csv
</code>```

prints

ID|NAME|CITY|AGE
1|d44aec35a11ff6fa8a800120dbef1cd7|BBC|12
2|157aa4a48373eaf0415ea4229b3d4421|FGD|17
3|ba3c08d4a65f1baa1d7220a6802b5710|ASD|18
4|69be622e1c0d417ceb9b8fb0aa9dc574|SDF|19
5|427872b1ac3a22dc154688ddc2050516|ASC|22
```

Body:
I have a scenario

where i want to hash some columns of csv file

how to do that with below data

ID|NAME|CITY|AGE
1|AB1|BBC|12
2|AB2|FGD|17
3|AB3|ASD|18
4|AB4|SDF|19
5|AB5|ASC|22

The Column name NAME | AGE should get hashed with random values

like below output

ID|NAME|CITY|AGE
1|68b329da9111314099c7d8ad5cb9c940|BBC|77bAD9da9893er34099c7d8ad5cb9c940
2|69b32fga9893e34099c7d8ad5cb9c940|FGD|68bAD9da989yue34099c7d8ad5cb9c940
3|46b329da9893e3403453d8ad5cb9c940|ASD|60bfgD9da9893e34099c7d8ad5cb9c940
4|50Cd29da9893e34099c7d8ad5cb9c940|SDF|67bAD9da98973e34099c7d8ad5cb9c940
5|67bAD9da9893e34099c7d8ad5cb9c940|ASC|67bAD9da11893e34099c7d8ad5cb9c940

When i tested this code below code gives me same value for the column 'NAME'  it should give  randomized values

awk '{
    tmp="echo " $2 " | openssl md5 | cut -f2 -d\" \""
tmp | getline cksum
close(tmp)
$2=cksum
print
}' < sample.csv

output :

 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940

Body:
You have to specify | as input and output field separators. Otherwise $2 is not what you expect, but an empty string.

awk -F '|' -v "OFS=|" 'FNR==1 { print; next } {
    tmp="echo " $2 " | openssl md5 | cut -f2 -d\" \""
tmp | getline cksum
close(tmp)
$2=cksum
print
}' sample.csv

prints

ID|NAME|CITY|AGE
1|d44aec35a11ff6fa8a800120dbef1cd7|BBC|12
2|157aa4a48373eaf0415ea4229b3d4421|FGD|17
3|ba3c08d4a65f1baa1d7220a6802b5710|ASD|18
4|69be622e1c0d417ceb9b8fb0aa9dc574|SDF|19
5|427872b1ac3a22dc154688ddc2050516|ASC|22


问:
Drop the columns in pandas dataframe
col_exclusions = ['numerator','Numerator' 'Denominator', "denominator"]

dataframe

```<code>id prim_numerator sec_Numerator tern_Numerator tern_Denominator final_denominator Result

1       12                23           45          54                      56         Fail
</code>```

Final output is id and Result

答:
You can also use the following approach where the column names are splitted then matched with col_exclusions

```<code>df.drop(columns=[i for i in df.columns if i.split("_")[-1] in col_exclusions], inplace=True)
print(df.head())
</code>```

Title: Drop the columns in pandas dataframe

Body:
col_exclusions = ['numerator','Numerator' 'Denominator', "denominator"]

dataframe

id prim_numerator sec_Numerator tern_Numerator tern_Denominator final_denominator Result

1       12                23           45          54                      56         Fail

Final output is id and Result

Body:
You can also use the following approach where the column names are splitted then matched with col_exclusions

df.drop(columns=[i for i in df.columns if i.split("_")[-1] in col_exclusions], inplace=True)
print(df.head())


问:
Submit input values which are not in form tag
Hi
i'm using Jquery
and i have many input fileds but they are not in <form> tag
How can i submit the fields value?

It must bu simple submit not ajax

thanks

答:
If you want to use the browser's submit and not use XHR, you'll need to wrap the input elements in a form and submit it.

```<code>$('#something :input')
 .wrapAll('<form action="somewhere.php" method="post" />')
 .submit();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to use the browser's submit and not use XHR, you'll need to wrap the input elements in a form and submit it.

$('#something :input')
 .wrapAll('<form action="somewhere.php" method="post" />')
 .submit();


问:
Encode JSON in bash script
I'm trying to import a Template to my Zabbix server with Zabbix API, i used this:

```<code>fileJSON=\""$(cat template_file)"\"

curl  -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "configuration.import",
    "params": {
        "format": "json",
        "rules": {
            "templates": {
                "createMissing": true,
                "updateExisting": true
            }
        },
        "source": $fileJSON
    },
    "auth": "6a977cd94b26b6156698459ac4d0f769",
    "id": 1
}' 'http://127.0.0.1/zabbix/api_jsonrpc.php' | jq '.'
</code>```

Here is the output:

```<code>{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}
</code>```

I just don't see any error… i tried to use an online parser website but he Don't see any error.
This var is directly filled with the export method of Zabbix (in JSON).
Here is the content of the file:

```<code>{
  "jsonrpc": "2.0",
  "result": "{\"zabbix_export\":{\"version\":\"4.4\",\"date\":\"2020-02-18T08:47:31Z\",\"groups\":[{\"name\":\"System\"}],\"templates\":[{\"template\":\"Template Systeme\",\"name\":\"Template Systeme\",\"groups\":[{\"name\":\"System\"}],\"discovery_rules\":[{\"name\":\"D\\u00e9couverte des services\",\"key\":\"service.discovery\",\"delay\":\"30s\"}]}]}}",
  "id": 1
}
</code>```

I think that the error is the format of the fileJSON, how to encode this variable in JSON format ?

答: From the look of the template_file output, the result key is not JSON but JSON string. Have you tried without JSON dumping it?

Title: Encode JSON in bash script

Body:
I'm trying to import a Template to my Zabbix server with Zabbix API, i used this:

fileJSON=\""$(cat template_file)"\"

curl  -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "configuration.import",
    "params": {
        "format": "json",
        "rules": {
            "templates": {
                "createMissing": true,
                "updateExisting": true
            }
        },
        "source": $fileJSON
    },
    "auth": "6a977cd94b26b6156698459ac4d0f769",
    "id": 1
}' 'http://127.0.0.1/zabbix/api_jsonrpc.php' | jq '.'

Here is the output:

{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}

I just don't see any error… i tried to use an online parser website but he Don't see any error.
This var is directly filled with the export method of Zabbix (in JSON).
Here is the content of the file:

{
  "jsonrpc": "2.0",
  "result": "{\"zabbix_export\":{\"version\":\"4.4\",\"date\":\"2020-02-18T08:47:31Z\",\"groups\":[{\"name\":\"System\"}],\"templates\":[{\"template\":\"Template Systeme\",\"name\":\"Template Systeme\",\"groups\":[{\"name\":\"System\"}],\"discovery_rules\":[{\"name\":\"D\\u00e9couverte des services\",\"key\":\"service.discovery\",\"delay\":\"30s\"}]}]}}",
  "id": 1
}

I think that the error is the format of the fileJSON, how to encode this variable in JSON format ?


问:
Load data from two databases to one WPF DataGrid
I am trying to populate data from two databases to one WPF DataGrid. Can somebody advise what I am doing wrong in my current code? Debugger grayed out this section:

```<code>            using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
            {
                dbConnectionFR.Open();
                OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                var table = new DataTable("COMPANY");
                dadapterFR.Fill(table);

                return table.DefaultView;

            }
</code>```

saying:

Severity  Code    Description Project File    Line    Suppression State
  Warning   CS0162  Unreachable code detected

Here is my full code:

```<code>using System.Data.Odbc;
using System.Windows;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;

namespace DB_inspector_FilterTest
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {

            try
            {
                ProgressBar.IsIndeterminate = true;

                DataGrid1.ItemsSource = await GetDataAsync();

                ProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private Task<DataView> GetDataAsync()
        {
            return Task.Run(() =>
            {

                string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DE875;dbq=@DEDBFS;Uid=DEUsername;Pwd=DEPassword;";

                string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

                string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=FR875;dbq=@FRDBFS;Uid=FRUsername;Pwd=FRPassword;";

                string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

                // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
                using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
                {
                    dbConnectionDE.Open();
                    OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                    dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                    var table = new DataTable("COMPANY");
                    dadapterDE.Fill(table);

                    return table.DefaultView;

                }
                using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
                {
                    dbConnectionFR.Open();
                    OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                    dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                    var table = new DataTable("COMPANY");
                    dadapterFR.Fill(table);

                    return table.DefaultView;

                }
            });
        }
}
</code>```

答:
You could for example merge the two DataTables into one:

```<code>private Task<DataView> GetDataAsync()
{
    return Task.Run(() =>
    {

        string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DE875;dbq=@DEDBFS;Uid=DEUsername;Pwd=DEPassword;";
        string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
        string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=FR875;dbq=@FRDBFS;Uid=FRUsername;Pwd=FRPassword;";
        string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

        DataTable dataTable = new DataTable("COMPANY");
        // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
        using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
        {
            dbConnectionDE.Open();
            OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
            dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

            dadapterDE.Fill(dataTable);

        }
        using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
        {
            dbConnectionFR.Open();
            OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
            dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

            var newTable = new DataTable("COMPANY");
            dadapterFR.Fill(newTable);

            dataTable.Merge(newTable);

        }

        return dataTable.DefaultView;
    });
}
</code>```

On a side note, it's a bad practice to write asynchronous wrappers: https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html

Body:
I am trying to populate data from two databases to one WPF DataGrid. Can somebody advise what I am doing wrong in my current code? Debugger grayed out this section:

            using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
            {
                dbConnectionFR.Open();
                OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                var table = new DataTable("COMPANY");
                dadapterFR.Fill(table);

                return table.DefaultView;

            }

saying:

Severity  Code    Description Project File    Line    Suppression State
  Warning   CS0162  Unreachable code detected

Here is my full code:

using System.Data.Odbc;
using System.Windows;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;

namespace DB_inspector_FilterTest
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {

            try
            {
                ProgressBar.IsIndeterminate = true;

                DataGrid1.ItemsSource = await GetDataAsync();

                ProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private Task<DataView> GetDataAsync()
        {
            return Task.Run(() =>
            {

                string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DE875;dbq=@DEDBFS;Uid=DEUsername;Pwd=DEPassword;";

                string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

                string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=FR875;dbq=@FRDBFS;Uid=FRUsername;Pwd=FRPassword;";

                string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

                // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
                using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
                {
                    dbConnectionDE.Open();
                    OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                    dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                    var table = new DataTable("COMPANY");
                    dadapterDE.Fill(table);

                    return table.DefaultView;

                }
                using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
                {
                    dbConnectionFR.Open();
                    OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                    dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                    var table = new DataTable("COMPANY");
                    dadapterFR.Fill(table);

                    return table.DefaultView;

                }
            });
        }
}

Body:
You could for example merge the two DataTables into one:

private Task<DataView> GetDataAsync()
{
    return Task.Run(() =>
    {

        string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DE875;dbq=@DEDBFS;Uid=DEUsername;Pwd=DEPassword;";
        string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
        string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=FR875;dbq=@FRDBFS;Uid=FRUsername;Pwd=FRPassword;";
        string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";

        DataTable dataTable = new DataTable("COMPANY");
        // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
        using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
        {
            dbConnectionDE.Open();
            OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
            dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

            dadapterDE.Fill(dataTable);

        }
        using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
        {
            dbConnectionFR.Open();
            OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
            dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

            var newTable = new DataTable("COMPANY");
            dadapterFR.Fill(newTable);

            dataTable.Merge(newTable);

        }

        return dataTable.DefaultView;
    });
}

On a side note, it's a bad practice to write asynchronous wrappers: https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html


问:
Can i get a time difference in minutes for subsequent rows in mysql using timestamp
```<code>`ID`,`NAMES`,   `TIMESTAMP`
'3', 'Sharon',  '2020-02-17 21:11:12'
'4', 'RALPH',   '2020-02-18 01:50:19'
</code>```

Above is an extraction from my table.I would want to find time difference between the two timestamps(i.e for ID=3 and ID=4). Also i would like to create a column for the time difference.Please someone help
Thanks

答: You can use TIMESTAMPDIFF() function</p>

Body:
`ID`,`NAMES`,   `TIMESTAMP`
'3', 'Sharon',  '2020-02-17 21:11:12'
'4', 'RALPH',   '2020-02-18 01:50:19'

Above is an extraction from my table.I would want to find time difference between the two timestamps(i.e for ID=3 and ID=4). Also i would like to create a column for the time difference.Please someone help
Thanks

Body: You can use TIMESTAMPDIFF() function


问:
Finding duplicate files according to md5 with bash
I want to write an algorithm about bash that it finds duplicate files

How can I add size option?

答:
If you can't use *dupes for any reason and the number of files is very high the sort+uniq won't have a good performance. In this case you could use something like this:

```<code>find . -not -empty -type f -printf "%012s" -exec md5sum {} \; | awk 'x[substr($0, 1, 44)]++'
</code>```

find will create a line for each file with the filesize in bytes (I used 12 positions but YMMV) and the md5 hash of the file (plus the name).

awk will filter the results without the need of being sorted previously. The 44 stands for 12 (for the filesize) + 32 (length of the hash). If you need some explanation about the awk program you can see the basics here.

Body:
If you can't use *dupes for any reason and the number of files is very high the sort+uniq won't have a good performance. In this case you could use something like this:

find . -not -empty -type f -printf "%012s" -exec md5sum {} \; | awk 'x[substr($0, 1, 44)]++'

find will create a line for each file with the filesize in bytes (I used 12 positions but YMMV) and the md5 hash of the file (plus the name).

awk will filter the results without the need of being sorted previously. The 44 stands for 12 (for the filesize) + 32 (length of the hash). If you need some explanation about the awk program you can see the basics here.


问:
Struggling with PDF output of bookdown
I thought it would be a good idea to write a longer report/protocol using bookdown since it's more comfortable to have one file per topic to write in instead of just one RMarkdown document with everything. Now I'm faced with the problem of sharing this document - the HTML looks best (except for wide tables being cut off) but is difficult to send via e-mail to a supervisor for example. I also can't expect anyone to be able to open the ePub format on their computer, so PDF would be the easiest choice. Now my problems:

My chapter headings are pretty long, which doesn't matter in HTML but they don't fit the page headers in the PDF document. In LaTeX I could define a short title for that, can I do that in bookdown as well?

I include figure files using knitr::include_graphics() inside of code chunks, so I generate the caption via the chunk options. For some figures, I can't avoid having an underscore in the caption, but that does not work out in LaTeX. Is there a way to escape the underscore that actually works (preferrably for HTML and PDF at the same time)? My LaTeX output looks like this after rendering:

```<code>\textbackslash{}begin\{figure\}
\includegraphics[width=0.6\linewidth,height=0.6\textheight]{figures/0165_HMMER} \textbackslash{}caption\{Output of HMMER for PA\_0165\}\label{fig:0165}
\textbackslash{}end\{figure\}
</code>```

Edit

MWE showing that the problem is an underscore in combination with out.height (or width) in percent:

```<code>---
title: "MWE FigCap"
author: "LilithElina"
date: "19 Februar 2020"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

## Including Plots

You can also embed plots, for example:

```{r pressure, echo=FALSE, fig.cap="This is a nice figure caption", out.height='40%'}
plot(pressure)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

```{r pressure2, echo=FALSE, fig.cap="This is a not nice figure_caption", out.height='40%'}
plot(pressure)
```
</code>```

答:
Concerning shorter headings: pandoc, which is used for the markdown to LaTeX conversion, does not offer a "shorter heading". You can do that yourself, though:

```<code># Really long chaper heading
\markboth{\thechapter~short heading}{}
[...]
## Really long section heading
\markright{\thesection~short heading}
</code>```

This assumes a document class with chapters and sections.

Concerning the underscore in the figure caption: For me it works for both PDF and HTML to escape the underscore:

```<code>```{r pressure2, echo=FALSE, fig.cap="This is a not nice figure\\_caption", out.height='40%'}
plot(pressure)
```
</code>```

Title: Struggling with PDF output of bookdown

Body:
I thought it would be a good idea to write a longer report/protocol using bookdown since it's more comfortable to have one file per topic to write in instead of just one RMarkdown document with everything. Now I'm faced with the problem of sharing this document - the HTML looks best (except for wide tables being cut off) but is difficult to send via e-mail to a supervisor for example. I also can't expect anyone to be able to open the ePub format on their computer, so PDF would be the easiest choice. Now my problems:

My chapter headings are pretty long, which doesn't matter in HTML but they don't fit the page headers in the PDF document. In LaTeX I could define a short title for that, can I do that in bookdown as well?

I include figure files using knitr::include_graphics() inside of code chunks, so I generate the caption via the chunk options. For some figures, I can't avoid having an underscore in the caption, but that does not work out in LaTeX. Is there a way to escape the underscore that actually works (preferrably for HTML and PDF at the same time)? My LaTeX output looks like this after rendering:

\textbackslash{}begin\{figure\}
\includegraphics[width=0.6\linewidth,height=0.6\textheight]{figures/0165_HMMER} \textbackslash{}caption\{Output of HMMER for PA\_0165\}\label{fig:0165}
\textbackslash{}end\{figure\}

Edit

MWE showing that the problem is an underscore in combination with out.height (or width) in percent:

---
title: "MWE FigCap"
author: "LilithElina"
date: "19 Februar 2020"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

## Including Plots

You can also embed plots, for example:

```{r pressure, echo=FALSE, fig.cap="This is a nice figure caption", out.height='40%'}
plot(pressure)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

```{r pressure2, echo=FALSE, fig.cap="This is a not nice figure_caption", out.height='40%'}
plot(pressure)
```

Body:
Concerning shorter headings: pandoc, which is used for the markdown to LaTeX conversion, does not offer a "shorter heading". You can do that yourself, though:

# Really long chaper heading
\markboth{\thechapter~short heading}{}
[...]
## Really long section heading
\markright{\thesection~short heading}

This assumes a document class with chapters and sections.

Concerning the underscore in the figure caption: For me it works for both PDF and HTML to escape the underscore:

```{r pressure2, echo=FALSE, fig.cap="This is a not nice figure\\_caption", out.height='40%'}
plot(pressure)
```


问:
How to append data to a file?
I trying to write into the txt file.

But with out losing the data that is already stored in the file.

But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.

My code is:

```<code>public void addWorker(Worker worker){
        workers.put(worker.getId(), worker);

    }

    public void printWorker (String id){
    Worker work = (Worker) workers.get( id );

    if (work == null) {
        System.out.println("Worker NOT found");
    }

    else {
         work.printText();
     }
    }
       public void printWorkers() {
           if (workers.size() == 0) {
               System.out.println("No workres");
                return;
           }

           Collection<Worker> c = workers.values();
           Iterator<Worker> itr = c.iterator();
           System.out.println("Workers in division "+dName+ ":");
           while (itr.hasNext()) {
                  Worker wo = itr.next();
                  wo.printText();
           }
       }

       public void writeToFile(){
           PrintWriter pw = null;
           try{
               pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
               Collection<Worker> c = workers.values();
               Iterator<Worker> itr = c.iterator();
               while (itr.hasNext()) {
                   Worker wo = itr.next();
                   pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
                   pw.println();
               }
            }
            catch(Exception e) {
                System.out.println(e);
            }
            finally {
                if (pw != null) {
                    pw.close();
                }
            }

        }

}
</code>```

Can you help me?

答:
Create a separate variable to emphasize that, appending to file.</p>

```<code>boolean append = true;
pw = new PrintWriter(new FileWriter(new File("filepath.txt"), append));
</code>```

Title: How to append data to a file?

Body:
I trying to write into the txt file.

But with out losing the data that is already stored in the file.

But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.

My code is:

public void addWorker(Worker worker){
        workers.put(worker.getId(), worker);

    }

    public void printWorker (String id){
    Worker work = (Worker) workers.get( id );

    if (work == null) {
        System.out.println("Worker NOT found");
    }

    else {
         work.printText();
     }
    }
       public void printWorkers() {
           if (workers.size() == 0) {
               System.out.println("No workres");
                return;
           }

           Collection<Worker> c = workers.values();
           Iterator<Worker> itr = c.iterator();
           System.out.println("Workers in division "+dName+ ":");
           while (itr.hasNext()) {
                  Worker wo = itr.next();
                  wo.printText();
           }
       }

       public void writeToFile(){
           PrintWriter pw = null;
           try{
               pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
               Collection<Worker> c = workers.values();
               Iterator<Worker> itr = c.iterator();
               while (itr.hasNext()) {
                   Worker wo = itr.next();
                   pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
                   pw.println();
               }
            }
            catch(Exception e) {
                System.out.println(e);
            }
            finally {
                if (pw != null) {
                    pw.close();
                }
            }

        }

}

Can you help me?

Body:
Create a separate variable to emphasize that, appending to file.

boolean append = true;
pw = new PrintWriter(new FileWriter(new File("filepath.txt"), append));


问:
$_FILES["imagefile"]["name"] return name but $_FILES["imagefile"]["tmp_name"] return null value?
In my case i was include enctype on myform like

```<code><form id="product_add" name="product_add" accept-charset="utf-8" action="product_add_inter.php" method="post" enctype="multipart/form-data">
</code>```

then my input type file is

```<code><input name="imagefile" class="form-control" type="file"   />
</code>```

Problem is in server side i need to upload my image to distination folder.I was tried to get file from form using

```<code>$_FILES["imagefile"]["name"]
</code>```

its worked and returned name of my image. But when i get the file using temp_name it return null values.

```<code>$_FILES["imagefile"]["tmp_name"]
</code>```

how can i solve this.

答:
I have Checked your Code and its absolutly working fine

```<code><?php
echo $_FILES["imagefile"]["name"];
?>
<form id="product_add" name="product_add" accept-charset="utf-8" action="Check.php" method="post" enctype="multipart/form-data">
<input name="imagefile" class="form-control" type="file"   />
<input type="submit" value="SUBMIT" />
</form>
</code>```

Please
Check If phpinfo(given below) whether "file_uploads" is ON and upload_max_filesize

```<code><?php
echo phpinfo();
?>
</code>```

Body:
In my case i was include enctype on myform like

<form id="product_add" name="product_add" accept-charset="utf-8" action="product_add_inter.php" method="post" enctype="multipart/form-data">

then my input type file is

<input name="imagefile" class="form-control" type="file"   />

Problem is in server side i need to upload my image to distination folder.I was tried to get file from form using

$_FILES["imagefile"]["name"]

its worked and returned name of my image. But when i get the file using temp_name it return null values.

$_FILES["imagefile"]["tmp_name"]

how can i solve this.

Body:
I have Checked your Code and its absolutly working fine

<?php
echo $_FILES["imagefile"]["name"];
?>
<form id="product_add" name="product_add" accept-charset="utf-8" action="Check.php" method="post" enctype="multipart/form-data">
<input name="imagefile" class="form-control" type="file"   />
<input type="submit" value="SUBMIT" />
</form>

Please
Check If phpinfo(given below) whether "file_uploads" is ON and upload_max_filesize

<?php
echo phpinfo();
?>


问:
How to copy a bundle html file to a document directory in iOS Swift?
I have been trying to save local index.html file to document directory but it does not save to local document directory.

here is my folder structure:

```<code>sampleHtml.xcodeproj
---->sampleHtml
-------->Web_Assets
------------> index.html
---->ViewController.swift
</code>```

Here is the code for saving and checking file path exist is not, if path exist then overwrite it else copy the new one.

```<code>func saveHtmlDoc(){
    let filemgr = FileManager.default
    let docURL = filemgr.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let destPath = docURL.path+"/www/"
    print("des path", destPath)
    let sourcePath = Bundle.main.resourceURL!.appendingPathComponent("Web_Assets").path
    print("sourc", sourcePath.appending("/index.html"))

      //COPY Web_Assets content from Bundle to Documents/www
      do {
          try filemgr.removeItem(atPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }
      do {
          try filemgr.copyItem(atPath:  sourcePath + "/", toPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }

}
</code>```

My issue is how to save index.html file to document directory and check the file path exist are not, if exist overwrite it or copy the new one.

Any help much appreciates it...

答:
I try and test below code, it work okey. Before add file, you need create folder first.</p>

```<code>func saveHtmlDoc() {
    let filemgr = FileManager.default
    let docURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let destPath = URL(string:docURL)?.appendingPathComponent("www")

    guard let newDestPath = destPath, let sourcePath = Bundle.main.path(forResource: "image", ofType: ".png"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent("image.png") else { return  }

    //CREATE FOLDER
    if !filemgr.fileExists(atPath: newDestPath.path) {
        do {
            try filemgr.createDirectory(atPath: newDestPath.path, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error.localizedDescription);
        }
    }
    else {
        print("Folder is exist")
    }

    if filemgr.fileExists(atPath: fullDestPath.path) {
        print("File is exist in \(fullDestPath.path)")
    }
    else {
        do {
            try filemgr.copyItem(atPath:  sourcePath, toPath: fullDestPath.path)
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
}
</code>```

Body:
I have been trying to save local index.html file to document directory but it does not save to local document directory.

here is my folder structure:

sampleHtml.xcodeproj
---->sampleHtml
-------->Web_Assets
------------> index.html
---->ViewController.swift

Here is the code for saving and checking file path exist is not, if path exist then overwrite it else copy the new one.

func saveHtmlDoc(){
    let filemgr = FileManager.default
    let docURL = filemgr.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let destPath = docURL.path+"/www/"
    print("des path", destPath)
    let sourcePath = Bundle.main.resourceURL!.appendingPathComponent("Web_Assets").path
    print("sourc", sourcePath.appending("/index.html"))

      //COPY Web_Assets content from Bundle to Documents/www
      do {
          try filemgr.removeItem(atPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }
      do {
          try filemgr.copyItem(atPath:  sourcePath + "/", toPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }

}

My issue is how to save index.html file to document directory and check the file path exist are not, if exist overwrite it or copy the new one.

Any help much appreciates it...

Body:
I try and test below code, it work okey. Before add file, you need create folder first.

func saveHtmlDoc() {
    let filemgr = FileManager.default
    let docURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let destPath = URL(string:docURL)?.appendingPathComponent("www")

    guard let newDestPath = destPath, let sourcePath = Bundle.main.path(forResource: "image", ofType: ".png"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent("image.png") else { return  }

    //CREATE FOLDER
    if !filemgr.fileExists(atPath: newDestPath.path) {
        do {
            try filemgr.createDirectory(atPath: newDestPath.path, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error.localizedDescription);
        }
    }
    else {
        print("Folder is exist")
    }

    if filemgr.fileExists(atPath: fullDestPath.path) {
        print("File is exist in \(fullDestPath.path)")
    }
    else {
        do {
            try filemgr.copyItem(atPath:  sourcePath, toPath: fullDestPath.path)
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
}


问:
Custom Rule class in Laravel - how to get message working?
Working on an existing project, so keeping the code structure the same as other developers is critical.

I've created a new Rule and added my Validator::extend to the boot(). However I can't get the validation error to display my custom message. Instead is just displays a default "validation.ruleName"

I'm writing a Validation rule that uses ImLiam's NHS Number validation package. The validate() and passes() work successfully. But the error message never changes.

How can I get the messages() method to display the custom output of the exception? (Instead of "validation.nhsnumber" in screenshot below?

App\Forms\MyForm: (using Kris Forms)

```<code>public function buildForm()
{
    $this->add('nhs_number', 'number', [
        'label' => 'NHS Number',
        'rules' => 'nullable|nhsnumber',
    ]);
    ...
}
</code>```

App\Providers\AppServiceProvider:

```<code>public function boot()
{

        Validator::extend('nhsnumber', \App\Rules\ValidNhsNumber::class);
}
</code>```

App\Rules\ValidNhsNumber:

```<code>namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use ImLiam\NhsNumber\InvalidNhsNumberException;
use ImLiam\NhsNumber\NhsNumber;

class ValidNhsNumber implements Rule
{
    private $message;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        try {
            $nhsNumber = new NhsNumber($value);
            $nhsNumber->validate(); // Will throw exception here if false
            return true;
        } catch (InvalidNhsNumberException $e) {
            $this->message = $e->getMessage();
        }
    }

    public function validate($attribute, $value, $params): bool
    {
        return $this->passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
</code>```

答:
Did you try to dump $this->message;? What does it display if you dump it? Do you even get to the public function message()? Try to put a dd($this-message) in the message() method.

Edit:

In your catch you are not returning anything at all. When it enters the catch it's not returning false or true. It's returning null.

Body:
Working on an existing project, so keeping the code structure the same as other developers is critical.

I've created a new Rule and added my Validator::extend to the boot(). However I can't get the validation error to display my custom message. Instead is just displays a default "validation.ruleName"

I'm writing a Validation rule that uses ImLiam's NHS Number validation package. The validate() and passes() work successfully. But the error message never changes.

How can I get the messages() method to display the custom output of the exception? (Instead of "validation.nhsnumber" in screenshot below?

App\Forms\MyForm: (using Kris Forms)

public function buildForm()
{
    $this->add('nhs_number', 'number', [
        'label' => 'NHS Number',
        'rules' => 'nullable|nhsnumber',
    ]);
    ...
}

App\Providers\AppServiceProvider:

public function boot()
{

        Validator::extend('nhsnumber', \App\Rules\ValidNhsNumber::class);
}

App\Rules\ValidNhsNumber:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use ImLiam\NhsNumber\InvalidNhsNumberException;
use ImLiam\NhsNumber\NhsNumber;

class ValidNhsNumber implements Rule
{
    private $message;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        try {
            $nhsNumber = new NhsNumber($value);
            $nhsNumber->validate(); // Will throw exception here if false
            return true;
        } catch (InvalidNhsNumberException $e) {
            $this->message = $e->getMessage();
        }
    }

    public function validate($attribute, $value, $params): bool
    {
        return $this->passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}


问:
curl -i http://ip.cn 301 Moved Permanently
I read an article and it mentioned a test method for network.

Expected result:

Real result:

```<code>curl -i http://ip.cn

HTTP/1.1 301 Moved Permanently
Date: Tue, 18 Feb 2020 09:16:12 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Tue, 18 Feb 2020 10:16:12 GMT
Location: https://ip.cn/
Alt-Svc: h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400
Server: cloudflare
CF-RAY: 566ee6a159a9d96a-HKG
</code>```

Updated:

Thanks for the answer, it works.

Here is the test result which meet the expectation.

```<code>➜  work git:(master) ✗ curl -i https://ip.cn
HTTP/2 200
date: Tue, 18 Feb 2020 10:12:29 GMT
content-type: application/json; charset=UTF-8
set-cookie: __cfduid=de415094860b360bfae3d5903804244451582020749; expires=Thu, 19-Mar-20 10:12:29 GMT; path=/; domain=.ip.cn; HttpOnly; SameSite=Lax
cf-cache-status: DYNAMIC
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
alt-svc: h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400
server: cloudflare
cf-ray: 566f39135e2feb61-LAX

{"ip": "124.64.19.119", "country": "北京市", "city": "联通”}

➜  work git:(master) ✗ export ALL_PROXY=socks5://127.0.0.1:1086

➜  work git:(master) ✗ curl -i https://ip.cn
HTTP/2 200
date: Tue, 18 Feb 2020 10:13:34 GMT
content-type: application/json; charset=UTF-8
set-cookie: __cfduid=d59e4719e6efbfddb9fd408db5c8d415f1582020814; expires=Thu, 19-Mar-20 10:13:34 GMT; path=/; domain=.ip.cn; HttpOnly; SameSite=Lax
cf-cache-status: DYNAMIC
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
alt-svc: h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400
server: cloudflare
cf-ray: 566f3aa8bdc9d942-HKG

{"ip": "112.119.149.55", "country": "香港特别行政区", "city": "电讯盈科"}
</code>```

A follow-up issue:

But it still could not download the dependency of android project.

```<code>gongzelong:android gongzelong$ ./gradlew build

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve com.google.gms:google-services:4.3.3.
     Required by:
         project :
      > Could not resolve com.google.gms:google-services:4.3.3.
         > Could not get resource 'https://dl.google.com/dl/android/maven2/com/google/gms/google-services/4.3.3/google-services-4.3.3.pom'.
            > Could not HEAD 'https://dl.google.com/dl/android/maven2/com/google/gms/google-services/4.3.3/google-services-4.3.3.pom'.
               > Read timed out

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 30s

</code>```

答: It wants you to use the HTTPS version so it sends back a redirect response. Add -L to the command line or use https:// in the URL...

Body:
I read an article and it mentioned a test method for network.

Expected result:

Real result:

curl -i http://ip.cn

HTTP/1.1 301 Moved Permanently
Date: Tue, 18 Feb 2020 09:16:12 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Tue, 18 Feb 2020 10:16:12 GMT
Location: https://ip.cn/
Alt-Svc: h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400
Server: cloudflare
CF-RAY: 566ee6a159a9d96a-HKG

Updated:

Thanks for the answer, it works.

Here is the test result which meet the expectation.

➜  work git:(master) ✗ curl -i https://ip.cn
HTTP/2 200
date: Tue, 18 Feb 2020 10:12:29 GMT
content-type: application/json; charset=UTF-8
set-cookie: __cfduid=de415094860b360bfae3d5903804244451582020749; expires=Thu, 19-Mar-20 10:12:29 GMT; path=/; domain=.ip.cn; HttpOnly; SameSite=Lax
cf-cache-status: DYNAMIC
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
alt-svc: h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400
server: cloudflare
cf-ray: 566f39135e2feb61-LAX

{"ip": "124.64.19.119", "country": "北京市", "city": "联通”}

➜  work git:(master) ✗ export ALL_PROXY=socks5://127.0.0.1:1086

➜  work git:(master) ✗ curl -i https://ip.cn
HTTP/2 200
date: Tue, 18 Feb 2020 10:13:34 GMT
content-type: application/json; charset=UTF-8
set-cookie: __cfduid=d59e4719e6efbfddb9fd408db5c8d415f1582020814; expires=Thu, 19-Mar-20 10:13:34 GMT; path=/; domain=.ip.cn; HttpOnly; SameSite=Lax
cf-cache-status: DYNAMIC
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
alt-svc: h3-25=":443"; ma=86400, h3-24=":443"; ma=86400, h3-23=":443"; ma=86400
server: cloudflare
cf-ray: 566f3aa8bdc9d942-HKG

{"ip": "112.119.149.55", "country": "香港特别行政区", "city": "电讯盈科"}

A follow-up issue:

But it still could not download the dependency of android project.

gongzelong:android gongzelong$ ./gradlew build

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve com.google.gms:google-services:4.3.3.
     Required by:
         project :
      > Could not resolve com.google.gms:google-services:4.3.3.
         > Could not get resource 'https://dl.google.com/dl/android/maven2/com/google/gms/google-services/4.3.3/google-services-4.3.3.pom'.
            > Could not HEAD 'https://dl.google.com/dl/android/maven2/com/google/gms/google-services/4.3.3/google-services-4.3.3.pom'.
               > Read timed out

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 30s


问:
Using catchError() inside the pipe() shows an error at the .subscribe variable
I wanted to handle the errors for a method in angular. I read that I can use the catchError() inside of the .pipe().
When I added an catchError check I get the variable roomId marked with the red squiggly line, which says TS2345: Argument of type 'unknown' is not assignable to parameter of type 'number'

This is the part where I do the error check.

```<code>this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse)=>{
             if(error.status != 200){
               // handle error
             }else{
               // return error
               return throwError(error);
            }
         }),
</code>```

And here is the complete method.

```<code>public findRoom(room: Room): Observable<house> {
    return new Observable(house => {
      this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse)=>{
                  if(error.status != 200){
                    // handle error
                  }else{
                    // return error
                    return throwError(error);
                  }
                }),
      ).subscribe(roomId =>
        this.gointToThisRoom(roomId).pipe( <----- roomId throws that argument type unknown
          first()
        ).subscribe(roomInfo => {
            if (roomInfo.status === "failed") {
              house.next(house.failed);
            } else {
              this.downloadRoom(roomId).pipe(
                first()
              ).subscribe(blobFile =>
                this.getRoom(blobFile, name)
              );
              house.next(house.ready)
            }
          }
        )
      )
    });
  }
</code>```

Any idea why this is the case?

答:
Don't use new Observable constructor with subscription inside a subscription. It's hard to follow the logic, and you can't simply cancel pending operations by unsubscribing.

And // handle error should actually handle error.

I'd do something like this:

```<code>public findRoom(room: Room): Observable < house > {
    return this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse) => {
            if (error.status != 200) {
                return EMPTY;
            } else {
                // return error
                return throwError(error);
            }
        }),
        switchMap(roomId => this.gointToThisRoom(roomId)),
        first(),
        // ... the rest of the pipe
    );
}
</code>```

Body:
I wanted to handle the errors for a method in angular. I read that I can use the catchError() inside of the .pipe().
When I added an catchError check I get the variable roomId marked with the red squiggly line, which says TS2345: Argument of type 'unknown' is not assignable to parameter of type 'number'

This is the part where I do the error check.

this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse)=>{
             if(error.status != 200){
               // handle error
             }else{
               // return error
               return throwError(error);
            }
         }),

And here is the complete method.

public findRoom(room: Room): Observable<house> {
    return new Observable(house => {
      this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse)=>{
                  if(error.status != 200){
                    // handle error
                  }else{
                    // return error
                    return throwError(error);
                  }
                }),
      ).subscribe(roomId =>
        this.gointToThisRoom(roomId).pipe( <----- roomId throws that argument type unknown
          first()
        ).subscribe(roomInfo => {
            if (roomInfo.status === "failed") {
              house.next(house.failed);
            } else {
              this.downloadRoom(roomId).pipe(
                first()
              ).subscribe(blobFile =>
                this.getRoom(blobFile, name)
              );
              house.next(house.ready)
            }
          }
        )
      )
    });
  }

Any idea why this is the case?

Body:
Don't use new Observable constructor with subscription inside a subscription. It's hard to follow the logic, and you can't simply cancel pending operations by unsubscribing.

And // handle error should actually handle error.

I'd do something like this:

public findRoom(room: Room): Observable < house > {
    return this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse) => {
            if (error.status != 200) {
                return EMPTY;
            } else {
                // return error
                return throwError(error);
            }
        }),
        switchMap(roomId => this.gointToThisRoom(roomId)),
        first(),
        // ... the rest of the pipe
    );
}


问:
MySQL - conditionally add values from different tables?
Assume 3 tables:

Table 1 has information about a product's price (e.g. the base price)

Table 2 has information about a product's additional price factors (e.g. taxes, discounts, etc.)

Table 3 has flags indicating if Table 1 or Table 2 or both tables should be used in computing the product's total price

Is it possible in MySQL to compute the sum in this situation? If so, some guidance on the query would be appreciated.

答:
```<code>SELECT SUM(CASE (SELECT flag FROM table3)
           WHEN onlyTable1 THEN t1.col
           WHEN onlyTable2 THEN t2.col
           ELSE t1.col+t2.col END)

FROM table1 AS t1 JOIN table2 AS t2
</code>```


问:
How to integrate Firebase Auth with PHP app?
I have a simple PHP API which is used to authenticate users that use my app.
I have been trying to use Firebase Auth, without any success.
Following the documentation found here, I came to a point where:

I have created the Firebase project in the Firebase console.

I have created a Service Account, for which I have downloaded the Secret .json file that contains the credentials needed.

I have placed the file in the root directory of my app.

And I use this code to interact with the database:

```<code>    $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/path/to/file.json');

    $firebase = (new Factory)
        ->withServiceAccount($serviceAccount)
        ->createAuth();
</code>```

When dumping the $firebase instance I get this:

```<code>^ Kreait\Firebase\Auth {#78 ▼
  -client: Kreait\Firebase\Auth\ApiClient {#55 ▶}
  -tokenGenerator: Firebase\Auth\Token\Generator {#58 ▶}
  -idTokenVerifier: Kreait\Firebase\Auth\IdTokenVerifier {#77 ▶}
}
</code>```

Which makes me believe the connection is successful, but when I try to list all the users

```<code>    $firebase->listUsers();
</code>```

I get the following

```<code>^ Generator {#42 ▼
   this: Kreait\Firebase\Auth {#78 …}
   executing: {▼
     C:\Users\user\Projects\Simple-Api\vendor\kreait\firebase-
php\src\Firebase\Auth.php:110 {▼
       Kreait\Firebase\Auth->listUsers(int $maxResults = 1000, int $batchSize = 1000): Generator …
       › {
       ›     $pageToken = null;
       ›     $count = 0;
     }
   }
   closed: false
 }
</code>```

And when I try to loop through all the users like this:

```<code>   foreach ($users as $user) {
         var_dump($user);
     }
</code>```

I get these error:

```<code>cURL error 60: SSL certificate prblm: unable to get local issuer certificate
cURL error 77: SSL certificate prblm: unable to get local issuer certificate
</code>```

TEMPORARY FIX (not suggested for production):

Go to Guzzle Client.php class

Set verify to false

答:
If you continue to follow the documentation, you will find

https://firebase-php.readthedocs.io/en/stable/user-management.html#list-users

Auth::listUsers() returns a Generator, which you can either loop through with foreach() or convert to an array with iterator_to_array() - you should use the latter only if you limit the resultset, otherwise you will run into performance issues when PHP tries to load thousands of user records into memory.

Body:
I have a simple PHP API which is used to authenticate users that use my app.
I have been trying to use Firebase Auth, without any success.
Following the documentation found here, I came to a point where:

I have created the Firebase project in the Firebase console.

I have created a Service Account, for which I have downloaded the Secret .json file that contains the credentials needed.

I have placed the file in the root directory of my app.

And I use this code to interact with the database:

    $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/path/to/file.json');

    $firebase = (new Factory)
        ->withServiceAccount($serviceAccount)
        ->createAuth();

When dumping the $firebase instance I get this:

^ Kreait\Firebase\Auth {#78 ▼
  -client: Kreait\Firebase\Auth\ApiClient {#55 ▶}
  -tokenGenerator: Firebase\Auth\Token\Generator {#58 ▶}
  -idTokenVerifier: Kreait\Firebase\Auth\IdTokenVerifier {#77 ▶}
}

Which makes me believe the connection is successful, but when I try to list all the users

    $firebase->listUsers();

I get the following

^ Generator {#42 ▼
   this: Kreait\Firebase\Auth {#78 …}
   executing: {▼
     C:\Users\user\Projects\Simple-Api\vendor\kreait\firebase-
php\src\Firebase\Auth.php:110 {▼
       Kreait\Firebase\Auth->listUsers(int $maxResults = 1000, int $batchSize = 1000): Generator …
       › {
       ›     $pageToken = null;
       ›     $count = 0;
     }
   }
   closed: false
 }

And when I try to loop through all the users like this:

   foreach ($users as $user) {
         var_dump($user);
     }

I get these error:

cURL error 60: SSL certificate prblm: unable to get local issuer certificate
cURL error 77: SSL certificate prblm: unable to get local issuer certificate

TEMPORARY FIX (not suggested for production):

Go to Guzzle Client.php class

Set verify to false


问:
PIL thumbnail is rotating my image?
I'm attempting to take large (huge) images (from a digital camera), and convert them into something that I can display on the web. This seems straightforward, and probably should be. However, when I attempt to use PIL to create thumbnail versions, if my source image is taller than it is wide, the resulting image is rotated 90 degrees, such that the top of the source image is on the left of the resulting image. If the source image is wider than it is tall, the resulting image is the correct (original) orientation. Could it have to do with the 2-tuple I send in as the size? I'm using thumbnail, because it appears it was meant to preserve the aspect ratio. Or am I just being completely blind, and doing something dumb? The size tuple is 1000,1000 because I want the longest side to be shrunk to 1000 pixels, while keeping AR preserved.

Code seems simple

```<code>img = Image.open(filename)
img.thumbnail((1000,1000), Image.ANTIALIAS)
img.save(output_fname, "JPEG")
</code>```

Thanks in advance for any help.

答:
There is an easier approach to all this:

```<code>    from PIL import image
    im1 = Image.open(path_to_image)
    im1.thumbnail(size1, Image.ANTIALIAS)
    y, z = im1.size
    d = z * 1.5
    if y > d:
         im1.rotate(90, expand=1)
</code>```

I hope it helps :)

ContentLicense: CC BY-SA 2.5

Title: PIL thumbnail is rotating my image?

Body:
I'm attempting to take large (huge) images (from a digital camera), and convert them into something that I can display on the web. This seems straightforward, and probably should be. However, when I attempt to use PIL to create thumbnail versions, if my source image is taller than it is wide, the resulting image is rotated 90 degrees, such that the top of the source image is on the left of the resulting image. If the source image is wider than it is tall, the resulting image is the correct (original) orientation. Could it have to do with the 2-tuple I send in as the size? I'm using thumbnail, because it appears it was meant to preserve the aspect ratio. Or am I just being completely blind, and doing something dumb? The size tuple is 1000,1000 because I want the longest side to be shrunk to 1000 pixels, while keeping AR preserved.

Code seems simple

img = Image.open(filename)
img.thumbnail((1000,1000), Image.ANTIALIAS)
img.save(output_fname, "JPEG")

Thanks in advance for any help.

Body:
There is an easier approach to all this:

    from PIL import image
    im1 = Image.open(path_to_image)
    im1.thumbnail(size1, Image.ANTIALIAS)
    y, z = im1.size
    d = z * 1.5
    if y > d:
         im1.rotate(90, expand=1)

I hope it helps :)


问:
Scrollbar webkit properties with <ul> tag
In my code I have unordered list inside the div and same time I have added scrollbar to that . I want to use webkit properties with this ul.
I tried as below. </p>

```<code>.list > ul ::-webkit-scrollbar {
 width: 12px;
 background-color: #e4e7eb;
 }

.list > ul::-webkit-scrollbar-thumb {
  outline: 1px solid slategrey;
  border-radius: 14px;
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
  background-color: #ffffff;
}

.list > ul ::-webkit-scrollbar-track {
 -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
  border-radius: 14px;
  background-color: #e4e7eb;
}
</code>```

<p>"list" is div class name.
But this not work for me. Am I used correct way or any other way to use this?</p>

答:
Can you please check with below code hope it will work for you, but make sure it will only work for the Chrome & Safari browsers.

.list > ul {
  height: 150px;
  overflow-x: auto;
}
.list > ul::-webkit-scrollbar {
  width: 10px;
}

/* Track */
.list > ul::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */
.list > ul::-webkit-scrollbar-thumb {
  background: #888;
}

/* Handle on hover */
.list > ul::-webkit-scrollbar-thumb:hover {
  background: #555;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="list">
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
</div></code>```

Body:
In my code I have unordered list inside the div and same time I have added scrollbar to that . I want to use webkit properties with this ul.
I tried as below.

.list > ul ::-webkit-scrollbar {
 width: 12px;
 background-color: #e4e7eb;
 }

.list > ul::-webkit-scrollbar-thumb {
  outline: 1px solid slategrey;
  border-radius: 14px;
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
  background-color: #ffffff;
}

.list > ul ::-webkit-scrollbar-track {
 -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
  border-radius: 14px;
  background-color: #e4e7eb;
}

"list" is div class name.
But this not work for me. Am I used correct way or any other way to use this?

Body:
Can you please check with below code hope it will work for you, but make sure it will only work for the Chrome & Safari browsers.

.list > ul {
  height: 150px;
  overflow-x: auto;
}
.list > ul::-webkit-scrollbar {
  width: 10px;
}

/* Track */
.list > ul::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */
.list > ul::-webkit-scrollbar-thumb {
  background: #888;
}

/* Handle on hover */
.list > ul::-webkit-scrollbar-thumb:hover {
  background: #555;
}

<div class="list">
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
</div>


问:
Best way to convert String to Boolean in Java
I currently have a question about the database of my work.

They use a String based on 0 and 1 to indicate whether it is active or not. But for my logic I would like to use true or false.

Why? Because have redundant code. For example:

```<code>if(foo.getStateClient().equals("1"))
   //Do things...
</code>```

Imagine that with 6 or 7 fields more.

Cant modify the database. And I dont know if use Strings like the before example, or do anything to cast the String a Boolean.

And, always the state is 0 or 1

I appreciate any advice to be more optimal

Edit 1
I am not asking how doing, i am asking the Best practice to do that.

I am using Spring with Hibernate that for people ask me what ORM i am using.

答:
In the database a TINYINT 0/1 can immediately be a boolean on the java side.
So make the fields boolean (just maybe sometimes Boolean) and try whether it works.

In this way one may incrementally refactor all quasi-boolean fields to real ones.

If the fields are CHAR(1) instead, you still might succeed, possibly with some converter on the java entity side.

In this way your data model is clean, and there is no artiificial boiler plate code.

Body:
I currently have a question about the database of my work.

They use a String based on 0 and 1 to indicate whether it is active or not. But for my logic I would like to use true or false.

Why? Because have redundant code. For example:

if(foo.getStateClient().equals("1"))
   //Do things...

Imagine that with 6 or 7 fields more.

Cant modify the database. And I dont know if use Strings like the before example, or do anything to cast the String a Boolean.

And, always the state is 0 or 1

I appreciate any advice to be more optimal

Edit 1
I am not asking how doing, i am asking the Best practice to do that.

I am using Spring with Hibernate that for people ask me what ORM i am using.


问:
Does Pyspark `array` function preserve order?
Does array function pyspark.sql.functions.array(*cols) keep order in creating an array from cols?

As an example, if my dataframe is

```<code>+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   2|   3|
|   2|   4|   6|
|   7|   2|   4|
+----+----+----+
</code>```

Should I always expect it preserves the order in output array?

```<code>df.withColumn('col4', F.array('col1', 'col2', 'col3')).show()
+----+----+----+---------+
|col1|col2|col3|     col4|
+----+----+----+---------+
|   1|   2|   3|[1, 2, 3]|
|   2|   4|   6|[2, 4, 6]|
|   7|   2|   4|[7, 2, 4]|
+----+----+----+---------+
</code>```

Or it might change order of cols in output?

答:
The way you are creating array, it will not change Order. Order will be same in all case. It will keep same order like col1, col2, col3. It is totally depend on the order you use during array creation. It will not change means first value of col4 in your dataframe will be [1, 2, 3], it will be never like [1, 3, 2] or [3, 2, 1].

But if your concern is about vertically order (row wise) then it might change as per partition data. That you can manage by using SortBy, ParitionBy to preserve same order.

Body:
Does array function pyspark.sql.functions.array(*cols) keep order in creating an array from cols?

As an example, if my dataframe is

+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   2|   3|
|   2|   4|   6|
|   7|   2|   4|
+----+----+----+

Should I always expect it preserves the order in output array?

df.withColumn('col4', F.array('col1', 'col2', 'col3')).show()
+----+----+----+---------+
|col1|col2|col3|     col4|
+----+----+----+---------+
|   1|   2|   3|[1, 2, 3]|
|   2|   4|   6|[2, 4, 6]|
|   7|   2|   4|[7, 2, 4]|
+----+----+----+---------+

Or it might change order of cols in output?


问:
React Test Renderer: findAllByProps return double of what It should find when looking for testID in React Native
I'm using React Test Renderer with Jest to test my React Native app.

Here is a simple code example of what I'm doing:

```<code>it('renders one text', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findAllByProps({ testID: 'foo' }).length).toEqual(1);
});

it('renders two texts', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findAllByProps({ testID: 'foo' }).length).toEqual(2);
});
</code>```

The first test fails saying:

```<code>Expected: 1
Received: 2
</code>```

And the second test also fails:

```<code>Expected: 2
Received: 4
</code>```

Why does react test renderer using findAllByProps find double the instances?

PS: As a sanity check I also tried findByProps which works:

```<code>it('renders one text', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findByProps({ testID: 'foo' }).props.children).toEqual(text);
});
</code>```

答:
I've encountered the same issue when testing ReactJS component.

I've taken a deeper look into it and it turns out that under certain conditions findAllByProps may return two TestInstances matching the query, however those do not represent the same entity.
The first entity represents the props passed to the component, the second the actual component with it's whole structure and props applied.

In my case I had been querying for components with a certain className. Typically the constructed component would have it's className made of several aggregated classes (the ones we pass via props and ones we apply internally), however I had mocked the component and the mock used only the class which was passed via props. This way I ended up with two entities having the same single-word className, the first simply stored the props and className was one of them, the second represented the mock which handled the property by passing it directly to the element making it's className equal to the props.className.

I found that mechanism out by serialising the TestInstance object to a JSON.

Body:
I'm using React Test Renderer with Jest to test my React Native app.

Here is a simple code example of what I'm doing:

it('renders one text', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findAllByProps({ testID: 'foo' }).length).toEqual(1);
});

it('renders two texts', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findAllByProps({ testID: 'foo' }).length).toEqual(2);
});

The first test fails saying:

Expected: 1
Received: 2

And the second test also fails:

Expected: 2
Received: 4

Why does react test renderer using findAllByProps find double the instances?

PS: As a sanity check I also tried findByProps which works:

it('renders one text', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findByProps({ testID: 'foo' }).props.children).toEqual(text);
});


问:
How to revoke all jwt tokens for a specific user?
I know an access token is self-contained and therefore can't be revoked.
To my understanding, this is why the expiration time of an access token often is low. This enables one to revoke the refresh token, and thereby only allow users to be signed in, for the expiration time of the access token.

However, if I understand it correctly, a user is able to renew his token infinitely without the use of the refresh token.

One can initiate a silent authentication request by adding prompt=none. This is possible as long as your access token is still valid. Doing so will return a new access token, that is indistinguishable from a login performed directly without the prompt=none parameter.

If I understand this correctly, a user who once got a valid token is able to constantly renew this without me being able to "revoke" his access in any way?

Am I understanding this correctly, and if so, how do I go about revoking a user's access until he manually signs in again?

答:
The prompt=none silent renewal actually uses the user's IDP authentication cookie and not their access token.

The good news is that ASP.Net Core allows you to store the data held in said cookie on the serverside (e.g. in a database or distributed cache) and thus you can revoke said cookie any time you like. By deleting the cookie data related to that user account you effectively invalidate their current session(s) and thus can prevent any future silent renewals. Likewise you can delete all persisted grants (reference tokens and refresh tokens).

Check out the Microsoft.AspNetCore.Authentication.Cookies.ITicketStore interface and the CookieAuthenticationOptions.SessionStore property.


问:
ImportError of module libscrc on Raspberry Pi 3
I'm kinda new to Rpi's and I have a problem executing a library called libscrc with python (I use python3), I need this to calculate a crc checksum for my RS485 communication. On pycharm on my PC everything works fine, but when I implement this on my RPI3 I get errors, I already managed to install the pyserial library and this works fine, but I keep getting errors when trying to run libscrc (this is the link to the library: https://pypi.org/project/libscrc/ ). This is the error:

```<code>Traceback (most recent call last):
  File "Rs_485.py", line 1, in <module>
    import libscrc
  File "/home/pi/.local/lib/python3.6/site-packages/libscrc/__init__.py", line 14, in <module>
    from ._crcx  import *
ImportError: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory
</code>```

Can anyone help me? I already updated and upgraded the RPI.
When I try the following test command

pi@raspberrypi:~/codes $ python -m libscrc.testmodbus

I get:

/usr/bin/python: No module named libscrc

And I'm using python3.6 by the way

答:
Give it a try by using the github link of the libscrc project </p>

```<code>!pip install git+https://github.com/hex-in/libscrc.git
</code>```

<p>It worked this way for me! cheers! </p>

Body:
I'm kinda new to Rpi's and I have a problem executing a library called libscrc with python (I use python3), I need this to calculate a crc checksum for my RS485 communication. On pycharm on my PC everything works fine, but when I implement this on my RPI3 I get errors, I already managed to install the pyserial library and this works fine, but I keep getting errors when trying to run libscrc (this is the link to the library: https://pypi.org/project/libscrc/ ). This is the error:

Traceback (most recent call last):
  File "Rs_485.py", line 1, in <module>
    import libscrc
  File "/home/pi/.local/lib/python3.6/site-packages/libscrc/__init__.py", line 14, in <module>
    from ._crcx  import *
ImportError: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory

Can anyone help me? I already updated and upgraded the RPI.
When I try the following test command

pi@raspberrypi:~/codes $ python -m libscrc.testmodbus

I get:

/usr/bin/python: No module named libscrc

And I'm using python3.6 by the way

Body:
Give it a try by using the github link of the libscrc project

!pip install git+https://github.com/hex-in/libscrc.git

It worked this way for me! cheers!


问:
Python Findall not grabbing all matches
I'm scraping a webpage's HTML code and am currently trying to build a Regex to grab the information I need.
The pattern repeats about 20 times in my example and is as follows:
It should start with tivo (because it will either start with Ativo or Inativo) and should end in "Ver Detalhes".
This pattern repeats for about 20 times as I said before.

The line of code I'm using on this is:

```<code>posts=re.findall('(ativo.*?ver det)',text,re.IGNORECASE)
</code>```

But it doesn't work, as it simply gets 12 matches and I'm not understanding the reason why.
I've tried using .* instead of .*? but then it only extracts 3 matches instead.

The file can be found at the following link:
Source file

Is this something that is possible to extract?

答:
Perhaps some of your desired matches occur across one or more lines, in which case the .* in your pattern would not pick up on that.  A solution would be to do the search with "dot all" mode enabled, e.g.

```<code>posts = re.findall('\b(?:in)?ativo.*?ver detalhes\b', text, flags=re.IGNORECASE|re.DOTALL)
</code>```

I gave this answer going verbatim on what you said in your question:

and should end in "Ver Detalhes"

If you really expect the match to end in just ver det, then use:

```<code>posts = re.findall('\b(?:in)?ativo.*?ver det', text, flags=re.IGNORECASE|re.DOTALL)
</code>```

Title: Python Findall not grabbing all matches

Body:
I'm scraping a webpage's HTML code and am currently trying to build a Regex to grab the information I need.
The pattern repeats about 20 times in my example and is as follows:
It should start with tivo (because it will either start with Ativo or Inativo) and should end in "Ver Detalhes".
This pattern repeats for about 20 times as I said before.

The line of code I'm using on this is:

posts=re.findall('(ativo.*?ver det)',text,re.IGNORECASE)

But it doesn't work, as it simply gets 12 matches and I'm not understanding the reason why.
I've tried using .* instead of .*? but then it only extracts 3 matches instead.

The file can be found at the following link:
Source file

Is this something that is possible to extract?

Body:
Perhaps some of your desired matches occur across one or more lines, in which case the .* in your pattern would not pick up on that.  A solution would be to do the search with "dot all" mode enabled, e.g.

posts = re.findall('\b(?:in)?ativo.*?ver detalhes\b', text, flags=re.IGNORECASE|re.DOTALL)

I gave this answer going verbatim on what you said in your question:

and should end in "Ver Detalhes"

If you really expect the match to end in just ver det, then use:

posts = re.findall('\b(?:in)?ativo.*?ver det', text, flags=re.IGNORECASE|re.DOTALL)


问:
WP plugin: Why do I need to require the dependencies of a library?
In a WordPress plugin, this does NOT work

```<code><?php

/**
 * Plugin Name:       test
 * Plugin URI:        _
 * Description:       _
 * Version:           0.0.1
 * Author:            _
 * Author URI:        _
 * License:           GPL-2.0+
 * License URI:       _
 * Text Domain:       _
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
</code>```

But this DOES work

```<code>require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
</code>```

Where inside class-wp-filesystem-direct you can see that it extends from class-wp-filesystem-base

Why do I need to require the two libraries?

The error was

```<code>Fatal error: Uncaught Error: Class 'WP_Filesystem_Base' not found in /home/..../domains/..../public_html/wp-admin/includes/class-wp-filesystem-direct.php:16
</code>```

答:
The require statement works exactly as it's supposed to, the problem is what you're loading in.  It has dependencies that are unmet, and depends on other things that aren't loaded.

Loading class-wp-filesystem-direct.php will load the things in that file, but it won't go searching for other things it needs. WordPress doesn't use PHP autoloading

So some notes:

WP Admin include files in WordPress don't contain all their dependencies

If you try to load a class that inherits from a class that hasn't been loaded, you'll get a fatal error

You shouldn't be trying to include WP Admin files at the top of your plugin, it can cause issues by loading on the frontend

If you want to work with WP_FileSystem you don't need to load those files and folders

Your problem is that you can't just include random files in WP Admin, they have dependencies that need to be included beforehand.

So your require statement works fine,

Body:
In a WordPress plugin, this does NOT work

<?php

/**
 * Plugin Name:       test
 * Plugin URI:        _
 * Description:       _
 * Version:           0.0.1
 * Author:            _
 * Author URI:        _
 * License:           GPL-2.0+
 * License URI:       _
 * Text Domain:       _
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';

But this DOES work

require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';

Where inside class-wp-filesystem-direct you can see that it extends from class-wp-filesystem-base

Why do I need to require the two libraries?

The error was

Fatal error: Uncaught Error: Class 'WP_Filesystem_Base' not found in /home/..../domains/..../public_html/wp-admin/includes/class-wp-filesystem-direct.php:16


问:
Why implicit property declaration in PHP?
I'm wondering why the PHP language allows implicit property declaration when most languages need to define properties within the class declaration itself (see code below). Is there a practical use for this type of coding style?</p>

```<code>$user1 = new User();
$user1->name = "Kylie";
echo $user1->name;

class User{}
</code>```

答:
The use-case are value objects

```<code>$a = new stdClass;
$a->something = 12;
$a->somethingElse = 'Hello World';
myFunction ($a);
</code>```

This allows to create some objects, that just carry around structured data (something like structs in other languages), without the need to define a class for it.

Another point is, that -- because PHP is weakly-typed anyway -- there is no real reason to forbid it. If you need something stronger, overweite __set()

```<code>public function __set ($propertyName, $value) {
  throw new Exception("Undefined Property $propertyName");
}
</code>```

Body:
I'm wondering why the PHP language allows implicit property declaration when most languages need to define properties within the class declaration itself (see code below). Is there a practical use for this type of coding style?

$user1 = new User();
$user1->name = "Kylie";
echo $user1->name;

class User{}

Body:
The use-case are value objects

$a = new stdClass;
$a->something = 12;
$a->somethingElse = 'Hello World';
myFunction ($a);

This allows to create some objects, that just carry around structured data (something like structs in other languages), without the need to define a class for it.

Another point is, that -- because PHP is weakly-typed anyway -- there is no real reason to forbid it. If you need something stronger, overweite __set()

public function __set ($propertyName, $value) {
  throw new Exception("Undefined Property $propertyName");
}


问:
How to read data using the spreadsheets API without using oauth2
This is Yet another error 403 on Google Sheets API. Um trying to read the data from a Spreadsheet and expose it on a website, using some custom HTML filters.

So, there is this question:
Error 403 on Google Sheets API

Still, I cannot figure out what to do. I have setup my service account in the google cloud platform, granted it permissions to access my Spreadsheet - I have even made my SpreadSheet accessible via link (but that is restricted to emails from my organization, so it seems useless anyway). I've also activated domain-wide delegation for my service account - didn't make any difference at all. I'm pretty sure the issue is not related to a wrong key or some typo because, when I remove the access to the service email from the sheet, I steel get a 403 error, but it comes with a message saying the caller doesn't have access to that spreadsheet.

People keep mentioning OAuth, but I don't want to use that, since I'm intending to use a simple API access, as in this Google GitHub example. I'm using my business account, so there might be some issue related to that.

Here is the HTML (which I'm running from a simple HTTP server on python, not directly, given the fact the GAPI doesn't handle localhost/ sources very well):

<!DOCTYPE html>

    <title>Google Sheets API Quickstart</title>
    <meta charset="utf-8" />

Google Sheets API Quickstart

    <button id="authorize_button" style="display: none;">Authorize</button>
    <button id="signout_button" style="display: none;">Sign Out</button>

```

    <script type="text/javascript">
      // Client ID and API key from the Developer Console
      var API_KEY = 'My-API-KEY';
      var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
      var SCOPES = "https://www.googleapis.com/auth/spreadsheets.readonly";

      function handleClientLoad() {
        gapi.load('client', initClient);
      }

      function initClient() {
        gapi.client.init({
          apiKey: API_KEY,
          discoveryDocs: DISCOVERY_DOCS
        }).then(function(){listMajors();})
      }

      function appendPre(message) {
        var pre = document.getElementById('content');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }

      function listMajors() {
        gapi.client.sheets.spreadsheets.values.get({
          spreadsheetId: 'my-spreadsheet-id',
          range: 'Sheet1!A1:A10',
        }).then(function(response) {
          var range = response.result;
          if (range.values.length > 0) {
            appendPre('Name, Major:');
            for (i = 0; i < range.values.length; i++) {
              var row = range.values[i];
              // Print columns A and E, which correspond to indices 0 and 4.
              appendPre(row[0] + ', ' + row[4]);
            }
          } else {
            appendPre('No data found.');
          }
        }, function(response) {
          appendPre('Error: ' + response.result.error.message);
        });
      }
    </script>

    <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === lete') this.onload()">
    </script>
  </body>
</html>

</code>```

Does anyone have anyclue on what I'm missing, or what else can I try?

Edit: sharing the spreadsheet publicly is not an option. The is a business email, and, therefore, the only option I've got here is sharing it domain wide, as I've already stated above. Also, this is a business spreadsheet, and therefofe contains sentitive data. Doesn't really make sense to expose it publicly. Besides that, I've already shared the spreadsheet with the service email. What I'm trying to achieve, after all, is to read the data from the spreadsheet without using oauth, and emdding it on a website (I know there is a built-in embed tool, but that doesn't suit me because I need to add a html filter).

答:
If you try to access a Spreadsheet that is not public, you will have to use OAuth 2.0. Since it is not a public resource, you have to use the credentials of an account that has access to this resource.

In the example you provided, they are accessing a public resource, so the API key is enough. That's not your case.

Reference:

Using OAuth 2.0 to Access Google APIs

Body:
This is Yet another error 403 on Google Sheets API. Um trying to read the data from a Spreadsheet and expose it on a website, using some custom HTML filters.

So, there is this question:
Error 403 on Google Sheets API

Still, I cannot figure out what to do. I have setup my service account in the google cloud platform, granted it permissions to access my Spreadsheet - I have even made my SpreadSheet accessible via link (but that is restricted to emails from my organization, so it seems useless anyway). I've also activated domain-wide delegation for my service account - didn't make any difference at all. I'm pretty sure the issue is not related to a wrong key or some typo because, when I remove the access to the service email from the sheet, I steel get a 403 error, but it comes with a message saying the caller doesn't have access to that spreadsheet.

People keep mentioning OAuth, but I don't want to use that, since I'm intending to use a simple API access, as in this Google GitHub example. I'm using my business account, so there might be some issue related to that.

Here is the HTML (which I'm running from a simple HTTP server on python, not directly, given the fact the GAPI doesn't handle localhost/ sources very well):

<!DOCTYPE html>

    <title>Google Sheets API Quickstart</title>
    <meta charset="utf-8" />

Google Sheets API Quickstart

    <button id="authorize_button" style="display: none;">Authorize</button>
    <button id="signout_button" style="display: none;">Sign Out</button>

Does anyone have anyclue on what I'm missing, or what else can I try?

Edit: sharing the spreadsheet publicly is not an option. The is a business email, and, therefore, the only option I've got here is sharing it domain wide, as I've already stated above. Also, this is a business spreadsheet, and therefofe contains sentitive data. Doesn't really make sense to expose it publicly. Besides that, I've already shared the spreadsheet with the service email. What I'm trying to achieve, after all, is to read the data from the spreadsheet without using oauth, and emdding it on a website (I know there is a built-in embed tool, but that doesn't suit me because I need to add a html filter).


问:
How to find out the location of currently used MySQL configuration file in linux
How do I know which configuration file is used by MySQL currently? Is there any command or something to find it out?</p>

答:
you can find it by running the following command

```<code>mysql --help
</code>```

it will give you the mysql installed directory and all commands for mysql.

Body:
you can find it by running the following command

mysql --help

it will give you the mysql installed directory and all commands for mysql.


问:
php multiple headers
I'm using a header to show succes message after submit. I also want to redirect the user to the index.php page after 5 seconds, but somehow it doesn't work.</p>

```<code>if(mysqli_query($link, $sql)){
    header("Location: addbusiness.php?message=<div class='alert alert-success' role='alert' style='text-align: center; margin-bottom: 50px;'>Succes.</div>");
    header( "refresh:5;url=index.php" );
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
</code>```

答:
You simply can't do location and refresh at the same time, so you have to separate both headers, i.e. the refresh should be part of the page where you are displaying the message. Also, there is no reason (it's a bad practice actually) to pass entire HTML into the URL, better use some ID, like:

db.php

```<code><?php
    if(mysqli_query($link, $sql)){
        header("Location: addbusiness.php?message=1");
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
?>
</code>```

addbusiness.php

```<code><?php
    if(!empty($_GET['message'])){
        if($_GET['message'] == 1){
            header( "refresh:5;url=index.php" );
            echo "<div class='alert alert-success' role='alert' style='text-align: center; margin-bottom: 50px;'>Success.</div>";
        }else{
            //do something else
        }
    }
?>
</code>```

Based on such a condition, you also will avoid the refresh every time when visits addbusiness.php

Of course, in any case you have to ensure that there is no any HTML output to the browser before calling header(). In both pages.

Title: php multiple headers

Body:
I'm using a header to show succes message after submit. I also want to redirect the user to the index.php page after 5 seconds, but somehow it doesn't work.

if(mysqli_query($link, $sql)){
    header("Location: addbusiness.php?message=
Succes.
");
    header( "refresh:5;url=index.php" );
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

Body:
You simply can't do location and refresh at the same time, so you have to separate both headers, i.e. the refresh should be part of the page where you are displaying the message. Also, there is no reason (it's a bad practice actually) to pass entire HTML into the URL, better use some ID, like:

db.php

<?php
    if(mysqli_query($link, $sql)){
        header("Location: addbusiness.php?message=1");
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
?>

addbusiness.php

<?php
    if(!empty($_GET['message'])){
        if($_GET['message'] == 1){
            header( "refresh:5;url=index.php" );
            echo "<div class='alert alert-success' role='alert' style='text-align: center; margin-bottom: 50px;'>Success.</div>";
        }else{
            //do something else
        }
    }
?>

Based on such a condition, you also will avoid the refresh every time when visits addbusiness.php

Of course, in any case you have to ensure that there is no any HTML output to the browser before calling header(). In both pages.


问:
How to run GitHub Actions workflows locally?
I am planning to move our Travis CI build to GitHub Actions using Docker for our per-commit testing.

Can I reproducibly run these new GitHub Actions workflows locally? Is there a generic way to run any GitHub Actions workflow locally?

答:
You can use nektos/act which supports yaml syntax since 0.2.0 (prerelease).

Check out their latest release.