问:
Splitting date and time then put into other column
I'm working a small date time project. From my CSV file I have 4 columns, called Name, Employee ID, Data/Time, Status and in my Database columns are name, empID, date, timeIn, timeOut, Status.

Picture of my csv file: (Picture A)

And here is what I want to save in my database: (Picture B)

Example input CSV string:

```<code>Name,"Empoyee ID",Date/Time,Status
"Soriano, Jhoniel",901,"05/03/2019 1:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/04/2019 2:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/04/2019 3:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/06/2019 4:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/06/2019 5:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/07/2019 6:01:03 PM",C/In
</code>```

How can I get started on this problem?

Edit

I want to thanks @jimmix for giving me some idea to get started.

Here is the real scenario:

From my CSV file, I have the data you can found at (Picture A), then I will upload using my upload() function in into my MySQL database with the table name "tbldumpbio",

See the table structure below:

From my table tbldumpbio data, I have a function called processTimesheet()

Here's the code:

```<code>public function processTimesheet(){
        $this->load->model('dbquery');

            $query = $this->db->query("SELECT * FROM tbldumpbio");

            foreach ($query->result() as $row){

            $dateTimeExplArr = explode(' ', $row->datetimex);

            $dateStr = $dateTimeExplArr[0];
            $timeStr = $dateTimeExplArr[1];

            if($row->status='C/Out' and !isset($timeStr) || empty($timeStr) ){
                $timeStrOut ='';
            } else {
                $timeStrOut = $dateTimeExplArr[1];
            }

            if($row->status='C/In' and !isset($timeStr) || empty($timeStr) ){
                $timeStrIn ='';
            } else {
                $timeStrIn = $dateTimeExplArr[1];
            }

            $data = array(
                'ID' => '',
                'companyAccessID' => '',
                'name' => $row->name,
                'empCompID' => $row->empid,
                'date' => $dateStr,
                'timeIn' => $timeStrIn,
                'timeOut' => $timeStrOut,
                'status' => '',
                'inputType' => ''
            );
            $this->dbquery->modInsertval('tblempbioupload',$data);

            }
    }
</code>```

This function will add a another data into tblempbioupload. But here are the results that I'm getting with:

Please see the below data:

The problem is:

the date should not be duplicated

Time In data should be added if the status is 'C/In'

Time Out data should be added if the status is 'C/Out'

The expected result should be something like this:

答:
Not the shortest one but working:

```<code><?php

$csvMultilineStr =
'Name,"Empoyee ID",Date/Time,Status
"Soriano, Jhoniel",901,"05/03/2019 1:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/04/2019 2:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/04/2019 3:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/06/2019 4:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/06/2019 5:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/07/2019 6:01:03 PM",C/In';

//read CSV as every line = 1 array item
$csvArr = explode("\n", $csvMultilineStr);

//get header line as array of column names
//and remove that line from $csvArr
$headerArr = str_getcsv(array_shift($csvArr));

$emplIdKeyStr = "Empoyee ID";
$resultArr = [];

/**
 * Create array of arrays
 * that each array inside an array
 * is under key of emploeeId and
 * represents one CSV row
 *
 * [
 *   901 => [
 *              0 => [
 *                      'Name' => value
 *                      'Empoyee ID' => value2
 *                      ...
 *                  ],
 *             1 => [
 *                      'Name' => value
 *                      'Empoyee ID' => value2
 *                      ...
 *                  ]
 *          ]
 * ]
 *
 */
foreach($csvArr as $csvLineStr) {
    $csvEntryArr = str_getcsv($csvLineStr);
    $csvLineArr = array_combine($headerArr, $csvEntryArr);
    $emplIdInt = $csvLineArr[$emplIdKeyStr];
    $resultArr[$emplIdInt][] = $csvLineArr;
}

var_export($resultArr);

/**
 * Create array of arrays
 * as above but with key => value
 * structure
 *
 * [
 *  901 => [
 *              '05/03/2019' => [
 *                                  'C/In' => ...
 *                                  'C/Out' => ...
 *                                  'name' => ...
 *                              ]
 *          ]
 * ]
 *
 */
$resultTimeIoArr = [];
$timeInOutColSwStr = 'Status';
$dateTimeColStr = 'Date/Time';
foreach($resultArr as $emplIdInt => $emplEntyArr) {

    foreach($emplEntyArr as $emplSingleEntryArr) {
        $dateTimeStr = $emplSingleEntryArr[$dateTimeColStr];

        $dateTimeExplArr = explode(' ', $dateTimeStr);
        $dateStr = $dateTimeExplArr[0];
        $timeStr = $dateTimeExplArr[1];

        $resultTimeIoArr[$emplIdInt][$dateStr][$emplSingleEntryArr[$timeInOutColSwStr]] = $timeStr;
        $resultTimeIoArr[$emplIdInt][$dateStr]['name'] = '"' . $emplSingleEntryArr['Name'] . '"';
    }
}

/**
 * get sorted array by EmplId, Date, C/In or C/Out
 * as an arry similar to first one CsvArr
 */
$resultCsvArr = [];
$resultCsvLineArr = [];
foreach($resultTimeIoArr as $emplIdInt => $singleEmplArr) {

    foreach($singleEmplArr as $dateStr => $signleIoArr) {

        $resultCsvLineArr['Name'] = $signleIoArr['name'];
        $resultCsvLineArr['EmpID'] = $emplIdInt;
        $resultCsvLineArr['Date'] = $dateStr;

        if(!isset($signleIoArr['C/In']) || empty($signleIoArr['C/In'])) {
            $timeIn = '';
        } else {
            $timeIn = $signleIoArr['C/In'];
        }

        if(!isset($signleIoArr['C/Out']) || empty($signleIoArr['C/Out'])) {
            $timeOut = '';
        } else {
            $timeOut = $signleIoArr['C/Out'];
        }

        $resultCsvLineArr['timeIn'] = $timeIn;
        $resultCsvLineArr['timeOut'] = $timeOut;
        $resultCsvArr[] = $resultCsvLineArr;
    }
}

echo "--- Array Result ---\n";
var_export($resultCsvArr);

//get header line as arry of column names
//from the keys of the first array
$head = array_keys($resultCsvArr[0]);

//put arr of header as 1st sting to csv string
$csvStr = implode(',',$head) . "\n";

//put all the rest in result sting
foreach($resultCsvArr as $resultEntryArr) {
    $csvStr .= implode(',',$resultEntryArr) . "\n";
}

// file_put_contents('path-to-file', $csvStr);

echo "\n\n --- CSV Result ---\n";
print_r($csvStr);
</code>```

gives output:

--- Array Result ---

```<code>array (
  0 =>
  array (
    'Name' => '"Soriano, Jhoniel"',
    'EmpID' => 901,
    'Date' => '05/03/2019',
    'timeIn' => '',
    'timeOut' => '1:01:03',
  ),
  1 =>
  array (
    'Name' => '"Soriano, Jhoniel"',
    'EmpID' => 901,
    'Date' => '05/04/2019',
    'timeIn' => '2:01:03',
    'timeOut' => '3:01:03',
  ),
  2 =>
  array (
    'Name' => '"Soriano, Jhoniel"',
    'EmpID' => 901,
    'Date' => '05/06/2019',
    'timeIn' => '4:01:03',
    'timeOut' => '5:01:03',
  ),
  3 =>
  array (
    'Name' => '"Soriano, Jhoniel"',
    'EmpID' => 901,
    'Date' => '05/07/2019',
    'timeIn' => '6:01:03',
    'timeOut' => '',
  ),
)
</code>```

--- CSV Result ---

```<code>Name,EmpID,Date,timeIn,timeOut
"Soriano, Jhoniel",901,05/03/2019,,1:01:03
"Soriano, Jhoniel",901,05/04/2019,2:01:03,3:01:03
"Soriano, Jhoniel",901,05/06/2019,4:01:03,5:01:03
"Soriano, Jhoniel",901,05/07/2019,6:01:03,
</code>```

use:

```<code>file_put_contents('path-to-file', $csvStr);
</code>```

at the end to save the csv to file.

Body:
I'm working a small date time project. From my CSV file I have 4 columns, called Name, Employee ID, Data/Time, Status and in my Database columns are name, empID, date, timeIn, timeOut, Status.

Picture of my csv file: (Picture A)

And here is what I want to save in my database: (Picture B)

Example input CSV string:

Name,"Empoyee ID",Date/Time,Status
"Soriano, Jhoniel",901,"05/03/2019 1:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/04/2019 2:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/04/2019 3:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/06/2019 4:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/06/2019 5:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/07/2019 6:01:03 PM",C/In

How can I get started on this problem?

Edit

I want to thanks @jimmix for giving me some idea to get started.

Here is the real scenario:

From my CSV file, I have the data you can found at (Picture A), then I will upload using my upload() function in into my MySQL database with the table name "tbldumpbio",

See the table structure below:

From my table tbldumpbio data, I have a function called processTimesheet()

Here's the code:

public function processTimesheet(){
        $this->load->model('dbquery');

            $query = $this->db->query("SELECT * FROM tbldumpbio");

            foreach ($query->result() as $row){

            $dateTimeExplArr = explode(' ', $row->datetimex);

            $dateStr = $dateTimeExplArr[0];
            $timeStr = $dateTimeExplArr[1];

            if($row->status='C/Out' and !isset($timeStr) || empty($timeStr) ){
                $timeStrOut ='';
            } else {
                $timeStrOut = $dateTimeExplArr[1];
            }

            if($row->status='C/In' and !isset($timeStr) || empty($timeStr) ){
                $timeStrIn ='';
            } else {
                $timeStrIn = $dateTimeExplArr[1];
            }

            $data = array(
                'ID' => '',
                'companyAccessID' => '',
                'name' => $row->name,
                'empCompID' => $row->empid,
                'date' => $dateStr,
                'timeIn' => $timeStrIn,
                'timeOut' => $timeStrOut,
                'status' => '',
                'inputType' => ''
            );
            $this->dbquery->modInsertval('tblempbioupload',$data);

            }
    }

This function will add a another data into tblempbioupload. But here are the results that I'm getting with:

Please see the below data:

The problem is:

the date should not be duplicated

Time In data should be added if the status is 'C/In'

Time Out data should be added if the status is 'C/Out'

The expected result should be something like this:

Body:
Not the shortest one but working:

<?php

$csvMultilineStr =
'Name,"Empoyee ID",Date/Time,Status
"Soriano, Jhoniel",901,"05/03/2019 1:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/04/2019 2:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/04/2019 3:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/06/2019 4:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/06/2019 5:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/07/2019 6:01:03 PM",C/In';

