问:
How to use the same PHP script to fetch data for mobile app and website?
So, I have a website that hits up a very simple PHP script to display data from a database in an HTML table.

My question is simple; is it possible to write the PHP script in such a way that I can use the same script to get the same data and return it in JSON for the android app that will need it (without a single if(onMobileApp) type god statment which is basically equivalent to writing two scripts anyways)?

Or do I have to have two scripts, like

```<code>get_songs_web.php
get_songs_android.php
</code>```

It should be noted that speed of development is crucial here; I'm learning this skill for a 24h competition, so I'm writing procedural PHP, not OO.

As an example of the type of scripts I have, so that you can use it as an example in your responses, here is one of the ones used in the webpage:

```<code><?php
    // Connect to database
    $db_connection = mysqli_connect('localhost', 'root', '', 'songs_list_data')
    or die('Error connecting to MySQL server!');

    // Get data from HTML form
    $name = $_POST["song"];
    $artist = $_POST["artist"];

    // Add song to database
    $add_song_query = $db_connection->prepare("INSERT INTO songs"
            . "(artist, name)"
            . "VALUES (?, ?)");
    $add_song_query->bind_param("ss", $artist, $name);
    $add_song_query->execute();
    $add_song_query->close();
?>

<html>
    <table id="results">
        <?php
            $results_query = $db_connection->prepare("SELECT *"
                    . "FROM songs");
            mysqli_stmt_execute($results_query);
            $result = mysqli_stmt_get_result($results_query);
            $row_num = 1;
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                echo '<tr class="songs_table_row">';
                    echo '<td class="row_num">' . $row_num . '</td>';
                    echo '<td class="artst">' . $row['artist'] . '</td>';
                    echo '<td class="name">' . $row['name'] . '</td>';
                echo '</tr>';
                $row_num++;
            }
            mysqli_stmt_close($results_query);
        ?>
    </table>
</html>

<?php
    // Close database connection
    mysqli_close($db_connection);
?>
</code>```

答:
Like this?</p>

```<code><?php
$results_query = $db_connection->prepare("SELECT * FROM songs");
mysqli_stmt_execute($results_query);
$result = mysqli_stmt_get_result($results_query);
$row_num = 1;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
    $myDataArray[] = array(
        'row_num'   => $row_num,
        'artist'    => $row['artist'],
        'name'      => $row['name'],
    );
    $row_num++;
}
mysqli_stmt_close($results_query);

function displayHtmlTable($dataArray){
    $output = '';
    $output .= '<table>';
    $output .= '<tbody>';
    foreach($dataArray as $rowId => $rowData){
        $output .= '<tr>';
        foreach($rowData as $colId => $cellData){
            $output .= '<td class="' . $colId . '">' . $cellData . '<td>';
        }
        $output .= '</tr>';
    }
    $output .= '</tbody>';
    $output .= '<table>';
    return $output;
}

$useragent = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))){
    header('Content-Type: application/json');
    echo json_encode($myDataArray);
}else{
    echo displayHtmlTable($myDataArray);
}
</code>```

Body:
So, I have a website that hits up a very simple PHP script to display data from a database in an HTML table.

My question is simple; is it possible to write the PHP script in such a way that I can use the same script to get the same data and return it in JSON for the android app that will need it (without a single if(onMobileApp) type god statment which is basically equivalent to writing two scripts anyways)?

Or do I have to have two scripts, like

get_songs_web.php
get_songs_android.php

It should be noted that speed of development is crucial here; I'm learning this skill for a 24h competition, so I'm writing procedural PHP, not OO.

As an example of the type of scripts I have, so that you can use it as an example in your responses, here is one of the ones used in the webpage:

<?php
    // Connect to database
    $db_connection = mysqli_connect('localhost', 'root', '', 'songs_list_data')
    or die('Error connecting to MySQL server!');

    // Get data from HTML form
    $name = $_POST["song"];
    $artist = $_POST["artist"];

    // Add song to database
    $add_song_query = $db_connection->prepare("INSERT INTO songs"
            . "(artist, name)"
            . "VALUES (?, ?)");
    $add_song_query->bind_param("ss", $artist, $name);
    $add_song_query->execute();
    $add_song_query->close();
?>

        <?php
            $results_query = $db_connection->prepare("SELECT *"
                    . "FROM songs");
            mysqli_stmt_execute($results_query);
            $result = mysqli_stmt_get_result($results_query);
            $row_num = 1;
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                echo '
';
                    echo '' . $row_num . '	';
                    echo '' . $row['artist'] . '	';
                    echo '' . $row['name'] . '	';
                echo '
';
                $row_num++;
            }
            mysqli_stmt_close($results_query);
        ?>

<?php
    // Close database connection
    mysqli_close($db_connection);
?>

Body:
Like this?

<?php
$results_query = $db_connection->prepare("SELECT * FROM songs");
mysqli_stmt_execute($results_query);
$result = mysqli_stmt_get_result($results_query);
$row_num = 1;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
    $myDataArray[] = array(
        'row_num'   => $row_num,
        'artist'    => $row['artist'],
        'name'      => $row['name'],
    );
    $row_num++;
}
mysqli_stmt_close($results_query);

function displayHtmlTable($dataArray){
    $output = '';
    $output .= '<table>';
    $output .= '<tbody>';
    foreach($dataArray as $rowId => $rowData){
        $output .= '<tr>';
        foreach($rowData as $colId => $cellData){
            $output .= '<td class="' . $colId . '">' . $cellData . '<td>';
        }
        $output .= '</tr>';
    }
    $output .= '</tbody>';
    $output .= '<table>';
    return $output;
}

$useragent = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))){
    header('Content-Type: application/json');
    echo json_encode($myDataArray);
}else{
    echo displayHtmlTable($myDataArray);
}


来源: stackexchange

问:
Redis command to get all available keys on Redis Cluster?
I am using this

```<code>redisManager.redisClient.keys('*example*', function (err, keys) {
})
</code>```

But it only gives keys from only one of the redis cluster. How can I get keys from all cluster?

答:
You can use this code inorder to find keys from all cluster. Please refer to link for more info.</p>

