<commit_before>$(function () {
    'use strict';

    function initTables() {
        var cardView = false;

        if ($(window).width() < 640) {
            cardView = true;
        }

        $('#table, #column, #event, #method, #localization').bootstrapTable('destroy');

        $('#table').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', width: 60, sortable: true},
                {field: 'type', title: 'Type', align: 'center', width: 60},
                {field: 'description', title: 'Description', width: 400},
                {field: 'default', title: 'Default', align: 'right', width: 180}
            ],
            data: [
                {
                    name: 'classes',
                    type: 'String',
                    description: 'The class name of table.',
                    'default': 'table table-hover'
                },
                {
                    name: 'height',
                    type: 'Number',
                    description: 'The height of table.',
                    'default': 'undefined'
                },
                {
                    name: 'undefinedText',
                    type: 'String',
                    description: 'Defines the default undefined text.',
                    'default': '-'
                },
                {
                    name: 'striped',
                    type: 'Boolean',
                    description: 'True to stripe the rows.',
                    'default': 'false'
                },
                {
                    name: 'sortName',
                    type: 'String',
                    description: 'Defines which column can be sorted.',
                    'default': 'undefined'
                },
                {
                    name: 'sortOrder',
                    type: 'String',
                    description: 'Defines the column sort order, can only be "asc" or "desc".',
                    'default': 'asc'
                },
                {
                    name: 'columns',
                    type: 'Array',
                    description: 'The table columns config object, see column properties for more details.',
                    'default': '[]'
                },
                {
                    name: 'data',
                    type: 'Array',
                    description: 'The data to be loaded.',
                    'default': '[]'
                },
                {
                    name: 'method',
                    type: 'String',
                    description: 'The method type to request remote data.',
                    'default': 'get'
                },
                {
                    name: 'url',
                    type: 'String',
                    description: 'A URL to request data from remote site.',
                    'default': 'undefined'
                },
                {
                    name: 'queryParams',
                    type: 'Function',
                    description: 'When request remote data, sending additional parameters by format the queryParams.',
                    'default': 'function(pageSize, pageNumber, searchText) {return {};}'
                },
                {
                    name: 'pagination',
                    type: 'Boolean',
                    description: 'True to show a pagination toolbar on datagrid bottom.',
                    'default': 'false'
                },
                {
                    name: 'sidePagination',
                    type: 'String',
                    description: 'Defines the side pagination of table, can only be "client" or "server".',
                    'default': 'client'
                },
                {
                    name: 'totalRows',
                    type: 'Number',
                    description: 'Defines the total rows of table, you need to set this option when the sidePagination option is set to "server".',
                    'default': 0
                },
                {
                    name: 'pageNumber',
                    type: 'Number',
                    description: 'When set pagination property, initialize the page number.',
                    'default': 1
                },
                {
                    name: 'pageSize',
                    type: 'Number',
                    description: 'When set pagination property, initialize the page size.',
                    'default': 10
                },
                {
                    name: 'pageList',
                    type: 'Array',
                    description: 'When set pagination property, initialize the page size selecting list.',
                    'default': '[10, 25, 50, 100]'
                },
                {
                    name: 'search',
                    type: 'Boolean',
                    description: 'Enable the search input.',
                    'default': 'false'
                },
                {
                    name: 'selectItemName',
                    type: 'String',
                    description: 'The name of radio or checkbox input.',
                    'default': 'btSelectItem'
                },
                {
                    name: 'showHeader',
                    type: 'Boolean',
                    description: 'False to hide the table header.',
                    'default': 'true'
                },
                {
                    name: 'showColumns',
                    type: 'Boolean',
                    description: 'True to show the columns drop down list.',
                    'default': 'false'
                },
                {
                    name: 'idField',
                    type: 'String',
                    description: 'Indicate which field is an identity field.',
                    'default': 'undefined'
                },
                {
                    name: 'cardView',
                    type: 'Boolean',
                    description: 'True to show card view table, for example mobile view.',
                    'default': 'false'
                },
                {
                    name: 'clickToSelect',
                    type: 'Boolean',
                    description: 'True to select checkbox or radiobox when click rows.',
                    'default': 'false'
                }
            ]
        });
        $('#column').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', valign: 'middle', width: 60, sortable: true},
                {field: 'type', title: 'Type', align: 'center', valign: 'middle', width: 60},
                {field: 'description', title: 'Description', width: 400},
                {field: 'default', title: 'Default', align: 'right', valign: 'middle', width: 180}
            ],
            data: [
                {
                    name: 'radio',
                    type: 'Boolean',
                    description: 'True to show a radio. The radio column has fixed width.',
                    'default': 'false'
                },
                {
                    name: 'checkbox',
                    type: 'Boolean',
                    description: 'True to show a checkbox. The checkbox column has fixed width.',
                    'default': 'false'
                },
                {
                    name: 'field',
                    type: 'String',
                    description: 'The column field name.',
                    'default': 'undefined'
                },
                {
                    name: 'title',
                    type: 'String',
                    description: 'The column title text.',
                    'default': 'undefined'
                },
                {
                    name: 'align',
                    type: 'String',
                    description: 'Indicate how to align the column data. "left", "right", "center" can be used.',
                    'default': 'undefined'},
                {
                    name: 'valign',
                    type: 'String',
                    description: 'Indicate how to align the cell data. "top", "middle", "bottom" can be used.',
                    'default': 'undefined'
                },
                {
                    name: 'width',
                    type: 'Number',
                    description: 'The width of column. If not defined, the width will auto expand to fit its contents.',
                    'default': 'undefined'},
                {
                    name: 'sortable',
                    type: 'Boolean',
                    description: 'True to allow the column can be sorted.',
                    'default': 'false'
                },
                {
                    name: 'order',
                    type: 'String',
                    description: 'The default sort order, can only be "asc" or "desc".',
                    'default': 'asc'
                },
                {
                    name: 'visible',
                    type: 'Boolean',
                    description: 'True to visible the columns item.',
                    'default': 'true'
                },
                {
                    name: 'formatter',
                    type: 'Function',
                    description: 'The cell formatter function, take two parameters:
value: the field value.
row: the row record data.
index: the row index.',
                    'default': 'undefined'
                },
                {
                    name: 'sorter',
                    type: 'Function',
                    description: 'The custom field sort function that used to do local sorting, take two parameters:
a: the first field value.
 b: the second field value.',
                    'default': 'undefined'
                }
            ]
        });
        $('#event').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', valign: 'middle', width: 100, sortable: true},
                {field: 'parameter', title: 'Parameter', align: 'center', valign: 'middle', width: 100, sortable: true},
                {field: 'description', title: 'Description', width: 400, sortable: true}
            ],
            data: [
                {
                    name: 'onClickRow',
                    parameter: 'row',
                    description: 'Fires when user click a row, the parameters contains:
row: the record corresponding to the clicked row.'},
                {
                    name: 'onSort',
                    parameter: 'name, order',
                    description: 'Fires when user sort a column, the parameters contains:
name: the sort column field name
order: the sort column order.'
                },
                {
                    name: 'onCheck',
                    parameter: 'row',
                    description: 'Fires when user check a row, the parameters contains:
row: the record corresponding to the clicked row.'
                },
                {
                    name: 'onUncheck',
                    parameter: 'row',
                    description: 'Fires when user uncheck a row, the parameters contains:
row: the record corresponding to the clicked row.'
                },
                {
                    name: 'onCheckAll',
                    parameter: 'none',
                    description: 'Fires when user check all rows.'
                },
                {
                    name: 'onUncheckAll',
                    parameter: 'none',
                    description: 'Fires when user uncheck all rows.'
                },
                {
                    name: 'onLoadSuccess',
                    parameter: 'data',
                    description: 'Fires when remote data is loaded successfully.'
                },
                {
                    name: 'onLoadError',
                    parameter: 'status',
                    description: 'Fires when some errors occur to load remote data.'
                }
            ],
            onClickRow: function (row) {
                console.log('onClickRow', row);
            },
            onSort: function (name, order) {
                console.log('onSort', name, order);
            },
            onCheck: function(row) {
                console.log('onCheck', row);
            },
            onUncheck: function(row) {
                console.log('onUncheck', row);
            },
            onCheckAll: function() {
                console.log('onCheckAll');
            },
            onUncheckAll: function() {
                console.log('onUncheckAll');
            }
        });
        $('#method').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', valign: 'middle', width: 100},
                {field: 'parameter', title: 'Parameter', align: 'center', valign: 'middle', width: 100},
                {field: 'description', title: 'Description', width: 400}
            ]
        }).bootstrapTable('load', [
                {name: 'getSelections', parameter: 'none', description: 'Return all selected rows, when no record selected, am empty array will return.'},
                {name: 'load', parameter: 'data', description: 'Load the data to table.'}
            ]).bootstrapTable('append', [
                {name: 'append', parameter: 'data', description: 'Append the data to table.'},
                {name: 'mergeCells', parameter: 'options', description: 'Merge some cells to one cell, the options contains following properties:'},
                {name: 'mergeCells', parameter: 'options', description: 'index: the row index.'},
                {name: 'mergeCells', parameter: 'options', description: 'field: the field name.'},
                {name: 'mergeCells', parameter: 'options', description: 'rowspan: the rowspan count to be merged.'},
                {name: 'mergeCells', parameter: 'options', description: 'colspan: the colspan count to be merged.'},
                {name: 'refresh', parameter: 'none', description: 'Refresh the remote server data.'},
                {name: 'showLoading', parameter: 'none', description: 'Show loading status.'},
                {name: 'hideLoading', parameter: 'none', description: 'Hide loading status.'},
                {name: 'checkAll', parameter: 'none', description: 'Check all current page rows.'},
                {name: 'uncheckAll', parameter: 'none', description: 'Uncheck all current page rows.'},
                {name: 'resetView', parameter: 'none', description: 'Reset the bootstrap table view, like display error when init the table with display: none.'},
                {name: 'destroy', parameter: 'none', description: 'Destroy the bootstrap table.'}
            ]).bootstrapTable('mergeCells', {
                index: 3,
                field: 'name',
                rowspan: 5
            }).bootstrapTable('mergeCells', {
                index: 3,
                field: 'parameter',
                rowspan: 5
            });

        $('#localization').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', valign: 'middle', width: 100},
                {field: 'parameter', title: 'Parameter', align: 'center', valign: 'middle', width: 100},
                {field: 'default', title: 'Default', align: 'center', valign: 'middle', width: 200}
            ],
            data: [{
                name: 'formatLoadingMessage',
                parameter: '-',
                'default': 'Loading, please wait…'
            }, {
                name: 'formatRecordsPerPage',
                parameter: 'pageNumber',
                'default': '%s records per page'
            }, {
                name: 'formatShowingRows',
                parameter: 'pageFrom, pageTo, totalRows',
                'default': 'Showing %s to %s of %s rows'
            }, {
                name: 'formatSearch',
                parameter: '-',
                'default': 'Search'
            }, {
                name: 'formatNoMatches',
                parameter: '-',
                'default': 'No matching records found'
            }]
        });
    }

    var $window = $(window);
    var $body = $(document.body);

    var navHeight = $('.navbar').outerHeight(true) + 10;

    $body.scrollspy({
        target: '.bs-sidebar',
        offset: navHeight
    });

    $window.on('load', function () {
        $body.scrollspy('refresh')
    });

    $window.on('resize', function() {
        initTables();
    });

    // affix
    setTimeout(function () {
        var $sideBar = $('.bs-sidebar');

        $sideBar.affix({
            offset: {
                top: function () {
                    var offsetTop = $sideBar.offset().top;
                    var sideBarMargin = parseInt($sideBar.children(0).css('margin-top'), 10);
                    var navOuterHeight = $('.bs-docs-nav').height();

                    return (this.top = offsetTop - navOuterHeight - sideBarMargin);
                },
                bottom: function () {
                    return (this.bottom = $('.bs-footer').outerHeight(true));
                }
            }
        });
    }, 100);

    initTables();
});<commit_msg>Update docs.<commit_after>$(function () {
    'use strict';

    function initTables() {
        var cardView = false;

        if ($(window).width() < 640) {
            cardView = true;
        }

        $('#table, #column, #event, #method, #localization').bootstrapTable('destroy');

        $('#table').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', width: 60, sortable: true},
                {field: 'type', title: 'Type', align: 'center', width: 60},
                {field: 'description', title: 'Description', width: 400},
                {field: 'default', title: 'Default', align: 'right', width: 180}
            ],
            data: [
                {
                    name: 'classes',
                    type: 'String',
                    description: 'The class name of table.',
                    'default': 'table table-hover'
                },
                {
                    name: 'height',
                    type: 'Number',
                    description: 'The height of table.',
                    'default': 'undefined'
                },
                {
                    name: 'undefinedText',
                    type: 'String',
                    description: 'Defines the default undefined text.',
                    'default': '-'
                },
                {
                    name: 'striped',
                    type: 'Boolean',
                    description: 'True to stripe the rows.',
                    'default': 'false'
                },
                {
                    name: 'sortName',
                    type: 'String',
                    description: 'Defines which column can be sorted.',
                    'default': 'undefined'
                },
                {
                    name: 'sortOrder',
                    type: 'String',
                    description: 'Defines the column sort order, can only be "asc" or "desc".',
                    'default': 'asc'
                },
                {
                    name: 'columns',
                    type: 'Array',
                    description: 'The table columns config object, see column properties for more details.',
                    'default': '[]'
                },
                {
                    name: 'data',
                    type: 'Array',
                    description: 'The data to be loaded.',
                    'default': '[]'
                },
                {
                    name: 'method',
                    type: 'String',
                    description: 'The method type to request remote data.',
                    'default': 'get'
                },
                {
                    name: 'url',
                    type: 'String',
                    description: 'A URL to request data from remote site.',
                    'default': 'undefined'
                },
                {
                    name: 'contentType',
                    type: 'String',
                    description: 'The contentType of request remote data.',
                    'default': 'application/json'
                },
                {
                    name: 'queryParams',
                    type: 'Function',
                    description: 'When request remote data, sending additional parameters by format the queryParams.',
                    'default': 'function(pageSize, pageNumber, searchText) {return {};}'
                },
                {
                    name: 'pagination',
                    type: 'Boolean',
                    description: 'True to show a pagination toolbar on datagrid bottom.',
                    'default': 'false'
                },
                {
                    name: 'sidePagination',
                    type: 'String',
                    description: 'Defines the side pagination of table, can only be "client" or "server".',
                    'default': 'client'
                },
                {
                    name: 'totalRows',
                    type: 'Number',
                    description: 'Defines the total rows of table, you need to set this option when the sidePagination option is set to "server".',
                    'default': 0
                },
                {
                    name: 'pageNumber',
                    type: 'Number',
                    description: 'When set pagination property, initialize the page number.',
                    'default': 1
                },
                {
                    name: 'pageSize',
                    type: 'Number',
                    description: 'When set pagination property, initialize the page size.',
                    'default': 10
                },
                {
                    name: 'pageList',
                    type: 'Array',
                    description: 'When set pagination property, initialize the page size selecting list.',
                    'default': '[10, 25, 50, 100]'
                },
                {
                    name: 'search',
                    type: 'Boolean',
                    description: 'Enable the search input.',
                    'default': 'false'
                },
                {
                    name: 'selectItemName',
                    type: 'String',
                    description: 'The name of radio or checkbox input.',
                    'default': 'btSelectItem'
                },
                {
                    name: 'showHeader',
                    type: 'Boolean',
                    description: 'False to hide the table header.',
                    'default': 'true'
                },
                {
                    name: 'showColumns',
                    type: 'Boolean',
                    description: 'True to show the columns drop down list.',
                    'default': 'false'
                },
                {
                    name: 'idField',
                    type: 'String',
                    description: 'Indicate which field is an identity field.',
                    'default': 'undefined'
                },
                {
                    name: 'cardView',
                    type: 'Boolean',
                    description: 'True to show card view table, for example mobile view.',
                    'default': 'false'
                },
                {
                    name: 'clickToSelect',
                    type: 'Boolean',
                    description: 'True to select checkbox or radiobox when click rows.',
                    'default': 'false'
                }
            ]
        });
        $('#column').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', valign: 'middle', width: 60, sortable: true},
                {field: 'type', title: 'Type', align: 'center', valign: 'middle', width: 60},
                {field: 'description', title: 'Description', width: 400},
                {field: 'default', title: 'Default', align: 'right', valign: 'middle', width: 180}
            ],
            data: [
                {
                    name: 'radio',
                    type: 'Boolean',
                    description: 'True to show a radio. The radio column has fixed width.',
                    'default': 'false'
                },
                {
                    name: 'checkbox',
                    type: 'Boolean',
                    description: 'True to show a checkbox. The checkbox column has fixed width.',
                    'default': 'false'
                },
                {
                    name: 'field',
                    type: 'String',
                    description: 'The column field name.',
                    'default': 'undefined'
                },
                {
                    name: 'title',
                    type: 'String',
                    description: 'The column title text.',
                    'default': 'undefined'
                },
                {
                    name: 'align',
                    type: 'String',
                    description: 'Indicate how to align the column data. "left", "right", "center" can be used.',
                    'default': 'undefined'},
                {
                    name: 'valign',
                    type: 'String',
                    description: 'Indicate how to align the cell data. "top", "middle", "bottom" can be used.',
                    'default': 'undefined'
                },
                {
                    name: 'width',
                    type: 'Number',
                    description: 'The width of column. If not defined, the width will auto expand to fit its contents.',
                    'default': 'undefined'},
                {
                    name: 'sortable',
                    type: 'Boolean',
                    description: 'True to allow the column can be sorted.',
                    'default': 'false'
                },
                {
                    name: 'order',
                    type: 'String',
                    description: 'The default sort order, can only be "asc" or "desc".',
                    'default': 'asc'
                },
                {
                    name: 'visible',
                    type: 'Boolean',
                    description: 'True to visible the columns item.',
                    'default': 'true'
                },
                {
                    name: 'formatter',
                    type: 'Function',
                    description: 'The cell formatter function, take two parameters:
value: the field value.
row: the row record data.
index: the row index.',
                    'default': 'undefined'
                },
                {
                    name: 'sorter',
                    type: 'Function',
                    description: 'The custom field sort function that used to do local sorting, take two parameters:
a: the first field value.
 b: the second field value.',
                    'default': 'undefined'
                }
            ]
        });
        $('#event').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', valign: 'middle', width: 100, sortable: true},
                {field: 'parameter', title: 'Parameter', align: 'center', valign: 'middle', width: 100, sortable: true},
                {field: 'description', title: 'Description', width: 400, sortable: true}
            ],
            data: [
                {
                    name: 'onClickRow',
                    parameter: 'row',
                    description: 'Fires when user click a row, the parameters contains:
row: the record corresponding to the clicked row.'},
                {
                    name: 'onSort',
                    parameter: 'name, order',
                    description: 'Fires when user sort a column, the parameters contains:
name: the sort column field name
order: the sort column order.'
                },
                {
                    name: 'onCheck',
                    parameter: 'row',
                    description: 'Fires when user check a row, the parameters contains:
row: the record corresponding to the clicked row.'
                },
                {
                    name: 'onUncheck',
                    parameter: 'row',
                    description: 'Fires when user uncheck a row, the parameters contains:
row: the record corresponding to the clicked row.'
                },
                {
                    name: 'onCheckAll',
                    parameter: 'none',
                    description: 'Fires when user check all rows.'
                },
                {
                    name: 'onUncheckAll',
                    parameter: 'none',
                    description: 'Fires when user uncheck all rows.'
                },
                {
                    name: 'onLoadSuccess',
                    parameter: 'data',
                    description: 'Fires when remote data is loaded successfully.'
                },
                {
                    name: 'onLoadError',
                    parameter: 'status',
                    description: 'Fires when some errors occur to load remote data.'
                },
                {
                    name: 'onBeforeLoad',
                    parameter: 'res',
                    description: 'Fires before a request is made to load data.'
                }
            ],
            onClickRow: function (row) {
                console.log('onClickRow', row);
            },
            onSort: function (name, order) {
                console.log('onSort', name, order);
            },
            onCheck: function(row) {
                console.log('onCheck', row);
            },
            onUncheck: function(row) {
                console.log('onUncheck', row);
            },
            onCheckAll: function() {
                console.log('onCheckAll');
            },
            onUncheckAll: function() {
                console.log('onUncheckAll');
            }
        });
        $('#method').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', valign: 'middle', width: 100},
                {field: 'parameter', title: 'Parameter', align: 'center', valign: 'middle', width: 100},
                {field: 'description', title: 'Description', width: 400}
            ]
        }).bootstrapTable('load', [
                {name: 'getSelections', parameter: 'none', description: 'Return all selected rows, when no record selected, am empty array will return.'},
                {name: 'load', parameter: 'data', description: 'Load the data to table.'}
            ]).bootstrapTable('append', [
                {name: 'append', parameter: 'data', description: 'Append the data to table.'},
                {name: 'mergeCells', parameter: 'options', description: 'Merge some cells to one cell, the options contains following properties:'},
                {name: 'mergeCells', parameter: 'options', description: 'index: the row index.'},
                {name: 'mergeCells', parameter: 'options', description: 'field: the field name.'},
                {name: 'mergeCells', parameter: 'options', description: 'rowspan: the rowspan count to be merged.'},
                {name: 'mergeCells', parameter: 'options', description: 'colspan: the colspan count to be merged.'},
                {name: 'refresh', parameter: 'none', description: 'Refresh the remote server data.'},
                {name: 'showLoading', parameter: 'none', description: 'Show loading status.'},
                {name: 'hideLoading', parameter: 'none', description: 'Hide loading status.'},
                {name: 'checkAll', parameter: 'none', description: 'Check all current page rows.'},
                {name: 'uncheckAll', parameter: 'none', description: 'Uncheck all current page rows.'},
                {name: 'resetView', parameter: 'none', description: 'Reset the bootstrap table view, like display error when init the table with display: none.'},
                {name: 'destroy', parameter: 'none', description: 'Destroy the bootstrap table.'}
            ]).bootstrapTable('mergeCells', {
                index: 3,
                field: 'name',
                rowspan: 5
            }).bootstrapTable('mergeCells', {
                index: 3,
                field: 'parameter',
                rowspan: 5
            });

        $('#localization').bootstrapTable({
            cardView: cardView,
            columns: [
                {field: 'name', title: 'Name', align: 'center', valign: 'middle', width: 100},
                {field: 'parameter', title: 'Parameter', align: 'center', valign: 'middle', width: 100},
                {field: 'default', title: 'Default', align: 'center', valign: 'middle', width: 200}
            ],
            data: [{
                name: 'formatLoadingMessage',
                parameter: '-',
                'default': 'Loading, please wait…'
            }, {
                name: 'formatRecordsPerPage',
                parameter: 'pageNumber',
                'default': '%s records per page'
            }, {
                name: 'formatShowingRows',
                parameter: 'pageFrom, pageTo, totalRows',
                'default': 'Showing %s to %s of %s rows'
            }, {
                name: 'formatSearch',
                parameter: '-',
                'default': 'Search'
            }, {
                name: 'formatNoMatches',
                parameter: '-',
                'default': 'No matching records found'
            }]
        });
    }

    var $window = $(window);
    var $body = $(document.body);

    var navHeight = $('.navbar').outerHeight(true) + 10;

    $body.scrollspy({
        target: '.bs-sidebar',
        offset: navHeight
    });

    $window.on('load', function () {
        $body.scrollspy('refresh')
    });

    $window.on('resize', function() {
        initTables();
    });

    // affix
    setTimeout(function () {
        var $sideBar = $('.bs-sidebar');

        $sideBar.affix({
            offset: {
                top: function () {
                    var offsetTop = $sideBar.offset().top;
                    var sideBarMargin = parseInt($sideBar.children(0).css('margin-top'), 10);
                    var navOuterHeight = $('.bs-docs-nav').height();

                    return (this.top = offsetTop - navOuterHeight - sideBarMargin);
                },
                bottom: function () {
                    return (this.bottom = $('.bs-footer').outerHeight(true));
                }
            }
        });
    }, 100);

    initTables();
});<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { Provider } from 'react-redux'
import { Router } from 'react-router'
import { AppContainer } from 'react-hot-loader'
import getRoutes from '../../routes'