//read CSV as every line = 1 array item
$csvArr = explode("\n", $csvMultilineStr);

//get header line as array of column names
//and remove that line from $csvArr
$headerArr = str_getcsv(array_shift($csvArr));

$emplIdKeyStr = "Empoyee ID";
$resultArr = [];

/**
 * Create array of arrays
 * that each array inside an array
 * is under key of emploeeId and
 * represents one CSV row
 *
 * [
 *   901 => [
 *              0 => [
 *                      'Name' => value
 *                      'Empoyee ID' => value2
 *                      ...
 *                  ],
 *             1 => [
 *                      'Name' => value
 *                      'Empoyee ID' => value2
 *                      ...
 *                  ]
 *          ]
 * ]
 *
 */
foreach($csvArr as $csvLineStr) {
    $csvEntryArr = str_getcsv($csvLineStr);
    $csvLineArr = array_combine($headerArr, $csvEntryArr);
    $emplIdInt = $csvLineArr[$emplIdKeyStr];
    $resultArr[$emplIdInt][] = $csvLineArr;
}

var_export($resultArr);

/**
 * Create array of arrays
 * as above but with key => value
 * structure
 *
 * [
 *  901 => [
 *              '05/03/2019' => [
 *                                  'C/In' => ...
 *                                  'C/Out' => ...
 *                                  'name' => ...
 *                              ]
 *          ]
 * ]
 *
 */
$resultTimeIoArr = [];
$timeInOutColSwStr = 'Status';
$dateTimeColStr = 'Date/Time';
foreach($resultArr as $emplIdInt => $emplEntyArr) {

    foreach($emplEntyArr as $emplSingleEntryArr) {
        $dateTimeStr = $emplSingleEntryArr[$dateTimeColStr];

        $dateTimeExplArr = explode(' ', $dateTimeStr);
        $dateStr = $dateTimeExplArr[0];
        $timeStr = $dateTimeExplArr[1];

        $resultTimeIoArr[$emplIdInt][$dateStr][$emplSingleEntryArr[$timeInOutColSwStr]] = $timeStr;
        $resultTimeIoArr[$emplIdInt][$dateStr]['name'] = '"' . $emplSingleEntryArr['Name'] . '"';
    }
}

/**
 * get sorted array by EmplId, Date, C/In or C/Out
 * as an arry similar to first one CsvArr
 */
$resultCsvArr = [];
$resultCsvLineArr = [];
foreach($resultTimeIoArr as $emplIdInt => $singleEmplArr) {

    foreach($singleEmplArr as $dateStr => $signleIoArr) {

        $resultCsvLineArr['Name'] = $signleIoArr['name'];
        $resultCsvLineArr['EmpID'] = $emplIdInt;
        $resultCsvLineArr['Date'] = $dateStr;

        if(!isset($signleIoArr['C/In']) || empty($signleIoArr['C/In'])) {
            $timeIn = '';
        } else {
            $timeIn = $signleIoArr['C/In'];
        }

        if(!isset($signleIoArr['C/Out']) || empty($signleIoArr['C/Out'])) {
            $timeOut = '';
        } else {
            $timeOut = $signleIoArr['C/Out'];
        }

        $resultCsvLineArr['timeIn'] = $timeIn;
        $resultCsvLineArr['timeOut'] = $timeOut;
        $resultCsvArr[] = $resultCsvLineArr;
    }
}

echo "--- Array Result ---\n";
var_export($resultCsvArr);

//get header line as arry of column names
//from the keys of the first array
$head = array_keys($resultCsvArr[0]);

//put arr of header as 1st sting to csv string
$csvStr = implode(',',$head) . "\n";

//put all the rest in result sting
foreach($resultCsvArr as $resultEntryArr) {
    $csvStr .= implode(',',$resultEntryArr) . "\n";
}

// file_put_contents('path-to-file', $csvStr);

echo "\n\n --- CSV Result ---\n";
print_r($csvStr);

gives output:

--- Array Result ---

array (
  0 =>
  array (
    'Name' => '"Soriano, Jhoniel"',
    'EmpID' => 901,
    'Date' => '05/03/2019',
    'timeIn' => '',
    'timeOut' => '1:01:03',
  ),
  1 =>
  array (
    'Name' => '"Soriano, Jhoniel"',
    'EmpID' => 901,
    'Date' => '05/04/2019',
    'timeIn' => '2:01:03',
    'timeOut' => '3:01:03',
  ),
  2 =>
  array (
    'Name' => '"Soriano, Jhoniel"',
    'EmpID' => 901,
    'Date' => '05/06/2019',
    'timeIn' => '4:01:03',
    'timeOut' => '5:01:03',
  ),
  3 =>
  array (
    'Name' => '"Soriano, Jhoniel"',
    'EmpID' => 901,
    'Date' => '05/07/2019',
    'timeIn' => '6:01:03',
    'timeOut' => '',
  ),
)

--- CSV Result ---

Name,EmpID,Date,timeIn,timeOut
"Soriano, Jhoniel",901,05/03/2019,,1:01:03
"Soriano, Jhoniel",901,05/04/2019,2:01:03,3:01:03
"Soriano, Jhoniel",901,05/06/2019,4:01:03,5:01:03
"Soriano, Jhoniel",901,05/07/2019,6:01:03,

use:

file_put_contents('path-to-file', $csvStr);

at the end to save the csv to file.


来源: stackexchange

问:
Remove the first element from a multidimensional array with PHP
Form this array, how can I remove the first element of Provinces ?

```<code>Array
(
    [Country] => Canada
    [Provinces] => Array
        (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)
</code>```

Thanks.

答:
You can do that with unset():

unset( $myArray['Cities'][0] )

https://www.php.net/manual/en/function.unset.php

ContentLicense: CC BY-SA 4.0

Body:
Form this array, how can I remove the first element of Provinces ?