```<code>    var RedisCluster = require('node-redis-cluster').RedisCluster;

    var rcluster = RedisCluster.create([
        { port: 6379, host: '10.0.0.1' },
        { port: 6379, host: '10.0.0.2' },
        { port: 6379, host: '10.0.0.3' },
    ]);
    rcluster.execAll('keys', ['*'], function(err, results) {
    /* results will be
    {
        '10.0.0.1:6379': [ // keys],
        '10.0.0.2:6379': [ // keys],
        '10.0.0.3:6379': [ // keys]
    }
    */
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using this

redisManager.redisClient.keys('*example*', function (err, keys) {
})

But it only gives keys from only one of the redis cluster. How can I get keys from all cluster?

Body:
You can use this code inorder to find keys from all cluster. Please refer to link for more info.

    var RedisCluster = require('node-redis-cluster').RedisCluster;

    var rcluster = RedisCluster.create([
        { port: 6379, host: '10.0.0.1' },
        { port: 6379, host: '10.0.0.2' },
        { port: 6379, host: '10.0.0.3' },
    ]);
    rcluster.execAll('keys', ['*'], function(err, results) {
    /* results will be
    {
        '10.0.0.1:6379': [ // keys],
        '10.0.0.2:6379': [ // keys],
        '10.0.0.3:6379': [ // keys]
    }
    */
    });


问:
Wordpress Custom Logo with Description text
my Question is, is there anyway to add some descrption text to the Custom Logo Section. Like the description text you can see at website icon. See Screenshot attached. I wanna add some text under the word "Logo". Something like: "Your Logo should be 200px x 150px."

The Wordpress Codex doesn´t say anything about that. Is just width, height, flex width/height, header-text.

答: Seems like you want to add the text to the WordPress editing interface right? I don't really have much that part, but maybe reading this about customizing the WordPress admin will get you on your way?</p>


问:
Data Factory Execution Order on Pipeline
I'm having some troubles with the execution order of scheduled pipelines in Data Factory.

My pipeline is as follows:

```<code>{
    "name": "Copy_Stage_Upsert",
    "properties": {
        "description": "",
        "activities": [
            {
                "type": "Copy",
                "typeProperties": {
                    "source": {
                        "type": "BlobSource"
                    },
                    "sink": {
                        "type": "SqlDWSink",
                        "writeBatchSize": 10000,
                        "writeBatchTimeout": "00:10:00"
                    }
                },
                "inputs": [
                    {
                        "name": "csv_extracted_file"
                    }
                ],
                "outputs": [
                    {
                        "name": "stage_table"
                    }
                ],
                "policy": {
                    "timeout": "01:00:00",
                    "retry": 2
                },
                "scheduler": {
                    "frequency": "Hour",
                    "interval": 1
                },
                "name": "Copy to stage table"
            },
            {
                "type": "Copy",
                "typeProperties": {
                    "source": {
                        "type": "SqlDWSource",
                        "sqlReaderQuery": "SELECT * from table WHERE id NOT IN (SELECT id from stage_table) UNION ALL SELECT * from stage_table"
                    },
                    "sink": {
                        "type": "SqlDWSink",
                        "writeBatchSize": 10000,
                        "writeBatchTimeout": "00:10:00"
                    }
                },
                "inputs": [
                    {
                        "name": "stage_table"
                    }
                ],
                "outputs": [
                    {
                        "name": "upsert_table"
                    }
                ],
                "policy": {
                    "timeout": "01:00:00",
                    "retry": 2
                },
                "scheduler": {
                    "frequency": "Hour",
                    "interval": 1
                },
                "name": "Copy"
            },
            {
                "type": "SqlServerStoredProcedure",
                "typeProperties": {
                    "storedProcedureName": "sp_rename_tables"
                },
                "inputs": [
                    {
                        "name": "upsert_table"
                    }
                ],
                "outputs": [
                    {
                        "name": "table"
                    }
                ],
                "scheduler": {
                    "frequency": "Hour",
                    "interval": 1
                },
                "name": "Rename tables"
            }
        ],
        "start": "2017-02-09T18:00:00Z",
        "end": "9999-02-06T15:00:00Z",
        "isPaused": false,
        "hubName": "",
        "pipelineMode": "Scheduled"
    }
}
</code>```

For simplicity imagine that I've one pipeline called A with three simple tasks:
Task 1, Task 2 and finally Task 3.

Scenario A

One execution of Pipeline A scheduled.

It runs as:

Task 1 -> Task 2 -> Task 3

Scenario B

Two or more executions of Pipeline A scheduled to be executed.

It runs as:

First Scheduled Pipeline Task 1 -> Second Scheduled Pipeline Task 1 -> First Scheduled Pipeline Task 2 -> Second Scheduled Pipeline Task 2 -> First Scheduled Pipeline Task 2 -> First Scheduled Pipeline Task 3 -> Second Scheduled Pipeline Task 3.

Is it possible run the second scenario as:

First Scheduled Pipeline Task 1 -> First Scheduled Pipeline Task 2 -> First Scheduled Pipeline Task 3, Second Scheduled Pipeline Task 1 -> Second Scheduled Pipeline Task 2 -> Second Scheduled Pipeline Task 3

In other words, I need to finish the first scheduled pipeline before the second pipeline starts.

Thank you in advance!

答:
It's possible. However, it will require some fake input and output datasets to enforce the dependency behaviour and create the chain as you describe. So possible, but a dirty hack!

This isn't a great solution and it will become complicated if your outputs/downstream datasets in the second pipeline have different time slice intervals to the first. I recommend testing and understanding this.

Really ADF isn't designed to do what you want. It's not a tool to sequence things like steps in a SQL Agent job. ADF is for scale and parallel work streams.

As I understand in whispers from Microsoft peeps there might be more event driven scheduling coming soon in ADF. But I don't know for sure.

Hope this helps.

Body:
I'm having some troubles with the execution order of scheduled pipelines in Data Factory.

My pipeline is as follows:

{
    "name": "Copy_Stage_Upsert",
    "properties": {
        "description": "",
        "activities": [
            {
                "type": "Copy",
                "typeProperties": {
                    "source": {
                        "type": "BlobSource"
                    },
                    "sink": {
                        "type": "SqlDWSink",
                        "writeBatchSize": 10000,
                        "writeBatchTimeout": "00:10:00"
                    }
                },
                "inputs": [
                    {
                        "name": "csv_extracted_file"
                    }
                ],
                "outputs": [
                    {
                        "name": "stage_table"
                    }
                ],
                "policy": {
                    "timeout": "01:00:00",
                    "retry": 2
                },
                "scheduler": {
                    "frequency": "Hour",
                    "interval": 1
                },
                "name": "Copy to stage table"
            },
            {
                "type": "Copy",
                "typeProperties": {
                    "source": {
                        "type": "SqlDWSource",
                        "sqlReaderQuery": "SELECT * from table WHERE id NOT IN (SELECT id from stage_table) UNION ALL SELECT * from stage_table"
                    },
                    "sink": {
                        "type": "SqlDWSink",
                        "writeBatchSize": 10000,
                        "writeBatchTimeout": "00:10:00"
                    }
                },
                "inputs": [
                    {
                        "name": "stage_table"
                    }
                ],
                "outputs": [
                    {
                        "name": "upsert_table"
                    }
                ],
                "policy": {
                    "timeout": "01:00:00",
                    "retry": 2
                },
                "scheduler": {
                    "frequency": "Hour",
                    "interval": 1
                },
                "name": "Copy"
            },
            {
                "type": "SqlServerStoredProcedure",
                "typeProperties": {
                    "storedProcedureName": "sp_rename_tables"
                },
                "inputs": [
                    {
                        "name": "upsert_table"
                    }
                ],
                "outputs": [
                    {
                        "name": "table"
                    }
                ],
                "scheduler": {
                    "frequency": "Hour",
                    "interval": 1
                },
                "name": "Rename tables"
            }
        ],
        "start": "2017-02-09T18:00:00Z",
        "end": "9999-02-06T15:00:00Z",
        "isPaused": false,
        "hubName": "",
        "pipelineMode": "Scheduled"
    }
}

For simplicity imagine that I've one pipeline called A with three simple tasks:
Task 1, Task 2 and finally Task 3.

Scenario A

One execution of Pipeline A scheduled.

It runs as:

Task 1 -> Task 2 -> Task 3

Scenario B

Two or more executions of Pipeline A scheduled to be executed.

It runs as:

First Scheduled Pipeline Task 1 -> Second Scheduled Pipeline Task 1 -> First Scheduled Pipeline Task 2 -> Second Scheduled Pipeline Task 2 -> First Scheduled Pipeline Task 2 -> First Scheduled Pipeline Task 3 -> Second Scheduled Pipeline Task 3.

Is it possible run the second scenario as:

First Scheduled Pipeline Task 1 -> First Scheduled Pipeline Task 2 -> First Scheduled Pipeline Task 3, Second Scheduled Pipeline Task 1 -> Second Scheduled Pipeline Task 2 -> Second Scheduled Pipeline Task 3

In other words, I need to finish the first scheduled pipeline before the second pipeline starts.

Thank you in advance!


问:
Android, perform action when widget is clicked
Can someone provide me with an example of how to perform an action when the user taps on a widget? The only example I have found launches an activity. I assume that it must still do it with some sort of pending intent and maybe a broadcast receiver, but I'm not sure how to do it.</p>

答: Call RemoteViews.setOnClickPendingIntent on the views in your widget (assuming you have views in your widget).

ContentLicense: CC BY-SA 2.5


问:
Settings.Default.Upgrade() does not keep current settings
I have a WPF application that uses the built-in Settings functionality. When I release a new version of the application, I increase the assembly version and execute the following code at application start:

```<code>if (Settings.Default.IsSettingsUpgradeRequired) //this defaults to true when a new version of this software has been released
            {
                Settings.Default.Upgrade(); //upgrade the settings to the newer version
                Settings.Default.Reload();
                Settings.Default.IsSettingsUpgradeRequired = false;
                Settings.Default.LastSettingsUpdate = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
                Settings.Default.Save();
            }
