text:
/* Column module */

(function (global, angular) {
    "use strict";
    var smartTableColumnModule = angular.module('smartTable.column', ['smartTable.templateUrlList']).constant('DefaultColumnConfiguration', {
        isSortable: true,
        isEditable: false,
        type: 'text',

        //it is useless to have that empty strings, but it reminds what is available
        headerTemplateUrl: '',
        map: '',
        label: '',
        sortPredicate: '',
        formatFunction: '',
        formatParameter: '',
        filterPredicate: '',
        cellTemplateUrl: '',
        headerClass: '',
        cellClass: ''
    });

    function ColumnProvider(DefaultColumnConfiguration, templateUrlList) {

        function Column(config) {
            if (!(this instanceof Column)) {
                return new Column(config);
            }
            angular.extend(this, config);
        }

        this.setDefaultOption = function (option) {
            angular.extend(Column.prototype, option);
        };

        DefaultColumnConfiguration.headerTemplateUrl = templateUrlList.defaultHeader;
        this.setDefaultOption(DefaultColumnConfiguration);

        this.$get = function () {
            return Column;
        };
    }

    ColumnProvider.$inject = ['DefaultColumnConfiguration', 'templateUrlList'];
    smartTableColumnModule.provider('Column', ColumnProvider);

    //make it global so it can be tested
    global.ColumnProvider = ColumnProvider;
})(window, angular);