Array
(
    [Country] => Canada
    [Provinces] => Array
        (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)

Thanks.


问:
lxml returned me a list but it's empty
I was trying to make a list of all the top 1000 instagramer's acount from this website:'https://hypeauditor.com/top-instagram/'.
The list that returns from lxml is empty for both lxml.html and lxml.etree.

I tried to delete tbody, delete text(), and upper xpath, but it all failed.
what worth noticing is that, with upper xpath, it did return me something, but it is all but /n.

I first tried lxml.etree

```<code>market_url='https://hypeauditor.com/top-instagram/'
r_market=requests.get(market_url)
s_market=etree.HTML(r_market)`
file_market=s_market.xpath('//*[@id="bloggers-top-table"]/tr[1]/td[3]/a/text()')
</code>```

then I also tried lxml.html.

```<code>tree=html.fromstring(r_market.content)
result=tree.xpath('//*[@id="bloggers-top-table"]/tr/td/h4/text()')
</code>```

furthermore, I tried this xpath:

```<code>s_market.xpath('//*[@id="bloggers-top-table"]/tbody/text()')
</code>```

It did not give me any error. But after all the attempts, it still gives me wether empty list or a list full of n/.

I am not really experienced in web scraping so it is possible that I have just made a stupid error somewhere, but since without the data I can not start my machine learning model, I am really struggling, pls help.

答:
An easier way to do this would be to use pandas. It can read simple HTML Tables like this no problem. Try the following code to scrape the whole table.

```<code>import pandas as pd

df = pd.read_html('https://hypeauditor.com/top-instagram/')
</code>```

Title: lxml returned me a list but it's empty

Body:
I was trying to make a list of all the top 1000 instagramer's acount from this website:'https://hypeauditor.com/top-instagram/'.
The list that returns from lxml is empty for both lxml.html and lxml.etree.

I tried to delete tbody, delete text(), and upper xpath, but it all failed.
what worth noticing is that, with upper xpath, it did return me something, but it is all but /n.

I first tried lxml.etree

market_url='https://hypeauditor.com/top-instagram/'
r_market=requests.get(market_url)
s_market=etree.HTML(r_market)`
file_market=s_market.xpath('//*[@id="bloggers-top-table"]/tr[1]/td[3]/a/text()')

then I also tried lxml.html.

tree=html.fromstring(r_market.content)
result=tree.xpath('//*[@id="bloggers-top-table"]/tr/td/h4/text()')

furthermore, I tried this xpath:

s_market.xpath('//*[@id="bloggers-top-table"]/tbody/text()')

It did not give me any error. But after all the attempts, it still gives me wether empty list or a list full of n/.

I am not really experienced in web scraping so it is possible that I have just made a stupid error somewhere, but since without the data I can not start my machine learning model, I am really struggling, pls help.

Body:
An easier way to do this would be to use pandas. It can read simple HTML Tables like this no problem. Try the following code to scrape the whole table.

import pandas as pd

df = pd.read_html('https://hypeauditor.com/top-instagram/')


问:
How do I set trial period to android application before publishing in android market?
I have one query regarding android market. Actually I am going to launch an android application in market. I have read all steps before launching app in market means that versioning of app, signing of app and licensing of app. Actually the licensing of app is only for paid app. But I am going to launch my app using trial period. Suppose I want to publish my app for 30 days free to the user. After 30 days when user going to open that app, it will not be further accessible to the user. It will tell to the user to purchase it from the market.

is Licensing of app will be useful in this case? I have read that docs, but i am not getting the clear idea. Please suggest me what should I do in this case?

答: There's no easy way to do that that get's around uninstalling and reinstalling the app. You can do it by autogenerating some sort of login and using a unique device ID and communicating it to a server you own.</p>

ContentLicense: CC BY-SA 3.0


问:
How to count specific array values and assign the values in a table data
Here's my problem i have two arrays , one is multi dimensional array the second one is single array, these arrays is displayed in a two table. the multi-array is display in table 1 and single is in table 2. what i want to do is to count the number of employees for each position.

```<code><?php include_once('fake_db.php'); ?>

<h3>Department List</h3>
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
    <thead>
    <tr>
        <td>Name</td><td>Number of Employees</td><td>Action</td>
    </tr>
    </thead>
   <?php foreach($positions as $key => $value){ ?>

        <tr>
            <td><?= $value; ?></td>
            <td></td>
            <td><a href="profile.php?id=<?= $key; ?>">View Employee List</a></td>
        </tr>
    <?php } ?>
</table>
</code>```

fake_db.php

```<code>$employees = array
             (
                 array("name" => 'Jason Alipala', "employee_id" => 'G1001-05', "position" => 1),
                 array("name" => 'Bryann Revina', "employee_id" => 'G1009-03', "position" => 2),
                 array("name" => 'Jeniel Mangahis', "employee_id" => 'G1009-04', "position" => 2),
                 array("name" => 'Arjay Bussala', "employee_id" => 'G1009-05', "position" => 3),
                 array("name" => 'Ronnel Ines', "employee_id" => 'G1002-06', "position" => 3)
             );

$positions = array(1 => 'TL', 2 => 'Programmer', 3 => 'Converter');
</code>```

答:
To count the number of employees for each position, you can use array_count_values on the position column of the the employees array. For example:

```<code>$emp_positions = array_count_values(array_column($employees, 'position'));
foreach ($positions as $key => $value) {
    echo $positions[$key] . ' : ' . $emp_positions[$key] . ' employees' . PHP_EOL;
}
</code>```

Output:

```<code>TL : 1 employees
Programmer : 2 employees
Converter : 2 employees
</code>```

Demo on 3v4l.org

Body:
Here's my problem i have two arrays , one is multi dimensional array the second one is single array, these arrays is displayed in a two table. the multi-array is display in table 1 and single is in table 2. what i want to do is to count the number of employees for each position.

<?php include_once('fake_db.php'); ?>

Department List

        Name	Number of Employees	Action

   <?php foreach($positions as $key => $value){ ?>

            <?= $value; ?>

            <a href="profile.php?id=<?= $key; ?>">View Employee List

    <?php } ?>

fake_db.php

$employees = array
             (
                 array("name" => 'Jason Alipala', "employee_id" => 'G1001-05', "position" => 1),
                 array("name" => 'Bryann Revina', "employee_id" => 'G1009-03', "position" => 2),
                 array("name" => 'Jeniel Mangahis', "employee_id" => 'G1009-04', "position" => 2),
                 array("name" => 'Arjay Bussala', "employee_id" => 'G1009-05', "position" => 3),
                 array("name" => 'Ronnel Ines', "employee_id" => 'G1002-06', "position" => 3)
             );

$positions = array(1 => 'TL', 2 => 'Programmer', 3 => 'Converter');

Body:
To count the number of employees for each position, you can use array_count_values on the position column of the the employees array. For example:

$emp_positions = array_count_values(array_column($employees, 'position'));
foreach ($positions as $key => $value) {
    echo $positions[$key] . ' : ' . $emp_positions[$key] . ' employees' . PHP_EOL;
}

Output:

TL : 1 employees
Programmer : 2 employees
Converter : 2 employees

Demo on 3v4l.org


问:
How to structure nested Promises
I have a situation where I think the only choice for me is to nest some Promises within each other. I have a Promise that needs to be performed and a method that does something until that Promise is complete. Something like this:

```<code>let promise = new Promise((resolve, reject) => {

  // Do some stuff

});

doSomethingUntilPromiseisDone(promise);
</code>```

However, within my Promise, I need to execute another method that returns another Promise:

```<code>let promise = new Promise((resolve, reject) => {

  fetchValue(url)
    .then((value) => {

      // Do something here

    }).catch((err) => {
      console.error(err);
    });

});

doSomethingUntilPromiseisDone(promise);
</code>```

But now, in the fetchValue method's then statement, I have another method I need to execute that, guess what, returns another Promise:

```<code>let promise = new Promise((resolve, reject) => {

  fetchValue(url)
    .then((value) => {

      saveToCache(value)
        .then((success) => {

          console.log('success!!');
          resolve('success');

        });

    }).catch((err) => {
      console.error(err);
    });

});

doSomethingUntilPromiseisDone(promise);
</code>```

So in the end, I have a Promise, within a Promise, within a Promise. Is there someway I can structure this better so that it is more straightforward? It seems like nesting them within each other is counter to Promise's intended chaining approach.

答:
Each function will call the next one with the result of the method before.</p>

```<code>var promises = [1,2,3].map((guid)=>{
    return (param)=> {
      console.log("param", param);
      var id = guid;
      return new Promise(resolve => {
        // resolve in a random amount of time
        setTimeout(function () {
          resolve(id);
        }, (Math.random() * 1.5 | 0) * 1000);
      });
    }
}).reduce(function (acc, curr, index) {
  return acc.then(function (res) {
    return curr(res[index-1]).then(function (result) {
      console.log("result", result);
      res.push(result);
      return res;
    });
  });
}, Promise.resolve([]));
promises.then(console.log);
</code>```

Title: How to structure nested Promises

Body:
I have a situation where I think the only choice for me is to nest some Promises within each other. I have a Promise that needs to be performed and a method that does something until that Promise is complete. Something like this:

let promise = new Promise((resolve, reject) => {

  // Do some stuff

});

doSomethingUntilPromiseisDone(promise);

However, within my Promise, I need to execute another method that returns another Promise:

let promise = new Promise((resolve, reject) => {

  fetchValue(url)
    .then((value) => {

      // Do something here

    }).catch((err) => {
      console.error(err);
    });

});

doSomethingUntilPromiseisDone(promise);

But now, in the fetchValue method's then statement, I have another method I need to execute that, guess what, returns another Promise:

let promise = new Promise((resolve, reject) => {

  fetchValue(url)
    .then((value) => {

      saveToCache(value)
        .then((success) => {

          console.log('success!!');
          resolve('success');

        });

    }).catch((err) => {
      console.error(err);
    });

});

doSomethingUntilPromiseisDone(promise);

So in the end, I have a Promise, within a Promise, within a Promise. Is there someway I can structure this better so that it is more straightforward? It seems like nesting them within each other is counter to Promise's intended chaining approach.

Body:
Each function will call the next one with the result of the method before.

var promises = [1,2,3].map((guid)=>{
    return (param)=> {
      console.log("param", param);
      var id = guid;
      return new Promise(resolve => {
        // resolve in a random amount of time
        setTimeout(function () {
          resolve(id);
        }, (Math.random() * 1.5 | 0) * 1000);
      });
    }
}).reduce(function (acc, curr, index) {
  return acc.then(function (res) {
    return curr(res[index-1]).then(function (result) {
      console.log("result", result);
      res.push(result);
      return res;
    });
  });
}, Promise.resolve([]));
promises.then(console.log);


问:
Flutter CLI works in mac terminal but not in VSCode or Android Studio
As a title, I don't know why their build in Terminal in VSCode or Android Studio are not working.

bash: flutter: command not found

I have set Flutter path in ~/.bash_profile. here is the result of echo $PATH

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/dotnet:~/.dotnet/tools:/Applications/Visual
  Studio Code.app/Contents/Resources/app/bin:/Users/Mac/flutter/bin

答:
I have found the problem it's because I use $PWD to substitute as a user path.

So instead of doing this in ~/.bash_profile

```<code># Flutter
export PATH="$PATH:$PWD/flutter/bin"
</code>```

Change it to this

```<code># Flutter
export PATH="$PATH:/Users/Mac/flutter/bin"
</code>```

Body:
I have found the problem it's because I use $PWD to substitute as a user path.

So instead of doing this in ~/.bash_profile

# Flutter
export PATH="$PATH:$PWD/flutter/bin"

Change it to this

# Flutter
export PATH="$PATH:/Users/Mac/flutter/bin"


问:
How can I mathematically compare two unknown types in Scala?
I'm writing a little script evaluator function.  It takes two arguments and a comparison operator like this:

    def compare[T,U](a:T, op:String, b:U): Boolean = {
      op match {
        case "==" => a == b
        case "<"  => a < b
        // and so on with other comparators...
      }
    }
```

This code won't compile.  The '<' operator doesn't work on the generic types.  I couldn't find a parent class for numeric types with the '<' operator, so I can't even do something like:  def compare[T<:Numeric,U<:Numeric](...)

Is there a way to do this (or a library)?  Right now I can only test equal/not-equal.

答:
edit: Luis' answer involving using a single parameter type and relying on type inference is likely the best overall solution. If you are set on using two separate types, here are some options:

Since you are attempting to compare two separate classes, you cannot directly inherit a trait member implementation that will fit both. However, if you can provide function literals that will convert a class to a Double, you can use the following code.

```<code>def compare[T,U](a: T, op:String, b: U, tToDouble: T => Double, uToDouble: U => Double): Boolean = {
      op match {
        case "==" => tToDouble(a) == uToDouble(b)
        case "<"  => tToDouble(a) < uToDouble(b)
        // and so on with other comparators...
      }
    }
//example using Int
println(compare(1, "<", 2, (x:Int) => x.toDouble, (y:Int) => y.toDouble)) //true
</code>```

Unfortunately, we cannot use Ordering or Numeric, because those are parameterized traits and the expectation is for comparison against themselves. Another method is just to accept a comparator function that accepts objects of each type whenever you wish to compare two types of objects.

```<code>def compare[T,U](a: T, op:String, b: U, comparator: (T,U) => Int): Boolean = {
      op match {
        case "==" => comparator(a,b) == 0
        case "<"  => comparator(a,b) < 0
        // and so on with other comparators...
      }
    }

println(compare[Int, Int](1, "<", 2, (a,b) => a-b)) //true
</code>```

Body:
I'm writing a little script evaluator function.  It takes two arguments and a comparison operator like this:

    def compare[T,U](a:T, op:String, b:U): Boolean = {
      op match {
        case "==" => a == b
        case "<"  => a < b
        // and so on with other comparators...
      }
    }

This code won't compile.  The '<' operator doesn't work on the generic types.  I couldn't find a parent class for numeric types with the '<' operator, so I can't even do something like:  def compare[T<:Numeric,U<:Numeric](...)

Is there a way to do this (or a library)?  Right now I can only test equal/not-equal.

Body:
edit: Luis' answer involving using a single parameter type and relying on type inference is likely the best overall solution. If you are set on using two separate types, here are some options:

Since you are attempting to compare two separate classes, you cannot directly inherit a trait member implementation that will fit both. However, if you can provide function literals that will convert a class to a Double, you can use the following code.

def compare[T,U](a: T, op:String, b: U, tToDouble: T => Double, uToDouble: U => Double): Boolean = {
      op match {
        case "==" => tToDouble(a) == uToDouble(b)
        case "<"  => tToDouble(a) < uToDouble(b)
        // and so on with other comparators...
      }
    }
//example using Int
println(compare(1, "<", 2, (x:Int) => x.toDouble, (y:Int) => y.toDouble)) //true

Unfortunately, we cannot use Ordering or Numeric, because those are parameterized traits and the expectation is for comparison against themselves. Another method is just to accept a comparator function that accepts objects of each type whenever you wish to compare two types of objects.

def compare[T,U](a: T, op:String, b: U, comparator: (T,U) => Int): Boolean = {
      op match {
        case "==" => comparator(a,b) == 0
        case "<"  => comparator(a,b) < 0
        // and so on with other comparators...
      }
    }

println(compare[Int, Int](1, "<", 2, (a,b) => a-b)) //true


问:
How can you run a python function stored in a different file
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

```<code>main.py
map.py
Scripts/
  script1.py
</code>```

map.py contains just an array and a function to get the correct array index:

```<code>map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]
</code>```

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

```<code>selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.
</code>```

Any suggestions?

答:
In map.py, the following is simpler:

```<code>import Scripts.script1 as script1
map = {"One" : script1.function_one, "Two" : script1.function_two]
def return_mapping(str):
    return map[str]
