text:
/// <reference path="../lib/angular.1.2.26.js" />

// Directive that creates a searchable dropdown list.

// Associated attributes:-
// ac-model - use instead of ng-model
// ac-options - use instead of ng-options.

// Example:- <select class="ac-select" ac-model="colour" ac-options="c.name for c in colours"></select>

// Note:- ac-options works like ng-options, but does not support option groups

angular.module("acute.select", [])
.directive("acSelect", function($parse, acuteSelectService) {
    var defaultSettings = acuteSelectService.getSettings();
    return {
        restrict: "EAC",
        scope: {
            "acSettings": "@",
            "acOptions": "@",
            "model": "=acModel",
            "acChange": "&",
            "keyField": "@acKey",
            "acRefresh": "=",
            "acFocusWhen": "="
        },
        replace: true,
        templateUrl: defaultSettings.templatePath + "template.html",
        link: function(scope, element, attrs) {
            scope.initialise();
        },
        // **************************************************************
        //                          CONTROLLER
        // **************************************************************
        controller: function($scope, $element, $window, $rootScope, $timeout, $filter, navKey, safeApply) {

            $scope.initialise = function() {
                $scope.settings = acuteSelectService.getSettings();
                $scope.previousSearchText = "";
                $scope.searchText = "";
                $scope.longestText = "";
                $scope.comboText = "";
                $scope.items = [];
                $scope.allItems = [];        // Unfiltered
                $scope.selectedItem = null;
                $scope.allDataLoaded = false;
                $scope.scrollTo = 0;         // To change scroll position
                $scope.scrollPosition = 0;   // Reported scroll position
                $scope.listHeight = 0;
                $scope.matchFound = false;

                // Check that ac-options and ac-model values are set
                if (!$scope.acOptions || $scope.model === undefined) {
                    throw "ac-model and ac-options attributes must be set";
                }

                processSettings();

                // Parse acOptions

                // Value should be in the form "label for value in array" or "for value in array"
                var words = $scope.acOptions.split(' ');
                var len = words.length;
                $scope.textField = null;
                $scope.dataFunction = null;

                if (len > 3) {
                    if (len > 4) {
                        var label = words[len - 5];     // E.g. colour.name
                        $scope.textField = label.split(".")[1];
                    }
                    var dataName = words[len - 1];

                    // See if a data load function is specified, i.e. name ends in "()"
                    if (dataName.indexOf("()") === dataName.length - 2) {
                        dataName = dataName.substr(0, dataName.length - 2)
                        // Get a reference to the data function
                        var dataFunction = $scope.$parent.$eval(dataName);
                        if (typeof dataFunction === "function") {
                            $scope.dataFunction = dataFunction;
                            if ($scope.settings.loadOnCreate) {
                                // Load initial data (args are callback function, search text and item offset)
                                $scope.dataFunction($scope.dataCallback, "", 0);
                            }
                        }
                        else {
                            throw "Invalid data function: " + dataName;
                        }
                    }
                    else {
                        // Get the data from the parent $scope
                        var dataItems = $scope.$parent.$eval(dataName);
                        loadStaticData(dataItems);
                        // Watch for any change to the data
                        $scope.$parent.$watch(dataName, function(newVal, oldVal) {
                            if (newVal !== oldVal && angular.isArray(newVal)) {
                                loadStaticData(newVal)
                            }
                        });
                    }
                }

                // Save initial selection, if any
                $scope.setInitialSelection();
            };

            function loadStaticData(dataItems) {
                // Create dropdown items
                $scope.loadItems(dataItems, $scope.model);
                // Save selected item
                $scope.confirmedItem = angular.copy($scope.selectedItem);
                $scope.allDataLoaded = $scope.items.length > 0;
            }

            // If the ac-refresh attribute is set, watch it. If its value gets set to true, re-initialise.
            if ($scope.acRefresh !== undefined) {
                $scope.$watch("acRefresh", function(newValue, oldValue) {
                    if (newValue === true) {
                        $scope.initialise();
                    }
                });
            }

            // Handle ac-focus-when attribute. When set to true
            // give focus to either the combo or search text box
            if ($scope.acFocusWhen !== undefined) {
                $scope.$watch("acFocusWhen", function(newValue, oldValue) {
                    if (newValue === true) {
                        // Set flag to fire the ac-focus directive
                        if ($scope.settings.comboMode) {
                            $scope.comboFocus = true;
                        }
                        else {
                            $scope.searchBoxFocus = true;
                        }
                        $scope.acFocusWhen = false;
                    }
                });
            }

            $scope.setInitialSelection = function() {
                if ($scope.model) {
                    $scope.initialSelection = angular.copy($scope.model);
                    $scope.initialItem = $scope.getItemFromDataItem($scope.model, 0);
                    $scope.confirmedItem = $scope.selectedItem = $scope.initialItem;
                    $scope.comboText = $scope.confirmedItem ? $scope.confirmedItem.text : "";
                }
            };

            // Create dropdown items based on the source data items
            $scope.loadItems = function(dataItems, selectedDataItem) {
                var itemCount, itemIndex, item, key = $scope.keyField;

                if (angular.isArray(dataItems)) {

                    var foundSelected = false;
                    itemCount = $scope.items.length;

                    angular.forEach(dataItems, function(dataItem, index) {
                        itemIndex = itemCount + index;
                        item = $scope.getItemFromDataItem(dataItem, itemIndex);
                        if (item) {
                            $scope.items.push(item);
                            // If not currently filtering
                            if (!$scope.searchText) {
                                // Look for a matching item
                                if (dataItem === selectedDataItem || (key && selectedDataItem && dataItem[key] == selectedDataItem[key])) {
                                    confirmSelection(item);
                                    foundSelected = true;
                                }
                            }
                            else if ($scope.searchText.toLowerCase() === item.text.toLowerCase()) {
                                // Search text matches item
                                confirmSelection(item);
                            }

                            if (item.text.length > $scope.longestText.length) {
                                if ($scope.maxCharacters && item.text.length > $scope.maxCharacters) {
                                    $scope.longestText = item.text.substr(0, $scope.maxCharacters);
                                }
                                else {
                                    $scope.longestText = item.text;
                                }
                            }
                        }
                    });

                    // If not currently filtering and there's no selected item, but we have an initial selection
                    if (!$scope.searchText && $scope.initialSelection && !foundSelected) {
                        // Create a new item
                        item = $scope.getItemFromDataItem($scope.initialSelection, 0);
                        if (item) {
                            // Add it to the start of the items array
                            $scope.items.unshift(item);
                            // Update indexes
                            angular.forEach($scope.items, function(item, index) {
                                item.index = index;
                            });

                            confirmSelection(item);
                        }
                    }

                    // If data is not filtered
                    if (!$scope.searchText) {
                        angular.copy($scope.items, $scope.allItems);
                    }

                    $scope.setListHeight();

                    checkItemCount($scope.items);
                }
            };

            function processSettings() {
                if ($scope.acSettings) {
                    var settings = $scope.$eval($scope.acSettings);
                    if (typeof settings === "object") {
                        // Merge settings with default values
                        angular.extend($scope.settings, settings);
                    }
                }
                $scope.longestText = $scope.settings.placeholderText;

                $scope.maxTextWidth = "";

                // If maxWidth is set, limit textbox size, allowing room for dropdown icon
                if ($scope.settings.maxWidth) {
                    var maxWidth = parseInt($scope.settings.maxWidth);
                    // Set an approximate limit to the number of characters to allow in $scope.longestText
                    $scope.maxCharacters = Math.round(maxWidth / 6);
                    $scope.maxTextWidth = (maxWidth - 100) + "px";
                }
            }

            function checkItemCount() {
                $scope.noItemsFound = $scope.items.length === 0;
                $scope.noItemsAdditional = "";
                // If no item is found clear the selected item
                if ($scope.noItemsFound) {
                    $scope.selectedItem = null;
                    if ($scope.settings.comboMode && $scope.comboText && $scope.settings.allowCustomText) {
                        $scope.noItemsAdditional = "Press Enter to Add.";
                    }
                }
            }

            $scope.getItemFromDataItem = function(dataItem, itemIndex) {
                var item = null;
                if (dataItem !== null) {
                    if ($scope.textField === null || $scope.textField === undefined && typeof dataItem === 'string') {
                        item = { "text": dataItem, "value": dataItem, "index": itemIndex };
                    }
                    else if (dataItem[$scope.textField]) {
                        item = { "text": dataItem[$scope.textField], "value": dataItem, "index": itemIndex };
                    }
                }
                return item;
            };

            // Set height of list according to number of visible items
            $scope.setListHeight = function() {
                var itemCount = $scope.items.length;
                if (itemCount > $scope.settings.itemsInView) {
                    itemCount = $scope.settings.itemsInView;
                }

                $scope.listHeight = $scope.settings.itemHeight * itemCount;
            };

            $scope.$watch("model", function(newValue, oldValue) {
                if ($scope.modelUpdating) {
                    $scope.modelUpdating = false;
                }
                else if (!newValue && !oldValue) {
                    // Do nothing
                }
                else if (newValue && !oldValue) {
                    // Model no longer null
                    $scope.setInitialSelection();
                }
                else if (oldValue && !newValue) {
                    // Model cleared
                    $scope.setInitialSelection();
                }
                else {
                    // Check that the text is different
                    if (!$scope.textField || newValue[$scope.textField] !== oldValue[$scope.textField]) {
                        // Model has been changed in the parent scope
                        $scope.setInitialSelection();
                    }
                }
            });

            if ($scope.selectedItem) {
                $scope.comboText = $scope.selectedItem.text;
            }

            // Close all instances when user clicks elsewhere
            $window.onclick = function(event) {
                closeWhenClickingElsewhere(event, function() {
                    $scope.sentBroadcast = false;
                    $rootScope.$broadcast("ac-select-close-all");
                });
            };

            // Keyboard events
            $scope.keyHandler = function(event) {

                if (!$scope.settings.showSearchBox) {
                    handleCharCodes(event);
                }

                var keyCode = event.which || event.keyCode;

                if (keyCode === navKey.downArrow) {
                    $scope.popupVisible = true;
                }

                if ($scope.popupVisible || keyCode === navKey.del) {
                    var stopPropagation = true;
                    switch (keyCode) {
                        case navKey.downArrow:
                            downArrowKey();
                            break;
                        case navKey.upArrow:
                            upArrowKey();
                            break;
                        case navKey.enter:
                            enterKey();
                            break;
                        case navKey.end:
                            endKey();
                            break;
                        case navKey.home:
                            homeKey();
                            break;
                        case navKey.escape:
                            escapeKey();
                            break;
                        case navKey.del:
                            deleteKey(event);
                            break;
                        case navKey.pageUp:
                            pageUpKey();
                            break;
                        case navKey.pageDown:
                            pageDownKey();
                            break;
                        default:
                            stopPropagation = false;
                            break;
                    }

                    if (stopPropagation) event.stopPropagation();
                }
            };

            function handleCharCodes(event) {
                var character, i, item;
                if (event.keyCode) {
                    character = String.fromCharCode(event.keyCode);
                    for (i = 0; i < $scope.items.length; i++) {
                        item = $scope.items[i];
                        if (item.text.length > 0 && item.text.substr(0, 1).toUpperCase() === character) {
                            $scope.selectedItem = item;
                        }
                    }
                }
            }

            // Callback function to receive async data
            $scope.dataCallback = function(data, searchText, offset) {

                // Quit if search text has changed since the data function was called
                if (searchText !== undefined && searchText !== $scope.searchText) {
                    return;
                }

                var selectedDataItem = null;

                $scope.dataItems = data;

                // If we have a selected item, get its value
                if ($scope.selectedItem !== null) {
                    selectedDataItem = $scope.selectedItem.value;
                }
                else {
                    selectedDataItem = $scope.model;
                }

                // Clear all existing items, unless offset > 0, i.e. we're paging and getting additional items
                if (!offset || offset == 0) {
                    $scope.items = [];
                }

                $scope.loadItems(data, selectedDataItem);

                // If not in paging mode
                if (!$scope.settings.pageSize) {
                    // All data is now loaded
                    $scope.allDataLoaded = true;
                    // Clear loadOnOpen flag to avoid re-loading when dropdown is next opened
                    $scope.settings.loadOnOpen = false;
                }
                else {

                    // All data is loaded if fewer than [pageSize] items were returned
                    $scope.allDataLoaded = data.length < $scope.settings.pageSize;

                    // If user was scrolling down
                    if ($scope.requestedItemIndex) {
                        // Select first of the newly loaded items (if present)
                        if ($scope.requestedItemIndex < $scope.items.length) {
                            $scope.selectedItem = $scope.items[$scope.requestedItemIndex];
                            ensureItemVisible($scope.selectedItem);
                        }
                        $scope.requestedItemIndex = null;
                    }
                }

                if ($scope.allDataLoaded) {
                    $scope.previousSearchText = $scope.searchText;
                }

                $scope.loading = false;
                $scope.loadMessage = "Load more...";

            };

            $scope.findData = function() {
                filterData($scope.searchText);
            };

            $scope.comboTextChange = function() {
                $scope.popupVisible = true;
                $scope.ensureDataLoaded();
                $scope.searchText = $scope.comboText;
                if ($scope.comboText == '' && $scope.settings.allowClear) {
                    clearSelection();
                }

                filterData($scope.comboText);
            };

            // Show/hide popup
            $scope.togglePopup = function() {
                $scope.popupVisible = !$scope.popupVisible;
                if ($scope.popupVisible) {
                    // Pop-up opening
                    if ($scope.settings.comboMode) {
                        $timeout(function() { $scope.comboFocus = true; });
                    }
                    else {
                        $timeout(function() { $scope.searchBoxFocus = true; });
                    }
                    $scope.ensureDataLoaded();
                    clearClientFilter();
                }
            };

            $scope.ensureDataLoaded = function() {
                if (!$scope.allDataLoaded && $scope.dataFunction && $scope.settings.loadOnOpen) {
                    // Load initial data (args are callback function, search text and item offset)
                    $scope.dataFunction($scope.dataCallback, "", 0);
                }
            };

            // When clicking on the ac-select-main div
            $scope.mainClick = function() {
                // Close any other ac-select instances
                $scope.sentBroadcast = true;
                $rootScope.$broadcast("ac-select-close-all");
            };

            $scope.$on("ac-select-close-all", function() {
                if (!$scope.sentBroadcast && $scope.popupVisible) {
                    $scope.popupVisible = false;
                    safeApply($scope);
                    // If clear is not allowed and we're in combo mode
                    if (!$scope.settings.allowClear && $scope.settings.comboMode && $scope.selectedItem) {
                        // Update the combo text to reflect the currently selected item
                        $scope.comboText = $scope.confirmedItem.text;
                    }
                }
                else {
                    $scope.sentBroadcast = false;
                }
            });

            $scope.itemClick = function(i) {
                confirmSelection($scope.items[i]);
            };

            $scope.getItemClass = function(i) {
                if ($scope.selectedItem && $scope.items[i].value === $scope.selectedItem.value) {
                    return "ac-select-highlight";
                }
                else {
                    return "";
                }
            };

            $scope.addButtonClick = function() {
                if (customAddRequest()) {
                    confirmSelection(null);
                }
            };

            $scope.listScrolled = function(scrollPosition) {
                $scope.scrollPosition = scrollPosition;
                if ($scope.settings.pageSize) {
                    var totalHeight = $scope.items.length * $scope.settings.itemHeight;
                    // If scrolled past the last item
                    if (scrollPosition > totalHeight - $scope.listHeight) {
                        $scope.loadMore();
                    }
                }
            };

            // Load further data when paging is enabled
            $scope.loadMore = function() {
                if (!$scope.loading) {
                    $scope.loading = true;
                    $scope.loadMessage = "Loading...";

                    var offSet = $scope.items.length;
                    $scope.dataFunction($scope.dataCallback, $scope.searchText, offSet);
                }
            }

            // Private functions

            function confirmSelection(item, forceClose) {

                $scope.selectedItem = item;

                var oldConfirmedItem = $scope.confirmedItem;
                var close = false;
                if ($scope.selectedItem) {
                    $scope.confirmedItem = angular.copy($scope.selectedItem);
                    $scope.modelUpdating = true;
                    $scope.model = $scope.selectedItem.value;
                    $scope.comboText = $scope.selectedItem.text;
                    close = true;
                }
                else {
                    // Try adding as a custom item
                    if (customAddRequest()) {
                        close = true;
                    }
                }

                // If the pop-up is visible (i.e. not setting an initial selection)
                if ($scope.popupVisible) {
                    fireChangeEvent();
                }

                // Clear any initial selection
                $scope.initialSelection = null;
                $scope.initialItem == null;

                if ($scope.popupVisible && (close || forceClose)) {
                    $scope.popupVisible = false;
                    $scope.wrapperFocus = true;
                    // If all data is loaded
                    if ($scope.allDataLoaded && !$scope.settings.comboMode) {
                        // Clear the search text and filter
                        $scope.searchText = "";
                        clearClientFilter();
                    }
                }
            }

            function fireChangeEvent() {
                // Fire acChange function, if specified
                if (typeof $scope.acChange === 'function') {
                    $timeout(function () {
                      $scope.acChange({ value: $scope.selectedItem ? $scope.selectedItem.value : null });
                    });
                }
            }

            function customAddRequest() {
                var customText, dataItem;
                var added = false;
                if ($scope.settings.allowCustomText && !$scope.matchFound) {
                    customText = $scope.searchText;
                    if (customText.length > 0) {
                        // Create new data item
                        dataItem = {};
                        dataItem[$scope.textField] = customText;

                        // add the key field if it is defined.
                        if ($scope.keyField) {
                            dataItem[$scope.keyField] = customText;
                        }
                        $scope.modelUpdating = true;
                        $scope.model = dataItem;
                        $scope.confirmedItem = $scope.selectedItem = { "text": customText, "value": dataItem, "index": -1 };
                        $scope.items.push($scope.selectedItem);
                        $scope.allItems.push($scope.selectedItem);
                        added = true;
                    }
                }
                return added;
            }

            function enterKey() {
                confirmSelection($scope.selectedItem);
            }

            function downArrowKey() {
                if ($scope.items.length > 0) {
                    var selected = false;
                    if ($scope.selectedItem) {
                        var newIndex = $scope.selectedItem.index + 1;
                        if (newIndex < $scope.items.length) {
                            var targetItem = $scope.items[newIndex];
                            $scope.selectedItem = targetItem;
                            ensureItemVisible($scope.selectedItem);
                            selected = true;
                        }
                        else if ($scope.settings.pageSize && $scope.items.length >= $scope.settings.pageSize) {
                            $scope.requestedItemIndex = newIndex;
                            $scope.scrollTo += $scope.settings.itemHeight;
                            $scope.loadMore();
                        }
                    }
                    else {
                        // Select first item
                        $scope.selectedItem = $scope.items[0];
                        selected = true;
                    }
                }
            };

            function upArrowKey() {
                if ($scope.items.length > 0) {
                    if ($scope.selectedItem) {
                        var targetItem = $scope.items[$scope.selectedItem.index - 1];
                        if (targetItem) {
                            $scope.selectedItem = targetItem;
                            ensureItemVisible($scope.selectedItem);
                        }
                    }
                    else {
                        if ($scope.settings.comboMode) {
                            $scope.comboFocus = true;
                        }
                        else {
                            $scope.searchBoxFocus = true;
                        }
                    }
                }
            };

            function pageUpKey() {
                if ($scope.items.length > 0 && $scope.selectedItem) {
                    var newIndex = $scope.selectedItem.index - $scope.settings.itemsInView;
                    if (newIndex < 0) newIndex = 0;
                    var targetItem = $scope.items[newIndex];
                    if (targetItem) {
                        $scope.selectedItem = targetItem;
                        ensureItemVisible($scope.selectedItem);
                    }
                }
            };

            function pageDownKey() {
                var newIndex;
                if ($scope.items.length > 0) {
                    if ($scope.selectedItem) {
                        newIndex = $scope.selectedItem.index + $scope.settings.itemsInView;
                    }
                    else {
                        newIndex = $scope.settings.itemsInView - 1;
                    }
                    // If past the end
                    if (newIndex >= $scope.items.length) {
                        if ($scope.allDataLoaded) {
                            newIndex = $scope.items.length - 1;
                        }
                        else {

                        }
                    }
                    var targetItem = $scope.items[newIndex];
                    if (targetItem) {
                        $scope.selectedItem = targetItem;
                        ensureItemVisible($scope.selectedItem);
                    }
                }
            };

            function endKey() {
                if ($scope.items.length > 0) {
                    $scope.selectedItem = $scope.items[$scope.items.length - 1];
                    var totalHeight = $scope.settings.itemHeight * $scope.items.length;
                    $scope.scrollTo = totalHeight - $scope.listHeight;
                }
            }

            function homeKey() {
                if ($scope.items.length > 0) {
                    $scope.selectedItem = $scope.items[0];
                    $scope.scrollTo = 0;
                }
            }

            function escapeKey() {
                // Revert to last confirmed selection
                $scope.selectedItem = $scope.confirmedItem;
                confirmSelection($scope.selectedItem, true);
            }

            function deleteKey(event) {
                if ($scope.settings.allowClear) {
                    var srcElement = angular.element(event.target);
                    // If in combo textbox, ignore
                    if (srcElement.hasClass('ac-select-text')) {
                        event.stopPropagation();
                    }
                    else {
                        clearSelection();
                    }
                }
            }

            function clearSelection() {
                var oldConfirmedItem = $scope.confirmedItem;
                $scope.selectedItem = null;
                $scope.confirmedItem = null;
                $scope.modelUpdating = true;
                $scope.model = null;
                $scope.initialSelection = null;
                $scope.scrollTo = 0;
                $scope.comboText = "";

                if (oldConfirmedItem !== null) {
                    fireChangeEvent();
                }
            }

            function ensureItemVisible(item) {
                var itemHeight = $scope.settings.itemHeight;
                var itemTop = itemHeight * item.index;
                if (itemTop + itemHeight > $scope.listHeight + $scope.scrollPosition) {
                    $scope.scrollTo = itemTop + itemHeight - $scope.listHeight;
                }
                else if (itemTop < $scope.scrollPosition) {
                    $scope.scrollTo = itemTop;
                }
            }

            function filterData() {

                var itemCount = $scope.allItems.length;

                // If search text is blank
                // OR the search text is changed with less specificity
                // OR paging is enabled && current number of items is >= pageSize (or zero)
                if  ($scope.dataFunction &&
                        ($scope.searchText === ""
                        || ($scope.searchText.length < $scope.previousSearchText.length)
                        || ($scope.settings.pageSize && (itemCount >= $scope.settings.pageSize || itemCount === 0)))
                    ) {
                    // Data needs to be re-loaded.
                    $scope.allDataLoaded = false;
                }

                if ($scope.allDataLoaded) {

                    var itemsToFilter = $scope.allItems;

                    // If search text includes the previous search
                    if ($scope.previousSearchText && $scope.searchText.indexOf($scope.previousSearchText) != -1) {
                        // We can refine the filtering, without checking all items
                        itemsToFilter = $scope.items;
                    }

                    if ($scope.settings.filterType == "contains") {
                        $scope.items = $filter("filter")(itemsToFilter, function(item) {
                            // Check for match at start of items only
                            return item.text.toLowerCase().indexOf($scope.searchText.toLowerCase()) > -1;
                        });
                    }
                    else {
                        $scope.items = $filter("filter")(itemsToFilter, function(item) {
                            // Check for match at start of items only
                            return item.text.substr(0, $scope.searchText.length).toLowerCase() === $scope.searchText.toLowerCase();
                        });
                    }
                    // Update indexes
                    angular.forEach($scope.items, function(item, index) {
                        item.index = index;
                    });

                    checkItemCount();
                }
                else {
                    // Pass search text to data function (if it takes 2 or more arguments)
                    if ($scope.dataFunction && $scope.dataFunction.length >= 2) {
                        // If search text has enough chars (or it's just been cleared)
                        if ($scope.searchText.length >= $scope.settings.minSearchLength || $scope.searchText == "") {
                            // Get data
                            $scope.dataFunction($scope.dataCallback, $scope.searchText, 0);
                        }
                    }
                }

                // If narrowed down to one item (and search text isn't a subset of the previous search), select it
                if ($scope.items.length === 1 && $scope.previousSearchText.indexOf($scope.searchText) === -1) {
                    $scope.matchFound = true;
                    $scope.selectedItem = $scope.items[0];
                }
                else {
                    // See if the search text exactly matches one of the items
                    $scope.matchFound = searchTextMatchesItem();
                }

                $scope.previousSearchText = $scope.searchText
                $scope.setListHeight();
            }

            // Look for an item with text that exactly matches the search text
            function searchTextMatchesItem() {
                var i, valid = false;
                if ($scope.searchText.length > 0) {
                    for (i = 0; i < $scope.items.length; i++) {
                        if ($scope.searchText.toLowerCase() === $scope.items[i].text.toLowerCase()) {
                            $scope.selectedItem = $scope.items[i];
                            $scope.searchText = $scope.comboText = $scope.selectedItem.text;
                            valid = true;
                            break;
                        }
                    }
                }
                return valid;
            }

            // Remove any client filtering of items
            function clearClientFilter() {
                if ($scope.allDataLoaded) {
                    $scope.items = $scope.allItems;
                    $scope.setListHeight();
                }
            }

            function closeWhenClickingElsewhere(event, callbackFn) {

                var element = event.target;
                if (!element) return;

                var clickedOnPopup = false;
                // Check up to 10 levels up the DOM tree
                for (var i = 0; i < 10 && element && !clickedOnPopup; i++) {
                    var elementClasses = element.classList;
                    if (elementClasses !== undefined && elementClasses.contains('ac-select-wrapper')) {
                        clickedOnPopup = true;
                    }
                    else {
                        element = element.parentElement;
                    }
                }

                if (!clickedOnPopup) {
                    callbackFn();
                }
            }

            function log(text) {
                if (console && console.log && $scope.settings.debug) {
                    console.log("ac-select:- " + text);
                }
            }
        }
    };
})

