问:
Retrieving selected data from MySQL
I'm developing a small web app for uni and one of the requirements is that it has to have a list, with data from a database, that can be sorted by clicking on a certain category and then only the items from that category will get displayed.
I've managed to retrieve the data from the database into a table on the website, however, the drop down menu to select which category you would like to look at, doesn't work. Meaning that it displays all the items from the database no matter what. I do not receive any errors and really have no idea how I could solve this problem.
Hopefully someone will be able to help me with this.
Code for the function which is supposed to only display items from that category:

```<code>//Get ItemEntity objects from the database and return them in an array.
function GetItemByCategory($category) {
    // require 'dbconnect.php';

    //Open connection and Select database.
    $con = mysqli_connect("localhost", "root", "", "login") or die(mysqli_error);

    $query = "SELECT * FROM items WHERE category LIKE '$category'";
    $result = mysqli_query($con, $query) or die(mysqli_error($con));
    $itemArray = array();

    //Get data from database.
    while ($row = mysqli_fetch_array($result)) {

        $name = $row[1];
        $category = $row[2];
        $place = $row[3];
        $date = $row[4];
        $description = $row[5];
        $image = $row[6];

        //Create item objects and store them in an array.
        $item = new ItemEntity(-1, $name, $category, $place, $date, $description, $image);
        array_push($itemArray, $item);
    }
    //Close connection and return result
    mysqli_close($con);
    return $itemArray;
}

}
</code>```

I'm still quite new to this so it might be a simple fix but like I said, I'm lost so that's why I've reached out.
Thanks in advance and let me know if you need any more code from me.

//edit
HTML form which displays the data. If anything else is needed, let me know. Thanks for your help.

```<code>function CreateItemTables($categories)
    {
        $itemModel = new ItemModel();
        $itemArray = $itemModel->GetItemByCategory($categories);
        $result = "";

        // Generate an item table for each item entity in the array
        foreach ($itemArray as $key => $item) {
            $result = $result . "<table class = 'itemTable'>
                                <tr>
                                    <th rowspan='6' width = '150px' ><img runat = 'server' src = '$item->image'/></th>
                                    <th width = '75px' >Name: </th>
                                    <td>$item->name</td>
                                </tr>

                                <tr>
                                    <th>Category: </th>
                                    <td>$item->category</td>
                                </tr>

                                <tr>
                                    <th>Place: </th>
                                    <td>$item->place</td>
                                </tr>

                                <tr>
                                    <th>Date: </th>
                                    <td>$item->date</td>
                                </tr>

                                <tr>
                                    <td colspan='2' >$item->description</td>
                                </tr>

                                </table>";
        }
        return $result;
    }
</code>```

//edit 2 Whole ItemController class

```<code><?php

require ("Model/ItemModel.php");

/**
* Contains non-db related functions for the Item page
*/
class ItemController
{

    function CreateItemDropdownList()
    {
        $itemModel = new ItemModel();
        $result = "<form action = '' method = 'post' width = '200px'>
                    Please select a category: <select name = 'types' >
                    <option value = '%' >ALL</option>".$this->CreateOptionValues($itemModel->GetCategories())."
                    </select>
                    <input type = 'submit' value = 'Search'  /></form>";

                return $result;
    }
    function CreateOptionValues(array $valueArray)
    {
        $result = "";

        foreach ($valueArray as $value)
        {
            $result = $result . "<option value ='$value'>$value</option>";
        }
        return $result;
    }

    function CreateItemTables($categories)
    {
        $itemModel = new ItemModel();
        $itemArray = $itemModel->GetItemByCategory($categories);
        $result = "";

        // Generate an item table for each item entity in the array
        foreach ($itemArray as $key => $item) {
            $result = $result . "<table class = 'itemTable'>
                                <tr>
                                    <th rowspan='6' width = '150px' ><img runat = 'server' src = '$item->image'/></th>
                                    <th width = '75px' >Name: </th>
                                    <td>$item->name</td>
                                </tr>

                                <tr>
                                    <th>Category: </th>
                                    <td>$item->category</td>
                                </tr>

                                <tr>
                                    <th>Place: </th>
                                    <td>$item->place</td>
                                </tr>

                                <tr>
                                    <th>Date: </th>
                                    <td>$item->date</td>
                                </tr>

                                <tr>
                                    <td colspan='2' >$item->description</td>
                                </tr>

                                </table>";
        }
        return $result;
    }
}
?>
</code>```

答:
```<code> //changed like to = more accurate
$query = "SELECT * FROM items WHERE category = '$category'";
    $result = mysqli_query($con, $query) or die(mysqli_error($con));
    $itemArray = array();

    //Get data from database.
//note this
$i=0;

 while ($row = mysqli_fetch_array($result)) {
        //gave then a record number so you get the right data
        $name = $row[$i];
        $category = $row[$i];
        $place = $row[$i];
        $date = $row[$i];
        $description = $row[$i];
        $image = $row[$i];
$item = new ItemEntity($i, $name, $category, $place, $date, $description, $image);
$i++;
</code>```

Title: Retrieving selected data from MySQL

Body:
I'm developing a small web app for uni and one of the requirements is that it has to have a list, with data from a database, that can be sorted by clicking on a certain category and then only the items from that category will get displayed.
I've managed to retrieve the data from the database into a table on the website, however, the drop down menu to select which category you would like to look at, doesn't work. Meaning that it displays all the items from the database no matter what. I do not receive any errors and really have no idea how I could solve this problem.
Hopefully someone will be able to help me with this.
Code for the function which is supposed to only display items from that category:

//Get ItemEntity objects from the database and return them in an array.
function GetItemByCategory($category) {
    // require 'dbconnect.php';

    //Open connection and Select database.
    $con = mysqli_connect("localhost", "root", "", "login") or die(mysqli_error);

    $query = "SELECT * FROM items WHERE category LIKE '$category'";
    $result = mysqli_query($con, $query) or die(mysqli_error($con));
    $itemArray = array();

    //Get data from database.
    while ($row = mysqli_fetch_array($result)) {

        $name = $row[1];
        $category = $row[2];
        $place = $row[3];
        $date = $row[4];
        $description = $row[5];
        $image = $row[6];

        //Create item objects and store them in an array.
        $item = new ItemEntity(-1, $name, $category, $place, $date, $description, $image);
        array_push($itemArray, $item);
    }
    //Close connection and return result
    mysqli_close($con);
    return $itemArray;
}

}

I'm still quite new to this so it might be a simple fix but like I said, I'm lost so that's why I've reached out.
Thanks in advance and let me know if you need any more code from me.

//edit
HTML form which displays the data. If anything else is needed, let me know. Thanks for your help.

function CreateItemTables($categories)
    {
        $itemModel = new ItemModel();
        $itemArray = $itemModel->GetItemByCategory($categories);
        $result = "";

        // Generate an item table for each item entity in the array
        foreach ($itemArray as $key => $item) {
            $result = $result . "

                                    image'/>
                                    Name:
                                    $item->name

                                    Category:
                                    $item->category

                                    Place:
                                    $item->place

                                    Date:
                                    $item->date

                                    $item->description

";
        }
        return $result;
    }

//edit 2 Whole ItemController class

<?php

require ("Model/ItemModel.php");

/**
* Contains non-db related functions for the Item page
*/
class ItemController
{

    function CreateItemDropdownList()
    {
        $itemModel = new ItemModel();
        $result = "<form action = '' method = 'post' width = '200px'>
                    Please select a category: <select name = 'types' >
                    <option value = '%' >ALL</option>".$this->CreateOptionValues($itemModel->GetCategories())."
                    </select>
                    <input type = 'submit' value = 'Search'  /></form>";

                return $result;
    }
    function CreateOptionValues(array $valueArray)
    {
        $result = "";

        foreach ($valueArray as $value)
        {
            $result = $result . "<option value ='$value'>$value</option>";
        }
        return $result;
    }

    function CreateItemTables($categories)
    {
        $itemModel = new ItemModel();
        $itemArray = $itemModel->GetItemByCategory($categories);
        $result = "";

        // Generate an item table for each item entity in the array
        foreach ($itemArray as $key => $item) {
            $result = $result . "

                                    image'/>
                                    Name:
                                    $item->name

                                    Category:
                                    $item->category

                                    Place:
                                    $item->place

                                    Date:
                                    $item->date

                                    $item->description

";
        }
        return $result;
    }
}
?>


来源: stackexchange

问:
Xcode - Dark theme for the whole UI
How can one make Xcode's UI completely dark?

There must be a way to have a dark theme for Xcode (like Visual Studio has it for example). I'm not only talking about a way of styling the editor, but a full-on dark theme. Dark menus, dark console, dark file browser, dark menu bar, etc.

Xcode's bright UI hurts at night and I can't be the only one who's really searching for this ;)   (please don't recommand f.lux to me now, that's not a solution)

答:
You can reference to this article:

https://medium.com/@guilhermerambo/how-to-enable-real-dark-mode-on-os-x-macos-14966f9f7d24

Install a dark mode in system service,it make Xcode most control dark,it's not perfect, but works.

Hope Apple implement it someday.

ContentLicense: CC BY-SA 3.0

Title: Xcode - Dark theme for the whole UI


问:
Circumvent the sed backreference limit \1 through \9
The sed manual clearly states that the available backreferences available for the replacement string in a substitute are numbered \1 through \9. I'm trying to parse a log file that has 10 fields.

I have the regex formed for it but the tenth match (and anything after) isn't accessible.

Does anyone have an elegant way to circumvent this limitation in KSH (or any language that perhaps I can port to shell scripting)?

ContentLicense: CC BY-SA 2.5

Body:
If you have GNU awk, You can do things with much more in control. For this you would be needing match(source,/regex/,array) construct.