</code>```

In main.py:

```<code>selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
# to call the function: function_ptr(my_args)
</code>```

edit:

As mike said, you have to put an empty file called __init__.py in your Scripts directory

Body:
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

main.py
map.py
Scripts/
  script1.py

map.py contains just an array and a function to get the correct array index:

map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.

Any suggestions?

Body:
In map.py, the following is simpler:

import Scripts.script1 as script1
map = {"One" : script1.function_one, "Two" : script1.function_two]
def return_mapping(str):
    return map[str]

In main.py:

selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
# to call the function: function_ptr(my_args)

edit:

As mike said, you have to put an empty file called __init__.py in your Scripts directory


问:
Adding a Project Reference to a Xamarin Forms App
VS 2017 / C#.

I have a working Web and WebApi app.  A web page accessing the WebApi (both written by me). I am now trying to create a Mobile App using Xamarin forms to call the WebApi.  My mobile app needs access to a DTO project (part of my API).  I can add the reference to the xxx.Android App, but I need to reference the DTO's in the xxx.Mobile App.  There seems to be no option to add a reference in that 'shared' app.  This means my code error's as it cannot find the DTO definitions.

Anyone have advice?  Thanks.

答: You should be able to right-click the Dependencies of the Forms project and add the reference.


问:
Laravel Assert Redirect Ignoring Query Parameters
I have an api test that asserts for redirect to a specific route. The issue is the redirect url has query parameters that includes a timestamp which changes. Wondering if Laravel's assertions has an an alternative to assertRedirect method that ignores query parameters.

```<code>/** @test */
    public function test_can_redirect()
    {

        $this->call('GET', "users/auth")
            ->assertRedirect('http://localhost:8000/dashboard?timestamp=1550848436');
    }
</code>```

I want to assert a redirect to

```<code>http://localhost:8000/dashboard
</code>```

not

```<code>http://localhost:8000/dashboard?timestamp=1550848436
</code>```

答:
You could use getTargetUrl to extract what is without query string.

public function test_can_redirect()
{
    $redirectUrl = 'http://localhost:8000/dashboard';
    $res = $this->getJson('users/auth')->assertStatus(302); # Check if redirection
    # Or you could use this: $this->assertTrue($res->isRedirection());
    $parts = explode('?', $res->getTargetUrl());
    $this->assertTrue($parts[0] === $redirectUrl); # parts[0] is the url
wihtout query string

    # If you want to check the keys of query string, too
    $this->assertTrue(count($parts) === 2);  # check query string exists
    parse_str($parts[1], $query);
    $this->assertArrayKeys($query, ['time', ..., 'the key you want to check']);
}

protected function assertArrayKeys(array $array, array $checks)
{
    $keys = array_keys($array);
    foreach ($checks as $check) {
        $this->assertTrue(in_array($check, $keys));
    }
}
```

Body:
I have an api test that asserts for redirect to a specific route. The issue is the redirect url has query parameters that includes a timestamp which changes. Wondering if Laravel's assertions has an an alternative to assertRedirect method that ignores query parameters.

/** @test */
    public function test_can_redirect()
    {

        $this->call('GET', "users/auth")
            ->assertRedirect('http://localhost:8000/dashboard?timestamp=1550848436');
    }

I want to assert a redirect to

http://localhost:8000/dashboard

not

http://localhost:8000/dashboard?timestamp=1550848436


问:
Laravel Dusk 2.0 / Laravel 5.5 returns an empty page
I'm in the midst of upgrading my Laravel 5.3 website to 5.5 and unable to get Dusk working properly against my localhost. I have other unit tests working properly against my localhost but for some reason, Dusk returns "" for any local page. Local pages seem to work fine browsing it on my desktop.

My DuskTestCase

```<code>protected function driver()
{
    $options = (new ChromeOptions)->addArguments([
        '--disable-gpu',
        '--headless',
        '--no-sandbox',
        '--ignore-certificate-errors'
    ]);

    return RemoteWebDriver::create(
        'http://localhost:9515',
        DesiredCapabilities::chrome()
        ->setCapability(WebDriverCapabilityType::ACCEPT_SSL_CERTS, true)
        ->setCapability('acceptInsecureCerts', true)
        ->setCapability(
            ChromeOptions::CAPABILITY, $options
        )
    );
}
</code>```

My Sample Test

```<code>public function testBasicExample()
{
    $this->browse(function (Browser $browser) {

            $result = $browser->visit('http://localhost');
            $browser->screenshot('test');
            $browser->dump();
    });
}
</code>```

chrome driver works fine calling google.com and dumps content

hardcoded the url to localhost for testing

page is http not https

tried php artisan serve before calling test, same result

tried cache / config clear

created an .env.dusk.local file, didn't seem to affect it

chromedriver -v is ChromeDriver 2.44.609551

tried 127.0.0.1 no dice

答:
The only way I could make it working:</p>

```<code>public function testBasicExample()
{
    $this->browse(function (Browser $browser) {
        $browser->visit(env('APP_URL').'/home')
                ->assertSee('Laravel');
    });
}
</code>```

Body:
I'm in the midst of upgrading my Laravel 5.3 website to 5.5 and unable to get Dusk working properly against my localhost. I have other unit tests working properly against my localhost but for some reason, Dusk returns "" for any local page. Local pages seem to work fine browsing it on my desktop.

My DuskTestCase

protected function driver()
{
    $options = (new ChromeOptions)->addArguments([
        '--disable-gpu',
        '--headless',
        '--no-sandbox',
        '--ignore-certificate-errors'
    ]);

    return RemoteWebDriver::create(
        'http://localhost:9515',
        DesiredCapabilities::chrome()
        ->setCapability(WebDriverCapabilityType::ACCEPT_SSL_CERTS, true)
        ->setCapability('acceptInsecureCerts', true)
        ->setCapability(
            ChromeOptions::CAPABILITY, $options
        )
    );
}

My Sample Test

public function testBasicExample()
{
    $this->browse(function (Browser $browser) {

            $result = $browser->visit('http://localhost');
            $browser->screenshot('test');
            $browser->dump();
    });
}

chrome driver works fine calling google.com and dumps content

hardcoded the url to localhost for testing

page is http not https

tried php artisan serve before calling test, same result

tried cache / config clear

created an .env.dusk.local file, didn't seem to affect it

chromedriver -v is ChromeDriver 2.44.609551

tried 127.0.0.1 no dice

Body:
The only way I could make it working:

public function testBasicExample()
{
    $this->browse(function (Browser $browser) {
        $browser->visit(env('APP_URL').'/home')
                ->assertSee('Laravel');
    });
}


问:
Problem uploading code to ESP8266: esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for package header
I'm trying to upload the example Blink code to my ESP8266 modules, 1 of which is an ESP8266-07, the other a WeMos D1 mini PRO. I've installed the library for the ESPs according to online instructions. I'm uploading from Ubuntu 16.04, Arduino 1.8.9. I've also made sure to use sudo chmod 666 /dev/ttyUSB0.

I've tried uploading both through a normal USB cable and through a USB-TTL board, both of which made no difference. My Tools > Board settings are "Generic ESP8266 module" for the ESP8266-07 and "LOLIN(WEMOS) D1 mini Pro" for my mini Pro. In all 4 cases (2 different boards, 2 uploading cables/gateways), I've got the same error message.

```<code>raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for package header
</code>```

I've also tried uploading the code to my Node MCU, in which case, I got a different error:

```<code>esptools.FatalError: Invalid head of package (0x46)
</code>```

答:
I've resolved the problems with the ESP8266-07 and D1 mini Pro by changing the upload speed to 115200.

Another important thing to note is to set the right boards:  "Generic ESP8266 module" for the ESP8266-07 and "LOLIN(WEMOS) D1 mini Pro" for the mini Pro. I sometimes forget to do so when changing between the 2 boards.

However, I haven't yet resolved the problem where my NodeMCU keeps returning esptool.FatalError: Invalid head of packet (0x46)

Body:
I'm trying to upload the example Blink code to my ESP8266 modules, 1 of which is an ESP8266-07, the other a WeMos D1 mini PRO. I've installed the library for the ESPs according to online instructions. I'm uploading from Ubuntu 16.04, Arduino 1.8.9. I've also made sure to use sudo chmod 666 /dev/ttyUSB0.

I've tried uploading both through a normal USB cable and through a USB-TTL board, both of which made no difference. My Tools > Board settings are "Generic ESP8266 module" for the ESP8266-07 and "LOLIN(WEMOS) D1 mini Pro" for my mini Pro. In all 4 cases (2 different boards, 2 uploading cables/gateways), I've got the same error message.

raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for package header

I've also tried uploading the code to my Node MCU, in which case, I got a different error:

esptools.FatalError: Invalid head of package (0x46)


问:
Julia: Call previous value within Map function
I have been acclimating myself with the higher order functions like map, filter, and reduce. Honestly, I feel like I'm cheating because the code is so clean! Anyway...

Say I am preforming a map function on an array and the output of anonymous function is dependent on the preceding value. How would i call the previous value?

For instance:

A statement to check if each value has a factor of 3

```<code>julia> A
4-element Array{Int64,1}:
  3
  6
  9
 36

julia> reduce(&, map(x-> x%3 == 0, A))
true
</code>```

How would I call the previous value to check if it is a factor of the current value?

```<code>julia> reduce(&, map( x -> x==A[1] ? true : x % 3 == 0, A))
true

#I want to change the 3 to the previous value like..
psuedo code> reduce(&, map( x -> x==A[1] ? true : x % x[i-1] == 0, A))
</code>```

Any ideas? Or, am I pushing the limits on this?

答:
Just as in a for loop, you can take elements as x in A or get elements via an index, as i in 1:length(A):

```<code>reduce(&, map(i -> A[i]==A[1] ? true : A[i] % A[i-1] == 0, 1:length(A)))
</code>```

