code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
var tracery = require('tracery-grammar') var Twit = require('twit') var T = new Twit({ consumer_key: 'wvtSnu5ggH7sSMYSJYknhdu2i', consumer_secret: 'QKmTb7Mpv5a6m9EwSXAXwspHN2BE8N3wuMq4ovsL1D7O17vLOJ', access_token: '742038889846673408-bN7DuJGszTpvv7Eg71aowiIPLvLuQPe', access_token_secret: 'eBpTJNFA8tjQzs0kLo3rccgIioqAgGIHDxovKlKFt4Jm8', timeout_ms: 60*1000, }) var grammarObj = { "S": ["#Billionaire# #Destroys# #Publication# #Prep# #Reason#"], "Billionaire": ["Peter Thiel", "Mark Zuckerberg", "Elon Musk", "Sergey Brin", "Bill Gates", "Eric Schmidt","Larry Ellison", "Paul Graham", "Larry Page", "Dustin Moskovitz", "Jay Koum", "David Duffield", "Michael Bloomberg", "Tim Cook", "Jeff Bezos", "David Koch", "Jim Walton", "Steve Ballmer", "Donald Trump", "Mark Cuban"], "Destroys": ["bankrupts", "financially ruins", "anonymously funds legal action against", "sues", "suppresses writing by", "defunds", "attempts to #Verb#", "attempts to #Verb#", "attempts to #Verb#"], "Verb": ["silence", "defund", "bankrupt", "destroy", "suppress writing by", "smother", "ruin", "take down"], "Publication": ["Gawker","New York Times","Us Weekly","The Wall Street Journal", "Highlights Magazine", "Car and Driver", "Vogue", "The New Yorker", "TMZ", "The New Republic", "Techcrunch","Politico","Time Magazine","Sports Illustrated", "Playboy", "Men's Health", "Cosmopolitan", "GQ", "Harper's", "Lapham's Quarterly", "Mother Jones", "Jacobin", "The Guardian", "USA Today", "Buzzfeed", "The Intercept", "Vice", "Washington Post", "The Onion", "Rookie Magazine"], "Prep": ["because of", "over", "because of long-simmering resentment over", "in reaction to", "in retaliation over", "as revenge for", "in anger over", "to get even over", "in hysterical rage over"], "Reason": ["spilled Lime-A-Rita", "#Diff# yacht directions", "misleading stock tip", "leaked jorts photo", "bad chili dog recommendation", "#Diff# crossword puzzle", "difficult-to-use VR story", "unfunny comic strip", "mean comment on website from user #USERNAME#", "disappointing weather forecast", "condescending Rogaine ad", "documentary on novelty Poke'mon condoms", "leaked rare insect sex tape", "negative coverage of his #PROJECTZ#", "negative review of his #PROJECTZ#"], "Diff" : ["confusing", "hard", "difficult", "challenging", "sloppy"], "USERNAME" : ["DarknEvil666", "The0neTrueR0y", "MagicNutsack", "M1necraft0r94", "TonyRomoFan68", "GunsRPpl2", "xXxYourMomxXx "], "PROJECTZ": ["high-stakes fashion reality show", "SHOWZ performance", "self-directed mumblecore film", "solo electonic music project", "Star Wars memorabilia collection", "inaugural foot modeling photoshoot", "post-impressionist painting of Rand Paul", "Literotica.com submissions", "embarrassing fursona", "glass harp rendition of I Will Survive"], "SHOWZ" : ["American Ninja Warrior", "Dancing with the Stars", "Celebrity Chopped", "Deal or No Deal"] } var grammar = tracery.createGrammar(grammarObj) function generate(){ var t = grammar.flatten("#S#"); T.post('statuses/update', { status: t }, function(err, data, response) { console.log(t) }) } setInterval(generate, 20000)
toddwords/toddwords.github.io
dla2/week4-bots/billionaireBotNode.js
JavaScript
mit
3,165
'use strict'; /** * @name keta.directives.AppBar * @author Vincent Romanus <vincent.romanus@kiwigrid.com> * @module keta.directives.AppBar * @description * <p> * Horizontal navigation bar called AppBar with multiple menus (World Switcher, Menu Bar Toggle, Notification Bar * Toggle, App Title, User Menu, Language Menu and Energy Manager Menu). * </p> * @example * &lt;div data-keta-app-bar * data-event-bus-id="eventBusId" * data-locales="locales" * data-css-classes="appBarCssClasses" * data-current-locale="currentLocale" * data-fallback-locale="fallbackLocale" * data-labels="labels" * data-links="links" * data-worlds="worlds" * data-display-modes="displayModes" * data-root-app="rootApp"&gt; * &lt;a data-ng-href="{{rootApp.link}}" title="{{rootApp.name[currentLocale]}}"&gt; * &lt;img src="img/logo.svg"&gt; * &lt;/a&gt; * &lt;/div&gt; * @example * &lt;div data-keta-app-bar * data-event-bus-id="eventBusId" * data-locales="locales" * data-css-classes="appBarCssClasses" * data-current-locale="currentLocale" * data-fallback-locale="fallbackLocale" * data-labels="labels" * data-links="links" * data-worlds="worlds" * data-display-modes="displayModes"&gt; * &lt;a data-ng-href="/" title="My App root"&gt; * &lt;img src="img/logo.svg"&gt; * &lt;/a&gt; * &lt;/div&gt; * @example * angular.module('exampleApp', ['keta.directives.AppBar']) * .controller('ExampleController', function($scope, ketaAppBarMessageKeys) { * * // id of eventBus instance to use to retrieve data * $scope.eventBusId = 'kiwibus'; * * // array of locales to use for language menu * $scope.locales = [{ * name: 'Deutsch', * nameShort: 'DE', * code: 'de_DE' * }, { * name: 'English', * nameShort: 'EN', * code: 'en_GB' * }]; * * // custom CSS classes for different menu parts of this directive * $scope.appBarCssClasses[ketaAppBarConstants.COMPONENT.WORLD_SWITCHER] = 'my-world-switcher-class'; * $scope.appBarCssClasses[ketaAppBarConstants.COMPONENT.MENU_BAR_TOGGLE] = 'my-menu-toggle-class'; * $scope.appBarCssClasses[ketaAppBarConstants.COMPONENT.NOTIFICATION_BAR_TOGGLE] = 'my-notification-class'; * $scope.appBarCssClasses[ketaAppBarConstants.COMPONENT.APP_TITLE] = 'my-app-title-class'; * $scope.appBarCssClasses[ketaAppBarConstants.COMPONENT.USER_MENU] = 'my-user-menu-class'; * $scope.appBarCssClasses[ketaAppBarConstants.COMPONENT.LANGUAGE_MENU] = 'my-language-menu-class'; * $scope.appBarCssClasses[ketaAppBarConstants.COMPONENT.ENERGY_MANAGER_MENU] = 'my-em-menu-class'; * * // current locale * $scope.currentLocale = 'de_DE'; * * // fallback if locale from user profile is not * // found in the $scope.locales array. * $scope.fallbackLocale = 'en_GB'; * * // override default-labels if necessary * // get default labels * $scope.labels = ketaAppBarMessageKeys; * * // use case 1: overwrite specific key * $scope.labels.de_DE['__keta.directives.AppBar_app_title'] = 'Meine App'; * * // use case 2: add locale * $scope.labels.fr_FR = { * '__keta.directives.AppBar_app_title': 'Applications', * '__keta.directives.AppBar_all_apps': 'Toutes les applications', * '__keta.directives.AppBar_all_energy_managers': 'toutes les Energy-Managers', * '__keta.directives.AppBar_energy_manager': 'Energy-Manager', * '__keta.directives.AppBar_user_logout': 'Se Déconnecter', * '__keta.directives.AppBar_user_profile': 'Profil de l'utilisateur' * }; * * // object of link to use in template * // the directive sets default links that can be overwritten by the keys of this object * $scope.links = { * ALL_APPS: '/#/applications/', * ALL_ENERGY_MANAGERS: '?deviceClass=com.kiwigrid.devices.EnergyManager/#/devices', * APP_ROOT: '/#/landing-page', * USER_PROFILE: '/#/users/profile', * USER_LOGOUT: '/#/users/logout' * }; * * // array of worlds to display in world switcher * // the first world ('Desktop') is automatically prepended as first menu-entry * $scope.worlds = [{ * name: 'Market', * link: 'https://market.mycompany.com' * }, { * name: 'Service', * link: 'https://service.mycompany.com' * }]; * * // object to configure display modes at size xxs, xs, sm, md, and lg * $scope.displayModes = { * worldSwitcher: { * xxs: 'hidden', * xs: 'hidden', * sm: 'hidden', * md: 'hidden', * lg: 'hidden' * }, * menuBarToggle: { * xxs: 'hidden', * xs: 'compact', * sm: 'full', * md: 'full', * lg: 'full' * }, * notificationBarToggle: { * xxs: 'hidden', * xs: 'hidden', * sm: 'hidden', * md: 'hidden', * lg: 'hidden' * }, * appTitle: { * xxs: 'hidden', * xs: 'hidden', * sm: 'full', * md: 'full', * lg: 'full' * }, * userMenu: { * xxs: 'hidden', * xs: 'compact', * sm: 'full', * md: 'full', * lg: 'full' * }, * languageMenu: { * xxs: 'hidden', * xs: 'compact', * sm: 'full', * md: 'full', * lg: 'full' * }, * energyManagerMenu: { * xxs: 'hidden', * xs: 'compact', * sm: 'full', * md: 'full', * lg: 'full' * }, * compactMenu: { * xxs: 'full', * xs: 'full', * sm: 'hidden', * md: 'hidden', * lg: 'hidden' * } * }; * * // object of root app to use in transclusion template * // will be filled automatically by directive * $scope.rootApp = {}; * * }); */ angular.module('keta.directives.AppBar', [ 'keta.directives.Sidebar', 'keta.services.AccessToken', 'keta.services.ApplicationSet', 'keta.services.Device', 'keta.services.DeviceSet', 'keta.services.EventBusDispatcher', 'keta.services.EventBusManager', 'keta.services.User', 'keta.utils.Application', 'keta.utils.Common' ]) .constant('ketaAppBarConstants', { COMPONENT: { WORLD_SWITCHER: 'worldSwitcher', MENU_BAR_TOGGLE: 'menuBarToggle', NOTIFICATION_BAR_TOGGLE: 'notificationBarToggle', APP_TITLE: 'appTitle', USER_MENU: 'userMenu', LANGUAGE_MENU: 'languageMenu', ENERGY_MANAGER_MENU: 'energyManagerMenu', COMPACT_MENU: 'compactMenu', STATUS_LINK: 'statusLink' }, ROOT_APP_ID: 'kiwigrid.usersettingsapp', SIZE: { XXS: 'xxs', XS: 'xs', SM: 'sm', MD: 'md', LG: 'lg' }, STATE: { HIDDEN: 'hidden', FULL: 'full', COMPACT: 'compact' }, TOGGLES: { USER_PROFILE: 'USER_PROFILE', USER_LOGOUT: 'USER_LOGOUT' }, USER_ROLE: { ADMIN: 'ADMIN', DEMO_USER: 'DEMO_USER', FITTER: 'FITTER', SERVICE: 'SERVICE', SUPER_ADMIN: 'SUPER_ADMIN', USER: 'USER' } }) // message keys with default values .constant('ketaAppBarMessageKeys', { 'en_GB': { '__keta.directives.AppBar_app_title': 'Application', '__keta.directives.AppBar_all_apps': 'All Apps', '__keta.directives.AppBar_all_energy_managers': 'All Energy-Managers', '__keta.directives.AppBar_energy_manager': 'Energy-Manager', '__keta.directives.AppBar_user_logout': 'Logout', '__keta.directives.AppBar_user_profile': 'User Account', '__keta.directives.AppBar_logged_in_as': 'You are temporarily logged in as', '__keta.directives.AppBar_drop_access': 'Drop access', '__keta.directives.AppBar_status_link': 'Status' }, 'de_DE': { '__keta.directives.AppBar_app_title': 'Applikation', '__keta.directives.AppBar_all_apps': 'Alle Apps', '__keta.directives.AppBar_all_energy_managers': 'Alle Energy-Manager', '__keta.directives.AppBar_energy_manager': 'Energy-Manager', '__keta.directives.AppBar_user_logout': 'Abmelden', '__keta.directives.AppBar_user_profile': 'Benutzerkonto', '__keta.directives.AppBar_logged_in_as': 'Sie sind temporär angemeldet als', '__keta.directives.AppBar_drop_access': 'Zugriff beenden', '__keta.directives.AppBar_status_link': 'Status' }, 'es_ES': { '__keta.directives.AppBar_app_title': 'Aplicación', '__keta.directives.AppBar_all_apps': 'Todas las aplicaciónes', '__keta.directives.AppBar_all_energy_managers': 'Todas las Energy-Managers', '__keta.directives.AppBar_energy_manager': 'Energy-Manager', '__keta.directives.AppBar_user_logout': 'Cerrar sesión', '__keta.directives.AppBar_user_profile': 'Cuenta de usuario', '__keta.directives.AppBar_logged_in_as': 'Has iniciado sesión temporalmente como', '__keta.directives.AppBar_drop_access': 'Terminar acceso', '__keta.directives.AppBar_status_link': 'Status' }, 'fr_FR': { '__keta.directives.AppBar_app_title': 'Application', '__keta.directives.AppBar_all_apps': 'Toutes les Applications', '__keta.directives.AppBar_all_energy_managers': 'Tous les Energy-Managers', '__keta.directives.AppBar_energy_manager': 'Energy-Manager', '__keta.directives.AppBar_user_logout': 'Se déconnecter', '__keta.directives.AppBar_user_profile': 'Compte d’utilisateur', '__keta.directives.AppBar_logged_in_as': 'Vous êtes connecté en tant que temporairement', '__keta.directives.AppBar_drop_access': 'Déposez accès', '__keta.directives.AppBar_status_link': 'Status' }, 'nl_NL': { '__keta.directives.AppBar_app_title': 'Applicatie', '__keta.directives.AppBar_all_apps': 'Alle applicaties', '__keta.directives.AppBar_all_energy_managers': 'Alle Energy-Managers', '__keta.directives.AppBar_energy_manager': 'Energy-Manager', '__keta.directives.AppBar_user_logout': 'Uitloggen', '__keta.directives.AppBar_user_profile': 'Gebruikers account', '__keta.directives.AppBar_logged_in_as': 'U bent tijdelijk aangemeld als', '__keta.directives.AppBar_drop_access': 'Drop toegang', '__keta.directives.AppBar_status_link': 'Status' }, 'it_IT': { '__keta.directives.AppBar_app_title': 'Application', '__keta.directives.AppBar_all_apps': 'Tutte le applicazioni', '__keta.directives.AppBar_all_energy_managers': 'Tutti gli Energy-Managers', '__keta.directives.AppBar_energy_manager': 'Energy-Manager', '__keta.directives.AppBar_user_logout': 'Disconnettersi', '__keta.directives.AppBar_user_profile': 'Account utente', '__keta.directives.AppBar_logged_in_as': 'Stai temporaneamente l’accesso come', '__keta.directives.AppBar_drop_access': 'Goccia accesso', '__keta.directives.AppBar_status_link': 'Status' }, 'sv_SE': { '__keta.directives.AppBar_app_title': 'Tillämpning', '__keta.directives.AppBar_all_apps': 'Alla tillämpningar', '__keta.directives.AppBar_all_energy_managers': 'Alla Energy-Managers', '__keta.directives.AppBar_energy_manager': 'Energy-Manager', '__keta.directives.AppBar_user_logout': 'Logga ut', '__keta.directives.AppBar_user_profile': 'Användarkonto', '__keta.directives.AppBar_logged_in_as': 'Du är tillfälligt inloggad som', '__keta.directives.AppBar_drop_access': 'Släpp åtkomst', '__keta.directives.AppBar_status_link': 'Status' } }) .directive('ketaAppBar', function AppBarDirective( $rootScope, $window, $document, $filter, $log, ketaEventBusDispatcher, ketaEventBusManager, ketaDeviceSet, ketaApplicationSet, ketaUser, ketaAccessToken, ketaAccessTokenConstants, ketaAppBarConstants, ketaAppBarMessageKeys, ketaDeviceConstants, ketaSidebarConstants, ketaCommonUtils, ketaApplicationUtils ) { return { restrict: 'EA', replace: true, scope: { // id of eventBus instance to use to retrieve data eventBusId: '=?', // array of locales to use for language menu // this will be sorted alphabetically in ascending order locales: '=?', // css classes for different parts of the appBar // defined as object cssClasses: '=?', // current locale currentLocale: '=?', // fallback if locale from user profile is not // found in the $scope.locales array. fallbackLocale: '=?', // object of labels to use in template labels: '=?', // object of link to use in template links: '=?', // array of worlds with label and link worlds: '=?', // string with link to status page statusLink: '=?', // display mode configuration object displayModes: '=?', // environment-specific link to the root app and all available translations as an object. // It will be set by the appBar directive itself and can be used by the parent scope afterwards // (e.g. to set the logo link and title tag in the top left corner). // The object-keys are 'name' (object with keys for all supported languages) and 'link'. rootApp: '=?', // feature toggles based on user role toggles: '=?' }, transclude: true, templateUrl: '/components/directives/app-bar.html', link: function linkAppBarDirective(scope, element) { // get menu data scope.user = {}; scope.menus = {}; scope.worlds = scope.worlds || []; scope.locales = scope.locales || []; scope.cssClasses = scope.cssClasses || {}; scope.energyManagers = []; scope.impersonationInfo = {}; // sort locales scope.locales = $filter('orderBy')(scope.locales, 'name'); // event bus scope.eventBusId = scope.eventBusId || 'kiwibus'; var eventBus = ketaEventBusManager.get(scope.eventBusId); var STATES = ketaAppBarConstants.STATE; var SIZES = ketaAppBarConstants.SIZE; var DEFAULT_CONTAINER_HEIGHT = 120; scope.MENU_ELEMENTS = ketaAppBarConstants.COMPONENT; var DECIMAL_RADIX = 10, HIDDEN_CLASS_PREFIX = 'hidden-', VISIBLE_CLASS_PREFIX = 'visible-'; var DEFAULT_LOCALE_FALLBACK = 'en_GB'; // all sizes have NONE state var sizesFullState = {}; sizesFullState[SIZES.XXS] = STATES.FULL; sizesFullState[SIZES.XS] = STATES.FULL; sizesFullState[SIZES.SM] = STATES.FULL; sizesFullState[SIZES.MD] = STATES.FULL; sizesFullState[SIZES.LG] = STATES.FULL; // standard STATES for userMenu, energyManagerMenu and languageMenu var sizesDefaultState = {}; sizesDefaultState[SIZES.XXS] = STATES.HIDDEN; sizesDefaultState[SIZES.XS] = STATES.HIDDEN; sizesDefaultState[SIZES.SM] = STATES.COMPACT; sizesDefaultState[SIZES.MD] = STATES.COMPACT; sizesDefaultState[SIZES.LG] = STATES.FULL; // standard STATES for World Switcher var sizesHiddenState = {}; sizesHiddenState[SIZES.XXS] = STATES.HIDDEN; sizesHiddenState[SIZES.XS] = STATES.HIDDEN; sizesHiddenState[SIZES.SM] = STATES.HIDDEN; sizesHiddenState[SIZES.MD] = STATES.HIDDEN; sizesHiddenState[SIZES.LG] = STATES.HIDDEN; var defaultDisplayModes = {}; defaultDisplayModes[scope.MENU_ELEMENTS.WORLD_SWITCHER] = sizesHiddenState; defaultDisplayModes[scope.MENU_ELEMENTS.MENU_BAR_TOGGLE] = sizesFullState; defaultDisplayModes[scope.MENU_ELEMENTS.NOTIFICATION_BAR_TOGGLE] = sizesFullState; defaultDisplayModes[scope.MENU_ELEMENTS.APP_TITLE] = sizesFullState; defaultDisplayModes[scope.MENU_ELEMENTS.STATUS_LINK] = sizesFullState; defaultDisplayModes[scope.MENU_ELEMENTS.USER_MENU] = sizesDefaultState; defaultDisplayModes[scope.MENU_ELEMENTS.ENERGY_MANAGER_MENU] = sizesDefaultState; defaultDisplayModes[scope.MENU_ELEMENTS.LANGUAGE_MENU] = sizesDefaultState; defaultDisplayModes[scope.MENU_ELEMENTS.COMPACT_MENU] = {}; defaultDisplayModes[scope.MENU_ELEMENTS.COMPACT_MENU][SIZES.XXS] = STATES.COMPACT; defaultDisplayModes[scope.MENU_ELEMENTS.COMPACT_MENU][SIZES.XS] = STATES.COMPACT; defaultDisplayModes[scope.MENU_ELEMENTS.COMPACT_MENU][SIZES.SM] = STATES.HIDDEN; defaultDisplayModes[scope.MENU_ELEMENTS.COMPACT_MENU][SIZES.MD] = STATES.HIDDEN; defaultDisplayModes[scope.MENU_ELEMENTS.COMPACT_MENU][SIZES.LG] = STATES.HIDDEN; // default container height var scrollContainerHeight = DEFAULT_CONTAINER_HEIGHT; scope.container = element[0]; var navBars = element.find('nav'); var navbarFirst = navBars[0]; var navbarFirstHeight = 0; var impersonationBar = element[0].getElementsByClassName('impersonation-bar')[0]; var impersonationBarHeight = 0; var navbarSecond = navBars[1]; var navbarSecondHeight = 0; var navbarSecondMarginBottom = 0; /** * @description Checks if the given menu is visible in all screen sizes * @param {object} menuElement The menu element * @returns {boolean} Returns true if the menu is visible in any screen size */ var isMenuVisible = function isMenuVisible(menuElement) { var isVisible = false; angular.forEach(SIZES, function(size) { if (scope.displayModes[menuElement][size] !== STATES.HIDDEN) { isVisible = true; } }); return isVisible; }; /** * merges two objects, customObject overwrites values in defaultObject * @param {object} customObject custom object * @param {object} defaultObject default object to merge into custom object * @returns {object} merged result */ var mergeObjects = function mergeObjects(customObject, defaultObject) { var result = {}, value; for (value in customObject) { // if it's an object, merge if (value in defaultObject && typeof customObject[value] === 'object' && value !== null) { result[value] = mergeObjects(customObject[value], defaultObject[value]); // add it to result } else { result[value] = customObject[value]; } } // add the remaining properties from defaultObject for (value in defaultObject) { if (value in result) { continue; } result[value] = defaultObject[value]; } return result; }; /** * Set Container height for scrolling affix * @returns {void} */ var setContainerHeight = function setContainerHeight() { navbarFirstHeight = navbarFirst.offsetHeight; if (angular.isDefined(impersonationBar)) { impersonationBarHeight = impersonationBar.offsetHeight; } navbarSecondHeight = navbarSecond.offsetHeight; navbarSecondMarginBottom = parseInt( $window.getComputedStyle(navbarSecond, null).getPropertyValue('margin-bottom'), DECIMAL_RADIX ); // container height for fixed navigation scrollContainerHeight = navbarFirstHeight + impersonationBarHeight + navbarSecondHeight + navbarSecondMarginBottom; }; /** * @description * Checks if the given locale code is present * in the array of available locales (scope.locales). * @param {String} localeCode Locale code that should be checked * @returns {boolean} locale is available or not */ var isLocaleAvailable = function isLocaleAvailable(localeCode) { var isAvailable = false; angular.forEach(scope.locales, function(availableLocale) { if (angular.isDefined(availableLocale.code) && availableLocale.code === localeCode) { isAvailable = true; } }); return isAvailable; }; scope.displayModes = mergeObjects(scope.displayModes, defaultDisplayModes); scope.fallbackLocale = scope.fallbackLocale || DEFAULT_LOCALE_FALLBACK; scope.currentLocale = scope.currentLocale || scope.fallbackLocale; if (!isLocaleAvailable(scope.currentLocale)) { scope.currentLocale = scope.fallbackLocale; } // object of labels scope.MESSAGE_KEY_PREFIX = '__keta.directives.AppBar'; scope.labels = angular.extend(ketaAppBarMessageKeys, scope.labels); scope.getLabel = function getLabel(key) { return ketaCommonUtils.getLabelByLocale(key, scope.labels, scope.currentLocale); }; // get access token var accessToken = ketaAccessToken.decode(ketaAccessToken.get()); var defaultLinks = { ALL_APPS: null, ALL_ENERGY_MANAGERS: null, APP_ROOT: accessToken !== null && angular.isDefined(accessToken.user_id) ? ketaCommonUtils.addUrlParameter('/', 'userId', accessToken.user_id) : '/', USER_PROFILE: null, USER_LOGOUT: null }; // type constants used in ng-repeats orderBy filter scope.TYPES = { ENERGY_MANAGER: 'ENERGY_MANAGER' }; // limit constants used in ng-repeats limit filter scope.LIMITS = { ENERGY_MANAGER: 3 }; // order predicates and reverse flags var PREDICATES = { ENERGY_MANAGER: { field: 'name', reverse: false } }; scope.links = angular.isDefined(scope.links) ? angular.extend(defaultLinks, scope.links) : defaultLinks; var defaultToggles = {}; defaultToggles[ketaAppBarConstants.USER_ROLE.DEMO_USER] = {}; defaultToggles[ketaAppBarConstants.USER_ROLE.DEMO_USER] [ketaAppBarConstants.TOGGLES.USER_PROFILE] = false; scope.AVAILABLE_TOGGLES = ketaAppBarConstants.TOGGLES; /** * update toggles * @returns {void} nothing */ var updateToggles = function updateToggles() { if (angular.isDefined(scope.toggles)) { var toggles = angular.copy(defaultToggles); angular.forEach(scope.toggles, function(userRoleToggles, userRole) { if (!angular.equals(scope.toggles[userRole], {})) { toggles[userRole] = angular.extend(toggles[userRole] || {}, scope.toggles[userRole]); } }); scope.toggles = toggles; } else { scope.toggles = angular.copy(defaultToggles); } }; updateToggles(); /** * set default links that can be overwritten by the scope.links property * @returns {void} nothing */ var setDefaultLinks = function setDefaultLinks() { scope.links.USER_LOGOUT = angular.isString(scope.links.USER_LOGOUT) ? scope.links.USER_LOGOUT : '/rest/auth/logout'; ketaApplicationUtils.getAppList({ eventBusId: scope.eventBusId, filter: { appId: ketaAppBarConstants.ROOT_APP_ID } }).then(function(apps) { var entryUri = null; var name = {}; scope.rootApp = null; angular.forEach(apps, function(app) { if (angular.isDefined(app.appId) && app.appId === ketaAppBarConstants.ROOT_APP_ID && angular.isDefined(app.entryUri)) { // set entry uri entryUri = app.entryUri; // set name if (ketaCommonUtils.doesPropertyExist(app, 'meta.i18n')) { angular.forEach(Object.keys(app.meta.i18n), function(locale) { angular.forEach(scope.locales, function(availableLocale) { if (angular.isDefined(availableLocale.code) && availableLocale.code === locale) { name[availableLocale.code] = app.meta.i18n[locale].name; } }); }); } } }); // use link-element to easily access url params var link = document.createElement('a'); link.href = entryUri; if (entryUri !== null) { scope.rootApp = {}; scope.rootApp.link = ketaCommonUtils.addUrlParameter(entryUri, 'userId', accessToken.user_id); scope.rootApp.name = name; scope.worlds.unshift({ name: 'User Settings App', link: scope.rootApp.link }); } scope.links.ALL_APPS = angular.isString(scope.links.ALL_APPS) ? scope.links.ALL_APPS : ketaCommonUtils.addUrlParameter( entryUri + '#/applications', 'userId', accessToken.user_id ); scope.links.USER_PROFILE = angular.isString(scope.links.USER_PROFILE) ? scope.links.USER_PROFILE : ketaCommonUtils.addUrlParameter( entryUri + '#/user', 'userId', accessToken.user_id ); if (!angular.isString(scope.links.ALL_ENERGY_MANAGERS)) { var allManagersUri = ketaCommonUtils.addUrlParameter( entryUri, 'deviceClass', 'com.kiwigrid.devices.em.EnergyManager' ); scope.links.ALL_ENERGY_MANAGERS = ketaCommonUtils.addUrlParameter( allManagersUri + '#/devices', 'userId', accessToken.user_id ); } }); }; var allLinkKeysAlreadySet = true; angular.forEach(Object.keys(defaultLinks), function(linkKey) { if (defaultLinks[linkKey] === null) { allLinkKeysAlreadySet = false; } }); if (allLinkKeysAlreadySet === false) { setDefaultLinks(); } /** * get display mode and custom css classes * @param {string} menuName name of the menu * @param {string} elementType either 'menu' or 'label' * @returns {string} all css classes that should be applied to this element in the template */ scope.getClasses = function getClasses(menuName, elementType) { var classes = []; if (!angular.isDefined(elementType)) { elementType = 'menu'; } if (angular.isDefined(scope.menus[menuName]) && angular.isDefined(scope.menus[menuName].isOpen)) { if (scope.menus[menuName].isOpen) { classes.push('open'); } } angular.forEach(SIZES, function(size) { var state = scope.displayModes[menuName][size]; switch (elementType) { case 'menu': switch (state) { case STATES.HIDDEN: classes.push(HIDDEN_CLASS_PREFIX + size); break; case STATES.FULL: classes.push(VISIBLE_CLASS_PREFIX + size); break; case STATES.COMPACT: classes.push(VISIBLE_CLASS_PREFIX + size); break; default: break; } break; case 'label': if (state === STATES.COMPACT) { classes.push(HIDDEN_CLASS_PREFIX + size); } break; default: break; } }); if (angular.isString(scope.cssClasses[menuName])) { classes.push(scope.cssClasses[menuName]); } return classes.join(' '); }; /** * query energy managers, format: {name: 'ERC02-000001051', link: 'http://192.168.125.81'} * @returns {void} nothing */ var getDevices = function getDevices() { if (eventBus !== null && angular.isDefined(scope.user.userId) && isMenuVisible(scope.MENU_ELEMENTS.ENERGY_MANAGER_MENU)) { ketaDeviceSet.create(eventBus) .filter({ 'deviceModel.deviceClass': { '$in': [ketaDeviceConstants.CLASS.ENERGY_MANAGER] }, owner: scope.user.userId }) .project({ tagValues: { IdName: 1, SettingsNetworkMap: 1 } }) .query() .then(function(reply) { if (angular.isDefined(reply.result) && angular.isDefined(reply.result.items)) { var energyManagers = []; angular.forEach(reply.result.items, function(item) { var emIP = angular.isDefined(item.tagValues) && angular.isDefined(item.tagValues.SettingsNetworkMap) && angular.isDefined(item.tagValues.SettingsNetworkMap.value) && angular.isDefined(item.tagValues.SettingsNetworkMap.value.ipv4) ? item.tagValues.SettingsNetworkMap.value.ipv4 : null; if (emIP !== null) { energyManagers.push({ name: item.tagValues.IdName.value, link: 'http://' + emIP }); } }); scope.energyManagers = energyManagers; } }); } }; /** * returns the currently active entry in the language menu * @returns {object} active entry in language menu */ var getActiveLangEntry = function getActiveLangEntry() { var activeLangEntry = scope.locales[0] || {}; angular.forEach(scope.locales, function(value) { if (value.code === scope.currentLocale) { activeLangEntry = value; } }); return activeLangEntry; }; /** * @description * Searches in the object scope.user for the locale property and stores * it in the variable scope.currentLocale. * @returns {void} nothing */ var readLocaleFromUserProp = function readLocaleFromUserProp() { if (ketaCommonUtils.doesPropertyExist(scope.user, 'properties.locale.code') && isLocaleAvailable(scope.user.properties.locale.code)) { scope.currentLocale = scope.user.properties.locale.code; } }; /** * @description * Stores the given locale code on the user property via API call. * @param {string} localeCode locale code * @returns {void} nothing */ var writeLocaleUserProp = function writeLocaleUserProp(localeCode) { scope.user.properties = scope.user.properties || {}; scope.user.properties.locale = scope.user.properties.locale || {}; scope.user.properties.locale.code = localeCode; var params = { userId: scope.user.userId }; var body = { properties: scope.user.properties }; ketaEventBusDispatcher.send(eventBus, 'userservice', { action: 'mergeUser', body: body, params: params }, function(reply) { // log if in debug mode if (ketaEventBusManager.inDebugMode()) { $log.request(['userservice', { action: 'mergeUser', params: params, body: body }, reply], $log.ADVANCED_FORMATTER); } }); }; /** * updates the open state and currently active entry in the language menu * @returns {void} nothing */ var updateMenus = function updateMenus() { scope.menus = {}; scope.menus[scope.MENU_ELEMENTS.COMPACT_MENU] = {isOpen: false}; scope.menus[scope.MENU_ELEMENTS.WORLD_SWITCHER] = {isOpen: false}; scope.menus[scope.MENU_ELEMENTS.ENERGY_MANAGER_MENU] = {isOpen: false}; scope.menus[scope.MENU_ELEMENTS.USER_MENU] = {isOpen: false}; scope.menus[scope.MENU_ELEMENTS.LANGUAGE_MENU] = { isOpen: false, activeEntry: getActiveLangEntry() }; }; // query current user if (eventBus !== null) { ketaUser.getCurrent(eventBus) .then(function(reply) { scope.user = reply; readLocaleFromUserProp(); getDevices(); }); } // LOGIC --- /** * Checks, whether the currently opened app is * accessed by an impersonated user * @returns {boolean} impersonation status */ scope.isImpersonated = function isImpersonated() { var result = false; if (ketaAccessToken.isType(ketaAccessTokenConstants.SESSION_TYPE.IMPERSONATED)) { scope.impersonationInfo = { userId: ketaAccessToken.getUserId(), backUrl: ketaAccessToken.getBackUrl() }; result = true; } return result; }; /** * checks if the given toggle is enabled * @param {string} toggle to check * @returns {boolean} true if enabled */ scope.isEnabled = function isEnabled(toggle) { var enabled = true; var userRoleScores = {}; userRoleScores[ketaAppBarConstants.USER_ROLE.DEMO_USER] = 1; userRoleScores[ketaAppBarConstants.USER_ROLE.USER] = 2; userRoleScores[ketaAppBarConstants.USER_ROLE.FITTER] = 3; userRoleScores[ketaAppBarConstants.USER_ROLE.SERVICE] = 4; userRoleScores[ketaAppBarConstants.USER_ROLE.ADMIN] = 5; userRoleScores[ketaAppBarConstants.USER_ROLE.SUPER_ADMIN] = 6; var userRole = ketaAppBarConstants.USER_ROLE.DEMO_USER; if (angular.isDefined(scope.user) && angular.isDefined(scope.user.roles)) { scope.user.roles.forEach(function(role) { if (userRoleScores[userRole] < userRoleScores[role]) { userRole = role; } }); } if (angular.isDefined(scope.toggles[userRole]) && angular.isDefined(scope.toggles[userRole][toggle])) { enabled = scope.toggles[userRole][toggle]; } return enabled; }; /** * order elements by predicate * @param {string} type component type to order * @returns {function} ordering function that is used by ng-repeat in the template */ scope.order = function order(type) { var field = angular.isDefined(PREDICATES[type]) ? PREDICATES[type].field : 'name'; return function(item) { return angular.isDefined(item[field]) ? item[field] : ''; }; }; /** * returns if reverse ordering is active or not * @param {string} type component type to determine for * @returns {boolean} reverse ordering or not */ scope.reverse = function reverse(type) { return angular.isDefined(PREDICATES[type]) && angular.isDefined(PREDICATES[type].reverse) ? PREDICATES[type].reverse : false; }; scope.scrollOverNavbarFirst = false; angular.element($window).bind('scroll', function scroll() { if (angular.isDefined(navbarFirst)) { // scroll over navbar-level-1 if (this.scrollY > navbarFirstHeight + impersonationBarHeight) { scope.scrollOverNavbarFirst = true; // compensate empty space of fixed navbar with placeholder height element.css('height', scrollContainerHeight + 'px'); } else { scope.scrollOverNavbarFirst = false; element.css('height', 'auto'); } scope.menus.worldSwitcher.isOpen = false; scope.$digest(); } }); /** * toggle state of menu * @param {string} menuName name of the menu to toggle * @returns {void} nothing */ scope.toggleOpenState = function toggleOpenState(menuName) { if (angular.isDefined(scope.menus[menuName])) { var currentState = angular.copy(scope.menus[menuName].isOpen); scope.closeAllMenus(); if (currentState === scope.menus[menuName].isOpen) { scope.menus[menuName].isOpen = !scope.menus[menuName].isOpen; } } }; /** * close all menus by switching boolean flag isOpen * @returns {void} nothing */ scope.closeAllMenus = function closeAllMenus() { scope.menus[scope.MENU_ELEMENTS.WORLD_SWITCHER].isOpen = false; scope.menus[scope.MENU_ELEMENTS.USER_MENU].isOpen = false; scope.menus[scope.MENU_ELEMENTS.ENERGY_MANAGER_MENU].isOpen = false; scope.menus[scope.MENU_ELEMENTS.COMPACT_MENU].isOpen = false; scope.menus[scope.MENU_ELEMENTS.LANGUAGE_MENU].isOpen = false; }; /** * set locale if user selects another entry in the language menu * @param {object} locale new locale to set * @returns {void} nothing */ scope.setLocale = function setLocale(locale) { scope.currentLocale = locale.code; writeLocaleUserProp(locale.code); scope.menus[scope.MENU_ELEMENTS.LANGUAGE_MENU].activeEntry = locale; scope.closeAllMenus(); }; scope.$on('$locationChangeStart', function $locationChangeStart() { scope.closeAllMenus(); }); /** * check if a given entry is active to set corresponding css class * @param {string} menuName menu name * @param {object} entry menu entry object with all flags * @returns {boolean} flag menu entry is open or not */ scope.isActive = function isActive(menuName, entry) { return angular.isDefined(scope.menus[menuName]) && scope.menus[menuName].activeEntry === entry; }; /** * toggle sidebar if button is clicked * @param {object} $event jqLite event object * @param {string} position position of the sidebar ('left' or 'right') * @returns {void} nothing */ scope.toggleSidebar = function toggleSidebar($event, position) { $event.stopPropagation(); scope.closeAllMenus(); if (position === ketaSidebarConstants.POSITION.LEFT) { $rootScope.$broadcast(ketaSidebarConstants.EVENT.TOGGLE_SIDEBAR_LEFT); } else if (position === ketaSidebarConstants.POSITION.RIGHT) { $rootScope.$broadcast(ketaSidebarConstants.EVENT.TOGGLE_SIDEBAR_RIGHT); } }; $document.bind('click', function click(event) { var appBarHtml = element.html(), targetElementHtml = angular.element(event.target).html(); if (appBarHtml.indexOf(targetElementHtml) !== -1) { return; } scope.closeAllMenus(); scope.$digest(); }); scope.$watch('energyManagers', function watchEnergyManagers(newValue, oldValue) { if (newValue !== oldValue) { updateMenus(); } }); scope.$watch('currentLocale', function(newValue, oldValue) { if (newValue !== oldValue) { updateMenus(); } }); scope.$watch('toggles', function(newValue, oldValue) { if (!angular.equals(newValue, oldValue)) { updateToggles(); } }); scope.$watch('container.offsetHeight', function(newValue, oldValue) { if (newValue !== oldValue) { setContainerHeight(); } }); // INIT // ---- setContainerHeight(); updateMenus(); } }; }); // prepopulate template cache angular.module('keta.directives.AppBar') .run(function($templateCache) { $templateCache.put('/components/directives/app-bar.html', '<div class="navigation-container">' + ' <div class="impersonation-bar" data-ng-show="isImpersonated()">' + ' <div class="container-fluid">' + ' <span class="glyphicon glyphicon-warning-sign"></span>' + ' <span>' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_logged_in_as\') }}' + ' <strong>{{ user.givenName }} {{ user.familyName }} ({{impersonationInfo.userId}}). </strong>' + ' <a' + ' target="_self"' + ' href="{{impersonationInfo.backUrl}}"' + ' title="{{ getLabel(MESSAGE_KEY_PREFIX + \'_drop_access\') }}">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_drop_access\') }}' + ' </a>' + ' </span>' + ' </div>' + ' </div>' + '' + ' <nav class="navbar navbar-level-1 brand-bar keta-app-bar-first-row" role="navigation">' + ' <div class="container-fluid">' + ' <div data-ng-transclude></div>' + ' <div class="dropdown pull-right"' + ' data-ng-if="worlds.length > 0"' + ' data-ng-class="getClasses(MENU_ELEMENTS.WORLD_SWITCHER)">' + ' <a href="" class="dropdown-toggle" data-ng-click="toggleOpenState(MENU_ELEMENTS.WORLD_SWITCHER)">' + ' <span class="glyphicon glyphicon-th"></span>' + ' </a>' + ' <ul class="dropdown-menu">' + ' <li data-ng-repeat="world in worlds">' + ' <a data-ng-href="{{ world.link }}">{{ world.name }}</a>' + ' </li>' + ' </ul>' + ' </div>' + ' </div>' + ' </nav>' + '' + ' <nav class="navbar navbar-default navbar-level-2 keta-app-bar-second-row"' + ' data-ng-class="{\'navbar-fixed-top\': scrollOverNavbarFirst}"' + ' role="navigation">' + ' <div class="container-fluid">' + '' + ' <ul class="nav navbar-nav keta-app-bar-toggle">' + ' <li class="menu-navbar" data-ng-class="getClasses(MENU_ELEMENTS.MENU_BAR_TOGGLE)">' + ' <a href="" data-ng-click="toggleSidebar($event, \'left\')">' + ' <span class="glyphicon glyphicon-align-justify"></span>' + ' </a>' + ' </li>' + ' <li data-ng-class="getClasses(MENU_ELEMENTS.APP_TITLE)">' + ' <a data-ng-if="links.APP_ROOT !== null" class="application-title"' + ' data-ng-href="{{ links.APP_ROOT }}">{{ getLabel(MESSAGE_KEY_PREFIX + \'_app_title\') }}</a>' + ' <span data-ng-if="links.APP_ROOT === null" class="application-title">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_app_title\') }}' + ' </span>' + ' </li>' + ' </ul>' + '' + ' <ul class="nav navbar-nav navbar-right">' + '' + ' <li class="dropdown keta-app-bar-user-menu" data-ng-class="getClasses(MENU_ELEMENTS.USER_MENU)">' + ' <a href="" data-ng-click="toggleOpenState(MENU_ELEMENTS.USER_MENU)">' + ' <span class="glyphicon glyphicon-user"></span>' + ' <span class="navbar-label" data-ng-class="getClasses(MENU_ELEMENTS.USER_MENU, \'label\')">' + ' {{ user.givenName }} {{ user.familyName }}' + ' </span>' + ' <span class="caret"></span>' + ' </a>' + ' <ul class="dropdown-menu dropdown-menu-right">' + ' <li data-ng-if="isEnabled(AVAILABLE_TOGGLES.USER_PROFILE) && links.USER_PROFILE">' + ' <a data-ng-href="{{ links.USER_PROFILE }}" data-ng-click="closeAllMenus()">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_user_profile\') }}' + ' </a>' + ' </li>' + ' <li data-ng-if="isEnabled(AVAILABLE_TOGGLES.USER_LOGOUT)">' + ' <a data-ng-href="{{ links.USER_LOGOUT }}" data-ng-click="closeAllMenus()">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_user_logout\') }}' + ' </a>' + ' </li>' + ' </ul>' + ' </li>' + '' + ' <li class="dropdown keta-app-bar-em-menu"' + ' data-ng-if="energyManagers.length > 0"' + ' data-ng-class="getClasses(MENU_ELEMENTS.ENERGY_MANAGER_MENU)">' + ' <a href="" class="dropdown-toggle"' + ' data-ng-click="toggleOpenState(MENU_ELEMENTS.ENERGY_MANAGER_MENU)">' + ' <span class="glyphicon glyphicon-tasks" title="Energy-Manager"></span>' + ' <span class="navbar-label"' + ' data-ng-class="getClasses(MENU_ELEMENTS.ENERGY_MANAGER_MENU, \'label\')">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_energy_manager\') }}' + ' </span>' + ' <span>({{ energyManagers.length }})</span>' + ' <span class="caret"></span>' + ' </a>' + ' <ul class="dropdown-menu">' + ' <li data-ng-repeat="' + ' entry in energyManagers |' + ' orderBy:order(TYPES.ENERGY_MANAGER):reverse(TYPES.ENERGY_MANAGER) |' + ' limitTo:LIMITS.ENERGY_MANAGER">' + ' <a data-ng-href="{{ entry.link }}" data-ng-click="closeAllMenus()">' + ' {{ entry.name }}' + ' </a>' + ' </li>' + ' <li data-ng-if="energyManagers.length > LIMITS.ENERGY_MANAGER &&' + ' links.ALL_ENERGY_MANAGERS !== null &&' + ' labels.ALL_ENERGY_MANAGERS !== null">' + ' <a data-ng-href="{{ links.ALL_ENERGY_MANAGERS }}" data-ng-click="closeAllMenus()">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_all_energy_managers\') }}' + ' ({{ energyManagers.length }})' + ' </a>' + ' </li>' + ' </ul>' + ' </li>' + '' + ' <li class="dropdown keta-app-bar-lang-menu"' + ' data-ng-if="locales.length > 0"' + ' data-ng-class="getClasses(MENU_ELEMENTS.LANGUAGE_MENU)">' + ' <a href="" class="dropdown-toggle" data-ng-click="toggleOpenState(MENU_ELEMENTS.LANGUAGE_MENU)">' + ' <span class="glyphicon glyphicon-flag"' + ' title="{{ menus.languageMenu.activeEntry.nameShort }}"></span>' + ' <span class="navbar-label" data-ng-class="getClasses(MENU_ELEMENTS.LANGUAGE_MENU, \'label\')">' + ' {{ menus.languageMenu.activeEntry.nameShort }}' + ' </span>' + ' <span class="caret"></span>' + ' </a>' + ' <ul class="dropdown-menu">' + ' <li data-ng-repeat="locale in locales"' + ' data-ng-class="{ active: isActive(MENU_ELEMENTS.LANGUAGE_MENU, locale) }">' + ' <a href="" data-ng-click="setLocale(locale)">{{ locale.name }}</a>' + ' </li>' + ' </ul>' + ' </li>' + '' + ' <li class="dropdown keta-app-bar-status-link"' + ' data-ng-if="!!statusLink"' + ' data-ng-class="getClasses(MENU_ELEMENTS.STATUS_LINK)">' + ' <a href="{{statusLink}}" target="_blank">' + ' <span class="glyphicon glyphicon-zoom-in"' + ' title="Status"></span>' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_status_link\') }}' + ' </a>' + ' </li>' + '' + ' <li class="dropdown keta-app-bar-compact-menu" data-ng-class="getClasses(MENU_ELEMENTS.COMPACT_MENU)">' + ' <a href="" data-ng-click="toggleOpenState(MENU_ELEMENTS.COMPACT_MENU)">' + ' <span class="glyphicon glyphicon-option-vertical"></span>' + ' </a>' + ' <ul class="dropdown-menu dropdown-menu-right">' + ' <li>' + ' <a data-ng-href="{{ links.USER_PROFILE }}" data-ng-click="closeAllMenus()">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_user_profile\') }}' + ' </a>' + ' </li>' + ' <li>' + ' <a data-ng-href="{{ links.USER_LOGOUT }}" data-ng-click="closeAllMenus()">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_user_logout\') }}' + ' </a>' + ' </li>' + ' <li class="divider" data-ng-if="energyManagers.length"></li>' + ' <li data-ng-repeat="' + ' entry in energyManagers |' + ' orderBy:order(TYPES.ENERGY_MANAGER):reverse(TYPES.ENERGY_MANAGER) |' + ' limitTo:LIMITS.ENERGY_MANAGER">' + ' <a data-ng-href="{{ entry.link }}" data-ng-click="closeAllMenus()">' + ' {{ entry.name }}' + ' </a>' + ' </li>' + ' <li data-ng-if="energyManagers.length > LIMITS.ENERGY_MANAGER">' + ' <a data-ng-href="{{ links.ALL_ENERGY_MANAGERS }}" data-ng-click="closeAllMenus()">' + ' {{ getLabel(MESSAGE_KEY_PREFIX + \'_all_energy_managers\') }}' + ' ({{ energyManagers.length }})' + ' </a>' + ' </li>' + ' <li class="divider" data-ng-if="locales"></li>' + ' <li data-ng-repeat="entry in locales"' + ' data-ng-class="{ active: isActive(MENU_ELEMENTS.LANGUAGE_MENU, entry) }">' + ' <a href="" data-ng-click="setLocale(entry)">{{ entry.name }}</a>' + ' </li>' + ' </ul>' + ' </li>' + '' + ' <li class="keta-app-bar-notification-menu"' + ' data-ng-class="getClasses(MENU_ELEMENTS.NOTIFICATION_BAR_TOGGLE)">' + ' <a href="" id="toggleSidebarButton" data-ng-click="toggleSidebar($event, \'right\')">' + ' <span class="glyphicon glyphicon-bell"' + ' title="{{ getLabel(MESSAGE_KEY_PREFIX + \'_notifications\') }}"></span>' + ' <span data-ng-if="notifications.length > 0" class="badge">{{notifications.length}}</span>' + ' </a>' + ' </li>' + '' + ' </ul>' + ' </div>' + ' </nav>' + ' <div class="nav-backdrop"></div>' + '</div>' + ''); });
kiwigrid/keta
directives/app-bar.js
JavaScript
mit
46,485
let creates=document.querySelectorAll('.create'); let editSection=document.querySelector('#edit-section'); let editSectionSubmit=document.querySelector('#edit_section_submit'); let editInput=document.querySelectorAll('.edit-input'); creates.forEach(create =>{ create.addEventListener('click',e =>{ e.preventDefault(); // do not create a zone on the main page let view=document.querySelector('#view'); let currentPageId=view.dataset['currentPageId']; if(currentPageId==0){ return false; } // create element let newElement=document.createElement(e.target.innerHTML); newElement.innerHTML="new "+e.target.innerHTML +' double click to edit | drag to move'; /* Attribute */ newElement.setAttribute('id','id'+Date.now()); newElement.setAttribute('draggable',true); newElement.setAttribute('ondragstart',"event.dataTransfer.setData('text/plain',null)"); /* style */ // common newElement.style.position="absolute"; newElement.style.top="0"; newElement.style.right="0"; newElement.style.resize="both"; newElement.style.overflow="auto"; newElement.style.display="flex"; newElement.style.justifyContent="center"; newElement.style.alignItems="center"; newElement.style.width="200px"; newElement.style.height="100px"; newElement.style.color="#000"; newElement.style.backgroundColor="#369"; newElement.style.opacity=1; /* Event listener */ // on context menu event(right click) newElement.addEventListener('contextmenu',e =>{ e.preventDefault(); globalEdit(e.target, e.target.getAttribute('id')); },true) // Double click event newElement.addEventListener('dblclick', e =>{ e.preventDefault(); e.target.setAttribute('contenteditable',true); e.target.style.boxShadow="0 0 2px 2px #000"; e.target.focus(); // autofocus },true); // Blur Event newElement.addEventListener('blur',e =>{ e.target.setAttribute("contenteditable",false); e.target.style.boxShadow=""; }) // select the current page let currentPage=document.querySelector('#page'+currentPageId); currentPage.appendChild(newElement); }) }) editInput.forEach(input =>{ input.addEventListener('change',e =>{ let element=document.querySelector('#'+editSection.getAttribute('ref-id')); if(e.target.classList.contains('pixel')){ element.style[e.target.getAttribute('name')]=e.target.value+'px'; } element.style[e.target.getAttribute('name')]=e.target.value; }) }) editSectionSubmit.addEventListener('click',e =>{ editSection.style.display="none"; }) function globalEdit(element,elementId){ let editSection=document.querySelector('#edit-section'); /* attributes */ editSection.setAttribute('ref-id',elementId); editSection.style.display="block"; for(let i=0; i<editSection.children.length; i++){ for(let j=0; j<editSection.children[i].children.length; j++){ let input=editSection.children[i].children[j]; let name=input.getAttribute('name'); // specify the type if(input.type=="number"){ editSection.children[i].children[j].value=parseInt(element.style[name]); } if(input.type=="color"){ editSection.children[i].children[j].value=rgb2hex(element.style[name]); } } } } /* source http://wowmotty.blogspot.fr/2009/06/convert-jquery-rgb-output-to-hex-color.html */ let hexDigits = new Array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); //Function to convert rgb color to hex format function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function hex(x) { return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; }
DariosDjimado/PowerJS
src/create.js
JavaScript
mit
3,685
import { ADD_ROUND, EDIT_ROUND, CLEAR_ROUNDS } from '../constants'; function addRound(rounds, action) { return [ ...rounds, { id: action.roundId, scores: action.scores, }, ]; } function editRound(rounds, action) { return rounds.map((round) => { if (round.id === action.roundId) { return { id: round.id, scores: Object.assign({}, action.scores), }; } return round; }); } function clearRounds() { return []; } const roundReducer = (state = {}, action) => { switch (action.type) { case ADD_ROUND: return addRound(state, action); case EDIT_ROUND: return editRound(state, action); case CLEAR_ROUNDS: return clearRounds(); default: return state; } }; export default roundReducer;
fedebertolini/uno-score-tracker
src/reducers/round.js
JavaScript
mit
883
import React from 'react'; import createReactClass from 'create-react-class'; import moment from 'moment'; import SearchStatus from './search_status'; import TimeSelector from './time_selector'; import styles from '../stylesheets/application.less'; export default createReactClass({ displayName: 'SearchBox', getInitialState() { const { requestParams } = this.props; let startTime, endTime, usingCustomDates; if (requestParams.start_time && requestParams.end_time) { startTime = this.parseParamTime(requestParams.start_time); endTime = this.parseParamTime(requestParams.end_time); // Give some padding if start and end are the same if (startTime === endTime) { startTime -= 15 * 60000; endTime += 5 * 60000; } // Round the times down and up to the nearest hour startTime -= startTime % 3600000; if (endTime % 3600000 !== 0) { endTime += 3600000 - endTime % 3600000; } usingCustomDates = true; } let podName = null; if (requestParams.pod_names) { podName = requestParams.pod_names.split(',')[0]; if (this.props.podNames.indexOf(podName) === -1) { podName = null; } } return { terms: requestParams.search_terms && requestParams.search_terms.split(',') || [], startTime: startTime, endTime: endTime, usingCustomDates: usingCustomDates, podName: podName || '', }; }, parseParamTime(timeString) { if (timeString.match(/^\d{4}(-\d\d){2}$/)) { return moment(timeString).valueOf(); } else { // Allow seconds or milliseconds to be passed in if (timeString.length < 13) { timeString += '000'; } return parseInt(timeString); } }, expensiveQueryWarning() { const weekInMilliseconds = 3600000 * 24 * 7; if (this.state.endTime - this.state.startTime >= weekInMilliseconds) { if (!confirm('Warning: You have chosen to search more than a week of logs. This could be an expensive query. Continue anyways?')) { return; } } }, handleSearch(e) { e.preventDefault(); this.expensiveQueryWarning(); const startTime = this.state.startTime; let endTime = this.state.endTime; const node = this.searchInput; const { value } = node; const search_terms = this.state.terms.slice(0); if (value !== '') { search_terms.push(value); node.value = ''; this.setState({ terms: search_terms }); } const userId = this.userIdInput.value; const accountId = this.accountIdInput.value; const requestUUID = this.requestUUIDInput.value; const ignoreAnalytics = this.ignoreAnalyticsInput.checked; const hosts = this.hostName.value !== '' ? [this.hostName.value] : []; const pods = this.state.podName ? [this.state.podName] : []; if (this.state.usingCustomDates && endTime % 3600000 === 0) { endTime -= 1; } return this.props.handleSearch( search_terms, startTime, endTime, userId, accountId, hosts, pods, requestUUID, ignoreAnalytics ); }, handleKeyDown(event) { if (event.keyCode === 13 && event.shiftKey) { event.stopPropagation(); event.preventDefault(); const terms = this.state.terms.slice(0); terms.push(event.target.value); this.setState({ terms }); return event.target.value = ''; } }, handleKeyUp(event) { if ( event.keyCode === 8 && event.target.selectionStart === 0 && event.shiftKey ) { const terms = this.state.terms.slice(0); terms.pop(); return this.setState({ terms }); } }, componentDidMount() { const node = this.searchInput; if (node) { const addEvent = node.addEventListener || node.attachEvent; addEvent('keypress', this.handleKeyDown, false); return addEvent('keyup', this.handleKeyUp, false); } }, componentWillUnmount() { const node = this.searchInput; if (node) { const removeEvent = node.removeEventListener || node.detachEvent; removeEvent('keypress', this.handleKeyPress); return removeEvent('keyup', this.handleKeyUp); } }, onRemoveTerm(term) { const node = this.searchInput; const terms = this.state.terms.slice(0); terms.splice(terms.indexOf(term), 1); node.value = term; node.focus(); return this.setState({ terms }); }, handleChangeDates(startTime, endTime) { this.setState({ startTime: startTime, endTime: endTime, }); }, handleChangePod(event) { this.setState({ podName: event.target.value }); }, render() { const { requestParams } = this.props; const userId = requestParams.user_id; const accountId = requestParams.account_id; const requestUUID = requestParams.request_uuid; const hostName = requestParams.host_names ? requestParams.host_names.split(',')[0] : null; return ( <form className={`navbar-form ${styles.searchBox} form-inline`} onSubmit={this.handleSearch} > <div className={styles.controls}> <div className={styles.searchInput}> {this.state.terms.map((term, i) => { return ( <span className={styles.term} key={`${term}-${i}`} onClick={this.onRemoveTerm.bind(this, term)} > {term} </span> ); })} <input ref={input => this.searchInput = input} tabIndex="1" placeholder="Term. Shift enter adds new term. Shift-Backspace or click to remove term." /> </div> </div> <div className={styles.controls}> <TimeSelector startTime={this.state.startTime} endTime={this.state.endTime} handleChangeDates={this.handleChangeDates} handleChangeDisplayUTC={this.props.handleChangeDisplayUTC} /> <input className={styles.padded} ref={input => this.userIdInput = input} placeholder="UserID" defaultValue={userId} /> <input className={styles.padded} ref={input => this.accountIdInput = input} placeholder="AccountID" defaultValue={accountId} /> <select value={this.state.podName} onChange={this.handleChangePod} className={styles.padded} placeholder="PodName" > <option value="">All pods</option> {this.props.podNames.map((name, index) => { return ( <option key={name} value={name}> {name} </option> ); })} </select> <input className={styles.padded} ref={input => this.hostName = input} placeholder="HostName" defaultValue={hostName} /> <input className={styles.padded} ref={input => this.requestUUIDInput = input} placeholder="Request UUID" defaultValue={requestUUID} /> <label className={styles.padded}> <input ref={input => this.ignoreAnalyticsInput = input} type="checkbox" defaultChecked className={styles.padded} /> Ignore analytics </label> </div> <div className={styles.controls}> <input type="submit" value="Search" className="btn btn-primary" /> <SearchStatus queryInProgress={this.props.queryInProgress} numReturnedResults={this.props.numReturnedResults} errorMessage={this.props.errorMessage} /> </div> </form> ); }, });
aha-app/bigquery-log-viewer
src/components/search_box.js
JavaScript
mit
8,008
function EntryDetailsController($scope, $routeParams, $location, unlockedState) { "use strict"; $scope.unlockedState = unlockedState; var entryId = $routeParams.entryId; $scope.entry = unlockedState.entries.filter(function(entry) { return entry.id == entryId; })[0]; $scope.attributes = $scope.entry.keys.map(function(key) { return { 'key': key, 'value': ($scope.entry[key] || "").replace(/\n/g, "<br>") }; }); for (var protectedKey in $scope.entry.protectedData) { $scope.attributes.push({ 'key': protectedKey, 'value': '', 'protected': true, 'protectedAttr': $scope.entry.protectedData[protectedKey] }); } $scope.exposeAttribute = function(attr) { attr.value = unlockedState.getDecryptedAttribute($scope.entry, attr.key); } $scope.goBack = function() { $location.path('/startup'); } }
perfectapi/CKP
popups/controllers/entryDetailsController.js
JavaScript
mit
838
export const fetchCoreDatasets = state => ({ ...state, coreDatasets: { ...state.coreDatasets, isFetching: true } }); export const receiveCoreDatasets = (state, { payload }) => ({ ...state, coreDatasets: { ...state.coreDatasets, isFetching: false, status: 'success', items: payload } }); export const failureCoreDatasets = (state, { payload }) => ({ ...state, coreDatasets: { ...state.coreDatasets, isFetching: false, status: 'error', message: payload } });
resource-watch/prep-app
app/scripts/pages/explore/core-datasets-list/core-datasets-list-reducers.js
JavaScript
mit
489
(function(){ "use strict"; var FancyAnalyser = function(canvas, source, context) { var analyser = new Webvs.WebAudioAnalyser({ context: context }); var webvs = new Webvs.Main({ canvas: canvas, analyser: analyser, showStat: false }); //webvs.loadPreset(preset); //webvs.start(); analyser.connectToNode(source); this.analyser = analyser; this.vis = webvs; }; window.FancyAnalyser = FancyAnalyser; })();
seutje/saxomochrome
js/fancyAnalyser.js
JavaScript
mit
479
version https://git-lfs.github.com/spec/v1 oid sha256:cbe789dbe4588d64d07e4ed389e3dd22cd9870af2db9066219d7afbf752e6f4f size 9269
yogeshsaroya/new-cdnjs
ajax/libs/openlayers/2.12/lib/OpenLayers.min.js
JavaScript
mit
129
version https://git-lfs.github.com/spec/v1 oid sha256:6bc05383b25c2ec01df032f011a0a366d53347dc9b5392030d2ee9962df70880 size 10994
yogeshsaroya/new-cdnjs
ajax/libs/es6-shim/0.5.3/es6-shim.js
JavaScript
mit
130
ScalaJS.is.scala_collection_mutable_HashEntry = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_mutable_HashEntry))) }); ScalaJS.as.scala_collection_mutable_HashEntry = (function(obj) { if ((ScalaJS.is.scala_collection_mutable_HashEntry(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.collection.mutable.HashEntry") } }); ScalaJS.isArrayOf.scala_collection_mutable_HashEntry = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_mutable_HashEntry))) }); ScalaJS.asArrayOf.scala_collection_mutable_HashEntry = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_collection_mutable_HashEntry(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.collection.mutable.HashEntry;", depth) } }); ScalaJS.data.scala_collection_mutable_HashEntry = new ScalaJS.ClassTypeData({ scala_collection_mutable_HashEntry: 0 }, true, "scala.collection.mutable.HashEntry", undefined, { scala_collection_mutable_HashEntry: 1, java_lang_Object: 1 }); //@ sourceMappingURL=HashEntry.js.map
ignaciocases/hermeneumatics
node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/collection/mutable/HashEntry.js
JavaScript
mit
1,249
'use strict'; var instrumentUtil = require('../instrumentUtil.js'); /** * Schedules a certain hard-coded envelope on a given AudioParam, starting at t0. */ function scheduleParameterEnvelope(t0, param) { param.cancelScheduledValues(t0); param.linearRampToValueAtTime(0, t0); param.linearRampToValueAtTime(1, t0 + 0.001); param.linearRampToValueAtTime(0.3, t0 + 0.101); param.linearRampToValueAtTime(0, t0 + 0.500); } /** * Backend constructor */ function Backend(ctx) { // create nodes this.ctx = ctx; this.oscNode = ctx.createOscillator(); this.oscNode.type = 'square'; this.oscNode.frequency.value = 100; this.oscNode.start(0); this.filterNode = ctx.createBiquadFilter(); this.filterNode.type = 'lowpass'; this.filterNode.frequency.value = 2000; this.filterNode.Q.value = 1; this.volumeEnvNode = ctx.createGain(); this.volumeEnvNode.gain.value = 0; // connect them up this.oscNode.connect(this.filterNode); this.filterNode.connect(this.volumeEnvNode); } Backend.prototype.processInput = function(data, clockTime) { // for now, no matter what input we get, we just play the same "note" var ctxCur = this.ctx.currentTime; var t; if (clockTime > ctxCur) { console.log('comp: OK'); t = clockTime; } else { console.log('comp: BEHIND'); t = ctxCur; } // var t = (clockTime > ctxCur) ? clockTime : ctxCur; scheduleParameterEnvelope(t, this.volumeEnvNode.gain); }; Backend.prototype.getOutputNode = function() { return this.volumeEnvNode; } module.exports = { createBackend: function(ctx) { return new Backend(ctx); }, createFrontend: function(container, sendData) { container.innerHTML = '<div id="note-button" style="height:100px;border:1px solid green;line-height:100px;text-align:center">Synth Note</div>'; instrumentUtil.addPressListener(container.querySelector('#note-button'), function(e) { e.preventDefault(); sendData(); }); } }
rsimmons/music-for-no-instrument
browser/instruments/synthnote.js
JavaScript
mit
1,958
/** * @desc * Service description * */ (function() { 'use strict'; angular.module('__name-pattern__', [ ]).factory('__namePattern__', __namePattern__); __namePattern__.$inject = []; function __namePattern__() { var service = { api: api }; function api() { } return service; } })();
icyheights/angular-templates
src/service.js
JavaScript
mit
311
module.exports.client_env = {houndify_clientID: 'Byf_ChsnhCMR9057BRRpKQ=='};
hello-marcus/hello-marcus
react-client/src/client_env.js
JavaScript
mit
77
// Controller var MyController = {}; // add new button event handler MyController.addNewButton = function(event){ MyLogger.log('MyController-addNewButton - start'); event = getEvent(event); // show the add form box and hide add new button MyView.hideAddNewButton(); MyLogger.log('MyController-addNewButton - end'); preventEvent(event); }; // add new Submit event handler MyController.addNewSubmitButton = function(event){ MyLogger.log('MyController-addNewSubmitButton - start'); event = getEvent(event); // get the form data var data = []; data['firstname'] = document.getElementById('firstname').value; data['lastname'] = document.getElementById('lastname').value; data['email'] = document.getElementById('email').value; data['other'] = document.getElementById('other').checked; data['other-txt'] = document.getElementById('other-txt').value; MyLogger.traceObject(data); // validate form data var validFlag = true; var invalidFields = MyModel.validate(data); MyLogger.log('MyController-addNewSubmitButton - 1'); MyLogger.traceObject(invalidFields); MyLogger.log('MyController-addNewSubmitButton - 2'); if (invalidFields.length) { // generate the view and show the message var message = new MyView.Message(invalidFields, 'error'); message.show(); validFlag = false; } else { // Hide messge var message = new MyView.Message({}, ''); message.hide(); } if(validFlag) { // if add mode if(document.getElementById('action').value=='add') { // add form data to model and return unique id of the record var id = MyModel.add(data); // add form data to display list to view MyView.addNewDatatoDisplayList(id,data); // hide the add form box and show add new button MyView.showAddNewButton(); } else { var id = document.getElementById('uid').value; MyModel.update(id,data); // add form data to display list to view MyView.updateDatatoDisplayList(id,data); MyView.resetSRNumber(); // hide the add form box and show add new button or detail box MyView.hideEditBox(); } } MyLogger.log('MyController-addNewSubmitButton - end'); preventEvent(event); }; // add new Cancel event handler MyController.addNewCancelButton = function(event){ MyLogger.log('MyController-addNewCancelButton - start'); event = getEvent(event); // hide the add form box and show add new button MyView.showAddNewButton(); MyLogger.log('MyController-addNewCancelButton - end'); preventEvent(event); }; // detail, edit and delete event handler MyController.detailEditDeleteButtons = function(event){ MyLogger.log('MyController-detailEditDeleteButtons - start'); event = getEvent(event); MyLogger.log('MyController-detailEditDeleteButtons - event.target-'+event.target); var target = (event.target) ? event.target : event.srcElement; MyLogger.log('MyController-detailEditDeleteButtons - target.type-'+target.type); if(target.type != undefined && target.type=='button') { MyLogger.log('MyController-detailEditDeleteButtons - target.value-'+target.value); if(target.value!='') { // get the id of selected target var id = target.parentNode.parentNode.parentNode.id; MyLogger.log('MyController-detailEditDeleteButtons - id-'+id); switch(target.value) { case 'Detail': var data = MyModel.read(id); MyLogger.traceObject(data); // show detail box MyView.showDetailBox(id,data); break; case 'Edit': var data = MyModel.read(id); MyLogger.traceObject(data); // open form box in edit mode MyView.showEditBox(id,data); break; case 'Delete': var dflag = MyModel.remove(id); MyLogger.log('MyController-detailEditDeleteButtons - dflag-'+dflag); if(dflag) { // remove this form display list MyView.removeFromDisplayList(event); // reset the sr number MyView.resetSRNumber(event); MyView.showAddNewButton(); } break; default: MyLogger.log('MyController-detailEditDeleteButtons - default'); } } } MyLogger.log('MyController-detailEditDeleteButtons - end'); preventEvent(event); }; // hide detail event handler MyController.backDetailButton = function(event){ MyLogger.log('MyController-backDetailButton - start'); event = getEvent(event); // hide detail box MyView.hideDetailBox(); MyLogger.log('MyController-backDetailButton - end'); preventEvent(event); };
maheshvnit/mvc-crud
controller.js
JavaScript
mit
4,488
'use strict'; var _ = require('lodash'); var Q = require('q'); var Page = require('../../../../../../base/Page'); var deserialize = require('../../../../../../base/deserialize'); var serialize = require('../../../../../../base/serialize'); var values = require('../../../../../../base/values'); var AllTimePage; var AllTimeList; var AllTimeInstance; var AllTimeContext; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.UsageContext.RecordContext.AllTimePage * @augments Page * @description Initialize the AllTimePage * * @param {Twilio.Api.V2010} version - Version of the resource * @param {object} response - Response from the API * @param {object} solution - Path solution * * @returns AllTimePage */ /* jshint ignore:end */ function AllTimePage(version, response, solution) { // Path Solution this._solution = solution; Page.prototype.constructor.call(this, version, response, this._solution); } _.extend(AllTimePage.prototype, Page.prototype); AllTimePage.prototype.constructor = AllTimePage; /* jshint ignore:start */ /** * Build an instance of AllTimeInstance * * @function getInstance * @memberof Twilio.Api.V2010.AccountContext.UsageContext.RecordContext.AllTimePage * @instance * * @param {object} payload - Payload response from the API * * @returns AllTimeInstance */ /* jshint ignore:end */ AllTimePage.prototype.getInstance = function getInstance(payload) { return new AllTimeInstance( this._version, payload, this._solution.accountSid ); }; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.UsageContext.RecordContext.AllTimeList * @description Initialize the AllTimeList * * @param {Twilio.Api.V2010} version - Version of the resource * @param {string} accountSid - * A 34 character string that uniquely identifies this resource. */ /* jshint ignore:end */ function AllTimeList(version, accountSid) { /* jshint ignore:start */ /** * @function allTime * @memberof Twilio.Api.V2010.AccountContext.UsageContext.RecordContext * @instance * * @param {string} sid - sid of instance * * @returns {Twilio.Api.V2010.AccountContext.UsageContext.RecordContext.AllTimeContext} */ /* jshint ignore:end */ function AllTimeListInstance(sid) { return AllTimeListInstance.get(sid); } AllTimeListInstance._version = version; // Path Solution AllTimeListInstance._solution = { accountSid: accountSid }; AllTimeListInstance._uri = _.template( '/Accounts/<%= accountSid %>/Usage/Records/AllTime.json' // jshint ignore:line )(AllTimeListInstance._solution); /* jshint ignore:start */ /** * Streams AllTimeInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory efficient. * * If a function is passed as the first argument, it will be used as the callback function. * * @function each * @memberof Twilio.Api.V2010.AccountContext.UsageContext.RecordContext.AllTimeList * @instance * * @param {object|function} opts - ... * @param {all_time.category} [opts.category] - The category * @param {Date} [opts.startDateBefore] - The start_date * @param {Date} [opts.startDate] - The start_date * @param {Date} [opts.startDateAfter] - The start_date * @param {Date} [opts.endDateBefore] - The end_date * @param {Date} [opts.endDate] - The end_date * @param {Date} [opts.endDateAfter] - The end_date * @param {number} [opts.limit] - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize=50] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @param {Function} [opts.callback] - * Function to process each record. If this and a positional * callback are passed, this one will be used * @param {Function} [opts.done] - * Function to be called upon completion of streaming * @param {Function} [callback] - Function to process each record */ /* jshint ignore:end */ AllTimeListInstance.each = function each(opts, callback) { opts = opts || {}; if (_.isFunction(opts)) { opts = { callback: opts }; } else if (_.isFunction(callback) && !_.isFunction(opts.callback)) { opts.callback = callback; } if (_.isUndefined(opts.callback)) { throw new Error('Callback function must be provided'); } var done = false; var currentPage = 1; var limits = this._version.readLimits({ limit: opts.limit, pageSize: opts.pageSize }); function onComplete(error) { done = true; if (_.isFunction(opts.done)) { opts.done(error); } } function fetchNextPage(fn) { var promise = fn(); if (_.isUndefined(promise)) { onComplete(); return; } promise.then(function(page) { _.each(page.instances, function(instance) { if (done) { return false; } opts.callback(instance, onComplete); }); if ((limits.pageLimit && limits.pageLimit <= currentPage)) { onComplete(); } else if (!done) { currentPage++; fetchNextPage(_.bind(page.nextPage, page)); } }); promise.catch(onComplete); } fetchNextPage(_.bind(this.page, this, opts)); }; /* jshint ignore:start */ /** * @description Lists AllTimeInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback function. * * @function list * @memberof Twilio.Api.V2010.AccountContext.UsageContext.RecordContext.AllTimeList * @instance * * @param {object|function} opts - ... * @param {all_time.category} [opts.category] - The category * @param {Date} [opts.startDateBefore] - The start_date * @param {Date} [opts.startDate] - The start_date * @param {Date} [opts.startDateAfter] - The start_date * @param {Date} [opts.endDateBefore] - The end_date * @param {Date} [opts.endDate] - The end_date * @param {Date} [opts.endDateAfter] - The end_date * @param {number} [opts.limit] - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ AllTimeListInstance.list = function list(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var allResources = []; opts.callback = function(resource, done) { allResources.push(resource); if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) { done(); } }; opts.done = function(error) { if (_.isUndefined(error)) { deferred.resolve(allResources); } else { deferred.reject(error); } }; if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } this.each(opts); return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single page of AllTimeInstance records from the API. * Request is executed immediately * * If a function is passed as the first argument, it will be used as the callback function. * * @function page * @memberof Twilio.Api.V2010.AccountContext.UsageContext.RecordContext.AllTimeList * @instance * * @param {object|function} opts - ... * @param {all_time.category} [opts.category] - The category * @param {Date} [opts.startDateBefore] - The start_date * @param {Date} [opts.startDate] - The start_date * @param {Date} [opts.startDateAfter] - The start_date * @param {Date} [opts.endDateBefore] - The end_date * @param {Date} [opts.endDate] - The end_date * @param {Date} [opts.endDateAfter] - The end_date * @param {string} [opts.pageToken] - PageToken provided by the API * @param {number} [opts.pageNumber] - * Page Number, this value is simply for client state * @param {number} [opts.pageSize] - Number of records to return, defaults to 50 * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ AllTimeListInstance.page = function page(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'Category': opts.category, 'StartDate<': serialize.iso8601Date(opts.startDateBefore), 'StartDate': serialize.iso8601Date(opts.startDate), 'StartDate>': serialize.iso8601Date(opts.startDateAfter), 'EndDate<': serialize.iso8601Date(opts.endDateBefore), 'EndDate': serialize.iso8601Date(opts.endDate), 'EndDate>': serialize.iso8601Date(opts.endDateAfter), 'PageToken': opts.pageToken, 'Page': opts.pageNumber, 'PageSize': opts.pageSize }); var promise = this._version.page({ uri: this._uri, method: 'GET', params: data }); promise = promise.then(function(payload) { deferred.resolve(new AllTimePage( this._version, payload, this._solution )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; return AllTimeListInstance; } /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.UsageContext.RecordContext.AllTimeInstance * @description Initialize the AllTimeContext * * @property {string} accountSid - The account_sid * @property {string} apiVersion - The api_version * @property {all_time.category} category - The category * @property {string} count - The count * @property {string} countUnit - The count_unit * @property {string} description - The description * @property {Date} endDate - The end_date * @property {number} price - The price * @property {string} priceUnit - The price_unit * @property {Date} startDate - The start_date * @property {string} subresourceUris - The subresource_uris * @property {string} uri - The uri * @property {string} usage - The usage * @property {string} usageUnit - The usage_unit * * @param {Twilio.Api.V2010} version - Version of the resource * @param {object} payload - The instance payload */ /* jshint ignore:end */ function AllTimeInstance(version, payload, accountSid) { this._version = version; // Marshaled Properties this.accountSid = payload.account_sid; // jshint ignore:line this.apiVersion = payload.api_version; // jshint ignore:line this.category = payload.category; // jshint ignore:line this.count = payload.count; // jshint ignore:line this.countUnit = payload.count_unit; // jshint ignore:line this.description = payload.description; // jshint ignore:line this.endDate = deserialize.iso8601DateTime(payload.end_date); // jshint ignore:line this.price = deserialize.decimal(payload.price); // jshint ignore:line this.priceUnit = payload.price_unit; // jshint ignore:line this.startDate = deserialize.iso8601DateTime(payload.start_date); // jshint ignore:line this.subresourceUris = payload.subresource_uris; // jshint ignore:line this.uri = payload.uri; // jshint ignore:line this.usage = payload.usage; // jshint ignore:line this.usageUnit = payload.usage_unit; // jshint ignore:line // Context this._context = undefined; this._solution = { accountSid: accountSid, }; } module.exports = { AllTimePage: AllTimePage, AllTimeList: AllTimeList, AllTimeInstance: AllTimeInstance, AllTimeContext: AllTimeContext };
theryankennedy/twilio-contact-center
twilio-node/lib/rest/api/v2010/account/usage/record/allTime.js
JavaScript
mit
12,700
/** * @author maurobuselli@gmail.com */ (function () { 'use strict'; angular.module('AngularPanelsApp.pages.dashboard') .directive('blurFeed', blurFeed); /** @ngInject */ function blurFeed() { return { restrict: 'E', controller: 'BlurFeedCtrl', templateUrl: 'app/pages/dashboard/blurFeed/blurFeed.html' }; } })();
mauroBus/angular-panels-app
src/app/pages/dashboard/blurFeed/blurFeed.directive.js
JavaScript
mit
360
version https://git-lfs.github.com/spec/v1 oid sha256:916bf99ecc2fa4718710c675263d392edf1fe350056f36c509005f08ee0d4b6f size 3879
yogeshsaroya/new-cdnjs
ajax/libs/angular.js/1.4.0-beta.6/i18n/angular-locale_uk-ua.js
JavaScript
mit
129
var cryptoLib = require('../lib/crypto.js'); var ByteBuffer = require('bytebuffer'); var bignum = require('browserify-bignum'); var crypto = require('crypto'); var dappTransactionsLib = require('../lib/dapptransactions.js'); function getBytes(block, skipSignature) { var size = 8 + 4 + 4 + 4 + 32 + 32 + 8 + 4 + 4 + 64; var bb = new ByteBuffer(size, true); if (block.prevBlockId) { var pb = bignum(block.prevBlockId).toBuffer({size: '8'}); for (var i = 0; i < 8; i++) { bb.writeByte(pb[i]); } } else { for (var i = 0; i < 8; i++) { bb.writeByte(0); } } bb.writeInt(block.height); bb.writeInt(block.timestamp); bb.writeInt(block.payloadLength); var ph = new Buffer(block.payloadHash, 'hex'); for (var i = 0; i < ph.length; i++) { bb.writeByte(ph[i]); } var pb = new Buffer(block.delegate, 'hex'); for (var i = 0; i < pb.length; i++) { bb.writeByte(pb[i]); } var pb = bignum(block.pointId).toBuffer({size: '8'}); for (var i = 0; i < 8; i++) { bb.writeByte(pb[i]); } bb.writeInt(block.pointHeight); bb.writeInt(block.count); if (!skipSignature && block.signature) { var pb = new Buffer(block.signature, 'hex'); for (var i = 0; i < pb.length; i++) { bb.writeByte(pb[i]); } } bb.flip(); var b = bb.toBuffer(); return b; } module.exports = { new: function (genesisAccount, genesisBlock, publicKeys) { var delegates = publicKeys.map(function (key) { return "+" + key; }) var delegatesTransaction = { type: 4, amount: 0, fee: 0, timestamp: 0, recipientId: null, senderId: genesisAccount.address, senderPublicKey: genesisAccount.keypair.publicKey, asset: { delegates: { list: delegates } } } var block = { delegate: genesisAccount.keypair.publicKey, height: 1, pointId: genesisBlock.id, pointHeight: 1, transactions: [], timestamp: 0 } block.transactions.push(delegatesTransaction); block.count = block.transactions.length; bytes = dappTransactionsLib.getTransactionBytes(delegatesTransaction); delegatesTransaction.signature = cryptoLib.sign(genesisAccount.keypair, bytes); bytes = dappTransactionsLib.getTransactionBytes(delegatesTransaction); delegatesTransaction.id = cryptoLib.getId(bytes); block.payloadLength = bytes.length; block.payloadHash = crypto.createHash('sha256').update(bytes).digest().toString('hex'); var bytes = getBytes(block); block.signature = cryptoLib.sign(genesisAccount.keypair, bytes); bytes = getBytes(block); block.id = cryptoLib.getId(bytes); return block; } }
LiskHQ/lisk-cli
helpers/dapp.js
JavaScript
mit
2,556
import { saveContent } from 'redux/note' import { setEncryptedContent, setSavingState } from 'redux/vault' import { encrypt } from '../../../../services/encryption' import { saveVault } from '../../../../services/google-api' export const saveNote = (event, passphrase, content) => (dispatch) => { // dispatch(setLoading(true)) dispatch(setSavingState('saving')) encrypt(passphrase, content).then((ciphertext) => { dispatch(setEncryptedContent(ciphertext)) return saveVault({ data: ciphertext }) }).then((e) => { // console.log(e) dispatch(saveContent()) dispatch(setSavingState('just-saved')) setTimeout(() => { dispatch(setSavingState('saved')) }, 5000) // dispatch(setLoading(false)) }).catch(() => { console.log('ko') }) }
getvault/getvault.github.io
src/components/Wizard/WizardEditor/VaultBar/vaultbar.actions.js
JavaScript
mit
781
var searchData= [ ['allchnls',['ALLCHNLS',['../csoundCore_8h.html#a83fc6b1f004833fab4c9555e30fd3bf0',1,'csoundCore.h']]], ['amplmsg',['AMPLMSG',['../csoundCore_8h.html#a2d132168442a7a7c6fbaa4a0c1e5d49a',1,'csoundCore.h']]], ['arg_5fconstant',['ARG_CONSTANT',['../csoundCore_8h.html#aeaee15c78c0bd235027a59215b24fda5',1,'csoundCore.h']]], ['arg_5fglobal',['ARG_GLOBAL',['../csoundCore_8h.html#a0cf32a40cfa1106a3ed856b0a93aded7',1,'csoundCore.h']]], ['arg_5flabel',['ARG_LABEL',['../csoundCore_8h.html#aed496b68ae5a79954ea613c8567bbc19',1,'csoundCore.h']]], ['arg_5flocal',['ARG_LOCAL',['../csoundCore_8h.html#a5f73cd7e0117fbdd551ca4b1a1e9e700',1,'csoundCore.h']]], ['arg_5fpfield',['ARG_PFIELD',['../csoundCore_8h.html#af7d702da79b98d4a14bf83acc5711994',1,'csoundCore.h']]], ['arg_5fstring',['ARG_STRING',['../csoundCore_8h.html#a4de5ed5fcf59a18b24bc9f6449cc9356',1,'csoundCore.h']]], ['async_5fglobal',['ASYNC_GLOBAL',['../csoundCore_8h.html#aeb94c8d411c6e7dc2351b07e7278104f',1,'csoundCore.h']]], ['async_5flocal',['ASYNC_LOCAL',['../csoundCore_8h.html#ac6a0a441704c2196eb163b30dfd13e9a',1,'csoundCore.h']]] ];
ketchupok/csound.github.io
docs/api/search/defines_1.js
JavaScript
mit
1,132
// ================================================================= // get the packages we need ======================================== // ================================================================= var express = require('express'); var app = express(); var cors = require('cors'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var morgan = require('morgan'); var config = require('./config'); // get our config file // ================================================================= // configuration =================================================== // ================================================================= var port = process.env.PORT || 8080; // port where app will be runing mongoose.connect(config.database); // connect to database app.set('superSecret', config.secret); // secret variable // use body parser so we can get info from POST and/or URL parameters app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // seting up app to have cors app.use(cors()); // use morgan to log requests to the console app.use(morgan('dev')); // ================================================================= // routes ========================================================== // ================================================================= // basic route (http://localhost:8080) app.get('/', function(req, res) { res.send('Hello! The API is at http://localhost:' + port + '/api'); }); // --------------------------------------------------------- // get an instance of the router for api routes // --------------------------------------------------------- var apiRoutes = express.Router(); // loading default routes require('./app/routes/default.js')(app, apiRoutes); app.use('/api', apiRoutes); // Making prettier unauthorized method app.use(function(err, req, res, next){ if (err.constructor.name === 'UnauthorizedError') { res.status(401).send('Unauthorized'); } }); // Listening on port app.listen(port, function () { console.log('listening on http://localhost:' + port); });
Eisenheim38/expressjs-auth-token-example
server.js
JavaScript
mit
2,120
var expect = require('expect.js'); var Backend = require('../lib/backend'); var MilestoneDB = require('../lib/milestone-db'); var NoOpMilestoneDB = require('../lib/milestone-db/no-op'); var Snapshot = require('../lib/snapshot'); var util = require('./util'); describe('Base class', function () { var db; beforeEach(function () { db = new MilestoneDB(); }); it('calls back with an error when trying to get a snapshot', function (done) { db.getMilestoneSnapshot('books', '123', 1, function (error) { expect(error.code).to.be(5019); done(); }); }); it('emits an error when trying to get a snapshot', function (done) { db.on('error', function (error) { expect(error.code).to.be(5019); done(); }); db.getMilestoneSnapshot('books', '123', 1); }); it('calls back with an error when trying to save a snapshot', function (done) { db.saveMilestoneSnapshot('books', {}, function (error) { expect(error.code).to.be(5020); done(); }); }); it('emits an error when trying to save a snapshot', function (done) { db.on('error', function (error) { expect(error.code).to.be(5020); done(); }); db.saveMilestoneSnapshot('books', {}); }); it('calls back with an error when trying to get a snapshot before a time', function (done) { db.getMilestoneSnapshotAtOrBeforeTime('books', '123', 1000, function (error) { expect(error.code).to.be(5021); done(); }); }); it('calls back with an error when trying to get a snapshot after a time', function (done) { db.getMilestoneSnapshotAtOrAfterTime('books', '123', 1000, function (error) { expect(error.code).to.be(5022); done(); }); }); }); describe('NoOpMilestoneDB', function () { var db; beforeEach(function () { db = new NoOpMilestoneDB(); }); it('does not error when trying to save and fetch a snapshot', function (done) { var snapshot = new Snapshot( 'catcher-in-the-rye', 2, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye' }, null ); util.callInSeries([ function (next) { db.saveMilestoneSnapshot('books', snapshot, next); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', null, next); }, function (snapshot, next) { expect(snapshot).to.be(undefined); next(); }, done ]); }); it('emits an event when saving without a callback', function (done) { db.on('save', function () { done(); }); db.saveMilestoneSnapshot('books', undefined); }); }); module.exports = function (options) { var create = options.create; describe('Milestone Database', function () { var db; var backend; beforeEach(function (done) { create(function (error, createdDb) { if (error) return done(error); db = createdDb; backend = new Backend({ milestoneDb: db }); done(); }); }); afterEach(function (done) { db.close(done); }); it('can call close() without a callback', function (done) { create(function (error, db) { if (error) return done(error); db.close(); done(); }); }); it('stores and fetches a milestone snapshot', function (done) { var snapshot = new Snapshot( 'catcher-in-the-rye', 2, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye' }, null ); util.callInSeries([ function (next) { db.saveMilestoneSnapshot('books', snapshot, next); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 2, next); }, function (retrievedSnapshot, next) { expect(retrievedSnapshot).to.eql(snapshot); next(); }, done ]); }); it('fetches the most recent snapshot before the requested version', function (done) { var snapshot1 = new Snapshot( 'catcher-in-the-rye', 1, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye' }, null ); var snapshot2 = new Snapshot( 'catcher-in-the-rye', 2, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye', author: 'J.D. Salinger' }, null ); var snapshot10 = new Snapshot( 'catcher-in-the-rye', 10, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye', author: 'J.D. Salinger', publicationDate: '1951-07-16' }, null ); util.callInSeries([ function (next) { db.saveMilestoneSnapshot('books', snapshot1, next); }, function (next) { db.saveMilestoneSnapshot('books', snapshot2, next); }, function (next) { db.saveMilestoneSnapshot('books', snapshot10, next); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 4, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot2); next(); }, done ]); }); it('fetches the most recent snapshot even if they are inserted in the wrong order', function (done) { var snapshot1 = new Snapshot( 'catcher-in-the-rye', 1, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye' }, null ); var snapshot2 = new Snapshot( 'catcher-in-the-rye', 2, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye', author: 'J.D. Salinger' }, null ); util.callInSeries([ function (next) { db.saveMilestoneSnapshot('books', snapshot2, next); }, function (next) { db.saveMilestoneSnapshot('books', snapshot1, next); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 4, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot2); next(); }, done ]); }); it('fetches the most recent snapshot when the version is null', function (done) { var snapshot1 = new Snapshot( 'catcher-in-the-rye', 1, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye' }, null ); var snapshot2 = new Snapshot( 'catcher-in-the-rye', 2, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye', author: 'J.D. Salinger' }, null ); util.callInSeries([ function (next) { db.saveMilestoneSnapshot('books', snapshot1, next); }, function (next) { db.saveMilestoneSnapshot('books', snapshot2, next); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', null, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot2); next(); }, done ]); }); it('errors when fetching an undefined version', function (done) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', undefined, function (error) { expect(error).to.be.ok(); done(); }); }); it('errors when fetching version -1', function (done) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', -1, function (error) { expect(error).to.be.ok(); done(); }); }); it('errors when fetching version "foo"', function (done) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 'foo', function (error) { expect(error).to.be.ok(); done(); }); }); it('errors when fetching a null collection', function (done) { db.getMilestoneSnapshot(null, 'catcher-in-the-rye', 1, function (error) { expect(error).to.be.ok(); done(); }); }); it('errors when fetching a null ID', function (done) { db.getMilestoneSnapshot('books', null, 1, function (error) { expect(error).to.be.ok(); done(); }); }); it('errors when saving a null collection', function (done) { var snapshot = new Snapshot( 'catcher-in-the-rye', 1, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye' }, null ); db.saveMilestoneSnapshot(null, snapshot, function (error) { expect(error).to.be.ok(); done(); }); }); it('returns undefined if no snapshot exists', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 1, next); }, function (snapshot, next) { expect(snapshot).to.be(undefined); next(); }, done ]); }); it('does not store a milestone snapshot on commit', function (done) { util.callInSeries([ function (next) { var doc = backend.connect().get('books', 'catcher-in-the-rye'); doc.create({ title: 'Catcher in the Rye' }, next); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', null, next); }, function (snapshot, next) { expect(snapshot).to.be(undefined); next(); }, done ]); }); it('can save without a callback', function (done) { var snapshot = new Snapshot( 'catcher-in-the-rye', 1, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye' }, null ); db.on('save', function (collection, snapshot) { expect(collection).to.be('books'); expect(snapshot).to.eql(snapshot); done(); }); db.saveMilestoneSnapshot('books', snapshot); }); it('errors when the snapshot is undefined', function (done) { db.saveMilestoneSnapshot('books', undefined, function (error) { expect(error).to.be.ok(); done(); }); }); describe('snapshots with timestamps', function () { var snapshot1 = new Snapshot( 'catcher-in-the-rye', 1, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye' }, { ctime: 1000, mtime: 1000 } ); var snapshot2 = new Snapshot( 'catcher-in-the-rye', 2, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye', author: 'JD Salinger' }, { ctime: 1000, mtime: 2000 } ); var snapshot3 = new Snapshot( 'catcher-in-the-rye', 3, 'http://sharejs.org/types/JSONv0', { title: 'Catcher in the Rye', author: 'J.D. Salinger' }, { ctime: 1000, mtime: 3000 } ); beforeEach(function (done) { util.callInSeries([ function (next) { db.saveMilestoneSnapshot('books', snapshot1, next); }, function (next) { db.saveMilestoneSnapshot('books', snapshot2, next); }, function (next) { db.saveMilestoneSnapshot('books', snapshot3, next); }, done ]); }); describe('fetching a snapshot before or at a time', function () { it('fetches a snapshot before a given time', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshotAtOrBeforeTime('books', 'catcher-in-the-rye', 2500, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot2); next(); }, done ]); }); it('fetches a snapshot at an exact time', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshotAtOrBeforeTime('books', 'catcher-in-the-rye', 2000, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot2); next(); }, done ]); }); it('fetches the first snapshot for a null timestamp', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshotAtOrBeforeTime('books', 'catcher-in-the-rye', null, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot1); next(); }, done ]); }); it('returns an error for a string timestamp', function (done) { db.getMilestoneSnapshotAtOrBeforeTime('books', 'catcher-in-the-rye', 'not-a-timestamp', function (error) { expect(error).to.be.ok(); done(); }); }); it('returns an error for a negative timestamp', function (done) { db.getMilestoneSnapshotAtOrBeforeTime('books', 'catcher-in-the-rye', -1, function (error) { expect(error).to.be.ok(); done(); }); }); it('returns undefined if there are no snapshots before a time', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshotAtOrBeforeTime('books', 'catcher-in-the-rye', 0, next); }, function (snapshot, next) { expect(snapshot).to.be(undefined); next(); }, done ]); }); it('errors if no collection is provided', function (done) { db.getMilestoneSnapshotAtOrBeforeTime(undefined, 'catcher-in-the-rye', 0, function (error) { expect(error).to.be.ok(); done(); }); }); it('errors if no ID is provided', function (done) { db.getMilestoneSnapshotAtOrBeforeTime('books', undefined, 0, function (error) { expect(error).to.be.ok(); done(); }); }); }); describe('fetching a snapshot after or at a time', function () { it('fetches a snapshot after a given time', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshotAtOrAfterTime('books', 'catcher-in-the-rye', 2500, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot3); next(); }, done ]); }); it('fetches a snapshot at an exact time', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshotAtOrAfterTime('books', 'catcher-in-the-rye', 2000, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot2); next(); }, done ]); }); it('fetches the last snapshot for a null timestamp', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshotAtOrAfterTime('books', 'catcher-in-the-rye', null, next); }, function (snapshot, next) { expect(snapshot).to.eql(snapshot3); next(); }, done ]); }); it('returns an error for a string timestamp', function (done) { db.getMilestoneSnapshotAtOrAfterTime('books', 'catcher-in-the-rye', 'not-a-timestamp', function (error) { expect(error).to.be.ok(); done(); }); }); it('returns an error for a negative timestamp', function (done) { db.getMilestoneSnapshotAtOrAfterTime('books', 'catcher-in-the-rye', -1, function (error) { expect(error).to.be.ok(); done(); }); }); it('returns undefined if there are no snapshots after a time', function (done) { util.callInSeries([ function (next) { db.getMilestoneSnapshotAtOrAfterTime('books', 'catcher-in-the-rye', 4000, next); }, function (snapshot, next) { expect(snapshot).to.be(undefined); next(); }, done ]); }); it('errors if no collection is provided', function (done) { db.getMilestoneSnapshotAtOrAfterTime(undefined, 'catcher-in-the-rye', 0, function (error) { expect(error).to.be.ok(); done(); }); }); it('errors if no ID is provided', function (done) { db.getMilestoneSnapshotAtOrAfterTime('books', undefined, 0, function (error) { expect(error).to.be.ok(); done(); }); }); }); }); describe('milestones enabled for every version', function () { beforeEach(function (done) { var options = { interval: 1 }; create(options, function (error, createdDb) { if (error) return done(error); db = createdDb; backend = new Backend({ milestoneDb: db }); done(); }); }); it('stores a milestone snapshot on commit', function (done) { db.on('save', function (collection, snapshot) { expect(collection).to.be('books'); expect(snapshot.data).to.eql({ title: 'Catcher in the Rye' }); done(); }); var doc = backend.connect().get('books', 'catcher-in-the-rye'); doc.create({ title: 'Catcher in the Rye' }); }); }); describe('milestones enabled for every other version', function () { beforeEach(function (done) { var options = { interval: 2 }; create(options, function (error, createdDb) { if (error) return done(error); db = createdDb; backend = new Backend({ milestoneDb: db }); done(); }); }); it('only stores even-numbered versions', function (done) { db.on('save', function (collection, snapshot) { if (snapshot.v !== 4) return; util.callInSeries([ function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 1, next); }, function (snapshot, next) { expect(snapshot).to.be(undefined); next(); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 2, next); }, function (snapshot, next) { expect(snapshot.v).to.be(2); next(); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 3, next); }, function (snapshot, next) { expect(snapshot.v).to.be(2); next(); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 4, next); }, function (snapshot, next) { expect(snapshot.v).to.be(4); next(); }, done ]); }); var doc = backend.connect().get('books', 'catcher-in-the-rye'); util.callInSeries([ function (next) { doc.create({ title: 'Catcher in the Rye' }, next); }, function (next) { doc.submitOp({ p: ['author'], oi: 'J.F.Salinger' }, next); }, function (next) { doc.submitOp({ p: ['author'], od: 'J.F.Salinger', oi: 'J.D.Salinger' }, next); }, function (next) { doc.submitOp({ p: ['author'], od: 'J.D.Salinger', oi: 'J.D. Salinger' }, next); } ]); }); it('can have the saving logic overridden in middleware', function (done) { backend.use('commit', function (request, callback) { request.saveMilestoneSnapshot = request.snapshot.v >= 3; callback(); }); db.on('save', function (collection, snapshot) { if (snapshot.v !== 4) return; util.callInSeries([ function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 1, next); }, function (snapshot, next) { expect(snapshot).to.be(undefined); next(); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 2, next); }, function (snapshot, next) { expect(snapshot).to.be(undefined); next(); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 3, next); }, function (snapshot, next) { expect(snapshot.v).to.be(3); next(); }, function (next) { db.getMilestoneSnapshot('books', 'catcher-in-the-rye', 4, next); }, function (snapshot, next) { expect(snapshot.v).to.be(4); next(); }, done ]); }); var doc = backend.connect().get('books', 'catcher-in-the-rye'); util.callInSeries([ function (next) { doc.create({ title: 'Catcher in the Rye' }, next); }, function (next) { doc.submitOp({ p: ['author'], oi: 'J.F.Salinger' }, next); }, function (next) { doc.submitOp({ p: ['author'], od: 'J.F.Salinger', oi: 'J.D.Salinger' }, next); }, function (next) { doc.submitOp({ p: ['author'], od: 'J.D.Salinger', oi: 'J.D. Salinger' }, next); } ]); }); }); }); };
share/livedb
test/milestone-db.js
JavaScript
mit
22,014
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var http_1 = require("@angular/http"); require('rxjs/add/operator/toPromise'); var LojaService = (function () { function LojaService(http) { this.http = http; } LojaService.prototype.getLoja = function () { return this.http.get("/loja") .toPromise() .then(function (response) { return response.json(); }) .catch(function (response) { return response.json(); }); }; LojaService.prototype.getAreas = function () { return this.http.get("/loja/areas") .toPromise() .then(function (response) { return response.json(); }) .catch(); }; LojaService.prototype.getAreasRelacionadas = function () { return this.http.get("/loja/areas-relacionadas") .toPromise() .then(function (response) { return response.json(); }) .catch(); }; LojaService.prototype.salvarLoja = function (loja) { return this.http.post("/loja/salvar", loja) .toPromise() .then(function (response) { return response.json(); }); }; LojaService.prototype.handleError = function (error) { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); }; LojaService.prototype.getCep = function (cep) { return this.http.get("/cep/" + cep) .toPromise() .then(function (response) { return response.json(); }) .catch(function (response) { return response.json(); }); }; LojaService = __decorate([ core_1.Injectable(), __metadata('design:paramtypes', [http_1.Http]) ], LojaService); return LojaService; }()); exports.LojaService = LojaService; //# sourceMappingURL=loja.service.js.map
fabioresende/BrasilConf-Front
app/dashboard/loja/loja.service.js
JavaScript
mit
2,605
var Type = require("@kaoscript/runtime").Type; module.exports = function() { function blend(x, y, percentage) { if(arguments.length < 3) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 3)"); } if(x === void 0 || x === null) { throw new TypeError("'x' is not nullable"); } else if(!Type.isNumber(x)) { throw new TypeError("'x' is not of type 'Number'"); } if(y === void 0 || y === null) { throw new TypeError("'y' is not nullable"); } else if(!Type.isNumber(y)) { throw new TypeError("'y' is not of type 'Number'"); } if(percentage === void 0 || percentage === null) { throw new TypeError("'percentage' is not nullable"); } else if(!Type.isNumber(percentage)) { throw new TypeError("'percentage' is not of type 'Number'"); } return ((1 - percentage) * x) + (percentage * y); } };
kaoscript/kaoscript
test/fixtures/compile/xample/xample.blend.decl.js
JavaScript
mit
864
/* jshint node: true */ 'use strict'; module.exports = function(grunt) { grunt.initConfig({ jscs: { main: ['Gruntfile.js', '*.js'] }, jshint: { options: { jshintrc: true }, files: { src: ['Gruntfile.js', '*.js'] } } }); grunt.loadNpmTasks('grunt-jscs'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.registerTask('default', ['lint']); grunt.registerTask('lint', ['jscs', 'jshint']); };
bsdavidson/LD32
Gruntfile.js
JavaScript
mit
464
define("ace/snippets/gherkin",["require","exports","module"],function(e,i,n){"use strict";i.snippetText=undefined,i.scope="gherkin"}); //# sourceMappingURL=node_modules/ace-builds/src-min/snippets/gherkin.js.map
sdonaghey03/hia-forum
build/public/src/modules/ace/snippets/gherkin.js
JavaScript
mit
211
/** * config/common.js */ module.exports = { service: { name: 'webpack-in-5min-vuejs', page: 'default', region: 'ap-northeast-1' }, api: { headers: { 'X-Harry-Potter-Identity': 'default', 'X-Harry-Potter-Secured-Item': 'nimbus-2000', 'X-Harry-Potter-Secured-Key': 'expecto-patronum' } } };
minagawah/webpack-in-5min-vuejs
src/config/common.js
JavaScript
mit
386
jQuery.fn.isOnScreen = function() { var win = jQuery(window); var viewport = { top: win.scrollTop(), left: win.scrollLeft() }; viewport.right = viewport.left + win.width(); viewport.bottom = viewport.top + win.height(); var bounds = this.offset(); bounds.right = bounds.left + this.outerWidth(); bounds.bottom = bounds.top + this.outerHeight(); return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom)); }; jQuery(function($) { /*********************************** Global Variables ************************************/ var $window = $(window); var $body = $('body'); /*********************************** Scrollers ************************************/ function scrollTo(object, speed) { var $object; var scroll; if (typeof speed === "undefined" || speed === null) { speed = 1500; } if (typeof object === 'string') { $object = $(object); scroll = $object.offset().top - 70; } else if (object instanceof $) { $object = object; scroll = $object.offset().top - 70; } else if ($.isNumeric(object)) { scroll = object; } else { $object = $('body'); scroll = $object.offset().top - 70; } scroll = (scroll >= 0) ? scroll : 0; $('body, html').animate({ scrollTop: scroll }, speed); } $('a[data-scrollTo]').click(function(e) { var target = $(this).attr('data-scrollTo'); scrollTo(target); e.preventDefault(); }); $('#backtotop').click(function() { scrollTo(0); }); $('.next-section').click(function() { var $btn = $(this); var $parent = $btn.parents('section'); var parentindex = $('section').index($parent); var $nextparent = $('section').eq(parentindex + 1); scrollTo($nextparent); }); /*********************************** Element Animation ************************************/ function animate() { $('[data-animate]').each(function() { var $this = $(this); if ($this.isOnScreen()) { var animation = $this.attr('data-animate'); var delay = $this.attr('data-animate-delay') ? $this.attr('data-animate-delay') : 0; setTimeout(function() { $this.addClass('animated').addClass(animation); }, delay); } }); } /*********************************** Window Binding ************************************/ var delay = (function() { var timer = 0; return function(callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); $window.scroll(function(e) { var scrolled = $window.scrollTop(); animate(); if (scrolled > 0) { $('#navbar').removeClass('navbar-lg'); } else { $('#navbar').addClass('navbar-lg'); } if (scrolled > 100) { $('#backtotop').removeClass('opacity-hide'); } else { $('#backtotop').addClass('opacity-hide'); } }).trigger('scroll'); $window.resize(function() { }).trigger('resize'); });
coderconf/Farsi-Website
src/assets/js/animated.js
JavaScript
mit
3,466
var config = require("../config/config.js"); /** * [entities description] * _id,info,orderId,createdOn */ var entities = config.db.collection("logistics"); module.exports = { /** * 添加物流信息 * @param {[type]} orderId [description] * @param {[type]} info [description] * @param {Function} done [description] */ addLogistics: function(orderId, info, done) { var logistics = { info: info, orderId: config.mongojs.ObjectId(orderId), createdOn: new Date() } entities.save(logistics, function(err, success) { if (success) { return done({ status: true, data: success }); } else { return done({ status: false, err: err }); } }); }, /** * 获取物流列表 * @param {[type]} orderId [description] * @param {Function} done [description] * @return {[type]} [description] */ getLogistics: function(orderId, done) { var objOrderId = config.mongojs.ObjectId(orderId); entities.find({ orderId: objOrderId }, function(err, success) { if (success) { return done({ status: true, data: success }); } else { return done({ status: false, err: err }); } }); } }
DannyChanSz/cgb-server
models/logistics.js
JavaScript
mit
1,642
var config = require('config') var jsonld = require('jsonld') var exports = module.exports = {} exports.contextAll = config['contextAll'] exports.buildJsonLdContext = function (prefixes) { var context = JSON.parse(JSON.stringify(prefixes)) delete context['urn'] // all the aliases // some fancy stuff for agents results context['topFiveTermsString'] = { '@id': 'nyplapp:topFiveTermsString', '@container': '@list' } context['topFiveRolesString'] = { '@id': 'nyplapp:topFiveTermsString', '@container': '@list' } context['birthDate'] = 'dbo:birthDate' context['birthYear'] = 'dbo:birthYear' context['birthDecade'] = 'nypl:birthDecade' context['deathDate'] = 'dbo:deathDate' context['deathYear'] = 'dbo:deathYear' context['deathDecade'] = 'nypl:deathDecade' // FIX ME context['startYear'] = 'dbo:startYear' context['endYear'] = 'dbo:endYear' context['created'] = 'dcterms:created' context['thumbnail'] = 'dbo:thumbnail' context['filename'] = 'nypl:filename' context['owner'] = 'nypl:owner' context['dcFlag'] = 'nypl:dcflag' context['publicDomain'] = 'nypl:publicDomain' context['suppressed'] = 'nypl:suppressed' context['hasMember'] = 'pcdm:hasMember' context['memberOf'] = 'pcdm:memberOf' context['hasEquivalent'] = 'bf:hasEquivalent' context['idBarcode'] = 'dcterms:identifier' context['idBnum'] = 'dcterms:identifier' context['idMss'] = 'dcterms:identifier' context['idMssColl'] = 'dcterms:identifier' context['idObjNum'] = 'dcterms:identifier' context['idRlin'] = 'dcterms:identifier' context['idOclc'] = 'dcterms:identifier' context['idExhib'] = 'dcterms:identifier' context['idUuid'] = 'dcterms:identifier' context['idCallnum'] = 'dcterms:identifier' context['idCatnyp'] = 'dcterms:identifier' context['idMmsDb'] = 'dcterms:identifier' context['idIsbn'] = 'dcterms:identifier' context['idIssn'] = 'dcterms:identifier' context['idHathi'] = 'dcterms:identifier' context['idLccCoarse'] = 'dcterms:identifier' context['idOwi'] = 'dcterms:identifier' context['idDcc'] = 'dcterms:identifier' context['idLcc'] = 'dcterms:identifier' context['idAcqnum'] = 'dcterms:identifier' context['uriWikidata'] = 'skos:exactMatch' context['uriDbpedia'] = 'skos:exactMatch' context['uriViaf'] = 'skos:exactMatch' context['uriLc'] = 'skos:exactMatch' context['prefLabel'] = 'skos:prefLabel' context['note'] = 'skos:note' context['depiction'] = 'foaf:depiction' context['wikipedia'] = 'foaf:isPrimaryTopicOf' context['title'] = 'dcterms:title' context['type'] = 'dcterms:type' context['titleAlt'] = 'dcterms:alternative' context['identifier'] = 'dcterms:identifier' context['description'] = 'dcterms:description' context['contributor'] = 'dcterms:contributor' context['subject'] = 'dcterms:subject' context['language'] = 'dcterms:language' context['holdingCount'] = 'classify:holdings' context['searchResultScore'] = 'nyplapp:searchResultScore' context['searchResult'] = 'nyplapp:searchResult' context['totalResults'] = 'nyplapp:totalResults' context['currentPage'] = 'nyplapp:searchResultPage' context['morePages'] = 'nyplapp:searchResultMorePages' context['useCount'] = 'nyplapp:useCount' context['isSubject'] = 'nyplapp:isSubject' context['isContributor'] = 'nyplapp:isContributor' context['result'] = 'schema:result' context['itemListElement'] = 'schema:itemListElement' context['itemList'] = 'schema:ItemList' return context } exports.context = exports.buildJsonLdContext(config.prefixes) exports.eachValue = function (a, cb) { switch (typeof a) { case 'object': return a.map(cb) case 'undefined': return null default: if (a) return cb(a) } } exports.flatenTriples = function (object) { var flat = {objectLiteral: {}, objectUri: {}} for (var key in object) { // is this a triple if (config['predicatesAgents'].indexOf(key) > -1 || config['predicatesResources'].indexOf(key) > -1) { object[key].forEach((value) => { if (value.objectLiteral) { if (!flat.objectLiteral[key]) flat.objectLiteral[key] = [] flat.objectLiteral[key].push(value.objectLiteral) } if (value.objectUri) { if (!flat.objectUri[key]) flat.objectUri[key] = [] flat.objectUri[key].push(value.objectUri) if (value.label) { if (!flat.objectUri[key + ':label']) flat.objectUri[key + ':label'] = [] flat.objectUri[key + ':label'].push({uri: value.objectUri, label: value.label}) } } }) } } return flat } exports.expandObjectUri = function (objectUri) { if (!objectUri) return false var split = objectUri.split(':') var prefix = split[0] split.shift(0, 1) var value = split.join(':') var uriBase = config.prefixes[prefix] if (!uriBase) { console.log('Unknown Prefix:', prefix) return false } return uriBase + value } // turns the objects into triples sans provo exports.returnNtTriples = function (obj, type) { var uri = null var triples = [] if (type === 'resource') { uri = '<http://data.nypl.org/resources/' + obj.uri + '>' } else if (type === 'agent') { uri = '<http://data.nypl.org/agents/' + obj.uri + '>' } else if (type === 'term') { uri = '<http://data.nypl.org/terms/' + obj.uri + '>' } else if (type === 'org') { uri = '<http://data.nypl.org/organizations/' + obj.uri + '>' } else if (type === 'dataset') { uri = '<http://data.nypl.org/datasets/' + obj.uri + '>' } else { return false } for (var p in obj) { if (config['predicatesAgents'].indexOf(p) > -1 || config['predicatesResources'].indexOf(p) > -1) { // it is a triple var expandedPredicate = '<' + exports.expandObjectUri(p) + '>' obj[p].forEach((o) => { var expandedObject = null if (o.objectUri) { expandedObject = '<' + exports.expandObjectUri(o.objectUri) + '>' } else { expandedObject = exports.expandObjectUri(o.objectLiteralType) if (expandedObject === false && o.objectLiteralType) { expandedObject = '@' + o.objectLiteralType } else if (typeof expandedObject === 'string') { expandedObject = '^^<' + expandedObject + '>' } else { expandedObject = '' } if (typeof o.objectLiteral === 'string') o.objectLiteral = o.objectLiteral.replace('"', '\\"').replace('\n', ' ') expandedObject = '"' + o.objectLiteral + '"' + expandedObject } triples.push(uri + ' ' + expandedPredicate + ' ' + expandedObject + '.') }) } } return triples } exports.returnNtJsonLd = function (obj, type, cb) { var triples = exports.returnNtTriples(obj, type).join('\n') // console.log(triples) jsonld.fromRDF(triples, {format: 'application/nquads'}, function (err, doc) { if (err) console.log(JSON.stringify(err, null, 2)) jsonld.compact(doc, exports.context, function (err, compacted) { if (err) console.log(err) cb(err, compacted) }) }) } // Applies validation against hash of params given spec // see `parseParams` exports.parseParams = function (params, spec) { var ret = {} Object.keys(spec).forEach(function (param) { // If user supplied value: if (params[param]) { var parsed = exports.parseParam(params[param], spec[param]) // Make sure it's a valid value if ((typeof parsed) !== 'undefined') { ret[param] = parsed // If not valid, fall back on default, if specified: } else if (spec[param].default) { ret[param] = spec[param].default } } else if (spec[param].default) { ret[param] = spec[param].default } }) return ret } // Given raw query param value `val` // returns value validated against supplied spec: // `type`: (int, string, date, object) - Type to validate (and cast) against // `range`: Array - Constrain allowed values to range // `fields`: Hash - When `type` is 'object', this property provides field spec to validate internal fields against exports.parseParam = function (val, spec) { if ((typeof val) === 'object' && !isNaN(Object.keys(val)[0])) { return Object.keys(val).map((i) => exports.parseParam(val[i], spec)).filter((v) => (typeof v) !== 'undefined') } switch (spec.type) { case 'date': case 'int': if (isNaN(val)) return spec.default val = Number.parseInt(val) break case 'object': val = exports.parseParams(val, spec.keys) break } if (spec.range) { if (val < spec.range[0]) return spec.default if (val > spec.range[1]) return spec.range[1] } return val } exports.gatherParams = function (req, acceptedParams) { // If specific params configured, pass those to handler // otherwise just pass `value` param (i.e. keyword search) acceptedParams = (typeof acceptedParams === 'undefined') ? ['page', 'per_page', 'value', 'q'] : acceptedParams var params = {} acceptedParams.forEach((k) => { params[k] = req.query[k] }) if (req.query.q) params.value = req.query.q return params } // exports.parseLocationFile = function(cb){ // var locations = {} // var stream = fs.createReadStream(__dirname + "/data/locations.csv") // var csvStream = csv() // .on("data", function(data){ // locations[data[0]] = { // name : data[1], // location : data[2], // code : data[3], // slug : data[4], // lat : data[5], // lng : data[6], // research : data[7].toLowerCase() // } // }) // .on("end", function(){ // cb(locations) // }) // stream.pipe(csvStream) // } // //check for the filename of the script running in ps aux output and return true if it is already listed // exports.checkIfRunning = function(cb,threshold){ // //on linux servers running this as a cron job it will be 3 // if (!threshold) threshold = 3 // var scriptName = process.argv[1].split("/")[process.argv[1].split("/").length-1] // var child = exec("ps aux", // function (error, stdout, stderr) { // if (stdout.split(scriptName).length > threshold){ // cb(true) // }else{ // cb(false) // } // }) // } // //our own exit method to kill the process but allow the logger to finish up anything it is doing // exports.exit = function(){ // setTimeout(function(){process.exit()},2000) // }
nypl-registry/registry-api
lib/util.js
JavaScript
mit
10,425
'use strict'; angular.module('pdb') .controller('HomeCtrl', ['$scope', 'userAPI', 'habitsAPI', function($scope, userAPI, habitsAPI) { //test $scope.userID = userAPI.getUserID(); $scope.lastUserID = userAPI.getLastUserID(); $scope.sessionID = userAPI.getSessionID(); $scope.isLoggedIn = userAPI.isLoggedIn(); $scope.userLogin = { username: userAPI.getLastUserID(), password: '' }; $scope.devStats = { deviceReady: false, userAgent: 'unknown', screenDimensions: 'unknown', windowDimensions: 'unknown', deviceOrientation: 'portrait', userEmail: '', averageHabitScore: 0, }; //called by loginForm $scope.login = function(userLogin){ userAPI.login(userLogin.username,userLogin.password).then( function(response){ if(response.data['responseCode'] == 'success'){ location.reload(); }//else display some login error message } ); }; $scope.logout = function(){ userAPI.logout(userAPI.getUserID(), userAPI.getSessionID()).then( function(){ location.reload(); } ); }; $scope.getUserInfo = function(){ userAPI.getUserInfo($scope.userID, $scope.sessionID).then( function(response){ console.log('getUserInfo response: ' + PDB.utils.stringifySafe(response)); //TODO: do something with results involving $scope.devStats if(response && response.data && response.data['responseCode'] == 'success'){ habitsAPI.averageScore(14).then(function(result){ $scope.devStats.averageHabitScore = parseFloat(result).toFixed(2); console.log('[home.js] $scope.devStats.averageHabitScore: ' + PDB.utils.stringifySafe($scope.devStats.averageHabitScore)); }); } } ); }; }]);
Initial-B/pdb
app/home/home.js
JavaScript
mit
1,691
import GlobalSetting, { UPDATE_IMMEDIATE, UPDATE_SERVER, UPDATE_STORE, UPDATE_THROTTLED } from './GlobalSetting'; import axios from "axios"; import { URL_GET_APP_SETTINGS, URL_POST_APP_SETTINGS } from "./ApiRoutes"; import boxedImmutable from "boxed-immutable"; import appEvents from './AppEvents'; const util = boxedImmutable.util; const _$ = boxedImmutable.box; const isArray = util.isArray; const eachProp = util.eachProp; const isFunction = util.isFunction; const isObject = util.isObjectLike; const UNDEFINED = util.UNDEFINED; export const appSettingChecks = { autoUpdateViews: 'auto-update-views', autoUpdateTranslationTable: 'auto-update-translation-table', confirmDeleteGroup: 'confirm-delete-group', confirmImportGroup: 'confirm-import-group', confirmImportGroupReplace: 'confirm-import-group-replace', confirmImportGroupDelete: 'confirm-import-group-delete', confirmPublishGroup: 'confirm-publish-group', confirmImportAllGroups: 'confirm-import-all-groups', confirmImportAllGroupsReplace: 'confirm-import-all-groups-replace', confirmImportAllGroupsDelete: 'confirm-import-all-groups-delete', confirmAddReferences: 'confirm-add-references', confirmPublishAllGroups: 'confirm-publish-all-groups', confirmAddSuffixedKeys: 'confirm-add-suffixed-keys', confirmDeleteSuffixedKeys: 'confirm-delete-suffixed-keys', confirmClearUserUiSettings: 'confirm-clear-user-ui-settings', }; export const appSettingForcedChecks = { confirmDeleteGroup: true, confirmAddReferences: true, confirmDeleteSuffixedKeys: true, confirmClearUserUiSettings: true, }; // app route to dashboard settings & defaults // "summary", "mismatches", "translationSettings", "userAdmin", export const dashboardConfig = { dashboards: { summary: { index: 0, showState: "showSummaryDashboard", title: 'messages.stats', collapseState: "collapseSummaryDashboard", defaultCollapse: true, defaultShow: true, defaultInclude: true, }, mismatches: { index: 1, showState: "showMismatchDashboard", title: 'messages.mismatches', collapseState: "collapseMismatchDashboard", defaultShow: true, defaultCollapse: true, defaultInclude: true, }, userAdmin: { index: 2, showState: "showUserManagementDashboard", title: 'messages.user-admin', collapseState: "collapseUserManagementDashboard", defaultShow: true, defaultInclude: true, isAvailable: isAdminEnabled, }, translationSettings: { index: 3, showState: "showTranslationSettings", title: 'messages.translation-settings', collapseState: "collapseTranslationSettings", defaultShow: true, defaultInclude: true, }, yandex: { index: 4, showState: "showYandexTranslation", title: 'messages.translation-ops', collapseState: "collapseYandexTranslation", defaultShow: false, defaultInclude: true, isDisabled: missingYandexKey, }, suffixedKeyOps: { index: 4, showState: "showSuffixedKeyOps", title: 'messages.suffixed-keyops', collapseState: "collapseSuffixedKeyOps", defaultShow: false, defaultInclude: false, isDisabled: missingYandexKey, }, // not shown as dashboards but available if needed appSettings: { index: 10, showState: "showAppSettings", collapseState: "collapseAppSettings", title: "messages.app-settings", defaultShow: false, defaultInclude: false, }, search: { index: 15, showState: "showSearchDashboard", collapseState: "collapseSearchDashboard", title: "messages.search-dashboard", defaultShow: false, defaultInclude: false, }, translations: { index: 20, showState: "showTranslationTable", collapseState: "collapseTranslationTable", title: "messages.translation-table", defaultShow: false, defaultInclude: false, }, groups: { index: 25, showState: "showGroupManagementDashboard", collapseState: "collapseGroupManagementDashboard", title: "messages.group-management-dashboard", defaultShow: false, defaultInclude: false, }, }, routeDashboards: { "": { settingsPrefix: "", includeDashboards: ["summary", "mismatches", "translationSettings", "userAdmin", 'yandex', 'suffixedKeyOps'], // excludeDashboards: [], }, "users": { settingsPrefix: "users", includeDashboards: ["summary", "mismatches", "translationSettings",], excludeDashboards: ["userAdmin",], }, "groups": { settingsPrefix: "groups", // includeDashboards: ["summary", "mismatches", "translationSettings"], excludeDashboards: ["summary", "mismatches", "userAdmin",], }, "topics": { settingsPrefix: "topics", // includeDashboards: [], // excludeDashboards: [], }, "settings": { settingsPrefix: "settings", includeDashboards: ["summary", "mismatches",], // excludeDashboards: ["translationSettings",], }, "search": { settingsPrefix: "search", // includeDashboards: ["summary", "mismatches", "translationSettings",], excludeDashboards: ["userAdmin",], }, "yandex": { settingsPrefix: "yandex", // includeDashboards: ["summary", "mismatches", "translationSettings",], excludeDashboards: ["Yandex",], }, }, }; // these are in uiSettings export class AppSettings extends GlobalSetting { constructor() { super("appSettings"); let defaults_$ = _$({ // default settings isAdminEnabled: false, connectionList: { "": "default" }, connectionName: "", transFilters: null, markdownKeySuffix: "", showUsage: false, resetUsage: false, usageInfoEnabled: false, mismatchEnabled: false, userLocalesEnabled: false, currentLocale: 'en', primaryLocale: 'en', translatingLocale: 'en', locales: ['en'], userLocales: ['en'], displayLocales: ['en'], groups: [], yandexKey: '', showUnpublishedSite: false, uiSettings: { yandexText: { "@@": '', }, // placeholder so Php does not convert empty object to empty array group: null, xDebugSession: null, searchText: '', showPublishButtons: true, // these are the buttons collapsePublishButtons: true, // these are the all groups buttons defaultSuffixes: '-type\n' + '-header\n' + '-heading\n' + '-description\n' + '-footer', }, suffixedKeyOps: { keys: '', suffixes: '', }, }); const updateSettingsType = { connectionName: UPDATE_IMMEDIATE, showUsage: UPDATE_THROTTLED, resetUsage: UPDATE_IMMEDIATE, currentLocale: UPDATE_THROTTLED, primaryLocale: UPDATE_THROTTLED, translatingLocale: UPDATE_THROTTLED, displayLocales: UPDATE_THROTTLED, showUnpublishedSite: UPDATE_THROTTLED, uiSettings: UPDATE_SERVER, // throttled but update server response ignored }; let transforms_$ = _$({ isAdminEnabled: _$.transform.toBoolean, showUsage: _$.transform.toBoolean, locales: _$.transform.toDefault(''), resetUsage: _$.transform.toBoolean, usageInfoEnabled: _$.transform.toBoolean, mismatchEnabled: _$.transform.toBoolean, userLocalesEnabled: _$.transform.toBoolean, showUnpublishedSite: _$.transform.toBoolean, uiSettings: { showPublishButtons: _$.transform.toBoolean, collapsePublishButtons: _$.transform.toBoolean, } }); // include default settings for dashboardShow, collapse eachProp.call(dashboardConfig.dashboards, (dashboard, dashboardName) => { dashboard.dashboardName = dashboardName; const showState = util.firstDefined(dashboard.defaultShow, false); const collapseState = util.firstDefined(dashboard.defaultCollapse, false); const transformShow = showState ? _$.transform.toBooleanDefaultTrue : _$.transform.toBoolean; const transformCollapse = collapseState ? _$.transform.toBooleanDefaultTrue : _$.transform.toBoolean; transforms_$.uiSettings[dashboard.showState] = transformShow; transforms_$.uiSettings[dashboard.collapseState] = transformCollapse; defaults_$.uiSettings[dashboard.showState] = showState; defaults_$.uiSettings[dashboard.collapseState] = collapseState; // include default settings for dashboardShow, collapse route specific eachProp.call(dashboardConfig.routeDashboards, (routeConfig, route) => { const explicitlyIncluded = routeConfig.includeDashboards && routeConfig.includeDashboards.indexOf(dashboardName) !== -1; const implicitlyIncluded = !routeConfig.includeDashboards || explicitlyIncluded; const explicitlyExcluded = routeConfig.excludeDashboards && routeConfig.excludeDashboards.indexOf(dashboardName) !== -1; if ((explicitlyIncluded || implicitlyIncluded && dashboard.defaultInclude) && !explicitlyExcluded) { // dashboard available for this route, add it so it won't need searching if (!routeConfig.dashboards) routeConfig.dashboards = []; const settingsPrefix = routeConfig.settingsPrefix; if (!settingsPrefix) { routeConfig.dashboards.push(dashboard); } else { routeConfig.dashboards.push(Object.assign({}, dashboard, { showState: `${settingsPrefix}.${dashboard.showState}`, collapseState: `${settingsPrefix}.${dashboard.collapseState}`, })); transforms_$.uiSettings[settingsPrefix][dashboard.showState] = transformShow; transforms_$.uiSettings[settingsPrefix][dashboard.collapseState] = transformCollapse; defaults_$.uiSettings[settingsPrefix][dashboard.showState] = showState; defaults_$.uiSettings[settingsPrefix][dashboard.collapseState] = collapseState; } } }); }); // need to sort the dashboards in the arrays in order of their index eachProp.call(dashboardConfig.routeDashboards, (routeConfig, route) => { if (routeConfig.dashboards) { routeConfig.dashboards.sort((a, b) => a.index - b.index); } }); eachProp.call(appSettingChecks, (value,key) => { if (appSettingForcedChecks.hasOwnProperty(key)) { const setTo = appSettingForcedChecks[key]; transforms_$.uiSettings[key] = setTo ? _$.transform.toAlwaysTrue : _$.transform.toAlwaysFalse; defaults_$.uiSettings[key] = setTo; } else { transforms_$.uiSettings[key] = _$.transform.toBooleanDefaultTrue; defaults_$.uiSettings[key] = true; } }); const defaultSettings = defaults_$.$_value; const transforms = transforms_$.$_value; this.setStateTransforms(transforms); this.setDefaultSettings(defaultSettings, updateSettingsType); window.setTimeout(()=>{ this.load(); }, 100); } // implement to test if can request settings from server serverCanLoad() { return true; } adjustServerData(result, isLoad) { let data = result.data; if (isLoad) { const uiSettings = data.uiSettings; if (!uiSettings) { data.uiSettings = data.appSettings; } if (uiSettings && uiSettings.yandexText !== undefined && (!isObject(uiSettings.yandexText) || isArray(uiSettings.yandexText))) { // php converting empty objects to arrays if using prefer assoc option uiSettings.yandexText = {}; } data.uiSettings = uiSettings; // merge all the default uiSettings the server may not have data = util.mergeDefaults.call(result.data, { uiSettings: appSettings.getState().uiSettings }); } data && delete data.appSettings; return data; } // implement to request settings from server serverLoad() { axios.get(URL_GET_APP_SETTINGS().url) .then((result) => { // server may not have defaults, fill in from settings with fallback to defaults const data = this.adjustServerData(result, true); this.processServerUpdate(data); }); } // implement to send server request updateServer(settings, frameId) { const api = URL_POST_APP_SETTINGS(settings); axios .post(api.url, api.data) .then((result) => { const data = this.adjustServerData(result, false); this.processServerUpdate(data, frameId); }); } getRouteDashboard(dashboardRoute) { // may need to filter out ones not enabled if (isObject(dashboardRoute)) { dashboardRoute = dashboardRoute.path.substr(1); // chop off the leading / and we're good to go const type = typeof dashboardRoute; let tmp = 0; } const routeDashboards = dashboardConfig.routeDashboards[dashboardRoute]; if (routeDashboards && routeDashboards.dashboards) { const dashboards = routeDashboards.dashboards.filter(dashboard => dashboard.isAvailable === UNDEFINED || dashboard.isAvailable()); return dashboards; } return null; } getRouteSettingPrefix(dashboardRoute) { // may need to filter out ones not enabled dashboardRoute = this.dashboardRoute(dashboardRoute); const routeDashboards = dashboardConfig.routeDashboards[dashboardRoute]; if (routeDashboards && routeDashboards.settingsPrefix) { return routeDashboards.settingsPrefix; } return ''; } dashboardRoute(dashboardRoute) { if (isObject(dashboardRoute)) { dashboardRoute = dashboardRoute.path && dashboardRoute.path.substr(1) || ''; // chop off the leading / and we're good to go const type = typeof dashboardRoute; let tmp = 0; } return dashboardRoute; } } const appSettings = new AppSettings(); export const appSettings_$ = appSettings.getBoxed(); export function isAdminEnabled() { return appSettings_$.isAdminEnabled(); } export function missingYandexKey() { const yandexKey = appSettings_$.yandexKey(); return !yandexKey; } export default appSettings;
vsch/laravel-translation-manager
resources/assets/js/helpers/AppSettings.js
JavaScript
mit
16,056
var data = { "module": "scene", "method": "draw", "params": { "shapes": [{ "shape": { "type": "polyline", "geometry": { "isClosed": true, "rightVector": { "x": 100, "y": 100, "z": 2 }, "points": [{ "x": 500, "y": 100, "z": 2 }, { "x": 500, "y": 500, "z": 2 }, { "x": 100, "y": 500, "z": 2 }, { "x": 100, "y": 100, "z": 2 }] }, "style": { "fill": { "r": 255, "g": 80, "b": 90, "a": 255 }, "stroke": { "r": 1, "g": 2, "b": 2, "a": 2 } } } }] } }; var ctx; // defined globally function websocketMessage(evt) { if (evt.module == "scene") { if (evt.method == "draw") { drawScene(evt.params.shapes, ctx); } } } function drawScene(shapes, context) { for (var i = 0; i < shapes.length; i++) { drawShape(shapes[i].shape, context); } } function drawShape(shape, context) { var geometry = shape.geometry; var type = shape.type; console.log(shape); var isBeginPath = false; switch(type) { case 'polyline': context.beginPath(); isBeginPath = true; var points = geometry.points; for (var i = 0; i < points.length; i++) { var point = points[i]; if (i == 0) context.moveTo(point.x, point.y); else context.lineTo(point.x, point.y); } if (geometry.isClosed) context.lineTo(points[0].x, points[0].y); break; } // close the path if (isBeginPath) context.closePath(); var style = shape.style; if (typeof style.fill !== 'undefined') { context.fillStyle = getCSSColor(style.fill); if (type == 'polyline') context.fill(); } if (typeof style.stroke !== 'undefined') { context.strokeStyle = getCSSColor(style.fill); if (type == 'polyline') context.stroke(); } } function getCSSColor(c) { return 'rgba(' + c.r + ',' + c.g + ',' + c.b + ',' + c.a + ')'; } $(document).ready(function(){ var canvas = document.getElementById('ofxCanvasEvents-canvas'); ctx = canvas.getContext('2d'); websocketMessage(data); });
brannondorsey/ofxCanvasEvents
example_advanced/bin/data/DocumentRoot/js/main.js
JavaScript
mit
2,369
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){ var click_event = new MouseEvent('click', { 'view': window, 'bubbles': true, 'cancelable': true }); switch(request.action){ case 'NEXT-MK': document.getElementById('play-next').dispatchEvent(click_event); break; case 'PREV-MK': document.getElementById('play-prev').dispatchEvent(click_event); break; case 'PLAY-PAUSE-MK': document.getElementById('play-pause').dispatchEvent(click_event); break; } });
julianxhokaxhiu/chrome-grooveshark-mediakeys-reloaded
js/app.js
JavaScript
mit
632
module.exports = function (grunt) { // Project configuration. grunt.initConfig({ mocha_istanbul: { coverage: { src: 'tests', options: { timeout: 30000, ignoreLeaks: false, check: { statements: 60, branches: 50, functions: 60, lines: 60 } } } }, jshint: { options: { jshintrc: true, }, src: ['tests/**/*.js'] }, clean: ['tmp'] }); // Load grunt plugins for modules. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-mocha-istanbul'); grunt.loadNpmTasks('grunt-contrib-clean'); // Register tasks. grunt.registerTask('default', ['mocha_istanbul:coverage', 'clean']); };
marinvvasilev/appcelerator-githubauth
Gruntfile.js
JavaScript
mit
966
var AMP = AMP || {}; (function(root, CJS){ // 'use strict'; /*---------------------------------------------------------------------- @constructor ----------------------------------------------------------------------*/ /** * <h4>Easingを管理します</h4> * * @class AMP.Ease * @extends AMP.Ease * @constructor */ function Ease(){} // 基底クラスを継承 AMP.inherits(Ease, AMP.Ease); // prototype var p = Ease.prototype; /*-------------------------------------------------------------------------- @property --------------------------------------------------------------------------*/ /** * <h4>createjs Easing用ネームスペース</h4> * see: http://www.CJS.com/Docs/TweenJS/files/tweenjs_p.js.html * * @property createjs * @type {Object} */ p.CJS = {}; /* 1 Sine -----------------------------------------------------------------*/ /** * @property CJS._1_SINE_IN * @type {String} */ p.CJS._1_SINE_IN = CJS.Ease.sineIn; /** * @property CJS._1_SINE_OUT * @type {String} */ p.CJS._1_SINE_OUT = CJS.Ease.sineOut; /** * @property CJS._1_SINE_IN_OUT * @type {String} */ p.CJS._1_SINE_IN_OUT = CJS.Ease.sineInOut; /* 2 Quad -----------------------------------------------------------------*/ /** * @property CJS._2_QUAD_IN * @type {String} */ p.CJS._2_QUAD_IN = CJS.Ease.quadIn; /** * @property CJS._2_QUAD_OUT * @type {String} */ p.CJS._2_QUAD_OUT = CJS.Ease.quadOut; /** * @property CJS._2_QUAD_IN_OUT * @type {String} */ p.CJS._2_QUAD_IN_OUT = CJS.Ease.quadInOut; /* 3 Cubic -----------------------------------------------------------------*/ /** * @property CJS._3_CUBIC_IN * @type {String} */ p.CJS._3_CUBIC_IN = CJS.Ease.cubicIn; /** * @property CJS._3_CUBIC_OUT * @type {String} */ p.CJS._3_CUBIC_OUT = CJS.Ease.cubicOut; /** * @property CJS._3_CUBIC_IN_OUT * @type {String} */ p.CJS._3_CUBIC_IN_OUT = CJS.Ease.cubicInOut; /* 4 Quart -----------------------------------------------------------------*/ /** * @property CJS._4_QUART_IN * @type {String} */ p.CJS._4_QUART_IN = CJS.Ease.quartIn; /** * @property CJS._4_QUART_OUT * @type {String} */ p.CJS._4_QUART_OUT = CJS.Ease.quartOut; /** * @property CJS._4_QUART_IN_OUT * @type {String} */ p.CJS._4_QUART_IN_OUT = CJS.Ease.quartInOut; /* 5 Quint -----------------------------------------------------------------*/ /** * @property CJS._5_QUINT_IN * @type {String} */ p.CJS._5_QUINT_IN = CJS.Ease.quintIn; /** * @property CJS._5_QUINT_OUT * @type {String} */ p.CJS._5_QUINT_OUT = CJS.Ease.quintOut; /** * @property CJS._5_QUINT_IN_OUT * @type {String} */ p.CJS._5_QUINT_IN_OUT = CJS.Ease.quintInOut; /* 6 Expo -----------------------------------------------------------------*/ /** * @property CJS._6_EXPO_IN * @type {String} */ p.CJS._6_EXPO_IN = CJS.Ease.getPowIn(6); /** * @property CJS._6_EXPO_OUT * @type {String} */ p.CJS._6_EXPO_OUT = CJS.Ease.getPowOut(6); /** * @property CJS._6_EXPO_IN_OUT * @type {String} */ p.CJS._6_EXPO_IN_OUT = CJS.Ease.getPowInOut(6); /* 7 Circ -----------------------------------------------------------------*/ /** * @property CJS._7_CIRC_IN * @type {String} */ p.CJS._7_CIRC_IN = CJS.Ease.circIn; /** * @property CJS._7_CIRC_OUT * @type {String} */ p.CJS._7_CIRC_OUT = CJS.Ease.circOut; /** * @property CJS._7_CIRC_IN_OUT * @type {String} */ p.CJS._7_CIRC_IN_OUT = CJS.Ease.circInOut; /* Linear -----------------------------------------------------------------*/ /** * @property CJS._LINEAR * @type {String} */ p.CJS._LINEAR = CJS.Ease.linear; /* Back -----------------------------------------------------------------*/ /** * @property CJS._BACK_IN * @type {String} */ p.CJS._BACK_IN = CJS.Ease.backIn; /** * @property CJS._BACK_OUT * @type {String} */ p.CJS._BACK_OUT = CJS.Ease.backOut; /** * @property CJS._BACK_IN_OUT * @type {String} */ p.CJS._BACK_IN_OUT = CJS.Ease.backInOut; /* Elastic -----------------------------------------------------------------*/ /** * @property CJS._ELASTIC_IN * @type {String} */ p.CJS._ELASTIC_IN = CJS.Ease.elasticIn; /** * @property CJS._ELASTIC_OUT * @type {String} */ p.CJS._ELASTIC_OUT = CJS.Ease.elasticOut; /** * @property CJS._ELASTIC_IN_OUT * @type {String} */ p.CJS._ELASTIC_IN_OUT = CJS.Ease.elasticInOut; /* Bounce -----------------------------------------------------------------*/ /** * @property CJS._BOUNCE_IN * @type {String} */ p.CJS._BOUNCE_IN = CJS.Ease.bounceIn; /** * @property CJS._BOUNCE_OUT * @type {String} */ p.CJS._BOUNCE_OUT = CJS.Ease.bounceOut; /** * @property CJS._BOUNCE_IN_OUT * @type {String} */ p.CJS._BOUNCE_IN_OUT = CJS.Ease.bounceInOut; /*-------------------------------------------------------------------------- export --------------------------------------------------------------------------*/ AMP.Ease = Ease; AMP.ease = new Ease(); }(window, createjs));
hyukihiro/ampjs
_bk/amp/createjs/utilities/Ease.js
JavaScript
mit
5,321
/* global describe, it */ import React from "react"; import ReactDOMServer from "react-dom/server"; import { expect } from "chai"; // eslint-disable-line import/no-extraneous-dependencies import InputElement from "../../index"; describe("Test prerender", () => { it("should return a string", () => { const result = ReactDOMServer.renderToString( <InputElement value="some" mask="799" /> ); expect(typeof result).to.equal("string"); }); });
sanniassin/react-input-mask
tests/server-render/server-render.js
JavaScript
mit
464
s = document.createElement("script"); s.setAttribute ("type", "text/x-mathjax-config"); // Push the chem extension into the root extensions since TeX isn't loaded yet. s.innerText += "MathJax.Hub.config.extensions.push('TeX/mhchem.js');"; document.getElementsByTagName("head")[0].appendChild(s);
arthanzel/breve
packages/Core.Math.Chem/MathChem.js
JavaScript
mit
296
function Bill(){ this.items = []; } Bill.prototype.addItem = function(item){ this.items.push(item); } Bill.prototype.total = function(){ var total = 0; for (i=0; i < this.items.length; i++) { var price = this.items[i].convert_price(); total += price; } return total; }; Bill.prototype.clear = function(){ this.items.length = 0; }
Heintzdm/check-it-out-app
app/assets/javascripts/bill.js
JavaScript
mit
355
// @flow import { _extractLibDefsFromNpmPkgDir as extractLibDefsFromNpmPkgDir, _parsePkgNameVer as parsePkgNameVer, _validateVersionNumPart as validateVersionNumPart, _validateVersionPart as validateVersionPart, getInstalledNpmLibDefs, getNpmLibDefs, findNpmLibDef, } from '../npmLibDefs'; import path from 'path'; const BASE_FIXTURE_ROOT = path.join(__dirname, '__npmLibDefs-fixtures__'); describe('npmLibDefs', () => { describe('extractLibDefsFromNpmPkgDir', () => { const FIXTURE_ROOT = path.join( BASE_FIXTURE_ROOT, 'extractLibDefsFromNpmPkgDir', ); it('succeeds on well-formed repo', async () => { const UNDERSCORE_PATH = path.join( FIXTURE_ROOT, 'well-formed', 'definitions', 'npm', 'underscore_v1.x.x', ); const errs = new Map(); const defs = await extractLibDefsFromNpmPkgDir( UNDERSCORE_PATH, null, 'underscore_v1.x.x', errs, ); expect([...errs.entries()]).toEqual([]); expect(defs).toEqual( expect.arrayContaining([ { flowVersion: { kind: 'ranged', lower: { major: 0, minor: 13, patch: 'x', prerel: null, }, upper: { major: 0, minor: 37, patch: 'x', prerel: null, }, }, name: 'underscore', path: path.join( UNDERSCORE_PATH, 'flow_v0.13.x-v0.37.x', 'underscore_v1.x.x.js', ), scope: null, testFilePaths: [ path.join(UNDERSCORE_PATH, 'test_underscore-v1.js'), ], version: 'v1.x.x', }, { flowVersion: { kind: 'ranged', lower: { major: 0, minor: 38, patch: 'x', prerel: null, }, upper: null, }, name: 'underscore', path: path.join( UNDERSCORE_PATH, 'flow_v0.38.x-', 'underscore_v1.x.x.js', ), scope: null, testFilePaths: [ path.join(UNDERSCORE_PATH, 'test_underscore-v1.js'), path.join(UNDERSCORE_PATH, 'flow_v0.38.x-', 'test_underscore.js'), ], version: 'v1.x.x', }, ]), ); }); it('fails on bad package dir name', async () => { const UNDERSCORE_PATH = path.join( FIXTURE_ROOT, 'bad-pkg-namever', 'definitions', 'npm', 'underscore_v1', ); const defsPromise1 = extractLibDefsFromNpmPkgDir( UNDERSCORE_PATH, null, 'underscore_v1', ); let err = null; try { await defsPromise1; } catch (e) { err = e; } expect(err && err.message).toBe( 'underscore_v1: Malformed npm package name! Expected the name to be ' + 'formatted as <PKGNAME>_v<MAJOR>.<MINOR>.<PATCH>', ); const errs = new Map(); const defsPromise2 = extractLibDefsFromNpmPkgDir( UNDERSCORE_PATH, null, 'underscore_v1', errs, ); expect(await defsPromise2).toEqual([]); expect([...errs.entries()]).toEqual([ [ 'underscore_v1', [ 'Malformed npm package name! Expected the name to be formatted as ' + '<PKGNAME>_v<MAJOR>.<MINOR>.<PATCH>', ], ], ]); }); it('fails on unexpected files', async () => { const UNDERSCORE_PATH = path.join( FIXTURE_ROOT, 'unexpected-pkg-file', 'definitions', 'npm', 'underscore_v1.x.x', ); const errs = new Map(); const defsPromise2 = extractLibDefsFromNpmPkgDir( UNDERSCORE_PATH, null, 'underscore_v1.x.x', errs, ); expect((await defsPromise2).length).toBe(2); expect([...errs.entries()]).toEqual([ [ 'underscore_v1.x.x/asdfdir', ['Flow versions must start with `flow_`'], ], [ path.join('underscore_v1.x.x', 'flow_v0.38.x-', 'asdf2'), [ 'Unexpected file. This directory can only contain test files or a ' + 'libdef file named `underscore_v1.x.x.js`.', ], ], [ path.join('underscore_v1.x.x', 'flow_v0.38.x-', 'asdf2dir'), [ 'Unexpected sub-directory. This directory can only contain test ' + 'files or a libdef file named `underscore_v1.x.x.js`.', ], ], ]); }); it('fails if flow versions overlap', async () => { const UNDERSCORE_PATH = path.join( FIXTURE_ROOT, 'overlapping-flow-versions', 'definitions', 'npm', 'underscore_v1.x.x', ); const defsPromise1 = extractLibDefsFromNpmPkgDir( UNDERSCORE_PATH, null, 'underscore_v1.x.x', ); let err = null; try { await defsPromise1; } catch (e) { err = e; } expect(err && err.message).toBe( 'npm/underscore_v1.x.x: Flow versions not disjoint!', ); const errs = new Map(); const defsPromise2 = extractLibDefsFromNpmPkgDir( UNDERSCORE_PATH, null, 'underscore_v1.x.x', errs, ); expect((await defsPromise2).length).toBe(2); expect([...errs.entries()]).toEqual([ ['npm/underscore_v1.x.x', ['Flow versions not disjoint!']], ]); }); it('fails if no libdefs are found', async () => { const UNDERSCORE_PATH = path.join( FIXTURE_ROOT, 'empty-libdef-dir', 'definitions', 'npm', 'underscore_v1.x.x', ); const defsPromise1 = extractLibDefsFromNpmPkgDir( UNDERSCORE_PATH, null, 'underscore_v1.x.x', ); let err = null; try { await defsPromise1; } catch (e) { err = e; } expect(err && err.message).toBe( 'npm/underscore_v1.x.x: No libdef files found!', ); const errs = new Map(); const defsPromise2 = extractLibDefsFromNpmPkgDir( UNDERSCORE_PATH, null, 'underscore_v1.x.x', errs, ); expect(await defsPromise2).toEqual([]); expect([...errs.entries()]).toEqual([ ['npm/underscore_v1.x.x', ['No libdef files found!']], ]); }); // Fails at random (see #1229) // it('fails if libdef not published on npm', async () => { // const TOTALLY_NOT_REAL_PKG_PATH = path.join( // FIXTURE_ROOT, // 'pkg-not-on-npm', // 'definitions', // 'npm', // 'totally-not-real-pkg_v1.x.x', // ); // const errs = new Map(); // const defsPromise2 = extractLibDefsFromNpmPkgDir( // TOTALLY_NOT_REAL_PKG_PATH, // null, // 'totally-not-real-pkg_v1.x.x', // errs, // true, // ); // expect((await defsPromise2).length).toBe(2); // expect([...errs.entries()]).toEqual([ // ['totally-not-real-pkg', ['Package does not exist on npm!']], // ]); // }); }); describe('findNpmLibDef', () => { describe('when no cached libDefs found', () => { it('returns null', async () => { jest.setTimeout(10000); const pkgName = 'jest-test-npm-package'; const pkgVersion = 'v1.0.0'; const flowVersion = {kind: 'all'}; const filtered = await findNpmLibDef(pkgName, pkgVersion, flowVersion); expect(filtered).toBeNull(); }); }); describe('when non-semver package provided', () => { it("doesn't throw error", async () => { const pkgName = 'flow-bin'; const pkgVersion = 'github:flowtype/flow-bin'; const flowVersion = {kind: 'all'}; let filtered; let error; try { filtered = await findNpmLibDef(pkgName, pkgVersion, flowVersion); } catch (e) { error = e; } expect(error).toBeUndefined(); expect(filtered).toBeNull(); }); }); }); describe('getInstalledNpmLibDefs', () => { const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'getInstalledNpmLibDefs'); it('returns an empty map when /flow-typed dir not present', async () => { const installedLibdefs = await getInstalledNpmLibDefs( path.join(FIXTURE_ROOT, 'emptyFlowTypedDir'), ); expect(installedLibdefs.size).toBe(0); }); it('finds unscoped libdefs', async () => { const installedLibdefs = await getInstalledNpmLibDefs( path.join(FIXTURE_ROOT, 'unscopedLibDefs'), ); expect(installedLibdefs.size).toBe(2); const semverLibDef = installedLibdefs.get( 'flow-typed/npm/semver_v5.1.x.js', ); // Since Flow doesn't understand Jest/Jasmine predicates, we wrap in a // vanilla one if (semverLibDef == null) { expect(semverLibDef).not.toEqual(null); } else { if (semverLibDef.kind !== 'LibDef') { expect(semverLibDef.kind).toBe('LibDef'); } else { expect(semverLibDef.libDef).toEqual({ flowVersion: { kind: 'specific', ver: { major: 0, minor: 27, patch: 0, prerel: null, }, }, name: 'semver', path: 'flow-typed/npm/semver_v5.1.x.js', scope: null, testFilePaths: [], version: 'v5.1.x', }); } } }); it('finds scoped libdefs', async () => { const installedLibdefs = await getInstalledNpmLibDefs( path.join(FIXTURE_ROOT, 'scopedLibDefs'), ); expect(installedLibdefs.size).toBe(1); const semverLibDef = installedLibdefs.get( 'flow-typed/npm/@kadira/storybook_v1.x.x.js', ); // Since Flow doesn't understand Jest/Jasmine predicates, we wrap in a // vanilla one if (semverLibDef == null) { expect(semverLibDef).not.toEqual(null); } else { if (semverLibDef.kind !== 'LibDef') { expect(semverLibDef.kind).toBe('LibDef'); } else { expect(semverLibDef.libDef).toEqual({ flowVersion: { kind: 'specific', ver: { major: 0, minor: 30, patch: 'x', prerel: null, }, }, name: 'storybook', path: 'flow-typed/npm/@kadira/storybook_v1.x.x.js', scope: '@kadira', testFilePaths: [], version: 'v1.x.x', }); } } }); it('finds libDef with fully-bounded semver range', async () => { const installedLibdefs = await getInstalledNpmLibDefs( path.join(FIXTURE_ROOT, 'unscopedLibDefs'), ); expect(installedLibdefs.size).toBe(2); const semverLibDef = installedLibdefs.get( 'flow-typed/npm/react-redux_v5.x.x.js', ); // Since Flow doesn't understand Jest/Jasmine predicates, we wrap in a // vanilla one if (semverLibDef == null) { expect(semverLibDef).not.toEqual(null); } else { if (semverLibDef.kind !== 'LibDef') { expect(semverLibDef.kind).toBe('LibDef'); } else { expect(semverLibDef.libDef).toEqual({ flowVersion: { kind: 'ranged', lower: { major: 0, minor: 30, patch: 'x', prerel: null, }, upper: { major: 0, minor: 52, patch: 'x', prerel: null, }, }, name: 'react-redux', path: 'flow-typed/npm/react-redux_v5.x.x.js', scope: null, testFilePaths: [], version: 'v5.x.x', }); } } }); }); describe('getNpmLibDefs', () => { const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'getNpmLibDefs'); it('parses npm scope name correctly', async () => { const FIXTURE_DIR = path.join(FIXTURE_ROOT, 'scoped-pkgs', 'definitions'); const libDefs = await getNpmLibDefs(FIXTURE_DIR); expect(libDefs.length).toBe(4); const scopedLibDefs = libDefs.filter(def => def.scope !== null); expect(scopedLibDefs.length).toBe(2); }); it('errors when an unexpected file is in definitions/npm/', async () => { const FIXTURE_DIR = path.join( FIXTURE_ROOT, 'unexpected-file', 'definitions', ); let err = null; try { await getNpmLibDefs(FIXTURE_DIR); } catch (e) { err = e; } const UNEXPECTED_FILE = path.join(FIXTURE_DIR, 'npm', 'unexpected-file'); expect(err && err.message).toBe( `${UNEXPECTED_FILE}: Expected only directories to be present in this ` + `directory.`, ); const errs = new Map(); const libDefs = await getNpmLibDefs(FIXTURE_DIR, errs); expect(libDefs.length).toEqual(2); expect([...errs.entries()]).toEqual([ [ UNEXPECTED_FILE, ['Expected only directories to be present in this directory.'], ], ]); }); }); describe('parsePkgNameVer', () => { it('parses non-wildcard libs', () => { expect(parsePkgNameVer('lib_v1.2.3', 'contexthere')).toEqual({ pkgName: 'lib', pkgVersion: { major: 1, minor: 2, patch: 3, }, }); expect(parsePkgNameVer('lib_v1.2.3-asdf', 'contexthere')).toEqual({ pkgName: 'lib', pkgVersion: { major: 1, minor: 2, patch: 3, prerel: 'asdf', }, }); }); it('parses wildcard minor libs', () => { expect(parsePkgNameVer('lib_v1.x.x', 'contexthere')).toEqual({ pkgName: 'lib', pkgVersion: { major: 1, minor: 'x', patch: 'x', }, }); expect(parsePkgNameVer('lib_v1.x.x-asdf', 'contexthere')).toEqual({ pkgName: 'lib', pkgVersion: { major: 1, minor: 'x', patch: 'x', prerel: 'asdf', }, }); }); it('parses wildcard patch libs', () => { expect(parsePkgNameVer('lib_v1.2.x', 'contexthere')).toEqual({ pkgName: 'lib', pkgVersion: { major: 1, minor: 2, patch: 'x', }, }); expect(parsePkgNameVer('lib_v1.2.x-asdf', 'contexthere')).toEqual({ pkgName: 'lib', pkgVersion: { major: 1, minor: 2, patch: 'x', prerel: 'asdf', }, }); }); it('errors on wildcard major', () => { expect(() => parsePkgNameVer('lib_vx.x.x', 'contexthere')).toThrow( 'lib_vx.x.x: Malformed npm package name! Expected the name to be ' + 'formatted as <PKGNAME>_v<MAJOR>.<MINOR>.<PATCH>', ); const errs = new Map(); expect(parsePkgNameVer('lib_vx.x.x', 'contexthere', errs)).toEqual(null); expect([...errs.entries()]).toEqual([ [ 'lib_vx.x.x', [ 'Malformed npm package name! Expected the name to be ' + 'formatted as <PKGNAME>_v<MAJOR>.<MINOR>.<PATCH>', ], ], ]); }); }); describe('validateVersionNumPart', () => { it('returns a number when a string-number is given', () => { expect(validateVersionNumPart('42', '', '')).toBe(42); }); it('errors when a non-number-string is given', () => { const errmsg = "contexthere: Invalid major number: 'x'. Expected a number."; expect(() => validateVersionNumPart('x', 'major', 'contexthere')).toThrow( errmsg, ); const errs = new Map(); expect(validateVersionNumPart('x', 'major', 'contexthere', errs)).toEqual( -1, ); expect([...errs.entries()]).toEqual([ ['contexthere', ["Invalid major number: 'x'. Expected a number."]], ]); }); }); describe('validateVersionPart', () => { it('returns "x" when given "x"', () => { expect(validateVersionPart('x', '', '')).toBe('x'); }); }); });
mwalkerwells/flow-typed
cli/src/lib/npm/__tests__/npmLibDefs-test.js
JavaScript
mit
16,661
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "google_chromeuxreport");
DataFire/Integrations
integrations/generated/google_chromeuxreport/index.js
JavaScript
mit
175
/* INITIALIZATIONS */ // Material design $.material.init(); // Initialize bootstrap tooltip // $('[data-toggle="popover"]').popover(); $(document).ready(function () { $('[data-toggle="tooltip"]').tooltip(); }); // Initialize toastr toastr.options = { "positionClass": "toast-top-left", "showDuration": "300", "hideDuration": "1000", "timeOut": "7000", "extendedTimeOut": "2000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }; // initialize sortable var el = document.getElementById('draggable'); /* initialize draggable elements*/ if (el != null) { Sortable.create(el, { animation: 150, draggable: ".drag" }); } // Mobile Menu $(function () { $('#navmenu').slicknav({ label: 'MENÜÜ' }); $("div.slicknav_menu").addClass("hidden-lg hidden-md"); $('.slicknav_menu').prepend('<a href="/" title=""><img class="logo-menu padding-5" src="/img/logo.png" alt="Logo"/></a>'); }); // Vertically center modals http://www.minimit.com/articles/solutions-tutorials/vertical-center-bootstrap-3-modals var modalVerticalCenterClass = ".modal"; function centerModals($element) { var $modals; if ($element.length) { $modals = $element; } else { $modals = $(modalVerticalCenterClass + ':visible'); } $modals.each(function () { var $clone = $(this).clone().css('display', 'block').appendTo('body'); var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2); top = top > 0 ? top : 0; $clone.remove(); $(this).find('.modal-content').css("margin-top", top); }); } $(modalVerticalCenterClass).on('show.bs.modal', function () { centerModals($(this)); }); $(window).on('resize', centerModals); /* Exercise scripts */ function loginRequired() { toastr.info('Vastamiseks peate sisse logima!'); } // user has chosen to see the answer var solutionSeen = false; function showAnswer(id, type) { id = parseInt(id); type = parseInt(type); if (solutionSeen) return; $(".se-pre-con").fadeIn("fast"); $.ajax({ url: "/answer/show/" + id, type: "post", dataType: "JSON", data: { '_token': $('input[name="_token"]').val() }, success: function (data) { var answers = JSON.parse(data.answers); var answersId = JSON.parse(data.answers_id); var listElements = null; switch (type) { case 1 : var inputField = document.getElementById('answer-input'); answers.push(inputField.value.trim()); inputField.disabled = true; inputField.value = answers[0]; inputField.className += " correct-answer"; break; case 2 : listElements = document.querySelectorAll('input[name = "answer"]'); for (var i = 0; i < listElements.length; i++) { listElements[i].disabled = true; if (listElements[i].id == answersId[0]) { listElements[i].checked = true; } else listElements[i].checked = false; } break; case 3 : listElements = document.querySelectorAll('input[name = "answer"]'); for (var i = 0; i < listElements.length; i++) { listElements[i].disabled = true; if (answersId.indexOf(parseInt(listElements[i].id)) >= 0) { listElements[i].checked = true; } else { listElements[i].checked = false; } } break; case 4 : listElements = document.getElementsByClassName("drag-item"); for (var i = 0; i < answers.length; i++) { listElements[i].innerText = ""; listElements[i].insertAdjacentHTML('beforeend', answers[i]); listElements[i].className = "drag-item"; } break; } if (data.solution != null && data.solution != "") { document.getElementById('solution-text').insertAdjacentHTML('beforeend', data.solution); document.getElementById('solution').style.display = "block"; reloadWiris(); } document.getElementById('submit-answer').disabled = true; solutionSeen = true; if (data.seenOrSolved == false) { toastr.warning('Selle ülesande eest ei ole enam võimalik punkte saada.'); } $(".se-pre-con").fadeOut("slow"); }, error: function (xhr) { if (xhr.status == 420) { toastr.error("Sessioon on aegunud. Palun värskendage lehte (F5)!") } else { toastr.error('Viga ühendusega ( kood ' + xhr.status + ")"); } $(".se-pre-con").fadeOut("slow"); } }); } // User has chosen to submit the exercise answer function submitAnswer(event, id, type) { id = parseInt(id); type = parseInt(type); event.preventDefault(); answers = []; switch (type) { case 1 : answers.push(document.getElementById("answer-input").value.trim()); break; case 2 : var input = document.querySelector('input[name = "answer"]:checked'); if (input != null) answers.push(input.id); else { toastr.info('Vastamiseks on tarvis sisestada vastus.'); return; } break; case 3 : var listElements = document.querySelectorAll('input[name = "answer"]:checked'); for (var i = 0; i < listElements.length; i++) { answers.push(listElements[i].id) } break; case 4 : var listElements = document.getElementsByClassName("drag-item"); for (var i = 0; i < listElements.length; i++) { answers.push(listElements[i].id); } break; } var postArray = JSON.stringify(answers); var form = document.getElementById('submit-answer').form; startLoader(form); $.ajax({ url: "/answer/check/" + id, type: "post", dataType: "JSON", data: { '_token': $('input[name="_token"]').val(), 'answers': postArray }, success: function (data) { if (data.response) { var points = document.getElementById('user-points'); toastr.success('Te vastasite õigesti!'); if (data.points != points.innerHTML) { $('.user-bar .fa-trophy').fadeOut(0).hide(function () { $('.user-bar .fa-arrow-up').fadeIn(800).delay(3000).fadeOut(800).queue(function () { $('.user-bar .fa-trophy').fadeIn(0); }) }); } if (data.solution != null && data.solution != "") { document.getElementById('solution-text').insertAdjacentHTML('beforeend', data.solution); document.getElementById('solution').style.display = "block"; reloadWiris(); } points.innerText = data.points; $("#active").removeClass("btn-not-solved").addClass("btn-solved"); document.getElementById('submit-answer').disabled = true; } else { $("#wrong-answer").modal({ keyboard: false, backdrop: 'static' }) } endLoader(form); }, error: function (xhr) { if (xhr.status == 420) { toastr.error("Sessioon on aegunud. Palun värskendage lehte (F5)") } else { toastr.error('Viga ühendusega ( kood ' + xhr.status + ")"); } endLoader(form); } }); } /* image zoom on click*/ $('#ex-content').find('img').addClass('ex-image'); $(function () { $('.ex-image').on('click', function () { $('.enlargeImageModalSource').attr('src', $(this).attr('src')); $('#enlargeImageModal').modal(); }); }); function startLoader(form) { width = $(form).find("button, input[type='submit']").find(".md-spinner-text").width(); $(form).find('.md-spinner').fadeIn("fast").css({"display": "block", "min-width": width}); $(form).find(".md-spinner-text").hide(); } function endLoader(form) { $(form).find('.md-spinner').fadeOut("slow", function () { $(form).find(".md-spinner-text").show(); }); } /* search bar*/ // modified from http://codeconvey.com/expanding-search-bar-with-jquery/ $(document).ready(function () { var searchIcon = $('.search-icon'); var searchInput = $('.search-input'); var searchBox = $('.search'); var isOpen = false; $(document).mouseup(function () { if (isOpen == true) { searchInput.val(''); searchBox.removeClass('search-open'); isOpen = false; } }); searchIcon.mouseup(function () { return false; }); searchBox.mouseup(function () { return false; }); searchIcon.click(function () { if (isOpen == false) { searchBox.addClass('search-open'); isOpen = true; } else { if ($("#search").val() != "") { var form = document.getElementById("search-form"); startLoader(form); form.submit(); } else { searchBox.removeClass('search-open'); isOpen = false; } } }); }); function reloadWiris() { var script = document.createElement('script'); script.id = 'wiris'; script.type = 'text/javascript'; script.src = " /lib/js/plugins/tiny_mce_wiris/integration/WIRISplugins.js?viewer=image"; $('#wiris').remove(); document.getElementsByTagName('head')[0].appendChild(script); } /* registration */ function checkAvailabilityUser(id) { var username = $("#username").val(); if (username.length > 0) { var form = document.getElementById('username-form'); jQuery.ajax({ url: "/availability/username/"+id, data: { _token: $('input[name="_token"]').val(), username: username }, type: "POST", success: function (data) { var icon = document.getElementById('user-status'); if (data.response == "true") { form.className = "form-group has-success"; icon.innerHTML = "<span class='glyphicon glyphicon-ok' style='margin-top: 15px'></span>"; document.getElementById('username-error').innerHTML = "" } else { form.className = "form-group has-error"; icon.innerHTML = "<span class='glyphicon glyphicon-remove' style='margin-top: 15px'></span>"; document.getElementById('username-error').innerHTML = '<span class="help-block help-error"><strong>Selline kasutajanimi on juba olemas</strong></span>'; } }, error: function () { } }); } } function checkAvailabilityEmail(id) { var email = $("#email").val(); var icon = document.getElementById('email-status'); var form = document.getElementById('email-form'); if (validateEmail(email)) { jQuery.ajax({ url: "/availability/email/"+id, data: { _token: $('input[name="_token"]').val(), email: email }, type: "POST", success: function (data) { if (data.response == "true") { form.className = "form-group has-success"; icon.innerHTML = "<span class='glyphicon glyphicon-ok' style='margin-top: 15px'></span>"; document.getElementById('email-error').innerHTML = "" } else { form.className = "form-group has-error"; icon.innerHTML = "<span class='glyphicon glyphicon-remove' style='margin-top: 15px'></span>"; document.getElementById('email-error').innerHTML = '<span class="help-block help-error"><strong>Selline email on juba kasutuses</strong></span>'; } }, error: function () { } }); } else { form.className = "form-group has-error"; icon.innerHTML = "<span class='glyphicon glyphicon-remove' style='margin-top: 15px'></span>"; document.getElementById('email-error').innerHTML = '<span class="help-block help-error"><strong>See ei ole korrektne email</strong></span>'; } } function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function validateField(fieldName) { var value = $("#" + fieldName).val(); var form = document.getElementById(fieldName + '-form'); var errorBlock = document.getElementById(fieldName + '-error'); var icon = document.getElementById(fieldName + '-status'); var errorMsg = "See väli tuleb täita"; var minLength = 0; if (fieldName == "password") { errorMsg = "Salasõna peab olema vähemalt 6 tähemärki"; minLength = 5; } if (value.length > minLength) { form.className = "form-group has-success"; icon.innerHTML = "<span class='glyphicon glyphicon-ok' style='margin-top: 15px'></span>"; errorBlock.innerHTML = "" } else { form.className = "form-group has-error"; icon.innerHTML = "<span class='glyphicon glyphicon-remove' style='margin-top: 15px'></span>"; errorBlock.innerHTML = '<span class="help-block help-error"><strong>' + errorMsg + '</strong></span>'; } } $(document).ready(function () { $("#password-confirm").keyup(validatePasswordMatching); }); function validatePasswordMatching() { var form = document.getElementById('password-confirm-form'); var errorBlock = document.getElementById('password-confirm-error'); var icon = document.getElementById('password-confirm-status'); form.className = "form-group has-error"; var pw1 = $("#password-confirm").val(); if (pw1.length >= 6) { if ($("#password").val() == pw1) { form.className = "form-group has-success"; icon.innerHTML = "<span class='glyphicon glyphicon-ok' style='margin-top: 15px'></span>"; errorBlock.innerHTML = "" } else { form.className = "form-group has-error"; icon.innerHTML = "<span class='glyphicon glyphicon-remove' style='margin-top: 15px'></span>"; errorBlock.innerHTML = '<span class="help-block has-error help-error"><strong>Salasõnad ei klapi</strong></span>'; } } else { form.className = "form-group has-error"; icon.innerHTML = "<span class='glyphicon glyphicon-remove' style='margin-top: 15px'></span>"; errorBlock.innerHTML = '<span class="help-block help-error"><strong>Salasõna peab olema vähemalt 6 tähemärki</strong></span>'; } }
mpeedosk/nupuvere
public/js/scripts.js
JavaScript
mit
15,914
import Ember from 'ember'; import ResetScrollMixin from '../../../mixins/reset-scroll'; import { module, test } from 'qunit'; module('ResetScrollMixin'); // Replace this with your real tests. test('it works', function(assert) { var ResetScrollObject = Ember.Object.extend(ResetScrollMixin); var subject = ResetScrollObject.create(); assert.ok(subject); });
felixrieseberg/liquid-windows-store
tests/unit/mixins/reset-scroll-test.js
JavaScript
mit
365
var express = require('express'), bodyParser = require('body-parser'), morgan = require('morgan'), config = require('./config'), constants = require('./config/const'), expressError = require('express-error') app = express(); // Parse bodies! app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Logging ( morgan can do log rotation ) app.use(morgan('dev')); // View Helpers app.use(function(req, res, next) { res.locals.version = config.version; next(); }); // Set routes app.use('/api/v1', require('./routes/v1/api')); // Handle 500 errors in dev mode if (config.enviroment === constants.DEV) { app.use(expressError.express3({ contextLinesCount: 5, handleUncaughtException: true })); } // Serve static files.. usually nginx will do that but for now // it's ok like that if (config.enviroment === constants.PROD) { app.use(express.static(constants.PROD_FOLDER)); } else { app.use(express.static(constants.DEV_FOLDER)); } // Runs app var server = app.listen(config.port, function() { console.log('App server listening on port ' + server.address().port); });
aiboy/COD.js
server.js
JavaScript
mit
1,210
import test from 'ava'; import { CLIEngine } from 'eslint'; import path from 'path'; const lint = (code) => { const linter = new CLIEngine({ configFile: path.resolve(__dirname, '..', '.eslintrc.js'), }); const report = linter.executeOnText(code); return { errorCount: report.errorCount, violatedRuleIds: report.results[0].messages.map(message => message.ruleId), }; }; test('tabs indenting is forbidden', (t) => { const code = ` import process from 'process'; if (process.cwd()) { \tprocess.cwd(); } `; t.snapshot(lint(code)); }); test('double-quoted strings are forbidden', (t) => { const code = ` import process from "process"; process.cwd(); `; t.snapshot(lint(code)); });
LidskaSila/eslint-config
__tests__/incorrect.js
JavaScript
mit
713
Template.CellList.onCreated(function(){ var self = this; self.autorun(function(){ self.subscribe('cells'); }); }); Template.CellList.helpers({ cells:()=>{ return Cell.find({},{sort: {group: 1, name: 1}}); } });
rassweiler/kr-display
client/cells/CellList.js
JavaScript
mit
220
/*****************************************************************************/ /* SapHanaConfig: Event Handlers */ /*****************************************************************************/ import _ from 'underscore'; Template.SapHanaConfig.events({ 'click #testConnection': (e,tmpl) => { //var view = Blaze.render(Template.Loading, document.getElementById('spinner')); var serverHostUrl = $('#serverHostUrl').val(); var protocol = $("[name='protocol']:checked").val(); var companyId = $('#companyId').val(); var username = $('#username').val(); var password = $('#password').val(); if(serverHostUrl.length < 1) { swal("Validation error", `Please enter the IP Address & Port of your SAP HANA instance`, "error"); return } else if(username.length < 1) { swal("Validation error", `Please enter the Successfactors username`, "error"); return } else if(password.length < 1) { swal("Validation error", `Please enter the Successfactors password`, "error"); return } //-- let businessUnitId = Session.get('context') let hanaConfig = { serverHostUrl : serverHostUrl, protocol : protocol, companyId : companyId, businessId: businessUnitId, username : username, password : password, } tmpl.$('#testConnection').text('Connecting ... '); tmpl.$('#testConnection').attr('disabled', true); //-- Meteor.call('hanaIntegration/testConnection', businessUnitId, hanaConfig, (err, res) => { tmpl.$('#testConnection').text('Test Connection'); tmpl.$('#testConnection').removeAttr('disabled'); if (!err){ let responseAsObj = JSON.parse(res) let dialogType = (responseAsObj.status === true) ? "success" : "error" swal("Connection Status", responseAsObj.message, dialogType); } else { swal("Server error", `Please try again at a later time`, "error"); } }); }, 'blur #tab1-data-body tr input': (e, tmpl) => { let domElem = e.currentTarget; let unitId = domElem.getAttribute('id') let unitGlAccountCode = domElem.value || "" let units = Template.instance().units.get() let currentUnit = _.find(units, function (o) { return o._id === unitId; }) // currentUnit.costCenterCode = unitGlAccountCode currentUnit.successFactors = currentUnit.successFactors || {} currentUnit.successFactors.costCenter = currentUnit.successFactors.costCenter || {} currentUnit.successFactors.costCenter.code = unitGlAccountCode Template.instance().units.set(units); }, 'blur #tab2-data-body tr input': (e, tmpl) => { let domElem = e.currentTarget; let paytypeId = domElem.getAttribute('id') let creditGlAccountCode = domElem.value || "" let payTypes = Template.instance().payTypes.get() let currentPaytype = _.find(payTypes, function (o) { return o._id === paytypeId; }) currentPaytype.creditGLAccountCode = creditGlAccountCode Template.instance().payTypes.set(payTypes); }, 'click #saveSapCostCenterCodes': (e, tmpl) => { let businessUnitId = Session.get('context') let theUnits = Template.instance().units.get() Meteor.call("hanaIntegration/updateUnitCostCenters", businessUnitId, theUnits, (err, res) => { if(res) { swal('Success', 'Cost center codes were successfully updated', 'success') } else { console.log(err); swal('Error', err.reason, 'error') } }) }, // 'click #savePaytypes': (e, tmpl) => { // let businessUnitId = Session.get('context') // let theUnits = Template.instance().units.get() // Meteor.call("sapB1integration/updateUnitCostCenters", businessUnitId, theUnits, (err, res) => { // if(res) { // swal('Success', 'Cost center codes were successfully updated', 'success') // } else { // console.log(err); // swal('Error', err.reason, 'error') // } // }) // }, 'click #savePayTypesGlAccounts': (e, tmpl) => { let businessUnitId = Session.get('context') let payTypeCreditGlAccountCode = [] let payTypeDebitGlAccountCode = [] // let payTypeProjectDebitAccountCode = [] // let payTypeProjectCreditAccountCode = [] $('input[name=payTypeCreditGlAccountCode]').each(function(anInput) { payTypeCreditGlAccountCode.push($(this).val()) }) $('input[name=payTypeDebitGlAccountCode]').each(function(anInput) { payTypeDebitGlAccountCode.push($(this).val()) }) // $('input[name=payTypeProjectDebitAccountCode]').each(function(anInput) { // payTypeProjectDebitAccountCode.push($(this).val()) // }) // $('input[name=payTypeProjectCreditAccountCode]').each(function(anInput) { // payTypeProjectCreditAccountCode.push($(this).val()) // }) let thePayTypes = Template.instance().payTypes.get().map((aPayType, index) => { return { payTypeId: aPayType.payTypeId, payTypeCreditAccountCode: payTypeCreditGlAccountCode[index], payTypeDebitAccountCode: payTypeDebitGlAccountCode[index], // payTypeProjectCreditAccountCode: payTypeProjectCreditAccountCode[index], // payTypeProjectDebitAccountCode: payTypeProjectDebitAccountCode[index] } }) // console.log(`The thePayTypes: ${JSON.stringify(thePayTypes)}`) //-- let taxesCreditGlAccountCode = [] let taxesDebitGlAccountCode = [] $('input[name=taxesCreditGlAccountCode]').each(function(anInput) { taxesCreditGlAccountCode.push($(this).val()) }) $('input[name=taxesDebitGlAccountCode]').each(function(anInput) { taxesDebitGlAccountCode.push($(this).val()) }) let theTaxes = Template.instance().taxes.get().map((aPayType, index) => { return { payTypeId: aPayType.payTypeId, payTypeCreditAccountCode: taxesCreditGlAccountCode[index], payTypeDebitAccountCode: taxesDebitGlAccountCode[index], } }) //-- let pensionsCreditGlAccountCode = [] let pensionsDebitGlAccountCode = [] $('input[name=pensionsCreditGlAccountCode]').each(function(anInput) { pensionsCreditGlAccountCode.push($(this).val()) }) $('input[name=pensionsDebitGlAccountCode]').each(function(anInput) { pensionsDebitGlAccountCode.push($(this).val()) }) let thePensions = [] Template.instance().pensions.get().forEach((aPension, index) => { const sapPensionPaymentConfig = { pensionId: aPension.pensionId, pensionCode: aPension.pensionCode, payTypeCreditAccountCode: pensionsCreditGlAccountCode[index], payTypeDebitAccountCode: pensionsDebitGlAccountCode[index], } thePensions.push(sapPensionPaymentConfig) }) Meteor.call("hanaIntegration/updatePayTypeGlAccountCodes", businessUnitId, thePayTypes, theTaxes, thePensions, (err, res) => { if(res) { console.log(JSON.stringify(res)); swal('Success', 'Pay type account codes were successfully updated', 'success') } else{ console.log(err); } }) } }); /*****************************************************************************/ /* SapHanaConfig: Helpers */ /*****************************************************************************/ Template.SapHanaConfig.helpers({ 'companyConnectionInfo': function() { return Template.instance().sapHanaConfig.get() }, 'costCenters': function () { return Template.instance().units.get() }, 'payTypes': function () { return Template.instance().payTypes.get() }, 'hanaGlAccounts': function() { return Template.instance().hanaGlAccounts.get() }, 'isFetchingPayTypes': function() { return Template.instance().isFetchingPayTypes.get() }, // "paytype": () => { // return Template.instance().paytypes.get() // }, "taxes": () => { return Template.instance().taxes.get() }, "pensions": () => { return Template.instance().pensions.get() }, "getCostCenterOrgChartParents": (unit) => { return Template.instance().getParentsText(unit) } // 'isFetchingHanaGlAccounts': function() { // return Template.instance().isFetchingSapHanaGlAccounts.get() // }, // selectedCostCenter: function (context, val) { // if(Template.instance().units.get()){ // // let units = Template.instance().units.get(); // units.code === val ? selected="selected" : ''; // } // }, }); /*****************************************************************************/ /* SapHanaConfig: Lifecycle Hooks */ /*****************************************************************************/ Template.SapHanaConfig.onCreated(function () { let self = this; let businessUnitId = Session.get('context'); self.subscribe('SapHanaIntegrationConfigs', businessUnitId); self.subscribe('getCostElement', businessUnitId); self.subscribe("PayTypes", businessUnitId); self.subscribe('taxes', businessUnitId) self.subscribe('pensions', businessUnitId) self.sapHanaConfig = new ReactiveVar() self.units = new ReactiveVar() self.payTypes = new ReactiveVar() self.taxes = new ReactiveVar() self.pensions = new ReactiveVar() self.hanaGlAccounts = new ReactiveVar() self.isFetchingPayTypes = new ReactiveVar(false) self.isFetchingSapHanaGlAccounts = new ReactiveVar(false) self.getParentsText = (unit) => {// We need parents 2 levels up let parentsText = '' if(unit.parentId) { let possibleParent = EntityObjects.findOne({_id: unit.parentId}) if(possibleParent) { parentsText += possibleParent.name if(possibleParent.parentId) { let possibleParent2 = EntityObjects.findOne({_id: possibleParent.parentId}) if(possibleParent2) { parentsText += ' >> ' + possibleParent2.name return parentsText } return '' } else return parentsText } else return '' } else return '' } // self.autorun(function() { // if (Template.instance().subscriptionsReady()){ // let config = SapHanaIntegrationConfigs.findOne({businessId: businessUnitId}) // self.sapHanaConfig.set(config) // self.payTypes.set(PayTypes.find({ // businessId: businessUnitId // }).fetch()) // if(config) { // self.isFetchingSapHanaGlAccounts.set(true) // Meteor.call('hanaIntegration/fetchGlAccounts', businessUnitId, (err, glAccounts) => { // console.log(`err: `, err) // self.isFetchingSapHanaGlAccounts.set(false) // if (!err) { // self.hanaGlAccounts.set(glAccounts) // } else { // swal("Server error", `Please try again at a later time`, "error"); // } // }); // } // } // }); self.autorun(function() { if (Template.instance().subscriptionsReady()){ let config = SapHanaIntegrationConfigs.findOne({businessId: businessUnitId}) self.sapHanaConfig.set(config) self.units.set(EntityObjects.find({otype: 'Unit'}).fetch()); self.payTypes.set(PayTypes.find({'status': 'Active'}).fetch().map(payType => { if(config) { let currentPayType = _.find(config.payTypes, function (oldPayType) { return oldPayType.payTypeId === payType._id; }) if(currentPayType) { _.extend(payType, currentPayType) } } else { } payType.payTypeId = payType._id return payType })); self.taxes.set(Tax.find({}).fetch().map(payType => { if(config) { let currentPayType = _.find(config.taxes, function (oldPayType) { return oldPayType.payTypeId === payType._id; }) if(currentPayType) { _.extend(payType, currentPayType) } } else { } payType.payTypeId = payType._id return payType })); let thePensions = [] Pensions.find({}).fetch().forEach(aPension => { if(config) { let sapEmployeePensionPayment = _.find(config.pensions, function (oldPayType) { return oldPayType.pensionId === aPension._id && oldPayType.pensionCode === aPension.code + "_EE"; }) let employeePension = {...aPension} if(sapEmployeePensionPayment) { _.extend(employeePension, sapEmployeePensionPayment) } employeePension.pensionId = aPension._id employeePension.pensionCode = aPension.code + "_EE" thePensions.push(employeePension) //-- let employerPension = {...aPension} let sapEmployerPensionPayment = _.find(config.pensions, function (oldPayType) { return oldPayType.pensionId === aPension._id && oldPayType.pensionCode === aPension.code + "_ER"; }) if(sapEmployerPensionPayment) { _.extend(employerPension, sapEmployerPensionPayment) } employerPension.pensionId = aPension._id employerPension.pensionCode = aPension.code + "_ER" thePensions.push(employerPension) } }); self.pensions.set(thePensions) } }) }); Template.SapHanaConfig.onRendered(function () { $('select.dropdown').dropdown(); $("html, body").animate({ scrollTop: 0 }, "slow"); var self = this; var oldIndex, newIndex; // fix a little rendering bug by clicking on step 1 $('#step1').click(); $('#progress-wizard-new').bootstrapWizard({ onTabShow: function (tab, navigation, index) { tab.prevAll().addClass('done'); tab.nextAll().removeClass('done'); tab.removeClass('done'); var $total = navigation.find('li').length; var $current = index + 1; if ($current >= $total) { $('#progress-wizard-new').find('.wizard .next').addClass('hide'); $('#progress-wizard-new').find('.wizard .finish').removeClass('hide'); } else { $('#progress-wizard-new').find('.wizard .next').removeClass('hide'); $('#progress-wizard-new').find('.wizard .finish').addClass('hide'); } var $percent = ($current / $total) * 100; $('#progress-wizard-new').find('.progress-bar').css('width', $percent + '%'); }, onTabClick: function (tab, navigation, index) { return true; } }); }); Template.SapHanaConfig.onDestroyed(function () { });
c2gconsulting/bp-core
main/app/client/templates/saphana_config/saphana_config.js
JavaScript
mit
16,278
var _ = require('lodash') var NZD = require('./dubbo') var Yaml = require('./yaml') var Oauth = require('./oauth') var request = require('../../promise').request var debug = require('debug')('zcyjiggly:remote') var httpProxy = require('http-proxy') var Promise = require('bluebird') var proxy = httpProxy.createProxyServer() var config = require('../../config') /** * 调用远程的数据 * 主要是连接dev zookeeper获取各个模块的接口 */ module.exports = { init: NZD.init, // 获取组件的数据 getCompData: function (path, params) { // 不服务器模拟 if (!config.dubbo) { return Promise.resolve({}) } return NZD.getEntry() .then(function (nzdEntry) { return Yaml.getService(nzdEntry, path, params) }) .then(function (result) { debug('request component done', path) if (!result) { return } var _SERVICES_ = _.assign(_.omit(result, '_DATA_'), { _USER_: Oauth.getCurrentUser() }) return _.assign(result._DATA_, { _SERVICES_: _SERVICES_ }) }).catch(function (err) { debug('getCompData error: ' + path, err) }) }, // 代理http请求 proxyRequest: function (req, res) { return new Promise(function (resolve, reject) { var uriPath = req.path if (uriPath == '/') { resolve(false) return } var domainUrl = Oauth.getProxyTarget(req.path) if (!domainUrl) { resolve(false) return } proxy.on('error', function (error) { debug('proxy error:' + domainUrl, error) reject() }) return Oauth.getAuthorization() .then(function (authorizationValue) { debug('start proxy request', domainUrl, req.path) proxy.web(req, res, {target: domainUrl, changeOrigin: true}) proxy.on('proxyReq', function (proxyReq, req, res, options) { proxyReq.setHeader('Authorization', authorizationValue) }) return true }) }) }, isComponent: Yaml.isComponent }
ZCY-frontend/jiggly
lib/data_provider/remote/index.js
JavaScript
mit
2,114
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" > <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" > <meta name="ROBOTS" content="NOARCHIVE"> <link rel="icon" type="image/vnd.microsoft.icon" href="https://ssl.gstatic.com/codesite/ph/images/phosting.ico"> <script type="text/javascript"> var codesite_token = null; var CS_env = {"assetHostPath": "https://ssl.gstatic.com/codesite/ph", "domainName": null, "profileUrl": null, "token": null, "relativeBaseUrl": "", "projectHomeUrl": "/p/base2", "loggedInUserEmail": null, "assetVersionPath": "https://ssl.gstatic.com/codesite/ph/16296466298460697337", "projectName": "base2"}; var _gaq = _gaq || []; _gaq.push( ['siteTracker._setAccount', 'UA-18071-1'], ['siteTracker._trackPageview']); _gaq.push( ['projectTracker._setAccount', 'UA-2328199-1'], ['projectTracker._trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga); })(); </script> <title>base2-legacy.js - base2 - A standards-based JavaScript Library. - Google Project Hosting </title> <link type="text/css" rel="stylesheet" href="https://ssl.gstatic.com/codesite/ph/16296466298460697337/css/core.css"> <link type="text/css" rel="stylesheet" href="https://ssl.gstatic.com/codesite/ph/16296466298460697337/css/ph_detail.css" > <link type="text/css" rel="stylesheet" href="https://ssl.gstatic.com/codesite/ph/16296466298460697337/css/d_sb.css" > <!--[if IE]> <link type="text/css" rel="stylesheet" href="https://ssl.gstatic.com/codesite/ph/16296466298460697337/css/d_ie.css" > <![endif]--> <style type="text/css"> .menuIcon.off { background: no-repeat url(https://ssl.gstatic.com/codesite/ph/images/dropdown_sprite.gif) 0 -42px } .menuIcon.on { background: no-repeat url(https://ssl.gstatic.com/codesite/ph/images/dropdown_sprite.gif) 0 -28px } .menuIcon.down { background: no-repeat url(https://ssl.gstatic.com/codesite/ph/images/dropdown_sprite.gif) 0 0; } tr.inline_comment { background: #fff; vertical-align: top; } div.draft, div.published { padding: .3em; border: 1px solid #999; margin-bottom: .1em; font-family: arial, sans-serif; max-width: 60em; } div.draft { background: #ffa; } div.published { background: #e5ecf9; } div.published .body, div.draft .body { padding: .5em .1em .1em .1em; max-width: 60em; white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; word-wrap: break-word; font-size: 1em; } div.draft .actions { margin-left: 1em; font-size: 90%; } div.draft form { padding: .5em .5em .5em 0; } div.draft textarea, div.published textarea { width: 95%; height: 10em; font-family: arial, sans-serif; margin-bottom: .5em; } .nocursor, .nocursor td, .cursor_hidden, .cursor_hidden td { background-color: white; height: 2px; } .cursor, .cursor td { background-color: darkblue; height: 2px; display: ''; } .list { border: 1px solid white; border-bottom: 0; } </style> </head> <body class="t4"> <script type="text/javascript"> window.___gcfg = {lang: 'en'}; (function() {var po = document.createElement("script"); po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s); })(); </script> <div class="headbg"> <div id="gaia"> <span> <a href="#" id="projects-dropdown" onclick="return false;"><u>My favorites</u> <small>&#9660;</small></a> | <a href="https://www.google.com/accounts/ServiceLogin?service=code&amp;ltmpl=phosting&amp;continue=https%3A%2F%2Fcode.google.com%2Fp%2Fbase2%2Fsource%2Fbrowse%2Fversion%2F1.0.2%2Fsrc%2Fbase2-legacy.js&amp;followup=https%3A%2F%2Fcode.google.com%2Fp%2Fbase2%2Fsource%2Fbrowse%2Fversion%2F1.0.2%2Fsrc%2Fbase2-legacy.js" onclick="_CS_click('/gb/ph/signin');"><u>Sign in</u></a> </span> </div> <div class="gbh" style="left: 0pt;"></div> <div class="gbh" style="right: 0pt;"></div> <div style="height: 1px"></div> <!--[if lte IE 7]> <div style="text-align:center;"> Your version of Internet Explorer is not supported. Try a browser that contributes to open source, such as <a href="http://www.firefox.com">Firefox</a>, <a href="http://www.google.com/chrome">Google Chrome</a>, or <a href="http://code.google.com/chrome/chromeframe/">Google Chrome Frame</a>. </div> <![endif]--> <table style="padding:0px; margin: 0px 0px 10px 0px; width:100%" cellpadding="0" cellspacing="0" itemscope itemtype="http://schema.org/CreativeWork"> <tr style="height: 58px;"> <td id="plogo"> <link itemprop="url" href="/p/base2"> <a href="/p/base2/"> <img src="https://ssl.gstatic.com/codesite/ph/images/defaultlogo.png" alt="Logo" itemprop="image"> </a> </td> <td style="padding-left: 0.5em"> <div id="pname"> <a href="/p/base2/"><span itemprop="name">base2</span></a> </div> <div id="psum"> <a id="project_summary_link" href="/p/base2/"><span itemprop="description">A standards-based JavaScript Library.</span></a> </div> </td> <td style="white-space:nowrap;text-align:right; vertical-align:bottom;"> <form action="/hosting/search"> <input size="30" name="q" value="" type="text"> <input type="submit" name="projectsearch" value="Search projects" > </form> </tr> </table> </div> <div id="mt" class="gtb"> <a href="/p/base2/" class="tab ">Project&nbsp;Home</a> <a href="/p/base2/issues/list" class="tab ">Issues</a> <a href="/p/base2/source/checkout" class="tab active">Source</a> <div class=gtbc></div> </div> <table cellspacing="0" cellpadding="0" width="100%" align="center" border="0" class="st"> <tr> <td class="subt"> <div class="st2"> <div class="isf"> <span class="inst1"><a href="/p/base2/source/checkout">Checkout</a></span> &nbsp; <span class="inst2"><a href="/p/base2/source/browse/">Browse</a></span> &nbsp; <span class="inst3"><a href="/p/base2/source/list">Changes</a></span> &nbsp; </form> <script type="text/javascript"> function codesearchQuery(form) { var query = document.getElementById('q').value; if (query) { form.action += '%20' + query; } } </script> </div> </div> </td> <td align="right" valign="top" class="bevel-right"></td> </tr> </table> <script type="text/javascript"> var cancelBubble = false; function _go(url) { document.location = url; } </script> <div id="maincol" > <div class="expand"> <div id="colcontrol"> <style type="text/css"> #file_flipper { white-space: nowrap; padding-right: 2em; } #file_flipper.hidden { display: none; } #file_flipper .pagelink { color: #0000CC; text-decoration: underline; } #file_flipper #visiblefiles { padding-left: 0.5em; padding-right: 0.5em; } </style> <table id="nav_and_rev" class="list" cellpadding="0" cellspacing="0" width="100%"> <tr> <td nowrap="nowrap" class="src_crumbs src_nav" width="33%"> <strong class="src_nav">Source path:&nbsp;</strong> <span id="crumb_root"> <a href="/p/base2/source/browse/">svn</a>/&nbsp;</span> <span id="crumb_links" class="ifClosed"><a href="/p/base2/source/browse/version/">version</a><span class="sp">/&nbsp;</span><a href="/p/base2/source/browse/version/1.0.2/">1.0.2</a><span class="sp">/&nbsp;</span><a href="/p/base2/source/browse/version/1.0.2/src/">src</a><span class="sp">/&nbsp;</span>base2-legacy.js</span> </td> <td nowrap="nowrap" width="33%" align="right"> <table cellpadding="0" cellspacing="0" style="font-size: 100%"><tr> <td class="flipper"><b>r310</b></td> </tr></table> </td> </tr> </table> <div class="fc"> <style type="text/css"> .undermouse span { background-image: url(https://ssl.gstatic.com/codesite/ph/images/comments.gif); } </style> <table class="opened" id="review_comment_area" ><tr> <td id="nums"> <pre><table width="100%"><tr class="nocursor"><td></td></tr></table></pre> <pre><table width="100%" id="nums_table_0"><tr id="gr_svn310_1" ><td id="1"><a href="#1">1</a></td></tr ><tr id="gr_svn310_2" ><td id="2"><a href="#2">2</a></td></tr ><tr id="gr_svn310_3" ><td id="3"><a href="#3">3</a></td></tr ><tr id="gr_svn310_4" ><td id="4"><a href="#4">4</a></td></tr ><tr id="gr_svn310_5" ><td id="5"><a href="#5">5</a></td></tr ><tr id="gr_svn310_6" ><td id="6"><a href="#6">6</a></td></tr ><tr id="gr_svn310_7" ><td id="7"><a href="#7">7</a></td></tr ><tr id="gr_svn310_8" ><td id="8"><a href="#8">8</a></td></tr ><tr id="gr_svn310_9" ><td id="9"><a href="#9">9</a></td></tr ><tr id="gr_svn310_10" ><td id="10"><a href="#10">10</a></td></tr ><tr id="gr_svn310_11" ><td id="11"><a href="#11">11</a></td></tr ><tr id="gr_svn310_12" ><td id="12"><a href="#12">12</a></td></tr ><tr id="gr_svn310_13" ><td id="13"><a href="#13">13</a></td></tr ><tr id="gr_svn310_14" ><td id="14"><a href="#14">14</a></td></tr ><tr id="gr_svn310_15" ><td id="15"><a href="#15">15</a></td></tr ><tr id="gr_svn310_16" ><td id="16"><a href="#16">16</a></td></tr ><tr id="gr_svn310_17" ><td id="17"><a href="#17">17</a></td></tr ><tr id="gr_svn310_18" ><td id="18"><a href="#18">18</a></td></tr ><tr id="gr_svn310_19" ><td id="19"><a href="#19">19</a></td></tr ><tr id="gr_svn310_20" ><td id="20"><a href="#20">20</a></td></tr ><tr id="gr_svn310_21" ><td id="21"><a href="#21">21</a></td></tr ><tr id="gr_svn310_22" ><td id="22"><a href="#22">22</a></td></tr ><tr id="gr_svn310_23" ><td id="23"><a href="#23">23</a></td></tr ><tr id="gr_svn310_24" ><td id="24"><a href="#24">24</a></td></tr ><tr id="gr_svn310_25" ><td id="25"><a href="#25">25</a></td></tr ><tr id="gr_svn310_26" ><td id="26"><a href="#26">26</a></td></tr ><tr id="gr_svn310_27" ><td id="27"><a href="#27">27</a></td></tr ><tr id="gr_svn310_28" ><td id="28"><a href="#28">28</a></td></tr ><tr id="gr_svn310_29" ><td id="29"><a href="#29">29</a></td></tr ><tr id="gr_svn310_30" ><td id="30"><a href="#30">30</a></td></tr ><tr id="gr_svn310_31" ><td id="31"><a href="#31">31</a></td></tr ><tr id="gr_svn310_32" ><td id="32"><a href="#32">32</a></td></tr ><tr id="gr_svn310_33" ><td id="33"><a href="#33">33</a></td></tr ><tr id="gr_svn310_34" ><td id="34"><a href="#34">34</a></td></tr ><tr id="gr_svn310_35" ><td id="35"><a href="#35">35</a></td></tr ><tr id="gr_svn310_36" ><td id="36"><a href="#36">36</a></td></tr ><tr id="gr_svn310_37" ><td id="37"><a href="#37">37</a></td></tr ><tr id="gr_svn310_38" ><td id="38"><a href="#38">38</a></td></tr ><tr id="gr_svn310_39" ><td id="39"><a href="#39">39</a></td></tr ><tr id="gr_svn310_40" ><td id="40"><a href="#40">40</a></td></tr ><tr id="gr_svn310_41" ><td id="41"><a href="#41">41</a></td></tr ><tr id="gr_svn310_42" ><td id="42"><a href="#42">42</a></td></tr ><tr id="gr_svn310_43" ><td id="43"><a href="#43">43</a></td></tr ><tr id="gr_svn310_44" ><td id="44"><a href="#44">44</a></td></tr ><tr id="gr_svn310_45" ><td id="45"><a href="#45">45</a></td></tr ><tr id="gr_svn310_46" ><td id="46"><a href="#46">46</a></td></tr ><tr id="gr_svn310_47" ><td id="47"><a href="#47">47</a></td></tr ><tr id="gr_svn310_48" ><td id="48"><a href="#48">48</a></td></tr ><tr id="gr_svn310_49" ><td id="49"><a href="#49">49</a></td></tr ><tr id="gr_svn310_50" ><td id="50"><a href="#50">50</a></td></tr ><tr id="gr_svn310_51" ><td id="51"><a href="#51">51</a></td></tr ><tr id="gr_svn310_52" ><td id="52"><a href="#52">52</a></td></tr ><tr id="gr_svn310_53" ><td id="53"><a href="#53">53</a></td></tr ><tr id="gr_svn310_54" ><td id="54"><a href="#54">54</a></td></tr ><tr id="gr_svn310_55" ><td id="55"><a href="#55">55</a></td></tr ><tr id="gr_svn310_56" ><td id="56"><a href="#56">56</a></td></tr ><tr id="gr_svn310_57" ><td id="57"><a href="#57">57</a></td></tr ><tr id="gr_svn310_58" ><td id="58"><a href="#58">58</a></td></tr ><tr id="gr_svn310_59" ><td id="59"><a href="#59">59</a></td></tr ><tr id="gr_svn310_60" ><td id="60"><a href="#60">60</a></td></tr ><tr id="gr_svn310_61" ><td id="61"><a href="#61">61</a></td></tr ><tr id="gr_svn310_62" ><td id="62"><a href="#62">62</a></td></tr ><tr id="gr_svn310_63" ><td id="63"><a href="#63">63</a></td></tr ><tr id="gr_svn310_64" ><td id="64"><a href="#64">64</a></td></tr ><tr id="gr_svn310_65" ><td id="65"><a href="#65">65</a></td></tr ><tr id="gr_svn310_66" ><td id="66"><a href="#66">66</a></td></tr ><tr id="gr_svn310_67" ><td id="67"><a href="#67">67</a></td></tr ><tr id="gr_svn310_68" ><td id="68"><a href="#68">68</a></td></tr ><tr id="gr_svn310_69" ><td id="69"><a href="#69">69</a></td></tr ><tr id="gr_svn310_70" ><td id="70"><a href="#70">70</a></td></tr ><tr id="gr_svn310_71" ><td id="71"><a href="#71">71</a></td></tr ><tr id="gr_svn310_72" ><td id="72"><a href="#72">72</a></td></tr ><tr id="gr_svn310_73" ><td id="73"><a href="#73">73</a></td></tr ><tr id="gr_svn310_74" ><td id="74"><a href="#74">74</a></td></tr ><tr id="gr_svn310_75" ><td id="75"><a href="#75">75</a></td></tr ><tr id="gr_svn310_76" ><td id="76"><a href="#76">76</a></td></tr ><tr id="gr_svn310_77" ><td id="77"><a href="#77">77</a></td></tr ><tr id="gr_svn310_78" ><td id="78"><a href="#78">78</a></td></tr ><tr id="gr_svn310_79" ><td id="79"><a href="#79">79</a></td></tr ><tr id="gr_svn310_80" ><td id="80"><a href="#80">80</a></td></tr ><tr id="gr_svn310_81" ><td id="81"><a href="#81">81</a></td></tr ><tr id="gr_svn310_82" ><td id="82"><a href="#82">82</a></td></tr ><tr id="gr_svn310_83" ><td id="83"><a href="#83">83</a></td></tr ><tr id="gr_svn310_84" ><td id="84"><a href="#84">84</a></td></tr ><tr id="gr_svn310_85" ><td id="85"><a href="#85">85</a></td></tr ><tr id="gr_svn310_86" ><td id="86"><a href="#86">86</a></td></tr ><tr id="gr_svn310_87" ><td id="87"><a href="#87">87</a></td></tr ><tr id="gr_svn310_88" ><td id="88"><a href="#88">88</a></td></tr ><tr id="gr_svn310_89" ><td id="89"><a href="#89">89</a></td></tr ><tr id="gr_svn310_90" ><td id="90"><a href="#90">90</a></td></tr ><tr id="gr_svn310_91" ><td id="91"><a href="#91">91</a></td></tr ><tr id="gr_svn310_92" ><td id="92"><a href="#92">92</a></td></tr ><tr id="gr_svn310_93" ><td id="93"><a href="#93">93</a></td></tr ><tr id="gr_svn310_94" ><td id="94"><a href="#94">94</a></td></tr ><tr id="gr_svn310_95" ><td id="95"><a href="#95">95</a></td></tr ><tr id="gr_svn310_96" ><td id="96"><a href="#96">96</a></td></tr ><tr id="gr_svn310_97" ><td id="97"><a href="#97">97</a></td></tr ><tr id="gr_svn310_98" ><td id="98"><a href="#98">98</a></td></tr ><tr id="gr_svn310_99" ><td id="99"><a href="#99">99</a></td></tr ><tr id="gr_svn310_100" ><td id="100"><a href="#100">100</a></td></tr ><tr id="gr_svn310_101" ><td id="101"><a href="#101">101</a></td></tr ><tr id="gr_svn310_102" ><td id="102"><a href="#102">102</a></td></tr ><tr id="gr_svn310_103" ><td id="103"><a href="#103">103</a></td></tr ><tr id="gr_svn310_104" ><td id="104"><a href="#104">104</a></td></tr ><tr id="gr_svn310_105" ><td id="105"><a href="#105">105</a></td></tr ><tr id="gr_svn310_106" ><td id="106"><a href="#106">106</a></td></tr ><tr id="gr_svn310_107" ><td id="107"><a href="#107">107</a></td></tr ><tr id="gr_svn310_108" ><td id="108"><a href="#108">108</a></td></tr ><tr id="gr_svn310_109" ><td id="109"><a href="#109">109</a></td></tr ><tr id="gr_svn310_110" ><td id="110"><a href="#110">110</a></td></tr ><tr id="gr_svn310_111" ><td id="111"><a href="#111">111</a></td></tr ><tr id="gr_svn310_112" ><td id="112"><a href="#112">112</a></td></tr ><tr id="gr_svn310_113" ><td id="113"><a href="#113">113</a></td></tr ><tr id="gr_svn310_114" ><td id="114"><a href="#114">114</a></td></tr ><tr id="gr_svn310_115" ><td id="115"><a href="#115">115</a></td></tr ><tr id="gr_svn310_116" ><td id="116"><a href="#116">116</a></td></tr ><tr id="gr_svn310_117" ><td id="117"><a href="#117">117</a></td></tr ><tr id="gr_svn310_118" ><td id="118"><a href="#118">118</a></td></tr ><tr id="gr_svn310_119" ><td id="119"><a href="#119">119</a></td></tr ><tr id="gr_svn310_120" ><td id="120"><a href="#120">120</a></td></tr ><tr id="gr_svn310_121" ><td id="121"><a href="#121">121</a></td></tr ><tr id="gr_svn310_122" ><td id="122"><a href="#122">122</a></td></tr ><tr id="gr_svn310_123" ><td id="123"><a href="#123">123</a></td></tr ><tr id="gr_svn310_124" ><td id="124"><a href="#124">124</a></td></tr ><tr id="gr_svn310_125" ><td id="125"><a href="#125">125</a></td></tr ><tr id="gr_svn310_126" ><td id="126"><a href="#126">126</a></td></tr ><tr id="gr_svn310_127" ><td id="127"><a href="#127">127</a></td></tr ><tr id="gr_svn310_128" ><td id="128"><a href="#128">128</a></td></tr ><tr id="gr_svn310_129" ><td id="129"><a href="#129">129</a></td></tr ><tr id="gr_svn310_130" ><td id="130"><a href="#130">130</a></td></tr ><tr id="gr_svn310_131" ><td id="131"><a href="#131">131</a></td></tr ><tr id="gr_svn310_132" ><td id="132"><a href="#132">132</a></td></tr ><tr id="gr_svn310_133" ><td id="133"><a href="#133">133</a></td></tr ><tr id="gr_svn310_134" ><td id="134"><a href="#134">134</a></td></tr ><tr id="gr_svn310_135" ><td id="135"><a href="#135">135</a></td></tr ><tr id="gr_svn310_136" ><td id="136"><a href="#136">136</a></td></tr ><tr id="gr_svn310_137" ><td id="137"><a href="#137">137</a></td></tr ><tr id="gr_svn310_138" ><td id="138"><a href="#138">138</a></td></tr ><tr id="gr_svn310_139" ><td id="139"><a href="#139">139</a></td></tr ><tr id="gr_svn310_140" ><td id="140"><a href="#140">140</a></td></tr ><tr id="gr_svn310_141" ><td id="141"><a href="#141">141</a></td></tr ><tr id="gr_svn310_142" ><td id="142"><a href="#142">142</a></td></tr ><tr id="gr_svn310_143" ><td id="143"><a href="#143">143</a></td></tr ><tr id="gr_svn310_144" ><td id="144"><a href="#144">144</a></td></tr ><tr id="gr_svn310_145" ><td id="145"><a href="#145">145</a></td></tr ><tr id="gr_svn310_146" ><td id="146"><a href="#146">146</a></td></tr ><tr id="gr_svn310_147" ><td id="147"><a href="#147">147</a></td></tr ><tr id="gr_svn310_148" ><td id="148"><a href="#148">148</a></td></tr ><tr id="gr_svn310_149" ><td id="149"><a href="#149">149</a></td></tr ><tr id="gr_svn310_150" ><td id="150"><a href="#150">150</a></td></tr ><tr id="gr_svn310_151" ><td id="151"><a href="#151">151</a></td></tr ><tr id="gr_svn310_152" ><td id="152"><a href="#152">152</a></td></tr ><tr id="gr_svn310_153" ><td id="153"><a href="#153">153</a></td></tr ><tr id="gr_svn310_154" ><td id="154"><a href="#154">154</a></td></tr ><tr id="gr_svn310_155" ><td id="155"><a href="#155">155</a></td></tr ><tr id="gr_svn310_156" ><td id="156"><a href="#156">156</a></td></tr ><tr id="gr_svn310_157" ><td id="157"><a href="#157">157</a></td></tr ><tr id="gr_svn310_158" ><td id="158"><a href="#158">158</a></td></tr ><tr id="gr_svn310_159" ><td id="159"><a href="#159">159</a></td></tr ><tr id="gr_svn310_160" ><td id="160"><a href="#160">160</a></td></tr ><tr id="gr_svn310_161" ><td id="161"><a href="#161">161</a></td></tr ><tr id="gr_svn310_162" ><td id="162"><a href="#162">162</a></td></tr ><tr id="gr_svn310_163" ><td id="163"><a href="#163">163</a></td></tr ><tr id="gr_svn310_164" ><td id="164"><a href="#164">164</a></td></tr ><tr id="gr_svn310_165" ><td id="165"><a href="#165">165</a></td></tr ><tr id="gr_svn310_166" ><td id="166"><a href="#166">166</a></td></tr ><tr id="gr_svn310_167" ><td id="167"><a href="#167">167</a></td></tr ><tr id="gr_svn310_168" ><td id="168"><a href="#168">168</a></td></tr ><tr id="gr_svn310_169" ><td id="169"><a href="#169">169</a></td></tr ><tr id="gr_svn310_170" ><td id="170"><a href="#170">170</a></td></tr ><tr id="gr_svn310_171" ><td id="171"><a href="#171">171</a></td></tr ><tr id="gr_svn310_172" ><td id="172"><a href="#172">172</a></td></tr ><tr id="gr_svn310_173" ><td id="173"><a href="#173">173</a></td></tr ><tr id="gr_svn310_174" ><td id="174"><a href="#174">174</a></td></tr ><tr id="gr_svn310_175" ><td id="175"><a href="#175">175</a></td></tr ><tr id="gr_svn310_176" ><td id="176"><a href="#176">176</a></td></tr ><tr id="gr_svn310_177" ><td id="177"><a href="#177">177</a></td></tr ><tr id="gr_svn310_178" ><td id="178"><a href="#178">178</a></td></tr ><tr id="gr_svn310_179" ><td id="179"><a href="#179">179</a></td></tr ><tr id="gr_svn310_180" ><td id="180"><a href="#180">180</a></td></tr ><tr id="gr_svn310_181" ><td id="181"><a href="#181">181</a></td></tr ><tr id="gr_svn310_182" ><td id="182"><a href="#182">182</a></td></tr ><tr id="gr_svn310_183" ><td id="183"><a href="#183">183</a></td></tr ><tr id="gr_svn310_184" ><td id="184"><a href="#184">184</a></td></tr ><tr id="gr_svn310_185" ><td id="185"><a href="#185">185</a></td></tr ><tr id="gr_svn310_186" ><td id="186"><a href="#186">186</a></td></tr ><tr id="gr_svn310_187" ><td id="187"><a href="#187">187</a></td></tr ><tr id="gr_svn310_188" ><td id="188"><a href="#188">188</a></td></tr ><tr id="gr_svn310_189" ><td id="189"><a href="#189">189</a></td></tr ><tr id="gr_svn310_190" ><td id="190"><a href="#190">190</a></td></tr ><tr id="gr_svn310_191" ><td id="191"><a href="#191">191</a></td></tr ><tr id="gr_svn310_192" ><td id="192"><a href="#192">192</a></td></tr ><tr id="gr_svn310_193" ><td id="193"><a href="#193">193</a></td></tr ><tr id="gr_svn310_194" ><td id="194"><a href="#194">194</a></td></tr ><tr id="gr_svn310_195" ><td id="195"><a href="#195">195</a></td></tr ><tr id="gr_svn310_196" ><td id="196"><a href="#196">196</a></td></tr ><tr id="gr_svn310_197" ><td id="197"><a href="#197">197</a></td></tr ><tr id="gr_svn310_198" ><td id="198"><a href="#198">198</a></td></tr ><tr id="gr_svn310_199" ><td id="199"><a href="#199">199</a></td></tr ><tr id="gr_svn310_200" ><td id="200"><a href="#200">200</a></td></tr ><tr id="gr_svn310_201" ><td id="201"><a href="#201">201</a></td></tr ><tr id="gr_svn310_202" ><td id="202"><a href="#202">202</a></td></tr ><tr id="gr_svn310_203" ><td id="203"><a href="#203">203</a></td></tr ><tr id="gr_svn310_204" ><td id="204"><a href="#204">204</a></td></tr ><tr id="gr_svn310_205" ><td id="205"><a href="#205">205</a></td></tr ><tr id="gr_svn310_206" ><td id="206"><a href="#206">206</a></td></tr ><tr id="gr_svn310_207" ><td id="207"><a href="#207">207</a></td></tr ><tr id="gr_svn310_208" ><td id="208"><a href="#208">208</a></td></tr ><tr id="gr_svn310_209" ><td id="209"><a href="#209">209</a></td></tr ><tr id="gr_svn310_210" ><td id="210"><a href="#210">210</a></td></tr ><tr id="gr_svn310_211" ><td id="211"><a href="#211">211</a></td></tr ><tr id="gr_svn310_212" ><td id="212"><a href="#212">212</a></td></tr ><tr id="gr_svn310_213" ><td id="213"><a href="#213">213</a></td></tr ><tr id="gr_svn310_214" ><td id="214"><a href="#214">214</a></td></tr ><tr id="gr_svn310_215" ><td id="215"><a href="#215">215</a></td></tr ><tr id="gr_svn310_216" ><td id="216"><a href="#216">216</a></td></tr ><tr id="gr_svn310_217" ><td id="217"><a href="#217">217</a></td></tr ><tr id="gr_svn310_218" ><td id="218"><a href="#218">218</a></td></tr ><tr id="gr_svn310_219" ><td id="219"><a href="#219">219</a></td></tr ><tr id="gr_svn310_220" ><td id="220"><a href="#220">220</a></td></tr ><tr id="gr_svn310_221" ><td id="221"><a href="#221">221</a></td></tr ><tr id="gr_svn310_222" ><td id="222"><a href="#222">222</a></td></tr ><tr id="gr_svn310_223" ><td id="223"><a href="#223">223</a></td></tr ><tr id="gr_svn310_224" ><td id="224"><a href="#224">224</a></td></tr ><tr id="gr_svn310_225" ><td id="225"><a href="#225">225</a></td></tr ><tr id="gr_svn310_226" ><td id="226"><a href="#226">226</a></td></tr ><tr id="gr_svn310_227" ><td id="227"><a href="#227">227</a></td></tr ><tr id="gr_svn310_228" ><td id="228"><a href="#228">228</a></td></tr ><tr id="gr_svn310_229" ><td id="229"><a href="#229">229</a></td></tr ><tr id="gr_svn310_230" ><td id="230"><a href="#230">230</a></td></tr ><tr id="gr_svn310_231" ><td id="231"><a href="#231">231</a></td></tr ><tr id="gr_svn310_232" ><td id="232"><a href="#232">232</a></td></tr ><tr id="gr_svn310_233" ><td id="233"><a href="#233">233</a></td></tr ><tr id="gr_svn310_234" ><td id="234"><a href="#234">234</a></td></tr ><tr id="gr_svn310_235" ><td id="235"><a href="#235">235</a></td></tr ><tr id="gr_svn310_236" ><td id="236"><a href="#236">236</a></td></tr ><tr id="gr_svn310_237" ><td id="237"><a href="#237">237</a></td></tr ><tr id="gr_svn310_238" ><td id="238"><a href="#238">238</a></td></tr ><tr id="gr_svn310_239" ><td id="239"><a href="#239">239</a></td></tr ><tr id="gr_svn310_240" ><td id="240"><a href="#240">240</a></td></tr ><tr id="gr_svn310_241" ><td id="241"><a href="#241">241</a></td></tr ></table></pre> <pre><table width="100%"><tr class="nocursor"><td></td></tr></table></pre> </td> <td id="lines"> <pre><table width="100%"><tr class="cursor_stop cursor_hidden"><td></td></tr></table></pre> <pre class="prettyprint lang-js"><table id="src_table_0"><tr id=sl_svn310_1 ><td class="source"><br></td></tr ><tr id=sl_svn310_2 ><td class="source">// This file is required if you wish to support any of the following browsers:<br></td></tr ><tr id=sl_svn310_3 ><td class="source">// * IE5.0 (Windows)<br></td></tr ><tr id=sl_svn310_4 ><td class="source">// * IE5.x (Mac)<br></td></tr ><tr id=sl_svn310_5 ><td class="source">// * Netscape 6<br></td></tr ><tr id=sl_svn310_6 ><td class="source">// * Safari 1.x<br></td></tr ><tr id=sl_svn310_7 ><td class="source"><br></td></tr ><tr id=sl_svn310_8 ><td class="source">window.undefined = void(0);<br></td></tr ><tr id=sl_svn310_9 ><td class="source"><br></td></tr ><tr id=sl_svn310_10 ><td class="source">new function() {<br></td></tr ><tr id=sl_svn310_11 ><td class="source"> var slice = Array.prototype.slice, html = document.documentElement;<br></td></tr ><tr id=sl_svn310_12 ><td class="source"><br></td></tr ><tr id=sl_svn310_13 ><td class="source"> window.$Legacy = {<br></td></tr ><tr id=sl_svn310_14 ><td class="source"> has: function(object, key) {<br></td></tr ><tr id=sl_svn310_15 ><td class="source"> if (object[key] !== undefined) return true;<br></td></tr ><tr id=sl_svn310_16 ><td class="source"> key = String(key);<br></td></tr ><tr id=sl_svn310_17 ><td class="source"> for (var i in object) if (i == key) return true;<br></td></tr ><tr id=sl_svn310_18 ><td class="source"> return false;<br></td></tr ><tr id=sl_svn310_19 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_20 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_21 ><td class="source"><br></td></tr ><tr id=sl_svn310_22 ><td class="source"> var jscript = NaN/*@cc_on||@_jscript_version@*/;<br></td></tr ><tr id=sl_svn310_23 ><td class="source"><br></td></tr ><tr id=sl_svn310_24 ><td class="source"> if (jscript &lt; 5.1) {<br></td></tr ><tr id=sl_svn310_25 ><td class="source"> var _onload = onload;<br></td></tr ><tr id=sl_svn310_26 ><td class="source"> onload = function() {<br></td></tr ><tr id=sl_svn310_27 ><td class="source"> with (base2.DOM) {<br></td></tr ><tr id=sl_svn310_28 ><td class="source"> var event = DocumentEvent.createEvent(document, &quot;Events&quot;);<br></td></tr ><tr id=sl_svn310_29 ><td class="source"> Event.initEvent(event, &quot;DOMContentLoaded&quot;, true, false);<br></td></tr ><tr id=sl_svn310_30 ><td class="source"> EventTarget.dispatchEvent(document, event);<br></td></tr ><tr id=sl_svn310_31 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_32 ><td class="source"> if (_onload) _onload();<br></td></tr ><tr id=sl_svn310_33 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_34 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_35 ><td class="source"><br></td></tr ><tr id=sl_svn310_36 ><td class="source"> if (typeof encodeURIComponent == &quot;undefined&quot;) {<br></td></tr ><tr id=sl_svn310_37 ><td class="source"> encodeURIComponent = function(string) {<br></td></tr ><tr id=sl_svn310_38 ><td class="source"> return escape(string).replace(/\%(21|7E|27|28|29)/g, unescape).replace(/[@+\/]/g, function(chr) {<br></td></tr ><tr id=sl_svn310_39 ><td class="source"> return &quot;%&quot; + chr.charCodeAt(0).toString(16).toUpperCase();<br></td></tr ><tr id=sl_svn310_40 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_41 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_42 ><td class="source"> decodeURIComponent = unescape;<br></td></tr ><tr id=sl_svn310_43 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_44 ><td class="source"><br></td></tr ><tr id=sl_svn310_45 ><td class="source"> if (!window.Error) {<br></td></tr ><tr id=sl_svn310_46 ><td class="source"> createError(&quot;Error&quot;);<br></td></tr ><tr id=sl_svn310_47 ><td class="source"> createError(&quot;TypeError&quot;);<br></td></tr ><tr id=sl_svn310_48 ><td class="source"> createError(&quot;SyntaxError&quot;);<br></td></tr ><tr id=sl_svn310_49 ><td class="source"> createError(&quot;ReferenceError&quot;);<br></td></tr ><tr id=sl_svn310_50 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_51 ><td class="source"><br></td></tr ><tr id=sl_svn310_52 ><td class="source"> function createError(name) {<br></td></tr ><tr id=sl_svn310_53 ><td class="source"> if (typeof window[name] == &quot;undefined&quot;) {<br></td></tr ><tr id=sl_svn310_54 ><td class="source"> var error = window[name] = function(message) {<br></td></tr ><tr id=sl_svn310_55 ><td class="source"> this.message = message;<br></td></tr ><tr id=sl_svn310_56 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_57 ><td class="source"> error.prototype = new window.Error;<br></td></tr ><tr id=sl_svn310_58 ><td class="source"> error.prototype.name = name;<br></td></tr ><tr id=sl_svn310_59 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_60 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_61 ><td class="source"><br></td></tr ><tr id=sl_svn310_62 ><td class="source"> function extend(klass, name, method) {<br></td></tr ><tr id=sl_svn310_63 ><td class="source"> if (!klass.prototype[name]) {<br></td></tr ><tr id=sl_svn310_64 ><td class="source"> klass.prototype[name] = method;<br></td></tr ><tr id=sl_svn310_65 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_66 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_67 ><td class="source"><br></td></tr ><tr id=sl_svn310_68 ><td class="source"> if (&quot;11&quot;.slice(-1) != &quot;1&quot;) { // for IE5.0<br></td></tr ><tr id=sl_svn310_69 ><td class="source"> var _slice = String.prototype.slice;<br></td></tr ><tr id=sl_svn310_70 ><td class="source"> String.prototype.slice = function(start, length) {<br></td></tr ><tr id=sl_svn310_71 ><td class="source"> if (arguments.length == 1 &amp;&amp; start &lt; 0) {<br></td></tr ><tr id=sl_svn310_72 ><td class="source"> arguments[0] = this.length + start;<br></td></tr ><tr id=sl_svn310_73 ><td class="source"> arguments[1] = -start;<br></td></tr ><tr id=sl_svn310_74 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_75 ><td class="source"> return _slice.apply(this, arguments);<br></td></tr ><tr id=sl_svn310_76 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_77 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_78 ><td class="source"> <br></td></tr ><tr id=sl_svn310_79 ><td class="source"> if (!Array.prototype.unshift) {<br></td></tr ><tr id=sl_svn310_80 ><td class="source"> extend(Array, &quot;pop&quot;, function() {<br></td></tr ><tr id=sl_svn310_81 ><td class="source"> if (this.length) {<br></td></tr ><tr id=sl_svn310_82 ><td class="source"> var i = this[this.length - 1];<br></td></tr ><tr id=sl_svn310_83 ><td class="source"> this.length--;<br></td></tr ><tr id=sl_svn310_84 ><td class="source"> return i;<br></td></tr ><tr id=sl_svn310_85 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_86 ><td class="source"> return undefined;<br></td></tr ><tr id=sl_svn310_87 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_88 ><td class="source"><br></td></tr ><tr id=sl_svn310_89 ><td class="source"> extend(Array, &quot;push&quot;, function() {<br></td></tr ><tr id=sl_svn310_90 ><td class="source"> for (var i = 0; i &lt; arguments.length; i++) {<br></td></tr ><tr id=sl_svn310_91 ><td class="source"> this[this.length] = arguments[i];<br></td></tr ><tr id=sl_svn310_92 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_93 ><td class="source"> return this.length;<br></td></tr ><tr id=sl_svn310_94 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_95 ><td class="source"><br></td></tr ><tr id=sl_svn310_96 ><td class="source"> extend(Array, &quot;shift&quot;, function() {<br></td></tr ><tr id=sl_svn310_97 ><td class="source"> var r = this[0];<br></td></tr ><tr id=sl_svn310_98 ><td class="source"> if (this.length) {<br></td></tr ><tr id=sl_svn310_99 ><td class="source"> var a = this.slice(1), i = a.length;<br></td></tr ><tr id=sl_svn310_100 ><td class="source"> while (i--) this[i] = a[i];<br></td></tr ><tr id=sl_svn310_101 ><td class="source"> this.length--;<br></td></tr ><tr id=sl_svn310_102 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_103 ><td class="source"> return r;<br></td></tr ><tr id=sl_svn310_104 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_105 ><td class="source"><br></td></tr ><tr id=sl_svn310_106 ><td class="source"> extend(Array, &quot;splice&quot;, function(i, c) {<br></td></tr ><tr id=sl_svn310_107 ><td class="source"> var r = c ? this.slice(i, i + c) : [];<br></td></tr ><tr id=sl_svn310_108 ><td class="source"> var a = this.slice(0, i).concat(slice.apply(arguments, [2])).concat(this.slice(i + c));<br></td></tr ><tr id=sl_svn310_109 ><td class="source"> this.length = i = a.length;<br></td></tr ><tr id=sl_svn310_110 ><td class="source"> while (i--) this[i] = a[i];<br></td></tr ><tr id=sl_svn310_111 ><td class="source"> return r;<br></td></tr ><tr id=sl_svn310_112 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_113 ><td class="source"><br></td></tr ><tr id=sl_svn310_114 ><td class="source"> extend(Array, &quot;unshift&quot;, function() {<br></td></tr ><tr id=sl_svn310_115 ><td class="source"> var a = this.concat.call(slice.apply(arguments, [0]), this), i = a.length;<br></td></tr ><tr id=sl_svn310_116 ><td class="source"> while (i--) this[i] = a[i];<br></td></tr ><tr id=sl_svn310_117 ><td class="source"> return this.length;<br></td></tr ><tr id=sl_svn310_118 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_119 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_120 ><td class="source"><br></td></tr ><tr id=sl_svn310_121 ><td class="source"> if (!Function.prototype.apply) {<br></td></tr ><tr id=sl_svn310_122 ><td class="source"> var ns = this;<br></td></tr ><tr id=sl_svn310_123 ><td class="source"> extend(Function, &quot;apply&quot;, function(a, b) {<br></td></tr ><tr id=sl_svn310_124 ><td class="source"> var c = &quot;*apply&quot;, d;<br></td></tr ><tr id=sl_svn310_125 ><td class="source"> if (a === undefined) a = ns;<br></td></tr ><tr id=sl_svn310_126 ><td class="source"> else if (a == null) a = window;<br></td></tr ><tr id=sl_svn310_127 ><td class="source"> else if (typeof a == &quot;string&quot;) a = new String(a);<br></td></tr ><tr id=sl_svn310_128 ><td class="source"> else if (typeof a == &quot;number&quot;) a = new Number(a);<br></td></tr ><tr id=sl_svn310_129 ><td class="source"> else if (typeof a == &quot;boolean&quot;) a = new Boolean(a);<br></td></tr ><tr id=sl_svn310_130 ><td class="source"> if (arguments.length == 1) b = [];<br></td></tr ><tr id=sl_svn310_131 ><td class="source"> else if (b[0] &amp;&amp; b[0].writeln) b[0] = b[0].documentElement.document || b[0];<br></td></tr ><tr id=sl_svn310_132 ><td class="source"> a[c] = this;<br></td></tr ><tr id=sl_svn310_133 ><td class="source"> switch (b.length) { // unroll for speed<br></td></tr ><tr id=sl_svn310_134 ><td class="source"> case 0: d = a[c](); break;<br></td></tr ><tr id=sl_svn310_135 ><td class="source"> case 1: d = a[c](b[0]); break;<br></td></tr ><tr id=sl_svn310_136 ><td class="source"> case 2: d = a[c](b[0],b[1]); break;<br></td></tr ><tr id=sl_svn310_137 ><td class="source"> case 3: d = a[c](b[0],b[1],b[2]); break;<br></td></tr ><tr id=sl_svn310_138 ><td class="source"> case 4: d = a[c](b[0],b[1],b[2],b[3]); break;<br></td></tr ><tr id=sl_svn310_139 ><td class="source"> case 5: d = a[c](b[0],b[1],b[2],b[3],b[4]); break;<br></td></tr ><tr id=sl_svn310_140 ><td class="source"> default:<br></td></tr ><tr id=sl_svn310_141 ><td class="source"> var args = [], i = b.length - 1;<br></td></tr ><tr id=sl_svn310_142 ><td class="source"> do args[i] = &quot;b[&quot; + i + &quot;]&quot;; while (i--);<br></td></tr ><tr id=sl_svn310_143 ><td class="source"> eval(&quot;d=a[c](&quot; + args + &quot;)&quot;);<br></td></tr ><tr id=sl_svn310_144 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_145 ><td class="source"> if (typeof a.valueOf == &quot;function&quot;) { // not a COM object<br></td></tr ><tr id=sl_svn310_146 ><td class="source"> delete a[c];<br></td></tr ><tr id=sl_svn310_147 ><td class="source"> } else {<br></td></tr ><tr id=sl_svn310_148 ><td class="source"> a[c] = undefined;<br></td></tr ><tr id=sl_svn310_149 ><td class="source"> if (d &amp;&amp; d.writeln) d = d.documentElement.document || d;<br></td></tr ><tr id=sl_svn310_150 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_151 ><td class="source"> return d;<br></td></tr ><tr id=sl_svn310_152 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_153 ><td class="source"><br></td></tr ><tr id=sl_svn310_154 ><td class="source"> extend(Function, &quot;call&quot;, function(o) {<br></td></tr ><tr id=sl_svn310_155 ><td class="source"> return this.apply(o, slice.apply(arguments, [1]));<br></td></tr ><tr id=sl_svn310_156 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_157 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_158 ><td class="source"><br></td></tr ><tr id=sl_svn310_159 ><td class="source"> extend(Number, &quot;toFixed&quot;, function(n) {<br></td></tr ><tr id=sl_svn310_160 ><td class="source"> // Andrea Giammarchi<br></td></tr ><tr id=sl_svn310_161 ><td class="source"> n = parseInt(n);<br></td></tr ><tr id=sl_svn310_162 ><td class="source"> var value = Math.pow(10, n);<br></td></tr ><tr id=sl_svn310_163 ><td class="source"> value = String(Math.round(this * value) / value);<br></td></tr ><tr id=sl_svn310_164 ><td class="source"> if (n &gt; 0) {<br></td></tr ><tr id=sl_svn310_165 ><td class="source"> value = value.split(&quot;.&quot;);<br></td></tr ><tr id=sl_svn310_166 ><td class="source"> if (!value[1]) value[1] = &quot;&quot;;<br></td></tr ><tr id=sl_svn310_167 ><td class="source"> value[1] += Array(n - value[1].length + 1).join(0);<br></td></tr ><tr id=sl_svn310_168 ><td class="source"> value = value.join(&quot;.&quot;);<br></td></tr ><tr id=sl_svn310_169 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_170 ><td class="source"> return value;<br></td></tr ><tr id=sl_svn310_171 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_172 ><td class="source"><br></td></tr ><tr id=sl_svn310_173 ><td class="source"> // Fix String.replace (Safari1.x/IE5.0).<br></td></tr ><tr id=sl_svn310_174 ><td class="source"> if (&quot;&quot;.replace(/^/, String)) {<br></td></tr ><tr id=sl_svn310_175 ><td class="source"> var GLOBAL = /(g|gi)$/;<br></td></tr ><tr id=sl_svn310_176 ><td class="source"> var RESCAPE = /([\/()[\]{}|*+-.,^$?\\])/g;<br></td></tr ><tr id=sl_svn310_177 ><td class="source"> var _replace = String.prototype.replace;<br></td></tr ><tr id=sl_svn310_178 ><td class="source"> String.prototype.replace = function(expression, replacement) {<br></td></tr ><tr id=sl_svn310_179 ><td class="source"> if (typeof replacement == &quot;function&quot;) { // Safari doesn&#39;t like functions<br></td></tr ><tr id=sl_svn310_180 ><td class="source"> if (expression &amp;&amp; expression.constructor == RegExp) {<br></td></tr ><tr id=sl_svn310_181 ><td class="source"> var regexp = expression;<br></td></tr ><tr id=sl_svn310_182 ><td class="source"> var global = regexp.global;<br></td></tr ><tr id=sl_svn310_183 ><td class="source"> if (global == null) global = GLOBAL.test(regexp);<br></td></tr ><tr id=sl_svn310_184 ><td class="source"> // we have to convert global RexpExps for exec() to work consistently<br></td></tr ><tr id=sl_svn310_185 ><td class="source"> if (global) regexp = new RegExp(regexp.source); // non-global<br></td></tr ><tr id=sl_svn310_186 ><td class="source"> } else {<br></td></tr ><tr id=sl_svn310_187 ><td class="source"> regexp = new RegExp(String(expression).replace(RESCAPE, &quot;\\$1&quot;));<br></td></tr ><tr id=sl_svn310_188 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_189 ><td class="source"> var match, string = this, result = &quot;&quot;;<br></td></tr ><tr id=sl_svn310_190 ><td class="source"> while (string &amp;&amp; (match = regexp.exec(string))) {<br></td></tr ><tr id=sl_svn310_191 ><td class="source"> result += string.slice(0, match.index) + replacement.apply(this, match);<br></td></tr ><tr id=sl_svn310_192 ><td class="source"> string = string.slice(match.index + match[0].length);<br></td></tr ><tr id=sl_svn310_193 ><td class="source"> if (!global) break;<br></td></tr ><tr id=sl_svn310_194 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_195 ><td class="source"> return result + string;<br></td></tr ><tr id=sl_svn310_196 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_197 ><td class="source"> return _replace.apply(this, arguments);<br></td></tr ><tr id=sl_svn310_198 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_199 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_200 ><td class="source"> <br></td></tr ><tr id=sl_svn310_201 ><td class="source"> // mozilla fixes<br></td></tr ><tr id=sl_svn310_202 ><td class="source"> if (window.Components) {<br></td></tr ><tr id=sl_svn310_203 ><td class="source"> // for older versions of gecko we need to use getPropertyValue() to<br></td></tr ><tr id=sl_svn310_204 ><td class="source"> // access css properties returned by getComputedStyle().<br></td></tr ><tr id=sl_svn310_205 ><td class="source"> // we don&#39;t want this so we fix it.<br></td></tr ><tr id=sl_svn310_206 ><td class="source"> try {<br></td></tr ><tr id=sl_svn310_207 ><td class="source"> var computedStyle = getComputedStyle(html, null);<br></td></tr ><tr id=sl_svn310_208 ><td class="source"> // the next line will throw an error for some versions of mozilla<br></td></tr ><tr id=sl_svn310_209 ><td class="source"> var pass = computedStyle.display;<br></td></tr ><tr id=sl_svn310_210 ><td class="source"> } catch (ex) {<br></td></tr ><tr id=sl_svn310_211 ><td class="source"> // the previous line will throw an error for some versions of mozilla<br></td></tr ><tr id=sl_svn310_212 ><td class="source"> } finally {<br></td></tr ><tr id=sl_svn310_213 ><td class="source"> if (!pass) {<br></td></tr ><tr id=sl_svn310_214 ><td class="source"> var UPPER_CASE = /[A-Z]/g;<br></td></tr ><tr id=sl_svn310_215 ><td class="source"> function dashLowerCase(match){return &quot;-&quot; + match.toLowerCase()};<br></td></tr ><tr id=sl_svn310_216 ><td class="source"> function assignStyleGetter(propertyName) {<br></td></tr ><tr id=sl_svn310_217 ><td class="source"> var cssName = propertyName.replace(UPPER_CASE, dashLowerCase);<br></td></tr ><tr id=sl_svn310_218 ><td class="source"> CSSStyleDeclaration.prototype.__defineGetter__(propertyName, function() {<br></td></tr ><tr id=sl_svn310_219 ><td class="source"> return this.getPropertyValue(cssName);<br></td></tr ><tr id=sl_svn310_220 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_221 ><td class="source"> };<br></td></tr ><tr id=sl_svn310_222 ><td class="source"> for (var propertyName in html.style) {<br></td></tr ><tr id=sl_svn310_223 ><td class="source"> if (typeof html.style[propertyName] == &quot;string&quot;) {<br></td></tr ><tr id=sl_svn310_224 ><td class="source"> assignStyleGetter(propertyName);<br></td></tr ><tr id=sl_svn310_225 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_226 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_227 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_228 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_229 ><td class="source"><br></td></tr ><tr id=sl_svn310_230 ><td class="source"> if (parseInt(navigator.productSub) &lt; 20040614) {<br></td></tr ><tr id=sl_svn310_231 ><td class="source"> HTMLInputElement.prototype.__defineGetter__(&quot;clientWidth&quot;, function() {<br></td></tr ><tr id=sl_svn310_232 ><td class="source"> var cs = getComputedStyle(this, null);<br></td></tr ><tr id=sl_svn310_233 ><td class="source"> return this.offsetWidth - parseInt(cs.borderLeftWidth) - parseInt(cs.borderRightWidth);<br></td></tr ><tr id=sl_svn310_234 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_235 ><td class="source"> HTMLInputElement.prototype.__defineGetter__(&quot;clientHeight&quot;, function() {<br></td></tr ><tr id=sl_svn310_236 ><td class="source"> var cs = getComputedStyle(this, null);<br></td></tr ><tr id=sl_svn310_237 ><td class="source"> return this.offsetHeight - parseInt(cs.borderTopWidth) - parseInt(cs.borderBottomWidth);<br></td></tr ><tr id=sl_svn310_238 ><td class="source"> });<br></td></tr ><tr id=sl_svn310_239 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_240 ><td class="source"> }<br></td></tr ><tr id=sl_svn310_241 ><td class="source">};<br></td></tr ></table></pre> <pre><table width="100%"><tr class="cursor_stop cursor_hidden"><td></td></tr></table></pre> </td> </tr></table> <script type="text/javascript"> var lineNumUnderMouse = -1; function gutterOver(num) { gutterOut(); var newTR = document.getElementById('gr_svn310_' + num); if (newTR) { newTR.className = 'undermouse'; } lineNumUnderMouse = num; } function gutterOut() { if (lineNumUnderMouse != -1) { var oldTR = document.getElementById( 'gr_svn310_' + lineNumUnderMouse); if (oldTR) { oldTR.className = ''; } lineNumUnderMouse = -1; } } var numsGenState = {table_base_id: 'nums_table_'}; var srcGenState = {table_base_id: 'src_table_'}; var alignerRunning = false; var startOver = false; function setLineNumberHeights() { if (alignerRunning) { startOver = true; return; } numsGenState.chunk_id = 0; numsGenState.table = document.getElementById('nums_table_0'); numsGenState.row_num = 0; if (!numsGenState.table) { return; // Silently exit if no file is present. } srcGenState.chunk_id = 0; srcGenState.table = document.getElementById('src_table_0'); srcGenState.row_num = 0; alignerRunning = true; continueToSetLineNumberHeights(); } function rowGenerator(genState) { if (genState.row_num < genState.table.rows.length) { var currentRow = genState.table.rows[genState.row_num]; genState.row_num++; return currentRow; } var newTable = document.getElementById( genState.table_base_id + (genState.chunk_id + 1)); if (newTable) { genState.chunk_id++; genState.row_num = 0; genState.table = newTable; return genState.table.rows[0]; } return null; } var MAX_ROWS_PER_PASS = 1000; function continueToSetLineNumberHeights() { var rowsInThisPass = 0; var numRow = 1; var srcRow = 1; while (numRow && srcRow && rowsInThisPass < MAX_ROWS_PER_PASS) { numRow = rowGenerator(numsGenState); srcRow = rowGenerator(srcGenState); rowsInThisPass++; if (numRow && srcRow) { if (numRow.offsetHeight != srcRow.offsetHeight) { numRow.firstChild.style.height = srcRow.offsetHeight + 'px'; } } } if (rowsInThisPass >= MAX_ROWS_PER_PASS) { setTimeout(continueToSetLineNumberHeights, 10); } else { alignerRunning = false; if (startOver) { startOver = false; setTimeout(setLineNumberHeights, 500); } } } function initLineNumberHeights() { // Do 2 complete passes, because there can be races // between this code and prettify. startOver = true; setTimeout(setLineNumberHeights, 250); window.onresize = setLineNumberHeights; } initLineNumberHeights(); </script> <div id="log"> <div style="text-align:right"> <a class="ifCollapse" href="#" onclick="_toggleMeta(this); return false">Show details</a> <a class="ifExpand" href="#" onclick="_toggleMeta(this); return false">Hide details</a> </div> <div class="ifExpand"> <div class="pmeta_bubble_bg" style="border:1px solid white"> <div class="round4"></div> <div class="round2"></div> <div class="round1"></div> <div class="box-inner"> <div id="changelog"> <p>Change log</p> <div> <a href="/p/base2/source/detail?spec=svn310&amp;r=310">r310</a> by dean.edwards on Mar 22, 2011 &nbsp; <a href="/p/base2/source/diff?spec=svn310&r=310&amp;format=side&amp;path=/version/1.0.2/src/base2-legacy.js&amp;old_path=/version/1.0.2/src/base2-legacy.js&amp;old=">Diff</a> </div> <pre>Patch release for Firefox 4.</pre> </div> <script type="text/javascript"> var detail_url = '/p/base2/source/detail?r=310&spec=svn310'; var publish_url = '/p/base2/source/detail?r=310&spec=svn310#publish'; // describe the paths of this revision in javascript. var changed_paths = []; var changed_urls = []; changed_paths.push('/version/1.0.2'); changed_urls.push('/p/base2/source/browse/version/1.0.2?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/base2-dom-fp.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/base2-dom-fp.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/base2-dom-p.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/base2-dom-p.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/base2-legacy-p.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/base2-legacy-p.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/base2-p.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/base2-p.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/doc'); changed_urls.push('/p/base2/source/browse/version/1.0.2/doc?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/doc/base2.html'); changed_urls.push('/p/base2/source/browse/version/1.0.2/doc/base2.html?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/doc/colorize.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/doc/colorize.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/doc/doc.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/doc/doc.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/doc/miniweb.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/doc/miniweb.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/src'); changed_urls.push('/p/base2/source/browse/version/1.0.2/src?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/src/base2-dom.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/src/base2-dom.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/1.0.2/src/base2-legacy.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/src/base2-legacy.js?r\x3d310\x26spec\x3dsvn310'); var selected_path = '/version/1.0.2/src/base2-legacy.js'; changed_paths.push('/version/1.0.2/src/base2.js'); changed_urls.push('/p/base2/source/browse/version/1.0.2/src/base2.js?r\x3d310\x26spec\x3dsvn310'); changed_paths.push('/version/latest'); changed_urls.push('/p/base2/source/browse/version/latest?r\x3d310\x26spec\x3dsvn310'); function getCurrentPageIndex() { for (var i = 0; i < changed_paths.length; i++) { if (selected_path == changed_paths[i]) { return i; } } } function getNextPage() { var i = getCurrentPageIndex(); if (i < changed_paths.length - 1) { return changed_urls[i + 1]; } return null; } function getPreviousPage() { var i = getCurrentPageIndex(); if (i > 0) { return changed_urls[i - 1]; } return null; } function gotoNextPage() { var page = getNextPage(); if (!page) { page = detail_url; } window.location = page; } function gotoPreviousPage() { var page = getPreviousPage(); if (!page) { page = detail_url; } window.location = page; } function gotoDetailPage() { window.location = detail_url; } function gotoPublishPage() { window.location = publish_url; } </script> <style type="text/css"> #review_nav { border-top: 3px solid white; padding-top: 6px; margin-top: 1em; } #review_nav td { vertical-align: middle; } #review_nav select { margin: .5em 0; } </style> <div id="review_nav"> <table><tr><td>Go to:&nbsp;</td><td> <select name="files_in_rev" onchange="window.location=this.value"> <option value="/p/base2/source/browse/version/1.0.2?r=310&amp;spec=svn310" >/version/1.0.2</option> <option value="/p/base2/source/browse/version/1.0.2/base2-dom-fp.js?r=310&amp;spec=svn310" >/version/1.0.2/base2-dom-fp.js</option> <option value="/p/base2/source/browse/version/1.0.2/base2-dom-p.js?r=310&amp;spec=svn310" >/version/1.0.2/base2-dom-p.js</option> <option value="/p/base2/source/browse/version/1.0.2/base2-legacy-p.js?r=310&amp;spec=svn310" >/version/1.0.2/base2-legacy-p.js</option> <option value="/p/base2/source/browse/version/1.0.2/base2-p.js?r=310&amp;spec=svn310" >/version/1.0.2/base2-p.js</option> <option value="/p/base2/source/browse/version/1.0.2/doc?r=310&amp;spec=svn310" >/version/1.0.2/doc</option> <option value="/p/base2/source/browse/version/1.0.2/doc/base2.html?r=310&amp;spec=svn310" >/version/1.0.2/doc/base2.html</option> <option value="/p/base2/source/browse/version/1.0.2/doc/colorize.js?r=310&amp;spec=svn310" >/version/1.0.2/doc/colorize.js</option> <option value="/p/base2/source/browse/version/1.0.2/doc/doc.js?r=310&amp;spec=svn310" >/version/1.0.2/doc/doc.js</option> <option value="/p/base2/source/browse/version/1.0.2/doc/miniweb.js?r=310&amp;spec=svn310" >/version/1.0.2/doc/miniweb.js</option> <option value="/p/base2/source/browse/version/1.0.2/src?r=310&amp;spec=svn310" >/version/1.0.2/src</option> <option value="/p/base2/source/browse/version/1.0.2/src/base2-dom.js?r=310&amp;spec=svn310" >/version/1.0.2/src/base2-dom.js</option> <option value="/p/base2/source/browse/version/1.0.2/src/base2-legacy.js?r=310&amp;spec=svn310" selected="selected" >/version/1.0.2/src/base2-legacy.js</option> <option value="/p/base2/source/browse/version/1.0.2/src/base2.js?r=310&amp;spec=svn310" >/version/1.0.2/src/base2.js</option> <option value="/p/base2/source/browse/version/latest?r=310&amp;spec=svn310" >/version/latest</option> </select> </td></tr></table> <div style="white-space:nowrap"> Project members, <a href="https://www.google.com/accounts/ServiceLogin?service=code&amp;ltmpl=phosting&amp;continue=https%3A%2F%2Fcode.google.com%2Fp%2Fbase2%2Fsource%2Fbrowse%2Fversion%2F1.0.2%2Fsrc%2Fbase2-legacy.js&amp;followup=https%3A%2F%2Fcode.google.com%2Fp%2Fbase2%2Fsource%2Fbrowse%2Fversion%2F1.0.2%2Fsrc%2Fbase2-legacy.js" >sign in</a> to write a code review</div> </div> </div> <div class="round1"></div> <div class="round2"></div> <div class="round4"></div> </div> <div class="pmeta_bubble_bg" style="border:1px solid white"> <div class="round4"></div> <div class="round2"></div> <div class="round1"></div> <div class="box-inner"> <div id="older_bubble"> <p>Older revisions</p> <a href="/p/base2/source/list?path=/version/1.0.2/src/base2-legacy.js&start=310">All revisions of this file</a> </div> </div> <div class="round1"></div> <div class="round2"></div> <div class="round4"></div> </div> <div class="pmeta_bubble_bg" style="border:1px solid white"> <div class="round4"></div> <div class="round2"></div> <div class="round1"></div> <div class="box-inner"> <div id="fileinfo_bubble"> <p>File info</p> <div>Size: 7671 bytes, 241 lines</div> <div><a href="//base2.googlecode.com/svn/version/1.0.2/src/base2-legacy.js">View raw file</a></div> </div> <div id="props"> <p>File properties</p> <dl> <dt>svn:eol-style</dt> <dd>native</dd> <dt>svn:keywords</dt> <dd>Id</dd> <dt>svn:mime-type</dt> <dd>text/javascript</dd> </dl> </div> </div> <div class="round1"></div> <div class="round2"></div> <div class="round4"></div> </div> </div> </div> </div> </div> </div> <script src="https://ssl.gstatic.com/codesite/ph/16296466298460697337/js/prettify/prettify.js"></script> <script type="text/javascript">prettyPrint();</script> <script src="https://ssl.gstatic.com/codesite/ph/16296466298460697337/js/source_file_scripts.js"></script> <script type="text/javascript" src="https://ssl.gstatic.com/codesite/ph/16296466298460697337/js/kibbles.js"></script> <script type="text/javascript"> var lastStop = null; var initialized = false; function updateCursor(next, prev) { if (prev && prev.element) { prev.element.className = 'cursor_stop cursor_hidden'; } if (next && next.element) { next.element.className = 'cursor_stop cursor'; lastStop = next.index; } } function pubRevealed(data) { updateCursorForCell(data.cellId, 'cursor_stop cursor_hidden'); if (initialized) { reloadCursors(); } } function draftRevealed(data) { updateCursorForCell(data.cellId, 'cursor_stop cursor_hidden'); if (initialized) { reloadCursors(); } } function draftDestroyed(data) { updateCursorForCell(data.cellId, 'nocursor'); if (initialized) { reloadCursors(); } } function reloadCursors() { kibbles.skipper.reset(); loadCursors(); if (lastStop != null) { kibbles.skipper.setCurrentStop(lastStop); } } // possibly the simplest way to insert any newly added comments // is to update the class of the corresponding cursor row, // then refresh the entire list of rows. function updateCursorForCell(cellId, className) { var cell = document.getElementById(cellId); // we have to go two rows back to find the cursor location var row = getPreviousElement(cell.parentNode); row.className = className; } // returns the previous element, ignores text nodes. function getPreviousElement(e) { var element = e.previousSibling; if (element.nodeType == 3) { element = element.previousSibling; } if (element && element.tagName) { return element; } } function loadCursors() { // register our elements with skipper var elements = CR_getElements('*', 'cursor_stop'); var len = elements.length; for (var i = 0; i < len; i++) { var element = elements[i]; element.className = 'cursor_stop cursor_hidden'; kibbles.skipper.append(element); } } function toggleComments() { CR_toggleCommentDisplay(); reloadCursors(); } function keysOnLoadHandler() { // setup skipper kibbles.skipper.addStopListener( kibbles.skipper.LISTENER_TYPE.PRE, updateCursor); // Set the 'offset' option to return the middle of the client area // an option can be a static value, or a callback kibbles.skipper.setOption('padding_top', 50); // Set the 'offset' option to return the middle of the client area // an option can be a static value, or a callback kibbles.skipper.setOption('padding_bottom', 100); // Register our keys kibbles.skipper.addFwdKey("n"); kibbles.skipper.addRevKey("p"); kibbles.keys.addKeyPressListener( 'u', function() { window.location = detail_url; }); kibbles.keys.addKeyPressListener( 'r', function() { window.location = detail_url + '#publish'; }); kibbles.keys.addKeyPressListener('j', gotoNextPage); kibbles.keys.addKeyPressListener('k', gotoPreviousPage); } </script> <script src="https://ssl.gstatic.com/codesite/ph/16296466298460697337/js/code_review_scripts.js"></script> <script type="text/javascript"> function showPublishInstructions() { var element = document.getElementById('review_instr'); if (element) { element.className = 'opened'; } } var codereviews; function revsOnLoadHandler() { // register our source container with the commenting code var paths = {'svn310': '/version/1.0.2/src/base2-legacy.js'} codereviews = CR_controller.setup( {"assetHostPath": "https://ssl.gstatic.com/codesite/ph", "domainName": null, "profileUrl": null, "token": null, "relativeBaseUrl": "", "projectHomeUrl": "/p/base2", "loggedInUserEmail": null, "assetVersionPath": "https://ssl.gstatic.com/codesite/ph/16296466298460697337", "projectName": "base2"}, '', 'svn310', paths, CR_BrowseIntegrationFactory); codereviews.registerActivityListener(CR_ActivityType.REVEAL_DRAFT_PLATE, showPublishInstructions); codereviews.registerActivityListener(CR_ActivityType.REVEAL_PUB_PLATE, pubRevealed); codereviews.registerActivityListener(CR_ActivityType.REVEAL_DRAFT_PLATE, draftRevealed); codereviews.registerActivityListener(CR_ActivityType.DISCARD_DRAFT_COMMENT, draftDestroyed); var initialized = true; reloadCursors(); } window.onload = function() {keysOnLoadHandler(); revsOnLoadHandler();}; </script> <script type="text/javascript" src="https://ssl.gstatic.com/codesite/ph/16296466298460697337/js/dit_scripts.js"></script> <script type="text/javascript" src="https://ssl.gstatic.com/codesite/ph/16296466298460697337/js/ph_core.js"></script> </div> <div id="footer" dir="ltr"> <div class="text"> <a href="/projecthosting/terms.html">Terms</a> - <a href="http://www.google.com/privacy.html">Privacy</a> - <a href="/p/support/">Project Hosting Help</a> </div> </div> <div class="hostedBy" style="margin-top: -20px;"> <span style="vertical-align: top;">Powered by <a href="http://code.google.com/projecthosting/">Google Project Hosting</a></span> </div> </body> </html>
royalrover/miscases
js/dean-edwards-name/base2-legacy.js
JavaScript
mit
62,831
'use strict'; const config = require('config'); const redis = require('socket.io-redis'); const http = require('http'); const express = require('express'); const Log = require('./log'); const log = new Log(({ 'level': config.get('log.level'), 'prefix': 'server' })); // process.env.PORT is required to allow AWS to auto start the application on automated port numbers const serverPort = process.env.PORT || config.get('server.port') || 3000; const redisPort = config.get('redis.port') || 6379; const redisHost = config.get('redis.host') || 'localhost'; // socket.io namespace const namespace = '/'; class Server { constructor(port) { const app = express(); const server = http.createServer(app); const io = require('socket.io')(server); this.io = io; log.log(`connecting to redis server at ${redisHost}:${redisPort}`); // You must have a redis server up and running. // `6379` is the default port that redis runs on io.adapter(redis({ 'key': 'foobar', 'host': redisHost, 'port': redisPort, 'requestsTimeout': 2000 })); setupEvents(io, port); app.get('/health', (req, res) => res.sendStatus(200)); server.listen(port, () => { if (typeof PhusionPassenger !== 'undefined') { log.log(`running in passenger on localhost:${port}`); } else { log.log(`listening on localhost:${port}`); } }); } } // Can also run from the command line with the `serve [port]` command require('yargs') .usage('$0 <cmd> [args]') .command('serve [port]', 'start the server', (yargs) => { return yargs.option('port', { describe: 'Port that the socket server instance should bind on', default: serverPort }) }, (argv) => { log.info('Setting up from argv.port: ' + argv.port); new Server(argv.port); }) .help() .argv // Can create server if port supplied as PORT environment variable. // Remember we don't want to start a server on require(), as we want to keep this // Server() testable. if (process.env.PORT) { new Server(process.env.PORT); } module.exports = Server; function setupEvents(io, port) { io.on('connection', socket => { log.log(`client connected on port ${port}`); socket.on('disconnect', reason => { log.log('a client disconnected'); if (!reason) log.info('no reason given for disconnection'); return; log.log('disconnecting reason:', reason); }); socket.on('disconnecting', reason => { log.log('a client is disconnecting'); // We want to tell all rooms the socket had joined that the user is leaving. getClientRooms(io, socket.id) .then(rooms => { rooms.forEach(room => { emitRoomPopulationChange(io, socket, room); }); }) .catch(err => log.error(err)); if (!reason) log.info('no reason given for disconnection'); return; log.log('disconnecting reason:', reason); }); // We simply pass the data back socket.on('echo', data => { socket.emit('echo', data); }); socket.on('join room', data => { if (!data || !data.roomId) { log.error('no roomId was supplied'); return; } socket.join(data.roomId); emitRoomPopulationChange(io, socket, data.roomId); socket.emit('joined room', {'roomId': data.roomId}); log.info(`client joined room ${data.roomId}`); }); }); } function emitRoomPopulationChange(io, socket, roomId) { if (socket.id === roomId) { log.log('roomId and socket.id match, not broadcasting to personal room'); return; } // tell the user how many other users are in the room getRoomClients(io, roomId) .then(clients => { const count = clients.length; log.log('found', count, 'clients in room', roomId); socket.broadcast .to(roomId) .emit('room population changed', {'count': count}); }) .catch(err => log.error(err)); } function getClientRooms(io, socketId) { log.log('getting rooms for socketId', socketId); return new Promise((resolve, reject) => { io.of('/').adapter.clientRooms(socketId, (err, rooms) => { if (err) return reject(err); resolve(rooms); }); }); } function getRoomClients(io, roomId) { return new Promise((resolve, reject) => { io.in(roomId).clients((err, clients) => { if (err) return reject(err); resolve(clients); }); }); }
plumpNation/sockets-experiment
src/index.js
JavaScript
mit
4,945
if (typeof params.insecure === 'string' || !params.insecure) { params.insecure = params.insecure === 'true' ? true : false; } var fixUrl = function(url) { fixedUrl = ''; if (url.indexOf("http") !== 0) { if (params.insecure) { fixedUrl = 'http://' + url; } else { fixedUrl = 'https://' + url; } } return fixedUrl; }; var parseResponse = function(resp) { var res = null; if (resp.StatusCode >= 200 && resp.StatusCode < 300) { try { res = JSON.parse(resp.Body); } catch (e) { res = resp.Body; } } else { err = resp.Status; if (resp.Body) { err += '\n' + resp.Body; } throw err; } if (res && res.length && res.length > 1 ) { // response body is array, then put it into object // we don't want to return array return { result: res }; } else if (res && res.length === 0) { return {}; } else { return res; } }; var url = fixUrl(params.url); var login = function(params) { var fullUrl = fixUrl(params.url) + '/cm/api/v1.0/oauth2/token'; var body = { grant_type: 'client_credentials', client_id: params.clientId, client_secret: params.clientSecret }; var res = httpMultipart( fullUrl, '', { Method: 'POST' }, body, params.insecure ); return parseResponse(res); }; var listEndpoints = function(url, token) { var fullUrl = fixUrl(url) + '/cm/api/v1.0/endpoint'; var res = http( fullUrl, { Method: 'GET', Headers: {'Authorization': ['Bearer ' + token]} }, params.insecure ); return parseResponse(res); }; var setEndpointStatus = function(url, token, endpointId, action) { // validate action // action can be "enroll" or "revoke" if (action !== 'enroll' && action !== 'revoke') { throw 'action must be "enroll" or "revoke"!'; } var fullUrl = fixUrl(url) + '/cm/api/v1.0/endpoint/' + endpointId; var res = http( fullUrl, { Method: 'POST', Headers: { 'Authorization': ['Bearer ' + token], 'Content-Type': ['application/json'] }, Body: JSON.stringify({ action: action }) }, params.insecure ); parseResponse(res); return 'Success'; }; switch(command) { case 'test-module': login(params); return true; case 'imp-sf-list-endpoints': var loginRes = login(params); return listEndpoints(params.url, loginRes.access_token); case 'imp-sf-set-endpoint-status': var loginRes = login(params); return setEndpointStatus(params.url, loginRes.access_token, args.endpointId, args.action); default: return true; }
demisto/content
Packs/Imperva_Skyfence/Integrations/ImpervaSkyfence/ImpervaSkyfence.js
JavaScript
mit
2,939
var survivalGuideApp = angular.module('survivalGuideApp', [ 'localytics.directives', 'admin.module' ]); survivalGuideApp.config(function($interpolateProvider){ $interpolateProvider.startSymbol('{[{').endSymbol('}]}'); }); var adminModule = angular.module("admin.module", [ 'ui.tree', 'ngCkeditor', 'localytics.directives' ]); adminModule.directive('fileModel', ['$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ modelSetter(scope, element[0].files[0]); }); }); } }; }]);
donatienthorez/sf_mobilIT_backEnd
web/assets/js/angular/app.js
JavaScript
mit
804
window.onload = initApp; var formRegister; var database; var config = { apiKey: "AIzaSyDT9Mtc91Yx0zSrBylkZcjll8LyGvz0naY", authDomain: "openviosperu-80885.firebaseapp.com", databaseURL: "https://openviosperu-80885.firebaseio.com", storageBucket: "openviosperu-80885.appspot.com", messagingSenderId: "41996574751" }; firebase.initializeApp(config); //*projectId: "openviosperu-80885", function initApp(){ formRegister = document.getElementById('formRegisterFire'); formRegister.addEventListener('submit', sendRegister, false) database = firebase.database().ref().child('registro'); } function sendRegister(event){ var names=$('#NombresCompletos').val(); var emailForm = $('#Correo').val(); if(names != '' && emailForm != ''){ database.push({ ApellidosCompletos: event.target.ApellidosCompletos.value, Correo: event.target.Correo.value, DNI: event.target.DNI.value, Direccion: event.target.Direccion.value, NombresCompletos: event.target.NombresCompletos.value, RUC: event.target.RUC.value, Telefonos: event.target.Telefonos.value }); $('.hide_element').text('GRACIAS POR REGISTRARTE, ESTAREMOS EN CONTACTO!').show(); formRegister.reset(); event.preventDefault(); }else{ $('#NombresCompletos').css({ background: '#efaaaa', border: '#fd5858' }); $('#Correo').css({ background: '#efaaaa', border: '#fd5858' }) $('.hide_element').text('llenar los campos obligatorios.').show(); event.preventDefault(); } } function notifyMe() { // Let's check if the browser supports notifications if (!("Notification" in window)) { console.log(""); } // Let's check whether notification permissions have alredy been granted else if (Notification.permission === "granted") { // If it's okay let's create a notification var notification = new Notification("Gracias por registrarte!"); } // Otherwise, we need to ask the user for permission else if (Notification.permission !== 'denied' || Notification.permission === "default") { Notification.requestPermission(function (permission) { // If the user accepts, let's create a notification if (permission === "granted") { var notification = new Notification("Gracias por registrarte!"); } }); } // At last, if the user has denied notifications, and you // want to be respectful there is no need to bother them any more. } //*function writeUserData(nombre, apellidos, telefonos, correo, direccion,DNI, RUC){ //* firebase.database().ref('users/' + nombre + " " + apellidos).set({ //* nombre: nombre, //* apellidos: apellidos, //* telefonos: telefonos, //* correo: correo, //* direccion: direccion, //* DNI: DNI, //* RUC: RUC //* }); //*} //*var enviar = document.getElementById("enviar-btn"); //*var gracias = document.getElementById("gracias"); //* //*var formulario = document.getElementsByTagName("input"); //*var nombre = formulario[0].value; //*var apellidos = formulario[1].value; //*var telefonos = formulario[2].value; //*var correo = formulario[3].value; //*var direccion = formulario[4].value; //*var DNI = formulario[5].value; //*var RUC = formulario[6].value; //*enviar.addEventListener('click', function() //*{ //* formulario = document.getElementsByTagName("input"); //* nombre = formulario[0].value; //* apellidos = formulario[1].value; //* telefonos = formulario[2].value; //* correo = formulario[3].value; //* direccion = formulario[4].value; //* DNI = formulario[5].value; //* RUC = formulario[6].value; //* //* if(nombre=="" || apellidos=="" //* || telefonos=="" || correo=="" //* || direccion=="")return; //* //* writeUserData(nombre, apellidos,telefonos, correo,direccion,DNI, RUC); //* gracias.classList.remove("hide"); //* gracias.classList.add("show"); //* console.log(formulario, apellidos, telefonos, correo, direccion, DNI, RUC); //*});
ronnyfly2/openvios
source/public/js/dist/app.js
JavaScript
mit
4,147
import THREE from "three"; import qsp from "../node_modules/querystringparser/js/querystringparser.js"; import makeSeedHash from "./makeSeedHash.es6.js"; import scan from "./scan.es6.js"; var querystring = window.location.search ? window.location.search.substr(1):""; var qs = qsp.parse(querystring); var cfg = require("./config.json"); Object.keys(cfg).forEach((key) => { cfg[key] = qs[key] || cfg[key]; }); cfg.cubicSize = Math.pow(cfg.size, 3); cfg.size = parseInt(cfg.size); cfg.hash = qs.hash || makeSeedHash(cfg); cfg.scan = scan(cfg.size); cfg.clock = new THREE.Clock(); console.log("cfg.hash", cfg.hash); export default cfg;
lagora/proc.edu.ria
src/config.es6.js
JavaScript
mit
639
var nconf = require('nconf'); var DEFAULT_ENV = 'local'; module.exports.getConf = function() { nconf.argv().env().file({ file: __dirname + '/../env/' + this.getEnvCode() + '.json' }); return nconf; }; module.exports.getEnvCode = function() { var env = process.env.NODE_ENV; return env ? env : DEFAULT_ENV; };
dthorne/BasketMinderWeb
server/lib/env.js
JavaScript
mit
355
/* Russian (UTF-8) initialisation for the jQuery UI date picker plugin. */ jQuery(function(a){a.datepicker.regional.ru={closeText:"\u0417\u0430\u043a\u0440\u044b\u0442\u044c",prevText:"&#x3c;\u041f\u0440\u0435\u0434",nextText:"\u0421\u043b\u0435\u0434&#x3e;",currentText:"\u0421\u0435\u0433\u043e\u0434\u043d\u044f",monthNames:"\u042f\u043d\u0432\u0430\u0440\u044c,\u0424\u0435\u0432\u0440\u0430\u043b\u044c,\u041c\u0430\u0440\u0442,\u0410\u043f\u0440\u0435\u043b\u044c,\u041c\u0430\u0439,\u0418\u044e\u043d\u044c,\u0418\u044e\u043b\u044c,\u0410\u0432\u0433\u0443\u0441\u0442,\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c,\u041e\u043a\u0442\u044f\u0431\u0440\u044c,\u041d\u043e\u044f\u0431\u0440\u044c,\u0414\u0435\u043a\u0430\u0431\u0440\u044c".split(","), monthNamesShort:"\u042f\u043d\u0432,\u0424\u0435\u0432,\u041c\u0430\u0440,\u0410\u043f\u0440,\u041c\u0430\u0439,\u0418\u044e\u043d,\u0418\u044e\u043b,\u0410\u0432\u0433,\u0421\u0435\u043d,\u041e\u043a\u0442,\u041d\u043e\u044f,\u0414\u0435\u043a".split(","),dayNames:"\u0432\u043e\u0441\u043a\u0440\u0435\u0441\u0435\u043d\u044c\u0435,\u043f\u043e\u043d\u0435\u0434\u0435\u043b\u044c\u043d\u0438\u043a,\u0432\u0442\u043e\u0440\u043d\u0438\u043a,\u0441\u0440\u0435\u0434\u0430,\u0447\u0435\u0442\u0432\u0435\u0440\u0433,\u043f\u044f\u0442\u043d\u0438\u0446\u0430,\u0441\u0443\u0431\u0431\u043e\u0442\u0430".split(","), dayNamesShort:"\u0432\u0441\u043a,\u043f\u043d\u0434,\u0432\u0442\u0440,\u0441\u0440\u0434,\u0447\u0442\u0432,\u043f\u0442\u043d,\u0441\u0431\u0442".split(","),dayNamesMin:"\u0412\u0441,\u041f\u043d,\u0412\u0442,\u0421\u0440,\u0427\u0442,\u041f\u0442,\u0421\u0431".split(","),weekHeader:"\u041d\u0435\u0434",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""};a.datepicker.setDefaults(a.datepicker.regional.ru)});
ProJobless/nyus
themes/javascript/compressed/jquery/ui/i18n/jquery.ui.datepicker-ru.js
JavaScript
mit
1,825
version https://git-lfs.github.com/spec/v1 oid sha256:56298732b762cfe158d004737cd73e374ff5b8fb33fa49b6c890ba682794fbaf size 179655
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/2.0/config/Accessible.js
JavaScript
mit
131
core.require('/shape/circle.js','/arrow/arcArrow.js',function (circlePP,arrowPP) { let item = svg.Element.mk('<g/>');// the root of the diagram we are assembling let circleP = core.installPrototype(circlePP); let arrowP = core.installPrototype(arrowPP); item.p1 = Point.mk(-50,0); item.p2 = Point.mk(50,0); circleP.r = 12; circleP.fill = 'blue'; // instantiate it twice; items in the catalog // are initially hidden by convention, since they normally // serve as prototypes; hence __show(). item.set('circle1',circleP.instantiate()).show(); item.set('circle2',circleP.instantiate()).show(); // now the arrows // set some parameters of the arrow prototype arrowP.stroke = 'orange'; arrowP.radius = 1; // radius of the arc as a multiple of arrow length arrowP.tailGap = 18; // gap between tail of arrow and its designated start point arrowP.headGap = 18; // gap between head of arrow and its designated end arrowP.solidHead = false; // instantiate it twice item.set('arrow1',arrowP.instantiate()).show(); item.set('arrow2',arrowP.instantiate()).show(); item.update = function () { let p1=this.p1,p2 = this.p2; this.circle1.moveto(p1); this.circle2.moveto(p2); this.arrow1.setEnds(p1,p2); this.arrow2.setEnds(p2,p1); this.arrow1.update(); this.arrow2.update(); } item.isKit = true; item.dragStart = function (startPos) { // not needed for this example, but included for illustration } item.dragStep = function (node,pos) { let p = (node.__name === 'circle1')?this.p1:this.p2; p.copyto(pos); this.update(); this.draw(); } circleP.draggableInKit = true; return item; });
chrisGoad/prototypejungle
example/simpleDiagram.js
JavaScript
mit
1,605
/** * Proxy ajax calls on i-blocks */ BEM.blocks['i-router'].define('GET,POST', /^\/ajax\/([\w\-]+)\/([^_][\w]+)/, 'i-ajax-proxy'); BEM.decl('i-ajax-proxy', {}, { _blockList: [], /** * Allow to proxy blocks * * @param {String} blockName */ allowBlock: function (blockName) { this._blockList.push(blockName); }, _parseJSONParam: function (str) { try { if (str) { return JSON.parse(decodeURIComponent(BEM.blocks['i-content'].unescapeHTML(str))); } else { return {}; } } catch (err) { console.log(err); return false; } }, /** * Create and send response to client * @param data * @param json * @private */ _successResponse: function (json) { BEM.blocks['i-response'].json(json); }, /** * Handle error * @param err * @private */ _failureResponse: function (err) { if (BEM.blocks['i-api-request'].isHttpError(err)) { BEM.blocks['i-response'].send(err.status, err.message); } else { BEM.blocks['i-response'].error(err); throw err; } }, /** * Handle missing handler * @returns {*} * @private */ _missingResponse: function () { BEM.blocks['i-response'].missing(); return Vow.fulfill(''); }, _checkMethod: function (blockName, methodName) { return this._blockList.indexOf(blockName) !== -1 && BEM.blocks[blockName] && typeof BEM.blocks[blockName][methodName] === 'function'; }, _runMethod: function (blockName, methodName, data) { //do not parse json and check secret key data.requestSource = 'ajax'; data.params = this._parseJSONParam(data.params); data.resource = BEM.blocks['i-content'].unescapeHTML(data.resource); if (data.body) { data.body = BEM.blocks['i-content'].unescapeHTML(data.body); } return BEM.blocks[blockName][methodName]( data.resource, data ); }, /** * Response with json * * @param {Array} matchers */ init: function (matchers) { var blockName = matchers[1], methodName = matchers[2], data = BEM.blocks['i-router'].getParams(); if (this._checkMethod(blockName, methodName, data)) { return this._runMethod(blockName, methodName, data) .then(this._successResponse.bind(this)) .fail(this._failureResponse.bind(this)); } else { return this._missingResponse(); } } });
vladrudych/realvnz
node_modules/bem-node/blocks/i-ajax-proxy/i-ajax-proxy.priv.js
JavaScript
mit
2,735
'use strict'; const net = require('net'); const EventEmitter = require('events'); module.exports = BackendCommunicator; function BackendCommunicator(host, port) { let self = this; this.client = null; this.eventEmitter = null; this.init = function(host, port) { this.client = new net.Socket(); let puffer = ''; this.client.on('data', function(data) { puffer += data; let dataArray = puffer.split(String.fromCharCode(0)); for (let i = 0; i < dataArray.length - 1; i++) { try { let object = JSON.parse(dataArray[i]); if (typeof object.action === 'undefined') { throw new Error('Data has no "action" field.'); } console.log("BC: Got message ", object.action, object.data); self.eventEmitter.emit(object.action, object.data); } catch (e) { self.eventEmitter.emit('invalidRequest', dataArray[i], e.stack); } } puffer = dataArray[dataArray.length - 1]; }); this.client.on('error', function(error) { self.eventEmitter.emit('socketError', error); }); this.client.connect(port, host, function() { self.eventEmitter.emit('connected'); }); this.eventEmitter = new EventEmitter(); this.eventEmitter.on('error', function(a) { }); }; this.init(host, port); this.sendCommand = function(action, data) { console.log("BC: sending message ", action, data); this.client.write(JSON.stringify({action: action, data: data}) + String.fromCharCode(0)); }; }
byWulf/gcs-game-base-nodejs
lib/backendCommunicator.js
JavaScript
mit
1,747
// needs Markdown.Converter.js at the moment (function () { var util = {}, position = {}, ui = {}, doc = window.document, re = window.RegExp, nav = window.navigator, SETTINGS = { lineLength: 72 }, // Used to work around some browser bugs where we can't use feature testing. uaSniffed = { isIE: /msie/.test(nav.userAgent.toLowerCase()), isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()), isOpera: /opera/.test(nav.userAgent.toLowerCase()) }; var defaultsStrings = { bold: "Strong <strong> Ctrl+B", boldexample: "strong text", italic: "Emphasis <em> Ctrl+I", italicexample: "emphasized text", link: "Hyperlink <a> Ctrl+L", linkdescription: "enter link description here", linkdialog: "<p><b>Insert Hyperlink</b></p><p>http://example.com/ \"optional title\"</p>", quote: "Blockquote <blockquote> Ctrl+Q", quoteexample: "Blockquote", code: "Code Sample <pre><code> Ctrl+K", codeexample: "enter code here", image: "Image <img> Ctrl+G", imagedescription: "enter image description here", imagedialog: "<p><b>Insert Image</b></p><p>http://example.com/images/diagram.jpg \"optional title\"<br><br>Need <a href='http://www.google.com/search?q=free+image+hosting' target='_blank'>free image hosting?</a></p>", olist: "Numbered List <ol> Ctrl+O", ulist: "Bulleted List <ul> Ctrl+U", litem: "List item", heading: "Heading <h1>/<h2> Ctrl+H", headingexample: "Heading", hr: "Horizontal Rule <hr> Ctrl+R", undo: "Undo - Ctrl+Z", redo: "Redo - Ctrl+Y", redomac: "Redo - Ctrl+Shift+Z", help: "Markdown Editing Help" }; // ------------------------------------------------------------------- // YOUR CHANGES GO HERE // // I've tried to localize the things you are likely to change to // this area. // ------------------------------------------------------------------- // The default text that appears in the dialog input box when entering // links. var imageDefaultText = "http://"; var linkDefaultText = "http://"; // ------------------------------------------------------------------- // END OF YOUR CHANGES // ------------------------------------------------------------------- // options, if given, can have the following properties: // options.helpButton = { handler: yourEventHandler } // options.strings = { italicexample: "slanted text" } // `yourEventHandler` is the click handler for the help button. // If `options.helpButton` isn't given, not help button is created. // `options.strings` can have any or all of the same properties as // `defaultStrings` above, so you can just override some string displayed // to the user on a case-by-case basis, or translate all strings to // a different language. // // For backwards compatibility reasons, the `options` argument can also // be just the `helpButton` object, and `strings.help` can also be set via // `helpButton.title`. This should be considered legacy. // // The constructed editor object has the methods: // - getConverter() returns the markdown converter object that was passed to the constructor // - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op. // - refreshPreview() forces the preview to be updated. This method is only available after run() was called. Markdown.Editor = function (markdownConverter, idPostfix, options) { options = options || {}; if (typeof options.handler === "function") { //backwards compatible behavior options = { helpButton: options }; } options.strings = options.strings || {}; if (options.helpButton) { options.strings.help = options.strings.help || options.helpButton.title; } var getString = function (identifier) { return options.strings[identifier] || defaultsStrings[identifier]; } idPostfix = idPostfix || ""; var hooks = this.hooks = new Markdown.HookCollection(); hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates * its own image insertion dialog, this hook should return true, and the callback should be called with the chosen * image url (or null if the user cancelled). If this hook returns false, the default dialog will be used. */ this.getConverter = function () { return markdownConverter; } var that = this, panels; this.run = function () { if (panels) return; // already initialized panels = new PanelCollection(idPostfix); var commandManager = new CommandManager(hooks, getString); var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); }); var undoManager, uiManager; if (!/\?noundo/.test(doc.location.href)) { undoManager = new UndoManager(function () { previewManager.refresh(); if (uiManager) // not available on the first call uiManager.setUndoRedoButtonStates(); }, panels); this.textOperation = function (f) { undoManager.setCommandMode(); f(); that.refreshPreview(); } } uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, options.helpButton, getString); uiManager.setUndoRedoButtonStates(); var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); }; forceRefresh(); }; } // before: contains all the text in the input box BEFORE the selection. // after: contains all the text in the input box AFTER the selection. function Chunks() { } // startRegex: a regular expression to find the start tag // endRegex: a regular expresssion to find the end tag Chunks.prototype.findTags = function (startRegex, endRegex) { var chunkObj = this; var regex; if (startRegex) { regex = util.extendRegExp(startRegex, "", "$"); this.before = this.before.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); regex = util.extendRegExp(startRegex, "^", ""); this.selection = this.selection.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); } if (endRegex) { regex = util.extendRegExp(endRegex, "", "$"); this.selection = this.selection.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); regex = util.extendRegExp(endRegex, "^", ""); this.after = this.after.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); } }; // If remove is false, the whitespace is transferred // to the before/after regions. // // If remove is true, the whitespace disappears. Chunks.prototype.trimWhitespace = function (remove) { var beforeReplacer, afterReplacer, that = this; if (remove) { beforeReplacer = afterReplacer = ""; } else { beforeReplacer = function (s) { that.before += s; return ""; } afterReplacer = function (s) { that.after = s + that.after; return ""; } } this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer); }; Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) { if (nLinesBefore === undefined) { nLinesBefore = 1; } if (nLinesAfter === undefined) { nLinesAfter = 1; } nLinesBefore++; nLinesAfter++; var regexText; var replacementText; // chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985 if (navigator.userAgent.match(/Chrome/)) { "X".match(/()./); } this.selection = this.selection.replace(/(^\n*)/, ""); this.startTag = this.startTag + re.$1; this.selection = this.selection.replace(/(\n*$)/, ""); this.endTag = this.endTag + re.$1; this.startTag = this.startTag.replace(/(^\n*)/, ""); this.before = this.before + re.$1; this.endTag = this.endTag.replace(/(\n*$)/, ""); this.after = this.after + re.$1; if (this.before) { regexText = replacementText = ""; while (nLinesBefore--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.before = this.before.replace(new re(regexText + "$", ""), replacementText); } if (this.after) { regexText = replacementText = ""; while (nLinesAfter--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.after = this.after.replace(new re(regexText, ""), replacementText); } }; // end of Chunks // A collection of the important regions on the page. // Cached so we don't have to keep traversing the DOM. // Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around // this issue: // Internet explorer has problems with CSS sprite buttons that use HTML // lists. When you click on the background image "button", IE will // select the non-existent link text and discard the selection in the // textarea. The solution to this is to cache the textarea selection // on the button's mousedown event and set a flag. In the part of the // code where we need to grab the selection, we check for the flag // and, if it's set, use the cached area instead of querying the // textarea. // // This ONLY affects Internet Explorer (tested on versions 6, 7 // and 8) and ONLY on button clicks. Keyboard shortcuts work // normally since the focus never leaves the textarea. function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); this.preview = doc.getElementById("wmd-preview" + postfix); this.input = doc.getElementById("wmd-input" + postfix); }; // Returns true if the DOM element is visible, false if it's hidden. // Checks if display is anything other than none. util.isVisible = function (elem) { if (window.getComputedStyle) { // Most browsers return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none"; } else if (elem.currentStyle) { // IE return elem.currentStyle["display"] !== "none"; } }; // Adds a listener callback to a DOM element which is fired on a specified // event. util.addEvent = function (elem, event, listener) { if (elem.attachEvent) { // IE only. The "on" is mandatory. elem.attachEvent("on" + event, listener); } else { // Other browsers. elem.addEventListener(event, listener, false); } }; // Removes a listener callback from a DOM element which is fired on a specified // event. util.removeEvent = function (elem, event, listener) { if (elem.detachEvent) { // IE only. The "on" is mandatory. elem.detachEvent("on" + event, listener); } else { // Other browsers. elem.removeEventListener(event, listener, false); } }; // Converts \r\n and \r to \n. util.fixEolChars = function (text) { text = text.replace(/\r\n/g, "\n"); text = text.replace(/\r/g, "\n"); return text; }; // Extends a regular expression. Returns a new RegExp // using pre + regex + post as the expression. // Used in a few functions where we have a base // expression and we want to pre- or append some // conditions to it (e.g. adding "$" to the end). // The flags are unchanged. // // regex is a RegExp, pre and post are strings. util.extendRegExp = function (regex, pre, post) { if (pre === null || pre === undefined) { pre = ""; } if (post === null || post === undefined) { post = ""; } var pattern = regex.toString(); var flags; // Replace the flags with empty space and store them. pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) { flags = flagsPart; return ""; }); // Remove the slash delimiters on the regular expression. pattern = pattern.replace(/(^\/|\/$)/g, ""); pattern = pre + pattern + post; return new re(pattern, flags); } // UNFINISHED // The assignment in the while loop makes jslint cranky. // I'll change it to a better loop later. position.getTop = function (elem, isInner) { var result = elem.offsetTop; if (!isInner) { while (elem = elem.offsetParent) { result += elem.offsetTop; } } return result; }; position.getHeight = function (elem) { return elem.offsetHeight || elem.scrollHeight; }; position.getWidth = function (elem) { return elem.offsetWidth || elem.scrollWidth; }; position.getPageSize = function () { var scrollWidth, scrollHeight; var innerWidth, innerHeight; // It's not very clear which blocks work with which browsers. if (self.innerHeight && self.scrollMaxY) { scrollWidth = doc.body.scrollWidth; scrollHeight = self.innerHeight + self.scrollMaxY; } else if (doc.body.scrollHeight > doc.body.offsetHeight) { scrollWidth = doc.body.scrollWidth; scrollHeight = doc.body.scrollHeight; } else { scrollWidth = doc.body.offsetWidth; scrollHeight = doc.body.offsetHeight; } if (self.innerHeight) { // Non-IE browser innerWidth = self.innerWidth; innerHeight = self.innerHeight; } else if (doc.documentElement && doc.documentElement.clientHeight) { // Some versions of IE (IE 6 w/ a DOCTYPE declaration) innerWidth = doc.documentElement.clientWidth; innerHeight = doc.documentElement.clientHeight; } else if (doc.body) { // Other versions of IE innerWidth = doc.body.clientWidth; innerHeight = doc.body.clientHeight; } var maxWidth = Math.max(scrollWidth, innerWidth); var maxHeight = Math.max(scrollHeight, innerHeight); return [maxWidth, maxHeight, innerWidth, innerHeight]; }; // Handles pushing and popping TextareaStates for undo/redo commands. // I should rename the stack variables to list. function UndoManager(callback, panels) { var undoObj = this; var undoStack = []; // A stack of undo states var stackPtr = 0; // The index of the current state var mode = "none"; var lastState; // The last state var timer; // The setTimeout handle for cancelling the timer var inputStateObj; // Set the mode for later logic steps. var setMode = function (newMode, noSave) { if (mode != newMode) { mode = newMode; if (!noSave) { saveState(); } } if (!uaSniffed.isIE || mode != "moving") { timer = setTimeout(refreshState, 1); } else { inputStateObj = null; } }; var refreshState = function (isInitialState) { inputStateObj = new TextareaState(panels, isInitialState); timer = undefined; }; this.setCommandMode = function () { mode = "command"; saveState(); timer = setTimeout(refreshState, 0); }; this.canUndo = function () { return stackPtr > 1; }; this.canRedo = function () { if (undoStack[stackPtr + 1]) { return true; } return false; }; // Removes the last state and restores it. this.undo = function () { if (undoObj.canUndo()) { if (lastState) { // What about setting state -1 to null or checking for undefined? lastState.restore(); lastState = null; } else { undoStack[stackPtr] = new TextareaState(panels); undoStack[--stackPtr].restore(); if (callback) { callback(); } } } mode = "none"; panels.input.focus(); refreshState(); }; // Redo an action. this.redo = function () { if (undoObj.canRedo()) { undoStack[++stackPtr].restore(); if (callback) { callback(); } } mode = "none"; panels.input.focus(); refreshState(); }; // Push the input area state to the stack. var saveState = function () { var currState = inputStateObj || new TextareaState(panels); if (!currState) { return false; } if (mode == "moving") { if (!lastState) { lastState = currState; } return; } if (lastState) { if (undoStack[stackPtr - 1].text != lastState.text) { undoStack[stackPtr++] = lastState; } lastState = null; } undoStack[stackPtr++] = currState; undoStack[stackPtr + 1] = null; if (callback) { callback(); } }; var handleCtrlYZ = function (event) { var handled = false; if ((event.ctrlKey || event.metaKey) && !event.altKey) { // IE and Opera do not support charCode. var keyCode = event.charCode || event.keyCode; var keyCodeChar = String.fromCharCode(keyCode); switch (keyCodeChar.toLowerCase()) { case "y": undoObj.redo(); handled = true; break; case "z": if (!event.shiftKey) { undoObj.undo(); } else { undoObj.redo(); } handled = true; break; } } if (handled) { if (event.preventDefault) { event.preventDefault(); } if (window.event) { window.event.returnValue = false; } return; } }; // Set the mode depending on what is going on in the input area. var handleModeChange = function (event) { if (!event.ctrlKey && !event.metaKey) { var keyCode = event.keyCode; if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) { // 33 - 40: page up/dn and arrow keys // 63232 - 63235: page up/dn and arrow keys on safari setMode("moving"); } else if (keyCode == 8 || keyCode == 46 || keyCode == 127) { // 8: backspace // 46: delete // 127: delete setMode("deleting"); } else if (keyCode == 13) { // 13: Enter setMode("newlines"); } else if (keyCode == 27) { // 27: escape setMode("escape"); } else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) { // 16-20 are shift, etc. // 91: left window key // I think this might be a little messed up since there are // a lot of nonprinting keys above 20. setMode("typing"); } } }; var setEventHandlers = function () { util.addEvent(panels.input, "keypress", function (event) { // keyCode 89: y // keyCode 90: z if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.keyCode == 89 || event.keyCode == 90)) { event.preventDefault(); } }); var handlePaste = function () { if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) { if (timer == undefined) { mode = "paste"; saveState(); refreshState(); } } }; util.addEvent(panels.input, "keydown", handleCtrlYZ); util.addEvent(panels.input, "keydown", handleModeChange); util.addEvent(panels.input, "mousedown", function () { setMode("moving"); }); panels.input.onpaste = handlePaste; panels.input.ondrop = handlePaste; }; var init = function () { setEventHandlers(); refreshState(true); saveState(); }; init(); } // end of UndoManager // The input textarea state/contents. // This is used to implement undo/redo by the undo manager. function TextareaState(panels, isInitialState) { // Aliases var stateObj = this; var inputArea = panels.input; this.init = function () { if (!util.isVisible(inputArea)) { return; } if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box return; } this.setInputAreaSelectionStartEnd(); this.scrollTop = inputArea.scrollTop; if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) { this.text = inputArea.value; } } // Sets the selected text in the input box after we've performed an // operation. this.setInputAreaSelection = function () { if (!util.isVisible(inputArea)) { return; } if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) { inputArea.focus(); inputArea.selectionStart = stateObj.start; inputArea.selectionEnd = stateObj.end; inputArea.scrollTop = stateObj.scrollTop; } else if (doc.selection) { if (doc.activeElement && doc.activeElement !== inputArea) { return; } inputArea.focus(); var range = inputArea.createTextRange(); range.moveStart("character", -inputArea.value.length); range.moveEnd("character", -inputArea.value.length); range.moveEnd("character", stateObj.end); range.moveStart("character", stateObj.start); range.select(); } }; this.setInputAreaSelectionStartEnd = function () { if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) { stateObj.start = inputArea.selectionStart; stateObj.end = inputArea.selectionEnd; } else if (doc.selection) { stateObj.text = util.fixEolChars(inputArea.value); // IE loses the selection in the textarea when buttons are // clicked. On IE we cache the selection. Here, if something is cached, // we take it. var range = panels.ieCachedRange || doc.selection.createRange(); var fixedRange = util.fixEolChars(range.text); var marker = "\x07"; var markedRange = marker + fixedRange + marker; range.text = markedRange; var inputText = util.fixEolChars(inputArea.value); range.moveStart("character", -markedRange.length); range.text = fixedRange; stateObj.start = inputText.indexOf(marker); stateObj.end = inputText.lastIndexOf(marker) - marker.length; var len = stateObj.text.length - util.fixEolChars(inputArea.value).length; if (len) { range.moveStart("character", -fixedRange.length); while (len--) { fixedRange += "\n"; stateObj.end += 1; } range.text = fixedRange; } if (panels.ieCachedRange) stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange panels.ieCachedRange = null; this.setInputAreaSelection(); } }; // Restore this state into the input area. this.restore = function () { if (stateObj.text != undefined && stateObj.text != inputArea.value) { inputArea.value = stateObj.text; } this.setInputAreaSelection(); inputArea.scrollTop = stateObj.scrollTop; }; // Gets a collection of HTML chunks from the inptut textarea. this.getChunks = function () { var chunk = new Chunks(); chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start)); chunk.startTag = ""; chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end)); chunk.endTag = ""; chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end)); chunk.scrollTop = stateObj.scrollTop; return chunk; }; // Sets the TextareaState properties given a chunk of markdown. this.setChunks = function (chunk) { chunk.before = chunk.before + chunk.startTag; chunk.after = chunk.endTag + chunk.after; this.start = chunk.before.length; this.end = chunk.before.length + chunk.selection.length; this.text = chunk.before + chunk.selection + chunk.after; this.scrollTop = chunk.scrollTop; }; this.init(); }; function PreviewManager(converter, panels, previewRefreshCallback) { var managerObj = this; var timeout; var elapsedTime; var oldInputText; var maxDelay = 3000; var startType = "delayed"; // The other legal value is "manual" // Adds event listeners to elements var setupEvents = function (inputElem, listener) { util.addEvent(inputElem, "input", listener); inputElem.onpaste = listener; inputElem.ondrop = listener; util.addEvent(inputElem, "keypress", listener); util.addEvent(inputElem, "keydown", listener); }; var getDocScrollTop = function () { var result = 0; if (window.innerHeight) { result = window.pageYOffset; } else if (doc.documentElement && doc.documentElement.scrollTop) { result = doc.documentElement.scrollTop; } else if (doc.body) { result = doc.body.scrollTop; } return result; }; var makePreviewHtml = function () { // If there is no registered preview panel // there is nothing to do. if (!panels.preview) return; var text = panels.input.value; if (text && text == oldInputText) { return; // Input text hasn't changed. } else { oldInputText = text; } var prevTime = new Date().getTime(); text = converter.makeHtml(text); // Calculate the processing time of the HTML creation. // It's used as the delay time in the event listener. var currTime = new Date().getTime(); elapsedTime = currTime - prevTime; pushPreviewHtml(text); }; // setTimeout is already used. Used as an event listener. var applyTimeout = function () { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (startType !== "manual") { var delay = 0; if (startType === "delayed") { delay = elapsedTime; } if (delay > maxDelay) { delay = maxDelay; } timeout = setTimeout(makePreviewHtml, delay); } }; var getScaleFactor = function (panel) { if (panel.scrollHeight <= panel.clientHeight) { return 1; } return panel.scrollTop / (panel.scrollHeight - panel.clientHeight); }; var setPanelScrollTops = function () { if (panels.preview) { panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview); } }; this.refresh = function (requiresRefresh) { if (requiresRefresh) { oldInputText = ""; makePreviewHtml(); } else { applyTimeout(); } }; this.processingTime = function () { return elapsedTime; }; var isFirstTimeFilled = true; // IE doesn't let you use innerHTML if the element is contained somewhere in a table // (which is the case for inline editing) -- in that case, detach the element, set the // value, and reattach. Yes, that *is* ridiculous. var ieSafePreviewSet = function (text) { var preview = panels.preview; var parent = preview.parentNode; var sibling = preview.nextSibling; parent.removeChild(preview); preview.innerHTML = text; if (!sibling) parent.appendChild(preview); else parent.insertBefore(preview, sibling); } var nonSuckyBrowserPreviewSet = function (text) { panels.preview.innerHTML = text; } var previewSetter; var previewSet = function (text) { if (previewSetter) return previewSetter(text); try { nonSuckyBrowserPreviewSet(text); previewSetter = nonSuckyBrowserPreviewSet; } catch (e) { previewSetter = ieSafePreviewSet; previewSetter(text); } }; var pushPreviewHtml = function (text) { var emptyTop = position.getTop(panels.input) - getDocScrollTop(); if (panels.preview) { previewSet(text); previewRefreshCallback(); } setPanelScrollTops(); if (isFirstTimeFilled) { isFirstTimeFilled = false; return; } var fullTop = position.getTop(panels.input) - getDocScrollTop(); if (uaSniffed.isIE) { setTimeout(function () { window.scrollBy(0, fullTop - emptyTop); }, 0); } else { window.scrollBy(0, fullTop - emptyTop); } }; var init = function () { setupEvents(panels.input, applyTimeout); makePreviewHtml(); if (panels.preview) { panels.preview.scrollTop = 0; } }; init(); }; // Creates the background behind the hyperlink text entry box. // And download dialog // Most of this has been moved to CSS but the div creation and // browser-specific hacks remain here. ui.createBackground = function () { var background = doc.createElement("div"), style = background.style; background.className = "wmd-prompt-background"; style.position = "absolute"; style.top = "0"; style.zIndex = "1000"; if (uaSniffed.isIE) { style.filter = "alpha(opacity=50)"; } else { style.opacity = "0.5"; } var pageSize = position.getPageSize(); style.height = pageSize[1] + "px"; if (uaSniffed.isIE) { style.left = doc.documentElement.scrollLeft; style.width = doc.documentElement.clientWidth; } else { style.left = "0"; style.width = "100%"; } doc.body.appendChild(background); return background; }; // This simulates a modal dialog box and asks for the URL when you // click the hyperlink or image buttons. // // text: The html for the input box. // defaultInputText: The default value that appears in the input box. // callback: The function which is executed when the prompt is dismissed, either via OK or Cancel. // It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel // was chosen). ui.prompt = function (text, defaultInputText, callback) { // These variables need to be declared at this level since they are used // in multiple functions. var dialog; // The dialog box. var input; // The text box where you enter the hyperlink. if (defaultInputText === undefined) { defaultInputText = ""; } // Used as a keydown event handler. Esc dismisses the prompt. // Key code 27 is ESC. var checkEscape = function (key) { var code = (key.charCode || key.keyCode); if (code === 27) { close(true); } }; // Dismisses the hyperlink input box. // isCancel is true if we don't care about the input text. // isCancel is false if we are going to keep the text. var close = function (isCancel) { util.removeEvent(doc.body, "keydown", checkEscape); var text = input.value; if (isCancel) { text = null; } else { // Fixes common pasting errors. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://'); if (!/^(?:https?|ftp):\/\//.test(text)) text = 'http://' + text; } dialog.parentNode.removeChild(dialog); callback(text); return false; }; // Create the text input box form/window. var createDialog = function () { // The main dialog box. dialog = doc.createElement("div"); dialog.className = "wmd-prompt-dialog"; dialog.style.padding = "10px;"; dialog.style.position = "fixed"; dialog.style.width = "400px"; dialog.style.zIndex = "1001"; // The dialog text. var question = doc.createElement("div"); question.innerHTML = text; question.style.padding = "5px"; dialog.appendChild(question); // The web form container for the text box and buttons. var form = doc.createElement("form"), style = form.style; form.onsubmit = function () { return close(false); }; style.padding = "0"; style.margin = "0"; style.cssFloat = "left"; style.width = "100%"; style.textAlign = "center"; style.position = "relative"; dialog.appendChild(form); // The input text box input = doc.createElement("input"); input.type = "text"; input.value = defaultInputText; style = input.style; style.display = "block"; style.width = "80%"; style.marginLeft = style.marginRight = "auto"; form.appendChild(input); // The ok button var okButton = doc.createElement("input"); okButton.type = "button"; okButton.onclick = function () { return close(false); }; okButton.value = "OK"; style = okButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; // The cancel button var cancelButton = doc.createElement("input"); cancelButton.type = "button"; cancelButton.onclick = function () { return close(true); }; cancelButton.value = "Cancel"; style = cancelButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; form.appendChild(okButton); form.appendChild(cancelButton); util.addEvent(doc.body, "keydown", checkEscape); dialog.style.top = "50%"; dialog.style.left = "50%"; dialog.style.display = "block"; if (uaSniffed.isIE_5or6) { dialog.style.position = "absolute"; dialog.style.top = doc.documentElement.scrollTop + 200 + "px"; dialog.style.left = "50%"; } doc.body.appendChild(dialog); // This has to be done AFTER adding the dialog to the form if you // want it to be centered. dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px"; dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px"; }; // Why is this in a zero-length timeout? // Is it working around a browser bug? setTimeout(function () { createDialog(); var defTextLen = defaultInputText.length; if (input.selectionStart !== undefined) { input.selectionStart = 0; input.selectionEnd = defTextLen; } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(false); range.moveStart("character", -defTextLen); range.moveEnd("character", defTextLen); range.select(); } input.focus(); }, 0); }; function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions, getString) { var inputBox = panels.input, buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements. makeSpritedButtonRow(); var keyEvent = "keydown"; if (uaSniffed.isOpera) { keyEvent = "keypress"; } util.addEvent(inputBox, keyEvent, function (key) { // Check to see if we have a button key and, if so execute the callback. if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) { var keyCode = key.charCode || key.keyCode; var keyCodeStr = String.fromCharCode(keyCode).toLowerCase(); switch (keyCodeStr) { case "b": doClick(buttons.bold); break; case "i": doClick(buttons.italic); break; case "l": doClick(buttons.link); break; case "q": doClick(buttons.quote); break; case "k": doClick(buttons.code); break; case "g": doClick(buttons.image); break; case "o": doClick(buttons.olist); break; case "u": doClick(buttons.ulist); break; case "h": doClick(buttons.heading); break; case "r": doClick(buttons.hr); break; case "y": doClick(buttons.redo); break; case "z": if (key.shiftKey) { doClick(buttons.redo); } else { doClick(buttons.undo); } break; default: return; } if (key.preventDefault) { key.preventDefault(); } if (window.event) { window.event.returnValue = false; } } }); // Auto-indent on shift-enter util.addEvent(inputBox, "keyup", function (key) { if (key.shiftKey && !key.ctrlKey && !key.metaKey) { var keyCode = key.charCode || key.keyCode; // Character 13 is Enter if (keyCode === 13) { var fakeButton = {}; fakeButton.textOp = bindCommand("doAutoindent"); doClick(fakeButton); } } }); // special handler because IE clears the context of the textbox on ESC if (uaSniffed.isIE) { util.addEvent(inputBox, "keydown", function (key) { var code = key.keyCode; if (code === 27) { return false; } }); } // Perform the button's action. function doClick(button) { inputBox.focus(); if (button.textOp) { if (undoManager) { undoManager.setCommandMode(); } var state = new TextareaState(panels); if (!state) { return; } var chunks = state.getChunks(); // Some commands launch a "modal" prompt dialog. Javascript // can't really make a modal dialog box and the WMD code // will continue to execute while the dialog is displayed. // This prevents the dialog pattern I'm used to and means // I can't do something like this: // // var link = CreateLinkDialog(); // makeMarkdownLink(link); // // Instead of this straightforward method of handling a // dialog I have to pass any code which would execute // after the dialog is dismissed (e.g. link creation) // in a function parameter. // // Yes this is awkward and I think it sucks, but there's // no real workaround. Only the image and link code // create dialogs and require the function pointers. var fixupInputArea = function () { inputBox.focus(); if (chunks) { state.setChunks(chunks); } state.restore(); previewManager.refresh(); }; var noCleanup = button.textOp(chunks, fixupInputArea); if (!noCleanup) { fixupInputArea(); } } if (button.execute) { button.execute(undoManager); } }; function setupButton(button, isEnabled) { var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var image = button.getElementsByTagName("span")[0]; if (isEnabled) { image.style.backgroundPosition = button.XShift + " " + normalYShift; button.onmouseover = function () { image.style.backgroundPosition = this.XShift + " " + highlightYShift; }; button.onmouseout = function () { image.style.backgroundPosition = this.XShift + " " + normalYShift; }; // IE tries to select the background image "button" text (it's // implemented in a list item) so we have to cache the selection // on mousedown. if (uaSniffed.isIE) { button.onmousedown = function () { if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection return; } panels.ieCachedRange = document.selection.createRange(); panels.ieCachedScrollTop = panels.input.scrollTop; }; } if (!button.isHelp) { button.onclick = function () { if (this.onmouseout) { this.onmouseout(); } doClick(this); return false; } } } else { image.style.backgroundPosition = button.XShift + " " + disabledYShift; button.onmouseover = button.onmouseout = button.onclick = function () { }; } } function bindCommand(method) { if (typeof method === "string") method = commandManager[method]; return function () { method.apply(commandManager, arguments); } } function makeSpritedButtonRow() { var buttonBar = panels.buttonBar; var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var buttonRow = document.createElement("ul"); buttonRow.id = "wmd-button-row" + postfix; buttonRow.className = 'wmd-button-row'; buttonRow = buttonBar.appendChild(buttonRow); var xPosition = 0; var makeButton = function (id, title, XShift, textOp) { var button = document.createElement("li"); button.className = "wmd-button"; button.style.left = xPosition + "px"; xPosition += 25; var buttonImage = document.createElement("span"); button.id = id + postfix; button.appendChild(buttonImage); button.title = title; button.XShift = XShift; if (textOp) button.textOp = textOp; setupButton(button, true); buttonRow.appendChild(button); return button; }; var makeSpacer = function (num) { var spacer = document.createElement("li"); spacer.className = "wmd-spacer wmd-spacer" + num; spacer.id = "wmd-spacer" + num + postfix; buttonRow.appendChild(spacer); xPosition += 25; } buttons.bold = makeButton("wmd-bold-button", getString("bold"), "0px", bindCommand("doBold")); buttons.italic = makeButton("wmd-italic-button", getString("italic"), "-20px", bindCommand("doItalic")); makeSpacer(1); buttons.link = makeButton("wmd-link-button", getString("link"), "-40px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, false); })); // commented out temporarily by nickelchen // buttons.quote = makeButton("wmd-quote-button", getString("quote"), "-60px", bindCommand("doBlockquote")); // buttons.code = makeButton("wmd-code-button", getString("code"), "-80px", bindCommand("doCode")); buttons.image = makeButton("wmd-image-button", getString("image"), "-100px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, true); })); makeSpacer(2); buttons.olist = makeButton("wmd-olist-button", getString("olist"), "-120px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, true); })); buttons.ulist = makeButton("wmd-ulist-button", getString("ulist"), "-140px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, false); })); buttons.heading = makeButton("wmd-heading-button", getString("heading"), "-160px", bindCommand("doHeading")); buttons.hr = makeButton("wmd-hr-button", getString("hr"), "-180px", bindCommand("doHorizontalRule")); makeSpacer(3); buttons.undo = makeButton("wmd-undo-button", getString("undo"), "-200px", null); buttons.undo.execute = function (manager) { if (manager) manager.undo(); }; var redoTitle = /win/.test(nav.platform.toLowerCase()) ? getString("redo") : getString("redomac"); // mac and other non-Windows platforms buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null); buttons.redo.execute = function (manager) { if (manager) manager.redo(); }; if (helpOptions) { var helpButton = document.createElement("li"); var helpButtonImage = document.createElement("span"); helpButton.appendChild(helpButtonImage); helpButton.className = "wmd-button wmd-help-button"; helpButton.id = "wmd-help-button" + postfix; helpButton.XShift = "-240px"; helpButton.isHelp = true; helpButton.style.right = "0px"; helpButton.title = getString("help"); helpButton.onclick = helpOptions.handler; setupButton(helpButton, true); buttonRow.appendChild(helpButton); buttons.help = helpButton; } setUndoRedoButtonStates(); } function setUndoRedoButtonStates() { if (undoManager) { setupButton(buttons.undo, undoManager.canUndo()); setupButton(buttons.redo, undoManager.canRedo()); } }; this.setUndoRedoButtonStates = setUndoRedoButtonStates; } function CommandManager(pluginHooks, getString) { this.hooks = pluginHooks; this.getString = getString; } var commandProto = CommandManager.prototype; // The markdown symbols - 4 spaces = code, > = blockquote, etc. commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)"; // Remove markdown symbols from the chunk selection. commandProto.unwrap = function (chunk) { var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g"); chunk.selection = chunk.selection.replace(txt, "$1 $2"); }; commandProto.wrap = function (chunk, len) { this.unwrap(chunk); var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"), that = this; chunk.selection = chunk.selection.replace(regex, function (line, marked) { if (new re("^" + that.prefixes, "").test(line)) { return line; } return marked + "\n"; }); chunk.selection = chunk.selection.replace(/\s+$/, ""); }; commandProto.doBold = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 2, this.getString("boldexample")); }; commandProto.doItalic = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 1, this.getString("italicexample")); }; // chunk: The selected region that will be enclosed with */** // nStars: 1 for italics, 2 for bold // insertText: If you just click the button without highlighting text, this gets inserted commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) { // Get rid of whitespace and fixup newlines. chunk.trimWhitespace(); chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n"); // Look for stars before and after. Is the chunk already marked up? // note that these regex matches cannot fail var starsBefore = /(\**$)/.exec(chunk.before)[0]; var starsAfter = /(^\**)/.exec(chunk.after)[0]; var prevStars = Math.min(starsBefore.length, starsAfter.length); // Remove stars if we have to since the button acts as a toggle. if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) { chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), ""); chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), ""); } else if (!chunk.selection && starsAfter) { // It's not really clear why this code is necessary. It just moves // some arbitrary stuff around. chunk.after = chunk.after.replace(/^([*_]*)/, ""); chunk.before = chunk.before.replace(/(\s?)$/, ""); var whitespace = re.$1; chunk.before = chunk.before + starsAfter + whitespace; } else { // In most cases, if you don't have any selected text and click the button // you'll get a selected, marked up region with the default text inserted. if (!chunk.selection && !starsAfter) { chunk.selection = insertText; } // Add the true markup. var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ? chunk.before = chunk.before + markup; chunk.after = markup + chunk.after; } return; }; commandProto.stripLinkDefs = function (text, defsToAdd) { text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm, function (totalMatch, id, link, newlines, title) { defsToAdd[id] = totalMatch.replace(/\s*$/, ""); if (newlines) { // Strip the title and return that separately. defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, ""); return newlines + title; } return ""; }); return text; }; commandProto.addLinkDef = function (chunk, linkDef) { var refNumber = 0; // The current reference number var defsToAdd = {}; // // Start with a clean slate by removing all previous link definitions. chunk.before = this.stripLinkDefs(chunk.before, defsToAdd); chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd); chunk.after = this.stripLinkDefs(chunk.after, defsToAdd); var defs = ""; var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g; var addDefNumber = function (def) { refNumber++; def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:"); defs += "\n" + def; }; // note that // a) the recursive call to getLink cannot go infinite, because by definition // of regex, inner is always a proper substring of wholeMatch, and // b) more than one level of nesting is neither supported by the regex // nor making a lot of sense (the only use case for nesting is a linked image) var getLink = function (wholeMatch, before, inner, afterInner, id, end) { inner = inner.replace(regex, getLink); if (defsToAdd[id]) { addDefNumber(defsToAdd[id]); return before + inner + afterInner + refNumber + end; } return wholeMatch; }; chunk.before = chunk.before.replace(regex, getLink); if (linkDef) { addDefNumber(linkDef); } else { chunk.selection = chunk.selection.replace(regex, getLink); } var refOut = refNumber; chunk.after = chunk.after.replace(regex, getLink); if (chunk.after) { chunk.after = chunk.after.replace(/\n*$/, ""); } if (!chunk.after) { chunk.selection = chunk.selection.replace(/\n*$/, ""); } chunk.after += "\n\n" + defs; return refOut; }; // takes the line as entered into the add link/as image dialog and makes // sure the URL and the optinal title are "nice". function properlyEncoded(linkdef) { return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) { link = link.replace(/\?.*$/, function (querypart) { return querypart.replace(/\+/g, " "); // in the query string, a plus and a space are identical }); link = decodeURIComponent(link); // unencode first, to prevent double encoding link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29'); link = link.replace(/\?.*$/, function (querypart) { return querypart.replace(/\+/g, "%2b"); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded }); if (title) { title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, ""); title = title.replace(/"/g, "quot;").replace(/\(/g, "&#40;").replace(/\)/g, "&#41;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } return title ? link + ' "' + title + '"' : link; }); } commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) { chunk.trimWhitespace(); chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/); var background; if (chunk.endTag.length > 1 && chunk.startTag.length > 0) { chunk.startTag = chunk.startTag.replace(/!?\[/, ""); chunk.endTag = ""; this.addLinkDef(chunk, null); } else { // We're moving start and end tag back into the selection, since (as we're in the else block) we're not // *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the // link text. linkEnteredCallback takes care of escaping any brackets. chunk.selection = chunk.startTag + chunk.selection + chunk.endTag; chunk.startTag = chunk.endTag = ""; if (/\n\n/.test(chunk.selection)) { this.addLinkDef(chunk, null); return; } var that = this; // The function to be executed when you enter a link and press OK or Cancel. // Marks up the link and adds the ref. var linkEnteredCallback = function (link) { background.parentNode.removeChild(background); if (link !== null) { // ( $1 // [^\\] anything that's not a backslash // (?:\\\\)* an even number (this includes zero) of backslashes // ) // (?= followed by // [[\]] an opening or closing bracket // ) // // In other words, a non-escaped bracket. These have to be escaped now to make sure they // don't count as the end of the link or similar. // Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets), // the bracket in one match may be the "not a backslash" character in the next match, so it // should not be consumed by the first match. // The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the // start of the string, so this also works if the selection begins with a bracket. We cannot solve // this by anchoring with ^, because in the case that the selection starts with two brackets, this // would mean a zero-width match at the start. Since zero-width matches advance the string position, // the first bracket could then not act as the "not a backslash" for the second. chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1); var linkDef = " [999]: " + properlyEncoded(link); var num = that.addLinkDef(chunk, linkDef); chunk.startTag = isImage ? "![" : "["; chunk.endTag = "][" + num + "]"; if (!chunk.selection) { if (isImage) { chunk.selection = that.getString("imagedescription"); } else { chunk.selection = that.getString("linkdescription"); } } } postProcessing(); }; background = ui.createBackground(); if (isImage) { if (!this.hooks.insertImageDialog(linkEnteredCallback)) ui.prompt(this.getString("imagedialog"), imageDefaultText, linkEnteredCallback); } else { ui.prompt(this.getString("linkdialog"), linkDefaultText, linkEnteredCallback); } return true; } }; // When making a list, hitting shift-enter will put your cursor on the next line // at the current indent level. commandProto.doAutoindent = function (chunk, postProcessing) { var commandMgr = this, fakeSelection = false; chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n"); // There's no selection, end the cursor wasn't at the end of the line: // The user wants to split the current list item / code line / blockquote line // (for the latter it doesn't really matter) in two. Temporarily select the // (rest of the) line to achieve this. if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) { chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) { chunk.selection = wholeMatch; return ""; }); fakeSelection = true; } if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doList) { commandMgr.doList(chunk); } } if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doBlockquote) { commandMgr.doBlockquote(chunk); } } if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { if (commandMgr.doCode) { commandMgr.doCode(chunk); } } if (fakeSelection) { chunk.after = chunk.selection + chunk.after; chunk.selection = ""; } }; commandProto.doBlockquote = function (chunk, postProcessing) { chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/, function (totalMatch, newlinesBefore, text, newlinesAfter) { chunk.before += newlinesBefore; chunk.after = newlinesAfter + chunk.after; return text; }); chunk.before = chunk.before.replace(/(>[ \t]*)$/, function (totalMatch, blankLine) { chunk.selection = blankLine + chunk.selection; return ""; }); chunk.selection = chunk.selection.replace(/^(\s|>)+$/, ""); chunk.selection = chunk.selection || this.getString("quoteexample"); // The original code uses a regular expression to find out how much of the // text *directly before* the selection already was a blockquote: /* if (chunk.before) { chunk.before = chunk.before.replace(/\n?$/, "\n"); } chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/, function (totalMatch) { chunk.startTag = totalMatch; return ""; }); */ // This comes down to: // Go backwards as many lines a possible, such that each line // a) starts with ">", or // b) is almost empty, except for whitespace, or // c) is preceeded by an unbroken chain of non-empty lines // leading up to a line that starts with ">" and at least one more character // and in addition // d) at least one line fulfills a) // // Since this is essentially a backwards-moving regex, it's susceptible to // catstrophic backtracking and can cause the browser to hang; // see e.g. http://meta.stackoverflow.com/questions/9807. // // Hence we replaced this by a simple state machine that just goes through the // lines and checks for a), b), and c). var match = "", leftOver = "", line; if (chunk.before) { var lines = chunk.before.replace(/\n$/, "").split("\n"); var inChain = false; for (var i = 0; i < lines.length; i++) { var good = false; line = lines[i]; inChain = inChain && line.length > 0; // c) any non-empty line continues the chain if (/^>/.test(line)) { // a) good = true; if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain inChain = true; } else if (/^[ \t]*$/.test(line)) { // b) good = true; } else { good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain } if (good) { match += line + "\n"; } else { leftOver += match + line; match = "\n"; } } if (!/(^|\n)>/.test(match)) { // d) leftOver += match; match = ""; } } chunk.startTag = match; chunk.before = leftOver; // end of change if (chunk.after) { chunk.after = chunk.after.replace(/^\n?/, "\n"); } chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/, function (totalMatch) { chunk.endTag = totalMatch; return ""; } ); var replaceBlanksInTags = function (useBracket) { var replacement = useBracket ? "> " : ""; if (chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } if (chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } }; if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) { this.wrap(chunk, SETTINGS.lineLength - 2); chunk.selection = chunk.selection.replace(/^/gm, "> "); replaceBlanksInTags(true); chunk.skipLines(); } else { chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, ""); this.unwrap(chunk); replaceBlanksInTags(false); if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n"); } if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n"); } } chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection); if (!/\n/.test(chunk.selection)) { chunk.selection = chunk.selection.replace(/^(> *)/, function (wholeMatch, blanks) { chunk.startTag += blanks; return ""; }); } }; commandProto.doCode = function (chunk, postProcessing) { var hasTextBefore = /\S[ ]*$/.test(chunk.before); var hasTextAfter = /^[ ]*\S/.test(chunk.after); // Use 'four space' markdown if the selection is on its own // line or is multiline. if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) { chunk.before = chunk.before.replace(/[ ]{4}$/, function (totalMatch) { chunk.selection = totalMatch + chunk.selection; return ""; }); var nLinesBack = 1; var nLinesForward = 1; if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { nLinesBack = 0; } if (/^\n(\t|[ ]{4,})/.test(chunk.after)) { nLinesForward = 0; } chunk.skipLines(nLinesBack, nLinesForward); if (!chunk.selection) { chunk.startTag = " "; chunk.selection = this.getString("codeexample"); } else { if (/^[ ]{0,3}\S/m.test(chunk.selection)) { if (/\n/.test(chunk.selection)) chunk.selection = chunk.selection.replace(/^/gm, " "); else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior chunk.before += " "; } else { chunk.selection = chunk.selection.replace(/^(?:[ ]{4}|[ ]{0,3}\t)/gm, ""); } } } else { // Use backticks (`) to delimit the code block. chunk.trimWhitespace(); chunk.findTags(/`/, /`/); if (!chunk.startTag && !chunk.endTag) { chunk.startTag = chunk.endTag = "`"; if (!chunk.selection) { chunk.selection = this.getString("codeexample"); } } else if (chunk.endTag && !chunk.startTag) { chunk.before += chunk.endTag; chunk.endTag = ""; } else { chunk.startTag = chunk.endTag = ""; } } }; commandProto.doList = function (chunk, postProcessing, isNumberedList) { // These are identical except at the very beginning and end. // Should probably use the regex extension function to make this clearer. var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/; var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/; // The default bullet is a dash but others are possible. // This has nothing to do with the particular HTML bullet, // it's just a markdown bullet. var bullet = "-"; // The number in a numbered list. var num = 1; // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list. var getItemPrefix = function () { var prefix; if (isNumberedList) { prefix = " " + num + ". "; num++; } else { prefix = " " + bullet + " "; } return prefix; }; // Fixes the prefixes of the other list items. var getPrefixedItem = function (itemText) { // The numbering flag is unset when called by autoindent. if (isNumberedList === undefined) { isNumberedList = /^\s*\d/.test(itemText); } // Renumber/bullet the list element. itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm, function (_) { return getItemPrefix(); }); return itemText; }; chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null); if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) { chunk.before += chunk.startTag; chunk.startTag = ""; } if (chunk.startTag) { var hasDigits = /\d+[.]/.test(chunk.startTag); chunk.startTag = ""; chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n"); this.unwrap(chunk); chunk.skipLines(); if (hasDigits) { // Have to renumber the bullet points if this is a numbered list. chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem); } if (isNumberedList == hasDigits) { return; } } var nLinesUp = 1; chunk.before = chunk.before.replace(previousItemsRegex, function (itemText) { if (/^\s*([*+-])/.test(itemText)) { bullet = re.$1; } nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); if (!chunk.selection) { chunk.selection = this.getString("litem"); } var prefix = getItemPrefix(); var nLinesDown = 1; chunk.after = chunk.after.replace(nextItemsRegex, function (itemText) { nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); chunk.trimWhitespace(true); chunk.skipLines(nLinesUp, nLinesDown, true); chunk.startTag = prefix; var spaces = prefix.replace(/./g, " "); this.wrap(chunk, SETTINGS.lineLength - spaces.length); chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces); }; commandProto.doHeading = function (chunk, postProcessing) { // Remove leading/trailing whitespace and reduce internal spaces to single spaces. chunk.selection = chunk.selection.replace(/\s+/g, " "); chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, ""); // If we clicked the button with no selected text, we just // make a level 2 hash header around some default text. if (!chunk.selection) { chunk.startTag = "## "; chunk.selection = this.getString("headingexample"); chunk.endTag = " ##"; return; } var headerLevel = 0; // The existing header level of the selected text. // Remove any existing hash heading markdown and save the header level. chunk.findTags(/#+[ ]*/, /[ ]*#+/); if (/#+/.test(chunk.startTag)) { headerLevel = re.lastMatch.length; } chunk.startTag = chunk.endTag = ""; // Try to get the current header level by looking for - and = in the line // below the selection. chunk.findTags(null, /\s?(-+|=+)/); if (/=+/.test(chunk.endTag)) { headerLevel = 1; } if (/-+/.test(chunk.endTag)) { headerLevel = 2; } // Skip to the next line so we can create the header markdown. chunk.startTag = chunk.endTag = ""; chunk.skipLines(1, 1); // We make a level 2 header if there is no current header. // If there is a header level, we substract one from the header level. // If it's already a level 1 header, it's removed. var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1; if (headerLevelToCreate > 0) { // The button only creates level 1 and 2 underline headers. // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner? var headerChar = headerLevelToCreate >= 2 ? "-" : "="; var len = chunk.selection.length; if (len > SETTINGS.lineLength) { len = SETTINGS.lineLength; } chunk.endTag = "\n"; while (len--) { chunk.endTag += headerChar; } } }; commandProto.doHorizontalRule = function (chunk, postProcessing) { chunk.startTag = "----------\n"; chunk.selection = ""; chunk.skipLines(2, 1, true); } })();
nickelchen/mdeditor_rails
vendor/assets/javascript/pagedown/Markdown.Editor.js
JavaScript
mit
82,932
// Defines NgShowController controller of a module lee.dorian.ng.NgModel angular.module( "lee.dorian.ng.NgShow", [] ).controller("NgShowController", [ // Refer to - https://www.w3schools.com/angular/angular_scopes.asp "$scope", // This method is called when its controller is defined. constructNgShowController ]); function constructNgShowController($scope) { // This property is a flag to decide whether to show an image. $scope.imageVisibility = true; // This method will be called by a click event from Show button. $scope.showImage = function () { $scope.imageVisibility = true; }; // This method will be called by a click event from Hide button. $scope.hideImage = function() { $scope.imageVisibility = false; }; }
netrance/Dorian-AngularJS-Examples
ng_ex-ngShow/NgShowController.js
JavaScript
mit
814
import React, { PropTypes } from 'react' import { Router, Route, Redirect, IndexRedirect, browserHistory } from 'react-router' import App from './components/app' import Cluster from './containers/cluster' import Jobs from './containers/jobs' import Job from './containers/job' import JobInfo from './components/JobInfo/JobInfo' import JobAllocs from './components/JobAllocations/JobAllocations' import JobEvals from './components/JobEvaluations/JobEvaluations' import JobTaskGroups from './components/JobTaskGroups/JobTaskGroups' import JobRaw from './components/JobRaw/JobRaw' import Allocations from './containers/allocations' import Allocation from './containers/allocation' import AllocInfo from './components/AllocationInfo/AllocationInfo' import AllocFiles from './components/AllocationFiles/AllocationFiles' import AllocRaw from './components/AllocationRaw/AllocationRaw' import Evaluations from './containers/evaluations' import Evaluation from './containers/evaluation' import EvalInfo from './components/EvaluationInfo/EvaluationInfo' import EvalAllocations from './components/EvaluationAllocations/EvaluationAllocations' import EvalRaw from './components/EvaluationRaw/EvaluationRaw' import Clients from './containers/clients' import Client from './containers/client' import ClientInfo from './components/ClientInfo/ClientInfo' import ClientStats from './components/ClientStats/ClientStats' import ClientAllocations from './components/ClientAllocations/ClientAllocations' import ClientEvaluations from './components/ClientEvaluations/ClientEvaluations' import ClientRaw from './components/ClientRaw/ClientRaw' import Servers from './containers/servers' import Server from './containers/server' import ServerInfo from './components/ServerInfo/ServerInfo' import ServerRaw from './components/ServerRaw/ServerRaw' import SelectNomadRegion from './containers/select_nomad_region' import ConsulKV from './containers/consul_kv' import ConsulServices from './containers/consul_services' import ConsulNodes from './containers/consul_nodes' import SelectConsulRegion from './containers/select_consul_region' const AppRouter = ({ history }) => <Router history={ history }> <Route path='/' component={ App }> // Legacy routes <Redirect from='/cluster' to='/nomad' /> <Redirect from='/servers' to='/nomad' /> <Redirect from='/servers/**' to='/nomad' /> <Redirect from='/clients' to='/nomad' /> <Redirect from='/clients/**' to='/nomad' /> <Redirect from='/jobs' to='/nomad' /> <Redirect from='/jobs/**' to='/nomad' /> <Redirect from='/allocations' to='/nomad' /> <Redirect from='/allocations/**' to='/nomad' /> <Redirect from='/evaluations/' to='/nomad' /> <Redirect from='/evaluations/**' to='/nomad' /> <IndexRedirect to='/nomad' /> // Consul <Route path='/consul' component={ SelectConsulRegion } /> <Redirect from='/consul/:region' to='/consul/:region/services' /> <Route path='/consul/:region/kv' component={ ConsulKV } /> <Route path='/consul/:region/kv/*' component={ ConsulKV } /> <Route path='/consul/:region/nodes' component={ ConsulNodes } /> <Route path='/consul/:region/nodes/:name' component={ ConsulNodes } /> <Route path='/consul/:region/services' component={ ConsulServices } /> <Route path='/consul/:region/services/:name' component={ ConsulServices } /> // Nomad <Route path='/nomad' component={ SelectNomadRegion } /> <Redirect from='/nomad/:region' to='/nomad/:region/cluster' /> <Route path='/nomad/:region/cluster' component={ Cluster } /> <Route path='/nomad/:region/servers' component={ Servers } /> <Route path='/nomad/:region/servers/:memberId' component={ Server }> <IndexRedirect to='/nomad/:region/servers/:memberId/info' /> <Route path='/nomad/:region/servers/:memberId/info' component={ ServerInfo } /> <Route path='/nomad/:region/servers/:memberId/raw' component={ ServerRaw } /> </Route> <Route path='/nomad/:region/jobs' component={ Jobs } /> <Route path='/nomad/:region/jobs/:jobId' component={ Job }> <IndexRedirect to='/nomad/:region/jobs/:jobId/info' /> <Route path='/nomad/:region/jobs/:jobId/info' component={ JobInfo } /> <Route path='/nomad/:region/jobs/:jobId/allocations' component={ JobAllocs } /> <Route path='/nomad/:region/jobs/:jobId/evaluations' component={ JobEvals } /> <Route path='/nomad/:region/jobs/:jobId/groups' component={ JobTaskGroups } /> <Route path='/nomad/:region/jobs/:jobId/raw' component={ JobRaw } /> </Route> <Route path='/nomad/:region/clients' component={ Clients } /> <Route path='/nomad/:region/clients/:nodeId' component={ Client }> <IndexRedirect to='/nomad/:region/clients/:nodeId/info' /> <Route path='/nomad/:region/clients/:nodeId/info' component={ ClientInfo } /> <Route path='/nomad/:region/clients/:nodeId/stats' component={ ClientStats } /> <Route path='/nomad/:region/clients/:nodeId/allocations' component={ ClientAllocations } /> <Route path='/nomad/:region/clients/:nodeId/evaluations' component={ ClientEvaluations } /> <Route path='/nomad/:region/clients/:nodeId/raw' component={ ClientRaw } /> </Route> <Route path='/nomad/:region/allocations' component={ Allocations } /> <Route path='/nomad/:region/allocations/:allocId' component={ Allocation }> <IndexRedirect to='/nomad/:region/allocations/:allocId/info' /> <Route path='/nomad/:region/allocations/:allocId/info' component={ AllocInfo } /> <Redirect from='/nomad/:region/allocations/:allocId/logs' to='/nomad/:region/allocations/:allocId/files' query={{ path: '/alloc/logs/' }} /> <Route path='/nomad/:region/allocations/:allocId/files' component={ AllocFiles } query={{ path: '' }} /> <Route path='/nomad/:region/allocations/:allocId/raw' component={ AllocRaw } /> </Route> <Route path='/nomad/:region/evaluations' component={ Evaluations } /> <Route path='/nomad/:region/evaluations/:evalId' component={ Evaluation }> <IndexRedirect to='/nomad/:region/evaluations/:evalId/info' /> <Route path='/nomad/:region/evaluations/:evalId/info' component={ EvalInfo } /> <Route path='/nomad/:region/evaluations/:evalId/allocations' component={ EvalAllocations } /> <Route path='/nomad/:region/evaluations/:evalId/raw' component={ EvalRaw } /> </Route> </Route> </Router> AppRouter.propTypes = { history: PropTypes.instanceOf(browserHistory.constructor).isRequired } export default AppRouter
Wintermute1/hashi-ui
frontend/src/router.js
JavaScript
mit
6,739
angular.module('moola').directive('contextMenu', ['$parse', function ($parse) { var self = this; return { restrict: 'A', scope: {}, link: function($scope, $elem, attrs){ var button = attrs.contextButton === undefined ? 2 : attrs.contextButton; $elem.hide(); $elem.addClass('context-menu'); $elem.parent().mousedown(function(e){ if (e.button!=button) return; console.log(e); $elem.fadeIn(150); setTimeout(function(){ $('body').bind('mousedown', hideFunction); if ($elem.offset().left < 0) $elem.css('transform', 'translateX('+(-$elem.offset().left)+'px)'); },10); }); var hideFunction = function(){ $('body').unbind('mousedown', hideFunction); setTimeout(function(){ $elem.fadeOut(250); },50); } } } }]);
Kjoep/moola
moola-webapp/src/main/webapp/contextMenu/contextMenu.js
JavaScript
mit
1,055
const http = require('http'); const url = require('url'); const querystring = require('querystring'); const oc = require('oc'); module.exports = (port, cb) => { port = port || 4000; cb = cb || function() { console.log('started'); }; const client = new oc.Client({ registries: { clientRendering: 'http://localhost:3000/', serverRendering: 'http://localhost:3000/' } }); return http .createServer(function(req, res) { const parameters = querystring.parse(url.parse(req.url).query); const components = [ { name: 'oc-client' }, { name: 'base-component-es6', parameters }, { name: 'base-component-handlebars', parameters }, { name: 'base-component-jade', parameters } ]; const options = { container: false, disableFailoverRendering: true, timeout: 100 }; client.renderComponents(components, options, function( err, [ocClient, es6Component, handlebarsComponent, jadeComponent] ) { if (err) { throw err; } res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); const html = `<!DOCTYPE html> <html> <head> <title>A page</title> </head> <body> ${es6Component.replace(/data-hash=\".*?\"/, '')} ${handlebarsComponent} ${jadeComponent} ${ocClient} </body> </html> `; res.end(html); }); }) .listen(port, cb); };
opencomponents/oc-template-jade
acceptance-setup/server.js
JavaScript
mit
1,569
'use strict'; angular.module('transcript.service.resource', ['ui.router']) .service('ResourceService', function($log, $http, $rootScope, $filter) { return { getResource: function(id_resource, profile) { let profileStr = ""; if(profile !== undefined) { profileStr = "?profile="+profile; } return $http.get($rootScope.api+"/resources/"+id_resource+profileStr ).then(function(response) { return response.data; }, function errorCallback(response) { $log.debug(response); return response; }); }, getResourceIntern: function(entity, idResource) { let resource = null; for(let idR in entity.resources) { if(entity.resources[idR]['id'] === idResource) { resource = entity.resources[idR]; break; } } return resource; }, postResource: function(resource) { return $http.post($rootScope.api+"/resources", resource). then(function(response) { return response.data; }, function errorCallback(response) { $log.debug(response); return response; }); }, getContributionsNumberByUser: function(resource, user) { let count = 0; for(let idV in resource['transcript']['_embedded']['version']) { let version = resource['transcript']['_embedded']['version'][idV]; if(version['username'] === user.email) { count++; } } return count; }, getContributors: function(resource) { let arrayContributors = []; for(let idV in resource['transcript']['_embedded']['version']) { let version = resource['transcript']['_embedded']['version'][idV]; if(!$filter('contains')(arrayContributors, version['username'])) { arrayContributors.push(version['username']); } } return arrayContributors; } }; }) ;
TranscribeToTEI/webapp
app/System/Services/ResourceService.js
JavaScript
mit
2,477
// external dependencies var natural = require('natural'); var inflector = new natural.NounInflector(); var _ = require('lodash-node/modern'); module.exports = function() { var site = this; var config = this.config; var Query = this.Query; var Post = this.Post; var Handlebars = this.Handlebars; function capitalize(word) { return word[0].toUpperCase() + word.slice(1); } function renderQuery(params, options) { var query = new Query(params, site.posts.all()); return _.map(query.run(), function(post) { return options.fn(post); }).join(''); } _.each(config.postTypes, function(type) { Handlebars.registerHelper('each' + capitalize(type), function(options) { var params = _.assign({type: type}, options.hash); return renderQuery(params, options); }); }); Handlebars.registerHelper('query', function(options) { return renderQuery(this.query, options); }); };
philipwalton/ingen
plugins/handlebars-helpers/query.js
JavaScript
mit
938
$(document).ready(function () { // send an HTTP DELETE request for the sign-out link $('a#sign-out').on("click", function (e) { e.preventDefault(); var request = $.ajax({ url: $(this).attr('href'), type: 'delete' }); request.done(function () { window.location = "/"; }); }); var generate_options = function(options) { options_array = []; for(i = 0; i < options.length; i++) { options_array.push('<input type="radio" name="options" value="' + options[i] + '"> ' + options[i] + '<br>'); }; return options_array }; $('#new_question').on('submit', function(event) { event.preventDefault(); var new_question = ( $( this ).serialize() ); $.ajax({ url: '/new_question', type: 'post', data: new_question, dataType: 'json' }).done( function(response) { var content = response.content var options = response.options var generated_options = generate_options(options); $('#new_questions').append('<div class="question"><h4>' + content + '</h4>' + generated_options.join("") + '<input type="hidden" name="question_id" value="' + response.question_id + '"></div>'); $('#no_questions').addClass('hidden'); $('input[type="text"]').val(''); }).fail( function(response) { console.log('you failllllled: ' + response) }); }); });
fiddler-crabs-2014/SurveyCoco
coco/public/js/application.js
JavaScript
mit
1,346
const { expect } = require('chai'); const nock = require('nock'); const API_URL = 'https://tenant.auth0.com'; const RolesManager = require(`../../src/management/RolesManager`); const { ArgumentError } = require('rest-facade'); describe('RolesManager', () => { before(function () { this.token = 'TOKEN'; this.roles = new RolesManager({ headers: { authorization: `Bearer ${this.token}` }, baseUrl: API_URL, }); }); describe('instance', () => { const methods = [ 'get', 'getAll', 'create', 'update', 'delete', 'getPermissions', 'addPermissions', 'removePermissions', 'getUsers', 'assignUsers', ]; methods.forEach((method) => { it(`should have a ${method} method`, function () { expect(this.roles[method]).to.exist.to.be.an.instanceOf(Function); }); }); }); describe('#constructor', () => { it('should error when no options are provided', () => { expect(() => { new RolesManager(); }).to.throw(ArgumentError, 'Must provide manager options'); }); it('should throw an error when no base URL is provided', () => { expect(() => { new RolesManager({}); }).to.throw(ArgumentError, 'Must provide a base URL for the API'); }); it('should throw an error when the base URL is invalid', () => { expect(() => { new RolesManager({ baseUrl: '' }); }).to.throw(ArgumentError, 'The provided base URL is invalid'); }); }); describe('#getAll', () => { beforeEach(function () { this.request = nock(API_URL).get('/roles').reply(200); }); it('should accept a callback', function (done) { this.roles.getAll(() => { done(); }); }); it('should return a promise if no callback is given', function (done) { this.roles.getAll().then(done.bind(null, null)).catch(done.bind(null, null)); }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).get('/roles').reply(500); this.roles.getAll().catch((err) => { expect(err).to.exist; done(); }); }); it('should pass the body of the response to the "then" handler', async function () { nock.cleanAll(); const data = [{ test: true }]; nock(API_URL).get('/roles').reply(200, data); const credentials = await this.roles.getAll(); expect(credentials).to.be.an.instanceOf(Array); expect(credentials.length).to.equal(data.length); expect(credentials[0].test).to.equal(data[0].test); }); it('should perform a GET request to /api/v2/roles', async function () { const { request } = this; await this.roles.getAll(); expect(request.isDone()).to.be.true; }); it('should include the token in the Authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) .get('/roles') .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); await this.roles.getAll(); expect(request.isDone()).to.be.true; }); it('should pass the parameters in the query-string', async function () { nock.cleanAll(); const params = { include_fields: true, fields: 'test', }; const request = nock(API_URL).get('/roles').query(params).reply(200); await this.roles.getAll(params); expect(request.isDone()).to.be.true; }); }); describe('#get', () => { beforeEach(function () { this.data = { id: 'rol_ID', name: 'My role', description: 'This is my role', }; this.request = nock(API_URL).get(`/roles/${this.data.id}`).reply(200, this.data); }); it('should accept a callback', function (done) { const params = { id: this.data.id }; this.roles.get(params, done.bind(null, null)); }); it('should return a promise if no callback is given', function (done) { this.roles.get({ id: this.data.id }).then(done.bind(null, null)).catch(done.bind(null, null)); }); it('should perform a POST request to /api/v2/roles/rol_ID', async function () { const { request } = this; await this.roles.get({ id: this.data.id }); expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).get(`/roles/${this.data.id}`).reply(500); this.roles.get({ id: this.data.id }).catch((err) => { expect(err).to.exist; done(); }); }); it('should include the token in the Authorization header', function (done) { nock.cleanAll(); const request = nock(API_URL) .get(`/roles/${this.data.id}`) .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); this.roles.get({ id: this.data.id }).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); describe('#create', () => { const data = { id: 'rol_ID', name: 'My role', description: 'This is my role', }; beforeEach(function () { this.request = nock(API_URL).post('/roles').reply(200); }); it('should accept a callback', function (done) { this.roles.create(data, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { this.roles.create(data).then(done.bind(null, null)).catch(done.bind(null, null)); }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).post('/roles').reply(500); this.roles.create(data).catch((err) => { expect(err).to.exist; done(); }); }); it('should perform a POST request to /api/v2/roles', async function () { const { request } = this; await this.roles.create(data); expect(request.isDone()).to.be.true; }); it('should pass the data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).post('/roles', data).reply(200); await this.roles.create(data); expect(request.isDone()).to.be.true; }); it('should include the token in the Authorization header', function (done) { nock.cleanAll(); const request = nock(API_URL) .post('/roles') .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); this.roles.create(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); describe('#update', () => { beforeEach(function () { this.data = { id: 'rol_ID' }; this.request = nock(API_URL).patch(`/roles/${this.data.id}`).reply(200, this.data); }); it('should accept a callback', function (done) { this.roles.update({ id: 'rol_ID' }, {}, done.bind(null, null)); }); it('should return a promise if no callback is given', function (done) { this.roles .update({ id: 'rol_ID' }, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); it('should perform a PATCH request to /api/v2/roles/rol_ID', function (done) { const { request } = this; this.roles.update({ id: 'rol_ID' }, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); it('should include the new data in the body of the request', async function () { nock.cleanAll(); const request = nock(API_URL).patch(`/roles/${this.data.id}`, this.data).reply(200); await this.roles.update({ id: 'rol_ID' }, this.data); expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).patch(`/roles/${this.data.id}`).reply(500); this.roles.update({ id: this.data.id }, this.data).catch((err) => { expect(err).to.exist; done(); }); }); }); describe('#delete', () => { const id = 'rol_ID'; beforeEach(function () { this.request = nock(API_URL).delete(`/roles/${id}`).reply(200); }); it('should accept a callback', function (done) { this.roles.delete({ id }, done.bind(null, null)); }); it('should return a promise when no callback is given', function () { expect(this.roles.delete({ id })).instanceOf(Promise); }); it(`should perform a delete request to /roles/${id}`, async function () { const { request } = this; await this.roles.delete({ id }); expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).delete(`/roles/${id}`).reply(500); this.roles.delete({ id }).catch((err) => { expect(err).to.exist; done(); }); }); it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) .delete(`/roles/${id}`) .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); await this.roles.delete({ id }); expect(request.isDone()).to.be.true; }); }); describe('#getPermissions', () => { const data = { id: 'role_id', }; beforeEach(function () { this.request = nock(API_URL).get(`/roles/${data.id}/permissions`).reply(200); }); it('should accept a callback', function (done) { this.roles.getPermissions(data, done.bind(null, null)); }); it('should return a promise when no callback is given', function () { expect(this.roles.getPermissions(data)).instanceOf(Promise); }); it('should perform a GET request to /api/v2/roles/rol_ID/permissions', async function () { const { request } = this; await this.roles.getPermissions(data); expect(request.isDone()).to.be.true; }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).get(`/roles/${data.id}/permissions`).reply(500); this.roles.getPermissions(data).catch((err) => { expect(err).to.exist; done(); }); }); it('should include the token in the authorization header', async function () { nock.cleanAll(); const request = nock(API_URL) .get(`/roles/${data.id}/permissions`) .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); await this.roles.getPermissions(data); expect(request.isDone()).to.be.true; }); }); describe('#addPermissions', () => { beforeEach(function () { this.data = { id: 'rol_ID', }; this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; this.request = nock(API_URL).post(`/roles/${this.data.id}/permissions`).reply(200); }); it('should accept a callback', function (done) { this.roles.addPermissions(this.data, {}, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { this.roles .addPermissions(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).post(`/roles/${this.data.id}/permissions`).reply(500); this.roles.addPermissions(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); it('should perform a POST request to /api/v2/roles/rol_ID/permissions', async function () { const { request } = this; await this.roles.addPermissions(this.data, {}); expect(request.isDone()).to.be.true; }); it('should pass the data in the body of the request', function (done) { nock.cleanAll(); const request = nock(API_URL) .post(`/roles/${this.data.id}/permissions`, this.body) .reply(200); this.roles.addPermissions(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); it('should include the token in the Authorization header', function (done) { nock.cleanAll(); const request = nock(API_URL) .post(`/roles/${this.data.id}/permissions`) .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); this.roles.addPermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); describe('#removePermissions', () => { beforeEach(function () { this.data = { id: 'rol_ID', }; this.body = { permission_name: 'My Permission', resource_server_identifier: 'test123' }; this.request = nock(API_URL).delete(`/roles/${this.data.id}/permissions`, {}).reply(200); }); it('should validate empty roleId', function () { const _this = this; expect(() => { _this.roles.removePermissions({ id: null }, _this.body, () => {}); }).to.throw('The roleId passed in params cannot be null or undefined'); }); it('should validate non-string roleId', function () { const _this = this; expect(() => { _this.roles.removePermissions({ id: 123 }, _this.body, () => {}); }).to.throw('The role Id has to be a string'); }); it('should accept a callback', function (done) { this.roles.removePermissions(this.data, {}, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { this.roles .removePermissions(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).post(`/roles/${this.data.id}/permissions`).reply(500); this.roles.removePermissions(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); it('should perform a DELETE request to /api/v2/roles/rol_ID/permissions', function (done) { const { request } = this; this.roles.removePermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); it('should pass the data in the body of the request', function (done) { nock.cleanAll(); const request = nock(API_URL) .delete(`/roles/${this.data.id}/permissions`, this.body) .reply(200); this.roles.removePermissions(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); it('should include the token in the Authorization header', function (done) { nock.cleanAll(); const request = nock(API_URL) .delete(`/roles/${this.data.id}/permissions`) .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); this.roles.removePermissions(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); describe('#getUsers', () => { const data = { id: 'role_id', }; beforeEach(function () { this.request = nock(API_URL).get(`/roles/${data.id}/users`).reply(200); }); it('should accept a callback', function (done) { this.roles.getUsers(data, done.bind(null, null)); }); it('should return a promise when no callback is given', function (done) { this.roles.getUsers(data).then(done.bind(null, null)); }); it('should perform a GET request to /api/v2/roles/rol_Id/users', function (done) { const { request } = this; this.roles.getUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).get(`/roles/${data.id}/users`).reply(500); this.roles.getUsers(data).catch((err) => { expect(err).to.exist; done(); }); }); it('should include the token in the authorization header', function (done) { nock.cleanAll(); const request = nock(API_URL) .get(`/roles/${data.id}/users`) .matchHeader('authorization', `Bearer ${this.token}`) .reply(200); this.roles.getUsers(data).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); describe('#assignUsers', () => { beforeEach(function () { this.data = { id: 'rol_ID', }; this.body = { users: ['userID1'] }; this.request = nock(API_URL).post(`/roles/${this.data.id}/users`).reply(200); }); it('should validate empty roleId', function () { const _this = this; expect(() => { _this.roles.assignUsers({ id: null }, _this.body, () => {}); }).to.throw('The roleId passed in params cannot be null or undefined'); }); it('should validate non-string roleId', function () { const _this = this; expect(() => { _this.roles.assignUsers({ id: 123 }, _this.body, () => {}); }).to.throw('The role Id has to be a string'); }); it('should accept a callback', function (done) { this.roles.assignUsers(this.data, {}, () => { done(); }); }); it('should return a promise if no callback is given', function (done) { this.roles .assignUsers(this.data, {}) .then(done.bind(null, null)) .catch(done.bind(null, null)); }); it('should pass any errors to the promise catch handler', function (done) { nock.cleanAll(); nock(API_URL).post(`/roles/${this.data.id}/users`).reply(500); this.roles.assignUsers(this.data, {}).catch((err) => { expect(err).to.exist; done(); }); }); it('should perform a POST request to /api/v2/roles/rol_ID/users', function (done) { const { request } = this; this.roles.assignUsers(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); it('should perform a POST request to /api/v2/roles/rol_ID/users with a callback', function (done) { const { request } = this; this.roles.assignUsers(this.data, {}, () => { expect(request.isDone()).to.be.true; done(); }); }); it('should pass the data in the body of the request', function (done) { nock.cleanAll(); const request = nock(API_URL).post(`/roles/${this.data.id}/users`, this.body).reply(200); this.roles.assignUsers(this.data, this.body).then(() => { expect(request.isDone()).to.be.true; done(); }); }); it('should include the token in the Authorization header', function (done) { nock.cleanAll(); const request = nock(API_URL) .post(`/roles/${this.data.id}/users`) .matchHeader('Authorization', `Bearer ${this.token}`) .reply(200); this.roles.assignUsers(this.data, {}).then(() => { expect(request.isDone()).to.be.true; done(); }); }); }); });
auth0/node-auth0
test/management/roles.tests.js
JavaScript
mit
19,433
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'client/bower_components/jquery/dist/jquery.js', 'client/bower_components/angular/angular.js', 'client/bower_components/angular-mocks/angular-mocks.js', 'client/bower_components/angular-resource/angular-resource.js', 'client/bower_components/angular-cookies/angular-cookies.js', 'client/bower_components/angular-sanitize/angular-sanitize.js', 'client/bower_components/angular-route/angular-route.js', 'client/bower_components/angular-bootstrap/ui-bootstrap-tpls.js', 'client/bower_components/lodash/dist/lodash.compat.js', 'client/bower_components/angular-socket-io/socket.js', 'client/bower_components/angular-ui-router/release/angular-ui-router.js', 'client/bower_components/ng-tags-input.min.js', 'client/app/app.js', 'client/app/app.coffee', 'client/app/**/*.js', 'client/app/**/*.coffee', 'client/components/**/*.js', 'client/components/**/*.coffee', 'client/app/**/*.jade', 'client/components/**/*.jade', 'client/app/**/*.html', 'client/components/**/*.html' ], preprocessors: { '**/*.jade': 'ng-jade2js', '**/*.html': 'html2js', '**/*.coffee': 'coffee', }, ngHtml2JsPreprocessor: { stripPrefix: 'client/' }, ngJade2JsPreprocessor: { stripPrefix: 'client/' }, // list of files / patterns to exclude exclude: [], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['PhantomJS'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
nanaaki/BooKlomw
karma.conf.js
JavaScript
mit
2,447
var assert = require('./assert'), Validator = require('../lib/validator'); describe('Validator Enum', function() { var validator = new Validator(), schema = { foo: { enum: ['foo', 'bar'] } }; it('should ignore an undefined value', function() { assert.valid(validator.validate({ foo : undefined }, schema), 'foo', 'enum'); }); it('should ignore a null value', function() { assert.valid(validator.validate({ foo : null }, schema), 'foo', 'enum'); }); });
nbroslawsky/schematograph
test/validator.enum.test.js
JavaScript
mit
470
'use strict'; define( function () { return function ( $scope, events, Categories ) { $scope.configCover = { fileName : 'cover_photo', url : 'cms-api/categories' }; $scope.configGrid = { fileName : 'grid_photo', url : 'cms-api/categories' }; $scope.category = { name : '' }; $scope.create = function () { Categories.create( $scope.category ); }; $scope.sections = Categories.query({ page : 1, per_page : 9999, type : 'SECTION' }); $scope.$on( events.FILEUPLOADER_DONE, function ( e, data ) { $scope.category[ Object.keys( data )[0] ] = data[ Object.keys( data )[0] ]; }); $scope.$on( 'CREATE_CATEGORY', function () { $scope.create(); }); $scope.$on( Categories.getEvent( 'CREATED' ), function () { $scope.$state.go( 'categories.list' ); }); $scope.$watch( 'category.name', function ( name ) { $scope.category.slug = slug( $scope.category.name, { lower : true }); }); }; });
chuckcfs/dgm
public/js/categories/CategoriesCreateCtrl.js
JavaScript
mit
1,288
'use strict' /** * Store and maintain the set of registered Swagger API Specs. * * Exposes a setter to update the host of all registered apis. */ class SwaggerApis { constructor() { this._apis = [] } add(api) { this._apis.push(api) this._updateHost(api) return this } atIndex(index) { return this._apis[index] } last() { return this._apis[this._apis.length - 1] } get size() { return this._apis.length } get host() { return this._host || process.env.API_HOST } set host(value) { this._host = value this.updateApis() } get schemes() { return this._schemes } set schemes(value) { if (typeof value === 'string') value = [ value ] this._schemes = value this.updateApis() } updateApis() { for (let api of this._apis) { this._updateHost(api) this._updateSchemes(api) } } _updateHost(api) { api.host = this.host || api.host } _updateSchemes(api) { api.schemes = this.schemes || api.schemes } } module.exports = SwaggerApis
mikestead/swagger-routes
src/SwaggerApis.js
JavaScript
mit
1,065
var ListView = Backbone.View.extend({ initialize: function() { this.options.collection.bind('add', this.addOne, this); this.options.collection.bind('reset', this.addAll, this); this.options.collection.bind('remove', this.removeOne, this); }, addAll: function() { var self = this; this.options.collection.each(function(element,i){ self.addOne(element,self); }); }, addOne: function(element){ }, removeOne: function(folder) { } });
maxpowel/Wixet
web/js/super_part_2_ListView_1.js
JavaScript
mit
569
'use strict'; var request = require('request'); var q = require('q'); var http = function (requestParams) { var defer = q.defer(); request(requestParams, function (error, response, body) { if(!error && response.statusCode == 200) { defer.resolve({ 'response': response, 'data': body }); } else { defer.reject({ 'response': response, 'error': error }); } }); return defer.promise; } var getRequestParams = function (method, url, headers) { var requestParams = { method: method, url: url }; setHeaderValues(headers, requestParams); return requestParams; } var setHeaderValues = function(headers, requestParams) { if(!headers) return; requestParams.headers = {}; headers.forEach(function(header){ requestParams.headers[header.key] = header.value; }); } var setQueryStringValues = function(params, requestParams) { if (!params) return; requestParams.qs = params; }; var setJsonValues = function(params, requestParams) { if (!params) return; requestParams.json = params; }; exports.get = function (url, headers, params) { var requestParams = getRequestParams('GET', url, headers); setQueryStringValues(params, requestParams); return http(requestParams); }; exports.post = function (url, headers, params) { var requestParams = getRequestParams('POST', url, headers); setJsonValues(params, requestParams); return http(requestParams); };
tverney/hexo-content-api
http.js
JavaScript
mit
1,461
/* eslint-disable no-restricted-syntax */ import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import { FormGroup, Checkbox } from 'react-bootstrap'; import s from './CourseMarks.css'; import { UnitPropType } from './AnswerList'; import User from '../../components/User/User'; import Link from '../../components/Link/Link'; import ScrollableTable from '../../components/ScrollableTable/ScrollableTable'; function getLatestMark(answers) { function getMark(marks) { if (!marks || !marks.length) return undefined; return marks.reduce((mark, m) => { if (new Date(m.createdAt) - new Date(mark.createdAt) > 0) return m; return mark; }); } function isMarkActual(answer, mark) { return mark && new Date(mark.createdAt) - new Date(answer.updatedAt) > 0; } if (!answers || !answers.length) return undefined; return (answers || []) .map(a => { const mark = getMark(a.marks); return { answer: a, mark, noMark: !isMarkActual(a, mark), }; }) .reduce((res, am) => { if (!res.mark) return am; if (new Date(am.answer.updatedAt) - new Date(res.answer.updatedAt) > 0) return { answer: am.answer, mark: am.mark || res.mark, noMark: !am.mark || !isMarkActual(am.answer, am.mark), }; return res; }); } function getSummaryMark(summary, units) { const sumWeight = units.reduce((sum, u) => sum + (u.weight || 1), 0); const res = Object.entries(summary || {}) .map(([unitId, val]) => ({ unit: units.find(u => u.id === unitId), ...getLatestMark(val), })) .reduce( (sum, um) => { sum.mark += (_.get(um.mark, 'mark', 0) * (um.unit.weight || 1)) / sumWeight; sum.noMark = sum.noMark || um.noMark; return sum; }, { mark: 0, noMark: false }, ); return { mark: { mark: res.mark }, answer: true, noMark: res.noMark }; } const summaryUnit = { id: 'summary', title: 'Summary', answerable: true, }; function buildSummaryCell(m, unit, answer) { const id = `summary ${answer.user.id}`; const summary = m.get(id) || {}; summary[unit.id] = summary[unit.id] || []; const u = summary[unit.id]; u.push(answer); m.set(id, summary); } function buildCell(m, unit, answer) { const id = `${unit.id} ${answer.user.id}`; const a = m.get(id) || []; a.push(answer); m.set(id, a); } function buildCells(units) { const m = new Map(); for (const unit of units) { for (const answer of unit.answers) { buildCell(m, unit, answer); buildSummaryCell(m, unit, answer); } } return m; } class UserMarks extends React.Component { static propTypes = { course: PropTypes.shape({ id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, units: PropTypes.arrayOf(UnitPropType), users: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string, email: PropTypes.string, }), ), }).isRequired, }; static sortUsers(a, b) { const name1 = a.profile.displayName; const name2 = b.profile.displayName; return name1.localeCompare(name2); } static sortUnits(a, b) { return a.title.localeCompare(b.title); } state = {}; renderHeader1 = val => <User key={val.id} user={val} hideTags />; renderHeader2 = val => { const { id, title } = val; return <Link to={`/courses/${this.props.course.id}/${id}`}>{title}</Link>; }; renderCell = (units, val, id) => { const { mark, answer, noMark } = id.startsWith('summary') ? getSummaryMark(val, units) || {} : getLatestMark(val) || {}; const tags = [s.mark]; if (!answer) tags.push(s.noAnswer); if (!mark || noMark) tags.push(s.noMark); return ( <td key={id} className={tags.join(' ')}> {mark && Math.floor(mark.mark)} </td> ); }; render() { const { units, users, title } = this.props.course; const { transpose } = this.state; const visUsers = users .filter(u => u.role === 'student') .sort(UserMarks.sortUsers); const visUnits = units.filter(u => u.answerable).sort(UserMarks.sortUnits); const cells = buildCells(visUnits); const renderCell = this.renderCell.bind(this, visUnits); return ( <div className={s.root}> <div className={s.container}> <h1>Marks of {title}</h1> <ScrollableTable transpose={transpose} data1={visUsers} renderHeader1={this.renderHeader1} data2={[].concat(visUnits).concat(summaryUnit)} renderHeader2={this.renderHeader2} dataCells={cells} // eslint-disable-next-line react/jsx-no-bind renderCell={renderCell} /> <FormGroup controlId="transpose"> <Checkbox checked={transpose} onChange={ev => this.setState({ transpose: ev.target.checked })} > Tranpose table </Checkbox> </FormGroup> </div> </div> ); } } export default withStyles(s)(UserMarks);
fkn/ndo
src/routes/course-marks/CourseMarks.js
JavaScript
mit
5,231
function Armour(name, lvl, armour, evasion, es, reqStr, reqDex, reqInt, impMods, modValues) { if (Array.isArray(name)) { var args = name; this.name = args[0]; this.lvl = args[1]; this.armour = args[2]; this.evasion = args[3]; this.es = args[4]; this.reqStr = args[5]; this.reqDex = args[6]; this.reqInt = args[7]; this.impMods = args[8]; this.modValues = args[9]; } } function Weapon(name, lvl, damage, speed, dps, reqStr, reqDex, reqInt, impMods, modValues) { if (Array.isArray(name)) { var args = name; this.name = args[0]; this.lvl = args[1]; this.damage = args[2]; this.speed = args[3]; this.dps = args[4]; this.reqStr = args[5]; this.reqDex = args[6]; this.reqInt = args[7]; this.impMods = args[8]; this.modValues = args[9]; } } function Jewelry(name, lvl, impMods, modValues) { if (Array.isArray(name)) { var args = name; this.name = args[0]; this.lvl = args[1]; this.impMods = args[2]; this.modValues = args[3]; if (this.impMods.indexOf(" / ") !== -1) { var sp1 = this.impMods.split(" / "); var sp2 = this.modValues.split(" / "); this.multi = true; this.impMod1 = sp1[0]; this.impMod2 = sp1[1]; this.modValue1 = sp2[0]; this.modValue2 = sp2[1]; } } } function Currency(name, stackSize, description) { if (Array.isArray(name)) { var args = name; this.name = args[0]; this.stackSize = args[1]; this.description = args[2]; } } exports.Armour = Armour; exports.Weapon = Weapon; exports.Jewelry = Jewelry; exports.Currency = Currency;
r3Fuze/poe
lib/item_class.js
JavaScript
mit
1,825
let mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.js('resources/assets/js/app.js', 'public/js') .js('resources/assets/js/admin.js', 'public/js') .js('resources/assets/js/submission.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css').version();
bqevin/agrigender-webapp-laravel
webpack.mix.js
JavaScript
mit
670
export {default} from 'ember-frost-viz/utils/frost-viz-rectangle'
notmessenger/ember-frost-viz
app/utils/frost-viz-rectangle.js
JavaScript
mit
66
var util = require('./util'); module.exports = function(app) { app.get('/collections', function (req, res) { var query = util.dbQuery(req.query || {}); app.settings.db.collections.find(query, function(err, collections) { var response = { data: collections, count: collections.length }; res.status(200).send(response); }); }); app.get('/collections/:collectionId', function (req, res) { var id = parseInt(req.params.collectionId); if(isNaN(id)){ res.status(400).send({error:'id must be numeric'}); return; } app.settings.db.collections.findOne(id, function(err, collection) { if(!collection){ res.status(404).send({error:'collection with id ' + id + ' does must exists'}) } res.status(200).send(collection); }); }); app.post('/collections', function (req, res) { var collection = req.body; //name validation if(!collection.name){ res.status(400).send({error:'name is required'}); return; } if(collection.name.length < 4){ res.status(404).send({error:'collection name must have at least 4 characters'}); return; } if(collection.name.length > 100){ res.status(404).send({error:'collection name must have less than 100 characters'}); return; } //description validation if(collection.description.length < 4){ res.status(404).send({error:'collection description must have at least 4 characters'}); return; } if(collection.description.length > 500){ res.status(404).send({error:'collection description must have less than 500 characters'}); return; } //photo_collection validation if(!collection.image_url){ res.status(400).send({error:'collection photo is required'}); return; } if(collection.image_url.length > 255){ res.status(404).send({error:'collection name must have less than 255 characters'}); return; } delete collection.id; app.settings.db.collections.insert(collection, function(err, result) { if(err) { res.status(503).send({error:err}); } res.status(200).send(result); }); }); app.put('/collections/:collectionId', function (req, res) { var collection = req.body; //id validation var id = parseInt(req.params.collectionId); if(isNaN(id)){ res.status(400).send({error:'id must be numeric'}); return; } //name validation if(!collection.name){ res.status(400).send({error:'name is required'}); return; } if(collection.name.length < 4){ res.status(404).send({error:'collection name must have at least 4 characters'}); return; } if(collection.name.length > 100){ res.status(404).send({error:'collection name must have less than 100 characters'}); return; } //description validation if(collection.description.length < 4){ res.status(404).send({error:'collection description must have at least 4 characters'}); return; } if(collection.description.length > 500){ res.status(404).send({error:'collection description must have less than 500 characters'}); return; } //photo_collection validation if(!collection.image_url){ res.status(400).send({error:'collection photo is required'}); return; } if(collection.image_url.length > 255){ res.status(404).send({error:'collection name must have less than 255 characters'}); return; } app.settings.db.collections.update(collection, function(err, result) { res.status(200).send(result); }); }); app.delete('/collections/:collectionId', function (req, res) { //id validation var id = parseInt(req.params.collectionId); if(isNaN(id)){ res.status(400).send({error:'id must be numeric'}); return; } app.settings.db.collections.destroy({id: id}, function(err, result) { res.status(200).send({status: "ok"}); }); }); };
marsui/chusrodriguez
api/collections.js
JavaScript
mit
3,803
require("./src/utils/prism-okaidia.css")
lucasflores/lucasflores.github.io
gatsby-browser.js
JavaScript
mit
42
/* * @overview 负责服务器数据交互 */ 'use strict'; (function (ns) { var defaults = { dataType: 'json', type: 'post', cache: false, xhrFields: { withCredentials: true } }; var manager = { $body: null, $me: null, call: function (url, data, options) { options = _.defaults(options, { url: url, data: data }, defaults); var self = this , error = options.error || this.onError , success = options.success || this.onSuccess; options.success = function (response) { if (response.code === 0) { self.postHandle(response); success.call(options.context, response); self.trigger('complete:call', response); } else { error(response); } }; options.error = function (xhr, status, err) { error.call(options.context, xhr, status, err); }; return $.ajax(options); }, fetch: function (url, handler, context) { return $.get(url, function (response) { handler.call(context, response); }); }, get: function (url, data, options) { options.method = 'get'; this.call(url, data, options); }, postHandle: function (response) { // 以后可以扩展成循环,现在先逐个添加好了 if ('me' in response) { this.$me.set(response.me); } }, onError: function (xhr, status, error) { console.log(xhr, status, error); if (status === 401) { this.$body.load('page/error.html'); } }, onProgress: function (loaded, total) { console.log(loaded / total); }, onSuccess: function (response) { console.log('success', response); } }; manager = _.extend(manager, Backbone.Events); ns.Manager = manager; }(Nervenet.createNameSpace('tp.service')));
Dianjoy/tiger-prawn
js/service/Manager.js
JavaScript
mit
1,871
import React, { Component } from 'react'; class Chat extends Component { render() { return ( <div>Hello Chat!!!!</div> ); } } export default Chat;
Elektro1776/Project_3
client/containers/chat/index.js
JavaScript
mit
167
/* * GET home page. */ exports.view = function(req, res) { res.render('index', { title: "Landing Page", layout: "index" }); };
jphung11/LifeBalance
routes/index.js
JavaScript
mit
153
const initStart = process.hrtime(); const { parseUserAgent } = require('detect-browser'); // Trigger a parse to force cache loading parseUserAgent('Test String'); const initTime = process.hrtime(initStart)[1] / 1000000000; const package = require(require('path').dirname( require.resolve('detect-browser') ) + '/package.json'); const version = package.version; let benchmark = false; const benchmarkPos = process.argv.indexOf('--benchmark'); if (benchmarkPos >= 0) { process.argv.splice(benchmarkPos, 1); benchmark = true; } const lineReader = require('readline').createInterface({ input: require('fs').createReadStream(process.argv[2]) }); const output = { results: [], parse_time: 0, init_time: initTime, memory_used: 0, version: version }; lineReader.on('line', function(line) { if (line === '') { return; } const start = process.hrtime(); const r = parseUserAgent(line); const end = process.hrtime(start)[1] / 1000000000; output.parse_time += end; if (benchmark) { return; } const result = { useragent: line, parsed: { browser: { name: r !== null && r.name ? r.name : null, version: r !== null && r.version ? r.version : null }, platform: { name: r !== null && r.os ? r.os : null, version: null }, device: { name: null, brand: null, type: null, ismobile: null } }, time: end }; output.results.push(result); }); lineReader.on('close', function() { output.memory_used = process.memoryUsage().heapUsed; console.log(JSON.stringify(output, null, 2)); });
diablomedia/useragent-parser-comparison
parsers/detect-browser-js-4/scripts/parse.js
JavaScript
mit
1,801
var WeatherBoard = function(){}; WeatherBoard.prototype.init = function(el, config){ var self = this; var location = config.location; var unit = config.unit || 'C'; el.innerHTML = 'Loading weather for '+location+'...'; self.update(el, location, unit); setInterval(function(){ self.update(el, location, unit); }, 10 * 60 * 1000); } WeatherBoard.prototype.callback = function(data){ var self = this; var el = WeatherEl; var unit = WeatherUnit; if(data && data.query){ var results = data.query.results; } if(results){ var result = (results.length > 1) ? results[0] : results; var country = result.channel.location.country; var city = result.channel.location.city; var temp = result.channel.item.condition.temp; if(country && city && temp){ el.innerHTML = '<h2>Weather</h2><p>'+temp+'&deg;'+unit+'</p><p>'+city+', '+country+'</p>'; }else{ el.innerHTML = '<h2>Weather</h2><p>No weather found for '+location+'</p>'; } } } WeatherBoard.prototype.update = function(el, location, unit){ var self = this; WeatherEl = el; WeatherUnit = unit; if(location){ var now = new Date(); var weatherUrl = 'http://query.yahooapis.com/v1/public/yql?format=json&rnd='+now.getFullYear()+now.getMonth()+now.getDay()+now.getHours()+'&diagnostics=false&callback=weatherCallback&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q='; weatherUrl += 'select * from weather.forecast where location in (select id from weather.search where query="'+location+'") and u="'+unit.toLowerCase()+'"'; if(LIB && LIB.areFeatures('parseJson', 'forEach')){ if(Loader && LIB.isHostMethod(Loader, 'load')){ window.weatherCallback = self.callback; Loader.load(weatherUrl, false, function(){ if(window.weatherCallback && typeof window.weatherCallback == 'function'){ delete window.weatherCallback; } }); } } }else{ el.innerHTML = '<p>No location provided for weather</p>'; } }
datagutt/JustDashboard
boards/weather/board.js
JavaScript
mit
1,927
app.controller('loginModalController', ['$scope', '$modalInstance', 'loginService', function ($scope, $modalInstance, loginService) { $scope.user = { username: '', password: '' }; $scope.form = { submitted: false }; $scope.error = { showError: false, errorText: '' }; $scope.login = function() { $scope.form.submitted = true; if ($scope.form.login_form.$invalid) { return; } loginService.login($scope.user).success(function(data) { if (data.loginSuccessfull == true) { $modalInstance.close(data.user); } else { $scope.error.showError = true; $scope.error.errorText = data.Message; } }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]);
dicehead3/Kaartenbak
Web2/app/controllers/modals/loginModalController.js
JavaScript
mit
1,017
$(function () { shell.initialize(); $('.scrollable').niceScroll({ boxzoom: false, cursoropacitymax: 0.7, cursorcolor: '#444', cursorborder: '1px solid #666' }); //$.validator.methods.number = function (value, element) { // if (Globalize.parseFloat(value)) { // return true; // } // return false; //} }); shell = { defaultFadeSpeed: 100, initialize: function () { this.confirmDialog = $('#shell-confirm'); this.shield = $('#shell-shield'); this.progressDialog = $('#shell-operation-progress'); this.successDialog = $('#shell-operation-success'); this.failureDialog = $('#shell-operation-failure'); this.popupDialog = $('#shell-popup-dialog'); $(document).ajaxError(function (event, request, settings) { shell.showFailureMessage(request.statusText, request.responseText); }); }, // // Confirmation Dialog // confirmDialog: null, isConfirmDialogInitialized: false, confirmationViewModel: { message: ko.observable(''), callback: null, show: function () { shell.showShield(); shell.confirmDialog.slideDown(); }, hide: function () { shell.confirmDialog.slideUp(); shell.hideShield(); }, onConfirm: function () { shell.confirmDialog.slideUp(); shell.hideShield(); if (typeof (this.callback) !== 'undefined') { this.callback(); } }, onDismiss: function () { this.hide(); } }, showConfirmation: function (message, confirmCallback) { shell.confirmationViewModel.message(message); shell.confirmationViewModel.callback = confirmCallback; if (!shell.isConfirmDialogInitialized) { ko.applyBindings(shell.confirmationViewModel, shell.confirmDialog[0]); shell.isConfirmDialogInitialized = true; } shell.confirmationViewModel.show(); }, // // Shield // shield: null, showShield: function () { this.shield.fadeIn(this.defaultFadeSpeed); }, hideShield: function () { this.shield.fadeOut(this.defaultFadeSpeed); }, // // Progress Indicator // progressDialog: null, isProgressDialogInitialized: false, progressViewModel: { message: ko.observable(''), show: function () { shell.progressDialog.slideDown(); }, hide: function () { shell.progressDialog.slideUp(); } }, showProgressMessage: function (message) { shell.progressViewModel.message(message); if (!shell.isProgressDialogInitialized) { ko.applyBindings(shell.progressViewModel, shell.progressDialog[0]); shell.isProgressDialogInitialized = true; } shell.failureViewModel.hide(); shell.progressViewModel.show(); }, hideProgressMessage: function () { shell.progressViewModel.hide(); }, // // Success Dialog // successDialog: null, isSuccessDialogInitialized: false, successViewModel: { message: ko.observable(''), show: function () { shell.progressViewModel.hide(); shell.successDialog.slideDown(); window.setTimeout(this.hide, 15000); }, hide: function () { shell.successDialog.slideUp(); }, onDismiss: function () { this.hide(); } }, showSuccessMessage: function (message) { shell.successViewModel.message(message); if (!shell.isSuccessDialogInitialized) { ko.applyBindings(shell.successViewModel, shell.successDialog[0]); shell.isSuccessDialogInitialized = true; } shell.successViewModel.show(); }, // // Failure Dialog // failureDialog: null, isFailureDialogInitialized: false, failureViewModel: { message: ko.observable(''), extendedHtml: ko.observable(''), showExpanded: ko.observable(false), show: function () { shell.progressViewModel.hide(); shell.failureDialog.slideDown(); }, hide: function () { shell.failureDialog.slideUp(); }, onDetails: function () { this.showExpanded(!this.showExpanded()); }, onDismiss: function () { this.hide() } }, showFailureMessage: function (message, extendedHtml) { shell.failureViewModel.message(message); shell.failureViewModel.extendedHtml(extendedHtml || ''); shell.failureViewModel.showExpanded(false); if (!shell.isFailureDialogInitialized) { ko.applyBindings(shell.failureViewModel, shell.failureDialog[0]); shell.isFailureDialogInitialized = true; } shell.failureViewModel.show(); }, // // Popup Dialog // popup: null, isPopupInitialized: false, popupViewModel: { self: this, title: ko.observable(''), templateId: ko.observable(''), data: ko.observable({}), callback: null, show: function () { shell.showShield(); shell.popupDialog.show(); }, hide: function () { shell.popupDialog.hide(); shell.hideShield(); }, fixScrollBar: function () { var content = $('#shell-popup-dialog-content'); content.getNiceScroll().hide(); content.getNiceScroll().resize().show(); // The dialog needs to be nudged in order to get the scroll to render properly var currentTop = $('#shell-popup-dialog-content').css('top'); content.css('top', currentTop + 1); content.css('top', currentTop); }, onDismiss: function () { this.hide(); }, onAccept: function () { var ret = true; if (this.callback != null) { ret = this.callback(self.data); } if (ret) { this.hide(); } } }, showPopupDialog: function (title, templateId, data, callback) { if (shell.isPopupInitialized) { ko.cleanNode(shell.popupDialog[0]); } shell.popupViewModel.title(title); shell.popupViewModel.templateId(templateId); shell.popupViewModel.data(data); shell.popupViewModel.callback = callback; if (!shell.isPopupInitialized) { shell.isPopupInitialized = true; } ko.applyBindings(shell.popupViewModel, shell.popupDialog[0]); shell.popupViewModel.show(); } };
OrderDynamics/stores
src/OrderDynamics.Stores.Web/wwwroot/js/shell.js
JavaScript
mit
7,181
var User = function User () { this.username = 'username'; this.salt = 'salt'; this.hash = 'hash'; }; User.prototype.save = function (callback) { callback(null); }; module.exports = User;
dgaubert/mammoth
test/fixtures/user.js
JavaScript
mit
197
"use strict"; var assert = require('assert'); var fs = require('fs'); var temp = require('temp'); var $S = require('suspend'), $R = $S.resume, $T = function(gen) { return function(done) { $S.run(gen, done); } }; var Nodalion = require('../nodalion.js'); var ns = Nodalion.namespace('/impred', ['testLocalStore', 'localStr', 'testNow', 'testUUID', 'testLocalQueue', 'testBase64Encode', 'testBase64Decode', 'testLoadNamespace', 'testLoadFile', 'testLoadFile2', 'readSourceFile', 'task', 'assert', 'pred', 'retract', 'loadSourceFileToContainer', 'removeSourceFileFromContainer']); var nodalion = new Nodalion(__dirname + '/../../prolog/cedalion.pl', '/tmp/impred-ced.log'); describe('impred', function(){ describe('local storage', function(){ it('should allow storing and fetching local state', $T(function*(){ var X = {var:'X'}; var result = yield nodalion.findAll(X, ns.testLocalStore(X), $R()); assert.deepEqual(result, [ns.localStr('bar')]); })); }); describe('local queue', function(){ it('should allow enqueuing and dequeing data', $T(function*(){ var X = {var:'X'}; var result = yield nodalion.findAll(X, ns.testLocalQueue(1, X), $R()); assert.deepEqual(result, ['helloworld']); })); it('should allow checking if the queue is empty', $T(function*(){ var X = {var:'X'}; var result = yield nodalion.findAll(X, ns.testLocalQueue(2, X), $R()); assert.deepEqual(result, ['YNY']); })); }); describe('now', function(){ it('should return the current time', $T(function*(){ var X = {var:'X'}; var result = yield nodalion.findAll(X, ns.testNow(X), $R()); var list = result[0].meaning(); assert(list[0] < list[1], list[0] + ' < ' + list[1]); assert(list[1] < list[2], list[1] + ' < ' + list[2]); assert(list[2] - list[0] < 1, (list[2] - list[0]) + ' < 1'); })); }); describe('uuid', function(){ it('should return a unique ID each time it is called', $T(function*(){ var X = {var:'X'}; var result = yield nodalion.findAll(X, ns.testUUID(X), $R()); var list = result[0].meaning(); assert.notEqual(list[0], list[1]); assert.notEqual(list[2], list[1]); list.forEach(function(id) { // Should be at least 128 bits assert(id.length * 6 > 128, (id.length * 6) + ' > 128'); }); })); }); describe('base64Encode(Plain)', function(){ it('should base64-encode the given Plain text', $T(function*(){ var X = {var:'X'}; var plain = "the quick brown fox and so on and so forth...."; var result = yield nodalion.findAll(X, ns.testBase64Encode(plain, X), $R()); var enc = result[0]; var buf = new Buffer(Buffer.byteLength(plain)); buf.write(plain); assert.equal(enc, buf.toString('base64')); })); }); describe('base64Decode(Enc)', function(){ it('should decode the given base64-encoded string', $T(function*(){ var X = {var:'X'}; var plain = "the quick brown fox and so on and so forth...."; var buf = new Buffer(Buffer.byteLength(plain)); buf.write(plain); var result = yield nodalion.findAll(X, ns.testBase64Decode(buf.toString('base64'), X), $R()); var dec = result[0]; assert.equal(dec, plain); })); }); describe('loadCedalionImage(FileName, Prep, PrepIn, PrepOut)', function(){ it('should load clauses from the given file', $T(function*(){ var X = {var:'X'}; var content = "'/impred#foo'(1):-'builtin#true'. '/impred#foo'(2):-'builtin#true'. '/impred#foo'(3):-'builtin#true'."; var file = yield temp.open({prefix: 'ced', suffix: '.pl'}, $R()); yield fs.write(file.fd, content, $R()); var result = yield nodalion.findAll(X, ns.testLoadNamespace(file.path, X), $R()); assert.deepEqual(result, [1, 2, 3]); })); it.skip('should load containers when needed', function(done){ this.timeout(7000); $S.callback(function*() { var hash = "QmdHZHRfuJ2QBXfvaMr3ksh3gKyoxc15LhRhKgEKrf4wnj"; var X = {var:'X'}; var nns = Nodalion.namespace('/nodalion', ['testContainer']); var result = yield nodalion.findAll(X, nns.testContainer(hash, X), $R()); assert.deepEqual(result, ['cloudlog']); })(done); }); }); var writeFile = $S.callback(function*(content) { var file = yield temp.open({prefix: 'example', suffix: '.ced'}, $R()); yield fs.write(file.fd, content, $R()); return file.path; }); describe('readSourceFile(FileName, NS)', () => { it('should return a list of the statements in a file', $T(function*() { var fileName = yield writeFile("hello(World). hola(Mondi).", $R()); var X = {var:'X'}; var res = yield nodalion.findAll(X, ns.task(ns.readSourceFile(fileName, '/foo'), X, {var:'T'}), $R()); assert.equal(res.length, 1); // One result res = res[0].meaning(); assert.equal(res.length, 2); // Two statements res = res[0]; assert.equal(res.name, 'builtin#loadedStatement'); assert.equal(res.args.length, 3); assert.equal(res.args[0], fileName); assert.equal(res.args[1].name, '/foo#hello'); var varNames = res.args[2].meaning(); assert.equal(varNames.length, 1); assert.equal(varNames[0].args[1], 'World'); })); }); describe('assert(Statement)', () => { it('should add the statement to the logic program', $T(function*() { // Add /foo:bar(3):-builtin:true to the program var builtin = Nodalion.namespace('builtin', ['true']); var foo = Nodalion.namespace('/foo', ['bar']); var statement = {name: ":-", args: [foo.bar(3), builtin.true()]}; yield nodalion.findAll({var: '_'}, ns.task(ns.assert(statement), {var: '_X'}, {var: '_T'}), $R()); // Query /foo:bar(X) var X = {var:'X'}; var res = yield nodalion.findAll(X, ns.pred(foo.bar(X)), $R()); assert.deepEqual(res, [3]); })); }); describe('retract(Statement)', () => { it('should remove the statement from the logic program', $T(function*() { // Add /foo2:bar(4):-builtin:true and /foo2:bar(5):-builtin:true to the program var builtin = Nodalion.namespace('builtin', ['true']); var foo = Nodalion.namespace('/foo2', ['bar']); yield nodalion.findAll({var: '_'}, ns.task(ns.assert({name: ":-", args: [foo.bar(4), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R()); yield nodalion.findAll({var: '_'}, ns.task(ns.assert({name: ":-", args: [foo.bar(5), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R()); // Remove /foo2:bar(4):-builtin:true yield nodalion.findAll({var: '_'}, ns.task(ns.retract({name: ":-", args: [foo.bar(4), builtin.true()]}), {var: '_X'}, {var: '_T'}), $R()); // Query /foo:bar(X) var X = {var:'X'}; var res = yield nodalion.findAll(X, ns.pred(foo.bar(X)), $R()); assert.deepEqual(res, [5]); })); }); describe('loadSourceFileToContainer(FileName, NS, Container)', () => { it('should load a cedalion source file on top of an image', $T(function*() { var X = {var:'X'}; var imageFileName = yield writeFile("'/impred#foo'(4):-'builtin#true'.", $R()); var exampleFileName = yield writeFile("foo(5):-builtin:true.", $R()); var result = yield nodalion.findAll(X, ns.testLoadFile(imageFileName, exampleFileName, '/impred', X), $R()); assert.deepEqual(result, [4, 5]); })) it('should support the loadedStatement() predicate', $T(function*() { var X = {var:'X'}; var imageFileName = yield writeFile("", $R()); var exampleFileName = yield writeFile("foo(7):-builtin:true. foo(8):-builtin:true.", $R()); var result = yield nodalion.findAll(X, ns.testLoadFile2(imageFileName, exampleFileName, '/impred', X), $R()); assert.deepEqual(result, [7, 8]); })) }); describe('removeSourceFileFromContainer(FileName, Container)', () => { it('should remove all statements loaded from that file from the container', $T(function*() { var X = {var:'X'}; var exampleFileName = yield writeFile("foo(1):-builtin:true.\nfoo(2):-builtin:true.", $R()); yield nodalion.findAll(X, ns.loadSourceFileToContainer(exampleFileName, '/impred', 'cont1'), $R()); var result = yield nodalion.findAll(X, ns.pred({name: 'cont1@/impred#foo', args:[X]}), $R()); assert.deepEqual(result, [1, 2]); yield nodalion.findAll(X, ns.removeSourceFileFromContainer(exampleFileName, 'cont1'), $R()); var result = yield nodalion.findAll(X, ns.pred({name: 'cont1@/impred#foo', args:[X]}), $R()); assert.deepEqual(result, []); })); }); });
brosenan/nodalion
js/test/impred-test.js
JavaScript
mit
9,640
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), chalk = require('chalk'), glob = require('glob'), fs = require('fs'), path = require('path'); /** * Get files by glob patterns */ var getGlobbedPaths = function (globPatterns, excludes) { // URL paths regex var urlRegex = new RegExp('^(?:[a-z]+:)?\/\/', 'i'); // eslint-disable-line // The output array var output = []; // If glob pattern is array then we use each pattern in a recursive way, otherwise we use glob if (_.isArray(globPatterns)) { globPatterns.forEach(function (globPattern) { output = _.union(output, getGlobbedPaths(globPattern, excludes)); }); } else if (_.isString(globPatterns)) { if (urlRegex.test(globPatterns)) { output.push(globPatterns); } else { var files = glob.sync(globPatterns); if (excludes) { files = files.map(function (file) { if (_.isArray(excludes)) { for (var i in excludes) { // eslint-disable-line if (excludes.hasOwnProperty(i)) { // eslint-disable-line file = file.replace(excludes[i], ''); } } } else { file = file.replace(excludes, ''); } return file; }); } output = _.union(output, files); } } return output; }; /** * Validate NODE_ENV existence */ var validateEnvironmentVariable = function () { var environmentFiles = glob.sync('./config/env/' + process.env.NODE_ENV + '.js'); console.log(); if (!environmentFiles.length) { if (process.env.NODE_ENV) { console.error(chalk.red('+ Error: No configuration file found for "' + process.env.NODE_ENV + '" environment using development instead')); } else { console.error(chalk.red('+ Error: NODE_ENV is not defined! Using default development environment')); } process.env.NODE_ENV = 'development'; } // Reset console color console.log(chalk.white('')); }; /** * Validate Secure=true parameter can actually be turned on * because it requires certs and key files to be available */ var validateSecureMode = function (config) { if (!config.secure || config.secure.ssl !== true) { return true; } var privateKey = fs.existsSync(path.resolve(config.secure.privateKey)); var certificate = fs.existsSync(path.resolve(config.secure.certificate)); if (!privateKey || !certificate) { console.log(chalk.red('+ Error: Certificate file or key file is missing, falling back to non-SSL mode')); console.log(chalk.red(' To create them, simply run the following from your shell: sh ./scripts/generate-ssl-certs.sh')); console.log(); config.secure.ssl = false; } }; /** * Validate Session Secret parameter is not set to default in production */ var validateSessionSecret = function (config, testing) { if (process.env.NODE_ENV !== 'production') { return true; } if (config.sessionSecret === 'OWWWLY') { if (!testing) { console.log(chalk.red('+ WARNING: It is strongly recommended that you change sessionSecret config while running in production!')); console.log(chalk.red(' Please add `sessionSecret: process.env.SESSION_SECRET || \'super amazing secret\'` to ')); console.log(chalk.red(' `config/env/production.js` or `config/env/local.js`')); console.log(); } return false; } else { return true; } }; /** * Initialize global configuration files */ var initGlobalConfigFolders = function (config, assets) { // Appending files config.folders = { server: {}, client: {} }; // Setting globbed client paths config.folders.client = getGlobbedPaths(path.join(process.cwd(), 'modules/*/client/'), process.cwd().replace(new RegExp(/\\/g), '/')); }; /** * Initialize global configuration files */ var initGlobalConfigFiles = function (config, assets) { // Appending files config.files = { server: {}, client: {} }; // Setting Globbed model files config.files.server.models = getGlobbedPaths(assets.server.models); // Setting Globbed route files config.files.server.routes = getGlobbedPaths(assets.server.routes); // Setting Globbed config files config.files.server.configs = getGlobbedPaths(assets.server.config); // Setting Globbed socket files config.files.server.sockets = getGlobbedPaths(assets.server.sockets); // Setting Globbed policies files config.files.server.policies = getGlobbedPaths(assets.server.policies); // Setting Globbed js files config.files.client.js = getGlobbedPaths(assets.client.lib.js, 'public/').concat(getGlobbedPaths(assets.client.js, ['public/'])); // Setting Globbed css files config.files.client.css = getGlobbedPaths(assets.client.lib.css, 'public/').concat(getGlobbedPaths(assets.client.css, ['public/'])); // Setting Globbed test files config.files.client.tests = getGlobbedPaths(assets.client.tests); }; /** * Initialize global configuration */ var initGlobalConfig = function () { // Validate NODE_ENV existence validateEnvironmentVariable(); /* eslint-disable global-require */ // Get the default assets var defaultAssets = require(path.join(process.cwd(), 'config/assets/default')); // Get the current assets var environmentAssets = require(path.join(process.cwd(), 'config/assets/', process.env.NODE_ENV)) || {}; // Merge assets var assets = _.merge(defaultAssets, environmentAssets); // Get the default config var defaultConfig = require(path.join(process.cwd(), 'config/env/default')); // Get the current config var environmentConfig = require(path.join(process.cwd(), 'config/env/', process.env.NODE_ENV)) || {}; // Merge config files var config = _.merge(defaultConfig, environmentConfig); // read package.json for OWWWLY project information var pkg = require(path.resolve('./package.json')); config.owwwly = pkg; // Extend the config object with the local-NODE_ENV.js custom/local environment. This will override any settings present in the local configuration. config = _.merge(config, (fs.existsSync(path.join(process.cwd(), 'config/env/local-' + process.env.NODE_ENV + '.js')) && require(path.join(process.cwd(), 'config/env/local-' + process.env.NODE_ENV + '.js'))) || {}); // Initialize global globbed files initGlobalConfigFiles(config, assets); // Initialize global globbed folders initGlobalConfigFolders(config, assets); // Validate Secure SSL mode can be used validateSecureMode(config); // Validate session secret validateSessionSecret(config); // Expose configuration utilities config.utils = { getGlobbedPaths: getGlobbedPaths, validateSessionSecret: validateSessionSecret }; return config; }; /** * Set configuration object */ module.exports = initGlobalConfig();
Tsuna-mi/owwwly-app
config/config.js
JavaScript
mit
6,799
/* * Some portions extracted from: * Parse JavaScript SDK — Version: 1.4.2 * */ import Ember from 'ember'; import DS from 'ember-data'; var get = Ember.get, forEach = Ember.ArrayPolyfills.forEach; export default DS.RESTAdapter.extend({ PARSE_APPLICATION_ID: null, PARSE_JAVASCRIPT_KEY: null, PARSE_HOST: null, PARSE_NAMESPACE: null, classesPath: 'classes', parseClientVersion: 'js1.4.2', init() { this._super(); this.set('applicationId', this.get('PARSE_APPLICATION_ID')); this.set('javascriptKey', this.get('PARSE_JAVASCRIPT_KEY')); this.set('host', this.get('PARSE_HOST') || 'https://api.parse.com'); this.set('namespace', this.get('PARSE_NAMESPACE') || '1'); this.set('installationId', this._getInstallationId()); this.set('sessionToken', null); this.set('userId', null); /* * avoid pre-flight. * Parse._ajax */ this.set('headers', { 'Content-Type': 'text/plain' }); }, _getInstallationId() { /* * Parse._getInstallationId */ let lsKey = `ember-parse/${this.get('applicationId')}/installationId`; if (this.get('installationId')) { return this.get('installationId'); } else if (localStorage.getItem(lsKey)) { return localStorage.getItem(lsKey); } else { let hexOctet = function() { return ( Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) ); }; let installationId = ( hexOctet() + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + hexOctet() + hexOctet()); localStorage.setItem(lsKey, installationId); return installationId; } }, ajaxOptions(url, type, options) { var hash = options || {}; hash.data = hash.data || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if ((hash.data && type !== 'GET')) { hash.contentType = 'application/json; charset=utf-8'; // Parse auth stuff hash.data._ClientVersion = this.get('parseClientVersion'); hash.data._ApplicationId = this.get('applicationId'); hash.data._JavaScriptKey = this.get('javascriptKey'); hash.data._InstallationId = this.get('installationId'); var _sessionToken = this.get('sessionToken'); if (_sessionToken) { hash.data._SessionToken = _sessionToken; } hash.data = JSON.stringify(hash.data); } var headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, ajaxError(jqXHR, responseText, errorThrown) { if (jqXHR.responseJSON.error === 'invalid session token') { // invalid session var session = this.container.lookup('service:session'); session.resetSession(); } return this._super(jqXHR, responseText, errorThrown); }, normalizeErrorResponse: function(status, headers, payload) { return [ { status: `${status}`, title: 'The backend responded with an error', details: payload.error, code: payload.code } ]; }, pathForType(type) { if ('user' === type) { return 'users'; } else if ('login' === type) { return type; } else if ('logout' === type) { return type; } else if ('requestPasswordReset' === type) { return type; } else if ('functions' === type) { return 'functions'; } else { return this.classesPath + '/' + this.parsePathForType(type); } }, // Using TitleStyle is recommended by Parse parsePathForType(type) { return Ember.String.capitalize(Ember.String.camelize(type)); }, parseClassName(key) { return Ember.String.capitalize(key); }, /** * Because Parse doesn't return a full set of properties on the * responses to updates, we want to perform a merge of the response * properties onto existing data so that the record maintains * latest data. */ createRecord(store, type, record) { var serializer = store.serializerFor(type.modelName), data = { _method: 'POST' }, adapter = this; serializer.serializeIntoHash(data, type, record, { includeId: true }); var promise = new Ember.RSVP.Promise(function(resolve, reject) { adapter.ajax(adapter.buildURL(type.modelName), 'POST', { data: data }) .then(function(json) { var completed = Ember.merge(data, json); resolve(completed); }, function(reason) { var err = `Code ${reason.responseJSON.code}: ${reason.responseJSON.error}`; reject(new Error(err)); }); }); return promise; }, updateRecord(store, type, snapshot) { var data = { _method: 'PUT' }, id = snapshot.id, serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot); // debugger; // snapshot.record._relationships.friends.members // snapshot.record._relationships.friends.canonicalMembers return this.ajax(this.buildURL(type.modelName, id, snapshot), 'POST', { data: data }); }, deleteRecord(store, type, snapshot) { var data = { _method: 'DELETE' }, id = snapshot.id; return this.ajax(this.buildURL(type.modelName, id, snapshot), 'POST', { data: data }); }, findRecord(store, type, id, snapshot) { var data = { _method: 'GET' }; return this.ajax(this.buildURL(type.modelName, id, snapshot), 'POST', { data: data }); }, findAll(store, type, sinceToken) { var data = { _method: 'GET' }; if (sinceToken) { data.since = sinceToken; } data.where = {}; return this.ajax(this.buildURL(type.modelName), 'POST', { data: data }); }, /** * Implementation of a hasMany that provides a Relation query for Parse * objects. */ findHasMany(store, record, relationship) { var related = JSON.parse(relationship); var query = { where: { '$relatedTo': { 'object': { '__type': 'Pointer', 'className': this.parseClassName(record.modelName), 'objectId': record.id }, key: related.key } }, _method: 'GET' }; // the request is to the related type and not the type for the record. // the query is where there is a pointer to this record. return this.ajax( this.buildURL(related.className), 'POST', { data: query }); }, /** * Implementation of findQuery that automatically wraps query in a * JSON string. * * @example * this.store.find('comment', { * where: { * post: { * "__type": "Pointer", * "className": "Post", * "objectId": post.get('id') * } * } * }); */ findQuery(store, type, query) { query._method = 'GET'; return this.ajax(this.buildURL(type.modelName), 'POST', { data: query }); }, shouldReloadAll() { return false; }, shouldBackgroundReloadRecord() { return false; } });
GetBlimp/ember-parse
addon/adapters/parse.js
JavaScript
mit
7,231
loadedInterfaceName = "TIME"; interfaceOrientation = "portrait"; control.timer = null; control.getCurrentTime = function() { var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); var seconds = currentTime.getSeconds(); if (minutes < 10) minutes = "0" + minutes; if (seconds < 10) seconds = "0" + seconds; timeLabel.setValue(hours + ":" + minutes + ":" + seconds); control.timer = setTimeout(control.getCurrentTime, 1000); } pages = [[ { "name": "refresh", "type": "Button", "x": .6, "y": .9, "width": .2, "height": .1, "startingValue": 0, "isLocal": true, "mode": "contact", "ontouchstart": "interfaceManager.refreshInterface()", "stroke": "#aaa", }, { "name": "refreshLabel", "type": "Label", "x": .6, "y": .9, "width": .2, "height": .1, "isLocal": true, "value": "refresh", }, { "name": "tabButton", "type": "Button", "x": .8, "y": .9, "width": .2, "height": .1, "mode": "toggle", "stroke": "#aaa", "isLocal": true, "ontouchstart": "if(this.value == this.max) { control.showToolbar(); } else { control.hideToolbar(); }", }, { "name": "tabButtonLabel", "type": "Label", "x": .8, "y": .9, "width": .2, "height": .1, "mode": "contact", "isLocal": true, "value": "menu", }, { "name": "timeLabel", "type": "Label", "x": 0, "y":0, "width":.5, "height": .5, "value":"time", "size":24, "oninit": "control.getCurrentTime()", }, ] ];
DaveThw/ControlForEOS
Control-examples/showTime.js
JavaScript
mit
1,531
let search = new Vue({ el: '#search', data: { results: [ { shelter_id: '1', name: 'San Francisco Homeless Outreach', address: '283 Steiner St.', beds_available: 0, filters: {women: false, open: false} }, { shelter_id: '2', name: 'Better Choices', address: '183 Mission St.', beds_available: 3, filters: {women: false, open: false} }, { shelter_id: '3', name: 'Catholic Charities of San Francisco', address: '17 Capp St.', beds_available: 39, filters: {women: false, open: false, showers: true} }, { shelter_id: '4', name: 'Care Outreach Services', address: '1774 Hayes St.', beds_available: 0, filters: {women: false, open: false} }, { shelter_id: '5', name: 'Helping Hands Shelter', address: '932 Martin Luther King Blvd.', beds_available: 77, filters: {women: false, open: true} }, { shelter_id: '6', name: 'San Francisco Women\'s Shelter', address: '238 Argent Ct.', beds_available: 8, filters: {women: true, open: true} }, { shelter_id: '7', name: 'San Francisco Men\'s Shelter', address: '241 Argent Ct.', beds_available: 3, filters: {men: true, women: false, open: true} }, { shelter_id: '8', name: 'Sunset Baptist Church', address: '1438 Ulloa St.', beds_available: 0, filters: {women: true, open: true, showers: true} }, { shelter_id: '9', name: 'Jazzy\'s Place', address: '238 Mission St.', beds_available: 11, filters: {women: false, open: true, showers: true, lgbtq: true} }, { shelter_id: '10', name: 'Salvation Army', address: '1749 Van Ness St.', beds_available: 183, filters: {women: false, open: true, showers: true, lgbtq: false} } ], filteredResults: [ { shelter_id: '1', name: 'San Francisco Homeless Outreach', address: '283 Steiner St.', beds_available: 0, filters: {women: false, open: false} }, { shelter_id: '2', name: 'Better Choices', address: '183 Mission St.', beds_available: 3, filters: {women: false, open: false} }, { shelter_id: '3', name: 'Catholic Charities of San Francisco', address: '17 Capp St.', beds_available: 39, filters: {women: false, open: false, showers: true} }, { shelter_id: '4', name: 'Care Outreach Services', address: '1774 Hayes St.', beds_available: 0, filters: {women: false, open: false} }, { shelter_id: '5', name: 'Helping Hands Shelter', address: '932 Martin Luther King Blvd.', beds_available: 77, filters: {women: false, open: true} }, { shelter_id: '6', name: 'San Francisco Women\'s Shelter', address: '238 Argent Ct.', beds_available: 8, filters: {women: true, open: true} }, { shelter_id: '7', name: 'San Francisco Men\'s Shelter', address: '241 Argent Ct.', beds_available: 3, filters: {men: true, women: false, open: true} }, { shelter_id: '8', name: 'Sunset Baptist Church', address: '1438 Ulloa St.', beds_available: 0, filters: {women: true, open: true, showers: true} }, { shelter_id: '9', name: 'Jazzy\'s Place', address: '238 Mission St.', beds_available: 11, filters: {women: false, open: true, showers: true, lgbtq: true} }, { shelter_id: '10', name: 'Salvation Army', address: '1749 Van Ness St.', beds_available: 183, filters: {women: false, open: true, showers: true, lgbtq: false} } ], checkedFilters: [] }, methods: { runFilters: function () { let filtered = this.results; this.checkedFilters.forEach( function ( f ) { debugger; switch ( f ) { case 'open': filtered = filtered.filter( (i) => i.filters.open ); break; case 'beds': filtered = filtered.filter( ( i ) => i.beds_available > 0 ); break; case 'women': filtered = filtered.filter( ( i ) => i.filters.women ); break; case 'showers': filtered = filtered.filter( ( i ) => i.filters.showers ); break; case 'men': filtered = filtered.filter( ( i ) => i.filters.men ); break; case 'lgbtq': filtered = filtered.filter( ( i ) => i.filters.lgbtq ); break; } }); this.filteredResults = filtered; }, }, components: { 'shelter-result': { template: ` <div class='shelter-result'> <div class='left'> <div class='name'>\{{ name }}</div> <div class='address'>\{{ address }}</div> </div> <div class='right'> <div class='beds-available'>\{{ beds_available }}</div> <span>beds available</span> </div> </div> `, props: ['shelter_id', 'name', 'address', 'beds_available'] } } }); $(document).ready( function () { $.ajax({ type: "GET", url: `http://127.0.0.1:3000/api/beds-available`, cache: false, success: function ( shelters ) { shelters = JSON.parse(shelters); search.results = []; for ( let s of shelters ) { } } }); });
moonlatency/agoodnightspace
public/javascripts/components/search.js
JavaScript
mit
5,284
/** * Configuration * @returns {undefined} */ (function(){ 'use strict'; angular .module('demoApp') .run([ "$rootScope", "$state", "loginService", function ($rootScope, $state, loginService) { $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { if (toState.authenticate && !loginService.isLogedin()) { $state.go('login'); event.preventDefault(); // transitionTo() promise will be rejected with // a 'transition prevented' error } }); }]); })();
sunil-mane/gulpDemo
src/app/config.js
JavaScript
mit
605
(function() { var negativeFilters; negativeFilters = { textTooLong: function(text) { return text.length > 16; }, textTooShort: function(text) { return text.length < 10; }, bogusNumber: function(text) { return /\(?555\)?-?555-?5555/g.test(text); }, bogusNumberWithDashes: function(text) { return /000-000-0000/g.test(text); }, yearsRange: function(text) { return /(18|19|20)\d{2}\-(18|19|20)\d{2}\b/.test(text); }, ISODate: function(text) { return /(18|19|20)\d{2}\-([0-1]\d)-([0-3]\d)\b/.test(text); }, date: function(text) { return /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/.test(text); }, ipAddress: function(text) { return /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/.test(text); }, decimalNumber: function(text) { return /^\d*\.\d*$/.test(text); }, twoSeperators: function(text) { return /[\(\)\.\-][\(\)\.\-]/.test(text); }, commas: function(text) { return /\d+\-?\d+\,\d+/.test(text); } }; module.exports = negativeFilters; }).call(this);
fbatroni/format-phone
lib/negative-filters.js
JavaScript
mit
1,098
{ var _ref4 = babelHelpers.asyncToGenerator(function*(a, b = 1, c, ...d) {}); return function four(_x5) { return _ref4.apply(this, arguments); }; }
stas-vilchik/bdd-ml
data/1169.js
JavaScript
mit
159
/*global module:false */ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: '<json:package.json>', meta: { banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */' }, lint: { files: ['grunt.js', 'lib/**/*.js', 'test/*.js'] }, mdlldr: { lil_: { root: './node_modules/lil_/lib', src: ['lil_.js'], dest: './build/lil_.js' }, lilobj: { root: './node_modules/lilobj/lib', src: ['lilobj.js'], dest: './build/lilobj.js', overrides : { lil_: 'lil_' } }, vladiator: { root: './node_modules/vladiator/lib', src: ['vladiator.js'], dest: './build/vladiator.js', overrides : { lil_: 'lil_' } }, lilmodel: { root: './lib', src: ['lilmodel.js'], dest: './build/lilmodel.js', overrides: { lil_: 'lil_', lilobj: 'lilobj', vladiator: 'vladiator' } } }, buster: { test: { config: 'test/buster.js' }, server: { port: 1111 } }, concat: { dist: { src: [ '<banner:meta.banner>', '<file_strip_banner:node_modules/lilprovider/lib/lilprovider.js>', '<file_strip_banner:build/lil_.js>', '<file_strip_banner:build/lilobj.js>', '<file_strip_banner:build/vladiator.js>', '<file_strip_banner:build/<%= pkg.name %>.js>' ], dest: 'dist/<%= pkg.name %>.js' } }, min: { dist: { src: ['<banner:meta.banner>', '<config:concat.dist.dest>'], dest: 'dist/<%= pkg.name %>.min.js' } }, watch: { files: '<config:lint.files>', tasks: 'lint buster' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, strict: false, eqnull: true, browser: true, node: true }, globals: {} }, uglify: {} }); // Default task. grunt.registerTask('default', 'lint mdlldr concat min buster'); grunt.loadNpmTasks('grunt-mdlldr'); grunt.loadNpmTasks('grunt-buster'); };
gushov/lilmodel
grunt.js
JavaScript
mit
2,619
var NAVTREEINDEX0 = { "_h5_t_l_8hpp.html":[2,0,0,0], "_h5_t_l_8hpp.html#a0a256efae396de32f6c8e17a0ac5b410":[2,0,0,0,48], "_h5_t_l_8hpp.html#a1068acc4b97b59901883bbb88b1f4434":[2,0,0,0,36], "_h5_t_l_8hpp.html#a112af217f39b59064ce8a48cccc74764":[2,0,0,0,50], "_h5_t_l_8hpp.html#a18b8ab0e48c3efb5dca7d93efd1bfbf6":[2,0,0,0,45], "_h5_t_l_8hpp.html#a18d3869e336e2b6a64ec318cf9890c90":[2,0,0,0,57], "_h5_t_l_8hpp.html#a195c328d15cb83d2cfede33d7a7a5b35":[2,0,0,0,38], "_h5_t_l_8hpp.html#a1c8362f6cee0689275ecfddccba88274":[2,0,0,0,46], "_h5_t_l_8hpp.html#a1d69ddff4138c6eae990acc82730d434":[2,0,0,0,37], "_h5_t_l_8hpp.html#a2bb6834f5cfb632c59f6b8833fb062e1":[2,0,0,0,56], "_h5_t_l_8hpp.html#a31797435e6c9f7813cc320fc4529192f":[2,0,0,0,53], "_h5_t_l_8hpp.html#a4d53214bda1e246cb4f3d3d6919d1380":[2,0,0,0,54], "_h5_t_l_8hpp.html#a5583c20a945634c741c4c006f5abd3a6":[2,0,0,0,51], "_h5_t_l_8hpp.html#a59058fd08440d7ea30ed09d8de233185":[2,0,0,0,27], "_h5_t_l_8hpp.html#a603d589a4de14384ef7d47104e6a7862":[2,0,0,0,43], "_h5_t_l_8hpp.html#a7ccc1cda9969334b121fe7715c9f874a":[2,0,0,0,28], "_h5_t_l_8hpp.html#a85542c4df7874da8c91127958faa22a4":[2,0,0,0,40], "_h5_t_l_8hpp.html#a889fa5a542d1ee8e363d2686f1e447d7":[2,0,0,0,47], "_h5_t_l_8hpp.html#a9435795a9a0055ccdfa8194228e692a2":[2,0,0,0,35], "_h5_t_l_8hpp.html#aa0de5dcbc2c4c8a99ed8e35774ba15ab":[2,0,0,0,39], "_h5_t_l_8hpp.html#aa1cd20e4f5fb1a248b8475f923d3b1b5":[2,0,0,0,52], "_h5_t_l_8hpp.html#aa42336b53e3ba0b95d2495ba8084df67":[2,0,0,0,49], "_h5_t_l_8hpp.html#ab1eb736c80826c4999a4644ff4d1b918":[2,0,0,0,31], "_h5_t_l_8hpp.html#ab549a1bd6205a5bff9dc8e5ca83fa76a":[2,0,0,0,42], "_h5_t_l_8hpp.html#ab5f7e50bf1e42f78c4fc0214b6cceb57":[2,0,0,0,33], "_h5_t_l_8hpp.html#ab61feeb286c0d3e6c82b22277ac9291b":[2,0,0,0,34], "_h5_t_l_8hpp.html#ac159834e78342cf3e5daf694c65b0dc9":[2,0,0,0,44], "_h5_t_l_8hpp.html#adcc1829002ae4d479fad02d0bf47f793":[2,0,0,0,41], "_h5_t_l_8hpp.html#add11f817badecc20cdffaeca031e7ab5":[2,0,0,0,32], "_h5_t_l_8hpp.html#ae09d3a5b75f86dad261e807592fee081":[2,0,0,0,58], "_h5_t_l_8hpp.html#ae8a2ececf9e0f95ab928f168fcedef34":[2,0,0,0,55], "_h5_t_l_8hpp.html#aee6ce891703ca7ed2cb72046c3d1768f":[2,0,0,0,29], "_h5_t_l_8hpp.html#af374af4623acf05fb53284ae67ffc911":[2,0,0,0,30], "_h5_t_l_8hpp_source.html":[2,0,0,0], "annotated.html":[1,0], "class_h5_t_l_1_1_attribute.html":[1,0,0,14], "class_h5_t_l_1_1_attribute.html#a0720b5f434e636e22a3ed34f847eec57":[1,0,0,14,13], "class_h5_t_l_1_1_attribute.html#a14e297e1930afdcb1e6f4fd446587b72":[1,0,0,14,11], "class_h5_t_l_1_1_attribute.html#a16fd54489901878488beb8fd75be846f":[1,0,0,14,8], "class_h5_t_l_1_1_attribute.html#a32ac6a40d8cbefb6b4b6cd069dcc919f":[1,0,0,14,12], "class_h5_t_l_1_1_attribute.html#a52de6c303533cc5f76ed4e158332da49":[1,0,0,14,6], "class_h5_t_l_1_1_attribute.html#a6429348b75c240ee43281d76fe523ba4":[1,0,0,14,0], "class_h5_t_l_1_1_attribute.html#a6d651fbe37b2311c62deed182d1d2371":[1,0,0,14,3], "class_h5_t_l_1_1_attribute.html#a7b476eaa2bdc241d05ae5d57861e3cb0":[1,0,0,14,1], "class_h5_t_l_1_1_attribute.html#a813d411fb240af759bc6f38f8b64aede":[1,0,0,14,4], "class_h5_t_l_1_1_attribute.html#a976384a5498eca27eeb00d20031ac6b0":[1,0,0,14,5], "class_h5_t_l_1_1_attribute.html#ab468364f2302366ca16e53edfbdfef21":[1,0,0,14,9], "class_h5_t_l_1_1_attribute.html#ad8ce0c28ab0d1c442a5ed668b3bcb62a":[1,0,0,14,10], "class_h5_t_l_1_1_attribute.html#aebc7274e4e3313000fdefac4aa2e18c3":[1,0,0,14,7], "class_h5_t_l_1_1_attribute.html#af0918ea5d8b3ee3eace2b4b70de083da":[1,0,0,14,2], "class_h5_t_l_1_1_d_props.html":[1,0,0,9], "class_h5_t_l_1_1_d_props.html#a3c5536e4dd3c26da5f0fd14b85929394":[1,0,0,9,13], "class_h5_t_l_1_1_d_props.html#a4477e3f09c8df3b9235cc59a6107d18b":[1,0,0,9,1], "class_h5_t_l_1_1_d_props.html#a4d9c048bbe6890fb8a76f42f5e41e02c":[1,0,0,9,9], "class_h5_t_l_1_1_d_props.html#a4e6371b21d3b981b9813709a367f7c8a":[1,0,0,9,8], "class_h5_t_l_1_1_d_props.html#a558ee807583c289f062942f91e6bfc39":[1,0,0,9,2], "class_h5_t_l_1_1_d_props.html#a881b1504af4a748112c0193ad712f058":[1,0,0,9,4], "class_h5_t_l_1_1_d_props.html#a8861717b78465e2b929a8f9822a25f91":[1,0,0,9,0], "class_h5_t_l_1_1_d_props.html#aa6168baf2f7cc4e171f8c65ed2e7f0e3":[1,0,0,9,11], "class_h5_t_l_1_1_d_props.html#ab50eedeeb4f15976869e2314cda43f28":[1,0,0,9,5], "class_h5_t_l_1_1_d_props.html#adf68d5443694c5a28d089efaca1ccefc":[1,0,0,9,14], "class_h5_t_l_1_1_d_props.html#ae0515ee98e2bcd02c55160a33a63aabf":[1,0,0,9,6], "class_h5_t_l_1_1_d_props.html#ae8ab837067c35b714b517f9cf08c6833":[1,0,0,9,12], "class_h5_t_l_1_1_d_props.html#ae93cfa78bd2904d835be0ef8c01ac328":[1,0,0,9,10], "class_h5_t_l_1_1_d_props.html#af1283799daeee775b41effb026792b79":[1,0,0,9,7], "class_h5_t_l_1_1_d_props.html#af24985828926acc30de48fbf2351620f":[1,0,0,9,3], "class_h5_t_l_1_1_d_space.html":[1,0,0,11], "class_h5_t_l_1_1_d_space.html#a0ba05245349237b1e42813cf4397fa32":[1,0,0,11,2], "class_h5_t_l_1_1_d_space.html#a0bacd841219760f82023a5c6d34d71c8":[1,0,0,11,4], "class_h5_t_l_1_1_d_space.html#a217bb888d3d9666e1105a7b839f130d7":[1,0,0,11,13], "class_h5_t_l_1_1_d_space.html#a361184a3052fd5fe5bd71454b244007d":[1,0,0,11,5], "class_h5_t_l_1_1_d_space.html#a376a9922dbf0eb7234bb33d5e14825a9":[1,0,0,11,6], "class_h5_t_l_1_1_d_space.html#a527298cfe321414033f52329a49e6b7a":[1,0,0,11,10], "class_h5_t_l_1_1_d_space.html#a62a6b850d17c08da4437c6080f7c3598":[1,0,0,11,12], "class_h5_t_l_1_1_d_space.html#a7557c53c7dc3b9b4e8a12cc35a438564":[1,0,0,11,11], "class_h5_t_l_1_1_d_space.html#a7abcd0097c46b8f3252b6610bca3ebd1":[1,0,0,11,9], "class_h5_t_l_1_1_d_space.html#a8d0637d8c3adbee551721f7fbd609de1":[1,0,0,11,14], "class_h5_t_l_1_1_d_space.html#a911e7f9f9398e7324c508f55fe63baaa":[1,0,0,11,7], "class_h5_t_l_1_1_d_space.html#aa253d3194c386398cd3a614022226091":[1,0,0,11,15], "class_h5_t_l_1_1_d_space.html#ab42688e0331b2b49d311d43dde36c31e":[1,0,0,11,16], "class_h5_t_l_1_1_d_space.html#ab93eacb81dea8d0c21041812e61f85ab":[1,0,0,11,18], "class_h5_t_l_1_1_d_space.html#abd4bab8f7ee748d7ea63f7f9b6248611":[1,0,0,11,17], "class_h5_t_l_1_1_d_space.html#abe4839703fc08c5851b8388ee43177ef":[1,0,0,11,1], "class_h5_t_l_1_1_d_space.html#add7bd418265b7dcea2e6b0fd60ea15e0":[1,0,0,11,0], "class_h5_t_l_1_1_d_space.html#aed1106ff0fb79eda9c2666b62eebc4d8":[1,0,0,11,8], "class_h5_t_l_1_1_d_space.html#af10333ae1d222213a34db2a338ae158c":[1,0,0,11,3], "class_h5_t_l_1_1_d_type.html":[1,0,0,4], "class_h5_t_l_1_1_d_type.html#a0839ae0745f1ed4f15bfe521f14e983e":[1,0,0,4,6], "class_h5_t_l_1_1_d_type.html#a11fb262f22fd509d1fb047120c5b0a92":[1,0,0,4,4], "class_h5_t_l_1_1_d_type.html#a16e2caeb17c88224bb286201d1b6463c":[1,0,0,4,8], "class_h5_t_l_1_1_d_type.html#a1ece4a21faeb565b63695521a0cf0767":[1,0,0,4,9], "class_h5_t_l_1_1_d_type.html#a2e4087bdb1aae026237ac05894e559b9":[1,0,0,4,3], "class_h5_t_l_1_1_d_type.html#a5ba85ceb49042ecd7c9a536d3342a143":[1,0,0,4,2], "class_h5_t_l_1_1_d_type.html#a693b78e01470174565503241195fa7d9":[1,0,0,4,5], "class_h5_t_l_1_1_d_type.html#a7de5859c78eac6aacb64b355c40db270":[1,0,0,4,0], "class_h5_t_l_1_1_d_type.html#a9b125e54e616f2bd5c0c52849c6b2383":[1,0,0,4,1], "class_h5_t_l_1_1_d_type.html#ab93eacb81dea8d0c21041812e61f85ab":[1,0,0,4,11], "class_h5_t_l_1_1_d_type.html#abd4bab8f7ee748d7ea63f7f9b6248611":[1,0,0,4,10], "class_h5_t_l_1_1_d_type.html#af32cf33b4b23e8326ea7134fac1fa6b8":[1,0,0,4,7], "class_h5_t_l_1_1_dataset.html":[1,0,0,16], "class_h5_t_l_1_1_dataset.html#a077d5bb62ed4b99db4900ae2af64cb7b":[1,0,0,16,27], "class_h5_t_l_1_1_dataset.html#a0857ba27c707399302da28064342915f":[1,0,0,16,1], "class_h5_t_l_1_1_dataset.html#a09b7f1c8bf3d92fd3dfdf0e21138350d":[1,0,0,16,6], "class_h5_t_l_1_1_dataset.html#a0a8e406f9036b0e95d6645bc7f17dd85":[1,0,0,16,14], "class_h5_t_l_1_1_dataset.html#a0db33d74e18e6908a30ee8048a42ae5d":[1,0,0,16,4], "class_h5_t_l_1_1_dataset.html#a0dbc91a3302c8affed45970aeb3cdd88":[1,0,0,16,2], "class_h5_t_l_1_1_dataset.html#a13145066f529134568242b3aa03ff991":[1,0,0,16,15], "class_h5_t_l_1_1_dataset.html#a1b66996cc6de6e7ea03a110e15888a3a":[1,0,0,16,19], "class_h5_t_l_1_1_dataset.html#a21a8ba439908fc08837b01e737247f37":[1,0,0,16,7], "class_h5_t_l_1_1_dataset.html#a2697825715974a353728f0d4d5658112":[1,0,0,16,32], "class_h5_t_l_1_1_dataset.html#a3ac128ce40c50aaf352c70c96c853748":[1,0,0,16,13], "class_h5_t_l_1_1_dataset.html#a3b0cc1434d993029fcbff1998767e0c3":[1,0,0,16,23], "class_h5_t_l_1_1_dataset.html#a57a932b797520777fb16ebe9161cffd5":[1,0,0,16,28], "class_h5_t_l_1_1_dataset.html#a59c376ac04cbb6f040d3bcf7ddac2c21":[1,0,0,16,31], "class_h5_t_l_1_1_dataset.html#a5eff3aaf3ac89c159cd8182400947b50":[1,0,0,16,25], "class_h5_t_l_1_1_dataset.html#a72b917d03cf1be028b0a60663f3735da":[1,0,0,16,11], "class_h5_t_l_1_1_dataset.html#a791cc0c96a11264f01137984487ee17c":[1,0,0,16,9], "class_h5_t_l_1_1_dataset.html#a82d72341e7102390af4995aaaea3962a":[1,0,0,16,10], "class_h5_t_l_1_1_dataset.html#a85346218808829de0cb2c84fa42efe86":[1,0,0,16,30], "class_h5_t_l_1_1_dataset.html#a870b88885b1edd806edcc15cc4a68b89":[1,0,0,16,12], "class_h5_t_l_1_1_dataset.html#a918b06db14171308441b89b701d827ba":[1,0,0,16,3], "class_h5_t_l_1_1_dataset.html#a919ef513e9cd4bb57c796551d4b1d2f7":[1,0,0,16,29], "class_h5_t_l_1_1_dataset.html#a993f08f7a55ecf7cef453c58af2de7c8":[1,0,0,16,21], "class_h5_t_l_1_1_dataset.html#aa7ffa9c5a6f1e11351fecea1dbf7d9c5":[1,0,0,16,20], "class_h5_t_l_1_1_dataset.html#aa8d9fd06fae090ddded69ac66040443a":[1,0,0,16,18], "class_h5_t_l_1_1_dataset.html#ab0f7e4ae35955b9c4990f23405b37186":[1,0,0,16,17], "class_h5_t_l_1_1_dataset.html#aba2bb711bf30e38ac5078663c200c318":[1,0,0,16,8], "class_h5_t_l_1_1_dataset.html#abddc9236c56c2631b70dc2347d5788bd":[1,0,0,16,16], "class_h5_t_l_1_1_dataset.html#add8fa95fb77a9167f432e5d6abddc2ed":[1,0,0,16,22], "class_h5_t_l_1_1_dataset.html#aebd58da33d992bb608067c85c944e688":[1,0,0,16,24], "class_h5_t_l_1_1_dataset.html#aec3ddf07a6b592c8e7f8b44e7fd35375":[1,0,0,16,26], "class_h5_t_l_1_1_dataset.html#af0f65d79e42993b413fdc48760a28bf5":[1,0,0,16,5], "class_h5_t_l_1_1_dataset.html#af6f2cd1a5170e2b7d866721c9be0fd11":[1,0,0,16,0], "class_h5_t_l_1_1_error_handler.html":[1,0,0,2], "class_h5_t_l_1_1_error_handler.html#ad45ba2e2661df16f5f78d4c1e9aeec33":[1,0,0,2,0], "class_h5_t_l_1_1_file.html":[1,0,0,18], "class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208":[1,0,0,18,0], "class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208a1827760549531e870388ec6866d0165e":[1,0,0,18,0,3], "class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208a7595a9318f8f007c8177eb6129cc8a55":[1,0,0,18,0,0], "class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208ab0b0c0c75d3e15b086124b605f60d753":[1,0,0,18,0,2], "class_h5_t_l_1_1_file.html#a19ac74cd8f7db7d836092d9354b51208afcf13dfdb15f7aa5839846725365a240":[1,0,0,18,0,1], "class_h5_t_l_1_1_file.html#a5499e761feeab4c85ca3aba1fb218ec9":[1,0,0,18,3], "class_h5_t_l_1_1_file.html#a91c89c5f48ddd0762fd39ee1e0ae73b8":[1,0,0,18,1], "class_h5_t_l_1_1_file.html#aa05382409178af69cda0f65a13bd969f":[1,0,0,18,2], "class_h5_t_l_1_1_group.html":[1,0,0,17], "class_h5_t_l_1_1_group.html#a1acf181964e091a05491bdd07dc2acf2":[1,0,0,17,28], "class_h5_t_l_1_1_group.html#a21fb4c34f51a8a56817f5a8ea1c8b9f3":[1,0,0,17,2], "class_h5_t_l_1_1_group.html#a23cda162d64c296d39cdd3c63551c275":[1,0,0,17,1], "class_h5_t_l_1_1_group.html#a24d333709b9200ecc94c51f4081ebd70":[1,0,0,17,24], "class_h5_t_l_1_1_group.html#a2b8d910eb930a2ec45b3051452a79d73":[1,0,0,17,9], "class_h5_t_l_1_1_group.html#a3161bd364a0f5f4df9d81619482ff559":[1,0,0,17,10], "class_h5_t_l_1_1_group.html#a33879ce41734238eb50b6917268d279d":[1,0,0,17,4], "class_h5_t_l_1_1_group.html#a35a7440b9f212a8498da095fffa6df6d":[1,0,0,17,18], "class_h5_t_l_1_1_group.html#a373048dcbc38705ab6439b7eb7d66a7e":[1,0,0,17,3], "class_h5_t_l_1_1_group.html#a3bc589843f86da0a0e3c7c0382c47188":[1,0,0,17,15], "class_h5_t_l_1_1_group.html#a3ebe23fce9aecac979096da6a71db0c5":[1,0,0,17,23], "class_h5_t_l_1_1_group.html#a574293c18fed3e5391267dd3c33bf81a":[1,0,0,17,7], "class_h5_t_l_1_1_group.html#a60f8bb8b3a76fa457331a375172fc716":[1,0,0,17,21], "class_h5_t_l_1_1_group.html#a709506d6232025482633abcb97a4d7c5":[1,0,0,17,8], "class_h5_t_l_1_1_group.html#a7f928985e0131b63c21764136bf1a01d":[1,0,0,17,14], "class_h5_t_l_1_1_group.html#a84745fdcd43c75880ca4cd1e064e4ac9":[1,0,0,17,16], "class_h5_t_l_1_1_group.html#a90c193fd37dd7f35b9b62f05f830b084":[1,0,0,17,26], "class_h5_t_l_1_1_group.html#aa7ec7b8867f7e0bcf2fb1ee7de321119":[1,0,0,17,27], "class_h5_t_l_1_1_group.html#aa894ff509b260d0c5d68a765a5940da9":[1,0,0,17,5], "class_h5_t_l_1_1_group.html#ab4fbf0c28300b542e2279f5e85fb641f":[1,0,0,17,25], "class_h5_t_l_1_1_group.html#ab6faa3a0b9c6f9358130e1e5e4a08ad1":[1,0,0,17,6], "class_h5_t_l_1_1_group.html#ab726c68a6db6a1055085e59dfb87621f":[1,0,0,17,17], "class_h5_t_l_1_1_group.html#ab8333c1f74f0d82b87b0a3056b36bfa7":[1,0,0,17,20], "class_h5_t_l_1_1_group.html#abbf255a903c6a9c5a5dcb33660ce0370":[1,0,0,17,12], "class_h5_t_l_1_1_group.html#ac23072a42de2e938f27e64ea0cd9d96f":[1,0,0,17,19], "class_h5_t_l_1_1_group.html#ac40bee3d18aed5cc150ec47d61554ef3":[1,0,0,17,13], "class_h5_t_l_1_1_group.html#acc0a96894857a334132329442482803b":[1,0,0,17,22], "class_h5_t_l_1_1_group.html#ad2459b5cc9b72fe123565b5afa9c0c8a":[1,0,0,17,0], "class_h5_t_l_1_1_group.html#af143a648b8feec1260727e16960afff1":[1,0,0,17,11], "class_h5_t_l_1_1_hyperslab.html":[1,0,0,13], "class_h5_t_l_1_1_hyperslab.html#a5dcf0570bbda6a425edaaf2af29f3fb1":[1,0,0,13,0], "class_h5_t_l_1_1_hyperslab.html#a6767e21930b6bf0045ff24344b062c25":[1,0,0,13,1], "class_h5_t_l_1_1_hyperslab.html#a70290a488decd4290d13257aae5e6a4b":[1,0,0,13,4], "class_h5_t_l_1_1_hyperslab.html#a84b19741f0b131c62fdf82a596ae3a29":[1,0,0,13,3], "class_h5_t_l_1_1_hyperslab.html#a9d67100bbeba66acc2d936da2ffdc79d":[1,0,0,13,8], "class_h5_t_l_1_1_hyperslab.html#ae3087ea27a6ab424547472e6c4a6c531":[1,0,0,13,7], "class_h5_t_l_1_1_hyperslab.html#ae3e0aa330ed576da3267eeb02e4ca4c0":[1,0,0,13,6], "class_h5_t_l_1_1_hyperslab.html#af558c4b94ecde78058d2c47520d1e8b0":[1,0,0,13,2], "class_h5_t_l_1_1_hyperslab.html#afc57fefbc6fa76330390afb77a3c889d":[1,0,0,13,5], "class_h5_t_l_1_1_i_d.html":[1,0,0,3], "class_h5_t_l_1_1_i_d.html#a408f510fcc998acb721e21c483846caa":[1,0,0,3,2], "class_h5_t_l_1_1_i_d.html#a51fe296eef6fafcddcbdac65255ea1e8":[1,0,0,3,0], "class_h5_t_l_1_1_i_d.html#a619d958450480ffdd8369ef2895560b5":[1,0,0,3,1], "class_h5_t_l_1_1_i_d.html#a62a65c2333d41830c1410a6487dee22d":[1,0,0,3,7], "class_h5_t_l_1_1_i_d.html#a71ff0b5de76ffecc1292c8b6ef8292f1":[1,0,0,3,6], "class_h5_t_l_1_1_i_d.html#a84bdd4ffb1463004dfaef450b4e19d37":[1,0,0,3,9], "class_h5_t_l_1_1_i_d.html#ac262957473b62ff680747b1244be8ff0":[1,0,0,3,4], "class_h5_t_l_1_1_i_d.html#ac3f6aeae98925e043f2e2e3c892d42fd":[1,0,0,3,3], "class_h5_t_l_1_1_i_d.html#ace3dd29ee46843c37e8622369698baf2":[1,0,0,3,8], "class_h5_t_l_1_1_i_d.html#ad1a35bb991077bb094cdb0bb44339907":[1,0,0,3,5], "class_h5_t_l_1_1_i_d.html#ade483b65e8a77310b025e86b11cbc38c":[1,0,0,3,10], "class_h5_t_l_1_1_l_props.html":[1,0,0,8], "class_h5_t_l_1_1_l_props.html#a32b5f1fffdf3c896f5bf227bc16ef4d7":[1,0,0,8,1], "class_h5_t_l_1_1_l_props.html#a6604710a45e0f3cc1c124be10b3d8dac":[1,0,0,8,0], "class_h5_t_l_1_1_l_props.html#aa517b340764074934db64700f5b8f904":[1,0,0,8,4], "class_h5_t_l_1_1_l_props.html#aad7af2c22c381bfb797ba6571efd0979":[1,0,0,8,3], "class_h5_t_l_1_1_l_props.html#ad653b9016ec853a59877d154a963f4fe":[1,0,0,8,2], "class_h5_t_l_1_1_object.html":[1,0,0,15], "class_h5_t_l_1_1_object.html#a0df22bfe64e6dad435b5213bd30f4b9f":[1,0,0,15,1], "class_h5_t_l_1_1_object.html#a2754b17af0171db4213ff3471f43735e":[1,0,0,15,5], "class_h5_t_l_1_1_object.html#a33796a47bc89d5296c62e979480a650a":[1,0,0,15,4], "class_h5_t_l_1_1_object.html#a78d80a9f9e9423d1d57c3b6a31900a32":[1,0,0,15,10], "class_h5_t_l_1_1_object.html#a8010c2daf63f2040fab6301f34285159":[1,0,0,15,3], "class_h5_t_l_1_1_object.html#aa30a49c0c7cef0c84c1b2a8ea281e191":[1,0,0,15,6], "class_h5_t_l_1_1_object.html#ab22f9aa2fa49a3a69a88e92612e31d2a":[1,0,0,15,7], "class_h5_t_l_1_1_object.html#ab4e2a0eb603b800ef2166050b0675270":[1,0,0,15,2], "class_h5_t_l_1_1_object.html#ab51c998e3e77a3dd32e6fb045adfac87":[1,0,0,15,9], "class_h5_t_l_1_1_object.html#ac17e32f04e0626a107f15bc9cf076214":[1,0,0,15,12], "class_h5_t_l_1_1_object.html#aceb78cc5b05918cf22a7f299baf790af":[1,0,0,15,0], "class_h5_t_l_1_1_object.html#adc6638b07f5ea389c7cd507837b0c0be":[1,0,0,15,11], "class_h5_t_l_1_1_object.html#afc9034606870ae1b5cd6a40f51ce35ee":[1,0,0,15,8], "class_h5_t_l_1_1_p_d_type.html":[1,0,0,5], "class_h5_t_l_1_1_p_d_type.html#a108044a31b27a19222feaaf06e801020":[1,0,0,5,1], "class_h5_t_l_1_1_p_d_type.html#a1a81627ad759d043623abd9311347fa4":[1,0,0,5,5], "class_h5_t_l_1_1_p_d_type.html#a300306023ca0360e2810732c7779681b":[1,0,0,5,2], "class_h5_t_l_1_1_p_d_type.html#a5d84f01f19b6b9adfe0592af6acff6bf":[1,0,0,5,0], "class_h5_t_l_1_1_p_d_type.html#a6addc1c1ab9e438912b9e3bf65cd6f6a":[1,0,0,5,3], "class_h5_t_l_1_1_p_d_type.html#a85fa032de8ec7be551f92e2115743518":[1,0,0,5,4], "class_h5_t_l_1_1_props.html":[1,0,0,7], "class_h5_t_l_1_1_props.html#a362a126d171e718c9505390e239759a6":[1,0,0,7,1], "class_h5_t_l_1_1_props.html#a3a3d47cfae590b862326a5f1d7de3090":[1,0,0,7,3], "class_h5_t_l_1_1_props.html#a3b066dc66162bf42d0c63b3aa0739444":[1,0,0,7,0], "class_h5_t_l_1_1_props.html#a6ef94b756784840c67410dd5dacdfa40":[1,0,0,7,2], "class_h5_t_l_1_1_props.html#a7c0e3fcebfb68468dc1c63958d31533b":[1,0,0,7,5], "class_h5_t_l_1_1_props.html#a90b5f20064452d9b1da869c2cbb317cb":[1,0,0,7,4], "class_h5_t_l_1_1_select_all.html":[1,0,0,12], "class_h5_t_l_1_1_selection.html":[1,0,0,10], "class_h5_t_l_1_1_selection.html#a171d5093cb878eb3e30d0779667fbb13":[1,0,0,10,3], "class_h5_t_l_1_1_selection.html#a9594895f58f917d8c450c66583d3f7ff":[1,0,0,10,2], "class_h5_t_l_1_1_selection.html#ab7e340d2861f5e60b0e80381d39ba0c3":[1,0,0,10,1], "class_h5_t_l_1_1_selection.html#aeab63be2c41250d0ab36c00356a8f750":[1,0,0,10,0], "class_h5_t_l_1_1_selection.html#af2025c1e456b063868920512aedc05c9":[1,0,0,10,4], "class_h5_t_l_1_1h5tl__error.html":[1,0,0,1], "class_h5_t_l_1_1h5tl__error.html#abd8aa21e8e8a60d268d57a770c754390":[1,0,0,1,1], "class_h5_t_l_1_1h5tl__error.html#ad46996ee68c341429d40437d57d2ccda":[1,0,0,1,0], "classes.html":[1,1], "dir_f33336c2fcaa8208dac3bc1a258ddbd4.html":[2,0,0], "files.html":[2,0], "functions.html":[1,3,0], "functions.html":[1,3,0,0], "functions_b.html":[1,3,0,1], "functions_c.html":[1,3,0,2], "functions_d.html":[1,3,0,3], "functions_e.html":[1,3,0,4], "functions_enum.html":[1,3,4] };
s-bear/H5TL
doc/html/navtreeindex0.js
JavaScript
mit
18,438