Example:

Sample input for test:

 echo "$x"
p1=aaa,p2=bb,p3=cc,p4=dd,p5=ee,p6=ff,p7=gg,p8=hh,p9=ii,p10=jj

sed works fine till \9 :

echo $x |sed -r 's/p1=([^,]+).*p2=([^,]+).*p3=([^,]+).*p4=([^,]+).*p5=([^,]+).*p6=([^,]+).*p7=([^,]+).*p8=([^,]+).*p9=([^,]+)(.*)/\1 \2 \3 \4 \5 \6 \7 \8 \9/'
aaa bb cc dd ee ff gg hh ii

sed broke when \10 is added, it is considered is \1+0.

echo $x |sed -r 's/p1=([^,]+).*p2=([^,]+).*p3=([^,]+).*p4=([^,]+).*p5=([^,]+).*p6=([^,]+).*p7=([^,]+).*p8=([^,]+).*p9=([^,]+).*p10=([^,]+)(.*)/\1 \2 \3 \4 \5 \6 \7 \8 \9 \10/'
aaa bb cc dd ee ff gg hh ii aaa0

awk to rescue when any back reference added more than 9 is added. Here 10th refrence is added:

echo "$x" |awk '{match($0,/p1=([^,]+).*p2=([^,]+).*p3=([^,]+).*p4=([^,]+).*p5=([^,]+).*p6=([^,]+).*p7=([^,]+).*p8=([^,]+).*p9=([^,]+).*p10=([^,]+)(.*)/,a);print a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10]}'
aaa bb cc dd ee ff gg hh ii jj


问:
Multiple DLL calls in VBA
I've created a C++ DLL with many Functions and I call them from excel sheet through VBA. The Problem I'm facing is the following:

I have many spreadsheet cells calling the same function at the same time every N seconds,it is taking a while to update the excel book. If called separately each run is very efficient however when multiple cells calls the function it runs serialized and takes too long.

My question is, how can I get better solution?  I thought if its possible the same function be called simultaneously and run on parallel or something like that, so I can the routine faster.

Thanks

答:
You need to make your C++ functions directly callable multi-threaded UDFs in an XLL: then Excel's calculation engine will exploit multi-threading using multiple cores.

To do this you will need to use the Excel 'C' Api SDK

https://msdn.microsoft.com/en-us/library/office/bb687829.aspx

https://msdn.microsoft.com/en-us/library/office/bb687883.aspx

Title: Multiple DLL calls in VBA


问:
EXTJS Writer Grid - removal of row - client and serverside
At the moment when I remove a row - it reappears on the client side - refreshing the page I see it has indeed been deleted

Adding a store.reload in the method means it appears again and then disappears when the store is reloaded.

Any help appreciated

```<code>// The DataWriter component.
var writer = new Ext.data.JsonWriter({
    encode: false
})

Ext.namespace('codeblender');

codeblender.app = function() {
    /**
     * Render the ground links
     *
     * @param val
     * @param p
     * @param record
     * @return
     */
    function rendererGroundLink(val, p, record) {
        var string = record.data.ground;
        var newContent = string.replace(/ /g, '-');

        return ('<a href="venues/' + newContent.toLowerCase() + '/" target="_new">' + record.data.ground + '</a>');
    }

    // Public space
    return {

        // Public methods
        init: function() {
            // !Create the data store
            var store = new Ext.data.JsonStore({
                fields: [{
                    name: 'id',
                    type: 'int'
                }, {
                    name: 'division_id',
                    type: 'int'
                }, {
                    name: 'competition',
                    type: 'string'
                }, {
                    name: 'date',
                    type: 'date',
                    dateFormat: 'Y-m-d'
                }, {
                    name: 'time',
                    type: 'time'
                }, {
                    name: 'referee',
                    type: 'string'
                }, {
                    name: 'ground',
                    type: 'string'
                }, {
                    name: 'team_a',
                    type: 'string'
                }, {
                    name: 'score_a',
                    type: 'string'
                }, {
                    name: 'scorer_a',
                    type: 'string'
                }, {
                    name: 'team_b',
                    type: 'string'
                }, {
                    name: 'score_b',
                    type: 'string'
                }, {
                    name: 'scorer_b',
                    type: 'string'
                }],

                idProperty: 'id',
                messageProperty: 'message',
                pruneModifiedRecords: true,
                remoteSort: true,
                restful: true,
                root: 'data',
                sortInfo: {
                    field: 'date',
                    direction: "DESC"
                },
                successProperty: 'success',
                totalProperty: 'totalCount',
                url: '/restfixture',
                writer: writer
            });

            store.load({
                params: {
                    start: 0,
                    limit: 50,
                    sort: 'date',
                    dir: 'DESC'
                }
            });

            // !Create the Team data store
            var storeTeam = new Ext.data.JsonStore({
                baseParams: {
                    status: 'Active'
                },
                fields: [{
                    name: 'id',
                    type: 'int'
                }, {
                    name: 'team',
                    type: 'string'
                }],
                restful: true,
                root: 'data',
                sortInfo: {
                    field: 'team',
                    direction: "ASC"
                },
                url: '/restteam'
            });

            // !Create the Ground data store
            var storeGround = new Ext.data.JsonStore({
                fields: [{
                    name: 'id',
                    type: 'int'
                }, {
                    name: 'ground',
                    type: 'string'
                }],
                restful: true,
                root: 'data',
                url: '/restground'
            });

            // !Create the Referee data store
            var storeReferee = new Ext.data.JsonStore({
                fields: [{
                    name: 'id',
                    type: 'int'
                }, {
                    name: 'referee',
                    type: 'string'
                }],
                restful: true,
                root: 'data',
                url: '/restreferee'
            });

            // !Create the column model
            var columns = [{
                    header: 'Division',
                    sortable: true,
                    dataIndex: 'division_id',
                    width: 75,
                    editor: {
                        allowBlank: false,
                        editable: false,
                        lazyRender: true,
                        mode: 'local',
                        store: [
                            [1, 'Division 1'],
                            [2, 'Division 2'],
                            [3, 'Division 3']
                        ],
                        triggerAction: 'all',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Competition',
                    sortable: true,
                    dataIndex: 'competition',
                    editor: {
                        allowBlank: false,
                        editable: false,
                        lazyRender: true,
                        mode: 'local',
                        store: ['Season 8', 'Cup 8', 'Season 7', 'Cup 7', 'Season 6', 'Cup 6', 'Season 5', 'Cup 5', 'Season 4', 'Cup 4', 'Season 3', 'Cup 3', 'Season 2', 'Cup 2', 'Season 1', 'Cup 1'],
                        triggerAction: 'all',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Date',
                    sortable: true,
                    dataIndex: 'date',
                    xtype: 'datecolumn',
                    format: 'Y-m-d',
                    width: 100,
                    editor: {
                        allowBlank: false,
                        editable: true,
                        emptyText: 'Date',
                        format: 'Y-m-d',
                        xtype: 'datefield'
                    }
                }, {
                    header: 'Time',
                    sortable: false,
                    dataIndex: 'time',
                    editor: {
                        allowBlank: false,
                        editable: false,
                        format: 'H:i:s',
                        increment: 5,
                        minValue: '09:00:00',
                        xtype: 'timefield'
                    }
                }, {
                    header: 'Referee',
                    sortable: true,
                    dataIndex: 'referee',
                    editor: {
                        allowBlank: false,
                        displayField: 'referee',
                        editable: false,
                        emptyText: 'Select Referee',
                        forceSelection: true,
                        lazyRender: true,
                        mode: 'remote',
                        store: storeReferee,
                        triggerAction: 'all',
                        valueField: 'id',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Ground',
                    sortable: true,
                    dataIndex: 'ground',
                    renderer: rendererGroundLink,
                    editor: {
                        allowBlank: false,
                        displayField: 'ground',
                        editable: false,
                        emptyText: 'Select Ground',
                        forceSelection: true,
                        lazyRender: true,
                        mode: 'remote',
                        store: storeGround,
                        triggerAction: 'all',
                        valueField: 'id',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Team A',
                    sortable: true,
                    dataIndex: 'team_a',
                    editor: {
                        allowBlank: false,
                        displayField: 'team',
                        editable: false,
                        emptyText: 'Select Team A',
                        forceSelection: true,
                        lazyRender: true,
                        mode: 'remote',
                        name: 'team',
                        store: storeTeam,
                        triggerAction: 'all',
                        valueField: 'id',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Score A',
                    sortable: true,
                    dataIndex: 'score_a',
                    editor: {
                        xtype: 'spinnerfield'
                    }
                }, {
                    header: 'Scorer A',
                    sortable: false,
                    dataIndex: 'scorer_a',
                    editor: {
                        xtype: 'textarea'
                    }
                }, {
                    header: 'Team B',
                    sortable: true,
                    dataIndex: 'team_b',
                    editor: {
                        allowBlank: false,
                        displayField: 'team',
                        editable: false,
                        emptyText: 'Select Team B',
                        forceSelection: true,
                        lazyRender: true,
                        mode: 'remote',
                        name: 'team',
                        store: storeTeam,
                        triggerAction: 'all',
                        valueField: 'id',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Score B',
                    sortable: true,
                    dataIndex: 'score_b',
                    editor: {
                        xtype: 'spinnerfield'
                    }
                }, {
                    header: 'Scorer B',
                    sortable: false,
                    dataIndex: 'scorer_b',
                    editor: {
                        xtype: 'textarea'
                    }
                }

            ];

            // Create the pager
            var pagingBar = new Ext.PagingToolbar({
                displayInfo: true,
                displayMsg: '{0} - {1} of {2}',
                emptyMsg: 'No Data',
                pageSize: 50,
                store: store
            });

            // Create the Grid
            var grid = new xg.GridPanel({
                bbar: pagingBar,
                columns: columns,
                height: 500,
                iconCls: 'icon-grid',
                loadMask: {
                    msg: 'Loading data.',
                    enabled: true
                },
                plugins: [rowEditor],
                renderTo: 'dbGrid',
                sm: new Ext.grid.RowSelectionModel({
                    singleSelect: true
                }),
                store: store,
                stripeRows: true,
                tbar: [{
                    text: 'Add',
                    iconCls: 'icon-add',
                    handler: function() {
                        var record = new store.recordType({
                            division_id: 1,
                            date: (new Date()).clearTime(),
                            time: '10:00:00',
                            referee: '',
                            ground: '',
                            team_a: '',
                            score_a: '',
                            team_b: '',
                            score_b: ''
                        });

                        grid.suspendEvents();
                        rowEditor.stopEditing();
                        grid.store.insert(0, record);
                        grid.getView().refresh();
                        grid.getSelectionModel().selectRow(0);
                        rowEditor.startEditing(0);
                        grid.resumeEvents();
                    }
                }, {
                    iconCls: 'icon-del',
                    text: 'Remove Fixture',
                    handler: function() {

                        rowEditor.stopEditing();
                        grid.suspendEvents();

                        var record = grid.getSelectionModel().getSelected();

                        if (record) {
                            store.remove(record);
                        }

                        store.reload({}, true);
                        grid.resumeEvents();
                    }
                }],
                title: 'Fixtures',
                viewConfig: {
                    forceFit: true
                }
            });
        }
    };

}();
</code>```