or, because it may shortcut evaluation when false:

```<code>all(i -> A[i]==A[1] ? true : A[i] % A[i-1] == 0, 1:length(A))
</code>```

Body:
I have been acclimating myself with the higher order functions like map, filter, and reduce. Honestly, I feel like I'm cheating because the code is so clean! Anyway...

Say I am preforming a map function on an array and the output of anonymous function is dependent on the preceding value. How would i call the previous value?

For instance:

A statement to check if each value has a factor of 3

julia> A
4-element Array{Int64,1}:
  3
  6
  9
 36

julia> reduce(&, map(x-> x%3 == 0, A))
true

How would I call the previous value to check if it is a factor of the current value?

julia> reduce(&, map( x -> x==A[1] ? true : x % 3 == 0, A))
true

#I want to change the 3 to the previous value like..
psuedo code> reduce(&, map( x -> x==A[1] ? true : x % x[i-1] == 0, A))

Any ideas? Or, am I pushing the limits on this?

Body:
Just as in a for loop, you can take elements as x in A or get elements via an index, as i in 1:length(A):

reduce(&, map(i -> A[i]==A[1] ? true : A[i] % A[i-1] == 0, 1:length(A)))

or, because it may shortcut evaluation when false:

all(i -> A[i]==A[1] ? true : A[i] % A[i-1] == 0, 1:length(A))


问:
How to convert this sentence into a first order logic well formed formula?
I am trying to convert the following sentence to a well formed formula using first-order logic(Predicate logic).

All towers are of the same color.

I have defined the following predicates:

Tower(x) :: x is a tower.

Color(x, y) :: x is of color y

I am not able to convert the aforementioned sentence into a well formed formula using the above predicates. Is it possible to convert it using the above predicates or some new predicate should be required. Please advise.

EDIT: Forgot to add a detail. There are only three available colours in the world (red, green, blue). Can this detail be used. Does that make any difference to the solution?

答:
Let's not assume that any towers or colors exist.</p>

```<code>tower(x) ∧ tower(y) ∧ color(x,z) → color(y,z)
</code>```

Body:
Let's not assume that any towers or colors exist.

tower(x) ∧ tower(y) ∧ color(x,z) → color(y,z)


问:
How to display all posts by a user in octobrcms
I am trying to display all posts by a user and have this in my code that works only when a user is signed in and displays all the user's posts.

```<code>$id =  Auth::getUser()->id;

    $this['allproducts'] = Advert::where('user_id', $id)->orderby('created_at','desc')->get();
</code>```

I want to make this visible to all signed in or not. when i logged out and try to access the url, it throws up an error

Trying to get property 'id' of non-object

答:
try using: If there is no authenticated user it gives null and it should not fetch. (If user_id does not remain null on Advert model table)</p>

```<code>$id =  Auth::getUser()->id ?? null;
</code>```

Body:
I am trying to display all posts by a user and have this in my code that works only when a user is signed in and displays all the user's posts.

$id =  Auth::getUser()->id;

    $this['allproducts'] = Advert::where('user_id', $id)->orderby('created_at','desc')->get();

I want to make this visible to all signed in or not. when i logged out and try to access the url, it throws up an error

Trying to get property 'id' of non-object

Body:
try using: If there is no authenticated user it gives null and it should not fetch. (If user_id does not remain null on Advert model table)

$id =  Auth::getUser()->id ?? null;


问:
why expect cannot match `[0-9]`?
From the following script we can see a simple number cannot be matched by [0-9], but in the regexp document, it said it support this. Why my version does not work?</p>

```<code>#!/bin/expect
set timeout 20
set remote_cmd_prompt_regex "> $"
spawn bash --noprofile --norc
send "PS1='> '\r"
expect {
    -regexp "$remote_cmd_prompt_regex" {
        puts "Host ->$expect_out(buffer)"
        send "echo 99\r"
        # match with .* works
        expect -regexp ".*\\n(.+)\\n$remote_cmd_prompt_regex"
        puts "regex group ->$expect_out(1,string)"
        send "echo 89\r"
        # match with [0-9] does not work why?
        expect -regexp ".*\\n(\[0-9]+)\\n$remote_cmd_prompt_regex"
        puts "regex group ->$expect_out(1,string)"
    }
    timeout {
    puts "Timeout error!"
    exit 1
    }
}
</code>```

答:
Usually (in canonical pty mode), each \n sent to a pty will be converted to \r\n so you need to change \n to \r\n in the RE pattern. Example:

[STEP 101] # cat foo.exp
#!/usr/bin/expect

set ps_re "> $"
spawn -noecho bash --noprofile --norc

expect bash
send "PS1='> '\r"
expect -re $ps_re

for { set i 10 } { $i < 15 } { incr i } {
    send "echo $i\r"
    expect -re ".*\\r\\n(\[0-9]+)\\r\\n$ps_re"
}