/* Directives */
(function (angular) {
    "use strict";
    angular.module('smartTable.directives', ['smartTable.templateUrlList', 'smartTable.templates'])
        .directive('smartTable', ['templateUrlList', 'DefaultTableConfiguration', function (templateList, defaultConfig) {
            return {
                restrict: 'EA',
                scope: {
                    columnCollection: '=columns',
                    dataCollection: '=rows',
                    config: '='
                },
                replace: 'true',
                templateUrl: templateList.smartTable,
                controller: 'TableCtrl',
                link: function (scope, element, attr, ctrl) {

                    var templateObject;

                    scope.$watch('config', function (config) {
                        var newConfig = angular.extend({}, defaultConfig, config),
                            length = scope.columns !== undefined ? scope.columns.length : 0;

                        ctrl.setGlobalConfig(newConfig);

                        //remove the checkbox column if needed
                        if (newConfig.selectionMode !== 'multiple' || newConfig.displaySelectionCheckbox !== true) {
                            for (var i = length - 1; i >= 0; i--) {
                                if (scope.columns[i].isSelectionColumn === true) {
                                    ctrl.removeColumn(i);
                                }
                            }
                        } else {
                            //add selection box column if required
                            ctrl.insertColumn({cellTemplateUrl: templateList.selectionCheckbox, headerTemplateUrl: templateList.selectAllCheckbox, isSelectionColumn: true}, 0);
                        }
                    }, true);

                    //insert columns from column config
                    scope.$watch('columnCollection', function (oldValue, newValue) {

                        ctrl.clearColumns();

                        if (scope.columnCollection) {
                            for (var i = 0, l = scope.columnCollection.length; i < l; i++) {
                                ctrl.insertColumn(scope.columnCollection[i]);
                            }
                        } else {
                            //or guess data Structure
                            if (scope.dataCollection && scope.dataCollection.length > 0) {
                                templateObject = scope.dataCollection[0];
                                angular.forEach(templateObject, function (value, key) {
                                    if (key[0] != '$') {
                                        ctrl.insertColumn({label: key, map: key});
                                    }
                                });
                            }
                        }
                    }, true);

                    //if item are added or removed into the data model from outside the grid
                    scope.$watch('dataCollection.length', function (oldValue, newValue) {
                        if (oldValue !== newValue) {
                            ctrl.sortBy();//it will trigger the refresh... some hack ?
                        }
                    });
                }
            };
        }])
        //just to be able to select the row
        .directive('smartTableDataRow', function () {

            return {
                require: '^smartTable',
                restrict: 'C',
                link: function (scope, element, attr, ctrl) {

                    element.bind('click', function () {
                        scope.$apply(function () {
                            ctrl.toggleSelection(scope.dataRow);
                        })
                    });
                }
            };
        })
        //header cell with sorting functionality or put a checkbox if this column is a selection column
        .directive('smartTableHeaderCell',function () {
            return {
                restrict: 'C',
                require: '^smartTable',
                link: function (scope, element, attr, ctrl) {
                    element.bind('click', function () {
                        scope.$apply(function () {
                            ctrl.sortBy(scope.column);
                        });
                    })
                }
            };
        }).directive('smartTableSelectAll', function () {
            return {
                restrict: 'C',
                require: '^smartTable',
                link: function (scope, element, attr, ctrl) {
                    element.bind('click', function (event) {
                        ctrl.toggleSelectionAll(element[0].checked === true);
                    })
                }
            };
        })
        //credit to Valentyn shybanov : http://stackoverflow.com/questions/14544741/angularjs-directive-to-stoppropagation
        .directive('stopEvent', function () {
            return {
                restrict: 'A',
                link: function (scope, element, attr) {
                    element.bind(attr.stopEvent, function (e) {
                        e.stopPropagation();
                    });
                }
            }
        })
        //the global filter
        .directive('smartTableGlobalSearch', ['templateUrlList', function (templateList) {
            return {
                restrict: 'C',
                require: '^smartTable',
                scope: {
                    columnSpan: '@'
                },
                templateUrl: templateList.smartTableGlobalSearch,
                replace: false,
                link: function (scope, element, attr, ctrl) {

                    scope.searchValue = '';

                    scope.$watch('searchValue', function (value) {
                        //todo perf improvement only filter on blur ?
                        ctrl.search(value);
                    });
                }
            }
        }])
        //a customisable cell (see templateUrl) and editable
        //TODO check with the ng-include strategy
        .directive('smartTableDataCell', ['$filter', '$http', '$templateCache', '$compile', '$parse', function (filter, http, templateCache, compile, parse) {
            return {
                restrict: 'C',
                link: function (scope, element) {
                    var
                        column = scope.column,
                        isSimpleCell = !column.isEditable,
                        row = scope.dataRow,
                        format = filter('format'),
                        getter = parse(column.map),
                        childScope;

                    //can be useful for child directives
                    scope.$watch('dataRow', function (value) {
                        scope.formatedValue = format(getter(row), column.formatFunction, column.formatParameter);
                        if (isSimpleCell === true) {
                            element.text(scope.formatedValue);
                        }
                    }, true);

                    function defaultContent() {
                        if (column.isEditable) {
                            element.html('

');
                            compile(element.contents())(scope);
                        } else {
                            element.text(scope.formatedValue);
                        }
                    }

                    scope.$watch('column.cellTemplateUrl', function (value) {

                        if (value) {
                            //we have to load the template (and cache it) : a kind of ngInclude
                            http.get(value, {cache: templateCache}).success(function (response) {

                                isSimpleCell = false;

                                //create a scope
                                childScope = scope.$new();
                                //compile the element with its new content and new scope
                                element.html(response);
                                compile(element.contents())(childScope);
                            }).error(defaultContent);

                        } else {
                            defaultContent();
                        }
                    });
                }
            };
        }])
        //directive that allows type to be bound in input
        .directive('inputType', function () {
            return {
                restrict: 'A',
                priority: 1,
                link: function (scope, ielement, iattr) {
                    //force the type to be set before inputDirective is called
                    var type = scope.$eval(iattr.type);
                    iattr.$set('type', type);
                }
            };
        })
        //an editable content in the context of a cell (see row, column)
        .directive('editableCell', ['templateUrlList', '$parse', function (templateList, parse) {
            return {
                restrict: 'EA',
                require: '^smartTable',
                templateUrl: templateList.editableCell,
                scope: {
                    row: '=',
                    column: '=',
                    type: '='
                },
                replace: true,
                link: function (scope, element, attrs, ctrl) {
                    var form = angular.element(element.children()[1]),
                        input = angular.element(form.children()[0]),
                        getter = parse(scope.column.map);

                    //init values
                    scope.isEditMode = false;
                    scope.$watch('row', function () {
                        scope.value = getter(scope.row);
                    }, true);

                    scope.submit = function () {
                        //update model if valid
                        if (scope.myForm.$valid === true) {
                            ctrl.updateDataRow(scope.row, scope.column.map, scope.value);
                            ctrl.sortBy();//it will trigger the refresh...  (ie it will sort, filter, etc with the new value)
                        }
                        scope.toggleEditMode();
                    };

                    scope.toggleEditMode = function () {
                        scope.value = getter(scope.row);
                        scope.isEditMode = scope.isEditMode !== true;
                    };

                    scope.$watch('isEditMode', function (newValue) {
                        if (newValue === true) {
                            input[0].select();
                            input[0].focus();
                        }
                    });

                    input.bind('blur', function () {
                        scope.$apply(function () {
                            scope.submit();
                        });
                    });
                }
            };
        }]);
})(angular);
/* Filters */
(function (angular) {
    "use strict";
    angular.module('smartTable.filters', []).
        constant('DefaultFilters', ['currency', 'date', 'json', 'lowercase', 'number', 'uppercase']).
        filter('format', ['$filter', 'DefaultFilters', function (filter, defaultfilters) {
            return function (value, formatFunction, filterParameter) {

                var returnFunction;

                if (formatFunction && angular.isFunction(formatFunction)) {
                    returnFunction = formatFunction;
                } else {
                    returnFunction = defaultfilters.indexOf(formatFunction) !== -1 ? filter(formatFunction) : function (value) {
                        return value;
                    };
                }
                return returnFunction(value, filterParameter);
            };
        }]);
})(angular);

/*table module */

(function (angular) {
    "use strict";
    angular.module('smartTable.table', ['smartTable.column', 'smartTable.utilities', 'smartTable.directives', 'smartTable.filters', 'ui.bootstrap.pagination.smartTable'])
        .constant('DefaultTableConfiguration', {
            selectionMode: 'none',
            isGlobalSearchActivated: false,
            displaySelectionCheckbox: false,
            isPaginationEnabled: true,
            itemsByPage: 10,
            maxSize: 5,

            //just to remind available option
            sortAlgorithm: '',
            filterAlgorithm: ''
        })
        .controller('TableCtrl', ['$scope', 'Column', '$filter', '$parse', 'ArrayUtility', 'DefaultTableConfiguration', function (scope, Column, filter, parse, arrayUtility, defaultConfig) {

            scope.columns = [];
            scope.dataCollection = scope.dataCollection || [];
            scope.displayedCollection = []; //init empty array so that if pagination is enabled, it does not spoil performances
            scope.numberOfPages = calculateNumberOfPages(scope.dataCollection);
            scope.currentPage = 1;
            scope.holder = {isAllSelected: false};

            var predicate = {},
                lastColumnSort;

            function isAllSelected() {
                var i,
                    l = scope.displayedCollection.length;
                for (i = 0; i < l; i++) {
                    if (scope.displayedCollection[i].isSelected !== true) {
                        return false;
                    }
                }
                return true;
            }

            function calculateNumberOfPages(array) {

                if (!angular.isArray(array) || array.length === 0 || scope.itemsByPage < 1) {
                    return 1;
                }
                return Math.ceil(array.length / scope.itemsByPage);
            }

            function sortDataRow(array, column) {
                var sortAlgo = (scope.sortAlgorithm && angular.isFunction(scope.sortAlgorithm)) === true ? scope.sortAlgorithm : filter('orderBy');
                if (column) {
                    return arrayUtility.sort(array, sortAlgo, column.sortPredicate, column.reverse);
                } else {
                    return array;
                }
            }

            function selectDataRow(array, selectionMode, index, select) {

                var dataRow, oldValue;

                if ((!angular.isArray(array)) || (selectionMode !== 'multiple' && selectionMode !== 'single')) {
                    return;
                }

                if (index >= 0 && index < array.length) {
                    dataRow = array[index];
                    if (selectionMode === 'single') {
                        //unselect all the others
                        for (var i = 0, l = array.length; i < l; i++) {
                            oldValue = array[i].isSelected;
                            array[i].isSelected = false;
                            if (oldValue === true) {
                                scope.$emit('selectionChange', {item: array[i]});
                            }
                        }
                    }
                    dataRow.isSelected = select;
                    scope.holder.isAllSelected = isAllSelected();
                    scope.$emit('selectionChange', {item: dataRow});
                }
            }

            /**
             * set the config (config parameters will be available through scope
             * @param config
             */
            this.setGlobalConfig = function (config) {
                angular.extend(scope, defaultConfig, config);
            };

            /**
             * change the current page displayed
             * @param page
             */
            this.changePage = function (page) {
                var oldPage = scope.currentPage;
                if (angular.isNumber(page.page)) {
                    scope.currentPage = page.page;
                    scope.displayedCollection = this.pipe(scope.dataCollection);
                    scope.holder.isAllSelected = isAllSelected();
                    scope.$emit('changePage', {oldValue: oldPage, newValue: scope.currentPage});
                }
            };

            /**
             * set column as the column used to sort the data (if it is already the case, it will change the reverse value)
             * @method sortBy
             * @param column
             */
            this.sortBy = function (column) {
                var index = scope.columns.indexOf(column);
                if (index !== -1) {
                    if (column.isSortable === true) {
                        // reset the last column used
                        if (lastColumnSort && lastColumnSort !== column) {
                            lastColumnSort.reverse = 'none';
                        }

                        column.sortPredicate = column.sortPredicate || column.map;
                        column.reverse = column.reverse !== true;
                        lastColumnSort = column;
                    }
                }

                scope.displayedCollection = this.pipe(scope.dataCollection);
            };

            /**
             * set the filter predicate used for searching
             * @param input
             * @param column
             */
            this.search = function (input, column) {

                var j, l = scope.columns.length;
                //update column and global predicate
                if (column && scope.columns.indexOf(column) !== -1) {
                    predicate.$ = '';
                    column.filterPredicate = input;
                } else {
                    for (j = 0; j < l; j++) {
                        scope.columns[j].filterPredicate = '';
                    }
                    predicate.$ = input;
                }

                for (j = 0; j < l; j++) {
                    predicate[scope.columns[j].map] = scope.columns[j].filterPredicate;
                }
                scope.displayedCollection = this.pipe(scope.dataCollection);

            };

            /**
             * combine sort, search and limitTo operations on an array,
             * @param array
             * @returns Array, an array result of the operations on input array
             */
            this.pipe = function (array) {
                var filterAlgo = (scope.filterAlgorithm && angular.isFunction(scope.filterAlgorithm)) === true ? scope.filterAlgorithm : filter('filter'),
                    output;
                //filter and sort are commutative
                output = sortDataRow(arrayUtility.filter(array, filterAlgo, predicate), lastColumnSort);
                scope.numberOfPages = calculateNumberOfPages(output);
                return scope.isPaginationEnabled ? arrayUtility.fromTo(output, (scope.currentPage - 1) * scope.itemsByPage, scope.itemsByPage) : output;
            };

            /*////////////
             Column API
             ///////////*/

            /**
             * insert a new column in scope.collection at index or push at the end if no index
             * @param columnConfig column configuration used to instantiate the new Column
             * @param index where to insert the column (at the end if not specified)
             */
            this.insertColumn = function (columnConfig, index) {
                var column = new Column(columnConfig);
                arrayUtility.insertAt(scope.columns, index, column);
            };

            /**
             * remove the column at columnIndex from scope.columns
             * @param columnIndex index of the column to be removed
             */
            this.removeColumn = function (columnIndex) {
                arrayUtility.removeAt(scope.columns, columnIndex);
            };

            /**
             * move column located at oldIndex to the newIndex in scope.columns
             * @param oldIndex index of the column before it is moved
             * @param newIndex index of the column after the column is moved
             */
            this.moveColumn = function (oldIndex, newIndex) {
                arrayUtility.moveAt(scope.columns, oldIndex, newIndex);
            };

            /**
             * remove all columns
             */
            this.clearColumns = function () {
                scope.columns.length = 0;
            };

            /*///////////
             ROW API
             */

            /**
             * select or unselect the item of the displayedCollection with the selection mode set in the scope
             * @param dataRow
             */
            this.toggleSelection = function (dataRow) {
                var index = scope.dataCollection.indexOf(dataRow);
                if (index !== -1) {
                    selectDataRow(scope.dataCollection, scope.selectionMode, index, dataRow.isSelected !== true);
                }
            };

            /**
             * select/unselect all the currently displayed rows
             * @param value if true select, else unselect
             */
            this.toggleSelectionAll = function (value) {
                var i = 0,
                    l = scope.displayedCollection.length;

                if (scope.selectionMode !== 'multiple') {
                    return;
                }
                for (; i < l; i++) {
                    selectDataRow(scope.displayedCollection, scope.selectionMode, i, value === true);
                }
            };

            /**
             * remove the item at index rowIndex from the displayed collection
             * @param rowIndex
             * @returns {*} item just removed or undefined
             */
            this.removeDataRow = function (rowIndex) {
                var toRemove = arrayUtility.removeAt(scope.displayedCollection, rowIndex);
                arrayUtility.removeAt(scope.dataCollection, scope.dataCollection.indexOf(toRemove));
            };

            /**
             * move an item from oldIndex to newIndex in displayedCollection
             * @param oldIndex
             * @param newIndex
             */
            this.moveDataRow = function (oldIndex, newIndex) {
                arrayUtility.moveAt(scope.displayedCollection, oldIndex, newIndex);
            };

            /**
             * update the model, it can be a non existing yet property
             * @param dataRow the dataRow to update
             * @param propertyName the property on the dataRow ojbect to update
             * @param newValue the value to set
             */
            this.updateDataRow = function (dataRow, propertyName, newValue) {
                var index = scope.displayedCollection.indexOf(dataRow),
                    getter = parse(propertyName),
                    setter = getter.assign,
                    oldValue;
                if (index !== -1) {
                    oldValue = getter(scope.displayedCollection[index]);
                    if (oldValue !== newValue) {
                        setter(scope.displayedCollection[index], newValue);
                        scope.$emit('updateDataRow', {item: scope.displayedCollection[index]});
                    }
                }
            };
        }]);
})(angular);

angular.module('smartTable.templates', ['partials/defaultCell.html', 'partials/defaultHeader.html', 'partials/editableCell.html', 'partials/globalSearchCell.html', 'partials/pagination.html', 'partials/selectAllCheckbox.html', 'partials/selectionCheckbox.html', 'partials/smartTable.html']);

angular.module("partials/defaultCell.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("partials/defaultCell.html",
        "{{formatedValue}}");
}]);

