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
Ext.namespace('Ext.ux.plugin'); Ext.onReady(function(){ /* This important rule solves many of the <object/iframe>.reInit issues encountered * when setting display:none on an upstream(parent) element (on all Browsers except IE). * This default rule enables the new Panel:hideMode 'nosize'. The rule is designed to * set height/width to 0 cia CSS if hidden or collapsed. * Additional selectors also hide 'x-panel-body's within layouts to prevent * container and <object, img, iframe> bleed-thru. */ var CSS = Ext.util.CSS; if(CSS){ CSS.getRule('.x-hide-nosize') || //already defined? CSS.createStyleSheet('.x-hide-nosize{height:0px!important;width:0px!important;border:none!important;zoom:1;}.x-hide-nosize * {height:0px!important;width:0px!important;border:none!important;zoom:1;}'); CSS.refreshCache(); } }); (function(){ var El = Ext.Element, A = Ext.lib.Anim, supr = El.prototype; var VISIBILITY = "visibility", DISPLAY = "display", HIDDEN = "hidden", NONE = "none"; var fx = {}; fx.El = { /** * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true. * @param {Mixed} value Boolean value to display the element using its default display, or a string to set the display directly. * @return {Ext.Element} this */ setDisplayed : function(value) { var me=this; me.visibilityCls ? (me[value !== false ?'removeClass':'addClass'](me.visibilityCls)) : supr.setDisplayed.call(me, value); return me; }, /** * Returns true if display is not "none" or the visibilityCls has not been applied * @return {Boolean} */ isDisplayed : function() { return !(this.hasClass(this.visibilityCls) || this.isStyle(DISPLAY, NONE)); }, // private fixDisplay : function(){ var me = this; supr.fixDisplay.call(me); me.visibilityCls && me.removeClass(me.visibilityCls); }, /** * Checks whether the element is currently visible using both visibility, display, and nosize class properties. * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false) * @return {Boolean} True if the element is currently visible, else false */ isVisible : function(deep) { var vis = this.visible || (!this.isStyle(VISIBILITY, HIDDEN) && (this.visibilityCls ? !this.hasClass(this.visibilityCls) : !this.isStyle(DISPLAY, NONE)) ); if (deep !== true || !vis) { return vis; } var p = this.dom.parentNode, bodyRE = /^body/i; while (p && !bodyRE.test(p.tagName)) { if (!Ext.fly(p, '_isVisible').isVisible()) { return false; } p = p.parentNode; } return true; }, //Assert isStyle method for Ext 2.x isStyle: supr.isStyle || function(style, val) { return this.getStyle(style) == val; } }; //Add basic capabilities to the Ext.Element.Flyweight class Ext.override(El.Flyweight, fx.El); /** * @class Ext.ux.plugin.VisibilityMode * @version 1.3.1 * @author Doug Hendricks. doug[always-At]theactivegroup.com * @copyright 2007-2009, Active Group, Inc. All rights reserved. * @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a> * @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a> * @singleton * @static * @desc This plugin provides an alternate mechanism for hiding Ext.Elements and a new hideMode for Ext.Components.<br /> * <p>It is generally designed for use with all browsers <b>except</b> Internet Explorer, but may used on that Browser as well. * <p>If included in a Component as a plugin, it sets it's hideMode to 'nosize' and provides a new supported * CSS rule that sets the height and width of an element and all child elements to 0px (rather than * 'display:none', which causes DOM reflow to occur and re-initializes nested OBJECT, EMBED, and IFRAMES elements) * @example var div = Ext.get('container'); new Ext.ux.plugin.VisibilityMode().extend(div); //You can override the Element (instance) visibilityCls to any className you wish at any time div.visibilityCls = 'my-hide-class'; div.hide() //or div.setDisplayed(false); // In Ext Layouts: someContainer.add({ xtype:'flashpanel', plugins: [new Ext.ux.plugin.VisibilityMode() ], ... }); // or, Fix a specific Container only and all of it's child items: // Note: An upstream Container may still cause Reflow issues when hidden/collapsed var V = new Ext.ux.plugin.VisibilityMode({ bubble : false }) ; new Ext.TabPanel({ plugins : V, defaults :{ plugins: V }, items :[....] }); */ Ext.ux.plugin.VisibilityMode = function(opt) { Ext.apply(this, opt||{}); var CSS = Ext.util.CSS; if(CSS && !Ext.isIE && this.fixMaximizedWindow !== false && !Ext.ux.plugin.VisibilityMode.MaxWinFixed){ //Prevent overflow:hidden (reflow) transitions when an Ext.Window is maximize. CSS.updateRule ( '.x-window-maximized-ct', 'overflow', ''); Ext.ux.plugin.VisibilityMode.MaxWinFixed = true; //only updates the CSS Rule once. } }; Ext.extend(Ext.ux.plugin.VisibilityMode , Object, { /** * @cfg {Boolean} bubble If true, the VisibilityMode fixes are also applied to parent Containers which may also impact DOM reflow. * @default true */ bubble : true, /** * @cfg {Boolean} fixMaximizedWindow If not false, the ext-all.css style rule 'x-window-maximized-ct' is disabled to <b>prevent</b> reflow * after overflow:hidden is applied to the document.body. * @default true */ fixMaximizedWindow : true, /** * * @cfg {array} elements (optional) A list of additional named component members to also adjust visibility for. * <br />By default, the plugin handles most scenarios automatically. * @default null * @example ['bwrap','toptoolbar'] */ elements : null, /** * @cfg {String} visibilityCls A specific CSS classname to apply to Component element when hidden/made visible. * @default 'x-hide-nosize' */ visibilityCls : 'x-hide-nosize', /** * @cfg {String} hideMode A specific hideMode value to assign to affected Components. * @default 'nosize' */ hideMode : 'nosize' , ptype : 'uxvismode', /** * Component plugin initialization method. * @param {Ext.Component} c The Ext.Component (or subclass) for which to apply visibilityMode treatment */ init : function(c) { var hideMode = this.hideMode || c.hideMode, plugin = this, bubble = Ext.Container.prototype.bubble, changeVis = function(){ var els = [this.collapseEl, this.actionMode].concat(plugin.elements||[]); Ext.each(els, function(el){ plugin.extend( this[el] || el ); },this); var cfg = { visFixed : true, animCollapse : false, animFloat : false, hideMode : hideMode, defaults : this.defaults || {} }; cfg.defaults.hideMode = hideMode; Ext.apply(this, cfg); Ext.apply(this.initialConfig || {}, cfg); }; c.on('render', function(){ // Bubble up the layout and set the new // visibility mode on parent containers // which might also cause DOM reflow when // hidden or collapsed. if(plugin.bubble !== false && this.ownerCt){ bubble.call(this.ownerCt, function(){ this.visFixed || this.on('afterlayout', changeVis, this, {single:true} ); }); } changeVis.call(this); }, c, {single:true}); }, /** * @param {Element/Array} el The Ext.Element (or Array of Elements) to extend visibilityCls handling to. * @param {String} visibilityCls The className to apply to the Element when hidden. * @return this */ extend : function(el, visibilityCls){ el && Ext.each([].concat(el), function(e){ if(e && e.dom){ if('visibilityCls' in e)return; //already applied or defined? Ext.apply(e, fx.El); e.visibilityCls = visibilityCls || this.visibilityCls; } },this); return this; } }); Ext.preg && Ext.preg('uxvismode', Ext.ux.plugin.VisibilityMode ); /** @sourceURL=<uxvismode.js> */ Ext.provide && Ext.provide('uxvismode'); })();
Eric-Brison/dynacase-core
Zone/Ui/uxvismode.js
JavaScript
agpl-3.0
9,949
/* * Copyright (C) 2016 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import $ from 'jquery' import fakeENV from 'helpers/fakeENV' import api from 'compiled/api/enrollmentTermsApi' import 'jquery.ajaxJSON' const deserializedTerms = [ { id: '1', name: 'Fall 2013 - Art', startAt: new Date('2013-06-03T02:57:42Z'), endAt: new Date('2013-12-03T02:57:53Z'), createdAt: new Date('2015-10-27T16:51:41Z'), gradingPeriodGroupId: '2' }, { id: '3', name: null, startAt: new Date('2014-01-03T02:58:36Z'), endAt: new Date('2014-03-03T02:58:42Z'), createdAt: new Date('2013-06-02T17:29:19Z'), gradingPeriodGroupId: '2' }, { id: '4', name: null, startAt: null, endAt: null, createdAt: new Date('2014-05-02T17:29:19Z'), gradingPeriodGroupId: '1' } ] const serializedTerms = { enrollment_terms: [ { id: 1, name: 'Fall 2013 - Art', start_at: '2013-06-03T02:57:42Z', end_at: '2013-12-03T02:57:53Z', created_at: '2015-10-27T16:51:41Z', grading_period_group_id: 2 }, { id: 3, name: null, start_at: '2014-01-03T02:58:36Z', end_at: '2014-03-03T02:58:42Z', created_at: '2013-06-02T17:29:19Z', grading_period_group_id: 2 }, { id: 4, name: null, start_at: null, end_at: null, created_at: '2014-05-02T17:29:19Z', grading_period_group_id: 1 } ] } QUnit.module('list', { setup() { this.server = sinon.fakeServer.create() this.fakeHeaders = '<http://some_url?page=1&per_page=10>; rel="last"' fakeENV.setup() ENV.ENROLLMENT_TERMS_URL = 'api/enrollment_terms' }, teardown() { fakeENV.teardown() this.server.restore() } }) test('calls the resolved endpoint', () => { sandbox.stub($, 'ajaxJSON') api.list() ok($.ajaxJSON.calledWith('api/enrollment_terms')) }) test('deserializes returned enrollment terms', function(assert) { const start = assert.async() this.server.respondWith('GET', /enrollment_terms/, [ 200, { 'Content-Type': 'application/json', Link: this.fakeHeaders }, JSON.stringify(serializedTerms) ]) api.list().then(terms => { deepEqual(terms, deserializedTerms) start() }) this.server.respond() }) test('rejects the promise upon errors', function(assert) { const start = assert.async() this.server.respondWith('GET', /enrollment_terms/, [ 404, {'Content-Type': 'application/json'}, 'FAIL' ]) api.list().catch(error => { ok('we got here') start() }) this.server.respond() })
djbender/canvas-lms
spec/coffeescripts/api/enrollmentTermsApiSpec.js
JavaScript
agpl-3.0
3,227
'use strict'; /* jshint node: true */ var logger = require('nlogger').logger(module); var express = require('express'); var _ = require('underscore'); var config = require('./config'); var poller = require('./poller'); var app = module.exports = express.createServer(); var reports = {}; function reapOldReports() { logger.info('starting reap cycle on reports: ', _.keys(reports).length); _.each(_.keys(reports), function(key) { var report = reports[key]; var age = Math.round(((new Date()).getTime() - report.reported)/1000); if (age >= config.reapAge) { logger.info('reaping stale report for: {}:{}', report.host, report.port); delete reports[key]; } }); } poller.emitter.on('report', function(report) { var key = report.host + ':' + report.port; reports[key] = report; }); app.configure(function() { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/pages', { maxAge: 60*60*1000 })); app.use(express.static(__dirname + '/static', { maxAge: 3*24*60*60*1000 })); app.use(express.compress()); }); app.configure(function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.get('/reports', function(req, res) { res.setHeader('Content-Type', 'application/json'); res.setHeader('Cache-Control', 'public, max-age=' + 10); res.send(JSON.stringify(reports)); res.end(); }); logger.info('starting web UI on port: ', config.httpPort); app.listen(config.httpPort); poller.startPollingMasterServer(); setInterval(reapOldReports, config.reapInterval*1000);
stainsby/redflare
app.js
JavaScript
agpl-3.0
1,636
OC.L10N.register( "settings", { "Delete" : "తొలగించు", "Server address" : "సేవకి చిరునామా", "Cancel" : "రద్దుచేయి", "Email" : "ఈమెయిలు", "Your email address" : "మీ ఈమెయిలు చిరునామా", "Password" : "సంకేతపదం", "New password" : "కొత్త సంకేతపదం", "Language" : "భాష", "Name" : "పేరు", "Username" : "వాడుకరి పేరు", "Personal" : "వ్యక్తిగతం", "Error" : "పొరపాటు" }, "nplurals=2; plural=(n != 1);");
jacklicn/owncloud
settings/l10n/te.js
JavaScript
agpl-3.0
668
OC.L10N.register( "settings", { "Enabled" : "Włączone", "Not enabled" : "Nie włączone", "Wrong password" : "Złe hasło", "Saved" : "Zapisano", "No user supplied" : "Niedostarczony użytkownik", "Unable to change password" : "Nie można zmienić hasła", "Authentication error" : "Błąd uwierzytelniania", "Please provide an admin recovery password, otherwise all user data will be lost" : "Podaj hasło odzyskiwania administratora, w przeciwnym razie wszystkie dane użytkownika zostaną utracone", "Wrong admin recovery password. Please check the password and try again." : "Błędne hasło odzyskiwania. Sprawdź hasło i spróbuj ponownie.", "Backend doesn't support password change, but the user's encryption key was successfully updated." : "Zaplecze nie obsługuje zmiany hasła, ale klucz szyfrowania użytkownika został pomyślnie zaktualizowany.", "installing and updating apps via the app store or Federated Cloud Sharing" : "instalacji i aktualizacji aplikacji za pośrednictwem sklepu z aplikacjami lub udziałem Stowarzyszonej Chmury", "Federated Cloud Sharing" : "Dzielenie się ze Stowarzyszoną Chmurą", "A problem occurred, please check your log files (Error: %s)" : "Wystąpił problem, sprawdź logi (Error: %s) ", "Migration Completed" : "Migracja Zakończona", "Group already exists." : "Grupa już istnieje.", "Unable to add group." : "Nie można dodać grupy.", "Unable to delete group." : "Nie można usunąć grupy.", "test email settings" : "przetestuj ustawienia email", "A problem occurred while sending the email. Please revise your settings. (Error: %s)" : "Wystąpił błąd podczas wysyłania wiadomości e-mail. Proszę zmienić swoje ustawienia. (Error: %s)", "Email sent" : "E-mail wysłany", "You need to set your user email before being able to send test emails." : "Musisz najpierw ustawić użytkownika e-mail, aby móc wysyłać wiadomości testowe.", "Invalid request" : "Nieprawidłowe żądanie", "Invalid mail address" : "Nieprawidłowy adres email", "A user with that name already exists." : "Użytkownik o tej nazwie już istnieje.", "Unable to create user." : "Nie można utworzyć użytkownika.", "Your %s account was created" : "Twoje konto %s zostało stworzone", "Unable to delete user." : "Nie można usunąć użytkownika.", "Settings saved" : "Ustawienia zachowane", "Unable to change full name" : "Nie można zmienić pełnej nazwy", "Unable to change email address" : "Nie można zmienić adresu e-mail", "Your full name has been changed." : "Twoja pełna nazwa została zmieniona.", "Forbidden" : "Zabronione", "Invalid user" : "Nieprawidłowy użytkownik", "Unable to change mail address" : "Nie można zmienić adresu email", "Email saved" : "E-mail zapisany", "Password confirmation is required" : "Wymagane jest potwierdzenie hasła", "Couldn't remove app." : "Nie można usunąć aplikacji.", "Couldn't update app." : "Nie można uaktualnić aplikacji.", "Are you really sure you want add {domain} as trusted domain?" : "Czy jesteś pewien/pewna że chcesz dodać \"{domain}\" jako zaufaną domenę?", "Add trusted domain" : "Dodaj zaufaną domenę", "Migration in progress. Please wait until the migration is finished" : "Trwa migracja. Proszę poczekać, aż migracja dobiegnie końca.", "Migration started …" : "Migracja rozpoczęta...", "Not saved" : "Nie zapisany", "Sending..." : "Wysyłam...", "Official" : "Oficjalny", "All" : "Wszystkie", "Update to %s" : "Uaktualnij do %s", "_You have %n app update pending_::_You have %n app updates pending_" : ["Masz %n oczekującą aktualizację aplikacji","Masz %n oczekujące aktualizacje aplikacji","Masz %n oczekujących aktualizacji aplikacji"], "No apps found for your version" : "Nie znaleziono aplikacji dla twojej wersji", "The app will be downloaded from the app store" : "Aplikacja zostanie pobrana z App Store", "Error while disabling app" : "Błąd podczas wyłączania aplikacji", "Disable" : "Wyłącz", "Enable" : "Włącz", "Error while enabling app" : "Błąd podczas włączania aplikacji", "Error: this app cannot be enabled because it makes the server unstable" : "Błąd: ta aplikacja nie może być włączona, ponieważ sprawia, że serwer jest niestabilny", "Error: could not disable broken app" : "Błąd: nie można wyłączyć zepsutą aplikację", "Error while disabling broken app" : "Błąd podczas wyłączania zepsutej aplikacji", "Updating...." : "Aktualizacja w toku...", "Error while updating app" : "Błąd podczas aktualizacji aplikacji", "Updated" : "Zaktualizowano", "Uninstalling ...." : "Odinstalowywanie....", "Error while uninstalling app" : "Błąd przy odinstalowywaniu aplikacji", "Uninstall" : "Odinstaluj", "The app has been enabled but needs to be updated. You will be redirected to the update page in 5 seconds." : "Aplikacja została włączona i musi być aktualizowana. Zostaniesz przekierowany na stronę aktualizacji za 5 sekund.", "App update" : "Aktualizacja aplikacji", "Approved" : "Zatwierdzony", "Experimental" : "Eksperymentalny", "No apps found for {query}" : "Nie znaleziono aplikacji dla {query}", "Allow filesystem access" : "Zezwalaj na dostęp do systemu plików", "Disconnect" : "Odłącz", "Revoke" : "Cofnij", "Internet Explorer" : "Internet Explorer", "Edge" : "Edge", "Firefox" : "Firefox", "Google Chrome" : "Google Chrome", "Safari" : "Safari", "Google Chrome for Android" : "Google Chrome dla Android", "iPhone iOS" : "iPhone iOS", "iPad iOS" : "iPad iOS", "iOS Client" : "Klient iOS", "Android Client" : "Klient Android", "Sync client - {os}" : "Klient synchronizacji - {os}", "This session" : "Ta sesja", "Copy" : "Skopiuj", "Copied!" : "Skopiowano!", "Not supported!" : "Nieobsługiwany!", "Press ⌘-C to copy." : "Wciśnij ⌘-C by skopiować.", "Press Ctrl-C to copy." : "Wciśnij Ctrl-C by skopiować.", "Error while loading browser sessions and device tokens" : "Błąd podczas ładowania sesji przeglądarek i tokenów urządzeń", "Error while creating device token" : "Błąd podczas tworzenia tokena urządzenia.", "Error while deleting the token" : "Błąd podczas usuwania tokena.", "An error occurred. Please upload an ASCII-encoded PEM certificate." : "Wystąpił błąd. Proszę przesłać certyfikat PEM w kodowaniu ASCII.", "Valid until {date}" : "Ważny do {date}", "Delete" : "Usuń", "Local" : "Lokalny", "Private" : "Prywatny", "Only visible to local users" : "Widoczne tylko dla użytkowników lokalnych", "Only visible to you" : "Widoczne tylko dla Ciebie", "Contacts" : "Kontakty", "Visible to local users and to trusted servers" : "Widoczne dla lokalnych użytkowników i zaufanych serwerów", "Public" : "Publiczny", "Will be synced to a global and public address book" : "Będą zsynchronizowane z globalną i publiczną książką adresową", "Select a profile picture" : "Wybierz zdjęcie profilu", "Very weak password" : "Bardzo słabe hasło", "Weak password" : "Słabe hasło", "So-so password" : "Mało skomplikowane hasło", "Good password" : "Dobre hasło", "Strong password" : "Mocne hasło", "Groups" : "Grupy", "Unable to delete {objName}" : "Nie można usunąć {objName}", "Error creating group: {message}" : "Błąd podczas tworzenia grupy: {message}", "A valid group name must be provided" : "Należy podać prawidłową nazwę grupy", "deleted {groupName}" : "usunięto {groupName}", "undo" : "cofnij", "never" : "nigdy", "deleted {userName}" : "usunięto {userName}", "Add group" : "Dodaj grupę", "Invalid quota value \"{val}\"" : "Nieprawidłowa wartość quota \"{val}\"", "no group" : "brak grupy", "Password successfully changed" : "Zmiana hasła udana.", "Changing the password will result in data loss, because data recovery is not available for this user" : "Zmiana hasła spowoduje utratę danych, ponieważ odzyskiwanie danych nie jest włączone dla tego użytkownika", "Could not change the users email" : "Nie można zmienić adresu e-mail użytkowników", "A valid username must be provided" : "Należy podać prawidłową nazwę użytkownika", "Error creating user: {message}" : "Błąd podczas tworzenia użytkownika: {message}", "A valid password must be provided" : "Należy podać prawidłowe hasło", "A valid email must be provided" : "Podaj poprawny adres email", "__language_name__" : "polski", "Unlimited" : "Bez limitu", "Personal info" : "Informacje osobiste", "Sessions" : "Sesje", "App passwords" : "Hasła aplikacji", "Sync clients" : "Klienty synchronizacji", "None" : "Nic", "Login" : "Login", "Plain" : "Czysty tekst", "NT LAN Manager" : "NT LAN Manager", "SSL/TLS" : "SSL/TLS", "STARTTLS" : "STARTTLS", "Email server" : "Serwer pocztowy", "Open documentation" : "Otwórz dokumentację", "This is used for sending out notifications." : "To jest używane do wysyłania powiadomień", "Send mode" : "Tryb wysyłki", "Encryption" : "Szyfrowanie", "From address" : "Z adresu", "mail" : "poczta", "Authentication method" : "Metoda autentykacji", "Authentication required" : "Wymagana autoryzacja", "Server address" : "Adres Serwera", "Port" : "Port", "Credentials" : "Poświadczenia", "SMTP Username" : "Użytkownik SMTP", "SMTP Password" : "Hasło SMTP", "Store credentials" : "Zapisz poświadczenia", "Test email settings" : "Ustawienia testowej wiadomości", "Send email" : "Wyślij email", "Server-side encryption" : "Szyfrowanie po stronie serwera", "Enable server-side encryption" : "Włącz szyfrowanie po stronie serwera", "Please read carefully before activating server-side encryption: " : "Proszę przeczytać uważnie przed aktywowaniem szyfrowania po stronie serwera:", "Be aware that encryption always increases the file size." : "Należy pamiętać, że szyfrowanie zawsze zwiększa rozmiar pliku.", "This is the final warning: Do you really want to enable encryption?" : "To ostatnie ostrzeżenie: Czy na pewno chcesz włączyć szyfrowanie?", "Enable encryption" : "Włącz szyfrowanie", "No encryption module loaded, please enable an encryption module in the app menu." : "Moduł szyfrowania nie jest załadowany, należy włączyć moduł szyfrowania w menu aplikacji.", "Select default encryption module:" : "Wybierz domyślny moduł szyfrujący:", "Start migration" : "Rozpocznij migrację", "Security & setup warnings" : "Ostrzeżenia bezpieczeństwa i konfiguracji", "PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." : "Wygląda na to, że ustawienia PHP ucinają bloki wklejonych dokumentów. To sprawi, że niektóre wbudowane aplikacje będą niedostępne.", "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Dzieje się tak prawdopodobnie przez cache lub akcelerator taki jak Zend OPcache lub eAccelerator.", "The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "Brak modułu PHP „fileinfo”. Zalecamy włączenie tego modułu, aby uzyskać najlepsze wyniki podczas wykrywania typów MIME.", "System locale can not be set to a one which supports UTF-8." : "Ustawienia regionalne systemu nie można ustawić na jeden, który obsługuje UTF-8.", "This means that there might be problems with certain characters in file names." : "Oznacza to, że mogą być problemy z niektórymi znakami w nazwach plików.", "We strongly suggest installing the required packages on your system to support one of the following locales: %s." : "Zalecamy instalację na Twoim systemie komponentów wymaganych do obsługi języków: %s", "It was not possible to execute the cronjob via CLI. The following technical errors have appeared:" : "Nie było możliwe do wykonania przez cron CLI. Pojawiły się następujące błędy techniczne:", "All checks passed." : "Wszystkie testy przeszły poprawnie.", "Cron" : "Cron", "Last cron job execution: %s." : "Ostatnie wykonanie zadania przez cron: %s.", "Last cron job execution: %s. Something seems wrong." : "Ostatnie wykonanie zadania przez cron: %s. Wydaje się być błędny.", "Cron was not executed yet!" : "Cron nie został jeszcze uruchomiony!", "Execute one task with each page loaded" : "Wykonuj jedno zadanie wraz z każdą wczytaną stroną", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php jest zarejestrowany w serwisie webcron do uruchamiania cron.php raz na 15 minut przez http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Użyj systemowej usługi cron do wywoływania cron.php co 15 minut.", "The cron.php needs to be executed by the system user \"%s\"." : "Cron.php musi być wykonywany przez użytkownika systemu \"%s\".", "Version" : "Wersja", "Sharing" : "Udostępnianie", "Allow apps to use the Share API" : "Zezwalaj aplikacjom na korzystanie z API udostępniania", "Allow users to share via link" : "Pozwól użytkownikom współdzielić przez link", "Allow public uploads" : "Pozwól na publiczne wczytywanie", "Enforce password protection" : "Wymuś zabezpieczenie hasłem", "Set default expiration date" : "Ustaw domyślną datę wygaśnięcia", "Expire after " : "Wygaś po", "days" : "dniach", "Enforce expiration date" : "Wymuś datę wygaśnięcia", "Allow resharing" : "Zezwalaj na ponowne udostępnianie", "Allow sharing with groups" : "Pozwól dzielić się z grupami", "Restrict users to only share with users in their groups" : "Ogranicz użytkowników do współdzielenia wyłącznie pomiędzy użytkownikami swoich grup", "Exclude groups from sharing" : "Wyklucz grupy z udostępniania", "These groups will still be able to receive shares, but not to initiate them." : "Grupy te nadal będą mogli otrzymywać udostępnione udziały, ale nie do ich inicjowania.", "Allow username autocompletion in share dialog. If this is disabled the full username needs to be entered." : "Pozwól użytkownikowi na autouzupełnianie w oknie użytkownika. Jeśli ta opcja jest wyłączona, to pełna nazwa musi być wprowadzona.", "Tips & tricks" : "Porady i wskazówki", "This is particularly recommended when using the desktop client for file synchronisation." : "Jest to szczególnie zalecane w przypadku korzystania z desktopowego klienta do synchronizacji plików.", "How to do backups" : "Jak zrobić kopie zapasowe", "Advanced monitoring" : "Zaawansowane monitorowanie", "Performance tuning" : "Podnoszenie wydajności", "Improving the config.php" : "Udoskonalać się w config.php", "Theming" : "Motyw", "Hardening and security guidance" : "Kierowanie i wzmacnianie bezpieczeństwa", "Developer documentation" : "Dokumentacja dewelopera", "by %s" : "przez %s", "Documentation:" : "Dokumentacja:", "User documentation" : "Dokumentacja użytkownika", "Admin documentation" : "Dokumentacja Administratora", "Visit website" : "Odwiedź stronę", "Report a bug" : "Zgłoś błąd", "Show description …" : "Pokaż opis ...", "Hide description …" : "Ukryj opis ...", "This app has an update available." : "Ta aplikacja ma dostępną aktualizację.", "This app has no minimum Nextcloud version assigned. This will be an error in the future." : "Ta aplikacja nie ma przypisanej minimalnej wersji Nextcloud. W przyszłości będzie to błąd.", "This app has no maximum Nextcloud version assigned. This will be an error in the future." : "Ta aplikacja nie ma przypisanej maksymalnej wersji Nextcloud. W przyszłości będzie to błąd.", "This app cannot be installed because the following dependencies are not fulfilled:" : "Ta aplikacja nie może być zainstalowana, ponieważ nie są spełnione następujące zależności:", "Enable only for specific groups" : "Włącz tylko dla określonych grup", "Common Name" : "Nazwa CN", "Valid until" : "Ważny do", "Issued By" : "Wydany przez", "Valid until %s" : "Ważny do %s", "Import root certificate" : "Importuj główny certyfikat", "Cheers!" : "Pozdrawiam!", "Administrator documentation" : "Dokumentacja Administratora", "Online documentation" : "Dokumentacja Online", "Forum" : "Forum", "Getting help" : "Otrzymać pomoc", "Commercial support" : "Wsparcie komercyjne", "You are using <strong>%s</strong> of <strong>%s</strong>" : "Używasz <strong>%s</strong> z <strong>%s</strong>", "Profile picture" : "Zdjęcie profilu", "Upload new" : "Wczytaj nowe", "Select from Files" : "Wybierz z Plików", "Remove image" : "Usuń zdjęcie", "png or jpg, max. 20 MB" : "png lub jpg, maks. 20 MB", "Picture provided by original account" : "Zdjęcie dostarczone przez oryginalne konto", "Cancel" : "Anuluj", "Choose as profile picture" : "Wybierz zdjęcie profilu", "Full name" : "Pełna nazwa", "No display name set" : "Brak nazwa wyświetlanej", "Email" : "Email", "Your email address" : "Twój adres e-mail", "No email address set" : "Brak adresu email", "For password recovery and notifications" : "W celu odzyskania hasła i powiadomień", "Phone number" : "Numer telefonu", "Your phone number" : "Twój numer telefonu", "Address" : "Adres", "Your postal address" : "Twój kod pocztowy", "Website" : "Strona WWW", "Your website" : "Twoja strona WWW", "Twitter" : "Twitter", "You are member of the following groups:" : "Jesteś członkiem następujących grup:", "Password" : "Hasło", "Current password" : "Bieżące hasło", "New password" : "Nowe hasło", "Change password" : "Zmień hasło", "Language" : "Język", "Help translate" : "Pomóż w tłumaczeniu", "Get the apps to sync your files" : "Pobierz aplikacje żeby synchronizować swoje pliki", "Desktop client" : "Klient na komputer", "Android app" : "Aplikacja Android", "iOS app" : "Aplikacja iOS", "Show First Run Wizard again" : "Uruchom ponownie kreatora pierwszego uruchomienia", "Web, desktop and mobile clients currently logged in to your account." : "Aktualnie zalogowany na swoim koncie z Web, komputerów i mobilnych urządzeń.", "Device" : "Urządzenie", "Last activity" : "Ostatnia aktywność", "Passcodes that give an app or device permissions to access your account." : "Hasła dostępu, które dają uprawnienia aplikacjom lub urządzeniom, do uzyskania dostępu do konta.", "Name" : "Nazwa", "App name" : "Nazwa aplikacji", "Create new app password" : "Utwórz nowe hasło do aplikacji", "Use the credentials below to configure your app or device." : "Skonfiguruj aplikację lub urządzenie, aby skorzystać z poniższego poświadczenia.", "For security reasons this password will only be shown once." : "Ze względów bezpieczeństwa hasło zostanie pokazane tylko raz.", "Username" : "Nazwa użytkownika", "Done" : "Ukończono", "Follow us on Google Plus!" : "Śledź nas na Google Plus!", "Like our facebook page!" : "Polub naszą stronę na Facebook!", "Subscribe to our twitter channel!" : "Zapisz się do naszego kanału na Twitterze!", "Subscribe to our news feed!" : "Zapisz się do naszego kanału informacyjnego!", "Subscribe to our newsletter!" : "Zapisz się do naszego newslettera!", "Show storage location" : "Pokaż miejsce przechowywania", "Show last log in" : "Pokaż ostatni login", "Show user backend" : "Pokaż moduł użytkownika", "Send email to new user" : "Wyślij email do nowego użytkownika", "Show email address" : "Pokaż adres email", "E-Mail" : "E-mail", "Create" : "Utwórz", "Admin Recovery Password" : "Hasło klucza odzyskiwania", "Enter the recovery password in order to recover the users files during password change" : "Wpisz hasło odzyskiwania, aby odzyskać pliki użytkowników podczas zmiany hasła", "Group name" : "Nazwa grupy", "Everyone" : "Wszyscy", "Admins" : "Administratorzy", "Default quota" : "Domyślny udział", "Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Proszę ustawić ograniczenie zasobów (np. \"512 MB\" albo \"12 GB\")", "Other" : "Inne", "Group admin for" : "Grupa admin dla", "Quota" : "Udział", "Storage location" : "Lokalizacja magazynu", "User backend" : "Moduł użytkownika", "Last login" : "Ostatnio zalogowany", "change full name" : "Zmień pełna nazwę", "set new password" : "ustaw nowe hasło", "change email address" : "zmień adres email", "Default" : "Domyślny", "log-level out of allowed range" : "wartość log-level spoza dozwolonego zakresu", "Language changed" : "Zmieniono język", "Admins can't remove themself from the admin group" : "Administratorzy nie mogą usunąć siebie samych z grupy administratorów", "Unable to add user to group %s" : "Nie można dodać użytkownika do grupy %s", "Unable to remove user from group %s" : "Nie można usunąć użytkownika z grupy %s", "Are you really sure you want add \"{domain}\" as trusted domain?" : "Czy jesteś pewien/pewna że chcesz dodać \"{domain}\" jako zaufaną domenę?", "Please wait...." : "Proszę czekać...", "iPhone" : "iPhone", "add group" : "dodaj grupę", "Everything (fatal issues, errors, warnings, info, debug)" : "Wszystko (Informacje, ostrzeżenia, błędy i poważne problemy, debug)", "Info, warnings, errors and fatal issues" : "Informacje, ostrzeżenia, błędy i poważne problemy", "Warnings, errors and fatal issues" : "Ostrzeżenia, błędy i poważne problemy", "Errors and fatal issues" : "Błędy i poważne problemy", "Fatal issues only" : "Tylko poważne problemy", "Log" : "Logi", "What to log" : "Jakie logi", "Download logfile" : "Pobierz plik log", "More" : "Więcej", "Less" : "Mniej", "The logfile is bigger than 100 MB. Downloading it may take some time!" : "Plik log jest większy niż 100MB. Ściąganie może trochę potrwać!", "Allow users to send mail notification for shared files" : "Zezwól użytkownikom na wysyłanie powiadomień email dla udostępnionych plików", "Allow users to send mail notification for shared files to other users" : "Zezwalaj użytkownikom na wysyłanie powiadomień pocztą dla współdzielonych plików do innych użytkowników", "Uninstall App" : "Odinstaluj aplikację", "Enable experimental apps" : "Włącz eksperymentalne aplikacje", "Hey there,<br><br>just letting you know that you now have an %s account.<br><br>Your username: %s<br>Access it: <a href=\"%s\">%s</a><br><br>" : "Witaj,<br><br>informujemy, że teraz masz konto na %s .<br><br>Twoja nazwa użytkownika: %s<br>Dostęp pod adresem: <a href=\"%s\">%s</a><br><br>", "Hey there,\n\njust letting you know that you now have an %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Witaj,\n\ninformujemy, że teraz masz konto na %s .\n\nTwoja nazwa użytkownika:: %s\nDostęp pod adresem: %s\n\n", "Add Group" : "Dodaj grupę", "Group" : "Grupa", "Default Quota" : "Domyślny udział", "Full Name" : "Pełna nazwa", "Group Admin for" : "Grupa Admin dla", "Storage Location" : "Lokalizacja magazynu", "User Backend" : "Moduł użytkownika", "Last Login" : "Ostatnio zalogowany" }, "nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);");
jbicha/server
settings/l10n/pl.js
JavaScript
agpl-3.0
24,071
/* * Copyright (C) 2012 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import I18n from 'i18n!calendar' import $ from 'jquery' import moment from 'moment' import natcompare from '../util/natcompare' import commonEventFactory from './commonEventFactory' import ValidatedFormView from '../views/ValidatedFormView' import SisValidationHelper from '../util/SisValidationHelper' import editAssignmentTemplate from 'jst/calendar/editAssignment' import editAssignmentOverrideTemplate from 'jst/calendar/editAssignmentOverride' import wrapper from 'jst/EmptyDialogFormWrapper' import genericSelectOptionsTemplate from 'jst/calendar/genericSelectOptions' import datePickerFormat from 'jsx/shared/helpers/datePickerFormat' import {showFlashAlert} from 'jsx/shared/FlashAlert' import withinMomentDates from 'jsx/shared/helpers/momentDateHelper' import 'jquery.instructure_date_and_time' import 'jquery.instructure_forms' import 'jquery.instructure_misc_helpers' import './fcMomentHandlebarsHelpers' export default class EditAssignmentDetailsRewrite extends ValidatedFormView { initialize(selector, event, contextChangeCB, closeCB) { this.event = event this.contextChangeCB = contextChangeCB this.closeCB = closeCB super.initialize({ title: this.event.title, contexts: this.event.possibleContexts(), date: this.event.startDate(), postToSISEnabled: ENV.POST_TO_SIS, postToSISName: ENV.SIS_NAME, postToSIS: this.event.eventType === 'assignment' ? this.event.assignment.post_to_sis : undefined, datePickerFormat: this.event.allDay ? 'medium_with_weekday' : 'full_with_weekday' }) this.currentContextInfo = null if (this.event.override) { this.template = editAssignmentOverrideTemplate } $(selector).append(this.render().el) this.setupTimeAndDatePickers() this.$el.find('select.context_id').triggerHandler('change', false) if (this.model == null) { this.model = this.generateNewEvent() } if (!this.event.isNewEvent()) { this.$el.find('.context_select').hide() this.$el.attr('method', 'PUT') return this.$el.attr( 'action', $.replaceTags(this.event.contextInfo.assignment_url, 'id', this.event.object.id) ) } } setContext(newContext) { this.$el .find('select.context_id') .val(newContext) .triggerHandler('change', false) } contextInfoForCode(code) { return this.event.possibleContexts().find(context => context.asset_string === code) } activate() { this.$el.find('select.context_id').change() if (this.event.assignment && this.event.assignment.assignment_group_id) { return this.$el .find('.assignment_group_select .assignment_group') .val(this.event.assignment.assignment_group_id) } } moreOptions(jsEvent) { jsEvent.preventDefault() const pieces = $(jsEvent.target) .attr('href') .split('#') const data = this.$el.getFormData({object_name: 'assignment'}) const params = {} if (data.name) { params.title = data.name } if (data.due_at && this.$el.find('.datetime_field').data('unfudged-date')) { params.due_at = this.$el .find('.datetime_field') .data('unfudged-date') .toISOString() } if (data.assignment_group_id) { params.assignment_group_id = data.assignment_group_id } params.return_to = window.location.href pieces[0] += `?${$.param(params)}` return (window.location.href = pieces.join('#')) } contextChange(jsEvent, propagate) { if (this.ignoreContextChange) return const context = $(jsEvent.target).val() this.currentContextInfo = this.contextInfoForCode(context) this.event.contextInfo = this.currentContextInfo if (this.currentContextInfo == null) return if (propagate !== false) this.contextChangeCB(context) // TODO: support adding a new assignment group from this select box const assignmentGroupsSelectOptionsInfo = { collection: this.currentContextInfo.assignment_groups.sort(natcompare.byKey('name')) } this.$el .find('.assignment_group') .html(genericSelectOptionsTemplate(assignmentGroupsSelectOptionsInfo)) // Update the edit and more options links with the new context this.$el.attr('action', this.currentContextInfo.create_assignment_url) const moreOptionsUrl = this.event.assignment ? `${this.event.assignment.html_url}/edit` : this.currentContextInfo.new_assignment_url return this.$el.find('.more_options_link').attr('href', moreOptionsUrl) } generateNewEvent() { return commonEventFactory({}, []) } submitAssignment(e) { e.preventDefault() const data = this.getFormData() this.disableWhileLoadingOpts = {buttons: ['.save_assignment']} if (data.assignment != null) { return this.submitRegularAssignment(e, data.assignment) } else { return this.submitOverride(e, data.assignment_override) } } unfudgedDate(date) { const unfudged = $.unfudgeDateForProfileTimezone(date) if (unfudged) { return unfudged.toISOString() } else { return '' } } getFormData() { const data = super.getFormData(...arguments) if (data.assignment != null) { data.assignment.due_at = this.unfudgedDate(data.assignment.due_at) } else { data.assignment_override.due_at = this.unfudgedDate(data.assignment_override.due_at) } return data } submitRegularAssignment(event, data) { data.due_at = this.unfudgedDate(data.due_at) if (this.event.isNewEvent()) { data.context_code = $(this.$el) .find('.context_id') .val() this.model = commonEventFactory(data, this.event.possibleContexts()) return this.submit(event) } else { this.event.title = data.title this.event.start = data.due_at // fudged this.model = this.event return this.submit(event) } } submitOverride(event, data) { this.event.start = data.due_at // fudged data.due_at = this.unfudgedDate(data.due_at) this.model = this.event return this.submit(event) } onSaveSuccess() { return this.closeCB() } onSaveFail(xhr) { let resp if ((resp = JSON.parse(xhr.responseText))) { showFlashAlert({message: resp.error, err: null, type: 'error'}) } this.closeCB() this.disableWhileLoadingOpts = {} return super.onSaveFail(xhr) } validateBeforeSave(data, errors) { if (data.assignment != null) { data = data.assignment errors = this._validateTitle(data, errors) } else { data = data.assignment_override } errors = this._validateDueDate(data, errors) return errors } _validateTitle(data, errors) { const post_to_sis = data.post_to_sis === '1' let max_name_length = 256 const max_name_length_required = ENV.MAX_NAME_LENGTH_REQUIRED_FOR_ACCOUNT if (post_to_sis && max_name_length_required) { max_name_length = ENV.MAX_NAME_LENGTH } const validationHelper = new SisValidationHelper({ postToSIS: post_to_sis, maxNameLength: max_name_length, name: data.name, maxNameLengthRequired: max_name_length_required }) if (!data.name || $.trim(data.name.toString()).length === 0) { errors['assignment[name]'] = [{message: I18n.t('name_is_required', 'Name is required!')}] } else if (validationHelper.nameTooLong()) { errors['assignment[name]'] = [ { message: I18n.t('Name is too long, must be under %{length} characters', { length: max_name_length + 1 }) } ] } return errors } _validateDueDate(data, errors) { let dueDate if ( this.event.eventType === 'assignment' && this.event.assignment.unlock_at && this.event.assignment.lock_at ) { const startDate = moment(this.event.assignment.unlock_at) const endDate = moment(this.event.assignment.lock_at) dueDate = moment(this.event.start) if (!withinMomentDates(dueDate, startDate, endDate)) { const rangeErrorMessage = I18n.t( 'Assignment has a locked date. Due date cannot be set outside of locked date range.' ) errors.lock_range = [{message: rangeErrorMessage}] showFlashAlert({ message: rangeErrorMessage, err: null, type: 'error' }) } } const post_to_sis = data.post_to_sis === '1' if (!post_to_sis) { return errors } const validationHelper = new SisValidationHelper({ postToSIS: post_to_sis, dueDateRequired: ENV.DUE_DATE_REQUIRED_FOR_ACCOUNT, dueDate: data.due_at }) const error_tag = data.name != null ? 'assignment[due_at]' : 'assignment_override[due_at]' if (validationHelper.dueDateMissing()) { errors[error_tag] = [{message: I18n.t('Due Date is required!')}] } return errors } setupTimeAndDatePickers() { const $field = this.$el.find('.datetime_field') return $field.datetime_field({ datepicker: { dateFormat: datePickerFormat( this.event.allDay ? I18n.t('#date.formats.medium_with_weekday') : I18n.t('#date.formats.full_with_weekday') ) } }) } } EditAssignmentDetailsRewrite.prototype.defaults = { width: 440, height: 384 } EditAssignmentDetailsRewrite.prototype.events = { ...EditAssignmentDetailsRewrite.prototype.events, 'click .save_assignment': 'submitAssignment', 'click .more_options_link': 'moreOptions', 'change .context_id': 'contextChange' } EditAssignmentDetailsRewrite.prototype.template = editAssignmentTemplate EditAssignmentDetailsRewrite.prototype.wrapper = wrapper EditAssignmentDetailsRewrite.optionProperty('assignmentGroup')
djbender/canvas-lms
app/coffeescripts/calendar/EditAssignmentDetails.js
JavaScript
agpl-3.0
10,456
/* * Ext JS Library 2.3.0 * Copyright(c) 2006-2009, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.form.Label * @extends Ext.BoxComponent * Basic Label field. * @constructor * Creates a new Label * @param {Ext.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component. */ Ext.form.Label = Ext.extend(Ext.BoxComponent, { /** * @cfg {String} text The plain text to display within the label (defaults to ''). If you need to include HTML * tags within the label's innerHTML, use the {@link #html} config instead. */ /** * @cfg {String} forId The id of the input element to which this label will be bound via the standard HTML 'for' * attribute. If not specified, the attribute will not be added to the label. */ /** * @cfg {String} html An HTML fragment that will be used as the label's innerHTML (defaults to ''). * Note that if {@link #text} is specified it will take precedence and this value will be ignored. */ // private onRender : function(ct, position){ if(!this.el){ this.el = document.createElement('label'); this.el.id = this.getId(); this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || ''); if(this.forId){ this.el.setAttribute('for', this.forId); } } Ext.form.Label.superclass.onRender.call(this, ct, position); }, /** * Updates the label's innerHTML with the specified string. * @param {String} text The new label text * @param {Boolean} encode (optional) False to skip HTML-encoding the text when rendering it * to the label (defaults to true which encodes the value). This might be useful if you want to include * tags in the label's innerHTML rather than rendering them as string literals per the default logic. * @return {Label} this */ setText: function(t, encode){ var e = encode === false; this[!e ? 'text' : 'html'] = t; delete this[e ? 'text' : 'html']; if(this.rendered){ this.el.dom.innerHTML = encode !== false ? Ext.util.Format.htmlEncode(t) : t; } return this; } }); Ext.reg('label', Ext.form.Label);
xwiki-labs/sankoreorg
web/src/main/webapp/skins/curriki20/extjs/source/widgets/form/Label.js
JavaScript
lgpl-2.1
2,602
/* * This file is part of Cockpit. * * Copyright (C) 2015 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ import { FIXTURE_BASIC } from "./fixture-basic.js"; import { FIXTURE_LARGE } from "./fixture-large.js"; import QUnit from "qunit-tests"; var angular = require("angular"); require("./kube-client"); require("./kube-client-cockpit"); require("./kube-client-mock"); (function() { /* Filled in with a function */ var inject; var module = angular.module("kubeClient.tests", [ "kubeClient", "kubeClient.mock" ]) .config([ 'KubeWatchProvider', 'KubeRequestProvider', function(KubeWatchProvider, KubeRequestProvider) { KubeWatchProvider.KubeWatchFactory = "MockKubeWatch"; KubeRequestProvider.KubeRequestFactory = "MockKubeRequest"; } ]); function injectLoadFixtures(fixtures) { inject([ "kubeLoader", "MockKubeData", function(loader, data) { if (fixtures) data.load(fixtures); loader.reset(true); } ]); } QUnit.test("loader load", function (assert) { var done = assert.async(); assert.expect(7); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", function(loader) { var promise = loader.load("nodes"); assert.ok(!!promise, "promise returned"); assert.equal(typeof promise.then, "function", "promise has then"); assert.equal(typeof promise.catch, "function", "promise has catch"); assert.equal(typeof promise.finally, "function", "promise has finally"); return promise.then(function(items) { assert.ok(angular.isArray(items), "got items array"); assert.equal(items.length, 1, "one node"); assert.equal(items[0].metadata.name, "127.0.0.1", "localhost node"); done(); }); }]); }); QUnit.test("loader load encoding", function (assert) { var done = assert.async(); assert.expect(2); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeSelect", "$q", function(loader, select, $q) { assert.equal(select().kind("Encoded").length, 0); var defer = $q.defer(); var x = loader.listen(function() { assert.equal(select().kind("Image").length, 1); x.cancel(); defer.resolve(); done(); }); loader.handle([{ "apiVersion": "v1", "kind": "Image", "metadata": { "name": "encoded:one", "resourceVersion": 10000, "uid": "11768037-ab8a-11e4-9a7c-100001001", "namespace": "default", "selfLink": "/oapi/v1/images/encoded%3Aone", }, }, { "apiVersion": "v1", "kind": "Image", "metadata": { "name": "encoded:one", "resourceVersion": 10000, "uid": "11768037-ab8a-11e4-9a7c-100001001", "namespace": "default", }, }, { "apiVersion": "v1", "kind": "Image", "metadata": { "name": "encoded:one", "resourceVersion": 10000, "uid": "11768037-ab8a-11e4-9a7c-100001001", "namespace": "default", "selfLink": "/oapi/v1/images/encoded:one", }, }]); return defer.promise; }]); }); QUnit.test("loader load fail", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", function(loader) { var promise = loader.load("nonexistant"); return promise.then(function(data) { assert.ok(!true, "successfully loaded"); }, function(response) { assert.equal(response.code, 404, "not found"); assert.equal(response.message, "Not found here", "not found message"); assert.ok(true, "not sucessfully loaded"); done(); }); }]); }); QUnit.test("loader watch", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", function(loader) { return loader.watch("nodes").then(function(response) { assert.ok("/api/v1/nodes/127.0.0.1" in loader.objects, "found node"); var node = loader.objects["/api/v1/nodes/127.0.0.1"]; assert.equal(node.metadata.name, "127.0.0.1", "localhost node"); assert.equal(typeof node.spec.capacity, "object", "node has resources"); done(); }); }]); }); QUnit.test("list nodes", function (assert) { var done = assert.async(); assert.expect(6); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeSelect", function(loader, select) { return loader.watch("nodes").then(function() { var nodes = select().kind("Node"); assert.ok("/api/v1/nodes/127.0.0.1" in nodes, "found node"); var node = nodes["/api/v1/nodes/127.0.0.1"]; assert.equal(node.metadata.name, "127.0.0.1", "localhost node"); assert.equal(typeof node.spec.capacity, "object", "node has resources"); /* The same thing should be returned */ var nodes1 = select().kind("Node"); assert.strictEqual(nodes, nodes1, "same object returned"); /* Key should not be encoded as JSON */ var parsed = JSON.parse(JSON.stringify(node)); assert.ok(!("key" in parsed), "key should not be serialized"); assert.strictEqual(parsed.key, undefined, "key not be undefined after serialize"); done(); }); }]); }); QUnit.test("list pods", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeSelect", function(loader, select) { return loader.watch("pods").then(function() { var pods = select().kind("Pod"); assert.equal(pods.length, 3, "found pods"); var pod = pods["/api/v1/namespaces/default/pods/apache"]; assert.equal(typeof pod, "object", "found pod"); assert.equal(pod.metadata.labels.name, "apache", "pod has label"); done(); }); }]); }); QUnit.test("set namespace", function (assert) { var done = assert.async(); assert.expect(7); injectLoadFixtures(FIXTURE_BASIC); inject(["$q", "kubeLoader", "kubeSelect", function($q, loader, select) { return loader.watch("pods").then(function() { var pods = select().kind("Pod"); assert.equal(pods.length, 3, "number of pods"); assert.strictEqual(loader.limits.namespace, null, "namespace is null"); loader.limit({ namespace: "other" }); assert.strictEqual(loader.limits.namespace, "other", "namespace is other"); pods = select().kind("Pod"); assert.equal(pods.length, 1, "pods from namespace other"); assert.ok("/api/v1/namespaces/other/pods/apache" in pods, "other pod"); loader.limit({ namespace: null }); assert.strictEqual(loader.limits.namespace, null, "namespace is null again"); var defer = $q.defer(); var listened = false; var x = loader.listen(function() { if (listened) { pods = select().kind("Pod"); assert.equal(pods.length, 3, "all pods back"); x.cancel(); defer.resolve(); done(); } listened = true; }); return defer.promise; }); }]); }); QUnit.test("add pod", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(FIXTURE_BASIC); inject(["$q", "kubeLoader", "kubeSelect", "MockKubeData", function($q, loader, select, data) { return loader.watch("pods").then(function() { var pods = select().kind("Pod"); assert.equal(pods.length, 3, "number of pods"); assert.equal(pods["/api/v1/namespaces/default/pods/apache"].metadata.labels.name, "apache", "pod has label"); var defer = $q.defer(); var x = loader.listen(function() { var pods = select().kind("Pod"); if (pods.length === 4) { assert.equal(pods["/api/v1/namespaces/default/pods/aardvark"].metadata.labels.name, "aardvark", "new pod present in items"); x.cancel(); defer.resolve(); done(); } }); data.update("namespaces/default/pods/aardvark", { "kind": "Pod", "metadata": { "name": "aardvark", "uid": "22768037-ab8a-11e4-9a7c-080027300d85", "namespace": "default", "labels": { "name": "aardvark" }, }, "spec": { "volumes": null, "containers": [ ], "imagePullPolicy": "IfNotPresent" } }); return defer.promise; }); }]); }); QUnit.test("update pod", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(FIXTURE_BASIC); inject(["$q", "kubeLoader", "kubeSelect", "MockKubeData", function($q, loader, select, data) { return loader.watch("pods").then(function() { var pods = select().kind("Pod"); assert.equal(pods.length, 3, "number of pods"); assert.equal(pods["/api/v1/namespaces/default/pods/apache"].metadata.labels.name, "apache", "pod has label"); var defer = $q.defer(); var listened = false; var x = loader.listen(function() { var pods; if (listened) { pods = select().kind("Pod"); assert.equal(pods["/api/v1/namespaces/default/pods/apache"].metadata.labels.name, "apachepooo", "pod has changed"); x.cancel(); defer.resolve(); done(); } listened = true; }); data.update("namespaces/default/pods/apache", { "kind": "Pod", "metadata": { "name": "apache", "uid": "11768037-ab8a-11e4-9a7c-080027300d85", "namespace": "default", "labels": { "name": "apachepooo" }, } }); return defer.promise; }); }]); }); QUnit.test("remove pod", function (assert) { var done = assert.async(); assert.expect(5); injectLoadFixtures(FIXTURE_BASIC); inject(["$q", "kubeLoader", "kubeSelect", "MockKubeData", function($q, loader, select, data) { return loader.watch("pods").then(function() { var pods = select().kind("Pod"); assert.equal(pods.length, 3, "number of pods"); assert.equal(pods["/api/v1/namespaces/default/pods/apache"].metadata.labels.name, "apache", "pod has label"); var defer = $q.defer(); var listened = false; var x = loader.listen(function() { var pods; if (listened) { pods = select().kind("Pod"); assert.equal(pods.length, 2, "removed a pod"); assert.strictEqual(pods["/api/v1/namespaces/default/pods/apache"], undefined, "removed pod"); assert.equal(pods["/api/v1/namespaces/default/pods/database-1"].metadata.labels.name, "wordpressreplica", "other pod"); x.cancel(); defer.resolve(); done(); } listened = true; }); data.update("namespaces/default/pods/apache", null); return defer.promise; }); }]); }); QUnit.test("list services", function (assert) { var done = assert.async(); assert.expect(4); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeSelect", function(loader, select) { return loader.watch("services").then(function() { var services = select().kind("Service"); var x; var svc = null; for (x in services) { svc = services[x]; break; } assert.ok(!!svc, "got a service"); assert.equal(services.length, 2, "number of services"); assert.equal(svc.metadata.name, "kubernetes", "service id"); assert.equal(svc.spec.selector.component, "apiserver", "service has label"); done(); }); }]); }); var CREATE_ITEMS = [ { "kind": "Pod", "apiVersion": "v1", "metadata": { "name": "pod1", "uid": "d072fb85-f70e-11e4-b829-10c37bdb8410", "resourceVersion": "634203", "labels": { "name": "pod1" }, }, "spec": { "volumes": null, "containers": [{ "name": "database", "image": "mysql", "ports": [{ "containerPort": 3306, "protocol": "TCP" }], }], "nodeName": "127.0.0.1" } }, { "kind": "Node", "apiVersion": "v1", "metadata": { "name": "node1", "uid": "6e51438e-d161-11e4-acbc-10c37bdb8410", "resourceVersion": "634539", }, "spec": { "externalID": "172.2.3.1" } } ]; QUnit.test("create", function (assert) { var done = assert.async(); assert.expect(2); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { loader.watch("pods"); loader.watch("nodes"); loader.watch("namespaces"); return methods.create(CREATE_ITEMS, "namespace1").then(function() { assert.equal(loader.objects["/api/v1/namespaces/namespace1/pods/pod1"].metadata.name, "pod1", "pod object"); assert.equal(loader.objects["/api/v1/nodes/node1"].metadata.name, "node1", "node object"); done(); }); }]); }); QUnit.test("create namespace exists", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { loader.watch("pods"); loader.watch("nodes"); loader.watch("namespaces"); var NAMESPACE_ITEM = { "apiVersion" : "v1", "kind" : "Namespace", "metadata" : { "name": "namespace1" } }; return methods.create(NAMESPACE_ITEM).then(function() { assert.ok("/api/v1/namespaces/namespace1" in loader.objects, "namespace created"); return methods.create(CREATE_ITEMS, "namespace1").then(function() { assert.ok("/api/v1/namespaces/namespace1/pods/pod1" in loader.objects, "pod created"); assert.ok("/api/v1/nodes/node1" in loader.objects, "node created"); done(); }); }); }]); }); QUnit.test("create namespace default", function (assert) { var done = assert.async(); assert.expect(2); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { loader.watch("pods"); loader.watch("nodes"); loader.watch("namespaces"); return methods.create(CREATE_ITEMS).then(function() { assert.equal(loader.objects["/api/v1/namespaces/default/pods/pod1"].metadata.name, "pod1", "pod created"); assert.equal(loader.objects["/api/v1/nodes/node1"].metadata.name, "node1", "node created"); done(); }); }]); }); QUnit.test("create object exists", function (assert) { var done = assert.async(); assert.expect(1); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { loader.watch("pods"); loader.watch("nodes"); loader.watch("namespaces"); var items = CREATE_ITEMS.slice(); items.push(items[0]); return methods.create(items).then(function(response) { assert.equal(response, false, "should have failed"); done(); }, function(response) { assert.equal(response.code, 409, "http already exists"); done(); }); }]); }); QUnit.test("delete pod", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { var watch = loader.watch("pods"); return methods.create(CREATE_ITEMS, "namespace2").then(function() { assert.ok("/api/v1/namespaces/namespace2/pods/pod1" in loader.objects, "pod created"); return methods.delete("/api/v1/namespaces/namespace2/pods/pod1").then(function() { assert.ok(true, "remove succeeded"); return watch.finally(function() { assert.ok(!("/api/v1/namespaces/namespace2/pods/pod1" in loader.objects), "pod was removed"); done(); }); }); }); }]); }); QUnit.test("patch pod", function (assert) { var done = assert.async(); assert.expect(4); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { var watch = loader.watch("pods"); var path = "/api/v1/namespaces/namespace2/pods/pod1"; return methods.create(CREATE_ITEMS, "namespace2").then(function() { assert.ok(path in loader.objects, "pod created"); return methods.patch(path, { "extra": "blah" }).then(function() { assert.ok(true, "patch succeeded"); return methods.patch(loader.objects[path], { "second": "test" }).then(function() { return watch.finally(function() { var pod = loader.objects[path]; assert.equal(pod.extra, "blah", "pod has changed"); assert.equal(pod.second, "test", "pod changed by own object"); done(); }); }); }); }); }]); }); QUnit.test("post", function (assert) { var done = assert.async(); assert.expect(1); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { return methods.post("/api/v1/namespaces/namespace1/pods", CREATE_ITEMS[0]).then(function(response) { assert.equal(response.metadata.name, "pod1", "pod object"); done(); }); }]); }); QUnit.test("post fail", function (assert) { var done = assert.async(); assert.expect(1); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { return methods.post("/api/v1/nodes", FIXTURE_BASIC["nodes/127.0.0.1"]).then(function() { assert.ok(false, "shouldn't succeed"); }, function(response) { assert.deepEqual(response, { "code": 409, "message": "Already exists" }, "got failure code"); done(); }); }]); }); QUnit.test("put", function (assert) { var done = assert.async(); assert.expect(1); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeMethods", function(loader, methods) { var node = { "kind": "Node", "metadata": { "name": "127.0.0.1", labels: { "test": "value" } } }; return methods.put("/api/v1/nodes/127.0.0.1", node).then(function(response) { assert.deepEqual(response.metadata.labels, { "test": "value" }, "put returned object"); done(); }); }]); }); QUnit.test("check resource ok", function (assert) { var done = assert.async(); assert.expect(0); injectLoadFixtures(null); inject(["kubeMethods", function(methods) { var data = { kind: "Blah", metadata: { name: "test" } }; done(); return methods.check(data); }]); }); QUnit.test("check resource name empty", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(null); inject(["kubeMethods", function(methods) { var data = { kind: "Blah", metadata: { name: "" } }; return methods.check(data).catch(function(ex) { assert.ok(angular.isArray(ex), "threw array of failures"); assert.equal(ex.length, 1, "number of errors"); assert.ok(ex[0] instanceof Error, "threw an error"); done(); }); }]); }); QUnit.test("check resource name missing", function (assert) { var done = assert.async(); assert.expect(1); injectLoadFixtures(null); inject(["kubeMethods", function(methods) { var data = { kind: "Blah", metadata: { } }; return methods.check(data).then(function() { assert.ok(true, "passed check"); done(); }, null); }]); }); QUnit.test("check resource name namespace bad", function (assert) { var done = assert.async(); assert.expect(6); injectLoadFixtures(null); inject(["kubeMethods", function(methods) { var data = { kind: "Blah", metadata: { name: "a#a", namespace: "" } }; var targets = { "metadata.name": "#name", "metadata.namespace": "#namespace" }; return methods.check(data, targets).catch(function(ex) { assert.ok(angular.isArray(ex), "threw array of failures"); assert.equal(ex.length, 2, "number of errors"); assert.ok(ex[0] instanceof Error, "threw an error"); assert.equal(ex[0].target, "#name", "correct name target"); assert.ok(ex[1] instanceof Error, "threw an error"); assert.equal(ex[1].target, "#namespace", "correct name target"); done(); }); }]); }); QUnit.test("check resource namespace bad", function (assert) { var done = assert.async(); assert.expect(4); injectLoadFixtures(null); inject(["kubeMethods", function(methods) { var data = { kind: "Blah", metadata: { name: "aa", namespace: "" } }; var targets = { "metadata.name": "#name", "metadata.namespace": "#namespace" }; return methods.check(data, targets).catch(function(ex) { assert.ok(angular.isArray(ex), "threw array of failures"); assert.equal(ex.length, 1, "number of errors"); assert.ok(ex[0] instanceof Error, "threw an error"); assert.equal(ex[0].target, "#namespace", "correct name target"); done(); }); }]); }); QUnit.test("lookup uid", function (assert) { var done = assert.async(); assert.expect(3); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeSelect", function(loader, select) { return loader.watch("pods").then(function() { /* Get the item */ var item = select().kind("Pod") .one(); var uid = item.metadata.uid; assert.ok(uid, "Have uid"); var by_uid_item = select().uid(uid) .one(); assert.strictEqual(item, by_uid_item, "load uid"); /* Shouldn't match */ item = select().uid("bad") .one(); assert.strictEqual(item, null, "mismatch uid"); done(); }); }]); }); QUnit.test("lookup host", function (assert) { var done = assert.async(); assert.expect(2); injectLoadFixtures(FIXTURE_BASIC); inject(["kubeLoader", "kubeSelect", function(loader, select) { return loader.watch("pods").then(function() { /* Get the item */ var item = select().host("127.0.0.1") .one(); assert.deepEqual(item.metadata.selfLink, "/api/v1/namespaces/default/pods/database-1", "correct pod"); /* Shouldn't match */ item = select().host("127.0.0.2") .one(); assert.strictEqual(item, null, "mismatch host"); done(); }); }]); }); QUnit.test("lookup", function (assert) { var done = assert.async(); assert.expect(6); injectLoadFixtures(FIXTURE_LARGE); inject(["kubeLoader", "kubeSelect", function(loader, select) { var expected = { "apiVersion": "v1", "kind": "ReplicationController", "metadata": { "labels": { "example": "mock", "name": "3controller" }, "name": "3controller", "resourceVersion": 10000, "uid": "11768037-ab8a-11e4-9a7c-100001001", "namespace": "default", "selfLink": "/api/v1/namespaces/default/replicationcontrollers/3controller", }, "spec": { "replicas": 1, "selector": { "factor3": "yes" } } }; return loader.watch("replicationcontrollers").then(function() { /* Get the item */ var item = select().kind("ReplicationController") .name("3controller") .namespace("default") .one(); assert.deepEqual(item, expected, "correct item"); /* The same item, without namespace */ item = select().kind("ReplicationController") .name("3controller") .one(); assert.deepEqual(item, expected, "selected without namespace"); /* Any replication controller */ item = select().kind("ReplicationController") .one(); assert.equal(item.kind, "ReplicationController", "any replication controller"); /* Shouldn't match */ item = select().kind("BadKind") .name("3controller") .namespace("default") .one(); assert.strictEqual(item, null, "mismatch kind"); item = select().kind("ReplicationController") .name("badcontroller") .namespace("default") .one(); assert.strictEqual(item, null, "mismatch name"); item = select().kind("ReplicationController") .name("3controller") .namespace("baddefault") .one(); assert.strictEqual(item, null, "mismatch namespace"); done(); }); }]); }); QUnit.test("select", function (assert) { var done = assert.async(); assert.expect(12); injectLoadFixtures(FIXTURE_LARGE); inject(["kubeLoader", "kubeSelect", function(loader, select) { return loader.watch("pods").then(function() { var image = { kind: "Image" }; /* same thing twice */ var first = select(image); var second = select(image); assert.strictEqual(first, second, "identical for single object"); /* null thing twice */ first = select(null); second = select(null); assert.strictEqual(first, second, "identical for null object"); /* Select everything odd, 500 pods */ var results = select().namespace("default") .label({ "type": "odd" }); assert.equal(results.length, 500, "correct amount"); /* The same thing should be returned */ var results1 = select().namespace("default") .label({ "type": "odd" }); assert.strictEqual(results, results1, "same object returned"); /* Select everything odd, but wrong namespace, no pods */ results = select().namespace("other") .label({ "type": "odd" }); assert.equal(results.length, 0, "other namespace no pods"); /* The same ones selected even when a second (present) label */ results = select().namespace("default") .label({ "type": "odd", "tag": "silly" }); assert.equal(results.length, 500, "with additional label"); /* Nothing selected when additional invalid field */ results = select().namespace("default") .label({ "type": "odd", "tag": "billy" }); assert.equal(results.length, 0, "no objects"); /* Limit by kind */ results = select().kind("Pod") .namespace("default") .label({ "type": "odd" }); assert.equal(results.length, 500, "by kind"); /* Limit by invalid kind */ results = select().kind("Ood") .namespace("default") .label({ "type": "odd" }); assert.equal(results.length, 0, "nothing for invalid kind"); /* Everything selected when no selector */ results = select().namespace("default"); assert.equal(results.length, 1000, "all pods"); /* Nothing selected when bad namespace */ results = select().namespace("bad"); assert.equal(results.length, 0, "bad namespace no objects"); /* Nothing selected when empty selector */ results = select().label({ }); assert.equal(results.length, 0, "nothing selected"); done(); }); }]); }); angular.module('exceptionOverride', []).factory('$exceptionHandler', function() { return function(exception, cause) { exception.message += ' (caused by "' + cause + '")'; throw exception; }; }); module.run([ '$injector', function($injector) { inject = function inject(func) { return $injector.invoke(func); }; QUnit.start(); } ]); angular.bootstrap(document, ['kubeClient.tests']); }());
andreasn/cockpit
pkg/kubernetes/scripts/test-kube-client.js
JavaScript
lgpl-2.1
34,267
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of EventTarget as defined by W3C DOM 2/3. * * @see ../demos/eventtarget.html */ /** * Namespace for events */ goog.provide('goog.events.EventTarget'); goog.require('goog.Disposable'); goog.require('goog.events'); /** * This implements the EventTarget interface as defined by W3C DOM 2/3. The * main difference from the spec is that the this does not know about event * propagation and therefore the flag whether to use bubbling or capturing is * not used. * * Another difference is that event objects do not really have to implement * the Event interface. An object is treated as an event object if it has a * type property. * * It also allows you to pass a string instead of an event object and in that * case an event like object is created with the type set to the string value. * * Unless propagation is stopped, events dispatched by an EventTarget bubble * to its parent event target, returned by <code>getParentEventTarget</code>. * To set the parent event target, call <code>setParentEventTarget</code> or * override <code>getParentEventTarget</code> in a subclass. Subclasses that * don't support changing the parent event target should override the setter * to throw an error. * * Example usage: * <pre> * var et = new goog.events.EventTarget; * function f(e) { * alert("Type: " + e.type + "\nTarget: " + e.target); * } * et.addEventListener("foo", f); * ... * et.dispatchEvent({type: "foo"}); // will call f * // or et.dispatchEvent("foo"); * ... * et.removeEventListener("foo", f); * * // You can also use the EventHandler interface: * var eh = { * handleEvent: function(e) { * ... * } * }; * et.addEventListener("bar", eh); * </pre> * * @constructor * @extends {goog.Disposable} */ goog.events.EventTarget = function() { goog.Disposable.call(this); }; goog.inherits(goog.events.EventTarget, goog.Disposable); /** * Used to tell if an event is a real event in goog.events.listen() so we don't * get listen() calling addEventListener() and vice-versa. * @type {boolean} * @private */ goog.events.EventTarget.prototype.customEvent_ = true; /** * Parent event target, used during event bubbling. * @type {goog.events.EventTarget?} * @private */ goog.events.EventTarget.prototype.parentEventTarget_ = null; /** * Returns the parent of this event target to use for bubbling. * * @return {goog.events.EventTarget} The parent EventTarget or null if there * is no parent. */ goog.events.EventTarget.prototype.getParentEventTarget = function() { return this.parentEventTarget_; }; /** * Sets the parent of this event target to use for bubbling. * * @param {goog.events.EventTarget?} parent Parent EventTarget (null if none). */ goog.events.EventTarget.prototype.setParentEventTarget = function(parent) { this.parentEventTarget_ = parent; }; /** * Adds an event listener to the event target. The same handler can only be * added once per the type. Even if you add the same handler multiple times * using the same type then it will only be called once when the event is * dispatched. * * Supported for legacy but use goog.events.listen(src, type, handler) instead. * * @param {string} type The type of the event to listen for. * @param {Function|Object} handler The function to handle the event. The * handler can also be an object that implements the handleEvent method * which takes the event object as argument. * @param {boolean=} opt_capture In DOM-compliant browsers, this determines * whether the listener is fired during the capture or bubble phase * of the event. * @param {Object=} opt_handlerScope Object in whose scope to call the listener. */ goog.events.EventTarget.prototype.addEventListener = function( type, handler, opt_capture, opt_handlerScope) { goog.events.listen(this, type, handler, opt_capture, opt_handlerScope); }; /** * Removes an event listener from the event target. The handler must be the * same object as the one added. If the handler has not been added then * nothing is done. * @param {string} type The type of the event to listen for. * @param {Function|Object} handler The function to handle the event. The * handler can also be an object that implements the handleEvent method * which takes the event object as argument. * @param {boolean=} opt_capture In DOM-compliant browsers, this determines * whether the listener is fired during the capture or bubble phase * of the event. * @param {Object=} opt_handlerScope Object in whose scope to call the listener. */ goog.events.EventTarget.prototype.removeEventListener = function( type, handler, opt_capture, opt_handlerScope) { goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope); }; /** * Dispatches an event (or event like object) and calls all listeners * listening for events of this type. The type of the event is decided by the * type property on the event object. * * If any of the listeners returns false OR calls preventDefault then this * function will return false. If one of the capture listeners calls * stopPropagation, then the bubble listeners won't fire. * * @param {string|Object|goog.events.Event} e Event object. * @return {boolean} If anyone called preventDefault on the event object (or * if any of the handlers returns false this will also return false. */ goog.events.EventTarget.prototype.dispatchEvent = function(e) { return goog.events.dispatchEvent(this, e); }; /** * Unattach listeners from this object. Classes that extend EventTarget may * need to override this method in order to remove references to DOM Elements * and additional listeners, it should be something like this: * <pre> * MyClass.prototype.disposeInternal = function() { * MyClass.superClass_.disposeInternal.call(this); * // Dispose logic for MyClass * }; * </pre> * @protected */ goog.events.EventTarget.prototype.disposeInternal = function() { goog.events.EventTarget.superClass_.disposeInternal.call(this); goog.events.removeAll(this); this.parentEventTarget_ = null; };
andrewschaaf/closure-library-mirror
closure/goog/events/eventtarget.js
JavaScript
apache-2.0
6,787
/** * Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ RED.clipboard = (function() { var dialog; var dialogContainer; var exportNodesDialog; var importNodesDialog; var disabled = false; function setupDialogs() { dialog = $('<div id="clipboard-dialog" class="hide node-red-dialog"><form class="dialog-form form-horizontal"></form></div>') .appendTo("body") .dialog({ modal: true, autoOpen: false, width: 500, resizable: false, buttons: [ { id: "clipboard-dialog-cancel", text: RED._("common.label.cancel"), click: function() { $( this ).dialog( "close" ); } }, { id: "clipboard-dialog-close", class: "primary", text: RED._("common.label.close"), click: function() { $( this ).dialog( "close" ); } }, { id: "clipboard-dialog-copy", class: "primary", text: RED._("clipboard.export.copy"), click: function() { $("#clipboard-export").select(); document.execCommand("copy"); document.getSelection().removeAllRanges(); RED.notify(RED._("clipboard.nodesExported")); $( this ).dialog( "close" ); } }, { id: "clipboard-dialog-ok", class: "primary", text: RED._("common.label.import"), click: function() { RED.view.importNodes($("#clipboard-import").val(),$("#import-tab > a.selected").attr('id') === 'import-tab-new'); $( this ).dialog( "close" ); } } ], open: function(e) { $(this).parent().find(".ui-dialog-titlebar-close").hide(); }, close: function(e) { } }); dialogContainer = dialog.children(".dialog-form"); exportNodesDialog = '<div class="form-row">'+ '<label style="width:auto;margin-right: 10px;" data-i18n="clipboard.export.copy"></label>'+ '<span id="export-range-group" class="button-group">'+ '<a id="export-range-selected" class="editor-button toggle" href="#" data-i18n="clipboard.export.selected"></a>'+ '<a id="export-range-flow" class="editor-button toggle" href="#" data-i18n="clipboard.export.current"></a>'+ '<a id="export-range-full" class="editor-button toggle" href="#" data-i18n="clipboard.export.all"></a>'+ '</span>'+ '</div>'+ '<div class="form-row">'+ '<textarea readonly style="resize: none; width: 100%; border-radius: 4px;font-family: monospace; font-size: 12px; background:#f3f3f3; padding-left: 0.5em; box-sizing:border-box;" id="clipboard-export" rows="5"></textarea>'+ '</div>'+ '<div class="form-row" style="text-align: right;">'+ '<span id="export-format-group" class="button-group">'+ '<a id="export-format-mini" class="editor-button editor-button-small toggle" href="#" data-i18n="clipboard.export.compact"></a>'+ '<a id="export-format-full" class="editor-button editor-button-small toggle" href="#" data-i18n="clipboard.export.formatted"></a>'+ '</span>'+ '</div>'; importNodesDialog = '<div class="form-row">'+ '<textarea style="resize: none; width: 100%; border-radius: 0px;font-family: monospace; font-size: 12px; background:#eee; padding-left: 0.5em; box-sizing:border-box;" id="clipboard-import" rows="5" placeholder="'+ RED._("clipboard.pasteNodes")+ '"></textarea>'+ '</div>'+ '<div class="form-row">'+ '<label style="width:auto;margin-right: 10px;" data-i18n="clipboard.import.import"></label>'+ '<span id="import-tab" class="button-group">'+ '<a id="import-tab-current" class="editor-button toggle selected" href="#" data-i18n="clipboard.export.current"></a>'+ '<a id="import-tab-new" class="editor-button toggle" href="#" data-i18n="clipboard.import.newFlow"></a>'+ '</span>'+ '</div>'; } function validateImport() { var importInput = $("#clipboard-import"); var v = importInput.val(); v = v.substring(v.indexOf('['),v.lastIndexOf(']')+1); try { JSON.parse(v); importInput.removeClass("input-error"); importInput.val(v); $("#clipboard-dialog-ok").button("enable"); } catch(err) { if (v !== "") { importInput.addClass("input-error"); } $("#clipboard-dialog-ok").button("disable"); } } function importNodes() { if (disabled) { return; } dialogContainer.empty(); dialogContainer.append($(importNodesDialog)); dialogContainer.i18n(); $("#clipboard-dialog-ok").show(); $("#clipboard-dialog-cancel").show(); $("#clipboard-dialog-close").hide(); $("#clipboard-dialog-copy").hide(); $("#clipboard-dialog-ok").button("disable"); $("#clipboard-import").keyup(validateImport); $("#clipboard-import").on('paste',function() { setTimeout(validateImport,10)}); $("#import-tab > a").click(function(evt) { evt.preventDefault(); if ($(this).hasClass('disabled') || $(this).hasClass('selected')) { return; } $(this).parent().children().removeClass('selected'); $(this).addClass('selected'); }); dialog.dialog("option","title",RED._("clipboard.importNodes")).dialog("open"); } function exportNodes() { if (disabled) { return; } dialogContainer.empty(); dialogContainer.append($(exportNodesDialog)); dialogContainer.i18n(); $("#export-format-group > a").click(function(evt) { evt.preventDefault(); if ($(this).hasClass('disabled') || $(this).hasClass('selected')) { return; } $(this).parent().children().removeClass('selected'); $(this).addClass('selected'); var flow = $("#clipboard-export").val(); if (flow.length > 0) { var nodes = JSON.parse(flow); var format = $(this).attr('id'); if (format === 'export-format-full') { flow = JSON.stringify(nodes,null,4); } else { flow = JSON.stringify(nodes); } $("#clipboard-export").val(flow); } }); $("#export-range-group > a").click(function(evt) { evt.preventDefault(); if ($(this).hasClass('disabled') || $(this).hasClass('selected')) { return; } $(this).parent().children().removeClass('selected'); $(this).addClass('selected'); var type = $(this).attr('id'); var flow = ""; var nodes = null; if (type === 'export-range-selected') { var selection = RED.view.selection(); nodes = RED.nodes.createExportableNodeSet(selection.nodes); } else if (type === 'export-range-flow') { var activeWorkspace = RED.workspaces.active(); nodes = RED.nodes.filterNodes({z:activeWorkspace}); var parentNode = RED.nodes.workspace(activeWorkspace)||RED.nodes.subflow(activeWorkspace); nodes.unshift(parentNode); nodes = RED.nodes.createExportableNodeSet(nodes); } else if (type === 'export-range-full') { nodes = RED.nodes.createCompleteNodeSet(false); } if (nodes !== null) { if (RED.settings.flowFilePretty) { flow = JSON.stringify(nodes,null,4); } else { flow = JSON.stringify(nodes); } } if (flow.length > 0) { $("#export-copy").removeClass('disabled'); } else { $("#export-copy").addClass('disabled'); } $("#clipboard-export").val(flow); }) $("#clipboard-dialog-ok").hide(); $("#clipboard-dialog-cancel").hide(); $("#clipboard-dialog-copy").hide(); $("#clipboard-dialog-close").hide(); var selection = RED.view.selection(); if (selection.nodes) { $("#export-range-selected").click(); } else { $("#export-range-selected").addClass('disabled').removeClass('selected'); $("#export-range-flow").click(); } if (RED.settings.flowFilePretty) { $("#export-format-full").click(); } else { $("#export-format-mini").click(); } $("#clipboard-export") .focus(function() { var textarea = $(this); textarea.select(); textarea.mouseup(function() { textarea.unbind("mouseup"); return false; }) }); dialog.dialog("option","title",RED._("clipboard.exportNodes")).dialog( "open" ); setTimeout(function() { $("#clipboard-export").focus(); if (!document.queryCommandEnabled("copy")) { $("#clipboard-dialog-cancel").hide(); $("#clipboard-dialog-close").show(); } else { $("#clipboard-dialog-cancel").show(); $("#clipboard-dialog-copy").show(); } },0); } function hideDropTarget() { $("#dropTarget").hide(); RED.keyboard.remove("escape"); } return { init: function() { setupDialogs(); RED.events.on("view:selection-changed",function(selection) { if (!selection.nodes) { RED.menu.setDisabled("menu-item-export",true); RED.menu.setDisabled("menu-item-export-clipboard",true); RED.menu.setDisabled("menu-item-export-library",true); } else { RED.menu.setDisabled("menu-item-export",false); RED.menu.setDisabled("menu-item-export-clipboard",false); RED.menu.setDisabled("menu-item-export-library",false); } }); RED.actions.add("core:show-export-dialog",exportNodes); RED.actions.add("core:show-import-dialog",importNodes); RED.events.on("editor:open",function() { disabled = true; }); RED.events.on("editor:close",function() { disabled = false; }); RED.events.on("search:open",function() { disabled = true; }); RED.events.on("search:close",function() { disabled = false; }); RED.events.on("type-search:open",function() { disabled = true; }); RED.events.on("type-search:close",function() { disabled = false; }); RED.events.on("palette-editor:open",function() { disabled = true; }); RED.events.on("palette-editor:close",function() { disabled = false; }); $('#chart').on("dragenter",function(event) { if ($.inArray("text/plain",event.originalEvent.dataTransfer.types) != -1) { $("#dropTarget").css({display:'table'}); RED.keyboard.add("*", "escape" ,hideDropTarget); } }); $('#dropTarget').on("dragover",function(event) { if ($.inArray("text/plain",event.originalEvent.dataTransfer.types) != -1) { event.preventDefault(); } }) .on("dragleave",function(event) { hideDropTarget(); }) .on("drop",function(event) { var data = event.originalEvent.dataTransfer.getData("text/plain"); hideDropTarget(); data = data.substring(data.indexOf('['),data.lastIndexOf(']')+1); RED.view.importNodes(data); event.preventDefault(); }); }, import: importNodes, export: exportNodes } })();
MaxXx1313/my-node-red
editor/js/ui/clipboard.js
JavaScript
apache-2.0
13,673
//// [subtypingWithCallSignaturesA.ts] declare function foo3(cb: (x: number) => number): typeof cb; var r5 = foo3((x: number) => ''); // error //// [subtypingWithCallSignaturesA.js] var r5 = foo3(function (x) { return ''; });
DickvdBrink/TypeScript
tests/baselines/reference/subtypingWithCallSignaturesA.js
JavaScript
apache-2.0
232
define(function(require, exports, module) { var $ = require('jquery'); var leftBtn =$('#company-list').find('.left-btn'), rightBtn = $('#company-list').find('.right-btn'), show = $('#company-list').find('.show'); module.exports = { i:0, // 处理鼠标移入移出事件 onHoverAndOut: function() { var _this = this; $('#company-list').on('mouseover', function() { leftBtn.show(); rightBtn.show(); }); $('#company-list').on('mouseout', function() { leftBtn.hide(); rightBtn.hide(); }); }, //处理点击事件 onClick: function() { var _this = this; leftBtn.on('click', function() { _this.rightMove(); }); rightBtn.on('click', function() { _this.leftMove(); }); }, leftMove: function() { var value = 164; this.i = this.i + 1; if (this.i >= 7) { this.i = 0; } value = this.i * value; this.val = value; show.animate({ left: "-" + value + "px" }, 1000); }, rightMove: function() { var value = 164; if (this.i <= 0) { this.i = 7; } value = (this.i - 1) * value; this.val = value; show.animate({ left: "-" + value + "px" }, 1000); this.i = this.i - 1; } } })
despise-all/front-demo
jike home page/js/cooperation-company.js
JavaScript
apache-2.0
1,646
'use strict'; //debugger; //pageSetUp(); var soProfiling; var soProfileInstance = function() { soProfiling = new soProfilingObject(); soProfiling.Load(); }; var soProfilingObject = function() { var THIS = this; var numberFormat = d3.format(",f"); THIS.type = "materialCount"; //constructTabs(THIS); this.Load = function(obj) { //enableLoading(); var source = $(obj).data("source"); THIS.source = source || $("#myTab").find("li.active").data("source"); var request = { "source" : THIS.source, "viewType" : "default" }; drawChart(); /*callAjaxService("JiraProfile", callbackSuccessSOProfile, callBackFailure, request, "POST");*/ }; this.loadViewType = function(viewType) { //enableLoading(); THIS.type = viewType; setTimeout(function() { drawChart(); //disableLoading(); }, 50); }; var callbackSuccessSOProfile = function(data) { /* * private String soCount; a private String companyCode; b private * String companyName; c private String salesOrg; d private String * salesOrgName; e private String salesGroup; f private String * salesGroupName; g private String division; h private String * divisionName; i private String salesDocType; j private String * plantGroup; k private String plantName; l private String netValue; m * private String source; n private String region; o private String * lastChanged; p private String materialType; q private String soType; * r */ //disableLoading(); if (data && data.isException){ showNotification("error",data.customMessage); return; } if (data != undefined && data != null && data["aggregatedSalesOrderList"] != undefined && data["aggregatedSalesOrderList"] != null && data["aggregatedSalesOrderList"].length > 0) { THIS.data = data["aggregatedSalesOrderList"]; drawChart(); } }; var drawChart = function() { d3.csv("data/jiraData.csv", function(error, experiments) { console.log(experiments); experiments.forEach(function(x) { x.count = 1; }); /*var chart = dc.pieChart("#test");*/ var ndx = crossfilter(experiments); THIS.pieChartIssueType = dc.pieChart("#pie-chart-IssueType"); var pieChartIssueTypeDimension = ndx.dimension(function(d){return d.Issue_Type; }); var pieIssueType = pieChartIssueTypeDimension.group(); THIS.pieChartStatus = dc.pieChart("#pie-chart-Status"); var pieChartStatusDimension = ndx.dimension(function(d){return d.Status; }); var pieStatus = pieChartStatusDimension.group(); THIS.pieChartFixVersions = dc.pieChart("#pie-chart-FixVersions"); var pieChartFixVersionsDimension = ndx.dimension(function(d){return d.FixVersions; }); var pieFixVersions = pieChartFixVersionsDimension.group(); THIS.pieChartPriority = dc.pieChart("#pie-chart-Priority"); var pieChartPriorityDimension = ndx.dimension(function(d){return d.Priority; }); var piePriority = pieChartPriorityDimension.group(); THIS.pieChartResolution = dc.pieChart("#pie-chart-Resolution"); var pieChartResolutionDimension = ndx.dimension(function(d){return d.Resolution; }); var pieResolution = pieChartResolutionDimension.group(); THIS.pieChartComponents = dc.pieChart("#pie-chart-Components"); var pieChartComponentsDimension = ndx.dimension(function(d){return d.Components; }); var pieComponents = pieChartComponentsDimension.group(); THIS.pieChartEpicTheme = dc.pieChart("#pie-chart-EpicTheme"); var pieChartEpicThemeDimension = ndx.dimension(function(d){return d.Epic_theme; }); var pieEpicTheme = pieChartEpicThemeDimension.group(); THIS.rowChartAssignee = dc.pieChart("#row-Chart-Assignee"); var rowChartAssigneeDimension = ndx.dimension(function(d){return d.Assignee; }); var rowAssignee = rowChartAssigneeDimension.group(); THIS.pieChartReporter = dc.pieChart("#pie-chart-Reporter"); var pieChartReporterDimension = ndx.dimension(function(d){return d.Reporter; }); var pieReporter = pieChartReporterDimension.group(); THIS.horzBarChartProject = dc.rowChart("#row-chart-Project"); var barChartProjectDimension = ndx.dimension(function(d){return d.project; }); var barProject = barChartProjectDimension.group(); THIS.horzBarChartProject .width(250).height(600) .dimension(barChartProjectDimension) .group(barProject) .elasticX(true); THIS.timelineAreaChart1 = dc.lineChart("#timeline-area-chart1"); var timelineAreaChart1Dimension = ndx.dimension(function(d){return d.TimeSpent; }); var timelineAreaProject = timelineAreaChart1Dimension.group(); THIS.timelineAreaChart1 .width(250).height(300) .dimension(barChartProjectDimension) .group(barProject) .elasticX(true); THIS.pieChartIssueType.width(170).height(150).radius(60) .dimension(pieChartIssueTypeDimension) .group(pieIssueType) .renderlet(function (chart) { //console.log(chart.filters()); });; THIS.pieChartStatus.width(170).height(150).radius(60) .dimension(pieChartStatusDimension) .group(pieStatus) .renderlet(function (chart) { //console.log(chart.filters()); });; THIS.pieChartFixVersions.width(170).height(150).radius(60) .dimension(pieChartFixVersionsDimension) .group(pieFixVersions) .renderlet(function (chart) { //console.log(chart.filters()); });; THIS.pieChartPriority.width(170).height(150).radius(60).innerRadius(30) .dimension(pieChartPriorityDimension) .group(piePriority) .renderlet(function (chart) { //console.log(chart.filters()); });; THIS.pieChartResolution.width(170).height(150).radius(60) .dimension(pieChartResolutionDimension) .group(pieResolution) .renderlet(function (chart) { //console.log(chart.filters()); });; THIS.rowChartAssignee .width(170).height(150).radius(60) .dimension(rowChartAssigneeDimension) .group(rowAssignee); THIS.pieChartComponents.width(170).height(150).radius(60).innerRadius(30) .dimension(pieChartComponentsDimension) .group(pieComponents) .renderlet(function (chart) { //console.log(chart.filters()); });; THIS.pieChartEpicTheme.width(170).height(150).radius(60) .dimension(pieChartEpicThemeDimension) .group(pieEpicTheme) .renderlet(function (chart) { });; THIS.pieChartReporter .width(170).height(150).radius(60) .dimension(pieChartReporterDimension) .group(pieReporter); THIS.pieChartIssueType.render(); THIS.pieChartStatus.render(); THIS.pieChartFixVersions.render(); THIS.pieChartPriority.render(); THIS.pieChartResolution.render(); THIS.pieChartComponents.render(); THIS.pieChartEpicTheme.render(); THIS.rowChartAssignee.render(); THIS.horzBarChartProject.render(); THIS.pieChartReporter.render(); }); /*var data = THIS.data; $("[id^=pie-chart] h4").addClass("hide"); if (THIS.source == "JDE") $("#pie-chart-SalesGroup .axisLabel").html("Sales Territory"); else $("#pie-chart-SalesGroup .axisLabel").html("Sales Group"); var dateFormat = d3.time.format("%m/%d/%Y"); data.forEach(function(d) { d.dd = dateFormat.parse(d.p); d.month = d3.time.month(d.dd); d.a = +d.a; d.m = +d.m; d.zz = (THIS.type == "netvalue") ? isNaN(d.m) ? 0 : d.m : isNaN(d.a) ? 0 : d.a; }); var ndx = crossfilter(data); var all = ndx.groupAll(); THIS.pieChartCompanyCode = dc.pieChart("#pie-chart-CompanyCode"); var pieChartCompanyCodeDimension = ndx.dimension(function(d) { return (d.b || "Others") + "-" + (d.c || "Not Available"); }); var pieCompanyCode = pieChartCompanyCodeDimension.group(); if (pieCompanyCode.size() > 1 || pieCompanyCode.all()[0].key.split("-")[0] != "Others") { pieCompanyCode = pieCompanyCode.reduceSum( function(d) { return d.zz; }); } else { $("#pie-chart-CompanyCode h4").removeClass("hide"); pieCompanyCode = pieCompanyCode.reduceSum( function() { return 0; }); } THIS.pieChartDivision = dc.pieChart("#pie-chart-Division"); var pieChartDivisionDimension = ndx.dimension(function(d) { return (d.h || "Others") + "-" + (d.i || "Not Available"); }); var pieDivision = pieChartDivisionDimension.group(); if (pieDivision.size() > 1 || pieDivision.all()[0].key.split("-")[0] != "Others") { pieDivision = pieDivision.reduceSum( function(d) { return d.zz; }); } else { $("#pie-chart-Division h4").removeClass("hide"); pieDivision = pieDivision.reduceSum( function() { return 0; }); } // for orderreason pie - begin THIS.pieChartOrderReason = dc.pieChart("#pie-chart-OrderReason"); var pieChartOrderReasonDimension = ndx.dimension(function(d) { return (d.t || "Others") + "-" + (d.u || "Not Available"); }); var pieOrderReason = pieChartOrderReasonDimension.group(); if (pieOrderReason.size() > 1 || pieOrderReason.all()[0].key.split("-")[0] != "Others") { pieOrderReason = pieOrderReason.reduceSum( function(d) { return d.zz; }); } else { $("#pie-chart-OrderReason h4").removeClass("hide"); pieOrderReason = pieOrderReason.reduceSum( function() { return 0; }); } // for orderreason pie - End // for ordercategory pie - Start THIS.pieChartOrderCategory = dc.pieChart("#pie-chart-OrderCategory"); var pieChartOrderCategoryDimension = ndx.dimension(function(d) { return d.v|| "Others"; }); var pieOrderCategory = pieChartOrderCategoryDimension.group(); if (pieOrderCategory.size() > 1 || pieOrderCategory.all()[0].key.split("-")[0] != "Others") { pieOrderCategory = pieOrderCategory.reduceSum( function(d) { return d.zz; }); } else { $("#pie-chart-OrderCategory h4").removeClass("hide"); pieOrderCategory = pieOrderCategory.reduceSum( function() { return 0; }); } // for ordercategory pie - End THIS.pieChartPlant = dc.pieChart("#pie-chart-plant"); var pieChartPlantDimension = ndx.dimension(function(d) { return (d.k || "Others") + "-" + (d.l || "Not Available"); }); var piePlant = pieChartPlantDimension.group(); if (piePlant.size() > 1 || piePlant.all()[0].key.split("-")[0] != "Others") { piePlant = piePlant.reduceSum(function(d) { return d.zz; }); }else { $("#pie-chart-plant h4").removeClass("hide"); piePlant = piePlant.reduceSum( function() { return 0; }); } THIS.pieChartMaterialType = dc.pieChart("#pie-chart-MaterialType"); var pieChartMaterialTypeDimension = ndx.dimension(function(d) { return d.q || "Others"; }); var pieMaterialType = null; if (pieChartMaterialTypeDimension.group().size() > 1 || pieChartMaterialTypeDimension.group().all()[0].key.split("-")[0] != "Others") { pieMaterialType = pieChartMaterialTypeDimension.group().reduceSum( function(d) { return d.zz; }); } else{ $("#pie-chart-MaterialType h4").removeClass("hide"); pieMaterialType = pieChartMaterialTypeDimension.group().reduceSum( function() { return 0; }); } THIS.pieChartSalesDocType = dc.pieChart("#pie-chart-Sales-Doc-Type"); var pieChartSalesDocTypeDimension = ndx.dimension(function(d) { return (d.j || "Others") + "-" + (d.s || "Not Available"); }); var pieSalesDocType = null; if (pieChartSalesDocTypeDimension.group().size() > 1 || pieChartSalesDocTypeDimension.group().all()[0].key.split("-")[0] != "Others") { pieSalesDocType = pieChartSalesDocTypeDimension.group().reduceSum( function(d) { return d.zz; }); } else { $("#pie-chart-Sales-Doc-Type h4").removeClass("hide"); pieSalesDocType = pieChartSalesDocTypeDimension.group().reduceSum( function() { return 0; }); } THIS.pieChartSalesOrg = dc.pieChart("#pie-chart-SalesOrg"); var pieChartSalesOrgpDimension = ndx.dimension(function(d) { return (d.d || "Others") + "-" + (d.e || "Not Available"); }); var pieSalesOrg = pieChartSalesOrgpDimension.group(); if (pieSalesOrg.size() > 1 || pieSalesOrg.all()[0].key.split("-")[0] != "Others") { pieSalesOrg = pieSalesOrg.reduceSum( function(d) { return d.zz; }); } else { $("#pie-chart-SalesOrg h4").removeClass("hide"); pieSalesOrg = pieSalesOrg.reduceSum( function() { return 0; }); } THIS.pieChartSalesGroup = dc.pieChart("#pie-chart-SalesGroup"); var pieChartSalesGroupDimension = ndx.dimension(function(d) { return (d.f || "Others") + "-" + (d.g || "Not Available"); }); var pieSalesGroup = pieChartSalesGroupDimension.group(); if (pieSalesGroup.size() > 1 || pieSalesGroup.all()[0].key.split("-")[0] != "Others") { pieSalesGroup = pieSalesGroup.reduceSum( function(d) { return d.zz; }); } else { $("#pie-chart-SalesGroup h4").removeClass("hide"); pieSalesGroup = pieSalesGroup.reduceSum( function() { return 0; }); } THIS.horzBarChart = dc.rowChart("#row-chart"); THIS.timelineAreaChart = dc.lineChart("#timeline-area-chart"); THIS.timelineChart = dc.barChart("#timeline-chart"); var timelineDimension = ndx.dimension(function(d) { return d.month; }); var timelineGroup = timelineDimension.group().reduceSum(function(d) { return d.zz; }); var timelineAreaGroup = timelineDimension.group().reduce( function(p, v) { ++p.count; if (isNaN(v.m)) v.m = 0; p.total += v.m;// (v.open + v.close) / 2; return p; }, function(p, v) { --p.count; if (isNaN(v.m)) v.m = 0; p.total -= v.m;// (v.open + v.close) / 2; return p; }, function() { return { count : 0, total : 0, }; }); // counts per weekday var horzBarDimension = ndx.dimension(function(d) { return d.r || ""; }); var horzBarGrp = horzBarDimension.group().reduceSum(function(d) { return d.zz; }); THIS.pieChartCompanyCode.width(170).height(150).radius(60).dimension( pieChartCompanyCodeDimension).group(pieCompanyCode).label( function(d) { var companyCode = d.key.split("-"); return companyCode[0]; }).on('filtered', function(chart) { THIS.refreshTable(pieChartCompanyCodeDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartDivision.width(170).height(150).radius(60).innerRadius(30) .dimension(pieChartDivisionDimension).group(pieDivision).label( function(d) { var division = d.key.split("-"); return division[0]; }).on('filtered', function(chart) { THIS.refreshTable(pieChartDivisionDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartPlant.width(170).height(150).radius(60) // .colors(colorScale) .dimension(pieChartPlantDimension).group(piePlant).label(function(d) { var plantGroup = d.key.split("-"); return plantGroup[0]; }).on('filtered', function(chart) { THIS.refreshTable(pieChartPlantDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartSalesOrg.width(170).height(150).radius(60).innerRadius(30) .dimension(pieChartSalesOrgpDimension).group(pieSalesOrg) .label(function(d) { var purchaseOrg = d.key.split("-"); return purchaseOrg[0]; }).on('filtered', function(chart) { THIS.refreshTable(pieChartSalesOrgpDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartMaterialType.width(170).height(150).radius(60) .innerRadius(30).dimension(pieChartMaterialTypeDimension) .group(pieMaterialType).on('filtered', function(chart) { THIS.refreshTable(pieChartMaterialTypeDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartSalesDocType.width(170).height(150).radius(60) .innerRadius(30).dimension(pieChartSalesDocTypeDimension) .group(pieSalesDocType).on('filtered', function(chart) { THIS.refreshTable(pieChartSalesDocTypeDimension); }).label(function(d) { var name = d.key.split("-"); return name[0]; }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartSalesGroup.width(170).height(150).radius(60).dimension( pieChartSalesGroupDimension).group(pieSalesGroup).label( function(d) { var purchaseGrp = d.key.split("-"); return purchaseGrp[0]; }).on('filtered', function(chart) { THIS.refreshTable(pieChartSalesGroupDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartMaterialType.width(170).height(150).radius(60) .innerRadius(30).dimension(pieChartMaterialTypeDimension) .group(pieMaterialType).on('filtered', function(chart) { THIS.refreshTable(pieChartMaterialTypeDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartOrderReason.width(170).height(150).radius(60) .innerRadius(30).dimension(pieChartOrderReasonDimension).label( function(d) { var purchaseGrp = d.key.split("-"); return purchaseGrp[0]; }) .group(pieOrderReason).on('filtered', function(chart) { THIS.refreshTable(pieChartOrderReasonDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); THIS.pieChartOrderCategory.width(170).height(150).radius(60) .innerRadius(30).dimension(pieChartOrderCategoryDimension).label( function(d) { var purchaseGrp = d.key.split("-"); return purchaseGrp[0]; }) .group(pieOrderCategory).on('filtered', function(chart) { THIS.refreshTable(pieChartOrderCategoryDimension); }).title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }); // #### Row Chart THIS.horzBarChart.width(180).height(700).margins({ top : 20, left : 10, right : 10, bottom : 20 }).group(horzBarGrp).dimension(horzBarDimension).on('filtered', function(chart) { THIS.refreshTable(horzBarDimension); }) // assign colors to each value in the x scale domain .ordinalColors( [ '#3182bd', '#6baed6', '#9e5ae1', '#c64bef', '#da8aab' ]) .label(function(d) { return d.key;// .split(".")[1]; }) // title sets the row text .title( function(d) { return THIS.type == "netvalue" ? d.key + ': $' + numberFormat(d.value) : d.key + ': ' + numberFormat(d.value); }).elasticX(true).xAxis().ticks(4); THIS.timelineAreaChart.renderArea(true).width($('#content').width()) .height(150).transitionDuration(1000).margins({ top : 30, right : 70, bottom : 25, left : 80 }).dimension(timelineDimension).mouseZoomable(true).rangeChart( THIS.timelineChart).x( d3.time.scale() .domain( [ new Date(2011, 0, 1), new Date(2015, 11, 31) ])) .round(d3.time.month.round).xUnits(d3.time.months).elasticY( true).renderHorizontalGridLines(true).brushOn(false) .group(timelineAreaGroup, "Vendor Count").valueAccessor( function(d) { return d.value.total; }).on('filtered', function(chart) { THIS.refreshTable(timelineDimension); }) // .stack(timelineSecondGroup, "Material Count", function(d) // { // return d.value; // }) // title can be called by any stack layer. .title(function(d) { var value = d.value.total; if (isNaN(value)) value = 0; return dateFormat(d.key) + "\n$" + numberFormat(value); }); THIS.timelineChart.width($('#content').width()).height(80).margins({ top : 40, right : 70, bottom : 20, left : 80 }).dimension(timelineDimension).group(timelineGroup).centerBar(true) .gap(1).x( d3.time.scale() .domain( [ new Date(2011, 0, 1), new Date(2015, 11, 31) ])) .round(d3.time.month.round).alwaysUseRounding(true).xUnits( d3.time.months); dc.dataCount(".dc-data-count").dimension(ndx).group(all); var dataTableData = data.slice(0, 100); THIS.dataTable = $(".dc-data-table") .DataTable( { "sDom" : "<'dt-top-row'Tlf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>", "bProcessing" : true, "bLengthChange" : true, "bSort" : true, "bInfo" : true, "bJQueryUI" : false, "scrollX" : true, "aaData" : dataTableData, "oTableTools" : { "aButtons" : [ { "sExtends" : "collection", "sButtonText" : 'Export <span class="caret" />', "aButtons" : [ "csv", "pdf" ] } ], "sSwfPath" : "js/plugin/datatables/media/swf/copy_csv_xls_pdf.swf" }, "bDestroy" : true, "processing" : true, "aoColumns" : [ { "mDataProp" : null, "sDefaultContent" : '<img src="./img/details_open.png">' }, { "mDataProp" : "a", "sDefaultContent" : "0", "sClass" : "numbercolumn" }, { "mDataProp" : "b", "sDefaultContent" : "", }, { "mDataProp" : "h", "sDefaultContent" : "", }, { "mDataProp" : "k", "sDefaultContent" : "", }, { "mData" : "q", "sDefaultContent" : "" }, { "mDataProp" : "j", "sDefaultContent" : "", }, { "mDataProp" : "d", "sDefaultContent" : "", }, { "mDataProp" : "f", "sDefaultContent" : "", }, { "mDataProp" : "m", "sDefaultContent" : "0", "mRender" : function(data, type, full) { if (isNaN(data)) data = 0; return numberFormat(data); }, "sClass" : "numbercolumn" }, { "mDataProp" : "r", "sDefaultContent" : "", }, { "mDataProp" : "p", "sClass" : "numbercolumn", "sDefaultContent" : "" }, ], "fnRowCallback" : function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { var request = { "viewType" : "level2", "source" : aData.n || "null", "companyCode" : aData.b || "null", "plant" : aData.k || "null", "salesOrg" : aData.d || "null", "salesType" : aData.j || "null", "salesGroup" : aData.f || "null", "soType" : aData.r || "null", "materialType" : aData.q || "null", "lastChangeDate" : aData.p || "null", "division" : aData.h || "null", "region" : "CAN", "customerId" : "null" }; * private String soCount; a private String * companyCode; b private String companyName; c * private String salesOrg; d private String * salesOrgName; e private String salesGroup; f * private String salesGroupName; g private * String division; h private String * divisionName; i private String salesDocType; * j private String plantGroup; k private String * plantName; l private String netValue; m * private String source; n private String * region; o private String lastChanged; p * private String materialType; q private String * soType; r $(nRow).attr({ "id" : "row" + iDisplayIndex }).unbind('click').bind('click', request, soProfiling.callLevel2soProfile); } }); */ dc.renderAll(); }; this.callLevel2soProfile = function(request) { var tr = $(this).closest('tr'); THIS.childId = "child" + $(tr).attr("id"); if ($(tr).find('td:eq(0)').hasClass("expandRow")) { $($(tr).find('td:eq(0)').find('img')).attr('src', './img/details_open.png'); $("#" + THIS.childId).hide(50); } else { $($(tr).find('td:eq(0)').find('img')).attr('src', './img/details_close.png'); if (!$(tr).next().hasClass("childRowtable")) { $(tr).after($("<tr/>").addClass("childRowtable").attr({ "id" : THIS.childId }).append($("<td/>")).append($("<td/>").attr({ "colspan" : "13", "id" : THIS.childId + "td" }).addClass("carousel"))); //enableLoading(THIS.childId + "td", "50%", "45%"); request = request.data; callAjaxService("JiraProfile", function(response) { callbackSucessLevel2SOProfile(response, request); }, callBackFailure, request, "POST"); } else { $("#" + THIS.childId).show(50); } } $(tr).find('td:eq(0)').toggleClass("expandRow"); }; var callbackSucessLevel2SOProfile = function(response, request) { //disableLoading(THIS.childId + "td"); if (response && response.isException){ showNotification("error",response.customMessage); return; } var childTabledata = null; if (response != null) childTabledata = response["level2SalesOrderList"]; $("#" + THIS.childId + "td") .show() .html("") .append( $("<table/>") .addClass("table table-hover dc-data-table") .attr({ "id" : THIS.childId + "Table" }) .append( $("<thead/>") .append( $("<tr/>") .append( $( "<th/>") .html( "Sales Order")) .append( $( "<th/>") .html( "Material #")) .append( $( "<th/>") .html( "Customer ID")) .append( $( "<th/>") .html( "Customer Name")) .append( $( "<th/>") .html( "Plant Name")) .append( $( "<th/>") .html( "Line Item")) .append( $( "<th/>") .html( "Net Value"))))); $("#" + THIS.childId + "Table") .DataTable( { "sDom" : "<'dt-top-row'Tlf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>", "bProcessing" : true, "bLengthChange" : true, // "bServerSide": true, "bInfo" : true, "bFilter" : false, "bJQueryUI" : false, "aaData" : childTabledata, "scrollX" : true, "oTableTools" : { "aButtons" : [ { "sExtends" : "collection", "sButtonText" : 'Export <span class="caret" />', "aButtons" : [ "csv", "pdf" ] } ], "sSwfPath" : "js/plugin/datatables/media/swf/copy_csv_xls_pdf.swf" }, "aoColumns" : [ { "mDataProp" : "salesDoc", "sDefaultContent" : "" }, { "mDataProp" : "materialNumber", "sDefaultContent" : "" }, { "mDataProp" : "customerId", "sDefaultContent" : "" }, { "mDataProp" : "customerName", "sDefaultContent" : "" }, { "mDataProp" : "plantName", "sDefaultContent" : "" }, { "mDataProp" : "salesItem", "sDefaultContent" : "" }, { "mDataProp" : "netValue", "sDefaultContent" : "", "mRender" : function(data, type, full) { return numberFormat(data); }, "sClass" : "numbercolumn" } ], "fnRowCallback" : function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { $(nRow) .attr( { 'onClick' : "javascript:thirdLevelDrillDownSO('', '" + aData.salesDoc + "','100','" + request.source + "')", 'data-target' : '#myModalthredlevel', 'data-toggle' : 'modal' }); } }); }; this.refreshTable = function(dim) { if (THIS.dataTable !== null && dim !== null) { THIS.dataTable.fnClearTable(); THIS.dataTable.fnAddData(dim.top(100)); THIS.dataTable.fnDraw(); } else console .log('[While Refreshing Data Table] This should never happen..'); }; d3.selectAll("#version").text(dc.version); /* * var config = { endpoint : 'soprofile', dataKey: * 'aggregatedSalesOrderList', dataType: 'json', dataPreProcess: function(d) { * d.dd = dateFormat.parse(d.p); d.month = d3.time.month(d.dd); d.a = +d.a; * d.m = +d.m; }, mappings : [{ chartType : 'pie', htmlElement: * '#pie-chart-CompanyCode', field: 'companycode', resetHandler: "#resetCC" * },{ chartType : 'pie', htmlElement: '#pie-chart-plant', field: * 'accgroup', groupon: 'glamount', groupRound: true, resetHandler: * "#resetPlant" },{ chartType : 'pie', htmlElement: '#pie-chart-Division', * field: 'tradpartner', groupon: 'glamount', groupRound: true, * resetHandler: "#resetDiv" },{ chartType : 'pie', htmlElement: * '#pie-chart-MaterialType', field: 'userid', groupon: 'glamount', * groupRound: true, resetHandler: "#resetMT" },{ chartType : 'pie', * htmlElement: '#pie-chart-Sales-Doc-Type', field: 'tcode', groupon: * 'glamount', groupRound: true, resetHandler: "#resetDT" },{ chartType : * 'pie', htmlElement: '#pie-chart-SalesOrg', field: 'tcode', groupon: * 'glamount', groupRound: true, resetHandler: "#resetSO" },{ chartType : * 'pie', htmlElement: '#pie-chart-SalesGroup', field: 'tcode', groupon: * 'glamount', groupRound: true, resetHandler: "#resetSG" },{ chartType : * 'horbar', htmlElement: '#row-chart', field: 'doctype', resetHandler:'' * },{ chartType : 'timeline', htmlElement: '#timeline-area-chart', * subHtmlElement: '#timeline-chart', field: 'month', group: 'glamount', * resetHandler:'#resetTAC', mapFunction:function(p, v) { ++p.count; if * (isNaN(v.m)) v.m = 0; p.total += v.m;// (v.open + v.close) / 2; return p; }, * reduceFunction : function(p, v) { --p.count; p.total -= v.netprice;// * (v.open + v.close) / 2; return p; }, countFunction: function() { return { * count : 0, total : 0 }; } },{ chartType : 'table', htmlElement: * '.dc-data-table', field: 'date', groupon: 'companycode', coloums: * 'date,a, b,h,k,q,j,d,f,m,r,p', sortby: 'companycode', summarydiv : * '.dc-data-count', renderlet: 'dc-table-group', resetHandler:'#resetRC' }] }; */ // var sop = new Profiling(config); // sop.init(function(){ // $('#loading').hide(); // }); }; soProfileInstance();
Durgesh1988/core
client/htmls/public/js/jiraprofiling/e2e_JiraProfiling.js
JavaScript
apache-2.0
32,814
import './styles.scss'; import {View} from 'backbone'; import {className} from '../../decorators'; import bem from 'b_'; import $ from 'jquery'; import {defaults} from 'underscore'; export const POSITION = { 'top': function({top, left, width}, {offset}, tipSize) { return { top: top - tipSize.height - offset, left: left + width / 2 - tipSize.width / 2 }; }, 'center': function({top, left, height, width}, offsets, tipSize) { return { top: top + height / 2, left: left + width / 2 - tipSize.width / 2 }; }, 'right': function({top, left, height, width}, {offset}, tipSize) { return { top: top + height / 2 - tipSize.height / 2, left: left + width + offset }; }, 'left': function({top, left, height}, {offset}, tipSize) { return { top: top + height / 2 - tipSize.height / 2, left: left - offset - tipSize.width }; }, 'bottom': function({top, left, height, width}, {offset}, tipSize) { return { top: top + height + offset, left: left + width / 2 - tipSize.width / 2 }; }, 'bottom-left': function({top, left, height, width}, {offset}, tipSize) { return { top: top + height + offset, left: left + width - tipSize.width }; } }; @className('tooltip') class TooltipView extends View { static container = $(document.body); initialize(options) { this.options = options; defaults(this.options, {offset: 10}); } render() { this.constructor.container.append(this.$el); } isVisible() { return this.$el.is(':visible'); } setContent(text) { this.$el.html(text); } show(text, anchor) { const {position} = this.options; this.setContent(text); this.$el.addClass(bem(this.className, {position})); this.render(); if(document.dir === 'rtl' && position === 'right'){ this.$el.css(POSITION['left']( anchor[0].getBoundingClientRect(), {offset: this.options.offset}, this.$el[0].getBoundingClientRect())); } else if(document.dir === 'rtl' && position === 'left'){ this.$el.css(POSITION['right']( anchor[0].getBoundingClientRect(), {offset: this.options.offset}, this.$el[0].getBoundingClientRect())); } else { this.$el.css(POSITION[position]( anchor[0].getBoundingClientRect(), {offset: this.options.offset}, this.$el[0].getBoundingClientRect())); } } hide() { this.$el.remove(); } } export default TooltipView;
TpSr52/allure2
allure-generator/src/main/javascript/components/tooltip/TooltipView.js
JavaScript
apache-2.0
2,793
const handleError = (message) => { $("#errorMessage").text(message); $("#domoMessage").animate({width:'toggle'},350); } const sendAjax = (action, data) => { $.ajax({ cache: false, type: "POST", url: action, data: data, dataType: "json", success: (result, status, xhr) => { $("#domoMessage").animate({width:'hide'},350); window.location = result.redirect; }, error: (xhr, status, error) => { const messageObj = JSON.parse(xhr.responseText); handleError(messageObj.error); } }); } $(document).ready(() => { $("#signupForm").on("submit", (e) => { e.preventDefault(); $("#domoMessage").animate({width:'hide'},350); if($("#user").val() == '' || $("#pass").val() == '' || $("#pass2").val() == '') { handleError("RAWR! All fields are required"); return false; } if($("#pass").val() !== $("#pass2").val()) { handleError("RAWR! Passwords do not match"); return false; } sendAjax($("#signupForm").attr("action"), $("#signupForm").serialize()); return false; }); $("#loginForm").on("submit", (e) => { e.preventDefault(); $("#domoMessage").animate({width:'hide'},350); if($("#user").val() == '' || $("#pass").val() == '') { handleError("RAWR! Username or password is empty"); return false; } sendAjax($("#loginForm").attr("action"), $("#loginForm").serialize()); return false; }); $("#domoForm").on("submit", (e) => { e.preventDefault(); $("#domoMessage").animate({width:'hide'},350); if($("#domoName").val() == '' || $("#domoAge").val() == '') { handleError("RAWR! All fields are required"); return false; } sendAjax($("#domoForm").attr("action"), $("#domoForm").serialize()); return false; }); });
CScavone96/DomomakerA
client/client.js
JavaScript
apache-2.0
1,835
/// <reference path="../../services/office365/scripts/utility.js" /> /// <reference path="../../services/office365/scripts/o365adal.js" /> /// <reference path="../../services/office365/scripts/exchange.js" /> (function () { 'use strict'; angular.module('app365').controller('calendarDetailCtrl', ['$scope', '$stateParams', '$location', 'app365api', calendarDetailCtrl]); function calendarDetailCtrl($scope, $stateParams, $location, app365api) { var vm = this; // Get event with specified event id. vm.getEvent = function () { var outlookClient = app365api.outlookClientObj(); NProgress.start(); outlookClient.me.calendar.events.getEvent($stateParams.id).fetch() .then(function (event) { // Get event detail like subject, location, attendees etc. vm.subject = event.subject; vm.start = event.start; vm.end = event.end; vm.bodypreview = event.bodyPreview; vm.location = event.location.displayName; var attendees; event.attendees.forEach(function (attendee) { if (typeof attendees == 'undefined') { attendees = attendee.emailAddress.name } else { attendees += "," + attendee.emailAddress.name; } }); vm.attendees = attendees; $scope.$apply(); NProgress.done(); }); }; vm.getEvent(); } })();
OfficeDev/Cordova-Calendar-App-Code-Sample
app/calendar/calendar-detail-ctrl.js
JavaScript
apache-2.0
1,637
define({ "viewer": { "common": { "close": "Lukk", "focusMainstage": "Send tastaturfokus til media", "expandImage": "Utvid bilde" }, "a11y": { "skipToContent": "Gå til fortelling", "headerAria": "Historieoverskrift", "panelAria": "Historiefortelling", "mainStageAria": "Gjeldende historieavsnittmedier", "logoLinkAria": "Logokobling", "toTop": "Gå til begynnelsen av fortellingen", "focusContent": "Gå tilbake til fortelling", "navAria": "Historieavsnitt", "navPreviousAria": "Forrige avsnitt", "navNextAria": "Neste avsnitt", "toSectionAria": "Gå til avsnittet %SECTION_NUMBER%: %SECTION_TITLE%", "toNextGroupAria": "Neste avsnittsgruppe (%SECTION_RANGE%)", "toPrevGroupAria": "Forrige avsnittsgruppe (%SECTION_RANGE%)", "loadingAria": "Historieinnholdet lastes inn" }, "loading": { "step1": "Laster inn historien", "step2": "Laster inn data", "step3": "Initialiserer", "loadBuilder": "Går over til byggeverktøyet", "long": "Karthistorie initialiseres", "long2": "Takk for at du venter", "failButton": "Last inn historien på nytt" }, "signin": { "title": "Krever godkjenning", "explainViewer": "Logg på med en konto på %PORTAL_LINK% for å få tilgang til historien.", "explainBuilder": "Logg på med en konto på %PORTAL_LINK% for å konfigurere historien." }, "errors": { "boxTitle": "Det har oppstått en feil", "invalidConfig": "Ugyldig konfigurasjon", "invalidConfigNoApp": "Identifikator for webkartprogram ikke angitt i index.html.", "invalidConfigNoAppDev": "Det er ikke angitt en webkartapplikasjons-ID i URL-parameterne (?appid=). App-ID-konfigurasjonen i Index.html ignoreres i utviklingsmodus.", "unspecifiedConfigOwner": "Godkjent eier er ikke konfigurert.", "invalidConfigOwner": "Historieeier er ikke godkjent.", "createMap": "Kan ikke opprette kart", "invalidApp": "%TPL_NAME% finnes ikke eller er ikke tilgjengelig.", "appLoadingFail": "Noe gikk galt, og %TPL_NAME% ble ikke lastet inn på riktig måte.", "notConfiguredDesktop": "Historien er ikke konfigurert ennå.", "notConfiguredMobile": "Byggeverktøyet %TPL_NAME% støttes ikke med denne skjermstørrelsen. Hvis det er mulig, endrer du størrelsen på nettleseren for å få tilgang til byggeverktøyet. Du kan også lage historien på en enhet med større skjerm.", "notConfiguredMobile2": "Snu enheten i liggende retning for å bruke byggeverktøyet %TPL_NAME%.", "notAuthorized": "Du har ikke tillatelse til å lese denne historien", "notAuthorizedBuilder": "Du har ikke tillatelse til å bruke byggeverktøyet %TPL_NAME%.", "noBuilderIE": "Byggeverktøyet er ikke støttet i Internet Explorer før versjon %VERSION%. %UPGRADE%", "noViewerIE": "Denne historien er ikke støttet i Internet Explorer før versjon %VERSION%. %UPGRADE%", "noViewerIE2": "Du prøver å vise denne historien ved hjelp av en eldre nettleser som ikke støttes. Det kan være funksjoner som ikke fungerer eller andre uventede problemer. Vi foreslår at du oppgraderer til Internet Explorer 11 eller bruker en annen nettleser, for eksempel Chrome.", "noViewerIE3": "Mot slutten av 2017 vil denne historien ikke lenger lastes på denne nettleseren. I mellomtiden må du bruke en nettleser som støttes for å se denne historien.", "upgradeBrowser": "<a href='http://browsehappy.com/' target='_blank'>Oppdater webleseren</a>.", "mapLoadingFail": "Noe gikk galt, og kartet ble ikke lastet inn på riktig måte.", "signOut": "Logg ut", "print0": "Beklager, denne fortellingen kan ikke skrives ut.", "print1": "For å skrive ut denne fortellingen bruker du utskriftsknappen i delingsdialogboksen.", "print2": "Beklager, en utskriftsvennlig versjon av fortellingen er vanligvis tilgjengelig gjennom delingsdialogen, men denne dialogen har blitt deaktivert av forfatteren.", "attention": "Obs!" }, "mobileView": { "tapForDetails": "Trykk for å se detaljer", "clickForDetails": "Få mer informasjon", "swipeToExplore": "Sveip for å utforske", "tapForMap": "Trykk for å gå tilbake", "clickForMap": "TILBAKE" }, "floatLayout": { "scroll": "Rull" }, "sideLayout": { "scroll": "Rull nedover for å se mer!" }, "mainStage": { "back": "Tilbake", "errorDeleted": "Denne koblingen er ikke aktiv (seksjonen er slettet)", "errorNotPublished": "Denne koblingen er ikke aktiv (seksjonen er ikke publisert)" }, "headerFromCommon": { "storymapsText": "Et fortellingskart", "builderButton": "Rediger", "facebookTooltip": "Del på Facebook", "twitterTooltip": "Del på Twitter", "bitlyTooltip": "Del eller skriv ut", "templateTitle": "Angi tittel på malen", "templateSubtitle": "Angi undertittel for malen", "share": "Del", "checking": "Kontrollerer historieinnholdet", "fix": "Løs problemer i historien", "noerrors": "Ingen problemer oppdaget", "tooltipAutoplayDisabled": "Dette er ikke tilgjengelig i automatisk avspillingsmodus", "notshared": "Historien er ikke delt" }, "mapFromCommon": { "overview": "Oversiktskart", "legend": "Tegnforklaring", "home": "Zoom hjem" }, "shareFromCommon": { "copy": "Kopier", "copied": "Kopiert", "open": "Åpne", "embed": "Bygg inn på webside", "embedExplain": "Bruk følgende HTML-kode for å bygge inn historien på en webside.", "size": "Størrelse (bredde/høyde):", "autoplayLabel": "Automatisk avspillingsmodus", "autoplayExplain1": "Automatisk avspillingsmodus går videre i historien med gitte intervaller. Dette fungerer utmerket til kiosker eller informasjonsskjermer, men kan i andre situasjoner gjøre det vanskeligere å lese historien. Denne funksjonen støttes ikke på små skjermer.", "autoplayExplain2": "Når denne modusen er aktivert, vises det kontroller for å spille av/pause historien og justere navigeringshastigheten.", "linksupdated": "Koblingene ble oppdatert", "print": "Skriv ut", "printInstruction1": "Vent til hele fortellingen er lastet før du skriver ut", "printInstruction1a": "Hvis det tar lang tid å laste inn denne siden eller visse medier ikke vises, prøver du å skrive ut et mindre antall avsnitt.", "printInstruction1b": "For å får best resultat kan det hende du må aktivere utskrift av bakgrunnselementer i utskriftsalternativene i nettleseren.", "printInstruction2": "Denne siden kan ikke deles med andre, del i stedet koblingen ${link}", "link": "koble til fortellingen", "optionsHeader": "Alternativer", "printOptPageBreak": "Begynn hver del på en ny side", "makeTextBlack": "Gjør all tekst svart", "showLinks": "Vis koblings-URL-er", "madeWith": "Denne fortellingen er laget med ${JOURNAL_LINK_TEXT}.", "journalLinkText": "Esris Story Map Journal", "readItOnline": "Les den interaktive versjonen på nettet på ${link}.", "printMSWarning": "koblingen er bare tilgjengelig i fortellingen på nett", "printVideoWarning": "Denne videoen kan sees i den elektroniske versjonen av dette fortellingskartet", "printRangeHeader": "Skriv ut en del av denne fortellingen", "sectionLabel": "Avsnitt:", "apply": "Bruk", "resetRange": "Tilbakestill hele fortellingen" } } });
Esri/map-journal-storytelling-template-js
src/resources/tpl/viewer/nls/nb/template.js
JavaScript
apache-2.0
7,637
Bridge.merge(new System.Globalization.CultureInfo("kn", true), { englishName: "Kannada", nativeName: "ಕನ್ನಡ", numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), { nanSymbol: "NaN", negativeSign: "-", positiveSign: "+", negativeInfinitySymbol: "-∞", positiveInfinitySymbol: "∞", percentSymbol: "%", percentGroupSizes: [3], percentDecimalDigits: 2, percentDecimalSeparator: ".", percentGroupSeparator: ",", percentPositivePattern: 1, percentNegativePattern: 1, currencySymbol: "₹", currencyGroupSizes: [3,2], currencyDecimalDigits: 2, currencyDecimalSeparator: ".", currencyGroupSeparator: ",", currencyNegativePattern: 12, currencyPositivePattern: 0, numberGroupSizes: [3], numberDecimalDigits: 2, numberDecimalSeparator: ".", numberGroupSeparator: ",", numberNegativePattern: 1 }), dateTimeFormat: Bridge.merge(new System.Globalization.DateTimeFormatInfo(), { abbreviatedDayNames: ["ಭಾನು.","ಸೋಮ.","ಮಂಗಳ.","ಬುಧ.","ಗುರು.","ಶುಕ್ರ.","ಶನಿ."], abbreviatedMonthGenitiveNames: ["ಜನವರಿ","ಫೆಬ್ರವರಿ","ಮಾರ್ಚ್","ಎಪ್ರಿಲ್","ಮೇ","ಜೂನ್","ಜುಲೈ","ಆಗಸ್ಟ್","ಸೆಪ್ಟಂಬರ್","ಅಕ್ಟೋಬರ್","ನವೆಂಬರ್","ಡಿಸೆಂಬರ್",""], abbreviatedMonthNames: ["ಜನವರಿ","ಫೆಬ್ರವರಿ","ಮಾರ್ಚ್","ಎಪ್ರಿಲ್","ಮೇ","ಜೂನ್","ಜುಲೈ","ಆಗಸ್ಟ್","ಸೆಪ್ಟಂಬರ್","ಅಕ್ಟೋಬರ್","ನವೆಂಬರ್","ಡಿಸೆಂಬರ್",""], amDesignator: "ಪೂರ್ವಾಹ್ನ", dateSeparator: "-", dayNames: ["ಭಾನುವಾರ","ಸೋಮವಾರ","ಮಂಗಳವಾರ","ಬುಧವಾರ","ಗುರುವಾರ","ಶುಕ್ರವಾರ","ಶನಿವಾರ"], firstDayOfWeek: 1, fullDateTimePattern: "dd MMMM yyyy HH:mm:ss", longDatePattern: "dd MMMM yyyy", longTimePattern: "HH:mm:ss", monthDayPattern: "MMMM d", monthGenitiveNames: ["ಜನವರಿ","ಫೆಬ್ರವರಿ","ಮಾರ್ಚ್","ಏಪ್ರೀಲ್","ಮೇ","ಜೂನ್","ಜುಲೈ","ಆಗಸ್ಟ್","ಸೆಪ್ಟಂಬರ್","ಅಕ್ಟೋಬರ್","ನವೆಂಬರ್","ಡಿಸೆಂಬರ್",""], monthNames: ["ಜನವರಿ","ಫೆಬ್ರವರಿ","ಮಾರ್ಚ್","ಏಪ್ರೀಲ್","ಮೇ","ಜೂನ್","ಜುಲೈ","ಆಗಸ್ಟ್","ಸೆಪ್ಟಂಬರ್","ಅಕ್ಟೋಬರ್","ನವೆಂಬರ್","ಡಿಸೆಂಬರ್",""], pmDesignator: "ಅಪರಾಹ್ನ", rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", shortDatePattern: "dd-MM-yy", shortestDayNames: ["ರ","ಸ","ಮ","ಬ","ಗ","ಶ","ಶ"], shortTimePattern: "HH:mm", sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", sortableDateTimePattern1: "yyyy'-'MM'-'dd", timeSeparator: ":", universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", yearMonthPattern: "MMMM, yyyy", roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz" }), TextInfo: Bridge.merge(new System.Globalization.TextInfo(), { ANSICodePage: 0, CultureName: "kn-IN", EBCDICCodePage: 500, IsRightToLeft: false, LCID: 1099, listSeparator: ",", MacCodePage: 2, OEMCodePage: 1, IsReadOnly: true }) });
AndreyZM/Bridge
Bridge/Resources/Locales/kn.js
JavaScript
apache-2.0
3,779
'use strict'; innoApp .controller('HeaderCtrl',["$scope", "AuthService", function ($scope,AuthService) { // Fetching role name $scope.role = AuthService.getRole(); //Setting menu for admin and other user dynamic if($scope.role === "admin"){ $scope.menu = [ { name: 'user'}, { name: 'role'} ]; } }]);
riyazbhanvadia/Angular-base-structure
inno/app/lucius/common/controller/header.js
JavaScript
apache-2.0
353
var utils = require('enyo/utils'), kind = require('enyo/kind'); describe('language', function () { describe('usage', function () { describe('Callee', function () { var dn = ''; var fn = function() { dn = arguments.callee.displayName; }; it('should have proper callee', function () { fn.displayName = "fn"; fn(); expect(dn).to.equal('fn') }); }); describe('Class', function () { var AClass; before(function () { AClass = kind({ name: "AClass" }); }); after(function () { AClass = null; }); it('should be a function', function () { expect(AClass).to.be.a('function') }); }); describe('isString', function () { var iframe; before(function () { var iframeDoc; // Create alternate window context to write vars from iframe = document.createElement("iframe"), document.body.appendChild(iframe); iframeDoc = iframe.contentDocument || iframe.contentWindow.document; iframeDoc.write("<script>parent.iString = new String('hello');</script>"); iframeDoc.close(); }); after(function () { document.body.removeChild(iframe); iframe = null; }); it('should determine strings properly', function () { expect(utils.isString("string")).to.be.true; }); // This will fail: // - instanceof from another context // - typeof (b/c it is a string instance) // https://github.com/enyojs/enyo/issues/2 /* global iString */ it('should determine strings written from other window contexts correctly', function () { expect(utils.isString(iString)).to.be.true; }); }); describe('indexOf', function () { it('should have proper index', function () { var index = utils.indexOf("foo", [null, null, null, null,"foo"]); expect(index).to.equal(4) }); }); describe('indexOf greater than array length', function () { it('should equal -1', function () { var index = utils.indexOf("foo", [null, null, null, null,"foo"], 10); expect(index).to.equal(-1) }); }); describe('AsyncMethod', function () { var timesCalled; before(function () { timesCalled = 0; }); it('should be called twice', function (done) { utils.asyncMethod(function () { timesCalled++; }); utils.asyncMethod(this, function (i) { timesCalled += i; }, 1); setTimeout(function() { expect(timesCalled).to.equal(2) done(); }, 25); }); }); describe('isObject', function () { it('should be true that an object is an object', function () { expect(utils.isObject({})).to.be.true }); it('should not be true that undefined is an object', function () { expect(utils.isObject(undefined)).to.be.false }); it('should not be true that null is an object', function () { expect(utils.isObject(null)).to.be.false }); it('should not be true that an array is an object', function () { expect(utils.isObject([1,2,3])).to.be.false }); it('should not be true that a number is an object', function () { expect(utils.isObject(42)).to.be.false }); it('should not be true that a string is an object', function () { expect(utils.isObject("forty-two")).to.be.false }); }); describe('isArray', function () { it('should not be true that an object is an array', function () { expect(utils.isArray({})).to.be.false }); it('should not be true that undefined is an array', function () { expect(utils.isArray(undefined)).to.be.false }); it('should not be true that null is an array', function () { expect(utils.isArray(null)).to.be.false }); it('should be true that an array is an array', function () { expect(utils.isArray([1,2,3])).to.be.true }); it('should not be true that a number is an array', function () { expect(utils.isArray(42)).to.be.false }); it('should not be true that a string is an array', function () { expect(utils.isArray("forty-two")).to.be.false }); }); }); });
enyojs/enyo
test/tests/lang.js
JavaScript
apache-2.0
3,991
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!*************************************!*\ !*** ./loaders/css-loader/index.js ***! \*************************************/ /***/ function(module, exports, __webpack_require__) { it("should handle the css loader correctly", function() { (__webpack_require__(/*! css!../_css/stylesheet.css */ 1) + "").indexOf(".rule-direct").should.not.be.eql(-1); (__webpack_require__(/*! css!../_css/stylesheet.css */ 1) + "").indexOf(".rule-import1").should.not.be.eql(-1); (__webpack_require__(/*! css!../_css/stylesheet.css */ 1) + "").indexOf(".rule-import2").should.not.be.eql(-1); }); /***/ }, /* 1 */ /*!************************************************************!*\ !*** (webpack)/~/css-loader!./loaders/_css/stylesheet.css ***! \************************************************************/ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! (webpack)/~/css-loader/cssToString.js */ 2)(); __webpack_require__(/*! (webpack)/~/css-loader/mergeImport.js */ 3)(exports, __webpack_require__(/*! -!(webpack)/~/css-loader!./folder/stylesheet-import1.css */ 4), ""); exports.push([module.id, "\r\n\r\n.rule-direct {\r\n\tbackground: lightgreen;\r\n}", ""]); /***/ }, /* 2 */ /*!*********************************************!*\ !*** (webpack)/~/css-loader/cssToString.js ***! \*********************************************/ /***/ function(module, exports, __webpack_require__) { module.exports = function() { var list = []; list.toString = function toString() { var result = []; for(var i = 0; i < this.length; i++) { var item = this[i]; if(item[2]) { result.push("@media " + item[2] + "{" + item[1] + "}"); } else { result.push(item[1]); } } return result.join(""); }; return list; } /***/ }, /* 3 */ /*!*********************************************!*\ !*** (webpack)/~/css-loader/mergeImport.js ***! \*********************************************/ /***/ function(module, exports, __webpack_require__) { module.exports = function(list, importedList, media) { for(var i = 0; i < importedList.length; i++) { var item = importedList[i]; if(media && !item[2]) item[2] = media; else if(media) { item[2] = "(" + item[2] + ") and (" + media + ")"; } list.push(item); } }; /***/ }, /* 4 */ /*!***************************************************************************!*\ !*** (webpack)/~/css-loader!./loaders/_css/folder/stylesheet-import1.css ***! \***************************************************************************/ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! (webpack)/~/css-loader/cssToString.js */ 2)(); __webpack_require__(/*! (webpack)/~/css-loader/mergeImport.js */ 3)(exports, __webpack_require__(/*! -!(webpack)/~/css-loader!resources-module/stylesheet-import2.css */ 6), "print, screen"); __webpack_require__(/*! (webpack)/~/css-loader/mergeImport.js */ 3)(exports, __webpack_require__(/*! -!(webpack)/~/css-loader!./stylesheet-import3.css */ 5), "print and screen"); exports.push([module.id, "\r\n\r\n\r\n.rule-import1 {\r\n\tbackground: lightgreen;\r\n}\r\n", ""]); /***/ }, /* 5 */ /*!***************************************************************************!*\ !*** (webpack)/~/css-loader!./loaders/_css/folder/stylesheet-import3.css ***! \***************************************************************************/ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! (webpack)/~/css-loader/cssToString.js */ 2)(); exports.push([module.id, ".rule-import2 {\r\n\tbackground: red !important;\r\n}", ""]); /***/ }, /* 6 */ /*!***************************************************************************************!*\ !*** (webpack)/~/css-loader!./loaders/_css/~/resources-module/stylesheet-import2.css ***! \***************************************************************************************/ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! (webpack)/~/css-loader/cssToString.js */ 2)(); exports.push([module.id, ".rule-import2 {\r\n\tbackground: lightgreen;\r\n}", ""]); /***/ } /******/ ])
raml-org/raml-dotnet-parser-2
source/Raml.Parser/node_modules/raml-1-0-parser/node_modules/webpack/test/js/normal/loaders/css-loader/bundle.js
JavaScript
apache-2.0
5,685
/*+*********************************************************************************** * The contents of this file are subject to the vtiger CRM Public License Version 1.0 * ("License"); You may not use this file except in compliance with the License * The Original Code is: vtiger CRM Open Source * The Initial Developer of the Original Code is vtiger. * Portions created by vtiger are Copyright (C) vtiger. * All Rights Reserved. *************************************************************************************/ var Settings_Picklist_Js = { registerModuleChangeEvent : function() { jQuery('#pickListModules').on('change',function(e){ var element = jQuery(e.currentTarget); var selectedModule = jQuery(e.currentTarget).val(); if(selectedModule.length <= 0) { Settings_Vtiger_Index_Js.showMessage({'type': 'error','text':app.vtranslate('JS_PLEASE_SELECT_MODULE')}); return; } var params = { module : app.getModuleName(), parent : app.getParentModuleName(), source_module : selectedModule, view : 'IndexAjax', mode : 'getPickListDetailsForModule' } var progressIndicatorElement = jQuery.progressIndicator({ 'position' : 'html', 'blockInfo' : { 'enabled' : true } }); AppConnector.request(params).then(function(data){ jQuery('#modulePickListContainer').html(data); progressIndicatorElement.progressIndicator({'mode':'hide'}); app.changeSelectElementView(jQuery('#modulePickListContainer')); Settings_Picklist_Js.registerModulePickListChangeEvent(); jQuery('#modulePickList').trigger('change'); }); }); }, registerModulePickListChangeEvent : function() { jQuery('#modulePickList').on('change',function(e){ var params = { module : app.getModuleName(), parent : app.getParentModuleName(), source_module : jQuery('#pickListModules').val(), view : 'IndexAjax', mode : 'getPickListValueForField', pickListFieldId : jQuery(e.currentTarget).val() } var progressIndicatorElement = jQuery.progressIndicator({ 'position' : 'html', 'blockInfo' : { 'enabled' : true } }); AppConnector.request(params).then(function(data){ jQuery('#modulePickListValuesContainer').html(data); app.showSelect2ElementView(jQuery('#rolesList')); Settings_Picklist_Js.registerItemActions(); progressIndicatorElement.progressIndicator({'mode':'hide'}); }) }) }, registerAddItemEvent : function() { jQuery('#addItem').on('click',function(e){ var data = jQuery('#createViewContents').find('.modal'); var clonedCreateView = data.clone(true,true).removeClass('basicCreateView').addClass('createView'); clonedCreateView.find('.rolesList').addClass('select2'); var callBackFunction = function(data) { jQuery('[name="addItemForm"]',data).validationEngine(); Settings_Picklist_Js.registerAddItemSaveEvent(data); Settings_Picklist_Js.regiserSelectRolesEvent(data); } app.showModalWindow(clonedCreateView, function(data) { if(typeof callBackFunction == 'function') { callBackFunction(data); } }); }); }, registerAssingValueToRuleEvent : function() { jQuery('#assignValue').on('click',function() { var pickListValuesTable = jQuery('#pickListValuesTable'); var selectedListItem = jQuery('.selectedListItem',pickListValuesTable); if(selectedListItem.length > 0) { var selectedValues = []; jQuery.each(selectedListItem,function(i,element) { selectedValues.push(jQuery(element).closest('tr').data('key')); }); } var params = { module : app.getModuleName(), parent : app.getParentModuleName(), source_module : jQuery('#pickListModules').val(), view : 'IndexAjax', mode : 'showAssignValueToRoleView', pickListFieldId : jQuery('#modulePickList').val() } AppConnector.request(params).then(function(data) { app.showModalWindow(data); jQuery('[name="addItemForm"]',jQuery(data)).validationEngine(); Settings_Picklist_Js.registerAssignValueToRoleSaveEvent(jQuery(data)); if(selectedListItem.length > 0) { jQuery('[name="assign_values[]"]',jQuery('#assignValueToRoleForm')).select2('val',selectedValues); } }); }); }, registerAssignValueToRoleSaveEvent : function(data) { jQuery('#assignValueToRoleForm').on('submit',function(e) { var form = jQuery(e.currentTarget); var assignValuesSelectElement = jQuery('[name="assign_values[]"]',form); var assignValuesSelect2Element = app.getSelect2ElementFromSelect(assignValuesSelectElement); var assignValueResult = Vtiger_MultiSelect_Validator_Js.invokeValidation(assignValuesSelectElement); if(assignValueResult != true){ assignValuesSelect2Element.validationEngine('showPrompt', assignValueResult , 'error','topLeft',true); } else { assignValuesSelect2Element.validationEngine('hide'); } var rolesSelectElement = jQuery('[name="rolesSelected[]"]',form); var select2Element = app.getSelect2ElementFromSelect(rolesSelectElement); var result = Vtiger_MultiSelect_Validator_Js.invokeValidation(rolesSelectElement); if(result != true){ select2Element.validationEngine('showPrompt', result , 'error','bottomLeft',true); } else { select2Element.validationEngine('hide'); } if(assignValueResult != true || result != true) { e.preventDefault(); return; } else { form.find('[name="saveButton"]').attr('disabled',"disabled"); } var params = jQuery(e.currentTarget).serializeFormData(); AppConnector.request(params).then(function(data) { if(typeof data.result != 'undefined') { app.hideModalWindow(); Settings_Vtiger_Index_Js.showMessage({text:app.vtranslate('JS_VALUE_ASSIGNED_SUCCESSFULLY'),type : 'success'}) } }); e.preventDefault(); }); }, registerEnablePickListValueClickEvent : function() { jQuery('#listViewContents').on('click','.assignToRolePickListValue',function(e) { jQuery('#saveOrder').removeAttr('disabled'); var pickListVaue = jQuery(e.currentTarget) if(pickListVaue.hasClass('selectedCell')) { pickListVaue.removeClass('selectedCell').addClass('unselectedCell'); pickListVaue.find('.icon-ok').remove(); } else { pickListVaue.removeClass('unselectedCell').addClass('selectedCell'); pickListVaue.prepend('<i class="icon-ok pull-left"></i>'); } }); }, registerenableOrDisableListSaveEvent : function() { jQuery('#saveOrder').on('click',function(e) { var progressIndicatorElement = jQuery.progressIndicator({ 'position' : 'html', 'blockInfo' : { 'enabled' : true, 'elementToBlock' : jQuery('.tab-content') } }); var pickListValues = jQuery('.assignToRolePickListValue'); var disabledValues = []; var enabledValues = []; jQuery.each(pickListValues,function(i,element) { var currentValue = jQuery(element); if(currentValue.hasClass('selectedCell')){ enabledValues.push(currentValue.data('value')); } else { disabledValues.push(currentValue.data('value')); } }); var params = { module : app.getModuleName(), parent : app.getParentModuleName(), action : 'SaveAjax', mode : 'enableOrDisable', enabled_values : enabledValues, disabled_values : disabledValues, picklistName : jQuery('[name="picklistName"]').val(), rolesSelected : jQuery('#rolesList').val() } AppConnector.request(params).then(function(data) { if(typeof data.result != 'undefined') { jQuery(e.currentTarget).attr('disabled','disabled'); progressIndicatorElement.progressIndicator({mode : 'hide'}); Settings_Vtiger_Index_Js.showMessage({text:app.vtranslate('JS_LIST_UPDATED_SUCCESSFULLY'),type : 'success'}) } }); }); }, regiserSelectRolesEvent : function(data) { data.find('[name="rolesSelected[]"]').on('change',function(e) { var rolesSelectElement = jQuery(e.currentTarget); var selectedValue = rolesSelectElement.val(); if(jQuery.inArray('all', selectedValue) != -1){ rolesSelectElement.select2("val", ""); rolesSelectElement.select2("val","all"); rolesSelectElement.select2("close"); rolesSelectElement.find('option').not(':first').attr('disabled','disabled'); data.find(jQuery('.modal-body')).append('<div class="alert alert-info textAlignCenter">'+app.vtranslate('JS_ALL_ROLES_SELECTED')+'</div>') } else { rolesSelectElement.find('option').removeAttr('disabled','disabled'); data.find('.modal-body').find('.alert').remove(); } }); }, registerRenameItemEvent : function() { var thisInstance = this; jQuery('#renameItem').on('click',function(e){ var pickListValuesTable = jQuery('#pickListValuesTable'); var selectedListItem = jQuery('.selectedListItem',pickListValuesTable); var selectedListItemLength = selectedListItem.length; if(selectedListItemLength > 1) { var params = { title : app.vtranslate('JS_MESSAGE'), text: app.vtranslate('JS_MORE_THAN_ONE_ITEM_SELECTED'), animation: 'show', type: 'error' }; Vtiger_Helper_Js.showPnotify(params); return; } else{ var params = { module : app.getModuleName(), parent : app.getParentModuleName(), source_module : jQuery('#pickListModules').val(), view : 'IndexAjax', mode : 'showEditView', pickListFieldId : jQuery('#modulePickList').val(), fieldValue : selectedListItem.closest('tr').data('key') } AppConnector.request(params).then(function(data){ app.showModalWindow(data); var form = jQuery('#renameItemForm'); thisInstance.registerScrollForNonEditablePicklistValues(form); form.validationEngine(); Settings_Picklist_Js.registerRenameItemSaveEvent(); }); } }); }, /** * Function to register the scroll bar for NonEditable Picklist Values */ registerScrollForNonEditablePicklistValues : function(container) { jQuery(container).find('.nonEditablePicklistValues').slimScroll({ height: '70px', size: '6px' }); }, registerDeleteItemEvent : function() { var thisInstance = this; jQuery('#deleteItem').on('click',function(e){ var pickListValuesTable = jQuery('#pickListValuesTable'); var selectedListItem = jQuery('.selectedListItem',pickListValuesTable); var selectedListItemsArray = new Array(); jQuery.each(selectedListItem,function(index,element){ selectedListItemsArray.push(jQuery(element).closest('tr').data('key')); }) var pickListValues = jQuery('.pickListValue',pickListValuesTable); if(pickListValues.length == selectedListItem.length) { Settings_Vtiger_Index_Js.showMessage({text:app.vtranslate('JS_YOU_CANNOT_DELETE_ALL_THE_VALUES'),type : 'error'}) return; } var params = { module : app.getModuleName(), parent : app.getParentModuleName(), source_module : jQuery('#pickListModules').val(), view : 'IndexAjax', mode : 'showDeleteView', pickListFieldId : jQuery('#modulePickList').val(), fieldValue : JSON.stringify(selectedListItemsArray) } thisInstance.showDeleteItemForm(params); }); }, registerDeleteOptionEvent : function() { function result(value) { var replaceValueElement = jQuery('#replaceValue'); if(typeof value.added != 'undefined'){ var id = value.added.id; jQuery('#replaceValue option[value="'+id+'"]').remove(); replaceValueElement.trigger('liszt:updated'); } else { var id = value.removed.id; var text = value.removed.text; replaceValueElement.append('<option value="'+id+'">'+text+'</option>'); replaceValueElement.trigger('liszt:updated'); } } jQuery('[name="delete_value[]"]').on("change", function(e) { result({ val:e.val, added:e.added, removed:e.removed }); }) }, duplicateItemNameCheck : function(container) { var pickListValues = JSON.parse(jQuery('[name="pickListValues"]',container).val()); var pickListValuesArr = new Array(); jQuery.each(pickListValues,function(i,e){ var decodedValue = app.getDecodedValue(e); pickListValuesArr.push(jQuery.trim(decodedValue.toLowerCase())); }); var mode = jQuery('[name="mode"]', container).val(); var newValue = jQuery.trim(jQuery('[name="newValue"]',container).val()); var lowerCasedNewValue = newValue.toLowerCase(); //Checking the new picklist value is already exists if(jQuery.inArray(lowerCasedNewValue,pickListValuesArr) != -1){ //while renaming the picklist values if(mode == 'rename') { var oldValue = jQuery.trim(jQuery('[name="oldValue"]',container).val()); var lowerCasedOldValue = oldValue.toLowerCase(); //allow to rename when the new value should not be same as old value and the new value only with case diffrence if(oldValue != newValue && lowerCasedOldValue == lowerCasedNewValue) { return false; } } //while adding or renaming with different existing value return true; } else { return false; } }, registerChangeRoleEvent : function() { jQuery('#rolesList').on('change',function(e) { var progressIndicatorElement = jQuery.progressIndicator({ 'position' : 'html', 'blockInfo' : { 'enabled' : true, 'elementToBlock' : jQuery('.tab-content') } }); var rolesList = jQuery(e.currentTarget); var params = { module : app.getModuleName(), parent : app.getParentModuleName(), view : 'IndexAjax', mode : 'getPickListValueByRole', rolesSelected : rolesList.val(), pickListFieldId : jQuery('#modulePickList').val() } AppConnector.request(params).then(function(data) { jQuery('#pickListValeByRoleContainer').html(data); Settings_Picklist_Js.registerenableOrDisableListSaveEvent(); progressIndicatorElement.progressIndicator({mode : 'hide'}); }); }) }, registerAddItemSaveEvent : function(container) { container.find('[name="addItemForm"]').on('submit',function(e){ var form = jQuery(e.currentTarget); var validationResult = form.validationEngine('validate'); if(validationResult == true) { var duplicateCheckResult = Settings_Picklist_Js.duplicateItemNameCheck(container); if(duplicateCheckResult == true) { var errorMessage = app.vtranslate('JS_DUPLIACATE_ENTRIES_FOUND_FOR_THE_VALUE'); var newValueEle = jQuery('[name="newValue"]',container); var newValue = newValueEle.val(); newValueEle.validationEngine('showPrompt', errorMessage+' '+'"'+newValue+'"' , 'error','bottomLeft',true); e.preventDefault(); return; } var invalidFields = form.data('jqv').InvalidFields; if(invalidFields.length == 0){ form.find('[name="saveButton"]').attr('disabled',"disabled"); } var params = jQuery(e.currentTarget).serializeFormData(); var newValue = params.newValue; params.newValue = jQuery.trim(newValue); AppConnector.request(params).then(function(data) { var newValue = jQuery.trim(jQuery('[name="newValue"]',container).val()); var dragImagePath = jQuery('#dragImagePath').val(); var newElement = '<tr class="pickListValue cursorPointer"><td class="textOverflowEllipsis"><img class="alignMiddle" src="'+dragImagePath+'" />&nbsp;&nbsp;'+newValue+'</td></tr>'; var newPickListValueRow = jQuery(newElement).appendTo(jQuery('#pickListValuesTable').find('tbody')); newPickListValueRow.attr('data-key',newValue); app.hideModalWindow(); var params = { title : app.vtranslate('JS_MESSAGE'), text: app.vtranslate('JS_ITEM_ADDED_SUCCESSFULLY'), animation: 'show', type: 'success' }; Vtiger_Helper_Js.showPnotify(params); //update the new item in the hidden picklist values array var pickListValuesEle = jQuery('[name="pickListValues"]'); var pickListValuesArray = JSON.parse(pickListValuesEle.val()); pickListValuesArray.push(newValue); pickListValuesEle.val(JSON.stringify(pickListValuesArray)); }); } e.preventDefault(); }); }, registerRenameItemSaveEvent : function() { jQuery('#renameItemForm').on('submit',function(e) { var form = jQuery(e.currentTarget); var validationResult = form.validationEngine('validate'); if(validationResult == true) { var duplicateCheckResult = Settings_Picklist_Js.duplicateItemNameCheck(form); var newValueEle = jQuery('[name="newValue"]',form); var newValue = jQuery.trim(newValueEle.val()); if(duplicateCheckResult == true) { var errorMessage = app.vtranslate('JS_DUPLIACATE_ENTRIES_FOUND_FOR_THE_VALUE'); newValueEle.validationEngine('showPrompt', errorMessage+' '+'"'+newValue+'"' , 'error','bottomLeft',true); e.preventDefault(); return; } var oldValue = jQuery('[name="oldValue"]',form).val(); var params = jQuery(e.currentTarget).serializeFormData(); params.newValue = newValue; var invalidFields = form.data('jqv').InvalidFields; if(invalidFields.length == 0){ form.find('[name="saveButton"]').attr('disabled',"disabled"); } AppConnector.request(params).then(function(data) { if(typeof data.result != 'undefined'){ app.hideModalWindow(); var encodedOldValue = oldValue.replace(/"/g, '\\"'); var dragImagePath = jQuery('#dragImagePath').val(); var renamedElement = '<tr class="pickListValue cursorPointer"><td class="textOverflowEllipsis"><img class="alignMiddle" src="'+dragImagePath+'" />&nbsp;&nbsp;'+newValue+'</td></tr>'; var renamedElement = jQuery(renamedElement).attr('data-key',newValue); jQuery('[data-key="'+encodedOldValue+'"]').replaceWith(renamedElement) var params = { title : app.vtranslate('JS_MESSAGE'), text: app.vtranslate('JS_ITEM_RENAMED_SUCCESSFULLY'), animation: 'show', type: 'success' }; Vtiger_Helper_Js.showPnotify(params); //update the new item in the hidden picklist values array var pickListValuesEle = jQuery('[name="pickListValues"]'); var pickListValuesArray = JSON.parse(pickListValuesEle.val()); var index = pickListValuesArray.indexOf(oldValue); pickListValuesArray.splice(index, 1); pickListValuesArray.push(newValueEle.val()); pickListValuesEle.val(JSON.stringify(pickListValuesArray)); } }); } e.preventDefault(); }); }, showDeleteItemForm : function(params) { var thisInstance = this; AppConnector.request(params).then(function(data){ app.showModalWindow(data, function(data) { if(typeof callBackFunction == 'function') { callBackFunction(data); } }); }); var callBackFunction = function(data) { var form = data.find('#deleteItemForm'); thisInstance.registerScrollForNonEditablePicklistValues(form); var maximumSelectionSize = jQuery('#pickListValuesCount').val()-1; app.changeSelectElementView(jQuery('[name="delete_value[]"]'), 'select2', {maximumSelectionSize: maximumSelectionSize,dropdownCss : {'z-index' : 100001}}); Settings_Picklist_Js.registerDeleteOptionEvent(); var params = app.getvalidationEngineOptions(true); params.onValidationComplete = function(form, valid){ if(valid) { var selectElement = jQuery('[name="delete_value[]"]'); var select2Element = app.getSelect2ElementFromSelect(selectElement); var result = Vtiger_MultiSelect_Validator_Js.invokeValidation(selectElement); if(result != true){ select2Element.validationEngine('showPrompt', result , 'error','topLeft',true); e.preventDefault(); return; } else { select2Element.validationEngine('hide'); form.find('[name="saveButton"]').attr('disabled',"disabled"); } var deleteValues = jQuery('[name="delete_value[]"]').val(); var params = form.serializeFormData(); AppConnector.request(params).then(function(data) { if(typeof data.result != 'undefined'){ app.hideModalWindow(); //delete the item in the hidden picklist values array var pickListValuesEle = jQuery('[name="pickListValues"]'); var pickListValuesArray = JSON.parse(pickListValuesEle.val()); jQuery.each(deleteValues,function(i,e){ var encodedOldValue = e.replace(/"/g, '\\"'); jQuery('[data-key="'+encodedOldValue+'"]').remove(); var index = pickListValuesArray.indexOf(e); pickListValuesArray.splice(index, 1); }); pickListValuesEle.val(JSON.stringify(pickListValuesArray)); var params = { title : app.vtranslate('JS_MESSAGE'), text: app.vtranslate('JS_ITEMS_DELETED_SUCCESSFULLY'), animation: 'show', type: 'success' }; Vtiger_Helper_Js.showPnotify(params); } }); } return false; } form.validationEngine(params); } }, registerSelectPickListValueEvent : function() { jQuery("#pickListValuesTable").on('click','.pickListValue',function(event) { var currentRow = jQuery(event.currentTarget); var currentRowTd = currentRow.find('td'); event.preventDefault(); if(event.ctrlKey) { currentRowTd.toggleClass('selectedListItem'); } else { jQuery(".pickListValue").find('td').not(currentRowTd).removeClass("selectedListItem"); currentRowTd.toggleClass('selectedListItem'); } }); }, registerPickListValuesSortableEvent : function() { var tbody = jQuery( "tbody",jQuery('#pickListValuesTable')); tbody.sortable({ 'helper' : function(e,ui){ //while dragging helper elements td element will take width as contents width //so we are explicity saying that it has to be same width so that element will not //look like distrubed ui.children().each(function(index,element){ element = jQuery(element); element.width(element.width()); }) return ui; }, 'containment' : tbody, 'revert' : true, update: function(e, ui ) { jQuery('#saveSequence').removeAttr('disabled'); } }); }, registerSaveSequenceClickEvent : function() { jQuery('#saveSequence').on('click',function(e) { var progressIndicatorElement = jQuery.progressIndicator({ 'position' : 'html', 'blockInfo' : { 'enabled' : true, 'elementToBlock' : jQuery('.tab-content') } }); var pickListValuesSequenceArray = {} var pickListValues = jQuery('#pickListValuesTable').find('.pickListValue'); jQuery.each(pickListValues,function(i,element) { pickListValuesSequenceArray[jQuery(element).data('key')] = ++i; }); var params = { module : app.getModuleName(), parent : app.getParentModuleName(), action : 'SaveAjax', mode : 'saveOrder', picklistValues : pickListValuesSequenceArray, picklistName : jQuery('[name="picklistName"]').val() } AppConnector.request(params).then(function(data) { if(typeof data.result != 'undefined') { jQuery('#saveSequence').attr('disabled','disabled'); progressIndicatorElement.progressIndicator({mode : 'hide'}); Settings_Vtiger_Index_Js.showMessage({text:app.vtranslate('JS_SEQUENCE_UPDATED_SUCCESSFULLY'),type : 'success'}) } }); }); }, registerAssingValueToRoleTabClickEvent : function() { jQuery('#assignedToRoleTab').on('click',function(e) { jQuery('#rolesList').trigger('change'); }); }, registerItemActions : function() { Settings_Picklist_Js.registerAddItemEvent(); Settings_Picklist_Js.registerRenameItemEvent(); Settings_Picklist_Js.registerDeleteItemEvent(); Settings_Picklist_Js.registerSelectPickListValueEvent(); Settings_Picklist_Js.registerAssingValueToRuleEvent(); Settings_Picklist_Js.registerChangeRoleEvent(); Settings_Picklist_Js.registerAssingValueToRoleTabClickEvent(); Settings_Picklist_Js.registerPickListValuesSortableEvent(); Settings_Picklist_Js.registerSaveSequenceClickEvent(); }, registerEvents : function() { Settings_Picklist_Js.registerModuleChangeEvent(); Settings_Picklist_Js.registerModulePickListChangeEvent(); Settings_Picklist_Js.registerItemActions(); Settings_Picklist_Js.registerEnablePickListValueClickEvent(); } } jQuery(document).ready(function(){ Settings_Picklist_Js.registerEvents(); }) Vtiger_Base_Validator_Js("Vtiger_FieldLabel_Validator_Js",{ /** *Function which invokes field validation *@param accepts field element as parameter * @return error if validation fails true on success */ invokeValidation: function(field, rules, i, options){ var instance = new Vtiger_FieldLabel_Validator_Js(); instance.setElement(field); var response = instance.validate(); if(response != true){ return instance.getError(); } } },{ /** * Function to validate the field label * @return true if validation is successfull * @return false if validation error occurs */ validate: function(){ var fieldValue = this.getFieldValue(); return this.validateValue(fieldValue); }, validateValue : function(fieldValue){ var specialChars = /[<\>\"]/ ; if (specialChars.test(fieldValue)) { var errorInfo = app.vtranslate('JS_SPECIAL_CHARACTERS')+" < > \" "+app.vtranslate('JS_NOT_ALLOWED'); this.setError(errorInfo); return false; } return true; } });
gdbhosale/vtigerTemplate
isleenlayout/modules/Settings/Picklist/resources/Picklist.js
JavaScript
apache-2.0
25,072
'use strict' // dependencies var path = require('path'), request = require('request'), // container connections ccs = []; // function to get all containers function GetAllContainers(host, func) { request({ json: true, method: 'GET', uri: host + '/containers/json' }, function (err, resp, body) { var containers = []; if (err) { return func(err, containers); } if (resp.statusCode != 200) { return func(new Error("Status from server was: " + resp.statusCode), containers); } if (body.length <= 0) { return func(new Error("You have no containers currently.", containers)) } body.forEach(function(el) { containers.push(el) }); return func(err, containers); }); }; function GetStats(host, containerID, statsCB) { ccs.map(function(e){ e.destroy(); ccs.pop(); }) ccs.push(request({ json: true, method: 'GET', uri: host + '/containers/' + containerID + '/stats' }) .on('data', function(data){ statsCB(JSON.parse(data)) })) }; exports.GetAllContainers = GetAllContainers; exports.GetStats = GetStats;
elgalu/docker-mon
utils/index.js
JavaScript
apache-2.0
1,264
// InstrumentClone.js // // Copyright 2018 High Fidelity, Inc. // Created by Robin Wilson 7/5/2018 // Expands on guitarMexico.js created by Rebecca Stankus 01/31/18 // // Entity script that plays the sound while holding the entity. // Chooses the sound bite randomly from a list passed in. // Takes two parameters : // musicURLs - list of relative music urls // audioVolumeLevel - sets the magnitude of the sounds defaults to 0.3 // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html /* global module */ var NO_HANDS = 0; var ONE_HAND = 1; var BOTH_HANDS = 2; var LIFETIME_ON_PICKUP = 18; var LIFETIME_ON_RELEASE = 8; var SECS_TO_MS = 1000; var UPDATE_POSITION_MS = 50; var FIRST_LOAD_TIMEOUT = 50; var DEFAULT_VOLUME_LEVEL = 0.1; var DEBUG = false; var InstrumentClone = function (musicURLs, audioVolumeLevel) { this.musicURLs = musicURLs; this.audioVolumeLevel = audioVolumeLevel || DEFAULT_VOLUME_LEVEL; this.injector = null; this.playing = false; this.sounds = []; this.firstLoad = true; this.handNum = 0; this.updatePositionInterval = null; this.currentPosition; }; InstrumentClone.prototype = { // ENTITY METHODS preload: function (entityID) { this.entityID = entityID; var entityProperties = Entities.getEntityProperties(this.entityID, ["position", "name", "age"]); this.currentPosition = entityProperties.position; this.handNum = 0; Script.setTimeout(function(){ if (entityProperties.name && entityProperties.name.indexOf("clone") !== -1){ if (DEBUG) { print("Instrument clone: preload edit lifetime ", entityProperties.name); } Entities.editEntity(this.entityID, { lifetime: entityProperties.age + LIFETIME_ON_PICKUP }); } }, FIRST_LOAD_TIMEOUT); this.loadSounds(); }, startNearGrab: function (thisEntity, otherEntity, collision) { if (DEBUG) { print("Instrument clone: Start near grab"); } if (this.handNum === NO_HANDS) { this.handNum = ONE_HAND; } else { this.handNum = BOTH_HANDS; } var age = Entities.getEntityProperties(this.entityID, "age").age; Entities.editEntity(this.entityID, { lifetime: age + LIFETIME_ON_PICKUP }); this.startSound(); }, releaseGrab: function () { if (DEBUG) { print("Instrument clone: release grab"); } if (this.handNum === BOTH_HANDS) { this.handNum = ONE_HAND; } else { this.stopSound(); var age = Entities.getEntityProperties(this.entityID, "age").age; Entities.editEntity(this.entityID, { lifetime: age + LIFETIME_ON_RELEASE }); this.handNum = NO_HANDS; } }, // clickReleaseOnEntity: function (entityID, mouseEvent) { // if (mouseEvent.isLeftButton) { // if (!this.playing) { // this.startSound(); // } else { // this.stopSound(); // } // } // }, unload: function () { this.stopSound(); this.handNum = NO_HANDS; }, // END ENTITY METHODS // SOUND UTILITIES loadSounds: function () { if (DEBUG) { print("Instrument clone: load sounds ", JSON.stringify(this.musicURLs)); } var _this = this; this.musicURLs.forEach(function (soundURL, idx) { _this.sounds[idx] = SoundCache.getSound(Script.resolvePath(soundURL)); }); this.firstLoad = true; if (DEBUG) { print("Instrument clone: Sounds are:", JSON.stringify(this.sounds)); } }, startSound: function () { var _this = this; if (DEBUG) { print("Instrument clone: Start sound, first load is ", this.firstLoad); } if (this.firstLoad) { // Give time to ensure random sound is downloaded on first pickup Script.setTimeout(function () { _this.playSound(); }, FIRST_LOAD_TIMEOUT); this.firstLoad = false; } else { this.playSound(); } }, getRandomSound: function () { var randSound = this.sounds[Math.floor(Math.random() * this.sounds.length)]; return randSound; }, playSound: function () { var _this = this; var sound = this.getRandomSound(); if (DEBUG) { print("Instrument clone: isPlaying ", !this.playing, " soundDownloaded", sound.downloaded); print("Instrument clone: Random soung ", JSON.stringify(sound)); } if (!this.playing && sound.downloaded) { var position = Entities.getEntityProperties(this.entityID, 'position').position; // Play sound this.injector = Audio.playSound(sound, { position: position, inputVolume: _this.audioVolumeLevel }); this.playing = true; var injector = this.injector; var entityID = this.entityID; // Update sound position using interval this.updatePositionInterval = Script.setInterval(function () { var position = Entities.getEntityProperties(entityID, 'position').position; injector.options = { position: position }; }, UPDATE_POSITION_MS); // length of sound timeout var soundLength = sound.duration * SECS_TO_MS; Script.setTimeout(function () { if (_this.playing) { _this.stopSound(); } }, soundLength); } }, stopSound: function () { if (DEBUG) { print("Instrument clone: stop sound"); } this.playing = false; if (this.injector) { this.injector.stop(); this.injector = null; } if (this.updatePositionInterval) { Script.clearInterval(this.updatePositionInterval); this.updatePositionInterval = null; } } // END SOUND UTILITIES }; module.exports = { instrumentClone: InstrumentClone };
RebeccaStankus/hifi-content
DomainContent/Korea/Instruments/InstrumentClone.js
JavaScript
apache-2.0
6,371
/** * Convenient Redis Storage mock for testing purposes */ var util = require ('util'); function StorageMocked(data){ data = data || {}; this.currentOutage = data.currentOutage; } exports = module.exports = StorageMocked; StorageMocked.prototype.startOutage = function (service, outageData, callback) { this.currentOutage = outageData; setImmediate(function(){ callback(null); }); }; StorageMocked.prototype.getCurrentOutage = function (service, callback) { var self = this; setImmediate(function(){ callback(null, self.currentOutage); }); }; StorageMocked.prototype.saveLatency = function (service, timestamp, latency, callback) { setImmediate(function(){ callback(null); }); }; StorageMocked.prototype.archiveCurrentOutageIfExists = function (service, callback) { var self = this; setImmediate(function(){ callback(null, self.currentOutage); }); }; StorageMocked.prototype.flush_database = function (callback){ setImmediate(function(){ callback(null); }); };
metao1/WatchSite
test/lib/mock/storage-mocked.js
JavaScript
apache-2.0
1,023
/* * Copyright (C) 2015-2017 NS Solutions Corporation, All Rights Reserved. */ (function() { /** * @namespace hifive.pitalium.explorer.constant */ h5.u.obj.expose('hifive.pitalium.explorer.constant', {}); })();
hifive/hifive-test-explorer
pitalium-explorer/src/main/webapp/src/common/constant.js
JavaScript
apache-2.0
226
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js export default [ [ ['saa sita za usiku', 'saa sita za mchana', 'alfajiri', 'asubuhi', 'mchana', 'jioni', 'usiku'], , ], , [ '00:00', '12:00', ['04:00', '07:00'], ['07:00', '12:00'], ['12:00', '16:00'], ['16:00', '19:00'], ['19:00', '04:00'] ] ]; //# sourceMappingURL=sw-KE.js.map
HeH-Projects/team-agozzino
frontend/node_modules/@angular/common/locales/extra/sw-KE.js
JavaScript
apache-2.0
624
/*! jQuery UI - v1.12.0 - 2016-07-11 * http://jqueryui.com * Copyright jQuery Foundation and other contributors; Licensed */ !function(a){"function"==typeof define&&define.amd?define(["jquery","./version","./escape-selector"],a):a(jQuery)}(function(a){return a.fn.labels=function(){var b,c,d,e,f;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(e=this.eq(0).parents("label"),d=this.attr("id"),d&&(b=this.eq(0).parents().last(),f=b.add(b.length?b.siblings():this.siblings()),c="label[for='"+a.ui.escapeSelector(d)+"']",e=e.add(f.find(c).addBack(c))),this.pushStack(e))}});
weilinghsu/mesFrontend
bower_components/jquery-ui/ui/minified/labels.js
JavaScript
apache-2.0
603
/******************************************************************************* * Copyright 2013-2014 Aerospike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ /******************************************************************************* * * node range_put --start <start> --end <end> --skip <skip> * * Write records with given key range. * * Examples: * * Write records with keys in range 1-100 * * node range_put --start 1 --end 100 * * Read records with keys in range 1-100, skipping every 5th key (in sequence) * * node range_get --start 1 --end 100 --skip 5 * * Write records with keys in range 900-1000 * * node range_put --start 900 * ******************************************************************************/ var fs = require('fs'); var aerospike = require('aerospike'); var yargs = require('yargs'); var Policy = aerospike.policy; var Status = aerospike.status; /******************************************************************************* * * Options parsing * ******************************************************************************/ var argp = yargs .usage("$0 [options]") .options({ help: { boolean: true, describe: "Display this message." }, host: { alias: "h", default: "127.0.0.1", describe: "Aerospike database address." }, port: { alias: "p", default: 3000, describe: "Aerospike database port." }, timeout: { alias: "t", default: 10, describe: "Timeout in milliseconds." }, 'log-level': { alias: "l", default: aerospike.log.INFO, describe: "Log level [0-5]" }, 'log-file': { default: undefined, describe: "Path to a file send log messages to." }, namespace: { alias: "n", default: "test", describe: "Namespace for the keys." }, set: { alias: "s", default: "demo", describe: "Set for the keys." }, start: { default: 1, describe: "Start value for the key range." }, end: { default: 1000, describe: "End value for the key range." }, skip: { default: 0, describe: "Skip every n keys." } }); var argv = argp.argv; if ( argv.help === true ) { argp.showHelp(); process.exit(0); } /******************************************************************************* * * Configure the client. * ******************************************************************************/ config = { // the hosts to attempt to connect with. hosts: [ { addr: argv.host, port: argv.port } ], // log configuration log: { level: argv['log-level'], file: argv['log-file'] ? fs.openSync(argv['log-file'], "a") : 2 }, // default policies policies: { timeout: argv.timeout } }; /******************************************************************************* * * Perform the operation * ******************************************************************************/ aerospike.client(config).connect(function (err, client) { if ( err.code != Status.AEROSPIKE_OK ) { console.error("Error: Aerospike server connection error. ", err.message); process.exit(1); } // // Perform the operation // function put_done(client, start, end, skip) { var total = end - start + 1; var done = 0; var success = 0; var failure = 0; var skipped = 0; var timeLabel = "range_put @ " + total; console.time(timeLabel); return function(err, key, skippy) { if ( skippy === true ) { console.log("SKIP - ", key); skipped++; } else { switch ( err.code ) { case Status.AEROSPIKE_OK: console.log("OK - ", key); success++; break; default: console.log("ERR - ", err, key); failure++; } } done++; if ( done >= total ) { console.timeEnd(timeLabel); console.log(); console.log("RANGE: start=%d end=%d skip=%d)", start, end, skip); console.log("RESULTS: (%d completed, %d success, %d failed, %d skipped)", done, success, failure, skipped); console.log(); client.close(); } } } function put_start(client, start, end, skip) { var done = put_done(client, start, end, skip); var i = start, s = 0; for (; i <= end; i++ ) { var key = { ns: argv.namespace, set: argv.set, key: i }; if ( skip !== 0 && ++s >= skip ) { s = 0; done(null, key, true); continue; } var record = { k: i, s: "abc", i: i * 1000 + 123, b: new Buffer([0xa, 0xb, 0xc]) }; var metadata = { ttl: 10000, gen: 0 }; client.put(key, record, metadata, done); } } put_start(client, argv.start, argv.end, argv.skip); });
aerospike/concurrency-control-tic-tac-toe
node_modules/aerospike/examples/range_put.js
JavaScript
apache-2.0
6,299
/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Relevance UI Team, * Aug 2015 */ (function (angular) { "use strict"; angular.module('dashboard') .controller('orchestrationUpdateChefRunlistCtrl', ['$scope', '$q', '$modalInstance', 'responseFormatter', 'cookbookRunlistAttr', 'chefSelectorComponent', '$timeout', '$http', 'workzoneServices','workzoneEnvironment','genericServices', function ($scope, $q, $modalInstance, responseFormatter, cookbookRunlistAttr, chefSelectorComponent, $timeout, $http, workzoneServices, workzoneEnvironment , genericServices) { /*Open only One Accordian-Group at a time*/ $scope.oneAtATime = true; /*Initialising First Accordian-group open on load*/ $scope.isFirstOpen = true; $scope.isOrchestrationUpdateChefRunLoading = true; var totalElements, selectedElements, factory, compositeSelector; $scope.allCBAttributes = []; $scope.editRunListAttributes = []; $scope.getCookBookListForOrg = function() { var p = workzoneEnvironment.getEnvParams(); genericServices.getTreeNew().then(function (orgs) { $scope.organObject=orgs; }); var param; if(p){ param = { url: '/organizations/'+p.org+'/chefRunlist' }; } else { param = { url: '/organizations/' + $scope.organObject[0].orgid + '/chefRunlist' }; } genericServices.promiseGet(param).then(function (result) { $scope.getCookBooks = result; var params; if(p){ params = { url: '/d4dMasters/org/' + p.org + '/templateType/SoftwareStack/templates' }; }else { params = { url: '/d4dMasters/org/' + $scope.organObject[0].orgid + '/templateType/SoftwareStack/templates' }; } genericServices.promiseGet(params).then(function (result) { $scope.getTemplates = result; //$scope.getSoftwareTemplatesForOrg(); var c = $scope.getCookBooks; //promise contains template list var t = $scope.getTemplates; //promise contains selected runlist for edit. var s = cookbookRunlistAttr.chefrunlist; //promise contains edited cookbook attributes list var a = cookbookRunlistAttr.cookbookAttributes; var e = $scope.editRunListAttributes; $scope.allPromiseMethod(c,t,s,a,e); }); }); }; //promise contain list of cookbooks and roles list $scope.allPromiseMethod = function(c,t,s,a,e) { var allPromise = $q.all([c, t, s, a, e]); $q.all([c, t, s, a, e]).then(function (allPromise) { $scope.chefServerID = allPromise[0].serverId; var list = responseFormatter.formatDataForChefClientRun(allPromise[0]); var template = responseFormatter.formatTemplateDataForChefClient(allPromise[1]); totalElements = responseFormatter.merge(list, template); selectedElements = allPromise[2]; factory = chefSelectorComponent.getComponent; $scope.allCBAttributes = allPromise[3]; $scope.editRunListAttributes = allPromise[4]; $scope.isOrchestrationUpdateChefRunLoading = false; $scope.init(); }); }; $scope.getCookBookListForOrg(); function registerUpdateEvent(obj) { obj.addListUpdateListener('updateList', $scope.updateAttributeList); } $scope.init = function () { $timeout(function () { //DOM has finished rendering after that initializing the component compositeSelector = new factory({ scopeElement: '#chefClientForOrchestration', optionList: totalElements, selectorList: selectedElements, isSortList: true, isSearchBoxEnable: true, isPriorityEnable: true, isExcludeDataFromOption: true, isOverrideHtmlTemplate: false, idList: { selectorList: '#selector', optionSelector: '#option', upBtn: '#btnRunlistItemUp', downBtn: '#btnRunlistItemDown', addToSelector: '#btnaddToRunlist', removeFromSelector: '#btnremoveFromRunlist', searchBox: '#searchBox' } }); registerUpdateEvent(compositeSelector); }, 10); if (selectedElements && selectedElements.length > 0 && $scope.editRunListAttributes) { $scope.updateAttributeList(selectedElements, selectedElements, 'add'); } }; angular.extend($scope, { cancel: function () { $modalInstance.dismiss('cancel'); }, changeSelection: function (className) { //compositeSelector. if (className === "all") { compositeSelector.resetFilters(); } else { compositeSelector.applyFilterThroughClass(className); } }, updateAttributeList: function () { var nodesList = arguments[0]; var updatedList = arguments[1]; var operationType = arguments[2]; if (operationType === 'add') { var data = []; for (var i = 0; i < nodesList.length; i++) { if (nodesList[i].className === "cookbook" || nodesList[i].className === "deploy") { data.push(nodesList[i].value); } } if (data.length > 0) { workzoneServices.getcookBookAttributes(data, $scope.chefServerID).then(function (response) { var data; if (response.data) { data = response.data; } else { data = response; } /*Scope apply done to force refresh screen after receiving the AJAX response*/ $scope.$apply(function () { if ($scope.editRunListAttributes) { for (var j = 0; j < data.length; j++) { for (var attrItem in data[j].attributes) { if ($scope.allCBAttributes && $scope.allCBAttributes[attrItem]) { data[j].attributes[attrItem].default = $scope.allCBAttributes[attrItem]; } } } //checking condition if the attribute length is > 0 and has been edited. if ($scope.allCBAttributes.length > 0) { $scope.allCBAttributes = angular.copy($scope.allCBAttributes, data); } else { $scope.allCBAttributes = data; } $scope.editRunListAttributes = false; } else { $scope.allCBAttributes = $scope.allCBAttributes.concat(data); } if (updatedList.length > 1) { var tmp = []; for (var i = 0; i < updatedList.length; i++) { for (var k = 0; k < $scope.allCBAttributes.length; k++) { if (updatedList[i].value === $scope.allCBAttributes[k].cookbookName) { tmp.push($scope.allCBAttributes[k]); break; } } } $scope.allCBAttributes = tmp; } }); }); } } else if (operationType === 'up' || operationType === 'down') { $scope.$apply(function () { var tmp = []; //reorder attribute list as per chaged runlist order. for (var i = 0; i < updatedList.length; i++) { for (var k = 0; k < $scope.allCBAttributes.length; k++) { if (updatedList[i].value === $scope.allCBAttributes[k].cookbookName) { tmp.push($scope.allCBAttributes[k]); break; } } } $scope.allCBAttributes = tmp; }); } else { for (var j = 0; j < nodesList.length; j++) { var nodeVal = nodesList[j].value; for (var k = 0; k < $scope.allCBAttributes.length; k++) { if (nodeVal === $scope.allCBAttributes[k].cookbookName) { $scope.allCBAttributes.splice(k, 1); break; } } } } }, ok: function () { var selectedCookBooks = compositeSelector.getSelectorList(); $modalInstance.close({list: selectedCookBooks, cbAttributes: $scope.allCBAttributes}); } }); } ]); })(angular);
RLOpenCatalyst/core
client/cat3/src/partials/sections/dashboard/popups/controller/orchestrationUpdateChefRunlistCtrl.js
JavaScript
apache-2.0
8,023
(function () { module.exports = { error: function () { console.error.apply(console,arguments) } } })()
timbur/Unreal.js
Plugins/UnrealJS/Content/Scripts/internal/util.js
JavaScript
apache-2.0
138
var searchData= [ ['revision_20history_20of_20cmsis_2dpack',['Revision History of CMSIS-Pack',['../pack_revisionHistory.html',1,'index']]] ];
STMicroelectronics/cmsis_core
docs/Pack/html/search/pages_6.js
JavaScript
apache-2.0
144
/** * * @authors Your Name (you@example.org) * @date 2015-11-23 12:01:49 * @version $Id$ */ /** * * @authors Your Name (you@example.org) * @date 2015-11-06 11:48:36 * @version $$Id$$ */ var $$ = function(el) { return new _$$(el); }; var _$$ = function(el) { this.el = (el && el.nodeType == 1)? el: document; }; _$$.prototype = { constructor: this, addEvent: function(type, fn, capture) { var el = this.el; if (window.addEventListener) { el.addEventListener(type, fn, capture); var ev = document.createEvent("HTMLEvents"); //D:\Laboratory\html\mygithub\mylabs\client\jquery\event 这里也有讲解 ev.initEvent(type, capture || false, false); //event.initEvent(eventType,canBubble,cancelable) //eventType字符串值。事件的类型。 //canBubble事件是否起泡。 //cancelable是否可以用 preventDefault() 方法取消事件。 // 在元素上存储创建的事件,方便自定义触发 if (!el["ev" + type]) { el["ev" + type] = ev; } } else if (window.attachEvent) { el.attachEvent("on" + type, fn); if (isNaN(el["cu" + type])) { // 自定义属性,触发事件用 el["cu" + type] = 0; } var fnEv = function(event) { if (event.propertyName == "cu" + type) { fn.call(el); } }; el.attachEvent("onpropertychange", fnEv); // 在元素上存储绑定的propertychange事件,方便删除 if (!el["ev" + type]) { el["ev" + type] = [fnEv]; } else { el["ev" + type].push(fnEv); } } return this; }, fireEvent: function(type) { var el = this.el; if (typeof type === "string") { if (document.dispatchEvent) { if (el["ev" + type]) { el.dispatchEvent(el["ev" + type]); } } else if (document.attachEvent) { // 改变对应自定义属性,触发自定义事件 el["cu" + type]++; } } return this; }, removeEvent: function(type, fn, capture) { var el = this.el; if (window.removeEventListener) { el.removeEventListener(type, fn, capture || false); } else if (document.attachEvent) { el.detachEvent("on" + type, fn); var arrEv = el["ev" + type]; if (arrEv instanceof Array) { for (var i=0; i<arrEv.length; i+=1) { // 删除该方法名下所有绑定的propertychange事件 el.detachEvent("onpropertychange", arrEv[i]); } } } return this; } }; var page = document.getElementById("page"); $$(page).addEvent("selectedEvent",function callback(event){ }); // ------------- 以下为测试用脚本------------ // var fnClick = function(e) { // e = e || window.event; // var target = e.target || e.srcElement; // if (target.nodeType === 1) { // alert("点击类型:" + e.type); // $$(target).fireEvent("alert"); // } // }, funAlert1 = function() { // alert("自定义alert事件弹出!"); // }, funAlert2 = function() { // alert("自定义alert事件再次弹出!"); // }; // // 测试用的张小姐图片 // var elImage = document.getElementById("image"); // $$(elImage) // .addEvent("click", fnClick) // .addEvent("alert", funAlert1) // .addEvent("alert", funAlert2); // // 删除自定义事件按钮 // var elButton = document.getElementById("button"); // $$(elButton).addEvent("click", function() { // $$(elImage) // .removeEvent("alert", funAlert1) // .removeEvent("alert", funAlert2); // alert("清除成功!"); // });
freiby/flex
server/nirvana-workbench/src/main/webapp/framework/js/EventFrame.js
JavaScript
apache-2.0
4,139
module.exports = function(grunt){ var config = { docs: { dir: "./test", target: "./doc/TestPlan.md" } }; return config; };
tev/cornerstone-grunt
src/tasks/cornerstone-docs/config.js
JavaScript
apache-2.0
150
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * List of WorkloadItem resources */ class WorkloadItemResourceList extends Array { /** * Create a WorkloadItemResourceList. */ constructor() { super(); } /** * Defines the metadata of WorkloadItemResourceList * * @returns {object} metadata of WorkloadItemResourceList * */ mapper() { return { required: false, serializedName: 'WorkloadItemResourceList', type: { name: 'Composite', className: 'WorkloadItemResourceList', modelProperties: { nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } }, value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'WorkloadItemResourceElementType', type: { name: 'Composite', className: 'WorkloadItemResource' } } } } } } }; } } module.exports = WorkloadItemResourceList;
xingwu1/azure-sdk-for-node
lib/services/recoveryServicesBackupManagement/lib/models/workloadItemResourceList.js
JavaScript
apache-2.0
1,545
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var App = require('app'); require('controllers/main/service/info/metric'); var testHelpers = require('test/helpers'); function getController() { return App.MainServiceInfoMetricsController.create(); } describe('App.MainServiceInfoMetricsController', function () { var controller; beforeEach(function () { controller = App.MainServiceInfoMetricsController.create(); }); App.TestAliases.testAsComputedOr(getController(), 'showTimeRangeControl', ['!isServiceWithEnhancedWidgets', 'someWidgetGraphExists']); describe("#getActiveWidgetLayout() for Enhanced Dashboard", function () { it("make GET call", function () { controller.reopen({ isServiceWithEnhancedWidgets: true, content: Em.Object.create({serviceName: 'HDFS'}) }); controller.getActiveWidgetLayout(); expect(testHelpers.findAjaxRequest('name', 'widgets.layouts.active.get')).to.exists; }); }); describe("#getActiveWidgetLayoutSuccessCallback()", function () { beforeEach(function () { sinon.stub( App.widgetLayoutMapper, 'map'); sinon.stub( App.widgetMapper, 'map'); }); afterEach(function () { App.widgetLayoutMapper.map.restore(); App.widgetMapper.map.restore(); }); it("isWidgetLayoutsLoaded should be set to true", function () { controller.reopen({ isServiceWithEnhancedWidgets: true, content: Em.Object.create({serviceName: 'HDFS'}) }); controller.getActiveWidgetLayoutSuccessCallback({items:[{ WidgetLayoutInfo: {} }]}); expect(controller.get('isWidgetsLoaded')).to.be.true; }); }); describe("#hideWidgetSuccessCallback()", function () { beforeEach(function () { sinon.stub(App.widgetLayoutMapper, 'map'); sinon.stub(controller, 'propertyDidChange'); var params = { data: { WidgetLayoutInfo: { widgets: [ {id: 1} ] } } }; controller.hideWidgetSuccessCallback({}, {}, params); }); afterEach(function () { App.widgetLayoutMapper.map.restore(); controller.propertyDidChange.restore(); }); it("mapper is called with valid data", function () { expect(App.widgetLayoutMapper.map.calledWith({ items: [{ WidgetLayoutInfo: { widgets: [ { WidgetInfo: { id: 1 } } ] } }] })).to.be.true; }); it('`widgets` is forced to be recalculated', function () { expect(controller.propertyDidChange.calledWith('widgets')).to.be.true; }); }); });
sekikn/ambari
ambari-web/test/controllers/main/service/info/metric_test.js
JavaScript
apache-2.0
3,482
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > The scope chain is initialised to contain the same objects, in the same order, as the calling context's scope chain es5id: 10.4.2_A1.1_T10 description: eval within global execution context flags: [noStrict] ---*/ var i; var j; str1 = ''; str2 = ''; var x = 1; var y = 2; for(i in this){ str1+=i; } eval('for(j in this){\nstr2+=j;\n}'); if(!(str1 === str2)){ $ERROR("#1: scope chain must contain same objects in the same order as the calling context"); }
m0ppers/arangodb
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/language/eval-code/S10.4.2_A1.1_T10.js
JavaScript
apache-2.0
617
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * A copy activity Netezza source. * * @extends models['CopySource'] */ class NetezzaSource extends models['CopySource'] { /** * Create a NetezzaSource. * @member {object} [query] A query to retrieve data from source. Type: * string (or Expression with resultType string). */ constructor() { super(); } /** * Defines the metadata of NetezzaSource * * @returns {object} metadata of NetezzaSource * */ mapper() { return { required: false, serializedName: 'NetezzaSource', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'type', clientName: 'type' }, uberParent: 'CopySource', className: 'NetezzaSource', modelProperties: { sourceRetryCount: { required: false, serializedName: 'sourceRetryCount', type: { name: 'Object' } }, sourceRetryWait: { required: false, serializedName: 'sourceRetryWait', type: { name: 'Object' } }, type: { required: true, serializedName: 'type', isPolymorphicDiscriminator: true, type: { name: 'String' } }, query: { required: false, serializedName: 'query', type: { name: 'Object' } } } } }; } } module.exports = NetezzaSource;
xingwu1/azure-sdk-for-node
lib/services/datafactoryManagement/lib/models/netezzaSource.js
JavaScript
apache-2.0
1,945
var searchData= [ ['shadow_5fack_5fstatus_5ft',['Shadow_Ack_Status_t',['../aws__iot__shadow__interface_8h.html#ad946163c2ac5df0aa896520949d47956',1,'aws_iot_shadow_interface.h']]], ['shadowactions_5ft',['ShadowActions_t',['../aws__iot__shadow__interface_8h.html#a1fc9e025434023d44d33737f8b7c2a8c',1,'aws_iot_shadow_interface.h']]] ];
chainlinq/boatkeeper
linux_mqtt_mbedtls-2.1.1/docs/html/search/enums_5.js
JavaScript
apache-2.0
338
import { expect } from 'chai'; import { targeting as targetingInstance, filters, getHighestCpmBidsFromBidPool, sortByDealAndPriceBucketOrCpm } from 'src/targeting.js'; import { config } from 'src/config.js'; import { createBidReceived } from 'test/fixtures/fixtures.js'; import CONSTANTS from 'src/constants.json'; import { auctionManager } from 'src/auctionManager.js'; import * as utils from 'src/utils.js'; import {deepClone} from 'src/utils.js'; const bid1 = { 'bidderCode': 'rubicon', 'width': '300', 'height': '250', 'statusMessage': 'Bid available', 'adId': '148018fe5e', 'cpm': 0.537234, 'ad': 'markup', 'ad_id': '3163950', 'sizeId': '15', 'requestTimestamp': 1454535718610, 'responseTimestamp': 1454535724863, 'timeToRespond': 123, 'pbLg': '0.50', 'pbMg': '0.50', 'pbHg': '0.53', 'adUnitCode': '/123456/header-bid-tag-0', 'bidder': 'rubicon', 'size': '300x250', 'adserverTargeting': { 'foobar': '300x250', [CONSTANTS.TARGETING_KEYS.BIDDER]: 'rubicon', [CONSTANTS.TARGETING_KEYS.AD_ID]: '148018fe5e', [CONSTANTS.TARGETING_KEYS.PRICE_BUCKET]: '0.53', [CONSTANTS.TARGETING_KEYS.DEAL]: '1234' }, 'dealId': '1234', 'netRevenue': true, 'currency': 'USD', 'ttl': 300 }; const bid2 = { 'bidderCode': 'rubicon', 'width': '300', 'height': '250', 'statusMessage': 'Bid available', 'adId': '5454545', 'cpm': 0.25, 'ad': 'markup', 'ad_id': '3163950', 'sizeId': '15', 'requestTimestamp': 1454535718610, 'responseTimestamp': 1454535724863, 'timeToRespond': 123, 'pbLg': '0.25', 'pbMg': '0.25', 'pbHg': '0.25', 'adUnitCode': '/123456/header-bid-tag-0', 'bidder': 'rubicon', 'size': '300x250', 'adserverTargeting': { 'foobar': '300x250', [CONSTANTS.TARGETING_KEYS.BIDDER]: 'rubicon', [CONSTANTS.TARGETING_KEYS.AD_ID]: '5454545', [CONSTANTS.TARGETING_KEYS.PRICE_BUCKET]: '0.25' }, 'netRevenue': true, 'currency': 'USD', 'ttl': 300 }; const bid3 = { 'bidderCode': 'rubicon', 'width': '300', 'height': '600', 'statusMessage': 'Bid available', 'adId': '48747745', 'cpm': 0.75, 'ad': 'markup', 'ad_id': '3163950', 'sizeId': '15', 'requestTimestamp': 1454535718610, 'responseTimestamp': 1454535724863, 'timeToRespond': 123, 'pbLg': '0.75', 'pbMg': '0.75', 'pbHg': '0.75', 'adUnitCode': '/123456/header-bid-tag-1', 'bidder': 'rubicon', 'size': '300x600', 'adserverTargeting': { 'foobar': '300x600', [CONSTANTS.TARGETING_KEYS.BIDDER]: 'rubicon', [CONSTANTS.TARGETING_KEYS.AD_ID]: '48747745', [CONSTANTS.TARGETING_KEYS.PRICE_BUCKET]: '0.75' }, 'netRevenue': true, 'currency': 'USD', 'ttl': 300 }; const nativeBid1 = { 'bidderCode': 'appnexus', 'width': 0, 'height': 0, 'statusMessage': 'Bid available', 'adId': '591e7c9354b633', 'requestId': '24aae81e32d6f6', 'mediaType': 'native', 'source': 'client', 'cpm': 10, 'creativeId': 97494403, 'currency': 'USD', 'netRevenue': true, 'ttl': 300, 'adUnitCode': '/19968336/prebid_native_example_1', 'appnexus': { 'buyerMemberId': 9325 }, 'meta': { 'advertiserId': 2529885 }, 'native': { 'title': 'This is a Prebid Native Creative', 'body': 'This is a Prebid Native Creative. There are many like it, but this one is mine.', 'sponsoredBy': 'Prebid.org', 'clickUrl': 'http://prebid.org/dev-docs/show-native-ads.html', 'clickTrackers': ['http://www.clickUrl.com/404'], 'impressionTrackers': ['http://imp.trackerUrl.com/it1'], 'javascriptTrackers': '<script>//js script here</script>', 'image': { 'url': 'http://vcdn.adnxs.com/p/creative-image/94/22/cd/0f/9422cd0f-f400-45d3-80f5-2b92629d9257.jpg', 'height': 2250, 'width': 3000 }, 'icon': { 'url': 'http://vcdn.adnxs.com/p/creative-image/bd/59/a6/c6/bd59a6c6-0851-411d-a16d-031475a51312.png', 'height': 83, 'width': 127 } }, 'auctionId': '72138a4a-b747-4192-9192-dcc41d675de8', 'responseTimestamp': 1565785219461, 'requestTimestamp': 1565785219405, 'bidder': 'appnexus', 'timeToRespond': 56, 'pbLg': '5.00', 'pbMg': '10.00', 'pbHg': '10.00', 'pbAg': '10.00', 'pbDg': '10.00', 'pbCg': '', 'size': '0x0', 'adserverTargeting': { [CONSTANTS.TARGETING_KEYS.BIDDER]: 'appnexus', [CONSTANTS.TARGETING_KEYS.AD_ID]: '591e7c9354b633', [CONSTANTS.TARGETING_KEYS.PRICE_BUCKET]: '10.00', [CONSTANTS.TARGETING_KEYS.SIZE]: '0x0', [CONSTANTS.TARGETING_KEYS.SOURCE]: 'client', [CONSTANTS.TARGETING_KEYS.FORMAT]: 'native', [CONSTANTS.NATIVE_KEYS.title]: 'This is a Prebid Native Creative', [CONSTANTS.NATIVE_KEYS.body]: 'This is a Prebid Native Creative. There are many like it, but this one is mine.', [CONSTANTS.NATIVE_KEYS.sponsoredBy]: 'Prebid.org', [CONSTANTS.NATIVE_KEYS.clickUrl]: 'http://prebid.org/dev-docs/show-native-ads.html', [CONSTANTS.NATIVE_KEYS.image]: 'http://vcdn.adnxs.com/p/creative-image/94/22/cd/0f/9422cd0f-f400-45d3-80f5-2b92629d9257.jpg', [CONSTANTS.NATIVE_KEYS.icon]: 'http://vcdn.adnxs.com/p/creative-image/bd/59/a6/c6/bd59a6c6-0851-411d-a16d-031475a51312.png' } }; const nativeBid2 = { 'bidderCode': 'dgads', 'width': 0, 'height': 0, 'statusMessage': 'Bid available', 'adId': '6e0aba55ed54e5', 'requestId': '4de26ec83d9661', 'mediaType': 'native', 'source': 'client', 'cpm': 1.90909091, 'creativeId': 'xuidx6c901261b0x2b2', 'currency': 'JPY', 'netRevenue': true, 'ttl': 60, 'referrer': 'http://test.localhost:9999/integrationExamples/gpt/demo_native.html?pbjs_debug=true', 'native': { 'image': { 'url': 'https://ads-tr.bigmining.com/img/300x250.png', 'width': 300, 'height': 250 }, 'title': 'Test Title', 'body': 'Test Description', 'sponsoredBy': 'test.com', 'clickUrl': 'http://prebid.org/', 'clickTrackers': ['https://www.clickUrl.com/404'], 'impressionTrackers': [ 'http://imp.trackerUrl.com/it2' ] }, 'auctionId': '72138a4a-b747-4192-9192-dcc41d675de8', 'responseTimestamp': 1565785219607, 'requestTimestamp': 1565785219409, 'bidder': 'dgads', 'adUnitCode': '/19968336/prebid_native_example_1', 'timeToRespond': 198, 'pbLg': '1.50', 'pbMg': '1.90', 'pbHg': '1.90', 'pbAg': '1.90', 'pbDg': '1.90', 'pbCg': '', 'size': '0x0', 'adserverTargeting': { [CONSTANTS.TARGETING_KEYS.BIDDER]: 'dgads', [CONSTANTS.TARGETING_KEYS.AD_ID]: '6e0aba55ed54e5', [CONSTANTS.TARGETING_KEYS.PRICE_BUCKET]: '1.90', [CONSTANTS.TARGETING_KEYS.SIZE]: '0x0', [CONSTANTS.TARGETING_KEYS.SOURCE]: 'client', [CONSTANTS.TARGETING_KEYS.FORMAT]: 'native', [CONSTANTS.NATIVE_KEYS.image]: 'https://ads-tr.bigmining.com/img/300x250.png', [CONSTANTS.NATIVE_KEYS.title]: 'Test Title', [CONSTANTS.NATIVE_KEYS.body]: 'Test Description', [CONSTANTS.NATIVE_KEYS.sponsoredBy]: 'test.com', [CONSTANTS.NATIVE_KEYS.clickUrl]: 'http://prebid.org/' } }; describe('targeting tests', function () { let sandbox; let enableSendAllBids = false; let useBidCache; beforeEach(function() { sandbox = sinon.sandbox.create(); useBidCache = true; let origGetConfig = config.getConfig; sandbox.stub(config, 'getConfig').callsFake(function (key) { if (key === 'enableSendAllBids') { return enableSendAllBids; } if (key === 'useBidCache') { return useBidCache; } return origGetConfig.apply(config, arguments); }); }); afterEach(function () { sandbox.restore(); }); describe('getAllTargeting', function () { let amBidsReceivedStub; let amGetAdUnitsStub; let bidExpiryStub; let logWarnStub; let logErrorStub; let bidsReceived; beforeEach(function () { bidsReceived = [bid1, bid2, bid3]; amBidsReceivedStub = sandbox.stub(auctionManager, 'getBidsReceived').callsFake(function() { return bidsReceived; }); amGetAdUnitsStub = sandbox.stub(auctionManager, 'getAdUnitCodes').callsFake(function() { return ['/123456/header-bid-tag-0']; }); bidExpiryStub = sandbox.stub(filters, 'isBidNotExpired').returns(true); logWarnStub = sinon.stub(utils, 'logWarn'); logErrorStub = sinon.stub(utils, 'logError'); }); afterEach(function() { config.resetConfig(); logWarnStub.restore(); logErrorStub.restore(); amBidsReceivedStub.restore(); amGetAdUnitsStub.restore(); bidExpiryStub.restore(); }); describe('when handling different adunit targeting value types', function () { const adUnitCode = '/123456/header-bid-tag-0'; const adServerTargeting = {}; let getAdUnitsStub; before(function() { getAdUnitsStub = sandbox.stub(auctionManager, 'getAdUnits').callsFake(function() { return [ { 'code': adUnitCode, [CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING]: adServerTargeting } ]; }); }); after(function() { getAdUnitsStub.restore(); }); afterEach(function() { delete adServerTargeting.test_type; }); const pairs = [ ['string', '2.3', '2.3'], ['number', 2.3, '2.3'], ['boolean', true, 'true'], ['string-separated', '2.3, 4.5', '2.3,4.5'], ['array-of-string', ['2.3', '4.5'], '2.3,4.5'], ['array-of-number', [2.3, 4.5], '2.3,4.5'], ['array-of-boolean', [true, false], 'true,false'] ]; pairs.forEach(([type, value, result]) => { it(`accepts ${type}`, function() { adServerTargeting.test_type = value; const targeting = targetingInstance.getAllTargeting([adUnitCode]); expect(targeting[adUnitCode].test_type).is.equal(result); }); }); }); describe('when hb_deal is present in bid.adserverTargeting', function () { let bid4; beforeEach(function() { bid4 = utils.deepClone(bid1); bid4.adserverTargeting['hb_bidder'] = bid4.bidder = bid4.bidderCode = 'appnexus'; bid4.cpm = 0; enableSendAllBids = true; bidsReceived.push(bid4); }); it('returns targeting with both hb_deal and hb_deal_{bidder_code}', function () { const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); // We should add both keys rather than one or the other expect(targeting['/123456/header-bid-tag-0']).to.contain.keys('hb_deal', `hb_deal_${bid1.bidderCode}`, `hb_deal_${bid4.bidderCode}`); // We should assign both keys the same value expect(targeting['/123456/header-bid-tag-0']['hb_deal']).to.deep.equal(targeting['/123456/header-bid-tag-0'][`hb_deal_${bid1.bidderCode}`]); }); }); it('will enforce a limit on the number of auction keys when auctionKeyMaxChars setting is active', function () { config.setConfig({ targetingControls: { auctionKeyMaxChars: 150 } }); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0', '/123456/header-bid-tag-1']); expect(targeting['/123456/header-bid-tag-1']).to.deep.equal({}); expect(targeting['/123456/header-bid-tag-0']).to.contain.keys('hb_pb', 'hb_adid', 'hb_bidder', 'hb_deal'); expect(targeting['/123456/header-bid-tag-0']['hb_adid']).to.equal(bid1.adId); expect(logWarnStub.calledOnce).to.be.true; }); it('will return an error when auctionKeyMaxChars setting is set too low for any auction keys to be allowed', function () { config.setConfig({ targetingControls: { auctionKeyMaxChars: 50 } }); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0', '/123456/header-bid-tag-1']); expect(targeting['/123456/header-bid-tag-1']).to.deep.equal({}); expect(targeting['/123456/header-bid-tag-0']).to.deep.equal({}); expect(logWarnStub.calledTwice).to.be.true; expect(logErrorStub.calledOnce).to.be.true; }); describe('when bidLimit is present in setConfig', function () { let bid4; beforeEach(function() { bid4 = utils.deepClone(bid1); bid4.adserverTargeting['hb_bidder'] = bid4.bidder = bid4.bidderCode = 'appnexus'; bid4.cpm = 2.25; bid4.adId = '8383838'; enableSendAllBids = true; bidsReceived.push(bid4); }); it('when sendBidsControl.bidLimit is set greater than 0 in getHighestCpmBidsFromBidPool', function () { config.setConfig({ sendBidsControl: { bidLimit: 2, dealPrioritization: true } }); const bids = getHighestCpmBidsFromBidPool(bidsReceived, utils.getHighestCpm, 2); expect(bids.length).to.equal(3); expect(bids[0].adId).to.equal('8383838'); expect(bids[1].adId).to.equal('148018fe5e'); expect(bids[2].adId).to.equal('48747745'); }); it('when sendBidsControl.bidLimit is set greater than 0 and deal priortization is false in getHighestCpmBidsFromBidPool', function () { config.setConfig({ sendBidsControl: { bidLimit: 2, dealPrioritization: false } }); const bids = getHighestCpmBidsFromBidPool(bidsReceived, utils.getHighestCpm, 2); expect(bids.length).to.equal(3); expect(bids[0].adId).to.equal('8383838'); expect(bids[1].adId).to.equal('148018fe5e'); expect(bids[2].adId).to.equal('48747745'); }); it('selects the top n number of bids when enableSendAllBids is true and and bitLimit is set', function () { config.setConfig({ sendBidsControl: { bidLimit: 1 } }); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); let limitedBids = Object.keys(targeting['/123456/header-bid-tag-0']).filter(key => key.indexOf(CONSTANTS.TARGETING_KEYS.PRICE_BUCKET + '_') != -1) expect(limitedBids.length).to.equal(1); }); it('sends all bids when enableSendAllBids is true and and bitLimit is above total number of bids received', function () { config.setConfig({ sendBidsControl: { bidLimit: 50 } }); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); let limitedBids = Object.keys(targeting['/123456/header-bid-tag-0']).filter(key => key.indexOf(CONSTANTS.TARGETING_KEYS.PRICE_BUCKET + '_') != -1) expect(limitedBids.length).to.equal(2); }); it('Sends all bids when enableSendAllBids is true and and bidLimit is set to 0', function () { config.setConfig({ sendBidsControl: { bidLimit: 0 } }); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); let limitedBids = Object.keys(targeting['/123456/header-bid-tag-0']).filter(key => key.indexOf(CONSTANTS.TARGETING_KEYS.PRICE_BUCKET + '_') != -1) expect(limitedBids.length).to.equal(2); }); }); describe('targetingControls.allowZeroCpmBids', function () { let bid4; let bidderSettingsStorage; before(function() { bidderSettingsStorage = $$PREBID_GLOBAL$$.bidderSettings; }); beforeEach(function () { bid4 = utils.deepClone(bid1); bid4.adserverTargeting = { hb_pb: '0.0', hb_adid: '567891011', hb_bidder: 'appnexus', }; bid4.bidder = bid4.bidderCode = 'appnexus'; bid4.cpm = 0; bidsReceived = [bid4]; }); after(function() { bidsReceived = [bid1, bid2, bid3]; $$PREBID_GLOBAL$$.bidderSettings = bidderSettingsStorage; }) it('targeting should not include a 0 cpm by default', function() { bid4.adserverTargeting = {}; const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.deep.equal({}); }); it('targeting should allow a 0 cpm with targetingControls.allowZeroCpmBids set to true', function () { $$PREBID_GLOBAL$$.bidderSettings = { standard: { allowZeroCpmBids: true } }; const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.include.all.keys('hb_pb', 'hb_bidder', 'hb_adid', 'hb_bidder_appnexus', 'hb_adid_appnexus', 'hb_pb_appnexus'); expect(targeting['/123456/header-bid-tag-0']['hb_pb']).to.equal('0.0') }); }); describe('targetingControls.allowTargetingKeys', function () { let bid4; beforeEach(function() { bid4 = utils.deepClone(bid1); bid4.adserverTargeting = { hb_deal: '4321', hb_pb: '0.1', hb_adid: '567891011', hb_bidder: 'appnexus', }; bid4.bidder = bid4.bidderCode = 'appnexus'; bid4.cpm = 0.1; // losing bid so not included if enableSendAllBids === false bid4.dealId = '4321'; enableSendAllBids = true; config.setConfig({ targetingControls: { allowTargetingKeys: ['BIDDER', 'AD_ID', 'PRICE_BUCKET'] } }); bidsReceived.push(bid4); }); it('targeting should include custom keys', function () { const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.include.all.keys('foobar'); }); it('targeting should include keys prefixed by allowed default targeting keys', function () { const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.include.all.keys('hb_bidder_rubicon', 'hb_adid_rubicon', 'hb_pb_rubicon'); expect(targeting['/123456/header-bid-tag-0']).to.include.all.keys('hb_bidder_appnexus', 'hb_adid_appnexus', 'hb_pb_appnexus'); }); it('targeting should not include keys prefixed by disallowed default targeting keys', function () { const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.not.have.all.keys(['hb_deal_appnexus', 'hb_deal_rubicon']); }); }); describe('targetingControls.addTargetingKeys', function () { let winningBid = null; beforeEach(function () { bidsReceived = [bid1, bid2, nativeBid1, nativeBid2].map(deepClone); bidsReceived.forEach((bid) => { bid.adserverTargeting[CONSTANTS.TARGETING_KEYS.SOURCE] = 'test-source'; bid.adUnitCode = 'adunit'; if (winningBid == null || bid.cpm > winningBid.cpm) { winningBid = bid; } }); enableSendAllBids = true; }); const expandKey = function (key) { const keys = new Set(); if (winningBid.adserverTargeting[key] != null) { keys.add(key); } bidsReceived .filter((bid) => bid.adserverTargeting[key] != null) .map((bid) => bid.bidderCode) .forEach((code) => keys.add(`${key}_${code}`.substr(0, 20))); return new Array(...keys); } const targetingResult = function () { return targetingInstance.getAllTargeting(['adunit'])['adunit']; } it('should include added keys', function () { config.setConfig({ targetingControls: { addTargetingKeys: ['SOURCE'] } }); expect(targetingResult()).to.include.all.keys(...expandKey(CONSTANTS.TARGETING_KEYS.SOURCE)); }); it('should keep default and native keys', function() { config.setConfig({ targetingControls: { addTargetingKeys: ['SOURCE'] } }); const defaultKeys = new Set(Object.values(CONSTANTS.DEFAULT_TARGETING_KEYS)); Object.values(CONSTANTS.NATIVE_KEYS).forEach((k) => defaultKeys.add(k)); const expectedKeys = new Set(); bidsReceived .map((bid) => Object.keys(bid.adserverTargeting)) .reduce((left, right) => left.concat(right), []) .filter((key) => defaultKeys.has(key)) .map(expandKey) .reduce((left, right) => left.concat(right), []) .forEach((k) => expectedKeys.add(k)); expect(targetingResult()).to.include.all.keys(...expectedKeys); }); it('should not be allowed together with allowTargetingKeys', function () { config.setConfig({ targetingControls: { allowTargetingKeys: [CONSTANTS.TARGETING_KEYS.BIDDER], addTargetingKeys: [CONSTANTS.TARGETING_KEYS.SOURCE] } }); expect(targetingResult).to.throw(); }); }); describe('targetingControls.allowSendAllBidsTargetingKeys', function () { let bid4; beforeEach(function() { bid4 = utils.deepClone(bid1); bid4.adserverTargeting = { hb_deal: '4321', hb_pb: '0.1', hb_adid: '567891011', hb_bidder: 'appnexus', }; bid4.bidder = bid4.bidderCode = 'appnexus'; bid4.cpm = 0.1; // losing bid so not included if enableSendAllBids === false bid4.dealId = '4321'; enableSendAllBids = true; config.setConfig({ targetingControls: { allowTargetingKeys: ['BIDDER', 'AD_ID', 'PRICE_BUCKET'], allowSendAllBidsTargetingKeys: ['PRICE_BUCKET', 'AD_ID'] } }); bidsReceived.push(bid4); }); it('targeting should include custom keys', function () { const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.include.all.keys('foobar'); }); it('targeting should only include keys prefixed by allowed default send all bids targeting keys and standard keys', function () { const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.include.all.keys('hb_bidder', 'hb_adid', 'hb_pb'); expect(targeting['/123456/header-bid-tag-0']).to.include.all.keys('hb_adid_rubicon', 'hb_pb_rubicon'); expect(targeting['/123456/header-bid-tag-0']).to.include.all.keys('hb_bidder', 'hb_adid', 'hb_pb', 'hb_adid_appnexus', 'hb_pb_appnexus'); }); it('targeting should not include keys prefixed by disallowed default targeting keys and disallowed send all bid targeting keys', function () { const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.not.have.all.keys(['hb_deal', 'hb_bidder_rubicon', 'hb_bidder_appnexus', 'hb_deal_appnexus', 'hb_deal_rubicon']); }); }); describe('targetingControls.alwaysIncludeDeals', function () { let bid4; beforeEach(function() { bid4 = utils.deepClone(bid1); bid4.adserverTargeting = { hb_deal: '4321', hb_pb: '0.1', hb_adid: '567891011', hb_bidder: 'appnexus', }; bid4.bidder = bid4.bidderCode = 'appnexus'; bid4.cpm = 0.1; // losing bid so not included if enableSendAllBids === false bid4.dealId = '4321'; enableSendAllBids = false; bidsReceived.push(bid4); }); it('does not include losing deals when alwaysIncludeDeals not set', function () { const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); // Rubicon wins bid and has deal, but alwaysIncludeDeals is false, so only top bid plus deal_id // appnexus does not get sent since alwaysIncludeDeals is not defined expect(targeting['/123456/header-bid-tag-0']).to.deep.equal({ 'hb_deal_rubicon': '1234', 'hb_deal': '1234', 'hb_pb': '0.53', 'hb_adid': '148018fe5e', 'hb_bidder': 'rubicon', 'foobar': '300x250' }); }); it('does not include losing deals when alwaysIncludeDeals set to false', function () { config.setConfig({ targetingControls: { alwaysIncludeDeals: false } }); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); // Rubicon wins bid and has deal, but alwaysIncludeDeals is false, so only top bid plus deal_id // appnexus does not get sent since alwaysIncludeDeals is false expect(targeting['/123456/header-bid-tag-0']).to.deep.equal({ 'hb_deal_rubicon': '1234', // This is just how it works before this PR, always added no matter what for winner if they have deal 'hb_deal': '1234', 'hb_pb': '0.53', 'hb_adid': '148018fe5e', 'hb_bidder': 'rubicon', 'foobar': '300x250' }); }); it('includes losing deals when alwaysIncludeDeals set to true and also winning deals bidder KVPs', function () { config.setConfig({ targetingControls: { alwaysIncludeDeals: true } }); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); // Rubicon wins bid and has a deal, so all KVPs for them are passed (top plus bidder specific) // Appnexus had deal so passed through expect(targeting['/123456/header-bid-tag-0']).to.deep.equal({ 'hb_deal_rubicon': '1234', 'hb_deal': '1234', 'hb_pb': '0.53', 'hb_adid': '148018fe5e', 'hb_bidder': 'rubicon', 'foobar': '300x250', 'hb_pb_rubicon': '0.53', 'hb_adid_rubicon': '148018fe5e', 'hb_bidder_rubicon': 'rubicon', 'hb_deal_appnexus': '4321', 'hb_pb_appnexus': '0.1', 'hb_adid_appnexus': '567891011', 'hb_bidder_appnexus': 'appnexus' }); }); it('includes winning bid even when it is not a deal, plus other deal KVPs', function () { config.setConfig({ targetingControls: { alwaysIncludeDeals: true } }); let bid5 = utils.deepClone(bid4); bid5.adserverTargeting = { hb_pb: '3.0', hb_adid: '111111', hb_bidder: 'pubmatic', }; bid5.bidder = bid5.bidderCode = 'pubmatic'; bid5.cpm = 3.0; // winning bid! delete bid5.dealId; // no deal with winner bidsReceived.push(bid5); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); // Pubmatic wins but no deal. So only top bid KVPs for them is sent // Rubicon has a dealId so passed through // Appnexus has a dealId so passed through expect(targeting['/123456/header-bid-tag-0']).to.deep.equal({ 'hb_bidder': 'pubmatic', 'hb_adid': '111111', 'hb_pb': '3.0', 'foobar': '300x250', 'hb_deal_rubicon': '1234', 'hb_pb_rubicon': '0.53', 'hb_adid_rubicon': '148018fe5e', 'hb_bidder_rubicon': 'rubicon', 'hb_deal_appnexus': '4321', 'hb_pb_appnexus': '0.1', 'hb_adid_appnexus': '567891011', 'hb_bidder_appnexus': 'appnexus' }); }); }); it('selects the top bid when enableSendAllBids true', function () { enableSendAllBids = true; let targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); // we should only get the targeting data for the one requested adunit expect(Object.keys(targeting).length).to.equal(1); let sendAllBidCpm = Object.keys(targeting['/123456/header-bid-tag-0']).filter(key => key.indexOf(CONSTANTS.TARGETING_KEYS.PRICE_BUCKET + '_') != -1) // we shouldn't get more than 1 key for hb_pb_${bidder} expect(sendAllBidCpm.length).to.equal(1); // expect the winning CPM to be equal to the sendAllBidCPM expect(targeting['/123456/header-bid-tag-0'][CONSTANTS.TARGETING_KEYS.PRICE_BUCKET + '_rubicon']).to.deep.equal(targeting['/123456/header-bid-tag-0'][CONSTANTS.TARGETING_KEYS.PRICE_BUCKET]); }); it('ensures keys are properly generated when enableSendAllBids is true and multiple bidders use native', function() { const nativeAdUnitCode = '/19968336/prebid_native_example_1'; enableSendAllBids = true; // update mocks for this test to return native bids amBidsReceivedStub.callsFake(function() { return [nativeBid1, nativeBid2]; }); amGetAdUnitsStub.callsFake(function() { return [nativeAdUnitCode]; }); let targeting = targetingInstance.getAllTargeting([nativeAdUnitCode]); expect(targeting[nativeAdUnitCode].hb_native_image).to.equal(nativeBid1.native.image.url); expect(targeting[nativeAdUnitCode].hb_native_linkurl).to.equal(nativeBid1.native.clickUrl); expect(targeting[nativeAdUnitCode].hb_native_title).to.equal(nativeBid1.native.title); expect(targeting[nativeAdUnitCode].hb_native_image_dgad).to.exist.and.to.equal(nativeBid2.native.image.url); expect(targeting[nativeAdUnitCode].hb_pb_dgads).to.exist.and.to.equal(nativeBid2.pbMg); expect(targeting[nativeAdUnitCode].hb_native_body_appne).to.exist.and.to.equal(nativeBid1.native.body); }); it('does not include adpod type bids in the getBidsReceived results', function () { let adpodBid = utils.deepClone(bid1); adpodBid.video = { context: 'adpod', durationSeconds: 15, durationBucket: 15 }; adpodBid.cpm = 5; bidsReceived.push(adpodBid); const targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); expect(targeting['/123456/header-bid-tag-0']).to.contain.keys('hb_deal', 'hb_adid', 'hb_bidder'); expect(targeting['/123456/header-bid-tag-0']['hb_adid']).to.equal(bid1.adId); }); }); // end getAllTargeting tests describe('getAllTargeting without bids return empty object', function () { let amBidsReceivedStub; let amGetAdUnitsStub; let bidExpiryStub; beforeEach(function () { amBidsReceivedStub = sandbox.stub(auctionManager, 'getBidsReceived').callsFake(function() { return []; }); amGetAdUnitsStub = sandbox.stub(auctionManager, 'getAdUnitCodes').callsFake(function() { return ['/123456/header-bid-tag-0']; }); bidExpiryStub = sandbox.stub(filters, 'isBidNotExpired').returns(true); }); it('returns targetingSet correctly', function () { let targeting = targetingInstance.getAllTargeting(['/123456/header-bid-tag-0']); // we should only get the targeting data for the one requested adunit to at least exist even though it has no keys to set expect(Object.keys(targeting).length).to.equal(1); }); }); // end getAllTargeting without bids return empty object describe('Targeting in concurrent auctions', function () { describe('check getOldestBid', function () { let bidExpiryStub; let auctionManagerStub; beforeEach(function () { bidExpiryStub = sandbox.stub(filters, 'isBidNotExpired').returns(true); auctionManagerStub = sandbox.stub(auctionManager, 'getBidsReceived'); }); it('should use bids from pool to get Winning Bid', function () { let bidsReceived = [ createBidReceived({bidder: 'appnexus', cpm: 7, auctionId: 1, responseTimestamp: 100, adUnitCode: 'code-0', adId: 'adid-1'}), createBidReceived({bidder: 'rubicon', cpm: 6, auctionId: 1, responseTimestamp: 101, adUnitCode: 'code-1', adId: 'adid-2'}), createBidReceived({bidder: 'appnexus', cpm: 6, auctionId: 2, responseTimestamp: 102, adUnitCode: 'code-0', adId: 'adid-3'}), createBidReceived({bidder: 'rubicon', cpm: 6, auctionId: 2, responseTimestamp: 103, adUnitCode: 'code-1', adId: 'adid-4'}), ]; let adUnitCodes = ['code-0', 'code-1']; let bids = targetingInstance.getWinningBids(adUnitCodes, bidsReceived); expect(bids.length).to.equal(2); expect(bids[0].adId).to.equal('adid-1'); expect(bids[1].adId).to.equal('adid-2'); }); it('should honor useBidCache', function() { useBidCache = true; auctionManagerStub.returns([ createBidReceived({bidder: 'appnexus', cpm: 7, auctionId: 1, responseTimestamp: 100, adUnitCode: 'code-0', adId: 'adid-1'}), createBidReceived({bidder: 'appnexus', cpm: 5, auctionId: 2, responseTimestamp: 102, adUnitCode: 'code-0', adId: 'adid-2'}), ]); let adUnitCodes = ['code-0']; targetingInstance.setLatestAuctionForAdUnit('code-0', 2); let bids = targetingInstance.getWinningBids(adUnitCodes); expect(bids.length).to.equal(1); expect(bids[0].adId).to.equal('adid-1'); useBidCache = false; bids = targetingInstance.getWinningBids(adUnitCodes); expect(bids.length).to.equal(1); expect(bids[0].adId).to.equal('adid-2'); }); it('should not use rendered bid to get winning bid', function () { let bidsReceived = [ createBidReceived({bidder: 'appnexus', cpm: 8, auctionId: 1, responseTimestamp: 100, adUnitCode: 'code-0', adId: 'adid-1', status: 'rendered'}), createBidReceived({bidder: 'rubicon', cpm: 6, auctionId: 1, responseTimestamp: 101, adUnitCode: 'code-1', adId: 'adid-2'}), createBidReceived({bidder: 'appnexus', cpm: 7, auctionId: 2, responseTimestamp: 102, adUnitCode: 'code-0', adId: 'adid-3'}), createBidReceived({bidder: 'rubicon', cpm: 6, auctionId: 2, responseTimestamp: 103, adUnitCode: 'code-1', adId: 'adid-4'}), ]; auctionManagerStub.returns(bidsReceived); let adUnitCodes = ['code-0', 'code-1']; let bids = targetingInstance.getWinningBids(adUnitCodes); expect(bids.length).to.equal(2); expect(bids[0].adId).to.equal('adid-2'); expect(bids[1].adId).to.equal('adid-3'); }); it('should use highest cpm bid from bid pool to get winning bid', function () { // Pool is having 4 bids from 2 auctions. There are 2 bids from rubicon, #2 which is highest cpm bid will be selected to take part in auction. let bidsReceived = [ createBidReceived({bidder: 'appnexus', cpm: 8, auctionId: 1, responseTimestamp: 100, adUnitCode: 'code-0', adId: 'adid-1'}), createBidReceived({bidder: 'rubicon', cpm: 9, auctionId: 1, responseTimestamp: 101, adUnitCode: 'code-0', adId: 'adid-2'}), createBidReceived({bidder: 'appnexus', cpm: 7, auctionId: 2, responseTimestamp: 102, adUnitCode: 'code-0', adId: 'adid-3'}), createBidReceived({bidder: 'rubicon', cpm: 8, auctionId: 2, responseTimestamp: 103, adUnitCode: 'code-0', adId: 'adid-4'}), ]; auctionManagerStub.returns(bidsReceived); let adUnitCodes = ['code-0']; let bids = targetingInstance.getWinningBids(adUnitCodes); expect(bids.length).to.equal(1); expect(bids[0].adId).to.equal('adid-2'); }); }); describe('check bidExpiry', function () { let auctionManagerStub; let timestampStub; beforeEach(function () { auctionManagerStub = sandbox.stub(auctionManager, 'getBidsReceived'); timestampStub = sandbox.stub(utils, 'timestamp'); }); it('should not include expired bids in the auction', function () { timestampStub.returns(200000); // Pool is having 4 bids from 2 auctions. All the bids are expired and only bid #3 is passing the bidExpiry check. let bidsReceived = [ createBidReceived({bidder: 'appnexus', cpm: 18, auctionId: 1, responseTimestamp: 100, adUnitCode: 'code-0', adId: 'adid-1', ttl: 150}), createBidReceived({bidder: 'sampleBidder', cpm: 16, auctionId: 1, responseTimestamp: 101, adUnitCode: 'code-0', adId: 'adid-2', ttl: 100}), createBidReceived({bidder: 'appnexus', cpm: 7, auctionId: 2, responseTimestamp: 102, adUnitCode: 'code-0', adId: 'adid-3', ttl: 300}), createBidReceived({bidder: 'rubicon', cpm: 6, auctionId: 2, responseTimestamp: 103, adUnitCode: 'code-0', adId: 'adid-4', ttl: 50}), ]; auctionManagerStub.returns(bidsReceived); let adUnitCodes = ['code-0', 'code-1']; let bids = targetingInstance.getWinningBids(adUnitCodes); expect(bids.length).to.equal(1); expect(bids[0].adId).to.equal('adid-3'); }); }); }); describe('sortByDealAndPriceBucketOrCpm', function() { it('will properly sort bids when some bids have deals and some do not', function () { let bids = [{ adserverTargeting: { hb_adid: 'abc', hb_pb: '1.00', hb_deal: '1234' } }, { adserverTargeting: { hb_adid: 'def', hb_pb: '0.50', } }, { adserverTargeting: { hb_adid: 'ghi', hb_pb: '20.00', hb_deal: '4532' } }, { adserverTargeting: { hb_adid: 'jkl', hb_pb: '9.00', hb_deal: '9864' } }, { adserverTargeting: { hb_adid: 'mno', hb_pb: '50.00', } }, { adserverTargeting: { hb_adid: 'pqr', hb_pb: '100.00', } }]; bids.sort(sortByDealAndPriceBucketOrCpm()); expect(bids[0].adserverTargeting.hb_adid).to.equal('ghi'); expect(bids[1].adserverTargeting.hb_adid).to.equal('jkl'); expect(bids[2].adserverTargeting.hb_adid).to.equal('abc'); expect(bids[3].adserverTargeting.hb_adid).to.equal('pqr'); expect(bids[4].adserverTargeting.hb_adid).to.equal('mno'); expect(bids[5].adserverTargeting.hb_adid).to.equal('def'); }); it('will properly sort bids when all bids have deals', function () { let bids = [{ adserverTargeting: { hb_adid: 'abc', hb_pb: '1.00', hb_deal: '1234' } }, { adserverTargeting: { hb_adid: 'def', hb_pb: '0.50', hb_deal: '4321' } }, { adserverTargeting: { hb_adid: 'ghi', hb_pb: '2.50', hb_deal: '4532' } }, { adserverTargeting: { hb_adid: 'jkl', hb_pb: '2.00', hb_deal: '9864' } }]; bids.sort(sortByDealAndPriceBucketOrCpm()); expect(bids[0].adserverTargeting.hb_adid).to.equal('ghi'); expect(bids[1].adserverTargeting.hb_adid).to.equal('jkl'); expect(bids[2].adserverTargeting.hb_adid).to.equal('abc'); expect(bids[3].adserverTargeting.hb_adid).to.equal('def'); }); it('will properly sort bids when no bids have deals', function () { let bids = [{ adserverTargeting: { hb_adid: 'abc', hb_pb: '1.00' } }, { adserverTargeting: { hb_adid: 'def', hb_pb: '0.10' } }, { adserverTargeting: { hb_adid: 'ghi', hb_pb: '10.00' } }, { adserverTargeting: { hb_adid: 'jkl', hb_pb: '10.01' } }, { adserverTargeting: { hb_adid: 'mno', hb_pb: '1.00' } }, { adserverTargeting: { hb_adid: 'pqr', hb_pb: '100.00' } }]; bids.sort(sortByDealAndPriceBucketOrCpm()); expect(bids[0].adserverTargeting.hb_adid).to.equal('pqr'); expect(bids[1].adserverTargeting.hb_adid).to.equal('jkl'); expect(bids[2].adserverTargeting.hb_adid).to.equal('ghi'); expect(bids[3].adserverTargeting.hb_adid).to.equal('abc'); expect(bids[4].adserverTargeting.hb_adid).to.equal('mno'); expect(bids[5].adserverTargeting.hb_adid).to.equal('def'); }); it('will properly sort bids when some bids have deals and some do not and by cpm when flag is set to true', function () { let bids = [{ cpm: 1.04, adserverTargeting: { hb_adid: 'abc', hb_pb: '1.00', hb_deal: '1234' } }, { cpm: 0.50, adserverTargeting: { hb_adid: 'def', hb_pb: '0.50', hb_deal: '4532' } }, { cpm: 0.53, adserverTargeting: { hb_adid: 'ghi', hb_pb: '0.50', hb_deal: '4532' } }, { cpm: 9.04, adserverTargeting: { hb_adid: 'jkl', hb_pb: '9.00', hb_deal: '9864' } }, { cpm: 50.00, adserverTargeting: { hb_adid: 'mno', hb_pb: '50.00', } }, { cpm: 100.00, adserverTargeting: { hb_adid: 'pqr', hb_pb: '100.00', } }]; bids.sort(sortByDealAndPriceBucketOrCpm(true)); expect(bids[0].adserverTargeting.hb_adid).to.equal('jkl'); expect(bids[1].adserverTargeting.hb_adid).to.equal('abc'); expect(bids[2].adserverTargeting.hb_adid).to.equal('ghi'); expect(bids[3].adserverTargeting.hb_adid).to.equal('def'); expect(bids[4].adserverTargeting.hb_adid).to.equal('pqr'); expect(bids[5].adserverTargeting.hb_adid).to.equal('mno'); }); }); describe('setTargetingForAst', function () { let sandbox, apnTagStub; beforeEach(function() { sandbox = sinon.createSandbox(); sandbox.stub(targetingInstance, 'resetPresetTargetingAST'); apnTagStub = sandbox.stub(window.apntag, 'setKeywords'); }); afterEach(function () { sandbox.restore(); }); it('should set single addUnit code', function() { let adUnitCode = 'testdiv-abc-ad-123456-0'; sandbox.stub(targetingInstance, 'getAllTargeting').returns({ 'testdiv1-abc-ad-123456-0': {hb_bidder: 'appnexus'} }); targetingInstance.setTargetingForAst(adUnitCode); expect(targetingInstance.getAllTargeting.called).to.equal(true); expect(targetingInstance.resetPresetTargetingAST.called).to.equal(true); expect(apnTagStub.callCount).to.equal(1); expect(apnTagStub.getCall(0).args[0]).to.deep.equal('testdiv1-abc-ad-123456-0'); expect(apnTagStub.getCall(0).args[1]).to.deep.equal({HB_BIDDER: 'appnexus'}); }); it('should set array of addUnit codes', function() { let adUnitCodes = ['testdiv1-abc-ad-123456-0', 'testdiv2-abc-ad-123456-0'] sandbox.stub(targetingInstance, 'getAllTargeting').returns({ 'testdiv1-abc-ad-123456-0': {hb_bidder: 'appnexus'}, 'testdiv2-abc-ad-123456-0': {hb_bidder: 'appnexus'} }); targetingInstance.setTargetingForAst(adUnitCodes); expect(targetingInstance.getAllTargeting.called).to.equal(true); expect(targetingInstance.resetPresetTargetingAST.called).to.equal(true); expect(apnTagStub.callCount).to.equal(2); expect(apnTagStub.getCall(1).args[0]).to.deep.equal('testdiv2-abc-ad-123456-0'); expect(apnTagStub.getCall(1).args[1]).to.deep.equal({HB_BIDDER: 'appnexus'}); }); }); });
gumgum/Prebid.js
test/spec/unit/core/targeting_spec.js
JavaScript
apache-2.0
43,362
/* jjs -Djava.system.class.loader=io.trivium.TriviumLoader -Djava.protocol.handler.pkgs=io.trivium.urlhandler -server -cp bnd-tibco-ems-receiver:tpe-timer:tsk-consoleLogger:bnd-timer:tpe-timerconfig:tsk-excel2table:tpe-error:tpe-timertick:tsk-java-compiler:tpe-logentry:trivium-core:tsk-js-runner:tpe-table:tsk-TimerTick2LogEntryMapper:tsk-log */ var args =["-cq","-cs","-ll","fine","-p","/Users/jens/tmp/store","-t","1m"]; var mainType = Java.type("io.trivium.Start"); mainType.main(args); var Central = Java.type("io.trivium.Central"); var Registry = Java.type('io.trivium.Registry'); var ObjectRef = Java.type('io.trivium.anystore.ObjectRef'); //print("central is running => "+Central.isRunning);
trivium-io/trivium-core
src/starter.js
JavaScript
apache-2.0
703
/** * Copyright (c) 2008-2009 The Open Source Geospatial Foundation * * Published under the BSD license. * See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text * of the license. */ /** api: example[attribute-form] * Attribute Form * -------------- * Create a form with fields from attributes read from a WFS * DescribeFeatureType response */ var form; Ext.onReady(function() { Ext.QuickTips.init(); // create attributes store var attributeStore = new GeoExt.data.AttributeStore({ url: "data/describe_feature_type.xml" }); form = new Ext.form.FormPanel({ renderTo: document.body, autoScroll: true, height: 300, width: 350, defaults: { width: 120, maxLengthText: "too long", minLengthText: "too short" }, plugins: [ new GeoExt.plugins.AttributeForm({ attributeStore: attributeStore, recordToFieldOptions: { labelTpl: new Ext.XTemplate( '{name}{[this.getStar(values)]}', { compiled: true, disableFormats: true, getStar: function(v) { return v.nillable ? '' : ' *'; } } ) } }) ] }); attributeStore.load(); });
mangadul/rutilahu-web
assets/js/geoext/examples/attribute-form.js
JavaScript
apache-2.0
1,488
const constants = require('./constants.js'); const AWS = constants.AWS; const DYNAMODB_TABLE = constants.DYNAMODB_TABLE; const model = require('./model.json'); // a static copy of your model, used to suggest custom slot values module.exports = { 'randomArrayElement': function(myArray) { return(myArray[Math.floor(Math.random() * myArray.length)]); }, 'capitalize': function(myString) { return myString.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); }, 'supportsDisplay': function(handlerInput) // returns true if the skill is running on a device with a display (Echo Show, Echo Spot, etc.) { // Enable your skill for display as shown here: https://alexa.design/enabledisplay const hasDisplay = handlerInput.requestEnvelope.context && handlerInput.requestEnvelope.context.System && handlerInput.requestEnvelope.context.System.device && handlerInput.requestEnvelope.context.System.device.supportedInterfaces && handlerInput.requestEnvelope.context.System.device.supportedInterfaces.Display; return hasDisplay; }, 'timeDelta': function(t1, t2) { const dt1 = new Date(t1); const dt2 = new Date(t2); const timeSpanMS = dt2.getTime() - dt1.getTime(); const span = { "timeSpanMIN": Math.floor(timeSpanMS / (1000 * 60 )), "timeSpanHR": Math.floor(timeSpanMS / (1000 * 60 * 60)), "timeSpanDAY": Math.floor(timeSpanMS / (1000 * 60 * 60 * 24)), "timeSpanDesc" : "" }; if (span.timeSpanHR < 2) { span.timeSpanDesc = span.timeSpanMIN + " minutes"; } else if (span.timeSpanDAY < 2) { span.timeSpanDesc = span.timeSpanHR + " hours"; } else { span.timeSpanDesc = span.timeSpanDAY + " days"; } return span; }, 'sayArray': function(myData, penultimateWord = 'and') { // the first argument is an array [] of items // the second argument is the list penultimate word; and/or/nor etc. Default to 'and' let result = ''; myData.forEach(function(element, index, arr) { if (index === 0) { result = element; } else if (index === myData.length - 1) { result += ` ${penultimateWord} ${element}`; } else { result += `, ${element}`; } }); return result; }, 'stripTags': function(str) { return str.replace(/<\/?[^>]+(>|$)/g, ""); }, 'getSampleUtterance': function(intent) { return randomElement(intent.samples); }, 'getSlotValues': function(filledSlots) { const slotValues = {}; Object.keys(filledSlots).forEach((item) => { const name = filledSlots[item].name; if (filledSlots[item] && filledSlots[item].resolutions && filledSlots[item].resolutions.resolutionsPerAuthority[0] && filledSlots[item].resolutions.resolutionsPerAuthority[0].status && filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code) { switch (filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code) { case 'ER_SUCCESS_MATCH': let resolutions = []; let vals = filledSlots[item].resolutions.resolutionsPerAuthority[0].values; for (let i = 0; i < vals.length; i++) { resolutions.push(vals[i].value.name); } slotValues[name] = { heardAs: filledSlots[item].value, resolved: filledSlots[item].resolutions.resolutionsPerAuthority[0].values[0].value.name, resolutions: resolutions, ERstatus: 'ER_SUCCESS_MATCH' }; break; case 'ER_SUCCESS_NO_MATCH': slotValues[name] = { heardAs: filledSlots[item].value, resolved: '', ERstatus: 'ER_SUCCESS_NO_MATCH' }; break; default: break; } } else { slotValues[name] = { heardAs: filledSlots[item].value, resolved: '', ERstatus: '' }; } }, this); return slotValues; }, 'getExampleSlotValues': function(intentName, slotName) { let examples = []; let slotType = ''; let slotValuesFull = []; let intents = model.interactionModel.languageModel.intents; for (let i = 0; i < intents.length; i++) { if (intents[i].name == intentName) { let slots = intents[i].slots; for (let j = 0; j < slots.length; j++) { if (slots[j].name === slotName) { slotType = slots[j].type; } } } } let types = model.interactionModel.languageModel.types; for (let i = 0; i < types.length; i++) { if (types[i].name === slotType) { slotValuesFull = types[i].values; } } slotValuesFull = module.exports.shuffleArray(slotValuesFull); examples.push(slotValuesFull[0].name.value); examples.push(slotValuesFull[1].name.value); if (slotValuesFull.length > 2) { examples.push(slotValuesFull[2].name.value); } return examples; }, 'getRecordCount': function(callback) { const params = { TableName: DYNAMODB_TABLE }; let docClient = new AWS.DynamoDB.DocumentClient(); docClient.scan(params, (err, data) => { if (err) { console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); } else { const skillUserCount = data.Items.length; callback(skillUserCount); } }); }, 'changeProsody' : function(attribute, current, change) { let newValue = ''; if (attribute === 'rate') { switch(current + '.' + change) { case 'x-slow.slower': case 'slow.slower': newValue = 'x-slow'; break; case 'medium.slower': case 'x-slow.faster': newValue = 'slow'; break; case 'fast.slower': case 'slow.faster': newValue = 'medium'; break; case 'x-fast.slower': case 'medium.faster': newValue = 'fast'; break; case 'x-fast.faster': case 'fast.faster': newValue = 'x-fast'; break; default: newValue = 'medium'; } } return newValue; }, 'sendTxtMessage': function(params, locale, callback) { let mobileNumber = params.PhoneNumber.toString(); if (locale === 'en-US') { if (mobileNumber.length < 10 ){ const errMsg = 'mobileNumber provided is too short: ' + mobileNumber + '. '; callback(errMsg); } if (mobileNumber.length == 10 ) { mobileNumber = '1' + mobileNumber; } } else { if (locale === 'other locales tbd') { // add validation and format code } } if (mobileNumber.substring(0,1) !== '+') { mobileNumber = '+' + mobileNumber; } let snsParams = params; snsParams.PhoneNumber = mobileNumber; const SNS = new AWS.SNS(); SNS.publish(snsParams, function(err, data){ // console.log('sending message to ' + mobileNumber ); if (err) console.log(err, err.stack); callback('I sent you a text message. '); }); }, 'generatePassPhrase': function() { // 'correct', 'horse', 'battery', 'staple' const word1 = ['nice', 'good', 'clear', 'kind', 'red', 'green', 'orange', 'yellow', 'brown', 'careful', 'powerful', 'vast', 'happy', 'deep', 'warm', 'cold', 'heavy', 'dry', 'quiet', 'sweet', 'short', 'long', 'late', 'early', 'quick', 'fast', 'slow', 'other','public','clean','proud', 'flat','round', 'loud', 'funny', 'free', 'tall', 'short', 'big', 'small']; const word2 = ['person', 'day', 'car', 'tree', 'fish', 'wheel', 'chair', 'sun', 'moon', 'star', 'story', 'voice', 'job', 'fact', 'record', 'computer', 'ocean', 'building', 'cat', 'dog', 'rabbit', 'carrot', 'orange', 'bread', 'soup', 'spoon', 'fork', 'straw', 'napkin', 'fold', 'pillow', 'radio', 'towel', 'pencil', 'table', 'mark', 'teacher', 'student', 'developer', 'raisin', 'pizza', 'movie', 'book', 'cup', 'plate', 'wall', 'door', 'window', 'shoes', 'hat', 'shirt', 'bag', 'page', 'clock', 'glass', 'button', 'bump', 'paint', 'song', 'story', 'memory', 'school', 'corner', 'wire', 'cable' ]; const numLimit = 999; const phraseObject = { 'word1': randomArrayElement(word1), 'word2': randomArrayElement(word2), 'number': Math.floor(Math.random() * numLimit) }; return phraseObject; }, 'shuffleArray': function(array) { // Fisher Yates shuffle! let currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }, 'incrementArray': function(arr, element) { for(let i = 0; i < arr.length; i++) { if (arr[i].name === element) { arr[i].value += 1; return arr; } } // no match, create new element arr.push({'name':element, 'value': 1}); return arr; }, 'sortArray': function(arr) { return arr.sort(function(a,b) {return (a.value > b.value) ? -1 : ((b.value > a.value) ? 1 : 0);} ); }, 'rankArray': function(arr) { // assumes sorted array let rank = 0; let previousValue = 0; let tiesAll = {}; let ties = []; for(let i = 0; i < arr.length; i++) { if (arr[i].value !== previousValue) { rank += 1; ties = []; } ties.push(arr[i].name); arr[i].rank = rank; arr[i].ties = ties; previousValue = arr[i].value; } // list other elements tied at the same rank for(let i = 0; i < arr.length; i++) { let tiesCleaned = []; for (let j = 0; j < arr[i].ties.length; j++) { if (arr[i].ties[j] !== arr[i].name) { tiesCleaned.push(arr[i].ties[j]); } } arr[i].ties = tiesCleaned; } return arr; } }; // another way to define helpers: extend a native type with a new function Array.prototype.diff = function(a) { return this.filter(function(i) {return a.indexOf(i) < 0;}); };
SleepyDeveloper/alexa-cookbook
tools/TestFlow/sampleskill2/helpers.js
JavaScript
apache-2.0
12,083
import { test } from 'ember-qunit'; import moduleFor from 'open-event-frontend/tests/helpers/unit-helper'; moduleFor('controller:public/cfs/new-speaker', 'Unit | Controller | public/cfs/new speaker', []); test('it exists', function(assert) { let controller = this.subject(); assert.ok(controller); });
harshitagupta30/open-event-frontend
tests/unit/controllers/public/cfs/new-speaker-test.js
JavaScript
apache-2.0
308
var mailServiceRoutes = (function () { 'use strict'; var HTTPStatus = require('http-status'), express = require('express'), tokenAuthMiddleware = require('../middlewares/token.authentication.middleware'), roleAuthMiddleware = require('../middlewares/role.authorization.middleware'), messageConfig = require('../configs/api.message.config'), emailServiceController = require('../controllers/email.service.server.controller'), mailServiceRouter = express.Router(); mailServiceRouter.route('/') /** * @api {get} /api/emailservice/ Get Email Service Setting Configuration Info * @apiPermission admin * @apiName getMailServiceConfig * @apiGroup EmailServiceSetting * @apiDescription Retrieves the Email Service setting Information Object if exists, else return empty object * @apiVersion 0.0.1 * @apiHeader (AuthorizationHeader) {String} authorization x-access-token value. * @apiHeaderExample {json} Header-Example: *{ * "x-access-token": "yJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImVtYWlsIjoiaGVsbG9AYml0c" * } * * @apiExample {curl} Example usage: * curl -i http://localhost:3000/api/emailservice * * * @apiSuccess {String} _id object id of the email service configuration data * @apiSuccess {String} serviceProviderType Type of Email service Providers. Email Service Providers can be any one of - 'mailgun', 'postmark', 'mandrill', 'sendgrid', 'amazon' or 'normal' email sending mechanism using google smtp * @apiSuccess {String} host hostname or IP address to connect to (defaults to 'localhost'). for [normal smtp] * @apiSuccess {Number} port port to connect to (defaults to 25 or 465). for [normal smtp] * @apiSuccess {String} authUserName authentication username, mainly google email address for google smtp. for [normal smtp] * @apiSuccess {String} authPassword password for the gmail account or user. for [normal smtp] * @apiSuccess {String} api_Key secret unique key to access the email service provider api. needed for [mandrill, mailgun, Amazon, sendGrid, postmark] * @apiSuccess {String} api_Secret secret unique key to access the email service provider api.needed for [Amaazon;] * @apiSuccess {String} api_User username of the user registered in the email service provider user database. * @apiSuccess {String} domain domain name of the email service provider. [mailgun] * @apiSuccess {Date} addedOn date at which email service configuration is saved. * @apiSuccess {Number} rateLimit limits the message count to be sent in a second (defaults to false) - available only if pool is set to true. needed for [Amazon ses] * @apiSuccess {Boolean} pool if set to true uses pooled connections (defaults to false), otherwise creates a new connection for every e-mail. * @apiSuccess {Boolean} secure if true the connection will only use TLS. If false (the default), TLS may still be upgraded to if available via the STARTTLS command. for [normal smtp] * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "57357eb98b22c55e361176a2", * "serviceProviderType": "mailgun", * "host": "smtp.gmail.com", * "port": 8000, * "authUserName": "shrawanlakhey@gmail.com", * "authPassword": "lakdehe@123", * "api_Key": "key-dfsew", * "api_Secret": "api-fdsfsd", * "api_User": "shrawan", * "domain": "sandbox73ad601fcdd74461b1c46820a59b2374.mailgun.org", * "addedOn": "2016-05-13T07:14:01.496Z", * "rateLimit": 300, * "pool": false, * "secure": true * } * * @apiError (UnAuthorizedError) {String} message authentication token was not supplied * @apiError (UnAuthorizedError) {Boolean} isToken to check if token is supplied or not , if token is supplied , returns true else returns false * @apiError (UnAuthorizedError) {Boolean} success true if jwt token verifies * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "isToken": true, * "success": false, * "message": "Authentication failed" * } * * * @apiError (UnAuthorizedError_1) {String} message You are not authorized to access this api route. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "message": "You are not authorized to access this api route." * } * * @apiError (UnAuthorizedError_2) {String} message You are not authorized to perform this action. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "message": "You are not authorized to perform this action" * } * * * @apiError (NotFound) {String} message Email service configuration not found * * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "message": "Email service configuration not found" * } * * @apiError (InternalServerError) {String} message Internal Server Error * * @apiErrorExample Error-Response: * HTTP/1.1 500 Internal Server Error * { * "message": "Internal Server Error" * } * */ .get( tokenAuthMiddleware.authenticate, roleAuthMiddleware.authorize, getMailServiceConfig ) /** * @api {post} /api/emailservice/ Post Email Service Configuration Info * @apiPermission admin * @apiName postMailServiceConfig * @apiGroup EmailServiceSetting * @apiParam {String} Mandatory serviceProviderType Type of Email service Providers. Email Service Providers can be any one of - 'mailgun', 'postmark', 'mandrill', 'sendgrid', 'amazon' or 'normal' email sending mechanism using google smtp * @apiDescription saves email service configuration setting information to the database so that we can send email to our users * @apiVersion 0.0.1 * @apiHeader (AuthorizationHeader) {String} authorization x-access-token value. * @apiHeaderExample {json} Header-Example: *{ * "x-access-token": "yJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImVtYWlsIjoiaGVsbG9AYml0c" * } * * @apiExample {curl} Example usage: * * curl \ * -v \ * -X POST \ * http://localhost:3000/api/emailservice \ * -H 'Content-Type: application/json' \ * -H 'x-access-token: eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImVtYWlsIjoiaGVsbG9AYml0c2JlYXQuY29tIiwidXNlcm5hbWUiOiJzdXBlcmFkbWluIiwiX2lkIjoiNTc3ZjVjMWI1ODY5OTAyZDY3ZWIyMmE4IiwidXNlckNvbmZpcm1lZCI6ZmFsc2UsImJsb2NrZWQiOmZhbHNlLCJkZWxldGVkIjpmYWxzZSwiYWRkZWRPbiI6IjIwMTYtMDctMDhUMDc6NTQ6MDMuNzY2WiIsInR3b0ZhY3RvckF1dGhFbmFibGVkIjpmYWxzZSwidXNlclJvbGUiOiJhZG1pbiIsImFjdGl2ZSI6dHJ1ZX0sImNsYWltcyI6eyJzdWJqZWN0IjoiNTc3ZjVjMWI1ODY5OTAyZDY3ZWIyMmE4IiwiaXNzdWVyIjoiaHR0cDovL2xvY2FsaG9zdDozMDAwIiwicGVybWlzc2lvbnMiOlsic2F2ZSIsInVwZGF0ZSIsInJlYWQiLCJkZWxldGUiXX0sImlhdCI6MTQ2ODUzMzgzMiwiZXhwIjoxNDY4NTUzODMyLCJpc3MiOiI1NzdmNWMxYjU4Njk5MDJkNjdlYjIyYTgifQ.bmHC9pUtN1aOZUOc62nNfywggLBUfpLhs0CyMuunhEpVJq4WLYZ7fcr2Ap8xn0WYL_yODPPuSYGIFZ8uk4nilA' \ * -d '{"serviceProviderType":"mailgun","domain":"www.mailgun.com","api_Key":"helloapikey123456"}' * * @apiSuccess {String} message Email service configuration saved successfully. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "message": "Email service configuration saved successfully" * } * * @apiError (UnAuthorizedError) {String} message authentication token was not supplied * @apiError (UnAuthorizedError) {Boolean} isToken to check if token is supplied or not , if token is supplied , returns true else returns false * @apiError (UnAuthorizedError) {Boolean} success true if jwt token verifies * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "isToken": true, * "success": false, * "message": "Authentication failed" * } * * * @apiError (UnAuthorizedError_1) {String} message You are not authorized to access this api route. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "message": "You are not authorized to access this api route." * } * * @apiError (UnAuthorizedError_2) {String} message You are not authorized to perform this action. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "message": "You are not authorized to perform this action" * } * * * @apiError (AlreadyExists) {String} message Email Service setting configuration already exists, only can update existing data. new inserts is not allowed * * @apiErrorExample Error-Response: * HTTP/1.1 409 Conflict * { * "message": "You can only update email service configuration setting" * } * * * @apiError (BadRequest) {String[]} message Email service configuration setting post method throws error if serviceProviderType, is not provided or invalid data entry for host, port authUserName, domain and rateLimit * * @apiErrorExample Error-Response: * HTTP/1.1 400 Bad Request * { * "message": "[{"param":"serviceProviderType","msg":"Email service provider is required","value":""},{"param":"domain","msg":"Invalid domain","value":"www."}]" * } * * @apiError (InternalServerError) {String} message Internal Server Error * * @apiErrorExample Error-Response: * HTTP/1.1 500 Internal Server Error * { * "message": "Internal Server Error" * } * */ .post( tokenAuthMiddleware.authenticate, roleAuthMiddleware.authorize, emailServiceController.postMailServiceConfig ); //middleware function that will be executed for every routes below this to get email service configuration setting object using id as parameter mailServiceRouter.use('/:mailServiceConfigId', tokenAuthMiddleware.authenticate, roleAuthMiddleware.authorize, function(req, res, next){ emailServiceController.getMailServiceConfigByID(req) .then(function(mailServiceConfig){ //saving in request object so that it can be used for other operations like updating data using put and patch method if(mailServiceConfig){ req.mailService = mailServiceConfig; next(); return null;// return a non-undefined value to signal that we didn't forget to return promise }else{ res.status(HTTPStatus.NOT_FOUND); res.json({ message: messageConfig.emailService.notFound }); } }) .catch(function(err){ return next(err); }); }); mailServiceRouter.route('/:mailServiceConfigId') /** * @api {get} /api/emailservice/:mailServiceConfigId Get Email Service Setting Configuration Info by id * @apiPermission admin * @apiName getMailServiceConfigByID * @apiGroup EmailServiceSetting * * * @apiParam {String} mailServiceConfigId object id of the email service data * * * @apiParamExample {json} Request-Example: * { * "mailServiceConfigId": "57889ae9585d9632523f1234" * } * * * @apiDescription Retrieves the Email Service setting Information Object by id if exists, else return empty object * @apiVersion 0.0.1 * @apiHeader (AuthorizationHeader) {String} authorization x-access-token value. * @apiHeaderExample {json} Header-Example: *{ * "x-access-token": "yJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImVtYWlsIjoiaGVsbG9AYml0c" * } * * @apiExample {curl} Example usage: * curl -i http://localhost:3000/api/emailservice/57357eb98b22c55e361176a2 \ * -H 'x-access-token: eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImVtYWlsIjoiaGVsbG9AYml0c2JlYXQuY29tIiwidXNlcm5hbWUiOiJzdXBlcmFkbWluIiwiX2lkIjoiNTc3ZjVjMWI1ODY5OTAyZDY3ZWIyMmE4IiwidXNlckNvbmZpcm1lZCI6ZmFsc2UsImJsb2NrZWQiOmZhbHNlLCJkZWxldGVkIjpmYWxzZSwiYWRkZWRPbiI6IjIwMTYtMDctMDhUMDc6NTQ6MDMuNzY2WiIsInR3b0ZhY3RvckF1dGhFbmFibGVkIjpmYWxzZSwidXNlclJvbGUiOiJhZG1pbiIsImFjdGl2ZSI6dHJ1ZX0sImNsYWltcyI6eyJzdWJqZWN0IjoiNTc3ZjVjMWI1ODY5OTAyZDY3ZWIyMmE4IiwiaXNzdWVyIjoiaHR0cDovL2xvY2FsaG9zdDozMDAwIiwicGVybWlzc2lvbnMiOlsic2F2ZSIsInVwZGF0ZSIsInJlYWQiLCJkZWxldGUiXX0sImlhdCI6MTQ2ODMxNjg4MiwiZXhwIjoxNDY4MzM2ODgyLCJpc3MiOiI1NzdmNWMxYjU4Njk5MDJkNjdlYjIyYTgifQ.agd70Nk8y4bcORqzQP4eTSZW_3lN9TpC9zIpKM5j98RkNqS43qVPRQyN3DfRS6CKblHyvYASisvQGpCvJSyfgw' * * * * @apiSuccess {String} _id object id of the email service configuration data * @apiSuccess {String} serviceProviderType Type of Email service Providers. Email Service Providers can be any one of - 'mailgun', 'postmark', 'mandrill', 'sendgrid', 'amazon' or 'normal' email sending mechanism using google smtp * @apiSuccess {String} host hostname or IP address to connect to (defaults to 'localhost'). for [normal smtp] * @apiSuccess {Number} port port to connect to (defaults to 25 or 465). for [normal smtp] * @apiSuccess {String} authUserName authentication username, mainly google email address for google smtp. for [normal smtp] * @apiSuccess {String} authPassword password for the gmail account or user. for [normal smtp] * @apiSuccess {String} api_Key secret unique key to access the email service provider api. needed for [mandrill, mailgun, Amazon, sendGrid, postmark] * @apiSuccess {String} api_Secret secret unique key to access the email service provider api.needed for [Amaazon;] * @apiSuccess {String} api_User username of the user registered in the email service provider user database. * @apiSuccess {String} domain domain name of the email service provider. [mailgun] * @apiSuccess {Date} addedOn date at which email service configuration is saved. * @apiSuccess {Number} rateLimit limits the message count to be sent in a second (defaults to false) - available only if pool is set to true. needed for [Amazon ses] * @apiSuccess {Boolean} pool if set to true uses pooled connections (defaults to false), otherwise creates a new connection for every e-mail. * @apiSuccess {Boolean} secure if true the connection will only use TLS. If false (the default), TLS may still be upgraded to if available via the STARTTLS command. for [normal smtp] * * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "57357eb98b22c55e361176a2", * "serviceProviderType": "mailgun", * "host": "smtp.gmail.com", * "port": 8000, * "authUserName": "shrawanlakhey@gmail.com", * "authPassword": "lakdehe@123", * "api_Key": "key-dfsew", * "api_Secret": "api-fdsfsd", * "api_User": "shrawan", * "domain": "sandbox73ad601fcdd74461b1c46820a59b2374.mailgun.org", * "addedOn": "2016-05-13T07:14:01.496Z", * "rateLimit": 300, * "pool": false, * "secure": true * } * * @apiError (UnAuthorizedError) {String} message authentication token was not supplied * @apiError (UnAuthorizedError) {Boolean} isToken to check if token is supplied or not , if token is supplied , returns true else returns false * @apiError (UnAuthorizedError) {Boolean} success true if jwt token verifies * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "isToken": true, * "success": false, * "message": "Authentication failed" * } * * * @apiError (UnAuthorizedError_1) {String} message You are not authorized to access this api route. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "message": "You are not authorized to access this api route." * } * * @apiError (UnAuthorizedError_2) {String} message You are not authorized to perform this action. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "message": "You are not authorized to perform this action" * } * * * @apiError (NotFound) {String} message Email service configuration not found * * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "message": "Email service configuration not found" * } * * @apiError (InternalServerError) {String} message Internal Server Error * * @apiErrorExample Error-Response: * HTTP/1.1 500 Internal Server Error * { * "message": "Internal Server Error" * } * */ .get(function(req, res){ res.status(HTTPStatus.OK); res.json(req.mailService); }) /** * @api {put} /api/emailservice/:mailServiceConfigId Updates Email Service Configuration Info * @apiPermission admin * @apiName updateMailService * @apiGroup EmailServiceSetting * * * @apiParam {String} mailServiceConfigId object id of the email service data * * * @apiParamExample {json} Request-Example: * { * "mailServiceConfigId": "57889ae9585d9632523f1234" * } * * * @apiDescription Updates existing email service configuration setting information to the database so that we can send email to our users * @apiVersion 0.0.1 * @apiHeader (AuthorizationHeader) {String} authorization x-access-token value. * @apiHeaderExample {json} Header-Example: *{ * "x-access-token": "yJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImVtYWlsIjoiaGVsbG9AYml0c" * } * * @apiExample {curl} Example usage: * * curl \ * -v \ * -X PUT \ * http://localhost:3000/api/emailservice/5788105fd519f49e17f0579f \ * -H 'Content-Type: application/json' \ * -H 'x-access-token: eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImVtYWlsIjoiaGVsbG9AYml0c2JlYXQuY29tIiwidXNlcm5hbWUiOiJzdXBlcmFkbWluIiwiX2lkIjoiNTc3ZjVjMWI1ODY5OTAyZDY3ZWIyMmE4IiwidXNlckNvbmZpcm1lZCI6ZmFsc2UsImJsb2NrZWQiOmZhbHNlLCJkZWxldGVkIjpmYWxzZSwiYWRkZWRPbiI6IjIwMTYtMDctMDhUMDc6NTQ6MDMuNzY2WiIsInR3b0ZhY3RvckF1dGhFbmFibGVkIjpmYWxzZSwidXNlclJvbGUiOiJhZG1pbiIsImFjdGl2ZSI6dHJ1ZX0sImNsYWltcyI6eyJzdWJqZWN0IjoiNTc3ZjVjMWI1ODY5OTAyZDY3ZWIyMmE4IiwiaXNzdWVyIjoiaHR0cDovL2xvY2FsaG9zdDozMDAwIiwicGVybWlzc2lvbnMiOlsic2F2ZSIsInVwZGF0ZSIsInJlYWQiLCJkZWxldGUiXX0sImlhdCI6MTQ2ODUzMzgzMiwiZXhwIjoxNDY4NTUzODMyLCJpc3MiOiI1NzdmNWMxYjU4Njk5MDJkNjdlYjIyYTgifQ.bmHC9pUtN1aOZUOc62nNfywggLBUfpLhs0CyMuunhEpVJq4WLYZ7fcr2Ap8xn0WYL_yODPPuSYGIFZ8uk4nilA' \ * -d '{"serviceProviderType":"postmark","domain":"www.mailgun.com","api_Key":"helloapikey123456"}' * * @apiSuccess {String} message Email service configuration updated successfully. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "message": "Email service configuration updated successfully" * } * * @apiError (UnAuthorizedError) {String} message authentication token was not supplied * @apiError (UnAuthorizedError) {Boolean} isToken to check if token is supplied or not , if token is supplied , returns true else returns false * @apiError (UnAuthorizedError) {Boolean} success true if jwt token verifies * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "isToken": true, * "success": false, * "message": "Authentication failed" * } * * * @apiError (UnAuthorizedError_1) {String} message You are not authorized to access this api route. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "message": "You are not authorized to access this api route." * } * * @apiError (UnAuthorizedError_2) {String} message You are not authorized to perform this action. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * { * "message": "You are not authorized to perform this action" * } * * * * @apiError (BadRequest) {String[]} message Email service configuration setting put method throws error if serviceProviderType, is not provided or invalid data entry for host, port authUserName, domain and rateLimit * * @apiErrorExample Error-Response: * HTTP/1.1 400 Bad Request * { * "message": "[{"param":"serviceProviderType","msg":"Email service provider is required","value":""},{"param":"domain","msg":"Invalid domain","value":"www."}]" * } * * @apiError (InternalServerError) {String} message Internal Server Error * * @apiErrorExample Error-Response: * HTTP/1.1 500 Internal Server Error * { * "message": "Internal Server Error" * } * */ .put( tokenAuthMiddleware.authenticate, roleAuthMiddleware.authorize, emailServiceController.updateMailService ); //function declaration to return email service configuration object to the client if exists else return not found message function getMailServiceConfig(req, res, next) { emailServiceController.getMailServiceConfig() .then(function(mailServiceConfig){ //if exists, return data in json format if (mailServiceConfig) { res.status(HTTPStatus.OK); res.json(mailServiceConfig); } else { res.status(HTTPStatus.NOT_FOUND); res.json({ message: messageConfig.emailService.notFound }); } }) .catch(function(err){ return next(err); }); } return mailServiceRouter; })(); module.exports = mailServiceRoutes;
avsek477/blogSite
lib/routes/email.service.configure.route.js
JavaScript
apache-2.0
23,312
// (C) Copyright 2015 Martin Dougiamas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. angular.module('mm.core') /** * Directive to open a link in external browser. * * @module mm.core * @ngdoc directive * @name mmBrowser * * @param {Boolean} [captureLink=false] If the link needs to be captured by the app. */ .directive('mmBrowser', function($mmUtil, $mmContentLinksHelper) { /** * Convenience function to open file or url in the browser. * * @param {String} href HREF to be opened */ function openInBrowser(href) { if (href.indexOf('cdvfile://') === 0 || href.indexOf('file://') === 0) { // We have a local file. $mmUtil.openFile(href).catch(function(error) { $mmUtil.showErrorModal(error); }); } else { // It's an external link, we will open with browser. $mmUtil.openInBrowser(href); } } return { restrict: 'A', priority: 100, link: function(scope, element, attrs) { element.on('click', function(event) { var href = element[0].getAttribute('href'); if (href) { event.preventDefault(); event.stopPropagation(); if (attrs.captureLink && attrs.captureLink !== 'false') { $mmContentLinksHelper.handleLink(href).then(function(treated) { if (!treated) { openInBrowser(href); } }); } else { openInBrowser(href); } } }); } }; });
jorisnicolas/moodlemobile2
www/core/directives/browser.js
JavaScript
apache-2.0
2,257
function test() { let tempScope = {}; Components.utils.import("resource://gre/modules/InlineSpellChecker.jsm", tempScope); let InlineSpellChecker = tempScope.InlineSpellChecker; ok(InlineSpellChecker, "InlineSpellChecker class exists"); for (var fname in tests) { tests[fname](); } } let tests = { // Test various possible dictionary name to ensure they display as expected. // XXX: This only works for the 'en-US' locale, as the testing involves localized output. testDictionaryDisplayNames: function() { let isc = new InlineSpellChecker(); // Check non-well-formed language tag. is(isc.getDictionaryDisplayName("-invalid-"), "-invalid-", "'-invalid-' should display as '-invalid-'"); // XXX: It isn't clear how we'd ideally want to display variant subtags. // Check valid language subtag. is(isc.getDictionaryDisplayName("en"), "English", "'en' should display as 'English'"); is(isc.getDictionaryDisplayName("en-fonipa"), "English (fonipa)", "'en-fonipa' should display as 'English (fonipa)'"); is(isc.getDictionaryDisplayName("en-qxqaaaaz"), "English (qxqaaaaz)", "'en-qxqaaaaz' should display as 'English (qxqaaaaz)'"); // Check valid language subtag and valid region subtag. is(isc.getDictionaryDisplayName("en-US"), "English (United States)", "'en-US' should display as 'English (United States)'"); is(isc.getDictionaryDisplayName("en-US-fonipa"), "English (United States) (fonipa)", "'en-US-fonipa' should display as 'English (United States) (fonipa)'"); is(isc.getDictionaryDisplayName("en-US-qxqaaaaz"), "English (United States) (qxqaaaaz)", "'en-US-qxqaaaaz' should display as 'English (United States) (qxqaaaaz)'"); // Check valid language subtag and invalid but well-formed region subtag. is(isc.getDictionaryDisplayName("en-QZ"), "English (QZ)", "'en-QZ' should display as 'English (QZ)'"); is(isc.getDictionaryDisplayName("en-QZ-fonipa"), "English (QZ) (fonipa)", "'en-QZ-fonipa' should display as 'English (QZ) (fonipa)'"); is(isc.getDictionaryDisplayName("en-QZ-qxqaaaaz"), "English (QZ) (qxqaaaaz)", "'en-QZ-qxqaaaaz' should display as 'English (QZ) (qxqaaaaz)'"); // Check valid language subtag and valid script subtag. todo_is(isc.getDictionaryDisplayName("en-Cyrl"), "English / Cyrillic", "'en-Cyrl' should display as 'English / Cyrillic'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-fonipa"), "English / Cyrillic (fonipa)", "'en-Cyrl-fonipa' should display as 'English / Cyrillic (fonipa)'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-qxqaaaaz"), "English / Cyrillic (qxqaaaaz)", "'en-Cyrl-qxqaaaaz' should display as 'English / Cyrillic (qxqaaaaz)'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-US"), "English (United States) / Cyrillic", "'en-Cyrl-US' should display as 'English (United States) / Cyrillic'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-US-fonipa"), "English (United States) / Cyrillic (fonipa)", "'en-Cyrl-US-fonipa' should display as 'English (United States) / Cyrillic (fonipa)'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-US-qxqaaaaz"), "English (United States) / Cyrillic (qxqaaaaz)", "'en-Cyrl-US-qxqaaaaz' should display as 'English (United States) / Cyrillic (qxqaaaaz)'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-QZ"), "English (QZ) / Cyrillic", "'en-Cyrl-QZ' should display as 'English (QZ) / Cyrillic'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-QZ-fonipa"), "English (QZ) / Cyrillic (fonipa)", "'en-Cyrl-QZ-fonipa' should display as 'English (QZ) / Cyrillic (fonipa)'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-QZ-qxqaaaaz"), "English (QZ) / Cyrillic (qxqaaaaz)", "'en-Cyrl-QZ-qxqaaaaz' should display as 'English (QZ) / Cyrillic (qxqaaaaz)'"); // Check valid language subtag and invalid but well-formed script subtag. is(isc.getDictionaryDisplayName("en-Qaaz"), "English / Qaaz", "'en-Qaaz' should display as 'English / Qaaz'"); is(isc.getDictionaryDisplayName("en-Qaaz-fonipa"), "English / Qaaz (fonipa)", "'en-Qaaz-fonipa' should display as 'English / Qaaz (fonipa)'"); is(isc.getDictionaryDisplayName("en-Qaaz-qxqaaaaz"), "English / Qaaz (qxqaaaaz)", "'en-Qaaz-qxqaaaaz' should display as 'English / Qaaz (qxqaaaaz)'"); is(isc.getDictionaryDisplayName("en-Qaaz-US"), "English (United States) / Qaaz", "'en-Qaaz-US' should display as 'English (United States) / Qaaz'"); is(isc.getDictionaryDisplayName("en-Qaaz-US-fonipa"), "English (United States) / Qaaz (fonipa)", "'en-Qaaz-US-fonipa' should display as 'English (United States) / Qaaz (fonipa)'"); is(isc.getDictionaryDisplayName("en-Qaaz-US-qxqaaaaz"), "English (United States) / Qaaz (qxqaaaaz)", "'en-Qaaz-US-qxqaaaaz' should display as 'English (United States) / Qaaz (qxqaaaaz)'"); is(isc.getDictionaryDisplayName("en-Qaaz-QZ"), "English (QZ) / Qaaz", "'en-Qaaz-QZ' should display as 'English (QZ) / Qaaz'"); is(isc.getDictionaryDisplayName("en-Qaaz-QZ-fonipa"), "English (QZ) / Qaaz (fonipa)", "'en-Qaaz-QZ-fonipa' should display as 'English (QZ) / Qaaz (fonipa)'"); is(isc.getDictionaryDisplayName("en-Qaaz-QZ-qxqaaaaz"), "English (QZ) / Qaaz (qxqaaaaz)", "'en-Qaaz-QZ-qxqaaaaz' should display as 'English (QZ) / Qaaz (qxqaaaaz)'"); // Check invalid but well-formed language subtag. is(isc.getDictionaryDisplayName("qaz"), "qaz", "'qaz' should display as 'qaz'"); is(isc.getDictionaryDisplayName("qaz-fonipa"), "qaz (fonipa)", "'qaz-fonipa' should display as 'qaz (fonipa)'"); is(isc.getDictionaryDisplayName("qaz-qxqaaaaz"), "qaz (qxqaaaaz)", "'qaz-qxqaaaaz' should display as 'qaz (qxqaaaaz)'"); // Check invalid but well-formed language subtag and valid region subtag. is(isc.getDictionaryDisplayName("qaz-US"), "qaz (United States)", "'qaz-US' should display as 'qaz (United States)'"); is(isc.getDictionaryDisplayName("qaz-US-fonipa"), "qaz (United States) (fonipa)", "'qaz-US-fonipa' should display as 'qaz (United States) (fonipa)'"); is(isc.getDictionaryDisplayName("qaz-US-qxqaaaaz"), "qaz (United States) (qxqaaaaz)", "'qaz-US-qxqaaaaz' should display as 'qaz (United States) (qxqaaaaz)'"); // Check invalid but well-formed language subtag and invalid but well-formed region subtag. is(isc.getDictionaryDisplayName("qaz-QZ"), "qaz (QZ)", "'qaz-QZ' should display as 'qaz (QZ)'"); is(isc.getDictionaryDisplayName("qaz-QZ-fonipa"), "qaz (QZ) (fonipa)", "'qaz-QZ-fonipa' should display as 'qaz (QZ) (fonipa)'"); is(isc.getDictionaryDisplayName("qaz-QZ-qxqaaaaz"), "qaz (QZ) (qxqaaaaz)", "'qaz-QZ-qxqaaaaz' should display as 'qaz (QZ) (qxqaaaaz)'"); // Check invalid but well-formed language subtag and valid script subtag. todo_is(isc.getDictionaryDisplayName("qaz-Cyrl"), "qaz / Cyrillic", "'qaz-Cyrl' should display as 'qaz / Cyrillic'"); todo_is(isc.getDictionaryDisplayName("qaz-Cyrl-fonipa"), "qaz / Cyrillic (fonipa)", "'qaz-Cyrl-fonipa' should display as 'qaz / Cyrillic (fonipa)'"); todo_is(isc.getDictionaryDisplayName("qaz-Cyrl-qxqaaaaz"), "qaz / Cyrillic (qxqaaaaz)", "'qaz-Cyrl-qxqaaaaz' should display as 'qaz / Cyrillic (qxqaaaaz)'"); todo_is(isc.getDictionaryDisplayName("qaz-Cyrl-US"), "qaz (United States) / Cyrillic", "'qaz-Cyrl-US' should display as 'qaz (United States) / Cyrillic'"); todo_is(isc.getDictionaryDisplayName("qaz-Cyrl-US-fonipa"), "qaz (United States) / Cyrillic (fonipa)", "'qaz-Cyrl-US-fonipa' should display as 'qaz (United States) / Cyrillic (fonipa)'"); todo_is(isc.getDictionaryDisplayName("qaz-Cyrl-US-qxqaaaaz"), "qaz (United States) / Cyrillic (qxqaaaaz)", "'qaz-Cyrl-US-qxqaaaaz' should display as 'qaz (United States) / Cyrillic (qxqaaaaz)'"); todo_is(isc.getDictionaryDisplayName("qaz-Cyrl-QZ"), "qaz (QZ) / Cyrillic", "'qaz-Cyrl-QZ' should display as 'qaz (QZ) / Cyrillic'"); todo_is(isc.getDictionaryDisplayName("qaz-Cyrl-QZ-fonipa"), "qaz (QZ) / Cyrillic (fonipa)", "'qaz-Cyrl-QZ-fonipa' should display as 'qaz (QZ) / Cyrillic (fonipa)'"); todo_is(isc.getDictionaryDisplayName("qaz-Cyrl-QZ-qxqaaaaz"), "qaz (QZ) / Cyrillic (qxqaaaaz)", "'qaz-Cyrl-QZ-qxqaaaaz' should display as 'qaz (QZ) / Cyrillic (qxqaaaaz)'"); // Check invalid but well-formed language subtag and invalid but well-formed script subtag. is(isc.getDictionaryDisplayName("qaz-Qaaz"), "qaz / Qaaz", "'qaz-Qaaz' should display as 'qaz / Qaaz'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-fonipa"), "qaz / Qaaz (fonipa)", "'qaz-Qaaz-fonipa' should display as 'qaz / Qaaz (fonipa)'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-qxqaaaaz"), "qaz / Qaaz (qxqaaaaz)", "'qaz-Qaaz-qxqaaaaz' should display as 'qaz / Qaaz (qxqaaaaz)'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-US"), "qaz (United States) / Qaaz", "'qaz-Qaaz-US' should display as 'qaz (United States) / Qaaz'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-US-fonipa"), "qaz (United States) / Qaaz (fonipa)", "'qaz-Qaaz-US-fonipa' should display as 'qaz (United States) / Qaaz (fonipa)'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-US-qxqaaaaz"), "qaz (United States) / Qaaz (qxqaaaaz)", "'qaz-Qaaz-US-qxqaaaaz' should display as 'qaz (United States) / Qaaz (qxqaaaaz)'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-QZ"), "qaz (QZ) / Qaaz", "'qaz-Qaaz-QZ' should display as 'qaz (QZ) / Qaaz'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-QZ-fonipa"), "qaz (QZ) / Qaaz (fonipa)", "'qaz-Qaaz-QZ-fonipa' should display as 'qaz (QZ) / Qaaz (fonipa)'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-QZ-qxqaaaaz"), "qaz (QZ) / Qaaz (qxqaaaaz)", "'qaz-Qaaz-QZ-qxqaaaaz' should display as 'qaz (QZ) / Qaaz (qxqaaaaz)'"); // Check multiple variant subtags. todo_is(isc.getDictionaryDisplayName("en-Cyrl-US-fonipa-fonxsamp"), "English (United States) / Cyrillic (fonipa / fonxsamp)", "'en-Cyrl-US-fonipa-fonxsamp' should display as 'English (United States) / Cyrillic (fonipa / fonxsamp)'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-US-fonipa-qxqaaaaz"), "English (United States) / Cyrillic (fonipa / qxqaaaaz)", "'en-Cyrl-US-fonipa-qxqaaaaz' should display as 'English (United States) / Cyrillic (fonipa / qxqaaaaz)'"); todo_is(isc.getDictionaryDisplayName("en-Cyrl-US-fonipa-fonxsamp-qxqaaaaz"), "English (United States) / Cyrillic (fonipa / fonxsamp / qxqaaaaz)", "'en-Cyrl-US-fonipa-fonxsamp-qxqaaaaz' should display as 'English (United States) / Cyrillic (fonipa / fonxsamp / qxqaaaaz)'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-QZ-fonipa-fonxsamp"), "qaz (QZ) / Qaaz (fonipa / fonxsamp)", "'qaz-Qaaz-QZ-fonipa-fonxsamp' should display as 'qaz (QZ) / Qaaz (fonipa / fonxsamp)'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-QZ-fonipa-qxqaaaaz"), "qaz (QZ) / Qaaz (fonipa / qxqaaaaz)", "'qaz-Qaaz-QZ-fonipa-qxqaaaaz' should display as 'qaz (QZ) / Qaaz (fonipa / qxqaaaaz)'"); is(isc.getDictionaryDisplayName("qaz-Qaaz-QZ-fonipa-fonxsamp-qxqaaaaz"), "qaz (QZ) / Qaaz (fonipa / fonxsamp / qxqaaaaz)", "'qaz-Qaaz-QZ-fonipa-fonxsamp-qxqaaaaz' should display as 'qaz (QZ) / Qaaz (fonipa / fonxsamp / qxqaaaaz)'"); // Check numeric region subtag. todo_is(isc.getDictionaryDisplayName("es-419"), "Spanish (Latin America and the Caribbean)", "'es-419' should display as 'Spanish (Latin America and the Caribbean)'"); // Check that extension subtags are ignored. todo_is(isc.getDictionaryDisplayName("en-Cyrl-t-en-latn-m0-ungegn-2007"), "English / Cyrillic", "'en-Cyrl-t-en-latn-m0-ungegn-2007' should display as 'English / Cyrillic'"); // Check that privateuse subtags are ignored. is(isc.getDictionaryDisplayName("en-x-ignore"), "English", "'en-x-ignore' should display as 'English'"); is(isc.getDictionaryDisplayName("en-x-ignore-this"), "English", "'en-x-ignore-this' should display as 'English'"); is(isc.getDictionaryDisplayName("en-x-ignore-this-subtag"), "English", "'en-x-ignore-this-subtag' should display as 'English'"); // Check that both extension and privateuse subtags are ignored. todo_is(isc.getDictionaryDisplayName("en-Cyrl-t-en-latn-m0-ungegn-2007-x-ignore-this-subtag"), "English / Cyrillic", "'en-Cyrl-t-en-latn-m0-ungegn-2007-x-ignore-this-subtag' should display as 'English / Cyrillic'"); // XXX: Check grandfathered tags. }, };
sergecodd/FireFox-OS
B2G/gecko/toolkit/content/tests/browser/browser_InlineSpellChecker.js
JavaScript
apache-2.0
12,254
import Marked from 'marked' import hljs from 'highlight.js' const renderer = new Marked.Renderer() export const toc = [] renderer.heading = function(text, level) { var slug = text.toLowerCase().replace(/\s+/g, '-') toc.push({ level: level, slug: slug, title: text }) return `<h${level}><a href='#${slug}' id='${slug}' class='anchor'></a><a href='#${slug}'>${text}</a></h${level}>` } Marked.setOptions({ highlight: function(code, lang) { if (hljs.getLanguage(lang)) { return hljs.highlight(lang, code).value } else { return hljs.highlightAuto(code).value } }, renderer }) export const marked = text => { var tok = Marked.lexer(text) text = Marked.parser(tok).replace(/<pre>/ig, '<pre class="hljs">') return text }
Smallpath/Blog
admin/src/components/utils/marked.js
JavaScript
apache-2.0
773
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const Cc = Components.classes; const Ci = Components.interfaces; const Cr = Components.results; Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); Components.utils.import("resource://gre/modules/Services.jsm"); /* ==================== LoginManagerPrompter ==================== */ /* * LoginManagerPrompter * * Implements interfaces for prompting the user to enter/save/change auth info. * * nsILoginManagerPrompter: Used by Login Manager for saving/changing logins * found in HTML forms. */ function LoginManagerPrompter() { } LoginManagerPrompter.prototype = { classID : Components.ID("97d12931-abe2-11df-94e2-0800200c9a66"), QueryInterface : XPCOMUtils.generateQI([Ci.nsILoginManagerPrompter]), _factory : null, _window : null, _debug : false, // mirrors signon.debug __pwmgr : null, // Password Manager service get _pwmgr() { if (!this.__pwmgr) this.__pwmgr = Cc["@mozilla.org/login-manager;1"]. getService(Ci.nsILoginManager); return this.__pwmgr; }, __promptService : null, // Prompt service for user interaction get _promptService() { if (!this.__promptService) this.__promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"]. getService(Ci.nsIPromptService2); return this.__promptService; }, __strBundle : null, // String bundle for L10N get _strBundle() { if (!this.__strBundle) { var bunService = Cc["@mozilla.org/intl/stringbundle;1"]. getService(Ci.nsIStringBundleService); this.__strBundle = bunService.createBundle( "chrome://passwordmgr/locale/passwordmgr.properties"); if (!this.__strBundle) throw "String bundle for Login Manager not present!"; } return this.__strBundle; }, __brandBundle : null, // String bundle for L10N get _brandBundle() { if (!this.__brandBundle) { var bunService = Cc["@mozilla.org/intl/stringbundle;1"]. getService(Ci.nsIStringBundleService); this.__brandBundle = bunService.createBundle( "chrome://branding/locale/brand.properties"); if (!this.__brandBundle) throw "Branding string bundle not present!"; } return this.__brandBundle; }, __ellipsis : null, get _ellipsis() { if (!this.__ellipsis) { this.__ellipsis = "\u2026"; try { this.__ellipsis = Services.prefs.getComplexValue( "intl.ellipsis", Ci.nsIPrefLocalizedString).data; } catch (e) { } } return this.__ellipsis; }, /* * log * * Internal function for logging debug messages to the Error Console window. */ log : function (message) { if (!this._debug) return; dump("Pwmgr Prompter: " + message + "\n"); Services.console.logStringMessage("Pwmgr Prompter: " + message); }, /* ---------- nsILoginManagerPrompter prompts ---------- */ /* * init * */ init : function (aWindow, aFactory) { this._window = aWindow; this._factory = aFactory || null; var prefBranch = Services.prefs.getBranch("signon."); this._debug = prefBranch.getBoolPref("debug"); this.log("===== initialized ====="); }, /* * promptToSavePassword * */ promptToSavePassword : function (aLogin) { this._showSaveLoginNotification(aLogin); }, /* * _showLoginNotification * * Displays a notification doorhanger. * */ _showLoginNotification : function (aName, aText, aButtons) { this.log("Adding new " + aName + " notification bar"); let notifyWin = this._window.top; let chromeWin = this._getChromeWindow(notifyWin).wrappedJSObject; let browser = chromeWin.BrowserApp.getBrowserForWindow(notifyWin); let tabID = chromeWin.BrowserApp.getTabForBrowser(browser).id; // The page we're going to hasn't loaded yet, so we want to persist // across the first location change. // Sites like Gmail perform a funky redirect dance before you end up // at the post-authentication page. I don't see a good way to // heuristically determine when to ignore such location changes, so // we'll try ignoring location changes based on a time interval. let options = { persistWhileVisible: true, timeout: Date.now() + 10000 } var nativeWindow = this._getNativeWindow(); if (nativeWindow) nativeWindow.doorhanger.show(aText, aName, aButtons, tabID, options); }, /* * _showSaveLoginNotification * * Displays a notification doorhanger (rather than a popup), to allow the user to * save the specified login. This allows the user to see the results of * their login, and only save a login which they know worked. * */ _showSaveLoginNotification : function (aLogin) { // Ugh. We can't use the strings from the popup window, because they // have the access key marked in the string (eg "Mo&zilla"), along // with some weird rules for handling access keys that do not occur // in the string, for L10N. See commonDialog.js's setLabelForNode(). var neverButtonText = this._getLocalizedString("notifyBarNeverForSiteButtonText"); var neverButtonAccessKey = this._getLocalizedString("notifyBarNeverForSiteButtonAccessKey"); var rememberButtonText = this._getLocalizedString("notifyBarRememberButtonText"); var rememberButtonAccessKey = this._getLocalizedString("notifyBarRememberButtonAccessKey"); var notNowButtonText = this._getLocalizedString("notifyBarNotNowButtonText"); var notNowButtonAccessKey = this._getLocalizedString("notifyBarNotNowButtonAccessKey"); var brandShortName = this._brandBundle.GetStringFromName("brandShortName"); var displayHost = this._getShortDisplayHost(aLogin.hostname); var notificationText; if (aLogin.username) { var displayUser = this._sanitizeUsername(aLogin.username); notificationText = this._getLocalizedString( "saveLoginText", [brandShortName, displayUser, displayHost]); } else { notificationText = this._getLocalizedString( "saveLoginTextNoUsername", [brandShortName, displayHost]); } // The callbacks in |buttons| have a closure to access the variables // in scope here; set one to |this._pwmgr| so we can get back to pwmgr // without a getService() call. var pwmgr = this._pwmgr; var buttons = [ // "Remember" button { label: rememberButtonText, accessKey: rememberButtonAccessKey, popup: null, callback: function() { pwmgr.addLogin(aLogin); } }, // "Never for this site" button { label: neverButtonText, accessKey: neverButtonAccessKey, popup: null, callback: function() { pwmgr.setLoginSavingEnabled(aLogin.hostname, false); } }, // "Not now" button { label: notNowButtonText, accessKey: notNowButtonAccessKey, popup: null, callback: function() { /* NOP */ } } ]; this._showLoginNotification("password-save", notificationText, buttons); }, /* * promptToChangePassword * * Called when we think we detect a password change for an existing * login, when the form being submitted contains multiple password * fields. * */ promptToChangePassword : function (aOldLogin, aNewLogin) { this._showChangeLoginNotification(aOldLogin, aNewLogin.password); }, /* * _showChangeLoginNotification * * Shows the Change Password notification doorhanger. * */ _showChangeLoginNotification : function (aOldLogin, aNewPassword) { var notificationText; if (aOldLogin.username) { let displayUser = this._sanitizeUsername(aOldLogin.username); notificationText = this._getLocalizedString( "passwordChangeText", [displayUser]); } else { notificationText = this._getLocalizedString( "passwordChangeTextNoUser"); } var changeButtonText = this._getLocalizedString("notifyBarChangeButtonText"); var changeButtonAccessKey = this._getLocalizedString("notifyBarChangeButtonAccessKey"); var dontChangeButtonText = this._getLocalizedString("notifyBarDontChangeButtonText"); var dontChangeButtonAccessKey = this._getLocalizedString("notifyBarDontChangeButtonAccessKey"); // The callbacks in |buttons| have a closure to access the variables // in scope here; set one to |this._pwmgr| so we can get back to pwmgr // without a getService() call. var self = this; var buttons = [ // "Yes" button { label: changeButtonText, accessKey: changeButtonAccessKey, popup: null, callback: function() { self._updateLogin(aOldLogin, aNewPassword); } }, // "No" button { label: dontChangeButtonText, accessKey: dontChangeButtonAccessKey, popup: null, callback: function() { // do nothing } } ]; this._showLoginNotification("password-change", notificationText, buttons); }, /* * promptToChangePasswordWithUsernames * * Called when we detect a password change in a form submission, but we * don't know which existing login (username) it's for. Asks the user * to select a username and confirm the password change. * * Note: The caller doesn't know the username for aNewLogin, so this * function fills in .username and .usernameField with the values * from the login selected by the user. * * Note; XPCOM stupidity: |count| is just |logins.length|. */ promptToChangePasswordWithUsernames : function (logins, count, aNewLogin) { const buttonFlags = Ci.nsIPrompt.STD_YES_NO_BUTTONS; var usernames = logins.map(function (l) l.username); var dialogText = this._getLocalizedString("userSelectText"); var dialogTitle = this._getLocalizedString("passwordChangeTitle"); var selectedIndex = { value: null }; // If user selects ok, outparam.value is set to the index // of the selected username. var ok = this._promptService.select(null, dialogTitle, dialogText, usernames.length, usernames, selectedIndex); if (ok) { // Now that we know which login to use, modify its password. var selectedLogin = logins[selectedIndex.value]; this.log("Updating password for user " + selectedLogin.username); this._updateLogin(selectedLogin, aNewLogin.password); } }, /* ---------- Internal Methods ---------- */ /* * _updateLogin */ _updateLogin : function (login, newPassword) { var now = Date.now(); var propBag = Cc["@mozilla.org/hash-property-bag;1"]. createInstance(Ci.nsIWritablePropertyBag); if (newPassword) { propBag.setProperty("password", newPassword); // Explicitly set the password change time here (even though it would // be changed automatically), to ensure that it's exactly the same // value as timeLastUsed. propBag.setProperty("timePasswordChanged", now); } propBag.setProperty("timeLastUsed", now); propBag.setProperty("timesUsedIncrement", 1); this._pwmgr.modifyLogin(login, propBag); }, /* * _getChromeWindow * * Given a content DOM window, returns the chrome window it's in. */ _getChromeWindow: function (aWindow) { var chromeWin = aWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShell) .chromeEventHandler.ownerDocument.defaultView; return chromeWin; }, /* * _getNativeWindow * * Returns the NativeWindow to this prompter, or null if there isn't * a NativeWindow available (w/ error sent to logcat). */ _getNativeWindow : function () { let nativeWindow = null; try { let notifyWin = this._window.top; let chromeWin = this._getChromeWindow(notifyWin).wrappedJSObject; if (chromeWin.NativeWindow) { nativeWindow = chromeWin.NativeWindow; } else { Cu.reportError("NativeWindow not available on window"); } } catch (e) { // If any errors happen, just assume no native window helper. Cu.reportError("No NativeWindow available: " + e); } return nativeWindow; }, /* * _getLocalizedString * * Can be called as: * _getLocalizedString("key1"); * _getLocalizedString("key2", ["arg1"]); * _getLocalizedString("key3", ["arg1", "arg2"]); * (etc) * * Returns the localized string for the specified key, * formatted if required. * */ _getLocalizedString : function (key, formatArgs) { if (formatArgs) return this._strBundle.formatStringFromName( key, formatArgs, formatArgs.length); else return this._strBundle.GetStringFromName(key); }, /* * _sanitizeUsername * * Sanitizes the specified username, by stripping quotes and truncating if * it's too long. This helps prevent an evil site from messing with the * "save password?" prompt too much. */ _sanitizeUsername : function (username) { if (username.length > 30) { username = username.substring(0, 30); username += this._ellipsis; } return username.replace(/['"]/g, ""); }, /* * _getFormattedHostname * * The aURI parameter may either be a string uri, or an nsIURI instance. * * Returns the hostname to use in a nsILoginInfo object (for example, * "http://example.com"). */ _getFormattedHostname : function (aURI) { var uri; if (aURI instanceof Ci.nsIURI) { uri = aURI; } else { uri = Services.io.newURI(aURI, null, null); } var scheme = uri.scheme; var hostname = scheme + "://" + uri.host; // If the URI explicitly specified a port, only include it when // it's not the default. (We never want "http://foo.com:80") port = uri.port; if (port != -1) { var handler = Services.io.getProtocolHandler(scheme); if (port != handler.defaultPort) hostname += ":" + port; } return hostname; }, /* * _getShortDisplayHost * * Converts a login's hostname field (a URL) to a short string for * prompting purposes. Eg, "http://foo.com" --> "foo.com", or * "ftp://www.site.co.uk" --> "site.co.uk". */ _getShortDisplayHost: function (aURIString) { var displayHost; var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"]. getService(Ci.nsIEffectiveTLDService); var idnService = Cc["@mozilla.org/network/idn-service;1"]. getService(Ci.nsIIDNService); try { var uri = Services.io.newURI(aURIString, null, null); var baseDomain = eTLDService.getBaseDomain(uri); displayHost = idnService.convertToDisplayIDN(baseDomain, {}); } catch (e) { this.log("_getShortDisplayHost couldn't process " + aURIString); } if (!displayHost) displayHost = aURIString; return displayHost; }, }; // end of LoginManagerPrompter implementation var component = [LoginManagerPrompter]; this.NSGetFactory = XPCOMUtils.generateNSGetFactory(component);
sergecodd/FireFox-OS
B2G/gecko/mobile/android/components/LoginManagerPrompter.js
JavaScript
apache-2.0
17,631
/*global module: false, require: false, console: false */ 'use strict'; var React = require('react'); var PureRenderMixin = require('./PureRenderMixin'); var DataTable = require('react-data-components-bd2k').DataTable; require('react-data-components-bd2k/css/table-twbs.css'); function buildHeader(onClick, title) { return ( <span> {title} <span onClick={ev => {ev.stopPropagation(); onClick(title); }} className='help glyphicon glyphicon-question-sign superscript'/> </span> ); } var columns = [ {title: 'Gene', prop: 'Gene symbol'}, {title: ' HGVS ', prop: 'HGVS'}, {title: 'Pathogenicity', prop: 'Clinical significance'}, {title: 'Allele origin', prop: 'Allele origin'}, {title: 'CVA', prop: 'ClinVarAccession'} ]; var VariantTable = React.createClass({ mixins: [PureRenderMixin], getData: function () { return this.refs.table.state.data; }, render: function () { var {data, onHeaderClick, onRowClick, ...opts} = this.props; return ( <DataTable ref='table' {...opts} buildRowOptions={r => ({title: 'click for details', onClick: () => onRowClick(r.id)})} buildHeader={title => buildHeader(onHeaderClick, title)} columns={columns} initialData={data} initialPageLength={10} initialSortBy={{ title: 'Gene', prop: 'Gene', order: 'descending' }} pageLengthOptions={[ 10, 50, 100 ]} keys={['id']} /> ); } }); module.exports = VariantTable;
vipints/brca-website
js/VariantTable.js
JavaScript
apache-2.0
1,469
'use strict'; // ------------------------------------------------------------------------------------------ Test Dependencies var fs = require('fs'); var path = require('path'); var should = require('chai').should(); var nconf = require('nconf'); nconf.argv() .env() .file('local', { file: path.join(__dirname, '../../../local.json') }) .file({ file: path.join(__dirname, '../../../config.json') }); var settings = require('../../../lib/settings'); describe('Index View', function() { var sandbox; before(function () { return new Promise(function(resolve, reject) { settings.get(function(err, settings) { should.exist(settings); should.not.exist(err); sandbox = settings; resolve(); }); }); }); beforeEach(function *() { yield browser.url(sandbox.general.baseUrl); }); it('should have the window title based on user settings', function *() { var title = yield browser.getTitle() title.should.be.equal(sandbox.general.title); }); it('should have the header title based on user settings', function *() { var header = yield browser.getText('#hp header h1') header.should.be.equal(sandbox.general.title); }); it('should have the header subtitle based on user settings', function *() { var subtitle = yield browser.getText('#hp header h2') subtitle.should.be.equal(sandbox.general.subtitle); }); it('should have a link to the home page', function *() { var link = yield browser.isExisting('#hp header a[href="/"]'); link.should.be.equal(true); var linkText = yield browser.getText('#hp header a[href="/"]'); linkText.should.be.equal(sandbox.general.title); }); it('should have a link to the settings page', function *() { var link = yield browser.isExisting('ul.nav > li > a'); link.should.be.equal(true); var linkText = yield browser.getText('ul.nav > li > a') linkText.should.be.equal('Settings'); }); it('should have a form to enable downloading a file', function *() { var form = yield browser.isExisting('.download form'); form.should.be.equal(true); var action = yield browser.getAttribute('.download form', 'action'); should.exist(action); action.should.be.equal(sandbox.general.baseUrl + '/download'); var submit = yield browser.isExisting('.download form button[type=submit]'); submit.should.be.equal(true); }); it('should not have a form to enable downloading a file if this feature is disabled', function *() { var currentValue = sandbox.general.enableDownload; if(currentValue) { var enableDownload = yield browser.click('ul.nav > li > a') .click('input#enableDownload') .submitForm('.tab-pane.active form') .waitForExist('.tab-pane.active .alert strong', 5000) .isExisting('input#enableDownload:checked'); enableDownload.should.be.equal(false); } var download = yield browser.url('/') .isExisting('.download'); download.should.be.equal(false); var form = yield browser.url('/') .isExisting('.download form'); form.should.be.equal(false); var submit = yield browser.url('/') .isExisting('.download form button[type=submit]'); submit.should.be.equal(false); if(currentValue) { var enableDownload = yield browser.click('ul.nav > li > a') .click('input#enableDownload') .submitForm('.tab-pane.active form') .waitForExist('.tab-pane.active .alert strong', 5000) .isExisting('input#enableDownload:checked'); enableDownload.should.be.equal(true); } }); it('should have a form to enable downloading a file which throws an error when trying to exploit path traversal', function *() { var form = yield browser.isExisting('.download form'); form.should.be.equal(true); var action = yield browser.getAttribute('.download form', 'action'); should.exist(action); action.should.be.equal(sandbox.general.baseUrl + '/download'); var submit = yield browser.isExisting('.download form button[type=submit]'); submit.should.be.equal(true); var error = yield browser.setValue('input[name="token"]', '../config') .submitForm('.download form button[type=submit]') .waitForExist('.download form span.help-block span.text-danger') .getText('.download form span.help-block span.text-danger'); error.should.equals('Oh my... something went terribly wrong!'); }); it('should have a dropzone', function *() { var dropzone = yield browser.isExisting('.dz-action-add.dz-clickable.dropzone'); dropzone.should.be.equal(true); var previewTemplate = yield browser.isExisting('.dropzone .dz-preview-template'); previewTemplate.should.be.equal(true); var message = yield browser.isExisting('.dropzone .dz-default.dz-message'); message.should.be.equal(true); }); it('should have a fallback to dropzone', function *() { var currentValue = sandbox.dropzone.fallback; var fallback = yield browser.click('ul.nav > li > a') .click('a[href="/settings/transfer"]') .click('input#forceFallback') .submitForm('.tab-pane.active form') .url('/') .isExisting('.fallback'); fallback.should.be.equal(true); if(!currentValue) { fallback = yield browser.click('ul.nav > li > a') .click('a[href="/settings/transfer"]') .click('input#forceFallback') .submitForm('.tab-pane.active form') .url('/') .isExisting('.fallback'); fallback.should.be.equal(false); } }); it('should be possible to upload file and retrieve token', function *() { var currentValue = sandbox.dropzone.fallback; var fallback = yield browser.click('ul.nav > li > a') .click('a[href="/settings/transfer"]') .click('input#forceFallback') .submitForm('.tab-pane.active form') .url('/') .isExisting('.fallback'); fallback.should.be.equal(true); if(!sandbox.storage.location === 'local') { var alert = yield browser.click('ul.nav > li > a') .click('a[href="/settings/storage"]') .selectByVisibleText('select#StorageLocation', 'Local file system') .submitForm('.tab-pane.active form') .waitForExist('.tab-pane.active .alert strong', 5000) .getText('.tab-pane.active .alert strong'); alert.should.be.equal('Success!'); } var preview = yield browser.url('/') .waitForExist('input#payload') .execute(function() { // The WebDriverIO chooseFile() method cannot target an invisible input // It also does not work well with multiple file input jQuery("input#payload").removeAttr('multiple') .show(); }) .waitForVisible('input#payload') .chooseFile('input#payload', path.join(__dirname, '../../../README.md')) .submitForm('.fallback form') .waitForExist('.dz-preview-template') .getText('.dz-preview-template .dz-preview-description span[data-dz-name]') preview.should.be.equal('README.md'); var token = yield browser.getText('.dz-preview-item .dz-preview-description .dz-preview-result .text-success a') should.exist(token); var tokenLink = yield browser.getAttribute('.dz-preview-item .dz-preview-description .dz-preview-result .text-success a', 'href') tokenLink.should.be.equal(sandbox.general.baseUrl + '/download/' + token + '/'); var emailHeader = yield browser.getText('#hp .dz-completed-container .dz-upload-complete h2'); should.exist(emailHeader); var emailForm = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form'); emailForm.should.be.equal(true); var emailFrom = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form input#from'); emailFrom.should.be.equal(true); var emailTo = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form input#to'); emailTo.should.be.equal(true); var emailBody = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form textarea[name="email[body]"]'); emailBody.should.be.equal(true); var submit = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form button[type="submit"]'); submit.should.be.equal(true); if(!currentValue) { fallback = yield browser.click('ul.nav > li > a') .click('a[href="/settings/transfer"]') .click('input#forceFallback') .submitForm('.tab-pane.active form') .url('/') .isExisting('.fallback'); fallback.should.be.equal(false); } }); it('should be possible to upload encrypted file and retrieve token', function *() { var currentValue = sandbox.dropzone.fallback; if(!currentValue) { var fallback = yield browser.click('ul.nav > li > a') .click('a[href="/settings/transfer"]') .click('input#forceFallback') .submitForm('.tab-pane.active form') .url('/') .isExisting('.fallback'); fallback.should.be.equal(true); } if(!sandbox.storage.location === 'local') { var alert = yield browser.url('/') .click('ul.nav > li > a') .click('a[href="/settings/storage"]') .selectByVisibleText('select#StorageLocation', 'Local file system') .submitForm('.tab-pane.active form') .waitForExist('.tab-pane.active .alert strong', 5000) .getText('.tab-pane.active .alert strong'); alert.should.be.equal('Success!'); } var encrypted = yield browser.url('/') .click('ul.nav > li > a') .click('a[href="/settings/security"]') .click('input#encryptionEnabled') .setValue('input#encryptionKey', 'MySecretEncryptionKey') .submitForm('.tab-pane.active form') .waitForExist('.tab-pane.active .alert strong', 5000) .isExisting('input#encryptionEnabled:checked'); encrypted.should.be.equal(true); var preview = yield browser.url('/') .waitForExist('input#payload') .execute(function() { // The WebDriverIO chooseFile() method cannot target an invisible input // It also does not work well with multiple file input jQuery("input#payload").removeAttr('multiple') .show(); }) .waitForVisible('input#payload') .chooseFile('input#payload', path.join(__dirname, '../../../README.md')) .submitForm('.fallback form') .waitForExist('.dz-preview-template') .getText('.dz-preview-template .dz-preview-description span[data-dz-name]') preview.should.be.equal('README.md'); var token = yield browser.getText('.dz-preview-item .dz-preview-description .dz-preview-result .text-success a') should.exist(token); var tokenLink = yield browser.getAttribute('.dz-preview-item .dz-preview-description .dz-preview-result .text-success a', 'href') tokenLink.should.be.equal(sandbox.general.baseUrl + '/download/' + token + '/'); var emailHeader = yield browser.getText('#hp .dz-completed-container .dz-upload-complete h2'); should.exist(emailHeader); var emailForm = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form'); emailForm.should.be.equal(true); var emailFrom = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form input#from'); emailFrom.should.be.equal(true); var emailTo = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form input#to'); emailTo.should.be.equal(true); var emailBody = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form textarea[name="email[body]"]'); emailBody.should.be.equal(true); var submit = yield browser.isExisting('#hp .dz-completed-container .dz-upload-complete form button[type="submit"]'); submit.should.be.equal(true); if(!currentValue) { fallback = yield browser.click('ul.nav > li > a') .click('a[href="/settings/transfer"]') .click('input#forceFallback') .submitForm('.tab-pane.active form') .url('/') .isExisting('.fallback'); fallback.should.be.equal(false); } }); });
YouTransfer/YouTransfer
test/views/index/index.test.js
JavaScript
apache-2.0
12,162
/* jshint globalstrict:true, strict:true, maxlen: 5000 */ /* global describe, before, after, it, require*/ // ////////////////////////////////////////////////////////////////////////////// // / @brief tests for user access rights // / // / @file // / // / DISCLAIMER // / // / Copyright 2017 ArangoDB GmbH, Cologne, Germany // / // / Licensed under the Apache License, Version 2.0 (the "License"); // / you may not use this file except in compliance with the License. // / You may obtain a copy of the License at // / // / http://www.apache.org/licenses/LICENSE-2.0 // / // / Unless required by applicable law or agreed to in writing, software // / distributed under the License is distributed on an "AS IS" BASIS, // / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // / See the License for the specific language governing permissions and // / limitations under the License. // / // / Copyright holder is ArangoDB GmbH, Cologne, Germany // / // / @author Michael Hackstein // / @author Mark Vollmary // / @author Copyright 2017, ArangoDB GmbH, Cologne, Germany // ////////////////////////////////////////////////////////////////////////////// 'use strict'; const expect = require('chai').expect; const users = require('@arangodb/users'); const helper = require('@arangodb/user-helper'); const errors = require('@arangodb').errors; const graphModule = require('@arangodb/general-graph'); const namePrefix = helper.namePrefix; const dbName = helper.dbName; const rightLevels = helper.rightLevels; const testGraphName = `${namePrefix}GraphNew`; const testEdgeColName = `${namePrefix}EdgeColNew`; const testVertexColName = `${namePrefix}VertexColNew`; const userSet = helper.userSet; const systemLevel = helper.systemLevel; const dbLevel = helper.dbLevel; const colLevel = helper.colLevel; const arango = require('internal').arango; const db = require('internal').db; for (let l of rightLevels) { systemLevel[l] = new Set(); dbLevel[l] = new Set(); colLevel[l] = new Set(); } const switchUser = (user, dbname) => { arango.reconnect(arango.getEndpoint(), dbname, user, ''); }; switchUser('root', '_system'); helper.removeAllUsers(); describe('User Rights Management', () => { before(helper.generateAllUsers); after(helper.removeAllUsers); it('should check if all users are created', () => { switchUser('root', '_system'); expect(userSet.size).to.equal(helper.userCount); for (let name of userSet) { expect(users.document(name), `Could not find user: ${name}`).to.not.be.undefined; } }); it('should test rights for', () => { for (let name of userSet) { let canUse = false; try { switchUser(name, dbName); canUse = true; } catch (e) { canUse = false; } if (canUse) { describe(`user ${name}`, () => { before(() => { switchUser(name, dbName); }); describe('administrate on db level', () => { const rootTestCollection = (colName, switchBack = true) => { switchUser('root', dbName); let col = db._collection(colName); if (switchBack) { switchUser(name, dbName); } return col !== null; }; const rootCreateCollection = (colName, edge = false) => { if (!rootTestCollection(colName, false)) { if (edge) { db._createEdgeCollection(colName); } else { db._create(colName); } if (colLevel['none'].has(name)) { users.grantCollection(name, dbName, colName, 'none'); } else if (colLevel['ro'].has(name)) { users.grantCollection(name, dbName, colName, 'ro'); } else if (colLevel['rw'].has(name)) { users.grantCollection(name, dbName, colName, 'rw'); } } switchUser(name, dbName); }; const rootTestGraph = (switchBack = true) => { switchUser('root', dbName); const graph = graphModule._exists(testGraphName); if (switchBack) { switchUser(name, dbName); } return graph !== false; }; const rootDropGraph = () => { if (rootTestGraph(false)) { graphModule._drop(testGraphName, true); } switchUser(name, dbName); }; const rootCreateGraph = () => { if (!rootTestGraph(false)) { graphModule._create(testGraphName, [{ collection: testEdgeColName, 'from': [ testVertexColName ], 'to': [ testVertexColName ] }]); } switchUser(name, dbName); }; describe('drop a', () => { before(() => { db._useDatabase(dbName); rootDropGraph(); rootCreateCollection(testEdgeColName, true); rootCreateCollection(testVertexColName, false); rootCreateGraph(); }); after(() => { rootDropGraph(); }); it('graph', () => { expect(!rootTestGraph()).to.equal(false, 'Precondition failed, the graph does not exists'); if (dbLevel['rw'].has(name) && colLevel['rw'].has(name)) { graphModule._drop(testGraphName, true); expect(!rootTestGraph()).to.equal(true, 'Graph drop reported success, but graph was found afterwards.'); expect(!rootTestCollection(testEdgeColName)).to.equal(true, 'Graph drop reported success, but edge collection was found afterwards.'); expect(!rootTestCollection(testVertexColName)).to.equal(true, 'Graph drop reported success, but vertex collection was found afterwards.'); } else { try { graphModule._drop(testGraphName, true); } catch (e) { expect(e.errorNum).to.equal(errors.ERROR_FORBIDDEN.code); } expect(!rootTestGraph()).to.equal(false, `${name} was able to drop a graph with insufficent rights`); expect(!rootTestCollection(testEdgeColName)).to.equal(false, 'Graph drop reported error, but edge collection was not found afterwards.'); expect(!rootTestCollection(testVertexColName)).to.equal(false, 'Graph drop reported error, but vertex collection was not found afterwards.'); } }); }); describe('drop a', () => { before(() => { db._useDatabase(dbName); rootDropGraph(); rootCreateCollection(testEdgeColName, true); rootCreateCollection(testVertexColName, false); rootCreateGraph(); }); after(() => { rootDropGraph(); }); it('graph with specified collection access', () => { expect(rootTestGraph()).to.equal(true, 'Precondition failed, the graph still not exists'); expect(rootTestCollection(testEdgeColName)).to.equal(true, 'Precondition failed, the edge collection still not exists'); expect(rootTestCollection(testVertexColName)).to.equal(true, 'Precondition failed, the vertex collection still not exists'); if (dbLevel['rw'].has(name) && colLevel['rw'].has(name)) { graphModule._drop(testGraphName, true); expect(!rootTestGraph()).to.equal(true, 'Graph drop reported success, but graph was found afterwards.'); expect(!rootTestCollection(testEdgeColName)).to.equal(true, 'Graph drop reported success, but edge collection was found afterwards.'); expect(!rootTestCollection(testVertexColName)).to.equal(true, 'Graph drop reported success, but vertex collection was found afterwards.'); } else { try { graphModule._drop(testGraphName, true); } catch (e) { expect(e.errorNum).to.equal(errors.ERROR_FORBIDDEN.code); } expect(!rootTestGraph()).to.equal(false, `${name} was able to drop a graph with insufficent rights`); } }); }); }); }); } } }); });
hkernbach/arangodb
js/client/tests/authentication/user-access-right-drop-graph-spec.js
JavaScript
apache-2.0
8,646
var libCssList = [ "bootstrap/dist/css/bootstrap.css", "bootstrap/dist/css/bootstrap-theme.css" ]; var basePath = "lib/"; for (var fileIndex = 0; fileIndex < libCssList.length; fileIndex++) { libCssList[fileIndex] = basePath + libCssList[fileIndex]; } module.exports = libCssList;
monitise-mea/gerrit-dashboard-web
config/paths/lib-css-list.js
JavaScript
apache-2.0
296
/* @flow */ import { PropTypes } from 'react'; export function notImplemented(props: Object, propName: string, componentName: string): ?Error { if (props[propName]) { return new Error(`<${componentName}> "${propName}" is not implemented.`); } return null; } export function falsy(props: Object, propName: string, componentName: string): ?Error { if (props[propName]) { return new Error(`<${componentName}> should not have a "${propName}" prop.`); } return null; } export const component = PropTypes.oneOfType([PropTypes.func, PropTypes.string]);
Right-Men/Ironman
node_modules/react-router-native/modules/PropTypes.js
JavaScript
apache-2.0
570
var site = function (tenantId, options) { var tag, tags, rate, asset, assets, carbon = require('carbon'), store = require('/modules/store.js'), path = '/_system/governance/sites/' + options.provider + '/' + options.name + '/' + options.version, server = require('store').server, //site = require('/modules/site-browser.js'), um = server.userManager(tenantId), registry = server.systemRegistry(tenantId), am = store.assetManager('site', registry); asset = { "name": options.name, "lifecycle": null, "lifecycleState": null, "attributes": { "overview_status": options.status, "overview_name": options.name, "overview_version": options.version, "overview_description": options.description, "overview_url": options.url, "overview_provider": options.provider, "images_banner": options.banner, "images_thumbnail": options.thumbnail } }; assets = am.search({ attributes:{ overview_name: options.name, overview_provider: options.provider, overview_version: options.version } }, {start: 0, count: 10}); if(assets.length > 0){ asset.id = assets[0].id; am.update(asset); } else { am.add(asset); } um.authorizeRole(carbon.user.anonRole, path, carbon.registry.actions.GET); tags = options.tags; for (tag in tags) { if (tags.hasOwnProperty(tag)) { registry.tag(path, options.tags[tag]); } } rate = options.rate; if (options.rate != undefined) { registry.rate(path, rate); } }; var ebook = function (tenantId, options) { var tag, tags, rate, asset, assets, carbon = require('carbon'), store = require('/modules/store.js'), path = '/_system/governance/ebooks/' + options.provider + '/' + options.name + '/' + options.version, server = require('store').server, um = server.userManager(tenantId), registry = server.systemRegistry(tenantId), am = store.assetManager('ebook', registry); asset = { "name": options.name, "lifecycle": null, "lifecycleState": null, "attributes": { "overview_status": options.status, "overview_name": options.name, "overview_version": options.version, "overview_description": options.description, "overview_url": options.url, "overview_category": options.category, "overview_author": options.author, "overview_isbn": options.isbn, "overview_provider": options.provider, "images_banner": options.banner, "images_thumbnail": options.thumbnail } }; assets = am.search({ attributes: { overview_name: options.name, overview_provider: options.provider, overview_version: options.version } }, { start: 0, count: 10 }); if (assets.length > 0) { asset.id = assets[0].id; am.update(asset); } else { am.add(asset); } um.authorizeRole(carbon.user.anonRole, path, carbon.registry.actions.GET); tags = options.tags; for (tag in tags) { if (tags.hasOwnProperty(tag)) { registry.tag(path, options.tags[tag]); } } rate = options.rate; if (options.rate != undefined) { registry.rate(path, rate); } } var gadget = function (tenantId, options) { var tag, tags, rate, asset, assets, carbon = require('carbon'), store = require('/modules/store.js'), path = '/_system/governance/gadgets/' + options.provider + '/' + options.name + '/' + options.version, server = require('store').server, um = server.userManager(tenantId), registry = server.systemRegistry(tenantId), am = store.assetManager('gadget', registry); asset = { "name": options.name, "lifecycle":null, "lifecycleState":null, "attributes": { "overview_status": options.status, "overview_name": options.name, "overview_version": options.version, "overview_description": options.description, "overview_url": options.url, "overview_provider": options.provider, "images_banner": options.banner, "images_thumbnail": options.thumbnail } }; assets = am.search({ attributes: { overview_name: options.name, overview_provider: options.provider, overview_version: options.version } }, { start: 0, count: 10 }); if (assets.length > 0) { asset.id = assets[0].id; am.update(asset); } else { am.add(asset); } um.authorizeRole(carbon.user.anonRole, path, carbon.registry.actions.GET); tags = options.tags; for (tag in tags) { if (tags.hasOwnProperty(tag)) { registry.tag(path, options.tags[tag]); } } rate = options.rate; if (options.rate != undefined) { registry.rate(path, rate); } }; var buildSiteRXT = function (options) { var rxt = <metadata xmlns="http://www.wso2.org/governance/metadata"> <overview> <provider>{options.provider}</provider> <name>{options.name}</name> <version>{options.version}</version> <url>{options.url}</url> <status>{options.status}</status> <description>{options.description}</description> </overview> <images> <thumbnail>{options.thumbnail}</thumbnail> <banner>{options.banner}</banner> </images> </metadata>; return rxt; }; var buildEBookRXT = function (options) { var rxt = <metadata xmlns="http://www.wso2.org/governance/metadata"> <overview> <provider>{options.provider}</provider> <name>{options.name}</name> <version>{options.version}</version> <url>{options.url}</url> <status>{options.status}</status> <category>{options.category}</category> <isbn>{options.isbn}</isbn> <author>{options.author}</author> <description>{options.description}</description> </overview> <images> <thumbnail>{options.thumbnail}</thumbnail> <banner>{options.banner}</banner> </images> </metadata>; return rxt; }; var sso = function (tenantId, options) { var path = '/_system/config/repository/identity/SAMLSSO/' + options.issuer64, server = require('store').server, registry = server.systemRegistry(tenantId); registry.put(path, { properties: { 'Issuer': options.issuer, 'SAMLSSOAssertionConsumerURL': options.consumerUrl, 'doSignAssertions': options.doSign, 'doSingleLogout': options.singleLogout, 'useFullyQualifiedUsername': options.useFQUsername } }); };
cnapagoda/wso2Store
publisher/modules/deployer.js
JavaScript
apache-2.0
7,175
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {listenParent} from './messaging'; /** * Info about the current document/iframe. * @type {boolean} */ let inViewport = true; /** * @param {boolean} inV */ export function setInViewportForTesting(inV) { inViewport = inV; } // Active intervals. Must be global, because people clear intervals // with clearInterval from a different window. const intervals = {}; let intervalId = 0; /** * Add instrumentation to a window and all child iframes. * @param {!Window} win */ export function manageWin(win) { try { manageWin_(win); } catch (e) { // We use a try block, because the ad integrations often swallow errors. console./*OK*/error(e.message, e.stack); } } /** * @param {!Window} win */ function manageWin_(win) { if (win.ampSeen) { return; } win.ampSeen = true; // Instrument window. instrumentEntryPoints(win); // Watch for new iframes. installObserver(win); // Existing iframes. maybeInstrumentsNodes(win, win.document.querySelectorAll('iframe')); blockSyncPopups(win); } /** * Add instrumentation code to doc.write. * @param {!Window} parent * @param {!Window} win */ function instrumentDocWrite(parent, win) { const doc = win.document; const {close} = doc; doc.close = function() { parent.ampManageWin = function(win) { manageWin(win); }; if (!parent.ampSeen) { // .call does not work in Safari with document.write. doc.write('<script>window.parent.ampManageWin(window)</script>'); } doc._close = close; return doc._close(); }; } /** * Add instrumentation code to iframe's srcdoc. * @param {!Window} parent * @param {!Element} iframe */ function instrumentSrcdoc(parent, iframe) { let srcdoc = iframe.getAttribute('srcdoc'); parent.ampManageWin = function(win) { manageWin(win); }; srcdoc += '<script>window.parent.ampManageWin(window)</script>'; iframe.setAttribute('srcdoc', srcdoc); } /** * Instrument added nodes if they are instrumentable iframes. * @param {!Window} win * @param {!Array<!Node>|NodeList<!Node>|NodeList<!Element>|null} addedNodes */ function maybeInstrumentsNodes(win, addedNodes) { for (let n = 0; n < addedNodes.length; n++) { const node = addedNodes[n]; try { if (node.tagName != 'IFRAME') { continue; } const src = node.getAttribute('src'); const srcdoc = node.getAttribute('srcdoc'); if (src == null || /^(about:|javascript:)/i.test(src.trim()) || srcdoc) { if (node.contentWindow) { instrumentIframeWindow(node, win, node.contentWindow); node.addEventListener('load', () => { try { instrumentIframeWindow(node, win, node.contentWindow); } catch (e) { console./*OK*/error(e.message, e.stack); } }); } else if (srcdoc) { instrumentSrcdoc(parent, node); } } } catch (e) { console./*OK*/error(e.message, e.stack); } } } /** * Installs a mutation observer in a window to look for iframes. * @param {!Element} node * @param {!Window} parent * @param {!Window} win */ function instrumentIframeWindow(node, parent, win) { if (win.ampSeen) { return; } const doc = win.document; instrumentDocWrite(parent, win); if (doc.body && doc.body.childNodes.length) { manageWin(win); } } /** * Installs a mutation observer in a window to look for iframes. * @param {!Window} win */ function installObserver(win) { if (!window.MutationObserver) { return; } const observer = new MutationObserver(function(mutations) { for (let i = 0; i < mutations.length; i++) { maybeInstrumentsNodes(win, mutations[i].addedNodes); } }); observer.observe(win.document.documentElement, { subtree: true, childList: true, }); } /** * Replace timers with variants that can be throttled. * @param {!Window} win */ function instrumentEntryPoints(win) { // Change setTimeout to respect a minimum timeout. const {setTimeout} = win; win.setTimeout = function(fn, time) { time = minTime(time); arguments[1] = time; return setTimeout.apply(this, arguments); }; // Implement setInterval in terms of setTimeout to make // it respect the same rules win.setInterval = function(fn) { const id = intervalId++; const args = Array.prototype.slice.call(arguments); function wrapper() { next(); if (typeof fn == 'string') { // Handle rare and dangerous string arg case. return (0, win.eval/*NOT OK but whatcha gonna do.*/).call(win, fn); // lgtm [js/useless-expression] } else { return fn.apply(this, arguments); } } args[0] = wrapper; function next() { intervals[id] = win.setTimeout.apply(win, args); } next(); return id; }; const {clearInterval} = win; win.clearInterval = function(id) { clearInterval(id); win.clearTimeout(intervals[id]); delete intervals[id]; }; } /** * Blackhole the legacy popups since they should never be used for anything. * @param {!Window} win */ function blockSyncPopups(win) { let count = 0; function maybeThrow() { // Prevent deep recursion. if (count++ > 2) { throw new Error('security error'); } } try { win.alert = maybeThrow; win.prompt = function() { maybeThrow(); return ''; }; win.confirm = function() { maybeThrow(); return false; }; } catch (e) { console./*OK*/error(e.message, e.stack); } } /** * Calculates the minimum time that a timeout should have right now. * @param {number|undefined} time * @return {number|undefined} */ function minTime(time) { if (!inViewport) { time += 1000; } // Eventually this should throttle like this: // - for timeouts in the order of a frame use requestAnimationFrame // instead. // - only allow about 2-4 short timeouts (< 16ms) in a 16ms time frame. // Throttle further timeouts to requestAnimationFrame. return time; } export function installEmbedStateListener() { listenParent(window, 'embed-state', function(data) { inViewport = data.inViewport; }); }
bpaduch/amphtml
3p/environment.js
JavaScript
apache-2.0
6,816
module("tinymce.EnterKey", { setupModule: function() { QUnit.stop(); tinymce.init({ selector: "textarea", plugins: wpPlugins, add_unload_trigger: false, disable_nodechange: true, indent: false, skin: false, entities: 'raw', schema: 'html5', extended_valid_elements: 'div[id|style|contenteditable],span[id|style|contenteditable],#dt,#dd', valid_styles: { '*' : 'color,font-size,font-family,background-color,font-weight,font-style,text-decoration,float,margin,margin-top,margin-right,margin-bottom,margin-left,display,position,top,left' }, init_instance_callback: function(ed) { window.editor = ed; QUnit.start(); } }); }, teardown: function() { editor.settings.forced_root_block = 'p'; editor.settings.forced_root_block_attrs = null; editor.settings.end_container_on_empty_block = false; editor.settings.br_in_pre = true; editor.settings.keep_styles = true; delete editor.settings.force_p_newlines; } }); test('Enter at end of H1', function() { editor.setContent('<h1>abc</h1>'); Utils.setSelection('h1', 3); Utils.pressEnter(); equal(editor.getContent(), '<h1>abc</h1><p>\u00a0</p>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'P'); }); test('Enter in midde of H1', function() { editor.setContent('<h1>abcd</h1>'); Utils.setSelection('h1', 2); Utils.pressEnter(); equal(editor.getContent(), '<h1>ab</h1><h1>cd</h1>'); equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'H1'); }); test('Enter before text after EM', function() { editor.setContent('<p><em>a</em>b</p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p><em>a</em></p><p>b</p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeValue, 'b'); }); test('Enter before first IMG in P', function() { editor.setContent('<p><img alt="" src="about:blank" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p><img src="about:blank" alt="" /></p>'); }); test('Enter before last IMG in P with text', function() { editor.setContent('<p>abc<img alt="" src="about:blank" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p>abc</p><p><img src="about:blank" alt="" /></p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'IMG'); }); test('Enter before last IMG in P with IMG sibling', function() { editor.setContent('<p><img src="about:blank" alt="" /><img src="about:blank" alt="" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p><img src="about:blank" alt="" /></p><p><img src="about:blank" alt="" /></p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'IMG'); }); test('Enter after last IMG in P', function() { editor.setContent('<p>abc<img alt="" src="about:blank" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 2); Utils.pressEnter(); equal(editor.getContent(), '<p>abc<img src="about:blank" alt="" /></p><p>\u00a0</p>'); }); test('Enter before last INPUT in P with text', function() { editor.setContent('<p>abc<input type="text" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p>abc</p><p><input type="text" /></p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'INPUT'); }); test('Enter before last INPUT in P with IMG sibling', function() { editor.setContent('<p><input type="text" /><input type="text" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p><input type="text" /></p><p><input type="text" /></p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'INPUT'); }); test('Enter after last INPUT in P', function() { editor.setContent('<p>abc<input type="text" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 2); Utils.pressEnter(); equal(editor.getContent(), '<p>abc<input type="text" /></p><p>\u00a0</p>'); }); test('Enter at end of P', function() { editor.setContent('<p>abc</p>'); Utils.setSelection('p', 3); Utils.pressEnter(); equal(editor.getContent(), '<p>abc</p><p>\u00a0</p>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'P'); }); test('Enter at end of EM inside P', function() { editor.setContent('<p><em>abc</em></p>'); Utils.setSelection('em', 3); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<p><em>abc</em></p><p><em></em></p>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'EM'); }); test('Enter at middle of EM inside P', function() { editor.setContent('<p><em>abcd</em></p>'); Utils.setSelection('em', 2); Utils.pressEnter(); equal(editor.getContent(), '<p><em>ab</em></p><p><em>cd</em></p>'); equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'EM'); }); test('Enter at beginning EM inside P', function() { editor.setContent('<p><em>abc</em></p>'); Utils.setSelection('em', 0); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<p><em></em></p><p><em>abc</em></p>'); equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc'); }); test('Enter at end of STRONG in EM inside P', function() { editor.setContent('<p><em><strong>abc</strong></em></p>'); Utils.setSelection('strong', 3); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<p><em><strong>abc</strong></em></p><p><em><strong></strong></em></p>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'STRONG'); }); test('Enter at middle of STRONG in EM inside P', function() { editor.setContent('<p><em><strong>abcd</strong></em></p>'); Utils.setSelection('strong', 2); Utils.pressEnter(); equal(editor.getContent(), '<p><em><strong>ab</strong></em></p><p><em><strong>cd</strong></em></p>'); equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'STRONG'); }); test('Enter at beginning STRONG in EM inside P', function() { editor.setContent('<p><em><strong>abc</strong></em></p>'); Utils.setSelection('strong', 0); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<p><em><strong></strong></em></p><p><em><strong>abc</strong></em></p>'); equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc'); }); test('Enter at beginning of P', function() { editor.setContent('<p>abc</p>'); Utils.setSelection('p', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>abc</p>'); equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc'); }); test('Enter at middle of P with style, id and class attributes', function() { editor.setContent('<p id="a" class="b" style="color:#000">abcd</p>'); Utils.setSelection('p', 2); Utils.pressEnter(); equal(editor.getContent(), '<p id="a" class="b" style="color: #000;">ab</p><p class="b" style="color: #000;">cd</p>'); equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'P'); }); test('Enter at a range between H1 and P', function() { editor.setContent('<h1>abcd</h1><p>efgh</p>'); Utils.setSelection('h1', 2, 'p', 2); Utils.pressEnter(); equal(editor.getContent(), '<h1>abgh</h1>'); equal(editor.selection.getNode().nodeName, 'H1'); }); test('Enter at end of H1 in HGROUP', function() { editor.setContent('<hgroup><h1>abc</h1></hgroup>'); Utils.setSelection('h1', 3); Utils.pressEnter(); equal(editor.getContent(), '<hgroup><h1>abc</h1><h1>\u00a0</h1></hgroup>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'H1'); }); test('Enter inside empty TD', function() { editor.getBody().innerHTML = '<table><tr><td></td></tr></table>'; Utils.setSelection('td', 0); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<table><tbody><tr><td><p></p><p></p></td></tr></tbody></table>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside STRONG inside TD with BR', function() { editor.getBody().innerHTML = '<table><tr><td>d <strong>e</strong><br></td></tr></table>'; Utils.setSelection('strong', 1); Utils.pressEnter({shiftKey: true}); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<table><tbody><tr><td>d <strong>e<br></strong><br></td></tr></tbody></table>'); equal(editor.selection.getNode().nodeName, 'STRONG'); }); test('Enter inside middle of text node in body', function() { editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 2); Utils.pressEnter(); equal(editor.getContent(), '<p>ab</p><p>cd</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside at beginning of text node in body', function() { editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>abcd</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside at end of text node in body', function() { editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 4); Utils.pressEnter(); equal(editor.getContent(), '<p>abcd</p><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside empty body', function() { editor.getBody().innerHTML = ''; Utils.setSelection('body', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside empty li in beginning of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>'; Utils.setSelection('li', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><ol><li>a</li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside empty li at the end of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>'; Utils.setSelection('li:last', 0); Utils.pressEnter(); equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside empty li in the middle of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>'; Utils.setSelection('li:nth-child(2)', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p><ol><li>b</li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside empty li in beginning of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>'; Utils.setSelection('li', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>\u00a0</p><ol><li>a</li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside empty li at the end of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>'; Utils.setSelection('li:last', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside empty li in the middle of ol with forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>'; Utils.setSelection('li:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<ol><li>a</li></ol><br /><ol><li>b</li></ol>'); equal(editor.selection.getNode().nodeName, 'BODY'); }); test('Enter inside empty li in beginning of ol with forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>'; Utils.setSelection('li', 0); Utils.pressEnter(); equal(editor.getContent(), '<br /><ol><li>a</li></ol>'); equal(editor.selection.getNode().nodeName, 'BODY'); }); test('Enter inside empty li at the end of ol with forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>'; Utils.setSelection('li:last', 0); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<ol><li>a</li></ol><br>'); equal(editor.selection.getNode().nodeName, 'BODY'); }); test('Enter inside empty li in the middle of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>'; Utils.setSelection('li:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p><ol><li>b</li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); // Nested lists in LI elements test('Enter inside empty LI in beginning of OL in LI', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a' + '<ol>' + '<li><br></li>' + '<li>a</li>' + '</ol>' + '</li>' + '</ol>' ); Utils.setSelection('li li', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<li>' + '<ol>' + '<li>a</li>' + '</ol>' + '</li>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Enter inside empty LI in middle of OL in LI', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a' + '<ol>' + '<li>a</li>' + '<li><br></li>' + '<li>b</li>' + '</ol>' + '</li>' + '</ol>' ); Utils.setSelection('li li:nth-child(2)', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a' + '<ol>' + '<li>a</li>' + '</ol>' + '</li>' + '<li>\u00a0' + '<ol>' + '<li>b</li>' + '</ol>' + '</li>' + '</ol>' ); // Ignore on IE 7, 8 this is a known bug not worth fixing if (!tinymce.Env.ie || tinymce.Env.ie > 8) { equal(editor.selection.getNode().nodeName, 'LI'); } }); test('Enter inside empty LI in end of OL in LI', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a' + '<ol>' + '<li>a</li>' + '<li><br></li>' + '</ol>' + '</li>' + '</ol>' ); Utils.setSelection('li li:last', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a' + '<ol>' + '<li>a</li>' + '</ol>' + '</li>' + '<li></li>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); // Nested lists in OL elements // Ignore on IE 7, 8 this is a known bug not worth fixing if (!tinymce.Env.ie || tinymce.Env.ie > 8) { test('Enter before nested list', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a' + '<ul>' + '<li>b</li>' + '<li>c</li>' + '</ul>' + '</li>' + '</ol>' ); Utils.setSelection('ol > li', 1); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<li>\u00a0' + '<ul>' + '<li>b</li>' + '<li>c</li>' + '</ul>' + '</li>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); } test('Enter inside empty LI in beginning of OL in OL', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a</li>' + '<ol>' + '<li><br></li>' + '<li>a</li>' + '</ol>' + '</ol>' ); Utils.setSelection('ol ol li', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<li></li>' + '<ol>' + '<li>a</li>' + '</ol>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Enter inside empty LI in middle of OL in OL', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a</li>' + '<ol>' + '<li>a</li>' + '<li><br></li>' + '<li>b</li>' + '</ol>' + '</ol>' ); Utils.setSelection('ol ol li:nth-child(2)', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<ol>' + '<li>a</li>' + '</ol>' + '<li></li>' + '<ol>' + '<li>b</li>' + '</ol>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Enter inside empty LI in end of OL in OL', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a</li>' + '<ol>' + '<li>a</li>' + '<li><br></li>' + '</ol>' + '</ol>' ); Utils.setSelection('ol ol li:last', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<ol>' + '<li>a</li>' + '</ol>' + '<li></li>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Enter at beginning of first DT inside DL', function() { editor.getBody().innerHTML = '<dl><dt>a</dt></dl>'; Utils.setSelection('dt', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dt>\u00a0</dt><dt>a</dt></dl>'); equal(editor.selection.getNode().nodeName, 'DT'); }); test('Enter at beginning of first DD inside DL', function() { editor.getBody().innerHTML = '<dl><dd>a</dd></dl>'; Utils.setSelection('dd', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dd>\u00a0</dd><dd>a</dd></dl>'); equal(editor.selection.getNode().nodeName, 'DD'); }); test('Enter at beginning of middle DT inside DL', function() { editor.getBody().innerHTML = '<dl><dt>a</dt><dt>b</dt><dt>c</dt></dl>'; Utils.setSelection('dt:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dt>a</dt><dt>\u00a0</dt><dt>b</dt><dt>c</dt></dl>'); equal(editor.selection.getNode().nodeName, 'DT'); }); test('Enter at beginning of middle DD inside DL', function() { editor.getBody().innerHTML = '<dl><dd>a</dd><dd>b</dd><dd>c</dd></dl>'; Utils.setSelection('dd:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dd>a</dd><dd>\u00a0</dd><dd>b</dd><dd>c</dd></dl>'); equal(editor.selection.getNode().nodeName, 'DD'); }); test('Enter at end of last DT inside DL', function() { editor.getBody().innerHTML = '<dl><dt>a</dt></dl>'; Utils.setSelection('dt', 1); Utils.pressEnter(); equal(editor.getContent(), '<dl><dt>a</dt><dt>\u00a0</dt></dl>'); equal(editor.selection.getNode().nodeName, 'DT'); }); test('Enter at end of last DD inside DL', function() { editor.getBody().innerHTML = '<dl><dd>a</dd></dl>'; Utils.setSelection('dd', 1); Utils.pressEnter(); equal(editor.getContent(), '<dl><dd>a</dd><dd>\u00a0</dd></dl>'); equal(editor.selection.getNode().nodeName, 'DD'); }); test('Enter at end of last empty DT inside DL', function() { editor.getBody().innerHTML = '<dl><dt>a</dt><dt></dt></dl>'; Utils.setSelection('dt:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dt>a</dt></dl><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter at end of last empty DD inside DL', function() { editor.getBody().innerHTML = '<dl><dd>a</dd><dd></dd></dl>'; Utils.setSelection('dd:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dd>a</dd></dl><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter at beginning of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 0); Utils.pressEnter(); equal(editor.getContent(), '<ol><li></li><li><p>abcd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside middle of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 2); Utils.pressEnter(); equal(editor.getContent(), '<ol><li><p>ab</p></li><li><p>cd</p></li></ol>'); // Ignore on IE 7, 8 this is a known bug not worth fixing if (!tinymce.Env.ie || tinymce.Env.ie > 8) { equal(editor.selection.getNode().nodeName, 'P'); } }); test('Enter at end of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 4); Utils.pressEnter(); equal(editor.getContent(), '<ol><li><p>abcd</p></li><li></li></ol>'); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Shift+Enter at beginning of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ol><li><p><br />abcd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside middle of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ol><li><p>ab<br />cd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter at end of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 4); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li><p>abcd</p></li></ol>' : '<ol><li><p>abcd<br /><br /></p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Ctrl+Enter at beginning of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 0); Utils.pressEnter({ctrlKey: true}); equal(editor.getContent(), '<ol><li><p>\u00a0</p><p>abcd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Ctrl+Enter inside middle of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 2); Utils.pressEnter({ctrlKey: true}); equal(editor.getContent(), '<ol><li><p>ab</p><p>cd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Ctrl+Enter at end of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 4); Utils.pressEnter({ctrlKey: true}); equal(editor.getContent(), '<ol><li><p>abcd</p><p>\u00a0</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter in the middle of text in P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 2); Utils.pressEnter(); equal(editor.getContent(), '<p>ab<br />c</p>'); }); test('Enter at the end of text in P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 3); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), (tinymce.isIE && tinymce.Env.ie < 11) ? '<p>abc<br></p>' : '<p>abc<br><br></p>'); }); test('Enter at the middle of text in BODY with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 2); editor.focus(); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), 'ab<br>cd'); }); test('Enter at the beginning of text in BODY with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 0); editor.focus(); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<br>abcd'); }); test('Enter at the end of text in BODY with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 4); editor.focus(); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), (tinymce.isIE && tinymce.Env.ie < 11) ? 'abcd<br>' : 'abcd<br><br>'); }); test('Enter in empty P at the end of a blockquote and end_container_on_empty_block: true', function() { editor.settings.end_container_on_empty_block = true; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p>abc</p><p></p></blockquote>' : '<blockquote><p>abc</p><p><br></p></blockquote>'; Utils.setSelection('p:last', 0); Utils.pressEnter(); equal(editor.getContent(), '<blockquote><p>abc</p></blockquote><p>\u00a0</p>'); }); test('Enter in empty P at the beginning of a blockquote and end_container_on_empty_block: true', function() { editor.settings.end_container_on_empty_block = true; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p></p><p>abc</p></blockquote>' : '<blockquote><p><br></p><p>abc</p></blockquote>'; Utils.setSelection('p', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><blockquote><p>abc</p></blockquote>'); }); test('Enter in empty P at in the middle of a blockquote and end_container_on_empty_block: true', function() { editor.settings.end_container_on_empty_block = true; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p>abc</p><p></p><p>123</p></blockquote>' : '<blockquote><p>abc</p><p><br></p><p>123</p></blockquote>'; Utils.setSelection('p:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<blockquote><p>abc</p></blockquote><p>\u00a0</p><blockquote><p>123</p></blockquote>'); }); test('Enter inside empty P with empty P siblings', function() { // Tests that a workaround for an IE bug is working correctly editor.getBody().innerHTML = '<p></p><p></p><p>X</p>'; Utils.setSelection('p', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p><p>\u00a0</p><p>X</p>'); }); test('Enter at end of H1 with forced_root_block_attrs', function() { editor.settings.forced_root_block_attrs = {"class": "class1"}; editor.getBody().innerHTML = '<h1>a</h1>'; Utils.setSelection('h1', 1); Utils.pressEnter(); equal(editor.getContent(), '<h1>a</h1><p class="class1">\u00a0</p>'); }); test('Shift+Enter at beginning of P', function() { editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p><br />abc</p>'); }); test('Shift+Enter in the middle of P', function() { editor.getBody().innerHTML = '<p>abcd</p>'; Utils.setSelection('p', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>ab<br />cd</p>'); }); test('Shift+Enter at the end of P', function() { editor.getBody().innerHTML = '<p>abcd</p>'; Utils.setSelection('p', 4); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<p>abcd</p>' : '<p>abcd<br /><br /></p>'); }); test('Shift+Enter in the middle of B with a BR after it', function() { editor.getBody().innerHTML = '<p><b>abcd</b><br></p>'; Utils.setSelection('b', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p><b>ab<br />cd</b></p>'); }); test('Shift+Enter at the end of B with a BR after it', function() { editor.getBody().innerHTML = '<p><b>abcd</b><br></p>'; Utils.setSelection('b', 4); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p><b>abcd<br /></b></p>'); }); test('Enter in beginning of PRE', function() { editor.getBody().innerHTML = '<pre>abc</pre>'; Utils.setSelection('pre', 0); Utils.pressEnter(); equal(editor.getContent(), '<pre><br />abc</pre>'); }); test('Enter in the middle of PRE', function() { editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 2); Utils.pressEnter(); equal(editor.getContent(), '<pre>ab<br />cd</pre>'); }); test('Enter at the end of PRE', function() { editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 4); Utils.pressEnter(); equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<pre>abcd</pre>' : '<pre>abcd<br /><br /></pre>'); }); test('Enter in beginning of PRE and br_in_pre: false', function() { editor.settings.br_in_pre = false; editor.getBody().innerHTML = '<pre>abc</pre>'; Utils.setSelection('pre', 0); Utils.pressEnter(); equal(editor.getContent(), '<pre>\u00a0</pre><pre>abc</pre>'); }); test('Enter in the middle of PRE and br_in_pre: false', function() { editor.settings.br_in_pre = false; editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 2); Utils.pressEnter(); equal(editor.getContent(), '<pre>ab</pre><pre>cd</pre>'); }); test('Enter at the end of PRE and br_in_pre: false', function() { editor.settings.br_in_pre = false; editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 4); Utils.pressEnter(); equal(editor.getContent(), '<pre>abcd</pre><p>\u00a0</p>'); }); test('Shift+Enter in beginning of PRE', function() { editor.getBody().innerHTML = '<pre>abc</pre>'; Utils.setSelection('pre', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<pre>\u00a0</pre><pre>abc</pre>'); }); test('Shift+Enter in the middle of PRE', function() { editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<pre>ab</pre><pre>cd</pre>'); }); test('Shift+Enter at the end of PRE', function() { editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 4); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<pre>abcd</pre><p>\u00a0</p>'); }); test('Shift+Enter in beginning of P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>\u00a0</p><p>abc</p>'); }); test('Shift+Enter in middle of P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abcd</p>'; Utils.setSelection('p', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>ab</p><p>cd</p>'); }); test('Shift+Enter at the end of P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 3); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>abc</p><p>\u00a0</p>'); }); test('Shift+Enter in body with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = 'abcd'; var rng = editor.dom.createRng(); rng.setStart(editor.getBody().firstChild, 2); rng.setEnd(editor.getBody().firstChild, 2); editor.selection.setRng(rng); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>ab</p><p>cd</p>'); }); test('Enter at the end of DIV layer', function() { editor.settings.br_in_pre = false; editor.setContent('<div style="position: absolute; top: 1px; left: 2px;">abcd</div>'); Utils.setSelection('div', 4); Utils.pressEnter(); equal(editor.getContent(), '<div style="position: absolute; top: 1px; left: 2px;"><p>abcd</p><p>\u00a0</p></div>'); }); test('Enter in div inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div>abcd</div></div>'; Utils.setSelection('div div', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div>abcd</div></div>'); }); test('Enter in div with contentEditable:true inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true">abcd</div></div>'; Utils.setSelection('div div', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><p>ab</p><p>cd</p></div></div>'); }); test('Enter in span with contentEditable:true inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>'; Utils.setSelection('span', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>'); }); test('Shift+Enter in span with contentEditable:true inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>'; Utils.setSelection('span', 2); Utils.pressEnter({shiftKey: true}); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">ab<br>cd</span></div>'); }); test('Enter in span with contentEditable:true inside contentEditable:false div and forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>'; Utils.setSelection('span', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">ab<br>cd</span></div>'); }); test('Enter in em within contentEditable:true div inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><em>abcd</em></div></div>'; Utils.setSelection('em', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><p><em>ab</em></p><p><em>cd</em></p></div></div>'); }); test('Enter at end of text in a span inside a P and keep_styles: false', function() { editor.settings.keep_styles = false; editor.getBody().innerHTML = '<p><em><span style="font-size: 13px;">X</span></em></p>'; Utils.setSelection('span', 1); Utils.pressEnter(); equal(editor.getContent(), '<p><em><span style="font-size: 13px;">X</span></em></p><p>\u00a0</p>'); }); test('Shift+enter in LI when forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<ul><li>text</li></ul>'; Utils.setSelection('li', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ul><li>te<br />xt</li></ul>'); }); test('Enter when forced_root_block: false and force_p_newlines: true', function() { editor.settings.forced_root_block = false; editor.settings.force_p_newlines = true; editor.getBody().innerHTML = 'text'; Utils.setSelection('body', 2); Utils.pressEnter(); equal(editor.getContent(), '<p>te</p><p>xt</p>'); }); test('Enter at end of br line', function() { editor.settings.forced_root_block = false; editor.settings.force_p_newlines = true; editor.getBody().innerHTML = '<p>a<br>b</p>'; Utils.setSelection('p', 1); Utils.pressEnter(); equal(editor.getContent(), '<p>a</p><p><br />b</p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'BR'); }); // Ignore on IE 7, 8 this is a known bug not worth fixing if (!tinymce.Env.ie || tinymce.Env.ie > 8) { test('Enter before BR between DIVs', function() { editor.getBody().innerHTML = '<div>a<span>b</span>c</div><br /><div>d</div>'; var rng = editor.dom.createRng(); rng.setStartBefore(editor.dom.select('br')[0]); rng.setEndBefore(editor.dom.select('br')[0]); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<div>a<span>b</span>c</div><p>\u00a0</p><p>\u00a0</p><div>d</div>'); }); } // Only test these on modern browsers if (window.getSelection) { test('Enter behind table element', function() { var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table>'; rng.setStartAfter(editor.getBody().lastChild); rng.setEndAfter(editor.getBody().lastChild); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<table><tbody><tr><td>x</td></tr></tbody></table><p>\u00a0</p>'); }); test('Enter before table element', function() { var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table>'; rng.setStartBefore(editor.getBody().lastChild); rng.setEndBefore(editor.getBody().lastChild); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>'); }); test('Enter behind table followed by a p', function() { var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table><p>x</p>'; rng.setStartAfter(editor.getBody().firstChild); rng.setEndAfter(editor.getBody().firstChild); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<table><tbody><tr><td>x</td></tr></tbody></table><p>\u00a0</p><p>x</p>'); }); test('Enter before table element preceded by a p', function() { var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<p>x</p><table><tbody><td>x</td></tbody></table>'; rng.setStartBefore(editor.getBody().lastChild); rng.setStartBefore(editor.getBody().lastChild); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<p>x</p><p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>'); }); test('Enter twice before table element', function(){ var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<table><tbody><tr><td>x</td></tr></tbody></table>'; rng.setStartBefore(editor.getBody().lastChild); rng.setEndBefore(editor.getBody().lastChild); editor.selection.setRng(rng); Utils.pressEnter(); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>'); }); test('Enter after span with space', function() { editor.setContent('<p><b>abc </b></p>'); Utils.setSelection('b', 3); Utils.pressEnter(); equal(editor.getContent(), '<p><b>abc</b></p><p>\u00a0</p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'B'); notEqual(rng.startContainer.data, ' '); }); }
chiss22/letusquoteyou
www/wordpress-develop/tests/qunit/editor/tinymce/EnterKey.js
JavaScript
apache-2.0
39,319
var baseAt = require('../internal/baseAt'), baseFlatten = require('../internal/baseFlatten'), restParam = require('../function/restParam'); /** * Creates an array of elements corresponding to the given keys, or indexes, * of `collection`. Keys may be specified as individual arguments or as arrays * of keys. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {...(number|number[]|string|string[])} [props] The property names * or indexes of elements to pick, specified individually or in arrays. * @returns {Array} Returns the new array of picked elements. * @example * * _.at(['a', 'b', 'c'], [0, 2]); * // => ['a', 'c'] * * _.at(['barney', 'fred', 'pebbles'], 0, 2); * // => ['barney', 'pebbles'] */ var at = restParam(function (collection, props) { return baseAt(collection, baseFlatten(props)); }); module.exports = at;
ionutbarau/petstore
petstore-app/src/main/resources/static/node_modules/lodash/collection/at.js
JavaScript
apache-2.0
940
// module export if (typeof define === "function" && define.amd) { // AMD define("bridge", [], function () { return Bridge; }); } else if (typeof module !== "undefined" && module.exports) { // Node module.exports = Bridge; }
AndreyZM/Bridge
Bridge/Resources/.auxiliary/End.js
JavaScript
apache-2.0
273
/** * node buildHardBenchmark.js ./wiki_benchmark ./soft_benchmark * * nohup node buildSoftBenchmark.js ./soft_benchmark > buildSoftBenchmark.out 2>&1& */ var fs = require('fs'); var csv = require('csv'); //var outputDir = process.argv[2]; var targetBenchmarkDir = process.argv[2]; var surfaceFormsScores = []; var alreadyBenchmarked = {}; var repeatingParagraphs = 0; var nonRepeatingParagraphs = 0; var writtenBenchParagraph = 0; var alreadyBenchmarkedParagraph = 0; function produceSoftBenchmark(paragraphs) { console.log("==============================="); console.log("Writing benchamrk files"); console.log(paragraphs); console.log("==============================="); console.log("==============================="); csv().from(fs.createReadStream(__dirname + '/../../csv/encsv/paragraph.csv'), { delimiter : ',', escape: '"', relax: true }) .on('record', function(csvRow,index){ var paragraphId = csvRow[0]; var paragraphText = csvRow[1]; if (paragraphs[paragraphId] && !alreadyBenchmarked[paragraphs[paragraphId].surfaceForm + "##$##" + paragraphs[paragraphId].entity]) { // if (paragraphId == "344210#32") // console.log("PARAGRAPH!! 344210#32 %j", paragraphs[paragraphId]); fs.writeFileSync(targetBenchmarkDir + "/paragraph__" + paragraphId + "__" + paragraphs[paragraphId].score, paragraphText); fs.writeFileSync(targetBenchmarkDir + "/golden_standard__" + paragraphId, paragraphs[paragraphId].surfaceForm + "\n" + paragraphs[paragraphId].entity); alreadyBenchmarked[paragraphs[paragraphId].surfaceForm + "##$##" + paragraphs[paragraphId].entity] = 1; writtenBenchParagraph++; } else if (paragraphs[paragraphId]) { alreadyBenchmarkedParagraph++; } }) .on('parse_error', function(row){ console.log("Parsing error %j", row); return row.split(',') ; }) .on('end', function(count) { console.log('Read all lines: ' + count); console.log("Repeating paragraphs " + repeatingParagraphs); console.log("Non repeating paragraphs " + nonRepeatingParagraphs); console.log("Written paragraphs " + writtenBenchParagraph); console.log("Already benchmarked paragraphs " + alreadyBenchmarkedParagraph); }).on('error', function(error) { console.log("ERROR: " + error.message); process.exit(1); }); } var processedParagrahs = 0; function collectSoftParagraphs(surfaceFormMap) { console.log("Collecting benchmark paragraphs"); var paragraphs = {}; csv().from(fs.createReadStream(__dirname + '/../../csv/encsv/cleanedSorted/sortBySurfaceForms.csv'), { delimiter : ',', escape: '"', relax: true }) .on('record', function(csvRow,index){ var surfaceForm = csvRow[1]; var entity = csvRow[0].replace("http://en.wikipedia.org/wiki/", ""); var paragraph = csvRow[2]; if ((paragraph == "344210#32")){ //|| (entity == "Great_North_Road_(Great_Britain)")) { console.log("PARAGRAPH 344210#32!!"); console.log("csvRow %j", csvRow); } if (surfaceFormMap[surfaceForm + "###" + entity]) { if (paragraphs[paragraph]) { console.log("Repeating paragraph " + paragraph); repeatingParagraphs++; } else { nonRepeatingParagraphs++; } paragraphs[paragraph] = JSON.parse(JSON.stringify(surfaceFormMap[surfaceForm + "###" + entity])); paragraphs[paragraph].entity = entity; if ((paragraph == "344210#32")){ //|| (entity == "Great_North_Road_(Great_Britain)")) { console.log("PARAGRAPH 344210#32!! Storing..."); console.log(paragraphs[paragraph]); // console.log(paragraphs); // console.log("===$$==="); } } if (((++processedParagrahs) % 50000) == 0) { console.log("Processed mentions: " + processedParagrahs); } }) .on('parse_error', function(row){ console.log("Parsing error %j", row); return row.split(',') ; }) .on('end', function(count) { console.log("Paragraphs collected."); console.log(paragraphs); produceSoftBenchmark(paragraphs); }).on('error', function(error) { console.log("ERROR: " + error.message); process.exit(1); }); } csv().from(fs.createReadStream(__dirname + '/../../csv/encsv/hardSurfaceForms.csv'), { //csv().from(fs.createReadStream(__dirname + '/test/hardSurfaceForm.csv'), { delimiter : ',', escape: '"', relax: true }) .on('record', function(csvRow,index){ if (index > 0) { var surfaceForm = csvRow[0]; var candidates = csvRow[1]; var candidatesArr = candidates.split(";"); var candidatesCounts = []; for (var i in candidatesArr) { if (candidatesArr[i]) { var candidate = candidatesArr[i].split(" "); if(candidate[1]) { candidatesCounts.push({candidate: candidate[0], occurrences: candidate[1].match(/\[(.*)\]/)[1]}); } } } candidatesCounts = candidatesCounts.sort(function(candidateA, candidateB) { var a = parseInt(candidateA.occurrences); var b = parseInt(candidateB.occurrences); if (a < b) return 1; else if (a == b) return 0; else return -1; }); // console.log(candidatesCounts); surfaceFormsScores.push({ surfaceForm: surfaceForm, score: parseFloat(candidatesCounts[0].occurrences) / parseFloat(candidatesCounts[1].occurrences), candidateA: candidatesCounts[0].candidate, candidateB: candidatesCounts[1].candidate }); } }) .on('parse_error', function(row){ console.log("Parsing error %j", row); return row.split(',') ; }) .on('end', function(count) { console.log('Read all lines: ' + count); surfaceFormsScores.sort(function(sfA, sfB) { if (sfA.score > sfB.score) return 1; else if (sfA.score == sfB.score) return 0; else return -1; }); surfaceFormsScores = surfaceFormsScores.slice(0, 199); console.log("Prepared surface forms"); console.log(surfaceFormsScores); var surfaceFormMap = {}; for (var i in surfaceFormsScores) { surfaceFormMap[surfaceFormsScores[i].surfaceForm + "###" + surfaceFormsScores[i].candidateA] = surfaceFormsScores[i]; surfaceFormMap[surfaceFormsScores[i].surfaceForm + "###" + surfaceFormsScores[i].candidateB] = surfaceFormsScores[i]; surfaceFormMap[surfaceFormsScores[i].surfaceForm + "#A#" + surfaceFormsScores[i].candidateA] = surfaceFormsScores[i]; surfaceFormMap[surfaceFormsScores[i].surfaceForm + "#B#" + surfaceFormsScores[i].candidateB] = surfaceFormsScores[i]; } // console.log(surfaceFormMap); collectSoftParagraphs(surfaceFormMap); }).on('error', function(error) { console.log("ERROR: " + error.message); process.exit(1); });
ilasek/SemiTags
NerIndexingSupport/wiki_benchmark/buildSoftBenchmark.js
JavaScript
apache-2.0
7,326
/** * Configure app in a block instead of hard-coding values inside the scripts. */ var config = { //domain: 'http://localhost:63342/FeatureScapeApps', domain: '/featurescapeapps', quipUrl: '/camicroscope/osdCamicroscope.php', //reserve4Url: 'http://reserve4.informatics.stonybrook.edu/dev1/osdCamicroscope.php', imgcoll: 'images', quot: "%22", iiifServer: location.hostname, iiifPrefix: 'fcgi-bin/iipsrv.fcgi?iiif=', default_execution_id: 'tahsin-test-1', default_db: 'quip', default_subject_id: 'TCGA-05-4396', default_case_id: 'TCGA-05-4396-01Z-00-DX1' };
ajasniew/ViewerDockerContainer
html/featurescapeapps/js/config.js
JavaScript
apache-2.0
609
/** * Select2 Italian translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Nessuna corrispondenza trovata"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Inserisci ancora " + n + " caratter" + (n == 1? "e" : "i"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Inserisci " + n + " caratter" + (n == 1? "e" : "i") + " in meno"; }, formatSelectionTooBig: function (limit) { return "Puoi selezionare solo " + limit + " element" + (limit == 1 ? "o" : "i"); }, formatLoadMore: function (pageNumber) { return "Caricamento in corso..."; }, formatSearching: function () { return "Ricerca..."; } }); })(jQuery);
jaskaran-singh/spree_store
public/assets/select2_locale_it-e45548dc93d14ad49b80a69023ecfd28.js
JavaScript
apache-2.0
806
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ CLASS({ package: 'foam.apps.builder.wizard', name: 'NewOrExistingModelWizard', extends: 'foam.apps.builder.wizard.NewOrExistingWizard', requires: [ 'foam.apps.builder.wizard.ModelWizard', 'foam.apps.builder.wizard.ModelPreviewWizard', ], imports: [ 'modelDAO', ], exports: [ 'editView', 'innerEditView', ], properties: [ { name: 'data', postSet: function(old,nu) { if ( nu.baseModelId ) this.baseModel = nu.baseModelId; } }, { type: 'Model', name: 'baseModel', help: 'The list is filtered to only include models that extend baseModel.', postSet: function() { if ( this.modelDAO ) { this.existingDAO = this.modelDAO.where(EQ(Model.EXTENDS, this.baseModel.id)); } } }, { name: 'modelDAO', postSet: function(old,nu) { if ( this.baseModel ) { this.existingDAO = this.modelDAO.where(EQ(Model.EXTENDS, this.baseModel.id)); } }, }, { name: 'newViewFactory', label: 'Create a new Data Model', defaultValue: { factory_: 'foam.apps.builder.wizard.ModelWizard' }, }, { name: 'existingViewFactory', label: 'Copy an existing Data Model', defaultValue: null, }, { name: 'nextViewFactory', lazyFactory: function() { return this.newViewFactory; }, }, { name: 'selection', }, { name: 'existingDAO', view: { factory_: 'foam.ui.md.DAOListView', rowView: 'foam.apps.builder.datamodels.ModelCitationView', } }, { model_: 'foam.apps.builder.wizard.WizardViewFactoryProperty', name: 'editView', defaultValue: { factory_: 'foam.apps.builder.wizard.ModelPreviewWizard' }, }, { model_: 'foam.apps.builder.wizard.WizardViewFactoryProperty', name: 'innerEditView', defaultValue: function() {}, }, ], methods: [ function onNext() { this.SUPER(); if ( this.selection && this.nextViewFactory === this.existingViewFactory ) { this.data.getDataConfig().model = this.selection; } } ], });
jlhughes/foam
js/foam/apps/builder/wizard/NewOrExistingModelWizard.js
JavaScript
apache-2.0
2,478
/* * Copyright (c) 2015-2016 Fraunhofer FOKUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define([ "../core" ], function( jQuery ) { // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; return jQuery.parseXML; });
fhg-fokus-nubomedia/nubomedia-paas
src/main/resources/static/bower_components/jquery/src/ajax/parseXML.js
JavaScript
apache-2.0
1,095
// Based on https://github.com/chrisvfritz/vue-enterprise-boilerplate/blob/master/src/components/_globals.js // Globally register all base components for convenience, because they // will be used very frequently. Components are registered using the // PascalCased version of their file name. import Vue from 'vue'; import upperFirst from 'lodash/upperFirst'; import camelCase from 'lodash/camelCase'; // https://webpack.js.org/guides/dependency-management/#require-context const requireComponent = require.context( // Look for files in the current directory './shared/components', // Do not look in subdirectories false, // Only include "_base-" prefixed .vue files /\.vue$/, ); // For each matching file name... requireComponent.keys().forEach((fileName) => { // Get the component config const componentConfig = requireComponent(fileName); // Get the PascalCase version of the component name const componentName = upperFirst( camelCase( fileName // Remove the "./_" from the beginning .replace(/^\.\/_/, '') // Remove the file extension from the end .replace(/\.\w+$/, ''), ), ); // Globally register the component Vue.component(componentName, componentConfig.default || componentConfig); });
mssola/Portus
app/assets/javascripts/globals.js
JavaScript
apache-2.0
1,270
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ define([ 'underscore', 'backbone', 'knockout', "protocol", 'contrail-model', 'query-or-model', 'query-and-model', 'core-basedir/reports/qe/ui/js/common/qe.utils', 'contrail-list-model', ], function (_, Backbone, Knockout, protocolUtils, ContrailModel, QueryOrModel, QueryAndModel, qeUtils, ContrailListModel) { var QueryFormModel = ContrailModel.extend({ defaultSelectFields: [], disableSelectFields: [], disableSubstringInSelectFields: ['CLASS('], disableWhereFields: [], constructor: function (modelData, queryReqConfig) { var self = this, modelRemoteDataConfig, defaultQueryReqConfig = {chunk: 1, autoSort: true, chunkSize: cowc.QE_RESULT_CHUNK_SIZE_10K, async: true}; var defaultSelectFields = this.defaultSelectFields, disableFieldArray = [].concat(defaultSelectFields).concat(this.disableSelectFields), disableSubstringArray = this.disableSubstringInSelectFields; if (contrail.checkIfExist(modelData.table_name)) { modelRemoteDataConfig = getTableSchemaConfig(self, modelData.table_name, disableFieldArray, disableSubstringArray, this.disableWhereFields); } if(contrail.checkIfExist(queryReqConfig)) { defaultQueryReqConfig = $.extend(true, defaultQueryReqConfig, queryReqConfig); } this.defaultQueryReqConfig = defaultQueryReqConfig; ContrailModel.prototype.constructor.call(this, modelData, modelRemoteDataConfig); this.model().on("change:table_name", this.onChangeTable, this); this.model().on('change:select change:table_name change:time_range change:where change:filter change:time_granularity change:time_granularity_unit', function () { // TODO ContrailListModel should have reload function instead of whole model recreation just to get new data self.refresh() }) //TODO - Needs to be tested for Flow Pages this.model().on("change:time_range change:from_time change:to_time change:table_type", this.onChangeTime, this); return this; }, onChangeTime: function() { var self = this, table_type = self.model().get('table_type') if (table_type === cowc.QE_STAT_TABLE_TYPE || table_type === cowc.QE_OBJECT_TABLE_TYPE || table_type === cowc.QE_FLOW_TABLE_TYPE) { var setTableValuesCallbackFn = function (self, resultArr){ var currentSelectedTable = self.model().attributes.table_name; if (currentSelectedTable != null) { // If time_range is changed then Fetch active tables and check if selected table // is present in the response; if not then reset, else don't reset if (_.indexOf(resultArr, currentSelectedTable) == -1) { // reset everything except time range self.reset(self, null, false, true); } } } this.setTableValues(setTableValuesCallbackFn, table_type) } // use the timer trick to overcome a event firing sequence issue. setTimeout(function() { this.setTableFieldValues(); }.bind(this), 0); }, setTableValues: function(setTableValuesCallbackFn, tabletype) { var self = this, contrailViewModel = this.model(), timeRange = contrailViewModel.attributes.time_range; function fetchTableValues(fromTimeUTC, toTimeUTC) { var data = { fromTimeUTC: fromTimeUTC, toTimeUTC : toTimeUTC, table_name : 'StatTable.FieldNames.fields', select : ['name', 'fields.value'], where : [[{"name": "name", "value": tabletype, "op": 7}]] }; self.table_name_data_object({ status: cowc.DATA_REQUEST_STATE_FETCHING, data: [] }); $.ajax({ url: '/api/qe/table/column/values', type: "POST", data: JSON.stringify(data), contentType: "application/json; charset=utf-8", dataType: "json" }).done(function (resultJSON) { var resultArr = []; $.each(resultJSON.data, function(dataKey, dataValue) { var nameOption = dataValue.name.split(':')[1]; resultArr.push(nameOption); }); self.table_name_data_object({ status: cowc.DATA_REQUEST_STATE_SUCCESS_NOT_EMPTY, data: resultArr }); if(setTableValuesCallbackFn !== null){ setTableValuesCallbackFn(self, resultArr); } }).error(function(xhr) { self.table_name_data_object({ status: cowc.DATA_REQUEST_STATE_ERROR, error: xhr, data: [] }); }); } if (tabletype === cowc.QE_FLOW_TABLE_TYPE) { var resultArr = [ cowc.FLOW_SERIES_TABLE, cowc.FLOW_RECORD_TABLE ]; self.table_name_data_object({ status: cowc.DATA_REQUEST_STATE_SUCCESS_NOT_EMPTY, data: resultArr }); if(setTableValuesCallbackFn !== null){ setTableValuesCallbackFn(self, resultArr); } } else if (timeRange == -1) { var fromTimeUTC = new Date(contrailViewModel.attributes.from_time).getTime(), toTimeUTC = new Date(contrailViewModel.attributes.to_time).getTime(); fetchTableValues(fromTimeUTC, toTimeUTC); } else { qeUtils.fetchServerCurrentTime(function (serverCurrentTime) { var fromTimeUTC = serverCurrentTime - (timeRange * 1000), toTimeUTC = serverCurrentTime; fetchTableValues(fromTimeUTC, toTimeUTC); }); } }, setTableFieldValues: function() { var contrailViewModel = this.model(), tableName = contrailViewModel.attributes.table_name, timeRange = contrailViewModel.attributes.time_range; if (contrail.checkIfExist(tableName)) { qeUtils.fetchServerCurrentTime(function(serverCurrentTime) { var fromTimeUTC = serverCurrentTime - (timeRange * 1000), toTimeUTC = serverCurrentTime if (timeRange == -1) { fromTimeUTC = new Date(contrailViewModel.attributes.from_time).getTime(); toTimeUTC = new Date(contrailViewModel.attributes.to_time).getTime(); } var data = { fromTimeUTC: fromTimeUTC, toTimeUTC: toTimeUTC, table_name: 'StatTable.FieldNames.fields', select: ['name', 'fields.value'], where: [[{"name":"name","value":tableName,"op":7}]] }; $.ajax({ url: '/api/qe/table/column/values', type: "POST", data: JSON.stringify(data), contentType: "application/json; charset=utf-8", dataType: "json" }).done(function (resultJSON) { var valueOptionList = {}; if (_.includes(["FlowSeriesTable", "FlowRecordTable"], tableName)) { valueOptionList["protocol"] = [ "TCP", "UDP", "ICMP" ]; } $.each(resultJSON.data, function(dataKey, dataValue) { var nameOption = dataValue.name.split(':')[1]; if (!contrail.checkIfExist(valueOptionList[nameOption])) { valueOptionList[nameOption] = []; } valueOptionList[nameOption].push(dataValue['fields.value']); }); contrailViewModel.attributes.where_data_object['value_option_list'] = valueOptionList; }).error(function(xhr) { console.log(xhr); }); }); } }, onChangeTable: function() { var self = this, model = self.model(); if (self.table_type() == cowc.QE_OBJECT_TABLE_TYPE || self.table_type() == cowc.QE_STAT_TABLE_TYPE || self.table_type() === cowc.QE_FLOW_TABLE_TYPE) { self.reset(this, null, false, false); } var tableName = model.attributes.table_name, tableSchemeUrl = '/api/qe/table/schema/' + tableName, ajaxConfig = { url: tableSchemeUrl, type: 'GET' }, contrailViewModel = this.model(), defaultSelectFields = this.defaultSelectFields, disableFieldArray = [].concat(defaultSelectFields).concat(this.disableSelectFields), disableSubstringArray = this.disableSubstringInSelectFields; // qeUtils.adjustHeight4FormTextarea(model.attributes.query_prefix); if(tableName != '') { $.ajax(ajaxConfig).success(function(response) { var selectFields = getSelectFields4Table(response, disableFieldArray, disableSubstringArray), whereFields = getWhereFields4NameDropdown(response, tableName, self.disableWhereFields); var selectFields_Aggtype = []; self.select_data_object().requestState((selectFields.length > 0) ? cowc.DATA_REQUEST_STATE_SUCCESS_NOT_EMPTY : cowc.DATA_REQUEST_STATE_SUCCESS_EMPTY); contrailViewModel.set({ 'ui_added_parameters': { 'table_schema': response, 'table_schema_column_names_map' : getTableSchemaColumnMap(response) } }); setEnable4SelectFields(selectFields, self.select_data_object().enable_map()); setChecked4SelectFields(selectFields, self.select_data_object().checked_map()); self.select_data_object().select_fields(selectFields); contrailViewModel.attributes.where_data_object['name_option_list'] = whereFields; if (self.table_type() == cowc.QE_OBJECT_TABLE_TYPE || self.table_type() == cowc.QE_STAT_TABLE_TYPE || self.table_type() === cowc.QE_FLOW_TABLE_TYPE) { self.setTableFieldValues(); } }).error(function(xhr) { console.log(xhr); }); } }, formatModelConfig: function(modelConfig) { var whereOrClausesCollectionModel, filterAndClausesCollectionModel; whereOrClausesCollectionModel = new Backbone.Collection([]); modelConfig['where_or_clauses'] = whereOrClausesCollectionModel; filterAndClausesCollectionModel = new Backbone.Collection([]); modelConfig['filter_and_clauses'] = filterAndClausesCollectionModel; return modelConfig; }, saveSelect: function (callbackObj) { try { var checkedFields = qeUtils.getCheckedFields(this.select_data_object().checked_map()); if (contrail.checkIfFunction(callbackObj.init)) { callbackObj.init(); } this.select(checkedFields.join(", ")); if (contrail.checkIfFunction(callbackObj.success)) { callbackObj.success(); } } catch (error) { if (contrail.checkIfFunction(callbackObj.error)) { callbackObj.error(this.getFormErrorText(this.query_prefix())); } } }, saveWhere: function (callbackObj) { try { if (contrail.checkIfFunction(callbackObj.init)) { callbackObj.init(); } this.where(qeUtils.parseWhereCollection2String(this)); if (contrail.checkIfFunction(callbackObj.success)) { callbackObj.success(); } } catch (error) { if (contrail.checkIfFunction(callbackObj.error)) { callbackObj.error(this.getFormErrorText(this.query_prefix())); } } }, saveFilter: function (callbackObj) { try { if (contrail.checkIfFunction(callbackObj.init)) { callbackObj.init(); } this.filters(qeUtils.parseFilterCollection2String(this)); if (contrail.checkIfFunction(callbackObj.success)) { callbackObj.success(); } } catch (error) { if (contrail.checkIfFunction(callbackObj.error)) { callbackObj.error(this.getFormErrorText(this.query_prefix())); } } }, isTimeRangeCustom: function() { var self = this; /* TODO: time_range is somehow stored as string inside the dropdown, hence use == */ return self.time_range() == -1; }, isSelectTimeChecked: function() { var self = this, selectString = self.select(), selectStringCheckedFields = (selectString !== null) ? selectString.split(', ') : []; return selectStringCheckedFields.indexOf("T=") != -1; }, toggleAdvancedFields: function() { var showAdvancedOptions = this.model().get('show_advanced_options'); this.show_advanced_options(!showAdvancedOptions); }, getAdvancedOptionsText: function() { var showAdvancedOptions = this.show_advanced_options(); if (!showAdvancedOptions) { return 'Show Advanced Options'; } else { return 'Hide Advanced Options'; } }, getSortByOptionList: function(viewModel) { var validSortFields = qeUtils.getCheckedFields(this.select_data_object().checked_map()), invalidSortFieldsArr = ["T=" , "UUID"], resultSortFieldsDataArr = []; for(var i=0; i< validSortFields.length; i++){ if(invalidSortFieldsArr.indexOf(validSortFields[i]) === -1) { resultSortFieldsDataArr.push({id: validSortFields[i], text: validSortFields[i]}); } } return resultSortFieldsDataArr; }, toJSON: function () { var modelAttrs = this.model().attributes var attrs4Server = {} var ignoreKeyList = ['elementConfigMap', 'errors', 'locks', 'ui_added_parameters', 'where_or_clauses', 'select_data_object', 'where_data_object', 'filter_data_object', 'filter_and_clauses', 'sort_by', 'sort_order', 'log_category', 'log_type', 'is_request_in_progress', 'show_advanced_options', 'table_name_data_object'] for (var key in modelAttrs) { if (modelAttrs.hasOwnProperty(key) && ignoreKeyList.indexOf(key) === -1) { attrs4Server[key] = modelAttrs[key]; } } return attrs4Server; }, getQueryRequestPostData: function (serverCurrentTime, customQueryReqObj, useOldTime) { var self = this, formModelAttrs = this.toJSON(), queryReqObj = {}; /** * Analytics only understand protocol code. * So convert protocol name in where clause. */ if (formModelAttrs.where) { var regex = /(protocol\s*=\s*)(UDP|TCP|ICMP)/g; formModelAttrs.where = formModelAttrs.where.replace(regex, function(match, leftValue, protocolName) { return leftValue + protocolUtils.getProtocolCode(protocolName); }); } if(useOldTime != true) { qeUtils.setUTCTimeObj(this.query_prefix(), formModelAttrs, serverCurrentTime); } self.from_time_utc(formModelAttrs.from_time_utc); self.to_time_utc(formModelAttrs.to_time_utc); queryReqObj['formModelAttrs'] = formModelAttrs; queryReqObj.queryId = qeUtils.generateQueryUUID(); queryReqObj.engQueryStr = qeUtils.getEngQueryStr(formModelAttrs); queryReqObj = $.extend(true, self.defaultQueryReqConfig, queryReqObj, customQueryReqObj) return queryReqObj; }, reset: function (data, event, resetTR, resetTable) { if(resetTR) { this.time_range(600); } if(resetTable) { this.table_name(''); } this.time_granularity(60); this.time_granularity_unit('secs'); this.select(''); this.where(''); this.direction('1'); this.filters(''); this.select_data_object().reset(this); this.model().get('where_or_clauses').reset(); this.model().get('filter_and_clauses').reset(); }, addNewOrClauses: function(orClauseObject) { var self = this, whereOrClauses = this.model().get('where_or_clauses'), newOrClauses = []; $.each(orClauseObject, function(orClauseKey, orClauseValue) { newOrClauses.push(new QueryOrModel(self, orClauseValue)); }); whereOrClauses.add(newOrClauses); }, addNewFilterAndClause: function(andClauseObject) { var self = this, filterObj = andClauseObject.filter, limitObj = andClauseObject.limit, sortByArr = andClauseObject.sort_fields, sortOrderStr = andClauseObject.sort_order, filterAndClauses = this.model().attributes.filter_and_clauses; if(contrail.checkIfExist(filterObj)) { $.each(filterObj, function(filterObjKey, filterObjValue) { var modelDataObj = { name : filterObjValue.name, operator: filterObjValue.op, value : filterObjValue.value }; var newAndClause = new QueryAndModel(self.model().attributes, modelDataObj); filterAndClauses.add(newAndClause); }); } if(contrail.checkIfExist(limitObj)) { this.limit(limitObj); } if(contrail.checkIfExist(sortOrderStr)) { this.sort_order(sortOrderStr); } if(contrail.checkIfExist(sortByArr) && sortByArr.length > 0) { this.sort_by(sortByArr); } }, addFilterAndClause: function() { var andClauses = this.model().get('filter_and_clauses'), newAndClause = new QueryAndModel(this.model().attributes); andClauses.add([newAndClause]); }, isSuffixVisible: function(name) { var whereDataObject = this.model().get('where_data_object'); name = contrail.checkIfFunction(name) ? name() : name; return (qeUtils.getNameSuffixKey(name, whereDataObject['name_option_list']) != -1); }, getTimeGranularityUnits: function() { var self = this; return Knockout.computed(function () { var timeRange = self.time_range(), fromTime = new Date(self.from_time()).getTime(), toTime = new Date(self.to_time()).getTime(), timeGranularityUnits = []; timeGranularityUnits.push({id: "secs", text: "secs"}); if (timeRange == -1) { timeRange = (toTime - fromTime) / 1000; } if (timeRange > 60) { timeGranularityUnits.push({id: "mins", text: "mins"}); } if (timeRange > 3600) { timeGranularityUnits.push({id: "hrs", text: "hrs"}); } if (timeRange > 86400) { timeGranularityUnits.push({id: "days", text: "days"}); } return timeGranularityUnits; }, this); }, validations: { runQueryValidation: { table_type: { required: true, msg: window.cowm.getRequiredMessage('table type'), }, table_name: { required: true, msg: window.cowm.getRequiredMessage('table name'), }, select: { required: true, msg: window.cowm.getRequiredMessage('select'), }, from_time: function(value) { var fromTime = new Date(value).getTime(), toTime = new Date(this.attributes.to_time).getTime(), timeRange = this.attributes.time_range; if(fromTime > toTime && timeRange == -1) { return window.cowm.FROM_TIME_SMALLER_THAN_TO_TIME; } }, to_time: function(value) { var toTime = new Date(value).getTime(), fromTime = new Date(this.attributes.from_time).getTime(), timeRange = this.attributes.time_range; if (toTime < fromTime && timeRange == -1) { return window.cowm.TO_TIME_GREATER_THAN_FROM_TIME; } } } }, getDataModel: function (p) { var self = this, currQuery = JSON.stringify(this.toJSON()), // TOOD: modify this to use hashcode based on this.toJSON() queryResultPostData = {}; // reset data model on query change if (_.isUndefined(self.loader) || (currQuery !== self._lastQuery)) { queryResultPostData = self.getQueryRequestPostData(+new Date); // config changes to prevent query to be queued delete queryResultPostData.queryId; queryResultPostData.async = false; self.loader = new ContrailListModel({ remote: { ajaxConfig: { url: "/api/qe/query", type: "POST", data: JSON.stringify(queryResultPostData), dataFilter:function(data){ return data; } }, dataParser: function (response) { return response.data; }, }, }); self._lastQuery = currQuery; } return self.loader; }, refresh: function () { var self = this; self.loader = undefined; } }); function getTableSchemaConfig(model, tableName, disableFieldArray, disableSubstringArray, disableWhereFields) { var tableSchemeUrl = '/api/qe/table/schema/' + tableName, modelRemoteDataConfig = { remote: { ajaxConfig: { url: tableSchemeUrl, type: 'GET' }, setData2Model: function (contrailViewModel, response) { var selectFields = getSelectFields4Table(response, disableFieldArray, disableSubstringArray), whereFields = getWhereFields4NameDropdown(response, tableName, disableWhereFields); model.select_data_object().requestState((selectFields.length > 0) ? cowc.DATA_REQUEST_STATE_SUCCESS_NOT_EMPTY : cowc.DATA_REQUEST_STATE_SUCCESS_EMPTY); contrailViewModel.set({ 'ui_added_parameters': { 'table_schema': response, 'table_schema_column_names_map' : getTableSchemaColumnMap(response) } }); setEnable4SelectFields(selectFields, model.select_data_object().enable_map()); setChecked4SelectFields(selectFields, model.select_data_object().checked_map()); model.select_data_object().select_fields(selectFields); contrailViewModel.attributes.where_data_object['name_option_list'] = whereFields; } }, vlRemoteConfig: { vlRemoteList: [] } }; return modelRemoteDataConfig; }; function getTableSchemaColumnMap (tableSchema) { if (_.isEmpty(tableSchema)) { return {}; } var tableSchemaColumnMapObj = {}, cols = tableSchema.columns; for(var i = 0; i < cols.length; i++) { var colName = cols[i]["name"]; tableSchemaColumnMapObj[colName] = cols[i]; } return tableSchemaColumnMapObj; }; function getSelectFields4Table(tableSchema, disableFieldArray, disableSubstringArray) { if (_.isEmpty(tableSchema)) { return []; } var tableColumns = tableSchema['columns'], filteredSelectFields = []; $.each(tableColumns, function (k, v) { if (contrail.checkIfExist(v) && showSelectField(v.name, disableFieldArray, disableSubstringArray)) { filteredSelectFields.push(v); } }); _.sortBy(filteredSelectFields, 'name'); return filteredSelectFields; }; function showSelectField(fieldName, disableFieldArray, disableSubstringArray) { var showField = true; for (var i = 0; i < disableSubstringArray.length; i++) { if(fieldName.indexOf(disableSubstringArray[i]) != -1) { showField = false; break; } } if(disableFieldArray.indexOf(fieldName) != -1) { showField = false; } return showField; }; function getWhereFields4NameDropdown(tableSchema, tableName, disableWhereFields) { if (_.isEmpty(tableSchema)) { return []; } var tableSchemaFormatted = []; $.each(tableSchema.columns, function(schemaKey, schemaValue) { if (schemaValue.index && disableWhereFields.indexOf(schemaValue.name) == -1){ if (tableName === 'FlowSeriesTable' || tableName === 'FlowRecordTable') { if (schemaValue.name === 'protocol') { schemaValue.suffixes = ['sport', 'dport']; tableSchemaFormatted.push(schemaValue); } else if (schemaValue.name === 'sourcevn') { schemaValue.suffixes = ['sourceip']; tableSchemaFormatted.push(schemaValue); } else if (schemaValue.name === 'destvn') { schemaValue.suffixes = ['destip']; tableSchemaFormatted.push(schemaValue); } else if (schemaValue.name === 'vrouter') { tableSchemaFormatted.push(schemaValue); } else { schemaValue.index = false; } } else { tableSchemaFormatted.push(schemaValue); } } }); return tableSchemaFormatted } function setEnable4SelectFields(selectFields, isEnableMap) { for (var key in isEnableMap) { delete isEnableMap[key]; } for (var i = 0; i < selectFields.length; i++) { isEnableMap[selectFields[i]['name']] = ko.observable(true); } } function setChecked4SelectFields(selectFields, checkedMap) { var selectFieldsGroups = {}; _.each(cowc.SELECT_FIELDS_GROUPS, function(fieldGroupValue, fieldGroupKey) { selectFieldsGroups[fieldGroupValue] = []; }); for (var key in checkedMap) { delete checkedMap[key]; } _.each(selectFields, function(selectFieldValue, selectFieldKey) { var key = selectFieldValue.name, aggregateType = cowl.getFirstCharUpperCase(key.substring(0, key.indexOf('('))); if(key == 'T' || key == 'T=' ){ selectFieldsGroups["Time Range"].push(key); aggregateType = "Time Range"; } else if(aggregateType == ''){ selectFieldsGroups["Non Aggregate"].push(key); aggregateType = "Non Aggregate"; } else { selectFieldsGroups[aggregateType].push(key); } selectFieldValue['aggregate_type'] = cowl.getFirstCharUpperCase(aggregateType); }); _.each(selectFieldsGroups, function(aggregateFields, aggregateKey) { _.each(aggregateFields, function(fieldValue, fieldKey) { checkedMap[fieldValue] = ko.observable(false); }); }); } return QueryFormModel; });
nagakiran/contrail-web-core
webroot/js/models/QueryFormModel.js
JavaScript
apache-2.0
30,991
/** * jQuery Twitter Bootstrap Flickr Carousel v1.0.0 * http://jguadagno.github.io/twbs-FlickrCarousel/ * * Copyright 2014, Joseph Guadagno * Released under Apache 2.0 license * http://apache.org/licenses/LICENSE-2.0.html */ ; (function ($, window, document, undefined) { 'use strict'; var old = $.fn.twbsFlickrCarousel; // Contructor var TwbsFlickrCarousel = function (element, options) { this.$element = $(element); this.settings = $.extend({}, $.fn.twbsFlickrCarousel.defaults, options); if (this.settings.onPageClick instanceof(Function)) { this.$element.first().bind('page', this.settings.onPageClick); } if (this.settings.onLoadError instanceof(Function)) { this.$element.first().bind('page', this.settings.onLoadError); } this.getPhotos(this.settings.pageNumber); return this; } // Prototype TwbsFlickrCarousel.prototype = { constructImageElement: function(photo) { if (photo === undefined) { return ""; } return "http://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_" + this.settings.flickrSizeSuffix + "." + this.settings.flickrImageType; }, createCarouselItemCaption: function(title, description) { if (title === undefined) {title = ""; } if (description === undefined) {description = ""; } var caption = $('<div>').addClass('carousel-caption'); $('<h3>').text(title).appendTo(caption); $('<p>').text(description).appendTo(caption); return caption; }, createCarouselItem: function(photo) { var item = $('<div>').addClass('item'); $('<img>').attr('src', this.constructImageElement(photo, false)).attr('alt', photo.title._content).appendTo(item); this.createCarouselItemCaption(photo.title._content, photo.description._content).appendTo(item); return item; }, createCarouselIndicators: function() { // Draw out the indicator items var indicatorHolder = this.$element.find('.carousel-indicators'); if (indicatorHolder === undefined || indicatorHolder.length === 0) { indicatorHolder = $('<ol>').addClass('carousel-indicators').prependTo(this.$element); } indicatorHolder.children().remove(); for (var item = 0; item < this.settings.imagesPerPage; item++) { var indicator = $('<li>').attr('data-target', "#" + this.$element.attr('id')).attr('data-slide-to', item); if (item === 0) { indicator.addClass('active'); } indicator.appendTo(indicatorHolder); } }, createCarouselInner: function() { var carouselInner = this.$element.find('div.carousel-inner'); if (carouselInner === undefined || carouselInner.length === 0) { carouselInner = $('<div>').addClass('carousel-inner'); carouselInner.prependTo(this.$element); // Add the placeholder image var placeHolderUrl = "<img src='http://www.placehold.it/" + this.settings.width + "x" + this.settings.height + "&text=Fetching+images...' alt='Fetching images'>"; var item = $('<div>').addClass('item active'); $(placeHolderUrl).appendTo(item); item.appendTo(carouselInner); } return carouselInner; }, createCarouselNavigation: function() { var left = this.$element.find('a.left'); if (left === undefined || left.length === 0) { left = $('<a>').addClass('left carousel-control').attr('href', "#" + this.$element.attr('id')).attr('role', 'button').attr('data-slide', 'prev'); $('<span>').addClass('glyphicon glyphicon-chevron-left').appendTo(left); left.appendTo(this.$element); } var right = this.$element.find('a.right'); if (right === undefined || right.length === 0) { right = $('<a>').addClass('right carousel-control').attr('href', "#" + this.$element.attr('id')).attr('role', 'button').attr('data-slide', 'next'); $('<span>').addClass('glyphicon glyphicon-chevron-right').appendTo(right); right.appendTo(this.$element); } }, // TODO: Implement our own pagination createPaginationLinks: function(paginationElement, photos) { if (paginationElement === undefined || paginationElement.length === 0) { console.log("createPaginationLinks: paginationElement was undefined or not found"); return; } if (photos === undefined) { console.log("creationPagination: photos element was undefined"); return; } for (var page = 1; page < photos.pages; page++) { var listItem = $('<li>'); if (page === photos.page) { listItem.addClass('active'); } $('<span>').text(page).appendTo(listItem) listItem.appendTo(paginationElement); } }, getPhotoInfo: function(photo, addClass) { if (photo === undefined) { console.log("getPhotoInfo: The photo was undefined"); return; } var carouselInner = this.$element.find('div.carousel-inner') var twbsObject = this; $.getJSON(this.settings.flickrApiUrl, { method: "flickr.photos.getInfo", api_key: this.settings.flickrApiKey, photo_id: photo.id, secret: photo.secret, format: "json", nojsoncallback: "1" }).done(function (data) { var title = "", description = ""; if (data.stat !== "ok") { console.error("getPhotoInfo: Failed to get the details of the photo"); } else { var carouselItem = twbsObject.createCarouselItem(data.photo); if (addClass === 'active') { carouselItem.addClass('active'); } $(carouselItem).appendTo(carouselInner); } }); }, getPhotos: function(pageNumber) { var carouselElement = this.$element; var base = this; // Make sure the required elements for the carousel are there carouselElement.addClass("carousel slide").attr("data-ride", "carousel"); carouselElement.width(this.settings.width); this.createCarouselIndicators(); var carouselInner = this.createCarouselInner(); this.createCarouselNavigation(); $.getJSON(this.settings.flickrApiUrl, { method: "flickr.photos.search", api_key: this.settings.flickrApiKey, tags: this.settings.tagsToSearchFor, per_page: this.settings.imagesPerPage, page: pageNumber, format: "json", nojsoncallback: "1" }).done(function (data) { if (data.stat !== "ok") { console.error("getPhotos: Failed to get the list of photos"); return; } carouselInner.children().remove(); $.each(data.photos.photo, function (i, item) { if (i === 0) { base.getPhotoInfo(item, 'active'); } else { base.getPhotoInfo(item); } }); if (base.settings.paginationSelector !== undefined) { var paginationElement = $(base.settings.paginationSelector); if (paginationElement != undefined && paginationElement.length > 0 && ($.fn.twbsPagination)) { $(base.settings.paginationSelector).twbsPagination({ totalPages: data.photos.pages, visiblePages: base.settings.imagesPerPage, startPage: pageNumber, onPageClick: function (event, page) { base.getPhotos(page); } }); } } }); } }; // Plugin $.fn.twbsFlickrCarousel = function (option) { var args = Array.prototype.slice.call(arguments, 1); var methodReturn; var $this = $(this); var data = $this.data('twbs-flickrCarousel'); var options = typeof option === 'object' && option; if (!data) $this.data('twbs-flickrCarousel', (data = new TwbsFlickrCarousel(this, options) )); if (typeof option === 'string') methodReturn = data[ option ].apply(data, args); return ( methodReturn === undefined ) ? $this : methodReturn; }; $.fn.twbsFlickrCarousel.defaults = { flickrApiKey: '', flickrApiUrl: 'https://api.flickr.com/services/rest/', tagsToSearchFor: '', width: '600', height: '600', imagesPerPage: 10, pageNumber: 1, flickrSizeSuffix: 'z', flickrImageType: 'jpg', paginationSelector: '#flickr-pagination', paginationClass: 'pagination', onPageClick: null, onLoadError: null }; $.fn.twbsFlickrCarousel.Constructor = TwbsFlickrCarousel; $.fn.twbsFlickrCarousel.noConflict = function () { $.fn.twbsFlickrCarousel = old; return this; }; })(jQuery, window, document);
coderwurst/twbs-flickrCarousel
js/jquery.twbsFlickrCarousel.js
JavaScript
apache-2.0
10,017
// // Touches the DOM. // This file listens to events from the language selector and changes the // DOM to have the language requested. // Uses globals from chal-header.html. // // Selecting the current locale var selector = document.getElementById('lang-select') // add change listener selector.addEventListener('change', function (event) { // Go to page in the locale specified var location = window.location var url = location.href.replace(/built\/([a-z]{2}-[A-Z]{2})/, 'built/' + selector.value) location.href = url })
jlord/git-it-electron
lib/languages.js
JavaScript
bsd-2-clause
533
'use strict'; // utility for field require('./globals'); var consts = require('./consts'), c = consts.shorthand, time = require('./compiler/time'), util = require('./util'), schema = require('./schema/schema'); var vlfield = module.exports = {}; /** * @param field * @param opt * opt.nofn -- exclude bin, aggregate, timeUnit * opt.data - include 'data.' * opt.fn - replace fn with custom function prefix * opt.prefn - prepend fn with custom function prefix * @return {[type]} [description] */ vlfield.fieldRef = function(field, opt) { opt = opt || {}; var f = (opt.data ? 'data.' : '') + (opt.prefn || ''), nofn = opt.nofn || opt.fn, name = field.name; if (vlfield.isCount(field)) { return f + 'count'; } else if (!nofn && field.bin) { return f + 'bin_' + name; } else if (!nofn && field.aggregate) { return f + field.aggregate + '_' + name; } else if (!nofn && field.timeUnit) { return f + field.timeUnit + '_' + name; } else if (opt.fn) { return f + opt.fn + '_' + name; } else { return f + name; } }; vlfield.shorthand = function(f) { var c = consts.shorthand; return (f.aggregate ? f.aggregate + c.func : '') + (f.timeUnit ? f.timeUnit + c.func : '') + (f.bin ? 'bin' + c.func : '') + (f.name || '') + c.type + f.type; }; vlfield.shorthands = function(fields, delim) { delim = delim || c.delim; return fields.map(vlfield.shorthand).join(delim); }; vlfield.fromShorthand = function(shorthand) { var split = shorthand.split(c.type), i; var o = { name: split[0].trim(), type: split[1].trim() }; // check aggregate type for (i in schema.aggregate.enum) { var a = schema.aggregate.enum[i]; if (o.name.indexOf(a + '_') === 0) { o.name = o.name.substr(a.length + 1); if (a == 'count' && o.name.length === 0) o.name = '*'; o.aggregate = a; break; } } // check time timeUnit for (i in schema.timefns) { var tu = schema.timefns[i]; if (o.name && o.name.indexOf(tu + '_') === 0) { o.name = o.name.substr(o.length + 1); o.timeUnit = tu; break; } } // check bin if (o.name && o.name.indexOf('bin_') === 0) { o.name = o.name.substr(4); o.bin = true; } return o; }; var typeOrder = { N: 0, O: 1, G: 2, T: 3, Q: 4 }; vlfield.order = {}; vlfield.order.type = function(field) { if (field.aggregate==='count') return 4; return typeOrder[field.type]; }; vlfield.order.typeThenName = function(field) { return vlfield.order.type(field) + '_' + (field.aggregate === 'count' ? '~' : field.name.toLowerCase()); // ~ is the last character in ASCII }; vlfield.order.original = function() { return 0; // no swap will occur }; vlfield.order.name = function(field) { return field.name; }; vlfield.order.typeThenCardinality = function(field, stats){ return stats[field.name].distinct; }; var isType = vlfield.isType = function (fieldDef, type) { return fieldDef.type === type; }; var isTypes = vlfield.isTypes = function (fieldDef, types) { for (var t=0; t<types.length; t++) { if(fieldDef.type === types[t]) return true; } return false; }; /* * Most fields that use ordinal scale are dimensions. * However, YEAR(T), YEARMONTH(T) use time scale, not ordinal but are dimensions too. */ vlfield.isOrdinalScale = function(field) { return isTypes(field, [N, O]) || field.bin || ( isType(field, T) && field.timeUnit && time.isOrdinalFn(field.timeUnit) ); }; function isDimension(field) { return isTypes(field, [N, O]) || !!field.bin || ( isType(field, T) && !!field.timeUnit ); } /** * For encoding, use encoding.isDimension() to avoid confusion. * Or use Encoding.isType if your field is from Encoding (and thus have numeric data type). * otherwise, do not specific isType so we can use the default isTypeName here. */ vlfield.isDimension = function(field) { return field && isDimension(field); }; vlfield.isMeasure = function(field) { return field && !isDimension(field); }; vlfield.role = function(field) { return isDimension(field) ? 'dimension' : 'measure'; }; vlfield.count = function() { return {name:'*', aggregate: 'count', type: Q, displayName: vlfield.count.displayName}; }; vlfield.count.displayName = 'Number of Records'; vlfield.isCount = function(field) { return field.aggregate === 'count'; }; /** * For encoding, use encoding.cardinality() to avoid confusion. Or use Encoding.isType if your field is from Encoding (and thus have numeric data type). * otherwise, do not specific isType so we can use the default isTypeName here. */ vlfield.cardinality = function(field, stats, filterNull) { // FIXME need to take filter into account var stat = stats[field.name]; var type = field.type; filterNull = filterNull || {}; if (field.bin) { var bins = util.getbins(stat, field.bin.maxbins || schema.MAXBINS_DEFAULT); return (bins.stop - bins.start) / bins.step; } if (isType(field, T)) { var cardinality = time.cardinality(field, stats, filterNull, type); if(cardinality !== null) return cardinality; //otherwise use calculation below } if (field.aggregate) { return 1; } // remove null return stat.distinct - (stat.nulls > 0 && filterNull[type] ? 1 : 0); };
vivekratnavel/vega-lite
src/field.js
JavaScript
bsd-3-clause
5,310
import React, { Component } from 'react'; import Steps from './widgets/steps/steps'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; const styles = { container: { display: 'flex', justifyContent: 'space-around', flexDirection: 'column', marginBottom: '1vh', flex: 1, }, green: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#008000', fontSize: 0, textIndent: '-9999em', }, yellow: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#ffff00', fontSize: 0, textIndent: '-9999em', }, red: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#ff0000', fontSize: 0, textIndent: '-9999em', }, lightgray: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#d3d3d3', fontSize: 0, textIndent: '-9999em', }, black: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#000000', fontSize: 0, textIndent: '-9999em', }, }; class QA extends Component { static propTypes = { exposureId: PropTypes.string, qaTests: PropTypes.array, arms: PropTypes.array.isRequired, spectrographs: PropTypes.array.isRequired, mjd: PropTypes.string, date: PropTypes.string, time: PropTypes.string, navigateToMetrics: PropTypes.func, navigateToProcessingHistory: PropTypes.func, petalSizeFactor: PropTypes.number.isRequired, processId: PropTypes.number, monitor: PropTypes.bool, flavor: PropTypes.string, }; componentDidMount() { document.title = 'QA'; } renderMetrics = (step, spectrographNumber, arm) => { if (this.props.navigateToMetrics) { this.props.navigateToMetrics( step, spectrographNumber, arm, this.props.exposureId ); } }; renderSteps = () => { return ( <Steps navigateToProcessingHistory={this.props.navigateToProcessingHistory} qaTests={this.props.qaTests} renderMetrics={this.renderMetrics} mjd={this.props.mjd} exposureId={this.props.exposureId} date={this.props.date} time={this.props.time} petalSizeFactor={this.props.petalSizeFactor} processId={this.props.processId} monitor={this.props.monitor} flavor={this.props.flavor} /> ); }; render() { return <div style={styles.container}>{this.renderSteps()}</div>; } } export default withStyles(styles)(QA);
desihub/qlf
frontend/src/screens/qa/qa.js
JavaScript
bsd-3-clause
2,995
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; const {isLitHtmlTemplateCall} = require('./utils.js'); module.exports = { meta: { type: 'problem', docs: { description: 'Check for self closing custom element tag names in Lit templates.', category: 'Possible Errors', }, fixable: 'code', schema: [] // no options }, create: function(context) { return { TaggedTemplateExpression(node) { const isLitHtmlCall = isLitHtmlTemplateCall(node); if (!isLitHtmlCall) { return; } const text = node.quasi.quasis.map(templatePart => templatePart.value.raw).join('@TEMPLATE_EXPRESSION()'); if (text.match(/<@TEMPLATE_EXPRESSION\(\)([^>]*?)\/>/)) { context.report({ node, message: 'Custom elements should not be self closing.', }); } }, }; } };
ChromeDevTools/devtools-frontend
scripts/eslint_rules/lib/ban_self_closing_custom_element_tagnames.js
JavaScript
bsd-3-clause
1,026
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; const AssetServer = require('../AssetServer'); const getPlatformExtension = require('../node-haste').getPlatformExtension; const Bundler = require('../Bundler'); const MultipartResponse = require('./MultipartResponse'); const declareOpts = require('../lib/declareOpts'); const defaults = require('../../defaults'); const mime = require('mime-types'); const path = require('path'); const symbolicate = require('./symbolicate'); const terminal = require('../lib/terminal'); const url = require('url'); const debug = require('debug')('RNP:Server'); import type Module, {HasteImpl} from '../node-haste/Module'; import type {Stats} from 'fs'; import type {IncomingMessage, ServerResponse} from 'http'; import type ResolutionResponse from '../node-haste/DependencyGraph/ResolutionResponse'; import type Bundle from '../Bundler/Bundle'; import type HMRBundle from '../Bundler/HMRBundle'; import type {Reporter} from '../lib/reporting'; import type {GetTransformOptions} from '../Bundler'; import type {GlobalTransformCache} from '../lib/GlobalTransformCache'; import type {SourceMap, Symbolicate} from './symbolicate'; const { createActionStartEntry, createActionEndEntry, log, } = require('../Logger'); function debounceAndBatch(fn, delay) { let args = []; let timeout; return value => { args.push(value); clearTimeout(timeout); timeout = setTimeout(() => { const a = args; args = []; fn(a); }, delay); }; } type Options = { assetExts?: Array<string>, blacklistRE?: RegExp, cacheVersion?: string, extraNodeModules?: {}, getTransformOptions?: GetTransformOptions, globalTransformCache: ?GlobalTransformCache, hasteImpl?: HasteImpl, moduleFormat?: string, platforms?: Array<string>, polyfillModuleNames?: Array<string>, projectRoots: Array<string>, providesModuleNodeModules?: Array<string>, reporter: Reporter, resetCache?: boolean, silent?: boolean, transformModulePath?: string, transformTimeoutInterval?: number, watch?: boolean, }; export type BundleOptions = { +assetPlugins: Array<string>, dev: boolean, entryFile: string, +entryModuleOnly: boolean, +generateSourceMaps: boolean, +hot: boolean, +inlineSourceMap: boolean, +isolateModuleIDs: boolean, minify: boolean, onProgress: ?(doneCont: number, totalCount: number) => mixed, +platform: ?string, +resolutionResponse: ?{}, +runBeforeMainModule: Array<string>, +runModule: boolean, sourceMapUrl: ?string, unbundle: boolean, }; const dependencyOpts = declareOpts({ platform: { type: 'string', required: true, }, dev: { type: 'boolean', default: true, }, entryFile: { type: 'string', required: true, }, recursive: { type: 'boolean', default: true, }, hot: { type: 'boolean', default: false, }, minify: { type: 'boolean', default: undefined, }, }); const bundleDeps = new WeakMap(); const NODE_MODULES = `${path.sep}node_modules${path.sep}`; class Server { _opts: { assetExts: Array<string>, blacklistRE: void | RegExp, cacheVersion: string, extraNodeModules: {}, getTransformOptions?: GetTransformOptions, hasteImpl?: HasteImpl, moduleFormat: string, platforms: Array<string>, polyfillModuleNames: Array<string>, projectRoots: Array<string>, providesModuleNodeModules?: Array<string>, reporter: Reporter, resetCache: boolean, silent: boolean, transformModulePath: void | string, transformTimeoutInterval: ?number, watch: boolean, }; _projectRoots: Array<string>; _bundles: {}; _changeWatchers: Array<{ req: IncomingMessage, res: ServerResponse, }>; _fileChangeListeners: Array<(filePath: string) => mixed>; _assetServer: AssetServer; _bundler: Bundler; _debouncedFileChangeHandler: (filePath: string) => mixed; _hmrFileChangeListener: ?(type: string, filePath: string) => mixed; _reporter: Reporter; _symbolicateInWorker: Symbolicate; constructor(options: Options) { this._opts = { assetExts: options.assetExts || defaults.assetExts, blacklistRE: options.blacklistRE, cacheVersion: options.cacheVersion || '1.0', extraNodeModules: options.extraNodeModules || {}, getTransformOptions: options.getTransformOptions, globalTransformCache: options.globalTransformCache, hasteImpl: options.hasteImpl, moduleFormat: options.moduleFormat != null ? options.moduleFormat : 'haste', platforms: options.platforms || defaults.platforms, polyfillModuleNames: options.polyfillModuleNames || [], projectRoots: options.projectRoots, providesModuleNodeModules: options.providesModuleNodeModules, reporter: options.reporter, resetCache: options.resetCache || false, silent: options.silent || false, transformModulePath: options.transformModulePath, transformTimeoutInterval: options.transformTimeoutInterval, watch: options.watch || false, }; const processFileChange = ({type, filePath, stat}) => this.onFileChange(type, filePath, stat); this._reporter = options.reporter; this._projectRoots = this._opts.projectRoots; this._bundles = Object.create(null); this._changeWatchers = []; this._fileChangeListeners = []; this._assetServer = new AssetServer({ assetExts: this._opts.assetExts, projectRoots: this._opts.projectRoots, }); const bundlerOpts = Object.create(this._opts); bundlerOpts.assetServer = this._assetServer; bundlerOpts.allowBundleUpdates = this._opts.watch; bundlerOpts.globalTransformCache = options.globalTransformCache; bundlerOpts.watch = this._opts.watch; bundlerOpts.reporter = options.reporter; this._bundler = new Bundler(bundlerOpts); // changes to the haste map can affect resolution of files in the bundle this._bundler.getResolver().then(resolver => { resolver.getDependencyGraph().getWatcher().on( 'change', ({eventsQueue}) => eventsQueue.forEach(processFileChange), ); }); this._debouncedFileChangeHandler = debounceAndBatch(filePaths => { // only clear bundles for non-JS changes if (filePaths.every(RegExp.prototype.test, /\.js(?:on)?$/i)) { for (const key in this._bundles) { this._bundles[key].then(bundle => { const deps = bundleDeps.get(bundle); filePaths.forEach(filePath => { // $FlowFixMe(>=0.37.0) if (deps.files.has(filePath)) { // $FlowFixMe(>=0.37.0) deps.outdated.add(filePath); } }); }).catch(e => { debug(`Could not update bundle: ${e}, evicting from cache`); delete this._bundles[key]; }); } } else { debug('Clearing bundles due to non-JS change'); this._clearBundles(); } this._informChangeWatchers(); }, 50); this._symbolicateInWorker = symbolicate.createWorker(); } end(): mixed { return this._bundler.end(); } setHMRFileChangeListener(listener: ?(type: string, filePath: string) => mixed) { this._hmrFileChangeListener = listener; } addFileChangeListener(listener: (filePath: string) => mixed) { if (this._fileChangeListeners.indexOf(listener) === -1) { this._fileChangeListeners.push(listener); } } async buildBundle(options: BundleOptions): Promise<Bundle> { const bundle = await this._bundler.bundle(options); const modules = bundle.getModules(); const nonVirtual = modules.filter(m => !m.virtual); bundleDeps.set(bundle, { files: new Map(nonVirtual.map(({sourcePath, meta}) => [sourcePath, meta != null ? meta.dependencies : []], )), idToIndex: new Map(modules.map(({id}, i) => [id, i])), dependencyPairs: new Map( nonVirtual .filter(({meta}) => meta && meta.dependencyPairs) /* $FlowFixMe: the filter above ensures `dependencyPairs` is not null. */ .map(m => [m.sourcePath, m.meta.dependencyPairs]) ), outdated: new Set(), }); return bundle; } buildBundleFromUrl(reqUrl: string): Promise<Bundle> { const options = this._getOptionsFromUrl(reqUrl); return this.buildBundle(options); } buildBundleForHMR( options: {platform: ?string}, host: string, port: number, ): Promise<HMRBundle> { return this._bundler.hmrBundle(options, host, port); } getShallowDependencies(options: { entryFile: string, platform?: string, }): Promise<Array<Module>> { return Promise.resolve().then(() => { if (!options.platform) { options.platform = getPlatformExtension(options.entryFile); } const opts = dependencyOpts(options); return this._bundler.getShallowDependencies(opts); }); } getModuleForPath(entryFile: string): Promise<Module> { return this._bundler.getModuleForPath(entryFile); } getDependencies(options: { entryFile: string, platform: ?string, }): Promise<ResolutionResponse<Module>> { return Promise.resolve().then(() => { if (!options.platform) { options.platform = getPlatformExtension(options.entryFile); } const opts = dependencyOpts(options); return this._bundler.getDependencies(opts); }); } getOrderedDependencyPaths(options: {}): Promise<mixed> { return Promise.resolve().then(() => { const opts = dependencyOpts(options); return this._bundler.getOrderedDependencyPaths(opts); }); } onFileChange(type: string, filePath: string, stat: Stats) { this._assetServer.onFileChange(type, filePath, stat); // If Hot Loading is enabled avoid rebuilding bundles and sending live // updates. Instead, send the HMR updates right away and clear the bundles // cache so that if the user reloads we send them a fresh bundle const {_hmrFileChangeListener} = this; if (_hmrFileChangeListener) { // Clear cached bundles in case user reloads this._clearBundles(); _hmrFileChangeListener(type, filePath); return; } else if (type !== 'change' && filePath.indexOf(NODE_MODULES) !== -1) { // node module resolution can be affected by added or removed files debug('Clearing bundles due to potential node_modules resolution change'); this._clearBundles(); } Promise.all( this._fileChangeListeners.map(listener => listener(filePath)) ).then( () => this._onFileChangeComplete(filePath), () => this._onFileChangeComplete(filePath) ); } _onFileChangeComplete(filePath: string) { // Make sure the file watcher event runs through the system before // we rebuild the bundles. this._debouncedFileChangeHandler(filePath); } _clearBundles() { this._bundles = Object.create(null); } _informChangeWatchers() { const watchers = this._changeWatchers; const headers = { 'Content-Type': 'application/json; charset=UTF-8', }; watchers.forEach(function(w) { w.res.writeHead(205, headers); w.res.end(JSON.stringify({changed: true})); }); this._changeWatchers = []; } _processDebugRequest(reqUrl: string, res: ServerResponse) { let ret = '<!doctype html>'; const pathname = url.parse(reqUrl).pathname; /* $FlowFixMe: pathname would be null for an invalid URL */ const parts = pathname.split('/').filter(Boolean); if (parts.length === 1) { ret += '<div><a href="/debug/bundles">Cached Bundles</a></div>'; res.end(ret); } else if (parts[1] === 'bundles') { ret += '<h1> Cached Bundles </h1>'; Promise.all(Object.keys(this._bundles).map(optionsJson => this._bundles[optionsJson].then(p => { ret += '<div><h2>' + optionsJson + '</h2>'; ret += p.getDebugInfo(); }) )).then( () => res.end(ret), e => { res.writeHead(500); res.end('Internal Error'); terminal.log(e.stack); // eslint-disable-line no-console-disallow } ); } else { res.writeHead(404); res.end('Invalid debug request'); return; } } _processOnChangeRequest(req: IncomingMessage, res: ServerResponse) { const watchers = this._changeWatchers; watchers.push({ req, res, }); req.on('close', () => { for (let i = 0; i < watchers.length; i++) { if (watchers[i] && watchers[i].req === req) { watchers.splice(i, 1); break; } } }); } _rangeRequestMiddleware( req: IncomingMessage, res: ServerResponse, data: string, assetPath: string, ) { if (req.headers && req.headers.range) { const [rangeStart, rangeEnd] = req.headers.range.replace(/bytes=/, '').split('-'); const dataStart = parseInt(rangeStart, 10); const dataEnd = rangeEnd ? parseInt(rangeEnd, 10) : data.length - 1; const chunksize = (dataEnd - dataStart) + 1; res.writeHead(206, { 'Accept-Ranges': 'bytes', 'Content-Length': chunksize.toString(), 'Content-Range': `bytes ${dataStart}-${dataEnd}/${data.length}`, 'Content-Type': mime.lookup(path.basename(assetPath[1])), }); return data.slice(dataStart, dataEnd + 1); } return data; } _processAssetsRequest(req: IncomingMessage, res: ServerResponse) { const urlObj = url.parse(decodeURI(req.url), true); /* $FlowFixMe: could be empty if the url is invalid */ const assetPath: string = urlObj.pathname.match(/^\/assets\/(.+)$/); const processingAssetRequestLogEntry = log(createActionStartEntry({ action_name: 'Processing asset request', asset: assetPath[1], })); /* $FlowFixMe: query may be empty for invalid URLs */ this._assetServer.get(assetPath[1], urlObj.query.platform) .then( data => { // Tell clients to cache this for 1 year. // This is safe as the asset url contains a hash of the asset. if (process.env.REACT_NATIVE_ENABLE_ASSET_CACHING === true) { res.setHeader('Cache-Control', 'max-age=31536000'); } res.end(this._rangeRequestMiddleware(req, res, data, assetPath)); process.nextTick(() => { log(createActionEndEntry(processingAssetRequestLogEntry)); }); }, error => { console.error(error.stack); res.writeHead(404); res.end('Asset not found'); } ); } optionsHash(options: {}) { // onProgress is a function, can't be serialized return JSON.stringify(Object.assign({}, options, {onProgress: null})); } /** * Ensure we properly report the promise of a build that's happening, * including failed builds. We use that separately for when we update a bundle * and for when we build for scratch. */ _reportBundlePromise( options: {entryFile: string}, bundlePromise: Promise<Bundle>, ): Promise<Bundle> { this._reporter.update({ entryFilePath: options.entryFile, type: 'bundle_build_started', }); return bundlePromise.then(bundle => { this._reporter.update({ entryFilePath: options.entryFile, type: 'bundle_build_done', }); return bundle; }, error => { this._reporter.update({ entryFilePath: options.entryFile, error, type: 'bundle_build_failed', }); return Promise.reject(error); }); } useCachedOrUpdateOrCreateBundle(options: BundleOptions): Promise<Bundle> { const optionsJson = this.optionsHash(options); const bundleFromScratch = () => { const building = this.buildBundle(options); this._bundles[optionsJson] = building; return building; }; if (optionsJson in this._bundles) { return this._bundles[optionsJson].then(bundle => { const deps = bundleDeps.get(bundle); // $FlowFixMe(>=0.37.0) const {dependencyPairs, files, idToIndex, outdated} = deps; if (outdated.size) { const updatingExistingBundleLogEntry = log(createActionStartEntry({ action_name: 'Updating existing bundle', outdated_modules: outdated.size, })); debug('Attempt to update existing bundle'); // $FlowFixMe(>=0.37.0) deps.outdated = new Set(); const {platform, dev, minify, hot} = options; // Need to create a resolution response to pass to the bundler // to process requires after transform. By providing a // specific response we can compute a non recursive one which // is the least we need and improve performance. const bundlePromise = this._bundles[optionsJson] = Promise.all([ this.getDependencies({ platform, dev, hot, minify, entryFile: options.entryFile, recursive: false, }), Promise.all(Array.from(outdated, this.getModuleForPath, this)), ]).then(([response, changedModules]) => { debug('Update bundle: rebuild shallow bundle'); changedModules.forEach(m => { response.setResolvedDependencyPairs( m, dependencyPairs.get(m.path), {ignoreFinalized: true}, ); }); return this.buildBundle({ ...options, resolutionResponse: response.copy({ dependencies: changedModules, }), }).then(updateBundle => { const oldModules = bundle.getModules(); const newModules = updateBundle.getModules(); for (let i = 0, n = newModules.length; i < n; i++) { const moduleTransport = newModules[i]; const {meta, sourcePath} = moduleTransport; if (outdated.has(sourcePath)) { /* $FlowFixMe: `meta` could be empty */ if (!contentsEqual(meta.dependencies, new Set(files.get(sourcePath)))) { // bail out if any dependencies changed return Promise.reject(Error( `Dependencies of ${sourcePath} changed from [${ /* $FlowFixMe: `get` can return empty */ files.get(sourcePath).join(', ') }] to [${ /* $FlowFixMe: `meta` could be empty */ meta.dependencies.join(', ') }]` )); } oldModules[idToIndex.get(moduleTransport.id)] = moduleTransport; } } bundle.invalidateSource(); log(createActionEndEntry(updatingExistingBundleLogEntry)); debug('Successfully updated existing bundle'); return bundle; }); }).catch(e => { debug('Failed to update existing bundle, rebuilding...', e.stack || e.message); return bundleFromScratch(); }); return this._reportBundlePromise(options, bundlePromise); } else { debug('Using cached bundle'); return bundle; } }); } return this._reportBundlePromise(options, bundleFromScratch()); } processRequest( req: IncomingMessage, res: ServerResponse, next: () => mixed, ) { const urlObj = url.parse(req.url, true); const {host} = req.headers; debug(`Handling request: ${host ? 'http://' + host : ''}${req.url}`); /* $FlowFixMe: Could be empty if the URL is invalid. */ const pathname: string = urlObj.pathname; let requestType; if (pathname.match(/\.bundle$/)) { requestType = 'bundle'; } else if (pathname.match(/\.map$/)) { requestType = 'map'; } else if (pathname.match(/\.assets$/)) { requestType = 'assets'; } else if (pathname.match(/^\/debug/)) { this._processDebugRequest(req.url, res); return; } else if (pathname.match(/^\/onchange\/?$/)) { this._processOnChangeRequest(req, res); return; } else if (pathname.match(/^\/assets\//)) { this._processAssetsRequest(req, res); return; } else if (pathname === '/symbolicate') { this._symbolicate(req, res); return; } else { next(); return; } const options = this._getOptionsFromUrl(req.url); const requestingBundleLogEntry = log(createActionStartEntry({ action_name: 'Requesting bundle', bundle_url: req.url, entry_point: options.entryFile, })); let reportProgress = () => {}; if (!this._opts.silent) { reportProgress = (transformedFileCount, totalFileCount) => { this._reporter.update({ type: 'bundle_transform_progressed', entryFilePath: options.entryFile, transformedFileCount, totalFileCount, }); }; } const mres = MultipartResponse.wrap(req, res); options.onProgress = (done, total) => { reportProgress(done, total); mres.writeChunk({'Content-Type': 'application/json'}, JSON.stringify({done, total})); }; debug('Getting bundle for request'); const building = this.useCachedOrUpdateOrCreateBundle(options); building.then( p => { if (requestType === 'bundle') { debug('Generating source code'); const bundleSource = p.getSource({ inlineSourceMap: options.inlineSourceMap, minify: options.minify, dev: options.dev, }); debug('Writing response headers'); const etag = p.getEtag(); mres.setHeader('Content-Type', 'application/javascript'); mres.setHeader('ETag', etag); if (req.headers['if-none-match'] === etag) { debug('Responding with 304'); mres.writeHead(304); mres.end(); } else { mres.end(bundleSource); } debug('Finished response'); log(createActionEndEntry(requestingBundleLogEntry)); } else if (requestType === 'map') { const sourceMap = p.getSourceMapString({ minify: options.minify, dev: options.dev, }); mres.setHeader('Content-Type', 'application/json'); mres.end(sourceMap); log(createActionEndEntry(requestingBundleLogEntry)); } else if (requestType === 'assets') { const assetsList = JSON.stringify(p.getAssets()); mres.setHeader('Content-Type', 'application/json'); mres.end(assetsList); log(createActionEndEntry(requestingBundleLogEntry)); } }, error => this._handleError(mres, this.optionsHash(options), error) ).catch(error => { process.nextTick(() => { throw error; }); }); } _symbolicate(req: IncomingMessage, res: ServerResponse) { const symbolicatingLogEntry = log(createActionStartEntry('Symbolicating')); debug('Start symbolication'); /* $FlowFixMe: where is `rowBody` defined? Is it added by * the `connect` framework? */ Promise.resolve(req.rawBody).then(body => { const stack = JSON.parse(body).stack; // In case of multiple bundles / HMR, some stack frames can have // different URLs from others const urls = new Set(); stack.forEach(frame => { const sourceUrl = frame.file; // Skip `/debuggerWorker.js` which drives remote debugging because it // does not need to symbolication. // Skip anything except http(s), because there is no support for that yet if (!urls.has(sourceUrl) && !sourceUrl.endsWith('/debuggerWorker.js') && sourceUrl.startsWith('http')) { urls.add(sourceUrl); } }); const mapPromises = Array.from(urls.values()).map(this._sourceMapForURL, this); debug('Getting source maps for symbolication'); return Promise.all(mapPromises).then(maps => { debug('Sending stacks and maps to symbolication worker'); const urlsToMaps = zip(urls.values(), maps); return this._symbolicateInWorker(stack, urlsToMaps); }); }).then( stack => { debug('Symbolication done'); res.end(JSON.stringify({stack})); process.nextTick(() => { log(createActionEndEntry(symbolicatingLogEntry)); }); }, error => { console.error(error.stack || error); res.statusCode = 500; res.end(JSON.stringify({error: error.message})); } ); } _sourceMapForURL(reqUrl: string): Promise<SourceMap> { const options = this._getOptionsFromUrl(reqUrl); const building = this.useCachedOrUpdateOrCreateBundle(options); return building.then(p => p.getSourceMap({ minify: options.minify, dev: options.dev, })); } _handleError(res: ServerResponse, bundleID: string, error: { status: number, type: string, description: string, filename: string, lineNumber: number, errors: Array<{description: string, filename: string, lineNumber: number}>, }) { res.writeHead(error.status || 500, { 'Content-Type': 'application/json; charset=UTF-8', }); if (error.type === 'TransformError' || error.type === 'NotFoundError' || error.type === 'UnableToResolveError') { error.errors = [{ description: error.description, filename: error.filename, lineNumber: error.lineNumber, }]; res.end(JSON.stringify(error)); if (error.type === 'NotFoundError') { delete this._bundles[bundleID]; } } else { console.error(error.stack || error); res.end(JSON.stringify({ type: 'InternalError', message: 'react-packager has encountered an internal error, ' + 'please check your terminal error output for more details', })); } } _getOptionsFromUrl(reqUrl: string): BundleOptions { // `true` to parse the query param as an object. const urlObj = url.parse(reqUrl, true); /* $FlowFixMe: `pathname` could be empty for an invalid URL */ const pathname = decodeURIComponent(urlObj.pathname); // Backwards compatibility. Options used to be as added as '.' to the // entry module name. We can safely remove these options. const entryFile = pathname.replace(/^\//, '').split('.').filter(part => { if (part === 'includeRequire' || part === 'runModule' || part === 'bundle' || part === 'map' || part === 'assets') { return false; } return true; }).join('.') + '.js'; // try to get the platform from the url /* $FlowFixMe: `query` could be empty for an invalid URL */ const platform = urlObj.query.platform || getPlatformExtension(pathname); /* $FlowFixMe: `query` could be empty for an invalid URL */ const assetPlugin = urlObj.query.assetPlugin; const assetPlugins = Array.isArray(assetPlugin) ? assetPlugin : (typeof assetPlugin === 'string') ? [assetPlugin] : []; const dev = this._getBoolOptionFromQuery(urlObj.query, 'dev', true); const minify = this._getBoolOptionFromQuery(urlObj.query, 'minify', false); return { sourceMapUrl: url.format({ hash: urlObj.hash, pathname: pathname.replace(/\.bundle$/, '.map'), query: urlObj.query, search: urlObj.search, }), entryFile, dev, minify, hot: this._getBoolOptionFromQuery(urlObj.query, 'hot', false), runBeforeMainModule: defaults.runBeforeMainModule, runModule: this._getBoolOptionFromQuery(urlObj.query, 'runModule', true), inlineSourceMap: this._getBoolOptionFromQuery( urlObj.query, 'inlineSourceMap', false ), isolateModuleIDs: false, platform, resolutionResponse: null, entryModuleOnly: this._getBoolOptionFromQuery( urlObj.query, 'entryModuleOnly', false, ), generateSourceMaps: minify || !dev || this._getBoolOptionFromQuery(urlObj.query, 'babelSourcemap', false), assetPlugins, onProgress: null, unbundle: false, }; } _getBoolOptionFromQuery(query: ?{}, opt: string, defaultVal: boolean): boolean { /* $FlowFixMe: `query` could be empty when it comes from an invalid URL */ if (query[opt] == null) { return defaultVal; } return query[opt] === 'true' || query[opt] === '1'; } static DEFAULT_BUNDLE_OPTIONS; } Server.DEFAULT_BUNDLE_OPTIONS = { assetPlugins: [], dev: true, entryModuleOnly: false, generateSourceMaps: false, hot: false, inlineSourceMap: false, isolateModuleIDs: false, minify: false, onProgress: null, resolutionResponse: null, runBeforeMainModule: defaults.runBeforeMainModule, runModule: true, sourceMapUrl: null, unbundle: false, }; function contentsEqual<T>(array: Array<T>, set: Set<T>): boolean { return array.length === set.size && array.every(set.has, set); } function* zip<X, Y>(xs: Iterable<X>, ys: Iterable<Y>): Iterable<[X, Y]> { //$FlowIssue #9324959 const ysIter: Iterator<Y> = ys[Symbol.iterator](); for (const x of xs) { const y = ysIter.next(); if (y.done) { return; } yield [x, y.value]; } } module.exports = Server;
Maxwell2022/react-native
packager/src/Server/index.js
JavaScript
bsd-3-clause
29,966
'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunntag", "M\u00e4ntag", "Zi\u0161tag", "Mittwu\u010d", "Fr\u00f3ntag", "Fritag", "Sam\u0161tag" ], "ERANAMES": [ "v. Chr.", "n. Chr" ], "ERAS": [ "v. Chr.", "n. Chr" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Jenner", "Hornig", "M\u00e4rze", "Abrille", "Meije", "Br\u00e1\u010det", "Heiwet", "\u00d6ig\u0161te", "Herb\u0161tm\u00e1net", "W\u00edm\u00e1net", "Winterm\u00e1net", "Chri\u0161tm\u00e1net" ], "SHORTDAY": [ "Sun", "M\u00e4n", "Zi\u0161", "Mit", "Fr\u00f3", "Fri", "Sam" ], "SHORTMONTH": [ "Jen", "Hor", "M\u00e4r", "Abr", "Mei", "Br\u00e1", "Hei", "\u00d6ig", "Her", "W\u00edm", "Win", "Chr" ], "STANDALONEMONTH": [ "Jenner", "Hornig", "M\u00e4rze", "Abrille", "Meije", "Br\u00e1\u010det", "Heiwet", "\u00d6ig\u0161te", "Herb\u0161tm\u00e1net", "W\u00edm\u00e1net", "Winterm\u00e1net", "Chri\u0161tm\u00e1net" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d. MMMM y", "longDate": "d. MMMM y", "medium": "d. MMM y HH:mm:ss", "mediumDate": "d. MMM y", "mediumTime": "HH:mm:ss", "short": "y-MM-dd HH:mm", "shortDate": "y-MM-dd", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "CHF", "DECIMAL_SEP": ",", "GROUP_SEP": "\u2019", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4\u00a0", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "wae-ch", "localeID": "wae_CH", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);
mudunuriRaju/tlr-live
tollbackend/web/js/angular-1.5.5/i18n/angular-locale_wae-ch.js
JavaScript
bsd-3-clause
4,235
"use strict";; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var types_1 = __importDefault(require("./types")); function default_1(fork) { var types = fork.use(types_1.default); var Type = types.Type; var builtin = types.builtInTypes; var isNumber = builtin.number; // An example of constructing a new type with arbitrary constraints from // an existing type. function geq(than) { return Type.from(function (value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than); } ; // Default value-returning functions that may optionally be passed as a // third argument to Def.prototype.field. var defaults = { // Functions were used because (among other reasons) that's the most // elegant way to allow for the emptyArray one always to give a new // array instance. "null": function () { return null; }, "emptyArray": function () { return []; }, "false": function () { return false; }, "true": function () { return true; }, "undefined": function () { }, "use strict": function () { return "use strict"; } }; var naiveIsPrimitive = Type.or(builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined); var isPrimitive = Type.from(function (value) { if (value === null) return true; var type = typeof value; if (type === "object" || type === "function") { return false; } return true; }, naiveIsPrimitive.toString()); return { geq: geq, defaults: defaults, isPrimitive: isPrimitive, }; } exports.default = default_1; module.exports = exports["default"];
endlessm/chromium-browser
third_party/devtools-frontend/src/node_modules/ast-types/lib/shared.js
JavaScript
bsd-3-clause
1,900
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //<script> $(document).ready(function() { var curSource = "/alliance/dutylist/calendarsearch"; $('#dutylsitCalendar').fullCalendar({ contentHeight: 600, aspectRatio: 8, handleWindowResize: true, // Изменять размер календаря пропорционально изменению окна браузера editable: false, // Редактирование запрещено, т.к. источник событий json-feed из БД isRTL: false, // Отображать календарь в обратном порядке (true/false) // hiddenDays: [], // Скрыть дни недели [перечислить номера дней недели ч-з запятую] weekMode: 'liquid', weekNumbers: true, weekends: true, defaultView: 'month', selectable: false, editable: false, lang: 'ru', more: 3, firstday: 1, theme:true, buttonIcons: { prev: 'left-single-arrow', next: 'right-single-arrow', prevYear: 'left-double-arrow', nextYear: 'right-double-arrow' }, themeButtonsIcons: { prev: 'circle-triangle-w', next: 'circle-triangle-e', prevYear: 'seek-prev', nextYear: 'seek-next' }, // eventLimitClick // "popover" — показывает всплывающую панель со списком всех событий (по умолчанию) // "week" — переходит на вид недели, оглашенный в параметре header // "day" — переходит на вид дня, оглашенный в параметре header // название вида — текстовое название вида из списка доступных видов // функция — callback-функция для выполнения произвольного кода eventLimit: true, eventLimitClick: 'popover', views: { agenda: { eventLimit: 15, } }, // hiddenDays: [ 1, 2, 3, 4, 5 ], businessHours: { start: '9:00', // время начала end: '21:00', // время окончания dow: [ 6, 7 ] // days of week. an array of zero-based day of week integers (0=Sunday) дни недели, начиная с 0 (0-ВСК) }, // eventSources: [curSource[0],curSource[1]], eventSources: [ { url: curSource, cache: true, error: function() { alert("Ошибка получения источника событий"); }, }, ], header: { left: 'prev,today,next', center: 'title,filter', right: 'month,agendaWeek,agendaDay', }, eventRender: function eventRender(event, eventElement, element, view) { if (event.imageurl) { eventElement.find("div.fc-content").prepend("<div class='text-center' style='padding: 1px;'><img class='img-rounded' src='" + event.imageurl +"' width='50' height='50'></div>"); } return ['all', event.title].indexOf($('#employee_filter').val()) >= 0; }, eventClick: function(event, jsEvent, view) { $('#modalTitle').html(moment(event.start).format('DD/MM/YYYY') + ' - Оперативный дежурный на указанную дату:'); $('#modalBody').html("<div class='text-center'> <img class='img-rounded text-center' src='" + event.imageurl + "' width='50' height='50'>" + ' <b>' + event.title + '</b></div>'); $('#eventUrl').attr('href',event.url); $('#fullCalModal').modal(); }, dayClick: function(date, jsEvent, view) { var d = new Date(date); if (confirm("Перейти к выбранной дате - " + d.toLocaleDateString('en-GB') + " ?")) { $('#dutylsitCalendar').fullCalendar('changeView', 'agendaDay'); $('#dutylsitCalendar').fullCalendar('gotoDate', d); } // alert('Clicked on: ' + date.format()); // alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); // alert('Current view: ' + view.name); }, // Цвет дня в календаре: // dayRender : function(date, cell) { // var idx = null; // var today = new Date().toDateString(); // var ddate = date.toDate().toDateString(); // if (ddate == today) { // idx = cell.index() + 1; // cell.css("background-color", "azure"); // $( // ".fc-time-grid .fc-bg table tbody tr td:nth-child(" // + idx + ")").css( // "background-color", "azure"); // } // }, dayRender: function (date, cell) { var today = new Date().toDateString(); var end = new Date(); end.setDate(today+7); if (date.toDate().toDateString() === today) { cell.css("background-color", "#5cb85c"); } if(date.toDate().toDateString() > today && date.toDate().toDateString() <= end) { cell.css("background-color", "yellow"); } }, }); }); // DatePicker $('#dutylistDatepicker').datepicker({ dateFormat: 'yy-mm-dd', inline: true, showButtonPanel: true, changeYear: true, changeMonth: true, yearRange: '-2:+2', altField: '#dutylistDatepicker', altFormat: 'dd/mm/yy', beforeShow: function() { setTimeout(function(){ $('.ui-datepicker').css('z-index', 99999999999999); }, 0); }, onSelect: function(dateText, inst) { var d = new Date(dateText); if (confirm("Перейти к выбранной дате - " + d.toLocaleDateString('en-GB') + " ?")) { $('#dutylsitCalendar').fullCalendar('changeView', 'agendaDay'); $('#dutylsitCalendar').fullCalendar('gotoDate', d); } else { // alert(d.toLocaleDateString()); // $('#datepicker').datepicker('setDate', null); // $('#datepicker').val('').datepicker("refresh"); } } }); // Опции селектора $('#employee_filter').on('change',function(){ $('#dutylsitCalendar').fullCalendar('rerenderEvents'); }); function showOrHide() { cb = document.getElementById('checkbox'); if (cb.checked) hideDays(); else showDays(); } var hideDays = function() { $('#dutylsitCalendar').fullCalendar('option', { hiddenDays: [1, 2, 3, 4, 5], }); } var showDays = function() { $('#dutylsitCalendar').fullCalendar('option', { hiddenDays: [], }); } function hideSideBar() { document.getElementById("sidebar").style.display = "none"; } // $('#filterStatus').multiselect({ // numberDisplayed: 2, // enableFiltering: false, // includeSelectAllOption: true, // nonSelectedText: 'Статус', // });
m-ishchenko/AllianceCG
web/js/modules/alliance/dutylist/calendar.js
JavaScript
bsd-3-clause
8,663
var MemoryBlogStore = require('./MemoryBlogStore'); var blogStore = new MemoryBlogStore(); blogStore.addPost({ text: 'Hello' }, function(err, post) { console.log(err, post); }); blogStore.addPost({ text: 'Hello' }, function(err, post) { console.log(err, post); }); blogStore.addPost({ text: 'Hello' }, function(err, post) { console.log(err, post); }); // blogStore.getPostsRange(0, 2, function(err, posts) { // console.log(err, posts) // }); blogStore.getPostsAfter(1, 2, function(err, posts) { console.log(err, posts) });
galynacherniakhivska/Blog
server/sandbox.js
JavaScript
isc
537
var mysql = require('mysql'); function mysqlConn(config,logger) { this.connectionPool = mysql.createPool(config); this.initialized = true; this.logger = logger; } mysqlConn.prototype = { /// if the raw connection is needed getConnection: function (callback) { if (!this.initialized) { callback(new Error("Connection not initialized")); return; } this.connectionPool.getConnection(function (err, connection) { // Use the connection if (err ) this.logger.error('#Database -> Connection: ' + JSON.stringify(err)); if (callback) callback(err, connection); connection.release(); }); } ,executeSP: function (procedureName, params, callback) { if (!this.initialized) { callback(new Error("Connection not initialized")); return; } if (typeof (params) == "function" && callback == undefined) { callback = params; params = null; } var sql = 'CALL ' + procedureName + '(params)'; sql = this._injectParams(sql, params); var l= this.logger; //Execute stored procedure call this.connectionPool.query(sql, function (err, rows, fields) { if (err) { try { if (err.code == 'ER_SIGNAL_EXCEPTION' && err.sqlState == '45000' && err.message) { var errorCode = err.message.replace('ER_SIGNAL_EXCEPTION: ', ''); l.warn('#Database -> Stored Procedure: ' + sql + ' Error code ##' + errorCode + '## was relieved while executing stored procedure :' ,err); err.errorCode = errorCode; } else { l.error('#Database -> Stored Procedure: ' + sql + ' an error has occurred while executing stored procedure :', err); } } catch(e) { console.error(e); } callback(err, null); } else { l.debug('#Database -> Stored Procedure: ' + sql + ' connected to database successfully'); callback(null, rows); } }); } ,_injectParams: function (query, params) { //Inject parameters in Stored Procedure Call var parameters = ''; if (params) { params.forEach(function (param, index) { if (param == null || param.value == null) parameters += "null"; else{ try{ parameters += "@" + param.name + ':=' + mysql.escape(param.value); } catch(e) { console.log(e); throw e; } } if (index < params.length - 1) parameters += ","; }); } query = query.replace("params", parameters); return query; } , createCommand: function (procedureName) { return new mysqlCommand(procedureName, this); } }; function mysqlCommand(procedureName, connectionPool) { this.connectionPool = connectionPool; this.procedureName = procedureName; this.params = []; } mysqlCommand.prototype = { addParam: function (name, value) { this.params.push({ "name": name , "value" : value }); } ,getDataSet: function (callback) { this.connectionPool.executeSP(this.procedureName, this.params, function (err, data) { if (err) callback(err, null); else { if (data) callback(null, data); else callback(null, null); } }); } ,getDataTable: function (callback) { this.getDataSet(function (err, data) { if (err) callback(err, null); else { if (data && data.length > 0) callback(null, data[0]); else callback(null, []); } }); } ,getDataObject: function (callback) { this.getDataTable(function (err, data) { if (err) callback(err, null); else { if (data && data.length > 0) callback(null, data[0]); else callback(null, null); } }); } ,getScalar: function (callback) { this.getDataObject(function (err, data) { if (err) callback(err, null); else { if (data != null) { var key = Object.keys(data); callback(null, data[key[0]]); } else callback(null, null); } }); } } module.exports = mysqlConn;
javuio/MySQLNodeBootstrapAngular
modules/mDAL/mysql/mysqlDAL.js
JavaScript
mit
5,078
'use strict'; define([ 'three', 'explorer', 'underscore' ], function( THREE, Explorer, _ ) { var mp3names = ['crystalCenter', 'cellCollision', 'atomCollision', 'popOutOfAtom', 'dollHolder', 'atomUnderDoll', 'navCube', 'dollArrived', 'leapGrab', 'leapNoGrab']; function Sound(animationMachine) { this.procced = true, this.context ; this.animationMachine = animationMachine ; this.mute = true ; this.buffers = [] ; this.crystalHold ; this.crystalCameraOrbit ; this.crysCentrSource = {panner: undefined , dryGain: undefined , panX : 0, panZ : 0, gain : 0 }; this.steredLoops = {}; this.lattice; this.volume = 0.75 ; this.atomSourcePos = undefined; var _this = this ; try { this.context = new (window.AudioContext || window.webkitAudioContext)(); } catch(e) { this.procced = false; alert('Web Audio API not supported in this browser.'); } if(this.procced === true){ this.universalGainNode = this.context.createGain(); this.universalGainNode.gain.value = 0.75; this.universalGainNode.connect(this.context.destination); } }; Sound.prototype.changeVolume = function(arg){ if(arg.sound){ this.universalGainNode.gain.value = parseFloat(arg.sound)/100; } }; Sound.prototype.loadSamples = function(url){ var _this = this ; var request = new XMLHttpRequest(); request.open('GET', 'sounds/'+url+'.mp3', true); request.setRequestHeader ("Accept", "Access-Control-Allow-Origin: *'"); // to access locally the Mp3s request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; _this.context.decodeAudioData( audioData, function(buffer) { _this.buffers[url] = buffer; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } Sound.prototype.crystalCenterStop = function() { if(this.crystalHold) { clearInterval(this.crystalHold); } }; Sound.prototype.calculateAngle = function(x,z){ var vec1 = new THREE.Vector2(this.crystalCameraOrbit.control.target.x-this.crystalCameraOrbit.camera.position.x,this.crystalCameraOrbit.control.target.z-this.crystalCameraOrbit.camera.position.z); var vec2 = new THREE.Vector2(x-this.crystalCameraOrbit.camera.position.x,z-this.crystalCameraOrbit.camera.position.z); vec1.normalize(); vec2.normalize(); var angle = Math.atan2( vec2.y,vec2.x) - Math.atan2(vec1.y,vec1.x); var f =angle* (180/Math.PI); if(f > 180 ) f = f - 360; if(f < -180 ) f = f + 360; return f; }; Sound.prototype.soundSourcePos = function() { if(this.lattice === undefined){ return; } var centroid = new THREE.Vector3(0,0,0); if(this.atomSourcePos !== undefined){ centroid = this.atomSourcePos.clone(); } else{ var g = this.lattice.customBox(this.lattice.viewBox); if(g !== undefined){ centroid = new THREE.Vector3(); for ( var z = 0, l = g.vertices.length; z < l; z ++ ) { centroid.add( g.vertices[ z ] ); } centroid.divideScalar( g.vertices.length ); } } return centroid ; }; Sound.prototype.switcher = function(start) { if(this.procced && this.buffers.length === 0 && start === true){ for (var i = mp3names.length - 1; i >= 0; i--) { this.loadSamples(mp3names[i]); }; } var _this = this ; if(start === true){ this.mute = false ; this.crystalHold = setInterval( function() { var centroid = _this.soundSourcePos(); _this.animationMachine.produceWave(centroid, 'crystalCenter'); _this.play('crystalCenter', centroid, true); },2000); } else{ if(this.crystalHold) clearInterval(this.crystalHold); this.mute = true ; } }; Sound.prototype.stopStoredPlay = function(sampleName) { if(this.steredLoops[sampleName] !== undefined){ this.steredLoops[sampleName].stop(); } }; Sound.prototype.storePlay = function(sampleName) { var _this = this, voice; if(!this.mute){ voice = this.context.createBufferSource(); voice.buffer = this.buffers[sampleName] ; voice.connect(this.universalGainNode); this.steredLoops[sampleName] = voice ; voice.start(0); } }; Sound.prototype.play = function(sampleName, sourcePos, calcPanning) { if(!this.mute && mp3names.length === Object.keys(this.buffers).length){ var data; var voice = this.context.createBufferSource(); voice.buffer = this.buffers[sampleName] ; if(calcPanning){ data = this.calculatePanning(sourcePos); var dryGain = this.context.createGain(); var panner = this.context.createPanner(); panner.setPosition(data.panX, data.panY, data.panZ); dryGain.gain.value = data.gain; voice.connect(dryGain); dryGain.connect(panner); panner.connect(this.universalGainNode); } else{ voice.connect(this.universalGainNode); } voice.start(0); } }; // panning vars go from -1 to 1 var ttt = false; Sound.prototype.calculatePanning = function(objPos){ var _this = this ; var c = this.crystalCameraOrbit.camera.position.clone(); // custom panning method. panX goes sinusoidal and panZ is set according to panX so panX + panZ = 1 var panX = Math.sin( this.calculateAngle(objPos.x,objPos.z) * (Math.PI/180) ) ; var panZ = (panX <= 0 ? (1 + panX) : ( 1 - panX) ); var panY = 0; var distance = objPos.distanceTo(this.crystalCameraOrbit.camera.position ); var gain = (distance < 20 ? 1 : (1 - distance/700)) ; gain = gain * 1 ; if(gain < 0.1) gain = 0.1 ; return {'gain' : gain, 'panX' : panX, 'panY' : panY, 'panZ' : panZ }; } return Sound; });
gvcm/CWAPP
scripts/sound.js
JavaScript
mit
6,026
YUI.add("lang/gallery-message-format_lv",function(e){e.Intl.add("gallery-message-format","lv",{pluralRule:"set6"})},"gallery-2013.04.10-22-48");
inikoo/fact
libs/yui/yui3-gallery/build/gallery-message-format/lang/gallery-message-format_lv.js
JavaScript
mit
145
'use strict'; /* jshint -W030 */ var chai = require('chai') , expect = chai.expect , Support = require(__dirname + '/../support') , DataTypes = require(__dirname + '/../../../lib/data-types') , Sequelize = Support.Sequelize , dialect = Support.getTestDialect() , sinon = require('sinon'); describe(Support.getTestDialectTeaser('Hooks'), function() { beforeEach(function() { this.User = this.sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false }, mood: { type: DataTypes.ENUM, values: ['happy', 'sad', 'neutral'] } }); this.ParanoidUser = this.sequelize.define('ParanoidUser', { username: DataTypes.STRING, mood: { type: DataTypes.ENUM, values: ['happy', 'sad', 'neutral'] } }, { paranoid: true }); return this.sequelize.sync({ force: true }); }); describe('#define', function() { before(function() { this.sequelize.addHook('beforeDefine', function(attributes, options) { options.modelName = 'bar'; options.name.plural = 'barrs'; attributes.type = DataTypes.STRING; }); this.sequelize.addHook('afterDefine', function(factory) { factory.options.name.singular = 'barr'; }); this.model = this.sequelize.define('foo', {name: DataTypes.STRING}); }); it('beforeDefine hook can change model name', function() { expect(this.model.name).to.equal('bar'); }); it('beforeDefine hook can alter options', function() { expect(this.model.options.name.plural).to.equal('barrs'); }); it('beforeDefine hook can alter attributes', function() { expect(this.model.rawAttributes.type).to.be.ok; }); it('afterDefine hook can alter options', function() { expect(this.model.options.name.singular).to.equal('barr'); }); after(function() { this.sequelize.options.hooks = {}; this.sequelize.modelManager.removeModel(this.model); }); }); describe('#init', function() { before(function() { Sequelize.addHook('beforeInit', function(config, options) { config.database = 'db2'; options.host = 'server9'; }); Sequelize.addHook('afterInit', function(sequelize) { sequelize.options.protocol = 'udp'; }); this.seq = new Sequelize('db', 'user', 'pass', { dialect : dialect }); }); it('beforeInit hook can alter config', function() { expect(this.seq.config.database).to.equal('db2'); }); it('beforeInit hook can alter options', function() { expect(this.seq.options.host).to.equal('server9'); }); it('afterInit hook can alter options', function() { expect(this.seq.options.protocol).to.equal('udp'); }); after(function() { Sequelize.options.hooks = {}; }); }); describe('passing DAO instances', function() { describe('beforeValidate / afterValidate', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeValidate: function(user, options, fn) { expect(user).to.be.instanceof(User); beforeHooked = true; fn(); }, afterValidate: function(user, options, fn) { expect(user).to.be.instanceof(User); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); describe('beforeCreate / afterCreate', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeCreate: function(user, options, fn) { expect(user).to.be.instanceof(User); beforeHooked = true; fn(); }, afterCreate: function(user, options, fn) { expect(user).to.be.instanceof(User); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); describe('beforeDestroy / afterDestroy', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeDestroy: function(user, options, fn) { expect(user).to.be.instanceof(User); beforeHooked = true; fn(); }, afterDestroy: function(user, options, fn) { expect(user).to.be.instanceof(User); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function(user) { return user.destroy().then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); describe('beforeDelete / afterDelete', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeDelete: function(user, options, fn) { expect(user).to.be.instanceof(User); beforeHooked = true; fn(); }, afterDelete: function(user, options, fn) { expect(user).to.be.instanceof(User); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function(user) { return user.destroy().then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); describe('beforeUpdate / afterUpdate', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeUpdate: function(user, options, fn) { expect(user).to.be.instanceof(User); beforeHooked = true; fn(); }, afterUpdate: function(user, options, fn) { expect(user).to.be.instanceof(User); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function(user) { user.username = 'bawb'; return user.save({ fields: ['username'] }).then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); }); describe('Model#sync', function() { describe('on success', function() { it('should run hooks', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(afterHook); return this.User.sync().then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); it('should not run hooks when "hooks = false" option passed', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(afterHook); return this.User.sync({ hooks: false }).then(function() { expect(beforeHook).to.not.have.been.called; expect(afterHook).to.not.have.been.called; }); }); }); describe('on error', function() { it('should return an error from before', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeSync(function(options) { beforeHook(); throw new Error('Whoops!'); }); this.User.afterSync(afterHook); return expect(this.User.sync()).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); it('should return an error from after', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(function(options) { afterHook(); throw new Error('Whoops!'); }); return expect(this.User.sync()).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); describe('sequelize#sync', function() { describe('on success', function() { it('should run hooks', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy() , modelBeforeHook = sinon.spy() , modelAfterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.User.beforeSync(modelBeforeHook); this.User.afterSync(modelAfterHook); this.sequelize.afterBulkSync(afterHook); return this.sequelize.sync().then(function() { expect(beforeHook).to.have.been.calledOnce; expect(modelBeforeHook).to.have.been.calledOnce; expect(modelAfterHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); it('should not run hooks if "hooks = false" option passed', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy() , modelBeforeHook = sinon.spy() , modelAfterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.User.beforeSync(modelBeforeHook); this.User.afterSync(modelAfterHook); this.sequelize.afterBulkSync(afterHook); return this.sequelize.sync({ hooks: false }).then(function() { expect(beforeHook).to.not.have.been.called; expect(modelBeforeHook).to.not.have.been.called; expect(modelAfterHook).to.not.have.been.called; expect(afterHook).to.not.have.been.called; }); }); afterEach(function() { this.sequelize.options.hooks = {}; }); }); describe('on error', function() { it('should return an error from before', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.sequelize.beforeBulkSync(function(options) { beforeHook(); throw new Error('Whoops!'); }); this.sequelize.afterBulkSync(afterHook); return expect(this.sequelize.sync()).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); it('should return an error from after', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.sequelize.afterBulkSync(function(options) { afterHook(); throw new Error('Whoops!'); }); return expect(this.sequelize.sync()).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); afterEach(function() { this.sequelize.options.hooks = {}; }); }); }); describe('#removal', function() { it('should be able to remove by name', function() { var sasukeHook = sinon.spy() , narutoHook = sinon.spy(); this.User.hook('beforeCreate', 'sasuke', sasukeHook); this.User.hook('beforeCreate', 'naruto', narutoHook); return this.User.create({ username: 'makunouchi'}).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledOnce; this.User.removeHook('beforeCreate', 'sasuke'); return this.User.create({ username: 'sendo'}); }).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledTwice; }); }); it('should be able to remove by reference', function() { var sasukeHook = sinon.spy() , narutoHook = sinon.spy(); this.User.hook('beforeCreate', sasukeHook); this.User.hook('beforeCreate', narutoHook); return this.User.create({ username: 'makunouchi'}).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledOnce; this.User.removeHook('beforeCreate', sasukeHook); return this.User.create({ username: 'sendo'}); }).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledTwice; }); }); it('should be able to remove proxies', function() { var sasukeHook = sinon.spy() , narutoHook = sinon.spy(); this.User.hook('beforeSave', sasukeHook); this.User.hook('beforeSave', narutoHook); return this.User.create({ username: 'makunouchi'}).then((user) => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledOnce; this.User.removeHook('beforeSave', sasukeHook); return user.updateAttributes({ username: 'sendo'}); }).then(() => { expect(sasukeHook).to.have.been.calledOnce; expect(narutoHook).to.have.been.calledTwice; }); }); }); });
topikachu/sequelize
test/integration/hooks/hooks.test.js
JavaScript
mit
14,781
// // tselect01.js // Test for select // if(typeof exports === 'object') { var assert = require("assert"); var alasql = require('..'); }; describe('Create database', function(){ it('Create new database', function(done) { var db = new alasql.Database(); assert.deepEqual(db.tables, {}); done(); }); });
kanghj/alasql
test/test108.js
JavaScript
mit
342
/** * Returns the string, with after processing the following backslash escape sequences. * * attacklab: The polite way to do this is with the new escapeCharacters() function: * * text = escapeCharacters(text,"\\",true); * text = escapeCharacters(text,"`*_{}[]()>#+-.!",true); * * ...but we're sidestepping its use of the (slow) RegExp constructor * as an optimization for Firefox. This function gets called a LOT. */ showdown.subParser('encodeBackslashEscapes', function (text, options, globals) { 'use strict'; text = globals.converter._dispatch('encodeBackslashEscapes.before', text, options, globals); text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback); text = text.replace(/\\([`*_{}\[\]()>#+.!~=-])/g, showdown.helper.escapeCharactersCallback); text = globals.converter._dispatch('encodeBackslashEscapes.after', text, options, globals); return text; });
skiwer/myBlog
static/showdown/src/subParsers/encodeBackslashEscapes.js
JavaScript
mit
913
const ts = require('typescript'); const utils = require('tsutils'); const Lint = require('tslint'); const ERROR_MESSAGE = 'A TODO may only appear in inline (//) style comments. ' + 'This is meant to prevent a TODO from being accidentally included in any public API docs.'; /** * Rule that walks through all comments inside of the library and adds failures when it * detects TODO's inside of multi-line comments. TODOs need to be placed inside of single-line * comments. */ class Rule extends Lint.Rules.AbstractRule { apply(sourceFile) { return this.applyWithWalker(new NoExposedTodoWalker(sourceFile, this.getOptions())); } } class NoExposedTodoWalker extends Lint.RuleWalker { visitSourceFile(sourceFile) { utils.forEachComment(sourceFile, (fullText, commentRange) => { let isTodoComment = fullText.substring(commentRange.pos, commentRange.end).includes('TODO'); if (commentRange.kind === ts.SyntaxKind.MultiLineCommentTrivia && isTodoComment) { this.addFailureAt(commentRange.pos, commentRange.end - commentRange.pos, ERROR_MESSAGE); } }); super.visitSourceFile(sourceFile); } } exports.Rule = Rule;
nkwood/material2
tools/tslint-rules/noExposedTodoRule.js
JavaScript
mit
1,173
// this is just a demo. To run it execute from the root of repository: // // > npm start // // Then open ./example/index.html // module.exports.main = function () { var graph = require('ngraph.generators').balancedBinTree(6); var createPixiGraphics = require('../'); var pixiGraphics = createPixiGraphics(graph); var layout = pixiGraphics.layout; // just make sure first node does not move: layout.pinNode(graph.getNode(1), true); // begin animation loop: pixiGraphics.run(); }
fobdy/ngraph.pixi
example/index.js
JavaScript
mit
497
describe( 'AppCtrl', function() { describe( 'isCurrentUrl', function() { var AppCtrl, $location, $scope; beforeEach( module( 'app' ) ); beforeEach( inject( function( $controller, _$location_, $rootScope ) { $location = _$location_; $scope = $rootScope.$new(); AppCtrl = $controller( 'AppCtrl', { $location: $location, $scope: $scope }); })); it( 'should pass a dummy test', inject( function() { expect( AppCtrl ).toBeTruthy(); })); }); });
jjccww/poc
src/app/app.spec.js
JavaScript
mit
495
<p> Añadir nuevo comentario: </p> <p> <form method="POST" action="/quizzes/<%=quiz.id%>/comments/"> <input type="text" id="comment" name="comment[text]" value="" placeholder="Comentario" /> <p> <button type="submit">Enviar</button> </form> </p>
JavierAmorDeLaCruz/quiz
views/comments/new.js
JavaScript
mit
272
YUI.add("y3d-texture",function(e,t){var n=e.Lang;e.Texture=e.Base.create("texture",e.Base,[],{},{ATTRS:{image:{value:null},imageUrl:{value:"",validator:n.isString},webglTexture:{value:null}}}),e.TextureLoader=e.Base.create("texture-loader",e.Base,[],{initializer:function(){var t=this,n=t.get("textures"),r=t.get("unloadedTextures"),i,s,o,u;for(i=0;i<n.length;i++)s=n[i],o=new Image,u=s.get("imageUrl"),r[u]=s,o.onload=e.bind(t._onLoad,t,s),o.src=u,s.set("image",o)},_isEmpty:function(){var e=this,t=e.get("unloadedTextures"),n;for(n in t)if(t.hasOwnProperty(n))return!1;return!0},_onLoad:function(e){var t=this,n=e.get("imageUrl"),r=t.get("onLoad"),i=t.get("unloadedTextures");delete i[n],t._isEmpty()&&r()}},{ATTRS:{onLoad:{value:null},textures:{value:[],validator:n.isArray},unloadedTextures:{value:{}}}})},"gallery-2013.08.22-21-03",{requires:["base-build"]});
inikoo/fact
libs/yui/yui3-gallery/build/y3d-texture/y3d-texture-min.js
JavaScript
mit
865
module.exports = { entry: ["react", "react-dom", "lodash"] }
pugnascotia/webpack
test/benchmarkCases/libraries/webpack.config.js
JavaScript
mit
62
/* This utility processes the argument passed with the `lang` option in ember-cli, i.e. `ember (new||init||addon) app-name --lang=langArg` Execution Context (usage, input, output, error handling, etc.): - called directly by `init` IFF `--lang` flag is used in (new||init||addon) - receives single input: the argument passed with `lang` (herein `langArg`) - processes `langArg`: lang code validation + error detection / handling - DOES emit Warning messages if necessary - DOES NOT halt execution process / throw errors / disrupt the build - returns single result as output (to `init`): - `langArg` (if it is a valid language code) - `undefined` (otherwise) - `init` assigns the value of `commandOptions.lang` to the returned result - downstream, the `lang` attribute is assigned via inline template control: - file: `blueprints/app/files/app/index.html` - logic: `<html<% if(lang) { %> lang="<%= lang %>"<% } %>> Internal Mechanics -- the utility processes `langArg` to determine: - the value to return to `init` (i.e. validated lang code or undefined) - a descriptive category for the usage: `correct`, `incorrect`, `edge`, etc. - what message text (if any: category-dependent) to emit before return Warning Messages (if necessary): - An internal instance of `console-ui` is used to emit messages - IFF there is a message, it will be emitted before returning the result - Components of all emitted messages -- [Name] (writeLevel): 'example': - [`HEAD`] (WARNING): 'A warning was generated while processing `--lang`:' - [`BODY`] (WARNING): 'Invalid language code, `en-UK`' - [`STATUS`] (WARNING): '`lang` will NOT be set to `en-UK` in `index.html`' - [`HELP`] (INFO): 'Correct usage of `--lang`: ... ' */ 'use strict'; const { isLangCode } = require('is-language-code'); // Primary language code validation function (boolean) function isValidLangCode(langArg) { return isLangCode(langArg).res; } // Generates the result to pass back to `init` function getResult(langArg) { return isValidLangCode(langArg) ? langArg : undefined; } /* Misuse case: attempt to set application programming language via `lang` AND Edge case: valid language code AND a common programming language abbreviation ------------------------------------------------------------------------------- It is possible that a user might mis-interpret the type of `language` that is specified by the `--lang` flag. One notable potential `misuse case` is one in which the user thinks `--lang` specifies the application's programming language. For example, the user might call `ember new my-app --lang=typescript` expecting to achieve an effect similar to the one provided by the `ember-cli-typescript` addon. This misuse case is handled by checking the input `langArg` against an Array containing notable programming language-related values: language names (e.g. `JavaScript`), abbreviations (e.g. `js`), file extensions (e.g. `.js`), or versions (e.g. `ES6`), etc. Specifically, if `langArg` is found within this reference list, a WARNING message that describes correct `--lang` usage will be emitted. The `lang` attribute will not be assigned in `index.html`, and the user will be notified with a corresponding STATUS message. There are several edge cases (marked) where `langArg` is both a commonly-used abbreviation for a programming language AND a valid language code. The behavior for these cases is to assume the user has used `--lang` correctly and set the `lang` attribute to the valid code in `index.html`. To cover for potential misuage, several helpful messages will also be emitted: - `ts` is a valid language code AND a common programming language abbreviation - the `lang` attribute will be set to `ts` in the application - if this is not correct, it can be changed in `app/index.html` directly - (general `help` information about correct `--lang` usage) */ const PROG_LANGS = [ 'javascript', '.js', 'js', 'emcascript2015', 'emcascript6', 'es6', 'emcascript2016', 'emcascript7', 'es7', 'emcascript2017', 'emcascript8', 'es8', 'emcascript2018', 'emcascript9', 'es9', 'emcascript2019', 'emcascript10', 'es10', 'typescript', '.ts', 'node.js', 'node', 'handlebars', '.hbs', 'hbs', 'glimmer', 'glimmer.js', 'glimmer-vm', 'markdown', 'markup', 'html5', 'html4', '.md', '.html', '.htm', '.xhtml', '.xml', '.xht', 'md', 'html', 'htm', 'xhtml', '.sass', '.scss', '.css', 'sass', 'scss', // Edge Cases 'ts', // Tsonga 'TS', // Tsonga (case insensitivity check) 'xml', // Malaysian Sign Language 'xht', // Hattic 'css', // Costanoan ]; function isProgLang(langArg) { return langArg && PROG_LANGS.includes(langArg.toLowerCase().trim()); } function isValidCodeAndProg(langArg) { return isValidLangCode(langArg) && isProgLang(langArg); } /* Misuse case: `--lang` called without `langArg` (NB: parser bug workaround) ------------------------------------------------------------------------------- This is a workaround for handling an existing bug in the ember-cli parser where the `--lang` option is specified in the command without a corresponding value for `langArg`. As examples, the parser behavior would likely affect the following usages: 1. `ember new app-name --lang --skip-npm 2. `ember new app-name --lang` In this context, the unintended parser behavior is that `langArg` will be assingned to the String that immediately follows `--lang` in the command. If `--lang` is the last explicitly defined part of the command (as in the second example above), the first of any any `hidden` options pushed onto the command after the initial parse (e.g. `--disable-analytics`, `--no-watcher`) will be used when assigning `langArg`. In the above examples, `langArg` would likely be assigned as follows: 1. `ember new app-name --lang --skip-npm => `langArg='--skip-npm'` 2. `ember new app-name --lang` => `langArg='--disable-analytics'` The workaround impelemented herein is to check whether or not the value of `langArg` starts with a hyphen. The rationale for this approach is based on the following underlying assumptions: - ALL CLI options start with (at least one) hyphen - NO valid language codes start with a hyphen If the leading hyphen is detected, the current behavior is to assume `--lang` was declared without a corresponding specification. A WARNING message that describes correct `--lang` usage will be emitted. The `lang` attribute will not be assigned in `index.html`, and the user will be notified with a corresponding STATUS message. Execution will not be halted. Other complications related to this parser behavior are considered out-of-scope and not handled here. In the first example above, this workaround would ensure that `lang` is not assigned to `--skip-npm`, but it would not guarantee that `--skip-npm` is correctly processed as a command option. That is, `npm` may or may not get skipped during execution. */ function startsWithHyphen(langArg) { return langArg && langArg[0] === '-'; } // MESSAGE GENERATION: // 1. `HEAD` Message: template for all `--lang`-related warnings emitted const MSG_HEAD = `An issue with the \`--lang\` flag returned the following message:`; // 2. `BODY` Messages: category-dependent context information // Message context from language code validation (valid: null, invalid: reason) function getLangCodeMsg(langArg) { return isLangCode(langArg).message; } // Edge case: valid language code AND a common programming language abbreviation function getValidAndProgMsg(langArg) { return `The \`--lang\` flag has been used with argument \`${langArg}\`, which is BOTH a valid language code AND an abbreviation for a programming language. ${getProgLangMsg(langArg)}`; } // Misuse case: attempt to set application programming language via `lang` function getProgLangMsg(langArg) { return `Trying to set the app programming language to \`${langArg}\`? This is not the intended usage of the \`--lang\` flag.`; } // Misuse case: `--lang` called without `langArg` (NB: parser bug workaround) function getCliMsg() { return `Detected a \`--lang\` specification starting with command flag \`-\`. This issue is likely caused by using the \`--lang\` flag without a specification.`; } // 3. `STATUS` message: report if `lang` will be set in `index.html` function getStatusMsg(langArg, willSet) { return `The human language of the application will ${willSet ? `be set to ${langArg}` : `NOT be set`} in the \`<html>\` element's \`lang\` attribute in \`index.html\`.`; } // 4. `HELP` message: template for all `--lang`-related warnings emitted const MSG_HELP = `If this was not your intention, you may edit the \`<html>\` element's \`lang\` attribute in \`index.html\` manually after the process is complete. Information about using the \`--lang\` flag: The \`--lang\` flag sets the base human language of an app or test app: - \`app/index.html\` (app) - \`tests/dummy/app/index.html\` (addon test app) If used, the lang option must specfify a valid language code. For default behavior, remove the flag. See \`ember <command> help\` for more information.`; function getBodyMsg(langArg) { return isValidCodeAndProg(langArg) ? getValidAndProgMsg(langArg) : isProgLang(langArg) ? getProgLangMsg(langArg) : startsWithHyphen(langArg) ? getCliMsg(langArg) : getLangCodeMsg(langArg); } function getFullMsg(langArg) { return { head: MSG_HEAD, body: getBodyMsg(langArg), status: getStatusMsg(langArg, isValidCodeAndProg(langArg)), help: MSG_HELP, }; } function writeFullMsg(fullMsg, ui) { ui.setWriteLevel('WARNING'); ui.writeWarnLine(`${fullMsg.head}\n ${fullMsg.body}\``); ui.writeWarnLine(fullMsg.status); ui.setWriteLevel('INFO'); ui.writeInfoLine(fullMsg.help); } module.exports = function getLangArg(langArg, ui) { let fullMsg = getFullMsg(langArg); if (fullMsg.body) { writeFullMsg(fullMsg, ui); } return getResult(langArg); };
ember-cli/ember-cli
lib/utilities/get-lang-arg.js
JavaScript
mit
10,052
(function(b){var a=b.cultures,d=a.en,e=d.calendars.standard,c=a.no=b.extend(true,{},d,{name:"no",englishName:"Norwegian",nativeName:"norsk",language:"no",numberFormat:{",":" ",".":",",percent:{",":" ",".":","},currency:{pattern:["$ -n","$ n"],",":" ",".":",",symbol:"kr"}},calendars:{standard:b.extend(true,{},e,{"/":".",firstDay:1,days:{names:["søndag","mandag","tirsdag","onsdag","torsdag","fredag","lørdag"],namesAbbr:["sø","ma","ti","on","to","fr","lø"],namesShort:["sø","ma","ti","on","to","fr","lø"]},months:{names:["januar","februar","mars","april","mai","juni","juli","august","september","oktober","november","desember",""],namesAbbr:["jan","feb","mar","apr","mai","jun","jul","aug","sep","okt","nov","des",""]},AM:null,PM:null,patterns:{d:"dd.MM.yyyy",D:"d. MMMM yyyy",t:"HH:mm",T:"HH:mm:ss",f:"d. MMMM yyyy HH:mm",F:"d. MMMM yyyy HH:mm:ss",M:"d. MMMM",Y:"MMMM yyyy"}})}},a.no);c.calendar=c.calendars.standard})(jQuery)
Leandro-b-03/SmartBracelet
public/library/javascripts/jquery.GlobalMoneyInput/globinfo/jQuery.glob.no.min.js
JavaScript
mit
938
var EPOCH = 1900; var PATTERN = /(\d+)[^\/|-]/g; function iskabisat(year) { if(year % 4 === 0){ if(year % 100 === 0 && year % 400 !== 0) return false; else return true; } return false; } /* * kabisats: * Calculating how many kabisats' years in time span between * given year and primordial year, Y0 */ function kabisats(year) { var kabcount = 0; for(var i=1900; i<year; i++) { if(iskabisat(i)) kabcount++; } return kabcount; } function calcdays(date) { function months(mth) { var days = 0; for(var i=1; i<mth; i++) { if(extraday.indexOf(i) !== -1) days += 31; else if (i == 2) days += 28; else days += 30; } return days+1; } var extraday = [1, 3, 5, 7, 8, 10, 12]; var dayarr = date.match(PATTERN); var day = parseInt(dayarr[2]); var month = parseInt(dayarr[1]); var year = parseInt(dayarr[0]); var days = day + months(month) + (year - EPOCH) * 365 + kabisats(year); return days; } function triwara(day) { return ['Pasah', 'Beteng', 'Kajeng'][(day-1) % 3]; } function pancawara(day) { var pancalist = ["Umanis", "Paing", "Pon", "Wage", "Kliwon"]; return pancalist[(day-1) % 5]; } function saptawara(day) { return ["Redite", "Coma", "Anggara","Buda", "Wrespati", "Sukra", "Saniscara"][(day-1) % 7]; } function wuku(day) { var wukulist = [ "Sinta", "Landep", "Ukir", "Kulantir", "Tolu", "Gumbreg", "Wariga", "Warigadean", "Julungwangi", "Sungsang", "Dungulan", "Kuningan", "Langkir", "Medangsya", "Pujut", "Pahang", "Krulut", "Merakih", "Tambir", "Medangkungan", "Matal", "Uye", "Menail", "Prangbakat", "Bala", "Ugu", "Wayang", "Kelawu", "Dukut", "Watugunung" ]; idx = (Math.floor((day-1) / 7) + 12) % 30; return wukulist[idx]; } function bali_calendar(date) { var day = calcdays(date); return { Triwara: triwara(day), Pancawara: pancawara(day), Saptawara: saptawara(day), Wuku: wuku(day) }; } module.exports.bali_calendar = bali_calendar;
kadekParwanta/BaleKulkul_Server
server/models/Calendar.js
JavaScript
mit
2,055
var _elm_lang$window$Native_Window = function() { var size = _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) { callback(_elm_lang$core$Native_Scheduler.succeed({ width: window.innerWidth, height: window.innerHeight })); }); return { size: size }; }();
futoke/ar-project
web/client/elm-stuff/packages/elm-lang/window/1.0.1/src/Native/Window.js
JavaScript
mit
278
/* ShipManager.js KC3改 Ship Manager Managesship roster and does indexing for data access. Saves and loads list to and from localStorage */ (function(){ "use strict"; window.KC3ShipManager = { list: {}, max: 100, pendingShipNum: 0, // Get a specific ship by ID get :function( rosterId ){ // console.log("getting ship", rosterId, this.list["x"+rosterId]); return this.list["x"+rosterId] || (new KC3Ship()); }, // Count number of ships count :function(){ return Object.size(this.list) + this.pendingShipNum; }, // Add or replace a ship on the list add :function(data){ var didFlee = false; if(typeof data.api_id != "undefined"){ if (typeof this.list["x"+data.api_id] !== "undefined") { didFlee = this.list["x"+data.api_id].didFlee; } this.list["x"+data.api_id] = new KC3Ship(data); this.list["x"+data.api_id].didFlee = didFlee; }else if(typeof data.rosterId != "undefined"){ if (typeof this.list["x"+data.rosterId] !== "undefined") { didFlee = this.list["x"+data.rosterId].didFlee; } this.list["x"+data.rosterId] = new KC3Ship(data); this.list["x"+data.rosterId].didFlee = didFlee; } }, // Mass set multiple ships set :function(data){ var ctr; for(ctr in data){ if(!!data[ctr]){ this.add(data[ctr]); } } this.save(); }, // Remove ship from the list, scrapped, mod-fodded, or sunk remove :function( rosterId ){ console.log("removing ship", rosterId); var thisShip = this.list["x"+rosterId]; if(thisShip != "undefined"){ // initializing for fleet sanitizing of zombie ships var flatShips = PlayerManager.fleets .map(function(x){ return x.ships; }) .reduce(function(x,y){ return x.concat(y); }), shipTargetOnFleet = flatShips.indexOf(Number(rosterId)), // check from which fleet shipTargetFleetID = Math.floor(shipTargetOnFleet/6); // check whether the designated ship is on fleet or not if(shipTargetOnFleet >= 0){ PlayerManager.fleets[shipTargetFleetID].discard(rosterId); } // remove any equipments from her for(var gctr in thisShip.items){ if(thisShip.items[gctr] > -1){ KC3GearManager.remove( thisShip.items[gctr] ); } } delete this.list["x"+rosterId]; this.save(); KC3GearManager.save(); } }, // Show JSON string of the list for debugging purposes json: function(){ console.log(JSON.stringify(this.list)); }, // Save ship list onto local storage clear: function(){ this.list = {}; }, // Save ship list onto local storage save: function(){ localStorage.ships = JSON.stringify(this.list); }, // Load from storage and add each one to manager list load: function(){ if(typeof localStorage.ships != "undefined"){ this.clear(); var ShipList = JSON.parse(localStorage.ships); for(var ctr in ShipList){ this.add( ShipList[ctr] ); } return true; } return false; } }; })();
ethrundr/KC3Kai
src/library/managers/ShipManager.js
JavaScript
mit
3,115
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Create recovery plan input class. * */ class CreateRecoveryPlanInput { /** * Create a CreateRecoveryPlanInput. * @member {object} properties Recovery plan creation properties. * @member {string} [properties.primaryFabricId] The primary fabric Id. * @member {string} [properties.recoveryFabricId] The recovery fabric Id. * @member {string} [properties.failoverDeploymentModel] The failover * deployment model. Possible values include: 'NotApplicable', 'Classic', * 'ResourceManager' * @member {array} [properties.groups] The recovery plan groups. */ constructor() { } /** * Defines the metadata of CreateRecoveryPlanInput * * @returns {object} metadata of CreateRecoveryPlanInput * */ mapper() { return { required: false, serializedName: 'CreateRecoveryPlanInput', type: { name: 'Composite', className: 'CreateRecoveryPlanInput', modelProperties: { properties: { required: true, serializedName: 'properties', type: { name: 'Composite', className: 'CreateRecoveryPlanInputProperties' } } } } }; } } module.exports = CreateRecoveryPlanInput;
lmazuel/azure-sdk-for-node
lib/services/recoveryServicesSiteRecoveryManagement/lib/models/createRecoveryPlanInput.js
JavaScript
mit
1,634
describe("About Expects", function() { // We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(true).toBeTruthy(); //This should be true }); // To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = 2; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); // Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = 2; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); // Sometimes you need to be really exact about what you "type." it("should assert equality with ===", function () { var expectedValue = 2; var actualValue = (1 + 1); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); // Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(2); }); });
mchaperc/5.2-javascript-koans
koans/AboutExpects.js
JavaScript
mit
1,162
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the ComputeNodeListNextOptions class. * @constructor * Additional parameters for the listNext operation. * * @member {string} [clientRequestId] The caller-generated request identity, * in the form of a GUID with no decoration such as curly braces, e.g. * 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. * * @member {boolean} [returnClientRequestId] Whether the server should return * the client-request-id identifier in the response. * * @member {date} [ocpDate] The time the request was issued. If not specified, * this header will be automatically populated with the current system clock * time. * */ function ComputeNodeListNextOptions() { } /** * Defines the metadata of ComputeNodeListNextOptions * * @returns {object} metadata of ComputeNodeListNextOptions * */ ComputeNodeListNextOptions.prototype.mapper = function () { return { required: false, type: { name: 'Composite', className: 'ComputeNodeListNextOptions', modelProperties: { clientRequestId: { required: false, type: { name: 'String' } }, returnClientRequestId: { required: false, type: { name: 'Boolean' } }, ocpDate: { required: false, type: { name: 'DateTimeRfc1123' } } } } }; }; module.exports = ComputeNodeListNextOptions;
smithab/azure-sdk-for-node
lib/services/batch/lib/models/computeNodeListNextOptions.js
JavaScript
mit
1,806
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mustCall(onread)); function onread() { const as = hooks.activitiesOfTypes('FSREQWRAP'); let lastParent = 1; for (let i = 0; i < as.length; i++) { const a = as[i]; assert.strictEqual(a.type, 'FSREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; } checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[0]: while in onread callback'); checkInvocations(as[1], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[1]: while in onread callback'); checkInvocations(as[2], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[2]: while in onread callback'); // this callback is called from within the last fs req callback therefore // the last req is still going and after/destroy haven't been called yet checkInvocations(as[3], { init: 1, before: 1 }, 'reqwrap[3]: while in onread callback'); tick(2); } process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('FSREQWRAP'); const as = hooks.activitiesOfTypes('FSREQWRAP'); const a = as.pop(); checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, 'when process exits'); }
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/async-hooks/test-fsreqwrap-readFile.js
JavaScript
mit
1,626
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Stream = require('stream').Stream; (function testErrorListenerCatches() { var source = new Stream(); var dest = new Stream(); source.pipe(dest); var gotErr = null; source.on('error', function(err) { gotErr = err; }); var err = new Error('This stream turned into bacon.'); source.emit('error', err); assert.strictEqual(gotErr, err); })(); (function testErrorWithoutListenerThrows() { var source = new Stream(); var dest = new Stream(); source.pipe(dest); var err = new Error('This stream turned into bacon.'); var gotErr = null; try { source.emit('error', err); } catch (e) { gotErr = e; } assert.strictEqual(gotErr, err); })();
csr1010/xmmagik
test/simple/test-stream-pipe-error-handling.js
JavaScript
mit
1,890
import React from 'react'; import test from 'ava'; import { shallow } from 'enzyme'; import SettingsWrapper from '../SettingsWrapper'; test('renders if isEnabled', (t) => { const wrapper = shallow(<SettingsWrapper isEnabled />); t.true(wrapper.matchesElement(<div />)); }); test('renders with settings toggle when provided', (t) => { const settingsToggle = () => <div>Toggle</div>; const wrapper = shallow(<SettingsWrapper isEnabled SettingsToggle={settingsToggle} />); t.is(wrapper.html(), '<div><div>Toggle</div></div>'); }); test('renders with style', (t) => { const style = { backgroundColor: '#EDEDED' }; const wrapper = shallow(<SettingsWrapper isEnabled style={style} />); t.true(wrapper.matchesElement(<div style={{ backgroundColor: '#EDEDED' }} />)); }); test('renders with className', (t) => { const wrapper = shallow(<SettingsWrapper isEnabled className="className" />); t.true(wrapper.matchesElement(<div className="className" />)); }); test('renders with settings if visible and settings component is provided', (t) => { const settings = () => <div>Settings</div>; const wrapper = shallow(<SettingsWrapper isEnabled isVisible Settings={settings} />); t.is(wrapper.html(), '<div><div>Settings</div></div>'); }); test('renders without settings if isVisible is false and settings component is provided', (t) => { const settings = () => <div>Settings</div>; const wrapper = shallow(<SettingsWrapper isEnabled isVisible={false} Settings={settings} />); t.is(wrapper.html(), '<div></div>'); });
ttrentham/Griddle
src/components/__tests__/SettingsWrapperTest.js
JavaScript
mit
1,547
module.exports={A:{A:{"2":"J C G E B A TB"},B:{"2":"D X g H L"},C:{"2":"0 2 3 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p q v w x y z s r PB OB"},D:{"1":"0 2 4 8 m n o p q v w x y z s r DB AB SB BB","2":"F I J C G E B A D X g H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l"},E:{"2":"7 F I J C G E B A CB EB FB GB HB IB JB"},F:{"1":"Z a b c d e f K h i j k l m n o p q","2":"1 5 6 E A D H L M N O P Q R S T U V W t Y KB LB MB NB QB"},G:{"2":"7 9 G A u UB VB WB XB YB ZB aB bB"},H:{"2":"cB"},I:{"1":"r","2":"3 F dB eB fB gB u hB iB"},J:{"2":"C B"},K:{"1":"K","2":"1 5 6 B A D"},L:{"1":"8"},M:{"2":"s"},N:{"2":"B A"},O:{"2":"jB"},P:{"1":"F I"},Q:{"2":"kB"},R:{"1":"lB"}},B:5,C:"Web MIDI API"};
UrbanRiskSlumRedevelopment/Maya
node_modules/caniuse-lite/data/features/midi.js
JavaScript
mit
747