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
'use strict'; angular .module('ewbApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute', 'btford.socket-io' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .otherwise({ redirectTo: '/' }); });
vbud/ewb-client_OLD
app/scripts/app.js
JavaScript
apache-2.0
356
/** * This script is a demonstration of how you can create a TileMap and its layers programmatically (through the code) without having a JSON file define it for you. * **/ var IsometricTileMaps = new Kiwi.State('IsometricTileMaps'); IsometricTileMaps.preload = function () { //Load in the TileMap this.addJSON('mapjson', 'assets/isometric/isometric-tilemap.json'); //Load in our Tilemap Spritesheet. We will be using this for our tile assets. this.addSpriteSheet('blocks', 'assets/isometric/blocks.png', 64, 64); } IsometricTileMaps.create = function () { //Create the Tilemap. this.tilemap = new Kiwi.GameObjects.Tilemap.TileMap(this, 'mapjson', this.textures.blocks); for(var i = 0; i < this.tilemap.layers.length; i++) { this.addChild(this.tilemap.layers[i]); } } //Create's a new Kiwi.Game. /* * Param One - DOMID - String - ID of a DOMElement that the game will reside in. * Param Two - GameName - String - Name that the game will be given. * Param Three - State - Object - The state that is to be loaded by default. * Param Four - Options - Object - Optional options that the game will use whilst playing. Currently this is used to to choose the renderer/debugmode/device to target */ if(typeof gameOptions == "undefined") gameOptions = {}; var game = new Kiwi.Game('game', 'KiwiExample', IsometricTileMaps, gameOptions);
dfu23/swim-meet
lib/kiwi.js/examples/Tilemaps/IsometricTileMaps.js
JavaScript
apache-2.0
1,385
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/base/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var pow = require( '@stdlib/math/base/special/pow' ); var Float64Array = require( '@stdlib/array/float64' ); var pkg = require( './../package.json' ).name; var dmeanors = require( './../lib/dmeanors.js' ); // FUNCTIONS // /** * Creates a benchmark function. * * @private * @param {PositiveInteger} len - array length * @returns {Function} benchmark function */ function createBenchmark( len ) { var x; var i; x = new Float64Array( len ); for ( i = 0; i < x.length; i++ ) { x[ i ] = ( randu()*20.0 ) - 10.0; } return benchmark; function benchmark( b ) { var v; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { v = dmeanors( x.length, x, 1 ); if ( isnan( v ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( v ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); } } // MAIN // /** * Main execution sequence. * * @private */ function main() { var len; var min; var max; var f; var i; min = 1; // 10^min max = 6; // 10^max for ( i = min; i <= max; i++ ) { len = pow( 10, i ); f = createBenchmark( len ); bench( pkg+':len='+len, f ); } } main();
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dmeanors/benchmark/benchmark.js
JavaScript
apache-2.0
1,965
// @ts-nocheck 'use strict'; const _ = require('lodash'); const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule'); const report = require('../../utils/report'); const ruleMessages = require('../../utils/ruleMessages'); const validateOptions = require('../../utils/validateOptions'); const ruleName = 'at-rule-property-required-list'; const messages = ruleMessages(ruleName, { expected: (property, atRule) => `Expected property "${property}" for at-rule "${atRule}"`, }); function rule(list) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: list, possible: [_.isObject], }); if (!validOptions) { return; } root.walkAtRules((atRule) => { if (!isStandardSyntaxAtRule(atRule)) { return; } const { name, nodes } = atRule; const atRuleName = name.toLowerCase(); if (!list[atRuleName]) { return; } list[atRuleName].forEach((property) => { const propertyName = property.toLowerCase(); const hasProperty = nodes.find( ({ type, prop }) => type === 'decl' && prop.toLowerCase() === propertyName, ); if (hasProperty) { return; } return report({ message: messages.expected(propertyName, atRuleName), node: atRule, result, ruleName, }); }); }); }; } rule.ruleName = ruleName; rule.messages = messages; module.exports = rule;
kyleterry/sufr
pkg/ui/node_modules/stylelint/lib/rules/at-rule-property-required-list/index.js
JavaScript
apache-2.0
1,406
import { LightningElement, api } from 'lwc'; import { ComponentNonLockerizedMixin } from 'securemoduletest/componentNonLockerizedMixin'; import * as testUtil from 'securemoduletest/testUtil'; export default class ComponentLockerizedInSameNamespaceMixinNonLockerized extends ComponentNonLockerizedMixin(LightningElement) { @api COMPONENT = 'ComponentLockerizedInSameNamespaceMixinNonLockerized { NS: "securemoduletest" }'; @api NAME = 'Lockerized! [ChildClass]'; @api BOOLEAN_OVERRIDE = false; @api NULL_OVERRIDE = null; @api UNDEFINED_OVERRIDE = undefined; @api NUMBER_OVERRIDE = 999; @api STRING_OVERRIDE = 'Override!'; @api SYMBOL_OVERRIDE = Symbol('XYZ'); getWindowOverride() { return window; } getDocumentOverride() { return document; } getElementOverride() { return document.createElement('DIV'); } @api testPrimitives() { testUtil.assertEquals(false, this.BOOLEAN); testUtil.assertEquals(null, this.NULL); testUtil.assertEquals(undefined, this.UNDEFINED); testUtil.assertEquals(100, this.NUMBER); testUtil.assertEquals('Hello!', this.STRING); testUtil.assertEquals('Symbol(ABC)', this.SYMBOL.toString()); testUtil.assertEquals(false, this.BOOLEAN_OVERRIDE); testUtil.assertEquals(null, this.NULL_OVERRIDE); testUtil.assertEquals(undefined, this.UNDEFINED_OVERRIDE); testUtil.assertEquals(999, this.NUMBER_OVERRIDE); testUtil.assertEquals('Override!', this.STRING_OVERRIDE); testUtil.assertEquals('Symbol(XYZ)', this.SYMBOL_OVERRIDE.toString()); this.testBaseComponentPrimitives(); } @api testObjects() { testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.WINDOW.toString(), 'Property "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.DOCUMENT.toString(), 'Property "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.ELEMENT.toString(), 'Property "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.win.toString(), 'Object "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.doc.toString(), 'Object "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.el.toString(), 'Object "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.winFunction().toString(), 'Object function "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.docFunction().toString(), 'Object function "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.elFunction().toString(), 'Object function "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.winThisContextFunction().toString(), 'Object this context "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.docThisContextFunction().toString(), 'Object this context "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.OBJECT.elThisContextFunction().toString(), 'Object this context "element" not lockerized! [ChildClass]'); this.testBaseComponentObjects(); } @api testFunctions() { testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWindow().toString(), 'Function "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocument().toString(), 'Function "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.getElement().toString(), 'Function "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWindowOverride().toString(), 'Function override "window" not lockerized!'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocumentOverride().toString(), 'Function override "document" not lockerized!'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }',this.getElementOverride().toString(), 'Function override "element" not lockerized!'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWindowThisContext().toString(), 'Function this context "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocumentThisContext().toString(), 'Function this context "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }',this.getElementThisContext().toString(), 'Function this context "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWindowReturn(window).toString(), 'Function return "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocumentReturn(document).toString(), 'Function return "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.getElementReturn(document.createElement('DIV')).toString(), 'Function return "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWindowReturnFunction(function() { return window; }).toString(), 'Function return function "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocumentReturnFunction(function() { return document; }).toString(), 'Function return function "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.getElementReturnFunction(function() { return document.createElement('DIV'); }).toString(), 'Function return function "element" not lockerized! [ChildClass]'); this.testBaseComponentFunctions(); } @api testCreatedPrimitives() { super.BOOLEAN_SUPER = false; super.NULL_SUPER = null; super.UNDEFINED_SUPER = undefined; super.NUMBER_SUPER = 200; super.STRING_SUPER = "Super!"; super.SYMBOL_SUPER = Symbol('QWERTY'); testUtil.assertEquals(false, this.BOOLEAN_SUPER); testUtil.assertEquals(null, this.NULL_SUPER); testUtil.assertEquals(undefined, this.UNDEFINED_SUPER); testUtil.assertEquals(200, this.NUMBER_SUPER); testUtil.assertEquals('Super!', this.STRING_SUPER); testUtil.assertEquals('Symbol(QWERTY)', this.SYMBOL_SUPER.toString()); this.testBaseComponentCreatedPrimitives(); } @api testCreatedObjects() { super.winSuper = window; super.docSuper = document; super.elSuper = document.createElement('DIV'); super.objSuper = { 'win': window, 'doc': document, 'el': document.createElement('DIV'), 'winFunction': function() { return window; }, 'docFunction': function() { return document; }, 'elFunction': function() { return document.createElement('DIV'); }, 'winThisContextFunction': function() { return this.win; }, 'docThisContextFunction': function() { return this.doc; }, 'elThisContextFunction': function() { return this.el; } }; testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.winSuper.toString(), '[Super] Property "window" not lockerized!'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.docSuper.toString(), '[Super] Property "document" not lockerized!'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.elSuper.toString(), '[Super] Property "element" not lockerized!'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.win.toString(), '[Super] Object "window" not lockerized!'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.doc.toString(), '[Super] Object "document" not lockerized!'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.el.toString(), '[Super] Object "element" not lockerized!'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.winFunction().toString(), '[Super] Object function "window" not lockerized!'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.docFunction().toString(), '[Super] Object function "document" not lockerized!'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.elFunction().toString(), '[Super] Object function "element" not lockerized!'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.winThisContextFunction().toString(), '[Super] Object this context "window" not lockerized!'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.docThisContextFunction().toString(), '[Super] Object this context "document" not lockerized!'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.objSuper.elThisContextFunction().toString(), '[Super] Object this context "element" not lockerized!'); this.testBaseComponentCreatedObjects(); } @api testCreatedFunctions() { super.getWinSuper = function() { return window; }; super.getDocSuper = function() { return document; }; super.getElSuper = function() { return document.createElement('DIV'); }; super.getWinThisContextSuper = function() { return this.WINDOW; }; super.getDocThisContextSuper = function() { return this.DOCUMENT; }; super.getElThisContextSuper = function() { return this.ELEMENT; }; super.getWinReturnSuper = function(win) { return win; }; super.getDocReturnSuper = function(doc) { return doc; }; super.getElReturnSuper = function(el) { return el; }; super.getWinReturnFuncSuper = function(win) { return win(); }; super.getDocReturnFuncSuper = function(doc) { return doc(); }; super.getElReturnFuncSuper = function(el) { return el(); }; testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWinSuper().toString(), '[Super] Function "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocSuper().toString(), '[Super] Function "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.getElSuper().toString(), '[Super] Function "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWinThisContextSuper().toString(), '[Super] Function this context "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocThisContextSuper().toString(), '[Super] Function this context "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }',this.getElThisContextSuper().toString(), '[Super] Function this context "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWinReturnSuper(window).toString(), '[Super] Function return "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocReturnSuper(document).toString(), '[Super] Function return "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.getElReturnSuper(document.createElement('DIV')).toString(), '[Super] Function return "element" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureWindow: [object Window]{ key: {"namespace":"secureModuleTest"} }', this.getWinReturnFuncSuper(function() { return window; }).toString(), '[Super] Function return function "window" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureDocument: [object HTMLDocument]{ key: {"namespace":"secureModuleTest"} }', this.getDocReturnFuncSuper(function() { return document; }).toString(), '[Super] Function return function "document" not lockerized! [ChildClass]'); testUtil.assertEquals('SecureElement: [object HTMLDivElement]{ key: {"namespace":"secureModuleTest"} }', this.getElReturnFuncSuper(function() { return document.createElement('DIV'); }).toString(), '[Super] Function return function "element" not lockerized! [ChildClass]'); this.testBaseComponentCreatedFunctions(); } }
forcedotcom/aura
aura-modules/src/test/modules/securemoduletest/componentLockerizedInSameNamespaceMixinNonLockerized/componentLockerizedInSameNamespaceMixinNonLockerized.js
JavaScript
apache-2.0
15,023
/** * Include services used for the application */ const debug = require('debug')('badger'); const request = require('request'); const fs = require ('fs'); const path = require('path'); const config = require('../../config/config'); const base = require('../base/base'); const steps = require('../base/commonSteps'); let badgeNASmall = config.spatial.badgeNASmall; let badgeNABig = config.spatial.badgeNABig; exports.getBadgeFromData = (req, res) => { let passon = { body: req.body, extended: req.params.extended, req: req, res: res }; // save tracking info passon.res.tracking = { type: req.params.type, doi: passon.id, extended: (passon.extended === 'extended'), size: req.query.width, format: (req.query.format === undefined) ? 'svg' : req.query.format }; // check if there is a service for "spatial" badges if (base.hasSupportedService(config.spatial) === false) { debug('No service for badge %s found', passon.id); res.status(404).send('{"error":"no service for this type found"}'); return; } let getBadge; if (passon.extended === 'extended') { getBadge = sendBigBadge(passon) } else { getBadge = getCenterFromData(passon) .then(getGeoName) .then(sendSmallBadge) } return getBadge .then((passon) => { debug('Completed generating badge'); }) .catch(err => { if (err.badgeNA === true) { // Send 'N/A' badge debug("No badge information found: %s", err.msg); if (passon.extended === 'extended') { passon.res.na = true; passon.res.service = passon.service; passon.req.filePath = path.join(__dirname, badgeNABig); base.resizeAndSend(passon.req, passon.res); } else if (passon.extended === undefined) { res.na = true; res.tracking.service = passon.service; res.redirect(badgeNASmall); } else { res.status(404).send('not allowed'); } } else { // Send error response debug('Error generating badge: "%s" Original request: "%s"', err, passon.req.url); let status = 500; if (err.status) { status = err.status; } let msg = 'Internal error'; if (err.msg) { msg = err.msg; } res.status(status).send(JSON.stringify({ error: msg })); } }); }; exports.getBadgeFromReference = (req, res) => { let id = req.params.id; let extended; debug('Handling spatial badge generation for id %s', req.params.id); if (typeof req.params.extended !== 'undefined') { extended = req.params.extended; } let passon = { id: id, extended: extended, req: req, res: res }; // save tracking info passon.res.tracking = { type: req.params.type, doi: passon.id, extended: (passon.extended === 'extended'), size: req.query.width, format: (req.query.format === undefined) ? 'svg' : req.query.format }; // check if there is a service for "spatial" badges if (base.hasSupportedService(config.spatial) === false) { debug('No service for badge %s found', passon.id); res.status(404).send('{"error":"no service for this type found"}'); return; } let getBadge; if (passon.extended === 'extended') { getBadge = steps.getCompendiumID(passon) .then(steps.getCompendium) .then(sendBigBadge) } else { getBadge = steps.getCompendiumID(passon) .then(steps.getCompendium) .then(getCenterFromData) .then(getGeoName) .then(sendSmallBadge) } return getBadge .then((passon) => { debug('Completed generating badge'); }) .catch(err => { if (err.badgeNA === true) { // Send 'N/A' badge debug("No badge information found: %s", err.msg); if (passon.extended === 'extended') { passon.res.na = true; passon.res.service = passon.service; passon.req.filePath = path.join(__dirname, badgeNABig); base.resizeAndSend(passon.req, passon.res); } else if (passon.extended === undefined) { res.na = true; res.tracking.service = passon.service; res.redirect(badgeNASmall); } else { res.status(404).send('not allowed'); } } else { // Send error response debug('Error generating badge: "%s" Original request: "%s"', err, passon.req.url); let status = 500; if (err.status) { status = err.status; } let msg = 'Internal error'; if (err.msg) { msg = err.msg; } res.status(status).send(JSON.stringify({ error: msg })); } }); }; function getCenterFromData(passon) { return new Promise((fulfill, reject) => { // from o2r json to bbox debug('Reading spatial information from o2r data'); if (typeof passon.body === 'undefined') { let error = new Error(); error.msg = 'no geo name provided'; error.status = 404; error.badgeNA = true; reject(error); return; } let bbox; try { bbox = passon.body.metadata.o2r.spatial.union.geojson.bbox; debug('Bounding box is %s, %s, %s, %s', bbox[0], bbox[1], bbox[2], bbox[3]); } catch (err) { debug('Metadata: %O:', passon.body); err.badgeNA = true; err.msg = 'o2r compendium does not contain spatial information (bbox)'; reject(err); return; } //calculate the center of the polygon let result = calculateMeanCenter(bbox); passon.latitude = result[0]; passon.longitude = result[1]; fulfill(passon) }); } function getGeoName(passon) { return new Promise((fulfill, reject) => { let requestURL = config.ext.geonames + '?lat=' + passon.latitude + '&lng=' + passon.longitude +'&username=badges'; debug('Fetching geoname for compendium %s from %s', passon.compendiumID, requestURL); //and get the reversed geocoding for it request({ url: requestURL, timeout: config.timeout.geonames, proxy: config.net.proxy}, function (error,response,body){ if (error) { error.msg = 'Could not access geonames.org'; reject(error); return; } if(response.statusCode === 200) { let geoname = JSON.parse(body); let geoname_ocean; // send the badge with the geocoded information to client if (geoname.status) { request({url: 'http://api.geonames.org/oceanJSON?lat=' + passon.latitude + '&lng=' + passon.longitude + '&username=badges&username=badges', proxy: config.net.proxy}, function (error,response,body){ if(response.statusCode === 200) { geoname_ocean = JSON.parse(body); try { passon.geoName = geoname_ocean.ocean.name; } catch (err) { err.badgeNA = true; err.msg = 'no ocean name found'; reject(err); return; } fulfill(passon); } else { let error = new Error(); error.msg = 'could not get geoname ocean'; error.status = 404; error.badgeNA = true; reject(error); return; } }); } else if(geoname.codes) { if (geoname.adminName1) { passon.geoName = geoname.adminName1+"%2C%20"+geoname.countryName; fulfill(passon); } else { passon.geoName = geoname.countryName; fulfill(passon); } } } else { let error = new Error(); error.msg = 'could not get geoname'; error.status = 404; error.badgeNA = true; reject(error); return; } }); }); } function sendSmallBadge(passon) { return new Promise((fulfill, reject) => { debug('Sending badge for geo name %s', passon.geoName); if (typeof passon.geoName === 'undefined') { let error = new Error(); error.msg = 'no geo name provided'; error.status = 404; error.badgeNA = true; reject(error); return; } if (passon.service === undefined) { passon.service = 'unknown'; } let badgeString; // Encode badge string let locationString = passon.geoName.replace('-', '%20'); badgeString = 'location-' + locationString + '-blue.svg'; passon.res.tracking.service = passon.service; let redirectURL = config.badge.baseURL + badgeString + config.badge.options; passon.res.redirect(redirectURL); fulfill(passon); }); } function sendBigBadge(passon) { return new Promise((fulfill, reject) => { debug('Sending map'); let options = { dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true, } }; passon.res.tracking.service = passon.service; function sendNA(text) { passon.req.type = 'location'; let error = new Error(); error.msg = text; error.status = 404; error.badgeNA = true; reject(error); } let bbox; try { bbox = passon.body.metadata.o2r.spatial.spatial.union.geojson.bbox; } catch (err) { sendNA('could not read bbox of compendium'); return; } //Generate map let html = fs.readFileSync('./controllers/location/index_template.html', 'utf-8'); html.replace('bbox', "Hello"); //insert the locations into the html file / leaflet let file = html.replace('var bbox;', 'var bbox = ' + JSON.stringify(bbox) + ';'); let indexHTMLPath = './controllers/location/index.html'; fs.writeFile(indexHTMLPath, file, (err) => { if (err) { debug('Error writing index.html file to %s', indexHTMLPath); reject(err); return; } else { passon.req.filePath = path.join(__dirname, 'index.html'); passon.req.type = 'location'; passon.req.options = options; debug('Sending map %s', passon.req.filePath); base.resizeAndSend(passon.req, passon.res); fulfill(passon); } }); }); } /** * @desc calculate the mean center of a polygon * @param json geojson file containing the bbox of an area */ function calculateMeanCenter(bbox) { let x1 = parseFloat(bbox[1]); let y1 = parseFloat(bbox[0]); let x2 = parseFloat(bbox[3]); let y2 = parseFloat(bbox[2]); let centerX= x1 + ((x2 - x1) / 2); let centerY= y1 + ((y2 - y1) / 2); return [centerX,centerY]; }
LukasLohoff/o2r-badger
controllers/location/location.js
JavaScript
apache-2.0
12,283
/* * Copyright 2015 Concept * * 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. */ App = {};
bompi88/concept
both/app.js
JavaScript
apache-2.0
596
'use strict'; var $ = require('jquery'); var ko = require('knockout'); var Raven = require('raven-js'); require('jquery-ui'); require('knockout-sortable'); var lodashGet = require('lodash.get'); var osfLanguage = require('js/osfLanguage'); var rt = require('js/responsiveTable'); var $osf = require('./osfHelpers'); require('js/filters'); var AccessRequestModel = function(accessRequest, pageOwner, isRegistration, isParentAdmin, options) { var self = this; self.options = options; $.extend(self, accessRequest); self.permission = ko.observable(accessRequest.permission); self.permissionText = ko.observable(self.options.permissionMap[self.permission()]); self.visible = ko.observable(true); self.pageOwner = pageOwner; self.expanded = ko.observable(false); self.toggleExpand = function() { self.expanded(!self.expanded()); }; self.serialize = function() { return JSON.parse(ko.toJSON(self)); }; self.requestAccessPayload = function(trigger, permissions, visible) { return { 'data': { 'attributes': { 'trigger': trigger, 'permissions': permissions, 'visible': visible }, 'relationships': { 'target': { 'data': { 'type': 'node-requests', 'id': this.id } } }, 'type': 'node-request-actions' } }; }; self.respondToAccessRequest = function(trigger, data, event) { $osf.trackClick('button', 'click', trigger + '-project-access'); $osf.block(); var requestUrl = $osf.apiV2Url('actions/requests/'); var payload = self.requestAccessPayload(trigger, self.permission(), self.visible()); var request = $osf.ajaxJSON( 'POST', requestUrl, { 'is_cors': true, 'data': payload, 'fields': { xhrFields: {withCredentials: true} } } ); request.done(function() { window.location.reload(); }); request.fail(function(xhr, status, error){ $osf.unblock(); var errorMessage = lodashGet(xhr, 'responseJSON.message') || ('There was a problem trying to ' + trigger + ' the request from the user. ' + osfLanguage.REFRESH_OR_SUPPORT); $osf.growl('Could not '+ trigger + ' access request', errorMessage); Raven.captureMessage('Could not ' + trigger + ' access request', { extra: { url: requestUrl, status: status, error: error } }); }); }; self.profileUrl = ko.observable(accessRequest.user.url); self.optionsText = function(val) { return self.options.permissionMap[val]; }; }; var AccessRequestsViewModel = function(accessRequests, user, isRegistration, table) { var self = this; self.original = ko.observableArray(accessRequests); self.table = $(table); self.permissionMap = { read: 'Read', write: 'Read + Write', admin: 'Administrator' }; self.permissionList = Object.keys(self.permissionMap); self.requestToReject = ko.observable(''); self.accessRequests = ko.observableArray(); self.user = ko.observable(user); self.options = { permissionMap: self.permissionMap }; self.accessRequests(self.original().map(function(item) { return new AccessRequestModel(item, self.user(), isRegistration, false, self.options); })); self.serialize = function(accessRequest) { return accessRequest.serialize(); }; self.afterRender = function(elements, data) { var table; table = self.table[0]; if (!!table) { rt.responsiveTable(table); } }; self.collapsed = ko.observable(true); self.onWindowResize = function() { self.collapsed(self.table.children().filter('thead').is(':hidden')); }; }; //////////////// // Public API // //////////////// function AccessRequestManager(selector, accessRequests, user, isRegistration, table) { var self = this; self.selector = selector; self.$element = $(selector); self.accessRequests = accessRequests; self.viewModel = new AccessRequestsViewModel(accessRequests, user, isRegistration, table); self.init(); } AccessRequestManager.prototype.init = function() { $osf.applyBindings(this.viewModel, this.$element[0]); this.$element.show(); }; module.exports = AccessRequestManager;
icereval/osf.io
website/static/js/accessRequestManager.js
JavaScript
apache-2.0
4,816
import { newBidder, registerBidder, preloadBidderMappingFile } from 'src/adapters/bidderFactory'; import adapterManager from 'src/adapterManager'; import * as ajax from 'src/ajax'; import { expect } from 'chai'; import { STATUS } from 'src/constants'; import { userSync } from 'src/userSync' import * as utils from 'src/utils'; import { config } from 'src/config'; const CODE = 'sampleBidder'; const MOCK_BIDS_REQUEST = { bids: [ { bidId: 1, auctionId: 'first-bid-id', adUnitCode: 'mock/placement', params: { param: 5 } }, { bidId: 2, auctionId: 'second-bid-id', adUnitCode: 'mock/placement2', params: { badParam: 6 } } ] } function onTimelyResponseStub() { } describe('bidders created by newBidder', function () { let spec; let bidder; let addBidResponseStub; let doneStub; beforeEach(function () { spec = { code: CODE, isBidRequestValid: sinon.stub(), buildRequests: sinon.stub(), interpretResponse: sinon.stub(), getUserSyncs: sinon.stub() }; addBidResponseStub = sinon.stub(); doneStub = sinon.stub(); }); describe('when the ajax response is irrelevant', function () { let ajaxStub; beforeEach(function () { ajaxStub = sinon.stub(ajax, 'ajax'); addBidResponseStub.reset(); doneStub.reset(); }); afterEach(function () { ajaxStub.restore(); }); it('should handle bad bid requests gracefully', function () { const bidder = newBidder(spec); spec.getUserSyncs.returns([]); bidder.callBids({}); bidder.callBids({ bids: 'nothing useful' }, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.called).to.equal(false); expect(spec.isBidRequestValid.called).to.equal(false); expect(spec.buildRequests.called).to.equal(false); expect(spec.interpretResponse.called).to.equal(false); }); it('should call buildRequests(bidRequest) the params are valid', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.called).to.equal(false); expect(spec.isBidRequestValid.calledTwice).to.equal(true); expect(spec.buildRequests.calledOnce).to.equal(true); expect(spec.buildRequests.firstCall.args[0]).to.deep.equal(MOCK_BIDS_REQUEST.bids); }); it('should not call buildRequests the params are invalid', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(false); spec.buildRequests.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.called).to.equal(false); expect(spec.isBidRequestValid.calledTwice).to.equal(true); expect(spec.buildRequests.called).to.equal(false); }); it('should filter out invalid bids before calling buildRequests', function () { const bidder = newBidder(spec); spec.isBidRequestValid.onFirstCall().returns(true); spec.isBidRequestValid.onSecondCall().returns(false); spec.buildRequests.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.called).to.equal(false); expect(spec.isBidRequestValid.calledTwice).to.equal(true); expect(spec.buildRequests.calledOnce).to.equal(true); expect(spec.buildRequests.firstCall.args[0]).to.deep.equal([MOCK_BIDS_REQUEST.bids[0]]); }); it('should make no server requests if the spec doesn\'t return any', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.called).to.equal(false); }); it('should make the appropriate POST request', function () { const bidder = newBidder(spec); const url = 'test.url.com'; const data = { arg: 2 }; spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: url, data: data }); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.calledOnce).to.equal(true); expect(ajaxStub.firstCall.args[0]).to.equal(url); expect(ajaxStub.firstCall.args[2]).to.equal(JSON.stringify(data)); expect(ajaxStub.firstCall.args[3]).to.deep.equal({ method: 'POST', contentType: 'text/plain', withCredentials: true }); }); it('should make the appropriate POST request when options are passed', function () { const bidder = newBidder(spec); const url = 'test.url.com'; const data = { arg: 2 }; const options = { contentType: 'application/json' }; spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: url, data: data, options: options }); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.calledOnce).to.equal(true); expect(ajaxStub.firstCall.args[0]).to.equal(url); expect(ajaxStub.firstCall.args[2]).to.equal(JSON.stringify(data)); expect(ajaxStub.firstCall.args[3]).to.deep.equal({ method: 'POST', contentType: 'application/json', withCredentials: true }); }); it('should make the appropriate GET request', function () { const bidder = newBidder(spec); const url = 'test.url.com'; const data = { arg: 2 }; spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'GET', url: url, data: data }); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.calledOnce).to.equal(true); expect(ajaxStub.firstCall.args[0]).to.equal(`${url}?arg=2&`); expect(ajaxStub.firstCall.args[2]).to.be.undefined; expect(ajaxStub.firstCall.args[3]).to.deep.equal({ method: 'GET', withCredentials: true }); }); it('should make the appropriate GET request when options are passed', function () { const bidder = newBidder(spec); const url = 'test.url.com'; const data = { arg: 2 }; const opt = { withCredentials: false } spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'GET', url: url, data: data, options: opt }); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.calledOnce).to.equal(true); expect(ajaxStub.firstCall.args[0]).to.equal(`${url}?arg=2&`); expect(ajaxStub.firstCall.args[2]).to.be.undefined; expect(ajaxStub.firstCall.args[3]).to.deep.equal({ method: 'GET', withCredentials: false }); }); it('should make multiple calls if the spec returns them', function () { const bidder = newBidder(spec); const url = 'test.url.com'; const data = { arg: 2 }; spec.isBidRequestValid.returns(true); spec.buildRequests.returns([ { method: 'POST', url: url, data: data }, { method: 'GET', url: url, data: data } ]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(ajaxStub.calledTwice).to.equal(true); }); it('should not add bids for each placement code if no requests are given', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns([]); spec.interpretResponse.returns([]); spec.getUserSyncs.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(addBidResponseStub.callCount).to.equal(0); }); }); describe('when the ajax call succeeds', function () { let ajaxStub; let userSyncStub; let logErrorSpy; beforeEach(function () { ajaxStub = sinon.stub(ajax, 'ajax').callsFake(function(url, callbacks) { const fakeResponse = sinon.stub(); fakeResponse.returns('headerContent'); callbacks.success('response body', { getResponseHeader: fakeResponse }); }); addBidResponseStub.reset(); doneStub.resetBehavior(); userSyncStub = sinon.stub(userSync, 'registerSync') logErrorSpy = sinon.spy(utils, 'logError'); }); afterEach(function () { ajaxStub.restore(); userSyncStub.restore(); utils.logError.restore(); }); it('should call spec.interpretResponse() with the response content', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); spec.getUserSyncs.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(spec.interpretResponse.calledOnce).to.equal(true); const response = spec.interpretResponse.firstCall.args[0] expect(response.body).to.equal('response body') expect(response.headers.get('some-header')).to.equal('headerContent'); expect(spec.interpretResponse.firstCall.args[1]).to.deep.equal({ method: 'POST', url: 'test.url.com', data: {} }); expect(doneStub.calledOnce).to.equal(true); }); it('should call spec.interpretResponse() once for each request made', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns([ { method: 'POST', url: 'test.url.com', data: {} }, { method: 'POST', url: 'test.url.com', data: {} }, ]); spec.getUserSyncs.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(spec.interpretResponse.calledTwice).to.equal(true); expect(doneStub.calledOnce).to.equal(true); }); it('should only add bids for valid adUnit code into the auction, even if the bidder doesn\'t bid on all of them', function () { const bidder = newBidder(spec); const bid = { creativeId: 'creative-id', requestId: '1', ad: 'ad-url.com', cpm: 0.5, height: 200, width: 300, adUnitCode: 'mock/placement', currency: 'USD', netRevenue: true, ttl: 300 }; spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); spec.getUserSyncs.returns([]); spec.interpretResponse.returns(bid); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(addBidResponseStub.calledOnce).to.equal(true); expect(addBidResponseStub.firstCall.args[0]).to.equal('mock/placement'); expect(doneStub.calledOnce).to.equal(true); expect(logErrorSpy.callCount).to.equal(0); }); it('should call spec.getUserSyncs() with the response', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); spec.getUserSyncs.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(spec.getUserSyncs.calledOnce).to.equal(true); expect(spec.getUserSyncs.firstCall.args[1].length).to.equal(1); expect(spec.getUserSyncs.firstCall.args[1][0].body).to.equal('response body'); expect(spec.getUserSyncs.firstCall.args[1][0].headers).to.have.property('get'); expect(spec.getUserSyncs.firstCall.args[1][0].headers.get).to.be.a('function'); }); it('should register usersync pixels', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(false); spec.buildRequests.returns([]); spec.getUserSyncs.returns([{ type: 'iframe', url: 'usersync.com' }]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(userSyncStub.called).to.equal(true); expect(userSyncStub.firstCall.args[0]).to.equal('iframe'); expect(userSyncStub.firstCall.args[1]).to.equal(spec.code); expect(userSyncStub.firstCall.args[2]).to.equal('usersync.com'); }); it('should logError when required bid response params are missing', function () { const bidder = newBidder(spec); const bid = { requestId: '1', ad: 'ad-url.com', cpm: 0.5, height: 200, width: 300, placementCode: 'mock/placement' }; spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); spec.getUserSyncs.returns([]); spec.interpretResponse.returns(bid); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(logErrorSpy.calledOnce).to.equal(true); }); it('should logError when required bid response params are undefined', function () { const bidder = newBidder(spec); const bid = { 'ad': 'creative', 'cpm': '1.99', 'width': 300, 'height': 250, 'requestId': '1', 'creativeId': 'some-id', 'currency': undefined, 'netRevenue': true, 'ttl': 360 }; spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); spec.getUserSyncs.returns([]); spec.interpretResponse.returns(bid); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(logErrorSpy.calledOnce).to.equal(true); }); }); describe('when the ajax call fails', function () { let ajaxStub; beforeEach(function () { ajaxStub = sinon.stub(ajax, 'ajax').callsFake(function(url, callbacks) { callbacks.error('ajax call failed.'); }); addBidResponseStub.reset(); doneStub.reset(); }); afterEach(function () { ajaxStub.restore(); }); it('should not spec.interpretResponse()', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); spec.getUserSyncs.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(spec.interpretResponse.called).to.equal(false); expect(doneStub.calledOnce).to.equal(true); }); it('should not add bids for each adunit code into the auction', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); spec.interpretResponse.returns([]); spec.getUserSyncs.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(addBidResponseStub.callCount).to.equal(0); expect(doneStub.calledOnce).to.equal(true); }); it('should call spec.getUserSyncs() with no responses', function () { const bidder = newBidder(spec); spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); spec.getUserSyncs.returns([]); bidder.callBids(MOCK_BIDS_REQUEST, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(spec.getUserSyncs.calledOnce).to.equal(true); expect(spec.getUserSyncs.firstCall.args[1]).to.deep.equal([]); expect(doneStub.calledOnce).to.equal(true); }); }); }); describe('registerBidder', function () { let registerBidAdapterStub; let aliasBidAdapterStub; beforeEach(function () { registerBidAdapterStub = sinon.stub(adapterManager, 'registerBidAdapter'); aliasBidAdapterStub = sinon.stub(adapterManager, 'aliasBidAdapter'); }); afterEach(function () { registerBidAdapterStub.restore(); aliasBidAdapterStub.restore(); }); function newEmptySpec() { return { code: CODE, isBidRequestValid: function() { }, buildRequests: function() { }, interpretResponse: function() { }, }; } it('should register a bidder with the adapterManager', function () { registerBidder(newEmptySpec()); expect(registerBidAdapterStub.calledOnce).to.equal(true); expect(registerBidAdapterStub.firstCall.args[0]).to.have.property('callBids'); expect(registerBidAdapterStub.firstCall.args[0].callBids).to.be.a('function'); expect(registerBidAdapterStub.firstCall.args[1]).to.equal(CODE); expect(registerBidAdapterStub.firstCall.args[2]).to.be.undefined; }); it('should register a bidder with the appropriate mediaTypes', function () { const thisSpec = Object.assign(newEmptySpec(), { supportedMediaTypes: ['video'] }); registerBidder(thisSpec); expect(registerBidAdapterStub.calledOnce).to.equal(true); expect(registerBidAdapterStub.firstCall.args[2]).to.deep.equal({supportedMediaTypes: ['video']}); }); it('should register bidders with the appropriate aliases', function () { const thisSpec = Object.assign(newEmptySpec(), { aliases: ['foo', 'bar'] }); registerBidder(thisSpec); expect(registerBidAdapterStub.calledThrice).to.equal(true); // Make sure our later calls don't override the bidder code from previous calls. expect(registerBidAdapterStub.firstCall.args[0].getBidderCode()).to.equal(CODE); expect(registerBidAdapterStub.secondCall.args[0].getBidderCode()).to.equal('foo') expect(registerBidAdapterStub.thirdCall.args[0].getBidderCode()).to.equal('bar') expect(registerBidAdapterStub.firstCall.args[1]).to.equal(CODE); expect(registerBidAdapterStub.secondCall.args[1]).to.equal('foo') expect(registerBidAdapterStub.thirdCall.args[1]).to.equal('bar') }); }) describe('validate bid response: ', function () { let spec; let bidder; let addBidResponseStub; let doneStub; let ajaxStub; let logErrorSpy; let bids = [{ 'ad': 'creative', 'cpm': '1.99', 'width': 300, 'height': 250, 'requestId': '1', 'creativeId': 'some-id', 'currency': 'USD', 'netRevenue': true, 'ttl': 360 }]; beforeEach(function () { spec = { code: CODE, isBidRequestValid: sinon.stub(), buildRequests: sinon.stub(), interpretResponse: sinon.stub(), }; spec.isBidRequestValid.returns(true); spec.buildRequests.returns({ method: 'POST', url: 'test.url.com', data: {} }); addBidResponseStub = sinon.stub(); doneStub = sinon.stub(); ajaxStub = sinon.stub(ajax, 'ajax').callsFake(function(url, callbacks) { const fakeResponse = sinon.stub(); fakeResponse.returns('headerContent'); callbacks.success('response body', { getResponseHeader: fakeResponse }); }); logErrorSpy = sinon.spy(utils, 'logError'); }); afterEach(function () { ajaxStub.restore(); logErrorSpy.restore(); }); it('should add native bids that do have required assets', function () { let bidRequest = { bids: [{ bidId: '1', auctionId: 'first-bid-id', adUnitCode: 'mock/placement', params: { param: 5 }, nativeParams: { title: {'required': true}, }, mediaType: 'native', }] }; let bids1 = Object.assign({}, bids[0], { 'mediaType': 'native', 'native': { 'title': 'Native Creative', 'clickUrl': 'https://www.link.example', } } ); const bidder = newBidder(spec); spec.interpretResponse.returns(bids1); bidder.callBids(bidRequest, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(addBidResponseStub.calledOnce).to.equal(true); expect(addBidResponseStub.firstCall.args[0]).to.equal('mock/placement'); expect(logErrorSpy.callCount).to.equal(0); }); it('should not add native bids that do not have required assets', function () { let bidRequest = { bids: [{ bidId: '1', auctionId: 'first-bid-id', adUnitCode: 'mock/placement', params: { param: 5 }, nativeParams: { title: {'required': true}, }, mediaType: 'native', }] }; let bids1 = Object.assign({}, bids[0], { bidderCode: CODE, mediaType: 'native', native: { title: undefined, clickUrl: 'https://www.link.example', } } ); const bidder = newBidder(spec); spec.interpretResponse.returns(bids1); bidder.callBids(bidRequest, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(addBidResponseStub.calledOnce).to.equal(false); expect(logErrorSpy.callCount).to.equal(1); }); it('should add bid when renderer is present on outstream bids', function () { let bidRequest = { bids: [{ bidId: '1', auctionId: 'first-bid-id', adUnitCode: 'mock/placement', params: { param: 5 }, mediaTypes: { video: {context: 'outstream'} } }] }; let bids1 = Object.assign({}, bids[0], { bidderCode: CODE, mediaType: 'video', renderer: {render: () => true, url: 'render.js'}, } ); const bidder = newBidder(spec); spec.interpretResponse.returns(bids1); bidder.callBids(bidRequest, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(addBidResponseStub.calledOnce).to.equal(true); expect(addBidResponseStub.firstCall.args[0]).to.equal('mock/placement'); expect(logErrorSpy.callCount).to.equal(0); }); it('should add banner bids that have no width or height but single adunit size', function () { let bidRequest = { bids: [{ bidder: CODE, bidId: '1', auctionId: 'first-bid-id', adUnitCode: 'mock/placement', params: { param: 5 }, sizes: [[300, 250]], }] }; let bids1 = Object.assign({}, bids[0], { width: undefined, height: undefined } ); const bidder = newBidder(spec); spec.interpretResponse.returns(bids1); bidder.callBids(bidRequest, addBidResponseStub, doneStub, ajaxStub, onTimelyResponseStub); expect(addBidResponseStub.calledOnce).to.equal(true); expect(addBidResponseStub.firstCall.args[0]).to.equal('mock/placement'); expect(logErrorSpy.callCount).to.equal(0); }); }); describe('preload mapping url hook', function() { let fakeTranslationServer; let getLocalStorageStub; let adapterManagerStub; beforeEach(function () { fakeTranslationServer = sinon.fakeServer.create(); getLocalStorageStub = sinon.stub(utils, 'getDataFromLocalStorage'); adapterManagerStub = sinon.stub(adapterManager, 'getBidAdapter'); }); afterEach(function() { getLocalStorageStub.restore(); adapterManagerStub.restore(); config.resetConfig(); }); it('should preload mapping url file', function() { config.setConfig({ 'adpod': { 'brandCategoryExclusion': true } }); let adUnits = [{ code: 'midroll_1', mediaTypes: { video: { context: 'adpod' } }, bids: [ { bidder: 'sampleBidder1', params: { placementId: 14542875, } } ] }]; getLocalStorageStub.returns(null); adapterManagerStub.withArgs('sampleBidder1').returns({ getSpec: function() { return { 'getMappingFileInfo': function() { return { url: 'http://sample.com', refreshInDays: 7, key: `sampleBidder1MappingFile` } } } } }); preloadBidderMappingFile(sinon.spy(), adUnits); expect(fakeTranslationServer.requests.length).to.equal(1); }); it('should preload mapping url file for all bidders', function() { config.setConfig({ 'adpod': { 'brandCategoryExclusion': true } }); let adUnits = [{ code: 'midroll_1', mediaTypes: { video: { context: 'adpod' } }, bids: [ { bidder: 'sampleBidder1', params: { placementId: 14542875, } }, { bidder: 'sampleBidder2', params: { placementId: 123456, } } ] }]; getLocalStorageStub.returns(null); adapterManagerStub.withArgs('sampleBidder1').returns({ getSpec: function() { return { 'getMappingFileInfo': function() { return { url: 'http://sample.com', refreshInDays: 7, key: `sampleBidder1MappingFile` } } } } }); adapterManagerStub.withArgs('sampleBidder2').returns({ getSpec: function() { return { 'getMappingFileInfo': function() { return { url: 'http://sample.com', refreshInDays: 7, key: `sampleBidder2MappingFile` } } } } }); preloadBidderMappingFile(sinon.spy(), adUnits); expect(fakeTranslationServer.requests.length).to.equal(2); config.setConfig({ 'adpod': { 'brandCategoryExclusion': false } }); preloadBidderMappingFile(sinon.spy(), adUnits); expect(fakeTranslationServer.requests.length).to.equal(2); }); });
Adikteev/Prebid.js
test/spec/unit/core/bidderFactory_spec.js
JavaScript
apache-2.0
26,754
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ 'use strict'; async function main( datasetId, modelDisplayName, trainingPipelineDisplayName, project, location = 'us-central1' ) { // [START aiplatform_create_training_pipeline_video_action_recognition_sample] /** * TODO(developer): Uncomment these variables before running the sample.\ * (Not necessary if passing values as arguments) */ // const datasetId = 'YOUR_DATASET_ID'; // const modelDisplayName = 'YOUR_MODEL_DISPLAY_NAME'; // const trainingPipelineDisplayName = 'YOUR_TRAINING_PIPELINE_DISPLAY_NAME'; // const project = 'YOUR_PROJECT_ID'; // const location = 'YOUR_PROJECT_LOCATION'; const aiplatform = require('@google-cloud/aiplatform'); const {definition} = aiplatform.protos.google.cloud.aiplatform.v1.schema.trainingjob; // Imports the Google Cloud Pipeline Service Client library const {PipelineServiceClient} = aiplatform.v1; // Specifies the location of the api endpoint const clientOptions = { apiEndpoint: 'us-central1-aiplatform.googleapis.com', }; // Instantiates a client const pipelineServiceClient = new PipelineServiceClient(clientOptions); async function createTrainingPipelineVideoActionRecognition() { // Configure the parent resource const parent = `projects/${project}/locations/${location}`; // Values should match the input expected by your model. const trainingTaskInputObj = new definition.AutoMlVideoActionRecognitionInputs({ // modelType can be either 'CLOUD' or 'MOBILE_VERSATILE_1' modelType: 'CLOUD', }); const trainingTaskInputs = trainingTaskInputObj.toValue(); const modelToUpload = {displayName: modelDisplayName}; const inputDataConfig = {datasetId: datasetId}; const trainingPipeline = { displayName: trainingPipelineDisplayName, trainingTaskDefinition: 'gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_video_action_recognition_1.0.0.yaml', trainingTaskInputs, inputDataConfig, modelToUpload, }; const request = { parent, trainingPipeline, }; // Create training pipeline request const [response] = await pipelineServiceClient.createTrainingPipeline( request ); console.log('Create training pipeline video action recognition response'); console.log(`Name : ${response.name}`); console.log('Raw response:'); console.log(JSON.stringify(response, null, 2)); } createTrainingPipelineVideoActionRecognition(); // [END aiplatform_create_training_pipeline_video_action_recognition_sample] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
googleapis/nodejs-ai-platform
samples/create-training-pipeline-video-action-recognition.js
JavaScript
apache-2.0
3,310
Clazz.declarePackage ("J.g3d"); Clazz.load (null, "J.g3d.CylinderRenderer", ["J.util.ArrayUtil", "$.Shader"], function () { c$ = Clazz.decorateAsClass (function () { this.g3d = null; this.line3d = null; this.shader = null; this.colixA = 0; this.colixB = 0; this.shadesA = null; this.isScreenedA = false; this.shadesB = null; this.isScreenedB = false; this.xA = 0; this.yA = 0; this.zA = 0; this.dxB = 0; this.dyB = 0; this.dzB = 0; this.xAf = 0; this.yAf = 0; this.zAf = 0; this.dxBf = 0; this.dyBf = 0; this.dzBf = 0; this.tEvenDiameter = false; this.diameter = 0; this.endcaps = 0; this.tEndcapOpen = false; this.xEndcap = 0; this.yEndcap = 0; this.zEndcap = 0; this.argbEndcap = 0; this.colixEndcap = 0; this.endcapShadeIndex = 0; this.radius = 0; this.radius2 = 0; this.cosTheta = 0; this.cosPhi = 0; this.sinPhi = 0; this.clipped = false; this.drawBackside = false; this.xTip = 0; this.yTip = 0; this.zTip = 0; this.rasterCount = 0; this.tRaster = null; this.txRaster = null; this.tyRaster = null; this.tzRaster = null; this.xRaster = null; this.yRaster = null; this.zRaster = null; this.fp8ShadeIndexUp = null; this.yMin = 0; this.yMax = 0; this.xMin = 0; this.xMax = 0; this.zXMin = 0; this.zXMax = 0; Clazz.instantialize (this, arguments); }, J.g3d, "CylinderRenderer"); Clazz.prepareFields (c$, function () { this.tRaster = Clazz.newFloatArray (32, 0); this.txRaster = Clazz.newFloatArray (32, 0); this.tyRaster = Clazz.newFloatArray (32, 0); this.tzRaster = Clazz.newFloatArray (32, 0); this.xRaster = Clazz.newIntArray (32, 0); this.yRaster = Clazz.newIntArray (32, 0); this.zRaster = Clazz.newIntArray (32, 0); this.fp8ShadeIndexUp = Clazz.newIntArray (32, 0); }); Clazz.makeConstructor (c$, function (g3d) { this.g3d = g3d; this.line3d = g3d.line3d; this.shader = g3d.shader; }, "J.g3d.Graphics3D"); $_M(c$, "render", function (colixA, colixB, isScreenedA, isScreenedB, endcaps, diameter, xA, yA, zA, xB, yB, zB) { if (diameter > this.g3d.getRenderHeight () * 3) return; this.isScreenedA = isScreenedA; this.isScreenedB = isScreenedB; var r = Clazz.doubleToInt (diameter / 2) + 1; var codeMinA = this.g3d.clipCode3 (xA - r, yA - r, zA - r); var codeMaxA = this.g3d.clipCode3 (xA + r, yA + r, zA + r); var codeMinB = this.g3d.clipCode3 (xB - r, yB - r, zB - r); var codeMaxB = this.g3d.clipCode3 (xB + r, yB + r, zB + r); this.clipped = ((codeMinA | codeMaxA | codeMinB | codeMaxB) != 0); if ((codeMinA & codeMaxB & codeMaxA & codeMinB) != 0) return; this.dxB = xB - xA; this.dyB = yB - yA; this.dzB = zB - zA; if (diameter <= 1) { this.line3d.plotLineDelta (this.g3d.getColorArgbOrGray (colixA), isScreenedA, this.g3d.getColorArgbOrGray (colixB), isScreenedB, xA, yA, zA, this.dxB, this.dyB, this.dzB, this.clipped); return; }this.drawBackside = (this.clipped || endcaps == 2 || endcaps == 0); this.diameter = diameter; this.xA = xA; this.yA = yA; this.zA = zA; this.endcaps = endcaps; this.shadesA = this.g3d.getShades (this.colixA = colixA); this.shadesB = this.g3d.getShades (this.colixB = colixB); this.calcArgbEndcap (true, false); this.generateBaseEllipse (); if (endcaps == 2 || endcaps == 4) this.renderFlatEndcap (true); this.g3d.setZMargin (5); for (var i = this.rasterCount; --i >= 0; ) this.plotRaster (i); this.g3d.setZMargin (0); if (endcaps == 3) this.renderSphericalEndcaps (); }, "~N,~N,~B,~B,~N,~N,~N,~N,~N,~N,~N,~N"); $_M(c$, "renderBits", function (colixA, colixB, isScreenedA, isScreenedB, endcaps, diameter, xA, yA, zA, xB, yB, zB) { if (diameter > this.g3d.getRenderHeight () * 3) return; this.isScreenedA = isScreenedA; this.isScreenedB = isScreenedB; var r = Clazz.doubleToInt (diameter / 2) + 1; var ixA = Math.round (xA); var iyA = Math.round (yA); var izA = Math.round (zA); var ixB = Math.round (xB); var iyB = Math.round (yB); var izB = Math.round (zB); var codeMinA = this.g3d.clipCode3 (ixA - r, iyA - r, izA - r); var codeMaxA = this.g3d.clipCode3 (ixA + r, iyA + r, izA + r); var codeMinB = this.g3d.clipCode3 (ixB - r, iyB - r, izB - r); var codeMaxB = this.g3d.clipCode3 (ixB + r, iyB + r, izB + r); this.clipped = ((codeMinA | codeMaxA | codeMinB | codeMaxB) != 0); if ((codeMinA & codeMaxB & codeMaxA & codeMinB) != 0) return; this.dxBf = xB - xA; this.dyBf = yB - yA; this.dzBf = zB - zA; if (diameter == 0 || diameter == 1) { this.line3d.plotLineDelta (this.g3d.getColorArgbOrGray (colixA), isScreenedA, this.g3d.getColorArgbOrGray (colixB), isScreenedB, Clazz.floatToInt (xA), Clazz.floatToInt (yA), Clazz.floatToInt (zA), Clazz.floatToInt (this.dxBf), Clazz.floatToInt (this.dyBf), Clazz.floatToInt (this.dzBf), this.clipped); return; }if (diameter > 0) { this.diameter = diameter; this.xAf = xA; this.yAf = yA; this.zAf = zA; }this.drawBackside = (!isScreenedA && !isScreenedB && (this.clipped || endcaps == 2 || endcaps == 0)); this.xA = Clazz.floatToInt (this.xAf); this.yA = Clazz.floatToInt (this.yAf); this.zA = Clazz.floatToInt (this.zAf); this.dxB = Clazz.floatToInt (this.dxBf); this.dyB = Clazz.floatToInt (this.dyBf); this.dzB = Clazz.floatToInt (this.dzBf); this.shadesA = this.g3d.getShades (this.colixA = colixA); this.shadesB = this.g3d.getShades (this.colixB = colixB); this.endcaps = endcaps; this.calcArgbEndcap (true, true); if (diameter > 0) this.generateBaseEllipsePrecisely (false); if (endcaps == 2) this.renderFlatEndcapPrecisely (true); this.line3d.setLineBits (this.dxBf, this.dyBf); this.g3d.setZMargin (5); for (var i = this.rasterCount; --i >= 0; ) this.plotRasterBits (i); this.g3d.setZMargin (0); if (endcaps == 3) this.renderSphericalEndcaps (); this.xAf += this.dxBf; this.yAf += this.dyBf; this.zAf += this.dzBf; }, "~N,~N,~B,~B,~N,~N,~N,~N,~N,~N,~N,~N"); $_M(c$, "plotRasterBits", ($fz = function (i) { var fpz = this.fp8ShadeIndexUp[i] >> (8); var fpzBack = fpz >> 1; var x = this.xRaster[i]; var y = this.yRaster[i]; var z = this.zRaster[i]; if (this.tEndcapOpen && this.argbEndcap != 0) { if (this.clipped) { this.g3d.plotPixelClippedArgb (this.argbEndcap, this.xEndcap + x, this.yEndcap + y, this.zEndcap - z - 1); this.g3d.plotPixelClippedArgb (this.argbEndcap, this.xEndcap - x, this.yEndcap - y, this.zEndcap + z - 1); } else { this.g3d.plotPixelUnclippedArgb (this.argbEndcap, this.xEndcap + x, this.yEndcap + y, this.zEndcap - z - 1); this.g3d.plotPixelUnclippedArgb (this.argbEndcap, this.xEndcap - x, this.yEndcap - y, this.zEndcap + z - 1); }}this.line3d.plotLineDeltaBits (this.shadesA, this.isScreenedA, this.shadesB, this.isScreenedB, fpz, this.xA + x, this.yA + y, this.zA - z, this.dxB, this.dyB, this.dzB, this.clipped); if (this.drawBackside) { this.line3d.plotLineDelta (this.shadesA[fpzBack], this.isScreenedA, this.shadesB[fpzBack], this.isScreenedB, this.xA - x, this.yA - y, this.zA + z, this.dxB, this.dyB, this.dzB, this.clipped); }}, $fz.isPrivate = true, $fz), "~N"); $_M(c$, "renderCone", function (colix, isScreened, endcap, diameter, xA, yA, zA, xTip, yTip, zTip, doFill, isBarb) { if (diameter > this.g3d.getRenderHeight () * 3) return; this.dxBf = (xTip) - (this.xAf = xA); this.dyBf = (yTip) - (this.yAf = yA); this.dzBf = (zTip) - (this.zAf = zA); this.xA = Clazz.doubleToInt (Math.floor (this.xAf)); this.yA = Clazz.doubleToInt (Math.floor (this.yAf)); this.zA = Clazz.doubleToInt (Math.floor (this.zAf)); this.dxB = Clazz.doubleToInt (Math.floor (this.dxBf)); this.dyB = Clazz.doubleToInt (Math.floor (this.dyBf)); this.dzB = Clazz.doubleToInt (Math.floor (this.dzBf)); this.xTip = xTip; this.yTip = yTip; this.zTip = zTip; this.colixA = colix; this.isScreenedA = isScreened; this.shadesA = this.g3d.getShades (colix); var shadeIndexTip = this.shader.getShadeIndex (this.dxB, this.dyB, -this.dzB); this.g3d.plotPixelClippedScreened (this.shadesA[shadeIndexTip], this.isScreenedA, Clazz.floatToInt (xTip), Clazz.floatToInt (yTip), Clazz.floatToInt (zTip)); this.diameter = diameter; if (diameter <= 1) { if (diameter == 1) this.line3d.plotLineDelta (this.colixA, this.isScreenedA, this.colixA, this.isScreenedA, this.xA, this.yA, this.zA, this.dxB, this.dyB, this.dzB, this.clipped); return; }this.endcaps = endcap; this.calcArgbEndcap (false, true); this.generateBaseEllipsePrecisely (isBarb); if (!isBarb && this.endcaps == 2) this.renderFlatEndcapPrecisely (false); this.g3d.setZMargin (5); for (var i = this.rasterCount; --i >= 0; ) this.plotRasterCone (i, doFill, isBarb); this.g3d.setZMargin (0); }, "~N,~B,~N,~N,~N,~N,~N,~N,~N,~N,~B,~B"); $_M(c$, "generateBaseEllipse", ($fz = function () { this.tEvenDiameter = (this.diameter & 1) == 0; this.radius = this.diameter / 2.0; this.radius2 = this.radius * this.radius; var mag2d2 = this.dxB * this.dxB + this.dyB * this.dyB; if (mag2d2 == 0) { this.cosTheta = 1; this.cosPhi = 1; this.sinPhi = 0; } else { var mag2d = Math.sqrt (mag2d2); var mag3d = Math.sqrt (mag2d2 + this.dzB * this.dzB); this.cosTheta = this.dzB / mag3d; this.cosPhi = this.dxB / mag2d; this.sinPhi = this.dyB / mag2d; }this.calcRotatedPoint (0, 0, false); this.calcRotatedPoint (0.5, 1, false); this.calcRotatedPoint (1, 2, false); this.rasterCount = 3; this.interpolate (0, 1); this.interpolate (1, 2); }, $fz.isPrivate = true, $fz)); $_M(c$, "generateBaseEllipsePrecisely", ($fz = function (isBarb) { this.tEvenDiameter = (this.diameter & 1) == 0; this.radius = this.diameter / 2.0; this.radius2 = this.radius * this.radius; var mag2d2 = this.dxBf * this.dxBf + this.dyBf * this.dyBf; if (mag2d2 == 0) { this.cosTheta = 1; this.cosPhi = 1; this.sinPhi = 0; } else { var mag2d = Math.sqrt (mag2d2); var mag3d = Math.sqrt (mag2d2 + this.dzBf * this.dzBf); this.cosTheta = this.dzBf / mag3d; this.cosPhi = this.dxBf / mag2d; this.sinPhi = this.dyBf / mag2d; }if (isBarb) { this.calcRotatedPoint (0, 0, true); this.calcRotatedPoint (0.5, 1, true); this.rasterCount = 2; this.interpolatePrecisely (0, 1); } else { this.calcRotatedPoint (0, 0, true); this.calcRotatedPoint (0.5, 1, true); this.calcRotatedPoint (1, 2, true); this.rasterCount = 3; this.interpolatePrecisely (0, 1); this.interpolatePrecisely (1, 2); }for (var i = 0; i < this.rasterCount; i++) { this.xRaster[i] = Clazz.doubleToInt (Math.floor (this.txRaster[i])); this.yRaster[i] = Clazz.doubleToInt (Math.floor (this.tyRaster[i])); this.zRaster[i] = Clazz.doubleToInt (Math.floor (this.tzRaster[i])); } }, $fz.isPrivate = true, $fz), "~B"); $_M(c$, "calcRotatedPoint", ($fz = function (t, i, isPrecision) { this.tRaster[i] = t; var tPI = t * 3.141592653589793; var xT = Math.sin (tPI) * this.cosTheta; var yT = Math.cos (tPI); var xR = this.radius * (xT * this.cosPhi - yT * this.sinPhi); var yR = this.radius * (xT * this.sinPhi + yT * this.cosPhi); var z2 = this.radius2 - (xR * xR + yR * yR); var zR = (z2 > 0 ? Math.sqrt (z2) : 0); if (isPrecision) { this.txRaster[i] = xR; this.tyRaster[i] = yR; this.tzRaster[i] = zR; } else if (this.tEvenDiameter) { this.xRaster[i] = Clazz.doubleToInt (xR - 0.5); this.yRaster[i] = Clazz.doubleToInt (yR - 0.5); this.zRaster[i] = Clazz.doubleToInt (zR + 0.5); } else { this.xRaster[i] = Clazz.doubleToInt (xR); this.yRaster[i] = Clazz.doubleToInt (yR); this.zRaster[i] = Clazz.doubleToInt (zR + 0.5); }this.fp8ShadeIndexUp[i] = this.shader.getShadeFp8 (xR, yR, zR); }, $fz.isPrivate = true, $fz), "~N,~N,~B"); $_M(c$, "interpolate", ($fz = function (iLower, iUpper) { var dx = this.xRaster[iUpper] - this.xRaster[iLower]; if (dx < 0) dx = -dx; var dy = this.yRaster[iUpper] - this.yRaster[iLower]; if (dy < 0) dy = -dy; if ((dx + dy) <= 1) return; var tLower = this.tRaster[iLower]; var tUpper = this.tRaster[iUpper]; var iMid = this.allocRaster (false); for (var j = 4; --j >= 0; ) { var tMid = (tLower + tUpper) / 2; this.calcRotatedPoint (tMid, iMid, false); if ((this.xRaster[iMid] == this.xRaster[iLower]) && (this.yRaster[iMid] == this.yRaster[iLower])) { this.fp8ShadeIndexUp[iLower] = (this.fp8ShadeIndexUp[iLower] + this.fp8ShadeIndexUp[iMid]) >>> 1; tLower = tMid; } else if ((this.xRaster[iMid] == this.xRaster[iUpper]) && (this.yRaster[iMid] == this.yRaster[iUpper])) { this.fp8ShadeIndexUp[iUpper] = (this.fp8ShadeIndexUp[iUpper] + this.fp8ShadeIndexUp[iMid]) >>> 1; tUpper = tMid; } else { this.interpolate (iLower, iMid); this.interpolate (iMid, iUpper); return; }} this.xRaster[iMid] = this.xRaster[iLower]; this.yRaster[iMid] = this.yRaster[iUpper]; }, $fz.isPrivate = true, $fz), "~N,~N"); $_M(c$, "interpolatePrecisely", ($fz = function (iLower, iUpper) { var dx = Clazz.doubleToInt (Math.floor (this.txRaster[iUpper])) - Clazz.doubleToInt (Math.floor (this.txRaster[iLower])); if (dx < 0) dx = -dx; var dy = Clazz.doubleToInt (Math.floor (this.tyRaster[iUpper])) - Clazz.doubleToInt (Math.floor (this.tyRaster[iLower])); if (dy < 0) dy = -dy; if ((dx + dy) <= 1) return; var tLower = this.tRaster[iLower]; var tUpper = this.tRaster[iUpper]; var iMid = this.allocRaster (true); for (var j = 4; --j >= 0; ) { var tMid = (tLower + tUpper) / 2; this.calcRotatedPoint (tMid, iMid, true); if ((Clazz.doubleToInt (Math.floor (this.txRaster[iMid])) == Clazz.doubleToInt (Math.floor (this.txRaster[iLower]))) && (Clazz.doubleToInt (Math.floor (this.tyRaster[iMid])) == Clazz.doubleToInt (Math.floor (this.tyRaster[iLower])))) { this.fp8ShadeIndexUp[iLower] = (this.fp8ShadeIndexUp[iLower] + this.fp8ShadeIndexUp[iMid]) >>> 1; tLower = tMid; } else if ((Clazz.doubleToInt (Math.floor (this.txRaster[iMid])) == Clazz.doubleToInt (Math.floor (this.txRaster[iUpper]))) && (Clazz.doubleToInt (Math.floor (this.tyRaster[iMid])) == Clazz.doubleToInt (Math.floor (this.tyRaster[iUpper])))) { this.fp8ShadeIndexUp[iUpper] = (this.fp8ShadeIndexUp[iUpper] + this.fp8ShadeIndexUp[iMid]) >>> 1; tUpper = tMid; } else { this.interpolatePrecisely (iLower, iMid); this.interpolatePrecisely (iMid, iUpper); return; }} this.txRaster[iMid] = this.txRaster[iLower]; this.tyRaster[iMid] = this.tyRaster[iUpper]; }, $fz.isPrivate = true, $fz), "~N,~N"); $_M(c$, "plotRaster", ($fz = function (i) { var fpz = this.fp8ShadeIndexUp[i] >> (8); var fpzBack = fpz >> 1; var x = this.xRaster[i]; var y = this.yRaster[i]; var z = this.zRaster[i]; if (this.tEndcapOpen && this.argbEndcap != 0) { if (this.clipped) { this.g3d.plotPixelClippedArgb (this.argbEndcap, this.xEndcap + x, this.yEndcap + y, this.zEndcap - z - 1); this.g3d.plotPixelClippedArgb (this.argbEndcap, this.xEndcap - x, this.yEndcap - y, this.zEndcap + z - 1); } else { this.g3d.plotPixelUnclippedArgb (this.argbEndcap, this.xEndcap + x, this.yEndcap + y, this.zEndcap - z - 1); this.g3d.plotPixelUnclippedArgb (this.argbEndcap, this.xEndcap - x, this.yEndcap - y, this.zEndcap + z - 1); }}this.line3d.plotLineDeltaA (this.shadesA, this.isScreenedA, this.shadesB, this.isScreenedB, fpz, this.xA + x, this.yA + y, this.zA - z, this.dxB, this.dyB, this.dzB, this.clipped); if (this.drawBackside) { this.line3d.plotLineDelta (this.shadesA[fpzBack], this.isScreenedA, this.shadesB[fpzBack], this.isScreenedB, this.xA - x, this.yA - y, this.zA + z, this.dxB, this.dyB, this.dzB, this.clipped); }}, $fz.isPrivate = true, $fz), "~N"); $_M(c$, "allocRaster", ($fz = function (isPrecision) { while (this.rasterCount >= this.xRaster.length) { this.xRaster = J.util.ArrayUtil.doubleLengthI (this.xRaster); this.yRaster = J.util.ArrayUtil.doubleLengthI (this.yRaster); this.zRaster = J.util.ArrayUtil.doubleLengthI (this.zRaster); this.tRaster = J.util.ArrayUtil.doubleLengthF (this.tRaster); } while (this.rasterCount >= this.fp8ShadeIndexUp.length) this.fp8ShadeIndexUp = J.util.ArrayUtil.doubleLengthI (this.fp8ShadeIndexUp); if (isPrecision) while (this.rasterCount >= this.txRaster.length) { this.txRaster = J.util.ArrayUtil.doubleLengthF (this.txRaster); this.tyRaster = J.util.ArrayUtil.doubleLengthF (this.tyRaster); this.tzRaster = J.util.ArrayUtil.doubleLengthF (this.tzRaster); } return this.rasterCount++; }, $fz.isPrivate = true, $fz), "~B"); $_M(c$, "findMinMaxY", ($fz = function () { this.yMin = this.yMax = this.yRaster[0]; for (var i = this.rasterCount; --i > 0; ) { var y = this.yRaster[i]; if (y < this.yMin) this.yMin = y; else if (y > this.yMax) this.yMax = y; else { y = -y; if (y < this.yMin) this.yMin = y; else if (y > this.yMax) this.yMax = y; }} }, $fz.isPrivate = true, $fz)); $_M(c$, "findMinMaxX", ($fz = function (y) { this.xMin = 2147483647; this.xMax = -2147483648; for (var i = this.rasterCount; --i >= 0; ) { if (this.yRaster[i] == y) { var x = this.xRaster[i]; if (x < this.xMin) { this.xMin = x; this.zXMin = this.zRaster[i]; }if (x > this.xMax) { this.xMax = x; this.zXMax = this.zRaster[i]; }}if (this.yRaster[i] == -y) { var x = -this.xRaster[i]; if (x < this.xMin) { this.xMin = x; this.zXMin = -this.zRaster[i]; }if (x > this.xMax) { this.xMax = x; this.zXMax = -this.zRaster[i]; }}} }, $fz.isPrivate = true, $fz), "~N"); $_M(c$, "renderFlatEndcap", ($fz = function (tCylinder) { if (this.dzB == 0 || !this.g3d.setColix (this.colixEndcap)) return; var xT = this.xA; var yT = this.yA; var zT = this.zA; if (tCylinder && this.dzB < 0) { if (this.endcaps == 4) return; xT += this.dxB; yT += this.dyB; zT += this.dzB; }this.findMinMaxY (); for (var y = this.yMin; y <= this.yMax; ++y) { this.findMinMaxX (y); var count = this.xMax - this.xMin + 1; this.g3d.setColorNoisy (this.endcapShadeIndex); this.g3d.plotPixelsClippedRaster (count, xT + this.xMin, yT + y, zT - this.zXMin - 1, zT - this.zXMax - 1, null, null); } }, $fz.isPrivate = true, $fz), "~B"); $_M(c$, "renderFlatEndcapPrecisely", ($fz = function (tCylinder) { if (this.dzBf == 0 || !this.g3d.setColix (this.colixEndcap)) return; var xTf = this.xAf; var yTf = this.yAf; var zTf = this.zAf; if (tCylinder && this.dzBf < 0) { xTf += this.dxBf; yTf += this.dyBf; zTf += this.dzBf; }var xT = Clazz.floatToInt (xTf); var yT = Clazz.floatToInt (yTf); var zT = Clazz.floatToInt (zTf); this.findMinMaxY (); for (var y = this.yMin; y <= this.yMax; ++y) { this.findMinMaxX (y); var count = this.xMax - this.xMin + 1; this.g3d.setColorNoisy (this.endcapShadeIndex); this.g3d.plotPixelsClippedRaster (count, xT + this.xMin, yT + y, zT - this.zXMin - 1, zT - this.zXMax - 1, null, null); } }, $fz.isPrivate = true, $fz), "~B"); $_M(c$, "renderSphericalEndcaps", ($fz = function () { if (this.colixA != 0 && this.g3d.setColix (this.colixA)) this.g3d.fillSphereXYZ (this.diameter, this.xA, this.yA, this.zA + 1); if (this.colixB != 0 && this.g3d.setColix (this.colixB)) this.g3d.fillSphereXYZ (this.diameter, this.xA + this.dxB, this.yA + this.dyB, this.zA + this.dzB + 1); }, $fz.isPrivate = true, $fz)); $_M(c$, "plotRasterCone", ($fz = function (i, doFill, isBarb) { var x = this.txRaster[i]; var y = this.tyRaster[i]; var z = this.tzRaster[i]; var xUp = this.xAf + x; var yUp = this.yAf + y; var zUp = this.zAf - z; var xDn = this.xAf - x; var yDn = this.yAf - y; var zDn = this.zAf + z; var argb = this.shadesA[0]; if (this.tEndcapOpen && this.argbEndcap != 0) { this.g3d.plotPixelClippedScreened (this.argbEndcap, this.isScreenedA, Clazz.floatToInt (xUp), Clazz.floatToInt (yUp), Clazz.floatToInt (zUp)); this.g3d.plotPixelClippedScreened (this.argbEndcap, this.isScreenedA, Clazz.floatToInt (xDn), Clazz.floatToInt (yDn), Clazz.floatToInt (zDn)); }var fpz = this.fp8ShadeIndexUp[i] >> (8); if (argb != 0) { this.line3d.plotLineDeltaA (this.shadesA, this.isScreenedA, this.shadesA, this.isScreenedA, fpz, Clazz.floatToInt (xUp), Clazz.floatToInt (yUp), Clazz.floatToInt (zUp), Clazz.doubleToInt (Math.ceil (this.xTip - xUp)), Clazz.doubleToInt (Math.ceil (this.yTip - yUp)), Clazz.doubleToInt (Math.ceil (this.zTip - zUp)), true); if (doFill) { this.line3d.plotLineDeltaA (this.shadesA, this.isScreenedA, this.shadesA, this.isScreenedA, fpz, Clazz.floatToInt (xUp), Clazz.floatToInt (yUp) + 1, Clazz.floatToInt (zUp), Clazz.doubleToInt (Math.ceil (this.xTip - xUp)), Clazz.doubleToInt (Math.ceil (this.yTip - yUp)) + 1, Clazz.doubleToInt (Math.ceil (this.zTip - zUp)), true); this.line3d.plotLineDeltaA (this.shadesA, this.isScreenedA, this.shadesA, this.isScreenedA, fpz, Clazz.floatToInt (xUp) + 1, Clazz.floatToInt (yUp), Clazz.floatToInt (zUp), Clazz.doubleToInt (Math.ceil (this.xTip - xUp)) + 1, Clazz.doubleToInt (Math.ceil (this.yTip - yUp)), Clazz.doubleToInt (Math.ceil (this.zTip - zUp)), true); }if (!isBarb && !(this.endcaps != 2 && this.dzB > 0)) { this.line3d.plotLineDelta (argb, this.isScreenedA, argb, this.isScreenedA, Clazz.floatToInt (xDn), Clazz.floatToInt (yDn), Clazz.floatToInt (zDn), Clazz.doubleToInt (Math.ceil (this.xTip - xDn)), Clazz.doubleToInt (Math.ceil (this.yTip - yDn)), Clazz.doubleToInt (Math.ceil (this.zTip - zDn)), true); }}}, $fz.isPrivate = true, $fz), "~N,~B,~B"); $_M(c$, "calcArgbEndcap", ($fz = function (tCylinder, isFloat) { this.tEndcapOpen = false; var dzf = (isFloat ? this.dzBf : this.dzB); if (this.endcaps == 3 || dzf == 0) return; this.xEndcap = this.xA; this.yEndcap = this.yA; this.zEndcap = this.zA; var shadesEndcap; var dxf = (isFloat ? this.dxBf : this.dxB); var dyf = (isFloat ? this.dyBf : this.dyB); if (dzf >= 0 || !tCylinder) { this.endcapShadeIndex = this.shader.getShadeIndex (-dxf, -dyf, dzf); this.colixEndcap = this.colixA; shadesEndcap = this.shadesA; } else { this.endcapShadeIndex = this.shader.getShadeIndex (dxf, dyf, -dzf); this.colixEndcap = this.colixB; shadesEndcap = this.shadesB; this.xEndcap += this.dxB; this.yEndcap += this.dyB; this.zEndcap += this.dzB; }if (this.endcapShadeIndex > J.util.Shader.shadeIndexNoisyLimit) this.endcapShadeIndex = J.util.Shader.shadeIndexNoisyLimit; this.argbEndcap = shadesEndcap[this.endcapShadeIndex]; this.tEndcapOpen = (this.endcaps == 1); }, $fz.isPrivate = true, $fz), "~B,~B"); });
DeepLit/WHG
root/static/js/jsmol/j2s/J/g3d/CylinderRenderer.js
JavaScript
apache-2.0
22,042
const fetch = require('node-fetch'); const listen = require('test-listen'); const qs = require('querystring'); const { createServerWithHelpers } = require('../dist/helpers'); const mockListener = jest.fn(); const consumeEventMock = jest.fn(); const mockBridge = { consumeEvent: consumeEventMock }; let server; let url; async function fetchWithProxyReq(_url, opts = {}) { if (opts.body) { // eslint-disable-next-line opts = { ...opts, body: Buffer.from(opts.body) }; } consumeEventMock.mockImplementationOnce(() => opts); return fetch(_url, { ...opts, headers: { ...opts.headers, 'x-now-bridge-request-id': '2' }, }); } beforeEach(async () => { mockListener.mockClear(); consumeEventMock.mockClear(); mockListener.mockImplementation((req, res) => { res.send('hello'); }); consumeEventMock.mockImplementation(() => ({})); server = createServerWithHelpers(mockListener, mockBridge); url = await listen(server); }); afterEach(async () => { await server.close(); }); describe('contract with @now/node-bridge', () => { test('should call consumeEvent with the correct reqId', async () => { await fetchWithProxyReq(`${url}/`); expect(consumeEventMock).toHaveBeenLastCalledWith('2'); }); test('should not expose the request id header', async () => { await fetchWithProxyReq(`${url}/`, { headers: { 'x-test-header': 'ok' } }); const [{ headers }] = mockListener.mock.calls[0]; expect(headers['x-now-bridge-request-id']).toBeUndefined(); expect(headers['x-test-header']).toBe('ok'); }); }); describe('all helpers', () => { const nowHelpers = [ ['query', 0], ['cookies', 0], ['body', 0], ['status', 1], ['redirect', 1], ['send', 1], ['json', 1], ]; test('should not recalculate req properties twice', async () => { const spy = jest.fn(() => {}); const nowReqHelpers = nowHelpers.filter(([, i]) => i === 0); mockListener.mockImplementation((req, res) => { spy(...nowReqHelpers.map(h => req[h])); spy(...nowReqHelpers.map(h => req[h])); res.end(); }); await fetchWithProxyReq(`${url}/?who=bill`, { method: 'POST', body: JSON.stringify({ who: 'mike' }), headers: { 'content-type': 'application/json', cookie: 'who=jim' }, }); // here we test that bodySpy is called twice with exactly the same arguments for (let i = 0; i < 3; i += 1) { expect(spy.mock.calls[0][i]).toBe(spy.mock.calls[1][i]); } }); test('should be able to overwrite request properties', async () => { const spy = jest.fn(() => {}); mockListener.mockImplementation((...args) => { nowHelpers.forEach(([prop, n]) => { /* eslint-disable */ args[n][prop] = 'ok'; args[n][prop] = 'ok2'; spy(args[n][prop]); }); args[1].end(); }); await fetchWithProxyReq(url); nowHelpers.forEach((_, i) => expect(spy.mock.calls[i][0]).toBe('ok2')); }); test('should be able to reconfig request properties', async () => { const spy = jest.fn(() => {}); mockListener.mockImplementation((...args) => { nowHelpers.forEach(([prop, n]) => { // eslint-disable-next-line Object.defineProperty(args[n], prop, { value: 'ok' }); Object.defineProperty(args[n], prop, { value: 'ok2' }); spy(args[n][prop]); }); args[1].end(); }); await fetchWithProxyReq(url); nowHelpers.forEach((_, i) => expect(spy.mock.calls[i][0]).toBe('ok2')); }); }); describe('req.query', () => { test('req.query should reflect querystring in the url', async () => { await fetchWithProxyReq(`${url}/?who=bill&where=us`); expect(mockListener.mock.calls[0][0].query).toMatchObject({ who: 'bill', where: 'us', }); }); test('req.query should turn multiple params with same name into an array', async () => { await fetchWithProxyReq(`${url}/?a=2&a=1`); expect(mockListener.mock.calls[0][0].query).toMatchObject({ a: ['2', '1'], }); }); test('req.query should be {} when there is no querystring', async () => { await fetchWithProxyReq(url); const [{ query }] = mockListener.mock.calls[0]; expect(Object.keys(query).length).toBe(0); }); }); describe('req.cookies', () => { test('req.cookies should reflect req.cookie header', async () => { await fetchWithProxyReq(url, { headers: { cookie: 'who=bill; where=us', }, }); expect(mockListener.mock.calls[0][0].cookies).toMatchObject({ who: 'bill', where: 'us', }); }); }); describe('req.body', () => { test('req.body should be undefined by default', async () => { await fetchWithProxyReq(url); expect(mockListener.mock.calls[0][0].body).toBe(undefined); }); test('req.body should be undefined if content-type is not defined', async () => { await fetchWithProxyReq(url, { method: 'POST', body: 'hello', }); expect(mockListener.mock.calls[0][0].body).toBe(undefined); }); test('req.body should be a string when content-type is `text/plain`', async () => { await fetchWithProxyReq(url, { method: 'POST', body: 'hello', headers: { 'content-type': 'text/plain' }, }); expect(mockListener.mock.calls[0][0].body).toBe('hello'); }); test('req.body should be a buffer when content-type is `application/octet-stream`', async () => { await fetchWithProxyReq(url, { method: 'POST', body: 'hello', headers: { 'content-type': 'application/octet-stream' }, }); const [{ body }] = mockListener.mock.calls[0]; const str = body.toString(); expect(Buffer.isBuffer(body)).toBe(true); expect(str).toBe('hello'); }); test('req.body should be an object when content-type is `application/x-www-form-urlencoded`', async () => { const obj = { who: 'mike' }; await fetchWithProxyReq(url, { method: 'POST', body: qs.encode(obj), headers: { 'content-type': 'application/x-www-form-urlencoded' }, }); expect(mockListener.mock.calls[0][0].body).toMatchObject(obj); }); test('req.body should be an object when content-type is `application/json`', async () => { const json = { who: 'bill', where: 'us', }; await fetchWithProxyReq(url, { method: 'POST', body: JSON.stringify(json), headers: { 'content-type': 'application/json' }, }); expect(mockListener.mock.calls[0][0].body).toMatchObject(json); }); test('should work when body is empty and content-type is `application/json`', async () => { mockListener.mockImplementation((req, res) => { console.log(req.body); res.end(); }); const res = await fetchWithProxyReq(url, { method: 'POST', body: '', headers: { 'content-type': 'application/json' }, }); expect(res.status).toBe(200); expect(res.body).toMatchObject({}); }); test('should be able to try/catch parse errors', async () => { const bodySpy = jest.fn(() => {}); mockListener.mockImplementation((req, res) => { try { if (req.body === undefined) res.status(400); } catch (error) { bodySpy(error); } finally { res.end(); } }); await fetchWithProxyReq(url, { method: 'POST', body: '{"wrong":"json"', headers: { 'content-type': 'application/json' }, }); expect(bodySpy).toHaveBeenCalled(); const [error] = bodySpy.mock.calls[0]; expect(error.message).toMatch(/invalid json/i); expect(error.statusCode).toBe(400); }); }); describe('res.status', () => { test('res.status() should set the status code', async () => { mockListener.mockImplementation((req, res) => { res.status(404); res.end(); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(404); }); test('res.status() should be chainable', async () => { const spy = jest.fn(); mockListener.mockImplementation((req, res) => { spy(res, res.status(404)); res.end(); }); await fetchWithProxyReq(url); const [a, b] = spy.mock.calls[0]; expect(a).toBe(b); }); }); describe('res.redirect', () => { test('should redirect to login', async () => { mockListener.mockImplementation((req, res) => { res.redirect('/login'); res.end(); }); const res = await fetchWithProxyReq(url, { redirect: 'manual' }); expect(res.status).toBe(307); expect(res.headers.get('location')).toBe(url + '/login'); }); test('should redirect with status code 301', async () => { mockListener.mockImplementation((req, res) => { res.redirect(301, '/login'); res.end(); }); const res = await fetchWithProxyReq(url, { redirect: 'manual' }); expect(res.status).toBe(301); expect(res.headers.get('location')).toBe(url + '/login'); }); test('should show friendly error for invalid redirect', async () => { let error; mockListener.mockImplementation((req, res) => { try { res.redirect(307); } catch (err) { error = err; } res.end(); }); await fetchWithProxyReq(url, { redirect: 'manual' }); expect(error.message).toBe( `Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').` ); }); test('should show friendly error in case of passing null as first argument redirect', async () => { let error; mockListener.mockImplementation((req, res) => { try { res.redirect(null); } catch (err) { error = err; } res.end(); }); await fetchWithProxyReq(url, { redirect: 'manual' }); expect(error.message).toBe( `Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').` ); }); }); // tests based on expressjs test suite // see https://github.com/expressjs/express/blob/master/test/res.send.js describe('res.send', () => { test('should be chainable', async () => { const spy = jest.fn(); mockListener.mockImplementation((req, res) => { spy(res, res.send('hello')); }); await fetchWithProxyReq(url); const [a, b] = spy.mock.calls[0]; expect(a).toBe(b); }); describe('res.send()', () => { test('should set body to ""', async () => { mockListener.mockImplementation((req, res) => { res.send(); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(await res.text()).toBe(''); }); }); describe('.send(null)', () => { test('should set body to ""', async () => { mockListener.mockImplementation((req, res) => { res.send(null); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-length')).toBe('0'); expect(await res.text()).toBe(''); }); }); describe('.send(undefined)', () => { test('should set body to ""', async () => { mockListener.mockImplementation((req, res) => { res.send(undefined); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(await res.text()).toBe(''); }); }); describe('.send(String)', () => { test('should send as html', async () => { mockListener.mockImplementation((req, res) => { res.send('<p>hey</p>'); }); const res = await fetchWithProxyReq(url); expect(res.headers.get('content-type')).toBe('text/html; charset=utf-8'); expect(await res.text()).toBe('<p>hey</p>'); }); test('should set Content-Length', async () => { mockListener.mockImplementation((req, res) => { res.send('½ + ¼ = ¾'); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(Number(res.headers.get('content-length'))).toBe(12); expect(await res.text()).toBe('½ + ¼ = ¾'); }); test('should set ETag', async () => { mockListener.mockImplementation((req, res) => { res.send(Array(1000).join('-')); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('ETag')).toBe( 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"' ); }); test('should not override Content-Type', async () => { mockListener.mockImplementation((req, res) => { res.setHeader('Content-Type', 'text/plain'); res.send('hey'); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8'); expect(await res.text()).toBe('hey'); }); test('should override charset in Content-Type', async () => { mockListener.mockImplementation((req, res) => { res.setHeader('Content-Type', 'text/plain; charset=iso-8859-1'); res.send('hey'); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8'); expect(await res.text()).toBe('hey'); }); }); describe('.send(Buffer)', () => { test('should keep charset in Content-Type', async () => { mockListener.mockImplementation((req, res) => { res.setHeader('Content-Type', 'text/plain; charset=iso-8859-1'); res.send(Buffer.from('hi')); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('Content-Type')).toBe( 'text/plain; charset=iso-8859-1' ); expect(await res.text()).toBe('hi'); }); test('should set Content-Length', async () => { mockListener.mockImplementation((req, res) => { res.send(Buffer.from('½ + ¼ = ¾')); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(Number(res.headers.get('content-length'))).toBe(12); expect(await res.text()).toBe('½ + ¼ = ¾'); }); test('should send as octet-stream', async () => { mockListener.mockImplementation((req, res) => { res.send(Buffer.from('hello')); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('Content-Type')).toBe('application/octet-stream'); expect((await res.buffer()).toString('hex')).toBe( Buffer.from('hello').toString('hex') ); }); test('should set ETag', async () => { mockListener.mockImplementation((req, res) => { res.send(Buffer.alloc(999, '-')); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('ETag')).toBe( 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"' ); }); test('should not override Content-Type', async () => { mockListener.mockImplementation((req, res) => { res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.send(Buffer.from('hey')); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8'); expect(await res.text()).toBe('hey'); }); test('should not override ETag', async () => { mockListener.mockImplementation((req, res) => { res.setHeader('ETag', '"foo"'); res.send(Buffer.from('hey')); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('ETag')).toBe('"foo"'); expect(await res.text()).toBe('hey'); }); }); describe('.send(Object)', () => { test('should send as application/json', async () => { mockListener.mockImplementation((req, res) => { res.send({ name: 'tobi' }); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('Content-Type')).toBe( 'application/json; charset=utf-8' ); expect(await res.text()).toBe('{"name":"tobi"}'); }); }); describe('when the request method is HEAD', () => { test('should ignore the body', async () => { mockListener.mockImplementation((req, res) => { res.send('yay'); }); // TODO: fix this test // node-fetch is automatically ignoring the body so this test will never fail const res = await fetchWithProxyReq(url, { method: 'HEAD' }); expect(res.status).toBe(200); expect((await res.buffer()).toString()).toBe(''); }); }); describe('when .statusCode is 204', () => { test('should strip Content-* fields, Transfer-Encoding field, and body', async () => { mockListener.mockImplementation((req, res) => { res.statusCode = 204; res.setHeader('Transfer-Encoding', 'chunked'); res.send('foo'); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(204); expect(res.headers.get('Content-Type')).toBe(null); expect(res.headers.get('Content-Length')).toBe(null); expect(res.headers.get('Transfer-Encoding')).toBe(null); expect(await res.text()).toBe(''); }); }); describe('when .statusCode is 304', () => { test('should strip Content-* fields, Transfer-Encoding field, and body', async () => { mockListener.mockImplementation((req, res) => { res.statusCode = 304; res.setHeader('Transfer-Encoding', 'chunked'); res.send('foo'); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(304); expect(res.headers.get('Content-Type')).toBe(null); expect(res.headers.get('Content-Length')).toBe(null); expect(res.headers.get('Transfer-Encoding')).toBe(null); expect(await res.text()).toBe(''); }); }); // test('should always check regardless of length', async () => { // const etag = '"asdf"'; // mockListener.mockImplementation((req, res) => { // res.setHeader('ETag', etag); // res.send('hey'); // }); // const res = await fetchWithProxyReq(url, { // headers: { 'If-None-Match': etag }, // }); // expect(res.status).toBe(304); // }); // test('should respond with 304 Not Modified when fresh', async () => { // const etag = '"asdf"'; // mockListener.mockImplementation((req, res) => { // res.setHeader('ETag', etag); // res.send(Array(1000).join('-')); // }); // const res = await fetchWithProxyReq(url, { // headers: { 'If-None-Match': etag }, // }); // expect(res.status).toBe(304); // }); // test('should not perform freshness check unless 2xx or 304', async () => { // const etag = '"asdf"'; // mockListener.mockImplementation((req, res) => { // res.status(500); // res.setHeader('ETag', etag); // res.send('hey'); // }); // const res = await fetchWithProxyReq(url, { // headers: { 'If-None-Match': etag }, // }); // expect(res.status).toBe(500); // expect(await res.text()).toBe('hey'); // }); describe('etag', () => { test('should send ETag', async () => { mockListener.mockImplementation((req, res) => { res.send('kajdslfkasdf'); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('ETag')).toBe('W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"'); }); test('should send ETag for empty string response', async () => { mockListener.mockImplementation((req, res) => { res.send(''); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('ETag')).toBe('W/"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'); }); test('should send ETag for long response', async () => { mockListener.mockImplementation((req, res) => { res.send(Array(1000).join('-')); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('ETag')).toBe( 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"' ); }); test('should not override ETag when manually set', async () => { mockListener.mockImplementation((req, res) => { res.setHeader('etag', '"asdf"'); res.send('hello'); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('ETag')).toBe('"asdf"'); }); test('should not send ETag for res.send()', async () => { mockListener.mockImplementation((req, res) => { res.send(); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('ETag')).toBe(null); }); }); }); // tests based on expressjs test suite // see https://github.com/expressjs/express/blob/master/test/res.json.js describe('res.json', () => { test('should send be chainable', async () => { const spy = jest.fn(); mockListener.mockImplementation((req, res) => { spy(res, res.json({ hello: 'world' })); }); await fetchWithProxyReq(url); const [a, b] = spy.mock.calls[0]; expect(a).toBe(b); }); test('res.json() should send an empty body', async () => { mockListener.mockImplementation((req, res) => { res.json(); }); await fetchWithProxyReq(url); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe( 'application/json; charset=utf-8' ); expect(await res.text()).toBe(''); }); describe('.json(object)', () => { test('should not override previous Content-Types', async () => { mockListener.mockImplementation((req, res) => { res.setHeader('content-type', 'application/vnd.example+json'); res.json({ hello: 'world' }); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe( 'application/vnd.example+json; charset=utf-8' ); expect(await res.text()).toBe('{"hello":"world"}'); }); test('should set Content-Length and Content-Type', async () => { mockListener.mockImplementation((req, res) => { res.json({ hello: '½ + ¼ = ¾' }); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe( 'application/json; charset=utf-8' ); expect(Number(res.headers.get('content-length'))).toBe(24); expect(await res.text()).toBe('{"hello":"½ + ¼ = ¾"}'); }); describe('when given primitives', () => { test('should respond with json for null', async () => { mockListener.mockImplementation((req, res) => { res.json(null); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe( 'application/json; charset=utf-8' ); expect(await res.text()).toBe('null'); }); test('should respond with json for Number', async () => { mockListener.mockImplementation((req, res) => { res.json(300); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe( 'application/json; charset=utf-8' ); expect(await res.text()).toBe('300'); }); test('should respond with json for String', async () => { mockListener.mockImplementation((req, res) => { res.json('str'); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe( 'application/json; charset=utf-8' ); expect(await res.text()).toBe('"str"'); }); }); test('should respond with json when given an array', async () => { mockListener.mockImplementation((req, res) => { res.json(['foo', 'bar', 'baz']); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe( 'application/json; charset=utf-8' ); expect(await res.text()).toBe('["foo","bar","baz"]'); }); test('should respond with json when given an object', async () => { mockListener.mockImplementation((req, res) => { res.json({ name: 'tobi' }); }); const res = await fetchWithProxyReq(url); expect(res.status).toBe(200); expect(res.headers.get('content-type')).toBe( 'application/json; charset=utf-8' ); expect(await res.text()).toBe('{"name":"tobi"}'); }); }); });
zeit/now-cli
packages/now-node/test/helpers.test.js
JavaScript
apache-2.0
25,042
'use strict'; angular.module('app.controllers') .controller('HomeCtrl', function($scope, $http, $state,tree, $localStorage) { var treeArray = tree.data; console.log(treeArray.length); $scope.user = $localStorage.user; $scope.logout = function() { delete $localStorage.user; delete $localStorage.token; $state.go('access.signin'); } $scope.arrayContains = function (arr,str) { for (var k = 0; k < arr.length; k++) { if(arr[k] == str){ return k; }else{ console.log(arr[k]); if (typeof arr[k].label != 'undefined'){ if(arr[k].label == str){ return k; } } } }; return -1; }; var tree = []; $scope.fillTree = function (steps) { var lvl1 = steps[0]; var lvl2 = steps[1]; var lvl3 = steps[2]; var lvl4 = steps[3]; var current = null; var nivelMeter=''; var existing = null; if(lvl2 == null){ tree.push(lvl1+''); console.log("NIVEEEEEEEEEL1 --"+ lvl1) }else{ var pos = $scope.arrayContains(tree,lvl1); if(pos>-1){ if(typeof tree[pos].children == null){ tree[pos] = {label: lvl1, children:[]}; current = tree[pos].children; } current = tree[pos].children; if(lvl3 == null){ current.push(lvl2); }else{ var pos2 = $scope.arrayContains(current,lvl2); if(typeof current[pos2].children == null){ current[pos2] = {label: lvl2, children:[]}; current = current[pos2].children; } current = current[pos2].children; current.push(lvl3); } }else{ tree.push({label: lvl1, children:[]}); var pos = $scope.arrayContains(tree,lvl1); current = tree[pos].children; if(lvl3 == null){ current.push(lvl2); }else{ if(lvl4 ==null){ current.push({label: lvl2, children:[lvl3]}); }else{ current.push({label: lvl2, children:[{label: lvl3, children:[lvl4]}]}); } } } } } for (var x=0; x < treeArray.length; x++) { var steps = [treeArray[x].lev1,treeArray[x].lev2,treeArray[x].lev3,treeArray[x].lev4]; console.log(steps); $scope.fillTree(steps); } console.log(tree); //$scope.my_data = tree; $scope.my_data = [{ label: 'Proyectos', children: tree }]; //console.log($scope.my_data2); //$scope.my_data = $scope.my_data2; });
salvadoracosta/SS
client/app/home/home.controller.js
JavaScript
apache-2.0
3,046
import { setPropertiesFromJSON } from '../../json-helper'; import QuestionAnswer from '../finding/QuestionAnswer'; /** * Generated class for shr.sex.ContraceptiveMethodUsed. * @extends QuestionAnswer */ class ContraceptiveMethodUsed extends QuestionAnswer { /** * Get the entry information. * @returns {Entry} The shr.base.Entry */ get entryInfo() { return this._entryInfo; } /** * Set the entry information. * @param {Entry} entryInfo - The shr.base.Entry */ set entryInfo(entryInfo) { this._entryInfo = entryInfo; } /** * Get the value (aliases codeableConcept). * @returns {CodeableConcept} The shr.core.CodeableConcept */ get value() { return this._codeableConcept; } /** * Set the value (aliases codeableConcept). * @param {CodeableConcept} value - The shr.core.CodeableConcept */ set value(value) { this._codeableConcept = value; } /** * Get the CodeableConcept. * @returns {CodeableConcept} The shr.core.CodeableConcept */ get codeableConcept() { return this._codeableConcept; } /** * Set the CodeableConcept. * @param {CodeableConcept} codeableConcept - The shr.core.CodeableConcept */ set codeableConcept(codeableConcept) { this._codeableConcept = codeableConcept; } /** * Get the ObservationCode. * @returns {ObservationCode} The shr.finding.ObservationCode */ get observationCode() { return this._observationCode; } /** * Set the ObservationCode. * @param {ObservationCode} observationCode - The shr.finding.ObservationCode */ set observationCode(observationCode) { this._observationCode = observationCode; } /** * Get the ObservationComponent array. * @returns {Array<ObservationComponent>} The shr.finding.ObservationComponent array */ get observationComponent() { return this._observationComponent; } /** * Set the ObservationComponent array. * @param {Array<ObservationComponent>} observationComponent - The shr.finding.ObservationComponent array */ set observationComponent(observationComponent) { this._observationComponent = observationComponent; } /** * Deserializes JSON data to an instance of the ContraceptiveMethodUsed class. * The JSON must be valid against the ContraceptiveMethodUsed JSON schema, although this is not validated by the function. * @param {object} json - the JSON data to deserialize * @returns {ContraceptiveMethodUsed} An instance of ContraceptiveMethodUsed populated with the JSON data */ static fromJSON(json={}) { const inst = new ContraceptiveMethodUsed(); setPropertiesFromJSON(inst, json); return inst; } } export default ContraceptiveMethodUsed;
standardhealth/flux
src/model/shr/sex/ContraceptiveMethodUsed.js
JavaScript
apache-2.0
2,735
(function() {var implementors = {}; implementors["tokio_http2"] = ["impl <a class='trait' href='https://docs.serde.rs/serde/ser/trait.Serialize.html' title='serde::ser::Serialize'>Serialize</a> for Value",]; if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })()
lambdastackio/tokio-http2
docs/implementors/serde/ser/trait.Serialize.js
JavaScript
apache-2.0
426
OC.L10N.register( "settings", { "Cron" : "Крон", "Sharing" : "Споделување", "Security" : "Безбедност", "Email Server" : "Сервер за електронска пошта", "Log" : "Записник", "Authentication error" : "Грешка во автентикација", "Your full name has been changed." : "Вашето целосно име е променето.", "Unable to change full name" : "Не можам да го променам целото име", "Files decrypted successfully" : "Датотектие се успешно декриптирани", "Encryption keys deleted permanently" : "Енкрипциските клучеви се трајно избришани", "Backups restored successfully" : "Бекапите се успешно реставрирани", "Language changed" : "Јазикот е сменет", "Invalid request" : "Неправилно барање", "Admins can't remove themself from the admin group" : "Администраторите неможе да се избришат себеси од админ групата", "Unable to add user to group %s" : "Неможе да додадам корисник во група %s", "Unable to remove user from group %s" : "Неможе да избришам корисник од група %s", "Couldn't update app." : "Не можам да ја надградам апликацијата.", "Wrong password" : "Погрешна лозинка", "No user supplied" : "Нема корисничко име", "Unable to change password" : "Вашата лозинка неможе да се смени", "Enabled" : "Овозможен", "Saved" : "Снимено", "test email settings" : "провери ги нагодувањата за електронска пошта", "Email sent" : "Е-порака пратена", "Email saved" : "Електронската пошта е снимена", "Sending..." : "Испраќам...", "All" : "Сите", "Please wait...." : "Ве молам почекајте ...", "Error while disabling app" : "Грешка при исклучувањето на апликацијата", "Disable" : "Оневозможи", "Enable" : "Овозможи", "Error while enabling app" : "Грешка при вклучувањето на апликацијата", "Updating...." : "Надградувам ...", "Error while updating app" : "Грешка додека ја надградувам апликацијата", "Updated" : "Надграден", "Select a profile picture" : "Одбери фотографија за профилот", "Very weak password" : "Многу слаба лозинка", "Weak password" : "Слаба лозинка", "So-so password" : "Така така лозинка", "Good password" : "Добра лозинка", "Strong password" : "Јака лозинка", "Delete" : "Избриши", "Delete encryption keys permanently." : "Трајно бришење на енкрипциските клучеви.", "Restore encryption keys." : "Поврати ги енкрипцисиките клучеви.", "Groups" : "Групи", "Error creating group" : "Грешка при креирање на група", "A valid group name must be provided" : "Мора да се обезбеди валидно име на група", "undo" : "врати", "never" : "никогаш", "add group" : "додади група", "A valid username must be provided" : "Мора да се обезбеди валидно корисничко име ", "Error creating user" : "Грешка при креирање на корисникот", "A valid password must be provided" : "Мора да се обезбеди валидна лозинка", "__language_name__" : "__language_name__", "SSL root certificates" : "SSL root сертификати", "Encryption" : "Енкрипција", "Info, warnings, errors and fatal issues" : "Информации, предупредувања, грешки и фатални работи", "Warnings, errors and fatal issues" : "Предупредувања, грешки и фатални работи", "Errors and fatal issues" : "Грешки и фатални работи", "Fatal issues only" : "Само фатални работи", "None" : "Ништо", "Login" : "Најава", "Plain" : "Чиста", "NT LAN Manager" : "NT LAN Менаџер", "SSL" : "SSL", "TLS" : "TLS", "Security Warning" : "Безбедносно предупредување", "Setup Warning" : "Предупредување при подесување", "Database Performance Info" : "Информација за перформансите на базата на податоци", "Locale not working" : "Локалето не функционира", "Execute one task with each page loaded" : "Изврши по една задача со секоја вчитана страница", "Allow apps to use the Share API" : "Дозволете апликациите да го користат API-то за споделување", "Allow users to share via link" : "Допушти корисниците да споделуваат со линкови", "Enforce password protection" : "Наметни заштита на лозинка", "Allow public uploads" : "Дозволи јавен аплоуд", "Set default expiration date" : "Постави основен датум на истекување", "Expire after " : "Истекува по", "days" : "денови", "Enforce expiration date" : "Наметни датум на траење", "Allow resharing" : "Овозможи повторно споделување", "Restrict users to only share with users in their groups" : "Ограничи корисниците да споделуваат со корисници во своите групи", "Exclude groups from sharing" : "Исклучи групи од споделување", "Enforce HTTPS" : "Наметни HTTPS", "This is used for sending out notifications." : "Ова се користи за испраќање на известувања.", "Send mode" : "Мод на испраќање", "From address" : "Од адреса", "mail" : "Електронска пошта", "Authentication method" : "Метод на автентификација", "Authentication required" : "Потребна е автентификација", "Server address" : "Адреса на сервер", "Port" : "Порта", "Credentials" : "Акредитиви", "SMTP Username" : "SMTP корисничко име", "SMTP Password" : "SMTP лозинка", "Test email settings" : "Провери ги нагодувањаа за електронска пошта", "Send email" : "Испрати пошта", "Log level" : "Ниво на логирање", "More" : "Повеќе", "Less" : "Помалку", "Version" : "Верзија", "Developed by the <a href=\"http://ownCloud.org/contact\" target=\"_blank\">ownCloud community</a>, the <a href=\"https://github.com/owncloud\" target=\"_blank\">source code</a> is licensed under the <a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" target=\"_blank\"><abbr title=\"Affero General Public License\">AGPL</abbr></a>." : "Развој од <a href=\"http://ownCloud.org/contact\" target=\"_blank\">ownCloud заедницата</a>, <a href=\"https://github.com/owncloud\" target=\"_blank\">изворниот код</a> е лиценциран со<a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" target=\"_blank\"><abbr title=\"Affero General Public License\">AGPL</abbr></a>.", "by" : "од", "Documentation:" : "Документација:", "User Documentation" : "Корисничка документација", "Admin Documentation" : "Админстраторска документација", "Enable only for specific groups" : "Овозможи само на специфицирани групи", "Cheers!" : "Поздрав!", "Administrator Documentation" : "Администраторска документација", "Online Documentation" : "Документација на интернет", "Forum" : "Форум", "Bugtracker" : "Тракер на грешки", "Commercial Support" : "Комерцијална подршка", "Get the apps to sync your files" : "Преземете апликации за синхронизирање на вашите датотеки", "Show First Run Wizard again" : "Прикажи го повторно волшебникот при првото стартување", "You have used <strong>%s</strong> of the available <strong>%s</strong>" : "Имате искористено <strong>%s</strong> од достапните <strong>%s</strong>", "Password" : "Лозинка", "Your password was changed" : "Вашата лозинка беше променета.", "Unable to change your password" : "Вашата лозинка неможе да се смени", "Current password" : "Моментална лозинка", "New password" : "Нова лозинка", "Change password" : "Смени лозинка", "Full Name" : "Цело име", "Email" : "Е-пошта", "Your email address" : "Вашата адреса за е-пошта", "Profile picture" : "Фотографија за профил", "Upload new" : "Префрли нова", "Select new from Files" : "Одбери нова од датотеките", "Remove image" : "Отстрани ја фотографијата", "Either png or jpg. Ideally square but you will be able to crop it." : "Мора де биде png или jpg. Идеално квадрат, но ќе бидете во можност да ја исечете.", "Your avatar is provided by your original account." : "Вашиот аватар е креиран со вашата оригинална сметка", "Cancel" : "Откажи", "Choose as profile image" : "Одбери фотографија за профилот", "Language" : "Јазик", "Help translate" : "Помогни во преводот", "Import Root Certificate" : "Увези", "Log-in password" : "Лозинка за најавување", "Decrypt all Files" : "Дешифрирај ги сите датотеки", "Restore Encryption Keys" : "Обнови ги енкрипциските клучеви", "Delete Encryption Keys" : "Избриши ги енкрипцисиките клучеви", "Username" : "Корисничко име", "Create" : "Создај", "Admin Recovery Password" : "Обновување на Admin лозинката", "Add Group" : "Додади група", "Group" : "Група", "Everyone" : "Секој", "Admins" : "Администратори", "Default Quota" : "Предефинирана квота", "Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Ве молам внесете квота за просторот (нпр: \"512 MB\" или \"12 GB\")", "Unlimited" : "Неограничено", "Other" : "Останато", "Quota" : "Квота", "Storage Location" : "Локација на сториџот", "Last Login" : "Последна најава", "change full name" : "промена на целото име", "set new password" : "постави нова лозинка", "Default" : "Предефиниран" }, "nplurals=2; plural=(n % 10 == 1 && n % 100 != 11) ? 0 : 1;");
kebenxiaoming/owncloudRedis
settings/l10n/mk.js
JavaScript
apache-2.0
12,020
var gulp = require("gulp"), less = require("gulp-less"), minify = require("gulp-minify-css"), streamify = require("gulp-streamify"), uglify = require("gulp-uglify"); function logError(err) { console.log(err); this.emit("end"); } gulp.task("watch", function() { gulp.watch(__dirname + "/assets/*.less", ["styles"]); gulp.watch(__dirname + "/assets/*.js", ["scripts"]); }); gulp.task("styles", function() { return gulp.src(__dirname + "/assets/*.less") .on("error", logError) .pipe(less()) .pipe(minify()) .pipe(gulp.dest("public")); }); gulp.task("scripts", function() { return gulp.src(__dirname + "/assets/*.js") .on("error", logError) .pipe(streamify(uglify())) .pipe(gulp.dest("public")); }); gulp.task("default", ["styles", "scripts"]); gulp.task("dev", ["default", "watch"]);
montyanderson/sms-ui
gulpfile.js
JavaScript
apache-2.0
882
define(['angularAMD', 'factory_issue', 'constant_actionState', 'value_entity', 'ui-grid-js', 'ui-grid-custom-rowSelection'], function (angularAMD) { angularAMD.processQueue(); angularAMD.directive('tableDir', ['issueFactory', '$timeout', 'actionState', 'entity', '$q', '$http', function (issueFactory, $timeout, actionState, entity, $q, $http) { return { restrict: "E", scope: { action: "=", }, template: function (element, attrs) { return '<div ui-grid="gridOptions" class="grid" ui-grid-selection ui-grid-infinite-scroll></div>'; }, link: function (scope, element, attrs) { //scope.tableData = [{ Id: 1, Name: "UI" }]; scope.showTable = false; }, controller: function ($scope) { $scope.updateAct = function (id) { entity.Id = id; $scope.$parent.setAction(actionState.Update); }; $scope.deleteAct = function (id) { if (confirm("Do you want to delete this item?")) { $scope.$parent.setAction(actionState.Delete); issueFactory.delete({ id: id }, function () { $scope.$parent.setAction(actionState.Refresh); }); } }; $scope.$watch('action', function (nVal, oVal) { if (nVal == actionState.Refresh) { $scope.defaultValue(); $scope.getFirstData(); $scope.$parent.setAction(actionState.Add); } }); $scope.gridOptions = { appScopeProvider: $scope, infiniteScrollRowsFromEnd: 20, infiniteScrollUp: false, infiniteScrollDown: true, enableRowSelection: false, enableRowHeaderSelection: true, multiSelect: true, columnDefs: [ { name: 'Id' }, { name: 'Name' }, { name: ' ', cellTemplate: '<a href="javascript:void(0);" ng-click="grid.appScope.updateAct(row.entity.Id)">Update</a> | <a href="javascript:void(0);" ng-click="grid.appScope.deleteAct(row.entity.Id)">Delete</a>' } ], data: 'data', onRegisterApi: function (gridApi) { gridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.getDataDown); gridApi.infiniteScroll.on.needLoadMoreDataTop($scope, function() { gridApi.infiniteScroll.dataLoaded(); }); $scope.gridApi = gridApi; } }; $scope.getLink = function (skip, top) { return 'http://localhost:52726/odata/issues?$count=true&$skip=' + skip + '&top=' + top; } $scope.data = []; $scope.total = 0; $scope.skip = 0; $scope.top = 20; $scope.prelink = ''; $scope.curlink = $scope.getLink($scope.skip, $scope.top); $scope.nextlink = ''; $scope.defaultValue = function () { $scope.data = []; $scope.total = 0; $scope.skip = 0; $scope.top = 20; $scope.prelink = ''; $scope.curlink = $scope.getLink($scope.skip, $scope.top); $scope.nextlink = ''; } $scope.getFirstData = function () { var promise = $q.defer(); $http.get($scope.curlink) .success(function (data) { $scope.total = parseInt(data["@odata.count"]); $scope.skip += $scope.top; $scope.nextlink = $scope.getLink($scope.skip, $scope.top); $scope.data = $scope.data.concat(data.value); promise.resolve(); }); return promise.promise; }; $scope.getDataDown = function () { var promise = $q.defer(); $http.get($scope.nextlink) .success(function (data) { $scope.total = parseInt(data["@odata.count"]); $scope.skip += $scope.top; $scope.prelink = $scope.curlink; $scope.curlink = $scope.nextlink; $scope.nextlink = $scope.getLink($scope.skip, $scope.top); $scope.gridApi.infiniteScroll.saveScrollPercentage(); $scope.data = $scope.data.concat(data.value); $scope.gridApi.infiniteScroll.dataLoaded($scope.skip > 0, $scope.skip < $scope.total).then(function () { }).then(function () { promise.resolve(); }); }) .error(function (error) { $scope.gridApi.infiniteScroll.dataLoaded(); promise.reject(); }); return promise.promise; }; $scope.checkDataLength = function (discardDirection) { // work out whether we need to discard a page, if so discard from the direction passed in console.log($scope.skip, $scope.total); if ($scope.skip >= $scope.total) { // we want to remove a page $scope.gridApi.infiniteScroll.saveScrollPercentage(); if (discardDirection === 'up') { $scope.data = $scope.data.slice(100); $scope.firstPage++; $timeout(function () { // wait for grid to ingest data changes $scope.gridApi.infiniteScroll.dataRemovedTop($scope.skip >= 0, $scope.skip < $scope.total); }); } else { $scope.data = $scope.data.slice(0, 400); $scope.lastPage--; $timeout(function () { // wait for grid to ingest data changes $scope.gridApi.infiniteScroll.dataRemovedBottom($scope.skip > 0, $scope.skip < $scope.total); }); } } }; $scope.getFirstData(); } } }]); });
vknvnn/requirejs
Demo/apps/directives/issue/tableDirective.js
JavaScript
apache-2.0
7,119
/* @flow */ import React, {Component} from 'react'; import {List} from 'immutable'; import type {Report} from '../types/Report'; import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; import FontIcon from 'material-ui/FontIcon'; import {yellow500, red500, green500} from 'material-ui/styles/colors'; const styles = { table: { height: '300px' }, propToggleHeader: { margin: '20px auto 10px', }, }; type Props = { reports: List<Report>; }; class UserOverview extends Component<any, Props, void> { render() { const {reports} = this.props; return ( <div> <Table height={styles.table.height} fixedHeader={true} fixedFooter={true} selectable={false} multiSelectable={false} > <TableHeader displaySelectAll={false} adjustForCheckbox={false} enableSelectAll={false} > <TableRow> <TableHeaderColumn colSpan="4" tooltip="Current Reports" style={{textAlign: 'center'}}> Test-Reports </TableHeaderColumn> </TableRow> <TableRow> <TableHeaderColumn tooltip="The Name">Name</TableHeaderColumn> <TableHeaderColumn tooltip="What is the test about?">Description</TableHeaderColumn> <TableHeaderColumn tooltip="When was the test last executed?">Last Checked</TableHeaderColumn> <TableHeaderColumn tooltip="What was the result of that test?">Status</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false} deselectOnClickaway={false} showRowHover={true} stripedRows={true} > {reports.map(report => { const {id, name, description, timestamp, status} = report; let statusSymbol; if (status === 'OK') { statusSymbol = <FontIcon className="material-icons" color={green500}>check_circle</FontIcon>; } else if (status === 'FAIL') { statusSymbol = <FontIcon className="material-icons" color={red500}>error</FontIcon>; } else { statusSymbol = <FontIcon className="material-icons" color={yellow500}>warning</FontIcon>; } const lastExecuted = new Date(Number.parseInt(timestamp, 10)).toString(); return <TableRow key={id}> <TableRowColumn>{name}</TableRowColumn> <TableRowColumn>{description}</TableRowColumn> <TableRowColumn>{lastExecuted}</TableRowColumn> <TableRowColumn>{statusSymbol}</TableRowColumn> </TableRow>; })} </TableBody> </Table> </div> ); } } export default UserOverview;
DJCordhose/floreysoft-status
src/main/js/src/components/UserOverview.js
JavaScript
apache-2.0
3,797
/* jshint node:true */ 'use strict'; /** * Module dependencies. */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var joinRows = require('../core/join-rows'); var Handler = require('./handler'); var helper = require('../core/helper'); var Parser = function () { function Parser(options) { _classCallCheck(this, Parser); this._options = options || {}; this._handler = new Handler(this._options); this._headers = this._options.headers || []; this._escape = require('../core/escape-delimiters')(this._options.textDelimiter, this._options.rowDelimiter, this._options.forceTextDelimiter); } /** * Generates a CSV file with optional headers based on the passed JSON, * with can be an Object or Array. * * @param {Object|Array} json * @param {Function} done(err,csv) - Callback function * if error, returning error in call back. * if csv is created successfully, returning csv output to callback. */ _createClass(Parser, [{ key: 'parse', value: function parse(json, done, stream) { if (helper.isArray(json)) return done(null, this._parseArray(json, stream));else if (helper.isObject(json)) return done(null, this._parseObject(json)); return done(new Error('Unable to parse the JSON object, its not an Array or Object.')); } }, { key: '_checkRows', value: function _checkRows(rows) { var lastRow = null; var finalRows = []; var fillGaps = function fillGaps(col, index) { return col === '' || col === undefined ? lastRow[index] : col; }; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = rows[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var row = _step.value; var missing = this._headers.length - row.length; if (missing > 0) row = row.concat(Array(missing).join(".").split(".")); if (lastRow && this._options.fillGaps) row = row.map(fillGaps); finalRows.push(row.join(this._options.rowDelimiter)); lastRow = row; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return finalRows; } }, { key: '_parseArray', value: function _parseArray(json, stream) { var self = this; this._headers = this._headers || []; var fileRows = []; var outputFile = void 0; var fillRows = void 0; var getHeaderIndex = function getHeaderIndex(header) { var index = self._headers.indexOf(header); if (index === -1) { self._headers.push(header); index = self._headers.indexOf(header); } return index; }; //Generate the csv output fillRows = function fillRows(result) { var rows = []; var fillAndPush = function fillAndPush(row) { return rows.push(row.map(function (col) { return col != null ? col : ''; })); }; // initialize the array with empty strings to handle 'unpopular' headers var newRow = function newRow() { return new Array(self._headers.length).fill(null); }; var emptyRowIndexByHeader = {}; var currentRow = newRow(); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = result[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var element = _step2.value; var elementHeaderIndex = getHeaderIndex(element.item); if (currentRow[elementHeaderIndex] != undefined) { fillAndPush(currentRow); currentRow = newRow(); } emptyRowIndexByHeader[elementHeaderIndex] = emptyRowIndexByHeader[elementHeaderIndex] || 0; // make sure there isn't a empty row for this header if (self._options.fillTopRow && emptyRowIndexByHeader[elementHeaderIndex] < rows.length) { rows[emptyRowIndexByHeader[elementHeaderIndex]][elementHeaderIndex] = self._escape(element.value); emptyRowIndexByHeader[elementHeaderIndex] += 1; continue; } currentRow[elementHeaderIndex] = self._escape(element.value); emptyRowIndexByHeader[elementHeaderIndex] += 1; } // push last row } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } if (currentRow.length > 0) { fillAndPush(currentRow); } fileRows = fileRows.concat(self._checkRows(rows)); }; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = json[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var item = _step3.value; //Call checkType to list all items inside this object //Items are returned as a object {item: 'Prop Value, Item Name', value: 'Prop Data Value'} var itemResult = self._handler.check(item, self._options.mainPathItem, item, json); fillRows(itemResult); } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } if (!stream && self._options.includeHeaders) { //Add the headers to the first line fileRows.unshift(this.headers); } return joinRows(fileRows, self._options.endOfLine); } }, { key: '_parseObject', value: function _parseObject(json) { var self = this; var fileRows = []; var parseResult = []; var outputFile = void 0; var fillRows = void 0; var horizontalRows = [[], []]; fillRows = function fillRows(result) { var value = result.value || result.value === 0 ? result.value.toString() : self._options.undefinedString; value = self._escape(value); //Type header;value if (self._options.verticalOutput) { var row = [result.item, value]; fileRows.push(row.join(self._options.rowDelimiter)); } else { horizontalRows[0].push(result.item); horizontalRows[1].push(value); } }; for (var prop in json) { var prefix = ""; if (this._options.mainPathItem) prefix = this._options.mainPathItem + this._options.headerPathString; parseResult = this._handler.check(json[prop], prefix + prop, prop, json); parseResult.forEach(fillRows); } if (!this._options.verticalOutput) { fileRows.push(horizontalRows[0].join(this._options.rowDelimiter)); fileRows.push(horizontalRows[1].join(this._options.rowDelimiter)); } return joinRows(fileRows, this._options.endOfLine); } }, { key: 'headers', get: function get() { var _this = this; var headers = this._headers; if (this._options.rename && this._options.rename.length > 0) headers = headers.map(function (header) { return _this._options.rename[_this._options.headers.indexOf(header)] || header; }); if (this._options.forceTextDelimiter) { headers = headers.map(function (header) { return '' + _this._options.textDelimiter + header + _this._options.textDelimiter; }); } if (this._options.mapHeaders) headers = headers.map(this._options.mapHeaders); return headers.join(this._options.rowDelimiter); } }]); return Parser; }(); module.exports = Parser;
kauegimenes/jsonexport
dist/parser/csv.js
JavaScript
apache-2.0
9,306
// This file was automatically generated. Do not modify. 'use strict'; goog.provide('Blockly.Msg.en'); goog.require('Blockly.Msg'); Blockly.Msg.ADD_COMMENT = "Add Comment"; Blockly.Msg.AUTH = "Please authorize this app to enable your work to be saved and to allow it to be shared by you."; Blockly.Msg.CHANGE_VALUE_TITLE = "Change value:"; Blockly.Msg.CHAT = "Chat with your collaborator by typing in this box!"; Blockly.Msg.COLLAPSE_ALL = "Collapse Blocks"; Blockly.Msg.COLLAPSE_BLOCK = "Collapse Block"; Blockly.Msg.COLOUR_BLEND_COLOUR1 = "colour 1"; Blockly.Msg.COLOUR_BLEND_COLOUR2 = "colour 2"; Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; Blockly.Msg.COLOUR_BLEND_RATIO = "ratio"; Blockly.Msg.COLOUR_BLEND_TITLE = "blend"; Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Blends two colours together with a given ratio (0.0 - 1.0)."; Blockly.Msg.COLOUR_PICKER_HELPURL = "https://en.wikipedia.org/wiki/Color"; Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Choose a colour from the palette."; Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; Blockly.Msg.COLOUR_RANDOM_TITLE = "random colour"; Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Choose a colour at random."; Blockly.Msg.COLOUR_RGB_BLUE = "blue"; Blockly.Msg.COLOUR_RGB_GREEN = "green"; Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html"; Blockly.Msg.COLOUR_RGB_RED = "red"; Blockly.Msg.COLOUR_RGB_TITLE = "colour with"; Blockly.Msg.COLOUR_RGB_TOOLTIP = "Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#Loop_Termination_Blocks"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "break out of loop"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "continue with next iteration of loop"; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Break out of the containing loop."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Skip the rest of this loop, and continue with the next iteration."; Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Warning: This block may only be used within a loop."; Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#for_each for each block"; Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST = "in list"; Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST_TAIL = ""; Blockly.Msg.CONTROLS_FOREACH_INPUT_ITEM = "for each item"; Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "For each item in a list, set the variable '%1' to the item, and then do some statements."; Blockly.Msg.CONTROLS_FOR_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#count_with"; Blockly.Msg.CONTROLS_FOR_INPUT_FROM_TO_BY = "from %1 to %2 by %3"; Blockly.Msg.CONTROLS_FOR_INPUT_WITH = "count with"; Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Have the variable %1 take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks."; Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Add a condition to the if block."; Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Add a final, catch-all condition to the if block."; Blockly.Msg.CONTROLS_IF_HELPURL = "https://code.google.com/p/blockly/wiki/If_Then"; Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Add, remove, or reorder sections to reconfigure this if block."; Blockly.Msg.CONTROLS_IF_MSG_ELSE = "else"; Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "else if"; Blockly.Msg.CONTROLS_IF_MSG_IF = "if"; Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "If a value is true, then do some statements."; Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "If a value is true, then do the first block of statements. Otherwise, do the second block of statements."; Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements."; Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements."; Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop"; Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "do"; Blockly.Msg.CONTROLS_REPEAT_TITLE = "repeat %1 times"; Blockly.Msg.CONTROLS_REPEAT_TITLE_REPEAT = "repeat"; Blockly.Msg.CONTROLS_REPEAT_TITLE_TIMES = "times"; Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Do some statements several times."; Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://code.google.com/p/blockly/wiki/Repeat"; Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "repeat until"; Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "repeat while"; Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "While a value is false, then do some statements."; Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "While a value is true, then do some statements."; Blockly.Msg.DELETE_BLOCK = "Delete Block"; Blockly.Msg.DELETE_X_BLOCKS = "Delete %1 Blocks"; Blockly.Msg.DISABLE_BLOCK = "Disable Block"; Blockly.Msg.DUPLICATE_BLOCK = "Duplicate"; Blockly.Msg.ENABLE_BLOCK = "Enable Block"; Blockly.Msg.EXPAND_ALL = "Expand Blocks"; Blockly.Msg.EXPAND_BLOCK = "Expand Block"; Blockly.Msg.EXTERNAL_INPUTS = "External Inputs"; Blockly.Msg.HELP = "Help"; Blockly.Msg.INLINE_INPUTS = "Inline Inputs"; Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://en.wikipedia.org/wiki/Linked_list#Empty_lists"; Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "create empty list"; Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Returns a list, of length 0, containing no data records"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "list"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Add, remove, or reorder sections to reconfigure this list block."; Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "create list with"; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Add an item to the list."; Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Create a list with any number of items."; Blockly.Msg.LISTS_GET_INDEX_FIRST = "first"; Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# from end"; Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; Blockly.Msg.LISTS_GET_INDEX_GET = "get"; Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "get and remove"; Blockly.Msg.LISTS_GET_INDEX_LAST = "last"; Blockly.Msg.LISTS_GET_INDEX_RANDOM = "random"; Blockly.Msg.LISTS_GET_INDEX_REMOVE = "remove"; Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Returns the first item in a list."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Returns the item at the specified position in a list. #1 is the last item."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Returns the item at the specified position in a list. #1 is the first item."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Returns the last item in a list."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Returns a random item in a list."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Removes and returns the first item in a list."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Removes and returns the item at the specified position in a list. #1 is the last item."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Removes and returns the item at the specified position in a list. #1 is the first item."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Removes and returns the last item in a list."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Removes and returns a random item in a list."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Removes the first item in a list."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Removes the item at the specified position in a list. #1 is the last item."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Removes the item at the specified position in a list. #1 is the first item."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Removes the last item in a list."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Removes a random item in a list."; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "to # from end"; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "to #"; Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "to last"; Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_a_sublist"; Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "get sub-list from first"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "get sub-list from # from end"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "get sub-list from #"; Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Creates a copy of the specified portion of a list."; Blockly.Msg.LISTS_INDEX_OF_FIRST = "find first occurrence of item"; Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_Items_from_a_List"; Blockly.Msg.LISTS_INDEX_OF_LAST = "find last occurrence of item"; Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Returns the index of the first/last occurrence of the item in the list. Returns 0 if text is not found."; Blockly.Msg.LISTS_INLIST = "in list"; Blockly.Msg.LISTS_IS_EMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#is_empty"; Blockly.Msg.LISTS_IS_EMPTY_TITLE = "%1 is empty"; Blockly.Msg.LISTS_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#length_of"; Blockly.Msg.LISTS_LENGTH_TITLE = "length of %1"; Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Returns the length of a list."; Blockly.Msg.LISTS_REPEAT_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#create_list_with"; Blockly.Msg.LISTS_REPEAT_TITLE = "create list with item %1 repeated %2 times"; Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Creates a list consisting of the given value repeated the specified number of times."; Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#in_list_..._set"; Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "as"; Blockly.Msg.LISTS_SET_INDEX_INSERT = "insert at"; Blockly.Msg.LISTS_SET_INDEX_SET = "set"; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Inserts the item at the start of a list."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "Inserts the item at the specified position in a list. #1 is the last item."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Inserts the item at the specified position in a list. #1 is the first item."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Append the item to the end of a list."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Inserts the item randomly in a list."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Sets the first item in a list."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Sets the item at the specified position in a list. #1 is the last item."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Sets the item at the specified position in a list. #1 is the first item."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Sets the last item in a list."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Sets a random item in a list."; Blockly.Msg.LISTS_TOOLTIP = "Returns true if the list is empty."; Blockly.Msg.LOGIC_BOOLEAN_FALSE = "false"; Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://code.google.com/p/blockly/wiki/True_False"; Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Returns either true or false."; Blockly.Msg.LOGIC_BOOLEAN_TRUE = "true"; Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://en.wikipedia.org/wiki/Inequality_(mathematics)"; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Return true if both inputs equal each other."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Return true if the first input is greater than the second input."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Return true if the first input is greater than or equal to the second input."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Return true if the first input is smaller than the second input."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Return true if the first input is smaller than or equal to the second input."; Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Return true if both inputs are not equal to each other."; Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://code.google.com/p/blockly/wiki/Not"; Blockly.Msg.LOGIC_NEGATE_TITLE = "not %1"; Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Returns true if the input is false. Returns false if the input is true."; Blockly.Msg.LOGIC_NULL = "null"; Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; Blockly.Msg.LOGIC_NULL_TOOLTIP = "Returns null."; Blockly.Msg.LOGIC_OPERATION_AND = "and"; Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://code.google.com/p/blockly/wiki/And_Or"; Blockly.Msg.LOGIC_OPERATION_OR = "or"; Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Return true if both inputs are true."; Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Return true if at least one of the inputs is true."; Blockly.Msg.LOGIC_TERNARY_CONDITION = "test"; Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "if false"; Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "if true"; Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value."; Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://en.wikipedia.org/wiki/Arithmetic"; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Return the sum of the two numbers."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Return the quotient of the two numbers."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Return the difference of the two numbers."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Return the product of the two numbers."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Return the first number raised to the power of the second number."; Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; Blockly.Msg.MATH_CHANGE_INPUT_BY = "by"; Blockly.Msg.MATH_CHANGE_TITLE_CHANGE = "change"; Blockly.Msg.MATH_CHANGE_TOOLTIP = "Add a number to variable '%1'."; Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant"; Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity)."; Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; Blockly.Msg.MATH_CONSTRAIN_TITLE = "constrain %1 low %2 high %3"; Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Constrain a number to be between the specified limits (inclusive)."; Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; Blockly.Msg.MATH_IS_DIVISIBLE_BY = "is divisible by"; Blockly.Msg.MATH_IS_EVEN = "is even"; Blockly.Msg.MATH_IS_NEGATIVE = "is negative"; Blockly.Msg.MATH_IS_ODD = "is odd"; Blockly.Msg.MATH_IS_POSITIVE = "is positive"; Blockly.Msg.MATH_IS_PRIME = "is prime"; Blockly.Msg.MATH_IS_TOOLTIP = "Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false."; Blockly.Msg.MATH_IS_WHOLE = "is whole"; Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; Blockly.Msg.MATH_MODULO_TITLE = "remainder of %1 ÷ %2"; Blockly.Msg.MATH_MODULO_TOOLTIP = "Return the remainder from dividing the two numbers."; Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number"; Blockly.Msg.MATH_NUMBER_TOOLTIP = "A number."; Blockly.Msg.MATH_ONLIST_HELPURL = ""; Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "average of list"; Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "max of list"; Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "median of list"; Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "min of list"; Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "modes of list"; Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "random item of list"; Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "standard deviation of list"; Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "sum of list"; Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Return the average (arithmetic mean) of the numeric values in the list."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Return the largest number in the list."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Return the median number in the list."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Return the smallest number in the list."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Return a list of the most common item(s) in the list."; Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Return a random element from the list."; Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Return the standard deviation of the list."; Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Return the sum of all the numbers in the list."; Blockly.Msg.MATH_POWER_SYMBOL = "^"; Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "random fraction"; Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive)."; Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg.MATH_RANDOM_INT_TITLE = "random integer from %1 to %2"; Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Return a random integer between the two specified limits, inclusive."; Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "round"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "round down"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "round up"; Blockly.Msg.MATH_ROUND_TOOLTIP = "Round a number up or down."; Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root"; Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "absolute"; Blockly.Msg.MATH_SINGLE_OP_ROOT = "square root"; Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Return the absolute value of a number."; Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Return e to the power of a number."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Return the natural logarithm of a number."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Return the base 10 logarithm of a number."; Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Return the negation of a number."; Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Return 10 to the power of a number."; Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Return the square root of a number."; Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; Blockly.Msg.MATH_TRIG_ACOS = "acos"; Blockly.Msg.MATH_TRIG_ASIN = "asin"; Blockly.Msg.MATH_TRIG_ATAN = "atan"; Blockly.Msg.MATH_TRIG_COS = "cos"; Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions"; Blockly.Msg.MATH_TRIG_SIN = "sin"; Blockly.Msg.MATH_TRIG_TAN = "tan"; Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Return the arccosine of a number."; Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Return the arcsine of a number."; Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Return the arctangent of a number."; Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Return the cosine of a degree (not radian)."; Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Return the sine of a degree (not radian)."; Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Return the tangent of a degree (not radian)."; Blockly.Msg.ME = "Me"; Blockly.Msg.NEW_VARIABLE = "New variable..."; Blockly.Msg.NEW_VARIABLE_TITLE = "New variable name:"; Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "allow statements"; Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "with:"; Blockly.Msg.PROCEDURES_CALLNORETURN_CALL = ""; Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Run the user-defined function '%1'."; Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Run the user-defined function '%1' and use its output."; Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "with:"; Blockly.Msg.PROCEDURES_CREATE_DO = "Create '%1'"; Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "do something"; Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "to"; Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Creates a function with no output."; Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "return"; Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Creates a function with an output."; Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Warning: This function has duplicate parameters."; Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Highlight function definition"; Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "If a value is true, then return a second value."; Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Warning: This block may be used only within a function definition."; Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "input name:"; Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Add an input to the function."; Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "inputs"; Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Add, remove, or reorder inputs to this function."; Blockly.Msg.REMOVE_COMMENT = "Remove Comment"; Blockly.Msg.RENAME_VARIABLE = "Rename variable..."; Blockly.Msg.RENAME_VARIABLE_TITLE = "Rename all '%1' variables to:"; Blockly.Msg.TEXT_APPEND_APPENDTEXT = "append text"; Blockly.Msg.TEXT_APPEND_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification"; Blockly.Msg.TEXT_APPEND_TO = "to"; Blockly.Msg.TEXT_APPEND_TOOLTIP = "Append some text to variable '%1'."; Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Adjusting_text_case"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "to lower case"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "to Title Case"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "to UPPER CASE"; Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Return a copy of the text in a different case."; Blockly.Msg.TEXT_CHARAT_FIRST = "get first letter"; Blockly.Msg.TEXT_CHARAT_FROM_END = "get letter # from end"; Blockly.Msg.TEXT_CHARAT_FROM_START = "get letter #"; Blockly.Msg.TEXT_CHARAT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_text"; Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "in text"; Blockly.Msg.TEXT_CHARAT_LAST = "get last letter"; Blockly.Msg.TEXT_CHARAT_RANDOM = "get random letter"; Blockly.Msg.TEXT_CHARAT_TAIL = ""; Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Returns the letter at the specified position."; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Add an item to the text."; Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "join"; Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Add, remove, or reorder sections to reconfigure this text block."; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "to letter # from end"; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "to letter #"; Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "to last letter"; Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_a_region_of_text"; Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "in text"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "get substring from first letter"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "get substring from letter # from end"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "get substring from letter #"; Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Returns a specified portion of the text."; Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Finding_text"; Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "in text"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "find first occurrence of text"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "find last occurrence of text"; Blockly.Msg.TEXT_INDEXOF_TAIL = ""; Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Returns the index of the first/last occurrence of first text in the second text. Returns 0 if text is not found."; Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Checking_for_empty_text"; Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 is empty"; Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Returns true if the provided text is empty."; Blockly.Msg.TEXT_JOIN_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_creation"; Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "create text with"; Blockly.Msg.TEXT_JOIN_TOOLTIP = "Create a piece of text by joining together any number of items."; Blockly.Msg.TEXT_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification"; Blockly.Msg.TEXT_LENGTH_TITLE = "length of %1"; Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Returns the number of letters (including spaces) in the provided text."; Blockly.Msg.TEXT_PRINT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Printing_text"; Blockly.Msg.TEXT_PRINT_TITLE = "print %1"; Blockly.Msg.TEXT_PRINT_TOOLTIP = "Print the specified text, number or other value."; Blockly.Msg.TEXT_PROMPT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Getting_input_from_the_user"; Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Prompt for user for a number."; Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Prompt for user for some text."; Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "prompt for number with message"; Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "prompt for text with message"; Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; Blockly.Msg.TEXT_TEXT_TOOLTIP = "A letter, word, or line of text."; Blockly.Msg.TEXT_TRIM_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Trimming_%28removing%29_spaces"; Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "trim spaces from both sides of"; Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "trim spaces from left side of"; Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "trim spaces from right side of"; Blockly.Msg.TEXT_TRIM_TOOLTIP = "Return a copy of the text with spaces removed from one or both ends."; Blockly.Msg.VARIABLES_DEFAULT_NAME = "item"; Blockly.Msg.VARIABLES_GET_CREATE_SET = "Create 'set %1'"; Blockly.Msg.VARIABLES_GET_HELPURL = "https://code.google.com/p/blockly/wiki/Variables#Get"; Blockly.Msg.VARIABLES_GET_TAIL = ""; Blockly.Msg.VARIABLES_GET_TITLE = ""; Blockly.Msg.VARIABLES_GET_TOOLTIP = "Returns the value of this variable."; Blockly.Msg.VARIABLES_SET_CREATE_GET = "Create 'get %1'"; Blockly.Msg.VARIABLES_SET_HELPURL = "https://code.google.com/p/blockly/wiki/Variables#Set"; Blockly.Msg.VARIABLES_SET_TAIL = "to"; Blockly.Msg.VARIABLES_SET_TITLE = "set"; Blockly.Msg.VARIABLES_SET_TOOLTIP = "Sets this variable to be equal to the input."; Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE; Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE; Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.VARIABLES_GET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO; Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.PROCEDURES_CALLRETURN_CALL = Blockly.Msg.PROCEDURES_CALLNORETURN_CALL; Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF; Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF; Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
kallex/blockly
msg/js/en.js
JavaScript
apache-2.0
28,383
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global','./ListItemBaseRenderer','sap/ui/core/Renderer'],function(q,L,R){"use strict";var T=R.extend(L);T.renderLIAttributes=function(r,l){r.addClass("sapMTreeItemBase");if(!l.isTopLevel()){r.addClass("sapMTreeItemBaseChildren");}var i=l._getPadding();if(sap.ui.getCore().getConfiguration().getRTL()){r.addStyle("padding-right",i+"rem");}else{r.addStyle("padding-left",i+"rem");}};T.renderContentFormer=function(r,l){this.renderHighlight(r,l);this.renderExpander(r,l);this.renderMode(r,l,-1);};T.renderExpander=function(r,l){var e=l._getExpanderControl();if(e){r.renderControl(e);}};T.getAriaRole=function(l){return"treeitem";};T.getAccessibilityState=function(l){var a=L.getAccessibilityState.call(this,l);a.level=l.getLevel()+1;if(!l.isLeaf()){a.expanded=l.getExpanded();}return a;};return T;},true);
thbonk/electron-openui5-boilerplate
libs/openui5-runtime/resources/sap/m/TreeItemBaseRenderer.js
JavaScript
apache-2.0
1,016
define(function(require) { var ko = require('knockout'); require('ko_es5'); require('ko_postbox'); //require('/sitedesign/utils.js'); var StoreVM = function() { var self = this; self.jwt = misc_util.get_jwt_claims(); self.categories = []; self.store = null; self.visible = false; self.showView = function(store) { //self.jwt = misc_util.get_jwt_claims() self.store = store document.title = store.dc_title; ld_util.get(store.sus_categories, function(request){ if (request.status==200) { var ldp_contains = APPLICATION_ENVIRON.rdf_converter.make_simple_jso(request).ldp_contains; if (ldp_contains) self.categories = ldp_contains; } else { console.log( request.status ) } }) self.visible = true; }; self.displayName = function() { return self.jwt.disp ? self.jwt.disp : "Guest" } self.loggedIn = function() { return self.jwt.acc } self.login = function() { misc_util.get_login() } self.logout = function() { misc_util.post_logout() } self.hideView = function() { self.visible = false; }; self.initialize = function() { ko.postbox.subscribe("active_view", function(message) { if (message.view == 'store') { self.showView(message.data); } else self.hideView(); }, true); ko.postbox.subscribe("init_header", function(message) { //self.jwt = misc_util.get_jwt_claims() self.store = message.data }, true); } ko.track(this); }; return new StoreVM(); });
ld4apps/lda-examples
setupshop/wsgi/static/setupshop/shop/store.js
JavaScript
apache-2.0
2,030
/* eslint-disable no-unused-vars */ import React from "react"; /* eslint-enable no-unused-vars */ const BulkOptions = { user: { delete: { dropdownOption: <span className="text-danger">Delete</span>, title: "Are you sure?", actionPhrase: "will be deleted" } } }; module.exports = BulkOptions;
jcloud-shengtai/dcos-ui_CN
src/js/constants/BulkOptions.js
JavaScript
apache-2.0
324
import chalk from 'chalk'; import stamp from '../../util/output/stamp.ts'; import info from '../../util/output/info'; import error from '../../util/output/error'; import wait from '../../util/output/wait'; import rightPad from '../../util/output/right-pad'; import eraseLines from '../../util/output/erase-lines'; import chars from '../../util/output/chars'; import success from '../../util/output/success'; import note from '../../util/output/note'; import textInput from '../../util/input/text'; import invite from './invite'; import { writeToConfigFile } from '../../util/config/files'; import { getPkgName, getCommandName } from '../../util/pkg-name.ts'; const validateSlugKeypress = (data, value) => // TODO: the `value` here should contain the current value + the keypress // should be fixed on utils/input/text.js /^[a-zA-Z]+[a-zA-Z0-9_-]*$/.test(value + data); const validateNameKeypress = (data, value) => // TODO: the `value` here should contain the current value + the keypress // should be fixed on utils/input/text.js /^[ a-zA-Z0-9_-]+$/.test(value + data); const gracefulExit = () => { console.log(); // Blank line note( `Your team is now active for all ${getPkgName()} commands!\n Run ${getCommandName( `switch` )} to change it in the future.` ); return 0; }; const teamUrlPrefix = rightPad('Team URL', 14) + chalk.gray('vercel.com/'); const teamNamePrefix = rightPad('Team Name', 14); export default async function({ apiUrl, token, teams, config }) { let slug; let team; let elapsed; let stopSpinner; console.log( info( `Pick a team identifier for its url (e.g.: ${chalk.cyan( '`vercel.com/acme`' )})` ) ); do { try { // eslint-disable-next-line no-await-in-loop slug = await textInput({ label: `- ${teamUrlPrefix}`, validateKeypress: validateSlugKeypress, initialValue: slug, valid: team, forceLowerCase: true, }); } catch (err) { if (err.message === 'USER_ABORT') { console.log(info('Aborted')); return 0; } throw err; } elapsed = stamp(); stopSpinner = wait(teamUrlPrefix + slug); let res; try { // eslint-disable-next-line no-await-in-loop res = await teams.create({ slug }); stopSpinner(); team = res; } catch (err) { stopSpinner(); process.stdout.write(eraseLines(2)); console.error(error(err.message)); } } while (!team); process.stdout.write(eraseLines(2)); console.log(success(`Team created ${elapsed()}`)); console.log(`${chalk.cyan(`${chars.tick} `) + teamUrlPrefix + slug}\n`); console.log(info('Pick a display name for your team')); let name; try { name = await textInput({ label: `- ${teamNamePrefix}`, validateKeypress: validateNameKeypress, }); } catch (err) { if (err.message === 'USER_ABORT') { console.log(info('No name specified')); return gracefulExit(); } throw err; } elapsed = stamp(); stopSpinner = wait(teamNamePrefix + name); const res = await teams.edit({ id: team.id, name }); stopSpinner(); process.stdout.write(eraseLines(2)); if (res.error) { console.error(error(res.error.message)); console.log(`${chalk.red(`✖ ${teamNamePrefix}`)}${name}`); return 1; // TODO: maybe we want to ask the user to retry? not sure if // there's a scenario where that would be wanted } team = Object.assign(team, res); console.log(success(`Team name saved ${elapsed()}`)); console.log(`${chalk.cyan(`${chars.tick} `) + teamNamePrefix + team.name}\n`); stopSpinner = wait('Saving'); // Update config file const configCopy = Object.assign({}, config); if (configCopy.sh) { configCopy.sh.currentTeam = team; } else { configCopy.currentTeam = team.id; } writeToConfigFile(configCopy); stopSpinner(); await invite({ teams, args: [], token, apiUrl, config, introMsg: 'Invite your teammates! When done, press enter on an empty field', noopMsg: `You can invite teammates later by running ${getCommandName( `teams invite` )}`, }); gracefulExit(); }
zeit/now-cli
packages/now-cli/src/commands/teams/add.js
JavaScript
apache-2.0
4,215
FOAModel({ name: 'QIssueTileView', label: 'QIssue Tile View', extendsModel: 'View', properties: [ { name: 'browser' }, { name: 'issue', type: 'QIssue' } ], methods: { // Implement Sink put: function(issue) { if ( this.issue ) { this.issue.removeListener(this.onChange); } this.issue = issue.clone(); this.issue.addListener(this.onChange); }, // Implement Adapter f: function(issue) { var view = QIssueTileView.create({ browser: this.browser }); view.put(issue); return view; }, toString: function() { return this.toHTML(); } }, listeners: [ { name: 'onChange', code: function() { this.browser.IssueDAO.put(this.issue); } }, { name: 'dragStart', code: function(e) { e.dataTransfer.setData('application/x-foam-id', this.issue.id); e.dataTransfer.effectAllowed = 'move'; }, }, ], templates:[ { name: 'toHTML' } ] });
shepheb/foam
apps/quickbug/ui/QIssueTileView.js
JavaScript
apache-2.0
1,025
/** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); var isPositiveNumber = require( '@stdlib/assert/is-positive-number' ).isPrimitive; var isPlainObject = require( '@stdlib/assert/is-plain-object' ); var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isUint32Array = require( '@stdlib/assert/is-uint32array' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var copy = require( '@stdlib/utils/copy' ); var noop = require( '@stdlib/utils/noop' ); var constantFunction = require( '@stdlib/utils/constant-function' ); var iteratorSymbol = require( '@stdlib/symbol/iterator' ); var randu = require( '@stdlib/random/base/uniform' ).factory; var SQRT_THREE = require( '@stdlib/constants/float64/sqrt-three' ); var DEFAULTS = require( './defaults.json' ); // MAIN // /** * Returns an iterator which introduces additive white uniform noise with standard deviation `sigma`. * * ## Method * * - The variance of a uniform distribution is given by * * ```tex * \operatorname{Var} = \frac{(b-a)^2}{12} * ``` * * where \\( a \\) is the minimum support and \\( b \\) is the maximum support. * * - Accordingly, to generate uniform noise having zero mean and a desired standard deviation, we let \\( a = -b \\) and solve for \\( b \\). * * ```tex * \begin{align*} * \sigma &= \frac{b-a}{\sqrt{12}} \\ * \sigma \sqrt{12} &= b - a \\ * 2 \sigma \sqrt{3} &= b - (-b) \\ * 2 \sigma \sqrt{3} &= 2b \\ * b &= \sigma \sqrt{3} * \end{align*} * ``` * * where \\( \sigma \\) is the standard deviation. * * - Thus, to generate uniform noise having zero mean and a desired standard deviation, we sample from \\( \operatorname{unif}(-sigma\sqrt{3}, sigma\sqrt{3}) \\). * * @param {Iterator} iterator - input iterator * @param {PositiveNumber} sigma - standard deviation of the noise * @param {Options} [options] - function options * @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers on the interval `[0,1)` * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} first argument must be an iterator * @throws {TypeError} second argument must be a positive number * @throws {TypeError} third argument must be an object * @throws {TypeError} must provide valid options * @throws {Error} must provide a valid state * @returns {Iterator} iterator * * @example * var iterSineWave = require( '@stdlib/simulate/iter/sine-wave' ); * * var sine = iterSineWave({ * 'iter': 100 * }); * * var it = iterawun( sine, 0.5 ); * * var v = it.next().value; * // returns <number> * * v = it.next().value; * // returns <number> * * v = it.next().value; * // returns <number> * * // ... */ function iterawun( iterator, sigma, options ) { var runif; var opts; var iter; var FLG; var a; if ( !isIteratorLike( iterator ) ) { throw new TypeError( 'invalid argument. First argument must be an iterator. Value: `' + iterator + '`.' ); } if ( !isPositiveNumber( sigma ) ) { throw new TypeError( 'invalid argument. Second argument must be a positive number. Value: `' + sigma + '`.' ); } opts = copy( DEFAULTS ); if ( arguments.length > 2 ) { if ( !isPlainObject( options ) ) { throw new TypeError( 'invalid argument. Third argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'prng' ) ) { if ( !isFunction( options.prng ) ) { throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + options.prng + '`.' ); } opts.prng = options.prng; } // If provided a PRNG, ignore the `state` option, as we don't support getting or setting PRNG state. else if ( hasOwnProp( options, 'state' ) ) { opts.state = options.state; if ( !isUint32Array( options.state ) ) { throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + options.state + '`.' ); } } // If provided a PRNG, ignore the `seed` option, as a `seed`, by itself, is insufficient to guarantee reproducibility. If provided a state, ignore the `seed` option, as a PRNG state should contain seed information. else if ( hasOwnProp( options, 'seed' ) ) { opts.seed = options.seed; if ( options.seed === void 0 ) { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + options.seed + '`.' ); } } } a = sigma * SQRT_THREE; runif = randu( -a, a, opts ); // Create an iterator protocol-compliant object: iter = {}; setReadOnly( iter, 'next', next ); setReadOnly( iter, 'return', end ); // If an environment supports `Symbol.iterator` and the provided iterator is iterable, make the iterator iterable: if ( iteratorSymbol && isFunction( iterator[ iteratorSymbol ] ) ) { setReadOnly( iter, iteratorSymbol, factory ); } // If we are provided an "external" PRNG, we don't support getting or setting PRNG state, as we'd need to check for compatible state value types, etc, entailing considerable complexity. if ( options && options.prng ) { setReadOnly( iter, 'seed', null ); setReadOnly( iter, 'seedLength', null ); setReadWriteAccessor( iter, 'state', constantFunction( null ), noop ); setReadOnly( iter, 'stateLength', null ); setReadOnly( iter, 'byteLength', null ); setReadOnly( iter, 'PRNG', options.prng ); } else { setReadOnlyAccessor( iter, 'seed', getSeed ); setReadOnlyAccessor( iter, 'seedLength', getSeedLength ); setReadWriteAccessor( iter, 'state', getState, setState ); setReadOnlyAccessor( iter, 'stateLength', getStateLength ); setReadOnlyAccessor( iter, 'byteLength', getStateSize ); setReadOnly( iter, 'PRNG', runif.PRNG ); } return iter; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMT19937} seed */ function getSeed() { return runif.seed; } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return runif.seedLength; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return runif.stateLength; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return runif.byteLength; } /** * Returns the current PRNG state. * * @private * @returns {PRNGStateMT19937} current state */ function getState() { return runif.state; } /** * Sets the PRNG state. * * @private * @param {PRNGStateMT19937} s - generator state * @throws {Error} must provide a valid state */ function setState( s ) { runif.state = s; } /** * Returns an iterator protocol-compliant object containing the next iterated value. * * @private * @returns {Object} iterator protocol-compliant object */ function next() { var v; if ( FLG ) { return { 'done': true }; } v = iterator.next(); if ( v.done ) { FLG = true; return v; } if ( typeof v.value === 'number' ) { v = v.value + runif(); } else { v = NaN; } return { 'value': v, 'done': false }; } /** * Finishes an iterator. * * @private * @param {*} [value] - value to return * @returns {Object} iterator protocol-compliant object */ function end( value ) { FLG = true; if ( arguments.length ) { return { 'value': value, 'done': true }; } return { 'done': true }; } /** * Returns a new iterator. * * @private * @returns {Iterator} iterator */ function factory() { return iterawun( iterator[ iteratorSymbol ](), sigma, opts ); } } // EXPORTS // module.exports = iterawun;
stdlib-js/stdlib
lib/node_modules/@stdlib/simulate/iter/awun/lib/main.js
JavaScript
apache-2.0
9,301
/** * jQuery ligerUI 1.2.0 * * http://ligerui.com * * Author daomi 2013 [ gd_star@163.com ] * */ (function ($) { $.fn.ligerTab = function (options) { return $.ligerui.run.call(this, "ligerTab", arguments); }; $.fn.ligerGetTabManager = function () { return $.ligerui.run.call(this, "ligerGetTabManager", arguments); }; $.ligerDefaults.Tab = { height: null, heightDiff: 0, // 高度补差 changeHeightOnResize: false, contextmenu: true, dblClickToClose: false, //是否双击时关闭 dragToMove: false, //是否允许拖动时改变tab项的位置 onBeforeOverrideTabItem: null, onAfterOverrideTabItem: null, onBeforeRemoveTabItem: null, onAfterRemoveTabItem: null, onBeforeAddTabItem: null, onAfterAddTabItem: null, onBeforeSelectTabItem: null, onAfterSelectTabItem: null }; $.ligerDefaults.TabString = { closeMessage: "关闭当前页", closeOtherMessage: "关闭其他", closeAllMessage: "关闭所有", reloadMessage: "刷新" }; $.ligerMethos.Tab = {}; $.ligerui.controls.Tab = function (element, options) { $.ligerui.controls.Tab.base.constructor.call(this, element, options); }; $.ligerui.controls.Tab.ligerExtend($.ligerui.core.UIComponent, { __getType: function () { return 'Tab'; }, __idPrev: function () { return 'Tab'; }, _extendMethods: function () { return $.ligerMethos.Tab; }, _render: function () { var g = this, p = this.options; if (p.height) g.makeFullHeight = true; g.tab = $(this.element); g.tab.addClass("l-tab"); if (p.contextmenu && $.ligerMenu) { g.tab.menu = $.ligerMenu({ width: 100, items: [ { text: p.closeMessage, id: 'close', click: function () { g._menuItemClick.apply(g, arguments); } }, { text: p.closeOtherMessage, id: 'closeother', click: function () { g._menuItemClick.apply(g, arguments); } }, { text: p.closeAllMessage, id: 'closeall', click: function () { g._menuItemClick.apply(g, arguments); } }, { text: p.reloadMessage, id: 'reload', click: function () { g._menuItemClick.apply(g, arguments); } } ] }); } g.tab.content = $('<div class="l-tab-content"></div>'); $("> div", g.tab).appendTo(g.tab.content); g.tab.content.appendTo(g.tab); g.tab.links = $('<div class="l-tab-links"><ul style="left: 0px; "></ul></div>'); g.tab.links.prependTo(g.tab); g.tab.links.ul = $("ul", g.tab.links); var lselecteds = $("> div[lselected=true]", g.tab.content); var haslselected = lselecteds.length > 0; g.selectedTabId = lselecteds.attr("tabid"); $("> div", g.tab.content).each(function (i, box) { var li = $('<li class=""><a></a><div class="l-tab-links-item-left"></div><div class="l-tab-links-item-right"></div></li>'); var contentitem = $(this); if (contentitem.attr("title")) { $("> a", li).html(contentitem.attr("title")); contentitem.attr("title", ""); } var tabid = contentitem.attr("tabid"); if (tabid == undefined) { tabid = g.getNewTabid(); contentitem.attr("tabid", tabid); if (contentitem.attr("lselected")) { g.selectedTabId = tabid; } } li.attr("tabid", tabid); if (!haslselected && i == 0) g.selectedTabId = tabid; var showClose = contentitem.attr("showClose"); if (showClose) { li.append("<div class='l-tab-links-item-close'></div>"); } $("> ul", g.tab.links).append(li); if (!contentitem.hasClass("l-tab-content-item")) contentitem.addClass("l-tab-content-item"); if (contentitem.find("iframe").length > 0) { var iframe = $("iframe:first", contentitem); if (iframe[0].readyState != "complete") { if (contentitem.find(".l-tab-loading:first").length == 0) contentitem.prepend("<div class='l-tab-loading' style='display:block;'></div>"); var iframeloading = $(".l-tab-loading:first", contentitem); iframe.bind('load.tab', function () { iframeloading.hide(); }); } } }); //init g.selectTabItem(g.selectedTabId); //set content height if (p.height) { if (typeof (p.height) == 'string' && p.height.indexOf('%') > 0) { g.onResize(); if (p.changeHeightOnResize) { $(window).resize(function () { g.onResize.call(g); }); } } else { g.setHeight(p.height); } } if (g.makeFullHeight) g.setContentHeight(); //add even $("li", g.tab.links).each(function () { g._addTabItemEvent($(this)); }); g.tab.bind('dblclick.tab', function (e) { if (!p.dblClickToClose) return; g.dblclicking = true; var obj = (e.target || e.srcElement); var tagName = obj.tagName.toLowerCase(); if (tagName == "a") { var tabid = $(obj).parent().attr("tabid"); var allowClose = $(obj).parent().find("div.l-tab-links-item-close").length ? true : false; if (allowClose) { g.removeTabItem(tabid); } } g.dblclicking = false; }); g.set(p); }, _applyDrag: function (tabItemDom) { var g = this, p = this.options; g.droptip = g.droptip || $("<div class='l-tab-drag-droptip' style='display:none'><div class='l-drop-move-up'></div><div class='l-drop-move-down'></div></div>").appendTo('body'); var drag = $(tabItemDom).ligerDrag( { revert: true, animate: false, proxy: function () { var name = $(this).find("a").html(); g.dragproxy = $("<div class='l-tab-drag-proxy' style='display:none'><div class='l-drop-icon l-drop-no'></div></div>").appendTo('body'); g.dragproxy.append(name); return g.dragproxy; }, onRendered: function () { this.set('cursor', 'pointer'); }, onStartDrag: function (current, e) { if (!$(tabItemDom).hasClass("l-selected")) return false; if (e.button == 2) return false; var obj = e.srcElement || e.target; if ($(obj).hasClass("l-tab-links-item-close")) return false; }, onDrag: function (current, e) { if (g.dropIn == null) g.dropIn = -1; var tabItems = g.tab.links.ul.find('>li'); var targetIndex = tabItems.index(current.target); tabItems.each(function (i, item) { if (targetIndex == i) { return; } var isAfter = i > targetIndex; if (g.dropIn != -1 && g.dropIn != i) return; var offset = $(this).offset(); var range = { top: offset.top, bottom: offset.top + $(this).height(), left: offset.left - 10, right: offset.left + 10 }; if (isAfter) { range.left += $(this).width(); range.right += $(this).width(); } var pageX = e.pageX || e.screenX; var pageY = e.pageY || e.screenY; if (pageX > range.left && pageX < range.right && pageY > range.top && pageY < range.bottom) { g.droptip.css({ left: range.left + 5, top: range.top - 9 }).show(); g.dropIn = i; g.dragproxy.find(".l-drop-icon").removeClass("l-drop-no").addClass("l-drop-yes"); } else { g.dropIn = -1; g.droptip.hide(); g.dragproxy.find(".l-drop-icon").removeClass("l-drop-yes").addClass("l-drop-no"); } }); }, onStopDrag: function (current, e) { if (g.dropIn > -1) { var to = g.tab.links.ul.find('>li:eq(' + g.dropIn + ')').attr("tabid"); var from = $(current.target).attr("tabid"); setTimeout(function () { g.moveTabItem(from, to); }, 0); g.dropIn = -1; g.dragproxy.remove(); } g.droptip.hide(); this.set('cursor', 'default'); } }); return drag; }, _setDragToMove: function (value) { if (!$.fn.ligerDrag) return; //需要ligerDrag的支持 var g = this, p = this.options; if (value) { if (g.drags) return; g.drags = g.drags || []; g.tab.links.ul.find('>li').each(function () { g.drags.push(g._applyDrag(this)); }); } }, moveTabItem: function (fromTabItemID, toTabItemID) { var g = this; var from = g.tab.links.ul.find(">li[tabid=" + fromTabItemID + "]"); var to = g.tab.links.ul.find(">li[tabid=" + toTabItemID + "]"); var index1 = g.tab.links.ul.find(">li").index(from); var index2 = g.tab.links.ul.find(">li").index(to); if (index1 < index2) { to.after(from); } else { to.before(from); } }, //设置tab按钮(左和右),显示返回true,隐藏返回false setTabButton: function () { var g = this, p = this.options; var sumwidth = 0; $("li", g.tab.links.ul).each(function () { sumwidth += $(this).width() + 2; }); var mainwidth = g.tab.width(); if (sumwidth > mainwidth) { g.tab.links.append('<div class="l-tab-links-left"></div><div class="l-tab-links-right"></div>'); g.setTabButtonEven(); return true; } else { g.tab.links.ul.animate({ left: 0 }); $(".l-tab-links-left,.l-tab-links-right", g.tab.links).remove(); return false; } }, //设置左右按钮的事件 标签超出最大宽度时,可左右拖动 setTabButtonEven: function () { var g = this, p = this.options; $(".l-tab-links-left", g.tab.links).hover(function () { $(this).addClass("l-tab-links-left-over"); }, function () { $(this).removeClass("l-tab-links-left-over"); }).click(function () { g.moveToPrevTabItem(); }); $(".l-tab-links-right", g.tab.links).hover(function () { $(this).addClass("l-tab-links-right-over"); }, function () { $(this).removeClass("l-tab-links-right-over"); }).click(function () { g.moveToNextTabItem(); }); }, //切换到上一个tab moveToPrevTabItem: function () { var g = this, p = this.options; var btnWitdth = $(".l-tab-links-left", g.tab.links).width(); var leftList = new Array(); //记录每个tab的left,由左到右 $("li", g.tab.links).each(function (i, item) { var currentItemLeft = -1 * btnWitdth; if (i > 0) { currentItemLeft = parseInt(leftList[i - 1]) + $(this).prev().width() + 2; } leftList.push(currentItemLeft); }); var currentLeft = -1 * parseInt(g.tab.links.ul.css("left")); for (var i = 0; i < leftList.length - 1; i++) { if (leftList[i] < currentLeft && leftList[i + 1] >= currentLeft) { g.tab.links.ul.animate({ left: -1 * parseInt(leftList[i]) }); return; } } }, //切换到下一个tab moveToNextTabItem: function () { var g = this, p = this.options; var btnWitdth = $(".l-tab-links-right", g.tab).width(); var sumwidth = 0; var tabItems = $("li", g.tab.links.ul); tabItems.each(function () { sumwidth += $(this).width() + 2; }); var mainwidth = g.tab.width(); var leftList = new Array(); //记录每个tab的left,由右到左 for (var i = tabItems.length - 1; i >= 0; i--) { var currentItemLeft = sumwidth - mainwidth + btnWitdth + 2; if (i != tabItems.length - 1) { currentItemLeft = parseInt(leftList[tabItems.length - 2 - i]) - $(tabItems[i + 1]).width() - 2; } leftList.push(currentItemLeft); } var currentLeft = -1 * parseInt(g.tab.links.ul.css("left")); for (var j = 1; j < leftList.length; j++) { if (leftList[j] <= currentLeft && leftList[j - 1] > currentLeft) { g.tab.links.ul.animate({ left: -1 * parseInt(leftList[j - 1]) }); return; } } }, getTabItemCount: function () { var g = this, p = this.options; return $("li", g.tab.links.ul).length; }, getSelectedTabItemID: function () { var g = this, p = this.options; return $("li.l-selected", g.tab.links.ul).attr("tabid"); }, removeSelectedTabItem: function () { var g = this, p = this.options; g.removeTabItem(g.getSelectedTabItemID()); }, //覆盖选择的tabitem overrideSelectedTabItem: function (options) { var g = this, p = this.options; g.overrideTabItem(g.getSelectedTabItemID(), options); }, //覆盖 overrideTabItem: function (targettabid, options) { var g = this, p = this.options; if (g.trigger('beforeOverrideTabItem', [targettabid]) == false) return false; var tabid = options.tabid; if (tabid == undefined) tabid = g.getNewTabid(); var url = options.url; var content = options.content; var target = options.target; var text = options.text; var showClose = options.showClose; var height = options.height; //如果已经存在 if (g.isTabItemExist(tabid)) { return; } var tabitem = $("li[tabid=" + targettabid + "]", g.tab.links.ul); var contentitem = $(".l-tab-content-item[tabid=" + targettabid + "]", g.tab.content); if (!tabitem || !contentitem) return; tabitem.attr("tabid", tabid); contentitem.attr("tabid", tabid); if ($("iframe", contentitem).length == 0 && url) { contentitem.html("<iframe frameborder='0'></iframe>"); } else if (content) { contentitem.html(content); } $("iframe", contentitem).attr("name", tabid); if (showClose == undefined) showClose = true; if (showClose == false) $(".l-tab-links-item-close", tabitem).remove(); else { if ($(".l-tab-links-item-close", tabitem).length == 0) tabitem.append("<div class='l-tab-links-item-close'></div>"); } if (text == undefined) text = tabid; if (height) contentitem.height(height); $("a", tabitem).text(text); $("iframe", contentitem).attr("src", url); g.trigger('afterOverrideTabItem', [targettabid]); }, //设置页签项标题 setHeader: function(tabid,header) { $("li[tabid=" + tabid + "] a", this.tab.links.ul).text(header); }, //选中tab项 selectTabItem: function (tabid) { var g = this, p = this.options; if (g.trigger('beforeSelectTabItem', [tabid]) == false) return false; g.selectedTabId = tabid; $("> .l-tab-content-item[tabid=" + tabid + "]", g.tab.content).show().siblings().hide(); $("li[tabid=" + tabid + "]", g.tab.links.ul).addClass("l-selected").siblings().removeClass("l-selected"); g.trigger('afterSelectTabItem', [tabid]); }, //移动到最后一个tab moveToLastTabItem: function () { var g = this, p = this.options; var sumwidth = 0; $("li", g.tab.links.ul).each(function () { sumwidth += $(this).width() + 2; }); var mainwidth = g.tab.width(); if (sumwidth > mainwidth) { var btnWitdth = $(".l-tab-links-right", g.tab.links).width(); g.tab.links.ul.animate({ left: -1 * (sumwidth - mainwidth + btnWitdth + 2) }); } }, //判断tab是否存在 isTabItemExist: function (tabid) { var g = this, p = this.options; return $("li[tabid=" + tabid + "]", g.tab.links.ul).length > 0; }, //增加一个tab addTabItem: function (options) { var g = this, p = this.options; if (g.trigger('beforeAddTabItem', [tabid]) == false) return false; var tabid = options.tabid; if (tabid == undefined) tabid = g.getNewTabid(); var url = options.url; var content = options.content; var text = options.text; var showClose = options.showClose; var height = options.height; //如果已经存在 if (g.isTabItemExist(tabid)) { g.selectTabItem(tabid); return; } var tabitem = $("<li><a></a><div class='l-tab-links-item-left'></div><div class='l-tab-links-item-right'></div><div class='l-tab-links-item-close'></div></li>"); var contentitem = $("<div class='l-tab-content-item'><div class='l-tab-loading' style='display:block;'></div><iframe frameborder='0'></iframe></div>"); var iframeloading = $("div:first", contentitem); var iframe = $("iframe:first", contentitem); if (g.makeFullHeight) { var newheight = g.tab.height() - g.tab.links.height(); contentitem.height(newheight); } tabitem.attr("tabid", tabid); contentitem.attr("tabid", tabid); if (url) { iframe.attr("name", tabid) .attr("id", tabid) .attr("src", url) .bind('load.tab', function () { iframeloading.hide(); if (options.callback) options.callback(); }); } else { iframe.remove(); iframeloading.remove(); } if (content) { contentitem.html(content); } else if (options.target) { contentitem.append(options.target); } if (showClose == undefined) showClose = true; if (showClose == false) $(".l-tab-links-item-close", tabitem).remove(); if (text == undefined) text = tabid; if (height) contentitem.height(height); $("a", tabitem).text(text); g.tab.links.ul.append(tabitem); g.tab.content.append(contentitem); g.selectTabItem(tabid); if (g.setTabButton()) { g.moveToLastTabItem(); } //增加事件 g._addTabItemEvent(tabitem); if (p.dragToMove && $.fn.ligerDrag) { g.drags = g.drags || []; tabitem.each(function () { g.drags.push(g._applyDrag(this)); }); } g.trigger('afterAddTabItem', [tabid]); }, _addTabItemEvent: function (tabitem) { var g = this, p = this.options; tabitem.click(function () { var tabid = $(this).attr("tabid"); g.selectTabItem(tabid); }); //右键事件支持 g.tab.menu && g._addTabItemContextMenuEven(tabitem); $(".l-tab-links-item-close", tabitem).hover(function () { $(this).addClass("l-tab-links-item-close-over"); }, function () { $(this).removeClass("l-tab-links-item-close-over"); }).click(function () { var tabid = $(this).parent().attr("tabid"); g.removeTabItem(tabid); }); }, //移除tab项 removeTabItem: function (tabid) { var g = this, p = this.options; if (g.trigger('beforeRemoveTabItem', [tabid]) == false) return false; var currentIsSelected = $("li[tabid=" + tabid + "]", g.tab.links.ul).hasClass("l-selected"); if (currentIsSelected) { $(".l-tab-content-item[tabid=" + tabid + "]", g.tab.content).prev().show(); $("li[tabid=" + tabid + "]", g.tab.links.ul).prev().addClass("l-selected").siblings().removeClass("l-selected"); } var contentItem = $(".l-tab-content-item[tabid=" + tabid + "]", g.tab.content); var jframe = $('iframe', contentItem); if (jframe.length) { var frame = jframe[0]; frame.src = "about:blank"; frame.contentWindow.document.write(''); $.browser.msie && CollectGarbage(); jframe.remove(); } contentItem.remove(); $("li[tabid=" + tabid + "]", g.tab.links.ul).remove(); g.setTabButton(); g.trigger('afterRemoveTabItem', [tabid]); }, addHeight: function (heightDiff) { var g = this, p = this.options; var newHeight = g.tab.height() + heightDiff; g.setHeight(newHeight); }, setHeight: function (height) { var g = this, p = this.options; g.tab.height(height); g.setContentHeight(); }, setContentHeight: function () { var g = this, p = this.options; var newheight = g.tab.height() - g.tab.links.height(); g.tab.content.height(newheight); $("> .l-tab-content-item", g.tab.content).height(newheight); }, getNewTabid: function () { var g = this, p = this.options; g.getnewidcount = g.getnewidcount || 0; return 'tabitem' + (++g.getnewidcount); }, //notabid 过滤掉tabid的 //noclose 过滤掉没有关闭按钮的 getTabidList: function (notabid, noclose) { var g = this, p = this.options; var tabidlist = []; $("> li", g.tab.links.ul).each(function () { if ($(this).attr("tabid") && $(this).attr("tabid") != notabid && (!noclose || $(".l-tab-links-item-close", this).length > 0)) { tabidlist.push($(this).attr("tabid")); } }); return tabidlist; }, removeOther: function (tabid, compel) { var g = this, p = this.options; var tabidlist = g.getTabidList(tabid, true); $(tabidlist).each(function () { g.removeTabItem(this); }); }, reload: function (tabid) { var g = this, p = this.options; var contentitem = $(".l-tab-content-item[tabid=" + tabid + "]"); var iframeloading = $(".l-tab-loading:first", contentitem); var iframe = $("iframe:first", contentitem); var url = $(iframe).attr("src"); iframeloading.show(); iframe.attr("src", url).unbind('load.tab').bind('load.tab', function () { iframeloading.hide(); }); }, removeAll: function (compel) { var g = this, p = this.options; var tabidlist = g.getTabidList(null, true); $(tabidlist).each(function () { g.removeTabItem(this); }); }, onResize: function () { var g = this, p = this.options; if (!p.height || typeof (p.height) != 'string' || p.height.indexOf('%') == -1) return false; //set tab height if (g.tab.parent()[0].tagName.toLowerCase() == "body") { var windowHeight = $(window).height(); windowHeight -= parseInt(g.tab.parent().css('paddingTop')); windowHeight -= parseInt(g.tab.parent().css('paddingBottom')); g.height = p.heightDiff + windowHeight * parseFloat(g.height) * 0.01; } else { g.height = p.heightDiff + (g.tab.parent().height() * parseFloat(p.height) * 0.01); } g.tab.height(g.height); g.setContentHeight(); }, _menuItemClick: function (item) { var g = this, p = this.options; if (!item.id || !g.actionTabid) return; switch (item.id) { case "close": g.removeTabItem(g.actionTabid); g.actionTabid = null; break; case "closeother": g.removeOther(g.actionTabid); break; case "closeall": g.removeAll(); g.actionTabid = null; break; case "reload": g.selectTabItem(g.actionTabid); g.reload(g.actionTabid); break; } }, _addTabItemContextMenuEven: function (tabitem) { var g = this, p = this.options; tabitem.bind("contextmenu", function (e) { if (!g.tab.menu) return; g.actionTabid = tabitem.attr("tabid"); g.tab.menu.show({ top: e.pageY, left: e.pageX }); if ($(".l-tab-links-item-close", this).length == 0) { g.tab.menu.setDisabled('close'); } else { g.tab.menu.setEnabled('close'); } return false; }); } }); })(jQuery);
zj793039327/Jframework
source/java/web/component/ligerui/js/ligerTab.js
JavaScript
apache-2.0
30,179
import { enableLogger, expectWarn, expectNoWarn } from './../../../services/Logger.mock'; import { Iframe } from './Iframe'; describe('html.Iframe', () => { it('should work ', () => { const props = { type: 'Iframe', src: '#' }; enableLogger(() => { Iframe({ props, context: {} }); }); expectNoWarn(); }); it('should work width margins', () => { const props = { type: 'Iframe', src: '#', marginTop: 10, marginBottom: 20 }; enableLogger(() => { Iframe({ props, context: {} }); }); expectNoWarn(); }); it('not working without src', () => { const props = { type: 'Iframe' }; Iframe({ props, context: {} }); expectWarn(); }); });
webcerebrium/ec-react15-lib
src/editable/html/media/Iframe.test.js
JavaScript
apache-2.0
674
"use strict"; var gulp = require('gulp'); require('require-dir')('./tasks'); var common = require('./tasks/common'); require('web-component-tester').gulp.init(gulp); var args = require('yargs').argv; var version = '0.3.0'; gulp.task('default', function() { console.log('\n Use:\n gulp <clean|gwt[ --gwt-pretty]|test[:validation:sauce]>\n'); }); gulp.task('clean', ['clean:gwt']); gulp.task('gwt', ['gwt:compile', 'gwt:copy']); gulp.task('test', ['test:local']); gulp.task('test:validation', function(done) { common.test( { browserOptions: { name: common.localAddress() + ' / ' + new Date(), build: 'vaadin-components / validation' }, plugins: { sauce: { username: args.sauceUsername, accessKey: args.sauceAccessKey, browsers: [ 'Windows 7/chrome@41', 'Windows 7/firefox@36', 'Windows 7/internet explorer@11' ] }, 'teamcity-reporter': args.teamcity }, root: '.', webserver: { port: 2000, hostname: common.localAddress() } }, done); }); gulp.task('test:vaadin', function(done) { common.test( { browserOptions: { url: 'http://validation-hub.devnet.vaadin.com:4444/wd/hub' }, activeBrowsers: [ { browserName: "chrome", version: "40", platform: "VISTA" } ], root: '.', webserver: { port: 2000, hostname: common.localAddress() } }, done); }); gulp.task('test:sauce', function(done) { common.testSauce( [], ['Windows 7/chrome@41', 'Windows 7/firefox@36', 'Windows 7/internet explorer@11', 'OS X 10.10/safari@8.0', 'OS X 10.10/iphone@8.1', 'Linux/android@5.0'], 'vaadin-components / ' + version, done) });
shahrzadmn/vaadin-grid
gulpfile.js
JavaScript
apache-2.0
1,867
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ var Adaptive; (function (Adaptive) { /** @enum {Adaptive.ContactEmailType} Adaptive.ContactEmailType Enumeration ContactEmailType */ var ContactEmailType = (function () { function ContactEmailType(value) { this.value = value; } ContactEmailType.prototype.toString = function () { return this.value; }; /** @method @static Convert JSON parsed object to enumeration. @return {Adaptive.ContactEmailType} */ ContactEmailType.toObject = function (object) { var retValue = ContactEmailType.Unknown; if (object != null && object.value != null && ContactEmailType.hasOwnProperty(object.value)) { retValue = ContactEmailType[object.value]; } return retValue; }; /** @property {Adaptive.ContactEmailType} [Personal='Personal'] */ ContactEmailType.Personal = new ContactEmailType("Personal"); /** @property {Adaptive.ContactEmailType} [Work='Work'] */ ContactEmailType.Work = new ContactEmailType("Work"); /** @property {Adaptive.ContactEmailType} [Other='Other'] */ ContactEmailType.Other = new ContactEmailType("Other"); /** @property {Adaptive.ContactEmailType} [Unknown='Unknown'] */ ContactEmailType.Unknown = new ContactEmailType("Unknown"); return ContactEmailType; })(); Adaptive.ContactEmailType = ContactEmailType; })(Adaptive || (Adaptive = {})); //# sourceMappingURL=ContactEmailType.js.map
AdaptiveMe/adaptive-arp-javascript
adaptive-arp-js/src_units/ContactEmailType.js
JavaScript
apache-2.0
2,940
"use strict" var ReactWeb = require("react"); var models = require("../../models/common"); class App extends ReactWeb.Component { render(){ var data = JSON.stringify(models.Data.movieData); return ( <div> hello web: {data} </div> ) } } exports.App = App;
agtorre/lifeapp
client/lib/views/web/App.js
JavaScript
apache-2.0
328
var Tletherlynk = {}; Tletherlynk.Midi = ( function( window, undefined ) { var midi = null; // global MIDIAccess object var thisid = null; function Init(){ // //printout = document.getElementById("midistatus"); console.log("Hello midi") if (navigator.requestMIDIAccess){ // navigator.requestMIDIAccess().then( onMIDISuccess, onMIDIFailure ); navigator.requestMIDIAccess({ sysex: false }).then( onMIDISuccess, onMIDIFailure ); } else{ console.log("No MIDI support present in your browser. You're gonna have a bad time.") } } function onMIDISuccess( midiAccess ) { console.log( "MIDI ready!" ); midi = midiAccess; // store in the global (in real usage, would probably keep in an object instance) listInputsAndOutputs(midi); midi.onstatechange = function(e){ console.log("MIDI device "+e.port.state); listInputsAndOutputs(midi); } } function onMIDIFailure(msg) { console.log( "Failed to get MIDI access - " + msg ); } function listInputsAndOutputs( midiAccess ) { var haveAtLeastOneDevice=false; var inputs=midiAccess.inputs.values(); for ( var input = inputs.next(); input && !input.done; input = inputs.next()) { input.value.onmidimessage = MIDIMessageEventHandler; haveAtLeastOneDevice = true; console.log("Midi Inputs =",input.value) } if (!haveAtLeastOneDevice){ console.log("No MIDI input devices present. You're gonna have a bad time."); } var outputs=midiAccess.outputs.values(); for ( var output = outputs.next(); output && !output.done; output = outputs.next()) { console.log("Midi outputs",output.value); if(output.value.name=="APC Key 25" || output.value.name=="APC MINI"){ thisid=output.value.id; } } console.log("output id = ",thisid) } function Sendlight(something,pad,onoff){ // var noteOnMessage = [0x90, 36, 01]; var noteOnMessage = [something, pad, onoff]; if (thisid){ var output = midi.outputs.get(thisid); output.send( noteOnMessage ); } } function MIDIMessageEventHandler(event) { // console.log("input event = ",event.data[0],event.data[1],event.data[2]); var webmidievent = new CustomEvent('webmidievent', { 'detail': {'data1':event.data[0], 'data2':event.data[1], 'data3':event.data[2]} }); document.body.dispatchEvent(webmidievent); } return{ init:Init, sendlight:Sendlight }; } )( window );
Traderlynk/Etherlynk
communicator/extension/js/apc.midi.js
JavaScript
apache-2.0
2,570
/** * Copyright IBM Corp. 2016, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const { defineTest } = require('jscodeshift/dist/testUtils'); defineTest(__dirname, 'size-prop-update');
carbon-design-system/carbon-components
codemods/transforms/__tests__/size-prop-update-test.js
JavaScript
apache-2.0
300
/*eslint no-undef:0*/ /*eslint no-unused-vars:0*/ (function($) { // // This demo uses Animate.css, the collection of excellent CSS animations // https://daneden.github.io/animate.css/ // $.fn.extend({ animateCss: function (animationName, cb) { var animationEnd = "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend"; $(this).addClass("animated " + animationName).one(animationEnd, function() { $(this).removeClass("animated " + animationName); if (cb instanceof Function) { cb.call(this, animationName); } }); }, }); function enterDemoScene($panel) { switch ($panel.attr("id")) { case "basic": enterBasicDemoScene($, $panel); break; case "list": enterListDemoScene($, $panel); break; } } function leaveDemoScene($panel) { switch ($panel.attr("id")) { case "basic": leaveBasicDemoScene($, $panel); break; case "list": leaveListDemoScene($, $panel); break; } } function createIntroScene($) { $("#intro .fa-trash").tooltip().tooltip("disable"); dndx("#intro .fa-envelope", "#intro .fa-trash") .visualcue("Arrow") .onstart(function (eventType, $srcObj, $tgtObj, etc) { $srcObj.data("originalOffset", etc.offset); }) .ondrop(function (eventType, $srcObj, $tgtObj) { $srcObj.animateCss("fadeOutDown", function() { var $this = $(this); $this.offset($this.data("originalOffset")); }); $tgtObj.animateCss("tada", function() { $("#intro .fa-trash").tooltip("enable").tooltip("open"); setTimeout(function() { $("#intro .fa-trash").tooltip("close").tooltip("disable"); }, 2000); }); }) .cursor("move", "pointer"); } function enterIntroScene($, $panel) {} function leaveIntroScene($, $panel) {} $("#tabs").tabs({ active: 0, create: function(e, ui) { createIntroScene($); createBasicDemoScene($); createListDemoScene($); enterDemoScene(ui.panel); }, activate: function(e, ui) { leaveDemoScene(ui.oldPanel); enterDemoScene(ui.newPanel); }, }); }(jQuery));
suewonjp/DNDX.JS
demo/index.js
JavaScript
apache-2.0
2,625
var buf1 = new Buffer("Buffer Buffer Buffer!!!"); var len = buf1.length; // new buffer as slice of old var buf2 = buf1.slice(19,len); console.log(buf2.toString()); buf2.fill("*",0,4); console.log(buf2.toString()); console.log(buf1.toString());
Dr762/NodeJSBase
basics/buf_modify.js
JavaScript
apache-2.0
246
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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. */ import React, { Component } from 'react'; import { Table, Popconfirm } from 'antd'; import InlineEditor from './InlineEditor'; import API from '../../../../data/api.js'; import { Progress } from '../../../Shared'; import ApiPermissionValidation from '../../../../data/ApiPermissionValidation'; class DocumentsTable extends Component { constructor(props) { super(props); this.api_id = this.props.apiId; this.viewDocContentHandler = this.viewDocContentHandler.bind(this); this.handleCloseModal = this.handleCloseModal.bind(this); this.state = { showInlineEditor: false, documentId: null, selectedDocName: null, }; // TODO: Add permission/valid scope checks for document Edit/Delete actions } componentDidMount() { const api = new API(); const promisedAPI = api.get(this.api_id); promisedAPI .then((response) => { this.setState({ api: response.obj }); }) .catch((error) => { if (process.env.NODE_ENV !== 'production') { console.log(error); } const { status } = error; if (status === 404) { this.setState({ notFound: true }); } }); } /* On click listener for 'View' link on each document related row in the documents table. 1- If the document type is 'URL' open it in new tab 2- If the document type is 'INLINE' open the content with an inline editor 3- If the document type is 'FILE' download the file */ viewDocContentHandler(document) { if (document.sourceType === 'URL') { window.open(document.sourceUrl, '_blank'); } else if (document.sourceType === 'INLINE') { this.setState({ documentId: document.documentId, showInlineEditor: true, selectedDocName: document.name, }); } else if (document.sourceType === 'FILE') { const promised_get_content = this.props.client.getFileForDocument(this.props.apiId, document.documentId); promised_get_content .then((done) => { this.props.downloadFile(done); }) .catch((error_response) => { const error_data = JSON.parse(error_response.data); const messageTxt = 'Error[' + error_data.code + ']: ' + error_data.description + ' | ' + error_data.message + '.'; console.error(messageTxt); }); } } handleCloseModal() { this.setState({ showInlineEditor: false }); } render() { if (!this.state.api) { return <Progress />; } this.columns = [ { title: 'Name', dataIndex: 'name', key: 'name', }, { title: 'Source', dataIndex: 'sourceType', key: 'sourceType', }, { title: 'Actions', dataIndex: 'actions', key: 'actions', render: (text1, record) => ( <div> <ApiPermissionValidation userPermissions={this.state.api.userPermissionsForApi}> <a href='#' onClick={() => this.props.onEditAPIDocument(record)}> Edit| </a> </ApiPermissionValidation> <a href='#' onClick={() => this.viewDocContentHandler(record)}> View | </a> <ApiPermissionValidation userPermissions={this.state.api.userPermissionsForApi}> <Popconfirm title='Are you sure you want to delete this document?' onConfirm={() => this.props.deleteDocHandler(record.documentId)} okText='Yes' cancelText='No' > <a href='#'>Delete</a> </Popconfirm> </ApiPermissionValidation> </div> ), }, ]; return ( <div style={{ paddingTop: 20 }}> <h3 style={{ paddingBottom: 15 }}>Current Documents</h3> <Table dataSource={this.props.documentsList} columns={this.columns} /> {this.state.showInlineEditor && ( <InlineEditor showInlineEditor={this.state.showInlineEditor} handleCloseModal={this.handleCloseModal} apiId={this.props.apiId} documentId={this.state.documentId} documentName={this.state.selectedDocName} client={this.props.client} /> )} </div> ); } } export default DocumentsTable;
Minoli/carbon-apimgt
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Details/Documents/DocumentsTable.js
JavaScript
apache-2.0
5,936
var init={ verifyCode:'', loadinfo:function(obj){ }, createCode:function(obj){ code = ""; var codeLength = 4;//验证码的长度 var random = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z');//随机数 for(var i = 0; i < codeLength; i++) {//循环操作 var index = Math.floor(Math.random()*36);//取得随机数的索引(0~35) code += random[index];//根据索引取得随机数加到code上 } init.verifyCode = code;//把code值赋给验证码 $('#createcode').val(code); }, login:function(){ if($('#username').val()==''||$('#username').val()==undefined){ $('.login-name').find('p').text('请输入用户名!').show(); return false; } else{ $('.login-name').find('p').hide(); } if($('#password').val()==''||$('#password').val()==undefined){ $('.login-psw').find('p').text('请输入密码!').show(); return false; } else{ $('.login-psw').find('p').hide(); } if($('#verifycode').val()==''||$('#verifycode').val()==undefined){ $('.login-verify').find('p').text('请输入验证码!').show(); init.createCode(); return false; } else if($('#verifycode').val().length !=4){ $('.login-verify').find('p').text('请输入4位验证码!').show(); init.createCode(); return false; } else{ if($('#verifycode').val().toUpperCase()!=init.verifyCode){ $('.login-verify').find('p').text('验证码输入错误!').show(); init.createCode(); return false; } else{ $('.login-verify').find('p').hide(); } } $.ajax({ url:"", type:"post", data:{'username':$('#username').val(),'password':$('#password').val()}, dataType:"json" }).done(function(data){ }).fail(function(data){ }).always(function(){ }); } } $(function(){ init.createCode(); $('#createcode').click(function(){ init.createCode(); }); $('.main-button').click(function(){ init.login(); }) });
yangleo/cloud-github
openstack_dashboard/static/dashboard/js/login.js
JavaScript
apache-2.0
2,073
'use strict'; var base = require('../_base'); module.exports = function(warp){ return base.defineModel(warp, 'SnippetFlow', [ base.column_varchar_20('flow_type'), base.column_id('snippet_id', { index: true }), base.column_id('user_id'), base.column_varchar_50('name'), base.column_varchar_100('brief'), base.column_varchar_20('language'), base.column_varchar_20('environment'), base.column_varchar_100('keywords'), base.column_varchar_20('type', {defautValue:'code'}),//'code', 'file', 'zip' base.column_text('code'), base.column_text('help'), base.column_bigint('newversion'), base.column_bigint('score'), base.column_varchar_20('result', {defaultValue:'processing'}), base.column_text('contributor') //id1,id2,id3,... ], { table: 'snippet_flow' }); };
kittqiu/snippet-fibula
www/model/snippet/snippet_flow.js
JavaScript
apache-2.0
793
/** @Name:layui.form 表单组件 @Author:贤心 @License:LGPL */ layui.define('layer', function(exports){ "use strict"; var $ = layui.jquery ,layer = layui.layer ,hint = layui.hint() ,device = layui.device() ,MOD_NAME = 'form', ELEM = '.layui-form', THIS = 'layui-this', SHOW = 'layui-show' ,Form = function(){ this.config = { verify: { required: [ /[\S]+/ ,'必填项不能为空' ] ,phone: [ /^1\d{10}$/ ,'请输入正确的手机号' ] ,email: [ /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/ ,'邮箱格式不正确' ] ,url: [ /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/ ,'链接格式不正确' ] ,number: [ /^\d+$/ ,'只能填写数字' ] ,date: [ /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/ ,'日期格式不正确' ] ,identity: [ /(^\d{15}$)|(^\d{17}(x|X|\d)$)/ ,'请输入正确的身份证号' ] } }; }; //全局设置 Form.prototype.set = function(options){ var that = this; $.extend(true, that.config, options); return that; }; //验证规则设定 Form.prototype.verify = function(settings){ var that = this; $.extend(true, that.config.verify, settings); return that; }; //表单事件监听 Form.prototype.on = function(events, callback){ return layui.onevent(MOD_NAME, events, callback); }; //表单控件渲染 Form.prototype.render = function(type){ var that = this, items = { //下拉选择框 select: function(){ var TIPS = '请选择', CLASS = 'layui-form-select', TITLE = 'layui-select-title' ,selects = $(ELEM).find('select'), hide = function(e, clear){ if(!$(e.target).parent().hasClass(TITLE) || clear){ $('.'+CLASS).removeClass(CLASS+'ed'); } } ,events = function(reElem){ var select = $(this), title = reElem.find('.' + TITLE); //展开下拉 title.on('click', function(e){ reElem.hasClass(CLASS+'ed') ? reElem.removeClass(CLASS+'ed') : ( hide(e, true), reElem.addClass(CLASS+'ed') ); }); //选择 reElem.find('dl>dd').on('click', function(){ var othis = $(this), value = othis.attr('lay-value'); var filter = select.attr('lay-filter'); //获取过滤器 select.val(value).removeClass('layui-form-danger'), title.find('input').val(othis.text()); othis.addClass(THIS).siblings().removeClass(THIS); layui.event(MOD_NAME, 'select('+ filter +')', { elem: select[0] ,value: value }); }); reElem.find('dl>dt').on('click', function(e){ layui.stope(e); }); //关闭下拉 $(document).off('click', hide).on('click', hide) } selects.each(function(index, select){ var othis = $(this), hasRender = othis.next('.'+CLASS); var value = select.value, selected = $(select.options[select.selectedIndex]); //获取当前选中项 //替代元素 var reElem = $(['<div class="layui-unselect '+ CLASS +'">' ,'<div class="'+ TITLE +'"><input type="text" placeholder="'+ (select.options[0].innerHTML ? select.options[0].innerHTML : TIPS) +'" value="'+ (value ? selected.html() : '') +'" readonly class="layui-input layui-unselect">' ,'<i class="layui-edge"></i></div>' ,'<dl class="layui-anim layui-anim-upbit'+ (othis.find('optgroup')[0] ? ' layui-select-group' : '') +'">'+ function(options){ var arr = []; layui.each(options, function(index, item){ if(index === 0 && !item.value) return; if(item.tagName.toLowerCase() === 'optgroup'){ arr.push('<dt>'+ item.label +'</dt>'); } else { arr.push('<dd lay-value="'+ item.value +'" '+ (value === item.value ? 'class="'+ THIS +'"' : '')+'>'+ item.innerHTML +'</dd>'); } }); return arr.join(''); }(othis.find('*')) +'</dl>' ,'</div>'].join('')); hasRender[0] && hasRender.remove(); //如果已经渲染,则Rerender othis.after(reElem); events.call(this, reElem); }); } //复选框/开关 ,checkbox: function(){ var CLASS = { checkbox: ['layui-form-checkbox', 'layui-form-checked', 'checkbox'] ,_switch: ['layui-form-switch', 'layui-form-onswitch', 'switch'] } ,checks = $(ELEM).find('input[type=checkbox]') ,events = function(reElem, RE_CLASS){ var check = $(this); //勾选 reElem.on('click', function(){ var filter = check.attr('lay-filter'); //获取过滤器 check[0].checked ? ( check[0].checked = false ,reElem.removeClass(RE_CLASS[1]) ) : ( check[0].checked = true ,reElem.addClass(RE_CLASS[1]) ); layui.event(MOD_NAME, RE_CLASS[2]+'('+ filter +')', { elem: check[0] ,value: check[0].value }); }); } checks.each(function(index, check){ var othis = $(this), skin = othis.attr('lay-skin'); if(skin === 'switch') skin = '_'+skin; var RE_CLASS = CLASS[skin] || CLASS.checkbox; //替代元素 var hasRender = othis.next('.' + RE_CLASS[0]); var reElem = $(['<div class="layui-unselect '+ RE_CLASS[0] + ( check.checked ? (' '+RE_CLASS[1]) : '') +'">' ,{ _switch: '<i></i>' }[skin] || ('<span>'+ (check.title || '勾选') +'</span><i class="layui-icon">&#xe618;</i>') ,'</div>'].join('')); hasRender[0] && hasRender.remove(); //如果已经渲染,则Rerender othis.after(reElem); events.call(this, reElem, RE_CLASS); }); } //单选框 ,radio: function(){ var CLASS = 'layui-form-radio', ICON = ['&#xe643;', '&#xe63f;'] ,radios = $(ELEM).find('input[type=radio]') ,events = function(reElem){ var radio = $(this), ANIM = 'layui-anim-scaleSpring'; reElem.on('click', function(){ var name = radio[0].name, forms = radio.parents(ELEM); var filter = radio.attr('lay-filter'); //获取过滤器 var sameRadio = forms.find('input[name='+ name +']'); //找到相同name的兄弟 layui.each(sameRadio, function(){ var next = $(this).next('.'+CLASS); this.checked = false; next.removeClass(CLASS+'ed'); next.find('.layui-icon').removeClass(ANIM).html(ICON[1]); }); radio[0].checked = true; reElem.addClass(CLASS+'ed'); reElem.find('.layui-icon').addClass(ANIM).html(ICON[0]); layui.event(MOD_NAME, 'radio('+ filter +')', { elem: radio[0] ,value: radio[0].value }); }); }; radios.each(function(index, radio){ var othis = $(this), hasRender = othis.next('.' + CLASS); //替代元素 var reElem = $(['<div class="layui-unselect '+ CLASS + (radio.checked ? (' '+CLASS+'ed') : '') +'">' ,'<i class="layui-anim layui-icon">'+ ICON[radio.checked ? 0 : 1] +'</i>' ,'<span>'+ (radio.title||'未命名') +'</span>' ,'</div>'].join('')); hasRender[0] && hasRender.remove(); //如果已经渲染,则Rerender othis.after(reElem); events.call(this, reElem); }); } }; type ? ( items[type] ? items[type]() : hint.error('不支持的'+ type + '表单渲染') ) : layui.each(items, function(index, item){ item(); }); return that; }; //表单提交校验 var submit = function(){ var button = $(this), verify = form.config.verify, stop = null ,DANGER = 'layui-form-danger', field = {} ,elem = button.parents(ELEM) ,verifyElem = elem.find('*[lay-verify]') //获取需要校验的元素 ,formElem = button.parents('form')[0] //获取当前所在的form元素,如果存在的话 ,fieldElem = elem.find('input,select,textarea') //获取所有表单域 ,filter = button.attr('lay-filter'); //获取过滤器 //开始校验 layui.each(verifyElem, function(_, item){ var othis = $(this), ver = othis.attr('lay-verify'), tips = ''; var value = othis.val(), isFn = typeof verify[ver] === 'function'; othis.removeClass(DANGER); if(verify[ver] && (isFn ? tips = verify[ver](value, item) : !verify[ver][0].test(value)) ){ layer.msg(tips || verify[ver][1], { icon: 5 ,shift: 6 }); //非移动设备自动定位焦点 if(!device.android && !device.ios){ item.focus(); } othis.addClass(DANGER); return stop = true; } }); if(stop) return false; layui.each(fieldElem, function(_, item){ if(!item.name) return; if(/^checkbox|radio$/.test(item.type) && !item.checked) return; field[item.name] = item.value; }); //获取字段 return layui.event.call(this, MOD_NAME, 'submit('+ filter +')', { elem: this ,form: formElem ,field: field }); }; //自动完成渲染 var form = new Form(), dom = $(document); form.render(); //表单reset重置渲染 dom.on('reset', ELEM, function(){ setTimeout(function(){ form.render(); }, 50); }); //表单提交事件 dom.on('submit', ELEM, submit) .on('click', '*[lay-submit]', submit); exports(MOD_NAME, function(options){ return form.set(options); }); });
zhang-li-mark/psas
src/main/webapp/res/layui/lay/modules/form.js
JavaScript
apache-2.0
10,721
angular.module('app.layouts') .controller('PublicLayoutController', function( $rootScope, $scope, $mdSidenav, $state, $log, $Configuration, $mdDialog, $mdToast, $stateParams, $timeout, $galeLoading, $Identity ) { if ($Identity.isAuthenticated()) { $scope.user = $Identity.getCurrent(); } //------------------------------------------------------------------------------------ // Model $scope.config = { application: $Configuration.get("application") }; $scope.toogleMenu = function(side) { $mdSidenav(side).toggle(); }; $scope.logout = function() { $Identity.logOut(); }; });
dmunozgaete/Widul-Web
app/views/layouts/public.js
JavaScript
apache-2.0
851
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /*jslint node: true */ 'use strict'; // Variables const _ = require('lodash'), async = require('neo-async'); // Export module module.exports = { /** * Configure database * * @param database */ setup: function (database) { database.define('user', require('../schema/user')); }, /** * Create new user * * @param {KarmiaDatabase} database * @param {Object} data * @param {Function} callback */ create: function (database, data, callback) { data = data || {}; if (_.isFunction(data)) { callback = data; data = {}; } const sequence = database.sequence('user_id'), table = database.table('user'); async.waterfall([ function (done) { if (data.user_id) { done(null, data.user_id); } else { sequence.get(done); } }, function (user_id, done) { data.user_id = user_id; const user = new table.model(data); user.save(function (error, result) { done(error, result); }); } ], callback); }, /** * Create user context * * @param {KarmiaDatabase} database * @param {EqSession} session * @param {string} user_id * @param {Function} callback */ createContext: function (database, session, user_id, callback) { const user = database.suite('user').create(user_id); async.waterfall([ // Get user data user.get.bind(user), // Merge user data function (result, done) { result = result || {}; user.name = result.name; user.public_key = result.public_key; user.now = result.now; user.session = session; done(null, user); } ], callback); } }; /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */
eq-inc/eq-user
lib/index.js
JavaScript
apache-2.0
2,220
/*! Pts.js is licensed under Apache License 2.0. Copyright © 2017-current William Ngan and contributors. (https://github.com/williamngan/pts) */ import { Util } from "./Util"; import { Geom, Num } from "./Num"; import { Pt, Group } from "./Pt"; import { Mat } from "./LinearAlgebra"; let _errorLength = (obj, param = "expected") => Util.warn("Group's length is less than " + param, obj); let _errorOutofBound = (obj, param = "") => Util.warn(`Index ${param} is out of bound in Group`, obj); export class Line { static fromAngle(anchor, angle, magnitude) { let g = new Group(new Pt(anchor), new Pt(anchor)); g[1].toAngle(angle, magnitude, true); return g; } static slope(p1, p2) { return (p2[0] - p1[0] === 0) ? undefined : (p2[1] - p1[1]) / (p2[0] - p1[0]); } static intercept(p1, p2) { if (p2[0] - p1[0] === 0) { return undefined; } else { let m = (p2[1] - p1[1]) / (p2[0] - p1[0]); let c = p1[1] - m * p1[0]; return { slope: m, yi: c, xi: (m === 0) ? undefined : -c / m }; } } static sideOfPt2D(line, pt) { let _line = Util.iterToArray(line); return (_line[1][0] - _line[0][0]) * (pt[1] - _line[0][1]) - (pt[0] - _line[0][0]) * (_line[1][1] - _line[0][1]); } static collinear(p1, p2, p3, threshold = 0.01) { let a = new Pt(0, 0, 0).to(p1).$subtract(p2); let b = new Pt(0, 0, 0).to(p1).$subtract(p3); return a.$cross(b).divide(1000).equals(new Pt(0, 0, 0), threshold); } static magnitude(line) { let _line = Util.iterToArray(line); return (_line.length >= 2) ? _line[1].$subtract(_line[0]).magnitude() : 0; } static magnitudeSq(line) { let _line = Util.iterToArray(line); return (_line.length >= 2) ? _line[1].$subtract(_line[0]).magnitudeSq() : 0; } static perpendicularFromPt(line, pt, asProjection = false) { let _line = Util.iterToArray(line); if (_line[0].equals(_line[1])) return undefined; let a = _line[0].$subtract(_line[1]); let b = _line[1].$subtract(pt); let proj = b.$subtract(a.$project(b)); return (asProjection) ? proj : proj.$add(pt); } static distanceFromPt(line, pt) { let _line = Util.iterToArray(line); let projectionVector = Line.perpendicularFromPt(_line, pt, true); if (projectionVector) { return projectionVector.magnitude(); } else { return _line[0].$subtract(pt).magnitude(); } } static intersectRay2D(la, lb) { let _la = Util.iterToArray(la); let _lb = Util.iterToArray(lb); let a = Line.intercept(_la[0], _la[1]); let b = Line.intercept(_lb[0], _lb[1]); let pa = _la[0]; let pb = _lb[0]; if (a == undefined) { if (b == undefined) return undefined; let y1 = -b.slope * (pb[0] - pa[0]) + pb[1]; return new Pt(pa[0], y1); } else { if (b == undefined) { let y1 = -a.slope * (pa[0] - pb[0]) + pa[1]; return new Pt(pb[0], y1); } else if (b.slope != a.slope) { let px = (a.slope * pa[0] - b.slope * pb[0] + pb[1] - pa[1]) / (a.slope - b.slope); let py = a.slope * (px - pa[0]) + pa[1]; return new Pt(px, py); } else { if (a.yi == b.yi) { return new Pt(pa[0], pa[1]); } else { return undefined; } } } } static intersectLine2D(la, lb) { let _la = Util.iterToArray(la); let _lb = Util.iterToArray(lb); let pt = Line.intersectRay2D(_la, _lb); return (pt && Geom.withinBound(pt, _la[0], _la[1]) && Geom.withinBound(pt, _lb[0], _lb[1])) ? pt : undefined; } static intersectLineWithRay2D(line, ray) { let _line = Util.iterToArray(line); let _ray = Util.iterToArray(ray); let pt = Line.intersectRay2D(_line, _ray); return (pt && Geom.withinBound(pt, _line[0], _line[1])) ? pt : undefined; } static intersectPolygon2D(lineOrRay, poly, sourceIsRay = false) { let _lineOrRay = Util.iterToArray(lineOrRay); let _poly = Util.iterToArray(poly); let fn = sourceIsRay ? Line.intersectLineWithRay2D : Line.intersectLine2D; let pts = new Group(); for (let i = 0, len = _poly.length; i < len; i++) { let next = (i === len - 1) ? 0 : i + 1; let d = fn([_poly[i], _poly[next]], _lineOrRay); if (d) pts.push(d); } return (pts.length > 0) ? pts : undefined; } static intersectLines2D(lines1, lines2, isRay = false) { let group = new Group(); let fn = isRay ? Line.intersectLineWithRay2D : Line.intersectLine2D; for (let l1 of lines1) { for (let l2 of lines2) { let _ip = fn(l1, l2); if (_ip) group.push(_ip); } } return group; } static intersectGridWithRay2D(ray, gridPt) { let _ray = Util.iterToArray(ray); let t = Line.intercept(new Pt(_ray[0]).subtract(gridPt), new Pt(_ray[1]).subtract(gridPt)); let g = new Group(); if (t && t.xi) g.push(new Pt(gridPt[0] + t.xi, gridPt[1])); if (t && t.yi) g.push(new Pt(gridPt[0], gridPt[1] + t.yi)); return g; } static intersectGridWithLine2D(line, gridPt) { let _line = Util.iterToArray(line); let g = Line.intersectGridWithRay2D(_line, gridPt); let gg = new Group(); for (let i = 0, len = g.length; i < len; i++) { if (Geom.withinBound(g[i], _line[0], _line[1])) gg.push(g[i]); } return gg; } static intersectRect2D(line, rect) { let _line = Util.iterToArray(line); let _rect = Util.iterToArray(rect); let box = Geom.boundingBox(Group.fromPtArray(_line)); if (!Rectangle.hasIntersectRect2D(box, _rect)) return new Group(); return Line.intersectLines2D([_line], Rectangle.sides(_rect)); } static subpoints(line, num) { let _line = Util.iterToArray(line); let pts = new Group(); for (let i = 1; i <= num; i++) { pts.push(Geom.interpolate(_line[0], _line[1], i / (num + 1))); } return pts; } static crop(line, size, index = 0, cropAsCircle = true) { let _line = Util.iterToArray(line); let tdx = (index === 0) ? 1 : 0; let ls = _line[tdx].$subtract(_line[index]); if (ls[0] === 0 || size[0] === 0) return _line[index]; if (cropAsCircle) { let d = ls.unit().multiply(size[1]); return _line[index].$add(d); } else { let rect = Rectangle.fromCenter(_line[index], size); let sides = Rectangle.sides(rect); let sideIdx = 0; if (Math.abs(ls[1] / ls[0]) > Math.abs(size[1] / size[0])) { sideIdx = (ls[1] < 0) ? 0 : 2; } else { sideIdx = (ls[0] < 0) ? 3 : 1; } return Line.intersectRay2D(sides[sideIdx], _line); } } static marker(line, size, graphic = ("arrow" || "line"), atTail = true) { let _line = Util.iterToArray(line); let h = atTail ? 0 : 1; let t = atTail ? 1 : 0; let unit = _line[h].$subtract(_line[t]); if (unit.magnitudeSq() === 0) return new Group(); unit.unit(); let ps = Geom.perpendicular(unit).multiply(size[0]).add(_line[t]); if (graphic == "arrow") { ps.add(unit.$multiply(size[1])); return new Group(_line[t], ps[0], ps[1]); } else { return new Group(ps[0], ps[1]); } } static toRect(line) { let _line = Util.iterToArray(line); return new Group(_line[0].$min(_line[1]), _line[0].$max(_line[1])); } } export class Rectangle { static from(topLeft, widthOrSize, height) { return Rectangle.fromTopLeft(topLeft, widthOrSize, height); } static fromTopLeft(topLeft, widthOrSize, height) { let size = (typeof widthOrSize == "number") ? [widthOrSize, (height || widthOrSize)] : widthOrSize; return new Group(new Pt(topLeft), new Pt(topLeft).add(size)); } static fromCenter(center, widthOrSize, height) { let half = (typeof widthOrSize == "number") ? [widthOrSize / 2, (height || widthOrSize) / 2] : new Pt(widthOrSize).divide(2); return new Group(new Pt(center).subtract(half), new Pt(center).add(half)); } static toCircle(pts, within = true) { return Circle.fromRect(pts, within); } static toSquare(pts, enclose = false) { let _pts = Util.iterToArray(pts); let s = Rectangle.size(_pts); let m = (enclose) ? s.maxValue().value : s.minValue().value; return Rectangle.fromCenter(Rectangle.center(_pts), m, m); } static size(pts) { let p = Util.iterToArray(pts); return p[0].$max(p[1]).subtract(p[0].$min(p[1])); } static center(pts) { let p = Util.iterToArray(pts); let min = p[0].$min(p[1]); let max = p[0].$max(p[1]); return min.add(max.$subtract(min).divide(2)); } static corners(rect) { let _rect = Util.iterToArray(rect); let p0 = _rect[0].$min(_rect[1]); let p2 = _rect[0].$max(_rect[1]); return new Group(p0, new Pt(p2.x, p0.y), p2, new Pt(p0.x, p2.y)); } static sides(rect) { let [p0, p1, p2, p3] = Rectangle.corners(rect); return [ new Group(p0, p1), new Group(p1, p2), new Group(p2, p3), new Group(p3, p0) ]; } static boundingBox(rects) { let _rects = Util.iterToArray(rects); let merged = Util.flatten(_rects, false); let min = Pt.make(2, Number.MAX_VALUE); let max = Pt.make(2, Number.MIN_VALUE); for (let i = 0, len = merged.length; i < len; i++) { let k = 0; for (let m of merged[i]) { min[k] = Math.min(min[k], m[k]); max[k] = Math.max(max[k], m[k]); if (++k >= 2) break; } } return new Group(min, max); } static polygon(rect) { return Rectangle.corners(rect); } static quadrants(rect, center) { let _rect = Util.iterToArray(rect); let corners = Rectangle.corners(_rect); let _center = (center != undefined) ? new Pt(center) : Rectangle.center(_rect); return corners.map((c) => new Group(c, _center).boundingBox()); } static halves(rect, ratio = 0.5, asRows = false) { let _rect = Util.iterToArray(rect); let min = _rect[0].$min(_rect[1]); let max = _rect[0].$max(_rect[1]); let mid = (asRows) ? Num.lerp(min[1], max[1], ratio) : Num.lerp(min[0], max[0], ratio); return (asRows) ? [new Group(min, new Pt(max[0], mid)), new Group(new Pt(min[0], mid), max)] : [new Group(min, new Pt(mid, max[1])), new Group(new Pt(mid, min[1]), max)]; } static withinBound(rect, pt) { let _rect = Util.iterToArray(rect); return Geom.withinBound(pt, _rect[0], _rect[1]); } static hasIntersectRect2D(rect1, rect2, resetBoundingBox = false) { let _rect1 = Util.iterToArray(rect1); let _rect2 = Util.iterToArray(rect2); if (resetBoundingBox) { _rect1 = Geom.boundingBox(_rect1); _rect2 = Geom.boundingBox(_rect2); } if (_rect1[0][0] > _rect2[1][0] || _rect2[0][0] > _rect1[1][0]) return false; if (_rect1[0][1] > _rect2[1][1] || _rect2[0][1] > _rect1[1][1]) return false; return true; } static intersectRect2D(rect1, rect2) { let _rect1 = Util.iterToArray(rect1); let _rect2 = Util.iterToArray(rect2); if (!Rectangle.hasIntersectRect2D(_rect1, _rect2)) return new Group(); return Line.intersectLines2D(Rectangle.sides(_rect1), Rectangle.sides(_rect2)); } } export class Circle { static fromRect(pts, enclose = false) { let _pts = Util.iterToArray(pts); let r = 0; let min = r = Rectangle.size(_pts).minValue().value / 2; if (enclose) { let max = Rectangle.size(_pts).maxValue().value / 2; r = Math.sqrt(min * min + max * max); } else { r = min; } return new Group(Rectangle.center(_pts), new Pt(r, r)); } static fromTriangle(pts, enclose = false) { if (enclose) { return Triangle.circumcircle(pts); } else { return Triangle.incircle(pts); } } static fromCenter(pt, radius) { return new Group(new Pt(pt), new Pt(radius, radius)); } static withinBound(pts, pt, threshold = 0) { let _pts = Util.iterToArray(pts); let d = _pts[0].$subtract(pt); return d.dot(d) + threshold < _pts[1].x * _pts[1].x; } static intersectRay2D(circle, ray) { let _pts = Util.iterToArray(circle); let _ray = Util.iterToArray(ray); let d = _ray[0].$subtract(_ray[1]); let f = _pts[0].$subtract(_ray[0]); let a = d.dot(d); let b = f.dot(d); let c = f.dot(f) - _pts[1].x * _pts[1].x; let p = b / a; let q = c / a; let disc = p * p - q; if (disc < 0) { return new Group(); } else { let discSqrt = Math.sqrt(disc); let t1 = -p + discSqrt; let p1 = _ray[0].$subtract(d.$multiply(t1)); if (disc === 0) return new Group(p1); let t2 = -p - discSqrt; let p2 = _ray[0].$subtract(d.$multiply(t2)); return new Group(p1, p2); } } static intersectLine2D(circle, line) { let _pts = Util.iterToArray(circle); let _line = Util.iterToArray(line); let ps = Circle.intersectRay2D(_pts, _line); let g = new Group(); if (ps.length > 0) { for (let i = 0, len = ps.length; i < len; i++) { if (Rectangle.withinBound(_line, ps[i])) g.push(ps[i]); } } return g; } static intersectCircle2D(circle1, circle2) { let _pts = Util.iterToArray(circle1); let _circle = Util.iterToArray(circle2); let dv = _circle[0].$subtract(_pts[0]); let dr2 = dv.magnitudeSq(); let dr = Math.sqrt(dr2); let ar = _pts[1].x; let br = _circle[1].x; let ar2 = ar * ar; let br2 = br * br; if (dr > ar + br) { return new Group(); } else if (dr < Math.abs(ar - br)) { return new Group(_pts[0].clone()); } else { let a = (ar2 - br2 + dr2) / (2 * dr); let h = Math.sqrt(ar2 - a * a); let p = dv.$multiply(a / dr).add(_pts[0]); return new Group(new Pt(p.x + h * dv.y / dr, p.y - h * dv.x / dr), new Pt(p.x - h * dv.y / dr, p.y + h * dv.x / dr)); } } static intersectRect2D(circle, rect) { let _pts = Util.iterToArray(circle); let _rect = Util.iterToArray(rect); let sides = Rectangle.sides(_rect); let g = []; for (let i = 0, len = sides.length; i < len; i++) { let ps = Circle.intersectLine2D(_pts, sides[i]); if (ps.length > 0) g.push(ps); } return Util.flatten(g); } static toRect(circle, within = false) { let _pts = Util.iterToArray(circle); let r = _pts[1][0]; if (within) { let half = Math.sqrt(r * r) / 2; return new Group(_pts[0].$subtract(half), _pts[0].$add(half)); } else { return new Group(_pts[0].$subtract(r), _pts[0].$add(r)); } } static toTriangle(circle, within = true) { let _pts = Util.iterToArray(circle); if (within) { let ang = -Math.PI / 2; let inc = Math.PI * 2 / 3; let g = new Group(); for (let i = 0; i < 3; i++) { g.push(_pts[0].clone().toAngle(ang, _pts[1][0], true)); ang += inc; } return g; } else { return Triangle.fromCenter(_pts[0], _pts[1][0]); } } } export class Triangle { static fromRect(rect) { let _rect = Util.iterToArray(rect); let top = _rect[0].$add(_rect[1]).divide(2); top.y = _rect[0][1]; let left = _rect[1].clone(); left.x = _rect[0][0]; return new Group(top, _rect[1].clone(), left); } static fromCircle(circle) { return Circle.toTriangle(circle, true); } static fromCenter(pt, size) { return Triangle.fromCircle(Circle.fromCenter(pt, size)); } static medial(tri) { let _pts = Util.iterToArray(tri); if (_pts.length < 3) return _errorLength(new Group(), 3); return Polygon.midpoints(_pts, true); } static oppositeSide(tri, index) { let _pts = Util.iterToArray(tri); if (_pts.length < 3) return _errorLength(new Group(), 3); if (index === 0) { return Group.fromPtArray([_pts[1], _pts[2]]); } else if (index === 1) { return Group.fromPtArray([_pts[0], _pts[2]]); } else { return Group.fromPtArray([_pts[0], _pts[1]]); } } static altitude(tri, index) { let _pts = Util.iterToArray(tri); let opp = Triangle.oppositeSide(_pts, index); if (opp.length > 1) { return new Group(_pts[index], Line.perpendicularFromPt(opp, _pts[index])); } else { return new Group(); } } static orthocenter(tri) { let _pts = Util.iterToArray(tri); if (_pts.length < 3) return _errorLength(undefined, 3); let a = Triangle.altitude(_pts, 0); let b = Triangle.altitude(_pts, 1); return Line.intersectRay2D(a, b); } static incenter(tri) { let _pts = Util.iterToArray(tri); if (_pts.length < 3) return _errorLength(undefined, 3); let a = Polygon.bisector(_pts, 0).add(_pts[0]); let b = Polygon.bisector(_pts, 1).add(_pts[1]); return Line.intersectRay2D(new Group(_pts[0], a), new Group(_pts[1], b)); } static incircle(tri, center) { let _pts = Util.iterToArray(tri); let c = (center) ? center : Triangle.incenter(_pts); let area = Polygon.area(_pts); let perim = Polygon.perimeter(_pts, true); let r = 2 * area / perim.total; return Circle.fromCenter(c, r); } static circumcenter(tri) { let _pts = Util.iterToArray(tri); let md = Triangle.medial(_pts); let a = [md[0], Geom.perpendicular(_pts[0].$subtract(md[0])).p1.$add(md[0])]; let b = [md[1], Geom.perpendicular(_pts[1].$subtract(md[1])).p1.$add(md[1])]; return Line.intersectRay2D(a, b); } static circumcircle(tri, center) { let _pts = Util.iterToArray(tri); let c = (center) ? center : Triangle.circumcenter(_pts); let r = _pts[0].$subtract(c).magnitude(); return Circle.fromCenter(c, r); } } export class Polygon { static centroid(pts) { return Geom.centroid(pts); } static rectangle(center, widthOrSize, height) { return Rectangle.corners(Rectangle.fromCenter(center, widthOrSize, height)); } static fromCenter(center, radius, sides) { let g = new Group(); for (let i = 0; i < sides; i++) { let ang = Math.PI * 2 * i / sides; g.push(new Pt(Math.cos(ang) * radius, Math.sin(ang) * radius).add(center)); } return g; } static lineAt(pts, index) { let _pts = Util.iterToArray(pts); if (index < 0 || index >= _pts.length) throw new Error("index out of the Polygon's range"); return new Group(_pts[index], (index === _pts.length - 1) ? _pts[0] : _pts[index + 1]); } static lines(poly, closePath = true) { let _pts = Util.iterToArray(poly); if (_pts.length < 2) return _errorLength(new Group(), 2); let sp = Util.split(_pts, 2, 1); if (closePath) sp.push(new Group(_pts[_pts.length - 1], _pts[0])); return sp.map((g) => g); } static midpoints(poly, closePath = false, t = 0.5) { let sides = Polygon.lines(poly, closePath); let mids = sides.map((s) => Geom.interpolate(s[0], s[1], t)); return mids; } static adjacentSides(poly, index, closePath = false) { let _pts = Util.iterToArray(poly); if (_pts.length < 2) return _errorLength(new Group(), 2); if (index < 0 || index >= _pts.length) return _errorOutofBound(new Group(), index); let gs = []; let left = index - 1; if (closePath && left < 0) left = _pts.length - 1; if (left >= 0) gs.push(new Group(_pts[index], _pts[left])); let right = index + 1; if (closePath && right > _pts.length - 1) right = 0; if (right <= _pts.length - 1) gs.push(new Group(_pts[index], _pts[right])); return gs; } static bisector(poly, index) { let sides = Polygon.adjacentSides(poly, index, true); if (sides.length >= 2) { let a = sides[0][1].$subtract(sides[0][0]).unit(); let b = sides[1][1].$subtract(sides[1][0]).unit(); return a.add(b).divide(2); } else { return undefined; } } static perimeter(poly, closePath = false) { let lines = Polygon.lines(poly, closePath); let mag = 0; let p = Pt.make(lines.length, 0); for (let i = 0, len = lines.length; i < len; i++) { let m = Line.magnitude(lines[i]); mag += m; p[i] = m; } return { total: mag, segments: p }; } static area(pts) { let _pts = Util.iterToArray(pts); if (_pts.length < 3) return _errorLength(new Group(), 3); let det = (a, b) => a[0] * b[1] - a[1] * b[0]; let area = 0; for (let i = 0, len = _pts.length; i < len; i++) { if (i < _pts.length - 1) { area += det(_pts[i], _pts[i + 1]); } else { area += det(_pts[i], _pts[0]); } } return Math.abs(area / 2); } static convexHull(pts, sorted = false) { let _pts = Util.iterToArray(pts); if (_pts.length < 3) return _errorLength(new Group(), 3); if (!sorted) { _pts = _pts.slice(); _pts.sort((a, b) => a[0] - b[0]); } let left = (a, b, c) => { return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]) > 0; }; let dq = []; let bot = _pts.length - 2; let top = bot + 3; dq[bot] = _pts[2]; dq[top] = _pts[2]; if (left(_pts[0], _pts[1], _pts[2])) { dq[bot + 1] = _pts[0]; dq[bot + 2] = _pts[1]; } else { dq[bot + 1] = _pts[1]; dq[bot + 2] = _pts[0]; } for (let i = 3, len = _pts.length; i < len; i++) { let pt = _pts[i]; if (left(dq[bot], dq[bot + 1], pt) && left(dq[top - 1], dq[top], pt)) { continue; } while (!left(dq[bot], dq[bot + 1], pt)) { bot += 1; } bot -= 1; dq[bot] = pt; while (!left(dq[top - 1], dq[top], pt)) { top -= 1; } top += 1; dq[top] = pt; } let hull = new Group(); for (let h = 0; h < (top - bot); h++) { hull.push(dq[bot + h]); } return hull; } static network(poly, originIndex = 0) { let _pts = Util.iterToArray(poly); let g = []; for (let i = 0, len = _pts.length; i < len; i++) { if (i != originIndex) g.push(new Group(_pts[originIndex], _pts[i])); } return g; } static nearestPt(poly, pt) { let _near = Number.MAX_VALUE; let _item = -1; let i = 0; for (let p of poly) { let d = p.$subtract(pt).magnitudeSq(); if (d < _near) { _near = d; _item = i; } i++; } return _item; } static projectAxis(poly, unitAxis) { let _poly = Util.iterToArray(poly); let dot = unitAxis.dot(_poly[0]); let d = new Pt(dot, dot); for (let n = 1, len = _poly.length; n < len; n++) { dot = unitAxis.dot(_poly[n]); d = new Pt(Math.min(dot, d[0]), Math.max(dot, d[1])); } return d; } static _axisOverlap(poly1, poly2, unitAxis) { let pa = Polygon.projectAxis(poly1, unitAxis); let pb = Polygon.projectAxis(poly2, unitAxis); return (pa[0] < pb[0]) ? pb[0] - pa[1] : pa[0] - pb[1]; } static hasIntersectPoint(poly, pt) { let _poly = Util.iterToArray(poly); let c = false; for (let i = 0, len = _poly.length; i < len; i++) { let ln = Polygon.lineAt(_poly, i); if (((ln[0][1] > pt[1]) != (ln[1][1] > pt[1])) && (pt[0] < (ln[1][0] - ln[0][0]) * (pt[1] - ln[0][1]) / (ln[1][1] - ln[0][1]) + ln[0][0])) { c = !c; } } return c; } static hasIntersectCircle(poly, circle) { let _poly = Util.iterToArray(poly); let _circle = Util.iterToArray(circle); let info = { which: -1, dist: 0, normal: null, edge: null, vertex: null, }; let c = _circle[0]; let r = _circle[1][0]; let minDist = Number.MAX_SAFE_INTEGER; for (let i = 0, len = _poly.length; i < len; i++) { let edge = Polygon.lineAt(_poly, i); let axis = new Pt(edge[0].y - edge[1].y, edge[1].x - edge[0].x).unit(); let poly2 = new Group(c.$add(axis.$multiply(r)), c.$subtract(axis.$multiply(r))); let dist = Polygon._axisOverlap(_poly, poly2, axis); if (dist > 0) { return null; } else if (Math.abs(dist) < minDist) { let check = Rectangle.withinBound(edge, Line.perpendicularFromPt(edge, c)) || Circle.intersectLine2D(circle, edge).length > 0; if (check) { info.edge = edge; info.normal = axis; minDist = Math.abs(dist); info.which = i; } } } if (!info.edge) return null; let dir = c.$subtract(Polygon.centroid(_poly)).dot(info.normal); if (dir < 0) info.normal.multiply(-1); info.dist = minDist; info.vertex = c; return info; } static hasIntersectPolygon(poly1, poly2) { let _poly1 = Util.iterToArray(poly1); let _poly2 = Util.iterToArray(poly2); let info = { which: -1, dist: 0, normal: new Pt(), edge: new Group(), vertex: new Pt() }; let minDist = Number.MAX_SAFE_INTEGER; for (let i = 0, plen = (_poly1.length + _poly2.length); i < plen; i++) { let edge = (i < _poly1.length) ? Polygon.lineAt(_poly1, i) : Polygon.lineAt(_poly2, i - _poly1.length); let axis = new Pt(edge[0].y - edge[1].y, edge[1].x - edge[0].x).unit(); let dist = Polygon._axisOverlap(_poly1, _poly2, axis); if (dist > 0) { return null; } else if (Math.abs(dist) < minDist) { info.edge = edge; info.normal = axis; minDist = Math.abs(dist); info.which = (i < _poly1.length) ? 0 : 1; } } info.dist = minDist; let b1 = (info.which === 0) ? _poly2 : _poly1; let b2 = (info.which === 0) ? _poly1 : _poly2; let c1 = Polygon.centroid(b1); let c2 = Polygon.centroid(b2); let dir = c1.$subtract(c2).dot(info.normal); if (dir < 0) info.normal.multiply(-1); let smallest = Number.MAX_SAFE_INTEGER; for (let i = 0, len = b1.length; i < len; i++) { let d = info.normal.dot(b1[i].$subtract(c2)); if (d < smallest) { smallest = d; info.vertex = b1[i]; } } return info; } static intersectPolygon2D(poly1, poly2) { let _poly1 = Util.iterToArray(poly1); let _poly2 = Util.iterToArray(poly2); let lp = Polygon.lines(_poly1); let g = []; for (let i = 0, len = lp.length; i < len; i++) { let ins = Line.intersectPolygon2D(lp[i], _poly2, false); if (ins) g.push(ins); } return Util.flatten(g, true); } static toRects(polys) { let boxes = []; for (let g of polys) { boxes.push(Geom.boundingBox(g)); } let merged = Util.flatten(boxes, false); boxes.unshift(Geom.boundingBox(merged)); return boxes; } } export class Curve { static getSteps(steps) { let ts = new Group(); for (let i = 0; i <= steps; i++) { let t = i / steps; ts.push(new Pt(t * t * t, t * t, t, 1)); } return ts; } static controlPoints(pts, index = 0, copyStart = false) { let _pts = Util.iterToArray(pts); if (index > _pts.length - 1) return new Group(); let _index = (i) => (i < _pts.length - 1) ? i : _pts.length - 1; let p0 = _pts[index]; index = (copyStart) ? index : index + 1; return new Group(p0, _pts[_index(index++)], _pts[_index(index++)], _pts[_index(index++)]); } static _calcPt(ctrls, params) { let x = ctrls.reduce((a, c, i) => a + c.x * params[i], 0); let y = ctrls.reduce((a, c, i) => a + c.y * params[i], 0); if (ctrls[0].length > 2) { let z = ctrls.reduce((a, c, i) => a + c.z * params[i], 0); return new Pt(x, y, z); } return new Pt(x, y); } static catmullRom(pts, steps = 10) { let _pts = Util.iterToArray(pts); if (_pts.length < 2) return new Group(); let ps = new Group(); let ts = Curve.getSteps(steps); let c = Curve.controlPoints(_pts, 0, true); for (let i = 0; i <= steps; i++) { ps.push(Curve.catmullRomStep(ts[i], c)); } let k = 0; while (k < _pts.length - 2) { let cp = Curve.controlPoints(_pts, k); if (cp.length > 0) { for (let i = 0; i <= steps; i++) { ps.push(Curve.catmullRomStep(ts[i], cp)); } k++; } } return ps; } static catmullRomStep(step, ctrls) { let m = new Group(new Pt(-0.5, 1, -0.5, 0), new Pt(1.5, -2.5, 0, 1), new Pt(-1.5, 2, 0.5, 0), new Pt(0.5, -0.5, 0, 0)); return Curve._calcPt(ctrls, Mat.multiply([step], m, true)[0]); } static cardinal(pts, steps = 10, tension = 0.5) { let _pts = Util.iterToArray(pts); if (_pts.length < 2) return new Group(); let ps = new Group(); let ts = Curve.getSteps(steps); let c = Curve.controlPoints(_pts, 0, true); for (let i = 0; i <= steps; i++) { ps.push(Curve.cardinalStep(ts[i], c, tension)); } let k = 0; while (k < _pts.length - 2) { let cp = Curve.controlPoints(_pts, k); if (cp.length > 0) { for (let i = 0; i <= steps; i++) { ps.push(Curve.cardinalStep(ts[i], cp, tension)); } k++; } } return ps; } static cardinalStep(step, ctrls, tension = 0.5) { let m = new Group(new Pt(-1, 2, -1, 0), new Pt(-1, 1, 0, 0), new Pt(1, -2, 1, 0), new Pt(1, -1, 0, 0)); let h = Mat.multiply([step], m, true)[0].multiply(tension); let h2 = (2 * step[0] - 3 * step[1] + 1); let h3 = -2 * step[0] + 3 * step[1]; let pt = Curve._calcPt(ctrls, h); pt.x += h2 * ctrls[1].x + h3 * ctrls[2].x; pt.y += h2 * ctrls[1].y + h3 * ctrls[2].y; if (pt.length > 2) pt.z += h2 * ctrls[1].z + h3 * ctrls[2].z; return pt; } static bezier(pts, steps = 10) { let _pts = Util.iterToArray(pts); if (_pts.length < 4) return new Group(); let ps = new Group(); let ts = Curve.getSteps(steps); let k = 0; while (k < _pts.length - 3) { let c = Curve.controlPoints(_pts, k); if (c.length > 0) { for (let i = 0; i <= steps; i++) { ps.push(Curve.bezierStep(ts[i], c)); } k += 3; } } return ps; } static bezierStep(step, ctrls) { let m = new Group(new Pt(-1, 3, -3, 1), new Pt(3, -6, 3, 0), new Pt(-3, 3, 0, 0), new Pt(1, 0, 0, 0)); return Curve._calcPt(ctrls, Mat.multiply([step], m, true)[0]); } static bspline(pts, steps = 10, tension = 1) { let _pts = Util.iterToArray(pts); if (_pts.length < 2) return new Group(); let ps = new Group(); let ts = Curve.getSteps(steps); let k = 0; while (k < _pts.length - 3) { let c = Curve.controlPoints(_pts, k); if (c.length > 0) { if (tension !== 1) { for (let i = 0; i <= steps; i++) { ps.push(Curve.bsplineTensionStep(ts[i], c, tension)); } } else { for (let i = 0; i <= steps; i++) { ps.push(Curve.bsplineStep(ts[i], c)); } } k++; } } return ps; } static bsplineStep(step, ctrls) { let m = new Group(new Pt(-0.16666666666666666, 0.5, -0.5, 0.16666666666666666), new Pt(0.5, -1, 0, 0.6666666666666666), new Pt(-0.5, 0.5, 0.5, 0.16666666666666666), new Pt(0.16666666666666666, 0, 0, 0)); return Curve._calcPt(ctrls, Mat.multiply([step], m, true)[0]); } static bsplineTensionStep(step, ctrls, tension = 1) { let m = new Group(new Pt(-0.16666666666666666, 0.5, -0.5, 0.16666666666666666), new Pt(-1.5, 2, 0, -0.3333333333333333), new Pt(1.5, -2.5, 0.5, 0.16666666666666666), new Pt(0.16666666666666666, 0, 0, 0)); let h = Mat.multiply([step], m, true)[0].multiply(tension); let h2 = (2 * step[0] - 3 * step[1] + 1); let h3 = -2 * step[0] + 3 * step[1]; let pt = Curve._calcPt(ctrls, h); pt.x += h2 * ctrls[1].x + h3 * ctrls[2].x; pt.y += h2 * ctrls[1].y + h3 * ctrls[2].y; if (pt.length > 2) pt.z += h2 * ctrls[1].z + h3 * ctrls[2].z; return pt; } } //# sourceMappingURL=Op.js.map
williamngan/pts
dist/es2015/Op.js
JavaScript
apache-2.0
36,070
/* Inicializacion en espanol para la extensionn 'UI date picker' para jQuery. */ /* Traducido por Vester (xvester@gmail.com). */ jQuery(function($){ $.datepicker.regional['es'] = { closeText: 'Cerrar', prevText: '&#x3c;Ant', nextText: 'Sig&#x3e;', currentText: 'Hoy', monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio', 'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'], monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun', 'Jul','Ago','Sep','Oct','Nov','Dic'], dayNames: ['Domingo','Lunes','Martes','Mi&eacute;rcoles','Jueves','Viernes','S&aacute;bado'], dayNamesShort: ['Dom','Lun','Mar','Mi&eacute;','Juv','Vie','S&aacute;b'], dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','S&aacute;'], weekHeader: 'Sm', dateFormat: 'dd/mm/yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['es']); });
ignaciofuentes/school
app/assets/javascripts/jquery.ui.datepicker-es.js
JavaScript
apache-2.0
923
/* * Copyright 2016 - 2017 Anton Tananaev (anton@traccar.org) * * 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. */ Ext.define('Traccar.view.Statistics', { extend: 'Ext.grid.Panel', xtype: 'statisticsView', requires: [ 'Traccar.view.StatisticsController' ], controller: 'statistics', store: 'Statistics', tbar: [{ xtype: 'tbtext', html: Strings.reportFrom }, { xtype: 'datefield', reference: 'fromDateField', startDay: Traccar.Style.weekStartDay, format: Traccar.Style.dateFormat, value: new Date(new Date().getTime() - 24 * 60 * 60 * 1000) }, '-', { xtype: 'tbtext', html: Strings.reportTo }, { xtype: 'datefield', reference: 'toDateField', startDay: Traccar.Style.weekStartDay, format: Traccar.Style.dateFormat, value: new Date() }, '-', { text: Strings.reportShow, handler: 'onShowClick' }], columns: { defaults: { flex: 1, minWidth: Traccar.Style.columnWidthNormal }, items: [{ text: Strings.statisticsCaptureTime, dataIndex: 'captureTime', xtype: 'datecolumn', renderer: Traccar.AttributeFormatter.defaultFormatter() }, { text: Strings.statisticsActiveUsers, dataIndex: 'activeUsers' }, { text: Strings.statisticsActiveDevices, dataIndex: 'activeDevices' }, { text: Strings.statisticsRequests, dataIndex: 'requests' }, { text: Strings.statisticsMessagesReceived, dataIndex: 'messagesReceived' }, { text: Strings.statisticsMessagesStored, dataIndex: 'messagesStored' }, { text: Strings.notificationMail, dataIndex: 'mailSent' }, { text: Strings.notificationSms, dataIndex: 'smsSent' }, { text: Strings.statisticsGeocoder, dataIndex: 'geocoderRequests' }, { text: Strings.statisticsGeolocation, dataIndex: 'geolocationRequests' }] } });
awaissattar001/mtrack
traccar-web/web/app/view/Statistics.js
JavaScript
apache-2.0
2,738
/*globals oasp*/ describe('Module: \'app.offer-mgmt\', Service: \'offers\'', function () { 'use strict'; var contextPath = '/oasp-app/', $httpBackend, offers; beforeEach(module('app.offer-mgmt', function ($provide) { $provide.value('currentContextPath', oasp.mock.currentContextPathReturning(contextPath)); })); /*jslint nomen: true */ beforeEach(inject(function (_$httpBackend_, _offers_) { $httpBackend = _$httpBackend_; offers = _offers_; })); /*jslint nomen: false */ afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('loads all offers', function () { // given var allOffers = { pagination: {}, result: [ { id: '1' } ] }, allOffersResult, expectedOffer = { id: '1' }, searchCriteria = { pagination: { page: 1, total: true } }; $httpBackend.whenPOST(contextPath + 'services/rest/offermanagement/v1/offer/search', searchCriteria).respond(allOffers); // when offers.loadAllOffers() .then(function (response) { allOffersResult = response; }); $httpBackend.flush(); // then expect(allOffersResult[0]).toEqual(expectedOffer); }); it('should load all products', function () { // given var allProducts = { pagination: {}, result: [ { id: '1' } ] }, allProductsResult = {}, expectedProduct = { id: '1' }, searchCriteria = { pagination: { page: 1, total: true } }; $httpBackend.whenPOST(contextPath + 'services/rest/offermanagement/v1/product/search', searchCriteria).respond(allProducts); // when offers.loadAllProducts() .then(function (response) { allProductsResult = response; }); $httpBackend.flush(); // then expect(allProductsResult[0]).toEqual(expectedProduct); }); });
oasp-forge/bht-2017-RideSharing-Server
samples/server/src/main/client/app/offer-mgmt/offers.service.spec.js
JavaScript
apache-2.0
2,425
import {default as React,Component} from 'react'; import { render } from 'react-dom'; import Select2 from 'react-select2-wrapper'; import { dataOperation } from '../../service/DataOperation'; import { ErrorModal } from '../../others/ErrorModal'; import {codemirrorOptions, closeError, isJson} from '../../others/helper'; var Codemirror = require('react-codemirror'); require('codemirror/mode/javascript/javascript'); require('codemirror/addon/search/searchcursor.js'); require('codemirror/addon/search/search.js'); require('codemirror/addon/dialog/dialog.js'); require('codemirror/addon/edit/matchbrackets.js'); require('codemirror/addon/edit/closebrackets.js'); require('codemirror/addon/comment/comment.js'); require('codemirror/addon/display/placeholder'); require('codemirror/addon/fold/foldcode.js'); require('codemirror/addon/fold/foldgutter.js'); require('codemirror/addon/fold/brace-fold.js'); require('codemirror/addon/fold/xml-fold.js'); require('codemirror/addon/fold/markdown-fold.js'); require('codemirror/addon/fold/comment-fold.js'); export class JsonImport extends Component { constructor(props) { super(props); this.sample = null; this.state = { code: '', error: { title: null, message: null }, validFlag: false, "importType": "data" }; this.sampleObj = { "analyzer": { "standard_analyzer": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding" ] }, "whitespace_analyzer": { "type": "whitespace", "tokenizer": "whitespace", "filter": [ "lowercase", "asciifolding" ] } } }; this.updateCode = this.updateCode.bind(this); this.closeError = closeError.bind(this); this.submit = this.submit.bind(this); this.importTypeChange = this.importTypeChange.bind(this); this.applySettings = this.applySettings.bind(this); } componentWillMount() { this.submit.call(this); } updateCode(newCode) { this.setState({ code: newCode }, this.submit.bind(this)); } loadSample() { this.updateCode(JSON.stringify(this.sampleObj, null, 4)); } submit() { let isJson = this.isJson(this.state.code); if (isJson.validFlag) { let parsedJson = isJson.jsonInput; this.props.handleUpdate(parsedJson, this.state.selectedType, this.state.importType); } this.setState({ validFlag: isJson.validFlag }); } applySettings() { this.props.handleSubmit(); } isJson(jsonInput) { return isJson(jsonInput); } getValidMessage() { return this.props.successMessage ? this.props.successMessage : (this.state.validFlag ? 'JSON is valid ☺.' : 'JSON is invalid ☹.'); } importTypeChange(type) { this.setState({ importType: type }, this.submit.bind(this)); } render() { this.types = Object.keys(this.props.mappings); this.types.unshift(''); return ( <div className="JsonImport col-xs-12"> <span className={"json-valid-message import-bottom "+(this.state.validFlag ? 'text-success' : 'text-danger')}> {this.getValidMessage()} </span> <button onClick={() => this.applySettings()} className="btn btn-yellow import-bottom btn-submit"> Apply settings </button> <button onClick={() => this.loadSample()} className="btn btn-yellow load-sample btn-submit"> Load sample </button> <Codemirror ref="editor" value={this.state.code} onChange={this.updateCode} placeholder='Add json here' options={codemirrorOptions} /> <ErrorModal {...this.state.error} closeError={this.closeError} /> </div> ); } }
appbaseio/gem
app/mappingContainer/importSettings/JsonImport.js
JavaScript
apache-2.0
3,589
/** * Visual Blocks Editor * * Copyright 2012 Google Inc. * http://blockly.googlecode.com/ * * 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 Variable blocks for Blockly. * @author fraser@google.com (Neil Fraser) */ 'use strict'; goog.provide('Blockly.Blocks.variables'); goog.require('Blockly.Blocks'); Blockly.Blocks.variables_get = { // Variable getter. init: function() { this.setHelpUrl(Blockly.Msg.VARIABLES_GET_HELPURL); this.setHSV(312, 0.32, 0.62); this.appendDummyInput() .appendTitle(Blockly.Msg.VARIABLES_GET_TITLE) .appendTitle(new Blockly.FieldVariable( Blockly.Msg.VARIABLES_GET_ITEM), 'VAR') .appendTitle(Blockly.Msg.VARIABLES_GET_TAIL); this.setOutput(true); this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP); }, getVars: function() { return [this.getTitleValue('VAR')]; }, renameVar: function(oldName, newName) { if (Blockly.Names.equals(oldName, this.getTitleValue('VAR'))) { this.setTitleValue(newName, 'VAR'); } }, contextMenuType_: 'variables_set', customContextMenu: function(options) { var option = {enabled: true}; var name = this.getTitleValue('VAR'); option.text = Blockly.Msg.VARIABLES_GET_CREATE_SET.replace('%1', name); var xmlTitle = goog.dom.createDom('title', null, name); xmlTitle.setAttribute('name', 'VAR'); var xmlBlock = goog.dom.createDom('block', null, xmlTitle); xmlBlock.setAttribute('type', this.contextMenuType_); option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock); options.push(option); } }; Blockly.Blocks.variables_set = { // Variable setter. init: function() { this.setHelpUrl(Blockly.Msg.VARIABLES_SET_HELPURL); this.setHSV(312, 0.32, 0.62); this.appendValueInput('VALUE') .appendTitle(Blockly.Msg.VARIABLES_SET_TITLE) .appendTitle(new Blockly.FieldVariable( Blockly.Msg.VARIABLES_SET_ITEM), 'VAR') .appendTitle(Blockly.Msg.VARIABLES_SET_TAIL); this.setPreviousStatement(true); this.setNextStatement(true); this.setTooltip(Blockly.Msg.VARIABLES_SET_TOOLTIP); }, getVars: function() { return [this.getTitleValue('VAR')]; }, renameVar: function(oldName, newName) { if (Blockly.Names.equals(oldName, this.getTitleValue('VAR'))) { this.setTitleValue(newName, 'VAR'); } }, contextMenuMsg_: Blockly.Msg.VARIABLES_SET_CREATE_GET, contextMenuType_: 'variables_get', customContextMenu: Blockly.Blocks.variables_get.customContextMenu };
tobyk100/blockly-trunk
blocks/variables.js
JavaScript
apache-2.0
3,058
var AWS = require('aws-sdk'); // Create an S3 client var sqs = new AWS.SQS({region:"us-east-1"}); var params = { QueueNamePrefix: 'yun' }; sqs.listQueues(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response });
Tony607/aws_node
sqsListQueues.js
JavaScript
apache-2.0
314
'use strict'; const { debugLogger } = require('@terascope/utils'); const api = require('../../lib/api'); describe('startWorkers foundation API', () => { const context = { sysconfig: { terafoundation: { log_level: 'debug' } }, name: 'terafoundation' }; beforeEach(() => { // This sets up the API endpoints in the context. api(context); context.cluster = { isMaster: true, fork: jasmine.createSpy('cluster-fork') }; context.logger = debugLogger('terafondation-tests'); }); it('should call fork to create a worker', () => { const { foundation } = context.apis; const { fork } = context.cluster; foundation.startWorkers(1); expect(fork).toHaveBeenCalledWith({ assignment: 'worker', service_context: '{"assignment":"worker"}' }); }); it('should call fork to create a worker with environment', () => { const { foundation } = context.apis; const { fork } = context.cluster; foundation.startWorkers(1, { myoption: 'myoption' }); expect(fork).toHaveBeenCalledWith({ assignment: 'worker', service_context: '{"myoption":"myoption"}', myoption: 'myoption' }); }); it('fork should not be called if this is not the master', () => { const { foundation } = context.apis; const { fork } = context.cluster; context.cluster.isMaster = false; foundation.startWorkers(1, { myoption: 'myoption' }); expect(fork.calls.count()).toBe(0); }); it('should call fork 10 times to create 10 workers', () => { const { foundation } = context.apis; const { fork } = context.cluster; foundation.startWorkers(10); expect(fork.calls.count()).toBe(10); }); });
jsnoble/teraslice
packages/terafoundation/test/apis/startWorkers-spec.js
JavaScript
apache-2.0
1,923
/** * standard gulp build file for browser client projects */ 'use strict'; var gulp = require('gulp'), path = require('path'), gutil = require('gulp-util'), del = require('del'), gulpif = require('gulp-if'), plumber = require('gulp-plumber'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), jshint = require('gulp-jshint'), mocha = require('gulp-mocha'), map = require('map-stream'), fs = require('vinyl-fs'); var errorHandler = function(err) { gutil.beep(); console.log( err ); }; var paths = { src: 'lib/*/*.js', tests: 'test/*/*.js', inttests: 'integration-test/*.js', examples: 'examples/*.js' }; gulp.task('jshint', function() { gulp.src([ paths.src, paths.tests, paths.inttests, paths.examples ], { read:false } ) .pipe( plumber({ errorHandler:errorHandler }) ) .pipe( jshint() ) .pipe( jshint.reporter('jshint-stylish') ); }); gulp.task('mocha', function() { gulp.src( paths.tests, { read:false } ) .pipe( plumber({ errorHandler:errorHandler }) ) .pipe( mocha({ reporter:'spec' }) ); }); gulp.task('test', [ 'mocha', 'jshint' ] ); gulp.task('watch', [ 'test' ], function () { gulp.watch([ paths.src, paths.tests ], [ 'test' ]); }); gulp.task('default', [ 'test', 'watch' ]);
darrylwest/websocket-database-service
gulpfile.js
JavaScript
apache-2.0
1,333
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var string2buffer = require( '@stdlib/buffer/from-string' ); var decode = require( './../lib/decode.js' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.equal( typeof decode, 'function', 'main export is a function' ); t.end(); }); tape( 'the function converts a UTF-8 string to a specified encoding', function test( t ) { var str; str = decode( 'beep', 'base64' ); t.equal( str, string2buffer( 'beep' ).toString( 'base64' ), 'returns base64 encoded string' ); str = decode( 'beep', 'ascii' ); t.equal( str, string2buffer( 'beep' ).toString( 'ascii' ), 'returns ascii encoded string' ); t.end(); }); tape( 'the function returns the input string if the specified encoding is either `utf8` or `buffer`', function test( t ) { var str; str = decode( 'beep', 'utf8' ); t.equal( str, 'beep', 'returns utf8 encoding string' ); str = decode( 'beep', 'buffer' ); t.equal( str, 'beep', 'returns string having buffer encoding' ); t.end(); });
stdlib-js/stdlib
lib/node_modules/@stdlib/streams/node/split/test/test.decode.js
JavaScript
apache-2.0
1,685
var path = require('path'); var webpack = require('webpack'); var merge = require('lodash.merge'); var _ = require('lodash'); var StatsWriterPlugin = require("webpack-stats-plugin").StatsWriterPlugin; var ExtractTextPlugin = require("extract-text-webpack-plugin"); const DEBUG = !process.argv.includes('--release'); const VERBOSE = process.argv.includes('--verbose'); const WATCH = global.WATCH === undefined ? false : global.WATCH; const AUTOPREFIXER_BROWSERS = [ 'Android 2.3', 'Android >= 4', 'Chrome >= 35', 'Firefox >= 31', 'Explorer >= 9', 'iOS >= 7', 'Opera >= 12', 'Safari >= 7.1', ]; const GLOBALS = { 'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"', __DEV__: DEBUG, }; const config = { output: { publicPath: '/', sourcePrefix: ' ', }, cache: DEBUG, debug: DEBUG, stats: { colors: true, reasons: DEBUG, hash: VERBOSE, version: VERBOSE, timings: true, chunks: VERBOSE, chunkModules: VERBOSE, cached: VERBOSE, cachedAssets: VERBOSE, }, plugins: [ // css files from the extract-text-plugin loader new ExtractTextPlugin("[name]-[chunkhash].css"), // optimizations new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), ], resolve: { extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.json'], }, module: { loaders: [ { test: /\.jsx?$/, include: path.join(__dirname, '../../src'), loader: 'react-hot!babel' }, { test: /\.scss$/, include: path.join(__dirname, '../../src'), loader: ExtractTextPlugin.extract('style', 'css', 'sass') }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css') }, { test: /\.woff2?(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream' }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml' } ] } }; const appConfig = merge({}, config, { devtool: 'eval-source-map', entry: { main: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './src/app.js' ] }, output: { filename: './[name]-[hash].js', path: path.join(__dirname, '../../build/public'), publicPath: '../build/public' }, plugins: [ // Write out stats.json file to build directory. new StatsWriterPlugin({ transform: function (data) { return JSON.stringify({ main: data.assetsByChunkName.main[0], css: data.assetsByChunkName.main[1] }); } }), // css files from the extract-text-plugin loader new ExtractTextPlugin("[name]-[chunkhash].css"), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ] }); const serverConfig = merge({}, config, { entry: './src/server.js', output: { path: './build', filename: 'server.js', libraryTarget: 'commonjs2', }, target: 'node', externals: [ /^\.\/public\/stats\.json$/, function filter(context, request, cb) { const isExternal = request.match(/^[@a-z][a-z\/\.\-0-9]*$/i) && !request.match(/^react-routing/) && !context.match(/[\\/]react-routing/); cb(null, Boolean(isExternal)); }, ], node: { console: false, global: false, process: false, Buffer: false, __filename: false, __dirname: false, }, devtool: 'source-map', plugins: [ new webpack.DefinePlugin(GLOBALS), new webpack.BannerPlugin('require("source-map-support").install();', { raw: true, entryOnly: false }) ] }); export default [appConfig, serverConfig];
mortondev/rapport
tools/webpack/prod.config.js
JavaScript
apache-2.0
4,067
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 * */ import {checkIsEntityRef} from "../../common/checks"; function store($http, baseApiUrl) { const base = `${baseApiUrl}/survey-instance`; const getById = (id) => { return $http .get(`${base}/id/${id}`) .then(result => result.data); }; const findByEntityReference = (ref) => { checkIsEntityRef(ref); return $http .get(`${base}/entity/${ref.kind}/${ref.id}`) .then(r => r.data); }; const findForRecipientId = (personId) => { return $http .get(`${base}/recipient/id/${personId}`) .then(r => r.data); }; const findForUser = () => { return $http .get(`${base}/user`) .then(result => result.data); }; const findForSurveyRun = (id) => { return $http .get(`${base}/run/${id}`) .then(result => result.data); }; const findPreviousVersions = (originalId) => { return $http .get(`${base}/id/${originalId}/previous-versions`) .then(result => result.data); }; const findRecipients = (id) => { return $http .get(`${base}/${id}/recipients`) .then(result => result.data); }; const findResponses = (id) => { return $http .get(`${base}/${id}/responses`) .then(result => result.data); }; const saveResponse = (id, questionResponse) => { return $http .put(`${base}/${id}/response`, questionResponse) .then(result => result.data); }; const updateStatus = (id, command) => { return $http .put(`${base}/${id}/status`, command) .then(result => result.data); }; const updateDueDate = (id, command) => { return $http .put(`${base}/${id}/due-date`, command) .then(r => r.data); }; const updateRecipient = (id, command) => { return $http .put(`${base}/${id}/recipient`, command) .then(result => result.data); }; const markApproved = (id, reasonCommand) => { return $http .put(`${base}/${id}/approval`, reasonCommand) .then(result => result.data); }; const addRecipient = (surveyInstanceId, command) => { return $http .post(`${base}/${surveyInstanceId}/recipient`, command) .then(result => result.data); }; const deleteRecipient = (id, instanceRecipientId) => { return $http .delete(`${base}/${id}/recipient/${instanceRecipientId}`,) .then(result => result.data); }; return { getById, findByEntityReference, findForRecipientId, findForUser, findForSurveyRun, findPreviousVersions, findRecipients, findResponses, saveResponse, updateStatus, updateDueDate, updateRecipient, addRecipient, deleteRecipient, markApproved }; } store.$inject = [ '$http', 'BaseApiUrl' ]; const serviceName = 'SurveyInstanceStore'; export const SurveyInstanceStore_API = { getById: { serviceName, serviceFnName: 'getById', description: 'get survey instance for a given id' }, findByEntityReference: { serviceName, serviceFnName: 'findByEntityReference', description: 'finds survey instances for a given entity reference' }, findForRecipientId: { serviceName, serviceFnName: 'findForRecipientId', description: 'finds survey instances for a recipient person id' }, findForUser: { serviceName, serviceFnName: 'findForUser', description: 'finds survey instances for the current logged in user' }, findForSurveyRun: { serviceName, serviceFnName: 'findForSurveyRun', description: 'finds survey instances for a given survey run id' }, findRecipients: { serviceName, serviceFnName: 'findRecipients', description: 'finds recipients for a given survey instance id' }, findResponses: { serviceName, serviceFnName: 'findResponses', description: 'finds responses for a given survey instance id' }, findPreviousVersions: { serviceName, serviceFnName: 'findPreviousVersions', description: 'finds previouse versions for a given survey instance id' }, saveResponse: { serviceName, serviceFnName: 'saveResponse', description: 'save response for a given survey instance question' }, updateStatus: { serviceName, serviceFnName: 'updateStatus', description: 'update status for a given survey instance id' }, updateDueDate: { serviceName, serviceFnName: 'updateDueDate', description: 'update due date for a given survey instance id' }, updateRecipient: { serviceName, serviceFnName: 'updateRecipient', description: 'update recipient for a given survey instance id' }, markApproved: { serviceName, serviceFnName: 'markApproved', description: 'approve a survey instance response' }, addRecipient: { serviceName, serviceFnName: 'addRecipient', description: 'add recipient to a given survey instance id' }, deleteRecipient: { serviceName, serviceFnName: 'deleteRecipient', description: 'delete recipient from a given survey instance id' } }; export default { store, serviceName };
rovats/waltz
waltz-ng/client/survey/services/survey-instance-store.js
JavaScript
apache-2.0
6,299
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; var Int8Array = require( '@stdlib/array/int8' ); var Uint8Array = require( '@stdlib/array/uint8' ); var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); var Int16Array = require( '@stdlib/array/int16' ); var Uint16Array = require( '@stdlib/array/uint16' ); var Int32Array = require( '@stdlib/array/int32' ); var Uint32Array = require( '@stdlib/array/uint32' ); var Float32Array = require( '@stdlib/array/float32' ); var Float64Array = require( '@stdlib/array/float64' ); var isUint8ClampedArray = require( './../lib' ); var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) ); console.log( bool ); // => true bool = isUint8ClampedArray( new Int8Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( new Uint8Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( new Int16Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( new Uint16Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( new Int32Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( new Uint32Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( new Float32Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( new Float64Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( new Array( 10 ) ); console.log( bool ); // => false bool = isUint8ClampedArray( {} ); console.log( bool ); // => false bool = isUint8ClampedArray( null ); console.log( bool ); // => false
stdlib-js/stdlib
lib/node_modules/@stdlib/assert/is-uint8clampedarray/examples/index.js
JavaScript
apache-2.0
2,167
var structnd__opt__dnssl = [ [ "nd_opt_dnssl_len", "structnd__opt__dnssl.html#a7203fc7c273b4988ca8b4a9bad5d7f74", null ], [ "nd_opt_dnssl_lifetime", "structnd__opt__dnssl.html#a76ee23870cd053b228cf3901093c6b03", null ], [ "nd_opt_dnssl_reserved", "structnd__opt__dnssl.html#a1dd5d537f85a304ceb904b52ed63ba12", null ], [ "nd_opt_dnssl_type", "structnd__opt__dnssl.html#afb006f0d03893137ff299211b7458b65", null ] ];
vladn-ma/vladn-ovs-doc
doxygen/ovs_all/html/structnd__opt__dnssl.js
JavaScript
apache-2.0
429
import Ember from 'ember'; const { Route } = Ember; export default Route.extend({ titleToken() { return this.i18n.t('Notification Logs'); }, model() { return [ { receivedAt : new Date(), action : 'Invitation For Papers', title : 'Invitation to Submit Papers for event1', message : 'You have been invited to submit papers for event1', user : { name : 'test user', email : 'test@gmail.com' } }, { receivedAt : new Date(), action : 'New Session Proposal', title : 'New session proposal for event1', message : 'The event event1 has received a new session proposal.', user : { name : 'event user', email : 'event_user@gmail.com' } }, { receivedAt : new Date(), action : 'Ticket(s) Purchased to Organizer', title : 'New ticket purchase for event2 by buyer@mail.com (O1497634451-1) ', message : 'The order has been processed successfully', user : { name : 'event user', email : 'event_user@gmail.com' } } ]; } });
anu-007/open-event-frontend
app/routes/admin/reports/system-logs/notification-logs.js
JavaScript
apache-2.0
1,230
(function(){/** * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a * character code is whitespace. * * @private * @param {number} charCode The character code to inspect. * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`. */ function isSpace(charCode) { return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 || (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279))); } module.exports = isSpace; })();
durwasa-chakraborty/navigus
.demeteorized/bundle/programs/server/app/lib/node_modules/modulus/node_modules/zip-stream/node_modules/lodash/internal/isSpace.js
JavaScript
apache-2.0
658
'use strict' /* * Copyright 2017 Google 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. */ /** * Edge Management API calls * * @param proxyData * @param proxyData.org * @param proxyData.env * @param proxyData.user * @param proxyData.pass * @param proxyData.proxyname * * @module */ var request = require('request') var logger = require('./logger') /* Destructure, spread operator: Node 6 function auth(obj) { const {user, pass} = obj return {user, pass} } function mgmtUrl() { const vX = config.get('APIGEE_MGMT_API_URL') return [vX, ...arguments].join('/') } function org(obj, ...rest) { return mgmtUrl('organizations', obj.org, ...rest) } function orgEnv(obj, ...rest) { return org(obj, 'environments', obj.env, ...rest) } */ function auth(options, obj) { if (obj.user && obj.pass) { options.auth = { user: obj.user, pass: obj.pass } } else if (obj.basic) { options.headers = { 'Authorization': 'Basic ' + obj.basic } } else { options.auth = { bearer: obj.bearer } } } function mgmtUrl() { const args = Array.prototype.slice.call(arguments) const obj = args.shift() return [obj.configuration.get('APIGEE_MGMT_API_URL')].concat(args).join('/') } function org() { const args = Array.prototype.slice.call(arguments) const obj = args.shift() return mgmtUrl.apply(null, [obj, 'organizations', obj.org].concat(args)) } function orgEnv() { const args = Array.prototype.slice.call(arguments) const obj = args.shift() return org.apply(null, [obj, 'environments', obj.env].concat(args)) } function getProxyRevision (proxyData, callback) { var options = { url: org(proxyData, 'apis', proxyData.proxyname) } logger.log.info("Get proxy revision url: " + options.url) auth(options, proxyData) request.get(options, function (err, res, body) { if (err) { err.url = options.url var loggerError = logger.ERR_APIGEE_REQ_FAILED(err) callback(loggerError) } else if (res.statusCode == 401) { var loggerError = logger.ERR_APIGEE_AUTH(err, 401) callback(loggerError) } else if (res.statusCode == 404) { var loggerError = logger.ERR_APIGEE_PROXY_NOT_FOUND(err, 404) callback(loggerError) } else if (res.statusCode !== 200) { var loggerError = logger.ERR_APIGEE_GET_PROXY_REV_FAILED(body, res.statusCode) callback(loggerError) } else { body = JSON.parse(body) console.log(body) var revision = body.revision.pop() callback(null, revision) } }) } function importProxy (proxyData, zipBuffer, callback) { var formData = { file: zipBuffer } var options = { url: org(proxyData, 'apis'), formData: formData, qs: { action: 'import', name: proxyData.proxyname } } logger.log.info("Import proxy url: " + options.url, " proxy name: ", options.qs.name) auth(options, proxyData) request.post(options, function (err, httpResponse, body) { if (err) { err.url = options.url err.qs = options.qs var loggerError = logger.ERR_APIGEE_REQ_FAILED(err) callback(loggerError) } else if (httpResponse.statusCode !== 201) { var loggerError = logger.ERR_APIGEE_PROXY_UPLOAD(body, httpResponse.statusCode) callback(loggerError) } else { deployProxy(proxyData, callback) } }) } function deployments(obj, revision) { return orgEnv(obj, 'apis', obj.proxyname, 'revisions', revision, 'deployments') } function deployProxy (proxyData, callback) { // should get latest version and deploy that getProxyRevision(proxyData, function (err, revision) { if (err) { var loggerError = logger.ERR_UAE(err) callback(loggerError) } else { var options = { url: deployments(proxyData, revision) } logger.log.info("Deploy proxy url: " + options.url) auth(options, proxyData) request.post(options, function (err, res, body) { if (err) { var loggerError = logger.ERR_APIGEE_DEPLOY_PROXY(err) callback(loggerError) } else { try { body = JSON.parse(body) } catch (x) { } callback(null, { revision: revision, statusCode: res.statusCode, body: body }) } }) } }) } function undeployProxy (proxyData, callback) { // should get latest version and undeploy that getProxyRevision(proxyData, function (err, revision) { if (err) { var loggerError = logger.ERR_UAE(err) callback(loggerError) } else { var options = { url: deployments(proxyData, revision) } logger.log.info("Undeploy proxy url: " + options.url) auth(options, proxyData) request.del(options, function (err, res, body) { if (err) { var loggerError = logger.ERR_APIGEE_UNDEPLOY_PROXY_FAILED(err) callback(loggerError) } else { callback(null, res) } }) } }) } function getVirtualHosts (proxyData, callback) { var options = { url: orgEnv(proxyData, 'virtualhosts') } logger.log.info("Get virtual hosts url: " + options.url) auth(options, proxyData) request.get(options, function (err, res, body) { if (err) { err.url = options.url var loggerError = logger.ERR_APIGEE_REQ_FAILED(err) callback(loggerError) } else if (res.statusCode !== 200) { var loggerError = logger.ERR_PROXY_VHOSTS_NON200_RES(body, res.statusCode) callback(loggerError) } else { callback(null, body) } }) } function authenticate (authOptions, callback) { var options = { url: org(authOptions) } logger.log.info("Authenticate url: " + options.url) auth(options, authOptions) request.get(options, function (err, res, body) { if (err) { err.url = options.url var loggerError = logger.ERR_APIGEE_REQ_FAILED(err) callback(loggerError) } else if (res.statusCode !== 200) { var loggerError if (res.statusCode == 401 && authOptions.bearer) { loggerError = logger.ERR_APIGEE_AUTH_BEARER_FAILED(body, res.statusCode) } else { loggerError = logger.ERR_APIGEE_AUTH(body, res.statusCode) } callback(loggerError) } else { callback(null, body) } }) } module.exports = { importProxy: importProxy, getVirtualHosts: getVirtualHosts, deployProxy: deployProxy, undeployProxy: undeployProxy, authenticate: authenticate }
apigee/cloud-foundry-apigee
apigee-cf-service-broker/helpers/mgmt_api.js
JavaScript
apache-2.0
7,042
var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var config = require(__dirname + './../config/database'); var sequelize = new Sequelize(config.postgres.db, config.postgres.username, config.postgres.password, { host: config.postgres.host, dialect: 'postgres', autoIncrement: true }); var db = {}; fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf('.') !== 0) && (file !== 'index.js'); }) .forEach(function(file) { var model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if ('associate' in db[modelName]) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
ianjuma/morpheus
models/index.js
JavaScript
apache-2.0
813
/* * Copyright 2015 NamieTown * http://www.town.namie.fukushima.jp/ * 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(function(require, exports, module) { "use strict"; module.exports = { MenuView : require("./MenuView"), HeaderView : require("./HeaderView"), GlobalNavView : require("./GlobalNavView"), FooterView : require("./FooterView"), SettingsView : require("./SettingsView") }; });
codefornamie/namie-tablet-html5
www_dev/app/modules/view/common/index.js
JavaScript
apache-2.0
973
"use strict"; var Macaroon = require("./Macaroon"); var CaveatPacket = require("./CaveatPacket"); var CaveatPacketType = require("./CaveatPacketType"); var MacaroonsConstants = require("./MacaroonsConstants"); var Base64Tools = require("./Base64Tools"); var MacaroonsDeSerializer = (function () { function MacaroonsDeSerializer() { } MacaroonsDeSerializer.deserialize = function (serializedMacaroon) { var data = Buffer.from(Base64Tools.transformBase64UrlSafe2Base64(serializedMacaroon), 'base64'); var minLength = MacaroonsConstants.MACAROON_HASH_BYTES + MacaroonsConstants.KEY_VALUE_SEPARATOR_LEN + MacaroonsConstants.SIGNATURE.length; if (data.length < minLength) { throw new Error("Couldn't deserialize macaroon. Not enough bytes for signature found. There have to be at least " + minLength + " bytes"); } return MacaroonsDeSerializer.deserializeStream(new StatefulPacketReader(data)); }; MacaroonsDeSerializer.deserializeStream = function (packetReader) { var location = null; var identifier = null; var caveats = []; var signature = null; var s; var raw; for (var packet; (packet = MacaroonsDeSerializer.readPacket(packetReader)) != null;) { if (MacaroonsDeSerializer.bytesStartWith(packet.data, MacaroonsConstants.LOCATION_BYTES)) { location = MacaroonsDeSerializer.parsePacket(packet, MacaroonsConstants.LOCATION_BYTES); } else if (MacaroonsDeSerializer.bytesStartWith(packet.data, MacaroonsConstants.IDENTIFIER_BYTES)) { identifier = MacaroonsDeSerializer.parsePacket(packet, MacaroonsConstants.IDENTIFIER_BYTES); } else if (MacaroonsDeSerializer.bytesStartWith(packet.data, MacaroonsConstants.CID_BYTES)) { s = MacaroonsDeSerializer.parsePacket(packet, MacaroonsConstants.CID_BYTES); caveats.push(new CaveatPacket(CaveatPacketType.cid, s)); } else if (MacaroonsDeSerializer.bytesStartWith(packet.data, MacaroonsConstants.CL_BYTES)) { s = MacaroonsDeSerializer.parsePacket(packet, MacaroonsConstants.CL_BYTES); caveats.push(new CaveatPacket(CaveatPacketType.cl, s)); } else if (MacaroonsDeSerializer.bytesStartWith(packet.data, MacaroonsConstants.VID_BYTES)) { raw = MacaroonsDeSerializer.parseRawPacket(packet, MacaroonsConstants.VID_BYTES); caveats.push(new CaveatPacket(CaveatPacketType.vid, raw)); } else if (MacaroonsDeSerializer.bytesStartWith(packet.data, MacaroonsConstants.SIGNATURE_BYTES)) { signature = MacaroonsDeSerializer.parseSignature(packet, MacaroonsConstants.SIGNATURE_BYTES); } } return new Macaroon(location, identifier, signature, caveats); }; MacaroonsDeSerializer.parseSignature = function (packet, signaturePacketData) { var headerLen = signaturePacketData.length + MacaroonsConstants.KEY_VALUE_SEPARATOR_LEN; var len = Math.min(packet.data.length - headerLen, MacaroonsConstants.MACAROON_HASH_BYTES); var signature = Buffer.alloc(len); packet.data.copy(signature, 0, headerLen, headerLen + len); return signature; }; MacaroonsDeSerializer.parsePacket = function (packet, header) { var headerLen = header.length + MacaroonsConstants.KEY_VALUE_SEPARATOR_LEN; var len = packet.data.length - headerLen; if (packet.data[headerLen + len - 1] == MacaroonsConstants.LINE_SEPARATOR) len--; return packet.data.toString(MacaroonsConstants.IDENTIFIER_CHARSET, headerLen, headerLen + len); }; MacaroonsDeSerializer.parseRawPacket = function (packet, header) { var headerLen = header.length + MacaroonsConstants.KEY_VALUE_SEPARATOR_LEN; var len = packet.data.length - headerLen - MacaroonsConstants.LINE_SEPARATOR_LEN; var raw = Buffer.alloc(len); packet.data.copy(raw, 0, headerLen, headerLen + len); return raw; }; MacaroonsDeSerializer.bytesStartWith = function (bytes, startBytes) { if (bytes.length < startBytes.length) return false; for (var i = 0, len = startBytes.length; i < len; i++) { if (bytes[i] != startBytes[i]) return false; } return true; }; MacaroonsDeSerializer.readPacket = function (stream) { if (stream.isEOF()) return null; if (!stream.isPacketHeaderAvailable()) { throw new Error("Not enough header bytes available. Needed " + MacaroonsConstants.PACKET_PREFIX_LENGTH + " bytes."); } var size = stream.readPacketHeader(); var data = Buffer.alloc(size - MacaroonsConstants.PACKET_PREFIX_LENGTH); var read = stream.read(data); if (read < 0) return null; if (read != data.length) { throw new Error("Not enough data bytes available. Needed " + data.length + " bytes, but was only " + read); } return new Packet(size, data); }; return MacaroonsDeSerializer; }()); var Packet = (function () { function Packet(size, data) { this.size = size; this.data = data; } return Packet; }()); var StatefulPacketReader = (function () { function StatefulPacketReader(buffer) { this.seekIndex = 0; this.buffer = buffer; } StatefulPacketReader.prototype.read = function (data) { var len = Math.min(data.length, this.buffer.length - this.seekIndex); if (len > 0) { this.buffer.copy(data, 0, this.seekIndex, this.seekIndex + len); this.seekIndex += len; return len; } return -1; }; StatefulPacketReader.prototype.readPacketHeader = function () { return (StatefulPacketReader.HEX_ALPHABET[this.buffer[this.seekIndex++]] << 12) | (StatefulPacketReader.HEX_ALPHABET[this.buffer[this.seekIndex++]] << 8) | (StatefulPacketReader.HEX_ALPHABET[this.buffer[this.seekIndex++]] << 4) | StatefulPacketReader.HEX_ALPHABET[this.buffer[this.seekIndex++]]; }; StatefulPacketReader.prototype.isPacketHeaderAvailable = function () { return this.seekIndex <= (this.buffer.length - MacaroonsConstants.PACKET_PREFIX_LENGTH); }; StatefulPacketReader.prototype.isEOF = function () { return !(this.seekIndex < this.buffer.length); }; StatefulPacketReader.HEX_ALPHABET = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; return StatefulPacketReader; }()); module.exports = MacaroonsDeSerializer;
nitram509/macaroons.js
lib/MacaroonsDeSerializer.js
JavaScript
apache-2.0
7,135
import assert from 'assert'; import { jsdom } from 'jsdom'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import PaperCheckbox from '../src/paper-checkbox'; describe('PaperCheckbox', () => { before(() => { global.document = jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; }); describe('html output', () => { it('renders a div with className "paper-checkbox"', () => { let shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(<PaperCheckbox />); let result = shallowRenderer.getRenderOutput(); assert.equal(result.type, 'div'); assert(result.props.className.match(/paper\-checkbox/)); }); it('renders a single child (a checkbox) when no children are passed', () => { let shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(<PaperCheckbox />); let result = shallowRenderer.getRenderOutput(); assert(Array.isArray(result.props.children)); assert.equal(result.props.children.filter(c => c).length, 1); }); it('renders two children (a checkbox and a label) when children are passed', () => { let shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render( <PaperCheckbox id="x" onClick={() => {}}> click here </PaperCheckbox> ); let result = shallowRenderer.getRenderOutput(); assert(Array.isArray(result.props.children)); assert.equal(result.props.children.length, 2); }); }); describe('props', () => { it('renders children as a label', () => { let instance = TestUtils.renderIntoDocument( <PaperCheckbox id="y" onClick={() => {}}> test label </PaperCheckbox> ); let label = TestUtils.findRenderedDOMComponentWithClass(instance, 'checkbox-label'); assert.equal(label.textContent, 'test label'); }); }); describe('behavior', () => { class Container extends React.Component { constructor(props, context) { super(props, context); this.state = { checked: false }; } render() { return ( <div> <PaperCheckbox id="my-checkbox" checked={this.state.checked} onClick={() => this.setState({ checked: !this.state.checked })} > Click the label too </PaperCheckbox> </div> ); } } let counter = 0; class ReadOnlyContainer extends React.Component { constructor(props, context) { super(props, context); this.state = { checked: true }; } render() { return ( <div> <PaperCheckbox id="my-checkbox" checked={this.state.checked} disabled={true} onClick={() => { counter += 1; this.setState({ checked: !this.state.checked }); }} > Checkmate </PaperCheckbox> </div> ); } } it('calls the onClick callback when clicked', () => { let instance = TestUtils.renderIntoDocument(<Container />); let reactCheckbox = TestUtils.findRenderedComponentWithType(instance, PaperCheckbox); let domCheckbox = TestUtils.findRenderedDOMComponentWithClass(instance, 'checkbox'); assert.equal(reactCheckbox.props.checked, false); TestUtils.Simulate.click(domCheckbox); assert.equal(reactCheckbox.props.checked, true); TestUtils.Simulate.click(domCheckbox); assert.equal(reactCheckbox.props.checked, false); }); it('calls the onClick callback when the label is present and clicked', () => { let instance = TestUtils.renderIntoDocument(<Container />); let reactCheckbox = TestUtils.findRenderedComponentWithType(instance, PaperCheckbox); let domLabel = TestUtils.findRenderedDOMComponentWithTag(instance, 'label'); assert.equal(reactCheckbox.props.checked, false); TestUtils.Simulate.click(domLabel); assert.equal(reactCheckbox.props.checked, true); TestUtils.Simulate.click(domLabel); assert.equal(reactCheckbox.props.checked, false); }); it('calls the onClick callback when focused and Space is pressed', () => { let instance = TestUtils.renderIntoDocument(<Container />); let reactCheckbox = TestUtils.findRenderedComponentWithType(instance, PaperCheckbox); let domCheckbox = TestUtils.findRenderedDOMComponentWithClass(instance, 'checkbox'); TestUtils.Simulate.focus(domCheckbox); assert.equal(reactCheckbox.props.checked, false); TestUtils.Simulate.keyDown(domCheckbox, { key: 'Space', keyCode: 32, which: 32 }); assert.equal(reactCheckbox.props.checked, true); TestUtils.Simulate.keyDown(domCheckbox, { key: 'Space', keyCode: 32, which: 32 }); assert.equal(reactCheckbox.props.checked, false); }); it('never calls the onClick callback when disabled', () => { let instance = TestUtils.renderIntoDocument(<ReadOnlyContainer />); let reactCheckbox = TestUtils.findRenderedComponentWithType(instance, PaperCheckbox); let domCheckbox = TestUtils.findRenderedDOMComponentWithClass(instance, 'checkbox'); let domLabel = TestUtils.findRenderedDOMComponentWithTag(instance, 'label'); assert.equal(reactCheckbox.props.checked, true); assert.equal(counter, 0); TestUtils.Simulate.click(domCheckbox); assert.equal(reactCheckbox.props.checked, true); assert.equal(counter, 0); TestUtils.Simulate.click(domLabel); assert.equal(reactCheckbox.props.checked, true); assert.equal(counter, 0); TestUtils.Simulate.keyDown(domCheckbox, { key: 'Space', keyCode: 32, which: 32 }); assert.equal(reactCheckbox.props.checked, true); assert.equal(counter, 0); }); }); });
scienceai/paper-checkbox
test/test.js
JavaScript
apache-2.0
5,962
/** * @fileoverview Externs for sprintly API. * @externs */ /** * @const * @type {Object} */ var Sprintly = {}; /** * https://sprintly.uservoice.com/knowledgebase/articles/98355-products * @interface */ Sprintly.Product = function() {}; /** * @type {boolean} */ Sprintly.Product.prototype.admin; /** * @type {boolean} */ Sprintly.Product.prototype.archived; /** * @type {number} */ Sprintly.Product.prototype.id; /** * @type {string} */ Sprintly.Product.prototype.name; /** * @enum {string} Item type. */ Sprintly.ItemType = { defect: 'defect', story: 'story', task: 'task', test: 'test' }; /** * @interface */ Sprintly.Progress = function() {}; /** * @type {string} */ Sprintly.Progress.prototype.accepted_at; /** * @type {string} */ Sprintly.Progress.prototype.closed_at; /** * @type {string} */ Sprintly.Progress.prototype.closed_at; /** * Base sprintly entity * @interface */ Sprintly.Entity = function() {}; /** * @type {number} */ Sprintly.Entity.prototype.id; /** * @type {number} */ Sprintly.Entity.prototype.number; /** * https://sprintly.uservoice.com/knowledgebase/articles/98410-people * @interface * @extends {Sprintly.Entity} */ Sprintly.People = function() {}; /** * @type {boolean} */ Sprintly.People.prototype.admin; /** * @type {string} */ Sprintly.People.prototype.first_name; /** * @type {string} */ Sprintly.People.prototype.last_name; /** * @type {string} */ Sprintly.People.prototype.email; /** * https://sprintly.uservoice.com/knowledgebase/articles/98412-items * @interface * @extends {Sprintly.Entity} */ Sprintly.Item = function() {}; /** * @type {Sprintly.ItemType} */ Sprintly.Item.prototype.type; /** * @type {string} */ Sprintly.Item.prototype.status; /** * @type {Sprintly.Product} */ Sprintly.Item.prototype.product; /** * @type {Sprintly.Progress} */ Sprintly.Item.prototype.progress; /** * @type {string} */ Sprintly.Item.prototype.description; /** * @type {Array.<string>} */ Sprintly.Item.prototype.tags; /** * @type {boolean} */ Sprintly.Item.prototype.archived; /** * @type {string} */ Sprintly.Item.prototype.title; /** * @type {Sprintly.People} */ Sprintly.Item.prototype.created_by; /** * @type {string} */ Sprintly.Item.prototype.score; /** * @type {Sprintly.People} */ Sprintly.Item.prototype.assigned_to; /** * @type {string} */ Sprintly.Item.prototype.description; /** * @type {string} */ Sprintly.Item.prototype.short_url;
yathit/sprintly-service
externs/sprintly-api.js
JavaScript
apache-2.0
2,497
var metas = document.getElementsByTagName('meta'); var i; if (navigator.userAgent.match(/iPhone/i)) { for (i=0; i<metas.length; i++) { if (metas[i].name == "viewport") { metas[i].content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0"; } } document.addEventListener("gesturestart", gestureStart, false); } /** * Rescale the viewport. */ function gestureStart() { for (i=0; i<metas.length; i++) { if (metas[i].name == "viewport") { metas[i].content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"; } } }
google/abpackage
docs/javascripts/scale.fix.js
JavaScript
apache-2.0
570
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick 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 path = require('path'); var CommandParser = require('util/command_parser').CommandParser; /* * Options which are available to any command that requests them */ exports.GLOBAL_OPTIONS = { 'remote': { names: ['--remote', '-r'], dest: 'remote', title: 'remote', action: 'store', desc: 'The remote to use for this command' }, 'debug': { names: ['--debug', '-d'], dest: 'debug', title: 'debug', action: 'store_true', desc: 'Enable debug mode and print stack traces' } }; /** * Name of the cast client binary */ exports.BINARY = 'cast'; /** * Usage banner for cast client */ exports.BANNER = 'Usage: cast command [sub-command]'; /** * Commands to configure and parse for */ exports.COMMANDS = [ 'info', 'version', 'init', 'deploy', 'bundles/list', 'bundles/create', 'bundles/delete', 'bundles/validate-manifest', 'bundles/upload', 'instances/create', 'instances/upgrade', 'instances/destroy', 'instances/list', 'services/list', 'services/enable', 'services/disable', 'services/start', 'services/stop', 'services/restart', 'services/tail', 'remotes/add', 'remotes/delete', 'remotes/list', 'remotes/set-default', 'ca/list', 'ca/sign', 'ca/delete', 'jobs/list' ]; /** * Retrieve a command parser for the cast client * @return {CommandParser} A configured command parser. */ exports.getParser = function() { var p = new CommandParser(path.join(__dirname, 'commands')); p.binary = exports.BINARY; p.banner = exports.USAGE; p.addCommands(exports.COMMANDS); p.addGlobalOptions(exports.GLOBAL_OPTIONS); return p; };
cloudkick/cast
lib/cast-client/parser.js
JavaScript
apache-2.0
2,438
const {Helpers, DBH} = require('./helpers.js'); const md5 = require('js-md5'); const {Dil,Genelleme} = require("./language.js"); const Locks = {}; const IdFields = { bakteriler: ["CinsAdi", "TurAdi", "SubTur"], } global.Lock = (id) => new Promise(res => { Locks[id] = res; }); global.Unlock = (id,val) => { if(id in Locks && Locks[id]) { Locks[id](val); Locks[id] = null; } } //index //filter //search //chat //args da level, path, layer = 0 gerekli //level = "Belirtiler" path = "Hastaliklar/Belirtiler" let DoString = async function (string, args, job) { job(string, args); } let DoArray = async function (array, args, job, arrjob, objectjob) { if(arrjob) objectjob(array, args); for(let n of array) { DoRouter(n, args, job, arrjob, objectjob); } } let DoObj = async function (object, args, job, arrjob, objectjob) { if(objectjob) objectjob(object, args); if(object.Name) job(object.Name, args); for(let field in object) { if(field == "Name" || field[0] == "_") continue; let nargs = Helpers.ShallowCopy(args); nargs.level = field; nargs.path += `/${field}`; nargs.layer++; DoRouter(object[field], nargs, job, arrjob, objectjob); } } let DoRouter = async function (object, args, job, arrjob, objectjob) { if(typeof object == "string") { DoString(object, args, job); } else if(Array.isArray(object)) { DoArray(object, args, job, arrjob, objectjob); } else if(typeof object == "object") { DoObj(object, args, job, arrjob, objectjob); } } let DoStringSync = function (string, args, job) { job(string, args); } let DoArraySync = function (array, args, job, arrjob, objectjob) { if(arrjob) objectjob(array, args); for(let n of array) { DoRouterSync(n, args, job, arrjob, objectjob); } } let DoObjSync = function (object, args, job, arrjob, objectjob) { if(objectjob) objectjob(object, args); if(object.Name) job(object.Name, args); for(let field in object) { if(field == "Name" || field[0] == "_") continue; let nargs = Helpers.ShallowCopy(args); nargs.level = field; nargs.path += `/${field}`; nargs.layer++; DoRouterSync(object[field], nargs, job, arrjob, objectjob); } } let DoRouterSync = function (object, args, job, arrjob, objectjob) { if(typeof object == "string") { DoStringSync(object, args, job); } else if(Array.isArray(object)) { DoArraySync(object, args, job, arrjob, objectjob); } else if(typeof object == "object") { DoObjSync(object, args, job, arrjob, objectjob); } } let Arrayify = function (O) { if(!Array.isArray(O)) return [O]; else return O; } let NDEF = function (O,field,def = {}) { if(typeof O[field] === "undefined") { O[field] = def; } } let _S2ENG = function (text) { let ntext = ""; for(let k = 0; k < text.length; k++) { if(text[k] == "ç") ntext += "c"; else if(text[k] == "ö") ntext += "o"; else if(text[k] == "ğ") ntext += "g"; else if(text[k] == "ü") ntext += "u"; else if(text[k] == "ş") ntext += "s"; else if(text[k] == "ı") ntext += "i"; else ntext += text[k]; } return ntext; } let S2ENG = function (text) { if(Array.isArray(text)) { let arr = []; for(let t of text) { arr.push(_S2ENG(t)); } return arr; } else { return _S2ENG(text); } } Array.prototype.remove = function(el) { let ind = this.findIndex(e => e == el); if(ind != -1) { return this.splice(ind,1); } else { return this; } }; let ArrayMerge = function (arr1, arr2) { for(let e of arr2) { if(arr1.findIndex(x => x.toString() == e.toString()) == -1) { arr1.push(e); } } } let WhiteMerge = function (list, arr) { if(!arr || arr.length == 0) { list.mark = true; for(let k = 0; k < list.length; k++) { list.splice(k,1); k--; } } if(list.length == 0 && typeof list.mark === "undefined") { arr.map(e => list.push(e)); list.mark = true; } else { for(let k = 0; k < list.length; k++) { let e = list[k]; let ind = arr.findIndex(x => x.toString() == e.toString()); if(ind == -1) { list.splice(k,1); k--; } } } return list; } let BlackMerge = function (list, arr) { if(!arr || arr.length == 0) return list; for(let e of arr) { if(list.findIndex(x => x.toString() == e.toString()) == -1) list.push(e); } return list; } let WhiteBlackMerge = function (white, black) { for(let k = 0; k < white.length; k++) { let e = white[k]; if(black.findIndex(x => x.toString() == e.toString()) != -1) { white.splice(k,1); k--; } } } let Core = { GetObjectId: async function (coreName, onurid) { return await DBH.GetObjectId(onurid, coreName); }, GetObject: async function (coreName, objid) { return await DBH.GetObject(objid, coreName); }, SetObject: async function (coreName, obj, onurid) { return await DBH.SetObject(obj, onurid, coreName); }, GetIndex: async function (coreName, path) { let indpath = await DBH.GetIndexPath(path, coreName); if(!indpath) return null; return indpath.objs; }, SetIndex: async function (coreName, arr, path) { DBH.SetIndexPath({path: path, objs: arr, coreName: coreName}, coreName); }, AddObjToIndex: async function (coreName, path, objid) { DBH.AddObjToIndex(path, objid, coreName); }, DBChanged: async function (coreName) { await DBH.IncrementVersion(coreName); let online = await DBH.GetCoreField(coreName, "online"); if(online != 2) { await DBH.BackUpCore(coreName); } }, GetOnurID: function (type, B) { let id = ""; for(let f of IdFields[type]) { if(typeof B[f] !== "undefined") { id += B[f]; id += "-"; } } if(id[id.length -1] == "-") { id = id.slice(0, -1); } return id; }, Ekle: async function (coreName, BS) { BS = Arrayify(BS); let didChange = false; let type = await DBH.GetCoreType(coreName); for(let B of BS) { let onurid = this.GetOnurID(type, B); let hash = md5(B); let dogrulama = await DBH.CheckObject(onurid, hash, type, coreName); if(dogrulama) continue; didChange = true; B._ID = onurid; B._hash = hash; let objid = await this.SetObject(coreName, onurid, B); DoRouter(B, { level: "root", path: "root", layer: 0, },async (string, args) => { this.AddObjToIndex(coreName, args.path+"/"+string, objid); }); let langs = {}; DoRouterSync(B, { level: "root", path: "root", layer: 0, },(string, args) => { for(let lang in Dil) { if(lang[0] == "_")continue; NDEF(langs,lang,[]); langs[lang].push(S2ENG(Dil._Sozluk(string,false,lang).toLowerCase())); } }); for(let lang in langs) { DBH.SetSearchTextObjid(langs[lang], objid, lang, coreName); } } if(didChange) this.DBChanged(coreName); }, Remove: async function (coreName, onurid) { DBH.RemoveObject(onurid, coreName); this.DBChanged(); }, Filter: async function (cores, rules, send, count = -1, page) { let whiteCores = []; let blackCores = []; for(let c of cores) { if(!(await DBH.GetCoreField(c, "inverted"))) whiteCores.push(c); else blackCores.push(c); } let white = []; let black = []; let orlist = {}; let nfunc = async (path) => { let wtmp = []; let btmp = []; for(let core of whiteCores) { ArrayMerge(wtmp, await this.GetIndex(core, path)); } for(let core of blackCores) { ArrayMerge(btmp, await this.GetIndex(core, path)); } WhiteBlackMerge(wtmp,btmp); return wtmp; } for(let k = 0; k < rules.length; k++) { if(rules[k].status == 0) { continue; } let path = rules[k].path+"/"+rules[k].field; if(rules[k].status == 1) { let wtemp = await nfunc(path); WhiteMerge(white, wtemp); } else if(rules[k].status == 2) { let btemp = await nfunc(path); BlackMerge(black, btemp); } else { NDEF(orlist, rules[k].path, []); let otemp = await nfunc(path); BlackMerge(orlist[rules[k].path], otemp); } } for(let p in orlist) { WhiteMerge(white,orlist[p]); } WhiteBlackMerge(white,black); if(count != -1) { offset = page * count; white = white.filter((e,i,arr) => { if(i < offset || i >= offset + count) return false; return true; }); } white = await DBH.ObjidToOnurid(white, await DBH.GetCoreType(cores[0])); send(white, count, page); }, Search: async function (cores, text, send, lang = "", count = -1, page) { let whiteCores = []; let blackCores = []; for(let c of cores) { if(!(await DBH.GetCoreField(c, "inverted"))) whiteCores.push(c); else blackCores.push(c); } //lang i bol sadece secili dillerde arama text = S2ENG(text.toLowerCase()); let white = []; //blackCores ignored for now for(let core of whiteCores) { let tmpwhite = await DBH.SearchText(text, core, lang); if(tmpwhite == null) { continue; } ArrayMerge(white, tmpwhite); } if(white == null) { send(white, count, page); return null; } if(count != -1) { offset = page * count; white = white.filter((e,i,arr) => { if(i < offset || i >= offset + count) return false; return true; }); } white = await DBH.ObjidToOnurid(white, await DBH.GetCoreField(cores[0],"type")); send(white, count, page); }, GetLocalCopy: async function (coreName) { let online = await DBH.GetCoreField(coreName, "online"); if(online != 2) { return await DBH.GetBackUp(coreName); } return null; }, //getcounter? } let cBurnetii = { AileAdi: "Coxiellaceae", CinsAdi: "Coxiella", TurAdi: "burnetii", Gram: "Negative", Shape: {Name: "Kokobasil", Aciklama: ["Gram Boyasi Ile Zayif Boyanir","Giemsa Ile Iyi Boyanir"]}, Solunum: "Aerob", Hareket: "Hareketsiz", KulturOrtami: [{ Name: "Axenic Culture" }], Hastaliklar: { Name: "Q Atesi", Belirtiler: ["Ates","Bas Agrisi","Eklem Agrisi","Oksuruk","Dokuntu","Menenjit Bulgulari"], Aciklama: ["Tum Dunyada Yaygin","Insanda Akut Veya Kronik(5%)","Genelde Ciftlik Hayvanlarindan Kaynaklanir", "Cok Bulasici","Lab: Trombositopeni, KC Enzimlerinde Yukselme, Eritrosit Sedimentasyonda Yukselme"], }, Bulasma: ["Hava","Damlacik","Oral","Kene"], VirualanFaktorler: "Endospor", Aciklama : ["Zorunlu Hucre Ici","Fagolizozomlarda Yasar","Cevre Sartlarina Cok Direnclidir"], }; DBH.onConnected.push(async () => { //DBH.groups.new("ITF", "asd", [await DBH.users.getId("onurcan")]); //console.log(await DBH.groups.user.status("ITF", await DBH.users.getId("onurcan"))); //console.log(await DBH.GetCoreInfo("Bakteriler#Global")); /*await Core.Filter(["Bakteriler#Global"], [{path:"root/Gram",field: "Negative", status: 1},{path:"root/Gram",field: "Positive", status: 2}], (x) => console.log(x));*/ //await core.Ekle(cBurnetii); //await core.Search("Ateş", (x) => console.log(x)); //core.Remove("Coxiella-burnetii"); });
occ55/Mikrobiyoloji
yedek/core.js
JavaScript
apache-2.0
11,683
// Inner Modules var UI = {}; var Global = {}; // Initial Global.venueModel = Alloy.createModel("venue"); Global.venueId; Global.args = arguments[0] || {}; UI = function(){ return{ setViewUserOptions: function(){ }, setVenueInfoView: function(currentVenue){ if(_.isEmpty(currentVenue) || isNaN(currentVenue.get("legacyId"))){ alert("No se pudo recuperar la instalación"); } else{ $.venueName.setText(currentVenue.get("name")); $.venueAddress.setText(currentVenue.get("address")); $.venueCity.setText(currentVenue.get("city")); var items = []; items.push({ template: "options", pre: { text: "("+currentVenue.get("eventsQ")+")" }, desc: { text: "Eventos" } }); $.optionSection.setItems(items); var sportsString = "No disponible"; if(currentVenue.get("sports")){ sportsString = ""; _.each(currentVenue.get("sports"), function(element, index, list){ if(index==0){ sportsString += element.name; }else{ sportsString += ", " + element.name; } }); } $.venueSports.setText(sportsString); // map location var installationLoc = Alloy.Globals.Map.createAnnotation({ latitude: currentVenue.get("latitude"), longitude: currentVenue.get("longitude"), title: currentVenue.get("name"), subtitle:'', pincolor:Alloy.Globals.Map.ANNOTATION_RED, myid:1 // Custom property to uniquely identify this annotation. }); $.mapview.region = {latitude: currentVenue.get("latitude"), longitude:currentVenue.get("longitude"), latitudeDelta:0.01, longitudeDelta:0.01}; $.mapview.addAnnotation(installationLoc); } } }; }(); function init(initArgs){ if(!_.isEmpty(initArgs)){ Global.venueId = initArgs.venueId; Global.venueModel.getVenueDetail(Global.venueId, { success: function(respObj){ if(respObj){ UI.setVenueInfoView(respObj); }else{ alert("No se pudo obtener la información de la instalación"); $.venue_detail.close(); } } }); }else{ } } // Listeners $.stateBar.barLeftButton.addEventListener("click", function(){ $.venue_detail.close(); }); $.venue_detail.addEventListener('android:back', function(){ $.venue_detail.close(); }); $.optionListView.addEventListener("itemclick", function(e){ switch(e.itemIndex){ case 0: // members Alloy.Globals.openWindow($.venue_detail, "shared/general_list", {initOption: 4, venueId: Global.venueId}); break; } }); // Initial call init(Global.args);
inasacu/thepista_mobile
app/controllers/venue/venue_detail.js
JavaScript
apache-2.0
2,685
import Ember from 'ember'; import service from 'ember-service/inject'; import PatientIconClassNames from '../mixins/patient-icon-class-names'; export default Ember.Component.extend(PatientIconClassNames, { classNames: ['patient-summary'], store: service(), patient: null, currentAssessment: null, selectedRisk: null, huddle: null, hasRisks: false, risksWithBirthdayStart: Ember.computed('patient.sortedRisks', 'patient.birthDate', 'currentAssessment', function() { let currentAssessment = this.get('currentAssessment'); if (Ember.isNone(currentAssessment)) { return []; } let store = this.get('store'); let birthRisk = store.createRecord('risk-assessment', { date: this.get('patient.birthDate') }); let riskCode = store.createRecord('codeable-concept', { text: currentAssessment }); let rapc = store.createRecord('risk-assessment-prediction-component', { probabilityDecimal: 0 }); rapc.set('outcome', riskCode); birthRisk.get('prediction').pushObject(rapc); let risks = [birthRisk]; risks.pushObjects(this.get('patient.sortedRisks')); return risks.filterBy('prediction.firstObject.outcome.displayText', currentAssessment); }), patientPhoto: Ember.computed.reads('patient.photo') });
intervention-engine/frontend
app/components/patient-summary.js
JavaScript
apache-2.0
1,263
define(function() { // This code was written by Tyler Akins and has been placed in the // public domain. It would be nice if you left this header intact. // Base64 code from Tyler Akins -- http://rumkin.com var Base64 = (function () { var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var obj = { /** * Encodes a string in base64 * @param {String} input The string to encode in base64. */ encode: function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } while (i < input.length); return output; }, /** * Decodes a base64 string. * @param {String} input The string to decode. */ decode: function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } while (i < input.length); return output; } }; return obj; })(); /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ /* Some functions and variables have been stripped for use with Strophe */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * 8));} function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * 8));} function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));} function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));} /* * Calculate the SHA-1 of an array of big-endian words, and a bit length */ function core_sha1(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = new Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; var i, j, t, olda, oldb, oldc, oldd, olde; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; olde = e; for (j = 0; j < 80; j++) { if (j < 16) { w[j] = x[i + j]; } else { w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); } t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return [a, b, c, d, e]; } /* * Perform the appropriate triplet combination function for the current * iteration */ function sha1_ft(t, b, c, d) { if (t < 20) { return (b & c) | ((~b) & d); } if (t < 40) { return b ^ c ^ d; } if (t < 60) { return (b & c) | (b & d) | (c & d); } return b ^ c ^ d; } /* * Determine the appropriate additive constant for the current iteration */ function sha1_kt(t) { return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514; } /* * Calculate the HMAC-SHA1 of a key and some data */ function core_hmac_sha1(key, data) { var bkey = str2binb(key); if (bkey.length > 16) { bkey = core_sha1(bkey, key.length * 8); } var ipad = new Array(16), opad = new Array(16); for (var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * 8); return core_sha1(opad.concat(hash), 512 + 160); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert an 8-bit or 16-bit string to an array of big-endian words * In 8-bit function, characters >255 have their hi-byte silently ignored. */ function str2binb(str) { var bin = []; var mask = 255; for (var i = 0; i < str.length * 8; i += 8) { bin[i>>5] |= (str.charCodeAt(i / 8) & mask) << (24 - i%32); } return bin; } /* * Convert an array of big-endian words to a string */ function binb2str(bin) { var str = ""; var mask = 255; for (var i = 0; i < bin.length * 32; i += 8) { str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask); } return str; } /* * Convert an array of big-endian words to a base-64 string */ function binb2b64(binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; var triplet, j; for (var i = 0; i < binarray.length * 4; i += 3) { triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16) | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF); for (j = 0; j < 4; j++) { if (i * 8 + j * 6 > binarray.length * 32) { str += "="; } else { str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); } } } return str; } /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* * Everything that isn't used by Strophe has been stripped here! */ var MD5 = (function () { /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ var safe_add = function (x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; /* * Bitwise rotate a 32-bit number to the left. */ var bit_rol = function (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); }; /* * Convert a string to an array of little-endian words */ var str2binl = function (str) { var bin = []; for(var i = 0; i < str.length * 8; i += 8) { bin[i>>5] |= (str.charCodeAt(i / 8) & 255) << (i%32); } return bin; }; /* * Convert an array of little-endian words to a string */ var binl2str = function (bin) { var str = ""; for(var i = 0; i < bin.length * 32; i += 8) { str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & 255); } return str; }; /* * Convert an array of little-endian words to a hex string. */ var binl2hex = function (binarray) { var hex_tab = "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); } return str; }; /* * These functions implement the four basic operations the algorithm uses. */ var md5_cmn = function (q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q),safe_add(x, t)), s),b); }; var md5_ff = function (a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); }; var md5_gg = function (a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); }; var md5_hh = function (a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); }; var md5_ii = function (a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); }; /* * Calculate the MD5 of an array of little-endian words, and a bit length */ var core_md5 = function (x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var olda, oldb, oldc, oldd; for (var i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; }; var obj = { /* * These are the functions you'll usually want to call. * They take string arguments and return either hex or base-64 encoded * strings. */ hexdigest: function (s) { return binl2hex(core_md5(str2binl(s), s.length * 8)); }, hash: function (s) { return binl2str(core_md5(str2binl(s), s.length * 8)); } }; return obj; })(); /* This program is distributed under the terms of the MIT license. Please see the LICENSE file for details. Copyright 2006-2008, OGG, LLC */ /* jshint undef: true, unused: true:, noarg: true, latedef: true */ /*global document, window, setTimeout, clearTimeout, console, ActiveXObject, Base64, MD5, DOMParser */ // from sha1.js /*global core_hmac_sha1, binb2str, str_hmac_sha1, str_sha1, b64_hmac_sha1*/ /** File: strophe.js * A JavaScript library for XMPP BOSH/XMPP over Websocket. * * This is the JavaScript version of the Strophe library. Since JavaScript * had no facilities for persistent TCP connections, this library uses * Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate * a persistent, stateful, two-way connection to an XMPP server. More * information on BOSH can be found in XEP 124. * * This version of Strophe also works with WebSockets. * For more information on XMPP-over WebSocket see this RFC draft: * http://tools.ietf.org/html/draft-ietf-xmpp-websocket-00 */ /** PrivateFunction: Function.prototype.bind * Bind a function to an instance. * * This Function object extension method creates a bound method similar * to those in Python. This means that the 'this' object will point * to the instance you want. See * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind'>MDC's bind() documentation</a> and * <a href='http://benjamin.smedbergs.us/blog/2007-01-03/bound-functions-and-function-imports-in-javascript/'>Bound Functions and Function Imports in JavaScript</a> * for a complete explanation. * * This extension already exists in some browsers (namely, Firefox 3), but * we provide it to support those that don't. * * Parameters: * (Object) obj - The object that will become 'this' in the bound function. * (Object) argN - An option argument that will be prepended to the * arguments given for the function call * * Returns: * The bound function. */ if (!Function.prototype.bind) { Function.prototype.bind = function (obj /*, arg1, arg2, ... */) { var func = this; var _slice = Array.prototype.slice; var _concat = Array.prototype.concat; var _args = _slice.call(arguments, 1); return function () { return func.apply(obj ? obj : this, _concat.call(_args, _slice.call(arguments, 0))); }; }; } /** PrivateFunction: Array.prototype.indexOf * Return the index of an object in an array. * * This function is not supplied by some JavaScript implementations, so * we provide it if it is missing. This code is from: * http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf * * Parameters: * (Object) elt - The object to look for. * (Integer) from - The index from which to start looking. (optional). * * Returns: * The index of elt in the array or -1 if not found. */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) { from += len; } for (; from < len; from++) { if (from in this && this[from] === elt) { return from; } } return -1; }; } /* All of the Strophe globals are defined in this special function below so * that references to the globals become closures. This will ensure that * on page reload, these references will still be available to callbacks * that are still executing. */ (function (callback) { var Strophe; /** Function: $build * Create a Strophe.Builder. * This is an alias for 'new Strophe.Builder(name, attrs)'. * * Parameters: * (String) name - The root element name. * (Object) attrs - The attributes for the root element in object notation. * * Returns: * A new Strophe.Builder object. */ function $build(name, attrs) { return new Strophe.Builder(name, attrs); } /** Function: $msg * Create a Strophe.Builder with a <message/> element as the root. * * Parmaeters: * (Object) attrs - The <message/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $msg(attrs) { return new Strophe.Builder("message", attrs); } /** Function: $iq * Create a Strophe.Builder with an <iq/> element as the root. * * Parameters: * (Object) attrs - The <iq/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $iq(attrs) { return new Strophe.Builder("iq", attrs); } /** Function: $pres * Create a Strophe.Builder with a <presence/> element as the root. * * Parameters: * (Object) attrs - The <presence/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $pres(attrs) { return new Strophe.Builder("presence", attrs); } /** Class: Strophe * An object container for all Strophe library functions. * * This class is just a container for all the objects and constants * used in the library. It is not meant to be instantiated, but to * provide a namespace for library objects, constants, and functions. */ Strophe = { /** Constant: VERSION * The version of the Strophe library. Unreleased builds will have * a version of head-HASH where HASH is a partial revision. */ VERSION: "1.1.3", /** Constants: XMPP Namespace Constants * Common namespace constants from the XMPP RFCs and XEPs. * * NS.HTTPBIND - HTTP BIND namespace from XEP 124. * NS.BOSH - BOSH namespace from XEP 206. * NS.CLIENT - Main XMPP client namespace. * NS.AUTH - Legacy authentication namespace. * NS.ROSTER - Roster operations namespace. * NS.PROFILE - Profile namespace. * NS.DISCO_INFO - Service discovery info namespace from XEP 30. * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30. * NS.MUC - Multi-User Chat namespace from XEP 45. * NS.SASL - XMPP SASL namespace from RFC 3920. * NS.STREAM - XMPP Streams namespace from RFC 3920. * NS.BIND - XMPP Binding namespace from RFC 3920. * NS.SESSION - XMPP Session namespace from RFC 3920. * NS.XHTML_IM - XHTML-IM namespace from XEP 71. * NS.XHTML - XHTML body namespace from XEP 71. */ NS: { HTTPBIND: "http://jabber.org/protocol/httpbind", BOSH: "urn:xmpp:xbosh", CLIENT: "jabber:client", AUTH: "jabber:iq:auth", ROSTER: "jabber:iq:roster", PROFILE: "jabber:iq:profile", DISCO_INFO: "http://jabber.org/protocol/disco#info", DISCO_ITEMS: "http://jabber.org/protocol/disco#items", MUC: "http://jabber.org/protocol/muc", SASL: "urn:ietf:params:xml:ns:xmpp-sasl", STREAM: "http://etherx.jabber.org/streams", BIND: "urn:ietf:params:xml:ns:xmpp-bind", SESSION: "urn:ietf:params:xml:ns:xmpp-session", VERSION: "jabber:iq:version", STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas", XHTML_IM: "http://jabber.org/protocol/xhtml-im", XHTML: "http://www.w3.org/1999/xhtml" }, /** Constants: XHTML_IM Namespace * contains allowed tags, tag attributes, and css properties. * Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset. * See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended * allowed tags and their attributes. */ XHTML: { tags: ['a','blockquote','br','cite','em','img','li','ol','p','span','strong','ul','body'], attributes: { 'a': ['href'], 'blockquote': ['style'], 'br': [], 'cite': ['style'], 'em': [], 'img': ['src', 'alt', 'style', 'height', 'width'], 'li': ['style'], 'ol': ['style'], 'p': ['style'], 'span': ['style'], 'strong': [], 'ul': ['style'], 'body': [] }, css: ['background-color','color','font-family','font-size','font-style','font-weight','margin-left','margin-right','text-align','text-decoration'], validTag: function(tag) { for(var i = 0; i < Strophe.XHTML.tags.length; i++) { if(tag == Strophe.XHTML.tags[i]) { return true; } } return false; }, validAttribute: function(tag, attribute) { if(typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) { for(var i = 0; i < Strophe.XHTML.attributes[tag].length; i++) { if(attribute == Strophe.XHTML.attributes[tag][i]) { return true; } } } return false; }, validCSS: function(style) { for(var i = 0; i < Strophe.XHTML.css.length; i++) { if(style == Strophe.XHTML.css[i]) { return true; } } return false; } }, /** Constants: Connection Status Constants * Connection status constants for use by the connection handler * callback. * * Status.ERROR - An error has occurred * Status.CONNECTING - The connection is currently being made * Status.CONNFAIL - The connection attempt failed * Status.AUTHENTICATING - The connection is authenticating * Status.AUTHFAIL - The authentication attempt failed * Status.CONNECTED - The connection has succeeded * Status.DISCONNECTED - The connection has been terminated * Status.DISCONNECTING - The connection is currently being terminated * Status.ATTACHED - The connection has been attached */ Status: { ERROR: 0, CONNECTING: 1, CONNFAIL: 2, AUTHENTICATING: 3, AUTHFAIL: 4, CONNECTED: 5, DISCONNECTED: 6, DISCONNECTING: 7, ATTACHED: 8 }, /** Constants: Log Level Constants * Logging level indicators. * * LogLevel.DEBUG - Debug output * LogLevel.INFO - Informational output * LogLevel.WARN - Warnings * LogLevel.ERROR - Errors * LogLevel.FATAL - Fatal errors */ LogLevel: { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, FATAL: 4 }, /** PrivateConstants: DOM Element Type Constants * DOM element types. * * ElementType.NORMAL - Normal element. * ElementType.TEXT - Text data element. * ElementType.FRAGMENT - XHTML fragment element. */ ElementType: { NORMAL: 1, TEXT: 3, CDATA: 4, FRAGMENT: 11 }, /** PrivateConstants: Timeout Values * Timeout values for error states. These values are in seconds. * These should not be changed unless you know exactly what you are * doing. * * TIMEOUT - Timeout multiplier. A waiting request will be considered * failed after Math.floor(TIMEOUT * wait) seconds have elapsed. * This defaults to 1.1, and with default wait, 66 seconds. * SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where * Strophe can detect early failure, it will consider the request * failed if it doesn't return after * Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed. * This defaults to 0.1, and with default wait, 6 seconds. */ TIMEOUT: 1.1, SECONDARY_TIMEOUT: 0.1, /** Function: addNamespace * This function is used to extend the current namespaces in * Strophe.NS. It takes a key and a value with the key being the * name of the new namespace, with its actual value. * For example: * Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub"); * * Parameters: * (String) name - The name under which the namespace will be * referenced under Strophe.NS * (String) value - The actual namespace. */ addNamespace: function (name, value) { Strophe.NS[name] = value; }, /** Function: forEachChild * Map a function over some or all child elements of a given element. * * This is a small convenience function for mapping a function over * some or all of the children of an element. If elemName is null, all * children will be passed to the function, otherwise only children * whose tag names match elemName will be passed. * * Parameters: * (XMLElement) elem - The element to operate on. * (String) elemName - The child element tag name filter. * (Function) func - The function to apply to each child. This * function should take a single argument, a DOM element. */ forEachChild: function (elem, elemName, func) { var i, childNode; for (i = 0; i < elem.childNodes.length; i++) { childNode = elem.childNodes[i]; if (childNode.nodeType == Strophe.ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) { func(childNode); } } }, /** Function: isTagEqual * Compare an element's tag name with a string. * * This function is case insensitive. * * Parameters: * (XMLElement) el - A DOM element. * (String) name - The element name. * * Returns: * true if the element's tag name matches _el_, and false * otherwise. */ isTagEqual: function (el, name) { return el.tagName.toLowerCase() == name.toLowerCase(); }, /** PrivateVariable: _xmlGenerator * _Private_ variable that caches a DOM document to * generate elements. */ _xmlGenerator: null, /** PrivateFunction: _makeGenerator * _Private_ function that creates a dummy XML DOM document to serve as * an element and text node generator. */ _makeGenerator: function () { var doc; // IE9 does implement createDocument(); however, using it will cause the browser to leak memory on page unload. // Here, we test for presence of createDocument() plus IE's proprietary documentMode attribute, which would be // less than 10 in the case of IE9 and below. if (document.implementation.createDocument === undefined || document.implementation.createDocument && document.documentMode && document.documentMode < 10) { doc = this._getIEXmlDom(); doc.appendChild(doc.createElement('strophe')); } else { doc = document.implementation .createDocument('jabber:client', 'strophe', null); } return doc; }, /** Function: xmlGenerator * Get the DOM document to generate elements. * * Returns: * The currently used DOM document. */ xmlGenerator: function () { if (!Strophe._xmlGenerator) { Strophe._xmlGenerator = Strophe._makeGenerator(); } return Strophe._xmlGenerator; }, /** PrivateFunction: _getIEXmlDom * Gets IE xml doc object * * Returns: * A Microsoft XML DOM Object * See Also: * http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx */ _getIEXmlDom : function() { var doc = null; var docStrings = [ "Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM" ]; for (var d = 0; d < docStrings.length; d++) { if (doc === null) { try { doc = new ActiveXObject(docStrings[d]); } catch (e) { doc = null; } } else { break; } } return doc; }, /** Function: xmlElement * Create an XML DOM element. * * This function creates an XML DOM element correctly across all * implementations. Note that these are not HTML DOM elements, which * aren't appropriate for XMPP stanzas. * * Parameters: * (String) name - The name for the element. * (Array|Object) attrs - An optional array or object containing * key/value pairs to use as element attributes. The object should * be in the format {'key': 'value'} or {key: 'value'}. The array * should have the format [['key1', 'value1'], ['key2', 'value2']]. * (String) text - The text child data for the element. * * Returns: * A new XML DOM element. */ xmlElement: function (name) { if (!name) { return null; } var node = Strophe.xmlGenerator().createElement(name); // FIXME: this should throw errors if args are the wrong type or // there are more than two optional args var a, i, k; for (a = 1; a < arguments.length; a++) { if (!arguments[a]) { continue; } if (typeof(arguments[a]) == "string" || typeof(arguments[a]) == "number") { node.appendChild(Strophe.xmlTextNode(arguments[a])); } else if (typeof(arguments[a]) == "object" && typeof(arguments[a].sort) == "function") { for (i = 0; i < arguments[a].length; i++) { if (typeof(arguments[a][i]) == "object" && typeof(arguments[a][i].sort) == "function") { node.setAttribute(arguments[a][i][0], arguments[a][i][1]); } } } else if (typeof(arguments[a]) == "object") { for (k in arguments[a]) { if (arguments[a].hasOwnProperty(k)) { node.setAttribute(k, arguments[a][k]); } } } } return node; }, /* Function: xmlescape * Excapes invalid xml characters. * * Parameters: * (String) text - text to escape. * * Returns: * Escaped text. */ xmlescape: function(text) { text = text.replace(/\&/g, "&amp;"); text = text.replace(/</g, "&lt;"); text = text.replace(/>/g, "&gt;"); text = text.replace(/'/g, "&apos;"); text = text.replace(/"/g, "&quot;"); return text; }, /** Function: xmlTextNode * Creates an XML DOM text node. * * Provides a cross implementation version of document.createTextNode. * * Parameters: * (String) text - The content of the text node. * * Returns: * A new XML DOM text node. */ xmlTextNode: function (text) { return Strophe.xmlGenerator().createTextNode(text); }, /** Function: xmlHtmlNode * Creates an XML DOM html node. * * Parameters: * (String) html - The content of the html node. * * Returns: * A new XML DOM text node. */ xmlHtmlNode: function (html) { var node; //ensure text is escaped if (window.DOMParser) { var parser = new DOMParser(); node = parser.parseFromString(html, "text/xml"); } else { node = new ActiveXObject("Microsoft.XMLDOM"); node.async="false"; node.loadXML(html); } return node; }, /** Function: getText * Get the concatenation of all text children of an element. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * A String with the concatenated text of all text element children. */ getText: function (elem) { if (!elem) { return null; } var str = ""; if (elem.childNodes.length === 0 && elem.nodeType == Strophe.ElementType.TEXT) { str += elem.nodeValue; } for (var i = 0; i < elem.childNodes.length; i++) { if (elem.childNodes[i].nodeType == Strophe.ElementType.TEXT) { str += elem.childNodes[i].nodeValue; } } return Strophe.xmlescape(str); }, /** Function: copyElement * Copy an XML DOM element. * * This function copies a DOM element and all its descendants and returns * the new copy. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * A new, copied DOM element tree. */ copyElement: function (elem) { var i, el; if (elem.nodeType == Strophe.ElementType.NORMAL) { el = Strophe.xmlElement(elem.tagName); for (i = 0; i < elem.attributes.length; i++) { el.setAttribute(elem.attributes[i].nodeName.toLowerCase(), elem.attributes[i].value); } for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.copyElement(elem.childNodes[i])); } } else if (elem.nodeType == Strophe.ElementType.TEXT) { el = Strophe.xmlGenerator().createTextNode(elem.nodeValue); } return el; }, /** Function: createHtml * Copy an HTML DOM element into an XML DOM. * * This function copies a DOM element and all its descendants and returns * the new copy. * * Parameters: * (HTMLElement) elem - A DOM element. * * Returns: * A new, copied DOM element tree. */ createHtml: function (elem) { var i, el, j, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue; if (elem.nodeType == Strophe.ElementType.NORMAL) { tag = elem.nodeName.toLowerCase(); if(Strophe.XHTML.validTag(tag)) { try { el = Strophe.xmlElement(tag); for(i = 0; i < Strophe.XHTML.attributes[tag].length; i++) { attribute = Strophe.XHTML.attributes[tag][i]; value = elem.getAttribute(attribute); if(typeof value == 'undefined' || value === null || value === '' || value === false || value === 0) { continue; } if(attribute == 'style' && typeof value == 'object') { if(typeof value.cssText != 'undefined') { value = value.cssText; // we're dealing with IE, need to get CSS out } } // filter out invalid css styles if(attribute == 'style') { css = []; cssAttrs = value.split(';'); for(j = 0; j < cssAttrs.length; j++) { attr = cssAttrs[j].split(':'); cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase(); if(Strophe.XHTML.validCSS(cssName)) { cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, ""); css.push(cssName + ': ' + cssValue); } } if(css.length > 0) { value = css.join('; '); el.setAttribute(attribute, value); } } else { el.setAttribute(attribute, value); } } for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } catch(e) { // invalid elements el = Strophe.xmlTextNode(''); } } else { el = Strophe.xmlGenerator().createDocumentFragment(); for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } } else if (elem.nodeType == Strophe.ElementType.FRAGMENT) { el = Strophe.xmlGenerator().createDocumentFragment(); for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.createHtml(elem.childNodes[i])); } } else if (elem.nodeType == Strophe.ElementType.TEXT) { el = Strophe.xmlTextNode(elem.nodeValue); } return el; }, /** Function: escapeNode * Escape the node part (also called local part) of a JID. * * Parameters: * (String) node - A node (or local part). * * Returns: * An escaped node (or local part). */ escapeNode: function (node) { return node.replace(/^\s+|\s+$/g, '') .replace(/\\/g, "\\5c") .replace(/ /g, "\\20") .replace(/\"/g, "\\22") .replace(/\&/g, "\\26") .replace(/\'/g, "\\27") .replace(/\//g, "\\2f") .replace(/:/g, "\\3a") .replace(/</g, "\\3c") .replace(/>/g, "\\3e") .replace(/@/g, "\\40"); }, /** Function: unescapeNode * Unescape a node part (also called local part) of a JID. * * Parameters: * (String) node - A node (or local part). * * Returns: * An unescaped node (or local part). */ unescapeNode: function (node) { return node.replace(/\\20/g, " ") .replace(/\\22/g, '"') .replace(/\\26/g, "&") .replace(/\\27/g, "'") .replace(/\\2f/g, "/") .replace(/\\3a/g, ":") .replace(/\\3c/g, "<") .replace(/\\3e/g, ">") .replace(/\\40/g, "@") .replace(/\\5c/g, "\\"); }, /** Function: getNodeFromJid * Get the node portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the node. */ getNodeFromJid: function (jid) { if (jid.indexOf("@") < 0) { return null; } return jid.split("@")[0]; }, /** Function: getDomainFromJid * Get the domain portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the domain. */ getDomainFromJid: function (jid) { var bare = Strophe.getBareJidFromJid(jid); if (bare.indexOf("@") < 0) { return bare; } else { var parts = bare.split("@"); parts.splice(0, 1); return parts.join('@'); } }, /** Function: getResourceFromJid * Get the resource portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the resource. */ getResourceFromJid: function (jid) { var s = jid.split("/"); if (s.length < 2) { return null; } s.splice(0, 1); return s.join('/'); }, /** Function: getBareJidFromJid * Get the bare JID from a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the bare JID. */ getBareJidFromJid: function (jid) { return jid ? jid.split("/")[0] : null; }, /** Function: log * User overrideable logging function. * * This function is called whenever the Strophe library calls any * of the logging functions. The default implementation of this * function does nothing. If client code wishes to handle the logging * messages, it should override this with * > Strophe.log = function (level, msg) { * > (user code here) * > }; * * Please note that data sent and received over the wire is logged * via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput(). * * The different levels and their meanings are * * DEBUG - Messages useful for debugging purposes. * INFO - Informational messages. This is mostly information like * 'disconnect was called' or 'SASL auth succeeded'. * WARN - Warnings about potential problems. This is mostly used * to report transient connection errors like request timeouts. * ERROR - Some error occurred. * FATAL - A non-recoverable fatal error occurred. * * Parameters: * (Integer) level - The log level of the log message. This will * be one of the values in Strophe.LogLevel. * (String) msg - The log message. */ /* jshint ignore:start */ log: function (level, msg) { return; }, /* jshint ignore:end */ /** Function: debug * Log a message at the Strophe.LogLevel.DEBUG level. * * Parameters: * (String) msg - The log message. */ debug: function(msg) { this.log(this.LogLevel.DEBUG, msg); }, /** Function: info * Log a message at the Strophe.LogLevel.INFO level. * * Parameters: * (String) msg - The log message. */ info: function (msg) { this.log(this.LogLevel.INFO, msg); }, /** Function: warn * Log a message at the Strophe.LogLevel.WARN level. * * Parameters: * (String) msg - The log message. */ warn: function (msg) { this.log(this.LogLevel.WARN, msg); }, /** Function: error * Log a message at the Strophe.LogLevel.ERROR level. * * Parameters: * (String) msg - The log message. */ error: function (msg) { this.log(this.LogLevel.ERROR, msg); }, /** Function: fatal * Log a message at the Strophe.LogLevel.FATAL level. * * Parameters: * (String) msg - The log message. */ fatal: function (msg) { this.log(this.LogLevel.FATAL, msg); }, /** Function: serialize * Render a DOM element and all descendants to a String. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * The serialized element tree as a String. */ serialize: function (elem) { var result; if (!elem) { return null; } if (typeof(elem.tree) === "function") { elem = elem.tree(); } var nodeName = elem.nodeName; var i, child; if (elem.getAttribute("_realname")) { nodeName = elem.getAttribute("_realname"); } result = "<" + nodeName; for (i = 0; i < elem.attributes.length; i++) { if(elem.attributes[i].nodeName != "_realname") { result += " " + elem.attributes[i].nodeName.toLowerCase() + "='" + elem.attributes[i].value .replace(/&/g, "&amp;") .replace(/\'/g, "&apos;") .replace(/>/g, "&gt;") .replace(/</g, "&lt;") + "'"; } } if (elem.childNodes.length > 0) { result += ">"; for (i = 0; i < elem.childNodes.length; i++) { child = elem.childNodes[i]; switch( child.nodeType ){ case Strophe.ElementType.NORMAL: // normal element, so recurse result += Strophe.serialize(child); break; case Strophe.ElementType.TEXT: // text element to escape values result += Strophe.xmlescape(child.nodeValue); break; case Strophe.ElementType.CDATA: // cdata section so don't escape values result += "<![CDATA["+child.nodeValue+"]]>"; } } result += "</" + nodeName + ">"; } else { result += "/>"; } return result; }, /** PrivateVariable: _requestId * _Private_ variable that keeps track of the request ids for * connections. */ _requestId: 0, /** PrivateVariable: Strophe.connectionPlugins * _Private_ variable Used to store plugin names that need * initialization on Strophe.Connection construction. */ _connectionPlugins: {}, /** Function: addConnectionPlugin * Extends the Strophe.Connection object with the given plugin. * * Parameters: * (String) name - The name of the extension. * (Object) ptype - The plugin's prototype. */ addConnectionPlugin: function (name, ptype) { Strophe._connectionPlugins[name] = ptype; } }; /** Class: Strophe.Builder * XML DOM builder. * * This object provides an interface similar to JQuery but for building * DOM element easily and rapidly. All the functions except for toString() * and tree() return the object, so calls can be chained. Here's an * example using the $iq() builder helper. * > $iq({to: 'you', from: 'me', type: 'get', id: '1'}) * > .c('query', {xmlns: 'strophe:example'}) * > .c('example') * > .toString() * The above generates this XML fragment * > <iq to='you' from='me' type='get' id='1'> * > <query xmlns='strophe:example'> * > <example/> * > </query> * > </iq> * The corresponding DOM manipulations to get a similar fragment would be * a lot more tedious and probably involve several helper variables. * * Since adding children makes new operations operate on the child, up() * is provided to traverse up the tree. To add two children, do * > builder.c('child1', ...).up().c('child2', ...) * The next operation on the Builder will be relative to the second child. */ /** Constructor: Strophe.Builder * Create a Strophe.Builder object. * * The attributes should be passed in object notation. For example * > var b = new Builder('message', {to: 'you', from: 'me'}); * or * > var b = new Builder('messsage', {'xml:lang': 'en'}); * * Parameters: * (String) name - The name of the root element. * (Object) attrs - The attributes for the root element in object notation. * * Returns: * A new Strophe.Builder. */ Strophe.Builder = function (name, attrs) { // Set correct namespace for jabber:client elements if (name == "presence" || name == "message" || name == "iq") { if (attrs && !attrs.xmlns) { attrs.xmlns = Strophe.NS.CLIENT; } else if (!attrs) { attrs = {xmlns: Strophe.NS.CLIENT}; } } // Holds the tree being built. this.nodeTree = Strophe.xmlElement(name, attrs); // Points to the current operation node. this.node = this.nodeTree; }; Strophe.Builder.prototype = { /** Function: tree * Return the DOM tree. * * This function returns the current DOM tree as an element object. This * is suitable for passing to functions like Strophe.Connection.send(). * * Returns: * The DOM tree as a element object. */ tree: function () { return this.nodeTree; }, /** Function: toString * Serialize the DOM tree to a String. * * This function returns a string serialization of the current DOM * tree. It is often used internally to pass data to a * Strophe.Request object. * * Returns: * The serialized DOM tree in a String. */ toString: function () { return Strophe.serialize(this.nodeTree); }, /** Function: up * Make the current parent element the new current element. * * This function is often used after c() to traverse back up the tree. * For example, to add two children to the same element * > builder.c('child1', {}).up().c('child2', {}); * * Returns: * The Stophe.Builder object. */ up: function () { this.node = this.node.parentNode; return this; }, /** Function: attrs * Add or modify attributes of the current element. * * The attributes should be passed in object notation. This function * does not move the current element pointer. * * Parameters: * (Object) moreattrs - The attributes to add/modify in object notation. * * Returns: * The Strophe.Builder object. */ attrs: function (moreattrs) { for (var k in moreattrs) { if (moreattrs.hasOwnProperty(k)) { this.node.setAttribute(k, moreattrs[k]); } } return this; }, /** Function: c * Add a child to the current element and make it the new current * element. * * This function moves the current element pointer to the child, * unless text is provided. If you need to add another child, it * is necessary to use up() to go back to the parent in the tree. * * Parameters: * (String) name - The name of the child. * (Object) attrs - The attributes of the child in object notation. * (String) text - The text to add to the child. * * Returns: * The Strophe.Builder object. */ c: function (name, attrs, text) { var child = Strophe.xmlElement(name, attrs, text); this.node.appendChild(child); if (!text) { this.node = child; } return this; }, /** Function: cnode * Add a child to the current element and make it the new current * element. * * This function is the same as c() except that instead of using a * name and an attributes object to create the child it uses an * existing DOM element object. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * The Strophe.Builder object. */ cnode: function (elem) { var impNode; var xmlGen = Strophe.xmlGenerator(); try { impNode = (xmlGen.importNode !== undefined); } catch (e) { impNode = false; } var newElem = impNode ? xmlGen.importNode(elem, true) : Strophe.copyElement(elem); this.node.appendChild(newElem); this.node = newElem; return this; }, /** Function: t * Add a child text element. * * This *does not* make the child the new current element since there * are no children of text elements. * * Parameters: * (String) text - The text data to append to the current element. * * Returns: * The Strophe.Builder object. */ t: function (text) { var child = Strophe.xmlTextNode(text); this.node.appendChild(child); return this; }, /** Function: h * Replace current element contents with the HTML passed in. * * This *does not* make the child the new current element * * Parameters: * (String) html - The html to insert as contents of current element. * * Returns: * The Strophe.Builder object. */ h: function (html) { var fragment = document.createElement('body'); // force the browser to try and fix any invalid HTML tags fragment.innerHTML = html; // copy cleaned html into an xml dom var xhtml = Strophe.createHtml(fragment); while(xhtml.childNodes.length > 0) { this.node.appendChild(xhtml.childNodes[0]); } return this; } }; /** PrivateClass: Strophe.Handler * _Private_ helper class for managing stanza handlers. * * A Strophe.Handler encapsulates a user provided callback function to be * executed when matching stanzas are received by the connection. * Handlers can be either one-off or persistant depending on their * return value. Returning true will cause a Handler to remain active, and * returning false will remove the Handler. * * Users will not use Strophe.Handler objects directly, but instead they * will use Strophe.Connection.addHandler() and * Strophe.Connection.deleteHandler(). */ /** PrivateConstructor: Strophe.Handler * Create and initialize a new Strophe.Handler. * * Parameters: * (Function) handler - A function to be executed when the handler is run. * (String) ns - The namespace to match. * (String) name - The element name to match. * (String) type - The element type to match. * (String) id - The element id attribute to match. * (String) from - The element from attribute to match. * (Object) options - Handler options * * Returns: * A new Strophe.Handler object. */ Strophe.Handler = function (handler, ns, name, type, id, from, options) { this.handler = handler; this.ns = ns; this.name = name; this.type = type; this.id = id; this.options = options || {matchBare: false}; // default matchBare to false if undefined if (!this.options.matchBare) { this.options.matchBare = false; } if (this.options.matchBare) { this.from = from ? Strophe.getBareJidFromJid(from) : null; } else { this.from = from; } // whether the handler is a user handler or a system handler this.user = true; }; Strophe.Handler.prototype = { /** PrivateFunction: isMatch * Tests if a stanza matches the Strophe.Handler. * * Parameters: * (XMLElement) elem - The XML element to test. * * Returns: * true if the stanza matches and false otherwise. */ isMatch: function (elem) { var nsMatch; var from = null; if (this.options.matchBare) { from = Strophe.getBareJidFromJid(elem.getAttribute('from')); } else { from = elem.getAttribute('from'); } nsMatch = false; if (!this.ns) { nsMatch = true; } else { var that = this; Strophe.forEachChild(elem, null, function (elem) { if (elem.getAttribute("xmlns") == that.ns) { nsMatch = true; } }); nsMatch = nsMatch || elem.getAttribute("xmlns") == this.ns; } if (nsMatch && (!this.name || Strophe.isTagEqual(elem, this.name)) && (!this.type || elem.getAttribute("type") == this.type) && (!this.id || elem.getAttribute("id") == this.id) && (!this.from || from == this.from)) { return true; } return false; }, /** PrivateFunction: run * Run the callback on a matching stanza. * * Parameters: * (XMLElement) elem - The DOM element that triggered the * Strophe.Handler. * * Returns: * A boolean indicating if the handler should remain active. */ run: function (elem) { var result = null; try { result = this.handler(elem); } catch (e) { if (e.sourceURL) { Strophe.fatal("error: " + this.handler + " " + e.sourceURL + ":" + e.line + " - " + e.name + ": " + e.message); } else if (e.fileName) { if (typeof(console) != "undefined") { console.trace(); console.error(this.handler, " - error - ", e, e.message); } Strophe.fatal("error: " + this.handler + " " + e.fileName + ":" + e.lineNumber + " - " + e.name + ": " + e.message); } else { Strophe.fatal("error: " + e.message + "\n" + e.stack); } throw e; } return result; }, /** PrivateFunction: toString * Get a String representation of the Strophe.Handler object. * * Returns: * A String. */ toString: function () { return "{Handler: " + this.handler + "(" + this.name + "," + this.id + "," + this.ns + ")}"; } }; /** PrivateClass: Strophe.TimedHandler * _Private_ helper class for managing timed handlers. * * A Strophe.TimedHandler encapsulates a user provided callback that * should be called after a certain period of time or at regular * intervals. The return value of the callback determines whether the * Strophe.TimedHandler will continue to fire. * * Users will not use Strophe.TimedHandler objects directly, but instead * they will use Strophe.Connection.addTimedHandler() and * Strophe.Connection.deleteTimedHandler(). */ /** PrivateConstructor: Strophe.TimedHandler * Create and initialize a new Strophe.TimedHandler object. * * Parameters: * (Integer) period - The number of milliseconds to wait before the * handler is called. * (Function) handler - The callback to run when the handler fires. This * function should take no arguments. * * Returns: * A new Strophe.TimedHandler object. */ Strophe.TimedHandler = function (period, handler) { this.period = period; this.handler = handler; this.lastCalled = new Date().getTime(); this.user = true; }; Strophe.TimedHandler.prototype = { /** PrivateFunction: run * Run the callback for the Strophe.TimedHandler. * * Returns: * true if the Strophe.TimedHandler should be called again, and false * otherwise. */ run: function () { this.lastCalled = new Date().getTime(); return this.handler(); }, /** PrivateFunction: reset * Reset the last called time for the Strophe.TimedHandler. */ reset: function () { this.lastCalled = new Date().getTime(); }, /** PrivateFunction: toString * Get a string representation of the Strophe.TimedHandler object. * * Returns: * The string representation. */ toString: function () { return "{TimedHandler: " + this.handler + "(" + this.period +")}"; } }; /** Class: Strophe.Connection * XMPP Connection manager. * * This class is the main part of Strophe. It manages a BOSH connection * to an XMPP server and dispatches events to the user callbacks as * data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, SASL SCRAM-SHA1 * and legacy authentication. * * After creating a Strophe.Connection object, the user will typically * call connect() with a user supplied callback to handle connection level * events like authentication failure, disconnection, or connection * complete. * * The user will also have several event handlers defined by using * addHandler() and addTimedHandler(). These will allow the user code to * respond to interesting stanzas or do something periodically with the * connection. These handlers will be active once authentication is * finished. * * To send data to the connection, use send(). */ /** Constructor: Strophe.Connection * Create and initialize a Strophe.Connection object. * * The transport-protocol for this connection will be chosen automatically * based on the given service parameter. URLs starting with "ws://" or * "wss://" will use WebSockets, URLs starting with "http://", "https://" * or without a protocol will use BOSH. * * To make Strophe connect to the current host you can leave out the protocol * and host part and just pass the path, e.g. * * > var conn = new Strophe.Connection("/http-bind/"); * * WebSocket options: * * If you want to connect to the current host with a WebSocket connection you * can tell Strophe to use WebSockets through a "protocol" attribute in the * optional options parameter. Valid values are "ws" for WebSocket and "wss" * for Secure WebSocket. * So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call * * > var conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"}); * * Note that relative URLs _NOT_ starting with a "/" will also include the path * of the current site. * * Also because downgrading security is not permitted by browsers, when using * relative URLs both BOSH and WebSocket connections will use their secure * variants if the current connection to the site is also secure (https). * * BOSH options: * * by adding "sync" to the options, you can control if requests will * be made synchronously or not. The default behaviour is asynchronous. * If you want to make requests synchronous, make "sync" evaluate to true: * > var conn = new Strophe.Connection("/http-bind/", {sync: true}); * You can also toggle this on an already established connection: * > conn.options.sync = true; * * * Parameters: * (String) service - The BOSH or WebSocket service URL. * (Object) options - A hash of configuration options * * Returns: * A new Strophe.Connection object. */ Strophe.Connection = function (service, options) { // The service URL this.service = service; // Configuration options this.options = options || {}; var proto = this.options.protocol || ""; // Select protocal based on service or options if (service.indexOf("ws:") === 0 || service.indexOf("wss:") === 0 || proto.indexOf("ws") === 0) { this._proto = new Strophe.Websocket(this); } else { this._proto = new Strophe.Bosh(this); } /* The connected JID. */ this.jid = ""; /* the JIDs domain */ this.domain = null; /* stream:features */ this.features = null; // SASL this._sasl_data = {}; this.do_session = false; this.do_bind = false; // handler lists this.timedHandlers = []; this.handlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; this._authentication = {}; this._idleTimeout = null; this._disconnectTimeout = null; this.do_authentication = true; this.authenticated = false; this.disconnecting = false; this.connected = false; this.errors = 0; this.paused = false; this._data = []; this._uniqueId = 0; this._sasl_success_handler = null; this._sasl_failure_handler = null; this._sasl_challenge_handler = null; // Max retries before disconnecting this.maxRetries = 5; // setup onIdle callback every 1/10th of a second this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); // initialize plugins for (var k in Strophe._connectionPlugins) { if (Strophe._connectionPlugins.hasOwnProperty(k)) { var ptype = Strophe._connectionPlugins[k]; // jslint complaints about the below line, but this is fine var F = function () {}; // jshint ignore:line F.prototype = ptype; this[k] = new F(); this[k].init(this); } } }; Strophe.Connection.prototype = { /** Function: reset * Reset the connection. * * This function should be called after a connection is disconnected * before that connection is reused. */ reset: function () { this._proto._reset(); // SASL this.do_session = false; this.do_bind = false; // handler lists this.timedHandlers = []; this.handlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; this._authentication = {}; this.authenticated = false; this.disconnecting = false; this.connected = false; this.errors = 0; this._requests = []; this._uniqueId = 0; }, /** Function: pause * Pause the request manager. * * This will prevent Strophe from sending any more requests to the * server. This is very useful for temporarily pausing * BOSH-Connections while a lot of send() calls are happening quickly. * This causes Strophe to send the data in a single request, saving * many request trips. */ pause: function () { this.paused = true; }, /** Function: resume * Resume the request manager. * * This resumes after pause() has been called. */ resume: function () { this.paused = false; }, /** Function: getUniqueId * Generate a unique ID for use in <iq/> elements. * * All <iq/> stanzas are required to have unique id attributes. This * function makes creating these easy. Each connection instance has * a counter which starts from zero, and the value of this counter * plus a colon followed by the suffix becomes the unique id. If no * suffix is supplied, the counter is used as the unique id. * * Suffixes are used to make debugging easier when reading the stream * data, and their use is recommended. The counter resets to 0 for * every new connection for the same reason. For connections to the * same server that authenticate the same way, all the ids should be * the same, which makes it easy to see changes. This is useful for * automated testing as well. * * Parameters: * (String) suffix - A optional suffix to append to the id. * * Returns: * A unique string to be used for the id attribute. */ getUniqueId: function (suffix) { if (typeof(suffix) == "string" || typeof(suffix) == "number") { return ++this._uniqueId + ":" + suffix; } else { return ++this._uniqueId + ""; } }, /** Function: connect * Starts the connection process. * * As the connection process proceeds, the user supplied callback will * be triggered multiple times with status updates. The callback * should take two arguments - the status code and the error condition. * * The status code will be one of the values in the Strophe.Status * constants. The error condition will be one of the conditions * defined in RFC 3920 or the condition 'strophe-parsererror'. * * The Parameters _wait_, _hold_ and _route_ are optional and only relevant * for BOSH connections. Please see XEP 124 for a more detailed explanation * of the optional parameters. * * Parameters: * (String) jid - The user's JID. This may be a bare JID, * or a full JID. If a node is not supplied, SASL ANONYMOUS * authentication will be attempted. * (String) pass - The user's password. * (Function) callback - The connect callback function. * (Integer) wait - The optional HTTPBIND wait value. This is the * time the server will wait before returning an empty result for * a request. The default setting of 60 seconds is recommended. * (Integer) hold - The optional HTTPBIND hold value. This is the * number of connections the server will hold at one time. This * should almost always be set to 1 (the default). * (String) route - The optional route value. */ connect: function (jid, pass, callback, wait, hold, route) { this.jid = jid; /** Variable: authzid * Authorization identity. */ this.authzid = Strophe.getBareJidFromJid(this.jid); /** Variable: authcid * Authentication identity (User name). */ this.authcid = Strophe.getNodeFromJid(this.jid); /** Variable: pass * Authentication identity (User password). */ this.pass = pass; /** Variable: servtype * Digest MD5 compatibility. */ this.servtype = "xmpp"; this.connect_callback = callback; this.disconnecting = false; this.connected = false; this.authenticated = false; this.errors = 0; // parse jid for domain this.domain = Strophe.getDomainFromJid(this.jid); this._changeConnectStatus(Strophe.Status.CONNECTING, null); this._proto._connect(wait, hold, route); }, /** Function: attach * Attach to an already created and authenticated BOSH session. * * This function is provided to allow Strophe to attach to BOSH * sessions which have been created externally, perhaps by a Web * application. This is often used to support auto-login type features * without putting user credentials into the page. * * Parameters: * (String) jid - The full JID that is bound by the session. * (String) sid - The SID of the BOSH session. * (String) rid - The current RID of the BOSH session. This RID * will be used by the next request. * (Function) callback The connect callback function. * (Integer) wait - The optional HTTPBIND wait value. This is the * time the server will wait before returning an empty result for * a request. The default setting of 60 seconds is recommended. * Other settings will require tweaks to the Strophe.TIMEOUT value. * (Integer) hold - The optional HTTPBIND hold value. This is the * number of connections the server will hold at one time. This * should almost always be set to 1 (the default). * (Integer) wind - The optional HTTBIND window value. This is the * allowed range of request ids that are valid. The default is 5. */ attach: function (jid, sid, rid, callback, wait, hold, wind) { this._proto._attach(jid, sid, rid, callback, wait, hold, wind); }, /** Function: xmlInput * User overrideable function that receives XML data coming into the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.xmlInput = function (elem) { * > (user code) * > }; * * Due to limitations of current Browsers' XML-Parsers the opening and closing * <stream> tag for WebSocket-Connoctions will be passed as selfclosing here. * * BOSH-Connections will have all stanzas wrapped in a <body> tag. See * <Strophe.Bosh.strip> if you want to strip this tag. * * Parameters: * (XMLElement) elem - The XML data received by the connection. */ /* jshint unused:false */ xmlInput: function (elem) { return; }, /* jshint unused:true */ /** Function: xmlOutput * User overrideable function that receives XML data sent to the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.xmlOutput = function (elem) { * > (user code) * > }; * * Due to limitations of current Browsers' XML-Parsers the opening and closing * <stream> tag for WebSocket-Connoctions will be passed as selfclosing here. * * BOSH-Connections will have all stanzas wrapped in a <body> tag. See * <Strophe.Bosh.strip> if you want to strip this tag. * * Parameters: * (XMLElement) elem - The XMLdata sent by the connection. */ /* jshint unused:false */ xmlOutput: function (elem) { return; }, /* jshint unused:true */ /** Function: rawInput * User overrideable function that receives raw data coming into the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.rawInput = function (data) { * > (user code) * > }; * * Parameters: * (String) data - The data received by the connection. */ /* jshint unused:false */ rawInput: function (data) { return; }, /* jshint unused:true */ /** Function: rawOutput * User overrideable function that receives raw data sent to the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.rawOutput = function (data) { * > (user code) * > }; * * Parameters: * (String) data - The data sent by the connection. */ /* jshint unused:false */ rawOutput: function (data) { return; }, /* jshint unused:true */ /** Function: send * Send a stanza. * * This function is called to push data onto the send queue to * go out over the wire. Whenever a request is sent to the BOSH * server, all pending data is sent and the queue is flushed. * * Parameters: * (XMLElement | * [XMLElement] | * Strophe.Builder) elem - The stanza to send. */ send: function (elem) { if (elem === null) { return ; } if (typeof(elem.sort) === "function") { for (var i = 0; i < elem.length; i++) { this._queueData(elem[i]); } } else if (typeof(elem.tree) === "function") { this._queueData(elem.tree()); } else { this._queueData(elem); } this._proto._send(); }, /** Function: flush * Immediately send any pending outgoing data. * * Normally send() queues outgoing data until the next idle period * (100ms), which optimizes network use in the common cases when * several send()s are called in succession. flush() can be used to * immediately send all pending data. */ flush: function () { // cancel the pending idle period and run the idle function // immediately clearTimeout(this._idleTimeout); this._onIdle(); }, /** Function: sendIQ * Helper function to send IQ stanzas. * * Parameters: * (XMLElement) elem - The stanza to send. * (Function) callback - The callback function for a successful request. * (Function) errback - The callback function for a failed or timed * out request. On timeout, the stanza will be null. * (Integer) timeout - The time specified in milliseconds for a * timeout to occur. * * Returns: * The id used to send the IQ. */ sendIQ: function(elem, callback, errback, timeout) { var timeoutHandler = null; var that = this; if (typeof(elem.tree) === "function") { elem = elem.tree(); } var id = elem.getAttribute('id'); // inject id if not found if (!id) { id = this.getUniqueId("sendIQ"); elem.setAttribute("id", id); } var handler = this.addHandler(function (stanza) { // remove timeout handler if there is one if (timeoutHandler) { that.deleteTimedHandler(timeoutHandler); } var iqtype = stanza.getAttribute('type'); if (iqtype == 'result') { if (callback) { callback(stanza); } } else if (iqtype == 'error') { if (errback) { errback(stanza); } } else { throw { name: "StropheError", message: "Got bad IQ type of " + iqtype }; } }, null, 'iq', null, id); // if timeout specified, setup timeout handler. if (timeout) { timeoutHandler = this.addTimedHandler(timeout, function () { // get rid of normal handler that.deleteHandler(handler); // call errback on timeout with null stanza if (errback) { errback(null); } return false; }); } this.send(elem); return id; }, /** PrivateFunction: _queueData * Queue outgoing data for later sending. Also ensures that the data * is a DOMElement. */ _queueData: function (element) { if (element === null || !element.tagName || !element.childNodes) { throw { name: "StropheError", message: "Cannot queue non-DOMElement." }; } this._data.push(element); }, /** PrivateFunction: _sendRestart * Send an xmpp:restart stanza. */ _sendRestart: function () { this._data.push("restart"); this._proto._sendRestart(); this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); }, /** Function: addTimedHandler * Add a timed handler to the connection. * * This function adds a timed handler. The provided handler will * be called every period milliseconds until it returns false, * the connection is terminated, or the handler is removed. Handlers * that wish to continue being invoked should return true. * * Because of method binding it is necessary to save the result of * this function if you wish to remove a handler with * deleteTimedHandler(). * * Note that user handlers are not active until authentication is * successful. * * Parameters: * (Integer) period - The period of the handler. * (Function) handler - The callback function. * * Returns: * A reference to the handler that can be used to remove it. */ addTimedHandler: function (period, handler) { var thand = new Strophe.TimedHandler(period, handler); this.addTimeds.push(thand); return thand; }, /** Function: deleteTimedHandler * Delete a timed handler for a connection. * * This function removes a timed handler from the connection. The * handRef parameter is *not* the function passed to addTimedHandler(), * but is the reference returned from addTimedHandler(). * * Parameters: * (Strophe.TimedHandler) handRef - The handler reference. */ deleteTimedHandler: function (handRef) { // this must be done in the Idle loop so that we don't change // the handlers during iteration this.removeTimeds.push(handRef); }, /** Function: addHandler * Add a stanza handler for the connection. * * This function adds a stanza handler to the connection. The * handler callback will be called for any stanza that matches * the parameters. Note that if multiple parameters are supplied, * they must all match for the handler to be invoked. * * The handler will receive the stanza that triggered it as its argument. * The handler should return true if it is to be invoked again; * returning false will remove the handler after it returns. * * As a convenience, the ns parameters applies to the top level element * and also any of its immediate children. This is primarily to make * matching /iq/query elements easy. * * The options argument contains handler matching flags that affect how * matches are determined. Currently the only flag is matchBare (a * boolean). When matchBare is true, the from parameter and the from * attribute on the stanza will be matched as bare JIDs instead of * full JIDs. To use this, pass {matchBare: true} as the value of * options. The default value for matchBare is false. * * The return value should be saved if you wish to remove the handler * with deleteHandler(). * * Parameters: * (Function) handler - The user callback. * (String) ns - The namespace to match. * (String) name - The stanza name to match. * (String) type - The stanza type attribute to match. * (String) id - The stanza id attribute to match. * (String) from - The stanza from attribute to match. * (String) options - The handler options * * Returns: * A reference to the handler that can be used to remove it. */ addHandler: function (handler, ns, name, type, id, from, options) { var hand = new Strophe.Handler(handler, ns, name, type, id, from, options); this.addHandlers.push(hand); return hand; }, /** Function: deleteHandler * Delete a stanza handler for a connection. * * This function removes a stanza handler from the connection. The * handRef parameter is *not* the function passed to addHandler(), * but is the reference returned from addHandler(). * * Parameters: * (Strophe.Handler) handRef - The handler reference. */ deleteHandler: function (handRef) { // this must be done in the Idle loop so that we don't change // the handlers during iteration this.removeHandlers.push(handRef); }, /** Function: disconnect * Start the graceful disconnection process. * * This function starts the disconnection process. This process starts * by sending unavailable presence and sending BOSH body of type * terminate. A timeout handler makes sure that disconnection happens * even if the BOSH server does not respond. * * The user supplied connection callback will be notified of the * progress as this process happens. * * Parameters: * (String) reason - The reason the disconnect is occuring. */ disconnect: function (reason) { this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason); Strophe.info("Disconnect was called because: " + reason); if (this.connected) { var pres = false; this.disconnecting = true; if (this.authenticated) { pres = $pres({ xmlns: Strophe.NS.CLIENT, type: 'unavailable' }); } // setup timeout handler this._disconnectTimeout = this._addSysTimedHandler( 3000, this._onDisconnectTimeout.bind(this)); this._proto._disconnect(pres); } }, /** PrivateFunction: _changeConnectStatus * _Private_ helper function that makes sure plugins and the user's * callback are notified of connection status changes. * * Parameters: * (Integer) status - the new connection status, one of the values * in Strophe.Status * (String) condition - the error condition or null */ _changeConnectStatus: function (status, condition) { // notify all plugins listening for status changes for (var k in Strophe._connectionPlugins) { if (Strophe._connectionPlugins.hasOwnProperty(k)) { var plugin = this[k]; if (plugin.statusChanged) { try { plugin.statusChanged(status, condition); } catch (err) { Strophe.error("" + k + " plugin caused an exception " + "changing status: " + err); } } } } // notify the user's callback if (this.connect_callback) { try { this.connect_callback(status, condition); } catch (e) { Strophe.error("User connection callback caused an " + "exception: " + e); } } }, /** PrivateFunction: _doDisconnect * _Private_ function to disconnect. * * This is the last piece of the disconnection logic. This resets the * connection and alerts the user's connection callback. */ _doDisconnect: function () { // Cancel Disconnect Timeout if (this._disconnectTimeout !== null) { this.deleteTimedHandler(this._disconnectTimeout); this._disconnectTimeout = null; } Strophe.info("_doDisconnect was called"); this._proto._doDisconnect(); this.authenticated = false; this.disconnecting = false; // delete handlers this.handlers = []; this.timedHandlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; // tell the parent we disconnected this._changeConnectStatus(Strophe.Status.DISCONNECTED, null); this.connected = false; }, /** PrivateFunction: _dataRecv * _Private_ handler to processes incoming data from the the connection. * * Except for _connect_cb handling the initial connection request, * this function handles the incoming data for all requests. This * function also fires stanza handlers that match each incoming * stanza. * * Parameters: * (Strophe.Request) req - The request that has data ready. * (string) req - The stanza a raw string (optiona). */ _dataRecv: function (req, raw) { Strophe.info("_dataRecv called"); var elem = this._proto._reqToData(req); if (elem === null) { return; } if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) { if (elem.nodeName === this._proto.strip && elem.childNodes.length) { this.xmlInput(elem.childNodes[0]); } else { this.xmlInput(elem); } } if (this.rawInput !== Strophe.Connection.prototype.rawInput) { if (raw) { this.rawInput(raw); } else { this.rawInput(Strophe.serialize(elem)); } } // remove handlers scheduled for deletion var i, hand; while (this.removeHandlers.length > 0) { hand = this.removeHandlers.pop(); i = this.handlers.indexOf(hand); if (i >= 0) { this.handlers.splice(i, 1); } } // add handlers scheduled for addition while (this.addHandlers.length > 0) { this.handlers.push(this.addHandlers.pop()); } // handle graceful disconnect if (this.disconnecting && this._proto._emptyQueue()) { this._doDisconnect(); return; } var typ = elem.getAttribute("type"); var cond, conflict; if (typ !== null && typ == "terminate") { // Don't process stanzas that come in after disconnect if (this.disconnecting) { return; } // an error occurred cond = elem.getAttribute("condition"); conflict = elem.getElementsByTagName("conflict"); if (cond !== null) { if (cond == "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._changeConnectStatus(Strophe.Status.CONNFAIL, cond); } else { this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown"); } this.disconnect('unknown stream-error'); return; } // send each incoming stanza through the handler chain var that = this; Strophe.forEachChild(elem, null, function (child) { var i, newList; // process handlers newList = that.handlers; that.handlers = []; for (i = 0; i < newList.length; i++) { var hand = newList[i]; // encapsulate 'handler.run' not to lose the whole handler list if // one of the handlers throws an exception try { if (hand.isMatch(child) && (that.authenticated || !hand.user)) { if (hand.run(child)) { that.handlers.push(hand); } } else { that.handlers.push(hand); } } catch(e) { // if the handler throws an exception, we consider it as false Strophe.warn('Removing Strophe handlers due to uncaught exception: ' + e.message); } } }); }, /** Attribute: mechanisms * SASL Mechanisms available for Conncection. */ mechanisms: {}, /** PrivateFunction: _connect_cb * _Private_ handler for initial connection request. * * This handler is used to process the initial connection request * response from the BOSH server. It is used to set up authentication * handlers and start the authentication process. * * SASL authentication will be attempted if available, otherwise * the code will fall back to legacy authentication. * * Parameters: * (Strophe.Request) req - The current request. * (Function) _callback - low level (xmpp) connect callback function. * Useful for plugins with their own xmpp connect callback (when their) * want to do something special). */ _connect_cb: function (req, _callback, raw) { Strophe.info("_connect_cb was called"); this.connected = true; var bodyWrap = this._proto._reqToData(req); if (!bodyWrap) { return; } if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) { if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) { this.xmlInput(bodyWrap.childNodes[0]); } else { this.xmlInput(bodyWrap); } } if (this.rawInput !== Strophe.Connection.prototype.rawInput) { if (raw) { this.rawInput(raw); } else { this.rawInput(Strophe.serialize(bodyWrap)); } } var conncheck = this._proto._connect_cb(bodyWrap); if (conncheck === Strophe.Status.CONNFAIL) { return; } this._authentication.sasl_scram_sha1 = false; this._authentication.sasl_plain = false; this._authentication.sasl_digest_md5 = false; this._authentication.sasl_anonymous = false; this._authentication.legacy_auth = false; // Check for the stream:features tag var hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0; if (!hasFeatures) { hasFeatures = bodyWrap.getElementsByTagName("features").length > 0; } var mechanisms = bodyWrap.getElementsByTagName("mechanism"); var matched = []; var i, mech, found_authentication = false; if (!hasFeatures) { this._proto._no_auth_received(_callback); return; } if (mechanisms.length > 0) { for (i = 0; i < mechanisms.length; i++) { mech = Strophe.getText(mechanisms[i]); if (this.mechanisms[mech]) matched.push(this.mechanisms[mech]); } } this._authentication.legacy_auth = bodyWrap.getElementsByTagName("auth").length > 0; found_authentication = this._authentication.legacy_auth || matched.length > 0; if (!found_authentication) { this._proto._no_auth_received(_callback); return; } if (this.do_authentication !== false) this.authenticate(matched); }, /** Function: authenticate * Set up authentication * * Contiunues the initial connection request by setting up authentication * handlers and start the authentication process. * * SASL authentication will be attempted if available, otherwise * the code will fall back to legacy authentication. * */ authenticate: function (matched) { var i; // Sorting matched mechanisms according to priority. for (i = 0; i < matched.length - 1; ++i) { var higher = i; for (var j = i + 1; j < matched.length; ++j) { if (matched[j].prototype.priority > matched[higher].prototype.priority) { higher = j; } } if (higher != i) { var swap = matched[i]; matched[i] = matched[higher]; matched[higher] = swap; } } // run each mechanism var mechanism_found = false; for (i = 0; i < matched.length; ++i) { if (!matched[i].test(this)) continue; this._sasl_success_handler = this._addSysHandler( this._sasl_success_cb.bind(this), null, "success", null, null); this._sasl_failure_handler = this._addSysHandler( this._sasl_failure_cb.bind(this), null, "failure", null, null); this._sasl_challenge_handler = this._addSysHandler( this._sasl_challenge_cb.bind(this), null, "challenge", null, null); this._sasl_mechanism = new matched[i](); this._sasl_mechanism.onStart(this); var request_auth_exchange = $build("auth", { xmlns: Strophe.NS.SASL, mechanism: this._sasl_mechanism.name }); if (this._sasl_mechanism.isClientFirst) { var response = this._sasl_mechanism.onChallenge(this, null); request_auth_exchange.t(Base64.encode(response)); } this.send(request_auth_exchange.tree()); mechanism_found = true; break; } if (!mechanism_found) { // if none of the mechanism worked if (Strophe.getNodeFromJid(this.jid) === null) { // we don't have a node, which is required for non-anonymous // client connections this._changeConnectStatus(Strophe.Status.CONNFAIL, 'x-strophe-bad-non-anon-jid'); this.disconnect('x-strophe-bad-non-anon-jid'); } else { // fall back to legacy authentication this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null); this._addSysHandler(this._auth1_cb.bind(this), null, null, null, "_auth_1"); this.send($iq({ type: "get", to: this.domain, id: "_auth_1" }).c("query", { xmlns: Strophe.NS.AUTH }).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree()); } } }, _sasl_challenge_cb: function(elem) { var challenge = Base64.decode(Strophe.getText(elem)); var response = this._sasl_mechanism.onChallenge(this, challenge); var stanza = $build('response', { xmlns: Strophe.NS.SASL }); if (response !== "") { stanza.t(Base64.encode(response)); } this.send(stanza.tree()); return true; }, /** PrivateFunction: _auth1_cb * _Private_ handler for legacy authentication. * * This handler is called in response to the initial <iq type='get'/> * for legacy authentication. It builds an authentication <iq/> and * sends it, creating a handler (calling back to _auth2_cb()) to * handle the result * * Parameters: * (XMLElement) elem - The stanza that triggered the callback. * * Returns: * false to remove the handler. */ /* jshint unused:false */ _auth1_cb: function (elem) { // build plaintext auth iq var iq = $iq({type: "set", id: "_auth_2"}) .c('query', {xmlns: Strophe.NS.AUTH}) .c('username', {}).t(Strophe.getNodeFromJid(this.jid)) .up() .c('password').t(this.pass); if (!Strophe.getResourceFromJid(this.jid)) { // since the user has not supplied a resource, we pick // a default one here. unlike other auth methods, the server // cannot do this for us. this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe'; } iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid)); this._addSysHandler(this._auth2_cb.bind(this), null, null, null, "_auth_2"); this.send(iq.tree()); return false; }, /* jshint unused:true */ /** PrivateFunction: _sasl_success_cb * _Private_ handler for succesful SASL authentication. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_success_cb: function (elem) { if (this._sasl_data["server-signature"]) { var serverSignature; var success = Base64.decode(Strophe.getText(elem)); var attribMatch = /([a-z]+)=([^,]+)(,|$)/; var matches = success.match(attribMatch); if (matches[1] == "v") { serverSignature = matches[2]; } if (serverSignature != this._sasl_data["server-signature"]) { // remove old handlers this.deleteHandler(this._sasl_failure_handler); this._sasl_failure_handler = null; if (this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler); this._sasl_challenge_handler = null; } this._sasl_data = {}; return this._sasl_failure_cb(null); } } Strophe.info("SASL authentication succeeded."); if(this._sasl_mechanism) this._sasl_mechanism.onSuccess(); // remove old handlers this.deleteHandler(this._sasl_failure_handler); this._sasl_failure_handler = null; if (this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler); this._sasl_challenge_handler = null; } this._addSysHandler(this._sasl_auth1_cb.bind(this), null, "stream:features", null, null); // we must send an xmpp:restart now this._sendRestart(); return false; }, /** PrivateFunction: _sasl_auth1_cb * _Private_ handler to start stream binding. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_auth1_cb: function (elem) { // save stream:features for future usage this.features = elem; var i, child; for (i = 0; i < elem.childNodes.length; i++) { child = elem.childNodes[i]; if (child.nodeName == 'bind') { this.do_bind = true; } if (child.nodeName == 'session') { this.do_session = true; } } if (!this.do_bind) { this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } else { this._addSysHandler(this._sasl_bind_cb.bind(this), null, null, null, "_bind_auth_2"); var resource = Strophe.getResourceFromJid(this.jid); if (resource) { this.send($iq({type: "set", id: "_bind_auth_2"}) .c('bind', {xmlns: Strophe.NS.BIND}) .c('resource', {}).t(resource).tree()); } else { this.send($iq({type: "set", id: "_bind_auth_2"}) .c('bind', {xmlns: Strophe.NS.BIND}) .tree()); } } return false; }, /** PrivateFunction: _sasl_bind_cb * _Private_ handler for binding result and session start. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_bind_cb: function (elem) { if (elem.getAttribute("type") == "error") { Strophe.info("SASL binding failed."); var conflict = elem.getElementsByTagName("conflict"), condition; if (conflict.length > 0) { condition = 'conflict'; } this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition); return false; } // TODO - need to grab errors var bind = elem.getElementsByTagName("bind"); var jidNode; if (bind.length > 0) { // Grab jid jidNode = bind[0].getElementsByTagName("jid"); if (jidNode.length > 0) { this.jid = Strophe.getText(jidNode[0]); if (this.do_session) { this._addSysHandler(this._sasl_session_cb.bind(this), null, null, null, "_session_auth_2"); this.send($iq({type: "set", id: "_session_auth_2"}) .c('session', {xmlns: Strophe.NS.SESSION}) .tree()); } else { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } } } else { Strophe.info("SASL binding failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } }, /** PrivateFunction: _sasl_session_cb * _Private_ handler to finish successful SASL connection. * * This sets Connection.authenticated to true on success, which * starts the processing of user handlers. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_session_cb: function (elem) { if (elem.getAttribute("type") == "result") { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } else if (elem.getAttribute("type") == "error") { Strophe.info("Session creation failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } return false; }, /** PrivateFunction: _sasl_failure_cb * _Private_ handler for SASL authentication failure. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ /* jshint unused:false */ _sasl_failure_cb: function (elem) { // delete unneeded handlers if (this._sasl_success_handler) { this.deleteHandler(this._sasl_success_handler); this._sasl_success_handler = null; } if (this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler); this._sasl_challenge_handler = null; } if(this._sasl_mechanism) this._sasl_mechanism.onFailure(); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; }, /* jshint unused:true */ /** PrivateFunction: _auth2_cb * _Private_ handler to finish legacy authentication. * * This handler is called when the result from the jabber:iq:auth * <iq/> stanza is returned. * * Parameters: * (XMLElement) elem - The stanza that triggered the callback. * * Returns: * false to remove the handler. */ _auth2_cb: function (elem) { if (elem.getAttribute("type") == "result") { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } else if (elem.getAttribute("type") == "error") { this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); this.disconnect('authentication failed'); } return false; }, /** PrivateFunction: _addSysTimedHandler * _Private_ function to add a system level timed handler. * * This function is used to add a Strophe.TimedHandler for the * library code. System timed handlers are allowed to run before * authentication is complete. * * Parameters: * (Integer) period - The period of the handler. * (Function) handler - The callback function. */ _addSysTimedHandler: function (period, handler) { var thand = new Strophe.TimedHandler(period, handler); thand.user = false; this.addTimeds.push(thand); return thand; }, /** PrivateFunction: _addSysHandler * _Private_ function to add a system level stanza handler. * * This function is used to add a Strophe.Handler for the * library code. System stanza handlers are allowed to run before * authentication is complete. * * Parameters: * (Function) handler - The callback function. * (String) ns - The namespace to match. * (String) name - The stanza name to match. * (String) type - The stanza type attribute to match. * (String) id - The stanza id attribute to match. */ _addSysHandler: function (handler, ns, name, type, id) { var hand = new Strophe.Handler(handler, ns, name, type, id); hand.user = false; this.addHandlers.push(hand); return hand; }, /** PrivateFunction: _onDisconnectTimeout * _Private_ timeout handler for handling non-graceful disconnection. * * If the graceful disconnect process does not complete within the * time allotted, this handler finishes the disconnect anyway. * * Returns: * false to remove the handler. */ _onDisconnectTimeout: function () { Strophe.info("_onDisconnectTimeout was called"); this._proto._onDisconnectTimeout(); // actually disconnect this._doDisconnect(); return false; }, /** PrivateFunction: _onIdle * _Private_ handler to process events during idle cycle. * * This handler is called every 100ms to fire timed handlers that * are ready and keep poll requests going. */ _onIdle: function () { var i, thand, since, newList; // add timed handlers scheduled for addition // NOTE: we add before remove in the case a timed handler is // added and then deleted before the next _onIdle() call. while (this.addTimeds.length > 0) { this.timedHandlers.push(this.addTimeds.pop()); } // remove timed handlers that have been scheduled for deletion while (this.removeTimeds.length > 0) { thand = this.removeTimeds.pop(); i = this.timedHandlers.indexOf(thand); if (i >= 0) { this.timedHandlers.splice(i, 1); } } // call ready timed handlers var now = new Date().getTime(); newList = []; for (i = 0; i < this.timedHandlers.length; i++) { thand = this.timedHandlers[i]; if (this.authenticated || !thand.user) { since = thand.lastCalled + thand.period; if (since - now <= 0) { if (thand.run()) { newList.push(thand); } } else { newList.push(thand); } } } this.timedHandlers = newList; clearTimeout(this._idleTimeout); this._proto._onIdle(); // reactivate the timer only if connected if (this.connected) { this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); } } }; if (callback) { callback(Strophe, $build, $msg, $iq, $pres); } /** Class: Strophe.SASLMechanism * * encapsulates SASL authentication mechanisms. * * User code may override the priority for each mechanism or disable it completely. * See <priority> for information about changing priority and <test> for informatian on * how to disable a mechanism. * * By default, all mechanisms are enabled and the priorities are * * SCRAM-SHA1 - 40 * DIGEST-MD5 - 30 * Plain - 20 */ /** * PrivateConstructor: Strophe.SASLMechanism * SASL auth mechanism abstraction. * * Parameters: * (String) name - SASL Mechanism name. * (Boolean) isClientFirst - If client should send response first without challenge. * (Number) priority - Priority. * * Returns: * A new Strophe.SASLMechanism object. */ Strophe.SASLMechanism = function(name, isClientFirst, priority) { /** PrivateVariable: name * Mechanism name. */ this.name = name; /** PrivateVariable: isClientFirst * If client sends response without initial server challenge. */ this.isClientFirst = isClientFirst; /** Variable: priority * Determines which <SASLMechanism> is chosen for authentication (Higher is better). * Users may override this to prioritize mechanisms differently. * * In the default configuration the priorities are * * SCRAM-SHA1 - 40 * DIGEST-MD5 - 30 * Plain - 20 * * Example: (This will cause Strophe to choose the mechanism that the server sent first) * * > Strophe.SASLMD5.priority = Strophe.SASLSHA1.priority; * * See <SASL mechanisms> for a list of available mechanisms. * */ this.priority = priority; }; Strophe.SASLMechanism.prototype = { /** * Function: test * Checks if mechanism able to run. * To disable a mechanism, make this return false; * * To disable plain authentication run * > Strophe.SASLPlain.test = function() { * > return false; * > } * * See <SASL mechanisms> for a list of available mechanisms. * * Parameters: * (Strophe.Connection) connection - Target Connection. * * Returns: * (Boolean) If mechanism was able to run. */ /* jshint unused:false */ test: function(connection) { return true; }, /* jshint unused:true */ /** PrivateFunction: onStart * Called before starting mechanism on some connection. * * Parameters: * (Strophe.Connection) connection - Target Connection. */ onStart: function(connection) { this._connection = connection; }, /** PrivateFunction: onChallenge * Called by protocol implementation on incoming challenge. If client is * first (isClientFirst == true) challenge will be null on the first call. * * Parameters: * (Strophe.Connection) connection - Target Connection. * (String) challenge - current challenge to handle. * * Returns: * (String) Mechanism response. */ /* jshint unused:false */ onChallenge: function(connection, challenge) { throw new Error("You should implement challenge handling!"); }, /* jshint unused:true */ /** PrivateFunction: onFailure * Protocol informs mechanism implementation about SASL failure. */ onFailure: function() { this._connection = null; }, /** PrivateFunction: onSuccess * Protocol informs mechanism implementation about SASL success. */ onSuccess: function() { this._connection = null; } }; /** Constants: SASL mechanisms * Available authentication mechanisms * * Strophe.SASLAnonymous - SASL Anonymous authentication. * Strophe.SASLPlain - SASL Plain authentication. * Strophe.SASLMD5 - SASL Digest-MD5 authentication * Strophe.SASLSHA1 - SASL SCRAM-SHA1 authentication */ // Building SASL callbacks /** PrivateConstructor: SASLAnonymous * SASL Anonymous authentication. */ Strophe.SASLAnonymous = function() {}; Strophe.SASLAnonymous.prototype = new Strophe.SASLMechanism("ANONYMOUS", false, 10); Strophe.SASLAnonymous.test = function(connection) { return connection.authcid === null; }; Strophe.Connection.prototype.mechanisms[Strophe.SASLAnonymous.prototype.name] = Strophe.SASLAnonymous; /** PrivateConstructor: SASLPlain * SASL Plain authentication. */ Strophe.SASLPlain = function() {}; Strophe.SASLPlain.prototype = new Strophe.SASLMechanism("PLAIN", true, 20); Strophe.SASLPlain.test = function(connection) { return connection.authcid !== null; }; Strophe.SASLPlain.prototype.onChallenge = function(connection) { var auth_str = connection.authzid; auth_str = auth_str + "\u0000"; auth_str = auth_str + connection.authcid; auth_str = auth_str + "\u0000"; auth_str = auth_str + connection.pass; return auth_str; }; Strophe.Connection.prototype.mechanisms[Strophe.SASLPlain.prototype.name] = Strophe.SASLPlain; /** PrivateConstructor: SASLSHA1 * SASL SCRAM SHA 1 authentication. */ Strophe.SASLSHA1 = function() {}; /* TEST: * This is a simple example of a SCRAM-SHA-1 authentication exchange * when the client doesn't support channel bindings (username 'user' and * password 'pencil' are used): * * C: n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL * S: r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92, * i=4096 * C: c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j, * p=v0X8v3Bz2T0CJGbJQyF0X+HI4Ts= * S: v=rmF9pqV8S7suAoZWja4dJRkFsKQ= * */ Strophe.SASLSHA1.prototype = new Strophe.SASLMechanism("SCRAM-SHA-1", true, 40); Strophe.SASLSHA1.test = function(connection) { return connection.authcid !== null; }; Strophe.SASLSHA1.prototype.onChallenge = function(connection, challenge, test_cnonce) { var cnonce = test_cnonce || MD5.hexdigest(Math.random() * 1234567890); var auth_str = "n=" + connection.authcid; auth_str += ",r="; auth_str += cnonce; connection._sasl_data.cnonce = cnonce; connection._sasl_data["client-first-message-bare"] = auth_str; auth_str = "n,," + auth_str; this.onChallenge = function (connection, challenge) { var nonce, salt, iter, Hi, U, U_old, i, k; var clientKey, serverKey, clientSignature; var responseText = "c=biws,"; var authMessage = connection._sasl_data["client-first-message-bare"] + "," + challenge + ","; var cnonce = connection._sasl_data.cnonce; var attribMatch = /([a-z]+)=([^,]+)(,|$)/; while (challenge.match(attribMatch)) { var matches = challenge.match(attribMatch); challenge = challenge.replace(matches[0], ""); switch (matches[1]) { case "r": nonce = matches[2]; break; case "s": salt = matches[2]; break; case "i": iter = matches[2]; break; } } if (nonce.substr(0, cnonce.length) !== cnonce) { connection._sasl_data = {}; return connection._sasl_failure_cb(); } responseText += "r=" + nonce; authMessage += responseText; salt = Base64.decode(salt); salt += "\x00\x00\x00\x01"; Hi = U_old = core_hmac_sha1(connection.pass, salt); for (i = 1; i < iter; i++) { U = core_hmac_sha1(connection.pass, binb2str(U_old)); for (k = 0; k < 5; k++) { Hi[k] ^= U[k]; } U_old = U; } Hi = binb2str(Hi); clientKey = core_hmac_sha1(Hi, "Client Key"); serverKey = str_hmac_sha1(Hi, "Server Key"); clientSignature = core_hmac_sha1(str_sha1(binb2str(clientKey)), authMessage); connection._sasl_data["server-signature"] = b64_hmac_sha1(serverKey, authMessage); for (k = 0; k < 5; k++) { clientKey[k] ^= clientSignature[k]; } responseText += ",p=" + Base64.encode(binb2str(clientKey)); return responseText; }.bind(this); return auth_str; }; Strophe.Connection.prototype.mechanisms[Strophe.SASLSHA1.prototype.name] = Strophe.SASLSHA1; /** PrivateConstructor: SASLMD5 * SASL DIGEST MD5 authentication. */ Strophe.SASLMD5 = function() {}; Strophe.SASLMD5.prototype = new Strophe.SASLMechanism("DIGEST-MD5", false, 30); Strophe.SASLMD5.test = function(connection) { return connection.authcid !== null; }; /** PrivateFunction: _quote * _Private_ utility function to backslash escape and quote strings. * * Parameters: * (String) str - The string to be quoted. * * Returns: * quoted string */ Strophe.SASLMD5.prototype._quote = function (str) { return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"'; //" end string workaround for emacs }; Strophe.SASLMD5.prototype.onChallenge = function(connection, challenge, test_cnonce) { var attribMatch = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/; var cnonce = test_cnonce || MD5.hexdigest("" + (Math.random() * 1234567890)); var realm = ""; var host = null; var nonce = ""; var qop = ""; var matches; while (challenge.match(attribMatch)) { matches = challenge.match(attribMatch); challenge = challenge.replace(matches[0], ""); matches[2] = matches[2].replace(/^"(.+)"$/, "$1"); switch (matches[1]) { case "realm": realm = matches[2]; break; case "nonce": nonce = matches[2]; break; case "qop": qop = matches[2]; break; case "host": host = matches[2]; break; } } var digest_uri = connection.servtype + "/" + connection.domain; if (host !== null) { digest_uri = digest_uri + "/" + host; } var A1 = MD5.hash(connection.authcid + ":" + realm + ":" + this._connection.pass) + ":" + nonce + ":" + cnonce; var A2 = 'AUTHENTICATE:' + digest_uri; var responseText = ""; responseText += 'charset=utf-8,'; responseText += 'username=' + this._quote(connection.authcid) + ','; responseText += 'realm=' + this._quote(realm) + ','; responseText += 'nonce=' + this._quote(nonce) + ','; responseText += 'nc=00000001,'; responseText += 'cnonce=' + this._quote(cnonce) + ','; responseText += 'digest-uri=' + this._quote(digest_uri) + ','; responseText += 'response=' + MD5.hexdigest(MD5.hexdigest(A1) + ":" + nonce + ":00000001:" + cnonce + ":auth:" + MD5.hexdigest(A2)) + ","; responseText += 'qop=auth'; this.onChallenge = function () { return ""; }.bind(this); return responseText; }; Strophe.Connection.prototype.mechanisms[Strophe.SASLMD5.prototype.name] = Strophe.SASLMD5; })(function () { window.Strophe = arguments[0]; window.$build = arguments[1]; window.$msg = arguments[2]; window.$iq = arguments[3]; window.$pres = arguments[4]; }); /* This program is distributed under the terms of the MIT license. Please see the LICENSE file for details. Copyright 2006-2008, OGG, LLC */ /* jshint undef: true, unused: true:, noarg: true, latedef: true */ /*global window, setTimeout, clearTimeout, XMLHttpRequest, ActiveXObject, Strophe, $build */ /** PrivateClass: Strophe.Request * _Private_ helper class that provides a cross implementation abstraction * for a BOSH related XMLHttpRequest. * * The Strophe.Request class is used internally to encapsulate BOSH request * information. It is not meant to be used from user's code. */ /** PrivateConstructor: Strophe.Request * Create and initialize a new Strophe.Request object. * * Parameters: * (XMLElement) elem - The XML data to be sent in the request. * (Function) func - The function that will be called when the * XMLHttpRequest readyState changes. * (Integer) rid - The BOSH rid attribute associated with this request. * (Integer) sends - The number of times this same request has been * sent. */ Strophe.Request = function (elem, func, rid, sends) { this.id = ++Strophe._requestId; this.xmlData = elem; this.data = Strophe.serialize(elem); // save original function in case we need to make a new request // from this one. this.origFunc = func; this.func = func; this.rid = rid; this.date = NaN; this.sends = sends || 0; this.abort = false; this.dead = null; this.age = function () { if (!this.date) { return 0; } var now = new Date(); return (now - this.date) / 1000; }; this.timeDead = function () { if (!this.dead) { return 0; } var now = new Date(); return (now - this.dead) / 1000; }; this.xhr = this._newXHR(); }; Strophe.Request.prototype = { /** PrivateFunction: getResponse * Get a response from the underlying XMLHttpRequest. * * This function attempts to get a response from the request and checks * for errors. * * Throws: * "parsererror" - A parser error occured. * * Returns: * The DOM element tree of the response. */ getResponse: function () { var node = null; if (this.xhr.responseXML && this.xhr.responseXML.documentElement) { node = this.xhr.responseXML.documentElement; if (node.tagName == "parsererror") { Strophe.error("invalid response received"); Strophe.error("responseText: " + this.xhr.responseText); Strophe.error("responseXML: " + Strophe.serialize(this.xhr.responseXML)); throw "parsererror"; } } else if (this.xhr.responseText) { Strophe.error("invalid response received"); Strophe.error("responseText: " + this.xhr.responseText); Strophe.error("responseXML: " + Strophe.serialize(this.xhr.responseXML)); } return node; }, /** PrivateFunction: _newXHR * _Private_ helper function to create XMLHttpRequests. * * This function creates XMLHttpRequests across all implementations. * * Returns: * A new XMLHttpRequest. */ _newXHR: function () { var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); if (xhr.overrideMimeType) { xhr.overrideMimeType("text/xml"); } } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // use Function.bind() to prepend ourselves as an argument xhr.onreadystatechange = this.func.bind(null, this); return xhr; } }; /** Class: Strophe.Bosh * _Private_ helper class that handles BOSH Connections * * The Strophe.Bosh class is used internally by Strophe.Connection * to encapsulate BOSH sessions. It is not meant to be used from user's code. */ /** File: bosh.js * A JavaScript library to enable BOSH in Strophejs. * * this library uses Bidirectional-streams Over Synchronous HTTP (BOSH) * to emulate a persistent, stateful, two-way connection to an XMPP server. * More information on BOSH can be found in XEP 124. */ /** PrivateConstructor: Strophe.Bosh * Create and initialize a Strophe.Bosh object. * * Parameters: * (Strophe.Connection) connection - The Strophe.Connection that will use BOSH. * * Returns: * A new Strophe.Bosh object. */ Strophe.Bosh = function(connection) { this._conn = connection; /* request id for body tags */ this.rid = Math.floor(Math.random() * 4294967295); /* The current session ID. */ this.sid = null; // default BOSH values this.hold = 1; this.wait = 60; this.window = 5; this._requests = []; }; Strophe.Bosh.prototype = { /** Variable: strip * * BOSH-Connections will have all stanzas wrapped in a <body> tag when * passed to <Strophe.Connection.xmlInput> or <Strophe.Connection.xmlOutput>. * To strip this tag, User code can set <Strophe.Bosh.strip> to "body": * * > Strophe.Bosh.prototype.strip = "body"; * * This will enable stripping of the body tag in both * <Strophe.Connection.xmlInput> and <Strophe.Connection.xmlOutput>. */ strip: null, /** PrivateFunction: _buildBody * _Private_ helper function to generate the <body/> wrapper for BOSH. * * Returns: * A Strophe.Builder with a <body/> element. */ _buildBody: function () { var bodyWrap = $build('body', { rid: this.rid++, xmlns: Strophe.NS.HTTPBIND }); if (this.sid !== null) { bodyWrap.attrs({sid: this.sid}); } return bodyWrap; }, /** PrivateFunction: _reset * Reset the connection. * * This function is called by the reset function of the Strophe Connection */ _reset: function () { this.rid = Math.floor(Math.random() * 4294967295); this.sid = null; }, /** PrivateFunction: _connect * _Private_ function that initializes the BOSH connection. * * Creates and sends the Request that initializes the BOSH connection. */ _connect: function (wait, hold, route) { this.wait = wait || this.wait; this.hold = hold || this.hold; // build the body tag var body = this._buildBody().attrs({ to: this._conn.domain, "xml:lang": "en", wait: this.wait, hold: this.hold, content: "text/xml; charset=utf-8", ver: "1.6", "xmpp:version": "1.0", "xmlns:xmpp": Strophe.NS.BOSH }); if(route){ body.attrs({ route: route }); } var _connect_cb = this._conn._connect_cb; this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, _connect_cb.bind(this._conn)), body.tree().getAttribute("rid"))); this._throttledRequestHandler(); }, /** PrivateFunction: _attach * Attach to an already created and authenticated BOSH session. * * This function is provided to allow Strophe to attach to BOSH * sessions which have been created externally, perhaps by a Web * application. This is often used to support auto-login type features * without putting user credentials into the page. * * Parameters: * (String) jid - The full JID that is bound by the session. * (String) sid - The SID of the BOSH session. * (String) rid - The current RID of the BOSH session. This RID * will be used by the next request. * (Function) callback The connect callback function. * (Integer) wait - The optional HTTPBIND wait value. This is the * time the server will wait before returning an empty result for * a request. The default setting of 60 seconds is recommended. * Other settings will require tweaks to the Strophe.TIMEOUT value. * (Integer) hold - The optional HTTPBIND hold value. This is the * number of connections the server will hold at one time. This * should almost always be set to 1 (the default). * (Integer) wind - The optional HTTBIND window value. This is the * allowed range of request ids that are valid. The default is 5. */ _attach: function (jid, sid, rid, callback, wait, hold, wind) { this._conn.jid = jid; this.sid = sid; this.rid = rid; this._conn.connect_callback = callback; this._conn.domain = Strophe.getDomainFromJid(this._conn.jid); this._conn.authenticated = true; this._conn.connected = true; this.wait = wait || this.wait; this.hold = hold || this.hold; this.window = wind || this.window; this._conn._changeConnectStatus(Strophe.Status.ATTACHED, null); }, /** PrivateFunction: _connect_cb * _Private_ handler for initial connection request. * * This handler is used to process the Bosh-part of the initial request. * Parameters: * (Strophe.Request) bodyWrap - The received stanza. */ _connect_cb: function (bodyWrap) { var typ = bodyWrap.getAttribute("type"); var cond, conflict; if (typ !== null && typ == "terminate") { // an error occurred Strophe.error("BOSH-Connection failed: " + cond); cond = bodyWrap.getAttribute("condition"); conflict = bodyWrap.getElementsByTagName("conflict"); if (cond !== null) { if (cond == "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, cond); } else { this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown"); } this._conn._doDisconnect(); return Strophe.Status.CONNFAIL; } // check to make sure we don't overwrite these if _connect_cb is // called multiple times in the case of missing stream:features if (!this.sid) { this.sid = bodyWrap.getAttribute("sid"); } var wind = bodyWrap.getAttribute('requests'); if (wind) { this.window = parseInt(wind, 10); } var hold = bodyWrap.getAttribute('hold'); if (hold) { this.hold = parseInt(hold, 10); } var wait = bodyWrap.getAttribute('wait'); if (wait) { this.wait = parseInt(wait, 10); } }, /** PrivateFunction: _disconnect * _Private_ part of Connection.disconnect for Bosh * * Parameters: * (Request) pres - This stanza will be sent before disconnecting. */ _disconnect: function (pres) { this._sendTerminate(pres); }, /** PrivateFunction: _doDisconnect * _Private_ function to disconnect. * * Resets the SID and RID. */ _doDisconnect: function () { this.sid = null; this.rid = Math.floor(Math.random() * 4294967295); }, /** PrivateFunction: _emptyQueue * _Private_ function to check if the Request queue is empty. * * Returns: * True, if there are no Requests queued, False otherwise. */ _emptyQueue: function () { return this._requests.length === 0; }, /** PrivateFunction: _hitError * _Private_ function to handle the error count. * * Requests are resent automatically until their error count reaches * 5. Each time an error is encountered, this function is called to * increment the count and disconnect if the count is too high. * * Parameters: * (Integer) reqStatus - The request status. */ _hitError: function (reqStatus) { this.errors++; Strophe.warn("request errored, status: " + reqStatus + ", number of errors: " + this.errors); if (this.errors > 4) { this._onDisconnectTimeout(); } }, /** PrivateFunction: _no_auth_received * * Called on stream start/restart when no stream:features * has been received and sends a blank poll request. */ _no_auth_received: function (_callback) { if (_callback) { _callback = _callback.bind(this._conn); } else { _callback = this._conn._connect_cb.bind(this._conn); } var body = this._buildBody(); this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, _callback.bind(this._conn)), body.tree().getAttribute("rid"))); this._throttledRequestHandler(); }, /** PrivateFunction: _onDisconnectTimeout * _Private_ timeout handler for handling non-graceful disconnection. * * Cancels all remaining Requests and clears the queue. */ _onDisconnectTimeout: function () { var req; while (this._requests.length > 0) { req = this._requests.pop(); req.abort = true; req.xhr.abort(); // jslint complains, but this is fine. setting to empty func // is necessary for IE6 req.xhr.onreadystatechange = function () {}; // jshint ignore:line } }, /** PrivateFunction: _onIdle * _Private_ handler called by Strophe.Connection._onIdle * * Sends all queued Requests or polls with empty Request if there are none. */ _onIdle: function () { var data = this._conn._data; // if no requests are in progress, poll if (this._conn.authenticated && this._requests.length === 0 && data.length === 0 && !this._conn.disconnecting) { Strophe.info("no requests during idle cycle, sending " + "blank request"); data.push(null); } if (this._requests.length < 2 && data.length > 0 && !this._conn.paused) { var body = this._buildBody(); for (var i = 0; i < data.length; i++) { if (data[i] !== null) { if (data[i] === "restart") { body.attrs({ to: this._conn.domain, "xml:lang": "en", "xmpp:restart": "true", "xmlns:xmpp": Strophe.NS.BOSH }); } else { body.cnode(data[i]).up(); } } } delete this._conn._data; this._conn._data = []; this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid"))); this._processRequest(this._requests.length - 1); } if (this._requests.length > 0) { var time_elapsed = this._requests[0].age(); if (this._requests[0].dead !== null) { if (this._requests[0].timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) { this._throttledRequestHandler(); } } if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) { Strophe.warn("Request " + this._requests[0].id + " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) + " seconds since last activity"); this._throttledRequestHandler(); } } }, /** PrivateFunction: _onRequestStateChange * _Private_ handler for Strophe.Request state changes. * * This function is called when the XMLHttpRequest readyState changes. * It contains a lot of error handling logic for the many ways that * requests can fail, and calls the request callback when requests * succeed. * * Parameters: * (Function) func - The handler for the request. * (Strophe.Request) req - The request that is changing readyState. */ _onRequestStateChange: function (func, req) { Strophe.debug("request id " + req.id + "." + req.sends + " state changed to " + req.xhr.readyState); if (req.abort) { req.abort = false; return; } // request complete var reqStatus; if (req.xhr.readyState == 4) { reqStatus = 0; try { reqStatus = req.xhr.status; } catch (e) { // ignore errors from undefined status attribute. works // around a browser bug } if (typeof(reqStatus) == "undefined") { reqStatus = 0; } if (this.disconnecting) { if (reqStatus >= 400) { this._hitError(reqStatus); return; } } var reqIs0 = (this._requests[0] == req); var reqIs1 = (this._requests[1] == req); if ((reqStatus > 0 && reqStatus < 500) || req.sends > 5) { // remove from internal queue this._removeRequest(req); Strophe.debug("request id " + req.id + " should now be removed"); } // request succeeded if (reqStatus == 200) { // if request 1 finished, or request 0 finished and request // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to // restart the other - both will be in the first spot, as the // completed request has been removed from the queue already if (reqIs1 || (reqIs0 && this._requests.length > 0 && this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait))) { this._restartRequest(0); } // call handler Strophe.debug("request id " + req.id + "." + req.sends + " got 200"); func(req); this.errors = 0; } else { Strophe.error("request id " + req.id + "." + req.sends + " error " + reqStatus + " happened"); if (reqStatus === 0 || (reqStatus >= 400 && reqStatus < 600) || reqStatus >= 12000) { this._hitError(reqStatus); if (reqStatus >= 400 && reqStatus < 500) { this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING, null); this._conn._doDisconnect(); } } } if (!((reqStatus > 0 && reqStatus < 500) || req.sends > 5)) { this._throttledRequestHandler(); } } }, /** PrivateFunction: _processRequest * _Private_ function to process a request in the queue. * * This function takes requests off the queue and sends them and * restarts dead requests. * * Parameters: * (Integer) i - The index of the request in the queue. */ _processRequest: function (i) { var self = this; var req = this._requests[i]; var reqStatus = -1; try { if (req.xhr.readyState == 4) { reqStatus = req.xhr.status; } } catch (e) { Strophe.error("caught an error in _requests[" + i + "], reqStatus: " + reqStatus); } if (typeof(reqStatus) == "undefined") { reqStatus = -1; } // make sure we limit the number of retries if (req.sends > this.maxRetries) { this._onDisconnectTimeout(); return; } var time_elapsed = req.age(); var primaryTimeout = (!isNaN(time_elapsed) && time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)); var secondaryTimeout = (req.dead !== null && req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)); var requestCompletedWithServerError = (req.xhr.readyState == 4 && (reqStatus < 1 || reqStatus >= 500)); if (primaryTimeout || secondaryTimeout || requestCompletedWithServerError) { if (secondaryTimeout) { Strophe.error("Request " + this._requests[i].id + " timed out (secondary), restarting"); } req.abort = true; req.xhr.abort(); // setting to null fails on IE6, so set to empty function req.xhr.onreadystatechange = function () {}; this._requests[i] = new Strophe.Request(req.xmlData, req.origFunc, req.rid, req.sends); req = this._requests[i]; } if (req.xhr.readyState === 0) { Strophe.debug("request id " + req.id + "." + req.sends + " posting"); try { req.xhr.open("POST", this._conn.service, this._conn.options.sync ? false : true); } catch (e2) { Strophe.error("XHR open failed."); if (!this._conn.connected) { this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "bad-service"); } this._conn.disconnect(); return; } // Fires the XHR request -- may be invoked immediately // or on a gradually expanding retry window for reconnects var sendFunc = function () { req.date = new Date(); if (self._conn.options.customHeaders){ var headers = self._conn.options.customHeaders; for (var header in headers) { if (headers.hasOwnProperty(header)) { req.xhr.setRequestHeader(header, headers[header]); } } } req.xhr.send(req.data); }; // Implement progressive backoff for reconnects -- // First retry (send == 1) should also be instantaneous if (req.sends > 1) { // Using a cube of the retry number creates a nicely // expanding retry window var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait), Math.pow(req.sends, 3)) * 1000; setTimeout(sendFunc, backoff); } else { sendFunc(); } req.sends++; if (this._conn.xmlOutput !== Strophe.Connection.prototype.xmlOutput) { if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) { this._conn.xmlOutput(req.xmlData.childNodes[0]); } else { this._conn.xmlOutput(req.xmlData); } } if (this._conn.rawOutput !== Strophe.Connection.prototype.rawOutput) { this._conn.rawOutput(req.data); } } else { Strophe.debug("_processRequest: " + (i === 0 ? "first" : "second") + " request has readyState of " + req.xhr.readyState); } }, /** PrivateFunction: _removeRequest * _Private_ function to remove a request from the queue. * * Parameters: * (Strophe.Request) req - The request to remove. */ _removeRequest: function (req) { Strophe.debug("removing request"); var i; for (i = this._requests.length - 1; i >= 0; i--) { if (req == this._requests[i]) { this._requests.splice(i, 1); } } // IE6 fails on setting to null, so set to empty function req.xhr.onreadystatechange = function () {}; this._throttledRequestHandler(); }, /** PrivateFunction: _restartRequest * _Private_ function to restart a request that is presumed dead. * * Parameters: * (Integer) i - The index of the request in the queue. */ _restartRequest: function (i) { var req = this._requests[i]; if (req.dead === null) { req.dead = new Date(); } this._processRequest(i); }, /** PrivateFunction: _reqToData * _Private_ function to get a stanza out of a request. * * Tries to extract a stanza out of a Request Object. * When this fails the current connection will be disconnected. * * Parameters: * (Object) req - The Request. * * Returns: * The stanza that was passed. */ _reqToData: function (req) { try { return req.getResponse(); } catch (e) { if (e != "parsererror") { throw e; } this._conn.disconnect("strophe-parsererror"); } }, /** PrivateFunction: _sendTerminate * _Private_ function to send initial disconnect sequence. * * This is the first step in a graceful disconnect. It sends * the BOSH server a terminate body and includes an unavailable * presence if authentication has completed. */ _sendTerminate: function (pres) { Strophe.info("_sendTerminate was called"); var body = this._buildBody().attrs({type: "terminate"}); if (pres) { body.cnode(pres.tree()); } var req = new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid")); this._requests.push(req); this._throttledRequestHandler(); }, /** PrivateFunction: _send * _Private_ part of the Connection.send function for BOSH * * Just triggers the RequestHandler to send the messages that are in the queue */ _send: function () { clearTimeout(this._conn._idleTimeout); this._throttledRequestHandler(); this._conn._idleTimeout = setTimeout(this._conn._onIdle.bind(this._conn), 100); }, /** PrivateFunction: _sendRestart * * Send an xmpp:restart stanza. */ _sendRestart: function () { this._throttledRequestHandler(); clearTimeout(this._conn._idleTimeout); }, /** PrivateFunction: _throttledRequestHandler * _Private_ function to throttle requests to the connection window. * * This function makes sure we don't send requests so fast that the * request ids overflow the connection window in the case that one * request died. */ _throttledRequestHandler: function () { if (!this._requests) { Strophe.debug("_throttledRequestHandler called with " + "undefined requests"); } else { Strophe.debug("_throttledRequestHandler called with " + this._requests.length + " requests"); } if (!this._requests || this._requests.length === 0) { return; } if (this._requests.length > 0) { this._processRequest(0); } if (this._requests.length > 1 && Math.abs(this._requests[0].rid - this._requests[1].rid) < this.window) { this._processRequest(1); } } }; /* This program is distributed under the terms of the MIT license. Please see the LICENSE file for details. Copyright 2006-2008, OGG, LLC */ /* jshint undef: true, unused: true:, noarg: true, latedef: true */ /*global document, window, clearTimeout, WebSocket, DOMParser, Strophe, $build */ /** Class: Strophe.WebSocket * _Private_ helper class that handles WebSocket Connections * * The Strophe.WebSocket class is used internally by Strophe.Connection * to encapsulate WebSocket sessions. It is not meant to be used from user's code. */ /** File: websocket.js * A JavaScript library to enable XMPP over Websocket in Strophejs. * * This file implements XMPP over WebSockets for Strophejs. * If a Connection is established with a Websocket url (ws://...) * Strophe will use WebSockets. * For more information on XMPP-over WebSocket see this RFC draft: * http://tools.ietf.org/html/draft-ietf-xmpp-websocket-00 * * WebSocket support implemented by Andreas Guth (andreas.guth@rwth-aachen.de) */ /** PrivateConstructor: Strophe.Websocket * Create and initialize a Strophe.WebSocket object. * Currently only sets the connection Object. * * Parameters: * (Strophe.Connection) connection - The Strophe.Connection that will use WebSockets. * * Returns: * A new Strophe.WebSocket object. */ Strophe.Websocket = function(connection) { this._conn = connection; this.strip = "stream:stream"; var service = connection.service; if (service.indexOf("ws:") !== 0 && service.indexOf("wss:") !== 0) { // If the service is not an absolute URL, assume it is a path and put the absolute // URL together from options, current URL and the path. var new_service = ""; if (connection.options.protocol === "ws" && window.location.protocol !== "https:") { new_service += "ws"; } else { new_service += "wss"; } new_service += "://" + window.location.host; if (service.indexOf("/") !== 0) { new_service += window.location.pathname + service; } else { new_service += service; } connection.service = new_service; } }; Strophe.Websocket.prototype = { /** PrivateFunction: _buildStream * _Private_ helper function to generate the <stream> start tag for WebSockets * * Returns: * A Strophe.Builder with a <stream> element. */ _buildStream: function () { return $build("stream:stream", { "to": this._conn.domain, "xmlns": Strophe.NS.CLIENT, "xmlns:stream": Strophe.NS.STREAM, "version": '1.0' }); }, /** PrivateFunction: _check_streamerror * _Private_ checks a message for stream:error * * Parameters: * (Strophe.Request) bodyWrap - The received stanza. * connectstatus - The ConnectStatus that will be set on error. * Returns: * true if there was a streamerror, false otherwise. */ _check_streamerror: function (bodyWrap, connectstatus) { var errors = bodyWrap.getElementsByTagName("stream:error"); if (errors.length === 0) { return false; } var error = errors[0]; var condition = ""; var text = ""; var ns = "urn:ietf:params:xml:ns:xmpp-streams"; for (var i = 0; i < error.childNodes.length; i++) { var e = error.childNodes[i]; if (e.getAttribute("xmlns") !== ns) { break; } if (e.nodeName === "text") { text = e.textContent; } else { condition = e.nodeName; } } var errorString = "WebSocket stream error: "; if (condition) { errorString += condition; } else { errorString += "unknown"; } if (text) { errorString += " - " + condition; } Strophe.error(errorString); // close the connection on stream_error this._conn._changeConnectStatus(connectstatus, condition); this._conn._doDisconnect(); return true; }, /** PrivateFunction: _reset * Reset the connection. * * This function is called by the reset function of the Strophe Connection. * Is not needed by WebSockets. */ _reset: function () { return; }, /** PrivateFunction: _connect * _Private_ function called by Strophe.Connection.connect * * Creates a WebSocket for a connection and assigns Callbacks to it. * Does nothing if there already is a WebSocket. */ _connect: function () { // Ensure that there is no open WebSocket from a previous Connection. this._closeSocket(); // Create the new WobSocket this.socket = new WebSocket(this._conn.service, "xmpp"); this.socket.onopen = this._onOpen.bind(this); this.socket.onerror = this._onError.bind(this); this.socket.onclose = this._onClose.bind(this); this.socket.onmessage = this._connect_cb_wrapper.bind(this); }, /** PrivateFunction: _connect_cb * _Private_ function called by Strophe.Connection._connect_cb * * checks for stream:error * * Parameters: * (Strophe.Request) bodyWrap - The received stanza. */ _connect_cb: function(bodyWrap) { var error = this._check_streamerror(bodyWrap, Strophe.Status.CONNFAIL); if (error) { return Strophe.Status.CONNFAIL; } }, /** PrivateFunction: _handleStreamStart * _Private_ function that checks the opening stream:stream tag for errors. * * Disconnects if there is an error and returns false, true otherwise. * * Parameters: * (Node) message - Stanza containing the stream:stream. */ _handleStreamStart: function(message) { var error = false; // Check for errors in the stream:stream tag var ns = message.getAttribute("xmlns"); if (typeof ns !== "string") { error = "Missing xmlns in stream:stream"; } else if (ns !== Strophe.NS.CLIENT) { error = "Wrong xmlns in stream:stream: " + ns; } var ns_stream = message.namespaceURI; if (typeof ns_stream !== "string") { error = "Missing xmlns:stream in stream:stream"; } else if (ns_stream !== Strophe.NS.STREAM) { error = "Wrong xmlns:stream in stream:stream: " + ns_stream; } var ver = message.getAttribute("version"); if (typeof ver !== "string") { error = "Missing version in stream:stream"; } else if (ver !== "1.0") { error = "Wrong version in stream:stream: " + ver; } if (error) { this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, error); this._conn._doDisconnect(); return false; } return true; }, /** PrivateFunction: _connect_cb_wrapper * _Private_ function that handles the first connection messages. * * On receiving an opening stream tag this callback replaces itself with the real * message handler. On receiving a stream error the connection is terminated. */ _connect_cb_wrapper: function(message) { if (message.data.indexOf("<stream:stream ") === 0 || message.data.indexOf("<?xml") === 0) { // Strip the XML Declaration, if there is one var data = message.data.replace(/^(<\?.*?\?>\s*)*/, ""); if (data === '') return; //Make the initial stream:stream selfclosing to parse it without a SAX parser. data = message.data.replace(/<stream:stream (.*[^\/])>/, "<stream:stream $1/>"); var streamStart = new DOMParser().parseFromString(data, "text/xml").documentElement; this._conn.xmlInput(streamStart); this._conn.rawInput(message.data); //_handleStreamSteart will check for XML errors and disconnect on error if (this._handleStreamStart(streamStart)) { //_connect_cb will check for stream:error and disconnect on error this._connect_cb(streamStart); // ensure received stream:stream is NOT selfclosing and save it for following messages this.streamStart = message.data.replace(/^<stream:(.*)\/>$/, "<stream:$1>"); } } else if (message.data === "</stream:stream>") { this._conn.rawInput(message.data); this._conn.xmlInput(document.createElement("stream:stream")); this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Received closing stream"); this._conn._doDisconnect(); return; } else { var string = this._streamWrap(message.data); var elem = new DOMParser().parseFromString(string, "text/xml").documentElement; this.socket.onmessage = this._onMessage.bind(this); this._conn._connect_cb(elem, null, message.data); } }, /** PrivateFunction: _disconnect * _Private_ function called by Strophe.Connection.disconnect * * Disconnects and sends a last stanza if one is given * * Parameters: * (Request) pres - This stanza will be sent before disconnecting. */ _disconnect: function (pres) { if (this.socket.readyState !== WebSocket.CLOSED) { if (pres) { this._conn.send(pres); } var close = '</stream:stream>'; this._conn.xmlOutput(document.createElement("stream:stream")); this._conn.rawOutput(close); try { this.socket.send(close); } catch (e) { Strophe.info("Couldn't send closing stream tag."); } } this._conn._doDisconnect(); }, /** PrivateFunction: _doDisconnect * _Private_ function to disconnect. * * Just closes the Socket for WebSockets */ _doDisconnect: function () { Strophe.info("WebSockets _doDisconnect was called"); this._closeSocket(); }, /** PrivateFunction _streamWrap * _Private_ helper function to wrap a stanza in a <stream> tag. * This is used so Strophe can process stanzas from WebSockets like BOSH */ _streamWrap: function (stanza) { return this.streamStart + stanza + '</stream:stream>'; }, /** PrivateFunction: _closeSocket * _Private_ function to close the WebSocket. * * Closes the socket if it is still open and deletes it */ _closeSocket: function () { if (this.socket) { try { this.socket.close(); } catch (e) {} } this.socket = null; }, /** PrivateFunction: _emptyQueue * _Private_ function to check if the message queue is empty. * * Returns: * True, because WebSocket messages are send immediately after queueing. */ _emptyQueue: function () { return true; }, /** PrivateFunction: _onClose * _Private_ function to handle websockets closing. * * Nothing to do here for WebSockets */ _onClose: function() { if(this._conn.connected && !this._conn.disconnecting) { Strophe.error("Websocket closed unexcectedly"); this._conn._doDisconnect(); } else { Strophe.info("Websocket closed"); } }, /** PrivateFunction: _no_auth_received * * Called on stream start/restart when no stream:features * has been received. */ _no_auth_received: function (_callback) { Strophe.error("Server did not send any auth methods"); this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Server did not send any auth methods"); if (_callback) { _callback = _callback.bind(this._conn); _callback(); } this._conn._doDisconnect(); }, /** PrivateFunction: _onDisconnectTimeout * _Private_ timeout handler for handling non-graceful disconnection. * * This does nothing for WebSockets */ _onDisconnectTimeout: function () {}, /** PrivateFunction: _onError * _Private_ function to handle websockets errors. * * Parameters: * (Object) error - The websocket error. */ _onError: function(error) { Strophe.error("Websocket error " + error); this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established was disconnected."); this._disconnect(); }, /** PrivateFunction: _onIdle * _Private_ function called by Strophe.Connection._onIdle * * sends all queued stanzas */ _onIdle: function () { var data = this._conn._data; if (data.length > 0 && !this._conn.paused) { for (var i = 0; i < data.length; i++) { if (data[i] !== null) { var stanza, rawStanza; if (data[i] === "restart") { stanza = this._buildStream(); rawStanza = this._removeClosingTag(stanza); stanza = stanza.tree(); } else { stanza = data[i]; rawStanza = Strophe.serialize(stanza); } this._conn.xmlOutput(stanza); this._conn.rawOutput(rawStanza); this.socket.send(rawStanza); } } this._conn._data = []; } }, /** PrivateFunction: _onMessage * _Private_ function to handle websockets messages. * * This function parses each of the messages as if they are full documents. [TODO : We may actually want to use a SAX Push parser]. * * Since all XMPP traffic starts with "<stream:stream version='1.0' xml:lang='en' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='3697395463' from='SERVER'>" * The first stanza will always fail to be parsed... * Addtionnaly, the seconds stanza will always be a <stream:features> with the stream NS defined in the previous stanza... so we need to 'force' the inclusion of the NS in this stanza! * * Parameters: * (string) message - The websocket message. */ _onMessage: function(message) { var elem, data; // check for closing stream if (message.data === "</stream:stream>") { var close = "</stream:stream>"; this._conn.rawInput(close); this._conn.xmlInput(document.createElement("stream:stream")); if (!this._conn.disconnecting) { this._conn._doDisconnect(); } return; } else if (message.data.search("<stream:stream ") === 0) { //Make the initial stream:stream selfclosing to parse it without a SAX parser. data = message.data.replace(/<stream:stream (.*[^\/])>/, "<stream:stream $1/>"); elem = new DOMParser().parseFromString(data, "text/xml").documentElement; if (!this._handleStreamStart(elem)) { return; } } else { data = this._streamWrap(message.data); elem = new DOMParser().parseFromString(data, "text/xml").documentElement; } if (this._check_streamerror(elem, Strophe.Status.ERROR)) { return; } //handle unavailable presence stanza before disconnecting if (this._conn.disconnecting && elem.firstChild.nodeName === "presence" && elem.firstChild.getAttribute("type") === "unavailable") { this._conn.xmlInput(elem); this._conn.rawInput(Strophe.serialize(elem)); // if we are already disconnecting we will ignore the unavailable stanza and // wait for the </stream:stream> tag before we close the connection return; } this._conn._dataRecv(elem, message.data); }, /** PrivateFunction: _onOpen * _Private_ function to handle websockets connection setup. * * The opening stream tag is sent here. */ _onOpen: function() { Strophe.info("Websocket open"); var start = this._buildStream(); this._conn.xmlOutput(start.tree()); var startString = this._removeClosingTag(start); this._conn.rawOutput(startString); this.socket.send(startString); }, /** PrivateFunction: _removeClosingTag * _Private_ function to Make the first <stream:stream> non-selfclosing * * Parameters: * (Object) elem - The <stream:stream> tag. * * Returns: * The stream:stream tag as String */ _removeClosingTag: function(elem) { var string = Strophe.serialize(elem); string = string.replace(/<(stream:stream .*[^\/])\/>$/, "<$1>"); return string; }, /** PrivateFunction: _reqToData * _Private_ function to get a stanza out of a request. * * WebSockets don't use requests, so the passed argument is just returned. * * Parameters: * (Object) stanza - The stanza. * * Returns: * The stanza that was passed. */ _reqToData: function (stanza) { return stanza; }, /** PrivateFunction: _send * _Private_ part of the Connection.send function for WebSocket * * Just flushes the messages that are in the queue */ _send: function () { this._conn.flush(); }, /** PrivateFunction: _sendRestart * * Send an xmpp:restart stanza. */ _sendRestart: function () { clearTimeout(this._conn._idleTimeout); this._conn._onIdle.bind(this._conn)(); } }; return Strophe; });
rwth-acis/ROLE-SDK
services/roleUUPrototype/src/main/webapp/script/xmpp/strophe.js
JavaScript
apache-2.0
170,022
var structOvsFlowPut = [ [ "actions", "structOvsFlowPut.html#ad97ea8cbeafd204e136aa82c6ec2b298", null ], [ "actionsLen", "structOvsFlowPut.html#a7d4dea38a2ae23c571f256e6103ca58e", null ], [ "dpNo", "structOvsFlowPut.html#a7f0a986091afae06ec70dcce58e23157", null ], [ "flags", "structOvsFlowPut.html#a1f294328f2bd8ecb3cb90cabbb901d50", null ], [ "key", "structOvsFlowPut.html#aae3c9ae1e37396e7f7a2a0417b41becd", null ] ];
vladn-ma/vladn-ovs-doc
doxygen/ovs_all/html/structOvsFlowPut.js
JavaScript
apache-2.0
440
var React = require('react/addons'), Router = require('react-router'), serialPort = require('serialport'); var Preferences = React.createClass({ mixins: [Router.Navigation], getInitialState: function () { return { selectedPort: '' }; }, handleGoBackClick: function () { this.goBack(); }, render: function () { return ( <div className="preferences"> <div className="preferences-content"> <a onClick={this.handleGoBackClick}>Go Back</a> <div className="title">App Settings</div> <div className="option"> <div className="option-name"> Serial Port </div> <div className="option-value"> <SerialPortSelector/> </div> </div> </div> </div> ); } }); var PortsList = React.createClass({ getInitialState: function(){ return {data: this.props.selectedport}; }, render: function(){ var selectedport = this.data; var options = this.props.data.map(function (port) { return ( <option key={port.comName} value={port.comName}>{port.comName} </option> ); }); return (<select value={selectedport} className="portList" onChange={this._onSelect}> {options} </select>); }, _onSelect: function(event){ // SteveApi.setPort(event.target.value); this.setState({data: event.target.value}); } }); var SerialPortSelector = React.createClass({ getInitialState: function() { return {data: []}; }, componentDidMount: function() { var portlist = []; serialPort.list(function (err, ports) { ports.forEach(function(port) { portlist.push(port); }); this.setState({data: portlist}); }.bind(this)); }, render: function(){ return ( <PortsList data={this.state.data} selected={this.props.selectedport}/> ); } }); module.exports = Preferences;
clearbucketLabs/SteveApp
src/components/Preferences.react.js
JavaScript
apache-2.0
2,011
import PropTypes from 'prop-types'; import React from 'react'; import { ButtonGroup } from 'react-bootstrap'; import classNames from 'classnames'; import Action from './Action'; import OverlayTrigger from '../OverlayTrigger'; import Inject from '../Inject'; function getButtonGroupProps(props) { const buttonGroupProps = {}; Object.keys(ButtonGroup.propTypes).forEach(id => { if (props[id] !== undefined) { buttonGroupProps[id] = props[id]; } }); return buttonGroupProps; } /** * @param {object} props react props * @example const actions: [ { label: 'edit', icon: 'fa fa-edit', onClick: action('onEdit'), }, { label: 'delete', icon: 'fa fa-trash-o', onClick: action('onDelete'), }, { displayMode: 'dropdown', label: 'related items', icon: 'fa fa-file-excel-o', items: [ { label: 'document 1', onClick: action('document 1 click'), }, { label: 'document 2', onClick: action('document 2 click'), }, ], }, { id: 'split-dropdown-id', displayMode: 'splitDropdown', label: 'add file', onClick: action('onClick'), items: [ { label: 'file 1', onClick: action('file 1 click'), }, { label: 'file 2', onClick: action('file 2 click'), }, ], }, ]; <Actions actions={actions} tooltipPlacement="right" hideLabel link /> */ function Actions({ getComponent, hideLabel, link, tooltipPlacement, ...props }) { const buttonGroupProps = getButtonGroupProps(props); const Renderers = Inject.getAll(getComponent, { Action }); return ( <ButtonGroup className={classNames('tc-actions', props.className)} {...buttonGroupProps}> {props.actions.map((action, index) => { const extraParams = {}; if (hideLabel) { extraParams.hideLabel = hideLabel; } if (link) { extraParams.link = link; } if (tooltipPlacement) { extraParams.tooltipPlacement = tooltipPlacement; } return <Renderers.Action key={index} {...action} {...extraParams} />; })} </ButtonGroup> ); } Actions.displayName = 'Actions'; Actions.propTypes = { actions: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape(Action.propTypes)])), className: PropTypes.string, hideLabel: PropTypes.bool, tooltipPlacement: OverlayTrigger.propTypes.placement, link: PropTypes.bool, ...ButtonGroup.propTypes, }; Actions.defaultProps = { actions: [], }; export default Actions;
Talend/ui
packages/components/src/Actions/Actions.component.js
JavaScript
apache-2.0
2,392
define([ 'services/AuthAPI', ], function ( AuthAPI, ) { return class PermissionService { static isPermittedGetInfo(sourceKey, conceptId) { return AuthAPI.isPermitted(`vocabulary:${sourceKey}:concept:${conceptId}:get`); } static isPermittedGetRC(sourceKey) { return AuthAPI.isPermitted(`cdmresults:${sourceKey}:conceptRecordCount:post`); } } });
anthonysena/Atlas
js/pages/concept-sets/PermissionService.js
JavaScript
apache-2.0
365
// Derived from: // https://www.gamefaqs.com/ps4/835628-persona-5/faqs/74769 // https://www.gamefaqs.com/ps4/835628-persona-5/faqs/74765 const personae = [ {'arcana': 'Chariot', 'level': 3, 'name': 'Agathion', }, {'arcana': 'Chariot', 'level': 10, 'name': 'Slime', }, {'arcana': 'Chariot', 'level': 16, 'name': 'Shiisaa', }, {'arcana': 'Chariot', 'level': 21, 'name': 'Shiki-Ouji', }, {'arcana': 'Chariot', 'level': 25, 'name': 'Kin-Ki', }, {'arcana': 'Chariot', 'level': 31, 'name': 'Ara Mitama', }, {'arcana': 'Chariot', 'level': 39, 'name': 'White Rider', }, {'arcana': 'Chariot', 'level': 55, 'name': 'Cerberus', }, {'arcana': 'Chariot', 'level': 64, 'name': 'Thor', }, {'arcana': 'Chariot', 'level': 86, 'name': 'Chi You', 'max': true, 'special': true, }, {'arcana': 'Death', 'level': 3, 'name': 'Mandrake', }, {'arcana': 'Death', 'level': 9, 'name': 'Mokoi', }, {'arcana': 'Death', 'level': 19, 'name': 'Matador', }, {'arcana': 'Death', 'level': 29, 'name': 'Pisaca', }, {'arcana': 'Death', 'level': 39, 'name': 'Hell Biker', }, {'arcana': 'Death', 'level': 40, 'name': 'Hope Diamond', }, {'arcana': 'Death', 'level': 53, 'name': 'Pale Rider', }, {'arcana': 'Death', 'level': 62, 'name': 'Chernobog', }, {'arcana': 'Death', 'level': 65, 'name': 'Thanatos', }, {'arcana': 'Death', 'level': 69, 'name': 'Thanatos Picaro', }, {'arcana': 'Death', 'level': 72, 'name': 'Mot', }, {'arcana': 'Death', 'level': 79, 'name': 'Alice', 'max': true, 'special': true, }, {'arcana': 'Devil', 'level': 5, 'name': 'Incubus', }, {'arcana': 'Devil', 'level': 10, 'name': 'Andras', }, {'arcana': 'Devil', 'level': 25, 'name': 'Flauros', 'special': true, }, {'arcana': 'Devil', 'level': 32, 'name': 'Lilim', }, {'arcana': 'Devil', 'level': 43, 'name': 'Pazuzu', }, {'arcana': 'Devil', 'level': 58, 'name': 'Baphomet', }, {'arcana': 'Devil', 'level': 62, 'name': 'Nebiros', }, {'arcana': 'Devil', 'level': 68, 'name': 'Belial', }, {'arcana': 'Devil', 'level': 84, 'name': 'Beelzebub', 'max': true, }, {'arcana': 'Emperor', 'level': 10, 'name': 'Regent', }, {'arcana': 'Emperor', 'level': 16, 'name': 'Eligor', }, {'arcana': 'Emperor', 'level': 28, 'name': 'Setanta', }, {'arcana': 'Emperor', 'level': 36, 'name': 'Thoth', }, {'arcana': 'Emperor', 'level': 44, 'name': 'Okuninushi', }, {'arcana': 'Emperor', 'level': 52, 'name': 'Barong', }, {'arcana': 'Emperor', 'level': 61, 'name': 'King Frost', }, {'arcana': 'Emperor', 'level': 66, 'name': 'Oberon', }, {'arcana': 'Emperor', 'level': 75, 'name': 'Baal', }, {'arcana': 'Emperor', 'level': 82, 'name': 'Odin', 'max': true, }, {'arcana': 'Empress', 'level': 15, 'name': 'Queen\'s Necklace', }, {'arcana': 'Empress', 'level': 20, 'name': 'Yaksini', }, {'arcana': 'Empress', 'level': 26, 'name': 'Lamia', }, {'arcana': 'Empress', 'level': 40, 'name': 'Hariti', }, {'arcana': 'Empress', 'level': 50, 'name': 'Dakini', }, {'arcana': 'Empress', 'level': 56, 'name': 'Titania', }, {'arcana': 'Empress', 'level': 77, 'name': 'Kali', }, {'arcana': 'Empress', 'level': 80, 'name': 'Mother Harlot', 'max': true, }, {'arcana': 'Fool', 'level': 1, 'name': 'Arsene', }, {'arcana': 'Fool', 'level': 8, 'name': 'Obariyon', }, {'arcana': 'Fool', 'level': 16, 'name': 'High Pixie', }, {'arcana': 'Fool', 'level': 20, 'name': 'Izanagi', }, {'arcana': 'Fool', 'level': 23, 'name': 'Izanagi Picaro', }, {'arcana': 'Fool', 'level': 26, 'name': 'Orpheus', }, {'arcana': 'Fool', 'level': 29, 'name': 'Orpheus Picaro', }, {'arcana': 'Fool', 'level': 32, 'name': 'Decarabia', }, {'arcana': 'Fool', 'level': 38, 'name': 'Legion', }, {'arcana': 'Fool', 'level': 42, 'name': 'Ose', }, {'arcana': 'Fool', 'level': 49, 'name': 'Bugs', 'special': true, }, {'arcana': 'Fool', 'level': 50, 'name': 'Crystal Skull', }, {'arcana': 'Fool', 'level': 61, 'name': 'Dionysus', }, {'arcana': 'Fool', 'level': 67, 'name': 'Black Frost', 'special': true, }, {'arcana': 'Fool', 'level': 83, 'name': 'Vishnu', 'max': true, }, {'arcana': 'Fool', 'level': 95, 'name': 'Satanael', 'special': true, }, {'arcana': 'Fortune', 'level': 20, 'name': 'Stone of Scone', 'special': true, }, {'arcana': 'Fortune', 'level': 26, 'name': 'Clotho', }, {'arcana': 'Fortune', 'level': 30, 'name': 'Ariadne', }, {'arcana': 'Fortune', 'level': 34, 'name': 'Lachesis', }, {'arcana': 'Fortune', 'level': 39, 'name': 'Atropos', }, {'arcana': 'Fortune', 'level': 42, 'name': 'Ariadne Picaro', }, {'arcana': 'Fortune', 'level': 46, 'name': 'Fortuna', }, {'arcana': 'Fortune', 'level': 52, 'name': 'Norn', }, {'arcana': 'Fortune', 'level': 56, 'name': 'Asterius', }, {'arcana': 'Fortune', 'level': 62, 'name': 'Asterius Picaro', }, {'arcana': 'Fortune', 'level': 69, 'name': 'Lakshmi', 'max': true, }, {'arcana': 'Hanged Man', 'level': 9, 'name': 'Hua Po', }, {'arcana': 'Hanged Man', 'level': 14, 'name': 'Inugami', }, {'arcana': 'Hanged Man', 'level': 21, 'name': 'Orthrus', }, {'arcana': 'Hanged Man', 'level': 29, 'name': 'Take-Minakata', }, {'arcana': 'Hanged Man', 'level': 35, 'name': 'Emperor\'s Amulet', }, {'arcana': 'Hanged Man', 'level': 42, 'name': 'Hecatoncheires', }, {'arcana': 'Hanged Man', 'level': 60, 'name': 'Moloch', }, {'arcana': 'Hanged Man', 'level': 68, 'name': 'Vasuki', 'special': true, }, {'arcana': 'Hanged Man', 'level': 82, 'name': 'Attis', 'max': true, }, {'arcana': 'Hermit', 'level': 4, 'name': 'Bicorn', }, {'arcana': 'Hermit', 'level': 9, 'name': 'Koropokkuru', }, {'arcana': 'Hermit', 'level': 13, 'name': 'Ippon-Datara', }, {'arcana': 'Hermit', 'level': 17, 'name': 'Sudama', }, {'arcana': 'Hermit', 'level': 24, 'name': 'Naga', }, {'arcana': 'Hermit', 'level': 35, 'name': 'Arahabaki', }, {'arcana': 'Hermit', 'level': 42, 'name': 'Kumbhanda', }, {'arcana': 'Hermit', 'level': 49, 'name': 'Koumokuten', }, {'arcana': 'Hermit', 'level': 56, 'name': 'Kurama Tengu', }, {'arcana': 'Hermit', 'level': 75, 'name': 'Ongyo-Ki', 'max': true, 'special': true, }, {'arcana': 'Hierophant', 'level': 9, 'name': 'Berith', }, {'arcana': 'Hierophant', 'level': 17, 'name': 'Orobas', }, {'arcana': 'Hierophant', 'level': 22, 'name': 'Phoenix', }, {'arcana': 'Hierophant', 'level': 25, 'name': 'Anzu', }, {'arcana': 'Hierophant', 'level': 39, 'name': 'Unicorn', }, {'arcana': 'Hierophant', 'level': 42, 'name': 'Daisoujou', }, {'arcana': 'Hierophant', 'level': 63, 'name': 'Forneus', }, {'arcana': 'Hierophant', 'level': 67, 'name': 'Bishamonten', }, {'arcana': 'Hierophant', 'level': 76, 'name': 'Kohryu', 'max': true, 'special': true, }, {'arcana': 'Judgement', 'level': 37, 'name': 'Anubis', }, {'arcana': 'Judgement', 'level': 59, 'name': 'Trumpeter', 'special': true, }, {'arcana': 'Judgement', 'level': 64, 'name': 'Yamata-no-Orochi', }, {'arcana': 'Judgement', 'level': 74, 'name': 'Abaddon', }, {'arcana': 'Judgement', 'level': 81, 'name': 'Messiah', }, {'arcana': 'Judgement', 'level': 82, 'name': 'Shiva', 'special': true, }, {'arcana': 'Judgement', 'level': 87, 'name': 'Michael', 'special': true, }, {'arcana': 'Judgement', 'level': 90, 'name': 'Messiah Picaro', }, {'arcana': 'Judgement', 'level': 92, 'name': 'Satan', 'max': true, }, {'arcana': 'Justice', 'level': 12, 'name': 'Angel', }, {'arcana': 'Justice', 'level': 16, 'name': 'Archangel', }, {'arcana': 'Justice', 'level': 29, 'name': 'Principality', }, {'arcana': 'Justice', 'level': 41, 'name': 'Power', }, {'arcana': 'Justice', 'level': 60, 'name': 'Melchizedek', }, {'arcana': 'Justice', 'level': 68, 'name': 'Dominion', }, {'arcana': 'Justice', 'level': 71, 'name': 'Throne', 'special': true, }, {'arcana': 'Justice', 'level': 81, 'name': 'Uriel', }, {'arcana': 'Justice', 'level': 89, 'name': 'Metatron', 'max': true, 'special': true, }, {'arcana': 'Lovers', 'level': 2, 'name': 'Pixie', }, {'arcana': 'Lovers', 'level': 6, 'name': 'Saki Mitama', }, {'arcana': 'Lovers', 'level': 19, 'name': 'Leanan Sidhe', }, {'arcana': 'Lovers', 'level': 29, 'name': 'Ame-no-Uzume', }, {'arcana': 'Lovers', 'level': 42, 'name': 'Kushinada-Hime', }, {'arcana': 'Lovers', 'level': 50, 'name': 'Narcissus', }, {'arcana': 'Lovers', 'level': 56, 'name': 'Parvati', }, {'arcana': 'Lovers', 'level': 78, 'name': 'Raphael', }, {'arcana': 'Lovers', 'level': 85, 'name': 'Ishtar', 'max': true, }, {'arcana': 'Magician', 'level': 2, 'name': 'Jack-o\'-Lantern', }, {'arcana': 'Magician', 'level': 11, 'name': 'Jack Frost', }, {'arcana': 'Magician', 'level': 17, 'name': 'Nekomata', }, {'arcana': 'Magician', 'level': 24, 'name': 'Sandman', }, {'arcana': 'Magician', 'level': 28, 'name': 'Choronzon', }, {'arcana': 'Magician', 'level': 43, 'name': 'Queen Mab', }, {'arcana': 'Magician', 'level': 48, 'name': 'Rangda', }, {'arcana': 'Magician', 'level': 59, 'name': 'Surt', }, {'arcana': 'Magician', 'level': 76, 'name': 'Futsunushi', 'max': true, }, {'arcana': 'Moon', 'level': 7, 'name': 'Succubus', }, {'arcana': 'Moon', 'level': 12, 'name': 'Onmoraki', }, {'arcana': 'Moon', 'level': 16, 'name': 'Kaguya', }, {'arcana': 'Moon', 'level': 20, 'name': 'Nue', }, {'arcana': 'Moon', 'level': 24, 'name': 'Sui-Ki', }, {'arcana': 'Moon', 'level': 25, 'name': 'Kaguya Picaro', }, {'arcana': 'Moon', 'level': 29, 'name': 'Black Ooze', }, {'arcana': 'Moon', 'level': 33, 'name': 'Mothman', }, {'arcana': 'Moon', 'level': 44, 'name': 'Girimehkala', }, {'arcana': 'Moon', 'level': 50, 'name': 'Tsukiyomi', }, {'arcana': 'Moon', 'level': 55, 'name': 'Tsukiyomi Picaro', }, {'arcana': 'Moon', 'level': 60, 'name': 'Lilith', }, {'arcana': 'Moon', 'level': 75, 'name': 'Sandalphon', 'max': true, }, {'arcana': 'Priestess', 'level': 6, 'name': 'Silky', }, {'arcana': 'Priestess', 'level': 11, 'name': 'Apsaras', }, {'arcana': 'Priestess', 'level': 25, 'name': 'Koh-i-Noor', }, {'arcana': 'Priestess', 'level': 26, 'name': 'Isis', }, {'arcana': 'Priestess', 'level': 40, 'name': 'Kikuri-Hime', }, {'arcana': 'Priestess', 'level': 45, 'name': 'Scathach', }, {'arcana': 'Priestess', 'level': 50, 'name': 'Sarasvati', }, {'arcana': 'Priestess', 'level': 55, 'name': 'Skadi', }, {'arcana': 'Priestess', 'level': 73, 'name': 'Cybele', 'max': true, }, {'arcana': 'Star', 'level': 11, 'name': 'Kodama', }, {'arcana': 'Star', 'level': 23, 'name': 'Fuu-Ki', }, {'arcana': 'Star', 'level': 30, 'name': 'Neko Shogun', 'special': true, }, {'arcana': 'Star', 'level': 36, 'name': 'Kaiwan', }, {'arcana': 'Star', 'level': 43, 'name': 'Ananta', }, {'arcana': 'Star', 'level': 52, 'name': 'Garuda', }, {'arcana': 'Star', 'level': 64, 'name': 'Hanuman', }, {'arcana': 'Star', 'level': 67, 'name': 'Cu Chulainn', }, {'arcana': 'Star', 'level': 80, 'name': 'Sraosha', 'special': true, }, {'arcana': 'Star', 'level': 93, 'name': 'Lucifer', 'max': true, 'special': true, }, {'arcana': 'Strength', 'level': 6, 'name': 'Kelpie', }, {'arcana': 'Strength', 'level': 14, 'name': 'Kusi Mitama', }, {'arcana': 'Strength', 'level': 19, 'name': 'Oni', }, {'arcana': 'Strength', 'level': 24, 'name': 'Rakshasa', }, {'arcana': 'Strength', 'level': 30, 'name': 'Orlov', }, {'arcana': 'Strength', 'level': 31, 'name': 'Zouchouten', }, {'arcana': 'Strength', 'level': 44, 'name': 'Valkyrie', }, {'arcana': 'Strength', 'level': 69, 'name': 'Siegfried', }, {'arcana': 'Strength', 'level': 80, 'name': 'Zaou-Gongen', 'max': true, }, {'arcana': 'Sun', 'level': 19, 'name': 'Suzaku', }, {'arcana': 'Sun', 'level': 39, 'name': 'Mithras', }, {'arcana': 'Sun', 'level': 42, 'name': 'Yurlungur', }, {'arcana': 'Sun', 'level': 49, 'name': 'Horus', }, {'arcana': 'Sun', 'level': 53, 'name': 'Ganesha', }, {'arcana': 'Sun', 'level': 57, 'name': 'Yatagarasu', }, {'arcana': 'Sun', 'level': 63, 'name': 'Quetzalcoatl', }, {'arcana': 'Sun', 'level': 76, 'name': 'Asura-Ou', 'max': true, 'special': true, }, {'arcana': 'Temperance', 'level': 7, 'name': 'Genbu', }, {'arcana': 'Temperance', 'level': 11, 'name': 'Koppa Tengu', }, {'arcana': 'Temperance', 'level': 15, 'name': 'Makami', }, {'arcana': 'Temperance', 'level': 20, 'name': 'Nigi Mitama', }, {'arcana': 'Temperance', 'level': 25, 'name': 'Jikokuten', }, {'arcana': 'Temperance', 'level': 33, 'name': 'Mitra', }, {'arcana': 'Temperance', 'level': 49, 'name': 'Byakko', }, {'arcana': 'Temperance', 'level': 55, 'name': 'Raja Naga', }, {'arcana': 'Temperance', 'level': 62, 'name': 'Seiryu', }, {'arcana': 'Temperance', 'level': 77, 'name': 'Gabriel', }, {'arcana': 'Temperance', 'level': 84, 'name': 'Ardha', 'max': true, 'special': true, }, {'arcana': 'Tower', 'level': 32, 'name': 'Jatayu', }, {'arcana': 'Tower', 'level': 37, 'name': 'Belphegor', }, {'arcana': 'Tower', 'level': 41, 'name': 'Red Rider', }, {'arcana': 'Tower', 'level': 44, 'name': 'Magatsu-Izanagi', }, {'arcana': 'Tower', 'level': 48, 'name': 'Magatsu-Izanagi Picaro',}, {'arcana': 'Tower', 'level': 51, 'name': 'Seth', 'special': true, }, {'arcana': 'Tower', 'level': 59, 'name': 'Black Rider', }, {'arcana': 'Tower', 'level': 73, 'name': 'Mara', }, {'arcana': 'Tower', 'level': 79, 'name': 'Yoshitsune', 'special': true, }, {'arcana': 'Tower', 'level': 85, 'name': 'Mada', 'max': true, }, ]; const arcana2Combos = [ {'source': ['Chariot', 'Chariot' ], 'result': 'Chariot' }, {'source': ['Chariot', 'Death' ], 'result': 'Devil' }, {'source': ['Chariot', 'Devil' ], 'result': 'Temperance' }, {'source': ['Chariot', 'Fortune' ], 'result': 'Priestess' }, {'source': ['Chariot', 'Hanged Man' ], 'result': 'Fool' }, {'source': ['Chariot', 'Hermit' ], 'result': 'Devil' }, {'source': ['Chariot', 'Justice' ], 'result': 'Moon' }, {'source': ['Chariot', 'Moon' ], 'result': 'Lovers' }, {'source': ['Chariot', 'Star' ], 'result': 'Moon' }, {'source': ['Chariot', 'Strength' ], 'result': 'Hermit' }, {'source': ['Chariot', 'Sun' ], 'result': 'Priestess' }, {'source': ['Chariot', 'Temperance' ], 'result': 'Strength' }, {'source': ['Chariot', 'Tower' ], 'result': 'Fortune' }, {'source': ['Death', 'Death' ], 'result': 'Death' }, {'source': ['Death', 'Devil' ], 'result': 'Chariot' }, {'source': ['Death', 'Moon' ], 'result': 'Hierophant' }, {'source': ['Death', 'Star' ], 'result': 'Devil' }, {'source': ['Death', 'Sun' ], 'result': 'Priestess' }, {'source': ['Death', 'Temperance' ], 'result': 'Hanged Man' }, {'source': ['Death', 'Tower' ], 'result': 'Sun' }, {'source': ['Devil', 'Devil' ], 'result': 'Devil' }, {'source': ['Devil', 'Judgement' ], 'result': 'Lovers' }, {'source': ['Devil', 'Moon' ], 'result': 'Chariot' }, {'source': ['Devil', 'Star' ], 'result': 'Strength' }, {'source': ['Devil', 'Sun' ], 'result': 'Hermit' }, {'source': ['Devil', 'Tower' ], 'result': 'Magician' }, {'source': ['Emperor', 'Chariot' ], 'result': 'Strength' }, {'source': ['Emperor', 'Death' ], 'result': 'Hermit' }, {'source': ['Emperor', 'Devil' ], 'result': 'Justice' }, {'source': ['Emperor', 'Emperor' ], 'result': 'Emperor' }, {'source': ['Emperor', 'Fortune' ], 'result': 'Sun' }, {'source': ['Emperor', 'Hanged Man' ], 'result': 'Devil' }, {'source': ['Emperor', 'Hermit' ], 'result': 'Hierophant' }, {'source': ['Emperor', 'Hierophant' ], 'result': 'Fortune' }, {'source': ['Emperor', 'Judgement' ], 'result': 'Priestess' }, {'source': ['Emperor', 'Justice' ], 'result': 'Chariot' }, {'source': ['Emperor', 'Lovers' ], 'result': 'Fool' }, {'source': ['Emperor', 'Moon' ], 'result': 'Tower' }, {'source': ['Emperor', 'Star' ], 'result': 'Lovers' }, {'source': ['Emperor', 'Strength' ], 'result': 'Tower' }, {'source': ['Emperor', 'Sun' ], 'result': 'Judgement' }, {'source': ['Emperor', 'Temperance' ], 'result': 'Devil' }, {'source': ['Emperor', 'Tower' ], 'result': 'Star' }, {'source': ['Empress', 'Chariot' ], 'result': 'Star' }, {'source': ['Empress', 'Death' ], 'result': 'Fool' }, {'source': ['Empress', 'Devil' ], 'result': 'Sun' }, {'source': ['Empress', 'Emperor' ], 'result': 'Justice' }, {'source': ['Empress', 'Empress' ], 'result': 'Empress' }, {'source': ['Empress', 'Fortune' ], 'result': 'Hermit' }, {'source': ['Empress', 'Hanged Man' ], 'result': 'Priestess' }, {'source': ['Empress', 'Hermit' ], 'result': 'Strength' }, {'source': ['Empress', 'Hierophant' ], 'result': 'Fool' }, {'source': ['Empress', 'Judgement' ], 'result': 'Emperor' }, {'source': ['Empress', 'Justice' ], 'result': 'Lovers' }, {'source': ['Empress', 'Lovers' ], 'result': 'Judgement' }, {'source': ['Empress', 'Moon' ], 'result': 'Fortune' }, {'source': ['Empress', 'Star' ], 'result': 'Lovers' }, {'source': ['Empress', 'Strength' ], 'result': 'Chariot' }, {'source': ['Empress', 'Sun' ], 'result': 'Tower' }, {'source': ['Empress', 'Temperance' ], 'result': 'Priestess' }, {'source': ['Empress', 'Tower' ], 'result': 'Emperor' }, {'source': ['Fool', 'Chariot' ], 'result': 'Moon' }, {'source': ['Fool', 'Death' ], 'result': 'Strength' }, {'source': ['Fool', 'Devil' ], 'result': 'Temperance' }, {'source': ['Fool', 'Emperor' ], 'result': 'Temperance' }, {'source': ['Fool', 'Empress' ], 'result': 'Hanged Man' }, {'source': ['Fool', 'Fool' ], 'result': 'Fool' }, {'source': ['Fool', 'Fortune' ], 'result': 'Lovers' }, {'source': ['Fool', 'Hanged Man' ], 'result': 'Tower' }, {'source': ['Fool', 'Hermit' ], 'result': 'Priestess' }, {'source': ['Fool', 'Hierophant' ], 'result': 'Hermit' }, {'source': ['Fool', 'Judgement' ], 'result': 'Sun' }, {'source': ['Fool', 'Justice' ], 'result': 'Star' }, {'source': ['Fool', 'Lovers' ], 'result': 'Chariot' }, {'source': ['Fool', 'Magician' ], 'result': 'Death' }, {'source': ['Fool', 'Moon' ], 'result': 'Justice' }, {'source': ['Fool', 'Priestess' ], 'result': 'Moon' }, {'source': ['Fool', 'Star' ], 'result': 'Magician' }, {'source': ['Fool', 'Strength' ], 'result': 'Death' }, {'source': ['Fool', 'Sun' ], 'result': 'Justice' }, {'source': ['Fool', 'Temperance' ], 'result': 'Hierophant' }, {'source': ['Fool', 'Tower' ], 'result': 'Empress' }, {'source': ['Fortune', 'Death' ], 'result': 'Star' }, {'source': ['Fortune', 'Devil' ], 'result': 'Hierophant' }, {'source': ['Fortune', 'Fortune' ], 'result': 'Fortune' }, {'source': ['Fortune', 'Hanged Man' ], 'result': 'Emperor' }, {'source': ['Fortune', 'Judgement' ], 'result': 'Tower' }, {'source': ['Fortune', 'Moon' ], 'result': 'Sun' }, {'source': ['Fortune', 'Star' ], 'result': 'Devil' }, {'source': ['Fortune', 'Strength' ], 'result': 'Temperance' }, {'source': ['Fortune', 'Sun' ], 'result': 'Star' }, {'source': ['Fortune', 'Temperance' ], 'result': 'Empress' }, {'source': ['Fortune', 'Tower' ], 'result': 'Hanged Man' }, {'source': ['Hanged Man', 'Death' ], 'result': 'Moon' }, {'source': ['Hanged Man', 'Devil' ], 'result': 'Fortune' }, {'source': ['Hanged Man', 'Hanged Man' ], 'result': 'Hanged Man' }, {'source': ['Hanged Man', 'Judgement' ], 'result': 'Star' }, {'source': ['Hanged Man', 'Moon' ], 'result': 'Strength' }, {'source': ['Hanged Man', 'Star' ], 'result': 'Justice' }, {'source': ['Hanged Man', 'Sun' ], 'result': 'Hierophant' }, {'source': ['Hanged Man', 'Temperance' ], 'result': 'Death' }, {'source': ['Hanged Man', 'Tower' ], 'result': 'Hermit' }, {'source': ['Hermit', 'Death' ], 'result': 'Strength' }, {'source': ['Hermit', 'Devil' ], 'result': 'Priestess' }, {'source': ['Hermit', 'Fortune' ], 'result': 'Star' }, {'source': ['Hermit', 'Hanged Man' ], 'result': 'Star' }, {'source': ['Hermit', 'Hermit' ], 'result': 'Hermit' }, {'source': ['Hermit', 'Judgement' ], 'result': 'Emperor' }, {'source': ['Hermit', 'Moon' ], 'result': 'Priestess' }, {'source': ['Hermit', 'Star' ], 'result': 'Strength' }, {'source': ['Hermit', 'Strength' ], 'result': 'Hierophant' }, {'source': ['Hermit', 'Sun' ], 'result': 'Devil' }, {'source': ['Hermit', 'Temperance' ], 'result': 'Strength' }, {'source': ['Hermit', 'Tower' ], 'result': 'Judgement' }, {'source': ['Hierophant', 'Chariot' ], 'result': 'Star' }, {'source': ['Hierophant', 'Death' ], 'result': 'Chariot' }, {'source': ['Hierophant', 'Devil' ], 'result': 'Hanged Man' }, {'source': ['Hierophant', 'Fortune' ], 'result': 'Justice' }, {'source': ['Hierophant', 'Hanged Man' ], 'result': 'Sun' }, {'source': ['Hierophant', 'Hermit' ], 'result': 'Fortune' }, {'source': ['Hierophant', 'Hierophant' ], 'result': 'Hierophant' }, {'source': ['Hierophant', 'Judgement' ], 'result': 'Empress' }, {'source': ['Hierophant', 'Justice' ], 'result': 'Hanged Man' }, {'source': ['Hierophant', 'Lovers' ], 'result': 'Strength' }, {'source': ['Hierophant', 'Moon' ], 'result': 'Priestess' }, {'source': ['Hierophant', 'Star' ], 'result': 'Tower' }, {'source': ['Hierophant', 'Strength' ], 'result': 'Fool' }, {'source': ['Hierophant', 'Sun' ], 'result': 'Lovers' }, {'source': ['Hierophant', 'Temperance' ], 'result': 'Death' }, {'source': ['Hierophant', 'Tower' ], 'result': 'Judgement' }, {'source': ['Judgement', 'Judgement' ], 'result': 'Judgement' }, {'source': ['Justice', 'Death' ], 'result': 'Fool' }, {'source': ['Justice', 'Devil' ], 'result': 'Fool' }, {'source': ['Justice', 'Fortune' ], 'result': 'Emperor' }, {'source': ['Justice', 'Hanged Man' ], 'result': 'Lovers' }, {'source': ['Justice', 'Hermit' ], 'result': 'Magician' }, {'source': ['Justice', 'Justice' ], 'result': 'Justice' }, {'source': ['Justice', 'Moon' ], 'result': 'Devil' }, {'source': ['Justice', 'Star' ], 'result': 'Empress' }, {'source': ['Justice', 'Strength' ], 'result': 'Hierophant' }, {'source': ['Justice', 'Sun' ], 'result': 'Hanged Man' }, {'source': ['Justice', 'Temperance' ], 'result': 'Emperor' }, {'source': ['Justice', 'Tower' ], 'result': 'Sun' }, {'source': ['Lovers', 'Chariot' ], 'result': 'Temperance' }, {'source': ['Lovers', 'Death' ], 'result': 'Temperance' }, {'source': ['Lovers', 'Devil' ], 'result': 'Moon' }, {'source': ['Lovers', 'Fortune' ], 'result': 'Strength' }, {'source': ['Lovers', 'Hanged Man' ], 'result': 'Sun' }, {'source': ['Lovers', 'Hermit' ], 'result': 'Chariot' }, {'source': ['Lovers', 'Judgement' ], 'result': 'Hanged Man' }, {'source': ['Lovers', 'Justice' ], 'result': 'Judgement' }, {'source': ['Lovers', 'Lovers' ], 'result': 'Lovers' }, {'source': ['Lovers', 'Moon' ], 'result': 'Magician' }, {'source': ['Lovers', 'Star' ], 'result': 'Chariot' }, {'source': ['Lovers', 'Strength' ], 'result': 'Death' }, {'source': ['Lovers', 'Sun' ], 'result': 'Empress' }, {'source': ['Lovers', 'Temperance' ], 'result': 'Strength' }, {'source': ['Lovers', 'Tower' ], 'result': 'Empress' }, {'source': ['Magician', 'Chariot' ], 'result': 'Priestess' }, {'source': ['Magician', 'Death' ], 'result': 'Hermit' }, {'source': ['Magician', 'Devil' ], 'result': 'Hierophant' }, {'source': ['Magician', 'Emperor' ], 'result': 'Hanged Man' }, {'source': ['Magician', 'Empress' ], 'result': 'Justice' }, {'source': ['Magician', 'Fortune' ], 'result': 'Justice' }, {'source': ['Magician', 'Hanged Man' ], 'result': 'Empress' }, {'source': ['Magician', 'Hermit' ], 'result': 'Lovers' }, {'source': ['Magician', 'Hierophant' ], 'result': 'Death' }, {'source': ['Magician', 'Judgement' ], 'result': 'Strength' }, {'source': ['Magician', 'Justice' ], 'result': 'Emperor' }, {'source': ['Magician', 'Lovers' ], 'result': 'Devil' }, {'source': ['Magician', 'Magician' ], 'result': 'Magician' }, {'source': ['Magician', 'Moon' ], 'result': 'Lovers' }, {'source': ['Magician', 'Priestess' ], 'result': 'Temperance' }, {'source': ['Magician', 'Star' ], 'result': 'Priestess' }, {'source': ['Magician', 'Strength' ], 'result': 'Fool' }, {'source': ['Magician', 'Sun' ], 'result': 'Hierophant' }, {'source': ['Magician', 'Temperance' ], 'result': 'Chariot' }, {'source': ['Magician', 'Tower' ], 'result': 'Temperance' }, {'source': ['Moon', 'Judgement' ], 'result': 'Fool' }, {'source': ['Moon', 'Moon' ], 'result': 'Moon' }, {'source': ['Moon', 'Sun' ], 'result': 'Empress' }, {'source': ['Priestess', 'Chariot' ], 'result': 'Hierophant' }, {'source': ['Priestess', 'Death' ], 'result': 'Magician' }, {'source': ['Priestess', 'Devil' ], 'result': 'Moon' }, {'source': ['Priestess', 'Emperor' ], 'result': 'Empress' }, {'source': ['Priestess', 'Empress' ], 'result': 'Emperor' }, {'source': ['Priestess', 'Fortune' ], 'result': 'Magician' }, {'source': ['Priestess', 'Hanged Man' ], 'result': 'Death' }, {'source': ['Priestess', 'Hermit' ], 'result': 'Temperance' }, {'source': ['Priestess', 'Hierophant' ], 'result': 'Magician' }, {'source': ['Priestess', 'Judgement' ], 'result': 'Justice' }, {'source': ['Priestess', 'Justice' ], 'result': 'Death' }, {'source': ['Priestess', 'Lovers' ], 'result': 'Fortune' }, {'source': ['Priestess', 'Moon' ], 'result': 'Hierophant' }, {'source': ['Priestess', 'Priestess' ], 'result': 'Priestess' }, {'source': ['Priestess', 'Star' ], 'result': 'Hermit' }, {'source': ['Priestess', 'Strength' ], 'result': 'Devil' }, {'source': ['Priestess', 'Sun' ], 'result': 'Chariot' }, {'source': ['Priestess', 'Temperance' ], 'result': 'Devil' }, {'source': ['Priestess', 'Tower' ], 'result': 'Hanged Man' }, {'source': ['Star', 'Judgement' ], 'result': 'Fortune' }, {'source': ['Star', 'Moon' ], 'result': 'Temperance' }, {'source': ['Star', 'Star' ], 'result': 'Star' }, {'source': ['Star', 'Sun' ], 'result': 'Judgement' }, {'source': ['Strength', 'Death' ], 'result': 'Hierophant' }, {'source': ['Strength', 'Devil' ], 'result': 'Death' }, {'source': ['Strength', 'Hanged Man' ], 'result': 'Temperance' }, {'source': ['Strength', 'Moon' ], 'result': 'Magician' }, {'source': ['Strength', 'Star' ], 'result': 'Moon' }, {'source': ['Strength', 'Strength' ], 'result': 'Strength' }, {'source': ['Strength', 'Sun' ], 'result': 'Moon' }, {'source': ['Strength', 'Temperance' ], 'result': 'Chariot' }, {'source': ['Strength', 'Tower' ], 'result': 'Chariot' }, {'source': ['Sun', 'Judgement' ], 'result': 'Death' }, {'source': ['Sun', 'Sun' ], 'result': 'Sun' }, {'source': ['Temperance', 'Devil' ], 'result': 'Fool' }, {'source': ['Temperance', 'Judgement' ], 'result': 'Hermit' }, {'source': ['Temperance', 'Moon' ], 'result': 'Fortune' }, {'source': ['Temperance', 'Star' ], 'result': 'Sun' }, {'source': ['Temperance', 'Sun' ], 'result': 'Magician' }, {'source': ['Temperance', 'Temperance' ], 'result': 'Temperance' }, {'source': ['Temperance', 'Tower' ], 'result': 'Fortune' }, {'source': ['Tower', 'Judgement' ], 'result': 'Moon' }, {'source': ['Tower', 'Moon' ], 'result': 'Hermit' }, {'source': ['Tower', 'Star' ], 'result': 'Death' }, {'source': ['Tower', 'Sun' ], 'result': 'Emperor' }, {'source': ['Tower', 'Tower' ], 'result': 'Tower' }, ]; const arcana3Combos = [ ]; const specialCombos = [ {'result': 'Alice', 'sources': ['Nebiros', 'Belial']}, {'result': 'Ardha', 'sources': ['Parvati', 'Shiva']}, {'result': 'Asura-Ou', 'sources': ['Zouchouten', 'Jikokuten', 'Koumokuten', 'Bishamonten']}, {'result': 'Black Frost', 'sources': ['Jack O\'Lantern', 'Jack Frost', 'King Frost']}, {'result': 'Bugs', 'sources': ['Pixie', 'Pisaca', 'Hariti']}, {'result': 'Chi You', 'sources': ['Hecatoncheires', 'White Rider', 'Thor', 'Yoshitsune', 'Cu Chulainn']}, {'result': 'Flauros', 'sources': ['Berith', 'Andras', 'Eligor']}, {'result': 'Kohryu', 'sources': ['Genbu', 'Seiryu', 'Suzaku', 'Byakko']}, {'result': 'Lucifer', 'sources': ['Anubis', 'Ananta', 'Trumpeter', 'Michael', 'Metatron', 'Satan']}, {'result': 'Metatron', 'sources': ['Principality', 'Power', 'Dominion', 'Melchizedek', 'Sandalphon', 'Michael']}, {'result': 'Michael', 'sources': ['Raphael', 'Gabriel', 'Uriel']}, {'result': 'Neko Shogun', 'sources': ['Kodama', 'Sudama', 'Anzu']}, {'result': 'Ongyo-Ki', 'sources': ['Kin-Ki', 'Sui-Ki', 'Fuu-Ki']}, {'result': 'Satanael', 'sources': ['Arsene', 'Anzu', 'Ishtar', 'Satan', 'Lucifer', 'Michael']}, {'result': 'Seth', 'sources': ['Isis', 'Thoth', 'Anubis', 'Horus']}, {'result': 'Shiva', 'sources': ['Rangda', 'Barong']}, {'result': 'Sraosha', 'sources': ['Mithra', 'Mithras', 'Melchizedek', 'Lilith', 'Gabriel']}, {'result': 'Throne', 'sources': ['Power', 'Melchizedek', 'Dominion']}, {'result': 'Trumpeter', 'sources': ['White Rider', 'Red Rider', 'Black Rider', 'Pale Rider']}, {'result': 'Vasuki', 'sources': ['Naga', 'Raja Naga', 'Ananta']}, {'result': 'Yoshitsune', 'sources': ['Okuninushi', 'Shiki-Ouji', 'Arahabaki', 'Yatagarasu', 'Futsunushi']} ];
arantius/persona-fusion-calculator
data5.js
JavaScript
apache-2.0
35,212
/** * Copyright 2021 The Google Earth Engine Community Authors * * 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 * * https://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. */ // [START earthengine__apidocs__ee_geometry_point_buffer] // Define a Point object. var point = ee.Geometry.Point(-122.082, 37.42); // Apply the buffer method to the Point object. var pointBuffer = point.buffer({'distance': 100}); // Print the result to the console. print('point.buffer(...) =', pointBuffer); // Display relevant geometries on the map. Map.setCenter(-122.085, 37.422, 15); Map.addLayer(point, {'color': 'black'}, 'Geometry [black]: point'); Map.addLayer(pointBuffer, {'color': 'red'}, 'Result [red]: point.buffer'); // [END earthengine__apidocs__ee_geometry_point_buffer]
google/earthengine-community
samples/javascript/apidocs/ee-geometry-point-buffer.js
JavaScript
apache-2.0
1,271
(function() { 'use strict'; function SearchPanelController(BingGeoCoderService, SceneService, PathControls, Messagebus, $window, toastr, THREE, proj4) { this.query = ''; this.hasGeoLocation = 'geolocation' in $window.navigator; this.clear = function() { this.query = ''; }; this.onLocationResponse = function(resources) { if (resources.length === 0) { toastr.warning('No results', 'Location not found'); return; } var resource = resources[0]; this.query = resource.name.replace(', Nederland', ''); var location = resource.point.coordinates; this.gotoLocation(location[1], location[0]); }; this.search = function() { BingGeoCoderService.geocode(this.query).then( this.onLocationResponse.bind(this), function() { toastr.error('Search failed', 'for some reason'); } ); }; /** * When enter is pressed inside input field perform a search */ this.onQueryKeyPress = function($event) { var enterCode = 13; if ($event.keyCode === enterCode) { this.search(); } }; this.gotoLocation = function(longitude, latitude) { var altitude = 0; var bingProjection = 'EPSG:4326'; var bingLocation = [longitude, latitude]; var nlProjection = 'EPSG:28992'; // look at location var geoLocation = proj4(bingProjection, nlProjection, bingLocation); var geoVector = new THREE.Vector3(geoLocation[0], geoLocation[1], altitude); var sceneLocation = SceneService.toLocal(geoVector); // move camera to location var moveOffsetX = 0; var moveOffsetY = -1000; var moveOffsetZ = 1000; var geoLocationMove = [geoLocation[0] + moveOffsetX, geoLocation[1] + moveOffsetY]; var sceneLocationMove = SceneService.toLocal(new THREE.Vector3(geoLocationMove[0], geoLocationMove[1], altitude + moveOffsetZ)); PathControls.moveTo(sceneLocationMove); PathControls.lookat(sceneLocation); }; this.gotoCurrentLocation = function() { $window.navigator.geolocation.getCurrentPosition(function(position) { var c = position.coords; this.gotoLocation(c.longitude, c.latitude); }.bind(this), function() { toastr.error('Unable to get current location'); }); }; } angular.module('pattyApp.searchbox') .controller('SearchPanelController', SearchPanelController); })();
NLeSC/ahn-pointcloud-viewer
app/scripts/searchbox/searchbox.controller.js
JavaScript
apache-2.0
2,469
var app = angular.module("Gallery", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl: "home-page" }) .when("/photo/:photoId", { templateUrl: "photo-page" }); });
oprohonnyi/presentation_src
ng-training/2nd meetup/app/main.js
JavaScript
apache-2.0
220
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.once = once; function once(proto, name, descriptor) { if (!descriptor.value) { throw new ArgumentError(); } var done = false; var value = null; var fn = descriptor.value; descriptor.value = function () { if (done) { return value; } done = true; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return value = fn.call.apply(fn, [this].concat(args)); }; }
hansl/zenjs
lib/lib/annotations.js
JavaScript
apache-2.0
569
/** * TenantWorkerObject * provides API function wrapper for all calls the the Tenant services */ function TenantWorkerObject() { var _endpoint = "../../../api/tenant.svc/"; var _ajax = new AJAX(); var _lastResult = null; this.GetAllTenants = _getAllTenants; this.AddTenant = _addTenant; function _getAllTenants() { var _json = _ajax.GetNowAsText("GET", _endpoint + "all", null); if(_json!=_lastResult) { _lastResult = _json; return _json; } return null; } function _addTenant(_data) { var _postdata = "frm_domain=" + encodeURIComponent(_data["name"]) + "&frm_username=" + encodeURIComponent(_data["username"]) + "&frm_password=" + encodeURIComponent(_data["password"]); var _result = _ajax.GetNowAsText("POST", _endpoint + "tenant", _postdata); console.log("WORKER: ADD TENANT: " + _result); } }
Hevelian/hevelian-identity-web
src/main/webapp/scripts/hevelian/objects/TenantWorkerObject.js
JavaScript
apache-2.0
854
import {GestureEventListeners} from '@polymer/polymer/lib/mixins/gesture-event-listeners.js'; import * as Gestures from '@polymer/polymer/lib/utils/gestures.js'; import './contextMenuConnector.js'; window.Vaadin.Flow.Legacy.GestureEventListeners = GestureEventListeners; window.Vaadin.Flow.Legacy.Gestures = Gestures;
opencirclesolutions/dynamo
dynamo-frontend-export/node_modules/@vaadin/flow-frontend/contextMenuConnector-es6.js
JavaScript
apache-2.0
319
import Component from '@glimmer/component'; /** * Draws tiles. * * @param { hash } def - section definition * ```javascript * { * label: 'Actions', * description: 'Please choose an action', * maxcol => 4, // maximum tiles per row (optional, default: maximum according to browser window) * align => 'left', // or 'center' or 'right' (optional, default: 'left') * tiles => [ * { * type: 'button', content => { ... }, * }, * { * type: 'newline', * }, * { * type: 'button', content => { ... }, * }, * ], * } * ``` * @module component/oxi-section/tiles */ export default class OxiSectionTilesComponent extends Component { get tiles() { let tiles = this.args.def.tiles || []; let maxcol = this.args.def.maxcol; if (! maxcol) return tiles; // insert a newline after maxcol columns let result = []; let newline = { type: 'newline' }; let col = 0; for (const t of tiles) { if (++col > maxcol) { result.push(newline); col = 0; } let newTile = { ...t, content: { ...t.content }, // explicitely copy content so Ember does not complain if we set format below }; if (t.type == 'newline') { col = 0; } else { newTile.content.format = 'tile'; // button format } result.push(newTile); } return result; } get align() { let defaultAlign = 'left'; let align = this.args.def.align || defaultAlign; return align.match(/^(left|right|center)$/) ? align : defaultAlign; } }
openxpki/openxpki
core/htdocs_source/app/pods/components/oxi-section/tiles/component.js
JavaScript
apache-2.0
1,815
/** * Created by jeffstern on 7/9/14. * Modified by Barbara Groh on 6/23/15. */ // This is the new way of creating JavaScript classes. It's not really a function. function Location(title, instagram, year) { this.title = title; this.instagram = instagram; this.year = year; } // A list of all 14 Pixar movies. var locations = [ // Each of these lines of code makes a new Movie object from the movie class new Location("Miami: Verizon Terremark", "gwc_verizon", 2014), new Location("Miami: FIU", "gwc.fiu", 2015), new Location("Seattle: Amazon", "gwcamazon", 2014), new Location("Bay Area: Intel", "gwcintel", 2014), new Location("San Jose: eBay's Front Porch", "gwcfrontporch", 2015), new Location("Bay Area: General Electric", "gwc_ge", 2014), new Location("San Jose: eBay", "gwc_swagjose", 2014), new Location("Seattle: Microsoft", "gwcmicrosoft", 2014), new Location("Bay Area: Square", "gwcsquared", 2014), new Location("Bay Area: Facebook", "gwcfacebook", 2014), new Location("NYC: AT&T", "gwc_att", 2014), new Location("San Jose: Adobe", "gwc_adobe", 2014), new Location("NYC: AppNexus", "gwcappnexus", 2014), new Location("Chicago", "girlswhocodechicago", 2015), new Location("Massachusetts", "girlswhocodemassachusetts", 2015), new Location("Washington D.C.", "girlswhocodedc", 2015), new Location("New Jersey", "girlswhocodenj", 2015), new Location("Seattle: Microsoft", "gwc_microsoftseattle", 2015), new Location("Miami: Miami-Dade College", "girlswhocode_mdc", 2015), new Location("Microsoft", "microsoftmv_gwc", 2015), new Location("LA: Google", "gwc_googlela", 2015), new Location("Bay Area: Electronic Arts", "gwc_ea", 2015), new Location("NYC: Cambio", "cambiogwc", 2014), new Location("San Francisco: ", "gwc_techwarriors", 2015), new Location("Bay Area", "girlswhocode.bayarea", 2015), new Location("NYC", "girlswhocodenyc", 2015), new Location("Seattle", "girlswhocodeseattle", 2015), new Location("LA", "girlswhocodela", 2015), new Location("Boutique", "gwcboutique", 2015), new Location("Miami", "girlswhocodemia", 2015), new Location("Bay Area: San Ramon", "gwcsanramon", 2015) ] /* showMoives Populates the movies div with each individual movie Input: An array of Movie objects */ function showLocation(locations) { $(" #locations ").empty(); // A jQuery method which clears the movies div for (var i = 0; i < locations.length; i++) { if(i%3==0) { $(" #locations ").append("<div class='row'></div>"); // A jQuery method to add a new row for every 3rd movie } // This string is the HTML that makes up each individual movie cell, // It uses movie[i] attributes so that each cell has unique information var locationHTML = "<div class='col-md-4 location'>" + "<a href='http://instagram.com/"+locations[i].instagram+"'><h3 class='locationname' style='color:#555555;'>" + locations[i].title + " (" + locations[i].year + ")</h3>" + "<p class='instagram' style='color:#555555;'>" +"@"+ locations[i].instagram + "</p></a>" + "<iframe src='http://widget.websta.me/in/" + locations[i].instagram + "/?s=200&w=2&h=3&b=0&p=10' allowtransparency='true' frameborder='0' scrolling='no' style='border:none;overflow:hidden;width:420px; height: 630px' ></iframe>"; $(" #locations .row:last-child").append(locationHTML); // A jQuery method that adds the new HTML string to the last row in the movies div if(i%3==2) { $(" #locations ").append("</div>"); } } } /* sortButtonClicked Calls appropriate sort method based on which link was clicked and repopulates movie grid. Input: String representing which button was clicked on */ function sortButtonClicked(link) { if (link === "date") { sortLocationsByYear(locations); } else if (link == "title") { sortLocationsByTitle(locations); } else if(link == "shuffle") { shuffle(locations); } showLocation(locations); } /* shuffle Input: Array Output: Shuffled array Function courtesy of http://jsfromhell.com/array/shuffle */ function shuffle(o) { for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } /* sortMoviesByYear You must implement a basic bubble sort algorithm to sort the movies based on it's year attribute. Input: a list of Movie objects. Output: Returns a list of Movie objects after they have been sorted by year. */ function sortLocationsByYear(locations) { for (var i = 0; i < locations.length; i++) { console.log(locations[i].year) } var swapped; do { swapped = false; for (var i=0; i < locations.length-1; i++) { if (locations[i].year < locations[i+1].year) { var temp = locations[i]; locations[i] = locations[i+1]; locations[i+1] = temp; swapped = true; } } } while (swapped); for (var i = 0; i < locations.length; i++) { console.log(locations[i].year); console.log(locations[i].title); } return locations; } /* sortMoviesByTitle You must implement a basic bubble sort algorithm to sort the movies based on it's title attribute. Input: a list of Movie objects. Output: returns a list of Movie objects after they have been sorted by title. */ function sortLocationsByTitle(locations) { for (var i = 0; i < locations.length; i++) { console.log(locations[i].title); } var swapped; do { swapped = false; for (var i=0; i < locations.length-1; i++) { if (locations[i].title > locations[i+1].title) { var temp = locations[i]; locations[i] = locations[i+1]; locations[i+1] = temp; swapped = true; } } } while (swapped); for (var i = 0; i < locations.length; i++) { console.log(locations[i].title); console.log(locations[i].year); } return locations; } // Code that gets run once the page has loaded. It also uses jQuery. $(document).ready(function () { sortLocationsByTitle(locations); sortLocationsByYear(locations); showLocation(locations); });
barbaragroh/barbaragroh.github.io
mobile/socialmediacode.js
JavaScript
apache-2.0
6,241
/** * ApiError - Base Error class * * @author Jefferson Sofarelli<jmsofarelli@gmail.com> * @author Christopher Will<dev@cwill-dev.com> * @date 07-09-2013 */ /** * Constructor * * @param {String} msg Error message * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error */ function ApiError (msg, msgArgs) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.message = msg; this.messageArgs = msgArgs; this.name = 'ApiError'; } // Inherits from Error. ApiError.prototype.__proto__ = Error.prototype; // Module exports. module.exports = exports = ApiError; // Expose subclasses ApiError.AuthenticationError = require('./../errors/authentication-error'); ApiError.BadRequestError = require('./../errors/bad-request-error'); ApiError.ConfigurationError = require('./../errors/configuration-error'); ApiError.InternalServerError = require('./../errors/internal-server-error'); ApiError.InvalidRequestError = require('./../errors/invalid-request-error'); ApiError.NotFoundError = require('./../errors/not-found-error'); ApiError.ServiceUnavailableError = require('./../errors/service-unavailable-error'); ApiError.ValidationError = require('./../errors/validation-error');
cwilldev/express-api
common/error.js
JavaScript
apache-2.0
1,249
'use strict'; describe('Service: constant', function () { // load the service's module beforeEach(module('ubirchAdminCrudApp')); // instantiate service var constant; beforeEach(inject(function (_constant_) { constant = _constant_; })); it('should do something', function () { expect(!!constant).toBe(true); }); });
ubirch/ubirch-admin-ui
test/spec/services/constant.js
JavaScript
apache-2.0
344
import Ember from 'ember'; import ScrollAreaActionContext from 'ember-cli-nf-graph/utils/nf/scroll-area-action-context'; /** A component that emits actions and events when scrolled or resized. @namespace components @class {nf-scroll-area} */ export default Ember.Component.extend({ /** The tag name of the component @property tagName @type {String} @default 'div' */ tagName: 'div', classNames: ['nf-scroll-area'], /** The name of the action to fire when scrolled @property scrollAction @type {String} @default null */ scrollAction: null, /** The name of the action to fire when resized @property resizeAction @type {String} @default null */ resizeAction: null, /** The name of the action to fire when scrolled *OR* resized @property changeAction @type {String} @default null */ changeAction: null, /** The name of the action to fire when the list of child DOM nodes changes @property childrenChangedAction @type {String} @default null */ childrenChangedAction: null, /** Gets or sets the scrollTop by percentage (decimal) of scrollHeight @property scrollTopPercentage @type {Number} */ scrollTopPercentage: function(key, value) { if(arguments.length > 1) { this._scrollTopPercentage = value; } return this._scrollTopPercentage; }.property().volatile(), _childMutationObserver: null, _setupChildMutationObserver: function() { var handler = function(e) { var context = this.createActionContext(e); this.sendAction('childrenChangedAction', context); this.sendAction('changeAction', context); }.bind(this); this._childMutationObserver = new MutationObserver(handler); this._childMutationObserver.observe(this.get('element'), { childList: true, subtree: true }); // trigger initial event handler(); }.on('didInsertElement'), _teardownChildMutationObserver: function(){ if(this._childMutationObserver) { this._childMutationObserver.disconnect(); } }.on('willDestroyElement'), _updateScrollTop: function(){ var element = this.get('element'); if(element) { var scrollTop = this.get('scrollTopPercentage') * (element.scrollHeight - this.$().outerHeight()); this.set('scrollTop', scrollTop); } }.observes('scrollTopPercentage').on('didInsertElement'), /** Gets or sets the scrollTop of the area @property scrollTop @type {Number} @default 0 */ scrollTop: function(key, value){ if(arguments.length > 1) { this._scrollTop = value; } return this._scrollTop; }.property().volatile(), _updateScroll: function(){ if(this.get('element')) { this.$().scrollTop(this.get('scrollTop')); } }.observes('scrollTop').on('didInsertElement'), /** The optional action data to send with the action contextl @property actionData @type Any @default null */ actionData: null, _onScroll: function(e){ var context = this.createActionContext(e); this._scrollTop = e.scrollTop; this._scrollTopPercentage = e.scrollTop / e.scrollHeight; this.trigger('didScroll', context); this.sendAction('scrollAction', context); this.sendAction('changeAction', context); }, _onResize: function(e) { var context = this.createActionContext(e); this._scrollTop = e.scrollTop; this._scrollTopPercentage = e.scrollTop / e.scrollHeight; this.trigger('didResize', context); this.sendAction('resizeAction', context); this.sendAction('changeAction', context); }, /** Creates an action context to send with an action @method createActionContext @param e {Event} the original event object if there is one @return {utils.nf.scroll-area-action-context} */ createActionContext: function(e){ var elem = this.$(); var context = { width: elem.width(), height: elem.height(), scrollLeft: elem.scrollLeft(), scrollTop: elem.scrollTop(), scrollWidth: elem[0].scrollWidth, scrollHeight: elem[0].scrollHeight, outerWidth: elem.outerWidth(), outerHeight: elem.outerHeight() }; context.data = this.get('actionData'); context.source = this; context.originalEvent = e; return ScrollAreaActionContext.create(context); }, _setupElement: function() { var elem = this.get('element'); if(elem) { elem.addEventListener('scroll', this._onScroll.bind(this)); elem.addEventListener('resize', this._onResize.bind(this)); } }.on('didInsertElement'), _unsubscribeEvents: function(){ var elem = this.get('element'); if(elem) { elem.removeEventListener('scroll', this._onScroll); elem.removeEventListener('resize', this._onResize); } }.on('willDestroyElement'), });
abarax/ember-cli-nf-graph
app/components/nf-scroll-area.js
JavaScript
apache-2.0
4,579
"use strict"; var fs = require("fs"); var path = require("path"); var env = process.env.NODE_ENV || "development"; var controllers = {}; fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf(".") !== 0) && (file !== "index.js"); }) .forEach(function(file) { var controller = require(path.join(__dirname, file)); controllers[controller.name] = controller; }); module.exports = controllers;
josegomezr/HAngulorRating
controllers/index.js
JavaScript
apache-2.0
456
define(["rdflib-pg-extension"], function(rdflibPg) { // TODO how to externalize this store configuration??? var fetcherTimeout = 4000; // $rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate = "https://www.stample.io/srv/cors?url="; $rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate = "http://localhost:9000/srv/cors?url="; //$rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate = "http://data.fm/proxy?uri="; var getDomainRoot = function() { console.log(window.location) return window.location.origin; }; // Proxy to work on sub-domains. $rdf.Fetcher.homeServer = getDomainRoot(); var store = rdflibPg.createNewStore(fetcherTimeout); console.debug("global RdfStore created",store); return store; });
read-write-web/react-foaf
js/scripts/globalRdfStore.js
JavaScript
apache-2.0
775
/** * @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 * * 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. */ CLASS({ package: 'foam.graphics.webgl.flat', name: 'Object', extendsModel: 'foam.graphics.webgl.core.Object', requires: [ 'foam.graphics.webgl.core.ArrayBuffer', 'foam.graphics.webgl.core.Shader', 'foam.graphics.webgl.core.Program', 'foam.graphics.webgl.matrix.ScaleMatrix4', 'foam.graphics.webgl.matrix.StackMatrix4', 'foam.graphics.webgl.matrix.TransMatrix4', ], properties: [ { name: 'texture' }, { name: 'textureCoords' }, { name: 'width', defaultValue: 10, }, { name: 'height', defaultValue: 10, }, { name: 'meshMatrix', lazyFactory: function() { var sc = this.ScaleMatrix4.create(); Events.map(this.width$, sc.sx$, function(v) { return v; }); Events.map(this.height$, sc.sy$, function(v) { return -v; }); Events.map(this.width$, sc.sz$, function(v) { return v; }); return this.StackMatrix4.create({ stack: [ this.TransMatrix4.create({ y: -1 }), sc ]}); } }, { name: 'shapeName', defaultValue: 'flatUnitRectangle', postSet: function() { this.mesh = this.glMeshLibrary.getMesh(this.shapeName); this.meshNormals = this.glMeshLibrary.getNormals(this.shapeName); this.textureCoords = this.mesh; } }, ], methods: [ function init() { this.SUPER(); this.shapeName = this.shapeName; this.program = this.Program.create(); this.program.fragmentShader = this.Shader.create({ type: "fragment", source: function() {/* precision mediump float; varying vec3 vNormal; varying vec3 vPosition; varying vec2 vTextureCoord; uniform sampler2D uSampler; void main(void) { vec4 texel = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)); if(texel.a < 0.01) discard; vec4 dark = vec4(0.0, 0.0, 0.0, 1.0); vec3 uLight = vec3(-10, -10, 15); // Mix in diffuse light float diffuse = dot(normalize(uLight), normalize(vNormal)); diffuse = max(0.0, diffuse); gl_FragColor = mix(dark, texel, 0.5 + 0.9 * diffuse); } */}, }); this.program.vertexShader = this.Shader.create({ type: "vertex", source: function() {/* attribute vec3 aVertexPosition; attribute vec3 aTexPosition; attribute vec3 aNormal; uniform mat4 positionMatrix; uniform mat4 relativeMatrix; uniform mat4 projectionMatrix; uniform mat4 meshMatrix; uniform mat4 normalMatrix; varying vec2 vTextureCoord; varying vec3 vNormal; varying vec3 vPosition; void main(void) { mat4 matrix = projectionMatrix * positionMatrix * relativeMatrix * meshMatrix; vNormal = vec3(normalMatrix * vec4(aNormal, 1.0)); vPosition = vec3(matrix * vec4(aVertexPosition, 1.0)); gl_Position = matrix * vec4(aVertexPosition, 1.0); vTextureCoord = vec2(aTexPosition.x, aTexPosition.y); } */} }); }, function textureSource() { /* return the image or video element to extract the texture from */ }, function render() { var gl = this.gl; if ( ! gl ) return; // Create a texture object that will contain the image. if ( ! this.texture ) { this.texture = gl.createTexture(); } // Bind the texture the target (TEXTURE_2D) of the active texture unit. gl.bindTexture(gl.TEXTURE_2D, this.texture); // Flip the image's Y axis to match the WebGL texture coordinate space. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); //gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // Upload the resized canvas image into the texture. // Note: a canvas is used here but can be replaced by an image object. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.textureSource()); }, function paintSelf(translucent) { if ( this.translucent !== translucent ) return; var gl = this.gl; if ( ! gl || ! this.texture ) return; this.program.use(); var sampler = gl.getUniformLocation(this.program.program, "uSampler"); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.uniform1i(sampler, 0); // attribute vars this.textureCoords.bind(); var texPositionAttribute = this.gl.getAttribLocation(this.program.program, "aTexPosition"); this.gl.vertexAttribPointer(texPositionAttribute, 3, gl.FLOAT, false, 0, 0); this.gl.enableVertexAttribArray(texPositionAttribute); this.SUPER(translucent); }, ] });
osric-the-knight/foam
js/foam/graphics/webgl/flat/Object.js
JavaScript
apache-2.0
5,891
var app_token = process.argv[2]; var private_key = process.argv[3]; var Ziggeo = require("../index.js"); var ZiggeoSdk = new Ziggeo(app_token, private_key); console.log('Start fetching video tokens '); // 'limit' will limit how much index operation will fetch the videos. default 50 max 100 ZiggeoSdk.Videos.index({limit:100}, { success: function (index) { var video_counter = 0; if (index.length > 0) { for (var i = 0; i < index.length; ++i) { // iterate fetched result console.log(index[i]); } } }, failure: function (args, error) { console.log("failed: " + error); return false; } });
Ziggeo/ZiggeoNodeSdk
demos/video_index.js
JavaScript
apache-2.0
614
/* Copyright (c) 2004-2016, The JS Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/has",["require","module"],function(g,h){var a=g.has||function(){};a.add("dom-addeventlistener",!!document.addEventListener);a.add("touch","ontouchstart"in document||"onpointerdown"in document&&0<navigator.maxTouchPoints||window.navigator.msMaxTouchPoints);a.add("touch-events","ontouchstart"in document);a.add("pointer-events","pointerEnabled"in window.navigator?window.navigator.pointerEnabled:"PointerEvent"in window);a.add("MSPointer",window.navigator.msPointerEnabled);a.add("device-width", screen.availWidth||innerWidth);var b=document.createElement("form");a.add("dom-attributes-explicit",0==b.attributes.length);a.add("dom-attributes-specified-flag",0<b.attributes.length&&40>b.attributes.length);a.clearElement=function(a){a.innerHTML="";return a};a.normalize=function(c,b){var d=c.match(/[\?:]|[^:\?]*/g),f=0,e=function(c){var b=d[f++];if(":"==b)return 0;if("?"==d[f++]){if(!c&&a(b))return e();e(!0);return e(c)}return b||0};return(c=e())&&b(c)};a.load=function(a,b,d){a?b([a],d):d()};return a}); //# sourceMappingURL=has.js.map
Caspar12/zh.sw
zh.web.site.admin/src/main/resources/static/js/dojo/dojo/has.js
JavaScript
apache-2.0
1,254
(function() { 'use strict'; angular.module('app.components') .directive('footerContent', FooterContentDirective); /** @ngInject */ function FooterContentDirective() { var directive = { restrict: 'AE', replace: true, scope: {}, link: link, templateUrl: 'app/components/footer/footer-content.html', controller: FooterController, controllerAs: 'vm', bindToController: true, }; return directive; function link(scope, element, attrs, controller, transclude) { controller.activate(); } /** @ngInject */ function FooterController(Navigation) { var vm = this; vm.activate = activate; vm.dateTime = new Date(); function activate() { } } } })();
dtaylor113/manageiq-ui-self_service
client/app/components/footer/footer-content.directive.js
JavaScript
apache-2.0
773
alert("dom.js wurde geladen!")
hasselbach/ec2016-ein-leben-ohne-notesclient
JavaFX/src/ec2016/demo05/application/dom.js
JavaScript
apache-2.0
30
Titanium.UI.setBackgroundImage('bg.png'); //creating a complete group for footer navigation /*var tabGroup = Titanium.UI.createTabGroup(); //first tab is for home var homeWindow = Titanium.UI.createWindow({ title:'Phoughts', url:'phoughtsList.js', backgroundImage : 'bg.png', navBarHidden:true }); var homeTab = Titanium.UI.createTab({ icon : 'homeicon.png', backgroundImage : 'naviconbg.png', title : 'Home', window : homeWindow, }); //second tab is for Memex var memexWindow = Titanium.UI.createWindow({ url:'memexList.js', title:'Memex', }); var memexTab = Titanium.UI.createTab({ icon : 'memicon.png', backgroundImage : 'naviconbg.png', title : 'Memex', window : memexWindow, }); //Third tab is for Connection var connectionWindow = Titanium.UI.createWindow({ url:'connectionList.js', title:'Connection', }); var connectionTab = Titanium.UI.createTab({ icon : 'connectionicon.png', backgroundImage : 'naviconbg.png', title : 'Connections', window : connectionWindow, }); //Fourth tab is for Chat var chatWindow = Titanium.UI.createWindow({ url:'chat.js', title:'Chat', }); var chatTab = Titanium.UI.createTab({ icon : 'chaticon.png', backgroundImage : 'naviconbg.png', title : 'Chat', window : chatWindow, }); tabGroup.addTab(homeTab); tabGroup.addTab(memexTab); tabGroup.addTab(connectionTab); tabGroup.addTab(chatTab); tabGroup.open();*/ Ti.API.info("home.js");
crystal520/fb
Resources_phinkit/home.js
JavaScript
apache-2.0
1,418
/* ============================================================= * bootstrap-collapse.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, 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. * ============================================================ */ /* Modified for use with PrototypeJS http://github.com/jwestbrook/bootstrap-prototype */ "use strict"; if(BootStrap === undefined) { var BootStrap = {}; } /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ BootStrap.Collapse = Class.create({ initialize : function (element, options) { this.$element = $(element) element.store('bootstrap:collapse',this) this.options = { toggle: true } Object.extend(this.options,options) if (this.options.parent) { this.$parent = $(this.options.parent) } var dimension = this.dimension() if(this.$element.style[dimension] === 'auto') { var scroll = ['scroll', dimension].join('-').camelize() this.reset(this.$element[scroll]+'px') } this.options.toggle && this.toggle() } , dimension: function () { var hasWidth = this.$element.hasClassName('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning) return dimension = this.dimension() scroll = ['scroll', dimension].join('-').camelize() actives = this.$parent && this.$parent.select('> .accordion-group > .in') if (actives && actives.length) { actives.each(function(el){ var bootstrapobject = el.retrieve('bootstrap:collapse') if (bootstrapobject && bootstrapobject.transitioning) return bootstrapobject.hide() }); } var newstyle = {} newstyle[dimension] = '0px' this.$element.setStyle(newstyle) this.transition('addClassName', 'show', 'bootstrap:shown') if(BootStrap.handleeffects == 'css'){ newstyle = {} newstyle[dimension] = this.$element[scroll]+'px' // newstyle[dimension] = 'auto' this.$element.setStyle(newstyle) } else if(BootStrap.handleeffects == 'effect' && typeof Effect !== 'undefined' && typeof Effect.BlindDown !== 'undefined'){ this.$element.blindDown({duration:0.5,afterFinish:function(effect){ // effect.element[method]('in') newstyle = {} newstyle[dimension] = this.$element[scroll]+'px' this.$element.setStyle(newstyle) }.bind(this)}) /* this.$element[dimension](this.$element[scroll] */ } } , hide: function () { var dimension if (this.transitioning) return dimension = this.dimension() this.reset(this.$element.getStyle(dimension)) this.transition('removeClassName', 'hide', 'bootstrap:hidden') this.reset('0px') if(BootStrap.handleeffects == 'effect' && typeof Effect !== 'undefined' && Effect.Queues.get('global').effects.length === 0) { var newstyle = {} newstyle[dimension] = '0px' this.$element.setStyle(newstyle) } } , reset: function (size) { var dimension = this.dimension() this.$element .removeClassName('collapse') var newstyle = {} newstyle[dimension] = size this.$element.setStyle(newstyle) this.$element[size !== null ? 'addClassName' : 'removeClassName']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent == 'show') this.reset() this.transitioning = 0 this.$element.fire(completeEvent) }.bind(this) var startEventObject = this.$element.fire('bootstrap:'+startEvent) if(startEventObject.defaultPrevented) return this.transitioning = 1 if(BootStrap.handleeffects == 'css' && this.$element.hasClassName('collapse')){ this.$element.observe(BootStrap.transitionendevent, complete) this.$element[method]('in') } else if(startEvent == 'hide' && BootStrap.handleeffects == 'effect' && typeof Effect !== 'undefined' && typeof Effect.BlindUp !== 'undefined') { this.$element.blindUp({duration:0.5,afterFinish:function(effect){ var dimension = this.dimension() effect.element[method]('in') var newstyle = {} newstyle[dimension] = '0px' this.$element.setStyle(newstyle) complete() }.bind(this)}) } else if(startEvent == 'show' && BootStrap.handleeffects == 'effect' && typeof Effect !== 'undefined' && typeof Effect.BlindUp !== 'undefined') { this.$element.blindDown({duration:0.5,beforeStart:function(effect){ var dimension = this.dimension() effect.element[method]('in') var newstyle = {} newstyle[dimension] = 'auto' this.$element.setStyle(newstyle) effect.element.hide() }.bind(this),afterFinish:function(effect){ complete() }.bind(this)}) } else { complete() this.$element[method]('in') } } , toggle: function () { this[this.$element.hasClassName('in') ? 'hide' : 'show']() } }); /*domload*/ document.observe('dom:loaded',function(){ $$('[data-toggle="collapse"]').each(function(e){ var href = e.readAttribute('href'); href = e.hasAttribute('href') ? href.replace(/.*(?=#[^\s]+$)/, '') : null var target = e.readAttribute('data-target') || href , options = {toggle : false} if(e.hasAttribute('data-parent')){ options.parent = e.readAttribute('data-parent').replace('#','') } target = $$(target).first() if(target.hasClassName('in')){ e.addClassName('collapsed') } else { e.removeClassName('collapsed') } new BootStrap.Collapse(target,options) }); document.on('click','[data-toggle="collapse"]',function(e,targetelement){ var href = targetelement.readAttribute('href'); href = targetelement.hasAttribute('href') ? href.replace(/.*(?=#[^\s]+$)/, '') : null var target = targetelement.readAttribute('data-target') || e.preventDefault() || href $$(target).first().retrieve('bootstrap:collapse').toggle(); }); });
jwestbrook/bootstrap-prototype
js/bootstrap-collapse_prototype.js
JavaScript
apache-2.0
6,440
/************************************************* * Copyright (c) 2015 Ansible, Inc. * * All Rights Reserved *************************************************/ /** * This is the list definition for the notification templates list * off of the settings page */ export default ['i18n', function(i18n){ return { name: 'notification_templates' , listTitle: i18n._('NOTIFICATION TEMPLATES'), iterator: 'notification_template', index: false, hover: false, fields: { status: { label: '', iconOnly: true, nosort: true, icon: 'icon-job-{{ notification_template.status }}', awPopOver: '{{ notification_template.template_status_html }}', dataTitle: i18n._("Recent Notifications"), dataPlacement: 'right', columnClass: 'col-lg-1 col-md-1 col-sm-2 col-xs-2 List-staticColumn--smallStatus' }, name: { key: true, label: i18n._('Name'), columnClass: 'col-md-3 col-sm-9 col-xs-9', linkTo: '/#/notification_templates/{{notification_template.id}}', awToolTip: '{{notification_template.description | sanitize}}', dataPlacement: 'top' }, notification_type: { label: i18n._('Type'), ngBind: "notification_template.type_label", searchType: 'select', searchOptions: [], excludeModal: true, columnClass: 'col-md-4 hidden-sm hidden-xs' } }, actions: { add: { mode: 'all', // One of: edit, select, all ngClick: 'addNotification()', awToolTip: i18n._('Create a new notification template'), actionClass: 'at-Button--add', actionId: 'button-add', ngShow: 'canAdd' } }, fieldActions: { columnClass: 'col-md-2 col-sm-3 col-xs-3', edit: { ngClick: "editNotification(notification_template.id)", icon: 'fa-edit', label: i18n._('Edit'), "class": 'btn-sm', awToolTip: i18n._('Edit notification'), dataPlacement: 'top', ngShow: 'notification_template.summary_fields.user_capabilities.edit' }, test: { ngClick: "testNotification(notification_template.id)", icon: 'fa-bell-o', label: i18n._('Edit'), "class": 'btn-sm', awToolTip: i18n._('Test notification'), dataPlacement: 'top', ngShow: 'notification_template.summary_fields.user_capabilities.edit' }, copy: { label: i18n._('Copy'), ngClick: 'copyNotification(notification_template)', "class": 'btn-danger btn-xs', awToolTip: i18n._('Copy notification'), dataPlacement: 'top', ngShow: 'notification_template.summary_fields.user_capabilities.copy' }, view: { ngClick: "editNotification(notification_template.id)", label: i18n._('View'), "class": 'btn-sm', awToolTip: i18n._('View notification'), dataPlacement: 'top', ngShow: '!notification_template.summary_fields.user_capabilities.edit' }, "delete": { ngClick: "deleteNotification(notification_template.id, notification_template.name)", icon: 'fa-trash', label: i18n._('Delete'), "class": 'btn-sm', awToolTip: i18n._('Delete notification'), dataPlacement: 'top', ngShow: 'notification_template.summary_fields.user_capabilities.delete' } } }; }];
wwitzel3/awx
awx/ui/client/src/notifications/notificationTemplates.list.js
JavaScript
apache-2.0
4,120
import React from 'react' import PropTypes from 'prop-types' import {compose} from 'recompose' import Table from 'react-bootstrap/lib/Table' import {FormattedMessage} from 'react-intl' import mapKeys from 'lodash/mapKeys' import camelCase from 'lodash/camelCase' import AccountLink from './shared/AccountLink' import FormattedAmount from './shared/FormattedAmount' import Asset from './shared/Asset' import {withDataFetchingContainer} from './shared/DataFetchingContainer' import {withDataFetchingAllContainer} from './shared/DataFetchingAllContainer' import {withPaging} from './shared/Paging' import {withSpinner} from './shared/Spinner' import TimeSynchronisedFormattedRelative from './shared/TimeSynchronizedFormattedRelative' import CSVExport from './shared/CSVExport' import {isPublicKey} from '../lib/stellar/utils' const Trade = ({account, singleAccountView, trade, parentRenderTimestamp}) => { const Base = ( <span> <FormattedAmount amount={trade.baseAmount} />{' '} <Asset code={trade.baseAssetCode} issuer={trade.baseAssetIssuer} type={trade.baseAssetType} /> </span> ) const Counter = ( <span> <FormattedAmount amount={trade.counterAmount} />{' '} <Asset code={trade.counterAssetCode} issuer={trade.counterAssetIssuer} type={trade.counterAssetType} /> </span> ) let baseFirst let account1, account2 if (singleAccountView) { const accountIsBase = account === trade.baseAccount baseFirst = !accountIsBase // account's bought asset first account1 = account account2 = accountIsBase ? trade.counterAccount : trade.baseAccount } else { baseFirst = trade.baseIsSeller account1 = trade.baseAccount account2 = trade.counterAccount } return ( <tr key={trade.id} className="trade"> <td> <span className="account-badge"> <AccountLink account={account1} /> </span> </td> <td>{baseFirst ? Base : Counter}</td> <td> <span className="account-badge"> <AccountLink account={account2} /> </span> </td> <td>{baseFirst ? Counter : Base}</td> <td> <span title={trade.time}> <TimeSynchronisedFormattedRelative initialNow={parentRenderTimestamp} value={trade.time} /> </span> </td> </tr> ) } Trade.propTypes = { parentRenderTimestamp: PropTypes.number, trade: PropTypes.shape({ id: PropTypes.string.isRequired, baseIsSeller: PropTypes.bool.isRequired, baseAccount: PropTypes.string.isRequired, counterAccount: PropTypes.string.isRequired, time: PropTypes.string.isRequired, }).isRequired, account: PropTypes.string, singleAccountView: PropTypes.bool, } class TradeTable extends React.Component { componentDidMount() { if (this.props.page === 0 && this.props.records.length < this.props.limit) { this.props.hidePagingFn() } } render() { const {server, parentRenderTimestamp, account, records} = this.props if (records.length === 0) return <div style={{marginTop: 20, marginBottom: 20}}>No Trades</div> const singleAccountView = isPublicKey(account) return ( <div> <Table id="trade-table" className="table-striped table-hover table-condensed" > <thead> <tr> <th> <FormattedMessage id="account" /> {' 1'} </th> <th> <FormattedMessage id="bought" /> </th> <th> <FormattedMessage id="account" /> {' 2'} </th> <th> <FormattedMessage id="bought" /> </th> <th> <FormattedMessage id="time" /> </th> </tr> </thead> <tbody> {records.map(trade => ( <Trade key={trade.id} trade={trade} account={account} singleAccountView={singleAccountView} parentRenderTimestamp={parentRenderTimestamp} /> ))} </tbody> </Table> <div className="text-center" id="csv-export"> <ExportToCSVComponent account={account} server={server} /> </div> </div> ) } } TradeTable.propTypes = { parentRenderTimestamp: PropTypes.number, records: PropTypes.array.isRequired, server: PropTypes.object.isRequired, account: PropTypes.string, accountView: PropTypes.bool, } const rspRecToPropsRec = record => { record.time = record.ledger_close_time return mapKeys(record, (v, k) => camelCase(k)) } const fetchRecords = ({account, limit, server}) => { const builder = server.trades() if (account) builder.forAccount(account) builder.limit(limit) builder.order('desc') return builder.call() } const callBuilder = props => props.server.trades() const ExportToCSVComponent = withDataFetchingAllContainer( fetchRecords, callBuilder )(CSVExport) const enhance = compose( withPaging(), withDataFetchingContainer(fetchRecords, rspRecToPropsRec, callBuilder), withSpinner() ) export default enhance(TradeTable)
chatch/stellarexplorer
src/components/TradeTable.js
JavaScript
apache-2.0
5,322
define(["dojo/_base/declare", "dojo/_base/lang", "dojo/Deferred", "dojo/request"], function(declare, lang, Deferred, dojoRequest) { var oThisClass = declare(null, { constructor: function(args) { lang.mixin(this,args); }, appendAccessToken: function(url) { var accessToken = this.getAccessToken(); if (accessToken) { if (url.indexOf("?") === -1) url += "?"; else url += "&"; url += "access_token="+encodeURIComponent(accessToken); } return url; }, checkError: function(error) { if (error && error.response && error.response.data && error.response.data.error) { return error.response.data.error; } }, getAccessToken: function() { var tkn = AppContext.appUser.appToken; if (tkn && tkn.access_token) return tkn.access_token; return null; }, getBaseUri: function() { return "."; }, getRestUri: function() { return "./rest"; }, /* ===================================================================== */ bulkChangeOwner: function(owner,newOwner) { var url = this.getRestUri()+"/metadata/bulk/changeOwner"; url += "?owner="+encodeURIComponent(owner); url += "&newOwner="+encodeURIComponent(newOwner); url = this.appendAccessToken(url); var info = {handleAs:"json"}; return dojoRequest.put(url,info); }, changeOwner: function(id,newOwner) { var url = this.getRestUri()+"/metadata/item/"; url += encodeURIComponent(id)+"/owner/"+encodeURIComponent(newOwner); url = this.appendAccessToken(url); var info = {handleAs:"json"}; return dojoRequest.put(url,info); }, deleteItem: function(id) { var url = this.getRestUri()+"/metadata/item/"; url += encodeURIComponent(id); url = this.appendAccessToken(url); var info = {handleAs:"json"}; return dojoRequest.del(url,info); }, generateToken: function(username,password) { // TODO needs to be https var url = this.getBaseUri()+"/oauth/token"; var content = { grant_type: "password", client_id: "geoportal-client", username: username, password: password }; var info = {handleAs:"json",data:content,headers:{Accept:"application/json"}}; return dojoRequest.post(url,info); }, pingGeoportal: function(accessToken) { var url = this.getRestUri()+"/geoportal"; var info = {handleAs:"json"}; if (!accessToken) accessToken = this.getAccessToken(); if (accessToken) info.query = {access_token:encodeURIComponent(accessToken)}; return dojoRequest.get(url,info); }, readMetadata: function(itemId) { var url = this.getRestUri()+"/metadata/item"; url += "/"+encodeURIComponent(itemId)+"/xml"; url = this.appendAccessToken(url); var info = {handleAs:"text"}; return dojoRequest.get(url,info); }, uploadMetadata: function(xml,itemId,filename) { var url = this.getRestUri()+"/metadata/item"; if (typeof itemId === "string" && itemId.length > 0) { url += "/"+encodeURIComponent(itemId); } url = this.appendAccessToken(url); if (typeof filename === "string" && filename.length > 0) { if (url.indexOf("?") === -1) url += "?"; else url += "&"; url += "filename="+encodeURIComponent(filename); } var headers = {"Content-Type": "application/xml"}; var info = {handleAs:"json",headers:headers,data:xml}; return dojoRequest.put(url,info); } }); return oThisClass; });
usgin/geoportal-server-catalog
geoportal/src/main/webapp/app/context/AppClient.js
JavaScript
apache-2.0
3,687
const qiniu = require("qiniu"); const proc = require("process"); var bucket = 'if-pbl'; var accessKey = proc.env.QINIU_ACCESS_KEY; var secretKey = proc.env.QINIU_SECRET_KEY; var mac = new qiniu.auth.digest.Mac(accessKey, secretKey); var options = { scope: bucket, } var putPolicy = new qiniu.rs.PutPolicy(options); var uploadToken = putPolicy.uploadToken(mac); var config = new qiniu.conf.Config(); var localFile = "/Users/jemy/Documents/qiniu.mp4"; config.zone = qiniu.zone.Zone_z0; config.useCdnDomain = true; var resumeUploader = new qiniu.resume_up.ResumeUploader(config); var putExtra = new qiniu.resume_up.PutExtra(); putExtra.params = { "x:name": "", "x:age": 27, } putExtra.fname = 'testfile.mp4'; putExtra.resumeRecordFile = 'progress.log'; putExtra.progressCallback = function(uploadBytes, totalBytes) { console.log("progress:" + uploadBytes + "(" + totalBytes + ")"); } //file resumeUploader.putFile(uploadToken, null, localFile, putExtra, function(respErr, respBody, respInfo) { if (respErr) { throw respErr; } if (respInfo.statusCode == 200) { console.log(respBody); } else { console.log(respInfo.statusCode); console.log(respBody); } });
wkmnet/admin-frontend
node_modules/qiniu/examples/resume_upload_simple.js
JavaScript
apache-2.0
1,192
var app = angular.module("application", ['ngRoute']); app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider.when('/', { templateUrl: '/public/html/views/home.html', controller: 'homeController' }); $routeProvider.when('/p', { templateUrl: '/public/html/views/userHome.html', controller: 'userHomeController' }); $locationProvider.html5Mode(true); } ]); //var controller = angular.module('controller', []); /*.when('/p', { templateUrl: '/public/html/templates/userHome.html', controller: 'userHomeController' });*/
pollend/BonAppeSEEKServer
server/public/js/main.js
JavaScript
apache-2.0
687