send "exit\r"
expect eof
[STEP 102] # expect foo.exp
bash-5.0# PS1='> '
> echo 10
10
> echo 11
11
> echo 12
12
> echo 13
13
> echo 14
14
> exit
exit
[STEP 103] #
```

Title: why expect cannot match `[0-9]`?

Body:
From the following script we can see a simple number cannot be matched by [0-9], but in the regexp document, it said it support this. Why my version does not work?

#!/bin/expect
set timeout 20
set remote_cmd_prompt_regex "> $"
spawn bash --noprofile --norc
send "PS1='> '\r"
expect {
    -regexp "$remote_cmd_prompt_regex" {
        puts "Host ->$expect_out(buffer)"
        send "echo 99\r"
        # match with .* works
        expect -regexp ".*\\n(.+)\\n$remote_cmd_prompt_regex"
        puts "regex group ->$expect_out(1,string)"
        send "echo 89\r"
        # match with [0-9] does not work why?
        expect -regexp ".*\\n(\[0-9]+)\\n$remote_cmd_prompt_regex"
        puts "regex group ->$expect_out(1,string)"
    }
    timeout {
    puts "Timeout error!"
    exit 1
    }
}


问:
Inserting data into database but getting incorrect syntax error
I'm trying to add student data into a database but keeps coming up with the error "incorrect syntax near the keyword 'Table'". I'm very new to using windows form does anybody know where I have gone wrong? </p>

```<code>private void BTAddstudent_Click(object sender, EventArgs e)
{
    try
    {
        string myconnection = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\tayla\OneDrive\Documents\StudentPerformance\StudentPerformance\Studentdatabase.mdf; Integrated Security = True";

        string Query = "Insert Into Table (ID, First name, Last name, Course 1, Course 2, Course 3, Course 4, Course 5, Course 6, Course 7, Course 8, Course 9, Course 10) values('" + this.txtbxID.Text + "','" + this.txtbxfirstname.Text + "','" + this.txtbxlastname.Text + "','" + this.txtbxcourse1.Text
            + "','" + this.txtbxcourse2.Text + "','" + this.txtbxcourse3.Text + "','" + this.txtbxcourse4.Text + "','" + this.txtbxcourse5.Text + "','" + this.txtbxcourse6.Text + "','" + this.txtbxcourse7.Text
            + "','" + this.txtbxcourse8.Text + "','" + this.txtbxcourse9.Text + "','" + this.txtbxcourse10.Text + "')";

        SqlConnection myconn = new SqlConnection(myconnection);
        SqlCommand mycom = new SqlCommand(Query, myconn);
        SqlDataReader reader1;
        myconn.Open();
        reader1 = mycom.ExecuteReader();
        while (reader1.Read()) ;
        {
        }
        myconn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
</code>```

答:
If you named your table Table, you must use brackets because Table is a reserved word. You must also use brackets in your column names if you use spaces.

Your sql statement should be like this:

```<code>Insert Into [Table] (ID, [First name], [Last name], [Course 1], [Course 2], ...
</code>```

Using parameterized query is better. It's easier to read and it prevents SQL injection attack.

Body:
I'm trying to add student data into a database but keeps coming up with the error "incorrect syntax near the keyword 'Table'". I'm very new to using windows form does anybody know where I have gone wrong?

private void BTAddstudent_Click(object sender, EventArgs e)
{
    try
    {
        string myconnection = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\tayla\OneDrive\Documents\StudentPerformance\StudentPerformance\Studentdatabase.mdf; Integrated Security = True";

        string Query = "Insert Into Table (ID, First name, Last name, Course 1, Course 2, Course 3, Course 4, Course 5, Course 6, Course 7, Course 8, Course 9, Course 10) values('" + this.txtbxID.Text + "','" + this.txtbxfirstname.Text + "','" + this.txtbxlastname.Text + "','" + this.txtbxcourse1.Text
            + "','" + this.txtbxcourse2.Text + "','" + this.txtbxcourse3.Text + "','" + this.txtbxcourse4.Text + "','" + this.txtbxcourse5.Text + "','" + this.txtbxcourse6.Text + "','" + this.txtbxcourse7.Text
            + "','" + this.txtbxcourse8.Text + "','" + this.txtbxcourse9.Text + "','" + this.txtbxcourse10.Text + "')";

        SqlConnection myconn = new SqlConnection(myconnection);
        SqlCommand mycom = new SqlCommand(Query, myconn);
        SqlDataReader reader1;
        myconn.Open();
        reader1 = mycom.ExecuteReader();
        while (reader1.Read()) ;
        {
        }
        myconn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Body:
If you named your table Table, you must use brackets because Table is a reserved word. You must also use brackets in your column names if you use spaces.

Your sql statement should be like this:

Insert Into [Table] (ID, [First name], [Last name], [Course 1], [Course 2], ...

Using parameterized query is better. It's easier to read and it prevents SQL injection attack.


答:
OK - slightly embarrassing, but will post in case others have this issue.
There is no "References" under the Project.  However, if you right-click the Project, there is an option to add a Reference.  It then creates it.</p>

Title: Adding a Project Reference to a Xamarin Forms App

Body:
VS 2017 / C#.

I have a working Web and WebApi app.  A web page accessing the WebApi (both written by me). I am now trying to create a Mobile App using Xamarin forms to call the WebApi.  My mobile app needs access to a DTO project (part of my API).  I can add the reference to the xxx.Android App, but I need to reference the DTO's in the xxx.Mobile App.  There seems to be no option to add a reference in that 'shared' app.  This means my code error's as it cannot find the DTO definitions.

Anyone have advice?  Thanks.


问:
focus filtering select on page load

why does the following code don't focus the filteringselect?

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript" src="http://yandex.st/dojo/1.6.0/dojo/dojo.xd.js" djConfig="parseOnLoad: true"></script>
    <style type="text/css">
            @import "http://yandex.st/dojo/1.6.0/dijit/themes/claro/claro.css";
    </style>
    <script type="text/javascript">
    <!--
    dojo.require("dijit.form.FilteringSelect");

    dojo.addOnLoad(function(){
        dijit.byId('dept').focus();
    });

    -->
    </script>
    </head>
    <body class="claro">
    <select name="dept" id="dept" dojoType="dijit.form.FilteringSelect" >
        <option value=""></option>
        <option value="test">test</option>
        <option value="test1">test1</option>
    </select>
    </body>
    </html>
</code>```

I tried it with ie7 and firefox 3/4 - it works.

but it fails in ie8 :-(

may this be a dojo bug - or am I doing something wrong?

when does dojo.addOnLoad() fire? after the DOM is ready, or after all widgets have properly been initalized?

regards

 gerhard

答:
I'm not sure what browsers fully support this, but you could try:

```<code><select name="dept" id="dept" dojoType="dijit.form.FilteringSelect" autofocus>
</code>```

Also, I don't see why you're using an Import statement if you could just use the link tag:

Before:

```<code><style type="text/css">
    @import "http://yandex.st/dojo/1.6.0/dijit/themes/claro/claro.css";
</style>
</code>```

After:

```<code><link rel="stylesheet" type="text/css" href="http://yandex.st/dojo/1.6.0/dijit/themes/claro/claro.css">
</code>```

Title: focus filtering select on page load

Body:
why does the following code don't focus the filteringselect?

    <!DOCTYPE html>

    <select name="dept" id="dept" dojoType="dijit.form.FilteringSelect" >
        <option value=""></option>
        <option value="test">test</option>
        <option value="test1">test1</option>
    </select>

I tried it with ie7 and firefox 3/4 - it works.

but it fails in ie8 :-(

may this be a dojo bug - or am I doing something wrong?

when does dojo.addOnLoad() fire? after the DOM is ready, or after all widgets have properly been initalized?

regards

 gerhard

Body:
I'm not sure what browsers fully support this, but you could try:

<select name="dept" id="dept" dojoType="dijit.form.FilteringSelect" autofocus>

Also, I don't see why you're using an Import statement if you could just use the link tag:

Before:

<style type="text/css">
    @import "http://yandex.st/dojo/1.6.0/dijit/themes/claro/claro.css";
</style>

After:

<link rel="stylesheet" type="text/css" href="http://yandex.st/dojo/1.6.0/dijit/themes/claro/claro.css">


问:
How to not handle pointer events in a Component derivate
I'd like to have a Container instance to handle pointer events. However when I start placing components in this container those steal the pointer events even if I set setIgnorePointerEvents(true) on those components like Label instances.

I assume it is not possible to create Component derivates that don't handle pointer events. Is that correct or how is it done?

Also it seems to be a bad idea to delegate pointer events to their parent containers since that would lead to recursion.

Are there best practices regarding handling of pointer events?

答: Set the container to focusable or just place an invisible focusable component on top of the container in a layered layout and grab all events there. You can then decide who receives an event by invoking the pointer events on that component manually.</p>


问:
Why \n in python gives two blank lines?
I can't understand why \n gives two blank lines in the output. For example:

```<code>>>> def my_function():
    print("ABC")
    print("\n")
    print("DEF")

>>> my_function()
ABC
                      # First blank line
                      # Second blank line
DEF
>>>
</code>```

Can anyone explain what happens here and how to fix it?

答: print() prints a newline at the end of its output by default.  print("\n") thus prints two newlines: the one in the "\n" string and the one at the end of the printing operation.

Title: Why \n in python gives two blank lines?

Body:
I can't understand why \n gives two blank lines in the output. For example:

>>> def my_function():
    print("ABC")
    print("\n")
    print("DEF")

>>> my_function()
ABC
                      # First blank line
                      # Second blank line
DEF
>>>

Can anyone explain what happens here and how to fix it?


问:
Prevent WordPress home page redirect after WP 4.4.1
The WP is redirecting the home page to the home_url (or site_url not sure since both are the same values) even when arrived to the page using the parked domains. This started after the recent update. Also, I confirmed, no htaccess, server configs nor any plugins doing the redirect.

After thorough research the solution I found are placing the following in the functions.php remove_action('template_redirect', 'redirect_canonical');. That solution is years old and don't seem to work anymore.

The way I set it up is I park the domains to the WP site, and the contents displayed are based on the domain. Just happens on the index page, if it has any urls appended, it works. Any help is appreciated.

答:
LTDInvestments is actually correct. In your wp-config.php, ensure that 'WP_HOME' and 'WP_SITEURL' have values which are lowercased.

This fixed it for me; I guess case-sensitivity is something you should mind throughout your wp-config.php and wp-admin settings.


问:
implement Smart Lock Password on Firebase Login
I have been trying to implement Smart Locks on my Firebase Login Auth method, but I have to admit for the past two days, the google docs tripped me.

Could anyone give me a help?

This is my Auth login with Google

```<code>val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()

    mGoogleApiClient = GoogleApiClient.Builder(this)
            .enableAutoManage(this, GoogleApiClient.OnConnectionFailedListener { })
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build()

    loginGoogleBtn.setOnClickListener {
        val signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient)
        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
        startActivityForResult(signInIntent, GOOGLE_SIGN_IN)
    }

}

override fun onStart() {
    super.onStart()
    // Check if user is signed in (non-null) and update UI accordingly.
    val currentUser = auth.currentUser
    updateUI(currentUser)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == GOOGLE_SIGN_IN) {
        val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
        if (result.isSuccess) {
            if (result.signInAccount != null) {
                val account = result.signInAccount!!
                val credential = GoogleAuthProvider.getCredential(account.idToken, null)
                firebaseLogin(credential)
            }

        } else {
            Log.e("Error", "Could not signin google")
        }
    } else {
        mCallbackManager.onActivityResult(requestCode, resultCode, data)
    }
}
</code>```

Thank you

答:
In your LoginActivity you can add this: </p>

```<code>private val smartLockClient by lazy {
    Credentials.getClient(this)
}

private val firebaseAuth by lazy {
    FirebaseAuth.getInstance()
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.login) // put a id "container" in the root ViewGroup

    // Run Google Smart Lock
    smartLock()
}

private fun smartLock() {
    container.visibility = View.GONE

    val credentialRequest = CredentialRequest.Builder()
            .setPasswordLoginSupported(true)
            .setIdTokenRequested(true)
            .setAccountTypes(IdentityProviders.GOOGLE, IdentityProviders.FACEBOOK)
            .build()
    smartLockClient.request(credentialRequest).addOnCompleteListener { task ->

        if (task.isSuccessful) {
            // See "Handle successful credential requests"
            val credential = task.result?.credential ?: return@addOnCompleteListener
            when (credential.accountType) {
                null -> {
                    firebaseAuth.signInWithEmailAndPassword(credential.id, credential.password
                            ?: "")
                }
                IdentityProviders.GOOGLE -> {

                    GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                            .setAccountName(credential.id)
                            .requestIdToken(getString(R.string.default_web_client_id))
                            .build()
                            .let { GoogleSignIn.getClient(this, it) }
                            .silentSignIn()
                            .addOnSuccessListener {
                                val authCredential = GoogleAuthProvider.getCredential(it.idToken, null)
                                firebaseAuth.signInWithCredential(authCredential)
                                        .addOnSuccessListener { onSignInSuccess() }
                                        .addOnFailureListener { onSignInFailure() }
                            }
                            .addOnFailureListener { onSignInFailure() }
                }
            }
        }
    }
}

private onSignInSuccess(){
    // navigate to your main page or something else
}

private onSignInFailure(){
    // smart lock fail, so show the user the buttons "Sign in with Google", "Sign in with Email", "Sign in With Facebook", etc.
    container.visibility = VISIBLE
}
</code>```

Body:
I have been trying to implement Smart Locks on my Firebase Login Auth method, but I have to admit for the past two days, the google docs tripped me.

Could anyone give me a help?

This is my Auth login with Google

val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()

    mGoogleApiClient = GoogleApiClient.Builder(this)
            .enableAutoManage(this, GoogleApiClient.OnConnectionFailedListener { })
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build()

    loginGoogleBtn.setOnClickListener {
        val signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient)
        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
        startActivityForResult(signInIntent, GOOGLE_SIGN_IN)
    }

}

override fun onStart() {
    super.onStart()
    // Check if user is signed in (non-null) and update UI accordingly.
    val currentUser = auth.currentUser
    updateUI(currentUser)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == GOOGLE_SIGN_IN) {
        val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
        if (result.isSuccess) {
            if (result.signInAccount != null) {
                val account = result.signInAccount!!
                val credential = GoogleAuthProvider.getCredential(account.idToken, null)
                firebaseLogin(credential)
            }

        } else {
            Log.e("Error", "Could not signin google")
        }
    } else {
        mCallbackManager.onActivityResult(requestCode, resultCode, data)
    }
}

Thank you

Body:
In your LoginActivity you can add this:

private val smartLockClient by lazy {
    Credentials.getClient(this)
}

private val firebaseAuth by lazy {
    FirebaseAuth.getInstance()
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.login) // put a id "container" in the root ViewGroup

    // Run Google Smart Lock
    smartLock()
}

private fun smartLock() {
    container.visibility = View.GONE

    val credentialRequest = CredentialRequest.Builder()
            .setPasswordLoginSupported(true)
            .setIdTokenRequested(true)
            .setAccountTypes(IdentityProviders.GOOGLE, IdentityProviders.FACEBOOK)
            .build()
    smartLockClient.request(credentialRequest).addOnCompleteListener { task ->

        if (task.isSuccessful) {
            // See "Handle successful credential requests"
            val credential = task.result?.credential ?: return@addOnCompleteListener
            when (credential.accountType) {
                null -> {
                    firebaseAuth.signInWithEmailAndPassword(credential.id, credential.password
                            ?: "")
                }
                IdentityProviders.GOOGLE -> {

                    GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                            .setAccountName(credential.id)
                            .requestIdToken(getString(R.string.default_web_client_id))
                            .build()
                            .let { GoogleSignIn.getClient(this, it) }
                            .silentSignIn()
                            .addOnSuccessListener {
                                val authCredential = GoogleAuthProvider.getCredential(it.idToken, null)
                                firebaseAuth.signInWithCredential(authCredential)
                                        .addOnSuccessListener { onSignInSuccess() }
                                        .addOnFailureListener { onSignInFailure() }
                            }
                            .addOnFailureListener { onSignInFailure() }
                }
            }
        }
    }
}

private onSignInSuccess(){
    // navigate to your main page or something else
}

private onSignInFailure(){
    // smart lock fail, so show the user the buttons "Sign in with Google", "Sign in with Email", "Sign in With Facebook", etc.
    container.visibility = VISIBLE
}


问:
Can I avoid two MySQL events running at the same time?
I have an event in MySQL that I want to run very frequently at least every 30 seconds.

It is processing data from a queue table that contains recently updated records. Sometimes I receive large batches of updates. When this occurs the event may take longer to run than the usual 2-3 seconds. If it is still running at the time of the next schedule, I want the next event to skip execution.

The best way I could think about doing this is to create a 'state' table in which I set a specific key to 1 when the process starts, set it back to 0 when it is complete.
I'd then alter the event to check the current status.

I'd prefer to do something nicer than that. Is there a feature I am missing completely?

I've looked into global variables but based on the documentation these only seem permissible for system variables.

Current Example Code

Here is the example code I'm currently testing.

```<code>acca_sync: BEGIN

  DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
    GET DIAGNOSTICS CONDITION 1 @sqlstate = RETURNED_SQLSTATE,
    @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
    SET @full_error = CONCAT("ERROR ", @errno, " (", @sqlstate, "): ", @text);
    call pa.log(concat("acca-acc_sync"," - Error - ", ifnull(@full_error,    "no error message")));
    UPDATE `acca`.`processing_state`
      SET `value` = 0
      WHERE `key` = 'acca_sync';
  END;

  call pa.log(CONCAT("Started acca_sync @ ", NOW()));
  SELECT `value`
    into @is_locked
    from `acca`.`processing_state`
    where `key` = 'acca_sync';

  IF @is_locked = 0 THEN
    UPDATE `acca`.`processing_state`
      SET `value` = 1
      WHERE `key` = 'acca_sync';
  ELSE
    CALL pa.log(CONCAT("acca_sync deferred due to active sync. @ ", NOW()));
    LEAVE acca_sync;
  END IF;

  call acca.event_sync();
  call pa.log(CONCAT("Completed acca_sync @ ", NOW()));

  UPDATE `acca`.`processing_state`
    SET `value` = 0
    WHERE `key` = 'acca_sync';

END
</code>```

Table Locking

Based on a comment I want to explain why I am not using a table lock. My experience with table locks is limited so I hope the below is correct and makes sense.

Source Data Tables

I have triggers that notify updates in queue tables. These are my source data tables from which I read data to process it.

My understanding is that a READ lock on these tables would not lock any other events that just read.
If I was to use a WRITE lock I would block any updates to any of the rows that I don't currently access.

Target Data Tables

I have multiple data sources that process data in different events. The rows these will amend in the target tables. There may be two different events running at the same time writing to the same table, so I don't artificially want to block the target tables

Other Tables

I could create a fake table that I would only have for the purpose of setting and then checking the existance of a lock. This seems absurd and I'd much rather instead create a single table locks with a lock_key and an is_locked column that I query each time.

答:
You can verify if is there any event running:

```<code> SELECT *
 FROM performance_schema.threads
 WHERE NAME LIKE '%event_worker%'
      AND TYPE='FOREGROUND'
</code>```

Other interesting table to watch:

```<code> SELECT * FROM information_schema.processlist
</code>```

Body:
I have an event in MySQL that I want to run very frequently at least every 30 seconds.

It is processing data from a queue table that contains recently updated records. Sometimes I receive large batches of updates. When this occurs the event may take longer to run than the usual 2-3 seconds. If it is still running at the time of the next schedule, I want the next event to skip execution.

The best way I could think about doing this is to create a 'state' table in which I set a specific key to 1 when the process starts, set it back to 0 when it is complete.
I'd then alter the event to check the current status.

I'd prefer to do something nicer than that. Is there a feature I am missing completely?

I've looked into global variables but based on the documentation these only seem permissible for system variables.

Current Example Code

Here is the example code I'm currently testing.

acca_sync: BEGIN

  DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
    GET DIAGNOSTICS CONDITION 1 @sqlstate = RETURNED_SQLSTATE,
    @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
    SET @full_error = CONCAT("ERROR ", @errno, " (", @sqlstate, "): ", @text);
    call pa.log(concat("acca-acc_sync"," - Error - ", ifnull(@full_error,    "no error message")));
    UPDATE `acca`.`processing_state`
      SET `value` = 0
      WHERE `key` = 'acca_sync';
  END;

  call pa.log(CONCAT("Started acca_sync @ ", NOW()));
  SELECT `value`
    into @is_locked
    from `acca`.`processing_state`
    where `key` = 'acca_sync';

  IF @is_locked = 0 THEN
    UPDATE `acca`.`processing_state`
      SET `value` = 1
      WHERE `key` = 'acca_sync';
  ELSE
    CALL pa.log(CONCAT("acca_sync deferred due to active sync. @ ", NOW()));
    LEAVE acca_sync;
  END IF;

  call acca.event_sync();
  call pa.log(CONCAT("Completed acca_sync @ ", NOW()));

  UPDATE `acca`.`processing_state`
    SET `value` = 0
    WHERE `key` = 'acca_sync';

END

Table Locking

Based on a comment I want to explain why I am not using a table lock. My experience with table locks is limited so I hope the below is correct and makes sense.

Source Data Tables

I have triggers that notify updates in queue tables. These are my source data tables from which I read data to process it.

My understanding is that a READ lock on these tables would not lock any other events that just read.
If I was to use a WRITE lock I would block any updates to any of the rows that I don't currently access.

Target Data Tables

I have multiple data sources that process data in different events. The rows these will amend in the target tables. There may be two different events running at the same time writing to the same table, so I don't artificially want to block the target tables

Other Tables

I could create a fake table that I would only have for the purpose of setting and then checking the existance of a lock. This seems absurd and I'd much rather instead create a single table locks with a lock_key and an is_locked column that I query each time.

Body:
You can verify if is there any event running:

 SELECT *
 FROM performance_schema.threads
 WHERE NAME LIKE '%event_worker%'
      AND TYPE='FOREGROUND'

Other interesting table to watch:

 SELECT * FROM information_schema.processlist


问:
What does ' ' (tow single quotations marks, one after the other, not the double that come together) do?
I'm printing this in Python (3.6)

```<code>print(' 'f' ')
</code>```

and it shows nothing!
What is happening?

It sounds like whatever I put inside the inner ' ', vanish.

答:
You are actually defining two strings there.

' ' - this is a normal space

f' ' - this is an f-string or format string. Any string that's prefixed with f is an f-string. This one also happens to be just a space.

So you have two spaces. Side-by-side. Python implicitly concatenates the two strings to give you the result. So the result of print is also just 2 spaces.

If you wanted to print "f", you can do:

```<code>print(' \'f\' ')
</code>```

You need to escape the single quotes.

Body:
I'm printing this in Python (3.6)

print(' 'f' ')

and it shows nothing!
What is happening?

It sounds like whatever I put inside the inner ' ', vanish.

Body:
You are actually defining two strings there.

' ' - this is a normal space

f' ' - this is an f-string or format string. Any string that's prefixed with f is an f-string. This one also happens to be just a space.

So you have two spaces. Side-by-side. Python implicitly concatenates the two strings to give you the result. So the result of print is also just 2 spaces.

If you wanted to print "f", you can do:

print(' \'f\' ')

You need to escape the single quotes.


问:
How to let a function check multiple things
I'm making a simple program that converts imperial units to metric units. Like kW to hp and mph to kph. I want to let python check the first variable for multiple keywords. So that if the first keywords aren't in the variable, it checks the next line of keywords

I've tried lists and played around with the conditions

```<code>def choice():
    choice = raw_input("What do you want to convert?")
    splitted = choice.split()
    value = float(splitted[0])
    if 'kw' or 'kW' in choice:
        kwpk(value)
    elif 'mph' in choice:
        miletokm(value)
</code>```

With this method it always returns the kwpk(value). Even if the input doesn't have the keywords in it. I'm kinda ashamed that i need to ask this, but it's bothering me for like 2 days now even though it's a very simple application.

Any help will be greatly appreciated :)