</code>```

The problem is that the previous settings are not maintained. Instead, a new folder under \AppData\Local\ is created each time a new version comes up. Thus, the default settings are used instead of those of the previous version. I know that, under normal circumstances, there should be ONE folder that contains many sub-folders with the application's version as name. Instead, I have MANY folders each containing only one folder with the application's version as name.
The folder structure in Local\ looks like this:

myApp.exe_Url_5s2axp5sywfyhblm3201qetpqnmwnvsc

myApp.exe_Url_ft4ih1ze0qsz5abu11t334omxo1431c0

myApp.exe_Url_glsc2d3cjmswry2bxebb53jndfptav1x

myApp.exe_Url_qngn1rqmbfyy42fdgpmc3ystsaknuxnv

myApp.exe_Url_vqn0ogftrchl1fild5fe34hmijvmd2zr

So how do I stop the system to create so many folders and make it only use one folder per application so that I can properly upgrade my settings?

Edit: another thing I noticed today is that if I change the location of the application's folder (lets say move it from desktop to C:\myApp), the application creates a new settings folder when first started. Why does the system not recognize it as the same application?

答:
I finally got it to work. I don't know the cause for the desrcibed behavior, but one of these 2 things fixed it:

Added the default manifest file and changed the "assemblyIdentity" node (the "version" attribute does not seem to have an effect on the Settings)

Activated the signing feature of Visual Studio (Project properties --> Signing)

Body:
I have a WPF application that uses the built-in Settings functionality. When I release a new version of the application, I increase the assembly version and execute the following code at application start:

if (Settings.Default.IsSettingsUpgradeRequired) //this defaults to true when a new version of this software has been released
            {
                Settings.Default.Upgrade(); //upgrade the settings to the newer version
                Settings.Default.Reload();
                Settings.Default.IsSettingsUpgradeRequired = false;
                Settings.Default.LastSettingsUpdate = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
                Settings.Default.Save();
            }

The problem is that the previous settings are not maintained. Instead, a new folder under \AppData\Local\ is created each time a new version comes up. Thus, the default settings are used instead of those of the previous version. I know that, under normal circumstances, there should be ONE folder that contains many sub-folders with the application's version as name. Instead, I have MANY folders each containing only one folder with the application's version as name.
The folder structure in Local\ looks like this:

myApp.exe_Url_5s2axp5sywfyhblm3201qetpqnmwnvsc

myApp.exe_Url_ft4ih1ze0qsz5abu11t334omxo1431c0

myApp.exe_Url_glsc2d3cjmswry2bxebb53jndfptav1x

myApp.exe_Url_qngn1rqmbfyy42fdgpmc3ystsaknuxnv

myApp.exe_Url_vqn0ogftrchl1fild5fe34hmijvmd2zr

So how do I stop the system to create so many folders and make it only use one folder per application so that I can properly upgrade my settings?

Edit: another thing I noticed today is that if I change the location of the application's folder (lets say move it from desktop to C:\myApp), the application creates a new settings folder when first started. Why does the system not recognize it as the same application?


问:
save tableview data in swift MVC
I have this code. I'm developing my app without storyboard:

SecondController.swift

```<code>class SecondController: UIViewController {

var items: [String] = ["DATA 1", "DATA 2", "DATA 3"]
let tableView: UITableView  =   UITableView()

init(){
    super.init(nibName: nil, bundle: nil)
    self.view = SecondView()
    self.view.backgroundColor=UIColor.green

    tableView.frame         =   CGRect(0, 50, 320, 200);
    tableView.delegate      =   self
    tableView.dataSource    =   self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    self.view.addSubview(tableView)
}

override var prefersStatusBarHidden: Bool {
    return true
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

func onClickListener(object : UIButton!) {
    self.navigationController!.popViewController(animated: false)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
}}
extension SecondController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
    return self.items.count
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.row)!")
    items.append("NEW DATA")
    print(items.count)
    self.tableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    cell.textLabel?.text = self.items[indexPath.row]
    return cell
}}
</code>```

And SecondView.swift

```<code>class SecondView: UIView {
var btnImage = UIButton(image: "resume")

override init(frame: CGRect){
    super.init(frame: screenSize)
    self.backgroundColor = UIColor.black

    // Btn
    self.btnImage.translatesAutoresizingMaskIntoConstraints = false
    addSubview(self.btnImage)
    self.btnImage.alignLeftOfViewVoid(padding: 1)
    self.btnImage.addTarget(self.parentViewController, action: #selector (SecondController.onClickListener(object:)), for: .touchUpInside)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

deinit{
    self.removeFromSuperview()
}}
</code>```

The table works perfectly, but when I press the button the app returns to FirstView and FirstController, and when I want return to SecondView and SecondController, I lose the new data items.

Where can I put the array data if I don't want lose them? Can I separate the TableView in another file?

Thank you

答:
You did not implement any data persistent method.

Take a look at this link, it shows a couple ways to persist your data.
It's form 2015, so you need to understand it and apply swift 3.1 accordingly.

Title: save tableview data in swift MVC

Body:
I have this code. I'm developing my app without storyboard:

SecondController.swift

class SecondController: UIViewController {

var items: [String] = ["DATA 1", "DATA 2", "DATA 3"]
let tableView: UITableView  =   UITableView()

init(){
    super.init(nibName: nil, bundle: nil)
    self.view = SecondView()
    self.view.backgroundColor=UIColor.green

    tableView.frame         =   CGRect(0, 50, 320, 200);
    tableView.delegate      =   self
    tableView.dataSource    =   self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    self.view.addSubview(tableView)
}

override var prefersStatusBarHidden: Bool {
    return true
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

func onClickListener(object : UIButton!) {
    self.navigationController!.popViewController(animated: false)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
}}
extension SecondController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
    return self.items.count
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.row)!")
    items.append("NEW DATA")
    print(items.count)
    self.tableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    cell.textLabel?.text = self.items[indexPath.row]
    return cell
}}

And SecondView.swift

class SecondView: UIView {
var btnImage = UIButton(image: "resume")

override init(frame: CGRect){
    super.init(frame: screenSize)
    self.backgroundColor = UIColor.black

    // Btn
    self.btnImage.translatesAutoresizingMaskIntoConstraints = false
    addSubview(self.btnImage)
    self.btnImage.alignLeftOfViewVoid(padding: 1)
    self.btnImage.addTarget(self.parentViewController, action: #selector (SecondController.onClickListener(object:)), for: .touchUpInside)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

deinit{
    self.removeFromSuperview()
}}

The table works perfectly, but when I press the button the app returns to FirstView and FirstController, and when I want return to SecondView and SecondController, I lose the new data items.

Where can I put the array data if I don't want lose them? Can I separate the TableView in another file?

Thank you


答:
You said you go back to FirstController, so your SecondController gets destroyed from memory along with items array. If you want to have them accessible across the app, you should create a Model class (according to MVC pattern that you mentioned yourself in your question title).

```<code>class DataStorage {
    static let shared = DataStorage()
    var items: [String] = ["DATA 1", "DATA 2", "DATA 3"]
}
</code>```

Now you can access this data from your SecondController like this:

```<code>func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
    return DataStorage.shared.items.count
}
</code>```

This is, of course, rough implementation, and you will most likely need to implement a set of methods in DataStorage class to modify (create, update, delete) your items.

UPD: This way lets you only store data in memory until app is terminated. In order to persist it, you need to store it on disk using CoreData, SQLite, Property Lists etc, as described in article suggested by @f_qi. Anyway, you should have separated Model file like DataStorage to manage this logic.

Title: save tableview data in swift MVC

Body:
You said you go back to FirstController, so your SecondController gets destroyed from memory along with items array. If you want to have them accessible across the app, you should create a Model class (according to MVC pattern that you mentioned yourself in your question title).

class DataStorage {
    static let shared = DataStorage()
    var items: [String] = ["DATA 1", "DATA 2", "DATA 3"]
}

Now you can access this data from your SecondController like this:

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
    return DataStorage.shared.items.count
}

This is, of course, rough implementation, and you will most likely need to implement a set of methods in DataStorage class to modify (create, update, delete) your items.

UPD: This way lets you only store data in memory until app is terminated. In order to persist it, you need to store it on disk using CoreData, SQLite, Property Lists etc, as described in article suggested by @f_qi. Anyway, you should have separated Model file like DataStorage to manage this logic.


问:
A more pythonic way to define an enum with dynamic members
I needed to create an enum to represent the ISO country codes. The country code data comes from a json file which can be obtained from: https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

So what I've done is:

```<code>data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
              for i in range(len(data))]

CountryCode = enum.Enum('CountryCode', codes_list,)

names_dict = {int(data[i]['country-code']):data[i]['name']
              for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)

CountryCode.choices = classmethod(lambda cls:((member.value, name)
                                  for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])
</code>```

This code snippet is frankly ugly. I looked at alternative ways to define the enum class but couldn't piece together a solution. Is there a way to define the enum in the following form:

```<code>class CountryCode(enum.Enum):

    data = json.load(open('slim-2.json'))
    # Some code to define the enum members

    @classmethod
    def choices(cls):
    # etc...