// Directive to set focus to an element when a specified expression is true
.directive('acFocus', function($timeout, $parse, safeApply) {
    return {
        restrict: "A",
        link: function(scope, element, attributes) {
            var setFocus = $parse(attributes.acFocus);
            scope.$watch(setFocus, function(value) {
                if (value === true) {
                    $timeout(function() {
                        element[0].focus();
                    });
                }
            });
            // Set the "setFocus" attribute value to 'false' on blur event
            // using the "assign" method on the function that $parse returns
            element.bind('blur', function() {
                safeApply(scope, function() { setFocus.assign(scope, false) });
            });
        }
    };
})

.directive('acSelectOnFocus', function() {
    return {
        restrict: 'A',
        scope: {
            acSelectOnFocus: "="
        },
        link: function(scope, element, attrs) {
            element.bind('focus', function() {
                if (scope.acSelectOnFocus !== false && scope.acSelectOnFocus !== 'false') {
                    element[0].select();
                }
            });
        }
    };
})

// Directive for a scroll container. Set the "ac-scroll-to" attribute to an expression and when its value changes,
// the div will scroll to that position
.directive('acScrollTo', function() {
    return {
        restrict: "A",
        scope: false,
        controller: function($scope, $element, $attrs) {
            var expression = $attrs.acScrollTo;
            $scope.$watch(expression, function() {
                var scrollTop = $scope.$eval(expression);
                angular.element($element)[0].scrollTop = scrollTop;
            });
        }
    };
})