class Root extends Component {
  render () {
    const { store, history } = this.props
    return (
      <AppContainer>
        <Provider store={store}>
          <Router key={Math.random()} history={history} routes={getRoutes()} />
        </Provider>
      </AppContainer>
    )
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired
}

export default Root
<commit_msg>refactor(containers): Root<commit_after>import React, { Component, PropTypes } from 'react'
import { Provider } from 'react-redux'
import { Router, RouterContext } from 'react-router'
import { AppContainer } from 'react-hot-loader'
import getRoutes from '../../routes'

class Root extends Component {
  render () {
    const { store, history, renderProps } = this.props
    return (
      <AppContainer>
        <Provider store={store}>
          { __SERVER__
            ? <RouterContext {...renderProps} />
            : <Router key={Math.random()} history={history} routes={getRoutes()} />
          }
        </Provider>
      </AppContainer>
    )
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
  renderProps: PropTypes.object
}

export default Root
<|endoftext|>


<commit_before>var favoritelist=new Array();
var onFavoritesChanged = function(){};
function initFavorites(){
	// addFavorite(1);
	// addFavorite(10);
	// console.log(isFavorite(10));
	// setDescription(1, "test");
	// console.log(getDescription(1));
	// console.log(getFavoritelist());
	// console.log(getFavoritelist());
	// saveCookie();

	// if(document.cookie){
		// console.log("Cookie: " + document.cookie);
		// favoritelist=JSON.parse(document.cookie);
	// }
	// console.log(getFavoritelist());
	// console.log(isFavorite(10));
	onFavoritesChanged();
//
}