答:
You've made a tiny error in your condition> When you're adding in two conditions seperated by a boolean operator, you'll have to mention them seperately.
Instead of:

```<code>if 'kw` or 'kW' in choice:
</code>```

Try:

```<code>if 'kw' in choice or 'kW' in choice:
</code>```

Even better, you can avoid the two cases and just use lower() to normalize the string.

```<code>def choice():
    choice = raw_input("What do you want to convert?")
    splitted = choice.split()
    value = float(splitted[0])
    if 'kw' in choice.lower():
        kwpk(value)
    elif 'mph' in choice:
        miletokm(value)

</code>```

Body:
I'm making a simple program that converts imperial units to metric units. Like kW to hp and mph to kph. I want to let python check the first variable for multiple keywords. So that if the first keywords aren't in the variable, it checks the next line of keywords

I've tried lists and played around with the conditions

def choice():
    choice = raw_input("What do you want to convert?")
    splitted = choice.split()
    value = float(splitted[0])
    if 'kw' or 'kW' in choice:
        kwpk(value)
    elif 'mph' in choice:
        miletokm(value)

With this method it always returns the kwpk(value). Even if the input doesn't have the keywords in it. I'm kinda ashamed that i need to ask this, but it's bothering me for like 2 days now even though it's a very simple application.

Any help will be greatly appreciated :)

Body:
You've made a tiny error in your condition> When you're adding in two conditions seperated by a boolean operator, you'll have to mention them seperately.
Instead of:

if 'kw` or 'kW' in choice:

Try:

if 'kw' in choice or 'kW' in choice:

Even better, you can avoid the two cases and just use lower() to normalize the string.

def choice():
    choice = raw_input("What do you want to convert?")
    splitted = choice.split()
    value = float(splitted[0])
    if 'kw' in choice.lower():
        kwpk(value)
    elif 'mph' in choice:
        miletokm(value)


问:
Using hiredis (redis client library)
I have the redis server installed, and can use it from the command line. Now, I am wanting to write a client program using hiredis. To begin with, I tried to compile example.c which is present in the hiredis directory:

```<code>vishal@expmach:~/redis-2.6.14/deps/hiredis$ ls

adapters  async.h       COPYING  dict.h        *example.c*        example-libevent.c
hiredis.c  Makefile  net.h      sds.c  test.c async.c   CHANGELOG.md  dict.c   example-
ae.c  example-libev.c  fmacros.h           hiredis.h  net.c     README.md  sds.h
</code>```