// Call a function when the element is scrolled
// E.g. ac-on-scroll="listScrolled()"
// N.B. take care not to use the result to directly update an acScrollTo expression
// as this will result in an infinite recursion!
.directive('acOnScroll', function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            var callbackName = attrs.acOnScroll;
            if (callbackName.indexOf("()") === callbackName.length - 2) {
                callbackName = callbackName.substr(0, callbackName.length - 2);
            }
            var callback = scope[callbackName];
            if (typeof callback === "function") {
                element.bind("scroll", function() {
                    callback(element[0].scrollTop);
                });
            }
        }
    };
})

.factory('navKey', function() {
    return {
        'backspace': 8,
        'tab': 9,
        'enter': 13,
        'escape': 27,
        'pageUp': 33,
        'pageDown': 34,
        'end': 35,
        'home': 36,
        'leftArrow': 37,
        'upArrow': 38,
        'rightArrow': 39,
        'downArrow': 40,
        'del': 46
    };
})

// safeApply service, courtesy Alex Vanston and Andrew Reutter
.factory('safeApply', [function($rootScope) {
    return function($scope, fn) {
        var phase = $scope.$root.$$phase;
        if (phase == '$apply' || phase == '$digest') {
            if (fn) {
                $scope.$eval(fn);
            }
        } else {
            if (fn) {
                $scope.$apply(fn);
            } else {
                $scope.$apply();
            }
        }
    }
}])

// Service to allow host pages to change settings for all instances (in their module.run function)
.factory('acuteSelectService', function() {

    var defaultSettings = {
        "templatePath": "/acute.select/",
        "noItemsText": "No items found.",
        "placeholderText": "Please select...",
        "itemHeight": 24,
        "itemsInView": 10,
        "pageSize": null,
        "minWidth": "100px",
        "maxWidth": "",
        "showSearchBox": true,
        "comboMode": false,
        "comboSelectOnFocus": true,
        "loadOnCreate": true,
        "loadOnOpen": false,      // If true, while loadOnCreate is false, the load function will be called when the dropdown opens
        "allowCustomText": false,
        "minSearchLength": 0,
        "filterType": "contains",    // or "start"
        "allowClear": true,
        "debug": false
    };

    return {
        getSettings: function() {
            // Add trailing "/" to template path if not present
            var len = defaultSettings.templatePath.length;
            if (len > 0 && defaultSettings.templatePath.substr(len - 1, 1) !== "/") {
                defaultSettings.templatePath += "/";
            }
            return angular.copy(defaultSettings);
        },

        updateSetting: function(settingName, value) {
            updateSingleSetting(settingName, value);
        },

        updateSettings: function(settings) {
            for (name in settings) {
                updateSingleSetting(name, settings[name]);
            }
        }
    };

    function updateSingleSetting(settingName, value) {
        if (defaultSettings.hasOwnProperty(settingName)) {
            defaultSettings[settingName] = value;
        }
    }
});


text:
// Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;

/**
 * The Enum Ios Notification Alert Type.
*/
public enum IosNotificationAlertType
{
    /**
    * device Default
    */
    DEVICE_DEFAULT,
    /**
    * banner
    */
    BANNER,
    /**
    * modal
    */
    MODAL,
    /**
    * none
    */
    NONE,
    /**
    * For IosNotificationAlertType values that were not expected from the service
    */
    UNEXPECTED_VALUE
}

redpajama_set_name: RedPajamaGithub


text:
uint64_t CPU_MillisecondsToTicks(uint64_t ticks);

// timer for bool events
static virtual_timer_t boolEventsTimer;

bool Events_Uninitialize_Platform()
{
    chVTReset(&boolEventsTimer);

    return true;
}

static void local_Events_SetBoolTimer_Callback(virtual_timer_t *vtp, void *arg)
{
    (void)vtp;
    NATIVE_PROFILE_PAL_EVENTS();
    bool *timerCompleteFlag = (bool *)arg;

    *timerCompleteFlag = true;
}

void Events_SetBoolTimer(bool *timerCompleteFlag, uint32_t millisecondsFromNow)
{
    NATIVE_PROFILE_PAL_EVENTS();

    if (timerCompleteFlag != NULL)
    {
        // no need to stop the timer even if it's running because the API does it anyway
        if (port_is_isr_context())
        {
            chVTSetI(
                &boolEventsTimer,
                TIME_MS2I(millisecondsFromNow),
                local_Events_SetBoolTimer_Callback,
                timerCompleteFlag);
        }
        else
        {
            chVTSet(
                &boolEventsTimer,
                TIME_MS2I(millisecondsFromNow),
                local_Events_SetBoolTimer_Callback,
                timerCompleteFlag);
        }
    }
}