</code>```

Any suggestions on how to do this?

答:
How about this?

```<code>data = json.load(open('slim-2.json'))
CountryCode = enum.Enum('CountryCode', [
    (x['alpha-2'], int(x['country-code'])) for x in data
])
CountryCode._names = {x['alpha-2']: x['name'] for x in data}
CountryCode.__str__ = lambda self: self._names[self.name]
CountryCode.choices = lambda: ((e.value, e.name) for e in CountryCode)
</code>```

Replaced [...data[i]... for i in range(len(data))] with [...x... for x in data]; You can itearte sequence (list, data in the code) without using indexes.

Used CountryCode.attr = ... consistently; instead of mixing CountryCode.attr = ... and setattr(CountryCode, 'attr', ...).

Body:
I needed to create an enum to represent the ISO country codes. The country code data comes from a json file which can be obtained from: https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes

So what I've done is:

data = json.load(open('slim-2.json'))
codes_list = [(data[i]['alpha-2'], int(data[i]['country-code']))
              for i in range(len(data))]

CountryCode = enum.Enum('CountryCode', codes_list,)

names_dict = {int(data[i]['country-code']):data[i]['name']
              for i in range(len(data))}
setattr(CountryCode, '_names', names_dict)

CountryCode.choices = classmethod(lambda cls:((member.value, name)
                                  for name, member in cls.__members__.items()))
setattr(CountryCode, '__str__' ,lambda self: self.__class__._names[self.value])

This code snippet is frankly ugly. I looked at alternative ways to define the enum class but couldn't piece together a solution. Is there a way to define the enum in the following form:

class CountryCode(enum.Enum):

    data = json.load(open('slim-2.json'))
    # Some code to define the enum members

    @classmethod
    def choices(cls):
    # etc...

Any suggestions on how to do this?

Body:
How about this?

data = json.load(open('slim-2.json'))
CountryCode = enum.Enum('CountryCode', [
    (x['alpha-2'], int(x['country-code'])) for x in data
])
CountryCode._names = {x['alpha-2']: x['name'] for x in data}
CountryCode.__str__ = lambda self: self._names[self.name]
CountryCode.choices = lambda: ((e.value, e.name) for e in CountryCode)

Replaced [...data[i]... for i in range(len(data))] with [...x... for x in data]; You can itearte sequence (list, data in the code) without using indexes.

Used CountryCode.attr = ... consistently; instead of mixing CountryCode.attr = ... and setattr(CountryCode, 'attr', ...).


问:
Twilio chat - client channels list is always nil
For embedded chat feature in an app we are using Twilio's Programmable Chat framework. TwilioChatClient was created as follows:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let token = utils.user_token {
        setupTwilio(token: token)
    }else {
        utils.getAccessToken({
            user_token in

            if let token = user_token as String! {
                self.setupTwilio(token: token)
            }
        })
    }
}

private func setupTwilio(token: String) {
    if client == nil {
        client = TwilioChatClient(token: token, properties: nil, delegate: self)
    }
}
</code>```

According to twilio documentation, we need client?.channelsList() to create, get, join, even delete a channel and client?.channelsList() we get is always nil.
FYI, the token is used for creating client is valid and client is not nil. Can someone tell me why we're getting nil for client?.channelsList()? Or are we missing something?

Another lame question, what are the differences between TwilioIPMessagingClient and TwilioChatClient? I assumed that TwilioChatClient is an upgrade of TwilioIPMessagingClient, but haven't found any clear documentation. Can anyone please get me the migration guide?

Edit

P.S.
We did wait for client to be initialized at delegate method; like

```<code>extension ChatViewController: TwilioChatClientDelegate {
    func chatClient(_ client: TwilioChatClient!, synchronizationStatusChanged status: TCHClientSynchronizationStatus) {
         guard status != .completed else {
             print("Show failed alert")
             return
         }

         guard client.channelsList() != nil else {
             print("channel list is nil");
             return
         }

         // create and/or join channel
         joinChatChannel();
   }
}
</code>```

But flow always fails at second guard.

答:
Thanks to @rbeiter and Twilio for their sincere support.
The problem was, we were missing the identity in token information. The Twilio log indicated that at

2017-03-15 06:38:03.842117 TwilioChatApplication[1053:482861] TNTwilsockClientImpl[3]: 0x16e2b7000 | 03/15/06:38:03.841 | INFO | 2 | TNTwilsockClientImpl | Close description: {"code":401,"status":"'identity' not present in token grants"}

According to rbeiter, If you are using one of Twilio's generators to build the token, this can be solved by setting the identity key in the grants hash or object.

Body:
For embedded chat feature in an app we are using Twilio's Programmable Chat framework. TwilioChatClient was created as follows:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let token = utils.user_token {
        setupTwilio(token: token)
    }else {
        utils.getAccessToken({
            user_token in

            if let token = user_token as String! {
                self.setupTwilio(token: token)
            }
        })
    }
}

private func setupTwilio(token: String) {
    if client == nil {
        client = TwilioChatClient(token: token, properties: nil, delegate: self)
    }
}

According to twilio documentation, we need client?.channelsList() to create, get, join, even delete a channel and client?.channelsList() we get is always nil.
FYI, the token is used for creating client is valid and client is not nil. Can someone tell me why we're getting nil for client?.channelsList()? Or are we missing something?

Another lame question, what are the differences between TwilioIPMessagingClient and TwilioChatClient? I assumed that TwilioChatClient is an upgrade of TwilioIPMessagingClient, but haven't found any clear documentation. Can anyone please get me the migration guide?

Edit

P.S.
We did wait for client to be initialized at delegate method; like

extension ChatViewController: TwilioChatClientDelegate {
    func chatClient(_ client: TwilioChatClient!, synchronizationStatusChanged status: TCHClientSynchronizationStatus) {
         guard status != .completed else {
             print("Show failed alert")
             return
         }

         guard client.channelsList() != nil else {
             print("channel list is nil");
             return
         }

         // create and/or join channel
         joinChatChannel();
   }
}

But flow always fails at second guard.


问:
Mongodb save date with timezone
I want to save date with timezone of singapore. Some of date are coming in singapore timezone and some are not. So i want to change the timezone of all the date (returning from api) to singapore first and then save to database.
Also i want that when i use new Date() (javascript) it automatically give the the date with singapore timezone.
My questions are:-
1.How to save all the date in mongo with Asia/Singapore timezone?
2.How to set new Date() timezone to Asia/Singapore ?

答:
I think the best way will be to add (or subtract) the gap between your timezone and the Singapore one, in your application.
Something like
 new Date().AddHours(+- gap);
Which driver are you using?

By the way, why don't you keep another "column" with the timezone id, so you can set the timezone correctly both for your country and for Singapore?

Title: Mongodb save date with timezone


问:
What do curly braces in the Windows registry mean?
I've been wondering this for a while and can't seem to get answer.

In Windows (maybe other places too), what do the curly braces mean? I'm guessing it has to do with hex but not sure.

Any help would be appreciated.

*UPDATE

I'm sorry I wasn't as specific as I should have been. I was talking about in the registry, but I've also seen it in folder paths.

答:
Repetition in regular expressions: /a{3,5}/.

Anonymous hash composers in Perl: my $rec = { };.  Also for dictionaries in Python.

Data assignments of structures or arrays in languages like C or Java: String data[] = { "TGF-βs", "XPTTD", "CIMPR", "CFU-F", "Qiagen", "BrdU-positive", "TSFLLRVYFQPGPPATAAPVPSPT", "Amersham", "DAPI-stained" };

Perl dereferencing operators: ${ $array_of_refs[17} }.

Hash subscripting in Perl: $ENV{USER}

Filename globbing in the shell:    % echo {this,that,those,these}_{here,there,everywhere} produces
    this_here this_there this_everywhere that_here that_there that_everywhere those_here those_there those_everywhere these_here these_there these_everywhere