angular.module("partials/defaultHeader.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("partials/defaultHeader.html",
        "{{column.label}}");
}]);

angular.module("partials/editableCell.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("partials/editableCell.html",
        "
\n" +
            "    {{value | format:column.formatFunction:column.formatParameter}}\n" +
            "\n" +
            "    <form ng-submit=\"submit()\" ng-show=\"isEditMode\" name=\"myForm\">\n" +
            "        <input name=\"myInput\" ng-model=\"value\" type=\"type\" input-type/>\n" +
            "    </form>\n" +
            "
");
}]);

angular.module("partials/globalSearchCell.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("partials/globalSearchCell.html",
        "Search :\n" +
            "<input type=\"text\" ng-model=\"searchValue\"/>");
}]);

angular.module("partials/pagination.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("partials/pagination.html",
        "
\n" +
            "
\n" +
            "
{{page.text}}
\n" +
            "
\n" +
            "
 ");
}]);

angular.module("partials/selectAllCheckbox.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("partials/selectAllCheckbox.html",
        "<input class=\"smart-table-select-all\"  type=\"checkbox\" ng-model=\"holder.isAllSelected\"/>");
}]);

angular.module("partials/selectionCheckbox.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("partials/selectionCheckbox.html",
        "<input type=\"checkbox\" ng-model=\"dataRow.isSelected\" stop-event=\"click\"/>");
}]);

angular.module("partials/smartTable.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("partials/smartTable.html",
        "
\n" +
            "
\n" +
            "
\n" +
            "        \n" +
            "        	\n" +
            "
\n" +
            "
\n" +
            "        \n" +
            "        	\n" +
            "
\n" +
            "
\n" +
            "
\n" +
            "
\n" +
            "        	\n" +
            "
\n" +
            "
\n" +
            "
\n" +
            "
\n" +
            "        \n" +
            "

\n" +
            "        	\n" +
            "
\n" +
            "
\n" +
            "
\n" +
            "\n" +
            "\n" +
            "");
}]);

(function (angular) {
    "use strict";
    angular.module('smartTable.templateUrlList', [])
        .constant('templateUrlList', {
            smartTable: 'partials/smartTable.html',
            smartTableGlobalSearch: 'partials/globalSearchCell.html',
            editableCell: 'partials/editableCell.html',
            selectionCheckbox: 'partials/selectionCheckbox.html',
            selectAllCheckbox: 'partials/selectAllCheckbox.html',
            defaultHeader: 'partials/defaultHeader.html',
            pagination: 'partials/pagination.html'
        });
})(angular);

(function (angular) {
    "use strict";
    angular.module('smartTable.utilities', [])

        .factory('ArrayUtility', function () {

            /**
             * remove the item at index from arrayRef and return the removed item
             * @param arrayRef
             * @param index
             * @returns {*}
             */
            var removeAt = function (arrayRef, index) {
                    if (index >= 0 && index < arrayRef.length) {
                        return arrayRef.splice(index, 1)[0];
                    }
                },

                /**
                 * insert item in arrayRef at index or a the end if index is wrong
                 * @param arrayRef
                 * @param index
                 * @param item
                 */
                    insertAt = function (arrayRef, index, item) {
                    if (index >= 0 && index < arrayRef.length) {
                        arrayRef.splice(index, 0, item);
                    } else {
                        arrayRef.push(item);
                    }
                },

                /**
                 * move the item at oldIndex to newIndex in arrayRef
                 * @param arrayRef
                 * @param oldIndex
                 * @param newIndex
                 */
                    moveAt = function (arrayRef, oldIndex, newIndex) {
                    var elementToMove;
                    if (oldIndex >= 0 && oldIndex < arrayRef.length && newIndex >= 0 && newIndex < arrayRef.length) {
                        elementToMove = arrayRef.splice(oldIndex, 1)[0];
                        arrayRef.splice(newIndex, 0, elementToMove);
                    }
                },

                /**
                 * sort arrayRef according to sortAlgorithm following predicate and reverse
                 * @param arrayRef
                 * @param sortAlgorithm
                 * @param predicate
                 * @param reverse
                 * @returns {*}
                 */
                    sort = function (arrayRef, sortAlgorithm, predicate, reverse) {

                    if (!sortAlgorithm || !angular.isFunction(sortAlgorithm)) {
                        return arrayRef;
                    } else {
                        return sortAlgorithm(arrayRef, predicate, reverse === true);//excpet if reverse is true it will take it as false
                    }
                },

                /**
                 * filter arrayRef according with filterAlgorithm and predicate
                 * @param arrayRef
                 * @param filterAlgorithm
                 * @param predicate
                 * @returns {*}
                 */
                    filter = function (arrayRef, filterAlgorithm, predicate) {
                    if (!filterAlgorithm || !angular.isFunction(filterAlgorithm)) {
                        return arrayRef;
                    } else {
                        return filterAlgorithm(arrayRef, predicate);
                    }
                },

                /**
                 * return an array, part of array ref starting at min and the size of length
                 * @param arrayRef
                 * @param min
                 * @param length
                 * @returns {*}
                 */
                    fromTo = function (arrayRef, min, length) {

                    var out = [],
                        limit,
                        start;

                    if (!angular.isArray(arrayRef)) {
                        return arrayRef;
                    }

                    start = Math.max(min, 0);
                    start = Math.min(start, (arrayRef.length - 1) > 0 ? arrayRef.length - 1 : 0);

                    length = Math.max(0, length);
                    limit = Math.min(start + length, arrayRef.length);

                    for (var i = start; i < limit; i++) {
                        out.push(arrayRef[i]);
                    }
                    return out;
                };

            return {
                removeAt: removeAt,
                insertAt: insertAt,
                moveAt: moveAt,
                sort: sort,
                filter: filter,
                fromTo: fromTo
            };
        });
})(angular);