Here are the commands:

```<code>vishal@expmach:~/redis-2.6.14/deps/hiredis$ gcc -c -I hiredis example.c
vishal@expmach:~/redis-2.6.14/deps/hiredis$ gcc -o example -I hiredis -L hiredis -lhiredis -lm
</code>```

/usr/bin/ld: cannot find -lhiredis
collect2: ld returned 1 exit status

I am not sure how to go about fixing this. Please help.

答:
```<code>gcc -o example example.c -lhiredis $(pkg-config --cflags --libs glib-2.0)
</code>```

Title: Using hiredis (redis client library)

Body:
I have the redis server installed, and can use it from the command line. Now, I am wanting to write a client program using hiredis. To begin with, I tried to compile example.c which is present in the hiredis directory:

vishal@expmach:~/redis-2.6.14/deps/hiredis$ ls

adapters  async.h       COPYING  dict.h        *example.c*        example-libevent.c
hiredis.c  Makefile  net.h      sds.c  test.c async.c   CHANGELOG.md  dict.c   example-
ae.c  example-libev.c  fmacros.h           hiredis.h  net.c     README.md  sds.h

Here are the commands:

vishal@expmach:~/redis-2.6.14/deps/hiredis$ gcc -c -I hiredis example.c
vishal@expmach:~/redis-2.6.14/deps/hiredis$ gcc -o example -I hiredis -L hiredis -lhiredis -lm

/usr/bin/ld: cannot find -lhiredis
collect2: ld returned 1 exit status

I am not sure how to go about fixing this. Please help.


问:
Reshape the data from long to wide format
I am looking for swift way of reshaping the data from long to wide format. Right now I have tried a code with nest for loops, though the job gets done, it takes a long time to generate the output.

```<code>SN NN EE Service_tier
A  B  C  economy
B  C  C  economy
P  Q  R  regular
Q  S  R  regular
S  R  R  regular
H  I  L  economy
I  J  L  economy
J  K  L  economy
K  L  L  economy
</code>```

The output expected is as below

```<code>SN hop1 hop2 hop3 hop4 service_tier
A   B    C              economy
P   Q    S    R         regular
H   I    J    K    L    economy
</code>```

currently the below code gets the job done. Am sure there is an effective and clean way to do this.

```<code>for (i in 1:lasrow){
  sn <- raw_d[i,1]
  nn <- raw_d[i,2]
  en <- raw_d[i,3]

  lc <- 1

  if(nn == en){
    d[lr,lc]<-sn
    d[lr,lc+1]<-nn
    d[lr,lc+2]<-en
    lr <- lr+1
  }
  else{
    while(nn!=en){
      d[lr,lc]<-sn
      lc <- lc+1
      next_d <- filter(raw_d,raw_d$SN==sn,raw_d$EN==en)
      if(dim(next_d)[1]==0){
        d[lr,lc]<-"broken bf"
        lc <- lc+1
        break
      }else{
        sn <- next_d$NN
        nn <- next_d$NN
        }
      }
    d[lr,lc]<-en
    lr<-lr+1
  }
}
</code>```

答:
We can use data.table.  Convert the 'data.frame' to 'dat.table' (setDT(df1), grouped by rleid on the 'Service_tier', change the value of 'SN' to first element grouped by 'grp', then grouped by 'Service_tier', 'SN', get the unique element of Subset of Data.table and dcast from 'long' to 'wide' format

```<code>library(data.table)
dcast(setDT(df1)[, SN := first(SN), rleid(Service_tier)][,
    unique(unlist(.SD)), .(SN, Service_tier)],
    SN + Service_tier ~ paste0("hop", rowid(SN)), value.var = "V1", fill = "")
#  SN Service_tier hop1 hop2 hop3 hop4
#1:  A      economy    B    C
#2:  H      economy    I    J    K    L
#3:  P      regular    Q    S    R
</code>```

data

```<code>df1 <- structure(list(SN = c("A", "B", "P", "Q", "S", "H", "I", "J",
"K"), NN = c("B", "C", "Q", "S", "R", "I", "J", "K", "L"), EE = c("C",
"C", "R", "R", "R", "L", "L", "L", "L"), Service_tier = c("economy",
"economy", "regular", "regular", "regular", "economy", "economy",
"economy", "economy")), class = "data.frame", row.names = c(NA,
-9L))
</code>```

Body:
I am looking for swift way of reshaping the data from long to wide format. Right now I have tried a code with nest for loops, though the job gets done, it takes a long time to generate the output.

SN NN EE Service_tier
A  B  C  economy
B  C  C  economy
P  Q  R  regular
Q  S  R  regular
S  R  R  regular
H  I  L  economy
I  J  L  economy
J  K  L  economy
K  L  L  economy

The output expected is as below

SN hop1 hop2 hop3 hop4 service_tier
A   B    C              economy
P   Q    S    R         regular
H   I    J    K    L    economy

currently the below code gets the job done. Am sure there is an effective and clean way to do this.

for (i in 1:lasrow){
  sn <- raw_d[i,1]
  nn <- raw_d[i,2]
  en <- raw_d[i,3]

  lc <- 1

  if(nn == en){
    d[lr,lc]<-sn
    d[lr,lc+1]<-nn
    d[lr,lc+2]<-en
    lr <- lr+1
  }
  else{
    while(nn!=en){
      d[lr,lc]<-sn
      lc <- lc+1
      next_d <- filter(raw_d,raw_d$SN==sn,raw_d$EN==en)
      if(dim(next_d)[1]==0){
        d[lr,lc]<-"broken bf"
        lc <- lc+1
        break
      }else{
        sn <- next_d$NN
        nn <- next_d$NN
        }
      }
    d[lr,lc]<-en
    lr<-lr+1
  }
}

Body:
We can use data.table.  Convert the 'data.frame' to 'dat.table' (setDT(df1), grouped by rleid on the 'Service_tier', change the value of 'SN' to first element grouped by 'grp', then grouped by 'Service_tier', 'SN', get the unique element of Subset of Data.table and dcast from 'long' to 'wide' format

library(data.table)
dcast(setDT(df1)[, SN := first(SN), rleid(Service_tier)][,
    unique(unlist(.SD)), .(SN, Service_tier)],
    SN + Service_tier ~ paste0("hop", rowid(SN)), value.var = "V1", fill = "")
#  SN Service_tier hop1 hop2 hop3 hop4
#1:  A      economy    B    C
#2:  H      economy    I    J    K    L
#3:  P      regular    Q    S    R

data

df1 <- structure(list(SN = c("A", "B", "P", "Q", "S", "H", "I", "J",
"K"), NN = c("B", "C", "Q", "S", "R", "I", "J", "K", "L"), EE = c("C",
"C", "R", "R", "R", "L", "L", "L", "L"), Service_tier = c("economy",
"economy", "regular", "regular", "regular", "economy", "economy",
"economy", "economy")), class = "data.frame", row.names = c(NA,
-9L))


问:
Objective-C release is not called explicitly
```<code>NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];
</code>```

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly

答: You're using a bad pointer in you NSLog(). You happen to be getting lucky in this case, but you should expect code like this to crash or fail in other ways.</p>

Body:
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly


问:
Why @dynamicCallable not compiling even though dynamicallyCall(withArguments:) is implemented?
My code is simple:

```<code>@dynamicCallable
struct A {
  func dynamicallyCall(withArguments arguments: Int...) -> Int {
    return 0
  }
}
</code>```

This is throwing the error:

```<code>@dynamicCallable attribute requires 'A' to have either a valid 'dynamicallyCall(withArguments:)' method or 'dynamicallyCall(withKeywordArguments:)' method
</code>```

Not sure what else I can try to make it work. Nothing seems to be misspelled either.

答:
The method signature is wrong, since the documentation specifies that it must have a single parameter that conforms to the "ExpressibleByArrayLiteral" protocol.

The declaration of the dynamicallyCall(withArguments:) method must
  have a single parameter that conforms to the ExpressibleByArrayLiteral
  protocol...

https://docs.swift.org/swift-book/ReferenceManual/Attributes.html (Check the dynamicCallable section)

So you shouldn't express it as Int... but as [Int] instead.

Body:
My code is simple:

@dynamicCallable
struct A {
  func dynamicallyCall(withArguments arguments: Int...) -> Int {
    return 0
  }
}

This is throwing the error:

@dynamicCallable attribute requires 'A' to have either a valid 'dynamicallyCall(withArguments:)' method or 'dynamicallyCall(withKeywordArguments:)' method

Not sure what else I can try to make it work. Nothing seems to be misspelled either.


问:
I have the following settings in php.ini but they aren't showing up in phpinfo
I have apcu enabled - version 4.0.11
Apache version: Apache/2.4.6 (Red Hat Enterprise Linux) OpenSSL/1.0.2k-fips PHP/5.6.31

This is at the end of php.ini

```<code>apc.cache_by_default=On
apc.file_update_protection=2
apc.filters=
apc.max_file_size=1M
apc.num_files_hint=5024
apc.stat=1
apc.write_lock=On
</code>```

I have also tried to put it in /etc/php.d/40-apcu.ini, but it had no effect.

I restarted apache after changing the files.

The reason I am trying to enable these variables is because we are upgrading to another server and these were the values on the old server. If they are no longer needed or supported that is fine, but I could not find any documentation saying that.

EDIT: Relevant PHP info

答:
I had the same issue, it was caused by entering the wrong phpinfo url.

Wrong url:

```<code>http://localhost/?phpinfo=1
</code>```

Correct url (note the -1 parameter)

```<code>http://localhost/?phpinfo=-1
</code>```

Body:
I have apcu enabled - version 4.0.11
Apache version: Apache/2.4.6 (Red Hat Enterprise Linux) OpenSSL/1.0.2k-fips PHP/5.6.31

This is at the end of php.ini

apc.cache_by_default=On
apc.file_update_protection=2
apc.filters=
apc.max_file_size=1M
apc.num_files_hint=5024
apc.stat=1
apc.write_lock=On

I have also tried to put it in /etc/php.d/40-apcu.ini, but it had no effect.

I restarted apache after changing the files.

The reason I am trying to enable these variables is because we are upgrading to another server and these were the values on the old server. If they are no longer needed or supported that is fine, but I could not find any documentation saying that.

EDIT: Relevant PHP info

Body:
I had the same issue, it was caused by entering the wrong phpinfo url.

Wrong url:

http://localhost/?phpinfo=1

Correct url (note the -1 parameter)

http://localhost/?phpinfo=-1