Hiding a semicolon in plain sight, since a CTRL-{ is a ;. That’s because the CONTROL- operation is an xor with an @.  \cC is @^C == chr(3), so \c{ is @^{ == chr(59) eq ";".

Balanced pick-your-own-quotes operators to avoid escaping slashes, like print if m{^/usr/local/bin}

History substitution disambiguating: “ !{v}doc would expand unambiguously to vi wumpus.mandoc”

Unambiguous octal and hex escapes in strings, like "10\o{377}01" and "The \x{bee} character is TAMIL DIGIT EIGHT".

A symbol used in mathematics and music.

The name of particularly little-known variable in Perl: perl -le '$} = "eskimo"; print $}' prints eskimo!


问:
read input from user and print it back on console in MIPS assembly
Im trying to make simple program which will read input from user and print it back on console here is part of mine program

```<code>LEAF(main)

#Print to user enter integer
    li    a0,1                # first argument fd 1
    la    a1,prompt           # second argument memory location of hello string
    li    a2,20               # lenght of string to print
    li    v0,__NR_write       # syscall write,they are defined in unistd.h
    syscall

#Raad the integer and save it in s0
    li    a0,0                # first argument for stdin is 0
    li    a1,unknown          # second argument is unknown
    li    a2,unknown          # third arg is also unknown
    li    v0,__NR_read
    syscall
    move s0, v0
</code>```

So mine program waits for input from user and after entering 1 or 9 the value of v0 and and S0 (inspected with gdb) are 0x2 not 0x1 and 0x9 respectively.

Edit:
so i just found this

```<code>sys_read(unsigned int fd, char __user *buf, size_t count);
</code>```

so second argument is __user *buf so its pointer to a *buf so is this where I should store it ?
and third argument is size_t count but count for what ? Count of number of byts ?

答:
I just solved it here is an answer</p>

```<code>#Read the integer and save it in s0
    nop
    nop
    li    a0,0      # firs argument, for stdin is 0 ISTR, see "man 2 read"
    la    a1,(var1) # second argument load adress of var1 into a1
    li    a2,12     # third argument is count of byts
    li    v0,__NR_read
    syscall
.data

var1:      .space     256
</code>```

Body:
Im trying to make simple program which will read input from user and print it back on console here is part of mine program

LEAF(main)

#Print to user enter integer
    li    a0,1                # first argument fd 1
    la    a1,prompt           # second argument memory location of hello string
    li    a2,20               # lenght of string to print
    li    v0,__NR_write       # syscall write,they are defined in unistd.h
    syscall

#Raad the integer and save it in s0
    li    a0,0                # first argument for stdin is 0
    li    a1,unknown          # second argument is unknown
    li    a2,unknown          # third arg is also unknown
    li    v0,__NR_read
    syscall
    move s0, v0

So mine program waits for input from user and after entering 1 or 9 the value of v0 and and S0 (inspected with gdb) are 0x2 not 0x1 and 0x9 respectively.

Edit:
so i just found this

sys_read(unsigned int fd, char __user *buf, size_t count);

so second argument is __user *buf so its pointer to a *buf so is this where I should store it ?
and third argument is size_t count but count for what ? Count of number of byts ?

Body:
I just solved it here is an answer

#Read the integer and save it in s0
    nop
    nop
    li    a0,0      # firs argument, for stdin is 0 ISTR, see "man 2 read"
    la    a1,(var1) # second argument load adress of var1 into a1
    li    a2,12     # third argument is count of byts
    li    v0,__NR_read
    syscall
.data

var1:      .space     256


问:
Fastlane: Difference between `build_settings` and `xcargs`?
I'm migrating a project to using Fastlane, and I need to pass GCC_PREPROCESSOR_DEFINITIONS to xcbuild. I noticed two arguments to gym, build_settings and xcargs. What is the difference between these two, and which is the best to use to define these preprocessor definitions?

答:
It seems like you're asking about gym, but the link in your question leads to the code for the fastlane xcodebuild action, which is a separate thing from gym.

To answer your question for gym, you should use the xcargs option additional arguments for the build phase. For the package phase, use the export_xcargs option instead.


问:
PHP map array data to HTML table while skipping some html table columns
Alo,

I have this array in php:

```<code>$data=array(1,2,3,4,5,6,7,8);
</code>```

I want to put it in html table that has the following structure (image)

The colored columns are to be skipped entirely. I have failed to do so but here is my attempt anyway:

```<code>$totalColumnsPerRow=8;
$skippableColumns=array(3,6,7,8);
$counter=1;
//loop the array now
$row="<tr>";
foreach($data as $val){
//do we need to start a new row or not?
 if ($counter==$totalColumnsPerRow){
 //close open row and create a new one.
 $counter=1;
 $row.="</tr><tr>":
  }

 //show I skip the current column or not?
 if(in_array($counter,$skippableColumns)){
 //skip column then add current value
 $row.="<td></td>";
 $row.="<td>$val</td>";
 }
 else{
 $row.="<td>$val</td>";
  }
 $counter++;
}
</code>```

That gives me the following table structure. If it had successfully skipped the rows, a new row would have started with value 5.

Here is a PHP fiddle

Any idea on how to like pause the loop and use it in usable column? Is my approach practical?

答:
I modified your code to recheck within the same loop (using the same $val data) with the seldom used, much maligned goto control. Minimal changes to your existing code.</p>

```<code>foreach($data as $val){
    //we'll come back here to decide on skip or write of next row when a skippable is encountered
    //this keeps us locked onto the same $val until it is written out
    recheck:
    //do we need to start a new row or not?
    if ($counter==$totalColumnsPerRow){
    //close open row and create a new one.
        $counter=1;
        $row.="</tr><tr>";
    }

    //show I skip the current column or not?
    if(in_array($counter,$skippableColumns)){
    //skip column then add current value
        $row.="<td></td>";
        $counter++;
        goto recheck;
    //   $row.="<td>$val</td>";
    }
    else{
        $row.="<td>$val</td>";
    }
    $counter++;
}
</code>```

Body:
Alo,

I have this array in php:

$data=array(1,2,3,4,5,6,7,8);

I want to put it in html table that has the following structure (image)

The colored columns are to be skipped entirely. I have failed to do so but here is my attempt anyway:

$totalColumnsPerRow=8;
$skippableColumns=array(3,6,7,8);
$counter=1;
//loop the array now
$row="
";
foreach($data as $val){
//do we need to start a new row or not?
 if ($counter==$totalColumnsPerRow){
 //close open row and create a new one.
 $counter=1;
 $row.="

":
  }

 //show I skip the current column or not?
 if(in_array($counter,$skippableColumns)){
 //skip column then add current value
 $row.="	";
 $row.="$val	";
 }
 else{
 $row.="$val	";
  }
 $counter++;
}

That gives me the following table structure. If it had successfully skipped the rows, a new row would have started with value 5.

Here is a PHP fiddle

Any idea on how to like pause the loop and use it in usable column? Is my approach practical?

Body:
I modified your code to recheck within the same loop (using the same $val data) with the seldom used, much maligned goto control. Minimal changes to your existing code.

foreach($data as $val){
    //we'll come back here to decide on skip or write of next row when a skippable is encountered
    //this keeps us locked onto the same $val until it is written out
    recheck:
    //do we need to start a new row or not?
    if ($counter==$totalColumnsPerRow){
    //close open row and create a new one.
        $counter=1;
        $row.="</tr><tr>";
    }

    //show I skip the current column or not?
    if(in_array($counter,$skippableColumns)){
    //skip column then add current value
        $row.="<td></td>";
        $counter++;
        goto recheck;
    //   $row.="<td>$val</td>";
    }
    else{
        $row.="<td>$val</td>";
    }
    $counter++;
}


问:
Most elegant isEmpty() Method for Binary Tree
I'm trying to write the most elegant isEmpty() method for my LinkedBinaryTree class.

When the compiler interacts with the if statement, it should return a boolean value or either true of false. However, since it is necessary to return a value outside the if statement, I've returned a value of false. My logic is that if (count == 0), isEmpty() returns true and doesn't bother with the second line (return false). Is this correct?

```<code>public class LinkedBinaryTree<T> implements BinaryTreeADT<T>
{
   protected int count;
   protected BinaryTreeNode<T> root;

   /**
    * Creates an empty binary tree.
    */
   public LinkedBinaryTree()
   {
      count = 0;
      root = null;
   }

   /**
    * Creates a binary tree with the specified element as its root.
    *
    * @param element  the element that will become the root of the new binary tree
    */
   public LinkedBinaryTree (T element)
   {
      count = 1;
      root = new BinaryTreeNode<T> (element);
   }

   /**
    * Returns true if this binary tree is empty and false otherwise.
    *
    * @return  true if this binary tree is empty
    */
   public boolean isEmpty()
   {
       if (count == 0);
       return false;
   }
</code>```

答:
You can just return your condition without "if" statement

```<code>public boolean isEmpty() {
   return (count == 0);
</code>```

}

Body:
I'm trying to write the most elegant isEmpty() method for my LinkedBinaryTree class.

When the compiler interacts with the if statement, it should return a boolean value or either true of false. However, since it is necessary to return a value outside the if statement, I've returned a value of false. My logic is that if (count == 0), isEmpty() returns true and doesn't bother with the second line (return false). Is this correct?

public class LinkedBinaryTree<T> implements BinaryTreeADT<T>
{
   protected int count;
   protected BinaryTreeNode<T> root;

   /**
    * Creates an empty binary tree.
    */
   public LinkedBinaryTree()
   {
      count = 0;
      root = null;
   }

   /**
    * Creates a binary tree with the specified element as its root.
    *
    * @param element  the element that will become the root of the new binary tree
    */
   public LinkedBinaryTree (T element)
   {
      count = 1;
      root = new BinaryTreeNode<T> (element);
   }

   /**
    * Returns true if this binary tree is empty and false otherwise.
    *
    * @return  true if this binary tree is empty
    */
   public boolean isEmpty()
   {
       if (count == 0);
       return false;
   }

Body:
You can just return your condition without "if" statement

public boolean isEmpty() {
   return (count == 0);

}


问:
FFmpeg record rtsp stream to file error
I use ffmpeg to record rtsp stream, it work good but the output file got some proble, when I use use K-Lite Codec Pack to open the output (avi) file the video cant be seek, forward, backward and dont display video time. It lock like i am viewing streaming.

here is the command i used

```<code>ffmpeg -i rtsp://27.74.xxx.xxx:55/ufirststream -acodec copy -vcodec copy abc.avi
</code>```

video playing error with K-Lite Codec Park image

答: Looks like header file not been updated on output file. It's recommended to close output file by pressing "q" button while ffmpeg reads input stream to properly finalize output file. </p>

Title: FFmpeg record rtsp stream to file error

Body:
I use ffmpeg to record rtsp stream, it work good but the output file got some proble, when I use use K-Lite Codec Pack to open the output (avi) file the video cant be seek, forward, backward and dont display video time. It lock like i am viewing streaming.

here is the command i used

ffmpeg -i rtsp://27.74.xxx.xxx:55/ufirststream -acodec copy -vcodec copy abc.avi

video playing error with K-Lite Codec Park image


问:
Write data on google sheets through android app form
I am new to android and I want to publish my form data which is created in an android app to google sheets. Can anyone help me out with this problem</p>

答:
This is totally doable. Checkout the Android Quickstart for Sheetsv4 to give you an idea of the code flow. Then the main thing you have to know is to Write on A Single/Multiple Range using

```<code>PUT https://sheets.googleapis.com/v4/spreadsheets/spreadsheet_id/values/range?
            valueInputOption=value_input_option
</code>```

You can find actual writing sample in Basic Writing:

```<code> https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId/values/Sheet1!A1:D5?valueInputOption=USER_ENTERED
</code>```

Body:
This is totally doable. Checkout the Android Quickstart for Sheetsv4 to give you an idea of the code flow. Then the main thing you have to know is to Write on A Single/Multiple Range using

PUT https://sheets.googleapis.com/v4/spreadsheets/spreadsheet_id/values/range?
            valueInputOption=value_input_option

You can find actual writing sample in Basic Writing:

 https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId/values/Sheet1!A1:D5?valueInputOption=USER_ENTERED


问:
Method to remove specific obsolete lines of code from an entire codebase?
I have some code:

```<code>#if SILOG
    SiAuto.Main.LogException(ex);
    // some other lines
#endif
</code>```

What would be the easiest way to remove surrounding #if from my entire codebase, i.e., end up with just:

```<code>SiAuto.Main.LogException(ex);
</code>```

I'm using Visual Studio 2010. I'll accept the first answer that I can test to see if it works. Looking forward to your ideas!

答:
Assuming your codebase is all in one solution file, and you don't have nested preprocessor directives, You can do a find and replace with a regexp:

```<code>\#if SILOG{(.*\n)@}\#endif
</code>```

For the replacement string, use this:

```<code>\1
</code>```

Make sure have are using the "Regular expressions" find option checked.

Step by step:

Open the find and replace dialog (ctrl+H)

Under "Find what:", enter "#if SILOG{(.*\n)@}#endif" without the quotes

Under "Replace with:", enter "\1" without the quotes

Under "Look in", select "Entire Solution"

Expand "Find options"

Check "Use:" and select "Regular expressions" from the combobox

Click "Find Next" to see if it worked

Click "Replace All" if you're brave

This won't fix the indentation of the code that was between the #if / #endif, however.

Body:
I have some code:

#if SILOG
    SiAuto.Main.LogException(ex);
    // some other lines
#endif

What would be the easiest way to remove surrounding #if from my entire codebase, i.e., end up with just:

SiAuto.Main.LogException(ex);

I'm using Visual Studio 2010. I'll accept the first answer that I can test to see if it works. Looking forward to your ideas!

Body:
Assuming your codebase is all in one solution file, and you don't have nested preprocessor directives, You can do a find and replace with a regexp:

\#if SILOG{(.*\n)@}\#endif

For the replacement string, use this:

\1

Make sure have are using the "Regular expressions" find option checked.

Step by step:

Open the find and replace dialog (ctrl+H)

Under "Find what:", enter "#if SILOG{(.*\n)@}#endif" without the quotes

Under "Replace with:", enter "\1" without the quotes

Under "Look in", select "Entire Solution"

Expand "Find options"

Check "Use:" and select "Regular expressions" from the combobox

Click "Find Next" to see if it worked

Click "Replace All" if you're brave

This won't fix the indentation of the code that was between the #if / #endif, however.


问:
No notification triggered on Bot FB Messenger mobile device
When I use Conversations.SendToConversationAsync, the message arrives well on FB messenger but it not there no notification.
How I can make to triggers notification on mobile device for FB messenger?

Thank you

答: Please make sure Messenger app has notification permissions. On Android, go to Settings -> Apps -> Messenger -> Notifications and make sure that Block All is not checked.</p>


问:
How to populate a dropdown in Symfony 3
I am a newbie in symfony and i have decided to explore symfony 3. I have two models: products and category and I want to populate a dropdown in a new product form with all the categories. How can i do this pls?
Below is what have done so far:

```<code><?php
</code>```

Product Model:

```<code>namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Persisters\Entity;
use Doctrine\ORM\Mapping\Column;

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 */
class Product
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $category;

    /**
     * @ORM\Column( type ="string", length=100)
     */
    private $name;

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    private $price;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Product
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param string $price
     *
     * @return Product
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return string
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Product
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set category
     *
     * @param \AppBundle\Entity\Category $category
     *
     * @return Product
     */
    public function setCategory(\AppBundle\Entity\Category $category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return \AppBundle\Entity\Category
     */
    public function getCategory()
    {
        return $this->category;
    }
}
</code>```

```<code>namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
 */
class Category
{

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="Product", mappedBy="category")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $products;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    public  function __construct()
    {
        $this->products= new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add product
     *
     * @param \AppBundle\Entity\Product $product
     *
     * @return Category
     */
    public function addProduct(\AppBundle\Entity\Product $product)
    {
        $this->products[] = $product;

        return $this;
    }

    /**
     * Remove product
     *
     * @param \AppBundle\Entity\Product $product
     */
    public function removeProduct(\AppBundle\Entity\Product $product)
    {
        $this->products->removeElement($product);
    }

    /**
     * Get products
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getProducts()
    {
        return $this->products;
    }
}
</code>```

<

```<code>?php
DefaultController:
namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Category;
use AppBundle\Entity\Product;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class DefaultController extends Controller
{

    /**
     * @Route("/product_new")
     */
    public function newAction(Request $request)
    {
        $category = new Category();

        $product = new Product();
        $form = $this->createFormBuilder($product)
            ->add('name', TextType::class)
            ->add('price', NumberType::class)
            ->add('description', TextareaType::class)
            ->add('category', EntityType::class, array(
                'class' => 'AppBundle:Category',
                'choices' => $category->getProducts(),
            ))
            ->add('save', SubmitType::class, array('label'=>'Create New Product'))
            ->getForm();

            $form->handleRequest($request);

            if($form->isSubmitted() && $form->isValid())
            {
               // $category->setName( $request->request->get('category'));
                //$product->setCategory( new Category('Cat1'));

                $product = $form->getData();

                $entityManager = $this->getDoctrine()->getManager();
                //$entityManager->persist($category);
                $entityManager->persist($product);

                $entityManager->flush();
                return $this->render('product/product_status.html.twig',
                    ['msg' =>'Saved new product with id ' . $product->getId()]);
            }else
            {
                return $this->render('product/product_new.html.twig', ['form'=> $form->createView(),]);

            }

    }

    /**
     * @Route("/new_product", name="new_product")
     */
    public function createAction(Request $request)
    {
        $product = new Product();
        $product->setName("Keyboard");
        $product->setPrice(19.9);
        $product->setDescription("Ergonomic and stylish!");

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($product);

        $entityManager->flush();
        return $this->render('product/product_status.html.twig',
            ['msg' =>'Saved new product with id ' . $product->getId()]);
    }

    /**
     * @Route("/show_product/{productId}")
     */
    public function showAction($productId)
    {
        $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);

        if(!$product)
        {
            $this->createNotFoundException("No Product was found with Id". $productId);
        }
            return $this->render('product/product_search.html.twig', ['product' => $product]);

    }

    /**
     * @Route("/product_list", name ="productlist")
     */
    public function listAction()
    {
        $products = $this->getDoctrine()->getRepository('AppBundle:Product')->findAll();

        if(!$products)
        {
            $this->createNotFoundException("No Product was found ");
        }
        return $this->render('product/product_list.html.twig', ['products' => $products]);

    }

    /**
     * @Route("/update_product/{productId}", name ="updateproduct")
     */
    public function updateAction($productId)
    {
        $entityManager = $this->getDoctrine()->getManager();
        $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);

        if($product)
        {
            $product->setName("Project");
            $product->setDescription("Sony Projector with LCD light");

            $entityManager->flush();

            return $this->redirectToRoute('productlist');

        }

    }

    /**
     * @Route("/delete_product/{productId}", name ="deleteproduct")
     */
    public function deleteAction($productId)
    {
        $entityManager = $this->getDoctrine()->getManager();
        $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);

        if($product)
        {
           $entityManager->remove($product);
            $entityManager->flush();

            return $this->redirectToRoute('productlist');

        }

    }
}
</code>```

答:
You can use query_builder option like below. You can adapt it to your application. Full example is here: Full webform style CRUD example with an embedded associated entity in symfony</p>

```<code>....
    private $country;

    public function __construct()
    {
        $this->country = [
            ....
            'class' => 'FootballFrontendBundle:Country',
            'query_builder' => function (EntityRepository $repo)
            {
                return $repo->createQueryBuilder('c')->orderBy('c.name', 'ASC');
            }
        ];
    }

    public function buildForm(FormBuilderInterface $builder, array $options = [])
    {
        $builder
            ....
            ->add('country', 'entity', $this->country);
    }

....
</code>```

Title: How to populate a dropdown in Symfony 3

Body:
I am a newbie in symfony and i have decided to explore symfony 3. I have two models: products and category and I want to populate a dropdown in a new product form with all the categories. How can i do this pls?
Below is what have done so far:

<?php

Product Model:

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Persisters\Entity;
use Doctrine\ORM\Mapping\Column;

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 */
class Product
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $category;

    /**
     * @ORM\Column( type ="string", length=100)
     */
    private $name;

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    private $price;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Product
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param string $price
     *
     * @return Product
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return string
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Product
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set category
     *
     * @param \AppBundle\Entity\Category $category
     *
     * @return Product
     */
    public function setCategory(\AppBundle\Entity\Category $category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return \AppBundle\Entity\Category
     */
    public function getCategory()
    {
        return $this->category;
    }
}

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
 */
class Category
{

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="Product", mappedBy="category")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $products;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    public  function __construct()
    {
        $this->products= new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add product
     *
     * @param \AppBundle\Entity\Product $product
     *
     * @return Category
     */
    public function addProduct(\AppBundle\Entity\Product $product)
    {
        $this->products[] = $product;

        return $this;
    }

    /**
     * Remove product
     *
     * @param \AppBundle\Entity\Product $product
     */
    public function removeProduct(\AppBundle\Entity\Product $product)
    {
        $this->products->removeElement($product);
    }

    /**
     * Get products
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getProducts()
    {
        return $this->products;
    }
}

<

?php
DefaultController:
namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Category;
use AppBundle\Entity\Product;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class DefaultController extends Controller
{

    /**
     * @Route("/product_new")
     */
    public function newAction(Request $request)
    {
        $category = new Category();

        $product = new Product();
        $form = $this->createFormBuilder($product)
            ->add('name', TextType::class)
            ->add('price', NumberType::class)
            ->add('description', TextareaType::class)
            ->add('category', EntityType::class, array(
                'class' => 'AppBundle:Category',
                'choices' => $category->getProducts(),
            ))
            ->add('save', SubmitType::class, array('label'=>'Create New Product'))
            ->getForm();

            $form->handleRequest($request);

            if($form->isSubmitted() && $form->isValid())
            {
               // $category->setName( $request->request->get('category'));
                //$product->setCategory( new Category('Cat1'));

                $product = $form->getData();

                $entityManager = $this->getDoctrine()->getManager();
                //$entityManager->persist($category);
                $entityManager->persist($product);

                $entityManager->flush();
                return $this->render('product/product_status.html.twig',
                    ['msg' =>'Saved new product with id ' . $product->getId()]);
            }else
            {
                return $this->render('product/product_new.html.twig', ['form'=> $form->createView(),]);

            }

    }

    /**
     * @Route("/new_product", name="new_product")
     */
    public function createAction(Request $request)
    {
        $product = new Product();
        $product->setName("Keyboard");
        $product->setPrice(19.9);
        $product->setDescription("Ergonomic and stylish!");

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($product);

        $entityManager->flush();
        return $this->render('product/product_status.html.twig',
            ['msg' =>'Saved new product with id ' . $product->getId()]);
    }

    /**
     * @Route("/show_product/{productId}")
     */
    public function showAction($productId)
    {
        $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);

        if(!$product)
        {
            $this->createNotFoundException("No Product was found with Id". $productId);
        }
            return $this->render('product/product_search.html.twig', ['product' => $product]);

    }

    /**
     * @Route("/product_list", name ="productlist")
     */
    public function listAction()
    {
        $products = $this->getDoctrine()->getRepository('AppBundle:Product')->findAll();

        if(!$products)
        {
            $this->createNotFoundException("No Product was found ");
        }
        return $this->render('product/product_list.html.twig', ['products' => $products]);

    }

    /**
     * @Route("/update_product/{productId}", name ="updateproduct")
     */
    public function updateAction($productId)
    {
        $entityManager = $this->getDoctrine()->getManager();
        $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);

        if($product)
        {
            $product->setName("Project");
            $product->setDescription("Sony Projector with LCD light");

            $entityManager->flush();

            return $this->redirectToRoute('productlist');

        }

    }

    /**
     * @Route("/delete_product/{productId}", name ="deleteproduct")
     */
    public function deleteAction($productId)
    {
        $entityManager = $this->getDoctrine()->getManager();
        $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);

        if($product)
        {
           $entityManager->remove($product);
            $entityManager->flush();

            return $this->redirectToRoute('productlist');

        }

    }
}