(function (angular) {
    angular.module('ui.bootstrap.pagination.smartTable', ['smartTable.templateUrlList'])

        .constant('paginationConfig', {
            boundaryLinks: false,
            directionLinks: true,
            firstText: 'First',
            previousText: '<',
            nextText: '>',
            lastText: 'Last'
        })

        .directive('paginationSmartTable', ['paginationConfig', 'templateUrlList', function (paginationConfig, templateUrlList) {
            return {
                restrict: 'EA',
                require: '^smartTable',
                scope: {
                    numPages: '=',
                    currentPage: '=',
                    maxSize: '='
                },
                templateUrl: templateUrlList.pagination,
                replace: true,
                link: function (scope, element, attrs, ctrl) {

                    // Setup configuration parameters
                    var boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;
                    var directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$eval(attrs.directionLinks) : paginationConfig.directionLinks;
                    var firstText = angular.isDefined(attrs.firstText) ? attrs.firstText : paginationConfig.firstText;
                    var previousText = angular.isDefined(attrs.previousText) ? attrs.previousText : paginationConfig.previousText;
                    var nextText = angular.isDefined(attrs.nextText) ? attrs.nextText : paginationConfig.nextText;
                    var lastText = angular.isDefined(attrs.lastText) ? attrs.lastText : paginationConfig.lastText;

                    // Create page object used in template
                    function makePage(number, text, isActive, isDisabled) {
                        return {
                            number: number,
                            text: text,
                            active: isActive,
                            disabled: isDisabled
                        };
                    }

                    scope.$watch('numPages + currentPage + maxSize', function () {
                        scope.pages = [];

                        // Default page limits
                        var startPage = 1, endPage = scope.numPages;

                        // recompute if maxSize
                        if (scope.maxSize && scope.maxSize < scope.numPages) {
                            startPage = Math.max(scope.currentPage - Math.floor(scope.maxSize / 2), 1);
                            endPage = startPage + scope.maxSize - 1;

                            // Adjust if limit is exceeded
                            if (endPage > scope.numPages) {
                                endPage = scope.numPages;
                                startPage = endPage - scope.maxSize + 1;
                            }
                        }

                        // Add page number links
                        for (var number = startPage; number <= endPage; number++) {
                            var page = makePage(number, number, scope.isActive(number), false);
                            scope.pages.push(page);
                        }

                        // Add previous & next links
                        if (directionLinks) {
                            var previousPage = makePage(scope.currentPage - 1, previousText, false, scope.noPrevious());
                            scope.pages.unshift(previousPage);

                            var nextPage = makePage(scope.currentPage + 1, nextText, false, scope.noNext());
                            scope.pages.push(nextPage);
                        }

                        // Add first & last links
                        if (boundaryLinks) {
                            var firstPage = makePage(1, firstText, false, scope.noPrevious());
                            scope.pages.unshift(firstPage);

                            var lastPage = makePage(scope.numPages, lastText, false, scope.noNext());
                            scope.pages.push(lastPage);
                        }

                        if (scope.currentPage > scope.numPages) {
                            scope.selectPage(scope.numPages);
                        }
                    });
                    scope.noPrevious = function () {
                        return scope.currentPage === 1;
                    };
                    scope.noNext = function () {
                        return scope.currentPage === scope.numPages;
                    };
                    scope.isActive = function (page) {
                        return scope.currentPage === page;
                    };

                    scope.selectPage = function (page) {
                        if (!scope.isActive(page) && page > 0 && page <= scope.numPages) {
                            scope.currentPage = page;
                            ctrl.changePage({ page: page });
                        }
                    };
                }
            };
        }]);
})(angular);


text:
package sizebay.catalog.client.model;

import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.Map;

@Getter
@Setter
public class StrongSize {

	private String groupMeasures;
	private Map<SizeSystem, String> labels = new HashMap<>();
	private Map<Measure, StrongMeasureRange> measures = new HashMap<>();
	private int totalSamples;
	private double accuracyPercentage;
	private int status;

}

redpajama_set_name: RedPajamaGithub


text:
class AboutDialog : public QDialog
{
  Q_OBJECT
public:
  explicit AboutDialog(QWidget * parent);
};


text:
A Squid3 caching proxy with SSL enabled in a Docker container, based on
https://github.com/toffer/docker-squid3-ssl and meant to be used from within
other Docker containers.

## Details

* Ubuntu 14.04 LTS (Trusty).
* Squid (Version 3.3.8).
* Built from source, with `--enable-ssl`.
* Automatically generates self-signed certificate.
* Configured to cache Docker images (default config for Squid3 doesn't handle
  Docker images very well.)

## Usage

Start Squid3 setting its hostname and container name:

```
$ docker run -d -h proxy.docker.dev --name squid3 fgrehm/squid3-ssl:v20140809
```

Start another container linking it to the proxy container and setting the
`http_proxy` env var to the linked container:

```
$ docker run -ti --rm \
           --link squid3:proxy.docker.dev \
           -e http_proxy="http://proxy.docker.dev:3128" \
           ubuntu:trusty bash
```

You can check that things are working by hitting the same URL twice from within
a linked container and checking the `X-Cache` header that Squid sets in the
responses. The second response should show a cache hit:

```
$ curl -s -i http://httpbin.org/ip | grep 'X-Cache:'
X-Cache: MISS from proxy

$ curl -s -i http://httpbin.org/ip | grep 'X-Cache:'
X-Cache: HIT from proxy
```

### Caching HTTPS requests

To use the proxy for HTTPS requests, the linked container needs to trust the
self-signed certificate generated by the Squid3 server. To setup and install the
CA certificate on an Ubuntu container, try these steps:

```
# Start Squid3 setting its hostname and container name:
$ docker run -d -h proxy.docker.dev --name squid3 fgrehm/squid3-ssl:v20140809

# Save the certificate into a file
$ docker logs squid3 | sed -n '/BEGIN/,/END/p' > proxy.docker.dev.crt

# Start a new container doing the appropriate setup
$ docker run -ti --rm \
           --link squid3:proxy.docker.dev \
           -v `pwd`/proxy.docker.dev.crt:/usr/share/ca-certificates/proxy.docker.dev.crt \
           -e http_proxy="http://proxy.docker.dev:3128" \
           -e https_proxy="http://proxy.docker.dev:3128" \
           ubuntu:trusty bash

# From within the container, trust the certificate
$ apt-get update && apt-get install -y ca-certificates curl
$ echo 'proxy.docker.dev.crt' >> /etc/ca-certificates.conf
$ /usr/sbin/update-ca-certificates
```

If your container gives you a way to "inject" scripts within its init process /
entrypoint, you can have that process automated.