	/*
	 * adds the ID to the Favoritelist
	 */
function addFavorite(id){
	if(!isFavorite()){
		favoritelist[id]={id:id,des:"",func:null};
		setFunction(id, function(x){return x;}+"");
		console.log( favoritelist[id].func +' favorit hinzugefügt');
		onFavoritesChanged();
	}
}
/*
 * returns Favoritelist
 */
function getFavoritelist(){
	return favoritelist;
}
/*
 * return true or false, if id is in favoritelist or not
 */
function isFavorite(id){
	console.log(favoritelist.hasOwnProperty(id));
	return favoritelist.hasOwnProperty(id);
}
/*
 * Removes Favorites from the list
 */
function removeFavorite(id){
	var index = favoritelist.indexOf(id);
	favoritelist.splice(index, 1);
	//schneidet aus Array raus
	console.log(id + " aus Array gelöscht");
	onFavoritesChanged();
}
function saveCookie(){
	var a=new Date();
	a=new Date(a.getTime() +1000*60*60*24*365*10);
	//cookie ist ein Jahr gültig?
	document.cookie=JSON.stringify(favoritelist)+";expires="+a.toGMTString();
	//jeder neue Wert wird hinten angehängt
	console.log(document.cookie+'cookie gespeichert');
	}
	/*
	 * Writes Description in the Favoriteliste
	 */
function setDescription(id, des){
		favoritelist[id].des=des;
	console.log("Beschreibung geändert");
	onFavoritesChanged();
	}
	/*
	 * Reads Description out of the Favoritelist
	 */
function getDescription(id){
	return "--";//favoritelist[id].des;
	}
	/*
	 * Writes Function in the FavoriteList
	 */
	function setFunction(id, func){
		favoritelist[id].func=func;
	console.log("Beschreibung geändert");
	onFavoritesChanged();
	}
	/*
	 * Reads Function out of the Favoritelist
	 */
function getFunction(id){
	return "--";//new Function(favoritelist[id].func);
	}
function toggleFavorite(id){
	isFavorite(id)?removeFavorite(id):addFavorite(id);
	}

function setOnFavoritesChanged(func) {
	onFavoritesChanged=func;
}
<commit_msg>Favorite Fixed<commit_after>var favoritelist=new Array();
var onFavoritesChanged = function(){};
function initFavorites(){
	// addFavorite(1);
	// addFavorite(10);
	// console.log(isFavorite(10));
	// setDescription(1, "test");
	// console.log(getDescription(1));
	// console.log(getFavoritelist());
	// console.log(getFavoritelist());
	// saveCookie();

	// if(document.cookie){
		// console.log("Cookie: " + document.cookie);
		// var cook=JSON.parse(document.cookie);
		 //favoritelist =encodeURI(cook);
		/*
		 * favoritelist=cook.replace('#',';');
		 */
	// }
	// console.log(getFavoritelist());
	// console.log(isFavorite(10));
	onFavoritesChanged();
//
}