Body:
You can use query_builder option like below. You can adapt it to your application. Full example is here: Full webform style CRUD example with an embedded associated entity in symfony

....
    private $country;

    public function __construct()
    {
        $this->country = [
            ....
            'class' => 'FootballFrontendBundle:Country',
            'query_builder' => function (EntityRepository $repo)
            {
                return $repo->createQueryBuilder('c')->orderBy('c.name', 'ASC');
            }
        ];
    }

    public function buildForm(FormBuilderInterface $builder, array $options = [])
    {
        $builder
            ....
            ->add('country', 'entity', $this->country);
    }

....


问:
how to select all records with every 15 minutes interval
My database updates every 1 minute of data but i need to display every 15 minutes data. how to select all records with 15 minutes data. if data starts from 07:00 so i need 07:15,07:30,07:45 like this.</p>

```<code>17:00   107.11  107.50
16:45   106.98  107.39
16:30   106.58  106.97
16:15   106.65  107.04
</code>```

答:
If this is saved in a TIME or DATE field, then you can get the "minute" value using the MINUTE() function.  Then you can check if that value is divisible by 15.

```<code>SELECT * FROM yourTable
WHERE MINUTE(timeData) % 15 = 0
</code>```

Body:
My database updates every 1 minute of data but i need to display every 15 minutes data. how to select all records with 15 minutes data. if data starts from 07:00 so i need 07:15,07:30,07:45 like this.