For example, if you use [phusion/baseimage](https://github.com/phusion/baseimage-docker)
you can create an executable script like the one below:

```sh
#!/bin/bash
set -e

# Install ca-certificates if needed
if ! [ -x /usr/sbin/update-ca-certificates ]; then
  apt-get update && apt-get install -y ca-certificates
fi

# Trust our certificate
if ! $(grep -q 'proxy.docker.dev.crt' /etc/ca-certificates.conf); then
  echo 'proxy.docker.dev.crt' >> /etc/ca-certificates.conf
  /usr/sbin/update-ca-certificates
fi
```

And run your containers like:

```
$ docker run -ti --rm \
           --link squid3:proxy.docker.dev \
           -v `pwd`/proxy.docker.dev.crt:/usr/share/ca-certificates/proxy.docker.dev.crt \
           -v `pwd`/proxy-script.sh:/etc/my_init.d/proxy-script.sh \
           -e http_proxy="http://proxy.docker.dev:3128" \
           -e https_proxy="http://proxy.docker.dev:3128" \
           phusion/baseimage /sbin/my_init -- bash -l
```

This will make sure that every time the container is brought up, it trusts the
proxy certificates and you don't need to do that by hand.

As with regular http requests, you can check that things are working by hitting
the same https URL twice from within a linked container (after trusting the
certificate) and checking the `X-Cache` header that Squid sets in the responses.
The second response should show a cache hit:

```
$ curl -s -i https://httpbin.org/ip | grep 'X-Cache:'
X-Cache: MISS from proxy

$ curl -s -i https://httpbin.org/ip | grep 'X-Cache:'
X-Cache: HIT from proxy
```

## Where does those `.deb`s come from?

I manually built the packages using a [separate Dockerfile](Dockerfile.build),
created a [GitHub release](https://github.com/fgrehm/squid3-ssl-docker/releases)
with a tarball of those debs and set up an [automated build](https://registry.hub.docker.com/u/fgrehm/squid3-ssl)
on Docker Hub.


text:
package tela.admin.categoria;

import dao.CategoriaDAO;
import modelo.Categoria;

public class CategoriaAtualizarTela extends javax.swing.JFrame {
    private Categoria categoria;

    /**
     * Creates new form CadastrarProduto
     * @param categoria
     */
    public CategoriaAtualizarTela(Categoria categoria) {
        this.categoria = categoria;
        initComponents();
        preencherCampos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lDescricao = new javax.swing.JLabel();
        tfDescricao = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        bAtualizar = new javax.swing.JButton();
        bCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Atualizar Categoria");
        setResizable(false);

        lDescricao.setText("Descrição");

        bAtualizar.setText("Atualizar");
        bAtualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAtualizarActionPerformed(evt);
            }
        });

        bCancelar.setText("Cancelar");
        bCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lDescricao, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(bAtualizar)
                        .addGap(58, 58, 58)
                        .addComponent(bCancelar))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(12, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lDescricao)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bAtualizar)
                    .addComponent(bCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_bCancelarActionPerformed

    private void bAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAtualizarActionPerformed
        atualizarCategoria();
        dispose();
    }//GEN-LAST:event_bAtualizarActionPerformed

    private void preencherCampos(){
        tfDescricao.setText(categoria.getDescricao());
    }

    private void atualizarCategoria(){
        if (!tfDescricao.getText().equals("") && !tfDescricao.getText().equals(categoria.getDescricao())){
            categoria.setDescricao(tfDescricao.getText());
            CategoriaDAO categoriaDAO = new CategoriaDAO();
            categoriaDAO.alterCategoria(categoria);
            dispose();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAtualizar;
    private javax.swing.JButton bCancelar;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lDescricao;
    private javax.swing.JTextField tfDescricao;
    // End of variables declaration//GEN-END:variables
}


text:
import six

class InstrumentMixin(object):
    def __init__(self, instruments):
        self._instruments = {i.order_book_id: i for i in instruments}
        self._sym_id_map = {i.symbol: k for k, i in six.iteritems(self._instruments)
                            # 过滤掉 CSI300, SSE50, CSI500, SSE180
                            if not i.order_book_id.endswith('INDX')}
        try:
            # FIXME
            # 沪深300 中证500 固定使用上证的
            for o in ['000300.XSHG', '000905.XSHG']:
                self._sym_id_map[self._instruments[o].symbol] = o
            # 上证180 及 上证180指数 两个symbol都指向 000010.XSHG
            self._sym_id_map[self._instruments['SSE180.INDX'].symbol] = '000010.XSHG'
        except KeyError:
            pass

    def sector(self, code):
        return [v.order_book_id for v in self._instruments.values()
                if v.type == 'CS' and v.sector_code == code]

    def industry(self, code):
        return [v.order_book_id for v in self._instruments.values()
                if v.type == 'CS' and v.industry_code == code]

    def all_instruments(self, types, dt=None):
        return [i for i in self._instruments.values()
                if ((dt is None or i.listed_date.date() <= dt.date() <= i.de_listed_date.date()) and
                    (types is None or i.type in types))]

    def _instrument(self, sym_or_id):
        try:
            return self._instruments[sym_or_id]
        except KeyError:
            try:
                sym_or_id = self._sym_id_map[sym_or_id]
                return self._instruments[sym_or_id]
            except KeyError:
                return None

    def instruments(self, sym_or_ids):
        if isinstance(sym_or_ids, six.string_types):
            return self._instrument(sym_or_ids)

        return [i for i in [self._instrument(sid) for sid in sym_or_ids] if i is not None]

    def get_future_contracts(self, underlying, date):
        date = date.replace(hour=0, minute=0, second=0)
        futures = [v for o, v in six.iteritems(self._instruments)
                   if v.type == 'Future' and v.underlying_symbol == underlying and
                   not o.endswith('88') and not o.endswith('99')]
        if not futures:
            return []

        return sorted(i.order_book_id for i in futures if i.listed_date <= date <= i.de_listed_date)


text:
package ${groupId};

import com.saucelabs.common.SauceOnDemandAuthentication;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.saucelabs.junit.Parallelized;
import com.saucelabs.junit.ConcurrentParameterized;
import com.saucelabs.junit.SauceOnDemandTestWatcher;

import java.net.URL;
import java.util.LinkedList;

import static org.junit.Assert.assertEquals;

import com.saucelabs.common.SauceOnDemandAuthentication;
import com.saucelabs.common.SauceOnDemandSessionIdProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.URL;
import java.util.LinkedList;

import static org.junit.Assert.assertEquals;

/**
 * Demonstrates how to write a JUnit test that runs tests against Sauce Labs using multiple browsers in parallel.
 * <p/>
 * The test also includes the {@link SauceOnDemandTestWatcher} which will invoke the Sauce REST API to mark
 * the test as passed or failed.
 *
 * @author Ross Rowe
 */
@RunWith(ConcurrentParameterized.class)
public class SampleSauceTest implements SauceOnDemandSessionIdProvider {

    /**
     * Constructs a {@link SauceOnDemandAuthentication} instance using the supplied user name/access key.  To use the authentication
     * supplied by environment variables or from an external file, use the no-arg {@link SauceOnDemandAuthentication} constructor.
     */
    public SauceOnDemandAuthentication authentication = new SauceOnDemandAuthentication("${userName}", "${accessKey}");

    /**
     * JUnit Rule which will mark the Sauce Job as passed/failed when the test succeeds or fails.
     */
    @Rule
    public SauceOnDemandTestWatcher resultReportingTestWatcher = new SauceOnDemandTestWatcher(this, authentication);

    /**
     * Represents the browser to be used as part of the test run.
     */
    private String browser;
    /**
     * Represents the operating system to be used as part of the test run.
     */
    private String os;
    /**
     * Represents the version of the browser to be used as part of the test run.
     */
    private String version;
    /**
     * Instance variable which contains the Sauce Job Id.
     */
    private String sessionId;

    /**
     * The {@link WebDriver} instance which is used to perform browser interactions with.
     */
    private WebDriver driver;

    /**
     * Constructs a new instance of the test.  The constructor requires three string parameters, which represent the operating
     * system, version and browser to be used when launching a Sauce VM.  The order of the parameters should be the same
     * as that of the elements within the {@link #browsersStrings()} method.
     * @param os
     * @param version
     * @param browser
     */
    public SampleSauceTest(String os, String version, String browser) {
        super();
        this.os = os;
        this.version = version;
        this.browser = browser;
    }

    /**
     * @return a LinkedList containing String arrays representing the browser combinations the test should be run against. The values
     * in the String array are used as part of the invocation of the test constructor
     */
    @ConcurrentParameterized.Parameters
    public static LinkedList browsersStrings() {
        LinkedList browsers = new LinkedList();
        browsers.add(new String[]{"Windows 8.1", "11", "internet explorer"});
        browsers.add(new String[]{"OSX 10.8", "6", "safari"});
        return browsers;
    }

    /**
     * Constructs a new {@link RemoteWebDriver} instance which is configured to use the capabilities defined by the {@link #browser},
     * {@link #version} and {@link #os} instance variables, and which is configured to run against ondemand.saucelabs.com, using
     * the username and access key populated by the {@link #authentication} instance.
     *
     * @throws Exception if an error occurs during the creation of the {@link RemoteWebDriver} instance.
     */
    @Before
    public void setUp() throws Exception {

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.BROWSER_NAME, browser);
        if (version != null) {
            capabilities.setCapability(CapabilityType.VERSION, version);
        }
        capabilities.setCapability(CapabilityType.PLATFORM, os);
        capabilities.setCapability("name", "Sauce Sample Test");
        this.driver = new RemoteWebDriver(
                new URL("https://" + authentication.getUsername() + ":" + authentication.getAccessKey() + "@ondemand.saucelabs.com:443/wd/hub"),
                capabilities);
        this.sessionId = (((RemoteWebDriver) driver).getSessionId()).toString();

    }

    /**
     * Runs a simple test verifying the title of the sauce labs test page.
     * @throws Exception
     */
    @Test
    public void sauceGuineaPig() throws Exception {
        driver.get("https://saucelabs.com/test/guinea-pig");
        assertEquals("I am a page title - Sauce Labs", driver.getTitle());
    }

    /**
     * Closes the {@link WebDriver} session.
     *
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        driver.quit();
    }

    /**
     *
     * @return the value of the Sauce Job id.
     */
    @Override
    public String getSessionId() {
        return sessionId;
    }
}


text:
<?php
namespace empire\framework\tests\cookie;