uint32_t Events_WaitForEvents(uint32_t powerLevel, uint32_t wakeupSystemEvents, uint32_t timeoutMilliseconds)
{
    // schedule an interrupt for this far in the future
    // timeout is in milliseconds, need to convert to ticks
    uint64_t countsRemaining = CPU_MillisecondsToTicks(timeoutMilliseconds);

#if defined(HAL_PROFILE_ENABLED)
    Events_WaitForEvents_Calls++;
#endif

    uint64_t expireTimeInTicks = HAL_Time_CurrentSysTicks() + countsRemaining;
    bool runContinuations = true;

    while (true)
    {
        EVENTS_HEART_BEAT;

        uint32_t events = Events_MaskedRead(wakeupSystemEvents);
        if (events)
        {
            return events;
        }

        if (expireTimeInTicks <= HAL_Time_CurrentSysTicks())
        {
            break;
        }

        // first check and possibly run any continuations
        // but only if we have slept after stalling
        if (runContinuations && !SystemState_QueryNoLock(SYSTEM_STATE_NO_CONTINUATIONS))
        {
            // if we stall on time, don't check again until after we sleep
            runContinuations = HAL_CONTINUATION::Dequeue_And_Execute();
        }
        else
        {
            // try stalled continuations again after sleeping
            runContinuations = true;

            HAL_COMPLETION::WaitForInterrupts(expireTimeInTicks, powerLevel, wakeupSystemEvents);
        }

        // no events, pass control to the OS
        osThreadYield();

        // check if reboot or exit flags were set when the other OS threads executed
        if (CLR_EE_DBG_IS(RebootPending) || CLR_EE_DBG_IS(ExitPending))
        {
            break;
        }

        // feed the watchdog...
        Watchdog_Reset();
    }

    return 0;
}

void FreeManagedEvent(uint8_t category, uint8_t subCategory, uint16_t data1, uint32_t data2)
{
    (void)category;
    (void)subCategory;
    (void)data1;
    (void)data2;

    NATIVE_PROFILE_PAL_EVENTS();
}


text:
package flca.xlsx.util;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

abstract class AbstractXlsxUtils {

	private final static Pattern NRS_LIST_PATTERN = Pattern.compile("(\\d*)(\\.\\.)(\\d*)");

	private static final String DELIM = ",";

	Set<Integer> getNrs(String value) {
		Set<Integer> r = new HashSet<Integer>();

		Matcher matcher = NRS_LIST_PATTERN.matcher(value);
		if (matcher.find()) {
			return getMultipleNrs(matcher);
		} else {
			String[] nrs = value.replace('.', ',').split(DELIM);
			for (int i = 0; i < nrs.length; i++) {
				String nr = nrs[i].trim();
				if (!nr.isEmpty()) {
					r.add(getNr(nr));
				}
			}
			return r;
		}
	}

	private Set<Integer> getMultipleNrs(final Matcher m) {
		Set<Integer> r = new HashSet<Integer>();
		for (int i = getNr(m.group(1)); i <= getNr(m.group(3)); i++) {
			r.add(i);
		}
		return r;
	}

	int getNr(String value) {
		return Integer.valueOf(value);
	}

	boolean isNumeric(String str) {
		if (str == null) {
			return false;
		}
		int sz = str.length();
		for (int i = 0; i < sz; i++) {
			if (Character.isDigit(str.charAt(i)) == false) {
				return false;
			}
		}
		return true;
	}

}


text:
package com.asafge.pocketplus;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.asafge.pocketplus.util.AndroidUtils;
import com.asafge.pocketplus.util.Utils;

public class SendLogActivity extends Activity {

	public final static String	TAG						= "SendLogActivity";												//$NON-NLS-1$

	public static final String	APP_PACKAGE				= "com.noinnion.android.newsplus.extension.google_reader";			//$NON-NLS-1$
	public static final String	APP_EMAIL				= "asafge@gmail.com";												//$NON-NLS-1$

	// directories
	public static final String	APP_DIRECTORY			= "/NewsPlus/";
	public static final String	APP_PATH				= Environment.getExternalStorageDirectory() + "/" + APP_DIRECTORY;

	public static final String	LOG_DIRECTORY			= APP_DIRECTORY + ".log/";
	public static final String	LOG_PATH				= Environment.getExternalStorageDirectory() + "/" + LOG_DIRECTORY;

	public static final String	EXTRA_SEND_LOG			= APP_PACKAGE + ".extra.SEND_LOG";									//$NON-NLS-1$
	public static final String	EXTRA_FEATURE_REQUEST	= APP_PACKAGE + ".extra.FEATURE_REQUEST";							//$NON-NLS-1$
	public static final String	EXTRA_BUG_REPORT 		= APP_PACKAGE + ".extra.BUG_REPORT";//$NON-NLS-1$

	final int					MAX_LOG_MESSAGE_LENGTH	= 100000;

	public final static String	LINE_SEPARATOR			= System.getProperty("line.separator");	//$NON-NLS-1$

	private AlertDialog			mMainDialog;
	private Intent				mSendIntent;
	private CollectLogTask		mCollectLogTask;
	private ProgressDialog		mProgressDialog;
	private String				mAdditonalInfo;
	private String[]			mFilterSpecs;
	private String				mFormat;
	private String				mBuffer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mSendIntent = null;
		boolean extraSendLog = false;
		Intent intent = getIntent();
		if (null != intent)
			extraSendLog = intent.getBooleanExtra(EXTRA_SEND_LOG, false);

		// init
		mFilterSpecs = new String[] { "*:W" };

		if (null == mSendIntent) {
			// standalone application
			mSendIntent = new Intent(Intent.ACTION_SEND);
			mSendIntent.setType("text/plain");//$NON-NLS-1$
			mSendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { APP_EMAIL });

			String subject = getString(R.string.log_feedback_subject);

			String version = AndroidUtils.getVersionName(this);
			version = (version == null ? "?" : version);

			subject += " " + getText(R.string.app_name) + " (" + version + ")";

			mSendIntent.putExtra(Intent.EXTRA_SUBJECT, subject);

			MessageFormat infoFormat = new MessageFormat(getText(R.string.log_device_info_fmt).toString());
			mAdditonalInfo = "";
			mAdditonalInfo += "\n\n";
			mAdditonalInfo += infoFormat.format(new String[] { version , Build.MODEL, Build.VERSION.RELEASE, getFormattedKernelVersion(), Build.DISPLAY });
			mFormat = "time";
		}

		if (extraSendLog) {
			mMainDialog = new AlertDialog.Builder(this).setTitle(getString(R.string.log_send_feedback))
				.setMessage(getString(R.string.log_main_dialog_text))
				.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						collectAndSendLog();
					}
				}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						finish();
					}
				}).show();
		}
		else {
			mSendIntent.putExtra(Intent.EXTRA_TEXT, mAdditonalInfo);
			startActivity(Intent.createChooser(mSendIntent, getString(R.string.log_chooser_title)));
			finish();
		}
	}

	@SuppressWarnings("unchecked")
	void collectAndSendLog() {
		/*
		 * Usage: logcat [options] [filterspecs]
		 * options include:
		 * -s Set default filter to silent.
		 * Like specifying filterspec '*:s'
		 * -f <filename> Log to file. Default to stdout
		 * -r [<kbytes>] Rotate log every kbytes. (16 if unspecified). Requires -f
		 * -n <count> Sets max number of rotated logs to <count>, default 4
		 * -v <format> Sets the log print format, where <format> is one of:
		 * brief process tag thread raw time threadtime long
		 * -c clear (flush) the entire log and exit
		 * -d dump the log and then exit (don't block)
		 * -g get the size of the log's ring buffer and exit
		 * -b <buffer> request alternate ring buffer
		 * ('main' (default), 'radio', 'events')
		 * -B output the log in binary
		 * filterspecs are a series of
		 * <tag>[:priority]
		 * where <tag> is a log component tag (or * for all) and priority is:
		 * V Verbose
		 * D Debug
		 * I Info
		 * W Warn
		 * E Error
		 * F Fatal
		 * S Silent (supress all output)
		 * '*' means '*:d' and <tag> by itself means <tag>:v
		 * If not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS.
		 * If no filterspec is found, filter defaults to '*:I'
		 * If not specified with -v, format is set from ANDROID_PRINTF_LOG
		 * or defaults to "brief"
		 */

		ArrayList<String> list = new ArrayList<String>();

		if (mFormat != null) {
			list.add("-v");
			list.add(mFormat);
		}

		if (mBuffer != null) {
			list.add("-b");
			list.add(mBuffer);
		}

		if (mFilterSpecs != null) {
			for (String filterSpec : mFilterSpecs) {
				list.add(filterSpec);
			}
		}

		mCollectLogTask = (CollectLogTask) new CollectLogTask().execute(list);
	}

	private class CollectLogTask extends AsyncTask<ArrayList<String>, Void, StringBuilder> {
		@Override
		protected void onPreExecute() {
			showProgressDialog(getString(R.string.log_acquiring_log_progress_dialog_message));
		}

		@Override
		protected StringBuilder doInBackground(ArrayList<String>... params) {
			final StringBuilder log = new StringBuilder();
			try {
				ArrayList<String> commandLine = new ArrayList<String>();
				commandLine.add("logcat");//$NON-NLS-1$
				commandLine.add("-d");//$NON-NLS-1$
				ArrayList<String> arguments = ((params != null) && (params.length > 0)) ? params[0] : null;
				if (null != arguments) {
					commandLine.addAll(arguments);
				}

				Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

				String line;
				while ((line = bufferedReader.readLine()) != null) {
					log.append(line);
					log.append(LINE_SEPARATOR);
				}
			} catch (IOException e) {
				Log.e(TAG, "CollectLogTask.doInBackground failed", e);//$NON-NLS-1$
			}

			return log;
		}

		@Override
		protected void onPostExecute(StringBuilder log) {
			if (null != log) {
				// truncate if necessary
				int keepOffset = Math.max(log.length() - MAX_LOG_MESSAGE_LENGTH, 0);
				if (keepOffset > 0){
					log.delete(0, keepOffset);
				}

				if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
					if (mAdditonalInfo != null) {
						log.insert(0, LINE_SEPARATOR);
						log.insert(0, mAdditonalInfo);
					}

					mSendIntent.putExtra(Intent.EXTRA_TEXT, log.toString());
				} else {
					String fn = "log_" + System.currentTimeMillis() + ".txt";
					try {
						Utils.writeContentToSD(LOG_DIRECTORY, fn, log.toString());

						if (mAdditonalInfo != null) mSendIntent.putExtra(Intent.EXTRA_TEXT, mAdditonalInfo);
						mSendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + LOG_PATH + fn));

					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				startActivity(Intent.createChooser(mSendIntent, getString(R.string.log_chooser_title)));
				dismissProgressDialog();
				dismissMainDialog();
				finish();
			} else {
				dismissProgressDialog();
				showErrorDialog(getString(R.string.log_failed_to_get_log_message));
			}
		}
	}

	void showErrorDialog(String errorMessage) {
		new AlertDialog.Builder(this).setTitle(getString(R.string.app_name)).setMessage(errorMessage).setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				finish();
			}
		}).show();
	}

	void dismissMainDialog() {
		if (null != mMainDialog && mMainDialog.isShowing()) {
			mMainDialog.dismiss();
			mMainDialog = null;
		}
	}

	void showProgressDialog(String message) {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.setMessage(message);
		mProgressDialog.setCancelable(true);
		mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				cancellCollectTask();
				finish();
			}
		});
		mProgressDialog.show();
	}

	private void dismissProgressDialog() {
		if (null != mProgressDialog && mProgressDialog.isShowing()) {
			mProgressDialog.dismiss();
			mProgressDialog = null;
		}
	}

	void cancellCollectTask() {
		if (mCollectLogTask != null && mCollectLogTask.getStatus() == AsyncTask.Status.RUNNING) {
			mCollectLogTask.cancel(true);
			mCollectLogTask = null;
		}
	}

	@Override
	protected void onPause() {
		cancellCollectTask();
		dismissProgressDialog();
		dismissMainDialog();

		super.onPause();
	}

	private String getFormattedKernelVersion() {
		String procVersionStr;

		try {
			BufferedReader reader = new BufferedReader(new FileReader("/proc/version"), 256);
			try {
				procVersionStr = reader.readLine();
			} finally {
				reader.close();
			}

			final String PROC_VERSION_REGEX = "\\w+\\s+" + /* ignore: Linux */
					"\\w+\\s+" + /* ignore: version */
					"([^\\s]+)\\s+" + /* group 1: 2.6.22-omap1 */
					"\\(([^\\s@]+(?:@[^\\s.]+)?)[^)]*\\)\\s+" + /* group 2: (xxxxxx@xxxxx.constant) */
					"\\([^)]+\\)\\s+" + /* ignore: (gcc ..) */
					"([^\\s]+)\\s+" + /* group 3: #26 */
					"(?:PREEMPT\\s+)?" + /* ignore: PREEMPT (optional) */
					"(.+)"; /* group 4: date */

			Pattern p = Pattern.compile(PROC_VERSION_REGEX);
			Matcher m = p.matcher(procVersionStr);

			if (!m.matches()) {
				Log.e(TAG, "Regex did not match on /proc/version: " + procVersionStr);
				return "Unavailable";
			} else if (m.groupCount() < 4) {
				Log.e(TAG, "Regex match on /proc/version only returned " + m.groupCount() + " groups");
				return "Unavailable";
			} else {
				return (new StringBuilder(m.group(1)).append("\n").append(m.group(2)).append(" ").append(m.group(3)).append("\n").append(m.group(4))).toString();
			}
		} catch (IOException e) {
			Log.e(TAG, "IO Exception when getting kernel version for Device Info screen", e);

			return "Unavailable";
		}
	}
}