17:00   107.11  107.50
16:45   106.98  107.39
16:30   106.58  106.97
16:15   106.65  107.04

Body:
If this is saved in a TIME or DATE field, then you can get the "minute" value using the MINUTE() function.  Then you can check if that value is divisible by 15.

SELECT * FROM yourTable
WHERE MINUTE(timeData) % 15 = 0


问:
Merge lines in bash
I would like to write a script that restores a file, but preserving the changes that may be done after the backout file is created.

With more details: at some moment I create a backup of a file (file_orig). Do some changes to the original file as well(file_my_changes). After that, the original file can be changed again (file_additional_changes), but after the restore I want to have the backup file, plus the additional changes (file_orig + file_addtional_changes). In general backing out my changes only.

I am talking about grub.cfg file, so the expected possible changes will be adding or removing parts of a line.

Is it possible this to be done with a bash script?

I have 2 ideas:

Add some comments above the lines I am going to change, and then before the resotore if the line differ from the one from the backed out file, to read the comment, which will tell me what exactly to remove from the line;

If there is a way to display only the part of the line that differs from the file_orig and file_additional_changes, then to replace this line with the line from file_orig + the part that differs. But I am not sure if this is possible to be done at all.

Example"

line1: This is line1

line2: This is another line1

Is it possible to display only "another"?

Of course any other ideas are welcome!

Thank you!

答:
One possibility would be to use POSIX commands patch and
diff.

Create the backup:

```<code>cp operational-file operational-file.001
</code>```

Edit the operational file.

Create a patch from the differences:

```<code>diff -u operational-file.001 operational-file > operational-file.patch001
</code>```