use \PHPUnit_Framework_TestCase;
use empire\framework\cookie\CookiePath;

/**
 * Test class for CookiePath.
 */
class CookiePathTest extends \PHPUnit_Framework_TestCase {

	/**
	 * Provides test data for the get path test.
	 *
	 * @return array the test data
	 */
	public function getPathProvider() {
		$res = array();
		$res[] = array(new CookiePath('/sites/', 'app', 'page'), '/sites/app/page/');
		$res[] = array(new CookiePath('/sites/', 'app', null), '/sites/app/');
		$res[] = array(new CookiePath('/sites/', null, null), '/sites/');
		$res[] = array(new CookiePath('/'), '/');
		return $res;
	}

	/**
	 * Tests getting the path.
	 *
	 * @dataProvider getPathProvider
	 * @covers empire\framework\cookie\CookiePath::getPath
	 */
	public function testGetPath(CookiePath $cookiePath, $res) {
		$this->assertSame($cookiePath->getPath(), $res);
	}

	/**
	 * Provides test data for the get path test.
	 *
	 * @return array the test data
	 */
	public function toStringProvider() {
		$res = array();
		$res[] = array(new CookiePath('/sites/', 'app', 'page'), '/sites/app/page/');
		$res[] = array(new CookiePath('/sites/', 'app', null), '/sites/app/');
		$res[] = array(new CookiePath('/sites/', null, null), '/sites/');
		$res[] = array(new CookiePath('/'), '/');
		return $res;
	}

	/**
	 * Tests returning a string representation.
	 *
	 * @dataProvider toStringProvider
	 * @covers empire\framework\cookie\CookiePath::__toString
	 */
	public function testToString($cookiePath, $res) {
		$this->assertEquals($res, $cookiePath);
	}

}


text:
module Dapp
  module Dimg
    module Build
      module Stage
        module Install
          class GAPreInstallPatch < GARelatedBase
            include Mod::Group

            def initialize(dimg, next_stage)
              @prev_stage = GAArchive.new(dimg, self)
              super
            end

            def related_stage_name
              :install
            end
          end # GAPostInstallPatch
        end
      end # Stage
    end # Build
  end # Dimg
end # Dapp


text:
package info.collaboration_station.utilities;

/**
 * Represents an event in the background which would need to be polled for and
 * responded to.
 *
 * @author johnmichaelreed2
 */
public interface BackgroundEvent {

    /**
     * Checks to see if a background event has occurred. If this method returns
     * true, {@link #respondToEventOccurance() } is called to handle the event.
     *
     * @return whether or not the event has occurred.
     */
    public abstract boolean checkForEventOccurance();

    /**
     * This method is triggered when {@link #checkForEventOccurance() } returns
     * true. This method responds to the background event detected by {@link #checkForEventOccurance()
     * }
     */
    public abstract void respondToEventOccurance();
}


text:
<?php
namespace App\Service;

use App\Entity\Award;
use App\Entity\Config;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;

class PredictionService
{
    /** @var EntityManagerInterface */
    private $em;

    /** @var ConfigService */
    private $configService;

    public function __construct(EntityManagerInterface $em, ConfigService $configService)
    {
        $this->em = $em;
        $this->configService = $configService;
    }

    public function arePredictionsLocked()
    {
        if ($this->configService->getConfig()->isReadOnly()) {
            return true;
        }

        if (!$this->configService->getConfig()->getStreamTime()) {
            return false;
        }

        return new DateTime('+14 days') > $this->configService->getConfig()->getStreamTime();
    }

    public function areResultsAvailable()
    {
        return $this->configService->getConfig()->isPagePublic('results');
    }

    public function isAwardResultAvailable(Award $award)
    {
        return $this->areResultsAvailable();
    }
}


text:
require 'spec_helper'

describe CsvFile do
  describe "validations" do
    let(:default_params) { {
        :contents => StringIO.new('a,b,c'),
        :column_names => ['a', 'b', 'c'],
        :types => ['a', 'b', 'c'],
        :delimiter => '"',
        :to_table => "new_table",
        :has_header => false,
        :new_table => false,
        :truncate => false,
        :user => users(:owner),
        :workspace => workspaces(:public)
    }}

    it "is not ready to import if it is missing a setting" do
      [:column_names, :types, :delimiter, :has_header, :to_table].each do |param|
        c = CsvFile.new(default_params.reject{ |k,v| k == param }, :without_protection => true)
        c.ready_to_import?.should be_false
      end
    end

    it "is valid when tab is the delimiter" do
      c = CsvFile.new(default_params.merge(:delimiter => "\t"), :without_protection => true)
      c.ready_to_import?.should be_true
    end

    it "requires a non-nil delimiter" do
      c = CsvFile.new(default_params.merge(:delimiter => nil), :without_protection => true)
      c.ready_to_import?.should be_false
    end

    it "requires a non-empty delimiter" do
      c = CsvFile.new(default_params.merge(:delimiter => ''), :without_protection => true)
      c.ready_to_import?.should be_false
    end

    it "does not validate the size of the CSV file if the file is not user uploaded" do
      any_instance_of(Paperclip::StringioAdapter) do |a|
        stub(a).size { ChorusConfig.instance['file_sizes_mb']['csv_imports'].megabytes + 1.megabyte }
      end
      c = CsvFile.new(default_params.merge(:user_uploaded => false), :without_protection => true)
      c.valid?.should be_true
    end

    it { should validate_presence_of(:user) }
    it { should validate_presence_of(:workspace) }

    context "validate file sizes" do
      let(:max_csv_import_size) {ChorusConfig.instance['file_sizes_mb']['csv_imports']}

      it { should validate_attachment_size(:contents).less_than(max_csv_import_size.megabytes) }
    end
  end

  it_behaves_like 'an upload that goes stale'

  describe '#escaped_column_names' do
    let(:csv_file) { FactoryGirl.build(:csv_file, :column_names => ['where', 'order', 'select'])}

    it 'returns escaped column names' do
      csv_file.escaped_column_names.should == %w{"where" "order" "select"}
    end
  end

  describe "#table_already_exists" do
    let(:csv_file) { csv_files(:default) }
    let(:user) { csv_file.user }
    let(:schema) { schemas(:public) }
    let(:workspace) { csv_file.workspace }
    let(:table_name) { "foo_bar" }
    subject { csv_file.table_already_exists(table_name) }

    before do
      workspace.sandbox = schema
      workspace.save!
      connection = Object.new
      stub(workspace.sandbox).connect_as(user) { connection }
      stub(connection).table_exists? { table_exists }
    end

    context "when the table exists" do
      let(:table_exists) { true }

      it { should be_true }
    end

    context "when the table does not exist" do
      let(:table_exists) { false }

      it { should be_false }
    end
  end
end


text:
angular.module('app.transactions')
	.config(['$translateProvider', function ($translateProvider) {
		$translateProvider.translations('fr', {
			transactions: {
				title: 'Transactions',
				pseudo: 'Pseudo',
				amount: 'Montant',
				date: 'Date',
				comment: 'Commentaire',
				edit: {
					legend: 'Transaction',
					contact: 'Contact',
					amount: 'Montant',
					payer: 'Qui a payé',
					credit: 'Moi',
					date: 'Date de la transaction',
					comment: 'Commentaire'
				}
			}
		});
	}])
;


text:
function generate_protos() {
  export GOPATH=$(go env GOPATH)
  export PATH=$GOPATH/bin:$PATH

  go get -u google.golang.org/protobuf/cmd/protoc-gen-go@v1.25.0

  find ./proto -type f -name "*.proto" -exec protoc --go_out=paths=source_relative:. {} \;
}

generate_protos


text:
package com.bbn.bue.common.strings.offsets;

/**
 * Character offsets by UTF-16 code units.  If all code points in a string are in the
 * basic multilingual plane, these will be the same as {@link CharOffset}s. However,
 * characters outside the BMP will be encoded as two UTF-16 code units.
 *
 * This is useful because Java stores strings using UTF-16 internally.
 */
public final class UTF16Offset extends AbstractOffset<UTF16Offset> {

  private UTF16Offset(final int val) {
    super(val);
  }

  public static UTF16Offset of(int val) {
    return new UTF16Offset(val);
  }

  @Override
  public String toString() {
    // j for Java
    return "j" + Integer.toString(asInt());
  }