答:
Try:

```<code>grid.getView().refresh()
</code>```

Instead of:

```<code>store.reload({}, true);
</code>```

Body:
At the moment when I remove a row - it reappears on the client side - refreshing the page I see it has indeed been deleted

Adding a store.reload in the method means it appears again and then disappears when the store is reloaded.

Any help appreciated

// The DataWriter component.
var writer = new Ext.data.JsonWriter({
    encode: false
})

Ext.namespace('codeblender');

codeblender.app = function() {
    /**
     * Render the ground links
     *
     * @param val
     * @param p
     * @param record
     * @return
     */
    function rendererGroundLink(val, p, record) {
        var string = record.data.ground;
        var newContent = string.replace(/ /g, '-');

        return ('' + record.data.ground + '');
    }

    // Public space
    return {

        // Public methods
        init: function() {
            // !Create the data store
            var store = new Ext.data.JsonStore({
                fields: [{
                    name: 'id',
                    type: 'int'
                }, {
                    name: 'division_id',
                    type: 'int'
                }, {
                    name: 'competition',
                    type: 'string'
                }, {
                    name: 'date',
                    type: 'date',
                    dateFormat: 'Y-m-d'
                }, {
                    name: 'time',
                    type: 'time'
                }, {
                    name: 'referee',
                    type: 'string'
                }, {
                    name: 'ground',
                    type: 'string'
                }, {
                    name: 'team_a',
                    type: 'string'
                }, {
                    name: 'score_a',
                    type: 'string'
                }, {
                    name: 'scorer_a',
                    type: 'string'
                }, {
                    name: 'team_b',
                    type: 'string'
                }, {
                    name: 'score_b',
                    type: 'string'
                }, {
                    name: 'scorer_b',
                    type: 'string'
                }],

                idProperty: 'id',
                messageProperty: 'message',
                pruneModifiedRecords: true,
                remoteSort: true,
                restful: true,
                root: 'data',
                sortInfo: {
                    field: 'date',
                    direction: "DESC"
                },
                successProperty: 'success',
                totalProperty: 'totalCount',
                url: '/restfixture',
                writer: writer
            });

            store.load({
                params: {
                    start: 0,
                    limit: 50,
                    sort: 'date',
                    dir: 'DESC'
                }
            });

            // !Create the Team data store
            var storeTeam = new Ext.data.JsonStore({
                baseParams: {
                    status: 'Active'
                },
                fields: [{
                    name: 'id',
                    type: 'int'
                }, {
                    name: 'team',
                    type: 'string'
                }],
                restful: true,
                root: 'data',
                sortInfo: {
                    field: 'team',
                    direction: "ASC"
                },
                url: '/restteam'
            });

            // !Create the Ground data store
            var storeGround = new Ext.data.JsonStore({
                fields: [{
                    name: 'id',
                    type: 'int'
                }, {
                    name: 'ground',
                    type: 'string'
                }],
                restful: true,
                root: 'data',
                url: '/restground'
            });

            // !Create the Referee data store
            var storeReferee = new Ext.data.JsonStore({
                fields: [{
                    name: 'id',
                    type: 'int'
                }, {
                    name: 'referee',
                    type: 'string'
                }],
                restful: true,
                root: 'data',
                url: '/restreferee'
            });

            // !Create the column model
            var columns = [{
                    header: 'Division',
                    sortable: true,
                    dataIndex: 'division_id',
                    width: 75,
                    editor: {
                        allowBlank: false,
                        editable: false,
                        lazyRender: true,
                        mode: 'local',
                        store: [
                            [1, 'Division 1'],
                            [2, 'Division 2'],
                            [3, 'Division 3']
                        ],
                        triggerAction: 'all',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Competition',
                    sortable: true,
                    dataIndex: 'competition',
                    editor: {
                        allowBlank: false,
                        editable: false,
                        lazyRender: true,
                        mode: 'local',
                        store: ['Season 8', 'Cup 8', 'Season 7', 'Cup 7', 'Season 6', 'Cup 6', 'Season 5', 'Cup 5', 'Season 4', 'Cup 4', 'Season 3', 'Cup 3', 'Season 2', 'Cup 2', 'Season 1', 'Cup 1'],
                        triggerAction: 'all',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Date',
                    sortable: true,
                    dataIndex: 'date',
                    xtype: 'datecolumn',
                    format: 'Y-m-d',
                    width: 100,
                    editor: {
                        allowBlank: false,
                        editable: true,
                        emptyText: 'Date',
                        format: 'Y-m-d',
                        xtype: 'datefield'
                    }
                }, {
                    header: 'Time',
                    sortable: false,
                    dataIndex: 'time',
                    editor: {
                        allowBlank: false,
                        editable: false,
                        format: 'H:i:s',
                        increment: 5,
                        minValue: '09:00:00',
                        xtype: 'timefield'
                    }
                }, {
                    header: 'Referee',
                    sortable: true,
                    dataIndex: 'referee',
                    editor: {
                        allowBlank: false,
                        displayField: 'referee',
                        editable: false,
                        emptyText: 'Select Referee',
                        forceSelection: true,
                        lazyRender: true,
                        mode: 'remote',
                        store: storeReferee,
                        triggerAction: 'all',
                        valueField: 'id',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Ground',
                    sortable: true,
                    dataIndex: 'ground',
                    renderer: rendererGroundLink,
                    editor: {
                        allowBlank: false,
                        displayField: 'ground',
                        editable: false,
                        emptyText: 'Select Ground',
                        forceSelection: true,
                        lazyRender: true,
                        mode: 'remote',
                        store: storeGround,
                        triggerAction: 'all',
                        valueField: 'id',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Team A',
                    sortable: true,
                    dataIndex: 'team_a',
                    editor: {
                        allowBlank: false,
                        displayField: 'team',
                        editable: false,
                        emptyText: 'Select Team A',
                        forceSelection: true,
                        lazyRender: true,
                        mode: 'remote',
                        name: 'team',
                        store: storeTeam,
                        triggerAction: 'all',
                        valueField: 'id',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Score A',
                    sortable: true,
                    dataIndex: 'score_a',
                    editor: {
                        xtype: 'spinnerfield'
                    }
                }, {
                    header: 'Scorer A',
                    sortable: false,
                    dataIndex: 'scorer_a',
                    editor: {
                        xtype: 'textarea'
                    }
                }, {
                    header: 'Team B',
                    sortable: true,
                    dataIndex: 'team_b',
                    editor: {
                        allowBlank: false,
                        displayField: 'team',
                        editable: false,
                        emptyText: 'Select Team B',
                        forceSelection: true,
                        lazyRender: true,
                        mode: 'remote',
                        name: 'team',
                        store: storeTeam,
                        triggerAction: 'all',
                        valueField: 'id',
                        xtype: 'combo'
                    }
                }, {
                    header: 'Score B',
                    sortable: true,
                    dataIndex: 'score_b',
                    editor: {
                        xtype: 'spinnerfield'
                    }
                }, {
                    header: 'Scorer B',
                    sortable: false,
                    dataIndex: 'scorer_b',
                    editor: {
                        xtype: 'textarea'
                    }
                }

            ];

            // Create the pager
            var pagingBar = new Ext.PagingToolbar({
                displayInfo: true,
                displayMsg: '{0} - {1} of {2}',
                emptyMsg: 'No Data',
                pageSize: 50,
                store: store
            });

            // Create the Grid
            var grid = new xg.GridPanel({
                bbar: pagingBar,
                columns: columns,
                height: 500,
                iconCls: 'icon-grid',
                loadMask: {
                    msg: 'Loading data.',
                    enabled: true
                },
                plugins: [rowEditor],
                renderTo: 'dbGrid',
                sm: new Ext.grid.RowSelectionModel({
                    singleSelect: true
                }),
                store: store,
                stripeRows: true,
                tbar: [{
                    text: 'Add',
                    iconCls: 'icon-add',
                    handler: function() {
                        var record = new store.recordType({
                            division_id: 1,
                            date: (new Date()).clearTime(),
                            time: '10:00:00',
                            referee: '',
                            ground: '',
                            team_a: '',
                            score_a: '',
                            team_b: '',
                            score_b: ''
                        });

                        grid.suspendEvents();
                        rowEditor.stopEditing();
                        grid.store.insert(0, record);
                        grid.getView().refresh();
                        grid.getSelectionModel().selectRow(0);
                        rowEditor.startEditing(0);
                        grid.resumeEvents();
                    }
                }, {
                    iconCls: 'icon-del',
                    text: 'Remove Fixture',
                    handler: function() {

                        rowEditor.stopEditing();
                        grid.suspendEvents();

                        var record = grid.getSelectionModel().getSelected();

                        if (record) {
                            store.remove(record);
                        }

                        store.reload({}, true);
                        grid.resumeEvents();
                    }
                }],
                title: 'Fixtures',
                viewConfig: {
                    forceFit: true
                }
            });
        }
    };

}();

Body:
Try:

grid.getView().refresh()

Instead of:

store.reload({}, true);


问:
Why does Spark report "error: not found: type Properties" when loading a data set?
I am running Spark 2.1.0 on Windows 10, I am following the Spark programming guide to load data using JDBC from MySQL. When I try to load data using the second method in the link, I get the following error.</p>

```<code>scala> val connectionProperties = new Properties()
<console>:44: error: not found: type Properties
       val connectionProperties = new Properties()
                                      ^
</code>```

答:
Use import java.util.Properties.

See https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html.

Body:
I am running Spark 2.1.0 on Windows 10, I am following the Spark programming guide to load data using JDBC from MySQL. When I try to load data using the second method in the link, I get the following error.

scala> val connectionProperties = new Properties()
<console>:44: error: not found: type Properties
       val connectionProperties = new Properties()
                                      ^


问:
C# Search in html, get links, follow them and grab some info from each page
I do NOT ask for the complete solution. It would be nice to hear any advice.

I'm sorry if that kind of question has already been asked.
Well, I have an html file containing a lot of lines (saved on my PC).
Example:

```<code></li><li class="vertical" style="width: 20%;">
<div class="item-box vertical flex-auto">
<div class="image-box vertical center flex-auto"><a target="_blank" href="https://www.aliexpress.com/item/-/32794448855.html?scm=1007.14110.78103.0&pvid=98337ce3-4886-4639-99f3-5dcaf226a0af" class="fade-in"><img src="./Электроника – Распродажа «Нам 7 лет» – AliExpress.com_files/HTB1fDZgPFXXXXXiapXXq6xXFXXXQ.jpg_350x350.jpg" alt="KingDian Новый Универсальный 2.5 "до 3.5" SSD HDD Окружающей Среды Пластмасс Адаптер Кронштейн Держатель Жесткого Диска для Настольных ПК"> </a></div>
</code>```

This code contains links like that:

```<code>https://www.aliexpress.com/item/-/32794448855.html?scm=1007.14110.78103.0&pvid=98337ce3-4886-4639-99f3-5dcaf226a0af
</code>```

I need to grab all the links of the kind. Export them to any type of a document. Follow them. And on each page I need to find the line containing the price (Id "j-sku-discount-price" on every page).

```<code><span id="j-sku-discount-price" class="p-price" itemprop="price" style="color: rgb(247, 43, 76);">4 467,04</span>
</code>```

This is the price found in html code:

```<code>4 467,04
</code>```

And export price so it would be close to its link.

E.g.:

```<code>https://www.aliexpress.com/item/-/32794448855.html?scm=1007.14110.78103.0&pvid=98337ce3-4886-4639-99f3-5dcaf226a0af 4 467,04
</code>```

It would be perfect if it could be stored in Excel.

Thank you for your ideas.

答:
You should use HtmlAgilityPack, and then use this on your HTML document.
But first download the string from site. Here you go, I helped you with your example:</p>

```<code>string urlAddress = "https://www.aliexpress.com/item/-/32794448855.html?scm=1007.14110.78103.0&pvid=98337ce3-4886-4639-99f3-5dcaf226a0af";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string data = "";
if (response.StatusCode == HttpStatusCode.OK)
{
     Stream receiveStream = response.GetResponseStream();
     StreamReader readStream = null;

     if (response.CharacterSet == null)
     {
         readStream = new StreamReader(receiveStream);
     }
     else
     {
         readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
     }

     data = readStream.ReadToEnd();

     response.Close();
     readStream.Close();
}

HtmlDocument document2 = new HtmlAgilityPack.HtmlDocument();
document2.LoadHtml(data);

var value = document2.GetElementbyId("j-sku-discount-price").InnerHtml; //value is "3.94"
</code>```

Body:
I do NOT ask for the complete solution. It would be nice to hear any advice.

I'm sorry if that kind of question has already been asked.
Well, I have an html file containing a lot of lines (saved on my PC).
Example:

This code contains links like that:

https://www.aliexpress.com/item/-/32794448855.html?scm=1007.14110.78103.0&pvid=98337ce3-4886-4639-99f3-5dcaf226a0af

I need to grab all the links of the kind. Export them to any type of a document. Follow them. And on each page I need to find the line containing the price (Id "j-sku-discount-price" on every page).

4 467,04

This is the price found in html code:

4 467,04

And export price so it would be close to its link.

E.g.:

https://www.aliexpress.com/item/-/32794448855.html?scm=1007.14110.78103.0&pvid=98337ce3-4886-4639-99f3-5dcaf226a0af 4 467,04

It would be perfect if it could be stored in Excel.

Thank you for your ideas.

Body:
You should use HtmlAgilityPack, and then use this on your HTML document.
But first download the string from site. Here you go, I helped you with your example:

string urlAddress = "https://www.aliexpress.com/item/-/32794448855.html?scm=1007.14110.78103.0&amp;pvid=98337ce3-4886-4639-99f3-5dcaf226a0af";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string data = "";
if (response.StatusCode == HttpStatusCode.OK)
{
     Stream receiveStream = response.GetResponseStream();
     StreamReader readStream = null;

     if (response.CharacterSet == null)
     {
         readStream = new StreamReader(receiveStream);
     }
     else
     {
         readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
     }

     data = readStream.ReadToEnd();

     response.Close();
     readStream.Close();
}

HtmlDocument document2 = new HtmlAgilityPack.HtmlDocument();
document2.LoadHtml(data);

var value = document2.GetElementbyId("j-sku-discount-price").InnerHtml; //value is "3.94"


问:
Unable to build Maven project due to Javadoc error?
Has anyone come across a similar Maven error as below?

I am unable to build my project due to the error below. All was working previously fine before I started working on the code.

I did not even work on the below defined interfaces and it seems to be related to Javadoc?

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.9.1:jar (attach-javadocs) on project jonney-project: MavenReportException: Error while creating archive:

[ERROR] Exit code: 1 - /Users/me/Work/myProject/library/src/main/java/com/me/someInterface.java:45: warning: no @return
[ERROR] public abstract boolean searchForDevce();
[ERROR] ^
[ERROR] /Users/me/Work/myProject/src/main/java/com/me/someInterfaceAgain.java:52: warning: no @return
[ERROR] public abstract boolean selectDevice(int pos);
[ERROR] ^
</code>```

答:
Just update your pom.xml with the properties tag, given below.</p>

```<code><properties>
    <additionalparam>-Xdoclint:none</additionalparam>
</properties>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Has anyone come across a similar Maven error as below?

I am unable to build my project due to the error below. All was working previously fine before I started working on the code.

I did not even work on the below defined interfaces and it seems to be related to Javadoc?

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.9.1:jar (attach-javadocs) on project jonney-project: MavenReportException: Error while creating archive:

[ERROR] Exit code: 1 - /Users/me/Work/myProject/library/src/main/java/com/me/someInterface.java:45: warning: no @return
[ERROR] public abstract boolean searchForDevce();
[ERROR] ^
[ERROR] /Users/me/Work/myProject/src/main/java/com/me/someInterfaceAgain.java:52: warning: no @return
[ERROR] public abstract boolean selectDevice(int pos);
[ERROR] ^

Body:
Just update your pom.xml with the properties tag, given below.

<properties>
    <additionalparam>-Xdoclint:none</additionalparam>
</properties>


问:
Unable to start as CATALINA_HOME contains a colon (:) character
I'm trying to run a startup script but I get an error that CATALINA_HOME contains a colon, which I see that it does, however that is the path to tomcat.

In other questions I saw examples of setting CATALINA_HOME that included colons, so I don't see what's different here.

I'm on a Windows machine, using MINGW64 and I have JAVA_HOME set.

```<code>$ ./startup.sh
Using CATALINA_HOME:   C:\projects\apache-tomcat-8.5.11
Unable to start as CATALINA_HOME contains a colon (:) character
</code>```

Anyone come across this before ?

答:
Instead of directly running the bat file, try to open a command window in that directory (right click on the folder while pressing ctrl key and "Open commad window here", in case you don't know) an type this:

catalina.bat run

See if that works.

Body:
I'm trying to run a startup script but I get an error that CATALINA_HOME contains a colon, which I see that it does, however that is the path to tomcat.

In other questions I saw examples of setting CATALINA_HOME that included colons, so I don't see what's different here.

I'm on a Windows machine, using MINGW64 and I have JAVA_HOME set.

$ ./startup.sh
Using CATALINA_HOME:   C:\projects\apache-tomcat-8.5.11
Unable to start as CATALINA_HOME contains a colon (:) character

Anyone come across this before ?


问:
Excel - Filling a blank value in one column with a value from another
I am trying to find a way to fill in the blank in come column with the value from another. I have one column, Mode of Communication, and then there are columns for "Email", "Phone", and "Chat". I want to fill in the blanks from Mode of Communication with the value, if present, from the three other columns. Is there a way to do this?

Example:

答:
It is a little unclear if there will only be content in one of the columns, or multiple columns, and if you want only one value returned, or all of them.

An easy way to get all of them is to concatenate the strings

```<code>=J23&" "&K23&" "&L23
</code>```

If there will only be an entry in one of the three columns, you can leave out the &" " parts (which just insert a space between each entry) and you will get the single value.
If you have a preferred order, then using IF will allow you to check first for Phone, then email etc.

Body:
It is a little unclear if there will only be content in one of the columns, or multiple columns, and if you want only one value returned, or all of them.

An easy way to get all of them is to concatenate the strings

=J23&" "&K23&" "&L23

If there will only be an entry in one of the three columns, you can leave out the &" " parts (which just insert a space between each entry) and you will get the single value.
If you have a preferred order, then using IF will allow you to check first for Phone, then email etc.


问:
How to retain same page when browser is refreshed in Angular 1.5?
In my project the router is set up like this :

```<code>   myApp.component("rsapproot", {
        transclude: true,
        template: "<ng-transclude></ng-transclude>",
        $routeConfig: [
            { path: "/login", component: "rsapplogin", name: "Login" },
            { path: "/tenant", component: "rsapptenantid", name: "Tenant" },
            { path: "/my-dashboard", component: "rsappmyrdash", name: "MyDash" },
            { path: "/my-reports", component: "rsappmyreports", name: "AppReports"},
            { path: "/equipment-details/:type/:id", component: "rsequipmentdetails", name: "EquipmentDetails" },
            { path: "/my/resources", component: "rsappresourceslist", name: "AppResourceList" },
</code>```

Now expected behaviour after F5 or when pasting URL is, respectively, having current path reloaded or navigating to the said path, instead the initial application path is loaded.

I know that in order to retain the page after reload app, a url representing the path should be given.

But that thing is already there and the paths respectively are all unique.

Then what am I missing ?

答:
This needs to be handled on the server side. Here's an example that illustrates the current problem:

You load the app at its initial path / and then navigate to /login. When you refresh the page, your web browser then sends a GET request to http://yourdomain.com/login which (I'm assuming) does not not respond by sending your Angular app (index.html) to the client.

You need to configure your server to respond to GET requests for all of your specified Angular paths with your index.html. This is often done with a catch-all route /* instead of specifying each route individually.

Body:
In my project the router is set up like this :

   myApp.component("rsapproot", {
        transclude: true,
        template: "<ng-transclude></ng-transclude>",
        $routeConfig: [
            { path: "/login", component: "rsapplogin", name: "Login" },
            { path: "/tenant", component: "rsapptenantid", name: "Tenant" },
            { path: "/my-dashboard", component: "rsappmyrdash", name: "MyDash" },
            { path: "/my-reports", component: "rsappmyreports", name: "AppReports"},
            { path: "/equipment-details/:type/:id", component: "rsequipmentdetails", name: "EquipmentDetails" },
            { path: "/my/resources", component: "rsappresourceslist", name: "AppResourceList" },

Now expected behaviour after F5 or when pasting URL is, respectively, having current path reloaded or navigating to the said path, instead the initial application path is loaded.

I know that in order to retain the page after reload app, a url representing the path should be given.

But that thing is already there and the paths respectively are all unique.

Then what am I missing ?


问:
jQuery/Ajax Rest api request
I'm trying to make an rest api request to realla https://realla.co/api/#/ from localhost, I have an api key and can make the request via PHP but having issues using ajax:

```<code>var URL = "https://realla.co/api/v1/listings/search";
var usr = 'api';
var psw = 'hidden';
$.ajax({
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  url: URL,
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "Basic " + btoa(usr + ":" + psw))
  },
  success: function(result) {
    console.log('success');
  },
  error: function(req, status, err) {
    console.log('Something went wrong', status, err);
  }
});
</code>```

Returns the error

```<code>XMLHttpRequest cannot load https://realla.co/api/v1/listings/search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://dw.dev' is therefore not allowed access. The response had HTTP status code 403.
</code>```

I tried to fix that problem with https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en but still get the same message.

I've added the following function (running Wordpress):

```<code>/*
 * Modify HTTP header
 */
function new_headers($headers) {

    if (!is_admin()) {
        $headers['Access-Control-Allow-Origin'] = '*';
        $headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS';
        $headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, X-Auth-Token';

    }

    return $headers;
}
add_filter('wp_headers', 'new_headers');
</code>```

I've tried other APIs (Facebook) and that works but I wonder if I'm missing something with this.

The documentation for Realla is pretty thin, but I wonder if I'm doing something wrong.

Thanks

答:
let's try this

it will work

Add header in requested resource file

```<code> <?php

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
 ?>
</code>```

Title: jQuery/Ajax Rest api request

Body:
I'm trying to make an rest api request to realla https://realla.co/api/#/ from localhost, I have an api key and can make the request via PHP but having issues using ajax:

var URL = "https://realla.co/api/v1/listings/search";
var usr = 'api';
var psw = 'hidden';
$.ajax({
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  url: URL,
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "Basic " + btoa(usr + ":" + psw))
  },
  success: function(result) {
    console.log('success');
  },
  error: function(req, status, err) {
    console.log('Something went wrong', status, err);
  }
});

Returns the error

XMLHttpRequest cannot load https://realla.co/api/v1/listings/search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://dw.dev' is therefore not allowed access. The response had HTTP status code 403.

I tried to fix that problem with https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en but still get the same message.

I've added the following function (running Wordpress):

/*
 * Modify HTTP header
 */
function new_headers($headers) {

    if (!is_admin()) {
        $headers['Access-Control-Allow-Origin'] = '*';
        $headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS';
        $headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, X-Auth-Token';

    }

    return $headers;
}
add_filter('wp_headers', 'new_headers');

I've tried other APIs (Facebook) and that works but I wonder if I'm missing something with this.

The documentation for Realla is pretty thin, but I wonder if I'm doing something wrong.

Thanks

Body:
let's try this

it will work

Add header in requested resource file

 <?php

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
 ?>


问:
Serialized PHP Reflection
Please consider the following example code:

```<code><?php

class a {
    function b() {}
}

$r=new ReflectionMethod(new a, "b");
var_dump($r->getParameters());
$s=serialize($r);
$r=unserialize($s);
var_dump($r->getParameters());

?>
</code>```

That produces the following output:

```<code>array(0) { }
Fatal error: ReflectionFunctionAbstract::getParameters() [<a href='reflectionfunctionabstract.getparameters'>reflectionfunctionabstract.getparameters</a>]: Internal error: Failed to retrieve the reflection object in [...]test.php on line 13
</code>```

The question stands, is there a way to correctly serialize/unserialize Reflection objects in PHP?

Thank you.

答: Use the JMS Serializer to serialize private and protected properties and also virtual properties using methods.</p>

Title: Serialized PHP Reflection

Body:
Please consider the following example code:

<?php

class a {
    function b() {}
}

$r=new ReflectionMethod(new a, "b");
var_dump($r->getParameters());
$s=serialize($r);
$r=unserialize($s);
var_dump($r->getParameters());

?>

That produces the following output:

array(0) { }
Fatal error: ReflectionFunctionAbstract::getParameters() [reflectionfunctionabstract.getparameters]: Internal error: Failed to retrieve the reflection object in [...]test.php on line 13

The question stands, is there a way to correctly serialize/unserialize Reflection objects in PHP?

Thank you.


问:
Row with closest column value
I have the following table:

```<code>CREATE TABLE items (
  id serial
  timestamp bigint
  CONSTRAINT id_pkey PRIMARY KEY (id),
);
</code>```

This table is used in an append-only fashion, so the timestamp values increase with the id. I need to find the row who's timestamp is closest to a specific $value.

Query 1: this requires two full table scans.

```<code>SELECT id FROM
  (
      (
          SELECT id, timestamp
          FROM records
          WHERE timestamp < $value
          ORDER BY timestamp DESC
          LIMIT 1
      )
      UNION ALL
      (
          SELECT id, timestamp
          FROM items
          WHERE timestamp >= $value
          ORDER BY timestamp ASC
          LIMIT 1
      )
) AS tmp
ORDER BY abs($value - timestamp)
LIMIT 1
</code>```

Query 2: This one seems like it should be faster, but for some reason it's not

```<code>SELECT id
FROM items
WHERE scan.gpstimestamp >= $value
ORDER BY id ASC
LIMIT 1
</code>```

Query 3: I'm experimenting with a custom aggregate which requires a full table scan, but doesn't need to sort anything or load any indexes.

```<code>create function closest_id_sfunc(
  agg_state bigint[2],
  id bigint,
  timestamp bigint,
  target_timestamp bigint
)
returns bigint[2]
immutable
language plpgsql
as $$
declare
  difference bigint;
begin
  difference := abs(timestamp - target_timestamp);
  if agg_state is null or difference < agg_state[0] then
    agg_state[0] = difference;
    agg_state[1] = id;
  end if;
  return agg_state;
end;
$$;

create function closest_id_finalfunc(agg_state bigint[2])
returns bigint
immutable
strict
language plpgsql
as $$
begin
  return agg_state[1];
end;
$$;

create aggregate closest_id (bigint, bigint, bigint)
(
    stype     = bigint[2],
    sfunc     = closest_id_sfunc,
    finalfunc = closest_id_finalfunc
);

SELECT closest_id(id, timestamp, $value) as id FROM items
</code>```

Why would query 2 be slower than query 1?

答:
Your second query won't work, because there might by a row before the provided timestamp, which is closer to the provided value. And accuracy is not the only concern here: there might not be a row, which is larger than the provided timestamp at all (and in the same time, a lower value exists).

Your first query looks efficient (when you use limit 1 in the subqueries too). But yes, it requires two table scans, when you don't have an index, but that you cannot work around. You'll need indexes for huge performance gains. There is a few trick however, which can be used.

My initial idea was that, you can avoid cost of the outer query's sort, by using conditionals instead:

(Note: I'll use ts as column name, as timestamp is a keyword & shouldn't be used as a column name, unless it is escaped.)

```<code>with l as (
  select   id, ts
  from     items
  where    ts < $value
  order by ts desc
  limit    1
),
g as (
  select   id, ts
  from     items
  where    ts >= $value
  order by ts asc
  limit    1
)
select    case
            when abs($value - l.ts) < abs($value - g.ts)
            then l.id
            else coalesce(g.id, l.id)
          end id
from      l
full join g on true
</code>```

However, this only caused a tiny performance gain in my tests (it seems PostgreSQL is pretty smart about sorting two rows only).

You can speed up your queries by using a direct "distance" calculation on some of PostgreSQL's geometric types. Note: these types usually use double precision for values and as such they can contain rounding errors. This will most likely not a problem, if your values are truly unix timestamps (in bigint).

Here is the query to use the always available point type's distance operator <-> on point(ts, 0) (so the second coordinate will always be zero):

```<code>select   id
from     items
order by point(ts, 0) <-> point($value, 0)
limit    1
</code>```

In my tests, this costs ~70% of your original query (or the CTE variant).

You can also use the cube module's cube type & its (euclidean) distance operator <-> (9.6+ feature) on cube(ts) (so the cube will always be a one-dimensional point):

```<code>select   id
from     items
order by cube(ts) <-> cube($value)
limit    1
</code>```

This is comparable to the point variant in speed. It will have some differences, when you use an index for it though.

(Note: you can initialize the module with create extension cube;.)

Indexes

So, the interesting part(s):

Your original query (or the CTE variant) can use the following (covering) index:

```<code>create index idx_items_ts_id on items (ts, id)
</code>```

With this, your original query (and the CTE variant) uses index-only scans, which costs ~1.5% of the same query (without an index).

The point variant can use the following GiST index:

(Note: the btree_gist module is required for id to be part of the index. You can initialize the module with create extension btree_gist;.)

```<code>create index idx_items_point_gist on items using gist (point(ts, 0), id)
</code>```

With this, the point variant costs ~1% of the original query (without an index).

The cube variant can use the following GiST index:

(Note: this also requires the btree_gist module.)

```<code>create index idx_items_cube_gist on items using gist (cube(ts), id)
</code>```

Again, this is still comparable to the point variant.

Conclusion (see edit later)

You can achieve the best performance with using point or cube (latter requires 9.6+). Also, indexes can help you a lot.

Further notes:

The point variant was actually faster sometimes (than the cube variant)

PostgreSQL took a really long time to build the cube index & I don't exactly know why

In theory, the cube index should be smaller, because it does not contain unnecessary zeros. But, because they are more general (N-dimensional), I might not be right about this. I suggest to try out both & measure (both index sizes & performance).

http://rextester.com/KNY52367 (the queries are here for cube too, but won't run, because rextester uses 9.5 right now).

Also, I tested a custom aggregate solution too (basically your version, but I used language sql functions to speed up a little bit, but still), it was ~10 times slower than your original query. IMHO, it is not worth at all. http://rextester.com/PLG94853

Edit: Just noticed, that the btree_gist module adds support for the distance operator <-> for the basic types (such as bigint).

So this query will outperform even the point and the cube variant too (with a little):

```<code>select   id
from     items
order by ts <-> $value
limit    1
</code>```

And this index will work best with the query above:

```<code>create index idx_items_ts_gist on items using gist (ts, id)
</code>```

http://rextester.com/XUF56126

Title: Row with closest column value

Body:
I have the following table:

CREATE TABLE items (
  id serial
  timestamp bigint
  CONSTRAINT id_pkey PRIMARY KEY (id),
);

This table is used in an append-only fashion, so the timestamp values increase with the id. I need to find the row who's timestamp is closest to a specific $value.

Query 1: this requires two full table scans.

SELECT id FROM
  (
      (
          SELECT id, timestamp
          FROM records
          WHERE timestamp < $value
          ORDER BY timestamp DESC
          LIMIT 1
      )
      UNION ALL
      (
          SELECT id, timestamp
          FROM items
          WHERE timestamp >= $value
          ORDER BY timestamp ASC
          LIMIT 1
      )
) AS tmp
ORDER BY abs($value - timestamp)
LIMIT 1

Query 2: This one seems like it should be faster, but for some reason it's not

SELECT id
FROM items
WHERE scan.gpstimestamp >= $value
ORDER BY id ASC
LIMIT 1

Query 3: I'm experimenting with a custom aggregate which requires a full table scan, but doesn't need to sort anything or load any indexes.

create function closest_id_sfunc(
  agg_state bigint[2],
  id bigint,
  timestamp bigint,
  target_timestamp bigint
)
returns bigint[2]
immutable
language plpgsql
as $$
declare
  difference bigint;
begin
  difference := abs(timestamp - target_timestamp);
  if agg_state is null or difference < agg_state[0] then
    agg_state[0] = difference;
    agg_state[1] = id;
  end if;
  return agg_state;
end;
$$;

create function closest_id_finalfunc(agg_state bigint[2])
returns bigint
immutable
strict
language plpgsql
as $$
begin
  return agg_state[1];
end;
$$;

create aggregate closest_id (bigint, bigint, bigint)
(
    stype     = bigint[2],
    sfunc     = closest_id_sfunc,
    finalfunc = closest_id_finalfunc
);

SELECT closest_id(id, timestamp, $value) as id FROM items

Why would query 2 be slower than query 1?

Body:
Your second query won't work, because there might by a row before the provided timestamp, which is closer to the provided value. And accuracy is not the only concern here: there might not be a row, which is larger than the provided timestamp at all (and in the same time, a lower value exists).

Your first query looks efficient (when you use limit 1 in the subqueries too). But yes, it requires two table scans, when you don't have an index, but that you cannot work around. You'll need indexes for huge performance gains. There is a few trick however, which can be used.

My initial idea was that, you can avoid cost of the outer query's sort, by using conditionals instead:

(Note: I'll use ts as column name, as timestamp is a keyword & shouldn't be used as a column name, unless it is escaped.)

with l as (
  select   id, ts
  from     items
  where    ts < $value
  order by ts desc
  limit    1
),
g as (
  select   id, ts
  from     items
  where    ts >= $value
  order by ts asc
  limit    1
)
select    case
            when abs($value - l.ts) < abs($value - g.ts)
            then l.id
            else coalesce(g.id, l.id)
          end id
from      l
full join g on true

However, this only caused a tiny performance gain in my tests (it seems PostgreSQL is pretty smart about sorting two rows only).

You can speed up your queries by using a direct "distance" calculation on some of PostgreSQL's geometric types. Note: these types usually use double precision for values and as such they can contain rounding errors. This will most likely not a problem, if your values are truly unix timestamps (in bigint).

Here is the query to use the always available point type's distance operator <-> on point(ts, 0) (so the second coordinate will always be zero):

select   id
from     items
order by point(ts, 0) <-> point($value, 0)
limit    1

In my tests, this costs ~70% of your original query (or the CTE variant).

You can also use the cube module's cube type & its (euclidean) distance operator <-> (9.6+ feature) on cube(ts) (so the cube will always be a one-dimensional point):

select   id
from     items
order by cube(ts) <-> cube($value)
limit    1

This is comparable to the point variant in speed. It will have some differences, when you use an index for it though.

(Note: you can initialize the module with create extension cube;.)

Indexes

So, the interesting part(s):

Your original query (or the CTE variant) can use the following (covering) index:

create index idx_items_ts_id on items (ts, id)

With this, your original query (and the CTE variant) uses index-only scans, which costs ~1.5% of the same query (without an index).

The point variant can use the following GiST index:

(Note: the btree_gist module is required for id to be part of the index. You can initialize the module with create extension btree_gist;.)

create index idx_items_point_gist on items using gist (point(ts, 0), id)

With this, the point variant costs ~1% of the original query (without an index).

The cube variant can use the following GiST index:

(Note: this also requires the btree_gist module.)

create index idx_items_cube_gist on items using gist (cube(ts), id)

Again, this is still comparable to the point variant.

Conclusion (see edit later)

You can achieve the best performance with using point or cube (latter requires 9.6+). Also, indexes can help you a lot.

Further notes:

The point variant was actually faster sometimes (than the cube variant)

PostgreSQL took a really long time to build the cube index & I don't exactly know why

In theory, the cube index should be smaller, because it does not contain unnecessary zeros. But, because they are more general (N-dimensional), I might not be right about this. I suggest to try out both & measure (both index sizes & performance).

http://rextester.com/KNY52367 (the queries are here for cube too, but won't run, because rextester uses 9.5 right now).

Also, I tested a custom aggregate solution too (basically your version, but I used language sql functions to speed up a little bit, but still), it was ~10 times slower than your original query. IMHO, it is not worth at all. http://rextester.com/PLG94853

Edit: Just noticed, that the btree_gist module adds support for the distance operator <-> for the basic types (such as bigint).

So this query will outperform even the point and the cube variant too (with a little):

select   id
from     items
order by ts <-> $value
limit    1

And this index will work best with the query above:

create index idx_items_ts_gist on items using gist (ts, id)

http://rextester.com/XUF56126


问:
Django - Saving formset data with different values
I have such models:

```<code>class House(models.Model):
  name = models.CharField(max_length=50, blank=True, null=True)

  def __unicode__(self):
    return '%s' % self.name

class Rooms(models.Model):
  house = models.ForeignKey(House, null=True)
  room = models.CharField(max_length=50, blank=True, null=True)
  people = models.IntegerField(blank=True, null=True)

  def __unicode__(self):
    return '%s' % self.room

class People(models.Model):
  room = models.ForeignKey(Rooms, null=True)
  name = models.CharField(max_length=30)
  surname = models.CharField(max_length=50)

  def __unicode__(self):
    return '%s' % self.surname
</code>```

So if in the house there are two rooms with two people in each room i need to save two People instances with one room key and the second with other room key instead of this my code saves four People instances in each Rooms.

My code looks like this:

```<code>for people in people_formset:
  name = adult_tourists.cleaned_data['name']
  surname = adult_tourists.cleaned_data['surname']
  for room in house.rooms_set.all():
    for people in range(room.people):
      p = People.objects.create(room=room, name=name, surname=surname)
      p.save()
</code>```

Thanks for help

答:
You can create a list where each room appears once for each person it can contain. You can then zip the formset forms and the list together, and create the person for each form.

```<code># creates a list of lists e.g. [[room1, room1], [room2], [room3]]
room_lists = [[room] * room.people for room in house.rooms_set.all()]

# flatten the list e.g. [room1, room1, room2, room3]
rooms = [room for room_list in room_lists for room in room_list]

# zip the lists together
for form, room in zip(people_formset, rooms):
    name = form.cleaned_data['name']
    surname = form.cleaned_data['surname']
    p = People.objects.create(room=room, name=name, surname=surname)
</code>```

The code may require further changes, for example to handle the case where there are more people than places in rooms.

Body:
I have such models:

class House(models.Model):
  name = models.CharField(max_length=50, blank=True, null=True)

  def __unicode__(self):
    return '%s' % self.name

class Rooms(models.Model):
  house = models.ForeignKey(House, null=True)
  room = models.CharField(max_length=50, blank=True, null=True)
  people = models.IntegerField(blank=True, null=True)

  def __unicode__(self):
    return '%s' % self.room

class People(models.Model):
  room = models.ForeignKey(Rooms, null=True)
  name = models.CharField(max_length=30)
  surname = models.CharField(max_length=50)

  def __unicode__(self):
    return '%s' % self.surname

So if in the house there are two rooms with two people in each room i need to save two People instances with one room key and the second with other room key instead of this my code saves four People instances in each Rooms.

My code looks like this:

for people in people_formset:
  name = adult_tourists.cleaned_data['name']
  surname = adult_tourists.cleaned_data['surname']
  for room in house.rooms_set.all():
    for people in range(room.people):
      p = People.objects.create(room=room, name=name, surname=surname)
      p.save()

Thanks for help

Body:
You can create a list where each room appears once for each person it can contain. You can then zip the formset forms and the list together, and create the person for each form.

# creates a list of lists e.g. [[room1, room1], [room2], [room3]]
room_lists = [[room] * room.people for room in house.rooms_set.all()]

# flatten the list e.g. [room1, room1, room2, room3]
rooms = [room for room_list in room_lists for room in room_list]

# zip the lists together
for form, room in zip(people_formset, rooms):
    name = form.cleaned_data['name']
    surname = form.cleaned_data['surname']
    p = People.objects.create(room=room, name=name, surname=surname)

The code may require further changes, for example to handle the case where there are more people than places in rooms.


问:
iOS - Navigation bar color transition when pressing back button
I'm trying to change the color of the navigation bar when pushing a view controller on the navigation stack, using barTintColor during navigationController(_:willShow:animated:).

Here is the code:

```<code>  func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    if viewController is ViewerViewController {
      navigationBar.barTintColor = UIColor(custom: .white)
      navigationBar.tintColor = UIColor(custom: .black)
    } else if viewController is FeedViewController {
      navigationBar.barTintColor = UIColor(custom: .blue)
      navigationBar.tintColor = UIColor(custom: .white)
    }
  }
</code>```

Everything works beautifully when I push the view controller and when I use the swipe back gesture (color transition is smooth in both ways).

However when I press the back button, color doesn't change at first, the navigation transition is done, and then color is changed with no animation.

Did anyone already encountered / resolved this issue ? Any clue would be appreciated.

答: I ended up using KMNavigationBarTransition library which works very well and doesn't require a single line of code.</p>

Body:
I'm trying to change the color of the navigation bar when pushing a view controller on the navigation stack, using barTintColor during navigationController(_:willShow:animated:).

Here is the code:

  func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    if viewController is ViewerViewController {
      navigationBar.barTintColor = UIColor(custom: .white)
      navigationBar.tintColor = UIColor(custom: .black)
    } else if viewController is FeedViewController {
      navigationBar.barTintColor = UIColor(custom: .blue)
      navigationBar.tintColor = UIColor(custom: .white)
    }
  }

Everything works beautifully when I push the view controller and when I use the swipe back gesture (color transition is smooth in both ways).

However when I press the back button, color doesn't change at first, the navigation transition is done, and then color is changed with no animation.

Did anyone already encountered / resolved this issue ? Any clue would be appreciated.


问:
C++ syntax highlighting for Visual Studio 2008?
I just want to see my own datatypes/functions/function parameters with a different color.

I have used Visual Assist X before, but it stopped working for some unknown reason. It doesn't color the custom functions or function parameters every time. Also, my trial time is over soon, and I am not going to buy something that doesn't work properly or whose most features I don't even use.

So, if there's any free syntax highlighting that colors all functions, etc. for Visual Studio 2008, that's what I'm looking for.

答: If you have the option to use Visual Studio 2010, there is Highlighterr, which changes the colors of classes, structs, macros and typedefs. There doesn’t appear to be a version for Visual Studio 2008, but what are you waiting for? ;-) C++0X awaits…</p>


问:
How to call class static function directly

let's say I have something like this:

Header.h:

```<code>namespace detail {

    template <typename T>
    class HiddenClass {

        /* Bunch of things... */

        template <typename ...ArgList>
        static HiddenClass<T> & function (const ArgList & ... argTail) {
            // Do something...
        }
    }
}
</code>```

And I want to call detail::HiddenClass<T>::function(***); but as you can see this is ridiculous. Not to mention that this function is supposed to be a part of the user interference. I can not expect "user" of my code to write detail::HiddenClass<T>::function(***); whenever he\she want to call function(***);

I Tried:

```<code>template <typename T>
using detail::HiddenClass<T>::function;
</code>```

And other approaches like this but i failed miserably...

Anyone can help somehow? Advice something

答:
You can provide a macro which will short the calling syntax:

```<code>#define MY_FUNCTION(Type, Arg) detail::HiddenClass<Type>::function(Arg)
</code>```

Then, its using from the global namespace will be much shorter, and no need of using:

```<code>HiddenClass<SomeType>& rc = MY_FUNCTION(SomeType, argTail);
</code>```

Body:
let's say I have something like this:

Header.h:

namespace detail {

    template <typename T>
    class HiddenClass {

        /* Bunch of things... */

        template <typename ...ArgList>
        static HiddenClass<T> & function (const ArgList & ... argTail) {
            // Do something...
        }
    }
}

And I want to call detail::HiddenClass<T>::function(***); but as you can see this is ridiculous. Not to mention that this function is supposed to be a part of the user interference. I can not expect "user" of my code to write detail::HiddenClass<T>::function(***); whenever he\she want to call function(***);

I Tried:

template <typename T>
using detail::HiddenClass<T>::function;

And other approaches like this but i failed miserably...

Anyone can help somehow? Advice something

Body:
You can provide a macro which will short the calling syntax:

#define MY_FUNCTION(Type, Arg) detail::HiddenClass<Type>::function(Arg)

Then, its using from the global namespace will be much shorter, and no need of using:

HiddenClass<SomeType>& rc = MY_FUNCTION(SomeType, argTail);


问:
python extend list by incremental values
Is there a nice simple method for extending a list n times, and doing so incrementally based on the existing values?

Basically I'm extrapolating a gradient, but don't want to invoke numpy/scipy if I can really avoid it.

I have some lists, lets say:

```<code>x = [1,2,3,4,5]
y = [10,20,30,40,50]
</code>```

Where I have already got a value for the average of the pairwise differences (the 'average gradient' of the list). I would now like to extend each list (let's say 20 times, to a total length of 25 each), where each subsequent value added is the previous value plus the computed average difference (if this was negative, obviously it would decrease).

So, x[5] would evaluate to x[4] + gradient.

Thus, the x list would ultimately end up:

```<code>x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
</code>```

Because the average difference in the original x = 1 (obviously this is just test data, in actuality I want to do this with more complicated floats in the y list.

答:
Yes you can.</p>

```<code>x = [1,2,3,4,5]
# Calculate your gradient, for simplicity I will just assign 1
# If the gradient has to change, calculate inside the loop
gradient = 1
for i in range(20):
    x.append(x[-1] + gradient)
</code>```

Body:
Is there a nice simple method for extending a list n times, and doing so incrementally based on the existing values?

Basically I'm extrapolating a gradient, but don't want to invoke numpy/scipy if I can really avoid it.

I have some lists, lets say:

x = [1,2,3,4,5]
y = [10,20,30,40,50]

Where I have already got a value for the average of the pairwise differences (the 'average gradient' of the list). I would now like to extend each list (let's say 20 times, to a total length of 25 each), where each subsequent value added is the previous value plus the computed average difference (if this was negative, obviously it would decrease).

So, x[5] would evaluate to x[4] + gradient.

Thus, the x list would ultimately end up:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]

Because the average difference in the original x = 1 (obviously this is just test data, in actuality I want to do this with more complicated floats in the y list.

Body:
Yes you can.

x = [1,2,3,4,5]
# Calculate your gradient, for simplicity I will just assign 1
# If the gradient has to change, calculate inside the loop
gradient = 1
for i in range(20):
    x.append(x[-1] + gradient)


问:
Got stuck while trying to procced with sqoop import
I am trying to import the data from MySQL to hadoop using below command

```<code>sqoop import --connect jdbc:mysql://192.168.0.107/manusql --table sales --username TEST2 --P --target-dir /home/sqoopdata -m 3
</code>```

But, the command execution got stuck at below process.

```<code>17/03/27 02:21:17 INFO orm.CompilationManager: Writing jar file: /tmp/sqoop-root/compile/01b7ea34648fcad142b7f3e142a8f087/sales.jar
17/03/27 02:21:17 WARN manager.MySQLManager: It looks like you are importing from mysql.
17/03/27 02:21:17 WARN manager.MySQLManager: This transfer can be faster! Use the --direct
17/03/27 02:21:17 WARN manager.MySQLManager: option to exercise a MySQL-specific fast path.
17/03/27 02:21:17 INFO manager.MySQLManager: Setting zero DATETIME behavior to convertToNull (mysql)
17/03/27 02:21:17 INFO mapreduce.ImportJobBase: Beginning import of sales
</code>```

Can someone help, please ?

答: Check resource manager logs there may be datatype incompatibility issue.Also try with -m 1 (single mapper) first for sequential access, then try for -m 3.</p>

Body:
I am trying to import the data from MySQL to hadoop using below command

sqoop import --connect jdbc:mysql://192.168.0.107/manusql --table sales --username TEST2 --P --target-dir /home/sqoopdata -m 3

But, the command execution got stuck at below process.

17/03/27 02:21:17 INFO orm.CompilationManager: Writing jar file: /tmp/sqoop-root/compile/01b7ea34648fcad142b7f3e142a8f087/sales.jar
17/03/27 02:21:17 WARN manager.MySQLManager: It looks like you are importing from mysql.
17/03/27 02:21:17 WARN manager.MySQLManager: This transfer can be faster! Use the --direct
17/03/27 02:21:17 WARN manager.MySQLManager: option to exercise a MySQL-specific fast path.
17/03/27 02:21:17 INFO manager.MySQLManager: Setting zero DATETIME behavior to convertToNull (mysql)
17/03/27 02:21:17 INFO mapreduce.ImportJobBase: Beginning import of sales

Can someone help, please ?


问:
How to get cell value on React-Bootstrap-Table?
I develop in React.js, and I'm using React-Bootstrap-Table. I need to get cell value on a sepcific column.

Is it possible to get cell value on a column ?

Thank you

答:
It's okay !
This is the solution : </p>

```<code>editFormatter(cell, row)  {row.nom_de_la_colonne}
</code>```

Body:
It's okay !
This is the solution :

editFormatter(cell, row)  {row.nom_de_la_colonne}


问:
Stop JavaScript Timer from another Function
I have the following Javascript code

```<code> function scrollOpenTimed() {
            var openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
        }

function a() {
      var _ouibounce = ouibounce(document.getElementById('modal'), {
        aggressive: true,
        timer: 0,
        callback: function() {
        console.log('ouibounce fired!');
        // cancel the openTimer
        }
      });
}
</code>```

At the moment I have scrollOpen being triggered after 3 seconds.

I want to cancel the timer and stop scrollOpen function being triggered When the callback function in function a() / ouibounce() function is triggered.

Any ideas how to do this appreciated.

Thanks

答:
Try this:     </p>

```<code>var openTimer;

function scrollOpenTimed() {
  openTimer = setTimeout(function() {
    scrollOpen();
  }, 3000);
}

function a() {
  var _ouibounce = ouibounce(document.getElementById('modal'), {
    aggressive: true,
    timer: 0,
    callback: function() {
      console.log('ouibounce fired!');
      clearTimeout(openTimer);
    }
  });
}
</code>```

Body:
I have the following Javascript code

 function scrollOpenTimed() {
            var openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
        }

function a() {
      var _ouibounce = ouibounce(document.getElementById('modal'), {
        aggressive: true,
        timer: 0,
        callback: function() {
        console.log('ouibounce fired!');
        // cancel the openTimer
        }
      });
}

At the moment I have scrollOpen being triggered after 3 seconds.

I want to cancel the timer and stop scrollOpen function being triggered When the callback function in function a() / ouibounce() function is triggered.

Any ideas how to do this appreciated.

Thanks

Body:
Try this:

var openTimer;

function scrollOpenTimed() {
  openTimer = setTimeout(function() {
    scrollOpen();
  }, 3000);
}

function a() {
  var _ouibounce = ouibounce(document.getElementById('modal'), {
    aggressive: true,
    timer: 0,
    callback: function() {
      console.log('ouibounce fired!');
      clearTimeout(openTimer);
    }
  });
}


问:
How to show web views in messenger
I'm following this: https://developers.facebook.com/docs/messenger-platform/webview/sharing

I've created custom classes :

```<code>[JsonObject(MemberSerialization.OptIn)]
        public class elements
        {
            [JsonProperty]
            public string title { get; set; }
            [JsonProperty]
            public string image_url { get; set; }
            [JsonProperty]
            public string subtitle { get; set; }
            [JsonProperty]
            public default_action default_action { get; set; }
            [JsonProperty]
            public buttons[] buttons { get; set; }
        }
        [JsonObject(MemberSerialization.OptIn)]
        public class default_action
        {

            [JsonProperty]
            public string type { get; set; }

            [JsonProperty]
            public string url { get; set; }
        }
        [JsonObject(MemberSerialization.OptIn)]
        public class buttons
        {

            [JsonProperty]
            public string type { get; set; }

            [JsonProperty]
            public string url { get; set; }

            [JsonProperty]
            public string title { get; set; }
        }
</code>```

Then, in method :

```<code>elements e = new elements();

                    e.default_action.type = "web_url";
                    e.default_action.type = "https://www.youtube.com/watch?v=kOkQ4T5WO9E";
                    e.title = "title";

                    List<buttons> list = new List<buttons>();
                    buttons b = new buttons();
                    b.title = "button title";
                    b.type = "web_url";
                    b.url = "https://www.youtube.com/watch?v=kOkQ4T5WO9E";
                    list.Add(b);
                    e.buttons = list.ToArray();

                    msg.ChannelData = e;
                    msg.Text = "test";
</code>```

But it throws an error. In bot framework dashboard can't see an issue.
How to debug this ?

答:
Take a look to the Microsoft Bot Framework .NET - Enrich your conversation with Facebook Messengers Webview video. It shows you how to utilize the Facebook Messenger extension to provide a Webview experience in your Bot Framework chatbot.

The demo code of the video is here.

Title: How to show web views in messenger

Body:
I'm following this: https://developers.facebook.com/docs/messenger-platform/webview/sharing

I've created custom classes :

[JsonObject(MemberSerialization.OptIn)]
        public class elements
        {
            [JsonProperty]
            public string title { get; set; }
            [JsonProperty]
            public string image_url { get; set; }
            [JsonProperty]
            public string subtitle { get; set; }
            [JsonProperty]
            public default_action default_action { get; set; }
            [JsonProperty]
            public buttons[] buttons { get; set; }
        }
        [JsonObject(MemberSerialization.OptIn)]
        public class default_action
        {

            [JsonProperty]
            public string type { get; set; }

            [JsonProperty]
            public string url { get; set; }
        }
        [JsonObject(MemberSerialization.OptIn)]
        public class buttons
        {

            [JsonProperty]
            public string type { get; set; }

            [JsonProperty]
            public string url { get; set; }

            [JsonProperty]
            public string title { get; set; }
        }

Then, in method :

elements e = new elements();

                    e.default_action.type = "web_url";
                    e.default_action.type = "https://www.youtube.com/watch?v=kOkQ4T5WO9E";
                    e.title = "title";

                    List<buttons> list = new List<buttons>();
                    buttons b = new buttons();
                    b.title = "button title";
                    b.type = "web_url";
                    b.url = "https://www.youtube.com/watch?v=kOkQ4T5WO9E";
                    list.Add(b);
                    e.buttons = list.ToArray();

                    msg.ChannelData = e;
                    msg.Text = "test";

But it throws an error. In bot framework dashboard can't see an issue.
How to debug this ?


问:
How to solve TortoiseGitPlink Fatal Error?
I was using Git with beanstalk in windows 7. Now I got new system with Windows 8.1. Now I configured Git and Tortoisegit with new system.Its working fine in local commit but when I pushed to live I got error:

```<code>Disconnected: No supported authentication methods available (Sever sent: public key)
</code>```

I added SSH key and all? Is there any problem in Windows 8.1?
Thanks

答: Or run Putty authentication agent (Pageant.exe) from TortoiseGit folder (usually C:\Program Files\TortoiseGit\bin) and add PuttyKey manually to the app.</p>

Body:
I was using Git with beanstalk in windows 7. Now I got new system with Windows 8.1. Now I configured Git and Tortoisegit with new system.Its working fine in local commit but when I pushed to live I got error:

Disconnected: No supported authentication methods available (Sever sent: public key)

I added SSH key and all? Is there any problem in Windows 8.1?
Thanks


答:
Following Nina Scholz's answer above, you should do:</p>

```<code>var openTimer;

function scrollOpenTimed() {
  openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
}

function a() {
  var _ouibounce = ouibounce(document.getElementById('modal'), {
    aggressive: true,
    timer: 0,
    callback: function() {
    console.log('ouibounce fired!');
      // cancel the openTimer
      clearTimeout(openTimer);
    }
  });
}
</code>```

Title: Stop JavaScript Timer from another Function

Body:
Following Nina Scholz's answer above, you should do:

var openTimer;

function scrollOpenTimed() {
  openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
}

function a() {
  var _ouibounce = ouibounce(document.getElementById('modal'), {
    aggressive: true,
    timer: 0,
    callback: function() {
    console.log('ouibounce fired!');
      // cancel the openTimer
      clearTimeout(openTimer);
    }
  });
}