Copy the operational file again.

```<code>cp operational-file operational-file.002
</code>```

Edit the operational file again.

Create a new patch

```<code>diff -u operational-file.002 operational-file > operational-file.patch002
</code>```

If you need to recover but skip the changes from patch.001, then:

```<code>cp operational-file.001 operational-file
patch -i patch.002
</code>```

This would apply just the second set of changes to the original file, as log as there's no overlap.

Consider using a version control system to keep records of the file changes.  Consider using date/time stamps instead of version numbers on the file names.

Title: Merge lines in bash

Body:
One possibility would be to use POSIX commands patch and
diff.

Create the backup:

cp operational-file operational-file.001

Edit the operational file.

Create a patch from the differences:

diff -u operational-file.001 operational-file > operational-file.patch001

Copy the operational file again.

cp operational-file operational-file.002

Edit the operational file again.

Create a new patch

diff -u operational-file.002 operational-file > operational-file.patch002

If you need to recover but skip the changes from patch.001, then:

cp operational-file.001 operational-file
patch -i patch.002

This would apply just the second set of changes to the original file, as log as there's no overlap.

Consider using a version control system to keep records of the file changes.  Consider using date/time stamps instead of version numbers on the file names.


问:
Breaking a grid into 50 square subunits in R using x y coordinates
I have data with X-Y coordinates on a rectangular grid

```<code>dX <- runif(1000,0, 500)
dY <- runif( 500,0, 500)
d <- data.frame(dX, dY)
</code>```

I want to assign 50 'plot numbers' to this data, such that anything between 0-100 dX and 0-100 dY is plot 1. anything between 100-200 dX and 1000-200 dY is plot 2. Etc. I can imagine writing 50 lines of code to do this, but I would really prefer to write 1!

答:
Here is a solution using the base R functions cut and interaction.

```<code>d$gridGroup <- interaction(cut(d$dX, breaks=seq(0, 1000, by=100)),
                           cut(d$dY, breaks=seq(0, 1000, by=100)), sep="X")

head(d)
         dX       dY           gridGroup
1  56.85171 418.8170   (0,100]X(400,500]
2 311.14970 243.7331 (300,400]X(200,300]
3 304.63737  55.1685   (300,400]X(0,100]
4 311.68972 175.6815 (300,400]X(100,200]
5 430.45769 380.5315 (400,500]X(300,400]
6 320.15530 194.8324 (300,400]X(100,200]
</code>```

This produces a factor variable with useful reference labels that correspond to the X grid and the Y grid. As suggested in the comments, cut can be used to produce a factor variable to depict intervals of a continuous variable. Then interaction can be used to produce the interaction of the two interval variables.

data

```<code>set.seed(1234)
dX <- runif(1000,0, 500)
dY <- runif( 500,0, 500)
d <- data.frame(dX, dY)
</code>```

Body:
I have data with X-Y coordinates on a rectangular grid

dX <- runif(1000,0, 500)
dY <- runif( 500,0, 500)
d <- data.frame(dX, dY)

I want to assign 50 'plot numbers' to this data, such that anything between 0-100 dX and 0-100 dY is plot 1. anything between 100-200 dX and 1000-200 dY is plot 2. Etc. I can imagine writing 50 lines of code to do this, but I would really prefer to write 1!

Body:
Here is a solution using the base R functions cut and interaction.

d$gridGroup <- interaction(cut(d$dX, breaks=seq(0, 1000, by=100)),
                           cut(d$dY, breaks=seq(0, 1000, by=100)), sep="X")

head(d)
         dX       dY           gridGroup
1  56.85171 418.8170   (0,100]X(400,500]
2 311.14970 243.7331 (300,400]X(200,300]
3 304.63737  55.1685   (300,400]X(0,100]
4 311.68972 175.6815 (300,400]X(100,200]
5 430.45769 380.5315 (400,500]X(300,400]
6 320.15530 194.8324 (300,400]X(100,200]

This produces a factor variable with useful reference labels that correspond to the X grid and the Y grid. As suggested in the comments, cut can be used to produce a factor variable to depict intervals of a continuous variable. Then interaction can be used to produce the interaction of the two interval variables.

data

set.seed(1234)
dX <- runif(1000,0, 500)
dY <- runif( 500,0, 500)
d <- data.frame(dX, dY)


问:
How to use JMX MBean for HikariCP in Spring boot application?
How to use JMX MBean for HikariCP in Spring boot application? I have a code like this:

```<code>@SpringBootApplication
public class App() { ... }
</code>```

And other class:

```<code>@Configuration
public class DatabaseCfg() {
@Bean
@ManagedOperation
public DataSource ds (@Value("${hikari.proprerties}") String config) {
HikariConfig hikariConfig = new HikariConfig(config);
return new HikariDataSource(hikariConfig);
}
</code>```

In Java Mission Control (or JMX Console) a saw only Datasource managed bean, not JMX MBean for HikariCP (link). Is it possible to add it too?

答:
I believe on your hikariConfig you need to set a few additional settings.  You need to register the MBeans and set a pool name on the configuration.

```<code>HikariConfig hiakriConfig = new HikariConfig(config);
hikariConfig.setRegisterMbeans(true);
kikariConfig.setPoolName("my-pool-1");
</code>```

Yes you obviously could drive these through the properties as well.  I'm not sure if you are including these in your properties file as they are not listed.  Also please note you are spelling properties wrong (@Value("${ds.proprerties}") should probably should be (@Value("${ds.properties}") but I'm not sure how you actually have named variables and property files.  You may want to double check if that is where you want to set all of the properties.

Body:
How to use JMX MBean for HikariCP in Spring boot application? I have a code like this:

@SpringBootApplication
public class App() { ... }

And other class:

@Configuration
public class DatabaseCfg() {
@Bean
@ManagedOperation
public DataSource ds (@Value("${hikari.proprerties}") String config) {
HikariConfig hikariConfig = new HikariConfig(config);
return new HikariDataSource(hikariConfig);
}

In Java Mission Control (or JMX Console) a saw only Datasource managed bean, not JMX MBean for HikariCP (link). Is it possible to add it too?

Body:
I believe on your hikariConfig you need to set a few additional settings.  You need to register the MBeans and set a pool name on the configuration.

HikariConfig hiakriConfig = new HikariConfig(config);
hikariConfig.setRegisterMbeans(true);
kikariConfig.setPoolName("my-pool-1");

Yes you obviously could drive these through the properties as well.  I'm not sure if you are including these in your properties file as they are not listed.  Also please note you are spelling properties wrong (@Value("${ds.proprerties}") should probably should be (@Value("${ds.properties}") but I'm not sure how you actually have named variables and property files.  You may want to double check if that is where you want to set all of the properties.


问:
Export and import DataFrames to Access file (.mdb)
I have 7 tables which I want to read from an Access file (.mdb), then I need to change the values using pandas DataFrame, and then save them again in a new Access file. Do you have any suggestion on how to do that?
I am relatively new in python, and any support is highly appreciated.</p>

答:
This may be some help: https://pypi.python.org/pypi/pandas_access

Everything should be straight forward after you're able to load the tables into pandas data frame. Then do the data manipulations you need to and send back to Access.


问:
How can I programmatically clear the RAM in swift?
In an iPhone, you can clear the RAM by holding down the power button, releasing it and then holding down the home button. I want to achieve this programmatically. </p>

答: There is no public API to do this, and doing it with the button combination is generally a bad idea anyway.</p>


问:
HashSet - Is accessing/finding a object in HashSet O(1)?
Average complexity of accessing a particular object/data in an array is O(n) , here n is array length.
Is it O(1) for finding an element in HashSet for Java?

```<code>HashSet<String> set=new HashSet<String>();
......
System.out.print(set.contains(Some_string);
</code>```

Is contains(String) method performing at O(1)?

答:
Yes, accessing and finding an element in HashSet is O(1).

HashSet stores elements using the hashing technique. Another important property of HashSet is that it contains only unique elements. For example you can check if the element already exists in HashSet.

```<code>HashSet<Integer> hs = new HashSet<String();
if(hs.add(10) == false) {
  //do something
}
</code>```

Body:
Average complexity of accessing a particular object/data in an array is O(n) , here n is array length.
Is it O(1) for finding an element in HashSet for Java?

HashSet<String> set=new HashSet<String>();
......
System.out.print(set.contains(Some_string);

Is contains(String) method performing at O(1)?

Body:
Yes, accessing and finding an element in HashSet is O(1).

HashSet stores elements using the hashing technique. Another important property of HashSet is that it contains only unique elements. For example you can check if the element already exists in HashSet.

HashSet<Integer> hs = new HashSet<String();
if(hs.add(10) == false) {
  //do something
}