  @Override
  public UTF16Offset shiftedCopy(final int shiftAmount) {
    return UTF16Offset.of(asInt() + shiftAmount);
  }
}


text:
layout: organization
category: local

title: Food Bank For NYC
impact_area: Human Rights
keywords:
location_services:
location_offices:
website: www.foodbanknyc.org

description:
mission: |
  Depending on the needs of the senior center, we hope to help them with their needs like food.

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: Queens
state: NY
address: |
  75-01 Broadway
  Queens NY 11373
lat: 40.746198
lng: -73.890289
phone: 718-478-7171
ext:
fax:
email:
preferred_contact:
contact_person_intro:
---


text:
<?php
namespace Application\Gateway;

use Rox\Gateway\MongoDb\AbstractGateway;

class Karts extends AbstractGateway
{

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal partial class Binder
    {
        internal struct ProcessedFieldInitializers
        {
            internal ImmutableArray<BoundInitializer> BoundInitializers { get; set; }
            internal BoundStatement? LoweredInitializers { get; set; }
            internal bool HasErrors { get; set; }
            internal ImportChain? FirstImportChain { get; set; }
        }

        internal static void BindFieldInitializers(
            CSharpCompilation compilation,
            SynthesizedInteractiveInitializerMethod? scriptInitializerOpt,
            ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> fieldInitializers,
            BindingDiagnosticBag diagnostics,
            ref ProcessedFieldInitializers processedInitializers)
        {
            var diagsForInstanceInitializers = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies);
            ImportChain? firstImportChain;
            processedInitializers.BoundInitializers = BindFieldInitializers(compilation, scriptInitializerOpt, fieldInitializers, diagsForInstanceInitializers, out firstImportChain);
            processedInitializers.HasErrors = diagsForInstanceInitializers.HasAnyErrors();
            processedInitializers.FirstImportChain = firstImportChain;
            diagnostics.AddRange(diagsForInstanceInitializers);
            diagsForInstanceInitializers.Free();
        }

        internal static ImmutableArray<BoundInitializer> BindFieldInitializers(
            CSharpCompilation compilation,
            SynthesizedInteractiveInitializerMethod? scriptInitializerOpt,
            ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers,
            BindingDiagnosticBag diagnostics,
            out ImportChain? firstImportChain)
        {
            if (initializers.IsEmpty)
            {
                firstImportChain = null;
                return ImmutableArray<BoundInitializer>.Empty;
            }

            var boundInitializers = ArrayBuilder<BoundInitializer>.GetInstance();
            if (scriptInitializerOpt is null)
            {
                BindRegularCSharpFieldInitializers(compilation, initializers, boundInitializers, diagnostics, out firstImportChain);
            }
            else
            {
                BindScriptFieldInitializers(compilation, scriptInitializerOpt, initializers, boundInitializers, diagnostics, out firstImportChain);
            }
            return boundInitializers.ToImmutableAndFree();
        }

        /// <summary>
        /// In regular C#, all field initializers are assignments to fields and the assigned expressions
        /// may not reference instance members.
        /// </summary>
        internal static void BindRegularCSharpFieldInitializers(
            CSharpCompilation compilation,
            ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers,
            ArrayBuilder<BoundInitializer> boundInitializers,
            BindingDiagnosticBag diagnostics,
            out ImportChain? firstDebugImports)
        {
            firstDebugImports = null;

            foreach (ImmutableArray<FieldOrPropertyInitializer> siblingInitializers in initializers)
            {
                // All sibling initializers share the same parent node and tree so we can reuse the binder
                // factory across siblings.  Unfortunately, we cannot reuse the binder itself, because
                // individual fields might have their own binders (e.g. because of being declared unsafe).
                BinderFactory? binderFactory = null;

                foreach (FieldOrPropertyInitializer initializer in siblingInitializers)
                {
                    FieldSymbol fieldSymbol = initializer.FieldOpt;
                    Debug.Assert((object)fieldSymbol != null);

                    // A constant field of type decimal needs a field initializer, so
                    // check if it is a metadata constant, not just a constant to exclude
                    // decimals. Other constants do not need field initializers.
                    if (!fieldSymbol.IsMetadataConstant)
                    {
                        //Can't assert that this is a regular C# compilation, because we could be in a nested type of a script class.
                        SyntaxReference syntaxRef = initializer.Syntax;

                        switch (syntaxRef.GetSyntax())
                        {
                            case EqualsValueClauseSyntax initializerNode:
                                if (binderFactory == null)
                                {
                                    binderFactory = compilation.GetBinderFactory(syntaxRef.SyntaxTree);
                                }

                                Binder parentBinder = binderFactory.GetBinder(initializerNode);

                                if (firstDebugImports == null)
                                {
                                    firstDebugImports = parentBinder.ImportChain;
                                }

                                parentBinder = parentBinder.GetFieldInitializerBinder(fieldSymbol);

                                BoundFieldEqualsValue boundInitializer = BindFieldInitializer(parentBinder, fieldSymbol, initializerNode, diagnostics);

                                if (!boundInitializer.Value.HasAnyErrors)
                                {
                                    var field = boundInitializer.Field;
                                    if (field.Type.IsRefLikeType)
                                    {
                                        BoundExpression value = parentBinder.ValidateEscape(boundInitializer.Value, CallingMethodScope, isByRef: false, diagnostics);
                                        boundInitializer = boundInitializer.Update(field, boundInitializer.Locals, value);
                                    }
                                }

                                boundInitializers.Add(boundInitializer);
                                break;

                            case ParameterSyntax parameterSyntax: // Initializer for a generated property based on record parameters

                                if (firstDebugImports == null)
                                {
                                    if (binderFactory == null)
                                    {
                                        binderFactory = compilation.GetBinderFactory(syntaxRef.SyntaxTree);
                                    }

                                    firstDebugImports = binderFactory.GetBinder(parameterSyntax).ImportChain;
                                }

                                boundInitializers.Add(new BoundFieldEqualsValue(parameterSyntax, fieldSymbol, ImmutableArray<LocalSymbol>.Empty,
                                                                                new BoundParameter(parameterSyntax,
                                                                                ((SynthesizedRecordPropertySymbol)fieldSymbol.AssociatedSymbol).BackingParameter).MakeCompilerGenerated()));
                                break;

                            default:
                                throw ExceptionUtilities.Unreachable();
                        }
                    }
                }
            }
        }

        internal Binder GetFieldInitializerBinder(FieldSymbol fieldSymbol, bool suppressBinderFlagsFieldInitializer = false)
        {
            Debug.Assert((ContainingMemberOrLambda is TypeSymbol containing && TypeSymbol.Equals(containing, fieldSymbol.ContainingType, TypeCompareKind.ConsiderEverything2)) || //should be the binder for the type
                    fieldSymbol.ContainingType.IsImplicitClass); //however, we also allow fields in namespaces to help support script scenarios

            Binder binder = this;

            if (!fieldSymbol.IsStatic && fieldSymbol.ContainingType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().SingleOrDefault() is SynthesizedRecordConstructor recordCtor)
            {
                binder = new InMethodBinder(recordCtor, binder);
            }

            return new LocalScopeBinder(binder).WithAdditionalFlagsAndContainingMemberOrLambda(suppressBinderFlagsFieldInitializer ? BinderFlags.None : BinderFlags.FieldInitializer, fieldSymbol);
        }