text:
.class public Landroid/content/res/Resources$NotFoundException;
.super Ljava/lang/RuntimeException;
.source "Resources.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/content/res/Resources;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "NotFoundException"
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 216
    invoke-direct {p0}, Ljava/lang/RuntimeException;-><init>()V

    .line 217
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;)V
    .locals 0
    .param p1, "name"    # Ljava/lang/String;

    .prologue
    .line 220
    invoke-direct {p0, p1}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;)V

    .line 221
    return-void
.end method


text:
@interface OFSocialNotification : NSObject {
	NSString* text;
	NSString* imageType;
	NSString* imageIdentifier;
	NSString* imageUrl;
	NSString* url;
}

@property(nonatomic, retain) NSString* text;
@property(nonatomic, retain) NSString* imageType;
@property(nonatomic, retain) NSString* imageIdentifier;
@property(nonatomic, retain) NSString* imageUrl;
@property(nonatomic, retain) NSString* url;

- (id)initWithText:(NSString*)_text;
- (id)initWithText:(NSString*)_text imageNamed:(NSString*)_imageName;
- (id)initWithText:(NSString*)_text imageNamed:(NSString*)_imageName linkedUrl:(NSString*)_url;
- (id)initWithText:(NSString*)_text imageType:(NSString*)_imageType imageId:(NSString*)_imageId;
- (id)initWithText:(NSString*)_text imageType:(NSString*)_imageType imageId:(NSString*)_imageId linkedUrl:(NSString*)_url;

@end


text:
package io.github.nejc92.sy.strategies;

import io.github.nejc92.sy.game.Action;
import io.github.nejc92.sy.game.PlayersOnBoard;
import io.github.nejc92.sy.players.Player;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MoveFiltering {

    public enum Uses {
        YES, NO
    }

    private static final List<Integer> SHOULDNT_USE_BLACK_FAIR_ROUNDS = new ArrayList<>(
            Arrays.asList(1, 2, 3, 8, 13, 18, 24)
    );
    private static final double SHOULD_USE_DOUBLE_MOVE_AVG_DISTANCE_THRESHOLD = 3;
    private static final double SHOULD_USE_DOUBLE_MOVE_GREEDY_THRESHOLD = 0.3;
    // private static final double SHOULD_USE_BLACK_FARE_TICKET_GREEDY_THRESHOLD = 0.3;

    public static boolean optimalToUseBlackFareTicket(int currentRound, List<Action> actions) {
        return !SHOULDNT_USE_BLACK_FAIR_ROUNDS.contains(currentRound) && !actionsContainOnlyTaxis(actions);
    }

    private static boolean actionsContainOnlyTaxis(List<Action> actions) {
        return actions.stream().allMatch(action -> action.isTransportationAction(Action.Transportation.TAXI));
    }

    public static boolean optimalToUseDoubleMoveCard(PlayersOnBoard playersOnBoard) {
        return playersOnBoard.hidersAverageDistanceToSeekers(Player.Type.SEEKER)
                <= SHOULD_USE_DOUBLE_MOVE_AVG_DISTANCE_THRESHOLD;
    }

    public static boolean shouldUseDoubleMoveCardGreedy() {
        return Math.random() < SHOULD_USE_DOUBLE_MOVE_GREEDY_THRESHOLD;
    }

    public static boolean shouldUseBlackFareTicketGreedy() {
        // todo: fix getAvailableActions() first
        // return Math.random() < SHOULD_USE_BLACK_FARE_TICKET_GREEDY_THRESHOLD;
        return true;
    }
}


text:
Concept of interoperability between Dart and JS. The main idea is that you write
code on Dart that is exact as JS code. So instead of this:

```dart
context.callMethod(r'$',['div']).callMethod('each',[(index,element) {
  element.style.color='#ccc';
  print(index);
}]);
```

you write this (and IDE understands you):

```dart
$('div').each((index, element) {
  element.style.color='#ccc';
  print(index);
});
```

and transformer will do the rest.