	/*
	 * adds the ID to the Favoritelist
	 */
function addFavorite(id){
	if(!isFavorite()){
		favoritelist[id]={id:id,des:"",func:null};
		setFunction(id, function(x){return x;}+"");
		console.log( favoritelist[id].func +' favorit hinzugefügt');
		onFavoritesChanged();
	}
}
/*
 * returns Favoritelist
 */
function getFavoritelist(){
	return favoritelist;
}
/*
 * return true or false, if id is in favoritelist or not
 */
function isFavorite(id){
	console.log(favoritelist.hasOwnProperty(id));
	return favoritelist.hasOwnProperty(id);
}
/*
 * Removes Favorites from the list
 */
function removeFavorite(id){
	var index = favoritelist.indexOf(id);
	favoritelist.splice(index, 1);
	//schneidet aus Array raus
	console.log(id + " aus Array gelöscht");
	onFavoritesChanged();
}
function saveCookie(){
	var a=new Date();
	a=new Date(a.getTime() +1000*60*60*24*365*10);
	//cookie ist ein Jahr gültig?
	document.cookie= changeFunctionToCookie+";expires="+a.toGMTString();
	//jeder neue Wert wird hinten angehängt
	console.log(document.cookie+'cookie gespeichert');
	}
	/*
	 * Writes Description in the Favoriteliste
	 */
function setDescription(id, des){
		favoritelist[id].des=des;
	console.log("Beschreibung geändert");
	onFavoritesChanged();
	}
	/*
	 * Reads Description out of the Favoritelist
	 */
function getDescription(id){
	return "--";//favoritelist[id].des;
	}
	/*
	 * Writes Function in the FavoriteList
	 */
	function setFunction(id, func){
		favoritelist[id].func=func;
	console.log("Beschreibung geändert");
	onFavoritesChanged();
	}
	/*
	 * Reads Function out of the Favoritelist
	 */
function getFunction(id){
	return "--";//new Function(favoritelist[id].func);
	}
 	/*
 	 * Changes the ; in Function to # , because of cut offs while saving
 	 * (cookie)
 	 */
function changeFunctionToCookie(){
	var cook=JSON.stringify(favoritelist);
	//var newString=cook.replace(';','#');
	var newString=decodeURI(cook);
	return newString;

}

function toggleFavorite(id){
	isFavorite(id)?removeFavorite(id):addFavorite(id);
	}

function setOnFavoritesChanged(func) {
	onFavoritesChanged=func;
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const marked = require('marked');
const renderer = new marked.Renderer();

renderer.code = function(code, lang) {
    code = code.replace(/"/g, '"'); // replace double quotes with "

    return `<codeblock content.one-way="'${code}'" type.one-way="'${lang}'"></codeblock>`;
}

let pages = [];

const files = ['quickstart', 'events', 'awards'];
for (let fileName of files) {
    const rawData = fs.readFileSync(path.resolve(__dirname, 'source', fileName + '.md'), {
        encoding: 'utf8'
    });
    const tokens = marked.lexer(rawData);

    let pageTitle = '';
    for (let token of tokens) {
        // heading 1
        if (token.type === 'heading' && token.depth === 1) {
            pageTitle = token.text;
        }
    }

    pages.push({
        title: pageTitle,
        id: fileName,
        file: fileName + '.html'
    });

    if (!fs.existsSync(path.resolve(__dirname, 'build'))) {
        fs.mkdirSync(path.resolve(__dirname, 'build'));
    }

    // Add HTML fluff so the docs site can interpret it
    // HACK The require tag is an implementation detail of the docs site, which should not be bleeding over but doesn't seem to work any other way
    let html = `<template>\n<require from="../../codeblock"></require>\n${marked(rawData, {renderer})}</template>`;

    fs.writeFileSync(path.resolve(__dirname, 'build', fileName + '.html'), html);
}

fs.writeFileSync(path.resolve(__dirname, 'build', 'sponge-client-docs.json'), JSON.stringify(pages, null, 4), 'utf-8');
<commit_msg>Data persistence docs<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const marked = require('marked');
const renderer = new marked.Renderer();

renderer.code = function(code, lang) {
    code = code.replace(/"/g, '"'); // replace double quotes with "

    return `<codeblock content.one-way="'${code}'" type.one-way="'${lang}'"></codeblock>`;
}

let pages = [];

const files = ['quickstart', 'events', 'awards', 'persistence'];
for (let fileName of files) {
    const rawData = fs.readFileSync(path.resolve(__dirname, 'source', fileName + '.md'), {
        encoding: 'utf8'
    });
    const tokens = marked.lexer(rawData);

    let pageTitle = '';
    for (let token of tokens) {
        // heading 1
        if (token.type === 'heading' && token.depth === 1) {
            pageTitle = token.text;
        }
    }

    pages.push({
        title: pageTitle,
        id: fileName,
        file: fileName + '.html'
    });

    if (!fs.existsSync(path.resolve(__dirname, 'build'))) {
        fs.mkdirSync(path.resolve(__dirname, 'build'));
    }

    // Add HTML fluff so the docs site can interpret it
    // HACK The require tag is an implementation detail of the docs site, which should not be bleeding over but doesn't seem to work any other way
    let html = `<template>\n<require from="../../codeblock"></require>\n${marked(rawData, {renderer})}</template>`;

    fs.writeFileSync(path.resolve(__dirname, 'build', fileName + '.html'), html);
}

fs.writeFileSync(path.resolve(__dirname, 'build', 'sponge-client-docs.json'), JSON.stringify(pages, null, 4), 'utf-8');
<|endoftext|>


<commit_before>(function($) {
"use strict";

if (Echo.AppServer.Dashboard.isDefined("Echo.Apps.VolumeOverTime.Dashboard")) return;

var dashboard = Echo.AppServer.Dashboard.manifest("Echo.Apps.VolumeOverTime.Dashboard");

dashboard.inherits = Echo.Utils.getComponent("Echo.AppServer.Dashboards.AppSettings");

dashboard.labels = {
	"failedToFetchToken": "Failed to fetch customer DataServer token: {reason}"
};

dashboard.mappings = {
	"dependencies.appkey": {
		"key": "dependencies.StreamServer.appkey"
	}
};

dashboard.dependencies = [{
	"url": "{config:cdnBaseURL.apps.appserver}/controls/configurator.js",
	"control": "Echo.AppServer.Controls.Configurator"
}, {
	"url": "{config:cdnBaseURL.apps.dataserver}/full.pack.js",
	"control": "Echo.DataServer.Controls.Pack"
}];

dashboard.config = {
	"appkeys": []
};

dashboard.config.ecl = [{
	"name": "targetURL",
	"component": "Echo.DataServer.Controls.Dashboard.DataSourceGroup",
	"type": "string",
	"required": true,
	"config": {
		"title": "",
		"labels": {
			"dataserverBundleName": "Echo Historical Volume Auto-Generated Bundle for {instanceName}"
		},
		"apiBaseURLs": {
			"DataServer": "{%= apiBaseURLs.DataServer %}"
		}
	}
}, {
	"component": "Group",
	"name": "presentation",
	"type": "object",
	"config": {
		"title": "Presentation"
	},
	"items": [{
		"component": "Select",
		"name": "visualization",
		"type": "string",
		"default": "bar",
		"config": {
			"title": "Chart style",
			"desc": "Specifies the chart type to be used",
			"options": [{
				"title": "Bar Chart",
				"value": "bar"
			}, {
				"title": "Line Chart",
				"value": "line"
			}]
		}
	}, {
		"component": "Input",
		"name": "maxIntervals",
		"type": "number",
		"default": 10,
		"config": {
			"title": "Maximum slices",
			"desc": "Specifies a maximum number of time slices for the chart"
		}
	}, {
	"component": "Input",
		"name": "maxWidth",
		"type": "number",
		"default": 700,
		"config": {
			"title": "Maximum width",
			"desc": "Specifies a maximum width (in pixels) of an App container",
			"data": {"sample": 700}
		}
	}, {
		"component": "Input",
		"name": "fillColor",
		"type": "string",
		"config": {
			"title": "Fill color",
			"desc": "Specifies the primary fill color of the chart",
			"data": {"sample": "#D8D8D8"}
		}
	}, {
		"component": "Input",
		"name": "strokeColor",
		"type": "string",
		"config": {
			"title": "Stroke color",
			"desc": "Specifies border color/line color of the chart",
			"data": {"sample": "#C0C0C0"}
		}
	}, {
		"component": "Input",
		"name": "highlightFill",
		"type": "string",
		"config": {
			"title": "Hover fill color",
			"desc": "Specifies primary fill color of the chart when mouse is hovering over it (for Bar Chart only)",
			"data": {"sample": "#C0C0C0"}
		}
	}, {
		"component": "Input",
		"name": "highlightStroke",
		"type": "string",
		"config": {
			"title": "Hover stroke color",
			"desc": "Specifies stroke color of the chart when mouse is hovering over it (for Bar Chart only)",
			"data": {"sample": "#C0C0C0"}
		}
	}]
}, {
	"component": "Group",
	"name": "dependencies",
	"type": "object",
	"config": {
		"title": "Dependencies"
	},
	"items": [{
		"component": "Select",
		"name": "appkey",
		"type": "string",
		"config": {
			"title": "StreamServer application key",
			"desc": "Specifies the application key for this instance",
			"options": []
		}
	}]
}];

dashboard.init = function() {
	var self = this, parent = $.proxy(this.parent, this);
	this._fetchDataServerToken(function() {
		self._requestData(function() {
			self.config.set("ecl", self._prepareECL(self.config.get("ecl")));
			parent();
		});
	});
};

dashboard.methods.declareInitialConfig = function() {
	var keys = this.get("appkeys", []);
	return {
		"targetURL": this._assembleTargetURL(),
		"dependencies": {
			"StreamServer": {
				"appkey": keys.length ? keys[0].key : undefined
			}
		}
	};
};

dashboard.methods._requestData = function(callback) {
	var self = this;
	var customerId = this.config.get("data.customer.id");
	var deferreds = [];
	var request = this.config.get("request");

	var requests = [{
		"name": "appkeys",
		"endpoint": "customer/" + customerId + "/appkeys"
	}, {
		"name": "domains",
		"endpoint": "customer/" + customerId + "/domains"
	}];
	$.map(requests, function(req) {
		var deferredId = deferreds.push($.Deferred()) - 1;
		request({
			"endpoint": req.endpoint,
			"success": function(response) {
				self.set(req.name, response);
				deferreds[deferredId].resolve();
			}
		});
	});
	$.when.apply($, deferreds).done(callback);
};

dashboard.methods._prepareECL = function(items) {
	var self = this;

	var instructions = {
		"targetURL": function(item) {
			item.config = $.extend({
				"instanceName": self.get("data.instance.name"),
				"domains": self.get("domains"),
				"apiToken": self.config.get("dataserverToken"),
				"valueHandler": function() {
					return self._assembleTargetURL();
				}
			}, item.config);
			return item;
		},
		"dependencies.appkey": function(item) {
			item.config.options = $.map(self.get("appkeys"), function(appkey) {
				return {
					"title": appkey.key,
					"value": appkey.key
				};
			});
			return item;
		}
	};
	return (function traverse(items, path) {
		return $.map(items, function(item) {
			var _path = path ? path + "." + item.name : item.name;
			if (item.type === "object" && item.items) {
				item.items = traverse(item.items, _path);
			} else if (instructions[_path]) {
				item = instructions[_path](item);
			}
			return item;
		});
	})(items, "");
};

dashboard.methods._fetchDataServerToken = function(callback) {
	var self = this;
	Echo.AppServer.API.request({
		"endpoint": "customer/{id}/subscriptions",
		"id": this.get("data.customer").id,
		"onData": function(response) {
			var token = Echo.Utils.foldl("", response, function(subscription, acc) {
				return subscription.product.name === "dataserver"
					? subscription.extra.token
					: acc;
			});
			if (token) {
				self.config.set("dataserverToken", token);
				callback.call(self);
			} else {
				self._displayError(
					self.labels.get("failedToFetchToken", {
						"reason": self.labels.get("dataserverSubscriptionNotFound")
					})
				);
			}
		},
		"onError": function(response) {
			self._displayError(self.labels.get("failedToFetchToken", {"reason": response.data.msg}));
		}
	}).send();
};

dashboard.methods._displayError = function(message) {
	this.showMessage({
		"type": "error",
		"message": message,
		"target": this.config.get("target")
	});
	this.ready();
};

dashboard.methods._assembleTargetURL = function() {
	var re =  new RegExp("\/" + this.get("data.instance.name") + "$");
	var targetURL = this.get("data.instance.config.targetURL");

	if (!targetURL || !targetURL.match(re)) {
		targetURL =  "http://" + this.get("domains")[0] + "/social-source-input/" + this.get("data.instance.name");
	}

	return targetURL;
};

Echo.AppServer.Dashboard.create(dashboard);

})(Echo.jQuery);
<commit_msg>Fix whitespaces<commit_after>(function($) {
"use strict";

if (Echo.AppServer.Dashboard.isDefined("Echo.Apps.VolumeOverTime.Dashboard")) return;

var dashboard = Echo.AppServer.Dashboard.manifest("Echo.Apps.VolumeOverTime.Dashboard");

dashboard.inherits = Echo.Utils.getComponent("Echo.AppServer.Dashboards.AppSettings");

dashboard.labels = {
	"failedToFetchToken": "Failed to fetch customer DataServer token: {reason}"
};

dashboard.mappings = {
	"dependencies.appkey": {
		"key": "dependencies.StreamServer.appkey"
	}
};

dashboard.dependencies = [{
	"url": "{config:cdnBaseURL.apps.appserver}/controls/configurator.js",
	"control": "Echo.AppServer.Controls.Configurator"
}, {
	"url": "{config:cdnBaseURL.apps.dataserver}/full.pack.js",
	"control": "Echo.DataServer.Controls.Pack"
}];

dashboard.config = {
	"appkeys": []
};

dashboard.config.ecl = [{
	"name": "targetURL",
	"component": "Echo.DataServer.Controls.Dashboard.DataSourceGroup",
	"type": "string",
	"required": true,
	"config": {
		"title": "",
		"labels": {
			"dataserverBundleName": "Echo Historical Volume Auto-Generated Bundle for {instanceName}"
		},
		"apiBaseURLs": {
			"DataServer": "{%= apiBaseURLs.DataServer %}"
		}
	}
}, {
	"component": "Group",
	"name": "presentation",
	"type": "object",
	"config": {
		"title": "Presentation"
	},
	"items": [{
		"component": "Select",
		"name": "visualization",
		"type": "string",
		"default": "bar",
		"config": {
			"title": "Chart style",
			"desc": "Specifies the chart type to be used",
			"options": [{
				"title": "Bar Chart",
				"value": "bar"
			}, {
				"title": "Line Chart",
				"value": "line"
			}]
		}
	}, {
		"component": "Input",
		"name": "maxIntervals",
		"type": "number",
		"default": 10,
		"config": {
			"title": "Maximum slices",
			"desc": "Specifies a maximum number of time slices for the chart"
		}
	}, {
	"component": "Input",
		"name": "maxWidth",
		"type": "number",
		"default": 700,
		"config": {
			"title": "Maximum width",
			"desc": "Specifies a maximum width (in pixels) of an App container",
			"data": {"sample": 700}
		}
	}, {
		"component": "Input",
		"name": "fillColor",
		"type": "string",
		"config": {
			"title": "Fill color",
			"desc": "Specifies the primary fill color of the chart",
			"data": {"sample": "#D8D8D8"}
		}
	}, {
		"component": "Input",
		"name": "strokeColor",
		"type": "string",
		"config": {
			"title": "Stroke color",
			"desc": "Specifies border color/line color of the chart",
			"data": {"sample": "#C0C0C0"}
		}
	}, {
		"component": "Input",
		"name": "highlightFill",
		"type": "string",
		"config": {
			"title": "Hover fill color",
			"desc": "Specifies primary fill color of the chart when mouse is hovering over it (for Bar Chart only)",
			"data": {"sample": "#C0C0C0"}
		}
	}, {
		"component": "Input",
		"name": "highlightStroke",
		"type": "string",
		"config": {
			"title": "Hover stroke color",
			"desc": "Specifies stroke color of the chart when mouse is hovering over it (for Bar Chart only)",
			"data": {"sample": "#C0C0C0"}
		}
	}]
}, {
	"component": "Group",
	"name": "dependencies",
	"type": "object",
	"config": {
		"title": "Dependencies"
	},
	"items": [{
		"component": "Select",
		"name": "appkey",
		"type": "string",
		"config": {
			"title": "StreamServer application key",
			"desc": "Specifies the application key for this instance",
			"options": []
		}
	}]
}];

dashboard.init = function() {
	var self = this, parent = $.proxy(this.parent, this);
	this._fetchDataServerToken(function() {
		self._requestData(function() {
			self.config.set("ecl", self._prepareECL(self.config.get("ecl")));
			parent();
		});
	});
};

dashboard.methods.declareInitialConfig = function() {
	var keys = this.get("appkeys", []);
	return {
		"targetURL": this._assembleTargetURL(),
		"dependencies": {
			"StreamServer": {
				"appkey": keys.length ? keys[0].key : undefined
			}
		}
	};
};

dashboard.methods._requestData = function(callback) {
	var self = this;
	var customerId = this.config.get("data.customer.id");
	var deferreds = [];
	var request = this.config.get("request");

	var requests = [{
		"name": "appkeys",
		"endpoint": "customer/" + customerId + "/appkeys"
	}, {
		"name": "domains",
		"endpoint": "customer/" + customerId + "/domains"
	}];
	$.map(requests, function(req) {
		var deferredId = deferreds.push($.Deferred()) - 1;
		request({
			"endpoint": req.endpoint,
			"success": function(response) {
				self.set(req.name, response);
				deferreds[deferredId].resolve();
			}
		});
	});
	$.when.apply($, deferreds).done(callback);
};

dashboard.methods._prepareECL = function(items) {
	var self = this;

	var instructions = {
		"targetURL": function(item) {
			item.config = $.extend({
				"instanceName": self.get("data.instance.name"),
				"domains": self.get("domains"),
				"apiToken": self.config.get("dataserverToken"),
				"valueHandler": function() {
					return self._assembleTargetURL();
				}
			}, item.config);
			return item;
		},
		"dependencies.appkey": function(item) {
			item.config.options = $.map(self.get("appkeys"), function(appkey) {
				return {
					"title": appkey.key,
					"value": appkey.key
				};
			});
			return item;
		}
	};
	return (function traverse(items, path) {
		return $.map(items, function(item) {
			var _path = path ? path + "." + item.name : item.name;
			if (item.type === "object" && item.items) {
				item.items = traverse(item.items, _path);
			} else if (instructions[_path]) {
				item = instructions[_path](item);
			}
			return item;
		});
	})(items, "");
};

dashboard.methods._fetchDataServerToken = function(callback) {
	var self = this;
	Echo.AppServer.API.request({
		"endpoint": "customer/{id}/subscriptions",
		"id": this.get("data.customer").id,
		"onData": function(response) {
			var token = Echo.Utils.foldl("", response, function(subscription, acc) {
				return subscription.product.name === "dataserver"
					? subscription.extra.token
					: acc;
			});
			if (token) {
				self.config.set("dataserverToken", token);
				callback.call(self);
			} else {
				self._displayError(
					self.labels.get("failedToFetchToken", {
						"reason": self.labels.get("dataserverSubscriptionNotFound")
					})
				);
			}
		},
		"onError": function(response) {
			self._displayError(self.labels.get("failedToFetchToken", {"reason": response.data.msg}));
		}
	}).send();
};

dashboard.methods._displayError = function(message) {
	this.showMessage({
		"type": "error",
		"message": message,
		"target": this.config.get("target")
	});
	this.ready();
};

dashboard.methods._assembleTargetURL = function() {
	var re = new RegExp("\/" + this.get("data.instance.name") + "$");
	var targetURL = this.get("data.instance.config.targetURL");

	if (!targetURL || !targetURL.match(re)) {
		targetURL = "http://" + this.get("domains")[0] + "/social-source-input/" + this.get("data.instance.name");
	}

	return targetURL;
};

Echo.AppServer.Dashboard.create(dashboard);

})(Echo.jQuery);
<|endoftext|>


<commit_before>import queryString from 'query-string';
import { stringifyRangeFilters, parseRangeFilters } from './range-filters';
import { stringifyCallTreeFilters, parseCallTreeFilters } from './call-tree-filters';

// {
//   // general:
//   dataSource: 'from-addon', 'local', 'public',
//   hash: '' or 'aoeurschsaoeuch',
//   selectedTab: 'summary' or 'calltree' or ...,
//   rangeFilters: [] or [{ start, end }, ...],
//   selectedThread: 0 or 1 or ...,
//
//   // only when selectedTab === 'calltree':
//   callTreeSearchString: '' or '::RunScript' or ...,
//   callTreeFilters: [[], [{type:'prefix', matchJSOnly:true, prefixFuncs:[1,3,7]}, {}, ...], ...], // one per thread
//   jsOnly: false or true,
//   invertCallstack: false or true,
// }

function dataSourceDirs(urlState) {
  const { dataSource } = urlState;
  switch (dataSource) {
    case 'from-addon':
      return ['from-addon'];
    case 'local':
      return ['local', urlState.hash];
    case 'public':
      return ['public', urlState.hash];
    default:
      return [];
  }
}

export function urlFromState(urlState) {
  const { dataSource } = urlState;
  if (dataSource === 'none') {
    return '/';
  }
  const pathname = '/' + [
    ...dataSourceDirs(urlState),
    urlState.selectedTab,
  ].join('/') + '/';
  const query = Object.assign({
    range: stringifyRangeFilters(urlState.rangeFilters) || undefined,
    thread: `${urlState.selectedThread}`,
  }, urlState.selectedTab === 'calltree' ? {
    search: urlState.callTreeSearchString || undefined,
    invertCallstack: urlState.invertCallstack ? null : undefined,
    jsOnly: urlState.jsOnly ? null : undefined,
    callTreeFilters: stringifyCallTreeFilters(urlState.callTreeFilters[urlState.selectedThread]) || undefined,
  } : {});
  const qString = queryString.stringify(query);
  return pathname + (qString ? '?' + qString : '');
}

export function stateFromCurrentLocation() {
  const pathname = window.location.pathname;
  const qString = window.location.search.substr(1);
  const hash = window.location.hash;
  const query = queryString.parse(qString);

  if (pathname === '/') {
    const legacyQuery = Object.assign({}, query, queryString.parse(hash));
    if ('filter' in legacyQuery) {
      const filters = JSON.parse(legacyQuery.filter);
      // We can't convert these parameters to the new URL parameters here
      // because they're relative to different things - the legacy range
      // filters were relative to profile.meta.startTime, and the new
      // rangeFilters param is relative to
      // getTimeRangeIncludingAllThreads(profile).start.
      // So we stuff this information into a global here, and then later,
      // once we have the profile, we convert that information into URL params
      // again. This is not pretty.
      window.legacyRangeFilters =
        filters.filter(f => f.type === 'RangeSampleFilter').map(({ start, end }) => ({ start, end }));

      return {
        dataSource: 'public',
        hash: ('report' in legacyQuery) ? legacyQuery.report : '',
        selectedTab: 'calltree',
        rangeFilters: [],
        selectedThread: 0,
        callTreeSearchString: '',
        callTreeFilters: {},
        jsOnly: false,
        invertCallstack: false,
      };
    }
  }

  const dirs = pathname.split('/').filter(d => d);
  const dataSource = dirs[0] || 'none';
  if (!['none', 'from-addon', 'local', 'public'].includes(dataSource)) {
    throw new Error('unexpected data source');
  }
  const needHash = ['local', 'public'].includes(dataSource);
  const selectedThread = query.thread !== undefined ? +query.thread : 0;
  return {
    dataSource,
    hash: needHash ? dirs[1] : '',
    selectedTab: (needHash ? dirs[2] : dirs[1]) || 'calltree',
    rangeFilters: query.range ? parseRangeFilters(query.range) : [],
    selectedThread: selectedThread,
    callTreeSearchString: query.search || '',
    callTreeFilters: {
      [selectedThread]: query.callTreeFilters ? parseCallTreeFilters(query.callTreeFilters) : [],
    },
    jsOnly: query.jsOnly !== undefined,
    invertCallstack: query.invertCallstack !== undefined,
  };
}
<commit_msg>Make legacy URLs work again.<commit_after>import queryString from 'query-string';
import { stringifyRangeFilters, parseRangeFilters } from './range-filters';
import { stringifyCallTreeFilters, parseCallTreeFilters } from './call-tree-filters';

// {
//   // general:
//   dataSource: 'from-addon', 'local', 'public',
//   hash: '' or 'aoeurschsaoeuch',
//   selectedTab: 'summary' or 'calltree' or ...,
//   rangeFilters: [] or [{ start, end }, ...],
//   selectedThread: 0 or 1 or ...,
//
//   // only when selectedTab === 'calltree':
//   callTreeSearchString: '' or '::RunScript' or ...,
//   callTreeFilters: [[], [{type:'prefix', matchJSOnly:true, prefixFuncs:[1,3,7]}, {}, ...], ...], // one per thread
//   jsOnly: false or true,
//   invertCallstack: false or true,
// }

function dataSourceDirs(urlState) {
  const { dataSource } = urlState;
  switch (dataSource) {
    case 'from-addon':
      return ['from-addon'];
    case 'local':
      return ['local', urlState.hash];
    case 'public':
      return ['public', urlState.hash];
    default:
      return [];
  }
}

export function urlFromState(urlState) {
  const { dataSource } = urlState;
  if (dataSource === 'none') {
    return '/';
  }
  const pathname = '/' + [
    ...dataSourceDirs(urlState),
    urlState.selectedTab,
  ].join('/') + '/';
  const query = Object.assign({
    range: stringifyRangeFilters(urlState.rangeFilters) || undefined,
    thread: `${urlState.selectedThread}`,
  }, urlState.selectedTab === 'calltree' ? {
    search: urlState.callTreeSearchString || undefined,
    invertCallstack: urlState.invertCallstack ? null : undefined,
    jsOnly: urlState.jsOnly ? null : undefined,
    callTreeFilters: stringifyCallTreeFilters(urlState.callTreeFilters[urlState.selectedThread]) || undefined,
  } : {});
  const qString = queryString.stringify(query);
  return pathname + (qString ? '?' + qString : '');
}

export function stateFromCurrentLocation() {
  const pathname = window.location.pathname;
  const qString = window.location.search.substr(1);
  const hash = window.location.hash;
  const query = queryString.parse(qString);

  if (pathname === '/') {
    const legacyQuery = Object.assign({}, query, queryString.parse(hash));
    if ('report' in legacyQuery) {
      if ('filter' in legacyQuery) {
        const filters = JSON.parse(legacyQuery.filter);
        // We can't convert these parameters to the new URL parameters here
        // because they're relative to different things - the legacy range
        // filters were relative to profile.meta.startTime, and the new
        // rangeFilters param is relative to
        // getTimeRangeIncludingAllThreads(profile).start.
        // So we stuff this information into a global here, and then later,
        // once we have the profile, we convert that information into URL params
        // again. This is not pretty.
        window.legacyRangeFilters =
          filters.filter(f => f.type === 'RangeSampleFilter').map(({ start, end }) => ({ start, end }));
      }
      return {
        dataSource: 'public',
        hash: legacyQuery.report,
        selectedTab: 'calltree',
        rangeFilters: [],
        selectedThread: 0,
        callTreeSearchString: '',
        callTreeFilters: {},
        jsOnly: false,
        invertCallstack: false,
      };
    }
  }

  const dirs = pathname.split('/').filter(d => d);
  const dataSource = dirs[0] || 'none';
  if (!['none', 'from-addon', 'local', 'public'].includes(dataSource)) {
    throw new Error('unexpected data source');
  }
  const needHash = ['local', 'public'].includes(dataSource);
  const selectedThread = query.thread !== undefined ? +query.thread : 0;
  return {
    dataSource,
    hash: needHash ? dirs[1] : '',
    selectedTab: (needHash ? dirs[2] : dirs[1]) || 'calltree',
    rangeFilters: query.range ? parseRangeFilters(query.range) : [],
    selectedThread: selectedThread,
    callTreeSearchString: query.search || '',
    callTreeFilters: {
      [selectedThread]: query.callTreeFilters ? parseCallTreeFilters(query.callTreeFilters) : [],
    },
    jsOnly: query.jsOnly !== undefined,
    invertCallstack: query.invertCallstack !== undefined,
  };
}
<|endoftext|>


<commit_before>
const limit = require('../../builders/limit');
const project = require('../../builders/project');

module.exports = {

  /**
   * Returns all rocket info
   */
  all: async ctx => {
    const data = await global.db
      .collection('ship')
      .find({})
      .project(project(ctx.request.query))
      .sort({ first_flight: 1 })
      .limit(limit(ctx.request.query))
      .toArray();
    ctx.body = data;
  },

  /**
   * Returns specific rocket info
   */
  specific: async ctx => {
    const data = await global.db
      .collection('ship')
      .find({ id: ctx.params.rocket })
      .project(project(ctx.request.query))
      .toArray();
    ctx.body = data[0];
  },

};
<commit_msg>corrected query params for ships<commit_after>
const limit = require('../../builders/limit');
const project = require('../../builders/project');

module.exports = {

  /**
   * Returns all ship info
   */
  all: async ctx => {
    const data = await global.db
      .collection('ship')
      .find({})
      .project(project(ctx.request.query))
      .sort({ ship_id: 1 })
      .limit(limit(ctx.request.query))
      .toArray();
    ctx.body = data;
  },

  /**
   * Returns specific ship info
   */
  specific: async ctx => {
    const data = await global.db
      .collection('ship')
      .find({ id: ctx.params.ship })
      .project(project(ctx.request.query))
      .toArray();
    ctx.body = data[0];
  },

};
<|endoftext|>


<commit_before><commit_msg>Исправлен баг, что при изменении типа обтекания таблицы, таблица смещалась по горизонтали (баг 18945).<commit_after><|endoftext|>


<commit_before>var vscode = require('vscode');

var bslProviders = require('./providers');

function activate(context) {

    context.subscriptions.push(vscode.languages.registerDocumentSymbolProvider("bsl", new bslProviders.DocumentSymbolProvider()));

    context.subscriptions.push(vscode.languages.registerDefinitionProvider("bsl", new bslProviders.DefinitionProvider()));

    vscode.languages.setLanguageConfiguration("bsl", {

        indentationRules: {
            decreaseIndentPattern: /^\s*(конецесли|конеццикла|конецпроцедуры|конецфункции|иначе|иначеесли|конецпопытки|исключение|endif|enddo|endprocedure|endfunction|else|elseif|endtry|except).*$/i,
            increaseIndentPattern: /^\s*(пока|процедура|функция|если|иначе|иначеесли|попытка|исключение|для|while|procedure|function|if|else|elseif|try|for)[^;]*$/i
        },
        comments: {
            lineComment: '//'
        },
        onEnterRules: [
            {
                beforeText: /^\s*\|([^\"]|"[^\"]*")*$/,
                action: { indentAction: vscode.IndentAction.None, appendText: '|' }
            },
            {
                beforeText: /^([^\|\"]|"[^\"]*")*\"[^\"]*$/,
                action: { indentAction: vscode.IndentAction.None, appendText: '|' }
            }

        ]

    });
}

exports.activate = activate;
<commit_msg>Fix xDrivenDevelopment/1c-syntax#79. Настройка отступов<commit_after>var vscode = require('vscode');

var bslProviders = require('./providers');

function activate(context) {

    context.subscriptions.push(vscode.languages.registerDocumentSymbolProvider("bsl", new bslProviders.DocumentSymbolProvider()));

    context.subscriptions.push(vscode.languages.registerDefinitionProvider("bsl", new bslProviders.DefinitionProvider()));

    vscode.languages.setLanguageConfiguration("bsl", {

        indentationRules: {
            decreaseIndentPattern: /^\s*(конецесли|конеццикла|конецпроцедуры|конецфункции|иначе|иначеесли|конецпопытки|исключение|endif|enddo|endprocedure|endfunction|else|elseif|endtry|except).*$/i,
            increaseIndentPattern: /^\s*(пока|процедура|функция|если|иначе|иначеесли|попытка|исключение|для|while|procedure|function|if|else|elseif|try|for)[^;]*$/i
        },
        comments: {
            lineComment: '//'
        },
        onEnterRules: [
            {
                beforeText: /^\s*\|([^\"]|"[^\"]*")*$/,
                action: { indentAction: vscode.IndentAction.None, appendText: '|' }
            },
            {
                beforeText: /^([^\|\"]|"[^\"]*")*\"[^\"]*$/,
                action: { indentAction: vscode.IndentAction.None, appendText: '|' }
            }

        ]

    });

    context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(function (textEditor) {
            applyConfigToTextEditor(textEditor);
    }));
    applyConfigToTextEditor(vscode.window.activeTextEditor);

}

exports.activate = activate;

function applyConfigToTextEditor(textEditor) {
  if (textEditor == null) {
      return;
  }
  var newOptions = {
    "insertSpaces" : false,
    "tabSize" : 4
  };
  var defaultOptions = {
    "insertSpaces" : vscode.workspace.getConfiguration("editor").get("insertSpaces"),
    "tabSize" : vscode.workspace.getConfiguration("editor").get("tabSize")
  };
  if (textEditor.document.languageId == "bsl") {
    if (textEditor.options.insertSpaces == defaultOptions.insertSpaces && (textEditor.options.tabSize == defaultOptions.tabSize || defaultOptions.tabSize == "auto")) {
      textEditor.options = newOptions;
    }
  } else {
    if (textEditor.options.insertSpaces == newOptions.insertSpaces && textEditor.options.tabSize == newOptions.tabSize) {
      textEditor.options = defaultOptions
    }
  }
}
<|endoftext|>


<commit_before>var counter = 0;//set this to what ever you want the start # to be
// var ducks = data.duckCount;
	countUP();//call the function once
	function countUP () {
      counter++;//increment the counter by 1
      if (counter < 4705) {
         setTimeout ( "countUP()", 1 );//runs itsself after 1000 miliseconds
      }
      jQuery( ".counter" ).html( "
"+ counter +"
" );
		// console.log(counter);
	}<commit_msg>not gonna do it right now<commit_after>var counter = 0;//set this to what ever you want the start # to be
// var ducks = data.duckCount;
	// countUP();//call the function once
	function countUP () {
      counter++;//increment the counter by 1
      if (counter < 4705) {
         setTimeout ( "countUP()", 1 );//runs itsself after 1000 miliseconds
      }
      jQuery( ".counter" ).html( "
"+ counter +"
" );
		// console.log(counter);
	}<|endoftext|>


<commit_before>import Backbone from 'backbone';

/**
 * This model is used to store the relevant values for map views (2D or 3D), such as camera options
 *
 * @memberof core/models
 *
 * @param {Object} attributes The attributes of the model instance
 * @param {Number[]} [attributes.center] The center of the view
 * @param {Number} [attributes.zoom] The zoomlevel of the view
 * @param {string} [attributes.tool] The currently selected tool
 * @param {bool} [attributes.isZooming] Indicator whether the map is currently zooming
 * @param {bool} [attributes.isPanning] Indicator whether the map is currently panning
 * @param {Number} [attributes.heading] The heading
 * @param {Number} [attributes.pitch] The pitch
 * @param {Number} [attributes.roll] The roll
 * @param {string?} [attributes.displayMode] The display mode of the map. One of 'map',
                                             'columbus' and 'globe'
 */

class MapModel extends Backbone.Model {
  validate(attrs) {
    if ([null, 'map', 'columbus', 'globe'].indexOf(attrs.displayMode) !== -1) {
      return 'invalid display mode';
    }
    return null;
  }

  show(featureOrExtent) {
    this.trigger('show', featureOrExtent);
  }
}

MapModel.prototype.defaults = {
  // the current center and zoom of the map view
  center: [0, 0],
  bbox: [0, 0, 1, 1],
  area: null,
  zoom: 2,
  minZoom: 0,
  maxZoom: 28,

  // the current start/end time selection
  time: [null, null],
  extendedTime: null,

  tool: null,

  // properties to indicate that the map is currently panned or zoomed by the user
  isZooming: false,
  isPanning: false,

  // for 3D viewers
  heading: 0,
  pitch: 0,
  roll: 0,

  displayMode: null, // one of 'map', 'columbus', 'globe'

  highlightFeature: null,
};

export default MapModel;
<commit_msg>Adding method to show the given time.<commit_after>import Backbone from 'backbone';

/**
 * This model is used to store the relevant values for map views (2D or 3D), such as camera options
 *
 * @memberof core/models
 *
 * @param {Object} attributes The attributes of the model instance
 * @param {Number[]} [attributes.center] The center of the view
 * @param {Number} [attributes.zoom] The zoomlevel of the view
 * @param {string} [attributes.tool] The currently selected tool
 * @param {bool} [attributes.isZooming] Indicator whether the map is currently zooming
 * @param {bool} [attributes.isPanning] Indicator whether the map is currently panning
 * @param {Number} [attributes.heading] The heading
 * @param {Number} [attributes.pitch] The pitch
 * @param {Number} [attributes.roll] The roll
 * @param {string?} [attributes.displayMode] The display mode of the map. One of 'map',
                                             'columbus' and 'globe'
 */

class MapModel extends Backbone.Model {
  validate(attrs) {
    if ([null, 'map', 'columbus', 'globe'].indexOf(attrs.displayMode) !== -1) {
      return 'invalid display mode';
    }
    return null;
  }

  show(featureOrExtent) {
    this.trigger('show', featureOrExtent);
  }

  showTime(timeExtent) {
    this.trigger('show:time', timeExtent);
  }
}

MapModel.prototype.defaults = {
  // the current center and zoom of the map view
  center: [0, 0],
  bbox: [0, 0, 1, 1],
  area: null,
  zoom: 2,
  minZoom: 0,
  maxZoom: 28,

  // the current start/end time selection
  time: [null, null],
  extendedTime: null,

  tool: null,

  // properties to indicate that the map is currently panned or zoomed by the user
  isZooming: false,
  isPanning: false,

  // for 3D viewers
  heading: 0,
  pitch: 0,
  roll: 0,

  displayMode: null, // one of 'map', 'columbus', 'globe'

  highlightFeature: null,
};

export default MapModel;
<|endoftext|>


<commit_before>var isInt = require('./helper').isInt;

var Fraction = function(a, b) {
    if (isInt(a) && isInt(b) && b) {
        this.numer = a;
        this.denom = b;
    }
};

var gcd = require('./helper').gcd;
var lcm = require('./helper').lcm;

Fraction.prototype.copy = function() {
    return new Fraction(this.numer, this.denom);
};

Fraction.prototype.reduce = function() {
    var copy = this.copy();

    var g = gcd(copy.numer, copy.denom);
    copy.numer = copy.numer / g;
    copy.denom = copy.denom / g;

    if (Math.sign(copy.denom) == -1 && Math.sign(copy.numer) == 1) {
        copy.numer *= -1;
        copy.denom *= -1;
    }

    return copy;
};

Fraction.prototype.add = function(f) {
    var a, b;

    if (f instanceof Fraction) {
        a = f.numer;
        b = f.denom;
    } else if (isInt(f)) {
        a = f;
        b = 1;
    }

    var copy = this.copy();

    if (this.denom == b) {
        copy.numer += a;
    } else {
        var m = lcm(copy.denom, b);
        var thisM = m / copy.denom;
        var otherM = m / b;

        copy.numer *= thisM;
        copy.denom *= thisM;

        a *= otherM;

        copy.numer += a;
    }

    return copy;
};

Fraction.prototype.subtract = function(f) {
    var copy = this.copy();

    if (f instanceof Fraction) {
        return copy.add(new Fraction(-f.numer, f.denom));
    } else if (isInt(f)) {
        return copy.add(new Fraction(-f, 1));
    }
};

Fraction.prototype.multiply = function(f) {
    var a, b;

    if (f instanceof Fraction) {
        a = f.numer;
        b = f.denom;
    } else if (isInt(f) && f) {
        a = f;
        b = 1;
    } else if (f == 0) {
        a = 0;
        b = 1;
    }

    var copy = this.copy();

    copy.numer *= a;
    copy.denom *= b;

    return copy;
};

Fraction.prototype.divide = function(f) {
    if (f == 0) {
        return;
    }

    var copy = this.copy();

    if (f instanceof Fraction) {
        return copy.multiply(new Fraction(f.denom, f.numer));
    } else if (isInt(f)) {
        return copy.multiply(new Fraction(1, f));
    }
};

Fraction.prototype.abs = function() {
    var copy = this.copy();
    copy = copy.reduce();
    copy.numer = Math.abs(copy.numer);
    return copy;
};

Fraction.prototype.decimal = function() {
    return this.numer / this.denom;
};

Fraction.prototype.print = function() {
    if (this.numer == 0) {
        return "0";
    } else if (this.denom == 1) {
        return this.numer;
    } else {
        return this.numer + "/" + this.denom;
    }
};

Fraction.prototype.tex = function() {
    if (this.numer == 0) {
        return "0";
    } else if (this.denom == 1) {
        return this.numer;
    } else {
        return "\\frac{" + this.numer + "}{" + this.denom + "}";
    }
};

module.exports = Fraction;<commit_msg>When denominator is 1 or -1, coerce numerator to string when printing<commit_after>var isInt = require('./helper').isInt;

var Fraction = function(a, b) {
    if (isInt(a) && isInt(b) && b) {
        this.numer = a;
        this.denom = b;
    }
};

var gcd = require('./helper').gcd;
var lcm = require('./helper').lcm;

Fraction.prototype.copy = function() {
    return new Fraction(this.numer, this.denom);
};

Fraction.prototype.reduce = function() {
    var copy = this.copy();

    var g = gcd(copy.numer, copy.denom);
    copy.numer = copy.numer / g;
    copy.denom = copy.denom / g;

    if (Math.sign(copy.denom) == -1 && Math.sign(copy.numer) == 1) {
        copy.numer *= -1;
        copy.denom *= -1;
    }

    return copy;
};

Fraction.prototype.add = function(f) {
    var a, b;

    if (f instanceof Fraction) {
        a = f.numer;
        b = f.denom;
    } else if (isInt(f)) {
        a = f;
        b = 1;
    }

    var copy = this.copy();

    if (this.denom == b) {
        copy.numer += a;
    } else {
        var m = lcm(copy.denom, b);
        var thisM = m / copy.denom;
        var otherM = m / b;

        copy.numer *= thisM;
        copy.denom *= thisM;

        a *= otherM;

        copy.numer += a;
    }

    return copy;
};

Fraction.prototype.subtract = function(f) {
    var copy = this.copy();

    if (f instanceof Fraction) {
        return copy.add(new Fraction(-f.numer, f.denom));
    } else if (isInt(f)) {
        return copy.add(new Fraction(-f, 1));
    }
};

Fraction.prototype.multiply = function(f) {
    var a, b;

    if (f instanceof Fraction) {
        a = f.numer;
        b = f.denom;
    } else if (isInt(f) && f) {
        a = f;
        b = 1;
    } else if (f == 0) {
        a = 0;
        b = 1;
    }

    var copy = this.copy();

    copy.numer *= a;
    copy.denom *= b;

    return copy;
};

Fraction.prototype.divide = function(f) {
    if (f == 0) {
        return;
    }

    var copy = this.copy();

    if (f instanceof Fraction) {
        return copy.multiply(new Fraction(f.denom, f.numer));
    } else if (isInt(f)) {
        return copy.multiply(new Fraction(1, f));
    }
};

Fraction.prototype.abs = function() {
    var copy = this.copy();
    copy = copy.reduce();
    copy.numer = Math.abs(copy.numer);
    return copy;
};

Fraction.prototype.decimal = function() {
    return this.numer / this.denom;
};

Fraction.prototype.print = function() {
    if (this.numer == 0) {
        return "0";
    } else if (this.denom == 1) {
        return this.numer.toString();
    } else if (this.denom == -1) {
        var num = this.numer * -1;
        return num.toString();
    } else {
        return this.numer + "/" + this.denom;
    }
};

Fraction.prototype.tex = function() {
    if (this.numer == 0) {
        return "0";
    } else if (this.denom == 1) {
        return this.numer.toString();
    } else if (this.denom == -1) {
        var num = this.numer * -1;
        return num.toString();
    } else {
        return "\\frac{" + this.numer + "}{" + this.denom + "}";
    }
};

module.exports = Fraction;<|endoftext|>


<commit_before>require(['model/page-state', 'util/navbuilder', 'jquery'], function(state, nav, $) {

  // http://stackoverflow.com/questions/6285491/are-there-universal-alternatives-to-window-onload-without-using-frameworks
  // Decided to do with jquery, to avoid messing up the window.onload
  $(document).ready(function() {

    compiledData = {}
    disapprovalEnabled = false
    baseUrl = nav.pluginServlets().build()
    repoId = state.getRepository().id;
    outstandingCount = 0
    callbacks = []

    tables = $("table tbody")
    tables.each(function() {
      $(this).find('tr').each(function() {
        var prId = $(this).attr("data-pullrequestid")
        outstandingCount += 1
        prd = $.get(baseUrl + '/disapproval/disapprove/' + repoId + '/' + prId)
        callbacks.push(prd)

        reviewers = $(this).children('.reviewers')
          prd.success(function(data) {

          // If things are not enabled, immediately bail out
          disapprovalEnabled = data.enabledForRepo
          if (!disapprovalEnabled) {
            return;
          }

          compiledData[prId.toString()] = data
        })
        // know when we are done by tracking outstanding calls
        prd.always(function() {
          outstandingCount -= 1
        })
      })
    })

    // when all callbacks are done...
    $.when.apply($, callbacks).then(function() {
      tables.each(function() {
        $(this).find('tr').each(function() {
          var prId = $(this).attr("data-pullrequestid")
          reviewers = $(this).children('.reviewers')

          disapprovalHtml = "";
          data = compiledData[prId.toString()]
          disapprovalDiv = $("

")
          if (data.disapproval) {
            console.log("Pull Request is Disapproved by " + data.disapprovedBy)
            disapprovalDiv.html($("").attr("src",baseUrl + "/disapproval/static-content/disapprovalface-trim.png")
                                                .css("max-height", "24px"))
          } else {
            console.log("Pull Request NOT Disapproved")
          }
          reviewers.before($("	").html(disapprovalDiv))
        })
      })

      // Add the header if it needs to be added
      if (disapprovalEnabled) {
        tableHead = $("table thead")
        tableHead.each(function() {
          $(this).find('tr').each(function() {
            reviewers = $(this).children('.reviewers')
            reviewers.before('Disapproval	')
          })
        })
      }
    })
  })
})

<commit_msg>ITOOLS-14101 Render each disapproval as the row is added<commit_after>require(['model/page-state', 'util/navbuilder', 'jquery'], function(state, nav, $) {

  /************
      BEGIN DISAPPROVAL PLUGIN
  *************/

  var prTotal = 0;
  var intervalNumber = 0;
  var baseUrl = undefined;
  var repoId = undefined;

  /*
    Extract query information from the page's URL
   */
  function getUrlParam (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href)
    if (results == null) {
      return null
    } else {
      return results[1] || 0
    }
  }

  /*
    Apply the disapproval information to a pull request row
   */
  function doDisapproval (row) {
    var prId = row.attr("data-pullrequestid");
    $.getJSON (baseUrl + "/disapproval/disapprove/" + repoId + "/" + prId, function(data) {
      if (!data.enabledForRepo) {
        return;
      }

      disapprovalDiv = $("

")
      if (data.disapproval) {
        console.log("Pull Request " + prId + " is Disapproved by " + data.disapprovedBy)
        disapprovalDiv.html($("").attr("src", baseUrl + "/disapproval/static-content/disapprovalface-trim.png")
                                            .css("max-height", "24px"))
      } else {
        console.log("Pull Request " + prId + " NOT Disapproved")
      }

      // Corner case of duplicate td's being inserted
      if (row.find("td.disapproval").size() === 0) {
        row.find("td.reviewers").before($("	").html(disapprovalDiv))
      } else {
        row.find("td.disapproval").html(disapprovalDiv)
      }

      if ($("table#pull-requests-table thead tr").find("th.disapproval").size() === 0) {
        $("table#pull-requests-table thead tr").find("th.reviewers").before($("Disapproval	"))
      }
    });
  }

  /*
    Scan for new rows without the disapprovals set up
   */
  function doNewDisapprovals () {
    var prRows = $("table#pull-requests-table tbody tr.pull-request-row")
    prRows.each(function (rowIndex) {
      if ($(this).find("td.disapproval").size() === 0) {
        doDisapproval($(this))
      }
    });
    console.log("We've done " + prRows.size() + " PR disapprovals so far.")

    // We've loaded the same # of PRs we know about, let's stop the interval
    if (prRows.size() >= prTotal) {
      clearInterval(intervalNumber)
      intervalNumber = 0;
    }
  }

  // http://stackoverflow.com/questions/6285491/are-there-universal-alternatives-to-window-onload-without-using-frameworks
  // Decided to do with jquery, to avoid messing up the window.onload
  $(document).ready(function() {

    baseUrl = nav.pluginServlets().build()
    repoId = state.getRepository().id;

    // Make sure we're querying for the right kind of PRs
    var prState = getUrlParam("state")
    if (prState == null) {
      prState = "open"
    }
    prRestBaseUrl = nav.rest().currentRepo().allPullRequests().build() + "?limit=100&state=" + prState

    // The rest api for pull requests won't let me get everything at once
    var allPRsCounted = false
    while (!allPRsCounted) {
      $.ajax({ url: prRestBaseUrl + "&start=" + prTotal,
               dataType:'json',
               async: false,
               success: function (data) {
                 prTotal += data.size;
                 if (data.isLastPage) {
                   allPRsCounted = true
                 }
               }
      });
    }
    console.log("There are " + prTotal + " total PRs")

    // Apply to the already loaded rows
    $("tr.pull-request-row").each(function (rowIndex) {
      doDisapproval($(this));
    });

    if (prTotal > 25) {
      intervalNumber = setInterval(doNewDisapprovals, 750);
    }

  })

})

<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { withApollo, graphql } from 'react-apollo';
import { saveItem, removeItem } from './with-item';
import capitalize from 'lodash/upperFirst';
import gql from 'graphql-tag';

const imageFields = `
  url
  crop
  width
  height
  caption
  source
`;
const userFields = `
  id
  email
  token
  name
`;
export default WrappedComponent => {
  @withApollo
  @graphql(gql`
    query getType($name: String!) {
      type: __type(name:$name) {
        name
        description
        fields {
          description
          name
          type {
            description
            kind
            name
            enumValues {
              name
            }
            fields {
              description
              name
              type {
                description
                kind
                name
                ofType {
                  kind
                  name
                }
              }
            }
            ofType {
              description
              kind
              name
              fields {
                description
                name
                type {
                  description
                  kind
                  name
                  fields {
                    description
                    name
                    type {
                      description
                      kind
                      name
                      ofType {
                        kind
                        name
                      }
                    }
                  }
                  ofType {
                    kind
                    name
                  }
                }
              }
            }
          }
        }
      }
    }
  `, { /* eslint-disable */
    options: ({ routeParams = {}, collection, name }) => ({
      skip: !!collection,
      variables: {
        name: capitalize(routeParams.model || name),
      },
    }),
  })
  class WithCollectionComponent extends Component {
    static propTypes = {
      client: PropTypes.object,
      attributes: PropTypes.string,
      name: PropTypes.string,
      includeStamps: PropTypes.bool,
    }
    save = item => {
      return saveItem(item, this.props.name, this.props.client, { id: item.id, attributes: this.getAttributes() });
    }
    remove = id => {
      return removeItem(id, this.props.name, this.props.client, { attributes: this.getAttributes() });
    }
    getAttributes = (col) => {
      const collection = col || (this.props.data && this.props.data.type) || this.props.collection || null;

      return `${collection.fields.map(field => {
        if (field.type.kind === 'ENUM' || field.type.kind === 'SCALAR') return field.name;
        else if (field.type.kind === 'LIST' && field.type.ofType && (field.type.ofType.kind === 'ENUM' || field.type.ofType.kind === 'SCALAR')) return field.name;
        else if (field.type.kind === 'LIST' && field.type.ofType && field.type.ofType.kind === 'OBJECT' && field.type.ofType.fields) return `${field.name} { ${this.getAttributes({ fields: field.type.ofType.fields })} }`;
        else if (field.type.kind === 'OBJECT' && field.type.name === 'Image') return `${field.name} { ${imageFields} }`;
        else if (field.type.kind === 'OBJECT' && field.type.name === 'User') return `${field.name} { ${userFields} }`;
        else if (field.type.kind === 'OBJECT' && field.type.fields) return `${field.name} { ${this.getAttributes({ fields: field.type.fields })} }`;
        return `${field.name} { id, name }`;
      }).filter(x => x).join(', ')}`;
    }
    render() {
      const { data, ...rest } = this.props;
      const collection = (this.props.data && this.props.data.type) || this.props.collection || null;
      if (!collection) return null;
      return <WrappedComponent
        {...rest}
        collectionLoading={data && data.loading}
        collection={collection}
        saveCollectionItem={this.save}
        removeCollectionItem={this.remove}
        attributes={this.getAttributes()}
      />;
    }
  }
  return WithCollectionComponent;
};
<commit_msg>add field description @prop support (@prop, @prop[0], @prop("test"), @prop[0]("test"))<commit_after>import React, { Component, PropTypes } from 'react';
import { withApollo, graphql } from 'react-apollo';
import { saveItem, removeItem } from './with-item';
import capitalize from 'lodash/upperFirst';
import gql from 'graphql-tag';

const specialFieldsMemo = {};
const imageFields = `
  url
  crop
  width
  height
  caption
  source
`;
const userFields = `
  id
  email
  token
  name
`;
export default WrappedComponent => {
  @withApollo
  @graphql(gql`
    query getType($name: String!) {
      type: __type(name:$name) {
        name
        description
        fields {
          description
          name
          type {
            description
            kind
            name
            enumValues {
              name
            }
            fields {
              description
              name
              type {
                description
                kind
                name
                ofType {
                  kind
                  name
                }
              }
            }
            ofType {
              description
              kind
              name
              fields {
                description
                name
                type {
                  description
                  kind
                  name
                  fields {
                    description
                    name
                    type {
                      description
                      kind
                      name
                      ofType {
                        kind
                        name
                      }
                    }
                  }
                  ofType {
                    kind
                    name
                  }
                }
              }
            }
          }
        }
      }
    }
  `, { /* eslint-disable */
    options: ({ routeParams = {}, collection, name }) => ({
      skip: !!collection,
      variables: {
        name: capitalize(routeParams.model || name),
      },
    }),
  })
  class WithCollectionComponent extends Component {
    static propTypes = {
      client: PropTypes.object,
      attributes: PropTypes.string,
      name: PropTypes.string,
      includeStamps: PropTypes.bool,
    }
    save = item => {
      return saveItem(item, this.props.name, this.props.client, { id: item.id, attributes: this.getAttributes() });
    }
    remove = id => {
      return removeItem(id, this.props.name, this.props.client, { attributes: this.getAttributes() });
    }
    getAttributes = (col) => {
      const collection = col || (this.props.data && this.props.data.type) || this.props.collection || null;

      return `${collection.fields.map(field => {
        if (field.type.kind === 'ENUM' || field.type.kind === 'SCALAR') return field.name;
        else if (field.type.kind === 'LIST' && field.type.ofType && (field.type.ofType.kind === 'ENUM' || field.type.ofType.kind === 'SCALAR')) return field.name;
        else if (field.type.kind === 'LIST' && field.type.ofType && field.type.ofType.kind === 'OBJECT' && field.type.ofType.fields) return `${field.name} { ${this.getAttributes({ fields: field.type.ofType.fields })} }`;
        else if (field.type.kind === 'OBJECT' && field.type.name === 'Image') return `${field.name} { ${imageFields} }`;
        else if (field.type.kind === 'OBJECT' && field.type.name === 'User') return `${field.name} { ${userFields} }`;
        else if (field.type.kind === 'OBJECT' && field.type.fields) return `${field.name} { ${this.getAttributes({ fields: field.type.fields })} }`;
        return `${field.name} { id, name }`;
      }).filter(x => x).join(', ')}`;
    }
    getWithSpecialFields = (collection) => {
      if (!collection) return;
      let specialFields = {};
      if (!specialFieldsMemo[collection.name]) {
        collection.fields.forEach(field => {
          if (!field.description) return;
          field.description.replace(/\@\w+(\[[0-9]+\])?(\(.+\))?/gi, (match, text, urlId) => {
            if (!match) return;
            let [split0, values] = match.split('(');
            let [name, index = null] = split0.split('[');
            name = name.substr(1);
            if (index) {
              try {
                index = parseInt(index.substr(index, index.length - 1));
              } catch(err) {
                index = null;
              }
            }
            const specialField = {
              field: field.name,
            };
            try {
              values.substr(0, values.length - 1).split(',').forEach((x, i) => {
                specialField[`arg${i}`] = JSON.parse(x);
              });
            } catch(err) { }

            if (index  || index === 0) {
              if (!specialFields[name]) specialFields[name] = [];
              specialFields[name].splice(index >= specialFields[name].length ? specialFields[name].length : index, 0, specialField);
            } else {
              specialFields[name] = specialField;
            }
          });
        });
        specialFieldsMemo[collection.name] = specialFields;
      } else {
        specialFields = specialFieldsMemo[collection.name]
      }
      return { ...collection, specialFields };
    }

    render() {
      const { data, ...rest } = this.props;
      const collection = (this.props.data && this.props.data.type) || this.props.collection || null;
      if (!collection) return null;
      return <WrappedComponent
        {...rest}
        collectionLoading={data && data.loading}
        collection={this.getWithSpecialFields(collection)}
        saveCollectionItem={this.save}
        removeCollectionItem={this.remove}
        attributes={this.getAttributes()}
      />;
    }
  }
  return WithCollectionComponent;
};
<|endoftext|>