        /// <summary>
        /// In script C#, some field initializers are assignments to fields and others are global
        /// statements.  There are no restrictions on accessing instance members.
        /// </summary>
        private static void BindScriptFieldInitializers(
            CSharpCompilation compilation,
            SynthesizedInteractiveInitializerMethod scriptInitializer,
            ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers,
            ArrayBuilder<BoundInitializer> boundInitializers,
            BindingDiagnosticBag diagnostics,
            out ImportChain? firstDebugImports)
        {
            firstDebugImports = null;

            for (int i = 0; i < initializers.Length; i++)
            {
                ImmutableArray<FieldOrPropertyInitializer> siblingInitializers = initializers[i];

                // All sibling initializers share the same parent node and tree so we can reuse the binder
                // factory across siblings.  Unfortunately, we cannot reuse the binder itself, because
                // individual fields might have their own binders (e.g. because of being declared unsafe).
                BinderFactory? binderFactory = null;
                // Label instances must be shared across all global statements.
                ScriptLocalScopeBinder.Labels? labels = null;

                for (int j = 0; j < siblingInitializers.Length; j++)
                {
                    var initializer = siblingInitializers[j];
                    var fieldSymbol = initializer.FieldOpt;

                    if ((object)fieldSymbol != null && fieldSymbol.IsConst)
                    {
                        // Constants do not need field initializers.
                        continue;
                    }

                    var syntaxRef = initializer.Syntax;
                    var syntaxTree = syntaxRef.SyntaxTree;
                    Debug.Assert(syntaxTree.Options.Kind != SourceCodeKind.Regular);

                    var syntax = (CSharpSyntaxNode)syntaxRef.GetSyntax();
                    var syntaxRoot = syntaxTree.GetCompilationUnitRoot();

                    if (binderFactory == null)
                    {
                        binderFactory = compilation.GetBinderFactory(syntaxTree);
                        labels = new ScriptLocalScopeBinder.Labels(scriptInitializer, syntaxRoot);
                    }

                    Binder scriptClassBinder = binderFactory.GetBinder(syntax);
                    Debug.Assert(scriptClassBinder.ContainingMemberOrLambda is NamedTypeSymbol { IsScriptClass: true });

                    if (firstDebugImports == null)
                    {
                        firstDebugImports = scriptClassBinder.ImportChain;
                    }

                    Binder parentBinder = new ExecutableCodeBinder(
                        syntaxRoot,
                        scriptInitializer,
                        new ScriptLocalScopeBinder(labels, scriptClassBinder));

                    BoundInitializer boundInitializer;
                    if ((object?)fieldSymbol != null)
                    {
                        boundInitializer = BindFieldInitializer(
                            parentBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.FieldInitializer, fieldSymbol),
                            fieldSymbol,
                            (EqualsValueClauseSyntax)syntax,
                            diagnostics);
                    }
                    else
                    {
                        boundInitializer = BindGlobalStatement(
                            parentBinder,
                            scriptInitializer,
                            (StatementSyntax)syntax,
                            diagnostics,
                            isLast: i == initializers.Length - 1 && j == siblingInitializers.Length - 1);
                    }

                    boundInitializers.Add(boundInitializer);
                }
            }
        }

        private static BoundInitializer BindGlobalStatement(
            Binder binder,
            SynthesizedInteractiveInitializerMethod scriptInitializer,
            StatementSyntax statementNode,
            BindingDiagnosticBag diagnostics,
            bool isLast)
        {
            var statement = binder.BindStatement(statementNode, diagnostics);
            if (isLast && !statement.HasAnyErrors)
            {
                // the result of the last global expression is assigned to the result storage for submission result:
                if (binder.Compilation.IsSubmission)
                {
                    // insert an implicit conversion for the submission return type (if needed):
                    var expression = InitializerRewriter.GetTrailingScriptExpression(statement);
                    if (expression != null &&
                        ((object?)expression.Type == null || !expression.Type.IsVoidType()))
                    {
                        var submissionResultType = scriptInitializer.ResultType;
                        expression = binder.GenerateConversionForAssignment(submissionResultType, expression, diagnostics);
                        statement = new BoundExpressionStatement(statement.Syntax, expression, expression.HasErrors);
                    }
                }

                // don't allow trailing expressions after labels (as in regular C#, labels must be followed by a statement):
                if (statement.Kind == BoundKind.LabeledStatement)
                {
                    var labeledStatementBody = ((BoundLabeledStatement)statement).Body;
                    while (labeledStatementBody.Kind == BoundKind.LabeledStatement)
                    {
                        labeledStatementBody = ((BoundLabeledStatement)labeledStatementBody).Body;
                    }

                    if (InitializerRewriter.GetTrailingScriptExpression(labeledStatementBody) != null)
                    {
                        Error(diagnostics, ErrorCode.ERR_SemicolonExpected, ((ExpressionStatementSyntax)labeledStatementBody.Syntax).SemicolonToken);
                    }
                }
            }

            return new BoundGlobalStatementInitializer(statementNode, statement);
        }

        private static BoundFieldEqualsValue BindFieldInitializer(Binder binder, FieldSymbol fieldSymbol, EqualsValueClauseSyntax equalsValueClauseNode,
            BindingDiagnosticBag diagnostics)
        {
            Debug.Assert(!fieldSymbol.IsMetadataConstant);

            var fieldsBeingBound = binder.FieldsBeingBound;

            var sourceField = fieldSymbol as SourceMemberFieldSymbolFromDeclarator;
            bool isImplicitlyTypedField = (object?)sourceField != null && sourceField.FieldTypeInferred(fieldsBeingBound);

            // If the type is implicitly typed, the initializer diagnostics have already been reported, so ignore them here:
            // CONSIDER (tomat): reusing the bound field initializers for implicitly typed fields.
            BindingDiagnosticBag initializerDiagnostics;
            if (isImplicitlyTypedField)
            {
                initializerDiagnostics = BindingDiagnosticBag.Discarded;
            }
            else
            {
                initializerDiagnostics = diagnostics;
            }

            binder = new ExecutableCodeBinder(equalsValueClauseNode, fieldSymbol, new LocalScopeBinder(binder));
            BoundFieldEqualsValue boundInitValue = binder.BindFieldInitializer(fieldSymbol, equalsValueClauseNode, initializerDiagnostics);

            return boundInitValue;
        }
    }
}


text:
#include <oledlg.h>

#define IDS_RESULTOBJDESC               101
#define IDS_RESULTFILEOBJDESC           102
#define IDS_BROWSE                      103
#define IDS_NOTOLEMOD                   104
#define IDS_NOTOLEMODCAPTION            105

#define UIINSERTOBJECT                  129

#define IDC_OBJTYPELIST                 1000
#define IDC_RESULT                      1001
#define IDC_CREATENEW                   1002
#define IDC_CREATECONTROL               1003
#define IDC_CREATEFROMFILE              1004
#define IDC_OBJTYPELBL                  1005
#define IDC_RESULTDESC                  1006
#define IDC_ADDCONTROL                  1007
#define IDC_ASICON                      1008
#define IDC_BROWSE                      1009
#define IDC_FILELBL                     1010
#define IDC_FILE                        1011

/* String ids for Paste Special */
#define IDS_PS_PASTE_DATA                 0x190
#define IDS_PS_PASTE_OBJECT               0x191
#define IDS_PS_PASTE_OBJECT_AS_ICON       0x192
#define IDS_PS_PASTE_LINK_DATA            0x193
#define IDS_PS_PASTE_LINK_OBJECT          0x194
#define IDS_PS_PASTE_LINK_OBJECT_AS_ICON  0x195
#define IDS_PS_NON_OLE                    0x196
#define IDS_PS_UNKNOWN_TYPE               0x197
#define IDS_PS_UNKNOWN_SRC                0x198
#define IDS_PS_UNKNOWN_APP                0x199


text:
/***
Generic IP utilities.

@license MIT
@module lua_ip
*/
#include <lua.h>
#include <lauxlib.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <net/if.h>

#if LUA_VERSION_NUM < 502
# define luaL_newlib(L,l) (lua_newtable(L), luaL_register(L,NULL,l))
# define lua_rawlen lua_objlen
#endif

/// Retrieve the first active non loopback IPv4 address
// @return ip_str
// @function get_ip()
static int get_ipv4(lua_State *L) {
  struct ifaddrs * ifAddrStruct=NULL;
  struct ifaddrs * ifa=NULL;
  void * tmpAddrPtr=NULL;

  getifaddrs(&ifAddrStruct);

  const char * interface = lua_tostring(L, 1);

  int found = 0;

  for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
    if (!ifa->ifa_addr) {
      continue;
    }

    if (!interface || strcmp(interface, ifa->ifa_name) == 0) {
      if ((ifa->ifa_flags & IFF_UP) == 0) continue; // Should be running
      if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) continue; // Should not be loopback

      if (ifa->ifa_addr->sa_family == AF_INET) { // Should be IPv4
        tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
        char addressBuffer[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);

        lua_pushstring(L, addressBuffer);
        found = 1;
        break;
      }
    }
  }

  if (!found) {
    lua_pushstring(L, NULL);
  }

  if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
  return 1;
}

static const luaL_Reg lua_ip[] = {
  {"get_ipv4", get_ipv4},
  {NULL, NULL}
};

int luaopen_lua_ip(lua_State *L){
  luaL_newlib(L, lua_ip);
  return 1;
}