To help IDE and transformer understand the code we use declaration files as in
TypeScript (http://www.typescriptlang.org/Handbook#writing-dts-files). We can
even try to automatically convert them (https://github.com/borisyankov/DefinitelyTyped)
to Dart.


text:
setfenv(1, require'winapi')
require'winapi.window'
require'winapi.comctl'

--creation

WC_EDIT = 'Edit'

ES_LEFT              = 0x0000
ES_CENTER            = 0x0001
ES_RIGHT             = 0x0002
ES_MULTILINE         = 0x0004
ES_UPPERCASE         = 0x0008
ES_LOWERCASE         = 0x0010
ES_PASSWORD          = 0x0020
ES_AUTOVSCROLL       = 0x0040
ES_AUTOHSCROLL       = 0x0080
ES_NOHIDESEL         = 0x0100
ES_OEMCONVERT        = 0x0400
ES_READONLY          = 0x0800
ES_WANTRETURN        = 0x1000
ES_NUMBER            = 0x2000

--commands

EM_GETSEL                = 0x00B0
EM_SETSEL                = 0x00B1
EM_GETRECT               = 0x00B2
EM_SETRECT               = 0x00B3
EM_SETRECTNP             = 0x00B4
EM_SCROLL                = 0x00B5
EM_LINESCROLL            = 0x00B6
EM_SCROLLCARET           = 0x00B7
EM_GETMODIFY             = 0x00B8
EM_SETMODIFY             = 0x00B9
EM_GETLINECOUNT          = 0x00BA
EM_LINEINDEX             = 0x00BB
EM_SETHANDLE             = 0x00BC
EM_GETHANDLE             = 0x00BD
EM_GETTHUMB              = 0x00BE
EM_LINELENGTH            = 0x00C1
EM_REPLACESEL            = 0x00C2
EM_GETLINE               = 0x00C4
EM_LIMITTEXT             = 0x00C5
EM_CANUNDO               = 0x00C6
EM_UNDO                  = 0x00C7
EM_FMTLINES              = 0x00C8
EM_LINEFROMCHAR          = 0x00C9
EM_SETTABSTOPS           = 0x00CB
EM_SETPASSWORDCHAR       = 0x00CC
EM_EMPTYUNDOBUFFER       = 0x00CD
EM_GETFIRSTVISIBLELINE   = 0x00CE
EM_SETREADONLY           = 0x00CF
EM_SETWORDBREAKPROC      = 0x00D0
EM_GETWORDBREAKPROC      = 0x00D1
EM_GETPASSWORDCHAR       = 0x00D2
EM_SETMARGINS            = 0x00D3
EM_GETMARGINS            = 0x00D4
EM_SETLIMITTEXT          = EM_LIMITTEXT   -- win40 Name change
EM_GETLIMITTEXT          = 0x00D5
EM_POSFROMCHAR           = 0x00D6
EM_CHARFROMPOS           = 0x00D7
EM_SETIMESTATUS          = 0x00D8
EM_GETIMESTATUS          = 0x00D9

Edit_Enable = EnableWindow
Edit_GetText = GetWindowText
Edit_SetText = SetWindowText

function Edit_GetLimitText(hwnd)
	return SNDMSG(hwnd, EM_GETLIMITTEXT)
end

function Edit_SetLimitText(hwnd, cchMax)
	SNDMSG(hwnd, EM_SETLIMITTEXT, cchMax)
end

function Edit_GetSel(hwnd)
	local p1, p2 = ffi.new'DWORD[1]', ffi.new'DWORD[1]'
	SNDMSG(hwnd, EM_GETSEL, p1, p2)
	return countfrom1(p1[0]), countfrom1(p2[0])
end

function Edit_SetSel(hwnd, i, j)
	SNDMSG(hwnd, EM_SETSEL, countfrom0(i), countfrom0(j))
end

function Edit_ReplaceSel(hwnd, s)
	s = wcs(s)
	SNDMSG(hwnd, EM_REPLACESEL, 0, ffi.cast('LPCTSTR', s))
end

function Edit_GetModify(hwnd)
	return SNDMSG(hwnd, EM_GETMODIFY) ~= 0
end

function Edit_SetModify(hwnd, fModified)
	SNDMSG(hwnd, EM_SETMODIFY, fModified and 1 or 0, 0)
end

function Edit_ScrollCaret(hwnd)
	SNDMSG(hwnd, EM_SCROLLCARET)
end

function Edit_LineFromChar(hwnd, charindex)
	return SNDMSG(hwnd, EM_LINEFROMCHAR, countfrom0(charindex))
end

function Edit_LineIndex(hwnd, lineindex)
	return SNDMSG(hwnd, EM_LINEINDEX, countfrom0(lineindex))
end

function Edit_LineLength(hwnd, lineindex)
	return SNDMSG(hwnd, EM_LINELENGTH, countfrom0(lineindex))
end

function Edit_Scroll(hwnd, dv, dh)
	SNDMSG(hwnd, EM_LINESCROLL, dh, dv)
end

function Edit_CanUndo(hwnd)
	return SNDMSG(hwnd, EM_CANUNDO) ~= 0
end

function Edit_Undo(hwnd)
	return SNDMSG(hwnd, EM_UNDO) ~= 0
end

function Edit_EmptyUndoBuffer(hwnd)
	SNDMSG(hwnd, EM_EMPTYUNDOBUFFER)
end

function Edit_SetPasswordChar(hwnd, ch)
	SNDMSG(hwnd, EM_SETPASSWORDCHAR, ffi.cast('WCHAR', ch)) --eg. wcs('*')[0]
end

function Edit_SetTabStops(hwnd, tabs)
	local tabs, n = array('int', tabs)
	checknz(SNDMSG(hwnd, EM_SETTABSTOPS, n, ffi.cast('const int *', tabs)))
	return tabs
end

function Edit_FmtLines(hwnd, fAddEOL)
	SNDMSG(hwnd, EM_FMTLINES, fAddEOL and 1 or 0)
end

function Edit_GetFirstVisibleLine(hwnd)
	return countfrom1(SNDMSG(hwnd, EM_GETFIRSTVISIBLELINE))
end

function Edit_SetReadOnly(hwnd, fReadOnly)
	checknz(SNDMSG(hwnd, EM_SETREADONLY, fReadOnly and 1 or 0))
end

function Edit_GetPasswordChar(hwnd)
	return ffi.cast('WCHAR', SNDMSG(hwnd, EM_GETPASSWORDCHAR))
end

WB_LEFT             = 0
WB_RIGHT            = 1
WB_ISDELIMITER      = 2

function Edit_SetWordBreakProc(hwnd, lpfnWordBreak)
	SNDMSG(hwnd, EM_SETWORDBREAKPROC, 0, lpfnWordBreak) --type EDITWORDBREAKPROC
end

function Edit_GetWordBreakProc(hwnd)
	return ffi.cast('EDITWORDBREAKPROC', SNDMSG(hwnd, EM_GETWORDBREAKPROC))
end

-- Edit control EM_SETMARGINS parameters
EC_LEFTMARGIN        = 0x0001
EC_RIGHTMARGIN       = 0x0002
EC_USEFONTINFO       = 0xffff

function Edit_SetMargins(hwnd, left, right)
	local lparam = MAKELPARAM(left, right)
	SNDMSG(hwnd, EM_SETMARGINS, EC_LEFTMARGIN, lparam)
	SNDMSG(hwnd, EM_SETMARGINS, EC_RIGHTMARGIN, lparam)
end

function Edit_SetMarginsUseFontInfo(hwnd, left, right)
	SNDMSG(hwnd, EM_SETMARGINS, EC_USEFONTINFO, MAKELPARAM(left, right))
end

function Edit_GetMargins(hwnd)
	return splitlong(SNDMSG(hwnd, EM_GETMARGINS))
end

ECM_FIRST               = 0x1500              -- Edit control messages
EM_SETCUEBANNER         = (ECM_FIRST + 1)     -- Set the cue banner with the lParm = LPCWSTR
EM_GETCUEBANNER         = (ECM_FIRST + 2)     -- Set the cue banner with the lParm = LPCWSTR
EM_SHOWBALLOONTIP       = (ECM_FIRST + 3)     -- Show a balloon tip associated to the edit control
EM_HIDEBALLOONTIP       = (ECM_FIRST + 4)     -- Hide any balloon tip associated with the edit control
EM_SETHILITE            = (ECM_FIRST + 5)
EM_GETHILITE            = (ECM_FIRST + 6)

function Edit_SetCueBannerText(hwnd, lpcwText, show_when_focused)
	checknz(SNDMSG(hwnd, EM_SETCUEBANNER, show_when_focused, wcs(lpcwText)))
end

function Edit_GetCueBannerText(hwnd, buf) --TODO: returns FALSE in XP
	local ws, sz = WCS(buf)
	checknz(SNDMSG(hwnd, EM_GETCUEBANNER, ws, sz+1))
	return buf or mbs(ws)
end

ffi.cdef[[
typedef struct _tagEDITBALLOONTIP
{
    DWORD   cbStruct;
    LPCWSTR pszTitle;
    LPCWSTR pszText;
    INT     ttiIcon;
} EDITBALLOONTIP, *PEDITBALLOONTIP;
]]

function Edit_ShowBalloonTip(hwnd, title, text, TTI, ebt)
	ebt = types.EDITBALLOONTIP(ebt)
	ebt.cbStruct = ffi.sizeof(ebt)
	title = wcs(title) --anchor
	text = wcs(text) --anchor
	ebt.pszTitle = title
	ebt.pszText = text
	ebt.ttiIcon = flags(TTI)
	checknz(SNDMSG(hwnd, EM_SHOWBALLOONTIP, 0, ffi.cast('EDITBALLOONTIP*', ebt)))
	return ebt
end

function Edit_HideBalloonTip(hwnd)
	checknz(SNDMSG(hwnd, EM_HIDEBALLOONTIP))
end

-- wParam of EM_GET/SETIMESTATUS
EMSIS_COMPOSITIONSTRING         = 0x0001
-- lParam for EMSIS_COMPOSITIONSTRING
EIMES_GETCOMPSTRATONCE          = 0x0001
EIMES_CANCELCOMPSTRINFOCUS      = 0x0002
EIMES_COMPLETECOMPSTRKILLFOCUS  = 0x0004

--WM_COMMAND notification codes

EN_SETFOCUS          = 0x0100
EN_KILLFOCUS         = 0x0200
EN_CHANGE            = 0x0300
EN_UPDATE            = 0x0400
EN_ERRSPACE          = 0x0500
EN_MAXTEXT           = 0x0501
EN_HSCROLL           = 0x0601
EN_VSCROLL           = 0x0602
EN_ALIGN_LTR_EC      = 0x0700
EN_ALIGN_RTL_EC      = 0x0701


text:
<?php

namespace Demo\TaskBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\AdminBundle\Form\FormMapper;

class PurchaseOrderEmbedAdmin extends Admin
{
    // setup the defaut sort column and order
    protected $datagridValues = array(
        '_sort_order' => 'DESC',
    );

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            //->add('status')
                ->add('status', 'choice', array(
    'choices' => array('Opened' => 'Opened', 'Closed' => 'Closed', 'InProgress' => 'InProgress', 'Delevired' => 'Delevired'),
                    'empty_value' => 'Select a Status',
))
            //->add('order_date')
//                ->add('order_date', null, array(
//                    'widget' => 'single_text',
//                    'format' => 'd.M.y',
//                    'required' => false,
//                    'attr' => array('class' => 'datepick-input',  "data-date-format"=>"dd.mm.yyyy"))
//                     )
//            ->add('order_date', 'doctrine_orm_datetime_range', array(), null, array(
//                'widget' => 'single_text',
//                'required' => false,
//                'attr' => array('class' => 'datepicker')))
                ->add('order_date', null, array(
                    'widget' => 'single_text',
                    'required' => false,
                    'attr' => array('class' => 'datepicker')))
            ->add('customer')
            ->add('product', null, array('by_reference' => false, 'expanded' => true, 'compound' => true))
                //->add('product', 'shtumi_ajax_autocomplete', array('entity_alias'=>'order'));
        ;
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('status')
            ->add('customer')
        ;
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('status')
            ->add('order_date')
            ->add('customer')
                ->add('_action', 'actions', array(
                'actions' => array(
                    'view' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
            //->add('product', null, array('by_reference' => false, 'expanded' => true, 'compound' => true))
        ;
    }
    public function getBatchActions()
    {
        // retrieve the default (currently only the delete action) actions
        $actions = parent::getBatchActions();

        // check user permissions
        if($this->hasRoute('edit') && $this->isGranted('EDIT') && $this->hasRoute('delete') && $this->isGranted('DELETE')) {
            $actions['extend'] = array(
                'label'            => 'Extend',
                'ask_confirmation' => true // If true, a confirmation will be asked before performing the action
            );

        }

        return $actions;
    }

}
?>


text:
function siteLink(contentItem, parentItem) {
  const siteUrl = "https://newspring.cc";
  const slug = contentItem.meta.urlTitle;
  const category = contentItem.channelName;
  const parentSlug = parentItem && parentItem.meta && parentItem.meta.urlTitle;

  switch (category) {
    case "series_newspring":
      return `${siteUrl}/sermons/${slug}`;
    case "sermons":
      return `${siteUrl}/sermons/${parentSlug}/${slug}`;
    case "studies":
      return `${siteUrl}/studies/${slug}`;
    case "study_entries":
      return `${siteUrl}/studies/${parentSlug}/${slug}`;
    case "devotionals":
      return `${siteUrl}/devotionals/${slug}`;
    case "newspring_albums":
      return `${siteUrl}/music/${slug}`;
    case "articles":
      return `${siteUrl}/articles/${slug}`;
    case "stories":
      return `${siteUrl}/stories/${slug}`;
    case "news":
      return `${siteUrl}/news/${slug}`;
    default:
      return null;
  }
}

export default siteLink;


text: SELECT DISTINCT log FROM t1 ORDER BY log


text:
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["children", "size", "sizeX"];
import { createScopedElement } from "../../lib/jsxRuntime";
import { classNames } from "../../lib/classNames";
import { getClassName } from "../../helpers/getClassName";
import { usePlatform } from "../../hooks/usePlatform";
import { withAdaptivity } from "../../hoc/withAdaptivity";
import "./CardGrid.css";

var CardGrid = function CardGrid(_ref) {
  var children = _ref.children,
      size = _ref.size,
      sizeX = _ref.sizeX,
      restProps = _objectWithoutProperties(_ref, _excluded);

  var platform = usePlatform();
  return createScopedElement("div", _extends({}, restProps, {
    vkuiClass: classNames(getClassName("CardGrid", platform), "CardGrid--".concat(size), "CardGrid--sizeX-".concat(sizeX))
  }), children);
};

CardGrid.defaultProps = {
  size: "s"
}; // eslint-disable-next-line import/no-default-export

export default withAdaptivity(CardGrid, {
  sizeX: true
});
//# sourceMappingURL=CardGrid.js.map


text:
package com.spaceheroes.task;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

import com.sforce.soap.apex.ExecuteAnonymousResult;
import com.sforce.soap.apex.SoapConnection;
import com.sforce.soap.partner.fault.InvalidSObjectFault;
import com.sforce.ws.ConnectionException;
import com.spaceheroes.util.SalesforceConfig;

public abstract class SalesforceTask extends Task {

	private String username;
	private String password;
	private String serverUrl = "login.salesforce.com";
	private Boolean ignoreErrors = false;

	protected Boolean error = false;

	public SalesforceTask() {
		super();
	}

	protected void handleException(Exception e) throws BuildException {
		String message = "";
		if (e instanceof InvalidSObjectFault) {
			message = e.getLocalizedMessage();
		} else if (e instanceof ConnectionException) {
			message = "Unable to connect to Salesforce";
		} else {
			message = e.getLocalizedMessage();
		}
		if (!getIgnoreErrors()) {
			throw new BuildException(message, e);
		} else {
			error = true;
			log("Ignored error: " + message);
		}
	}

	protected void executeApex(SoapConnection tc, String apexCode) throws BuildException {
		try {
			ExecuteAnonymousResult result = tc.executeAnonymous(apexCode);
			if (!result.isSuccess()) {
				String error = result.isCompiled() ? result.getExceptionMessage() : result.getCompileProblem();
				throw new BuildException(error);
			}
		} catch (ConnectionException e) {
			handleException(e);
		}
	}

	protected SalesforceConfig getConfig() {
		return new SalesforceConfig(username, password, serverUrl);
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getServerUrl() {
		return serverUrl;
	}

	public void setServerUrl(String serverUrl) {
		this.serverUrl = serverUrl;
	}

	protected String escapeSingleQuotes(String st) {
		//return StringUtils.replace(st, "'", "''");
		return st;
	}

	public Boolean getIgnoreErrors() {
		return ignoreErrors;
	}

	public void setIgnoreErrors(Boolean ignoreErrors) {
		this.ignoreErrors = ignoreErrors;
	}

}


text:
package com.hpe.application.automation.tools.results.projectparser.performance;

/**
 * Created by kazaky on 10/07/2016.
 */
public class PercentileTransactionWholeRun extends WholeRunResult {

    private String name;
    private double _precentage;

    public PercentileTransactionWholeRun() {
        _precentage = 0.0;
        name = "";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrecentage() {
        return _precentage;
    }

    public void setPrecentage(double precentage) {
        this._precentage = precentage;
    }

}


text:
import pytest

from appium import webdriver
from appium.common.exceptions import NoSuchContextException
from appium.options.common import AppiumOptions
from appium.webdriver.common.appiumby import AppiumBy
from test.helpers.constants import SERVER_URL_BASE

from .helper import desired_capabilities

@pytest.mark.skip(reason="Need to fix broken test")
class TestContextSwitching(object):
    def setup_method(self) -> None:
        caps = desired_capabilities.get_desired_capabilities('selendroid-test-app.apk')
        self.driver = webdriver.Remote(SERVER_URL_BASE, options=AppiumOptions().load_capabilities(caps))

    def teardown_method(self) -> None:
        self.driver.quit()

    def test_contexts_list(self) -> None:
        self._enter_webview()
        contexts = self.driver.contexts
        assert 2 == len(contexts)

    def test_move_to_correct_context(self) -> None:
        self._enter_webview()
        assert 'WEBVIEW_io.selendroid.testapp' == self.driver.current_context

    def test_actually_in_webview(self) -> None:
        self._enter_webview()
        self.driver.find_element(by=AppiumBy.CSS_SELECTOR, value='input[type=submit]').click()
        el = self.driver.find_element(by=AppiumBy.XPATH, value="//h1[contains(., 'This is my way')]")
        assert el is not None

    def test_move_back_to_native_context(self) -> None:
        self._enter_webview()
        self.driver.switch_to.context(None)
        assert 'NATIVE_APP' == self.driver.current_context

    def test_set_invalid_context(self) -> None:
        with pytest.raises(NoSuchContextException):
            self.driver.switch_to.context('invalid name')

    def _enter_webview(self) -> None:
        btn = self.driver.find_element(by=AppiumBy.NAME, value='buttonStartWebviewCD')
        btn.click()
        self.driver.switch_to.context('WEBVIEW')


text:
package heppdt

// Measurement holds a value and its associated error
type Measurement struct {
	Value float64
	Sigma float64
}


text:
package org.bosphorus.core.expression.scalar.executor.event;

import org.bosphorus.core.expression.scalar.executor.BaseStatelessExecutor1;
import org.bosphorus.core.expression.scalar.executor.IScalarExecutor1;

public class IIfExecutor<TInput, TOutput> extends BaseStatelessExecutor1<TInput, TOutput> {

	private IScalarExecutor1<? super TInput, Boolean> condition;
	private IScalarExecutor1<? super TInput, ? extends TOutput> trueValue;
	private IScalarExecutor1<? super TInput, ? extends TOutput> falseValue;

	public IIfExecutor(IScalarExecutor1<? super TInput, Boolean> condition,
			IScalarExecutor1<? super TInput, ? extends TOutput> trueValue,
			IScalarExecutor1<? super TInput, ? extends TOutput> falseValue) {
		this.condition = condition;
		this.trueValue = trueValue;
		this.falseValue = falseValue;
	}

	@Override
	public TOutput execute(TInput input) throws Exception {
		return condition.execute(input) ? trueValue.execute(input) : falseValue.execute(input);
	}

}


text:
class EmblCrossReference < ApplicationRecord
  include ReadOnlyModel

  belongs_to :uniprot_entry

  # Returns a set of sequence_ids for a given refseq_id
  def self.get_sequence_ids(insdc_id)
    connection.select_values("SELECT original_sequence_id
      FROM peptides
      LEFT JOIN  embl_cross_references ON peptides.uniprot_entry_id = embl_cross_references.uniprot_entry_id
      WHERE embl_cross_references.sequence_id = '#{insdc_id}'").to_set
  end
end


text:
require File.expand_path('../../../shared/complex/denominator', __FILE__)

ruby_version_is ""..."1.9" do

  require 'complex'

  # FIXME:
  # Complex#denominator requires the rational library,
  # as Integer#denominator is defined by it.
  # I think this method is pretty buggy, as there is no
  # denominator for Floats and rational might not always
  # be loaded, both resulting in a method missing exception.
  # Also, the documentation for Complex#denominator does
  # not mention a dependency for rational.
  require "rational"

  describe "Complex#denominator" do
    it_behaves_like(:complex_denominator, :denominator)
  end
end


text:
package org.apache.activemq.openwire.commands;

import org.apache.activemq.openwire.annotations.OpenWireType;
import org.apache.activemq.openwire.annotations.OpenWireProperty;

/**
 * @openwire:marshaller code="90"
 */
@OpenWireType(typeCode = 90)
public class MessageDispatchNotification extends BaseCommand {

    public static final byte DATA_STRUCTURE_TYPE = CommandTypes.MESSAGE_DISPATCH_NOTIFICATION;

    @OpenWireProperty(version = 1, sequence = 1, cached = true)
    protected ConsumerId consumerId;

    @OpenWireProperty(version = 1, sequence = 2, cached = true)
    protected OpenWireDestination destination;

    @OpenWireProperty(version = 1, sequence = 3)
    protected long deliverySequenceId;

    @OpenWireProperty(version = 1, sequence = 4)
    protected MessageId messageId;

    @Override
    public byte getDataStructureType() {
        return DATA_STRUCTURE_TYPE;
    }

    @Override
    public boolean isMessageDispatchNotification() {
        return true;
    }

    /**
     * @openwire:property version=1 cache=true
     */
    public ConsumerId getConsumerId() {
        return consumerId;
    }

    public void setConsumerId(ConsumerId consumerId) {
        this.consumerId = consumerId;
    }

    /**
     * @openwire:property version=1 cache=true
     */
    public OpenWireDestination getDestination() {
        return destination;
    }

    public void setDestination(OpenWireDestination destination) {
        this.destination = destination;
    }

    /**
     * @openwire:property version=1
     */
    public long getDeliverySequenceId() {
        return deliverySequenceId;
    }

    public void setDeliverySequenceId(long deliverySequenceId) {
        this.deliverySequenceId = deliverySequenceId;
    }

    /**
     * @openwire:property version=1
     */
    public MessageId getMessageId() {
        return messageId;
    }

    public void setMessageId(MessageId messageId) {
        this.messageId = messageId;
    }

    @Override
    public Response visit(CommandVisitor visitor) throws Exception {
        return visitor.processMessageDispatchNotification(this);
    }
}


text:
<?php

defined('_JEXEC') or die;

class JCommentsImportImproveMyCity extends JCommentsImportAdapter
{
	public function __construct()
	{
		$this->code = 'improvemycity';
		$this->extension = 'com_improvemycity';
		$this->name = 'ImproveMyCity';
		$this->author = 'URENIO Researh Unit';
		$this->license = 'GNU/AGPL';
		$this->licenseUrl = 'http://www.gnu.org/licenses/agpl.html';
		$this->siteUrl = 'https://github.com/icos-urenio/Improve-my-city';
		$this->tableName = '#__improvemycity_comments';
	}

	public function execute($language, $start = 0, $limit = 100)
	{
		$db = JFactory::getDBO();
		$source = $this->getCode();

		$query = $db->getQuery(true);

		$query->select('c.*');
		$query->from($db->quoteName($this->tableName) . ' AS c');
		$query->select('u.username as user_username, u.name as user_name, u.email as user_email');
		$query->join('LEFT', $db->quoteName('#__users') . ' AS u ON c.userid = u.id');
		$query->order($db->escape('c.created'));

		$db->setQuery($query, $start, $limit);
		$rows = $db->loadObjectList();

		foreach ($rows as $row) {
			$table = JTable::getInstance('Comment', 'JCommentsTable');
			$table->object_id = $row->improvemycityid;
			$table->object_group = 'com_improvemycity';
			$table->userid = $row->userid;
			$table->name = isset($row->user_name) ? $row->user_name : null;
			$table->username = isset($row->user_username) ? $row->user_username : null;
			$table->email = isset($row->user_email) ? $row->user_email : null;
			$table->comment = $row->description;
			$table->published = $row->state == 1;
			$table->date = $row->created;
			$table->lang = $language;
			$table->source_id = $row->id;
			$table->source = $source;
			$table->store();
		}
	}
}


text:
import { refund } from "../models/refund";
import { base } from "../base";
import MethodOverload = base.MethodOverload;

export class Refunds {
    /**
     * Get events
     * @param refundId
     * @param options
     */
    get: MethodOverload<string, refund.RefundData>;
}


text:
require 'spec_helper'

describe 'ECS Cluster' do
  include_context :terraform

  ecs_client = Aws::ECS::Client.new
  subject {
    ecs_client.describe_clusters({
      clusters: ["#{vars.component}-#{vars.deployment_identifier}-#{vars.cluster_name}"],
      include: ['SETTINGS']
    }).clusters[0]
  }

  it "exists" do
    expect(subject).not_to(be_nil)
  end

  context 'when container insights enabled' do
    before(:all) do
      reprovision(
          enable_container_insights: 'yes')
    end

    it 'has container insights enabled on the cluster' do
      expect(subject.settings[0][:name]).to(eq('containerInsights'))
      expect(subject.settings[0][:value]).to(eq('enabled'))
    end
  end

  context 'when container insights disabled' do
    before(:all) do
      reprovision(
          enable_container_insights: 'no')
    end

    it 'has container insights disabled on the cluster' do
      expect(subject.settings[0][:name]).to(eq('containerInsights'))
      expect(subject.settings[0][:value]).to(eq('disabled'))
    end
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 60(1): 165 (1973)

#### Original name
Actinopelte subglobosa T. Yokoy. & Tubaki, 1971

### Remarks
null


text:
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="colorPrimary">#263238</item>
        <item name="colorPrimaryDark">#212121</item>
        <item name="colorAccent">#FFC400</item>
    </style>

    <style name="AppCard" parent="CardView.Dark">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_gravity">center</item>
        <item name="android:layout_marginLeft">@dimen/activity_horizontal_margin</item>
        <item name="android:layout_marginRight">@dimen/activity_horizontal_margin</item>
        <item name="android:layout_marginTop">@dimen/activity_vertical_margin</item>
        <item name="cardCornerRadius">4dp</item>
    </style>

</resources>


text:
<?xml version="1.0"?>
<package>
    <name>sweep_ros</name>
    <version>0.2.0</version>
    <description>The sweep_ros package</description>

    <maintainer email="support@scanse.io">Kent Williams</maintainer>

    <license>MIT</license>

    <buildtool_depend>catkin</buildtool_depend>
    <build_depend>rosconsole</build_depend>
    <build_depend>roscpp</build_depend>
    <build_depend>sensor_msgs</build_depend>
    <build_depend>pcl_conversions</build_depend>
    <build_depend>pcl_msgs</build_depend>
    <run_depend>pcl_conversions</run_depend>
    <run_depend>rosconsole</run_depend>
    <run_depend>roscpp</run_depend>
    <run_depend>sensor_msgs</run_depend>
    <run_depend>pointcloud_to_laserscan</run_depend>

    <!-- The export tag contains other, unspecified, tags -->
    <export>
        <!-- Other tools can request additional information be placed here -->

    </export>
</package>


text:
package request

import (
	"bytes"
	"fmt"
	"time"

	logger "github.com/blendlabs/go-logger"
)

const (
	// Flag is a logger event flag.
	Flag logger.Flag = "request"
	// FlagResponse is a logger event flag.
	FlagResponse logger.Flag = "request.response"
)

// NewRequestListener creates a new request listener.
func NewRequestListener(listener func(Event)) logger.Listener {
	return func(e logger.Event) {
		if typed, isTyped := e.(Event); isTyped {
			listener(typed)
		}
	}
}

// Event is a logger event for outgoing requests.
type Event struct {
	ts  time.Time
	req *Meta
}

// Flag returns the event flag.
func (re Event) Flag() logger.Flag {
	return Flag
}

// Timestamp returns the event timestamp.
func (re Event) Timestamp() time.Time {
	return re.ts
}

// Request returns the request meta.
func (re Event) Request() *Meta {
	return re.req
}

// WriteText writes an outgoing request as text to a given buffer.
func (re Event) WriteText(tf logger.TextFormatter, buf *bytes.Buffer) {
	buf.WriteString(fmt.Sprintf("%s %s", re.req.Verb, re.req.URL.String()))
	if len(re.req.Body) > 0 {
		buf.WriteRune(logger.RuneNewline)
		buf.WriteString("request body")
		buf.WriteRune(logger.RuneNewline)
		buf.Write(re.req.Body)
	}
}

// WriteJSON implements logger.JSONWritable.
func (re Event) WriteJSON() logger.JSONObj {
	return logger.JSONObj{
		"req": re.req,
	}
}

// ResponseEvent is a response to outgoing requests.
type ResponseEvent struct {
	ts   time.Time
	req  *Meta
	res  *ResponseMeta
	body []byte
}

// Flag returns the event flag.
func (re ResponseEvent) Flag() logger.Flag {
	return FlagResponse
}

// Timestamp returns the event timestamp.
func (re ResponseEvent) Timestamp() time.Time {
	return re.ts
}

// Request returns the request meta.
func (re ResponseEvent) Request() *Meta {
	return re.req
}

// Response returns the response meta.
func (re ResponseEvent) Response() *ResponseMeta {
	return re.res
}

// Body returns the outgoing request body.
func (re ResponseEvent) Body() []byte {
	return re.body
}

// WriteText writes the event to a text writer.
func (re ResponseEvent) WriteText(tf logger.TextFormatter, buf *bytes.Buffer) {
	buf.WriteString(fmt.Sprintf("%s %s %s", re.req.Verb, re.req.URL.String(), tf.ColorizeStatusCode(re.res.StatusCode)))
	if len(re.body) > 0 {
		buf.WriteRune(logger.RuneNewline)
		buf.Write(re.body)
	}
}

// WriteJSON implements logger.JSONWritable.
func (re ResponseEvent) WriteJSON() logger.JSONObj {
	return logger.JSONObj{
		"req":  re.req,
		"res":  re.res,
		"body": re.body,
	}
}


text:
package com.jonnyzzz.teamcity.virtual.run.vagrant;

import com.jonnyzzz.teamcity.virtual.run.RelativePaths;
import com.jonnyzzz.teamcity.virtual.util.util.BuildProcessBase;
import com.jonnyzzz.teamcity.virtual.util.util.TryFinallyBuildProcess;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildProgressLogger;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;

/**
 * @author Eugene Petrenko (eugene.petrenko@gmail.com)
 */
public class VagrantFilePatcher {

  public void generateVagrantFile(@NotNull final VagrantContext context,
                                  @NotNull final BuildProgressLogger logger,
                                  @NotNull final File originalVagrantFile,
                                  @NotNull final TryFinallyBuildProcess builder,
                                  @NotNull final WithGeneratedVagrantfile continuation) throws RunBuildException {

    builder.addTryProcess(new BuildProcessBase() {
      @NotNull
      @Override
      protected BuildFinishedStatus waitForImpl() throws RunBuildException {

        final String text;
        try {
          text = FileUtil.readText(originalVagrantFile);
        } catch (IOException e) {
          throw new RuntimeException("Failed to read original Vagranfile. " + e.getMessage(), e);
        }

        final File backupFile;
        try {
          backupFile = FileUtil.createTempFile(context.getAgentTempDirectory(), "Vagrantfile", ".before.patch", true);
        } catch (IOException e) {
          throw new RuntimeException("Failed to create backup for for Vagrantfile. " + e.getMessage(), e);
        }

        try {
          FileUtil.copy(originalVagrantFile, backupFile);
        } catch (IOException e) {
          throw new RuntimeException("Failed to create backup file at: " + backupFile + ". " + e.getMessage(), e);
        }

        builder.addFinishProcess(new BuildProcessBase() {
          @NotNull
          @Override
          protected BuildFinishedStatus waitForImpl() throws RunBuildException {
            try {
              FileUtil.copy(backupFile, originalVagrantFile);
            } catch (IOException e) {
              FileUtil.delete(originalVagrantFile);
              //NOP
            }
            logger.message("Restored original Vagrantfile");
            FileUtil.delete(backupFile);
            return BuildFinishedStatus.FINISHED_SUCCESS;
          }
        });

        final File mountRoot = context.getCheckoutDirectory();
        final String basePath = context.getCheckoutMountPoint();

        final String patch = generateVagrantfile(mountRoot, basePath);
        logger.activityStarted("generate", "Added to the end of the Vagrantfile", "vagrant");
        logger.message(patch);
        logger.activityFinished("generate", "vagrant");

        writeVagrantFile(originalVagrantFile, text + "\n\n" + patch);

        final String relPath = RelativePaths.resolveRelativePath(mountRoot, context.getWorkingDirectory());
        continuation.execute(basePath + (relPath.length() == 0 ? "" : "/" + relPath));
        return BuildFinishedStatus.FINISHED_SUCCESS;
      }

      private void writeVagrantFile(@NotNull final File vagrantFile,
                                    @NotNull final String text) throws RunBuildException {
        try {
          FileUtil.writeFileAndReportErrors(vagrantFile, text);
        } catch (IOException e) {
          throw new RunBuildException("Failed to create Vargantfile. " + e.getMessage(), e);
        }
      }
    });
  }

  @NotNull
  private static String generateVagrantfile(@NotNull final File mountRoot,
                                            @NotNull final String destRoot) {
    final String escapedPath = escapePath(mountRoot.getPath());
    return "## Generated by TeamCity.Virtual plugin\n" +
            "Vagrant.configure(\"2\") do |config|\n" +
            "  config.vm.synced_folder \"" + escapedPath + "\", \"" + destRoot + "\"\n" +
            "end\n";
  }

  @NotNull
  public static String escapePath(@NotNull final String path) {
    if (File.separatorChar == '\\') {
      return path.replace("\\", "\\\\");
    }
    return path;
  }

  public interface WithGeneratedVagrantfile {
    void execute(@NotNull final String machinePathToWork) throws RunBuildException;
  }

}


text:
module LLT
  module Aligner
    class Sentences
      # Compares the string values of two containers and returns
      # a hash of ids { id_in_a => id_in_b }
      #
      # Takes the string values of these containers and places them in
      # a new dictionary.
      # We iterate over these then and delete keys from the the b dict in case
      # we find an equivalent. This should reduce the computation time of this
      # method, as the length of the dictionary where we search things in is getting
      # shorter after every successful alignment.
      def align_ids(a, b)
        x, y = [a, b].map { |c| container_to_s(c) }
        x.each_with_object({}) do |(k, v), result|
          if equivalent = y.find { |_, other_v| v == other_v }
            other_key = equivalent.first
            result[k] = other_key
            y.delete(other_key)
          end
        end
      end

      private

      def container_to_s(container)
        container.each_with_object({}) { |(k, v), hsh| hsh[k] = v.to_s }
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.robert.kafka</groupId>
	<artifactId>kclient</artifactId>
	<version>0.0.1</version>
	<packaging>pom</packaging>
	<name>kclient</name>

	<modules>
		<module>kclient-core</module>
	</modules>

</project>


text:
@import UIKit;

@interface UIColor (ColorAdjustment)

- (UIColor *)originateFloater_darkerColor;

@end


text:
import { Meteor } from 'meteor/meteor';

import { actionLinks } from '../../action-links/client';
import { getVoismartSetting } from '../../voismart-settings';
import { Phone } from '../../voismart-phone/client/phone';

actionLinks.register('webcAudioConf', function(message, params, instance) {
	if (params.number) {
		const user = Meteor.user();
		const enabled = getVoismartSetting(user, 'Phone_Enabled');

		if (enabled) {
			instance.tabBar.open('phone');
			Phone.newCall(params.number, false);
		}
	}
});