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
export { default } from 'ember-a11y/components/focusing-outlet';
ember-a11y/ember-a11y
app/components/focusing-outlet.js
JavaScript
mit
65
var url = ajaxurl; var controller = "advancerulesets"; var option = "com_ose_firewall"; jQuery(document).ready(function($){ var rulesetsDataTable = $('#AdvrulesetsTable').dataTable( { processing: true, serverSide: true, ajax: { url: url, type: "POST", data: function ( d ) { d.option = option; d.controller = controller; d.action = 'getRulesets'; d.task = 'getRulesets'; d.centnounce = $('#centnounce').val(); } }, columns: [ { "data": "id" }, { "data": "description" }, { "data": "attacktype" }, { "data": "impact" }, { "data": "action" }, { "data": "checkbox", sortable: false } ] }); $('#AdvrulesetsTable tbody').on( 'click', 'tr', function () { $(this).toggleClass('selected'); }); $('#checkedAll').on('click', function() { $('#AdvrulesetsTable').dataTable().api().rows() .nodes() .to$() .toggleClass('selected'); }) var statusFilter = $('<label>Status: <select name="statusFilter" id="statusFilter"><option value="-1"></option><option value="1">Active</option><option value="0">InActive</option></select></label>'); statusFilter.appendTo($("#AdvrulesetsTable_filter")).on( 'change', function () { var val = $('#statusFilter'); rulesetsDataTable.api().column(4) .search( val.val(), false, false ) .draw(); }); }); function changeItemStatus(id, status) { AppChangeItemStatus(id, status, '#AdvrulesetsTable', 'changeRuleStatus'); } /* var controller = "advancerulesets"; Ext.ns('oseATH', 'oseadantihackerRulesets'); function changeItemStatus(id, status) { Ext.Msg.confirm(O_CHANGE_FIREWALL_STATUS, O_CHANGE_FIREWALL_STATUS_DESC, function(btn, text){ if (btn == 'yes'){ oseChangeItemStatus(url, option, controller, 'changeRuleStatus', id, status, oseadantihackerRulesets.store); } }); } function installDB () { var win = oseGetWIn('advRulesinstaller', 'Checking Subscription Status', 900, 650); win.show(); win.update('Checking Subscription Status'); getRules (win); } function getRules (win) { Ext.Ajax.request({ url : url, params : { option : option, controller: controller, task: 'checkAPI', action: 'checkAPI' }, method: 'POST', success: function ( response, options ) { var msg = Ext.decode(response.responseText); if (msg.paid==false) { win.update(msg.message + '<br/>' + msg.refund + '<br/>' + msg.form + '<br/>' + msg.form2 + '<br/>' + msg.form3); } else { win.update(msg.message); } } }); } oseadantihackerRulesets.attacktypefields = new Array('id', 'name'); oseadantihackerRulesets.attacktypeStore = oseGetStore('attacktypeStore', oseadantihackerRulesets.attacktypefields, url, option, controller, 'getAttackTypes'); oseadantihackerRulesets.statusOption = oseGetRuleStatusOptions(); oseadantihackerRulesets.fields = new Array('id', 'description', 'attacktype', 'action'); oseadantihackerRulesets.store = oseGetStore('rulesets', oseadantihackerRulesets.fields, url, option, controller, 'getRulesets'); oseadantihackerRulesets.form = Ext.create('Ext.form.Panel', { bodyStyle : 'padding: 10px; padding-left: 20px', autoScroll : true, autoWidth : true, border : false, labelAlign : 'left', labelWidth : 150, buttons : [ { text : 'Save', handler : function() { oseFormSubmit(oseadantihackerRulesets.form, url, option, controller, 'addruleset', oseadantihackerRulesets.store, 'Please wait, this will take a few seconds ...'); } } ], items : [ oseGetNormalTextField('filter', O_FILTER, 100, 350, null), oseGetNormalTextField('impactfield', O_IMPACT, 100, 200, null), oseGetNormalTextArea('descriptionfield', O_DESCRIPTION, 100, 350), oseGetNormalMultiSelect('attacktype_select', O_ATTACKTYPE, 100, 350, oseadantihackerRulesets.attacktypeStore, 'id', 'name'), oseGetCombo('statusfield', O_STATUS, oseGetRuleStatusOptions(), 350, 100, 100, 1) ] }); oseadantihackerRulesets.panel = new Ext.grid.GridPanel({ id : 'oseadantihackerRulesets', name : 'oseadantihackerRulesets', selType : 'rowmodel', columns : [ { id : 'id', header : O_ID, hidden : false, dataIndex : 'id', width : '4.5%', sortable : true }, { id : 'rule', header : O_RULE, hidden : false, dataIndex : 'description', width : '55%', sortable : true }, { id : 'attacktype', header : O_ATTACKTYPE, hidden : false, dataIndex : 'attacktype', width : '30%', sortable : true }, { id : 'impact', header : O_IMPACT, hidden : false, dataIndex : 'impact', width : '4.5%', sortable : true }, { id : 'action', header : O_STATUS, hidden : false, dataIndex : 'action', width : '4.5%', sortable : true } ], sortInfo : { field : 'id', direction : "ASC" }, store : oseadantihackerRulesets.store, renderTo : 'oseadantihackerRulesets', height : 500, tbar : new Ext.Toolbar({ items : [ { xtype:'displayfield', value: O_LATEST_SIGNATURE, hideLabel: true }, { id: 'getRules', text: O_GET_RULES, handler: function(){ installDB(); } }, '->', oseGetStatusFilter(oseadantihackerRulesets) ] }), bbar : oseGetPaginator(oseadantihackerRulesets) }); */
joshuazhu/bedrocktest
ose-firewall/public/js/advancerulesets.js
JavaScript
mit
5,528
/** * This file contains all the logic for the game from the moment you are pressing "PLAY" */ import async from 'async'; import { Howl } from 'howler'; import SpotifyAPI from './SpotifyAPI' let sig; /** * Initiates the whole game and starts the selected playlist * * @param playlist playlist to play * @param signal signal to play in between the songs */ export default class Game { constructor(mPlayer, mStartProgressbar) { this.player = mPlayer; this.startProgressbar = mStartProgressbar; this.pausePlayback = this.pausePlayback.bind(this); this.nextSong = this.nextSong.bind(this); this.playSignal = this.playSignal.bind(this); this.fadeIn = this.fadeIn.bind(this); this.resumePlayback = this.resumePlayback.bind(this);this.sig; } start(playlist, signal, gameDuration, trackTime, playNextSong) { let startTimer = this.startTimer; let pauseSong = this.pausePlayback; let playSignal = this.playSignal; let nextSong = this.nextSong; let resumePlayback = this.resumePlayback; let startGame = () => { let count = 0; sig = signal; async.whilst( function () { return count < (gameDuration)/trackTime; }, function (callback) { startTimer(trackTime, signal.length).then((response) => { console.debug(response.message); console.debug('Running pause, play and next'); async.waterfall([ pauseSong, playSignal, playNextSong ? nextSong : resumePlayback ], function (err, result) { if (err) console.error(err); else { count++; console.debug('Count: ' + count); callback(null, count); } }) }); } ) }; this.startPlaylist(playlist, startGame); } startPlaylist(playlist, callback) { this.startProgressbar(); // Plays first track in playlist SpotifyAPI.play(playlist.uri, () => { callback(); console.log('Started playlist: "' + playlist.name + '"') }); } nextSong(status, callback) { let seek = 45 * 1000; this.startProgressbar(); this.player.nextTrack().then(() => { console.log("Next song..."); this.player.seek(seek).then(() => { console.debug("Seeking " + seek/1000 + "s"); this.fadeIn().then(() => { callback(null, 'done'); }) }) }); } resumePlayback(status, callback) { this.player.resume().then(() => { console.log("Resuming playback..."); this.fadeIn().then(() => { callback(null, 'done'); }) }) } pausePlayback(callback) { this.player.pause().then(() => { console.log("Paused music...") callback(null, 'done'); }) } startTimer(trackTime, signalLength) { console.debug("Starting timer"); return new Promise(function (resolve, reject) { setTimeout(() => { resolve({message: `Waited ${trackTime} seconds...`}); }, (trackTime)) }); } playSignal(res, callback) { let audio = new Howl({ src: [sig.url] }); audio.play(); setTimeout(() => { callback(null, 'done'); }, sig.length); } fadeIn() { let player = this.player; return new Promise(function (resolve, reject) { let volume = 0; async.whilst( function () { return volume < 1; }, function (callback) { console.debug("Volume: " + volume); player.setVolume(volume).then(() => { volume += 0.1; setTimeout(() => callback(null, volume), 500); }); }, function (err, n) { console.error(err); resolve(); }); }, ); } }
heekzz/PowerHour
frontend/components/Game.js
JavaScript
mit
4,663
(function() { var requirejsConfig = { paths: { jquery: "lib/jquery", lodash: "lib/lodash", backbone: "lib/backbone", store: "lib/store" }, shim: { jquery: { exports: "$" }, lodash: { exports: "_" }, backbone: { deps: ["jquery", "lodash"], exports: "Backbone" }, store: { exports: "Store" } } }; require.config(requirejsConfig); require(['ready', 'backbone'], function(ready) { console.log("required ready"); ready.init(); }); }());
jgable/chrome-extension-professional
scripts/main.js
JavaScript
mit
507
/* This Source Code Form is subject to the terms of the MIT license * If a copy of the MIT license was not distributed with this file, you can * obtain one at https://raw.github.com/mozilla/butter/master/LICENSE */ define( [ "localized", "core/eventmanager", "util/scrollbars", "ui/widget/tooltip", "ui/widget/textbox", "jquery" ], function( Localized, EventManager, Scrollbars, ToolTip, TextboxWrapper, $ ) { /** * Class: BaseEditor * * Extends a given object to be a BaseEditor, giving it rudamentary editor capabilities * * @param {Object} extendObject: Object to be extended to become a BaseEditor * @param {Butter} butter: An instance of Butter * @param {DOMElement} rootElement: The root element to which the editor's content will be attached * @param {Object} events: Events such as 'open' and 'close' can be defined on this object to be called at the appropriate times */ function BaseEditor( extendObject, butter, rootElement, events ) { EventManager.extend( extendObject ); extendObject.butter = butter; extendObject.rootElement = rootElement; extendObject.parentElement = null; // Used when applyExtraHeadTags is called -- see below var _extraStyleTags = [], _extraLinkTags = [], _colorHexCodes = { "black": "#000000", "silver": "#c0c0c0", "gray": "#808080", "white": "#ffffff", "maroon": "#800000", "red": "#ff00000", "purple": "#800080", "fuchsia": "#ff00ff", "green": "#008000", "lime": "#00ff00", "olive": "#808000", "yellow": "#ffff00", "navy": "#000080", "blue": "#0000ff", "teal": "#008080", "aqua": "#00ffff" }; var _errorMessageContainer; if ( !_errorMessageContainer && rootElement ) { _errorMessageContainer = rootElement.querySelector( "div.error-message" ); } /** * Member: open * * Opens the editor * * @param {DOMElement} parentElement: The element to which the editor's root will be attached */ extendObject.open = function( parentElement ) { extendObject.parentElement = parentElement; // Attach the editor's root element to the given parentElement. // Do this before calling the open event so that element size and structure are defined. extendObject.parentElement.appendChild( extendObject.rootElement ); // Update scrollbars, add one automatically if an allow-scrollbar class is added // See .addScrollbar for manual settings if ( extendObject.scrollbar ) { extendObject.scrollbar.update(); } else if ( extendObject.rootElement.classList.contains( "allow-scrollbar" ) ) { extendObject.addScrollbar(); } // If an open event existed on the events object passed into the constructor, call it if ( events.open ) { events.open.apply( extendObject, arguments ); } // Add tooltips extendObject.addTooltips(); extendObject.dispatch( "open" ); }; /** * Member: close * * Closes the editor */ extendObject.close = function() { // Remove the editor's root element from the element to which it was attached extendObject.rootElement.parentNode.removeChild( extendObject.rootElement ); // If a close event existed on the events object passed into the constructor, call it if ( events.close ) { events.close.apply( extendObject, arguments ); } extendObject.dispatch( "closed" ); }; /** * Member: applyExtraHeadTags * * If a tag that belongs in the <head> is present in the given layout, place it in the document's head. * * @param {DOMFragment} layout: DOMFragment containing the style tag */ extendObject.applyExtraHeadTags = function( layout ) { var linkNodes = layout.querySelectorAll( "link" ), styleNodes = layout.querySelectorAll( "style" ), x; for ( x = 0; x < linkNodes.length; x++ ) { _extraLinkTags[ x ] = linkNodes[ x ]; document.head.appendChild( _extraLinkTags[ x ] ); } for ( x = 0; x < styleNodes.length; x++ ) { _extraStyleTags[ x ] = styleNodes[ x ]; document.head.appendChild( _extraStyleTags[ x ] ); } }; extendObject.attachColorChangeHandler = function( element, trackEvent, propertyName, callback ) { var colorPickerElement = element.querySelector( ".color-picker" ), inputElement = element.querySelector( "input" ), initialValue = inputElement.value, self = this, colorToggle = element.querySelector( ".color-picker-toggle" ), colorPicker = $.farbtastic( colorPickerElement, { callback: function() {}, height: 195, width: 195 }); function validateColorValue( value ) { var message, i; if ( value.indexOf( "#" ) === -1 ) { message = Localized.get( "Invalid Color update" ) + " "; for ( i in _colorHexCodes ) { if ( _colorHexCodes.hasOwnProperty( i ) ) { if ( i === value.toLowerCase() ) { // Valid colour found. return ""; } else { message += i + ", "; } } } return message.substring( 0, message.lastIndexOf( "," ) ) + "."; } else if ( !value.match( /^#(?:[0-9a-fA-F]{3}){1,2}$/ ) ) { return Localized.get( "Invalid Hex Color format" ); } return ""; } function updateColor( value ) { var message = validateColorValue( value ), updateOptions = {}; // This is a valid colour if ( !message ) { inputElement.value = value; if ( _colorHexCodes[ value ] ) { // Colour picker only works with hex values, do not send named colours. colorPicker.setColor( _colorHexCodes[ value ] ); } else { colorPicker.setColor( value ); } colorToggle.style.background = value; self.setErrorState( false ); } updateOptions[ propertyName ] = value; if ( callback ) { callback( trackEvent, updateOptions, message, propertyName ); } else { trackEvent.update( updateOptions ); } } // Set default, but don't fire any callbacks yet. colorPicker.setColor( initialValue ); colorToggle.style.background = initialValue; // Now we can setup the callback. colorPicker.linkTo(function( value ) { if ( inputElement.value !== value ) { updateColor( value ); } }); inputElement.addEventListener( "change", function() { updateColor( inputElement.value ); }, false ); function onMousedown( e ) { e.stopPropagation(); e.preventDefault(); window.removeEventListener( "mousedown", onMousedown, true ); updateColor( inputElement.value ); inputElement.blur(); colorPickerElement.classList.add( "hidden" ); } function onMouseover() { colorPickerElement.removeEventListener( "mouseover", onMouseover, false ); inputElement.removeEventListener( "mouseover", onMouseover, false ); colorPickerElement.addEventListener( "mouseout", onMouseout, false ); inputElement.addEventListener( "mouseout", onMouseout, false ); window.removeEventListener( "mousedown", onMousedown, true ); } function onMouseout() { colorPickerElement.addEventListener("mouseover", onMouseover, false ); inputElement.addEventListener( "mouseover", onMouseover, false ); colorPickerElement.removeEventListener( "mouseout", onMouseout, false ); inputElement.removeEventListener( "mouseout", onMouseout, false ); window.addEventListener( "mousedown", onMousedown, true ); } function onFocus() { colorPickerElement.classList.remove( "hidden" ); } inputElement.addEventListener( "focus", onFocus, false ); colorPickerElement.addEventListener( "mouseover", onMouseover, false ); inputElement.addEventListener( "mouseover", onMouseover, false ); colorToggle.addEventListener( "click", function() { inputElement.focus(); window.addEventListener( "mousedown", onMousedown, true ); inputElement.addEventListener( "mouseout", onMouseout, false ); }, false ); }; /** * Member: addScrollbar * * Creates a scrollbar with the following options: * outer: The outer containing element. ( optional. Default = inner.ParentNode ) * inner: The inner element with the scrollable content. * container: The element to append the scrollbar to. */ extendObject.addScrollbar = function( options ) { var innerDefault = extendObject.rootElement.querySelector( ".scrollbar-inner" ); options = options || innerDefault && { inner: innerDefault, outer: extendObject.rootElement.querySelector( ".scrollbar-outer" ) || innerDefault.parentNode, appendTo: extendObject.rootElement.querySelector( ".scrollbar-container" ) || extendObject.rootElement }; if ( !options ) { return; } extendObject.scrollbar = new Scrollbars.Vertical( options.outer, options.inner ); options.appendTo.appendChild( extendObject.scrollbar.element ); extendObject.scrollbar.update(); return extendObject.scrollBar; }; /** * Member: addTooltips * * Add tooltips to all elements marked data-tooltip */ extendObject.addTooltips = function() { ToolTip.apply( extendObject.rootElement ); }; /** * Member: createTooltip * * Create a tooltip that can be used in any editor. * * @param {DOMElement} element: The element that is being listened to. * @param {Object} options: Configuration options for the tooltip. These include: * name: The name of the Tooltip. * element: The element that the Tooltip bases it's positioning around. * message: The message that's displayed to users. * top: The CSS top position of the Tooltip in relation to element. * left: The CSS left position of the Tooltip in relation to element. * hidden: The Tooltips initial visibility state. * hover: Triggers if the tooltip displays on hover of element. */ extendObject.createTooltip = function( element, options ) { var tooltip; if ( options && options.name ) { ToolTip.create( options ); tooltip = ToolTip.get( options.name ); element.addEventListener( "focus", function() { tooltip.hidden = false; }, false ); element.addEventListener( "blur", function() { tooltip.hidden = true; }, false ); } }; /** * Member: removeExtraHeadTags * * Remove all extra style/link tags that have been added to the document head. */ extendObject.removeExtraHeadTags = function() { var x; for ( x = 0; x < _extraLinkTags.length; x++ ) { document.head.removeChild( _extraLinkTags[ x ] ); } _extraLinkTags = []; for ( x = 0; x < _extraStyleTags.length; x++ ) { document.head.removeChild( _extraStyleTags[ x ] ); } _extraStyleTags = []; }; /** * Member: wrapTextInputElement * * Force element to auto select the text of the element upon click. * * @param {DOMElement} element: Element that will be wrapped * @param {Object} options: options that can be provided to customize functionality * readOnly: Force input element to be read-only. */ extendObject.wrapTextInputElement = function( element, options ) { return TextboxWrapper.applyTo( element, options ); }; /** * Member: setErrorState * * Sets the error state of the editor, making an error message visible. * * @param {String} message: Error message to display. */ extendObject.setErrorState = function( message ) { if ( message && _errorMessageContainer ) { _errorMessageContainer.innerHTML = message; _errorMessageContainer.parentNode.style.height = _errorMessageContainer.offsetHeight + "px"; _errorMessageContainer.parentNode.style.visibility = "visible"; _errorMessageContainer.parentNode.classList.add( "open" ); } else { _errorMessageContainer.innerHTML = ""; _errorMessageContainer.parentNode.style.height = ""; _errorMessageContainer.parentNode.style.visibility = ""; _errorMessageContainer.parentNode.classList.remove( "open" ); } }; extendObject.setErrorMessageContainer = function( messageContainer ) { _errorMessageContainer = messageContainer; }; window.addEventListener( "resize", function() { if ( extendObject.scrollbar ) { extendObject.scrollbar.update(); } }, false ); } return { extend: BaseEditor }; });
kaltura/popcorn.webmaker.org
public/src/editor/base-editor.js
JavaScript
mit
13,376
import authentication from 'feathers-authentication'; import { Strategy as FacebookStrategy } from 'passport-facebook'; import FacebookTokenStrategy from 'passport-facebook-token'; import { Strategy as GoogleStrategy } from 'passport-google-oauth20'; import { Strategy as GoogleTokenStrategy } from 'passport-google-token'; import jwt from 'feathers-authentication-jwt'; import local from 'feathers-authentication-local'; import oauth2 from 'feathers-authentication-oauth2'; import { addUserToResult } from '../../hooks'; export default function auth() { const app = this; const facebookConfig = { clientID: process.env.FACEBOOK_CLIENT_ID, clientSecret: process.env.FACEBOOK_CLIENT_SECRET, scope: [ 'public_profile', 'email' ], }; const googleConfig = { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, scope: [ 'profile' ], }; app .configure(authentication({ secret: process.env.TOKEN })) .configure(local()) .configure(jwt()) .configure(oauth2({ name: 'facebook', Strategy: FacebookStrategy, ...facebookConfig, })) .configure(oauth2({ name: 'facebook-token', Strategy: FacebookTokenStrategy, idField: 'facebookId', ...facebookConfig, })) .configure(oauth2({ name: 'google', Strategy: GoogleStrategy, ...googleConfig, })) .configure(oauth2({ name: 'google-token', Strategy: GoogleTokenStrategy, idField: 'googleId', ...googleConfig, })); app.service('authentication').hooks({ before: { create: [ authentication.hooks.authenticate(['jwt', 'local']), ], remove: [ authentication.hooks.authenticate('jwt') ], }, after: { create: [ addUserToResult(), ] } }); }
meatwallace/strap
src/server/services/authentication/index.js
JavaScript
mit
1,846
// flow-typed signature: 2dbc95c1b0e0b1906789eb510bba82a1 // flow-typed version: <<STUB>>/identity-obj-proxy_v^3.0.0/flow_v0.53.1 /** * This is an autogenerated libdef stub for: * * 'identity-obj-proxy' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'identity-obj-proxy' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'identity-obj-proxy/src/__tests__/import-es6-export-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/__tests__/import-es6-import-export-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/__tests__/import-es6-import-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/__tests__/import-vanilla-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/__tests__/index-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/__tests__/require-es6-export-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/__tests__/require-es6-import-export-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/__tests__/require-es6-import-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/__tests__/require-vanilla-test' { declare module.exports: any; } declare module 'identity-obj-proxy/src/index' { declare module.exports: any; } declare module 'identity-obj-proxy/src/test-redirections/idObjES6Export' { declare module.exports: any; } declare module 'identity-obj-proxy/src/test-redirections/idObjES6Import' { declare module.exports: any; } declare module 'identity-obj-proxy/src/test-redirections/idObjES6ImportExport' { declare module.exports: any; } // Filename aliases declare module 'identity-obj-proxy/src/__tests__/import-es6-export-test.js' { declare module.exports: $Exports<'identity-obj-proxy/src/__tests__/import-es6-export-test'>; } declare module 'identity-obj-proxy/src/__tests__/import-es6-import-export-test.js' { declare module.exports: $Exports< 'identity-obj-proxy/src/__tests__/import-es6-import-export-test', >; } declare module 'identity-obj-proxy/src/__tests__/import-es6-import-test.js' { declare module.exports: $Exports<'identity-obj-proxy/src/__tests__/import-es6-import-test'>; } declare module 'identity-obj-proxy/src/__tests__/import-vanilla-test.js' { declare module.exports: $Exports<'identity-obj-proxy/src/__tests__/import-vanilla-test'>; } declare module 'identity-obj-proxy/src/__tests__/index-test.js' { declare module.exports: $Exports<'identity-obj-proxy/src/__tests__/index-test'>; } declare module 'identity-obj-proxy/src/__tests__/require-es6-export-test.js' { declare module.exports: $Exports<'identity-obj-proxy/src/__tests__/require-es6-export-test'>; } declare module 'identity-obj-proxy/src/__tests__/require-es6-import-export-test.js' { declare module.exports: $Exports< 'identity-obj-proxy/src/__tests__/require-es6-import-export-test', >; } declare module 'identity-obj-proxy/src/__tests__/require-es6-import-test.js' { declare module.exports: $Exports<'identity-obj-proxy/src/__tests__/require-es6-import-test'>; } declare module 'identity-obj-proxy/src/__tests__/require-vanilla-test.js' { declare module.exports: $Exports<'identity-obj-proxy/src/__tests__/require-vanilla-test'>; } declare module 'identity-obj-proxy/src/index.js' { declare module.exports: $Exports<'identity-obj-proxy/src/index'>; } declare module 'identity-obj-proxy/src/test-redirections/idObjES6Export.js' { declare module.exports: $Exports<'identity-obj-proxy/src/test-redirections/idObjES6Export'>; } declare module 'identity-obj-proxy/src/test-redirections/idObjES6Import.js' { declare module.exports: $Exports<'identity-obj-proxy/src/test-redirections/idObjES6Import'>; } declare module 'identity-obj-proxy/src/test-redirections/idObjES6ImportExport.js' { declare module.exports: $Exports<'identity-obj-proxy/src/test-redirections/idObjES6ImportExport'>; }
boldr/boldr-ui
flow-typed/npm/identity-obj-proxy_vx.x.x.js
JavaScript
mit
4,337
jest.dontMock('../solutions/217-find-duplicate'); describe('find duplicate in array', function () { var find = require('../solutions/217-find-duplicate'); it("returns true when given [1,2,3,3,5]", function () { expect(find([1, 2, 3, 3, 5])).toBe(true); }); it("returns false when given [1,2,3,5]", function () { expect(find([1, 2, 3, 5])).toBe(false); }); it("returns false when given []", function () { expect(find([])).toBe(false); }); });
shuson/leetcode_solutions
__tests__/217-find-duplicate-test.js
JavaScript
mit
498
fc.sourceNormalizers = []; fc.sourceFetchers = []; var ajaxDefaults = { dataType: 'json', cache: false }; var eventGUID = 1; function EventManager(options, _sources) { var t = this; // exports t.isFetchNeeded = isFetchNeeded; t.fetchEvents = fetchEvents; t.addEventSource = addEventSource; t.removeEventSource = removeEventSource; t.updateEvent = updateEvent; t.renderEvent = renderEvent; t.removeEvents = removeEvents; t.clientEvents = clientEvents; t.normalizeEvent = normalizeEvent; // imports var trigger = t.trigger; var getView = t.getView; var reportEvents = t.reportEvents; // locals var stickySource = { events: [] }; var sources = [ stickySource ]; var rangeStart, rangeEnd; var currentFetchID = 0; var pendingSourceCnt = 0; var loadingLevel = 0; var cache = []; for (var i=0; i<_sources.length; i++) { _addEventSource(_sources[i]); } /* Fetching -----------------------------------------------------------------------------*/ function isFetchNeeded(start, end) { return !rangeStart || start < rangeStart || end > rangeEnd; } function fetchEvents(start, end) { rangeStart = start; rangeEnd = end; cache = []; var fetchID = ++currentFetchID; var len = sources.length; pendingSourceCnt = len; for (var i=0; i<len; i++) { fetchEventSource(sources[i], fetchID); } } function fetchEventSource(source, fetchID) { _fetchEventSource(source, function(events) { if (fetchID == currentFetchID) { if (events) { if (options.eventDataTransform) { events = $.map(events, options.eventDataTransform); } if (source.eventDataTransform) { events = $.map(events, source.eventDataTransform); } // TODO: this technique is not ideal for static array event sources. // For arrays, we'll want to process all events right in the beginning, then never again. for (var i=0; i<events.length; i++) { events[i].source = source; normalizeEvent(events[i]); } cache = cache.concat(events); } pendingSourceCnt--; if (!pendingSourceCnt) { reportEvents(cache); } } }); } function _fetchEventSource(source, callback) { var i; var fetchers = fc.sourceFetchers; var res; for (i=0; i<fetchers.length; i++) { res = fetchers[i](source, rangeStart, rangeEnd, callback); if (res === true) { // the fetcher is in charge. made its own async request return; } else if (typeof res == 'object') { // the fetcher returned a new source. process it _fetchEventSource(res, callback); return; } } var events = source.events; if (events) { if ($.isFunction(events)) { pushLoading(); events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) { callback(events); popLoading(); }); } else if ($.isArray(events)) { callback(events); } else { callback(); } }else{ var url = source.url; if (url) { var success = source.success; var error = source.error; var complete = source.complete; // retrieve any outbound GET/POST $.ajax data from the options var customData; if ($.isFunction(source.data)) { // supplied as a function that returns a key/value object customData = source.data(); } else { // supplied as a straight key/value object customData = source.data; } // use a copy of the custom data so we can modify the parameters // and not affect the passed-in object. var data = $.extend({}, customData || {}); var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); if (startParam) { data[startParam] = Math.round(+rangeStart / 1000); } if (endParam) { data[endParam] = Math.round(+rangeEnd / 1000); } pushLoading(); $.ajax($.extend({}, ajaxDefaults, source, { data: data, success: function(events) { events = events || []; var res = applyAll(success, this, arguments); if ($.isArray(res)) { events = res; } callback(events); }, error: function() { applyAll(error, this, arguments); callback(); }, complete: function() { applyAll(complete, this, arguments); popLoading(); } })); }else{ callback(); } } } /* Sources -----------------------------------------------------------------------------*/ function addEventSource(source) { source = _addEventSource(source); if (source) { pendingSourceCnt++; fetchEventSource(source, currentFetchID); // will eventually call reportEvents } } function _addEventSource(source) { if ($.isFunction(source) || $.isArray(source)) { source = { events: source }; } else if (typeof source == 'string') { source = { url: source }; } if (typeof source == 'object') { normalizeSource(source); sources.push(source); return source; } } function removeEventSource(source) { sources = $.grep(sources, function(src) { return !isSourcesEqual(src, source); }); // remove all client events from that source cache = $.grep(cache, function(e) { return !isSourcesEqual(e.source, source); }); reportEvents(cache); } /* Manipulation -----------------------------------------------------------------------------*/ function updateEvent(event) { // update an existing event var i, len = cache.length, e, defaultEventEnd = getView().defaultEventEnd, // getView??? startDelta = event.start - event._start, endDelta = event.end ? (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end : 0; // was null and event was just resized for (i=0; i<len; i++) { e = cache[i]; if (e._id == event._id && e != event) { e.start = new Date(+e.start + startDelta); if (event.end) { if (e.end) { e.end = new Date(+e.end + endDelta); }else{ e.end = new Date(+defaultEventEnd(e) + endDelta); } }else{ e.end = null; } e.title = event.title; e.url = event.url; e.allDay = event.allDay; e.className = event.className; e.editable = event.editable; e.color = event.color; e.backgroundColor = event.backgroundColor; e.borderColor = event.borderColor; e.textColor = event.textColor; normalizeEvent(e); } } normalizeEvent(event); reportEvents(cache); } function renderEvent(event, stick) { normalizeEvent(event); if (!event.source) { if (stick) { stickySource.events.push(event); event.source = stickySource; } cache.push(event); } reportEvents(cache); } function removeEvents(filter) { if (!filter) { // remove all cache = []; // clear all array sources for (var i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = []; } } }else{ if (!$.isFunction(filter)) { // an event ID var id = filter + ''; filter = function(e) { return e._id == id; }; } cache = $.grep(cache, filter, true); // remove events from array sources for (var i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = $.grep(sources[i].events, filter, true); } } } reportEvents(cache); } function clientEvents(filter) { if ($.isFunction(filter)) { return $.grep(cache, filter); } else if (filter) { // an event ID filter += ''; return $.grep(cache, function(e) { return e._id == filter; }); } return cache; // else, return all } /* Loading State -----------------------------------------------------------------------------*/ function pushLoading() { if (!loadingLevel++) { trigger('loading', null, true); } } function popLoading() { if (!--loadingLevel) { trigger('loading', null, false); } } /* Event Normalization -----------------------------------------------------------------------------*/ function normalizeEvent(event) { var source = event.source || {}; var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone); event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + ''); if (event.date) { if (!event.start) { event.start = event.date; } delete event.date; } event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone)); event.end = parseDate(event.end, ignoreTimezone); if (event.end && event.end <= event.start) { event.end = null; } event._end = event.end ? cloneDate(event.end) : null; if (event.allDay === undefined) { event.allDay = firstDefined(source.allDayDefault, options.allDayDefault); } if (event.className) { if (typeof event.className == 'string') { event.className = event.className.split(/\s+/); } }else{ event.className = []; } // TODO: if there is no start date, return false to indicate an invalid event // resources if(!event.resourceId) { return; } var resources = options.resources; $.each( resources, function(index, resource){ if(resource.id === event.resourceId) { event.resource = resource; } } ); } /* Utils ------------------------------------------------------------------------------*/ function normalizeSource(source) { if (source.className) { // TODO: repeat code, same code for event classNames if (typeof source.className == 'string') { source.className = source.className.split(/\s+/); } }else{ source.className = []; } var normalizers = fc.sourceNormalizers; for (var i=0; i<normalizers.length; i++) { normalizers[i](source); } } function isSourcesEqual(source1, source2) { return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); } function getSourcePrimitive(source) { return ((typeof source == 'object') ? (source.events || source.url) : '') || source; } }
Servoy/fullcalendar
src/EventManager.js
JavaScript
mit
10,168
mapApp.controller("ListController", ["$scope", "$sce", "ItineraryService", function ($scope, $sce, ItineraryService) { $scope.indexOfSelectedRow = null; $scope.itineraryList = []; $scope.transportationModes = ItineraryService.getTransportationModes(); $scope.currentTransportationMode = ItineraryService.getTransportationMode(); $scope.summaryText = ""; $scope.$watch("currentTransportationMode", function (newValue, oldValue) { if (newValue.mode !== oldValue.mode) { ItineraryService.setTransportationMode(newValue); } }, true ); $scope.$watchCollection(function () { return ItineraryService.getItinerary(); }, function (newItinerary, oldItinerary) { $scope.itineraryList = newItinerary; } ); $scope.$watch(function () { return ItineraryService.getSummaryText(); }, function (newSummaryText, oldSummaryText) { if (newSummaryText !== oldSummaryText) { $scope.summaryText = $sce.trustAsHtml(newSummaryText); } } ); $scope.selectRow = function(index) { if (!index && typeof index !== "number") { index = 0; } ItineraryService.setCurrentIndexOfItinerary(index); $scope.indexOfSelectedRow = ItineraryService.getCurrentIndexOfItinerary(); }; $scope.moveRowUp = function() { $scope.itineraryList = ItineraryService.changeOrderOfWaypointsInItinerary("up", $scope.indexOfSelectedRow); $scope.indexOfSelectedRow = ItineraryService.getCurrentIndexOfItinerary(); }; $scope.moveRowDown = function() { $scope.itineraryList = ItineraryService.changeOrderOfWaypointsInItinerary("down", $scope.indexOfSelectedRow); $scope.indexOfSelectedRow = ItineraryService.getCurrentIndexOfItinerary(); }; $scope.removeRow = function() { $scope.itineraryList = ItineraryService.removeWaypointFromItinerary($scope.indexOfSelectedRow); }; } ]);
ChristosMonogios/Itinerary-App-With-Here-Maps
public/javascripts/controllers/listController.js
JavaScript
mit
2,252
Template.showModal.onCreated(function () { this.templateName = new ReactiveVar() }); Template.showModal.onRendered(function() { // set template var this.templateName.set(this.data.template) var id = '#' + this.data.id this.autorun(_.bind(() => { Tracker.afterFlush(_.bind(() => { // after the modal window is added to dom // setup semantic ui specific callbacks // http://semantic-ui.com/modules/modal.html#/settings $('.ui.modal').modal({ onShow: function() { $(id + ' .field').removeClass("error") $(id).removeClass('loading') return WSL.ui.modal.onShow() }, onVisible: function() { return WSL.ui.modal.onVisible() }, onHide: function() { return WSL.ui.modal.onHide() }, onHidden: function() { return WSL.ui.modal.onHidden() }, onApprove: function (el) { $(id).addClass('loading') WSL.ui.modal.onApprove(el) return false }, onDeny: function(el) { $(id).removeClass('loading') $(id + ' .pointing.red').remove() closeModal('.ui.modal') WSL.ui.modal.onDeny(el) return false } }) },this)) })) }) Template.showModal.helpers({ template: function () { return Template.instance().templateName.get() } }) this.closeModal = function(id) { $(id).modal('hide') } this.openModal = function (id) { $(id).modal('show') }
heaven7/wsl-theme-semantic-ui
lib/client/modal/templates.js
JavaScript
mit
1,808
app.factory('MiliHelper', function() { var milisseconds = 1000; var seconds = 60 * milisseconds; var minutes = 60 * seconds; var hours = 24 * minutes; return { milisseconds: milisseconds, seconds: seconds, minutes: minutes, hours: hours }; });
CosmolabTeam/countdown-landing-page
public/js/services/MiliHelper.js
JavaScript
mit
260
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/home/flp/Code/juliaSets-v2/src/calc/index.js":[function(require,module,exports){ 'use strict'; module.exports = function (Constructor) { Constructor.prototype.calc_x = function calc_x(x,y) { return Math.pow(x, 2) - Math.pow(y, 2) + this.c[0]; }; Constructor.prototype.calc_y = function calc_y(x,y) { return 2*x*y + this.c[1]; }; } },{}],"/home/flp/Code/juliaSets-v2/src/main.js":[function(require,module,exports){ function Fractal_module() { this.c = [0.285 , 0]; this.k = 20; this.fase = 250; this.MAX_ITER = 256; this.n = 500; this.m = this.n; this.boundary = 2; this.step = this.boundary/this.n; this.ini = 0 - this.step * (this.n/2); //variables this.i; this.x; this.y; this.xi; this.yi; this.set = []; var canvas = document.getElementsByTagName('canvas')[0]; canvas.width = this.n; canvas.height = this.m; this.canvas = canvas.getContext("2d"); } //Methods! require('./method/hsvToRgb')(Fractal_module); require('./method/color')(Fractal_module); require('./method/draw_pixel')(Fractal_module); require('./method/norm')(Fractal_module); require('./method/init_set')(Fractal_module); require('./method/fractal')(Fractal_module); require('./calc')(Fractal_module); //kick start var fractal_module = new Fractal_module(); fractal_module.fractal(); },{"./calc":"/home/flp/Code/juliaSets-v2/src/calc/index.js","./method/color":"/home/flp/Code/juliaSets-v2/src/method/color/index.js","./method/draw_pixel":"/home/flp/Code/juliaSets-v2/src/method/draw_pixel/index.js","./method/fractal":"/home/flp/Code/juliaSets-v2/src/method/fractal/index.js","./method/hsvToRgb":"/home/flp/Code/juliaSets-v2/src/method/hsvToRgb/index.js","./method/init_set":"/home/flp/Code/juliaSets-v2/src/method/init_set/index.js","./method/norm":"/home/flp/Code/juliaSets-v2/src/method/norm/index.js"}],"/home/flp/Code/juliaSets-v2/src/method/color/index.js":[function(require,module,exports){ module.exports = function (Constructor) { Constructor.prototype.color = function color(i) { //TODO: return black when i = 0; var c = this.hsvToRgb( (this.k * i + this.fase) % 360 , 100, 90 ); return 'rgb(' + c.r + ',' + c.g + ',' + c.b + ')'; }; }; },{}],"/home/flp/Code/juliaSets-v2/src/method/draw_pixel/index.js":[function(require,module,exports){ module.exports = function (Constructor) { //TODO: //require('../color')(Constructor); Constructor.prototype.draw_pixel = function draw_pixel(x,y,i) { this.canvas.fillStyle = this.color(i); this.canvas.fillRect(x,y,1,1); }; } },{}],"/home/flp/Code/juliaSets-v2/src/method/fractal/index.js":[function(require,module,exports){ module.exports = function (Constructor) { Constructor.prototype.fractal = function () { this.init_set(); //calculate and draw the fractal for (this.y = 0; this.y < this.n; this.y++){ for(this.x = 0; this.x < this.m; this.x++) { for (this.i = 0; this.i < this.MAX_ITER; this.i++){ //setting the inner most loop as the iteration loop makes //breaking it easier thus more performant if (this.norm(this.set[this.y][this.x][0], this.set[this.y][this.x][1]) > 2 || this.i + 1 === this.MAX_ITER) { this.draw_pixel(this.x, this.y, this.set[this.y][this.x][2]); break; } this.set[this.y][this.x][0] = this.calc_x(this.set[this.y][this.x][0],this.set[this.y][this.x][1]); this.set[this.y][this.x][1] = this.calc_y(this.set[this.y][this.x][0],this.set[this.y][this.x][1]); this.set[this.y][this.x][2] += 1; } } } } } },{}],"/home/flp/Code/juliaSets-v2/src/method/hsvToRgb/index.js":[function(require,module,exports){ /** * HSV to RGB color conversion * * H runs from 0 to 360 degrees * S and V run from 0 to 100 * * Ported from the excellent java algorithm by Eugene Vishnevsky at: * http://www.cs.rit.edu/~ncs/color/t_convert.html */ //http://snipplr.com/view/14590 module.exports = function (Constructor) { Constructor.prototype.hsvToRgb = function hsvToRgb(h, s, v) { var r, g, b; var i; var f, p, q, t; // Make sure our arguments stay in-range h = Math.max(0, Math.min(360, h)); s = Math.max(0, Math.min(100, s)); v = Math.max(0, Math.min(100, v)); // We accept saturation and value arguments from 0 to 100 because that's // how Photoshop represents those values. Internally, however, the // saturation and value are calculated from a range of 0 to 1. We make // That conversion here. s /= 100; v /= 100; if(s == 0) { // Achromatic (grey) r = g = b = v; return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; } h /= 60; // sector 0 to 5 i = Math.floor(h); f = h - i; // factorial part of h p = v * (1 - s); q = v * (1 - s * f); t = v * (1 - s * (1 - f)); switch(i) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; default: // case 5: r = v; g = p; b = q; } return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) }; }; }; },{}],"/home/flp/Code/juliaSets-v2/src/method/init_set/index.js":[function(require,module,exports){ module.exports = function (Constructor) { //initialize array values Constructor.prototype.init_set = function () { for (this.y = 0; this.y < this.n; this.y++){ this.set[this.y] = []; for(this.x = 0; this.x < this.m; this.x++) { //el array esta formado por [this.x,y, numero_de_iteraciones] this.set[this.y][this.x] = [this.ini + this.step * this.x, -(this.ini + this.step*this.y), 0 ] } } } } },{}],"/home/flp/Code/juliaSets-v2/src/method/norm/index.js":[function(require,module,exports){ module.exports = function (Constructor) { Constructor.prototype.norm = function norm(x,y) { return Math.sqrt(Math.pow(x, 2) + Math.pow(y,2)) } } },{}]},{},["/home/flp/Code/juliaSets-v2/src/main.js"]);
franleplant/juliaSets-v2
bundle.js
JavaScript
mit
6,648
var jdb = require('../'); var DataSource = jdb.DataSource; var should = require('./init.js'); describe('Memory connector with mocked discovery', function() { var ds; before(function() { ds = new DataSource({connector: 'memory'}); var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'}, {type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'}, {type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}]; ds.discoverModelDefinitions = function(options, cb) { process.nextTick(function() { cb(null, models); }); }; var modelProperties = [{ owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'PRODUCT_ID', dataType: 'varchar', dataLength: 20, dataPrecision: null, dataScale: null, nullable: 0 }, { owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'LOCATION_ID', dataType: 'varchar', dataLength: 20, dataPrecision: null, dataScale: null, nullable: 0 }, { owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'AVAILABLE', dataType: 'int', dataLength: null, dataPrecision: 10, dataScale: 0, nullable: 1 }, { owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'TOTAL', dataType: 'int', dataLength: null, dataPrecision: 10, dataScale: 0, nullable: 1 }]; ds.discoverModelProperties = function(modelName, options, cb) { process.nextTick(function() { cb(null, modelProperties); }); }; }); it('should convert table/column names to camel cases', function(done) { ds.discoverSchemas('INVENTORY', {}, function(err, schemas) { if (err) return done(err); schemas.should.have.property('STRONGLOOP.INVENTORY'); var s = schemas['STRONGLOOP.INVENTORY']; s.name.should.be.eql('Inventory'); Object.keys(s.properties).should.be.eql( ['productId', 'locationId', 'available', 'total']); done(); }); }); it('should convert table/column names with custom mapper', function(done) { ds.discoverSchemas('INVENTORY', { nameMapper: function(type, name) { // Convert all names to lower case return name.toLowerCase(); } }, function(err, schemas) { if (err) return done(err); schemas.should.have.property('STRONGLOOP.INVENTORY'); var s = schemas['STRONGLOOP.INVENTORY']; s.name.should.be.eql('inventory'); Object.keys(s.properties).should.be.eql( ['product_id', 'location_id', 'available', 'total']); done(); }); }); it('should not convert table/column names with null custom mapper', function(done) { ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) { if (err) return done(err); schemas.should.have.property('STRONGLOOP.INVENTORY'); var s = schemas['STRONGLOOP.INVENTORY']; s.name.should.be.eql('INVENTORY'); Object.keys(s.properties).should.be.eql( ['PRODUCT_ID', 'LOCATION_ID', 'AVAILABLE', 'TOTAL']); done(); }); }); it('should honor connector\'s discoverSchemas implementation', function(done) { var models = { inventory: { product: {type: 'string'}, location: {type: 'string'} } }; ds.connector.discoverSchemas = function(modelName, options, cb) { process.nextTick(function() { cb(null, models); }); }; ds.discoverSchemas('INVENTORY', {nameMapper: null}, function(err, schemas) { if (err) return done(err); schemas.should.be.eql(models); done(); }); }); it('should callback function, passed as options parameter', function(done) { var models = { inventory: { product: {type: 'string'}, location: {type: 'string'} } }; ds.connector.discoverSchemas = function(modelName, options, cb) { process.nextTick(function() { cb(null, models); }); }; var options = function(err, schemas) { if (err) return done(err); schemas.should.be.eql(models); done(); }; ds.discoverSchemas('INVENTORY', options); }); it('should discover schemas using `discoverSchemas` - promise variant', function(done) { ds.connector.discoverSchemas = null; ds.discoverSchemas('INVENTORY', {}) .then(function(schemas) { schemas.should.have.property('STRONGLOOP.INVENTORY'); var s = schemas['STRONGLOOP.INVENTORY']; s.name.should.be.eql('Inventory'); Object.keys(s.properties).should.be.eql( ['productId', 'locationId', 'available', 'total'] ); done(); }) .catch(function(err) { done(err); }); }); describe('discoverSchema', function(){ var models; var schema; before(function() { schema = { name: 'Inventory', options: { idInjection: false, memory: { schema: 'STRONGLOOP', table: 'INVENTORY' } }, properties: { available: { length: null, memory: { columnName: 'AVAILABLE', dataLength: null, dataPrecision: 10, dataScale: 0, dataType: 'int', nullable: 1 }, precision: 10, required: false, scale: 0, type: undefined }, locationId: { length: 20, memory: { columnName: 'LOCATION_ID', dataLength: 20, dataPrecision: null, dataScale: null, dataType: 'varchar', nullable: 0 }, precision: null, required: true, scale: null, type: undefined }, productId: { length: 20, memory: { columnName: 'PRODUCT_ID', dataLength: 20, dataPrecision: null, dataScale: null, dataType: 'varchar', nullable: 0 }, precision: null, required: true, scale: null, type: undefined }, total: { length: null, memory: { columnName: 'TOTAL', dataLength: null, dataPrecision: 10, dataScale: 0, dataType: 'int', nullable: 1 }, precision: 10, required: false, scale: 0, type: undefined } } } ; }); it('should discover schema using `discoverSchema`', function(done) { ds.discoverSchema('INVENTORY', {}, function(err, schemas) { if (err) return done(err); schemas.should.be.eql(schema); done(); }); }); it('should callback function, passed as options parameter', function(done) { var options = function(err, schemas) { if (err) return done(err); schemas.should.be.eql(schema); done(); }; ds.discoverSchema('INVENTORY', options); }); it('should discover schema using `discoverSchema` - promise variant', function(done) { ds.discoverSchema('INVENTORY', {}) .then(function(schemas) { schemas.should.be.eql(schema); done(); }) .catch(function(err){ done(err); }); }); }); }); describe('discoverModelDefinitions', function(){ var ds; before(function(){ ds = new DataSource({connector: 'memory'}); var models = [{type: 'table', name: 'CUSTOMER', owner: 'STRONGLOOP'}, {type: 'table', name: 'INVENTORY', owner: 'STRONGLOOP'}, {type: 'table', name: 'LOCATION', owner: 'STRONGLOOP'}]; ds.connector.discoverModelDefinitions = function(options, cb) { process.nextTick(function() { cb(null, models); }); }; }); it('should discover model using `discoverModelDefinitions`', function(done) { ds.discoverModelDefinitions({}, function(err, schemas) { if (err) return done(err); var tableNames = schemas.map(function(s) { return s.name; }); tableNames.should.be.eql( ["CUSTOMER", "INVENTORY", "LOCATION"] ); done(); }); }); it('should callback function, passed as options parameter', function(done) { var options = function(err, schemas) { if (err) return done(err); var tableNames = schemas.map(function(s) { return s.name; }); tableNames.should.be.eql( ["CUSTOMER", "INVENTORY", "LOCATION"] ); done(); }; ds.discoverModelDefinitions(options); }); it('should discover model using `discoverModelDefinitions` - promise variant', function(done) { ds.discoverModelDefinitions({}) .then(function(schemas) { var tableNames = schemas.map(function(s) { return s.name; }); tableNames.should.be.eql( ["CUSTOMER", "INVENTORY", "LOCATION"] ); done(); }) .catch(function(err){ done(err); }); }); }); describe('discoverModelProperties', function(){ var ds; var modelProperties; before(function(){ ds = new DataSource({connector: 'memory'}); modelProperties = [{ owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'PRODUCT_ID', dataType: 'varchar', dataLength: 20, dataPrecision: null, dataScale: null, nullable: 0 }, { owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'LOCATION_ID', dataType: 'varchar', dataLength: 20, dataPrecision: null, dataScale: null, nullable: 0 }, { owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'AVAILABLE', dataType: 'int', dataLength: null, dataPrecision: 10, dataScale: 0, nullable: 1 }, { owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'TOTAL', dataType: 'int', dataLength: null, dataPrecision: 10, dataScale: 0, nullable: 1 }]; ds.connector.discoverModelProperties = function(modelName, options, cb) { process.nextTick(function() { cb(null, modelProperties); }); }; }); it('should callback function, passed as options parameter', function(done) { var options = function(err, schemas) { if (err) return done(err); schemas.should.be.eql(modelProperties); done(); }; ds.discoverModelProperties('INVENTORY', options); }); it('should discover model metadata using `discoverModelProperties`', function(done) { ds.discoverModelProperties('INVENTORY', {}, function(err, schemas) { if (err) return done(err); schemas.should.be.eql(modelProperties); done(); }); }); it('should discover model metadata using `discoverModelProperties` - promise variant', function(done) { ds.discoverModelProperties('INVENTORY', {}) .then(function(schemas) { schemas.should.be.eql(modelProperties); done(); }) .catch(function(err){ done(err); }); }); }); describe('discoverPrimaryKeys', function(){ var ds; var modelProperties; before(function(){ ds = new DataSource({connector: 'memory'}); primaryKeys = [ { owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'PRODUCT_ID', keySeq: 1, pkName: 'ID_PK' }, { owner: 'STRONGLOOP', tableName: 'INVENTORY', columnName: 'LOCATION_ID', keySeq: 2, pkName: 'ID_PK' }]; ds.connector.discoverPrimaryKeys = function(modelName, options, cb) { process.nextTick(function() { cb(null, primaryKeys); }); }; }); it('should discover primary key definitions using `discoverPrimaryKeys`', function(done) { ds.discoverPrimaryKeys('INVENTORY', {}, function(err, modelPrimaryKeys) { if (err) return done(err); modelPrimaryKeys.should.be.eql(primaryKeys); done(); }); }); it('should callback function, passed as options parameter', function(done) { var options = function(err, modelPrimaryKeys) { if (err) return done(err); modelPrimaryKeys.should.be.eql(primaryKeys); done(); }; ds.discoverPrimaryKeys('INVENTORY', options); }); it('should discover primary key definitions using `discoverPrimaryKeys` - promise variant', function(done) { ds.discoverPrimaryKeys('INVENTORY', {}) .then(function(modelPrimaryKeys) { modelPrimaryKeys.should.be.eql(primaryKeys); done(); }) .catch(function(err){ done(err); }); }); }); describe('discoverForeignKeys', function(){ var ds; var modelProperties; before(function(){ ds = new DataSource({connector: 'memory'}); foreignKeys = [{ fkOwner: 'STRONGLOOP', fkName: 'PRODUCT_FK', fkTableName: 'INVENTORY', fkColumnName: 'PRODUCT_ID', keySeq: 1, pkOwner: 'STRONGLOOP', pkName: 'PRODUCT_PK', pkTableName: 'PRODUCT', pkColumnName: 'ID' }]; ds.connector.discoverForeignKeys = function(modelName, options, cb) { process.nextTick(function() { cb(null, foreignKeys); }); }; }); it('should discover foreign key definitions using `discoverForeignKeys`', function(done) { ds.discoverForeignKeys('INVENTORY', {}, function(err, modelForeignKeys) { if (err) return done(err); modelForeignKeys.should.be.eql(foreignKeys); done(); }); }); it('should callback function, passed as options parameter', function(done) { var options = function(err, modelForeignKeys) { if (err) return done(err); modelForeignKeys.should.be.eql(foreignKeys); done(); }; ds.discoverForeignKeys('INVENTORY', options); }); it('should discover foreign key definitions using `discoverForeignKeys` - promise variant', function(done) { ds.discoverForeignKeys('INVENTORY', {}) .then(function(modelForeignKeys) { modelForeignKeys.should.be.eql(foreignKeys); done(); }) .catch(function(err){ done(err); }); }); }); describe('discoverExportedForeignKeys', function(){ var ds; var modelProperties; before(function(){ ds = new DataSource({connector: 'memory'}); exportedForeignKeys = [{ fkName: 'PRODUCT_FK', fkOwner: 'STRONGLOOP', fkTableName: 'INVENTORY', fkColumnName: 'PRODUCT_ID', keySeq: 1, pkName: 'PRODUCT_PK', pkOwner: 'STRONGLOOP', pkTableName: 'PRODUCT', pkColumnName: 'ID' }]; ds.connector.discoverExportedForeignKeys = function(modelName, options, cb) { process.nextTick(function() { cb(null, exportedForeignKeys); }); }; }); it('should discover foreign key definitions using `discoverExportedForeignKeys`', function(done) { ds.discoverExportedForeignKeys('INVENTORY', {}, function(err, modelForeignKeys) { if (err) return done(err); modelForeignKeys.should.be.eql(exportedForeignKeys); done(); }); }); it('should callback function, passed as options parameter', function(done) { var options = function(err, modelForeignKeys) { if (err) return done(err); modelForeignKeys.should.be.eql(exportedForeignKeys); done(); }; ds.discoverExportedForeignKeys('INVENTORY', options); }); it('should discover foreign key definitions using `discoverExportedForeignKeys` - promise variant', function(done) { ds.discoverExportedForeignKeys('INVENTORY', {}) .then(function(modelForeignKeys) { modelForeignKeys.should.be.eql(exportedForeignKeys); done(); }) .catch(function(err){ done(err); }); }); });
hackathon-5/team-boomtown-repo
node_modules/loopback-datasource-juggler/test/discovery.test.js
JavaScript
mit
16,263
define([ 'text!./templates/detail.html' ], function (template) { "use strict"; // todo: start respecting "deleted" flag by default on searches return { id: "_.characters.details", url: "/{id:int}", resolve: { character: ['dal', '$stateParams', '$state', function (dal, $stateParams, $state) { return dal.getNoun('character', $stateParams.id).then(function (character) { if (character.contextId) { return $state.go("_.stories.details.character", {id: character.contextId, charId: $stateParams.id}, {location: "replace"}); } return character; }); }], stories: ['dal', '$stateParams', function (dal, $stateParams) { return dal.getSearchResults('story', {nested: {path: "character", query: {bool: {should: [{match: {"character.id": $stateParams.id}}, {match: {"character.inheritsFromId": $stateParams.id}}]}}}}); }] }, // we're not actually nesting views (despite the nested state), so just hijack the root view views: { '@': { template: template, controller: ['character', 'stories', 'user', '$scope', function (character, stories, user, $scope) { $scope.isLoggedIn = user.isLoggedIn; $scope.stories = stories; $scope.character = character; }] } }, data: { displayName: '{{character.name || $stateParams.id}}' } }; });
moatra/stagert
app/assets/javascripts/character/detail.js
JavaScript
mit
1,633
/** * TodoFooter */ import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './TodoFooter.scss'; import classNames from 'classnames'; import TodoActions from '../../actions/TodoActions'; import TodoConstants from '../../constants/TodoConstants'; import history from '../../core/history'; const PATH_ALL = '/'; const PATH_ACTIVE = '/active/'; const PATH_COMPLETED = '/completed/'; class TodoFooter extends Component { constructor (props) { super(props); this.getCompleteTasks = this.getCompleteTasks.bind(this); this.incompleteTaskCount = this.incompleteTaskCount.bind(this); this.deleteCompleteTasks = this.deleteCompleteTasks.bind(this); this.filterAll = this.filterAll.bind(this); this.filterActive = this.filterActive.bind(this); this.filterCompleted = this.filterCompleted.bind(this); this.onLocationChange = this.onLocationChange.bind(this); history.listen(this.onLocationChange); } deleteCompleteTasks () { this.getCompleteTasks().forEach(item => TodoActions.destroy(item.id)); } getCompleteTasks () { return this.props.allTodos.filter(item => item.complete); } incompleteTaskCount () { return this.props.allTodos.length - this.getCompleteTasks().length; } filterAll () { history.push(PATH_ALL); } filterActive () { history.push(PATH_ACTIVE); } filterCompleted () { history.push(PATH_COMPLETED); } onLocationChange (event) { let path = event.pathname; let filter; if (path === PATH_ALL) { filter = TodoConstants.TODO_FILTER_ALL; } else if (path === PATH_ACTIVE) { filter = TodoConstants.TODO_FILTER_ACTIVE; } else if (path === PATH_COMPLETED) { filter = TodoConstants.TODO_FILTER_COMPLETED; } else { filter = false; } if (!filter) return; this.props.setFilter(filter); } render () { let incompleteTaskCount = this.incompleteTaskCount(); let AllCls = [s.filterItem]; if (this.props.filterType === TodoConstants.TODO_FILTER_ALL) { AllCls.push(s.active); } let ActiveCls = [s.filterItem]; if (this.props.filterType === TodoConstants.TODO_FILTER_ACTIVE) { ActiveCls.push(s.active); } let CompletedCls = [s.filterItem]; if (this.props.filterType === TodoConstants.TODO_FILTER_COMPLETED) { CompletedCls.push(s.active); } return( <section className={this.props.allTodos.length ? s.root : s.hidden}> <div className={s.left}> {incompleteTaskCount} item{incompleteTaskCount === 1 ? '' : 's'} left </div> <div className={s.filter}> <div className={classNames(AllCls)} onClick={this.filterAll}>All</div> <div className={classNames(ActiveCls)} onClick={this.filterActive}>Active</div> <div className={classNames(CompletedCls)} onClick={this.filterCompleted}>Completed</div> </div> <div className={s.delete} onClick={this.deleteCompleteTasks}> Clear completed </div> </section> ); } } export default withStyles(s)(TodoFooter);
dadish-etudes/react-todo
src/components/TodoFooter/TodoFooter.js
JavaScript
mit
2,980
'use strict'; const _ = { defaultsDeep: require('lodash.defaultsdeep'), findIndex: require('lodash.findindex'), isEmpty: require('lodash.isempty'), trimStart: require('lodash.trimstart'), trimEnd: require('lodash.trimend') }; // ----------------------------------------------------------------------------- const REMOVE_MARKDOWN = require('remove-markdown'); const STRIPTAGS = require('striptags'); // ----------------------------------------------------------------------------- /** * holds relevant functions and data */ const PLUGIN = { name: 'autometa', // the would also be the key used in frontmatter default_metas: {} }; // ----------------------------------------------------------------------------- const resolveURL = (base, path) => `${_.trimEnd(base, '/')}/${_.trimStart(path, '/')}` /** * @return {object} */ PLUGIN.get_options_defaults = () => { const out = { enable: true, // enables/disables everything - control per page using frontmatter image: true, // regular meta image used by search engines twitter: true, // twitter card og: true, // open graph: facebook, pinterest, google+ schema: true, // schema.org for google // ------------------------------------------------------------------------- // canonical_base is the canonical url base - best to set once in config.js // if set it will be used to prepend page path and add it to the following: // - canonical link // - twitter:url // - og:url canonical_base: '', // @todo //canonical_link: true, // // having only started with vuepress a few days ago, // so far, i couldn't figure out a proper way to extend config head // and add <link rel="canonical" href="resolveURL( canonical_base, $page.path )"> // ------------------------------------------------------------------------- author: { name: '', twitter: '', //url : '', // not used currently }, // ------------------------------------------------------------------------- // @notes: // // it's more logical to have this one set once in // `.vuepress/config.js` or `.vuepress/theme/index.js` `head` site: { name: '', twitter: '', //url : '', // not used currently }, // ------------------------------------------------------------------------- // not sure if these should be allowed to be set in frontmatter // order of what gets the highest priority: // // 1. frontmatter // 2. page excerpt // 3. content markdown paragraph // 4. content regular html <p> description_sources: [ 'frontmatter', 'excerpt', // markdown paragraph regex // @todo: needs work // /^((?:(?!^#)(?!^\-|\+)(?!^[0-9]+\.)(?!^!\[.*?\]\((.*?)\))(?!^\[\[.*?\]\])(?!^\{\{.*?\}\})[^\n]|\n(?! *\n))+)(?:\n *)+\n/img, // // this excludes blockquotes using `(?!^>)` ///^((?:(?!^#)(?!^\-|\+)(?!^[0-9]+\.)(?!^!\[.*?\]\((.*?)\))(?!^>)(?!^\[\[.*?\]\])(?!^\{\{.*?\}\})[^\n]|\n(?! *\n))+)(?:\n *)+\n/img, // html paragraph regex /<p(?:.*?)>(.*?)<\/p>/i, // ----------------------------------------------------------------------- // @notes: setting as array require escaping `\` //['^((?:(?!^#)(?!^\-|\+)(?!^[0-9]+\.)(?!^\[\[.*?\]\])(?!^\{\{.*?\}\})[^\n]|\n(?! *\n))+)(?:\n *)+\n', 'img'], //['<p(?:.*?)>(.*?)<\/p>', 'i'], ], // ------------------------------------------------------------------------- // @consider description max words/char // ------------------------------------------------------------------------- // order of what gets the highest priority: // // 1. frontmatter // 2. content markdown image such as `![alt text](http://url)` // 3. content regular html img image_sources: [ 'frontmatter', /!\[.*?\]\((.*?)\)/i, // markdown image regex /<img.*?src=['"](.*?)['"]/i, // html image regex // ----------------------------------------------------------------------- // @notes: setting as array require escaping `\` //['!\[.*?\]\((.*?)\)', 'i'], //['<img.*?src=[\'"](.*?)[\'"]', 'i'], ], }; // --------------------------------------------------------------------------- return out; }; // PLUGIN.get_options_defaults() /** * @return {object} */ PLUGIN.get_options = ($page, plugin_options) => { const { frontmatter } = $page; // --------------------------------------------------------------------------- // order of options override: // - defaults -> gets set in this file by `PLUGIN.get_default_options()` // - plugin options -> gets set in `config.js` // - frontmatter -> gets set in each page const options = _.defaultsDeep( frontmatter[PLUGIN.name], plugin_options, PLUGIN.get_options_defaults() ); // --------------------------------------------------------------------------- return options; }; // PLUGIN.get_options() /** * @return {string} */ PLUGIN.strip_markup = str => STRIPTAGS(REMOVE_MARKDOWN(str, { useImgAltText: false })); /** * @return {RegExp} */ PLUGIN.get_regex = re => (Array.isArray(re)) ? new RegExp(...re) : re; /** * check if string is a valid url * * @param {string} maybe_url * @return {bool} */ PLUGIN.is_url = (maybe_url) => { if (!maybe_url || typeof maybe_url !== 'string') { return false; } // --------------------------------------------------------------------------- const re_protocol_and_domain = /^(?:\w+:)?\/\/(\S+)$/; const match = maybe_url.match(re_protocol_and_domain); if (!match) { return false; } // --------------------------------------------------------------------------- const all_after_protocol = match[1]; if (!all_after_protocol) { return false; } // --------------------------------------------------------------------------- const re_domain_localhost = /^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/ const re_domain_non_localhost = /^[^\s\.]+\.\S{2,}$/; return (re_domain_localhost.test(all_after_protocol) || re_domain_non_localhost.test(all_after_protocol)); } // PLUGIN.is_url() /** * @return {string} */ PLUGIN.get_canonical_url = ($page, options) => { if (options.canonical_base && $page.path) { return resolveURL(options.canonical_base, $page.path); } }; // PLUGIN.get_canonical_url() /** * @return {string} */ PLUGIN.get_default_date = ($page, options) => { const { frontmatter } = $page; if (frontmatter.date) { return frontmatter.date; } }; // PLUGIN.get_default_date() /** * @return {string} */ PLUGIN.get_default_title = ($page, options) => { // default to page title let out = $page.title || ''; // --------------------------------------------------------------------------- // special handling for home const { frontmatter, _computed } = $page; if (frontmatter.home) { const site = _computed.$site; // @notes // highly unlikely, but i'm falling back to empty string // in case it was intentionally set so that no home title is added out = site.title || ''; } // --------------------------------------------------------------------------- return out; }; // PLUGIN.get_default_title() /** * @return {string} */ PLUGIN.get_default_description = ($page, options) => { // special handling for home const { frontmatter, _computed } = $page; if (frontmatter.home) { const site = _computed.$site; const description = site.description || ''; return description; } // --------------------------------------------------------------------------- if (_.isEmpty(options['description_sources'])) { return; } // --------------------------------------------------------------------------- let out = ''; for (const source of options['description_sources']) { let found = ''; // ------------------------------------------------------------------------- switch (source) { case 'frontmatter': if ($page.frontmatter.description) { found = $page.frontmatter.description; } break; // ----------------------------------------------------------------------- case 'excerpt': if ($page.excerpt) { found = $page.excerpt; } break; // ----------------------------------------------------------------------- default: // content without frontmatter - used with regex const content = $page.contentRendered || ''; if (content) { const regex = PLUGIN.get_regex(source); let match; if ((match = regex.exec(content)) !== null) { if (match[1]) { found = match[1]; } } } break; } // ------------------------------------------------------------------------- found = PLUGIN.strip_markup(found.trim()); // ------------------------------------------------------------------------- if (found) { out = found; break; } } // --------------------------------------------------------------------------- return out; }; // PLUGIN.get_default_description() /** * @return {string} */ PLUGIN.get_default_image_url = ($page, options) => { if (_.isEmpty(options['image_sources'])) { return; } // --------------------------------------------------------------------------- let out = ''; for (const source of options['image_sources']) { if ('frontmatter' === source) { if ($page.frontmatter.image) { out = $page.frontmatter.image; break; } } else { // content without frontmatter - used with regex const content = $page._strippedContent || ''; if (!content) { break; } // ----------------------------------------------------------------------- const regex = PLUGIN.get_regex(source); let match; if ((match = regex.exec(content)) !== null) { if (match[1]) { out = match[1]; break; } } } } // --------------------------------------------------------------------------- out = out.trim(); if (!out) { return; } // --------------------------------------------------------------------------- // support for image url as relative path if (PLUGIN.is_url(out)) { return out; } else { // only return it if we have a base url, // otherwise it's meaningless to add it if (options.canonical_base) { out = resolveURL(options.canonical_base, out); return out; } } }; // PLUGIN.get_default_image_url() /** * @return {object} */ PLUGIN.get_default_author = ($page, options) => { // @consider // // if author data is empty to default to git author if it has relevant details return options.author; }; // PLUGIN.get_default_author() /** * @return {object} */ PLUGIN.get_default_site = ($page, options) => { // @consider to default site name to _computed.$site.title return options.site; }; // PLUGIN.get_default_site() /** * @return {array} */ PLUGIN.default_metas.image = ($page, default_values) => { const out = []; // --------------------------------------------------------------------------- if (default_values.image) { out.push({ name: 'image', content: default_values.image, }); } // --------------------------------------------------------------------------- return out; }; // PLUGIN.default_metas.image() /** * @return {array} */ PLUGIN.default_metas.twitter = ($page, default_values) => { const out = [ { name: 'twitter:title', content: default_values.title, }, { name: 'twitter:description', content: default_values.description, }, ]; // --------------------------------------------------------------------------- if (default_values.image) { out.push({ name: 'twitter:card', content: 'summary_large_image', }); out.push({ name: 'twitter:image', content: default_values.image, }); } else { out.push({ name: 'twitter:card', content: 'summary', }); } // --------------------------------------------------------------------------- if (default_values.canonical_url) { out.push({ name: 'twitter:url', content: default_values.canonical_url, }); } // --------------------------------------------------------------------------- if (default_values.author.twitter) { out.push({ name: 'twitter:creator', content: `@${default_values.author.twitter.replace('@', '')}`, // @username }); } // --------------------------------------------------------------------------- if (default_values.site.twitter) { out.push({ name: 'twitter:site', content: `@${default_values.site.twitter.replace('@', '')}`, // @site_account }); } // --------------------------------------------------------------------------- return out; }; // PLUGIN.default_metas.twitter() /** * @return {array} */ PLUGIN.default_metas.og = ($page, default_values) => { let type = 'article'; const { frontmatter } = $page; if (frontmatter.home) { type = 'website'; } // --------------------------------------------------------------------------- let out = [ { property: 'og:type', content: type, }, { property: 'og:title', content: default_values.title, }, { property: 'og:description', content: default_values.description, }, ]; // --------------------------------------------------------------------------- if (default_values.image) { out.push({ property: 'og:image', content: default_values.image, }); } // --------------------------------------------------------------------------- if (default_values.canonical_url) { out.push({ property: 'og:url', content: default_values.canonical_url, }); } // --------------------------------------------------------------------------- if (default_values.site.name) { out.push({ property: 'og:site_name', content: default_values.site.name, }); } // --------------------------------------------------------------------------- // og article related if ('article' === type) { if (default_values.author.name) { out.push({ property: 'article:author', content: default_values.author.name, }); } // ------------------------------------------------------------------------- if (default_values.date) { out.push({ property: 'article:published_time', content: default_values.date, }); } // ------------------------------------------------------------------------- // @consider article:modified_time // ------------------------------------------------------------------------- if (!_.isEmpty(frontmatter.tags) && Array.isArray(frontmatter.tags)) { for (const tag of frontmatter.tags) { out.push({ property: 'article:tag', content: tag, }); } } } // --------------------------------------------------------------------------- return out; }; // PLUGIN.default_metas.og() /** * @return {array} */ PLUGIN.default_metas.schema = ($page, default_values) => { const out = [ { itemprop: 'name', content: default_values.title, }, { itemprop: 'description', content: default_values.description, }, ]; // --------------------------------------------------------------------------- if (default_values.image) { out.push({ itemprop: 'image', content: default_values.image, }); } // --------------------------------------------------------------------------- // @todo: // check if these meta tags require the `itemscope` and `itemtype` attributes // to be added to <html> tag // --------------------------------------------------------------------------- return out; }; // PLUGIN.default_metas.schema() /** * @return {array} */ PLUGIN.default_meta_tags = ($page, default_values, options) => { let out = []; // --------------------------------------------------------------------------- const keys = Object.keys(PLUGIN.default_metas); for (const key of keys) { if (options[key]) { out = out.concat(PLUGIN.default_metas[key]($page, default_values)); } } // --------------------------------------------------------------------------- return out.filter(e => e); }; // PLUGIN.default_meta_tags() // ----------------------------------------------------------------------------- module.exports = (plugin_options, context) => ({ extendsPage($page) { const { frontmatter } = $page; // ------------------------------------------------------------------------- const options = PLUGIN.get_options($page, plugin_options); if (!options.enable) { return; } // ------------------------------------------------------------------------- frontmatter.description = frontmatter.description || PLUGIN.get_default_description($page, options); // ------------------------------------------------------------------------- const default_values = { title: PLUGIN.get_default_title($page, options), date: PLUGIN.get_default_date($page, options), description: frontmatter.description, image_url: PLUGIN.get_default_image_url($page, options), canonical_url: PLUGIN.get_canonical_url($page, options), author: PLUGIN.get_default_author($page, options), site: PLUGIN.get_default_site($page, options), }; default_values.image = default_values.image_url; default_values.canonical = default_values.canonical_url; // ------------------------------------------------------------------------- const default_metas = PLUGIN.default_meta_tags($page, default_values, options); if (_.isEmpty(default_metas)) { return; } // ------------------------------------------------------------------------- frontmatter.meta = frontmatter.meta || []; for (const meta of default_metas) { // only add it if not already set in frontmatter const index = _.findIndex(frontmatter.meta, ['name', meta.name]); if (index === -1) { frontmatter.meta.push(meta); } } } });
c4software/bts-sio
.vuepress/plugins/autometa.js
JavaScript
mit
20,422
require('es5-shim'); require('babel-polyfill'); var Main = require('./main'); document.main = Main Main.init().then(function () { require("jquery")(window).resize(Main.repositionSupportPanelsHorizontally); });
digibib/ls.ext
redef/catalinker/client/src/bootstrap.js
JavaScript
mit
212
$(function () { $('.banner').unslider({ keys: true, // Enable keyboard (left, right) arrow shortcuts dots: true, // Display dot navigation // fluid: true // Support responsive design. May break non-responsive designs delay: 100000 }); $(document).ready( function() { $('.navbar').stickUp({ parts: { 0: 'feature', 1: 'plugin', 2: 'scene', 3: 'case', 4: 'price', 5: 'contact' }, itemClass: 'js-nav', itemHover: 'active' }); }); }) //功能组件 $(function(){ $('.plugin-cover').hover(function(){ $('.js-cover').show() },function(){ $('.js-cover').hide() }) $('.plugin-advert').hover(function(){ $('.js-advert').show() },function(){ $('.js-advert').hide() }) $('.plugin-menu').hover(function(){ $('.js-menu').show() },function(){ $('.js-menu').hide() }) $('.plugin-im').hover(function(){ $('.js-im').show() },function(){ $('.js-im').hide() }) $('.plugin-show').hover(function(){ $('.js-show').show() },function(){ $('.js-show').hide() }) }); // 案例 $(function(){ $('.js-tabs').tabulous({ effect: 'slideLeft' }); }); // 地图 function init() { var myLatlng = new qq.maps.LatLng(19.951274,110.556697); var myOptions = { zoom: 13, draggable: false, scrollwheel: false, disableDoubleClickZoom: false, center: myLatlng, // mapTypeId: qq.maps.MapTypeId.ROADMAP } var map = new qq.maps.Map(document.getElementById("container"), myOptions); var marker = new qq.maps.Label({ position: myLatlng, map: map, content:'云宿网络' }); } function loadScript() { var script = document.createElement("script"); script.type = "text/javascript"; //果然大厂,我服 script.src = "http://map.qq.com/api/js?v=2.exp&callback=init"; document.body.appendChild(script); } window.onload = loadScript;
Fucntion/yunshang
js/main.js
JavaScript
mit
2,159
version https://git-lfs.github.com/spec/v1 oid sha256:11d2d5f1087aaf16e2c1550a27b9b4c9721d64d389fd7ce317619cdfd8ffb13d size 21987
yogeshsaroya/new-cdnjs
ajax/libs/codemirror/3.20.0/addon/tern/tern.js
JavaScript
mit
130
version https://git-lfs.github.com/spec/v1 oid sha256:80d4cc38d4c3e94945c781ae3e980cb69f999fd27430feae888b961be813c6bb size 933
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.15.0/scrollview-list/scrollview-list-min.js
JavaScript
mit
128
/** * @file 编译首页文件,编译为中文版和英文版 * @author mengke01(kekee000@gmail.com) */ module.exports = function main(tpl) { return 'module.exports=' + JSON.stringify(tpl); };
ecomfe/fonteditor
build/tpl-loader.js
JavaScript
mit
203
var searchData= [ ['uchar',['uchar',['../utils_8h.html#a65f85814a8290f9797005d3b28e7e5fc',1,'utils.h']]], ['uint',['uint',['../utils_8h.html#a91ad9478d81a7aaf2593e8d9c3d06a14',1,'utils.h']]], ['uint16',['uint16',['../utils_8h.html#ac2a9e79eb120216f855626495b7bd18a',1,'utils.h']]], ['uint32',['uint32',['../utils_8h.html#acbd4acd0d29e2d6c43104827f77d9cd2',1,'utils.h']]], ['uint64',['uint64',['../utils_8h.html#abc0f5bc07737e498f287334775dff2b6',1,'utils.h']]], ['uint8',['uint8',['../utils_8h.html#a33a5e996e7a90acefb8b1c0bea47e365',1,'utils.h']]], ['ulong',['ulong',['../utils_8h.html#a718b4eb2652c286f4d42dc18a8e71a1a',1,'utils.h']]], ['use_5fsparse_5fhash',['USE_SPARSE_HASH',['../utils_8h.html#ace515f8c98b147abd94cb50505f6d375',1,'utils.h']]], ['ushort',['ushort',['../utils_8h.html#ab95f123a6c9bcfee6a343170ef8c5f69',1,'utils.h']]], ['utils_2ecpp',['utils.cpp',['../utils_8cpp.html',1,'']]], ['utils_2eh',['utils.h',['../utils_8h.html',1,'']]] ];
DDuarte/feup-cal
Project2/docs/html/search/all_75.js
JavaScript
mit
976
this.NesDb = this.NesDb || {}; NesDb[ '6A21DA874662C9B0F9C8F81241D5FBC89F3E2323' ] = { "$": { "name": "Galaga: Demons of Death", "class": "Licensed", "catalog": "NES-AG-EEC", "publisher": "Bandai", "developer": "Namco", "region": "Europe", "players": "2", "date": "1989-07-04" }, "cartridge": [ { "$": { "system": "NES-PAL-B", "crc": "999584A8", "sha1": "6A21DA874662C9B0F9C8F81241D5FBC89F3E2323", "dump": "ok", "dumper": "piteta", "datedumped": "2008-02-28" }, "board": [ { "$": { "type": "NES-NROM-256", "pcb": "NES-NROM-256-05", "mapper": "0" }, "prg": [ { "$": { "name": "PAL-AG-0 PRG", "size": "32k", "crc": "D0E899CA", "sha1": "33EBC0CB147519D88E76017D9EAC55DBC9FFD010" } } ], "chr": [ { "$": { "name": "NES-AG-0 CHR", "size": "8k", "crc": "E2D5964E", "sha1": "62B2CD49A6A4C6F1E2B0742DB3B7493E167E9A23" } } ], "cic": [ { "$": { "type": "3195A" } } ], "pad": [ { "$": { "h": "0", "v": "1" } } ] } ] } ] };
peteward44/WebNES
project/js/db/6A21DA874662C9B0F9C8F81241D5FBC89F3E2323.js
JavaScript
mit
1,240
formApp.service('dataServices', ['$firebase', function($firebase) { return { getUID : function() { return firebase.database().ref('/users/' + firebase.auth().currentUser.uid).once('value'); }, getUserFirstName: function () { return firebase.database().ref('/users/' + firebase.auth().currentUser.uid + '/FirstName').once('value'); }, getUserLastName: function () { return firebase.database().ref('/users/' + firebase.auth().currentUser.uid + '/LastName').once('value'); }, getFormsMetadata : function() { return firebase.database().ref('FormMetaData').once('value'); }, getFormOwnerFirstName : function(uid) { return firebase.database().ref('/users/' + uid + '/FirstName').once('value'); }, getFormOwnerLastName: function(uid) { return firebase.database().ref('/users/' + uid + '/LastName').once('value'); }, newFormMetaData: function(UID, formName, jobNumber) { return firebase.database().ref('/FormMetaData/' + jobNumber).set({ dateCreated: Date.now(), jobName: formName, jobNumber: jobNumber, ownedBy: UID, status: "Ongoing" }); }, }; }]);
SirDigbyChickenCaesar/AngularWebForm
components/scripts/services/dataServices.js
JavaScript
mit
1,119
Ibis.Parser = (function () { var Lexer = Ibis.Lexer; var Expr = Ibis.Expr; var Value = Ibis.Value; var IbisError = Ibis.IbisError; var exports = function () { return { ofString: ofString, parse: parse }; }; function ofString(string) { return { lexer: Lexer.ofString(string), headToken: null } } function parse(parser) { lookAhead(parser); if (parser.headToken == "EOF") { return null; } return parseStmt(parser); } function lookAhead(parser) { if (Lexer.advance(parser.lexer)) { parser.headToken = Lexer.token(parser.lexer); } else { parser.headToken = "EOF"; } } function parseStmt(parser) { var expr = parseDef(parser); switch (parser.headToken) { case "EOF": case ";;": break; default: throw new IbisError(expected(parser, ";;")); } return expr; } function parseDef(parser) { var expr = null; switch (parser.headToken) { case "let": expr = parseLet(parser); break; case "type": expr = parseTypeDef(parser); break; default: expr = parseExpr(parser); break; } return expr; } function parseExpr(parser) { return parseCompExpr(parser); } function parseCompExpr(parser) { var expr = parseSimpleExpr(parser); if (parser.headToken == ";") { lookAhead(parser); expr = Expr.createSeq(expr, parseCompExpr(parser)); } return expr; } function parseSimpleExpr(parser) { var expr = null; switch (parser.headToken) { case "fun": expr = parseAbs(parser); break; case "if": expr = parseIf(parser); break; case "case": expr = parseCase(parser); break; default: expr = parseLogicExpr(parser); break; } return expr; } function parseLogicExpr(parser) { return parseEqExpr(parser); } function parseEqExpr(parser) { var expr = parseConcatExpr(parser); while (parser.headToken.match(/=|<[>=]?|>=?/)) { var op = parser.headToken; lookAhead(parser); expr = createBinExpr(op, expr, parseConcatExpr(parser)); } return expr; } function parseConcatExpr(parser) { var expr = parseAddExpr(parser); if (parser.headToken.match(/\^/)) { var op = parser.headToken; lookAhead(parser); expr = createBinExpr(op, expr, parseConcatExpr(parser)); } return expr; } function parseAddExpr(parser) { var expr = parseMulExpr(parser); while (parser.headToken.match(/[+\-]/)) { var op = parser.headToken; lookAhead(parser); expr = createBinExpr(op, expr, parseMulExpr(parser)); } return expr; } function parseMulExpr(parser) { var expr = parseUnaryExpr(parser); while (parser.headToken.match(/[*\/]|mod/)) { var op = parser.headToken; lookAhead(parser); expr = createBinExpr(op, expr, parseUnaryExpr(parser)); } return expr; } function parseUnaryExpr(parser) { var expr = null; switch (parser.headToken) { case "-": lookAhead(parser); expr = Expr.createApp(Expr.createVar("(~-)"), parseUnaryExpr(parser)); break; default: expr = parsePrimExpr(parser); break; } return expr; } function parsePrimExpr(parser) { var expr = parseAtom(parser); while (parser.headToken == "INT" || parser.headToken == "IDENT" || parser.headToken == "STRING" || parser.headToken == "true" || parser.headToken == "false" || parser.headToken == "(") { expr = Expr.createApp(expr, parseAtom(parser)); } return expr; } function parseAtom(parser) { var expr = null; switch (parser.headToken) { case "INT": expr = parseInt(parser); break; case "STRING": expr = parseString(parser); break; case "IDENT": expr = parseIdent(parser); break; case "true": expr = parseTrue(parser); break; case "false": expr = parseFalse(parser); break; case "(": expr = parseParen(parser); break; default: throw new IbisError(unexpected(parser)); } return expr; } function parseInt(parser) { var expr = Expr.createConst(Value.createInt(Lexer.value(parser.lexer))); lookAhead(parser); return expr; } function parseString(parser) { var expr = Expr.createConst(Value.createString(Lexer.value(parser.lexer))); lookAhead(parser); return expr; } function parseIdent(parser) { var expr = Expr.createVar(Lexer.value(parser.lexer)); lookAhead(parser); return expr; } function parseAbs(parser) { lookAhead(parser); if (parser.headToken != "IDENT") { throw new IbisError(expected(parser, "IDENT")); } var varName = Expr.createVar(Lexer.value(parser.lexer)); lookAhead(parser); if (parser.headToken != "->") { throw new IbisError(expected(parser, "->")); } lookAhead(parser); var bodyExpr = parseSimpleExpr(parser); return Expr.createAbs(varName, bodyExpr); } function parseLet(parser) { lookAhead(parser); switch (parser.headToken) { case "IDENT": break; case "rec": return parseLetRec(parser); case "(": return parseLetTuple(parser, []); default: throw new IbisError(expected(parser, "IDENT")); } var varName = Lexer.value(parser.lexer); lookAhead(parser); if (parser.headToken != "=") { throw new IbisError(expected(parser, "=")); } lookAhead(parser); var valueExpr = parseSimpleExpr(parser); return Expr.createLet(varName, valueExpr); } function parseLetRec(parser) { lookAhead(parser); if (parser.headToken != "IDENT") { throw new IbisError(expected(parser, "IDENT")); } var varName = Expr.createVar(Lexer.value(parser.lexer)); lookAhead(parser); if (parser.headToken != "=") { throw new IbisError(expected(parser, "=")); } lookAhead(parser); if (parser.headToken != "fun") { throw new IbisError(expected(parser, "fun")); } var valueExpr = parseAbs(parser); return Expr.createLetRec(varName, valueExpr); } function parseLetTuple(parser, varNames) { lookAhead(parser); if (parser.headToken != "IDENT") { throw new IbisError(expected(parser, "IDENT")); } varNames.push(Lexer.value(parser.lexer)); lookAhead(parser); if (parser.headToken == ",") { return parseLetTuple(parser, varNames); } if (parser.headToken != ")") { throw new IbisError(expected(parser, ")")); } lookAhead(parser); if (parser.headToken != "=") { throw new IbisError(expected(parser, "=")); } lookAhead(parser); var valueExpr = parseSimpleExpr(parser); return Expr.createLetTuple(varNames, valueExpr); } function parseTrue(parser) { var expr = Expr.createConst(Value.True); lookAhead(parser); return expr; } function parseFalse(parser) { var expr = Expr.createConst(Value.False); lookAhead(parser); return expr; } function parseIf(parser) { lookAhead(parser); var condExpr = parseSimpleExpr(parser); if (parser.headToken != "then") { throw new IbisError(expected(parser, "then")); } lookAhead(parser); var thenExpr = parseSimpleExpr(parser); if (parser.headToken != "else") { throw new IbisError(expected(parser, "else")); } lookAhead(parser); var elseExpr = parseSimpleExpr(parser); return Expr.createIf(condExpr, thenExpr, elseExpr); } function parseCase(parser) { lookAhead(parser); var variantExpr = parseSimpleExpr(parser); if (parser.headToken != "of") { throw new IbisError(expected(parser, "of")); } var clauseExprs = {}; parseCaseClauses(parser, clauseExprs); var elseClause = null; if (parser.headToken == "else") { elseClause = parseElseClause(parser); } return Expr.createCase(variantExpr, clauseExprs, elseClause); } function parseCaseClauses(parser, clauseExprs) { lookAhead(parser); var ctorName = ""; switch (parser.headToken) { case "IDENT": ctorName = Lexer.value(parser.lexer); break; case "else": return; default: throw new IbisError(expected(parser, "IDENT")); } lookAhead(parser); if (parser.headToken != "->") { throw new IbisError(expected(parser, "->")); } lookAhead(parser); var bodyExpr = parseSimpleExpr(parser); clauseExprs[ctorName] = bodyExpr; if (parser.headToken == "|") { parseCaseClauses(parser, clauseExprs); } } function parseElseClause(parser) { lookAhead(parser); if (parser.headToken != "->") { throw new IbisError(expected(parser, "->")); } lookAhead(parser); return parseSimpleExpr(parser); } function parseParen(parser) { lookAhead(parser); if (parser.headToken == ")") { return parseUnit(parser); } var expr = parseExpr(parser); if (parser.headToken == ",") { return parseTuple(parser, [expr]); } if (parser.headToken != ")") { throw new IbisError(expected(parser, ")")); } lookAhead(parser); return expr; } function parseUnit(parser) { var expr = Expr.createConst(Value.Unit); lookAhead(parser); return expr; } function parseTuple(parser, exprArray) { lookAhead(parser); exprArray.push(parseExpr(parser)); if (parser.headToken == ",") { return parseTuple(parser, exprArray); } if (parser.headToken != ")") { throw new IbisError(expected(parser, ")")); } lookAhead(parser); return Expr.createTuple(exprArray); } function createBinExpr(op, lhs, rhs) { return Expr.createApp(Expr.createApp(Expr.createVar("(" + op + ")"), lhs), rhs); } function parseTypeDef(parser) { lookAhead(parser); if (parser.headToken != "IDENT") { throw new IbisError(expected(parser, "IDENT")); } var typeName = Lexer.value(parser.lexer); lookAhead(parser); if (parser.headToken != "=") { throw new IbisError(expected(parser, "(")); } var typeCtors = {}; parseTypeCtors(parser, typeCtors); return Expr.createVariantDef(typeName, typeCtors); } function parseTypeCtors(parser, map) { lookAhead(parser); if (parser.headToken != "IDENT") { throw new IbisError(expected(parser, "IDENT")); } var ctorName = Lexer.value(parser.lexer); lookAhead(parser); if (parser.headToken != "of") { throw new IbisError(expected(parser, "of")); } lookAhead(parser); var typeExpr = parseTypeExpr(parser); map[ctorName] = typeExpr; if (parser.headToken == "|") { parseTypeCtors(parser, map); return; } } function parseTypeExpr(parser) { var typeExpr = parseTypeMulExpr(parser); if (parser.headToken == "->") { lookAhead(parser); return Expr.createTypeFun(typeExpr, parseTypeExpr(parser)); } return typeExpr; } function parseTypeMulExpr(parser) { var typeExpr = parseTypeAtom(parser); var typeExprArray = [typeExpr]; while (parser.headToken == "*") { lookAhead(parser); typeExprArray.push(parseTypeAtom(parser)); } if (typeExprArray.length != 1) { return Expr.createTypeMul(typeExprArray); } return typeExpr; } function parseTypeAtom(parser) { var typeExpr = null; switch (parser.headToken) { case "IDENT": typeExpr = parseTypeVar(parser); break; case "(": typeExpr = parseTypeParen(parser); break; default: throw new IbisError(unexpected(parser)); } return typeExpr; } function parseTypeVar(parser) { var typeExpr = Expr.createTypeVar(Lexer.value(parser.lexer)); lookAhead(parser); return typeExpr; } function parseTypeParen(parser) { lookAhead(parser); var expr = parseTypeExpr(parser); if (parser.headToken != ")") { throw new IbisError(expected(parser, ")")); } lookAhead(parser); return expr; } function expected(parser, expectedToken) { return "unexpected " + parser.headToken + ", expected " + expectedToken; } function unexpected(parser) { return "unexpected " + parser.headToken } return exports(); })();
takuto-h/ibis-js
src/parser.js
JavaScript
mit
12,480
version https://git-lfs.github.com/spec/v1 oid sha256:37ee2a4a8074c1758213f80992b44af753bc33a3fd709dda63ac7a169520a584 size 23342
yogeshsaroya/new-cdnjs
ajax/libs/angular-filter/0.3.3/angular-filter.js
JavaScript
mit
130
/** * @file mip-ilaw66-xzh-index 组件 * @author */ define(function (require) { var $ = require('zepto'); var customElement = require('customElement').create(); /** * 备注:部分地方存在全局选择因为部分地方规则限定 */ customElement.prototype.firstInviewCallback = function () { // TODO var $el = $(this.element); bannerusernum(); var questionType; var tabHref; var lawyerId = ''; var flg = 0; var qSt = getQueryString('questionType'); var search = location.search.toLowerCase(); var channel = $el.find('#channel').val(); var userId = $el.find('#userId').val(); if (sessionStorage.getItem('ishomeorder')) { sessionStorage.clear('ishomeorder'); } function getQueryString(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.search.substr(1).match(reg); if (r !== null) { return unescape(r[2]); } return null; } function PopUp(option) { this.init(option); return this; } PopUp.prototype = { constructor: PopUp, init: function (option) { var This = this; This.option = { title: '弹窗标题', main: '弹窗内容', yes: '确定', no: '取消', popYes: function () {}, popNo: function () {} }; $.extend(true, this.option, option || {}); This.dom(); This.bindEvent(); }, dom: function () { var This = this; This.body = $('body'); var btnN = '<div class="back-leave" id="js-back-leave">' + This.option.yes + '</div>' + '<div class="back-continue" id="js-back-continue">' + This.option.no + '</div>'; if (!This.option.yes) { btnN = '<div class="back-continue back-continue__one" id="js-back-continue">' + This.option.no + '</div>'; } This.main = '<div class="back__pop popUP" style="display:none;" id="back__pop">' + '<div class="layer__wrapper"></div>' + '<div class="back__popLayer">' + '<span>' + This.option.title + '</span>' + '<span>' + This.option.main + '</span>' + btnN + '</div>' + '</div>'; This.body.append(This.main); This.PopUp = $el.find('.popUP'); This.PopUp.show(); }, bindEvent: function () { var This = this; // 点击离开事件 This.PopUp.on('click', '#js-back-leave', function () { This.PopUp.remove(); This.option.popYes(); }); // 点击确认事件 This.PopUp.on('click', '#js-back-continue', function () { This.PopUp.remove(); This.option.popNo(); }); // 点击遮罩层事件 --- 点击不关闭,必须点按钮 /*This.PopUp.on('click', '.layer__wrapper', function () { This.PopUp.remove(); })*/ } }; window.PopUp = PopUp; // 取消内容显示样式 function ToastUp(option) { this.init(option); return this; } ToastUp.prototype = { constructor: ToastUp, init: function (option) { var This = this; This.option = { main: '显示内容' }; $.extend(true, this.option, option || {}); This.dom(); This.bindEvent(); }, dom: function () { var This = this; This.body = $('body'); This.main = '<div class="back__pop ToastUp" style="display:none;" id="back__pop">' + '<div class="layer__wrapper layer__wrapper__toast"></div>' + '<div class="back__popLayer__toast">' + '<span>' + This.option.main + '</span>' + '</div>' + '</div>'; This.body.append(This.main); This.ToastUp = $el.find('.ToastUp'); This.ToastUp.show(); }, bindEvent: function () { var This = this; // 显示内容2秒 setTimeout(function () { This.ToastUp.remove(); }, 2000); } }; window.ToastUp = ToastUp; function backOr(f, a, e, d, c, b) { new PopUp({ title: f, main: a, yes: e, no: d, popYes: function (g) { c.call(this, g); }, popNo: function (g) { b.call(this, g); } }); } function toastOr(a) { new ToastUp({ main: a }); } function getQueryString(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.search.substr(1).match(reg); if (r !== null) { return unescape(r[2]); } return null; } var indexmessage = getQueryString('data'); if (indexmessage === 'ERROR' || indexmessage === 'ERROR1') { $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; $el.find('.popUp_sysErr').show(); } else if (indexmessage === 'ERROR2') { $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; $el.find('.popUp_unpaidErr').show(); } else if (indexmessage === 'ERROR3') { $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; $el.find('.popUp_unFinishedBillErr').show(); } else if (indexmessage === 'ERROR4') { $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; $el.find('#messagecontem').text('您今日取消咨询已达3次,请明天再来'); $el.find('.popUp_unpaidErr').show(); } $el.find('.headerright').click(function () { if (!userId) { sessionStorage.setItem('ishomeorder', '1'); } // window.top.location.href = 'mipilaw66xzh_orderlist'; window.top.location.href = 'baiduxzh/authorize?urlstring=mipilaw66xzh_orderlist'; }); // 公共 var flg = 0; // 滚屏控制 有弹出层出现 不可滚动 function controlScroll() { flg = $el.find('.background_kuang').css('display') !== 'none' ? 1 : 0; } $(window).scroll(function (a) { controlScroll(); if (flg === 1) { document.body.scrollTop = document.documentElement.scrollTop = 0; } a.stopPropagation(); }); document.addEventListener('touchmove', function (event) { controlScroll(); if (flg === 1) { if (document.all) { window.event.returnValue = false; } else { event.preventDefault(); } } }); function haveNoPaidOrder(b) { $el.find('#topay').click(function () { var a = false; var d = ''; $.ajax({ async: false, type: 'GET', data: { requestIdList: b.requestId }, url: 'checkFreeBill', success: function (c) { if (c.result === 2) { a = true; d = c.message; } }, error: function (c) { if (c.status === 403) { window.location.reload(); } } }); if (a) { toastOr(d); setTimeout(function () { window.location.reload(); }, 2e3); } else { $.ajax({ type: 'get', url: 'getRequestId', data: { requestId: b.requestId }, async: false, success: function (data) { console.log('是否合并支付单号:' + data); window.top.location.href = 'mipilaw66xzh_couponPay?requestId=' + data + '&questionType=' + b.questionType; }, error: function () { window.location.reload(); } }); } }); } $el.find('.media').click(function () { var tabHref = $(this).data('href'); $el.find('#' + $(this).data('href')).removeClass().addClass('tab-pane active'); flg = 1; event.preventDefault(); }); $el.find('.tab-content__close').click(function () { $(this).parent().parent().removeClass().addClass('tab-pane'); }); $el.find('.consulting').on('click', function () { var questionType = $(this).data('type'); directOrOrder(questionType); }); $el.find('.link_confirm').click(function (event) { $el.find('.popUp_sysErr').hide(); }); function directOrOrder(questionType) { // if ($el.find('#userId').val()) { // startConsulting(questionType); // } else { // var coudeurl=encodeURIComponent('request?questionType='+questionType) window.top.location.href = 'baiduxzh/authorize?questionType=' + questionType + '&urlstring=mipilaw66xzh_request'; // window.top.location.href = 'blank?questionType=' + questionType + '&channel=' + channel; // } } var tabHref; // function startConsulting(questionType) { // $.ajax({ // url: 'greeting?questionType=' + questionType + '&_csrf=' + $('#_csrf').val(), // type: 'POST', // success: function(data) { // if (data === 'ERROR' || data === 'ERROR1') { // $el.find('#' + tabHref).removeClass().addClass('tab-pane'); // flg = 0; // $el.find('.popUp_sysErr').show(); // } else if (data === 'ERROR2') { // $el.find('#' + tabHref).removeClass().addClass('tab-pane'); // flg = 0; // $el.find('.popUp_unpaidErr').show(); // } else if (data === 'ERROR3') { // $el.find('#' + tabHref).removeClass().addClass('tab-pane'); // flg = 0; // $el.find('.popUp_unFinishedBillErr').show(); // } else if (data === 'ERROR4') { // // toastOr("您今日取消咨询已达3次,请明天再来"); // $el.find('#' + tabHref).removeClass().addClass('tab-pane'); // flg = 0; // alert('您今日取消咨询已达3次,请明天再来'); // } else { // $el.find('#' + tabHref).removeClass().addClass('tab-pane'); // flg = 0; // window.top.location.href = 'request?data=' + data + '&questionType=' + questionType; // } // }, // error: function() { // // window.location.reload(); // } // }); // } // 调用banner状态 function bannerusernum() { $.ajax({ type: 'GET', url: 'getOrderCount', dataType: 'json', success: function (a) { // console.log(a); var rvFlg = false; if (!a) { return; } var b; if (a.RQ) { b = a.RQ; /*slogon部位内容start*/ var lawyerId = b.lawyerId; var questionType = b.questionType; var pathnamePage = location.pathname; var timestamp3; if (a.RV) { rvFlg = true; timestamp3 = a.RV.reservationTimeString; } if (pathnamePage.indexOf('articleNav') < 1) { // 首页加载视频时 var tempMoreHtml = ''; tempMoreHtml += '<li><div class="total_user">' + '<mip-img src="tempbaidu/images/bab.png"></mip-img>' + '累计服务人数&nbsp;<i class="userTotalNum">' + numtransform(b.countAll) + ' </i> 人</div></li>'; tempMoreHtml += '<li><div class="total_user">' + '<mip-img src="tempbaidu/images/bab.png"></mip-img>' + '今日咨询人数&nbsp;<i class="userTodayNum">' + numtransform(b.countToday) + ' </i> 人 </div></li>'; showSlogonMsg(tempMoreHtml, 2000); var tempHtml = '<ul id="hearderbox">'; if (b.payState === 6) { // 咨询过,欠费的用户 tempHtml += '<li style="margin-bottom:0"><div class="topay">' + '<mip-img src="tempbaidu/images/paytipicon.png"></mip-img>' + '您有一个订单未支付<p id="topay">去支付</p></div></li>'; } if (rvFlg) { tempHtml += '<li style="margin-bottom:0"><div class="tocheckreservation">' + '<mip-img src="tempbaidu/images/paytipicon.png"></mip-img>您预约了' + timestamp3 + '的咨询<p id="tocheckreservation">查看预约</p></div></li>'; } if (b.payState === 6 || rvFlg) { tempHtml += '</ul>'; $el.find('.slogonMsg').addClass('slogonMsg_new'); $el.find('.userinteractive, .headerbf').show(); $el.find('.userinteractive').html(tempHtml); // } if (b.payState === 6 && rvFlg) { startmarquee(20, 2000, 'hearderbox'); } haveNoPaidOrder(b); } $el.find('#tocheckreservation').click(function () { checkReservationExpired(); }); } } /*slogon部位内容end*/ }, error: function (a) { console.log('获取访问人数:' + a.countAll); } }); } // 初始化首页价格 $.ajax({ url: 'getPrice?channel=' + $el.find('#channel').val(), type: 'GET', // data: { // channel: $el.find('#channel').val() // }, success: function (data) { console.log(data); if (data.code === 200) { $el.find('.indexPrice').text(data.result); sessionStorage.setItem('productPrice', data.result); } }, error: function (jqXHR) { if (jqXHR.status === 403) { window.reload(); } } }); // var agreeImgSrc = $el.find('.radio-rule').find('img').attr('src'); $el.find('.tab-content__close').on('click', function () { $(this).parent().parent().removeClass().addClass('tab-pane'); flg = 0; }); $el.find('.media').on('click', function (event) { console.log($(this).data('href')); tabHref = $(this).data('href'); $el.find('#' + $(this).data('href')).removeClass().addClass('tab-pane active'); flg = 1; event.preventDefault(); }); /*新版操作end*/ document.addEventListener('touchmove', function (event) { // 监听滚动事件 if (flg === 1) { // 判断是遮罩显示时执行,禁止滚屏 event.preventDefault(); // 最关键的一句,禁止浏览器默认行为 } }); $el.find('.link_btn_uncheckErrConfirm').click(function () { $el.find('.popUp_err').hide(); }); function showSlogonMsg(tempMoreHtml, delayTime) { var tempHtml = '<ul id="slogonMsgId">'; tempHtml += tempMoreHtml; tempHtml += '</ul>'; $el.find('.slogonMsg').html(tempHtml); startmarquee(20, 2000, 'slogonMsgId'); } // 上下轮播 function startmarquee(speed, delay, ids) { // var lineH = $el.find('#slogonMsgId li').eq(0).height(); // 获取行高 var lineH = 40; // 获取 var p = false; var t; var o = document.getElementById(ids); if (!o) { return; } o.innerHTML += o.innerHTML; o.style.marginTop = 0; function start() { t = setInterval(scrolling, speed); if (!p) { o.style.marginTop = parseInt(o.style.marginTop, 10) - 1 + 'px'; } } function scrolling() { if (parseInt(o.style.marginTop, 10) % lineH !== 0) { o.style.marginTop = parseInt(o.style.marginTop, 10) - 1 + 'px'; if (Math.abs(parseInt(o.style.marginTop, 10)) >= o.scrollHeight / 2) { o.style.marginTop = 0; } } else { clearInterval(t); setTimeout(start, delay); } } setTimeout(start, delay); } // 开始咨询调用接口 function startConsulting(questionType) { $.ajax({ url: 'greeting?questionType=' + questionType + '&_csrf=' + $el.find('#_csrf').val(), type: 'POST', success: function (data) { if (data === 'ERROR' || data === 'ERROR1') { $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; $el.find('.popUp_sysErr').show(); } else if (data === 'ERROR2') { $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; $el.find('.popUp_unpaidErr').show(); } else if (data === 'ERROR3') { $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; $el.find('.popUp_unFinishedBillErr').show(); } else if (data === 'ERROR4') { // toastOr("您今日取消咨询已达3次,请明天再来"); $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; alert('您今日取消咨询已达3次,请明天再来'); } else { $el.find('#' + tabHref).removeClass().addClass('tab-pane'); flg = 0; window.top.location.href = 'mipilaw66xzh_request?data=' + data + '&questionType=' + questionType; } }, error: function () { window.location.reload(); } }); } // 预约咨询 function checkReservationExpired() { $.ajax({ type: 'GET', url: 'reservation/findRequestReservationByUserId', success: function (data) { console.log(data); if (data.info) { window.top.location.href = 'mipilaw66xzh_myreservation'; } else { toastOr(data.message); } }, error: function (a) { alert('系统异常,请稍后再试'); window.location.reload(); } }); } function numtransform(str) { var newStr = new Array(str.length + parseInt(str.length / 3, 10)); var strArray = str.split(''); newStr[newStr.length - 1] = strArray[strArray.length - 1]; var currentIndex = strArray.length - 1; for (var index = newStr.length - 1; index >= 0; index--) { if ((newStr.length - index) % 4 === 0) { newStr[index] = ','; } else { newStr[index] = strArray[currentIndex--]; } } var numafter = newStr.join(''); if (numafter.indexOf(',') === 0) { numafter = numafter.substring(1, numafter.length); } return numafter; } $el.find('.link_btn_sysErrConfirm').click(function () { $el.find('.popUp_sysErr').hide(); }); $el.find('.link_btn_unFinishedBillErrConfirm').click(function () { $el.find('.popUp_unFinishedBillErr').hide(); }); $el.find('.link_btn_unpaidErrConfirm').click(function () { // window.top.location.href = 'orderlist'; $el.find('.popUp_unpaidErr').hide(); }); $el.find('.link_btn_uncheckErrConfirm').click(function () { $el.find('.popUp_uncheckErr').hide(); $el.find('.popUp_confirm').hide(); }); /*暂挪去支付继续问弹窗*/ // 希望重试 $el.find('#still_reAsk').click(function () { $el.find('.popUp_confirm').hide(); $el.find('.loadingArea').show(); continueAsk2(lawyerId, questionType, '01', $el.find('#_csrf').val()); }); // 咨询其他律师时 $el.find('.link_others').click(function () { $el.find('.popUp_confirm').hide(); startConsulting(questionType); }); // function startConsulting(questionType, csrfToken, lawyerId) { // $.ajax({ // type: 'POST', // // data: { // // questionType: questionType, // // _csrf: csrfToken // // }, // url: 'greeting?questionType=' + questionType + '&_csrf=' + csrfToken, // success: function(data) { // if (data === 'ERROR' || data === 'ERROR1') { // $el.find('#err_msg').html('系统异常,请返回重新咨询'); // $el.find('.popUp_sysErr').fadeIn(); // } else if (data === 'ERROR2') { // $el.find('#err_msg').html('您有订单未支付,请支付后再咨询'); // $el.find('.popUp_sysErr').fadeIn(); // } else if (data === 'ERROR3') { // $el.find('#err_msg').html('您有订单未结束,请等待1分钟后再试'); // $el.find('.popUp_sysErr').fadeIn(); // } else { // if (lawyerId) { // window.top.location.href = 'request?data=' + data + '&questionType=' + questionType + '&lawyerId=' + lawyerId; // } else { // window.top.location.href = 'request?data=' + data + '&questionType=' + questionType; // } // } // }, // error: function(jqXHR) { // if (jqXHR.status === 403) { // window.location.reload(); // } // } // }); // } // 继续问---通知律师跳转到request页面(开始咨询;confirmTel页) function continueAsk(lawyerId, questionType, askingType, csrfToken) { $.ajax({ async: true, type: 'POST', url: 'continueAsk?lawyerId=' + lawyerId + '&questionType=' + questionType + '&_csrf=' + csrfToken, dataType: 'json', success: function (data) { $el.find('.loadingArea').hide(); var id = data.data; var state = data.state; if (id !== '') { window.top.location.href = 'mipilaw66xzh_request?data=' + id + '&questionType=' + questionType + '&askingType=' + askingType + '&lawyerId=' + lawyerId; } else { if (state === 1) { // 点击继续问,b律师正在服务中,设为true flg = true; $el.find('.popUp_confirm').fadeIn(); $el.find('#still_reAsk').attr('lawyerId', lawyerId); } else { var msg = data.error; $el.find('#tips').html(msg); $el.find('.popUp_confirm').hide(); $el.find('.popUp_uncheckErr').fadeIn(); } } }, error: function (jqXHR) { $el.find('.loadingArea').hide(); if (jqXHR.status === 403) { window.location.reload(); } } }); } // 继续问---通知律师跳转到informLawyer页面(orderlist页,首页slogon) function continueAsk2(lawyerId, questionType, askingType, csrfToken) { $.ajax({ async: true, type: 'POST', url: 'continueAsk?lawyerId=' + lawyerId + '&questionType=' + questionType + '&_csrf=' + csrfToken, dataType: 'json', success: function (data) { $el.find('.loadingArea').hide(); var id = data.data; var state = data.state; localStorage.setItem('reAskAvatar', data.avatar); localStorage.setItem('reAskName', data.lawyerName); localStorage.setItem('reAskSex', data.sex); if (id !== '') { // 传入lawyerId window.top.location.href = 'mipilaw66xzh_informLawyer?data=' + id + '&questionType=' + questionType + '&askingType=' + askingType + '&lawyerId=' + lawyerId; } else { $el.find('.loadingArea').hide(); if (state === 1) { // 点击继续问,b律师正在服务中,设为true flg = true; $el.find('.popUp_confirm').fadeIn(); $el.find('#still_reAsk').attr('lawyerId', lawyerId); } else { var msg = data.error; $el.find('#tips').html(msg); $el.find('.popUp_confirm').hide(); $el.find('.popUp_uncheckErr').fadeIn(); } } }, error: function (jqXHR) { $el.find('.loadingArea').hide(); if (jqXHR.status === 403) { window.location.reload(); } } }); } // continueAsk2 更改为 continueAskNew function continueAskNew(lawyerId, questionType, askingType, csrfToken, continueAskPage) { $.ajax({ async: true, type: 'POST', url: 'continueAskV3?lawyerId=' + lawyerId + '&questionType=' + questionType + '&_csrf=' + csrfToken + '&continueAskPage=' + continueAskPage, dataType: 'json', success: function (data) { console.log('继续问2', data); $el.find('.loadingArea').hide(); var id = data.data; var state = data.state; localStorage.setItem('reAskAvatar', data.avatar); localStorage.setItem('reAskName', data.lawyerName); localStorage.setItem('reAskSex', data.sex); localStorage.setItem('lawyerField', data.lawyerField); localStorage.setItem('goodCommentRate', data.goodCommentRate); if (id !== '') { // 传入lawyerId window.top.location.href = 'mipilaw66xzh_informLawyer?data=' + id + '&questionType=' + questionType + '&askingType=' + askingType + '&lawyerId=' + lawyerId + '&PABackJumpFlg=index'; } else { if (state === 1 || state === 2) { // 1.律师正在服务中 2.律师已下线 document.body.scrollTop = document.documentElement.scrollTop = 0; var title = '温馨提示'; var main = data.error + ',您可以稍后继续问,或由系统推荐其他律师'; var yes = '立刻推荐其他律师'; var no = '稍后继续问'; backOr(title, main, yes, no, function () { startConsulting(questionType); }, function () { $.ajax({ url: 'createContinueAskLater?lawyerId=' + lawyerId + '&questionType=' + questionType + '&_csrf=' + csrfToken, type: 'POST', // data: { // lawyerId: lawyerId, // questionType: questionType, // _csrf: csrfToken // }, success: function (data) { if (data === 'ERROR') { alert('系统异常'); } else { console.log(data); } }, error: function (jqXHR) { if (jqXHR.status === 403) { window.location.reload(); } } }); }); } else { var msg = data.error; $el.find('#tips').html(msg); $el.find('.popUp_confirm').hide(); $el.find('.popUp_uncheckErr').fadeIn(); } } }, error: function (jqXHR) { $el.find('.loadingArea').hide(); if (jqXHR.status === 403) { window.location.reload(); } } }); } }; return customElement; });
mipengine/mip-extensions-platform
mip-ilaw66-xzh-index/mip-ilaw66-xzh-index.js
JavaScript
mit
34,837
function mock(name) { var resolvedPath = process.cwd(); console.log(resolvedPath); try { var mockConfig = require(resolvedPath + '/mock.json'); } catch (e) { return { 'msg': 'no mock.json file!' } } return mockConfig[name] || []; } module.exports = mock;
devWayne/deserv
lib/mock.js
JavaScript
mit
318
// ------------------------------------ // Constants // ------------------------------------ export const COUNTER_INCREMENT = 'COUNTER_INCREMENT' // ------------------------------------ // Actions // ------------------------------------ export function increment (value = 1) { return { type : COUNTER_INCREMENT, payload : value } } /* This is a thunk, meaning it is a function that immediately returns a function for lazy evaluation. It is incredibly useful for creating async actions, especially when combined with redux-thunk! NOTE: This is solely for demonstration purposes. In a real application, you'd probably want to dispatch an action of COUNTER_DOUBLE and let the reducer take care of this logic. */ export const doubleAsync = () => { return (dispatch, getState) => { return new Promise((resolve) => { setTimeout(() => { dispatch(increment(getState().counter)) resolve() }, 200) }) } } export const actions = { increment, doubleAsync }
tinnguyenhuuletrong/react-metronic-dashboard
src/actions/counter.js
JavaScript
mit
1,032
"use strict"; var deepExtend = require("../../../util/deepExtend"); var lessTask = require("./lessTask"); var generateLessTasks = function generateLessTasks() { var gulp = arguments.length <= 0 || arguments[0] === undefined ? require("gulp") : arguments[0]; var options = arguments[1]; var _options = options; var taskName = _options.taskName; var _options$dependsOn = _options.dependsOn; var dependsOn = _options$dependsOn === undefined ? [] : _options$dependsOn; taskName = "build:css:less:" + taskName; options = deepExtend({}, options, { taskName: taskName, dependsOn: dependsOn }); gulp.task(taskName, dependsOn, function () { return lessTask(gulp, options); }); }; module.exports = generateLessTasks;
micnigh/gulp-frontend-tasks
dist/css/less/build/generateTasks.js
JavaScript
mit
746
import accounting from 'accounting'; export function toMoneyString(amount, withSign = false, postfix = 'SGD') { const sign = withSign && amount > 0 ? '+' : ''; return `${sign}${accounting.formatMoney(amount, '', 0, ' ')} ${postfix}`; }
singaporesamara/SOAS-DASHBOARD
app/utils/helpers/index.js
JavaScript
mit
241
"use strict"; module.exports = function(Promise, CapturedTrace) { var async = require("{{ site.baseurl }}async.js"); var Warning = require("{{ site.baseurl }}errors.js").Warning; var util = require("{{ site.baseurl }}util.js"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var debugging = false || (util.isNode && (!!process.env["BLUEBIRD_DEBUG"] || process.env["NODE_ENV"] === "development")); if (debugging) { async.disableTrampolineIfNecessary(); } Promise.prototype._ignoreRejections = function() { this._unsetRejectionIsUnhandled(); this._bitField = this._bitField | 16777216; }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 16777216) !== 0) return; this._setRejectionIsUnhandled(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { CapturedTrace.fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._getCarriedStackTrace() || this._settledValue; this._setUnhandledRejectionIsNotified(); CapturedTrace.fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 524288; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~524288); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 524288) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 2097152; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~2097152); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 2097152) > 0; }; Promise.prototype._setCarriedStackTrace = function (capturedTrace) { this._bitField = this._bitField | 1048576; this._fulfillmentHandler0 = capturedTrace; }; Promise.prototype._isCarryingStackTrace = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._getCarriedStackTrace = function () { return this._isCarryingStackTrace() ? this._fulfillmentHandler0 : undefined; }; Promise.prototype._captureStackTrace = function () { if (debugging) { this._trace = new CapturedTrace(this._peekContext()); } return this; }; Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { if (debugging && canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = CapturedTrace.parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } }; Promise.prototype._warn = function(message) { var warning = new Warning(message); var ctx = this._peekContext(); if (ctx) { ctx.attachExtraTrace(warning); } else { var parsed = CapturedTrace.parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } CapturedTrace.formatAndLogError(warning, ""); }; Promise.onPossiblyUnhandledRejection = function (fn) { possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; }; Promise.longStackTraces = function () { if (async.haveItemsQueued() && debugging === false ) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); } debugging = CapturedTrace.isSupported(); if (debugging) { async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return debugging && CapturedTrace.isSupported(); }; if (!CapturedTrace.isSupported()) { Promise.longStackTraces = function(){}; debugging = false; } return function() { return debugging; }; };
EdisonReklamebyraa/gautefalltomter
node_modules/node-sass/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/debuggability.js
JavaScript
mit
4,867
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ic_create = exports.ic_create = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" } }] };
xuan6/admin_dashboard_local_dev
node_modules/react-icons-kit/md/ic_create.js
JavaScript
mit
350
LOG("loading iCtl.js"); function iCtl(ctl_count) { LOG("iCtl(" + ctl_count + ")"); this.typeID = null; this.getTypeID = function() { return this.typeID; }; this.ctlNoteArray = initArray(-1, ctl_count); this.is_note_ctl = false; this.ctlCCArray = initArray(-1, ctl_count); this.is_cc_ctl = false; this.count = ctl_count; this.getCtlCount = function() { return this.count; }; } // // Overridden in implementation - event is relative to control index // iCtl.prototype.onNoteOn = function(ctl_index, value) { return; }; iCtl.prototype.onNoteOff = function(ctl_index) { return; }; iCtl.prototype.onUpdateCC = function(ctl_index, value) { return; }; // // Ctl functions // iCtl.prototype.setNoteArray = function(note_array) { for(var i = 0; i < note_array.length; i++) { if(i >= this.ctlNoteArray.length) { break; } if(note_array[i] >= 0 && note_array[i] <= 127) { this.ctlNoteArray[i] = note_array[i]; } } this.is_cc_ctl = false; this.is_note_ctl = true; }; iCtl.prototype.setCCArray = function(cc_array) { for(var i = 0; i < cc_array.length; i++) { if(i >= this.ctlCCArray.length) { break; } if(cc_array[i] >= 0 && cc_array[i] <= 127) { this.ctlCCArray[i] = cc_array[i]; } } this.is_note_ctl = false; this.is_cc_ctl = true; }; iCtl.prototype.setNoteRange = function(note, count) { for(var i = 0; i < count; i++) { if(i >= this.ctlNoteArray.length) { break; } if(note >= 0 && (note + i) <= 127) { this.ctlNoteArray[i] = note + i; } } this.is_cc_ctl = false; this.is_note_ctl = true; }; iCtl.prototype.setCCRange = function(cc, count) { for(var i = 0; i < count; i++) { if(i >= this.ctlCCArray.length) { break; } if(cc >= 0 && (cc + i) <= 127) { this.ctlCCArray[i] = cc + i; } } this.is_cc_ctl = false; this.is_note_ctl = true; }; iCtl.prototype.setNote = function(index, note) { if(index >= 0 && index <= this.count) { if(note >= 0 && note <= 127) { this.ctlNoteArray[index] = note; } } this.is_cc_ctl = false; this.is_note_ctl = true; }; iCtl.prototype.setCC = function(index, cc) { if(index >= 0 && index <= this.count) { if(cc >= 0 && cc <= 127) { this.ctlCCArray[index] = cc; } } this.is_note_ctl = false; this.is_cc_ctl = true; }; iCtl.prototype.getNoteIndex = function(note) { for(var i = 0; i < this.count; i++) { if(note == this.ctlNoteArray[i]) { return i; } } return -1; }; iCtl.prototype.getCCIndex = function(cc) { for(var i = 0; i < this.count; i++) { if(cc == this.ctlCCArray[i]) { return i; } } return -1; }; iCtl.prototype.noteOn = function(note, velocity) { if(this.is_note_ctl != true) { return -1; } var ctl_index = this.getNoteIndex(note); if(ctl_index == -1) { return -1; } this.onNoteOn(ctl_index, velocity); return ctl_index; }; iCtl.prototype.noteOff = function(note) { if(this.is_note_ctl != true) { return -1; } var ctl_index = this.getNoteIndex(note); if(ctl_index == -1) { return -1; } this.onNoteOff(ctl_index); return ctl_index; }; iCtl.prototype.updateCC = function(cc, value) { if(this.is_cc_ctl != true) { return -1; } var ctl_index = this.getCCIndex(cc); if(ctl_index == -1) { return -1; } this.onUpdateCC(ctl_index, value); return ctl_index; }; LOG("iCtl.js loaded");
shermanyo/shermap
iCtl.js
JavaScript
mit
3,530
var navbarButton = document.querySelector('.navbar__menu-button'); var navbarList = document.querySelector('.navbar__list'); var navbarListOpen = false; function toggleList() { navbarList.classList.toggle('navbar__list--active'); navbarListOpen = !navbarListOpen; } navbarButton.onclick = function() { toggleList(); };
logic-dev/LogicalCSS
src/js/navbar.js
JavaScript
mit
327
'use strict'; /** * Module dependencies */ var path = require('path'), config = require(path.resolve('./config/config')); /** * Transfers module init function. */ module.exports = function (app, db) { };
szaszolak/Bank-krwii
modules/transfers/server/config/transfers.server.config.js
JavaScript
mit
213
/** * Simple logger class. * * Assuming Firebug style console object is avaiable: http://getfirebug.com/logging * BUT it abstracts you from `console` avilabilty and implementation * as it will simply not run if the functions are not available. * * How it works: * ``` * var LOG = new Logger('function or class name or any other tag'); * LOG.info('some debug/notice information'); * LOG.warn('some warning (usually non-critical) information'); * LOG.error('some error (usually critical) information'); * ``` * * Note that you can pass any number of arguments and they will be stringified whenever possible. * ``` * data = {"test":123,abc:"def"} * LOG.info('the json data:', data); * ``` * * Output: * ``` * [tag] the json data:{ * "test":123,"abc":"def" * } * ``` * * Author: Maciej Jaros * Web: http://enux.pl/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license * GPL v3 http://opensource.org/licenses/GPL-3.0 * * @param {String} tag Tag to be put in console (e.g. class name). * @param {Object|Boolean} levels Preset for enabled levels (true|false for setting all levels). * @class Logger */ function Logger(tag, levels) { /** * Use to disable all levels for this logger instance. */ this.enabled = true; /** * Use to disable levels separately. */ this.enabledLevels = { info : true, warn : true, error : true }; /** * The tag text. * @private */ this._tag = tag; /** * Use to disable perfmonance logging. */ this.performanceEnabled = true; /** * Tracks performance tick for diffs. * @private */ this._performancePrevious = 0; // setup `_performanceNow` proxy for `performance.now` if (this.performanceEnabled) { this._performanceNow = (typeof(performance)!='undefined' && 'now' in performance) ? function () { return performance.now(); } // polly for iPhone... : function () { return (new Date()).getTime(); }; this._performancePrevious = this._performanceNow(); } this._initEnabled(levels); } /** * Init enabled levels. * @param {Object|Boolean} levels Preset for enabled levels (true|false for setting all levels). */ Logger.prototype._initEnabled = function (levels) { if (typeof(levels) === 'boolean') { this.enabled = levels; } else if (typeof(levels) === 'object') { for (var level in levels) { this.enabledLevels[level] = levels[level] ? true : false; } } }; /** * Check if logging is enabled for certain level. * * @param {String} level info|warn|error * @returns {Boolean} true if enabled */ Logger.prototype.isEnabled = function (level) { if (!this.enabled || typeof(console)==='undefined') { return false; } var enabled = false; switch (level) { case 'info': if ('log' in console) { enabled = this.enabledLevels.info; } break; case 'warn': if ('warn' in console) { enabled = this.enabledLevels.warn; } break; case 'error': if ('error' in console) { enabled = this.enabledLevels.error; } break; } return enabled; }; /** * Attempts to create a readable string from about anything. * * @private * * @param {mixed} variable Whatever to parse. * @returns {String} */ Logger.prototype._variableToReadableString = function (variable) { var text = variable; if (typeof(text) == 'undefined') { text = '[undefined]'; } else if (typeof(text) != 'string') { try { text = JSON.stringify(text); } catch (e) { try { text = JSON.stringify(JSON.decycle(text, true)); } catch (e) { text = text.toString(); } } text = text .replace(/","/g, '",\n"') // this should also work when a value is JSON.stringfied .replace(/\{"/g, '{\n"') .replace(/"\}(?=[,}]|$)/g, '"\n}') // this should also work when a value is JSON.stringfied ; } return text; }; /** * Render arguments for display in console. * * @private * * @param {Array} argumentsArray * This is either arguments array or a real Array object * (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments). * @returns {String} */ Logger.prototype._renderArguments = function (argumentsArray) { var text = ""; for (var i = 0; i < argumentsArray.length; i++) { text += this._variableToReadableString(argumentsArray[i]); } if (this._tag.length) { return "["+this._tag+"] " + text; } return text; }; /** * Performance info and checkpoint set. * * @param {String} comment Any comment e.g. tick info/ID. */ Logger.prototype.performance = function (comment) { if (this.performanceEnabled && this.isEnabled('info')) { var now = this._performanceNow(); this.info(comment, '; diff [ms]: ', now - this._performancePrevious); this._performancePrevious = now; } }; /** * Informational text, notice. * * @note All arugments are converted to text and passed to console. */ Logger.prototype.info = function () { if (this.isEnabled('info')) { console.log(this._renderArguments(arguments)); } }; /** * Warning text. * * @note All arugments are converted to text and passed to console. */ Logger.prototype.warn = function () { if (this.isEnabled('warn')) { console.warn(this._renderArguments(arguments)); } }; /** * Error text. * * @note All arugments are converted to text and passed to console. */ Logger.prototype.error = function () { if (this.isEnabled('error')) { console.error(this._renderArguments(arguments)); } }; if (typeof module !== 'undefined' && module.exports) { module.exports=Logger; }
Eccenux/veCustomSearch
src/logger.js
JavaScript
mit
5,749
requirejs(["js/pop.js"], function(app) { console.log('inited',app); app(); });
fulme/chrome-extension-scaffold
src/pop.js
JavaScript
mit
83
/*! JsRender v1.0.0-beta: http://github.com/BorisMoore/jsrender and http://jsviews.com/jsviews informal pre V1.0 commit counter: 63 */ /* * Optimized version of jQuery Templates, for rendering to string. * Does not require jQuery, or HTML DOM * Integrates with JsViews (http://jsviews.com/jsviews) * * Copyright 2015, Boris Moore * Released under the MIT License. */ (function(global, jQuery, undefined) { // global is the this object, which is window when running in the usual browser environment. "use strict"; if (jQuery && jQuery.render || global.jsviews) { return; } // JsRender is already loaded //========================== Top-level vars ========================== var versionNumber = "v1.0.0-beta", $, jsvStoreName, rTag, rTmplString, indexStr, // nodeJsModule, //TODO tmplFnsCache = {}, delimOpenChar0 = "{", delimOpenChar1 = "{", delimCloseChar0 = "}", delimCloseChar1 = "}", linkChar = "^", rPath = /^(!*?)(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g, // not object helper view viewProperty pathTokens leafToken rParams = /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(!*?[#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?[#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*(([)\]])(?=\s*[.^]|\s*$|[^\(\[])|[)\]])([([]?))|(\s+)/g, // lftPrn0 lftPrn bound path operator err eq path2 prn comma lftPrn2 apos quot rtPrn rtPrnDot prn2 space // (left paren? followed by (path? followed by operator) or (path followed by left paren?)) or comma or apos or quot or right paren or space rNewLine = /[ \t]*(\r\n|\n|\r)/g, rUnescapeQuotes = /\\(['"])/g, rEscapeQuotes = /['"\\]/g, // Escape quotes and \ character rBuildHash = /(?:\x08|^)(onerror:)?(?:(~?)(([\w$]+):)?([^\x08]+))\x08(,)?([^\x08]+)/gi, rTestElseIf = /^if\s/, rFirstElem = /<(\w+)[>\s]/, rAttrEncode = /[\x00`><"'&]/g, // Includes > encoding since rConvertMarkers in JsViews does not skip > characters in attribute strings rIsHtml = /[\x00`><\"'&]/, rHasHandlers = /^on[A-Z]|^convert(Back)?$/, rHtmlEncode = rAttrEncode, autoTmplName = 0, viewId = 0, charEntities = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "\x00": "&#0;", "'": "&#39;", '"': "&#34;", "`": "&#96;" }, htmlStr = "html", objectStr = "object", tmplAttr = "data-jsv-tmpl", $render = {}, jsvStores = { template: { compile: compileTmpl }, tag: { compile: compileTag }, helper: {}, converter: {} }, // jsviews object ($.views if jQuery is loaded) $views = { jsviews: versionNumber, settings: function(settings) { $extend($viewsSettings, settings); dbgMode($viewsSettings._dbgMode); if ($viewsSettings.jsv) { $viewsSettings.jsv(); } }, sub: { // subscription, e.g. JsViews integration View: View, Err: JsViewsError, tmplFn: tmplFn, cvt: convertArgs, parse: parseParams, extend: $extend, syntaxErr: syntaxError, onStore: {}, _ths: tagHandlersFromProps, _tg: function() { } // Constructor for tagDef }, map: dataMap, // If jsObservable loaded first, use that definition of dataMap _cnvt: convertVal, _tag: renderTag, _err: error }; function getDerivedMethod(baseMethod, method) { return function () { var ret, tag = this, prevBase = tag.base; tag.base = baseMethod; // Within method call, calling this.base will call the base method ret = method.apply(tag, arguments); // Call the method tag.base = prevBase; // Replace this.base to be the base method of the previous call, for chained calls return ret; }; } function getMethod(baseMethod, method) { // For derived methods (or handlers declared declaratively as in {{:foo onChange=~fooChanged}} replace by a derived method, to allow using this.base(...) // or this.baseApply(arguments) to call the base implementation. (Equivalent to this._super(...) and this._superApply(arguments) in jQuery UI) if ($isFunction(method)) { method = getDerivedMethod( !baseMethod ? noop // no base method implementation, so use noop as base method : baseMethod._d ? baseMethod // baseMethod is a derived method, so us it : getDerivedMethod(noop, baseMethod), // baseMethod is not derived so make its base method be the noop method method ); method._d = 1; // Add flag that this is a derived method } return method; } function tagHandlersFromProps(tag, tagCtx) { for (var prop in tagCtx.props) { if (rHasHandlers.test(prop)) { tag[prop] = getMethod(tag[prop], tagCtx.props[prop]); // Copy over the onFoo props, convert and convertBack from tagCtx.props to tag (overrides values in tagDef). // Note: unsupported scenario: if handlers are dynamically added ^onFoo=expression this will work, but dynamically removing will not work. } } } function retVal(val) { return val; } function noop() { return ""; } function dbgBreak(val) { debugger; // Insert breakpoint for debugging JsRender or JsViews. // Consider https://github.com/BorisMoore/jsrender/issues/239: // Usage examples: {{dbg:...}}, {{:~dbg(...)}}, {{for ... onAfterLink=~dbg}}, {{dbg .../}} etc. return this.base ? this.baseApply(arguments) : val; } function dbgMode(debugMode) { $viewsSettings._dbgMode = debugMode; indexStr = debugMode ? "Unavailable (nested view): use #getIndex()" : ""; // If in debug mode set #index to a warning when in nested contexts $tags("dbg", $helpers.dbg = $converters.dbg = debugMode ? dbgBreak : retVal); // Register {{dbg/}}, {{dbg:...}} and ~dbg() to insert break points for debugging - if in debug mode. } function JsViewsError(message) { // Error exception type for JsViews/JsRender // Override of $.views.sub.Error is possible this.name = ($.link ? "JsViews" : "JsRender") + " Error"; this.message = message || this.name; } function $extend(target, source) { var name; for (name in source) { target[name] = source[name]; } return target; } function $isFunction(ob) { return typeof ob === "function"; } (JsViewsError.prototype = new Error()).constructor = JsViewsError; //========================== Top-level functions ========================== //=================== // jsviews.delimiters //=================== function $viewsDelimiters(openChars, closeChars, link) { // Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^" // openChars, closeChars: opening and closing strings, each with two characters if (!$sub.rTag || openChars) { delimOpenChar0 = openChars ? openChars.charAt(0) : delimOpenChar0; // Escape the characters - since they could be regex special characters delimOpenChar1 = openChars ? openChars.charAt(1) : delimOpenChar1; delimCloseChar0 = closeChars ? closeChars.charAt(0) : delimCloseChar0; delimCloseChar1 = closeChars ? closeChars.charAt(1) : delimCloseChar1; linkChar = link || linkChar; openChars = "\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1; // Default is "{^{" closeChars = "\\" + delimCloseChar0 + "\\" + delimCloseChar1; // Default is "}}" // Build regex with new delimiters // tag (followed by / space or }) or cvtr+colon or html or code rTag = "(?:(?:(\\w+(?=[\\/\\s\\" + delimCloseChar0 + "]))|(?:(\\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\\*)))" + "\\s*((?:[^\\" + delimCloseChar0 + "]|\\" + delimCloseChar0 + "(?!\\" + delimCloseChar1 + "))*?)"; // make rTag available to JsViews (or other components) for parsing binding expressions $sub.rTag = rTag + ")"; rTag = new RegExp(openChars + rTag + "(\\/)?|(?:\\/(\\w+)))" + closeChars, "g"); // Default: bind tag converter colon html comment code params slash closeBlock // /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g rTmplString = new RegExp("<.*>|([^\\\\]|^)[{}]|" + openChars + ".*" + closeChars); // rTmplString looks for html tags or { or } char not preceded by \\, or JsRender tags {{xxx}}. Each of these strings are considered // NOT to be jQuery selectors } return [delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, linkChar]; } //========= // View.get //========= function getView(inner, type) { //view.get(inner, type) if (!type) { // view.get(type) type = inner; inner = undefined; } var views, i, l, found, view = this, root = !type || type === "root"; // If type is undefined, returns root view (view under top view). if (inner) { // Go through views - this one, and all nested ones, depth-first - and return first one with given type. found = view.type === type ? view : undefined; if (!found) { views = view.views; if (view._.useKey) { for (i in views) { if (found = views[i].get(inner, type)) { break; } } } else { for (i = 0, l = views.length; !found && i < l; i++) { found = views[i].get(inner, type); } } } } else if (root) { // Find root view. (view whose parent is top view) while (view.parent.parent) { found = view = view.parent; } } else { while (view && !found) { // Go through views - this one, and all parent ones - and return first one with given type. found = view.type === type ? view : undefined; view = view.parent; } } return found; } function getNestedIndex() { var view = this.get("item"); return view ? view.index : undefined; } getNestedIndex.depends = function() { return [this.get("item"), "index"]; }; function getIndex() { return this.index; } getIndex.depends = "index"; //========== // View.hlp //========== function getHelper(helper) { // Helper method called as view.hlp(key) from compiled template, for helper functions or template parameters ~foo var wrapped, view = this, ctx = view.linkCtx, res = (view.ctx || {})[helper]; if (res === undefined && ctx && ctx.ctx) { res = ctx.ctx[helper]; } if (res === undefined) { res = $helpers[helper]; } if (res) { if ($isFunction(res) && !res._wrp) { // If it is of type function, and not already wrapped, we will wrap it, so if called with no this pointer it will be called with the // view as 'this' context. If the helper ~foo() was in a data-link expression, the view will have a 'temporary' linkCtx property too. // Note that helper functions on deeper paths will have specific this pointers, from the preceding path. // For example, ~util.foo() will have the ~util object as 'this' pointer wrapped = function() { return res.apply((!this || this === global) ? view : this, arguments); }; wrapped._wrp = true; $extend(wrapped, res); // Attach same expandos (if any) to the wrapped function } } return wrapped || res; } //============== // jsviews._cnvt //============== function convertVal(converter, view, tagCtx, onError) { // self is template object or linkCtx object var tag, value, // if tagCtx is an integer, then it is the key for the compiled function to return the boundTag tagCtx boundTag = +tagCtx === tagCtx && view.tmpl.bnds[tagCtx-1], linkCtx = view.linkCtx; // For data-link="{cvt:...}"... onError = onError !== undefined && {props: {}, args: [onError]}; tagCtx = onError || (boundTag ? boundTag(view.data, view, $views) : tagCtx); value = tagCtx.args[0]; if (converter || boundTag) { tag = linkCtx && linkCtx.tag; if (!tag) { tag = $extend(new $sub._tg(), { _: { inline: !linkCtx, bnd: boundTag, unlinked: true }, tagName: ":", cvt: converter, flow: true, tagCtx: tagCtx, }); if (linkCtx) { linkCtx.tag = tag; tag.linkCtx = linkCtx; } tagCtx.ctx = extendCtx(tagCtx.ctx, (linkCtx ? linkCtx.view : view).ctx); } tag._er = onError && value; tagHandlersFromProps(tag, tagCtx); tagCtx.view = view; tag.ctx = tagCtx.ctx || {}; delete tagCtx.ctx; // Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id, view._.tag = tag; value = convertArgs(tag, tag.convert || converter !== "true" && converter)[0]; // If there is a convertBack but no convert, converter will be "true" // Call onRender (used by JsViews if present, to add binding annotations around rendered content) value = boundTag && view._.onRender ? view._.onRender(value, view, boundTag) : value; view._.tag = undefined; } return value != undefined ? value : ""; } function convertArgs(tag, converter) { var tagCtx = tag.tagCtx, view = tagCtx.view, args = tagCtx.args; converter = converter && ("" + converter === converter ? (view.getRsc("converters", converter) || error("Unknown converter: '" + converter + "'")) : converter); args = !args.length && !tagCtx.index // On the opening tag with no args, bind to the current data context ? [view.data] : converter ? args.slice() // If there is a converter, use a copy of the tagCtx.args array for rendering, and replace the args[0] in // the copied array with the converted value. But we do not modify the value of tag.tagCtx.args[0] (the original args array) : args; // If no converter, render with the original tagCtx.args if (converter) { if (converter.depends) { tag.depends = $sub.getDeps(tag.depends, tag, converter.depends, converter); } args[0] = converter.apply(tag, args); } return args; } //============= // jsviews._tag //============= function getResource(resourceType, itemName) { var res, store, view = this; while ((res === undefined) && view) { store = view.tmpl[resourceType]; res = store && store[itemName]; view = view.parent; } return res || $views[resourceType][itemName]; } function renderTag(tagName, parentView, tmpl, tagCtxs, isUpdate, onError) { // Called from within compiled template function, to render a template tag // Returns the rendered tag var tag, tags, attr, parentTag, i, l, itemRet, tagCtx, tagCtxCtx, content, tagDef, callInit, mapDef, thisMap, args, props, initialTmpl, ret = "", linkCtx = parentView.linkCtx || 0, ctx = parentView.ctx, parentTmpl = tmpl || parentView.tmpl, // if tagCtx is an integer, then it is the key for the compiled function to return the boundTag tagCtxs boundTag = +tagCtxs === tagCtxs && parentTmpl.bnds[tagCtxs-1]; if (tagName._is === "tag") { tag = tagName; tagName = tag.tagName; tagCtxs = tag.tagCtxs; } tag = tag || linkCtx.tag; onError = onError !== undefined && (ret += onError, [{props: {}, args: []}]); tagCtxs = onError || (boundTag ? boundTag(parentView.data, parentView, $views) : tagCtxs); l = tagCtxs.length; for (i = 0; i < l; i++) { if (!i && (!tmpl || !tag)) { tagDef = parentView.getRsc("tags", tagName) || error("Unknown tag: {{" + tagName + "}}"); } tagCtx = tagCtxs[i]; if (!linkCtx.tag || i && !linkCtx.tag._.inline || tag._er) { // Initialize tagCtx // For block tags, tagCtx.tmpl is an integer > 0 content = tagCtx.tmpl; content = tagCtx.content = content && parentTmpl.tmpls[content - 1]; $extend(tagCtx, { tmpl: (tag ? tag : tagDef).template || content, // Set the tmpl property to the content of the block tag render: renderContent, index: i, view: parentView, ctx: extendCtx(tagCtx.ctx, ctx) // Extend parentView.ctx // Possible future feature: //var updatedValueOfArg0 = this.tagCtx.get(0); //var updatedValueOfPropFoo = this.tagCtx.get("foo"); //var updatedValueOfCtxPropFoo = this.tagCtx.get("~foo"); //_fns: {}, //get: function(key) { // return (this._fns[key] = this._fns[key] || new Function("data,view,j,u", // "return " + $.views.sub.parse(this.params[+key === key ? "args" : (key.charAt(0) === "~" ? (key = key.slice(1), "ctx") : "props")][key]) + ";") // )(this.view.data, this.view, $views); //}, }); } if (tmpl = tagCtx.props.tmpl) { // If the tmpl property is overridden, set the value (when initializing, or, in case of binding: ^tmpl=..., when updating) tmpl = "" + tmpl === tmpl // if a string ? parentView.getRsc("templates", tmpl) || $templates(tmpl) : tmpl; tagCtx.tmpl = tmpl; } if (!tag) { // This will only be hit for initial tagCtx (not for {{else}}) - if the tag instance does not exist yet // Instantiate tag if it does not yet exist // If the tag has not already been instantiated, we will create a new instance. // ~tag will access the tag, even within the rendering of the template content of this tag. // From child/descendant tags, can access using ~tag.parent, or ~parentTags.tagName tag = new tagDef._ctr(); callInit = !!tag.init; tag._ = { inline: !linkCtx, unlinked: true }; if (linkCtx) { linkCtx.tag = tag; tag.linkCtx = linkCtx; } if (tag._.bnd = boundTag || linkCtx.fn) { // Bound if {^{tag...}} or data-link="{tag...}" tag._.arrVws = {}; } else if (tag.dataBoundOnly) { error("{^{" + tagName + "}} tag must be data-bound"); } tag.tagName = tagName; tag.parent = parentTag = ctx && ctx.tag; tag._def = tagDef; // same as tag.constructor.prototype tag.tagCtxs = tagCtxs; //TODO better perf for childTags() - keep child tag.tags array, (and remove child, when disposed) // tag.tags = []; // Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id } tagCtx.tag = tag; if (tag.dataMap && tag.tagCtxs) { tagCtx.map = tag.tagCtxs[i].map; // Copy over the compiled map instance from the previous tagCtxs to the refreshed ones } if (!tag.flow) { tagCtxCtx = tagCtx.ctx = tagCtx.ctx || {}; // tags hash: tag.ctx.tags, merged with parentView.ctx.tags, tags = tag.parents = tagCtxCtx.parentTags = ctx && extendCtx(tagCtxCtx.parentTags, ctx.parentTags) || {}; if (parentTag) { tags[parentTag.tagName] = parentTag; //TODO better perf for childTags: parentTag.tags.push(tag); } tags[tag.tagName] = tagCtxCtx.tag = tag; } } parentView._.tag = tag; if (!(tag._er = onError)) { tagHandlersFromProps(tag, tagCtxs[0]); tag.rendering = {}; // Provide object for state during render calls to tag and elses. (Used by {{if}} and {{for}}...) for (i = 0; i < l; i++) { tagCtx = tag.tagCtx = tag.tagCtxs[i]; props = tagCtx.props; args = convertArgs(tag, tag.convert); if (mapDef = props.dataMap || tag.dataMap) { if (args.length || props.dataMap) { thisMap = tagCtx.map; if (!thisMap || thisMap.src !== args[0] || isUpdate) { if (thisMap && thisMap.src) { thisMap.unmap(); // only called if observable map - not when only used in JsRender, e.g. by {{props}} } thisMap = tagCtx.map = mapDef.map(args[0], props); } args = [thisMap.tgt]; } } tag.ctx = tagCtx.ctx; if (!i && callInit) { initialTmpl = tag.template; tag.init(tagCtx, linkCtx, tag.ctx); callInit = undefined; if (tag.template !== initialTmpl) { tag._.tmpl = tag.template; // This will override the tag.template and also tagCtx.props.tmpl for all tagCtxs } } if (linkCtx) { // Set attr on linkCtx to ensure outputting to the correct target attribute. // Setting either linkCtx.attr or this.attr in the init() allows per-instance choice of target attrib. linkCtx.attr = tag.attr = linkCtx.attr || tag.attr; } itemRet = undefined; if (tag.render) { itemRet = tag.render.apply(tag, args); } args = args.length ? args : [parentView]; // no arguments - get data context from view. itemRet = itemRet !== undefined ? itemRet // Return result of render function unless it is undefined, in which case return rendered template : tagCtx.render(args[0], true) || (isUpdate ? undefined : ""); // No return value from render, and no template/content tagCtx.render(...), so return undefined ret = ret ? ret + (itemRet || "") : itemRet; // If no rendered content, this will be undefined } delete tag.rendering; } tag.tagCtx = tag.tagCtxs[0]; tag.ctx = tag.tagCtx.ctx; if (tag._.inline && (attr = tag.attr) && attr !== htmlStr) { // inline tag with attr set to "text" will insert HTML-encoded content - as if it was element-based innerText ret = attr === "text" ? $converters.html(ret) : ""; } return boundTag && parentView._.onRender // Call onRender (used by JsViews if present, to add binding annotations around rendered content) ? parentView._.onRender(ret, parentView, boundTag) : ret; } //================= // View constructor //================= function View(context, type, parentView, data, template, key, contentTmpl, onRender) { // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) var views, parentView_, tag, self = this, isArray = type === "array", self_ = { key: 0, useKey: isArray ? 0 : 1, id: "" + viewId++, onRender: onRender, bnds: {} }; self.data = data; self.tmpl = template; self.content = contentTmpl; self.views = isArray ? [] : {}; self.parent = parentView; self.type = type || "top"; // If the data is an array, this is an 'array view' with a views array for each child 'item view' // If the data is not an array, this is an 'item view' with a views 'hash' object for any child nested views // ._.useKey is non zero if is not an 'array view' (owning a data array). Use this as next key for adding to child views hash self._ = self_; self.linked = !!onRender; if (parentView) { views = parentView.views; parentView_ = parentView._; if (parentView_.useKey) { // Parent is an 'item view'. Add this view to its views object // self._key = is the key in the parent view hash views[self_.key = "_" + parentView_.useKey++] = self; self.index = indexStr; self.getIndex = getNestedIndex; tag = parentView_.tag; self_.bnd = isArray && (!tag || !!tag._.bnd && tag); // For array views that are data bound for collection change events, set the // view._.bnd property to true for top-level link() or data-link="{for}", or to the tag instance for a data-bound tag, e.g. {^{for ...}} } else { // Parent is an 'array view'. Add this view to its views array views.splice( // self._.key = self.index - the index in the parent view array self_.key = self.index = key, 0, self); } // If no context was passed in, use parent context // If context was passed in, it should have been merged already with parent context self.ctx = context || parentView.ctx; } else { self.ctx = context; } } View.prototype = { get: getView, getIndex: getIndex, getRsc: getResource, hlp: getHelper, _is: "view" }; //============= // Registration //============= function compileChildResources(parentTmpl) { var storeName, resources, resourceName, resource, settings, compile, onStore; for (storeName in jsvStores) { settings = jsvStores[storeName]; if ((compile = settings.compile) && (resources = parentTmpl[storeName + "s"])) { for (resourceName in resources) { // compile child resource declarations (templates, tags, tags["for"] or helpers) resource = resources[resourceName] = compile(resourceName, resources[resourceName], parentTmpl); if (resource && (onStore = $sub.onStore[storeName])) { // e.g. JsViews integration onStore(resourceName, resource, compile); } } } } } function compileTag(name, tagDef, parentTmpl) { var constructor, tmpl, baseTag, prop, compiledDef = new $sub._tg(); if ($isFunction(tagDef)) { // Simple tag declared as function. No presenter instantation. tagDef = { depends: tagDef.depends, render: tagDef }; } if (baseTag = tagDef.baseTag) { tagDef.flow = !!tagDef.flow; // default to false even if baseTag has flow=true tagDef.baseTag = baseTag = "" + baseTag === baseTag ? (parentTmpl && parentTmpl.tags[baseTag] || $tags[baseTag]) : baseTag; compiledDef = $extend(compiledDef, baseTag); for (prop in tagDef) { compiledDef[prop] = getMethod(baseTag[prop], tagDef[prop]); } } else { compiledDef = $extend(compiledDef, tagDef); } // Tag declared as object, used as the prototype for tag instantiation (control/presenter) if ((tmpl = compiledDef.template) !== undefined) { compiledDef.template = "" + tmpl === tmpl ? ($templates[tmpl] || $templates(tmpl)) : tmpl; } if (compiledDef.init !== false) { // Set init: false on tagDef if you want to provide just a render method, or render and template, but no constuctor or prototype. // so equivalent to setting tag to render function, except you can also provide a template. constructor = compiledDef._ctr = function() {}; (constructor.prototype = compiledDef).constructor = constructor; } if (parentTmpl) { compiledDef._parentTmpl = parentTmpl; } return compiledDef; } function baseApply(args) { // In derived method (or handler declared declaratively as in {{:foo onChange=~fooChanged}} can call base method, // using this.baseApply(arguments) (Equivalent to this._superApply(arguments) in jQuery UI) return this.base.apply(this, args); } function compileTmpl(name, tmpl, parentTmpl, options) { // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object //==== nested functions ==== function tmplOrMarkupFromStr(value) { // If value is of type string - treat as selector, or name of compiled template // Return the template object, if already compiled, or the markup string if (("" + value === value) || value.nodeType > 0) { try { elem = value.nodeType > 0 ? value : !rTmplString.test(value) // If value is a string and does not contain HTML or tag content, then test as selector && jQuery && jQuery(global.document).find(value)[0]; // TODO address case where DOM is not available // If selector is valid and returns at least one element, get first element // If invalid, jQuery will throw. We will stay with the original string. } catch (e) {} if (elem) { // Generally this is a script element. // However we allow it to be any element, so you can for example take the content of a div, // use it as a template, and replace it by the same content rendered against data. // e.g. for linking the content of a div to a container, and using the initial content as template: // $.link("#content", model, {tmpl: "#content"}); value = $templates[name = name || elem.getAttribute(tmplAttr)]; if (!value) { // Not already compiled and cached, so compile and cache the name // Create a name for compiled template if none provided name = name || "_" + autoTmplName++; elem.setAttribute(tmplAttr, name); // Use tmpl as options value = $templates[name] = compileTmpl(name, elem.innerHTML, parentTmpl, options); } elem = undefined; } return value; } // If value is not a string, return undefined } var tmplOrMarkup, elem; //==== Compile the template ==== tmpl = tmpl || ""; tmplOrMarkup = tmplOrMarkupFromStr(tmpl); // If options, then this was already compiled from a (script) element template declaration. // If not, then if tmpl is a template object, use it for options options = options || (tmpl.markup ? tmpl : {}); options.tmplName = name; if (parentTmpl) { options._parentTmpl = parentTmpl; } // If tmpl is not a markup string or a selector string, then it must be a template object // In that case, get it from the markup property of the object if (!tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr(tmpl.markup))) { if (tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode)) { // if the string references a compiled template object, but the debug or allowCode props are different, need to recompile tmplOrMarkup = tmplOrMarkup.markup; } } if (tmplOrMarkup !== undefined) { if (name && !parentTmpl) { $render[name] = function() { return tmpl.render.apply(tmpl, arguments); }; } if (tmplOrMarkup.fn || tmpl.fn) { // tmpl is already compiled, so use it, or if different name is provided, clone it if (tmplOrMarkup.fn) { if (name && name !== tmplOrMarkup.tmplName) { tmpl = extendCtx(options, tmplOrMarkup); } else { tmpl = tmplOrMarkup; } } } else { // tmplOrMarkup is a markup string, not a compiled template // Create template object tmpl = TmplObject(tmplOrMarkup, options); // Compile to AST and then to compiled function tmplFn(tmplOrMarkup.replace(rEscapeQuotes, "\\$&"), tmpl); } compileChildResources(options); return tmpl; } } function dataMap(mapDef) { function newMap(source, options) { this.tgt = mapDef.getTgt(source, options); } if ($isFunction(mapDef)) { // Simple map declared as function mapDef = { getTgt: mapDef }; } if (mapDef.baseMap) { mapDef = $extend($extend({}, mapDef.baseMap), mapDef); } mapDef.map = function(source, options) { return new newMap(source, options); }; return mapDef; } //==== /end of function compile ==== function TmplObject(markup, options) { // Template object constructor var htmlTag, wrapMap = $viewsSettings.wrapMap || {}, // Only used in JsViews. Otherwise empty: {} tmpl = $extend( { markup: markup, tmpls: [], links: {}, // Compiled functions for link expressions tags: {}, // Compiled functions for bound tag expressions bnds: [], _is: "template", render: fastRender }, options ); if (!options.htmlTag) { // Set tmpl.tag to the top-level HTML tag used in the template, if any... htmlTag = rFirstElem.exec(markup); tmpl.htmlTag = htmlTag ? htmlTag[1].toLowerCase() : ""; } htmlTag = wrapMap[tmpl.htmlTag]; if (htmlTag && htmlTag !== wrapMap.div) { // When using JsViews, we trim templates which are inserted into HTML contexts where text nodes are not rendered (i.e. not 'Phrasing Content'). // Currently not trimmed for <li> tag. (Not worth adding perf cost) tmpl.markup = $.trim(tmpl.markup); } return tmpl; } function registerStore(storeName, storeSettings) { function theStore(name, item, parentTmpl) { // The store is also the function used to add items to the store. e.g. $.templates, or $.views.tags // For store of name 'thing', Call as: // $.views.things(items[, parentTmpl]), // or $.views.things(name, item[, parentTmpl]) var onStore, compile, itemName, thisStore; if (name && typeof name === objectStr && !name.nodeType && !name.markup && !name.getTgt) { // Call to $.views.things(items[, parentTmpl]), // Adding items to the store // If name is a hash, then item is parentTmpl. Iterate over hash and call store for key. for (itemName in name) { theStore(itemName, name[itemName], item); } return $views; } // Adding a single unnamed item to the store if (item === undefined) { item = name; name = undefined; } if (name && "" + name !== name) { // name must be a string parentTmpl = item; item = name; name = undefined; } thisStore = parentTmpl ? parentTmpl[storeNames] = parentTmpl[storeNames] || {} : theStore; compile = storeSettings.compile; if (item === null) { // If item is null, delete this entry name && delete thisStore[name]; } else { item = compile ? (item = compile(name, item, parentTmpl)) : item; name && (thisStore[name] = item); } if (compile && item) { item._is = storeName; // Only do this for compiled objects (tags, templates...) } if (item && (onStore = $sub.onStore[storeName])) { // e.g. JsViews integration onStore(name, item, compile); } return item; } var storeNames = storeName + "s"; $views[storeNames] = theStore; jsvStores[storeName] = storeSettings; } //============== // renderContent //============== function $fastRender(data, context, noIteration) { var tmplElem = this.jquery && (this[0] || error('Unknown template: "' + this.selector + '"')), tmpl = tmplElem.getAttribute(tmplAttr); return fastRender.call(tmpl ? $templates[tmpl] : $templates(tmplElem), data, context, noIteration); } function tryFn(tmpl, data, view) { if ($viewsSettings._dbgMode) { try { return tmpl.fn(data, view, $views); } catch (e) { return error(e, view); } } return tmpl.fn(data, view, $views); } function fastRender(data, context, noIteration, parentView, key, onRender) { var self = this; if (!parentView && self.fn._nvw && !$.isArray(data)) { return tryFn(self, data, {tmpl: self}); // No views needed, so can directly call compiled template } return renderContent.call(self, data, context, noIteration, parentView, key, onRender); } function renderContent(data, context, noIteration, parentView, key, onRender) { function setItemVar(item) { // When itemVar is specified, set modified ctx with user-named ~item newCtx = $extend({}, context); newCtx[itemVar] = item; } // Render template against data as a tree of subviews (nested rendered template instances), or as a string (top-level template). // If the data is the parent view, treat as noIteration, re-render with the same data context. var i, l, newView, childView, itemResult, swapContent, tagCtx, contentTmpl, tag_, outerOnRender, tmplName, tmpl, noViews, itemVar, newCtx, self = this, result = ""; if (!!context === context) { noIteration = context; // passing boolean as second param - noIteration context = undefined; } if (typeof context !== objectStr) { context = undefined; // context must be a boolean (noIteration) or a plain object } if (key === true) { swapContent = true; key = 0; } if (self.tag) { // This is a call from renderTag or tagCtx.render(...) tagCtx = self; self = self.tag; tag_ = self._; tmplName = self.tagName; tmpl = tag_.tmpl || tagCtx.tmpl; tag_.noVws = noViews = self.attr && self.attr !== htmlStr, context = extendCtx(context, self.ctx); contentTmpl = tagCtx.content; // The wrapped content - to be added to views, below if (tagCtx.props.link === false) { // link=false setting on block tag // We will override inherited value of link by the explicit setting link=false taken from props // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. context = context || {}; context.link = false; } parentView = parentView || tagCtx.view; if (itemVar = tagCtx.props.itemVar) { if (itemVar.charAt(0) !== "~") { syntaxError("Use itemVar='~myItem'"); } itemVar = itemVar.slice(1); } data = arguments.length ? data : parentView; } else { tmpl = self; } if (tmpl) { if (!parentView && data && data._is === "view") { parentView = data; // When passing in a view to render or link (and not passing in a parent view) use the passed in view as parentView } if (parentView) { contentTmpl = contentTmpl || parentView.content; // The wrapped content - to be added as #content property on views, below onRender = onRender || parentView._.onRender; if (data === parentView) { // Inherit the data from the parent view. // This may be the contents of an {{if}} block data = parentView.data; } context = extendCtx(context, parentView.ctx); } if (!parentView || parentView.type === "top") { (context = context || {}).root = data; // Provide ~root as shortcut to top-level data. } if (!tmpl.fn) { tmpl = $templates[tmpl] || $templates(tmpl); } if (tmpl) { onRender = (context && context.link) !== false && !noViews && onRender; // If link===false, do not call onRender, so no data-linking marker nodes outerOnRender = onRender; if (onRender === true) { // Used by view.refresh(). Don't create a new wrapper view. outerOnRender = undefined; onRender = parentView._.onRender; } // Set additional context on views created here, (as modified context inherited from the parent, and to be inherited by child views) context = tmpl.helpers ? extendCtx(tmpl.helpers, context) : context; newCtx = context; if ($.isArray(data) && !noIteration) { // Create a view for the array, whose child views correspond to each data item. (Note: if key and parentView are passed in // along with parent view, treat as insert -e.g. from view.addViews - so parentView is already the view item for array) newView = swapContent ? parentView : (key !== undefined && parentView) || new View(context, "array", parentView, data, tmpl, key, contentTmpl, onRender); if (itemVar) { newView.it = itemVar; } itemVar = newView.it; for (i = 0, l = data.length; i < l; i++) { // Create a view for each data item. itemVar && setItemVar(data[i]); // use modified ctx with user-named ~item childView = new View(newCtx, "item", newView, data[i], tmpl, (key || 0) + i, contentTmpl, onRender); itemResult = tryFn(tmpl, data[i], childView); result += newView._.onRender ? newView._.onRender(itemResult, childView) : itemResult; } } else { // Create a view for singleton data object. The type of the view will be the tag name, e.g. "if" or "myTag" except for // "item", "array" and "data" views. A "data" view is from programmatic render(object) against a 'singleton'. itemVar && setItemVar(data); newView = swapContent ? parentView : new View(newCtx, tmplName || "data", parentView, data, tmpl, key, contentTmpl, onRender); if (tag_ && !self.flow) { newView.tag = self; } result += tryFn(tmpl, data, newView); } return outerOnRender ? outerOnRender(result, newView) : result; } } return ""; } //=========================== // Build and compile template //=========================== // Generate a reusable function that will serve to render a template against data // (Compile AST then build template function) function error(e, view, fallback) { var message = $viewsSettings.onError(e, view, fallback); if ("" + e === e) { // if e is a string, not an Exception, then throw new Exception throw new $sub.Err(message); } return !view.linkCtx && view.linked ? $converters.html(message) : message; } function syntaxError(message) { error("Syntax error\n" + message); } function tmplFn(markup, tmpl, isLinkExpr, convertBack, hasElse) { // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes // Used for compiling templates, and also by JsViews to build functions for data link expressions //==== nested functions ==== function pushprecedingContent(shift) { shift -= loc; if (shift) { content.push(markup.substr(loc, shift).replace(rNewLine, "\\n")); } } function blockTagCheck(tagName) { tagName && syntaxError('Unmatched or missing tag: "{{/' + tagName + '}}" in template:\n' + markup); } function parseTag(all, bind, tagName, converter, colon, html, comment, codeTag, params, slash, closeBlock, index) { // bind tag converter colon html comment code params slash closeBlock // /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g // Build abstract syntax tree (AST): [tagName, converter, params, content, hash, bindings, contentMarkup] if (html) { colon = ":"; converter = htmlStr; } slash = slash || isLinkExpr && !hasElse; var pathBindings = (bind || isLinkExpr) && [[]], props = "", args = "", ctxProps = "", paramsArgs = "", paramsProps = "", paramsCtxProps = "", onError = "", useTrigger = "", // Block tag if not self-closing and not {{:}} or {{>}} (special case) and not a data-link expression block = !slash && !colon && !comment; //==== nested helper function ==== tagName = tagName || (params = params || "#data", colon); // {{:}} is equivalent to {{:#data}} pushprecedingContent(index); loc = index + all.length; // location marker - parsed up to here if (codeTag) { if (allowCode) { content.push(["*", "\n" + params.replace(rUnescapeQuotes, "$1") + "\n"]); } } else if (tagName) { if (tagName === "else") { if (rTestElseIf.test(params)) { syntaxError('for "{{else if expr}}" use "{{else expr}}"'); } pathBindings = current[7] && [[]]; current[8] = markup.substring(current[8], index); // contentMarkup for block tag current = stack.pop(); content = current[2]; block = true; } if (params) { // remove newlines from the params string, to avoid compiled code errors for unterminated strings parseParams(params.replace(rNewLine, " "), pathBindings, tmpl) .replace(rBuildHash, function(all, onerror, isCtx, key, keyToken, keyValue, arg, param) { if (arg) { args += keyValue + ","; paramsArgs += "'" + param + "',"; } else if (isCtx) { ctxProps += key + keyValue + ","; paramsCtxProps += key + "'" + param + "',"; } else if (onerror) { onError += keyValue; } else { if (keyToken === "trigger") { useTrigger += keyValue; } props += key + keyValue + ","; paramsProps += key + "'" + param + "',"; hasHandlers = hasHandlers || rHasHandlers.test(keyToken); } return ""; }).slice(0, -1); } if (pathBindings && pathBindings[0]) { pathBindings.pop(); // Remove the bindings that was prepared for next arg. (There is always an extra one ready). } newNode = [ tagName, converter || !!convertBack || hasHandlers || "", block && [], parsedParam(paramsArgs, paramsProps, paramsCtxProps), parsedParam(args, props, ctxProps), onError, useTrigger, pathBindings || 0 ]; content.push(newNode); if (block) { stack.push(current); current = newNode; current[8] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag } } else if (closeBlock) { blockTagCheck(closeBlock !== current[0] && current[0] !== "else" && closeBlock); current[8] = markup.substring(current[8], index); // contentMarkup for block tag current = stack.pop(); } blockTagCheck(!current && closeBlock); content = current[2]; } //==== /end of nested functions ==== var result, newNode, hasHandlers, allowCode = tmpl && tmpl.allowCode, astTop = [], loc = 0, stack = [], content = astTop, current = [,,astTop]; //TODO result = tmplFnsCache[markup]; // Only cache if template is not named and markup length < ..., //and there are no bindings or subtemplates?? Consider standard optimization for data-link="a.b.c" // if (result) { // tmpl.fn = result; // } else { // result = markup; if (isLinkExpr) { markup = delimOpenChar0 + markup + delimCloseChar1; } blockTagCheck(stack[0] && stack[0][2].pop()[0]); // Build the AST (abstract syntax tree) under astTop markup.replace(rTag, parseTag); pushprecedingContent(markup.length); if (loc = astTop[astTop.length - 1]) { blockTagCheck("" + loc !== loc && (+loc[8] === loc[8]) && loc[0]); } // result = tmplFnsCache[markup] = buildCode(astTop, tmpl); // } if (isLinkExpr) { result = buildCode(astTop, markup, isLinkExpr); setPaths(result, [astTop[0][7]]); // With data-link expressions, pathBindings array is astTop[0][7] } else { result = buildCode(astTop, tmpl); } if (result._nvw) { result._nvw = !/[~#]/.test(markup); } return result; } function setPaths(fn, pathsArr) { var key, paths, i = 0, l = pathsArr.length; fn.deps = []; for (; i < l; i++) { paths = pathsArr[i]; for (key in paths) { if (key !== "_jsvto" && paths[key].length) { fn.deps = fn.deps.concat(paths[key]); // deps is the concatenation of the paths arrays for the different bindings } } } fn.paths = paths; // The array of paths arrays for the different bindings } function parsedParam(args, props, ctx) { return [args.slice(0, -1), props.slice(0, -1), ctx.slice(0, -1)]; } function paramStructure(parts, type) { return '\n\t' + (type ? type + ':{' : '') + 'args:[' + parts[0] + ']' + (parts[1] || !type ? ',\n\tprops:{' + parts[1] + '}' : "") + (parts[2] ? ',\n\tctx:{' + parts[2] + '}' : ""); } function parseParams(params, pathBindings, tmpl) { function parseTokens(all, lftPrn0, lftPrn, bound, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, rtPrnDot, prn2, space, index, full) { // /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(!*?[#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?[#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*(([)\]])(?=\s*[.^]|\s*$|\s)|[)\]])([([]?))|(\s+)/g, // lftPrn0 lftPrn bound path operator err eq path2 prn comma lftPrn2 apos quot rtPrn rtPrnDot prn2 space // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space bound = bindings && bound; if (bound && !eq) { path = bound + path; // e.g. some.fn(...)^some.path - so here path is "^some.path" } operator = operator || ""; lftPrn = lftPrn || lftPrn0 || lftPrn2; path = path || path2; // Could do this - but not worth perf cost?? :- // if (!path.lastIndexOf("#data.", 0)) { path = path.slice(6); } // If path starts with "#data.", remove that. prn = prn || prn2 || ""; var expr, exprFn, binds, theOb, newOb; function parsePath(allPath, not, object, helper, view, viewProperty, pathTokens, leafToken) { // rPath = /^(?:null|true|false|\d[\d.]*|(!*?)([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g, // none object helper view viewProperty pathTokens leafToken var subPath = object === "."; if (object) { path = path.slice(not.length); if (!subPath) { allPath = (helper ? 'view.hlp("' + helper + '")' : view ? "view" : "data") + (leafToken ? (viewProperty ? "." + viewProperty : helper ? "" : (view ? "" : "." + object) ) + (pathTokens || "") : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); allPath = allPath + (leafToken ? "." + leafToken : ""); allPath = not + (allPath.slice(0, 9) === "view.data" ? allPath.slice(5) // convert #view.data... to data... : allPath); } if (bindings) { binds = named === "linkTo" ? (bindto = pathBindings._jsvto = pathBindings._jsvto || []) : bndCtx.bd; if (theOb = subPath && binds[binds.length-1]) { if (theOb._jsv) { while (theOb.sb) { theOb = theOb.sb; } if (theOb.bnd) { path = "^" + path.slice(1); } theOb.sb = path; theOb.bnd = theOb.bnd || path.charAt(0) === "^"; } } else { binds.push(path); } pathStart[parenDepth] = index + (subPath ? 1 : 0); } } return allPath; } if (err && !aposed && !quoted) { syntaxError(params); } else { if (bindings && rtPrnDot && !aposed && !quoted) { // This is a binding to a path in which an object is returned by a helper/data function/expression, e.g. foo()^x.y or (a?b:c)^x.y // We create a compiled function to get the object instance (which will be called when the dependent data of the subexpression changes, to return the new object, and trigger re-binding of the subsequent path) if (!named || boundName || bindto) { expr = pathStart[parenDepth - 1]; if (full.length - 1 > index - (expr || 0)) { // We need to compile a subexpression expr = full.slice(expr, index + all.length); if (exprFn !== true) { // If not reentrant call during compilation binds = bindto || bndStack[parenDepth-1].bd; // Insert exprOb object, to be used during binding to return the computed object theOb = binds[binds.length-1]; if (theOb && theOb.prm) { while (theOb.sb && theOb.sb.prm) { theOb = theOb.sb; } newOb = theOb.sb = {path: theOb.sb, bnd: theOb.bnd}; } else { binds.push(newOb = {path: binds.pop()}); // Insert exprOb object, to be used during binding to return the computed object } // (e.g. "some.object()" in "some.object().a.b" - to be used as context for binding the following tokens "a.b") } rtPrnDot = delimOpenChar1 + ":" + expr // The parameter or function subexpression + " onerror=''" // set onerror='' in order to wrap generated code with a try catch - returning '' as object instance if there is an error/missing parent + delimCloseChar0; exprFn = tmplLinks[rtPrnDot]; if (!exprFn) { tmplLinks[rtPrnDot] = true; // Flag that this exprFn (for rtPrnDot) is being compiled tmplLinks[rtPrnDot] = exprFn = tmplFn(rtPrnDot, tmpl, true); // Compile the expression (or use cached copy already in tmpl.links) } if (exprFn !== true && newOb) { // If not reentrant call during compilation newOb._jsv = exprFn; newOb.prm = bndCtx.bd; newOb.bnd = newOb.bnd || newOb.path && newOb.path.indexOf("^") >= 0; } } } } return (aposed // within single-quoted string ? (aposed = !apos, (aposed ? all : '"')) : quoted // within double-quoted string ? (quoted = !quot, (quoted ? all : '"')) : ( (lftPrn ? (pathStart[parenDepth] = index++, bndCtx = bndStack[++parenDepth] = {bd: []}, lftPrn) : "") + (space ? (parenDepth ? "" // New arg or prop - so insert backspace \b (\x08) as separator for named params, used subsequently by rBuildHash, and prepare new bindings array : (paramIndex = full.slice(paramIndex, index), named ? (named = boundName = bindto = false, "\b") : "\b,") + paramIndex + (paramIndex = index + all.length, bindings && pathBindings.push(bndCtx.bd = []), "\b") ) : eq // named param. Remove bindings for arg and create instead bindings array for prop ? (parenDepth && syntaxError(params), bindings && pathBindings.pop(), named = path, boundName = bound, paramIndex = index + all.length, bound && (bindings = bndCtx.bd = pathBindings[named] = []), path + ':') : path // path ? (path.split("^").join(".").replace(rPath, parsePath) + (prn // some.fncall( ? (bndCtx = bndStack[++parenDepth] = {bd: []}, fnCall[parenDepth] = true, prn) : operator) ) : operator // operator ? operator : rtPrn // function ? ((fnCall[parenDepth] = false, bndCtx = bndStack[--parenDepth], rtPrn) + (prn // rtPrn and prn, e.g )( in (a)() or a()(), or )[ in a()[] ? (bndCtx = bndStack[++parenDepth], fnCall[parenDepth] = true, prn) : "") ) : comma ? (fnCall[parenDepth] || syntaxError(params), ",") // We don't allow top-level literal arrays or objects : lftPrn0 ? "" : (aposed = apos, quoted = quot, '"') )) ); } } var named, bindto, boundName, quoted, // boolean for string content in double quotes aposed, // or in single quotes bindings = pathBindings && pathBindings[0], // bindings array for the first arg bndCtx = {bd: bindings}, bndStack = {0: bndCtx}, paramIndex = 0, // list, tmplLinks = tmpl ? tmpl.links : bindings && (bindings.links = bindings.links || {}), // The following are used for tracking path parsing including nested paths, such as "a.b(c^d + (e))^f", and chained computed paths such as // "a.b().c^d().e.f().g" - which has four chained paths, "a.b()", "^c.d()", ".e.f()" and ".g" parenDepth = 0, fnCall = {}, // We are in a function call pathStart = {}; // tracks the start of the current path such as c^d() in the above example return (params + (tmpl ? " " : "")) .replace(rParams, parseTokens); } function buildCode(ast, tmpl, isLinkExpr) { // Build the template function code from the AST nodes, and set as property on the passed-in template object // Used for compiling templates, and also by JsViews to build functions for data link expressions var i, node, tagName, converter, tagCtx, hasTag, hasEncoder, getsVal, hasCnvt, needView, useCnvt, tmplBindings, pathBindings, params, boundOnErrStart, boundOnErrEnd, tagRender, nestedTmpls, tmplName, nestedTmpl, tagAndElses, content, markup, nextIsElse, oldCode, isElse, isGetVal, tagCtxFn, onError, tagStart, trigger, tmplBindingKey = 0, code = "", tmplOptions = {}, l = ast.length; if ("" + tmpl === tmpl) { tmplName = isLinkExpr ? 'data-link="' + tmpl.replace(rNewLine, " ").slice(1, -1) + '"' : tmpl; tmpl = 0; } else { tmplName = tmpl.tmplName || "unnamed"; if (tmpl.allowCode) { tmplOptions.allowCode = true; } if (tmpl.debug) { tmplOptions.debug = true; } tmplBindings = tmpl.bnds; nestedTmpls = tmpl.tmpls; } for (i = 0; i < l; i++) { // AST nodes: [tagName, converter, content, params, code, onError, pathBindings, contentMarkup, link] node = ast[i]; // Add newline for each callout to t() c() etc. and each markup string if ("" + node === node) { // a markup string to be inserted code += '\n+"' + node + '"'; } else { // a compiled tag expression to be inserted tagName = node[0]; if (tagName === "*") { // Code tag: {{* }} code += ";\n" + node[1] + "\nret=ret"; } else { converter = node[1]; content = !isLinkExpr && node[2]; tagCtx = paramStructure(node[3], 'params') + '},' + paramStructure(params = node[4]); onError = node[5]; trigger = node[6]; markup = node[8] && node[8].replace(rUnescapeQuotes, "$1"); if (isElse = tagName === "else") { pathBindings && pathBindings.push(node[7]); } else { tmplBindingKey = 0; if (tmplBindings && (pathBindings = node[7])) { // Array of paths, or false if not data-bound pathBindings = [pathBindings]; tmplBindingKey = tmplBindings.push(1); // Add placeholder in tmplBindings for compiled function } } if (isGetVal = tagName === ":") { if (converter) { tagName = converter === htmlStr ? ">" : converter + tagName; } } else { if (content) { // TODO optimize - if content.length === 0 or if there is a tmpl="..." specified - set content to null / don't run this compilation code - since content won't get used!! // Create template object for nested template nestedTmpl = TmplObject(markup, tmplOptions); nestedTmpl.tmplName = tmplName + "/" + tagName; // Compile to AST and then to compiled function buildCode(content, nestedTmpl); nestedTmpls.push(nestedTmpl); } if (!isElse) { // This is not an else tag. tagAndElses = tagName; // Switch to a new code string for this bound tag (and its elses, if it has any) - for returning the tagCtxs array oldCode = code; code = ""; } nextIsElse = ast[i + 1]; nextIsElse = nextIsElse && nextIsElse[0] === "else"; } tagStart = onError ? ";\ntry{\nret+=" : "\n+"; boundOnErrStart = ""; boundOnErrEnd= ""; if (isGetVal && (pathBindings || trigger || converter && converter !== htmlStr)) { // For convertVal we need a compiled function to return the new tagCtx(s) tagCtxFn = "return {" + tagCtx + "};"; tagRender = 'c("' + converter + '",view,'; tagCtxFn = new Function("data,view,j,u", " // " + tmplName + " " + tmplBindingKey + " " + tagName + "\n" + tagCtxFn); tagCtxFn._er = onError; boundOnErrStart = tagRender + tmplBindingKey + ","; boundOnErrEnd = ")"; tagCtxFn._tag = tagName; if (isLinkExpr) { return tagCtxFn; } setPaths(tagCtxFn, pathBindings); useCnvt = true; } code += (isGetVal ? (isLinkExpr ? (onError ? "\ntry{\n" : "") + "return " : tagStart) + (useCnvt // Call _cnvt if there is a converter: {{cnvt: ... }} or {^{cnvt: ... }} ? (useCnvt = undefined, needView = hasCnvt = true, tagRender + (pathBindings ? ((tmplBindings[tmplBindingKey - 1] = tagCtxFn), tmplBindingKey) // Store the compiled tagCtxFn in tmpl.bnds, and pass the key to convertVal() : "{" + tagCtx + "}") + ")") : tagName === ">" ? (hasEncoder = true, "h(" + params[0] + ')') : (getsVal = true, "((v=" + (params[0] || 'data') + ')!=null?v:"")') // Strict equality just for data-link="title{:expr}" so expr=null will remove title attribute ) : (needView = hasTag = true, "\n{view:view,tmpl:" // Add this tagCtx to the compiled code for the tagCtxs to be passed to renderTag() + (content ? nestedTmpls.length : "0") + "," // For block tags, pass in the key (nestedTmpls.length) to the nested content template + tagCtx + "},")); if (tagAndElses && !nextIsElse) { // This is a data-link expression or an inline bound tag without any elses, or the last {{else}} of an inline bound tag // We complete the code for returning the tagCtxs array code = "[" + code.slice(0, -1) + "]"; tagRender = 't("' + tagAndElses + '",view,this,'; if (isLinkExpr || pathBindings) { // This is a bound tag (data-link expression or inline bound tag {^{tag ...}}) so we store a compiled tagCtxs function in tmp.bnds code = new Function("data,view,j,u", " // " + tmplName + " " + tmplBindingKey + " " + tagAndElses + "\nreturn " + code + ";"); code._er = onError; code._tag = tagAndElses; if (pathBindings) { setPaths(tmplBindings[tmplBindingKey - 1] = code, pathBindings); } if (isLinkExpr) { return code; // For a data-link expression we return the compiled tagCtxs function } boundOnErrStart = tagRender + tmplBindingKey + ",undefined,"; boundOnErrEnd = ")"; } // This is the last {{else}} for an inline tag. // For a bound tag, pass the tagCtxs fn lookup key to renderTag. // For an unbound tag, include the code directly for evaluating tagCtxs array code = oldCode + tagStart + tagRender + (tmplBindingKey || code) + ")"; pathBindings = 0; tagAndElses = 0; } if (onError) { needView = true; code += ';\n}catch(e){ret' + (isLinkExpr ? "urn " : "+=") + boundOnErrStart + 'j._err(e,view,' + onError + ')' + boundOnErrEnd + ';}' + (isLinkExpr ? "" : 'ret=ret'); } } } } // Include only the var references that are needed in the code code = "// " + tmplName + "\nvar v" + (hasTag ? ",t=j._tag" : "") // has tag + (hasCnvt ? ",c=j._cnvt" : "") // converter + (hasEncoder ? ",h=j.converters.html" : "") // html converter + (isLinkExpr ? ";\n" : ',ret=""\n') + (tmplOptions.debug ? "debugger;" : "") + code + (isLinkExpr ? "\n" : ";\nreturn ret;"); try { code = new Function("data,view,j,u", code); } catch (e) { syntaxError("Compiled template code:\n\n" + code + '\n: "' + e.message + '"'); } if (tmpl) { tmpl.fn = code; } if (!needView) { code._nvw = true; } return code; } //========== // Utilities //========== // Merge objects, in particular contexts which inherit from parent contexts function extendCtx(context, parentContext) { // Return copy of parentContext, unless context is defined and is different, in which case return a new merged context // If neither context nor parentContext are defined, return undefined return context && context !== parentContext ? (parentContext ? $extend($extend({}, parentContext), context) : context) : parentContext && $extend({}, parentContext); } // Get character entity for HTML and Attribute encoding function getCharEntity(ch) { return charEntities[ch] || (charEntities[ch] = "&#" + ch.charCodeAt(0) + ";"); } //========================== Initialize ========================== for (jsvStoreName in jsvStores) { registerStore(jsvStoreName, jsvStores[jsvStoreName]); } var $templates = $views.templates, $converters = $views.converters, $helpers = $views.helpers, $tags = $views.tags, $sub = $views.sub, $viewsSettings = $views.settings; $sub._tg.prototype = { baseApply: baseApply }; if (jQuery) { //////////////////////////////////////////////////////////////////////////////////////////////// // jQuery is loaded, so make $ the jQuery object $ = jQuery; $.fn.render = $fastRender; if ($.observable) { $extend($sub, $.views.sub); // jquery.observable.js was loaded before jsrender.js $views.map = $.views.map; } } else { //////////////////////////////////////////////////////////////////////////////////////////////// // jQuery is not loaded. $ = global.jsviews = {}; $.isArray = Array.isArray || function(obj) { return $.toString.call(obj) === "[object Array]"; }; // //========================== Future Node.js support ========================== // if ((nodeJsModule = global.module) && nodeJsModule.exports) { // nodeJsModule.exports = $; // } } $.render = $render; $.views = $views; $.templates = $templates = $views.templates; $viewsSettings({ debugMode: dbgMode, delimiters: $viewsDelimiters, onError: function(e, view, fallback) { // Can override using $.views.settings({onError: function(...) {...}}); if (view) { // For render errors, e is an exception thrown in compiled template, and view is the current view. For other errors, e is an error string. e = fallback === undefined ? "{Error: " + (e.message || e) + "}" : $isFunction(fallback) ? fallback(e, view) : fallback; } return e == undefined ? "" : e; }, _dbgMode: true }); //========================== Register tags ========================== $tags({ "else": function() {}, // Does nothing but ensures {{else}} tags are recognized as valid "if": { render: function(val) { // This function is called once for {{if}} and once for each {{else}}. // We will use the tag.rendering object for carrying rendering state across the calls. // If not done (a previous block has not been rendered), look at expression for this block and render the block if expression is truthy // Otherwise return "" var self = this, ret = (self.rendering.done || !val && (arguments.length || !self.tagCtx.index)) ? "" : (self.rendering.done = true, self.selected = self.tagCtx.index, // Test is satisfied, so render content on current context. We call tagCtx.render() rather than return undefined // (which would also render the tmpl/content on the current context but would iterate if it is an array) self.tagCtx.render(self.tagCtx.view, true)); // no arg, so renders against parentView.data return ret; }, flow: true }, "for": { render: function(val) { // This function is called once for {{for}} and once for each {{else}}. // We will use the tag.rendering object for carrying rendering state across the calls. var finalElse, self = this, tagCtx = self.tagCtx, result = "", done = 0; if (!self.rendering.done) { if (finalElse = !arguments.length) { val = tagCtx.view.data; // For the final else, defaults to current data without iteration. } if (val !== undefined) { result += tagCtx.render(val, finalElse); // Iterates except on final else, if data is an array. (Use {{include}} to compose templates without array iteration) done += $.isArray(val) ? val.length : 1; } if (self.rendering.done = done) { self.selected = tagCtx.index; } // If nothing was rendered we will look at the next {{else}}. Otherwise, we are done. } return result; }, flow: true }, props: { baseTag: "for", dataMap: dataMap(getTargetProps) }, include: { flow: true }, "*": { // {{* code... }} - Ignored if template.allowCode is false. Otherwise include code in compiled template render: retVal, flow: true } }); function getTargetProps(source) { // this pointer is theMap - which has tagCtx.props too // arguments: tagCtx.args. var key, prop, props = []; if (typeof source === objectStr) { for (key in source) { prop = source[key]; if (!prop || !prop.toJSON || prop.toJSON()) { if (!$isFunction(prop)) { props.push({ key: key, prop: prop }); } } } } return props; } //========================== Register converters ========================== function htmlEncode(text) { // HTML encode: Replace < > & ' and " by corresponding entities. return text != null ? rIsHtml.test(text) && ("" + text).replace(rHtmlEncode, getCharEntity) || text : ""; } $converters({ html: htmlEncode, attr: htmlEncode, // Includes > encoding since rConvertMarkers in JsViews does not skip > characters in attribute strings url: function(text) { // URL encoding helper. return text != undefined ? encodeURI("" + text) : text === null ? text : ""; // null returns null, e.g. to remove attribute. undefined returns "" } }); //========================== Define default delimiters ========================== $viewsDelimiters(); })(this, this.jQuery);
hhkaos/badge-generator
js/jsrender.js
JavaScript
mit
66,836
define(['exports','events'],function(exports,events){ // Implementation for all known webbrowser var _cancelFullScreen = function() { return ( (document.exitFullscreen && document.exitFullscreen()) || (document.webkitExitFullscreen && document.webkitExitFullscreen()) || (document.webkitCancelFullScreen && document.webkitCancelFullScreen()) || (document.msExitFullscreen && document.msExitFullscreen()) || (document.mozCancelFullScreen && document.mozCancelFullScreen()) ); }; var _canFullScreen = function() { return document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.FullScreenEnabled; }; var _fullScreenElement = function() { return (document.fullScreenElement || document.webkitCurrentFullScreenElement || document.webkitFullScreenElement || document.mozFullScreenElement || document.msFullscreenElement); }; var _isFullScreen = function() { return !!(document.fullScreenElement || document.msFullScreenElement || document.mozFullScreen || document.webkitIsFullScreen); }; var _requestFullScreen = function(element) { if (element) { return ( (element.requestFullscreen && element.requestFullscreen()) || (element.webkitRequestFullscreen && element.webkitRequestFullscreen()) || (element.msRequestFullscreen && element.msRequestFullscreen()) || (element.mozRequestFullScreen && element.mozRequestFullScreen()) ); } }; // Statehandling var _fullScreenError = function() { events.trigger('screen::fullScreenError'); }; var _fullScreenChange = function() { var isFullScreen = _isFullScreen(); // trigger the fullScreenState events.trigger('screen::fullScreenChange',[isFullScreen]); }; /* doesn't work at the moment*/ document.addEventListener('fullscreenchange', _fullScreenChange,false); document.addEventListener('mozfullscreenchange', _fullScreenChange,false); document.addEventListener('webkitfullscreenchange', _fullScreenChange,false); document.addEventListener('msfullscreenchange', _fullScreenChange); document.addEventListener('webkitfullscreenerror', _fullScreenError,false); document.addEventListener('MSFullscreenError', _fullScreenError,false); document.addEventListener('mozfullscreenerror', _fullScreenError,false); document.addEventListener('fullscreenerror', _fullScreenError,false); exports.cancelFullScreen = _cancelFullScreen; exports.canFullScreen = _canFullScreen; exports.fullScreenElement = _fullScreenElement; exports.isFullScreen = _isFullScreen; exports.requestFullScreen = _requestFullScreen; });
Thomas-P/ESA03
static/scripts/app/screen.js
JavaScript
mit
2,595
import { parseToUppercase } from './utils'; import createTypes from './createTypes'; import createCreators from './createCreators'; import validateConfig from './validateConfig'; import toExternalTypes from './toExternalTypes'; /* @param {string} namespace - namespace to be uppercased and prefix your action types @param {Array} config - object with options */ export default function createActions(namespace, config) { const NAMESPACE = parseToUppercase(namespace); validateConfig(NAMESPACE, config); const actionKeys = Object.keys(config); const actionTypes = createTypes(actionKeys, NAMESPACE); const creators = createCreators(config, actionTypes); return { creators, types: toExternalTypes(config, actionTypes), }; }
viniciusdacal/redux-arc
src/createActions.js
JavaScript
mit
751
/** * Created by Fábio on 15-07-2014. */ /** * Created by Fábio on 07-07-2014. */ var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.send("hello"); }); io.on('connection', function(socket){ console.log('new user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('message', function(msg){ console.log('message: ' + msg); socket.broadcast.emit('message', msg); }); }); http.listen(3333, function(){ console.log('listening on *:3333'); });
rafanime/tactic
script/server_node.js
JavaScript
mit
676
// flow-typed signature: 809fe4c5558498f21c367ff498c43176 // flow-typed version: <<STUB>>/@babel/runtime_v^7.1.5/flow_v0.92.0 /** * This is an autogenerated libdef stub for: * * '@babel/runtime' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@babel/runtime' { declare module.exports: any } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@babel/runtime/helpers/applyDecoratedDescriptor' { declare module.exports: any } declare module '@babel/runtime/helpers/arrayWithHoles' { declare module.exports: any } declare module '@babel/runtime/helpers/arrayWithoutHoles' { declare module.exports: any } declare module '@babel/runtime/helpers/assertThisInitialized' { declare module.exports: any } declare module '@babel/runtime/helpers/AsyncGenerator' { declare module.exports: any } declare module '@babel/runtime/helpers/asyncGeneratorDelegate' { declare module.exports: any } declare module '@babel/runtime/helpers/asyncIterator' { declare module.exports: any } declare module '@babel/runtime/helpers/asyncToGenerator' { declare module.exports: any } declare module '@babel/runtime/helpers/awaitAsyncGenerator' { declare module.exports: any } declare module '@babel/runtime/helpers/AwaitValue' { declare module.exports: any } declare module '@babel/runtime/helpers/classCallCheck' { declare module.exports: any } declare module '@babel/runtime/helpers/classNameTDZError' { declare module.exports: any } declare module '@babel/runtime/helpers/classPrivateFieldGet' { declare module.exports: any } declare module '@babel/runtime/helpers/classPrivateFieldLooseBase' { declare module.exports: any } declare module '@babel/runtime/helpers/classPrivateFieldLooseKey' { declare module.exports: any } declare module '@babel/runtime/helpers/classPrivateFieldSet' { declare module.exports: any } declare module '@babel/runtime/helpers/classStaticPrivateFieldSpecGet' { declare module.exports: any } declare module '@babel/runtime/helpers/classStaticPrivateFieldSpecSet' { declare module.exports: any } declare module '@babel/runtime/helpers/construct' { declare module.exports: any } declare module '@babel/runtime/helpers/createClass' { declare module.exports: any } declare module '@babel/runtime/helpers/decorate' { declare module.exports: any } declare module '@babel/runtime/helpers/defaults' { declare module.exports: any } declare module '@babel/runtime/helpers/defineEnumerableProperties' { declare module.exports: any } declare module '@babel/runtime/helpers/defineProperty' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/applyDecoratedDescriptor' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/arrayWithHoles' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/arrayWithoutHoles' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/assertThisInitialized' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/AsyncGenerator' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/asyncGeneratorDelegate' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/asyncIterator' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/asyncToGenerator' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/awaitAsyncGenerator' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/AwaitValue' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/classCallCheck' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/classNameTDZError' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/classPrivateFieldGet' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/classPrivateFieldLooseBase' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/classPrivateFieldLooseKey' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/classPrivateFieldSet' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/construct' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/createClass' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/decorate' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/defaults' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/defineEnumerableProperties' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/defineProperty' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/extends' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/get' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/getPrototypeOf' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/inherits' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/inheritsLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/initializerDefineProperty' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/initializerWarningHelper' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/instanceof' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/interopRequireDefault' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/interopRequireWildcard' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/isNativeFunction' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/iterableToArray' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/iterableToArrayLimit' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/iterableToArrayLimitLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/jsx' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/newArrowCheck' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/nonIterableRest' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/nonIterableSpread' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/objectDestructuringEmpty' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/objectSpread' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/objectWithoutProperties' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/possibleConstructorReturn' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/readOnlyError' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/set' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/setPrototypeOf' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/skipFirstGeneratorNext' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/slicedToArray' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/slicedToArrayLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/superPropBase' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/taggedTemplateLiteral' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/taggedTemplateLiteralLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/temporalRef' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/temporalUndefined' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/toArray' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/toConsumableArray' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/toPrimitive' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/toPropertyKey' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/typeof' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/wrapAsyncGenerator' { declare module.exports: any } declare module '@babel/runtime/helpers/esm/wrapNativeSuper' { declare module.exports: any } declare module '@babel/runtime/helpers/extends' { declare module.exports: any } declare module '@babel/runtime/helpers/get' { declare module.exports: any } declare module '@babel/runtime/helpers/getPrototypeOf' { declare module.exports: any } declare module '@babel/runtime/helpers/inherits' { declare module.exports: any } declare module '@babel/runtime/helpers/inheritsLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/initializerDefineProperty' { declare module.exports: any } declare module '@babel/runtime/helpers/initializerWarningHelper' { declare module.exports: any } declare module '@babel/runtime/helpers/instanceof' { declare module.exports: any } declare module '@babel/runtime/helpers/interopRequireDefault' { declare module.exports: any } declare module '@babel/runtime/helpers/interopRequireWildcard' { declare module.exports: any } declare module '@babel/runtime/helpers/isNativeFunction' { declare module.exports: any } declare module '@babel/runtime/helpers/iterableToArray' { declare module.exports: any } declare module '@babel/runtime/helpers/iterableToArrayLimit' { declare module.exports: any } declare module '@babel/runtime/helpers/iterableToArrayLimitLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/jsx' { declare module.exports: any } declare module '@babel/runtime/helpers/newArrowCheck' { declare module.exports: any } declare module '@babel/runtime/helpers/nonIterableRest' { declare module.exports: any } declare module '@babel/runtime/helpers/nonIterableSpread' { declare module.exports: any } declare module '@babel/runtime/helpers/objectDestructuringEmpty' { declare module.exports: any } declare module '@babel/runtime/helpers/objectSpread' { declare module.exports: any } declare module '@babel/runtime/helpers/objectWithoutProperties' { declare module.exports: any } declare module '@babel/runtime/helpers/objectWithoutPropertiesLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/possibleConstructorReturn' { declare module.exports: any } declare module '@babel/runtime/helpers/readOnlyError' { declare module.exports: any } declare module '@babel/runtime/helpers/set' { declare module.exports: any } declare module '@babel/runtime/helpers/setPrototypeOf' { declare module.exports: any } declare module '@babel/runtime/helpers/skipFirstGeneratorNext' { declare module.exports: any } declare module '@babel/runtime/helpers/slicedToArray' { declare module.exports: any } declare module '@babel/runtime/helpers/slicedToArrayLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/superPropBase' { declare module.exports: any } declare module '@babel/runtime/helpers/taggedTemplateLiteral' { declare module.exports: any } declare module '@babel/runtime/helpers/taggedTemplateLiteralLoose' { declare module.exports: any } declare module '@babel/runtime/helpers/temporalRef' { declare module.exports: any } declare module '@babel/runtime/helpers/temporalUndefined' { declare module.exports: any } declare module '@babel/runtime/helpers/toArray' { declare module.exports: any } declare module '@babel/runtime/helpers/toConsumableArray' { declare module.exports: any } declare module '@babel/runtime/helpers/toPrimitive' { declare module.exports: any } declare module '@babel/runtime/helpers/toPropertyKey' { declare module.exports: any } declare module '@babel/runtime/helpers/typeof' { declare module.exports: any } declare module '@babel/runtime/helpers/wrapAsyncGenerator' { declare module.exports: any } declare module '@babel/runtime/helpers/wrapNativeSuper' { declare module.exports: any } declare module '@babel/runtime/regenerator/index' { declare module.exports: any } // Filename aliases declare module '@babel/runtime/helpers/applyDecoratedDescriptor.js' { declare module.exports: $Exports< '@babel/runtime/helpers/applyDecoratedDescriptor' > } declare module '@babel/runtime/helpers/arrayWithHoles.js' { declare module.exports: $Exports<'@babel/runtime/helpers/arrayWithHoles'> } declare module '@babel/runtime/helpers/arrayWithoutHoles.js' { declare module.exports: $Exports<'@babel/runtime/helpers/arrayWithoutHoles'> } declare module '@babel/runtime/helpers/assertThisInitialized.js' { declare module.exports: $Exports< '@babel/runtime/helpers/assertThisInitialized' > } declare module '@babel/runtime/helpers/AsyncGenerator.js' { declare module.exports: $Exports<'@babel/runtime/helpers/AsyncGenerator'> } declare module '@babel/runtime/helpers/asyncGeneratorDelegate.js' { declare module.exports: $Exports< '@babel/runtime/helpers/asyncGeneratorDelegate' > } declare module '@babel/runtime/helpers/asyncIterator.js' { declare module.exports: $Exports<'@babel/runtime/helpers/asyncIterator'> } declare module '@babel/runtime/helpers/asyncToGenerator.js' { declare module.exports: $Exports<'@babel/runtime/helpers/asyncToGenerator'> } declare module '@babel/runtime/helpers/awaitAsyncGenerator.js' { declare module.exports: $Exports<'@babel/runtime/helpers/awaitAsyncGenerator'> } declare module '@babel/runtime/helpers/AwaitValue.js' { declare module.exports: $Exports<'@babel/runtime/helpers/AwaitValue'> } declare module '@babel/runtime/helpers/classCallCheck.js' { declare module.exports: $Exports<'@babel/runtime/helpers/classCallCheck'> } declare module '@babel/runtime/helpers/classNameTDZError.js' { declare module.exports: $Exports<'@babel/runtime/helpers/classNameTDZError'> } declare module '@babel/runtime/helpers/classPrivateFieldGet.js' { declare module.exports: $Exports< '@babel/runtime/helpers/classPrivateFieldGet' > } declare module '@babel/runtime/helpers/classPrivateFieldLooseBase.js' { declare module.exports: $Exports< '@babel/runtime/helpers/classPrivateFieldLooseBase' > } declare module '@babel/runtime/helpers/classPrivateFieldLooseKey.js' { declare module.exports: $Exports< '@babel/runtime/helpers/classPrivateFieldLooseKey' > } declare module '@babel/runtime/helpers/classPrivateFieldSet.js' { declare module.exports: $Exports< '@babel/runtime/helpers/classPrivateFieldSet' > } declare module '@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js' { declare module.exports: $Exports< '@babel/runtime/helpers/classStaticPrivateFieldSpecGet' > } declare module '@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js' { declare module.exports: $Exports< '@babel/runtime/helpers/classStaticPrivateFieldSpecSet' > } declare module '@babel/runtime/helpers/construct.js' { declare module.exports: $Exports<'@babel/runtime/helpers/construct'> } declare module '@babel/runtime/helpers/createClass.js' { declare module.exports: $Exports<'@babel/runtime/helpers/createClass'> } declare module '@babel/runtime/helpers/decorate.js' { declare module.exports: $Exports<'@babel/runtime/helpers/decorate'> } declare module '@babel/runtime/helpers/defaults.js' { declare module.exports: $Exports<'@babel/runtime/helpers/defaults'> } declare module '@babel/runtime/helpers/defineEnumerableProperties.js' { declare module.exports: $Exports< '@babel/runtime/helpers/defineEnumerableProperties' > } declare module '@babel/runtime/helpers/defineProperty.js' { declare module.exports: $Exports<'@babel/runtime/helpers/defineProperty'> } declare module '@babel/runtime/helpers/esm/applyDecoratedDescriptor.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/applyDecoratedDescriptor' > } declare module '@babel/runtime/helpers/esm/arrayWithHoles.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/arrayWithHoles'> } declare module '@babel/runtime/helpers/esm/arrayWithoutHoles.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/arrayWithoutHoles' > } declare module '@babel/runtime/helpers/esm/assertThisInitialized.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/assertThisInitialized' > } declare module '@babel/runtime/helpers/esm/AsyncGenerator.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/AsyncGenerator'> } declare module '@babel/runtime/helpers/esm/asyncGeneratorDelegate.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/asyncGeneratorDelegate' > } declare module '@babel/runtime/helpers/esm/asyncIterator.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/asyncIterator'> } declare module '@babel/runtime/helpers/esm/asyncToGenerator.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/asyncToGenerator' > } declare module '@babel/runtime/helpers/esm/awaitAsyncGenerator.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/awaitAsyncGenerator' > } declare module '@babel/runtime/helpers/esm/AwaitValue.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/AwaitValue'> } declare module '@babel/runtime/helpers/esm/classCallCheck.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/classCallCheck'> } declare module '@babel/runtime/helpers/esm/classNameTDZError.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/classNameTDZError' > } declare module '@babel/runtime/helpers/esm/classPrivateFieldGet.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/classPrivateFieldGet' > } declare module '@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/classPrivateFieldLooseBase' > } declare module '@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/classPrivateFieldLooseKey' > } declare module '@babel/runtime/helpers/esm/classPrivateFieldSet.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/classPrivateFieldSet' > } declare module '@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet' > } declare module '@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet' > } declare module '@babel/runtime/helpers/esm/construct.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/construct'> } declare module '@babel/runtime/helpers/esm/createClass.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/createClass'> } declare module '@babel/runtime/helpers/esm/decorate.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/decorate'> } declare module '@babel/runtime/helpers/esm/defaults.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/defaults'> } declare module '@babel/runtime/helpers/esm/defineEnumerableProperties.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/defineEnumerableProperties' > } declare module '@babel/runtime/helpers/esm/defineProperty.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/defineProperty'> } declare module '@babel/runtime/helpers/esm/extends.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/extends'> } declare module '@babel/runtime/helpers/esm/get.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/get'> } declare module '@babel/runtime/helpers/esm/getPrototypeOf.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/getPrototypeOf'> } declare module '@babel/runtime/helpers/esm/inherits.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/inherits'> } declare module '@babel/runtime/helpers/esm/inheritsLoose.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/inheritsLoose'> } declare module '@babel/runtime/helpers/esm/initializerDefineProperty.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/initializerDefineProperty' > } declare module '@babel/runtime/helpers/esm/initializerWarningHelper.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/initializerWarningHelper' > } declare module '@babel/runtime/helpers/esm/instanceof.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/instanceof'> } declare module '@babel/runtime/helpers/esm/interopRequireDefault.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/interopRequireDefault' > } declare module '@babel/runtime/helpers/esm/interopRequireWildcard.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/interopRequireWildcard' > } declare module '@babel/runtime/helpers/esm/isNativeFunction.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/isNativeFunction' > } declare module '@babel/runtime/helpers/esm/iterableToArray.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/iterableToArray'> } declare module '@babel/runtime/helpers/esm/iterableToArrayLimit.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/iterableToArrayLimit' > } declare module '@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/iterableToArrayLimitLoose' > } declare module '@babel/runtime/helpers/esm/jsx.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/jsx'> } declare module '@babel/runtime/helpers/esm/newArrowCheck.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/newArrowCheck'> } declare module '@babel/runtime/helpers/esm/nonIterableRest.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/nonIterableRest'> } declare module '@babel/runtime/helpers/esm/nonIterableSpread.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/nonIterableSpread' > } declare module '@babel/runtime/helpers/esm/objectDestructuringEmpty.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/objectDestructuringEmpty' > } declare module '@babel/runtime/helpers/esm/objectSpread.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/objectSpread'> } declare module '@babel/runtime/helpers/esm/objectWithoutProperties.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/objectWithoutProperties' > } declare module '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose' > } declare module '@babel/runtime/helpers/esm/possibleConstructorReturn.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/possibleConstructorReturn' > } declare module '@babel/runtime/helpers/esm/readOnlyError.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/readOnlyError'> } declare module '@babel/runtime/helpers/esm/set.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/set'> } declare module '@babel/runtime/helpers/esm/setPrototypeOf.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/setPrototypeOf'> } declare module '@babel/runtime/helpers/esm/skipFirstGeneratorNext.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/skipFirstGeneratorNext' > } declare module '@babel/runtime/helpers/esm/slicedToArray.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/slicedToArray'> } declare module '@babel/runtime/helpers/esm/slicedToArrayLoose.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/slicedToArrayLoose' > } declare module '@babel/runtime/helpers/esm/superPropBase.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/superPropBase'> } declare module '@babel/runtime/helpers/esm/taggedTemplateLiteral.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/taggedTemplateLiteral' > } declare module '@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/taggedTemplateLiteralLoose' > } declare module '@babel/runtime/helpers/esm/temporalRef.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/temporalRef'> } declare module '@babel/runtime/helpers/esm/temporalUndefined.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/temporalUndefined' > } declare module '@babel/runtime/helpers/esm/toArray.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/toArray'> } declare module '@babel/runtime/helpers/esm/toConsumableArray.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/toConsumableArray' > } declare module '@babel/runtime/helpers/esm/toPrimitive.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/toPrimitive'> } declare module '@babel/runtime/helpers/esm/toPropertyKey.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/toPropertyKey'> } declare module '@babel/runtime/helpers/esm/typeof.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/typeof'> } declare module '@babel/runtime/helpers/esm/wrapAsyncGenerator.js' { declare module.exports: $Exports< '@babel/runtime/helpers/esm/wrapAsyncGenerator' > } declare module '@babel/runtime/helpers/esm/wrapNativeSuper.js' { declare module.exports: $Exports<'@babel/runtime/helpers/esm/wrapNativeSuper'> } declare module '@babel/runtime/helpers/extends.js' { declare module.exports: $Exports<'@babel/runtime/helpers/extends'> } declare module '@babel/runtime/helpers/get.js' { declare module.exports: $Exports<'@babel/runtime/helpers/get'> } declare module '@babel/runtime/helpers/getPrototypeOf.js' { declare module.exports: $Exports<'@babel/runtime/helpers/getPrototypeOf'> } declare module '@babel/runtime/helpers/inherits.js' { declare module.exports: $Exports<'@babel/runtime/helpers/inherits'> } declare module '@babel/runtime/helpers/inheritsLoose.js' { declare module.exports: $Exports<'@babel/runtime/helpers/inheritsLoose'> } declare module '@babel/runtime/helpers/initializerDefineProperty.js' { declare module.exports: $Exports< '@babel/runtime/helpers/initializerDefineProperty' > } declare module '@babel/runtime/helpers/initializerWarningHelper.js' { declare module.exports: $Exports< '@babel/runtime/helpers/initializerWarningHelper' > } declare module '@babel/runtime/helpers/instanceof.js' { declare module.exports: $Exports<'@babel/runtime/helpers/instanceof'> } declare module '@babel/runtime/helpers/interopRequireDefault.js' { declare module.exports: $Exports< '@babel/runtime/helpers/interopRequireDefault' > } declare module '@babel/runtime/helpers/interopRequireWildcard.js' { declare module.exports: $Exports< '@babel/runtime/helpers/interopRequireWildcard' > } declare module '@babel/runtime/helpers/isNativeFunction.js' { declare module.exports: $Exports<'@babel/runtime/helpers/isNativeFunction'> } declare module '@babel/runtime/helpers/iterableToArray.js' { declare module.exports: $Exports<'@babel/runtime/helpers/iterableToArray'> } declare module '@babel/runtime/helpers/iterableToArrayLimit.js' { declare module.exports: $Exports< '@babel/runtime/helpers/iterableToArrayLimit' > } declare module '@babel/runtime/helpers/iterableToArrayLimitLoose.js' { declare module.exports: $Exports< '@babel/runtime/helpers/iterableToArrayLimitLoose' > } declare module '@babel/runtime/helpers/jsx.js' { declare module.exports: $Exports<'@babel/runtime/helpers/jsx'> } declare module '@babel/runtime/helpers/newArrowCheck.js' { declare module.exports: $Exports<'@babel/runtime/helpers/newArrowCheck'> } declare module '@babel/runtime/helpers/nonIterableRest.js' { declare module.exports: $Exports<'@babel/runtime/helpers/nonIterableRest'> } declare module '@babel/runtime/helpers/nonIterableSpread.js' { declare module.exports: $Exports<'@babel/runtime/helpers/nonIterableSpread'> } declare module '@babel/runtime/helpers/objectDestructuringEmpty.js' { declare module.exports: $Exports< '@babel/runtime/helpers/objectDestructuringEmpty' > } declare module '@babel/runtime/helpers/objectSpread.js' { declare module.exports: $Exports<'@babel/runtime/helpers/objectSpread'> } declare module '@babel/runtime/helpers/objectWithoutProperties.js' { declare module.exports: $Exports< '@babel/runtime/helpers/objectWithoutProperties' > } declare module '@babel/runtime/helpers/objectWithoutPropertiesLoose.js' { declare module.exports: $Exports< '@babel/runtime/helpers/objectWithoutPropertiesLoose' > } declare module '@babel/runtime/helpers/possibleConstructorReturn.js' { declare module.exports: $Exports< '@babel/runtime/helpers/possibleConstructorReturn' > } declare module '@babel/runtime/helpers/readOnlyError.js' { declare module.exports: $Exports<'@babel/runtime/helpers/readOnlyError'> } declare module '@babel/runtime/helpers/set.js' { declare module.exports: $Exports<'@babel/runtime/helpers/set'> } declare module '@babel/runtime/helpers/setPrototypeOf.js' { declare module.exports: $Exports<'@babel/runtime/helpers/setPrototypeOf'> } declare module '@babel/runtime/helpers/skipFirstGeneratorNext.js' { declare module.exports: $Exports< '@babel/runtime/helpers/skipFirstGeneratorNext' > } declare module '@babel/runtime/helpers/slicedToArray.js' { declare module.exports: $Exports<'@babel/runtime/helpers/slicedToArray'> } declare module '@babel/runtime/helpers/slicedToArrayLoose.js' { declare module.exports: $Exports<'@babel/runtime/helpers/slicedToArrayLoose'> } declare module '@babel/runtime/helpers/superPropBase.js' { declare module.exports: $Exports<'@babel/runtime/helpers/superPropBase'> } declare module '@babel/runtime/helpers/taggedTemplateLiteral.js' { declare module.exports: $Exports< '@babel/runtime/helpers/taggedTemplateLiteral' > } declare module '@babel/runtime/helpers/taggedTemplateLiteralLoose.js' { declare module.exports: $Exports< '@babel/runtime/helpers/taggedTemplateLiteralLoose' > } declare module '@babel/runtime/helpers/temporalRef.js' { declare module.exports: $Exports<'@babel/runtime/helpers/temporalRef'> } declare module '@babel/runtime/helpers/temporalUndefined.js' { declare module.exports: $Exports<'@babel/runtime/helpers/temporalUndefined'> } declare module '@babel/runtime/helpers/toArray.js' { declare module.exports: $Exports<'@babel/runtime/helpers/toArray'> } declare module '@babel/runtime/helpers/toConsumableArray.js' { declare module.exports: $Exports<'@babel/runtime/helpers/toConsumableArray'> } declare module '@babel/runtime/helpers/toPrimitive.js' { declare module.exports: $Exports<'@babel/runtime/helpers/toPrimitive'> } declare module '@babel/runtime/helpers/toPropertyKey.js' { declare module.exports: $Exports<'@babel/runtime/helpers/toPropertyKey'> } declare module '@babel/runtime/helpers/typeof.js' { declare module.exports: $Exports<'@babel/runtime/helpers/typeof'> } declare module '@babel/runtime/helpers/wrapAsyncGenerator.js' { declare module.exports: $Exports<'@babel/runtime/helpers/wrapAsyncGenerator'> } declare module '@babel/runtime/helpers/wrapNativeSuper.js' { declare module.exports: $Exports<'@babel/runtime/helpers/wrapNativeSuper'> } declare module '@babel/runtime/regenerator/index.js' { declare module.exports: $Exports<'@babel/runtime/regenerator/index'> }
jcoreio/react-redux-features
flow-typed/npm/@babel/runtime_vx.x.x.js
JavaScript
mit
32,712
/** * ngtemplates is a Grunt plugin that takes all of your template files and * places them into JavaScript files as strings that are added to * AngularJS's template cache. */ module.exports = { app: { cwd: '<%= config.sourceDir %>', src: '<%= config.sourceFiles.templates %>', dest: '<%= config.buildDir %>/app/templates.js', options: { bootstrap: function(module, script) { 'use strict'; return 'define([\'angular\', \'app\'], function(angular, app) { app.run([\'$templateCache\', function($templateCache) {' + script + '}]); });'; } }, htmlmin: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeComments: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true } } };
timothytran/ngModular
grunt/ngtemplates.js
JavaScript
mit
1,020
#!/usr/bin/env node const exec = require('child_process').exec const commandExists = require('command-exists').sync const fs = require('fs') const readlineSync = require('readline-sync') const path = require('path') const xmlParser = require('xml2json') global.g = global g.log = function (msg) { console.log('[PUBMATE] ' + msg) } g.err = function (msg) { console.error('[PUBMATE] ' + msg) } g.fatal = function (msg) { g.err(msg) g.log('Terminating this shit.') process.exit(1) } g.readPlatformsJson = function() { if (fs.existsSync(path.normalize('platforms'))) { if (fs.existsSync(path.normalize('platforms/platforms.json'))) { return JSON.parse(fs.readFileSync('platforms/platforms.json')) } else { g.fatal("No platforms/platforms.json, add some platforms first noob, e.g.: cordova platform add android 2") } } else { g.fatal("No platforms/platforms.json, add some platforms first noob, e.g.: cordova platform add android 1") } } g.readPubmateJson = function() { if (fs.existsSync('pubmate.json')) { if (fs.existsSync('pubmate.json')) { return JSON.parse(fs.readFileSync('pubmate.json')) } } return { android: {}, ios: {} } } g.savePubmateJson = function(json) { fs.writeFileSync('pubmate.json', JSON.stringify(json)) } g.cli = { android: { usage: "pubmate android\n- Creates publishable file(s) for the Android version.", async handler () { let platforms = Object.keys(g.readPlatformsJson()) if (platforms.indexOf('android') > -1) { g.log('==========') g.log('Android...') await g.steps.android.findJarSigner() await g.steps.android.findZipAligner() await g.steps.android.buildRelease() await g.steps.android.sign() await g.steps.android.align() await g.steps.android.finish() } else { g.log('No Android platform in this Cordova project. You can add it using: cordova plaform add android') let doIt = readlineSync.question('Do you want me to do the job for you? (Y/n): ') if (doIt === 'Y') { g.log('Okay then...') let cmd = exec('cordova plaform add android') cmd.stderr.pipe(process.stderr) cmd.on('close', async (code) => { if (code > 0) { g.fatal('Cordova died. :\'(') } g.log('Done.') await g.steps.android.findJarSigner() await g.steps.android.findZipAligner() await g.steps.android.buildRelease() await g.steps.android.sign() await g.steps.android.align() await g.steps.android.finish() }) } else { g.log('Up to you.') } } } }, ios: { usage: "pubmate ios\n- Creates publishable file(s) for the iOS version.", async handler () { let platforms = Object.keys(g.readPlatformsJson()) if (platforms.indexOf('ios') > -1) { g.log('==========') g.log('iOS...') await g.steps.ios.checkBuildConfigExists() await g.steps.ios.checkBuildConfigStructure() await g.steps.ios.buildRelease() await g.steps.ios.finish() } else { g.log('No iOS platform in this Cordova project. You can add it using: cordova plaform add ios') let doIt = readlineSync.question('Do you want me to do the job for you? (Y/n): ') if (doIt === 'Y') { g.log('Okay then...') let cmd = exec('cordova plaform add ios') cmd.stderr.pipe(process.stderr) cmd.on('close', async (code) => { if (code > 0) { g.fatal('Cordova died. :\'(') } g.log('Done.') await g.steps.ios.checkBuildConfigExists() await g.steps.ios.checkBuildConfigStructure() await g.steps.ios.buildRelease() await g.steps.ios.finish() }) } else { g.log('Your choice.') } } } }, all: { usage: "pubmate - Creates publishable files for all platforms.", async handler () { g.log('All platforms, bring it...') let platforms = Object.keys(g.readPlatformsJson()) g.log('Okay, what do we have here...') if (platforms.length > 1) { g.log(platforms.join(', ')) } else { g.log('Just ' + platforms[0] + '.') } g.log("Alright, let's do this.") for (let i in platforms) { await g.cli[platforms[i]].handler() } g.log("PRO TIP: Before you publish your app, make sure your app ID (com.something.something) in your config.xml is what you finally want it to be, you can't change it later.") } }, help: { usage: "pubmate help <platform>\n- Displays help related to the specified platform command.", handler (command) { if (!command) { if (g.cli[process.argv[3]]) { console.log(g.cli[process.argv[3]].usage) } else { console.log("PubMate - turns your Cordova project into publishable file(s).") console.log('') console.log("Run in a Cordova project directory:") console.log("pubmate [platform] # to build project for a specified platform.") console.log("pubmate all # to build project for all platforms listed in your platforms/platforms.json file.") console.log('') console.log('Available platforms/commands: ', Object.keys(g.cli).join(', ')) console.log("apiko help <platform|command> # to read further.") console.log('') } } else { console.log(g.cli[command].usage) } } }, 'create-keystore': { usage: "pubmate android\n- Creates a keystore that may be used to sign Android APKs.", async handler () { g.log('Creating a keystore...') await g.steps.android.findJarSigner() await g.steps.android.createKeystore() g.log('The keystore android.keystore is ready for you in this directory, imporant information has been saved to pubmate.json.') } }, 'sign-and-zipalign': { usage: "pubmate android\n- Signs and zip-aligns an Android APK.", async handler () { g.log('Signing and zipaligning specific APK...') await g.steps.android.findJarSigner() await g.steps.android.findZipAligner() let apk = readlineSync.question('Which APK should be signed and zip-aligned? (path to the APK): ') while (!fs.existsSync(apk)) { apk = readlineSync.question('Non-existent file, try again. (path to the APK): ') } g.steps.android.unsigned = path.normalize(apk) g.log("OK, cool.") await g.steps.android.sign() await g.steps.android.align() await g.steps.android.finish() } }, } g.steps = { async publishingSteps (platform) { await g.steps.checkForCordova() await g.steps.checkForCordovaProject() await g.steps.readCordovaConfig() await g.steps.prepareProject() await g.cli[platform].handler() }, checkForCordova () { return new Promise((resolve, reject) => { g.log('Checking if Apache Cordova is installed...') if (!commandExists('cordova')) { g.fatal('Obviously you need to have Apache Cordova installed, get it at cordova.apache.org') } else { g.log('Fine.') resolve() } }) }, checkForCordovaProject () { return new Promise((resolve, reject) => { g.log('Checking if this is a Cordova project directory...') if (fs.existsSync('config.xml') && fs.existsSync('www')) { g.log('Good.') resolve() } else { g.fatal('Where else would you like to run this than in a Cordova project directory? Go there first.') } }) }, readCordovaConfig () { return new Promise((resolve, reject) => { g.log('Reading the Cordova config...') let xml = fs.readFileSync('config.xml') g.steps.config = JSON.parse(xmlParser.toJson(xml)) resolve() }) }, prepareProject () { return new Promise((resolve, reject) => { g.log('Running the \'prepare\' command here (installing missing plugins and platforms)...') let cmd = exec('cordova prepare') cmd.stderr.pipe(process.stderr) cmd.on('close', (code) => { if (code > 0) { g.fatal('Cordova died. :\'(') } g.log("OK, let's do this.") resolve() }) }) }, android: require('./android'), ios: require('./ios') } async function startup() { if (process.argv.indexOf('--verbose') >= 0) { g.cli.verbose = true g.log('Speechy mode activated.') } else { g.cli.verbose = false } if (process.argv[2]) { if (g.cli[process.argv[2]]) { switch (process.argv[2]) { case 'help': g.cli.help.handler(); break case 'create-keystore': await g.cli['create-keystore'].handler(); break case 'sign-and-zipalign': await g.cli['sign-and-zipalign'].handler(); break default: await g.steps.publishingSteps(process.argv[2]) g.log('Terminating, adios.') } } else { g.cli.help.handler() } } else { await g.steps.publishingSteps('all') g.log('Terminating, adios.') } } startup()
kasp1/PubMate
index.js
JavaScript
mit
9,251
joo.classLoader.prepare("package flash.errors",/* {*/ /** * The IOError exception is thrown when some type of input or output failure occurs. For example, an IOError exception is thrown if a read/write operation is attempted on a socket that has not connected or that has become disconnected. * <p><a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/errors/IOError.html#includeExamplesSummary">View the examples</a></p> * @see http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7ecc.html Working with the debugger versions of Flash runtimes * @see http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7ece.html Comparing the Error classes * @see http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7eb1.html flash.error package Error classes * */ "public dynamic class IOError extends Error",2,function($$private){;return[ /** * Creates a new IOError object. * @param message A string associated with the error object. * */ "public function IOError",function IOError$(message/*:String = ""*/) {if(arguments.length<1){message = "";} joo.Error.call(this,message); }, ];},[],["Error"], "0.8.0", "0.9.6" );
mohlendo/mohlendo.github.com
jangaroo/lsystem/joo/classes/flash/errors/IOError.js
JavaScript
mit
1,227
export const SET_ROUTERCONDITIOINS_CURRENT_TAB_INDEX = 'SET_ROUTERCONDITIOINS_CURRENT_TAB_INDEX';//当前的tab标签页的序号。 export const SET_ROUTERCONDITIOINS_CURRENT_TAB_KEY = 'SET_ROUTERCONDITIOINS_CURRENT_TAB_KEY';//当前的tab标签页的key值。 export const SET_ROUTERCONDITIOINS_TAB_TWO_TIMENODE_TYPES = 'SET_ROUTERCONDITIOINS_TAB_TWO_TIMENODE_TYPES';//各个tab要显示数据的时间点的类型24H/72H/1W.... export function setCurTabIndex(curTabIndex) { return { type: SET_ROUTERCONDITIOINS_CURRENT_TAB_INDEX, curTabIndex } } export function setCurTabKey(curTabKey) { return { type: SET_ROUTERCONDITIOINS_CURRENT_TAB_KEY, curTabKey } } export function setTab2TimeTypes(tab2TimeTypes) { return { type: SET_ROUTERCONDITIOINS_TAB_TWO_TIMENODE_TYPES, tab2TimeTypes } } export const actions = { setCurTabIndex, setCurTabKey, setTab2TimeTypes } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [SET_ROUTERCONDITIOINS_CURRENT_TAB_INDEX]: (state,action) => { return ({...state, curTabIndex: action.curTabIndex}) }, [SET_ROUTERCONDITIOINS_CURRENT_TAB_KEY]: (state,action) => { return ({...state, curTabKey: action.curTabKey}) }, [SET_ROUTERCONDITIOINS_TAB_TWO_TIMENODE_TYPES]: (state,action) => { return ({...state, tab2TimeTypes: action.tab2TimeTypes}) } } //======================= // reducer //======================== export const initialState = { curTabIndex: 0, curTabKey: 'status', //当前tab的key值,值可为:'status','update', 'reboot' tab2TimeTypes:{'status':'24H','update':'24H','reboot':'24H'} } export default function (state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
liuyaoao/omnyiq-sc1-server-render
src/reducers/RouterConditions_reducer.js
JavaScript
mit
1,874
const g_formatPattern = '(' + '(\\$\\{)(\\w+)\\}' + '|' + '\\$([^\\{][^\\$]*)?' + '|' + '[^\\$]+' + ')'; var g_formatRegex = new RegExp(g_formatPattern, 'g'); function FormatStringHelper(formatRegex, formatStr, formatData) { let resultStr = ''; let matches = null; while ((matches = formatRegex.exec(formatStr)) != null) { if (matches[2] === '${') { resultStr += formatData[matches[3]]; } else { resultStr += matches[1]; } } return resultStr; } function FormatString_Safe(formatStr, formatData) { let regexObj = new RegExp(g_formatPattern, 'g'); return FormatStringHelper(regexObj, formatStr, formatData); } function FormatString_Unsafe(formatStr, formatData) { g_formatRegex.lastIndex = 0; return FormatStringHelper(g_formatRegex, formatStr, formatData); } module.exports = { format: FormatString_Safe, formatUnsafe: FormatString_Unsafe };
formulaslug/expense
archive/lib/StringFormat.js
JavaScript
mit
1,044
module.exports = function(obj){ return Object.prototype.toString.call(obj) === '[object Array]'; };
manuelodelain/sprite-anim
src/utils/is-array.js
JavaScript
mit
101
module.exports={A:{A:{"1":"A B","2":"L H G E jB"},B:{"1":"8 C D e K I N J"},C:{"1":"0 1 2 3 5 7 9 J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB","2":"4 gB BB F L H G E aB ZB","33":"A B C D e K I N"},D:{"1":"0 1 2 3 7 8 9 c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB TB PB NB mB OB LB QB RB","2":"4 F L H G E A B C D","33":"5 e K I N J P Q R S T U V W X Y Z a b"},E:{"1":"6 H G E A B C D VB WB XB YB p bB","2":"4 F L SB KB UB"},F:{"1":"0 1 2 3 6 7 P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z","2":"E B C cB dB eB fB p AB hB","33":"5 K I N J"},G:{"1":"G D MB nB oB pB qB rB sB tB uB vB","2":"KB iB FB kB lB"},H:{"2":"wB"},I:{"1":"O","2":"BB F xB yB zB 0B FB","33":"1B 2B"},J:{"1":"A","2":"H"},K:{"1":"6 M","2":"A B C p AB"},L:{"1":"LB"},M:{"1":"O"},N:{"1":"A B"},O:{"1":"3B"},P:{"1":"4B 5B 6B 7B 8B","33":"F"},Q:{"1":"9B"},R:{"1":"AC"},S:{"1":"BC"}},B:2,C:"Page Visibility"};
Dans-labs/dariah
client/node_modules/caniuse-lite/data/features/pagevisibility.js
JavaScript
mit
977
realOverflow.factory('Alerts', [function() { var alerts = []; return { clear: function() { alerts = []; }, add: function(type, msg) { alerts.push({type: type, msg: msg}); }, get: function() { return alerts; }, remove: function(idx) { alerts.splice(idx, 1); } } }]);
bhague1281/realoverflow
static/app/js/services/AlertService.js
JavaScript
mit
328
/* Info Widget * ====================== */ var InfoWidget2 = BaseWidget.extend({ initialize : function() { this.Name = "Info Widget2" this.init() //this.updateFrequency = 5000 // every 5 seconds var slaveTemplateSource = $("#slave-template").html() this.slaveTemplate = Handlebars.compile(slaveTemplateSource) } , render: function() { var model = this.model.toJSON() , slaveMarkup = ''; if (model.role == "master") { // templates var templateSource = $("#info-widget-template2-master").html() for(var i = 0, len = model.connected_slaves; i < len; i++) { slaveMarkup += this.slaveTemplate(model['slave' + i]) } }else{ // templates var templateSource = $("#info-widget-template2-slave").html() } this.template = Handlebars.compile(templateSource) var markUp = this.template(model) $(this.el).html(markUp) $('#slave-infos').popover({ "title" : "slaves" , "content" : slaveMarkup }) } })
jiejieling/RdsMonitor
src/www/js/views/info-widget-view2.js
JavaScript
mit
1,156
var Icon = require('../icon'); var element = require('magic-virtual-element'); var clone = require('../clone'); exports.render = function render(component) { var props = clone(component.props); delete props.children; return element( Icon, props, element('path', { d: 'M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zM12 8c1.1 0 2-.9 2-2s-.9-2-2-2-1.99.9-1.99 2S10.9 8 12 8zm5-8H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zM7 2h10v10.5c0-1.67-3.33-2.5-5-2.5s-5 .83-5 2.5V2z' }) ); };
goto-bus-stop/deku-material-svg-icons
lib/image/camera-front.js
JavaScript
mit
520
-My build of DIGITAL Command Language: -Muhammad Adi Nugroho,S.Adm.Neg.: -Via My Notepad++ (HTML Editor): http://www.pawoon.com/assets/js/jquery-2.1.1.min.js -Via Google Chrome Console: -debugger:///VM41: Window Global Infinity : Infinity AnalyserNode : AnalyserNode() AnimationEvent : AnimationEvent() AppBannerPromptResult : AppBannerPromptResult() ApplicationCache : ApplicationCache() ApplicationCacheErrorEvent : ApplicationCacheErrorEvent() Array : Array() ArrayBuffer : ArrayBuffer() Attr : Attr() Audio : HTMLAudioElement() AudioBuffer : AudioBuffer() AudioBufferSourceNode : AudioBufferSourceNode() AudioContext : AudioContext() AudioDestinationNode : AudioDestinationNode() AudioListener : AudioListener() AudioNode : AudioNode() AudioParam : AudioParam() AudioProcessingEvent : AudioProcessingEvent() BarProp : BarProp() BatteryManager : BatteryManager() BeforeInstallPromptEvent : BeforeInstallPromptEvent() BeforeUnloadEvent : BeforeUnloadEvent() BiquadFilterNode : BiquadFilterNode() Blob : Blob() BlobEvent : BlobEvent() Boolean : Boolean() ByteLengthQueuingStrategy : ByteLengthQueuingStrategy() CDATASection : CDATASection() CSS : CSS() CSSFontFaceRule : CSSFontFaceRule() CSSGroupingRule : CSSGroupingRule() CSSImportRule : CSSImportRule() CSSKeyframeRule : CSSKeyframeRule() CSSKeyframesRule : CSSKeyframesRule() CSSMediaRule : CSSMediaRule() CSSNamespaceRule : CSSNamespaceRule() CSSPageRule : CSSPageRule() CSSRule : CSSRule() CSSRuleList : CSSRuleList() CSSStyleDeclaration : CSSStyleDeclaration() CSSStyleRule : CSSStyleRule() CSSStyleSheet : CSSStyleSheet() CSSSupportsRule : CSSSupportsRule() CSSViewportRule : CSSViewportRule() Cache : Cache() CacheStorage : CacheStorage() CanvasCaptureMediaStreamTrack : CanvasCaptureMediaStreamTrack() CanvasGradient : CanvasGradient() CanvasPattern : CanvasPattern() CanvasRenderingContext2D : CanvasRenderingContext2D() ChannelMergerNode : ChannelMergerNode() ChannelSplitterNode : ChannelSplitterNode() CharacterData : CharacterData() ClientRect : ClientRect() ClientRectList : ClientRectList() ClipboardEvent : ClipboardEvent() CloseEvent : CloseEvent() Comment : Comment() CompositionEvent : CompositionEvent() ConvolverNode : ConvolverNode() CountQueuingStrategy : CountQueuingStrategy() Credential : Credential() CredentialsContainer : CredentialsContainer() Crypto : Crypto() CryptoKey : CryptoKey() CustomEvent : CustomEvent() DOMError : DOMError() DOMException : DOMException() DOMImplementation : DOMImplementation() DOMParser : DOMParser() DOMStringList : DOMStringList() DOMStringMap : DOMStringMap() DOMTokenList : DOMTokenList() DataTransfer : DataTransfer() DataTransferItem : DataTransferItem() DataTransferItemList : DataTransferItemList() DataView : DataView() Date : Date() DelayNode : DelayNode() DeviceMotionEvent : DeviceMotionEvent() DeviceOrientationEvent : DeviceOrientationEvent() Document : Document() DocumentFragment : DocumentFragment() DocumentType : DocumentType() DragEvent : DragEvent() DynamicsCompressorNode : DynamicsCompressorNode() Element : Element() Error : Error() ErrorEvent : ErrorEvent() EvalError : EvalError() Event : Event() EventSource : EventSource() EventTarget : EventTarget() FederatedCredential : FederatedCredential() File : File() FileError : FileError() FileList : FileList() FileReader : FileReader() Float32Array : Float32Array() Float64Array : Float64Array() FocusEvent : FocusEvent() FontFace : FontFace() FormData : FormData() Function : Function() GainNode : GainNode() Gamepad : Gamepad() GamepadButton : GamepadButton() GamepadEvent : GamepadEvent() HTMLAllCollection : HTMLAllCollection() HTMLAnchorElement : HTMLAnchorElement() HTMLAreaElement : HTMLAreaElement() HTMLAudioElement : HTMLAudioElement() HTMLBRElement : HTMLBRElement() HTMLBaseElement : HTMLBaseElement() HTMLBodyElement : HTMLBodyElement() HTMLButtonElement : HTMLButtonElement() HTMLCanvasElement : HTMLCanvasElement() HTMLCollection : HTMLCollection() HTMLContentElement : HTMLContentElement() HTMLDListElement : HTMLDListElement() HTMLDataListElement : HTMLDataListElement() HTMLDetailsElement : HTMLDetailsElement() HTMLDialogElement : HTMLDialogElement() HTMLDirectoryElement : HTMLDirectoryElement() HTMLDivElement : HTMLDivElement() HTMLDocument : HTMLDocument() HTMLElement : HTMLElement() HTMLEmbedElement : HTMLEmbedElement() HTMLFieldSetElement : HTMLFieldSetElement() HTMLFontElement : HTMLFontElement() HTMLFormControlsCollection : HTMLFormControlsCollection() HTMLFormElement : HTMLFormElement() HTMLFrameElement : HTMLFrameElement() HTMLFrameSetElement : HTMLFrameSetElement() HTMLHRElement : HTMLHRElement() HTMLHeadElement : HTMLHeadElement() HTMLHeadingElement : HTMLHeadingElement() HTMLHtmlElement : HTMLHtmlElement() HTMLIFrameElement : HTMLIFrameElement() HTMLImageElement : HTMLImageElement() HTMLInputElement : HTMLInputElement() HTMLKeygenElement : HTMLKeygenElement() HTMLLIElement : HTMLLIElement() HTMLLabelElement : HTMLLabelElement() HTMLLegendElement : HTMLLegendElement() HTMLLinkElement : HTMLLinkElement() HTMLMapElement : HTMLMapElement() HTMLMarqueeElement : HTMLMarqueeElement() HTMLMediaElement : HTMLMediaElement() HTMLMenuElement : HTMLMenuElement() HTMLMetaElement : HTMLMetaElement() HTMLMeterElement : HTMLMeterElement() HTMLModElement : HTMLModElement() HTMLOListElement : HTMLOListElement() HTMLObjectElement : HTMLObjectElement() HTMLOptGroupElement : HTMLOptGroupElement() HTMLOptionElement : HTMLOptionElement() HTMLOptionsCollection : HTMLOptionsCollection() HTMLOutputElement : HTMLOutputElement() HTMLParagraphElement : HTMLParagraphElement() HTMLParamElement : HTMLParamElement() HTMLPictureElement : HTMLPictureElement() HTMLPreElement : HTMLPreElement() HTMLProgressElement : HTMLProgressElement() HTMLQuoteElement : HTMLQuoteElement() HTMLScriptElement : HTMLScriptElement() HTMLSelectElement : HTMLSelectElement() HTMLShadowElement : HTMLShadowElement() HTMLSlotElement : HTMLSlotElement() HTMLSourceElement : HTMLSourceElement() HTMLSpanElement : HTMLSpanElement() HTMLStyleElement : HTMLStyleElement() HTMLTableCaptionElement : HTMLTableCaptionElement() HTMLTableCellElement : HTMLTableCellElement() HTMLTableColElement : HTMLTableColElement() HTMLTableElement : HTMLTableElement() HTMLTableRowElement : HTMLTableRowElement() HTMLTableSectionElement : HTMLTableSectionElement() HTMLTemplateElement : HTMLTemplateElement() HTMLTextAreaElement : HTMLTextAreaElement() HTMLTitleElement : HTMLTitleElement() HTMLTrackElement : HTMLTrackElement() HTMLUListElement : HTMLUListElement() HTMLUnknownElement : HTMLUnknownElement() HTMLVideoElement : HTMLVideoElement() HashChangeEvent : HashChangeEvent() Headers : Headers() History : History() IDBCursor : IDBCursor() IDBCursorWithValue : IDBCursorWithValue() IDBDatabase : IDBDatabase() IDBFactory : IDBFactory() IDBIndex : IDBIndex() IDBKeyRange : IDBKeyRange() IDBObjectStore : IDBObjectStore() IDBOpenDBRequest : IDBOpenDBRequest() IDBRequest : IDBRequest() IDBTransaction : IDBTransaction() IDBVersionChangeEvent : IDBVersionChangeEvent() IIRFilterNode : IIRFilterNode() IdleDeadline : IdleDeadline() Image : HTMLImageElement() ImageBitmap : ImageBitmap() ImageData : ImageData() InputDeviceCapabilities : InputDeviceCapabilities() Int8Array : Int8Array() Int16Array : Int16Array() Int32Array : Int32Array() IntersectionObserver : IntersectionObserver() IntersectionObserverEntry : IntersectionObserverEntry() Intl : Object JSON : JSON KeyboardEvent : KeyboardEvent() Location : Location() MIDIAccess : MIDIAccess() MIDIConnectionEvent : MIDIConnectionEvent() MIDIInput : MIDIInput() MIDIInputMap : MIDIInputMap() MIDIMessageEvent : MIDIMessageEvent() MIDIOutput : MIDIOutput() MIDIOutputMap : MIDIOutputMap() MIDIPort : MIDIPort() Map : Map() Math : Math E : 2.718281828459045 LN2 : 0.6931471805599453 LN10 : 2.302585092994046 LOG2E : 1.4426950408889634 LOG10E : 0.4342944819032518 PI : 3.141592653589793 SQRT1_2 : 0.7071067811865476 SQRT2 : 1.4142135623730951 abs : abs() acos : acos() acosh : acosh() asin : asin() asinh : asinh() atan : atan() atan2 : atan2() atanh : atanh() cbrt : cbrt() ceil : ceil() clz32 : clz32() cos : cos() cosh : cosh() exp : exp() expm1 : expm1() floor : floor() fround : fround() hypot : hypot() imul : imul() log : log() log1p : log1p() log2 : log2() log10 : log10() max : max() min : min() pow : pow() random : random() round : round() sign : sign() sin : sin() sinh : sinh() sqrt : sqrt() tan : tan() tanh : tanh() trunc : trunc() Symbol(Symbol.toStringTag) : "Math" __proto__ : Object MediaDevices : MediaDevices() MediaElementAudioSourceNode : MediaElementAudioSourceNode() MediaEncryptedEvent : MediaEncryptedEvent() MediaError : MediaError() MediaKeyMessageEvent : MediaKeyMessageEvent() MediaKeySession : MediaKeySession() MediaKeyStatusMap : MediaKeyStatusMap() MediaKeySystemAccess : MediaKeySystemAccess() MediaKeys : MediaKeys() MediaList : MediaList() MediaQueryList : MediaQueryList() MediaQueryListEvent : MediaQueryListEvent() MediaRecorder : MediaRecorder() MediaSource : MediaSource() MediaStreamAudioDestinationNode : MediaStreamAudioDestinationNode() MediaStreamAudioSourceNode : MediaStreamAudioSourceNode() MediaStreamEvent : MediaStreamEvent() MediaStreamTrack : MediaStreamTrack() MessageChannel : MessageChannel() MessageEvent : MessageEvent() MessagePort : MessagePort() MimeType : MimeType() MimeTypeArray : MimeTypeArray() MouseEvent : MouseEvent() MutationEvent : MutationEvent() MutationObserver : MutationObserver() MutationRecord : MutationRecord() NaN : NaN NamedNodeMap : NamedNodeMap() Navigator : Navigator() Node : Node() NodeFilter : NodeFilter() NodeIterator : NodeIterator() NodeList : NodeList() Notification : Notification() Number : Number() Object : Object() OfflineAudioCompletionEvent : OfflineAudioCompletionEvent() OfflineAudioContext : OfflineAudioContext() Option : HTMLOptionElement() OscillatorNode : OscillatorNode() PERSISTENT : 1 PageTransitionEvent : PageTransitionEvent() PasswordCredential : PasswordCredential() Path2D : Path2D() Performance : Performance() PerformanceEntry : PerformanceEntry() PerformanceMark : PerformanceMark() PerformanceMeasure : PerformanceMeasure() PerformanceNavigation : PerformanceNavigation() PerformanceObserver : PerformanceObserver() PerformanceObserverEntryList : PerformanceObserverEntryList() PerformanceResourceTiming : PerformanceResourceTiming() PerformanceTiming : PerformanceTiming() PeriodicWave : PeriodicWave() PermissionStatus : PermissionStatus() Permissions : Permissions() Plugin : Plugin() PluginArray : PluginArray() PopStateEvent : PopStateEvent() Presentation : Presentation() PresentationAvailability : PresentationAvailability() PresentationConnection : PresentationConnection() PresentationConnectionAvailableEvent : PresentationConnectionAvailableEvent() PresentationConnectionCloseEvent : PresentationConnectionCloseEvent() PresentationRequest : PresentationRequest() ProcessingInstruction : ProcessingInstruction() ProgressEvent : ProgressEvent() Promise : Promise() PromiseRejectionEvent : PromiseRejectionEvent() Proxy : Proxy() PushManager : PushManager() PushSubscription : PushSubscription() RTCCertificate : RTCCertificate() RTCIceCandidate : RTCIceCandidate() RTCSessionDescription : RTCSessionDescription() RadioNodeList : RadioNodeList() Range : Range() RangeError : RangeError() ReadableStream : ReadableStream() ReferenceError : ReferenceError() Reflect : Object RegExp : RegExp() Request : Request() Response : Response() SVGAElement : SVGAElement() SVGAngle : SVGAngle() SVGAnimateElement : SVGAnimateElement() SVGAnimateMotionElement : SVGAnimateMotionElement() SVGAnimateTransformElement : SVGAnimateTransformElement() SVGAnimatedAngle : SVGAnimatedAngle() SVGAnimatedBoolean : SVGAnimatedBoolean() SVGAnimatedEnumeration : SVGAnimatedEnumeration() SVGAnimatedInteger : SVGAnimatedInteger() SVGAnimatedLength : SVGAnimatedLength() SVGAnimatedLengthList : SVGAnimatedLengthList() SVGAnimatedNumber : SVGAnimatedNumber() SVGAnimatedNumberList : SVGAnimatedNumberList() SVGAnimatedPreserveAspectRatio : SVGAnimatedPreserveAspectRatio() SVGAnimatedRect : SVGAnimatedRect() SVGAnimatedString : SVGAnimatedString() SVGAnimatedTransformList : SVGAnimatedTransformList() SVGAnimationElement : SVGAnimationElement() SVGCircleElement : SVGCircleElement() SVGClipPathElement : SVGClipPathElement() SVGComponentTransferFunctionElement : SVGComponentTransferFunctionElement() SVGCursorElement : SVGCursorElement() SVGDefsElement : SVGDefsElement() SVGDescElement : SVGDescElement() SVGDiscardElement : SVGDiscardElement() SVGElement : SVGElement() SVGEllipseElement : SVGEllipseElement() SVGFEBlendElement : SVGFEBlendElement() SVGFEColorMatrixElement : SVGFEColorMatrixElement() SVGFEComponentTransferElement : SVGFEComponentTransferElement() SVGFECompositeElement : SVGFECompositeElement() SVGFEConvolveMatrixElement : SVGFEConvolveMatrixElement() SVGFEDiffuseLightingElement : SVGFEDiffuseLightingElement() SVGFEDisplacementMapElement : SVGFEDisplacementMapElement() SVGFEDistantLightElement : SVGFEDistantLightElement() SVGFEDropShadowElement : SVGFEDropShadowElement() SVGFEFloodElement : SVGFEFloodElement() SVGFEFuncAElement : SVGFEFuncAElement() SVGFEFuncBElement : SVGFEFuncBElement() SVGFEFuncGElement : SVGFEFuncGElement() SVGFEFuncRElement : SVGFEFuncRElement() SVGFEGaussianBlurElement : SVGFEGaussianBlurElement() SVGFEImageElement : SVGFEImageElement() SVGFEMergeElement : SVGFEMergeElement() SVGFEMergeNodeElement : SVGFEMergeNodeElement() SVGFEMorphologyElement : SVGFEMorphologyElement() SVGFEOffsetElement : SVGFEOffsetElement() SVGFEPointLightElement : SVGFEPointLightElement() SVGFESpecularLightingElement : SVGFESpecularLightingElement() SVGFESpotLightElement : SVGFESpotLightElement() SVGFETileElement : SVGFETileElement() SVGFETurbulenceElement : SVGFETurbulenceElement() SVGFilterElement : SVGFilterElement() SVGForeignObjectElement : SVGForeignObjectElement() SVGGElement : SVGGElement() SVGGeometryElement : SVGGeometryElement() SVGGradientElement : SVGGradientElement() SVGGraphicsElement : SVGGraphicsElement() SVGImageElement : SVGImageElement() SVGLength : SVGLength() SVGLengthList : SVGLengthList() SVGLineElement : SVGLineElement() SVGLinearGradientElement : SVGLinearGradientElement() SVGMPathElement : SVGMPathElement() SVGMarkerElement : SVGMarkerElement() SVGMaskElement : SVGMaskElement() SVGMatrix : SVGMatrix() SVGMetadataElement : SVGMetadataElement() SVGNumber : SVGNumber() SVGNumberList : SVGNumberList() SVGPathElement : SVGPathElement() SVGPatternElement : SVGPatternElement() SVGPoint : SVGPoint() SVGPointList : SVGPointList() SVGPolygonElement : SVGPolygonElement() SVGPolylineElement : SVGPolylineElement() SVGPreserveAspectRatio : SVGPreserveAspectRatio() SVGRadialGradientElement : SVGRadialGradientElement() SVGRect : SVGRect() SVGRectElement : SVGRectElement() SVGSVGElement : SVGSVGElement() SVGScriptElement : SVGScriptElement() SVGSetElement : SVGSetElement() SVGStopElement : SVGStopElement() SVGStringList : SVGStringList() SVGStyleElement : SVGStyleElement() SVGSwitchElement : SVGSwitchElement() SVGSymbolElement : SVGSymbolElement() SVGTSpanElement : SVGTSpanElement() SVGTextContentElement : SVGTextContentElement() SVGTextElement : SVGTextElement() SVGTextPathElement : SVGTextPathElement() SVGTextPositioningElement : SVGTextPositioningElement() SVGTitleElement : SVGTitleElement() SVGTransform : SVGTransform() SVGTransformList : SVGTransformList() SVGUnitTypes : SVGUnitTypes() SVGUseElement : SVGUseElement() SVGViewElement : SVGViewElement() SVGViewSpec : SVGViewSpec() SVGZoomEvent : SVGZoomEvent() Screen : Screen() ScreenOrientation : ScreenOrientation() ScriptProcessorNode : ScriptProcessorNode() SecurityPolicyViolationEvent : SecurityPolicyViolationEvent() Selection : Selection() ServiceWorker : ServiceWorker() ServiceWorkerContainer : ServiceWorkerContainer() ServiceWorkerMessageEvent : ServiceWorkerMessageEvent() ServiceWorkerRegistration : ServiceWorkerRegistration() Set : Set() ShadowRoot : ShadowRoot() SharedWorker : SharedWorker() SiteBoundCredential : SiteBoundCredential() SourceBuffer : SourceBuffer() SourceBufferList : SourceBufferList() SpeechSynthesisEvent : SpeechSynthesisEvent() SpeechSynthesisUtterance : SpeechSynthesisUtterance() Storage : Storage() StorageEvent : StorageEvent() String : String() StyleSheet : StyleSheet() StyleSheetList : StyleSheetList() SubtleCrypto : SubtleCrypto() Symbol : Symbol() SyncManager : SyncManager() SyntaxError : SyntaxError() TEMPORARY : 0 Text : Text() TextDecoder : TextDecoder() TextEncoder : TextEncoder() TextEvent : TextEvent() TextMetrics : TextMetrics() TextTrack : TextTrack() TextTrackCue : TextTrackCue() TextTrackCueList : TextTrackCueList() TextTrackList : TextTrackList() TimeRanges : TimeRanges() Touch : Touch() TouchEvent : TouchEvent() TouchList : TouchList() TrackEvent : TrackEvent() TransitionEvent : TransitionEvent() TreeWalker : TreeWalker() TypeError : TypeError() UIEvent : UIEvent() URIError : URIError() URL : URL() URLSearchParams : URLSearchParams() Uint8Array : Uint8Array() Uint8ClampedArray : Uint8ClampedArray() Uint16Array : Uint16Array() Uint32Array : Uint32Array() VTTCue : VTTCue() ValidityState : ValidityState() WaveShaperNode : WaveShaperNode() WeakMap : WeakMap() WeakSet : WeakSet() WebGLActiveInfo : WebGLActiveInfo() WebGLBuffer : WebGLBuffer() WebGLContextEvent : WebGLContextEvent() WebGLFramebuffer : WebGLFramebuffer() WebGLProgram : WebGLProgram() WebGLRenderbuffer : WebGLRenderbuffer() WebGLRenderingContext : WebGLRenderingContext() WebGLShader : WebGLShader() WebGLShaderPrecisionFormat : WebGLShaderPrecisionFormat() WebGLTexture : WebGLTexture() WebGLUniformLocation : WebGLUniformLocation() WebKitAnimationEvent : AnimationEvent() WebKitCSSMatrix : WebKitCSSMatrix() WebKitMutationObserver : MutationObserver() WebKitTransitionEvent : TransitionEvent() WebSocket : WebSocket() WheelEvent : WheelEvent() Window : Window() Worker : Worker() XMLDocument : XMLDocument() XMLHttpRequest : XMLHttpRequest() XMLHttpRequestEventTarget : XMLHttpRequestEventTarget() XMLHttpRequestUpload : XMLHttpRequestUpload() XMLSerializer : XMLSerializer() XPathEvaluator : XPathEvaluator() XPathExpression : XPathExpression() XPathResult : XPathResult() XSLTProcessor : XSLTProcessor() __defineGetter__ : __defineGetter__() __defineSetter__ : __defineSetter__() __lookupGetter__ : __lookupGetter__() __lookupSetter__ : __lookupSetter__() addEventListener : addEventListener() alert : alert() applicationCache : ApplicationCache atob : atob() blur : () btoa : btoa() caches : CacheStorage cancelAnimationFrame : cancelAnimationFrame() cancelIdleCallback : cancelIdleCallback() captureEvents : captureEvents() chrome : Object clearInterval : clearInterval() clearTimeout : clearTimeout() clientInformation : Navigator close : () closed : false confirm : confirm() console : Object constructor : Window() createImageBitmap : createImageBitmap() crypto : Crypto decodeURI : decodeURI() decodeURIComponent : decodeURIComponent() defaultStatus : "" defaultstatus : "" devicePixelRatio : 2 dispatchEvent : dispatchEvent() document : document encodeURI : encodeURI() encodeURIComponent : encodeURIComponent() escape : escape() eval : eval() event : undefined external : Object fetch : fetch() find : find() focus : () frameElement : null frames : Window getComputedStyle : getComputedStyle() getMatchedCSSRules : getMatchedCSSRules() getSelection : getSelection() hasOwnProperty : hasOwnProperty() history : History indexedDB : IDBFactory innerHeight : 1660 innerWidth : 980 isFinite : isFinite() isNaN : isNaN() isPrototypeOf : isPrototypeOf() isSecureContext : true length : 0 localStorage : Storage location : Location locationbar : BarProp matchMedia : matchMedia() menubar : BarProp moveBy : moveBy() moveTo : moveTo() name : "" navigator : Navigator offscreenBuffering : true onabort : null onanimationend : null onanimationiteration : null onanimationstart : null onbeforeunload : null onblur : null oncancel : null oncanplay : null oncanplaythrough : null onchange : null onclick : null onclose : null oncontextmenu : null oncuechange : null ondblclick : null ondevicemotion : null ondeviceorientation : null ondeviceorientationabsolute : null ondrag : null ondragend : null ondragenter : null ondragleave : null ondragover : null ondragstart : null ondrop : null ondurationchange : null onemptied : null onended : null onerror : null onfocus : null onhashchange : null oninput : null oninvalid : null onkeydown : null onkeypress : null onkeyup : null onlanguagechange : null onload : null onloadeddata : null onloadedmetadata : null onloadstart : null onmessage : null onmousedown : null onmouseenter : null onmouseleave : null onmousemove : null onmouseout : null onmouseover : null onmouseup : null onmousewheel : null onoffline : null ononline : null onpagehide : null onpageshow : null onpause : null onplay : null onplaying : null onpopstate : null onprogress : null onratechange : null onrejectionhandled : null onreset : null onresize : null onscroll : null onsearch : null onseeked : null onseeking : null onselect : null onshow : null onstalled : null onstorage : null onsubmit : null onsuspend : null ontimeupdate : null ontoggle : null ontransitionend : null onunhandledrejection : null onunload : null onvolumechange : null onwaiting : null onwebkitanimationend : null onwebkitanimationiteration : null onwebkitanimationstart : null onwebkittransitionend : null onwheel : null open : open() openDatabase : openDatabase() opener : null outerHeight : 542 outerWidth : 320 pageXOffset : 0 pageYOffset : 0 parent : Window parseFloat : parseFloat() parseInt : parseInt() performance : Performance personalbar : BarProp postMessage : () print : print() prompt : prompt() propertyIsEnumerable : propertyIsEnumerable() releaseEvents : releaseEvents() removeEventListener : removeEventListener() requestAnimationFrame : requestAnimationFrame() requestIdleCallback : requestIdleCallback() resizeBy : resizeBy() resizeTo : resizeTo() screen : Screen screenLeft : 0 screenTop : 0 screenX : 0 screenY : 0 script : script.JOLLYWALLET_mainScript scroll : scroll() scrollBy : scrollBy() scrollTo : scrollTo() scrollX : 0 scrollY : 0 scrollbars : BarProp self : Window sessionStorage : Storage setInterval : setInterval() setTimeout : setTimeout() speechSynthesis : SpeechSynthesis status : "" statusbar : BarProp stop : stop() styleMedia : StyleMedia toLocaleString : toLocaleString() toString : toString() toolbar : BarProp top : Window undefined : undefined unescape : unescape() valueOf : valueOf() webkitAudioContext : AudioContext() webkitCancelAnimationFrame : webkitCancelAnimationFrame() webkitCancelRequestAnimationFrame : webkitCancelRequestAnimationFrame() webkitIDBCursor : IDBCursor() webkitIDBDatabase : IDBDatabase() webkitIDBFactory : IDBFactory() webkitIDBIndex : IDBIndex() webkitIDBKeyRange : IDBKeyRange() webkitIDBObjectStore : IDBObjectStore() webkitIDBRequest : IDBRequest() webkitIDBTransaction : IDBTransaction() webkitIndexedDB : IDBFactory webkitMediaStream : MediaStream() webkitOfflineAudioContext : OfflineAudioContext() webkitRTCPeerConnection : RTCPeerConnection() webkitRequestAnimationFrame : webkitRequestAnimationFrame() webkitRequestFileSystem : webkitRequestFileSystem() webkitResolveLocalFileSystemURL : webkitResolveLocalFileSystemURL() webkitSpeechGrammar : SpeechGrammar() webkitSpeechGrammarList : SpeechGrammarList() webkitSpeechRecognition : SpeechRecognition() webkitSpeechRecognitionError : SpeechRecognitionError() webkitSpeechRecognitionEvent : SpeechRecognitionEvent() webkitStorageInfo : DeprecatedStorageInfo webkitURL : URL() window : Window Symbol(Symbol.toStringTag) : "Window" Console Animations Network conditions Rendering Search Sensors Preserve log  2016-09-28 03:13:35.573 file://api.jollywallet.com/affiliate/client?p=16&dist=261&sub=chrome208 Failed to load resource: net::ERR_FILE_NOT_FOUND 
github-adi/repository
http/www.pawoon.com/assets/js/jquery-2.1.1.min.js
JavaScript
mit
23,990
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), bower: grunt.file.readJSON('bower.json'), shell: { publish: { command: 'npm publish' } }, bump: { options: { files: ['package.json', 'bower.json'], updateConfigs: ['pkg', 'bower'], commit: true, commitMessage: 'Release v%VERSION%', commitFiles: ['package.json'], createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: true, pushTo: 'upstream', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' } }, karma: { unit: { configFile: 'test/karma.conf.js', singleRun: true } }, jshint: { all: ['Gruntfile.js', 'src/*.js', 'test/**/*.js'] }, uglify: { options: { preserveComments: 'some', report: 'min' }, dist: { files: [{ expand: true, cwd: 'src/', src: ['*.js'], dest: 'dist/', ext: '.min.js' }] } }, clean: ['dist'] }); require('load-grunt-tasks')(grunt); grunt.registerTask('test', ['jshint', 'karma']); grunt.registerTask('default', ['jshint', 'karma', 'uglify:dist']); grunt.registerTask('release', 'Release a new version, push it and publish it', function(target) { if (!target) { target = 'patch'; } return grunt.task.run('bump-only:' + target, 'default', 'bump-commit', 'shell:publish'); }); };
angulartics/angulartics-piwik
Gruntfile.js
JavaScript
mit
1,779
var assert = require('assert'); var timezone_mock = require('../'); ////////////////////////////////////////////////////////////////////////// // Test that the mocked date behaves exactly the same as the system date when // mocking the same timezone. // JE: 2017-05-26, Node 6.9.1: This test seems to fail when specifying non- // existent dates (undefined behavior anyway), not sure if this was working // before or not. if (!new timezone_mock._Date().toString().match(/\(PDT\)|\(PST\)|\(Pacific Daylight Time\)|\(Pacific Standard Time\)/)) { // Because we only have timezone info for a couple timezones, we can only test // this if the timezone we're mocking is the same as the system timezone. // In theory this could be extended to be able to test any timezone for which // we have timezone data. assert.ok(false, 'These tests only work if the local system timezone is Pacific'); } timezone_mock.register('US/Pacific'); // function test(d) { // var ret = []; // ret.push(d.getTimezoneOffset()); // ret.push(d.getHours()); // d.setTime(new Date('2015-03-08T02:30:11.000Z').getTime()); // ret.push(d.getTimezoneOffset()); // ret.push(d.getHours()); // d.setTime(new Date('2015-03-07T02:30:11.000Z').getTime()); // ret.push(d.getTimezoneOffset()); // ret.push(d.getHours()); // d.setTime(new Date('2015-03-09T02:30:11.000Z').getTime()); // ret.push(d.getTimezoneOffset()); // ret.push(d.getHours()); // return ret; // } var orig = new timezone_mock._Date(); var mock = new Date(); function pad2(v) { return ('0' + v).slice(-2); } var ts = new Date('2013-01-01T00:00:00.000Z').getTime(); var was_ok = true; var last = ts; var end = ts + 5*365*24*60*60*1000; var ok; function check(label) { function check2(fn) { if (orig[fn]() !== mock[fn]()) { ok = false; if (was_ok) { console.log(' ' + fn + ' (' + label + ')', orig[fn](), mock[fn]()); } } } check2('getTimezoneOffset'); check2('getHours'); check2('getTime'); } for (; ts < end; ts += 13*60*1000) { orig.setTime(ts); mock.setTime(ts); assert.equal(orig.toISOString(), mock.toISOString()); ok = true; check('setTime'); var test = new timezone_mock._Date(ts); orig = new timezone_mock._Date('2015-01-01'); mock = new Date('2015-01-01'); orig.setFullYear(test.getUTCFullYear()); mock.setFullYear(test.getUTCFullYear()); orig.setMinutes(test.getUTCMinutes()); mock.setMinutes(test.getUTCMinutes()); orig.setHours(test.getUTCHours()); mock.setHours(test.getUTCHours()); check('setFullYear/Minutes/Hours'); orig.setDate(test.getUTCDate()); mock.setDate(test.getUTCDate()); check('setDate'); var str = test.getUTCFullYear() + '-' + pad2(test.getUTCMonth() + 1) + '-' + pad2(test.getUTCDate()) + ' ' + pad2(test.getUTCHours()) + ':' + pad2(test.getUTCMinutes()) + ':' + pad2(test.getUTCSeconds()); orig = new timezone_mock._Date(str); mock = new Date(str); check('constructor ' + str); if (was_ok !== ok) { console.log((ok ? 'OK ' : 'NOT OK') + ' - ' + ts + ' (' + (ts - last) + ') ' + orig.toISOString() + ' (' + orig.toLocaleString() + ')'); last = ts; was_ok = ok; } }
Jimbly/timezone-mock
tests/test-vs-local.js
JavaScript
mit
3,189
import { shallowMount, mount } from '@vue/test-utils'; import { GlButton } from '@gitlab/ui'; import DagAnnotations from '~/pipelines/components/dag/dag_annotations.vue'; import { singleNote, multiNote } from './mock_data'; describe('The DAG annotations', () => { let wrapper; const getColorBlock = () => wrapper.find('[data-testid="dag-color-block"]'); const getAllColorBlocks = () => wrapper.findAll('[data-testid="dag-color-block"]'); const getTextBlock = () => wrapper.find('[data-testid="dag-note-text"]'); const getAllTextBlocks = () => wrapper.findAll('[data-testid="dag-note-text"]'); const getToggleButton = () => wrapper.find(GlButton); const createComponent = (propsData = {}, method = shallowMount) => { if (wrapper?.destroy) { wrapper.destroy(); } wrapper = method(DagAnnotations, { propsData, data() { return { showList: true, }; }, }); }; afterEach(() => { wrapper.destroy(); wrapper = null; }); describe('when there is one annotation', () => { const currentNote = singleNote['dag-link103']; beforeEach(() => { createComponent({ annotations: singleNote }); }); it('displays the color block', () => { expect(getColorBlock().exists()).toBe(true); }); it('displays the text block', () => { expect(getTextBlock().exists()).toBe(true); expect(getTextBlock().text()).toBe(`${currentNote.source.name} → ${currentNote.target.name}`); }); it('does not display the list toggle link', () => { expect(getToggleButton().exists()).toBe(false); }); }); describe('when there are multiple annoataions', () => { beforeEach(() => { createComponent({ annotations: multiNote }); }); it('displays a color block for each link', () => { expect(getAllColorBlocks().length).toBe(Object.keys(multiNote).length); }); it('displays a text block for each link', () => { expect(getAllTextBlocks().length).toBe(Object.keys(multiNote).length); Object.values(multiNote).forEach((item, idx) => { expect( getAllTextBlocks() .at(idx) .text(), ).toBe(`${item.source.name} → ${item.target.name}`); }); }); it('displays the list toggle link', () => { expect(getToggleButton().exists()).toBe(true); expect(getToggleButton().text()).toBe('Hide list'); }); }); describe('the list toggle', () => { beforeEach(() => { createComponent({ annotations: multiNote }, mount); }); describe('clicking hide', () => { it('hides listed items and changes text to show', () => { expect(getAllTextBlocks().length).toBe(Object.keys(multiNote).length); expect(getToggleButton().text()).toBe('Hide list'); getToggleButton().trigger('click'); return wrapper.vm.$nextTick().then(() => { expect(getAllTextBlocks().length).toBe(0); expect(getToggleButton().text()).toBe('Show list'); }); }); }); describe('clicking show', () => { it('shows listed items and changes text to hide', () => { getToggleButton().trigger('click'); getToggleButton().trigger('click'); return wrapper.vm.$nextTick().then(() => { expect(getAllTextBlocks().length).toBe(Object.keys(multiNote).length); expect(getToggleButton().text()).toBe('Hide list'); }); }); }); }); });
mmkassem/gitlabhq
spec/frontend/pipelines/components/dag/dag_annotations_spec.js
JavaScript
mit
3,479
module.exports = function(emitter) { var inBlocks; emitter.on('sectionValue', function(type, value) { switch (value) { case 'BLOCKS': inBlocks = true; return; default: if (inBlocks) { emitter.emit('blockValue', type, value); } } }); emitter.on('endSection', function() { inBlocks = false; }); };
LiamKarlMitchell/dxf
lib/handlers/blocks.js
JavaScript
mit
450
describe('Testing timeline controller', function () { var controller, scope, configService, timelineService, deferredConfig, deferredTimeline, deferredRemoval, $q, httpBackend; var windowMock = { alert: function(message) { }, confirm: function(message){ } }; beforeEach(function () { // load the module module('sourceApp', function ($provide) { $provide.value('$window', windowMock); }); spyOn(windowMock, 'alert'); inject(function($controller, $rootScope, _$q_, _configService_, _$httpBackend_, _timelineService_){ scope = $rootScope.$new(); $q = _$q_; httpBackend = _$httpBackend_; configService = _configService_; timelineService = _timelineService_; deferredConfig = _$q_.defer(); spyOn(configService, "getConfig").and.returnValue(deferredConfig.promise); deferredTimeline = _$q_.defer(); deferredRemoval = _$q_.defer(); spyOn(timelineService, "getMissionTimelines").and.returnValue(deferredTimeline.promise); spyOn(timelineService, "removeTimeline").and.returnValue(deferredRemoval.promise); controller = $controller('TimelineCtrl', { $scope: scope, configService: configService, timelineService: timelineService }); }); }); it('should define the timeline controller', function() { expect(controller).toBeDefined(); }); it('should define the function submit()', function(){ expect(controller.submit).toBeDefined(); }); it('should define the function uploadTimelineData()', function(){ expect(controller.uploadTimelineData).toBeDefined(); }); it('should define the function removeTimeline()', function(){ expect(controller.removeTimeline).toBeDefined(); }) it('should call the service to get list of missions', function() { var missions = [ "ATest", "AZero"]; var configlist = [{ mission: "ATest", source: { filename: "GMAT-6.xlsx", ipaddress: "10.0.0.16", name: "GMAT" } },{ mission: "AZero", source: { filename: "SIM.xlsx", ipaddress: "10.0.0.11", name: "Julia" } }]; deferredConfig.resolve({ data : configlist }); // call digest cycle for this to work scope.$digest(); expect(configService.getConfig).toHaveBeenCalled(); expect(controller.missionNames).toBeDefined(); expect(controller.missionNames).toEqual(missions); }); it('should call the service to get list of timelines to be displayed', function() { var timelineList = [{ filename: "Timeline", file: "timeline.xlsx", mission: "ATest" }]; deferredTimeline.resolve({ data : timelineList }); // call digest cycle for this to work scope.$digest(); expect(timelineService.getMissionTimelines).toHaveBeenCalled(); expect(controller.timelinelist).toBeDefined(); expect(controller.timelinelist).toEqual(timelineList); expect(controller.timelinelist.length).toEqual(1); }); it('should call the upload function when upload form is valid', function(){ controller.timelinedataupload_form = { $valid: true }; controller.uploads = { file : "timeline.xlsx", filename : "Timeline", missionName : "ATest" }; spyOn(controller, "uploadTimelineData"); controller.submit(); expect(controller.uploadTimelineData).toHaveBeenCalled(); }); it('should alert the user when filename is empty', function(){ controller.timelinedataupload_form = { $valid: true }; controller.uploads = { file : "timeline.xlsx", filename : "", missionName : "ATest" }; spyOn(controller, "uploadTimelineData"); controller.submit(); expect(controller.uploadTimelineData).not.toHaveBeenCalled(); expect(windowMock.alert).toHaveBeenCalledWith('Please enter a name for the file'); }); it('should alert the user when file is not selected/browsed', function(){ controller.timelinedataupload_form = { $valid: true }; controller.uploads = { file : "", filename : "Timeline", missionName : "ATest" }; spyOn(controller, "uploadTimelineData"); controller.submit(); expect(controller.uploadTimelineData).not.toHaveBeenCalled(); expect(windowMock.alert).toHaveBeenCalledWith('No file uploaded. Please upload an excel file.'); }); it('should alert the user when mission is not selected', function(){ controller.timelinedataupload_form = { $valid: true }; controller.uploads = { file : "timeline.xlsx", filename : "Timeline", missionName : "" }; spyOn(controller, "uploadTimelineData"); controller.submit(); expect(controller.uploadTimelineData).not.toHaveBeenCalled(); expect(windowMock.alert).toHaveBeenCalledWith('Please select the mission'); }); it('should upload file when uploadTimelineData() is called and successfully alert the user', function(){ controller.timelinedataupload_form = { $valid: true, $setPristine : function(){} }; controller.uploads = { file : "timeline.xlsx", filename : "Timeline", missionName : "ATest" }; var response = { status : "ok", message : "Timeline data saved successfully for ATest" } httpBackend.when('POST', '/saveTimelineData').respond(200, response); controller.uploadTimelineData(); httpBackend.flush(); expect(windowMock.alert).toHaveBeenCalledWith('Timeline data saved successfully for ATest'); expect(controller.uploads).toEqual({}); }); it('should show the list of files when file is successfully uploaded', function(){ controller.timelinedataupload_form = { $valid: true, $setPristine : function(){} }; controller.uploads = { file : "timeline.xlsx", filename : "Timeline", missionName : "ATest" }; var response = { config: { data: { filename: "Timeline", mission: "ATest" } }, error_code : 0 } var timelineList = [{ filename: "Timeline", file: "timeline.xlsx", mission: "ATest" }]; httpBackend.when('POST', '/saveTimelineData').respond(200, response); controller.uploadTimelineData(); httpBackend.flush(); deferredTimeline.resolve({ data : timelineList }); // call digest cycle for this to work scope.$digest(); expect(timelineService.getMissionTimelines).toHaveBeenCalled(); expect(controller.timelinelist).toBeDefined(); expect(controller.timelinelist).toEqual(timelineList); expect(controller.timelinelist.length).toEqual(1); }); it('should alert error to user when uploading file is not successful', function(){ controller.timelinedataupload_form = { $valid: true, $setPristine : function(){} }; controller.uploads = { file : "timeline.xlsx", filename : "Timeline", missionName : "ATest" }; var response = { status: "error", message: "Invalid files: Sheet1/Sheet2 is empty" } httpBackend.when('POST', '/saveTimelineData').respond(200, response); controller.uploadTimelineData(); httpBackend.flush(); expect(windowMock.alert).toHaveBeenCalledWith('Invalid files: Sheet1/Sheet2 is empty'); }); it('should remove timeline from timelinelist when removeTimeline() is called', function(){ controller.timelinelist = [{ filename: "Timeline", file: "timeline.xlsx", mission: "ATest" }]; spyOn(windowMock, 'confirm').and.returnValue(true); deferredRemoval.resolve({ data : {error_code : 0}, status : 200, config : { data : { mission : "ATest", filename : "timeline.xlsx" }} }); controller.removeTimeline("Timeline", "ATest"); // call digest cycle for this to work scope.$digest(); expect(timelineService.removeTimeline).toHaveBeenCalledWith("Timeline", "ATest"); expect(windowMock.alert).toHaveBeenCalledWith('Timeline File: timeline.xlsx for mission ATest is deleted.'); }) });
quindar/quindar-proxy
app/tests/timelineCtrl.spec.js
JavaScript
mit
9,172
const rowdyMenuBar = { bindings: {}, controller: function() { let ctrl = this; ctrl.menuButtons = [ { name: 'Kombucha', sref: 'app.kombucha' }, { name: 'About', sref: 'app.about' }, { name: 'Taproom', subNav: [ { name: 'News', sref: 'app.taproomNews' }, { name: 'Events', sref: 'app.taproomEvents' } ] }, { name: 'Store', sref: 'app.store' } ]; }, template: ` <nav id="menu-bar"> <div id="nav-logo"> <a ui-sref="app.home"><img src="images/rowdyMermaidWordyLogo.png" alt="Rowdy Mermaid Logo"></a> </div> <div id="nav-links"> <div id="user-links"> <a><i class="fa fa-user"></i></a> <a ng-click="className='slide-in'"> <i class="fa fa-shopping-cart"></i> <span ng-mouseover="$ctrl.isShowing = true">{{$ctrl.data.name}}</span> </a> </div> <div id="page-links"> <rowdy-menu-button data="button" ng-repeat="button in $ctrl.menuButtons" class="menu-button-style"> </div> </div> <div class="cart" ng-class="className"> <div class="header"> <i class="fa fa-times" aria-hidden="true" ng-click="className=''"></i> <h2>Your Shopping Cart</h2> </div> <hr> <a ui-sref="app.store" ng-click="className=''">Continue shopping</a> </div> </nav> ` }; angular .module('RowdyMermaid-site.widgets') .component('rowdyMenuBar', rowdyMenuBar);
BootcampersCollective/RowdyMermaid
client/app/widgets/menubar/menubar.component.js
JavaScript
mit
1,604
var x; x=$(document); x.ready(inicializarEventos); function inicializarEventos() { //Mantenemos oculta la capa loading... ocultaLoading(); //muestraLoading(); } function muestraLoading(){ jQuery('#loading').show(); jQuery('#imgLoading').show(); } function ocultaLoading(){ jQuery('#loading').hide(); jQuery('#imgLoading').hide(); } var page, pics, tab, lang; $(function () { page = { path: function () { return $("<a />").attr("href", $.current_url || location.pathname)[0].pathname }, }, pics = { $btn: function () { return $("#filters #btn_picsnav a") }, $picsnav: function () { return $("#pictures_nav") }, togglePicsNav: function () { if(pics.$picsnav().is(":visible")){ //$('nav>#pictures_nav #fotosClientesCarouselContainer #fotosClientesCarousel').carousel('pause'); pics.hidePicsNav(); } else { if ($("#pictures_nav").html() == "") { var $contenidoAjax = pics.$picsnav().html(''); $.ajax({ url: Routing.generate('PortalClientesBundle_navFotografias'), success: function(data){ // Aquí desaparece la imagen ya que estamos reemplazando todo el HTML del contenido de la div. $contenidoAjax.html(data); pics.showPicsNav(); } }); } else { pics.showPicsNav(); //$('nav>#pictures_nav #fotosClientesCarouselContainer #fotosClientesCarousel').carousel('next'); } } }, hidePicsNav: function () { pics.$picsnav().slideUp(200) }, showPicsNav: function () { pics.$picsnav().slideDown(200) }, buildPicsNav: function () { url = Routing.generate('PortalClientesBundle_navFotografias'); pics.$picsnav().load(url); }, }, pics.$btn().on("click", function () { pics.togglePicsNav(); }) tab = { $list: function () { return $("body > nav .nav_tab") }, clearActive: function () { tab.$list().removeClass("active") }, setActive: function () { var a = page.path(); tab.clearActive(),a == "/Switrans2/web/app_dev.php/es" || a == "/Switrans2/web/app_dev.php/en" ? ($('body > nav .nav_tab:contains("Inicio")').addClass("active")) : a == "/Switrans2/web/app_dev.php/es/Portal/ClientesBundle/Informes" || a == "/Switrans2/web/app_dev.php/en/Portal/ClientesBundle/Informes" ? ($('body > nav .nav_tab:contains("Informes")').addClass("active")) : a == "/Switrans2/web/app_dev.php/es/Portal/ClientesBundle/Reclamos" || a == "/Switrans2/web/app_dev.php/en/Portal/ClientesBundle/Reclamos" ? ($('body > nav .nav_tab:contains("Reclamos")').addClass("active")) : a == "/Switrans2/web/app_dev.php/es/Portal/ClientesBundle/Facturacion" || a == "/Switrans2/web/app_dev.php/en/Portal/ClientesBundle/Facturacion" ? ($('body > nav .nav_tab:contains("Facturación")').addClass("active")) : tab.clearActive() } }, tab.setActive(), lang = { $langopt: function () { return $("#langs #languages_nav #langselect a") }, toggleLang: function () { if ($('#ingles_langselect').length) { var url = Routing.generate("PortalClientesBundle_homepage", { "_locale": "en"}); } else { var url = Routing.generate("PortalClientesBundle_homepage", { "_locale": "es"}); } $(location).attr('href',url); } }, lang.$langopt().on("click", function () { return lang.toggleLang(); }) // Initialize validator setDefaults $.validator.setDefaults({ highlight: function(input) { $(input).addClass("ui-state-highlight"); }, unhighlight: function(input) { $(input).removeClass("ui-state-highlight"); } }); });
wiccano/Symfony2-SoftwareFreedomDay2012
src/Admin/DashboardBundle/Resources/public/js/Switrans2Jquery.js
JavaScript
mit
3,733
import React, { Component } from 'react'; import { TabBarIOS, AppRegistry, StyleSheet, Text, View } from 'react-native'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import Icon from 'react-native-vector-icons/Ionicons'; class List extends Component { render(){ return ( <View style={styles.container}> <Text>List</Text> <FontAwesome name="address-book" size={80} color="#4F8EF7" /> </View> ) } } class Edit extends Component { render(){ return ( <View style={styles.container}> <Text>Edit</Text> <FontAwesome name="qq" size={80} color="#4F8EF7" /> </View> ) } } class Account extends Component { render(){ return ( <View style={styles.container}> <Text>Account</Text> <FontAwesome name="weibo" size={80} color="#4F8EF7" /> </View> ) } } class RNStudy extends Component { constructor(props) { super(props); this.state = {selectedTab: 'list'} } render() { return ( <TabBarIOS tintColor="white"> <Icon.TabBarItem iconName='ios-videocam-outline' selectedIconName='ios-videocam' selected={this.state.selectedTab === 'list'} onPress={() => { this.setState({ selectedTab: 'list', }); }}> <List /> </Icon.TabBarItem> <Icon.TabBarItem iconName='ios-recording-outline' selectedIconName='ios-recording' selected={this.state.selectedTab === 'edit'} onPress={() => { this.setState({ selectedTab: 'edit', }); }}> <Edit /> </Icon.TabBarItem> <Icon.TabBarItem iconName='ios-more-outline' selectedIconName='ios-more' selected={this.state.selectedTab === 'account'} onPress={() => { this.setState({ selectedTab: 'account', }); }}> <Account /> </Icon.TabBarItem> </TabBarIOS> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, }); AppRegistry.registerComponent('RNStudy', () => RNStudy);
csxiaoyaojianxian/JavaScriptStudy
19-移动端/01-react-native/04-图标组件/04-图标组件.js
JavaScript
mit
2,402
module.exports = { "configuration": { "appender": { "name": "console", "transports": [{ "module": "Console", "options": { "colorize": true, "timestamp": true } }] }, "logger": [{ "name": "http", "level": "warn", "appender-ref": "console" }], "root": { "level": "info", "appender-ref": "console" } } };
eyolas/yanlog
examples/app/yanlog.js
JavaScript
mit
541
'use strict'; const sinon = require('sinon'); const expect = require('chai').expect; const UserModel = require('../models/user-model'); const { registerUser, getUser, resetPassword } = require('./user-controller'); const factory = require('../utils/factory'); const encrypt = require('../utils/encrypt'); describe('user-controller', () => { let ctx; let userParams; beforeEach(function() { ctx = { request: { body: {}, token: { sub: 123 } }, body: {} }; }); // FIXME: Refactor and stub this test correctly. describe('register', () => { let create; beforeEach(function() { create = sinon.stub(factory, 'create'); userParams = { email: 'test@test.com', password: 'someTestPassword', isModified: () => true, encrypt, save: function() { return new Promise((resolve, reject) => { this.encrypt(() => { resolve(this); }); }); } }; create.returns(userParams); }); afterEach(() => { create.restore(); }); it('should register a user', async function() { ctx.request.body = { email: 'test@test.com', password: 'someTestPassword' }; await registerUser(ctx, () => {}); expect(ctx.body.email).to.equal(ctx.request.body.email); expect(ctx.body).to.have.property('password'); }); }); it('should get user info', async () => { const findById = sinon.stub(UserModel, 'findById'); findById.returns({ email: 'test@test.com', toJSON() { return { email: 'test@test.com' }; } }); await getUser(ctx); findById.restore(); expect(ctx.body).to.have.property('email', 'test@test.com'); }); it('should reset user password', async () => { ctx.request.body.password = 'abc123'; const findById = sinon.stub(UserModel, 'findById'); findById.returns({ email: 'test@test.com', toJSON() { return { email: 'test@test.com' }; }, save() { return new Promise((resolve, reject) => { encrypt.call(ctx.request.body, () => { resolve(Object.assign( ctx.request.body )); }); }); } }); await resetPassword(ctx); expect(ctx.body.password.length > 10).to.equal(true); }); });
JoelRoxell/heimdall
src/controllers/user-controller.spec.js
JavaScript
mit
2,425
// Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. // For example, // Given [3,2,1,5,6,4] and k = 2, return 5. // Note: // You may assume k is always valid, 1 ≤ k ≤ array's length. // Credits: // Special thanks to @mithmatt for adding this problem and creating all test cases. /** * @param {number[]} nums * @param {number} k * @return {number} */ var findKthLargest1 = function(nums, k) { nums.sort((a,b) => {return b-a;}); return nums[k - 1]; }; Array.prototype.swap = function (x,y) { var b = this[x]; this[x] = this[y]; this[y] = b; return this; } /** * This approach use quicksort, but stop when the partition is at the kth largest element */ var findKthLargest2 = function(nums, k, l, r) { var partition = function(arr, left, right) { var x = arr[right]; var i = left; for (let j = left; j < right; j++) { if (arr[j] <= x) arr.swap(i++, j); } arr.swap(i, right); return i; }; var p = partition(nums, l, r); // if partition if (p == (nums.length - k)) return nums[p]; else if (p < (nums.length - k)) return findKthLargest2(nums, k, p + 1, r); else return findKthLargest2(nums, k, l, p - 1); } var findKthLargest = function(nums, k) { return findKthLargest2(nums, k, 0, nums.length - 1); } console.log(findKthLargest([1,3,6,4,8,22,54,2,51,68,42,56],5));
seanxwzhang/LeetCode
215 Kth Largest Element in an Array/solution.js
JavaScript
mit
1,522
/** * This file is part of the react-fundamentals package. * * 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. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import * as Constants from "../app-constants"; const defaultState = { isLoading: true, bio: {}, repos: [] }; /** * Profile Reducer * * @param {object} state * @param {object} action * @returns {object} */ export default function profileReducer(state = defaultState, action) { switch (action.type) { case Constants.PROFILE_EVENT_LOADING: return { ...state, isLoading: true }; case Constants.PROFILE_EVENT_LOADED: return { ...state, isLoading: false, bio: action.profile.bio, repos: action.profile.repos }; case Constants.PROFILE_EVENT_UNLOAD: return { ...defaultState }; default: return state; } }
SeerUK/react-fundamentals
src/js/reducers/profile-reducer.js
JavaScript
mit
1,375
// Generated by CoffeeScript 1.6.3 (function() { var db, sha1; db = require('../db'); sha1 = require('sha1'); module.exports.apply = function(app) { app.get('/login', function(req, res) { return res.render('login.jade', { session: req.session, disablelogin: true }); }); return app.post('/login', function(req, res) { var admins, password, username, _ref; admins = db.admins; _ref = req.body, username = _ref.username, password = _ref.password; if (password != null) { password = sha1(password); } admins.forEach(function(admin) { if (admin.username === username && admin.password === password) { req.session.logined = true; req.session.username = admin.username; return res.redirect('/'); } }); if (!req.session.logined) { return res.error({ reason: '用户名密码验证错误', redirect: '/' }, req.session); } }); }; }).call(this);
yanke-guo/simple-ci
routers/Login.router.js
JavaScript
mit
1,039
// Copyright 2008-2009 University of Jyväskylä // // Authors: // Asko Soukka <asko.soukka@iki.fi> // Sacha Helfenstein <sh@jyu.fi> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation files // (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /*globals SoTech*/ /** @class SoTech.TableColumnView @extends SC.ListView */ SoTech.TableColumnView = SC.ListView.extend( /** @scope SoTech.TableColumnView.prototype */ { contentBinding: ".table.content", selectionBinding: ".table.selection", canEditContentBinding: ".table.canEditContent", canDeleteContentBinding: ".table.canDeleteContent", showAlternatingRowsBinding: ".table.showAlternatingRows", canReorderContentBinding: ".table.canReorderContent", isDropTargetBinding: ".table.isDropTarget", delegateBinding: ".table.delegate", targetBinding: ".table.target", actionBinding: ".table.action", rowHeightBinding: ".table.rowHeight", isEnabledBinding: ".table.isEnabled", textAlign: SC.ALIGN_LEFT, dragContentBinding: ".table.dragContent", proposedInsertionIndexBinding: ".table.proposedInsertionIndex", proposedDropOperationBinding: ".table.proposedDropOperation", exampleView: SC.ListItemView.extend({ textAlignBinding: ".parentView.textAlign", render: function(context, firstTime) { sc_super(); var textAlign = this.get("textAlign") || SC.ALIGN_LEFT; context.addStyle('text-align', textAlign); } }), table: function() { return this.getPath("parentView.parentView.parentView.parentView"); }.property().cacheable(), render: function(context, firstTime) { sc_super(); context.setClass("focus", this.getPath("table.hasFirstResponder")); }, moveRight: function() { var columns = this.getPath("table.childViews"), index = columns.indexOf(this.getPath("parentView.parentView.parentView")); if (index < columns.get("length") - 1) { columns[index + 1].rows.contentView.becomeFirstResponder(); } }, moveLeft: function() { var columns = this.getPath("table.childViews"), index = columns.indexOf(this.getPath("parentView.parentView.parentView")); if (index > 0) { columns[index - 1].rows.contentView.becomeFirstResponder(); } }, selectionChanged: function() { var sel = this.get("selection"), editable = this.get("canEditContent"); if (editable && this.get("isFirstResponder") && !SC.none(sel) && sel.get("length") === 1) { this.get("classNames").pushObject("st-cursor"); this.$().addClass("st-cursor"); } else { this.set("classNames", this.get("classNames").without("st-cursor")); this.$().removeClass("st-cursor"); } }.observes("selection", "isFirstResponder"), didBecomeFirstResponder: function() { sc_super(); this.get("pane")._pendingResponder = null; // stop bubling this.get("table").$(".sc-list-view").addClass("focus"); this.get("table").propertyDidChange("hasFirstResponder"); }, willLoseFirstResponder: function() { sc_super(); this.get("table").$(".sc-list-view").removeClass("focus"); this.get("table").propertyDidChange("hasFirstResponder"); }, reorderDataType: function() { return this.getPath("table.reorderDataType"); }.property().cacheable(), showInsertionPoint: function(itemView, dropOperation) { this.get("table").showInsertionPoint(itemView, dropOperation); }, hideInsertionPoint: function() { this.get("table").hideInsertionPoint(); }, _showInsertionPoint: function(itemView, dropOperation) { this.showInsertionPoint.base.apply(this, arguments); }, _hideInsertionPoint: function(itemView, dropOperation) { this.hideInsertionPoint.base.apply(this, arguments); }, _cv_dragViewFor: function(dragContent) { // find only the indexes that are in both dragContent and nowShowing. var indexes = this.get("nowShowing").without(dragContent); indexes = this.get("nowShowing").without(indexes); // get a custom view from TableView return this.get("table")._tv_dragViewFor(indexes, this); }, ghostActsLikeCursor: NO });
datakurre/sotech
frameworks/table_view/views/table_column.js
JavaScript
mit
5,066
var clv = require("../../../../index.js"); var assert = require("assert"); describe("Generated test - ins/undo/ins/rm/rm/undo/undo/ins/ins/ins/rm/ins/ins/ins/undo/rm/ins/ins/ins/undo - 20-ops-0b5d750e-abc3-49d1-b16c-396df33d35db", function() { var doc1 = new clv.string.Document("d7d526f0-5327-11e7-9905-cf77d4c19b39", 0, null); var doc2 = new clv.string.Document("d7d749d0-5327-11e7-9905-cf77d4c19b39", 0, null); var data1 = "Hello World"; var data2 = "Hello World"; var serverData = {"id":"6a7a20ec-d64b-4857-9dbd-57187b58e5e7","data":"Hello World","ops":[],"execOrder":0,"context":null}; it("Site d7d526f0-5327-11e7-9905-cf77d4c19b39 operations should be executed without errors", function() { var commit1 = [{"type":0,"at":11,"value":"tr"}]; var commitTuple1 = doc1.commit(commit1); data1 = clv.string.exec(data1, commitTuple1.toExec); var update1 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":3,"value":"r"},"execOrder":1},{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":11,"value":"tr"},"execOrder":2}]; var updateTuple1 = doc1.update(update1); data1 = clv.string.exec(data1, updateTuple1.toExec); var update2 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":2,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":0,"load":{"type":1,"at":5,"value":"o "},"execOrder":3}]; var updateTuple2 = doc1.update(update2); data1 = clv.string.exec(data1, updateTuple2.toExec); var commitTuple2 = doc1.undo(); data1 = clv.string.exec(data1, commitTuple2.toExec); var commit3 = [{"type":0,"at":2,"value":"ye"}]; var commitTuple3 = doc1.commit(commit3); data1 = clv.string.exec(data1, commitTuple3.toExec); var update3 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":1,"at":11,"value":"tr"},"execOrder":4}]; var updateTuple3 = doc1.update(update3); data1 = clv.string.exec(data1, updateTuple3.toExec); var update4 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":2,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"ye"},"execOrder":5}]; var updateTuple4 = doc1.update(update4); data1 = clv.string.exec(data1, updateTuple4.toExec); var update5 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"wq"},"execOrder":6}]; var updateTuple5 = doc1.update(update5); data1 = clv.string.exec(data1, updateTuple5.toExec); var update6 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":4,"value":"yrt"},"execOrder":7},{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":10,"value":"qw"},"execOrder":8}]; var updateTuple6 = doc1.update(update6); data1 = clv.string.exec(data1, updateTuple6.toExec); var commit4 = [{"type":1,"at":15,"value":"o"}]; var commitTuple4 = doc1.commit(commit4); data1 = clv.string.exec(data1, commitTuple4.toExec); var update7 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":1,"at":10,"value":"qw"},"execOrder":9}]; var updateTuple7 = doc1.update(update7); data1 = clv.string.exec(data1, updateTuple7.toExec); var update8 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":6,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":10,"value":"rl"},"execOrder":10},{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":15,"value":"o"},"execOrder":11}]; var updateTuple8 = doc1.update(update8); data1 = clv.string.exec(data1, updateTuple8.toExec); var commit5 = [{"type":1,"at":0,"value":"H"}]; var commitTuple5 = doc1.commit(commit5); data1 = clv.string.exec(data1, commitTuple5.toExec); var update9 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":7,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":12,"value":"wr"},"execOrder":12}]; var updateTuple9 = doc1.update(update9); data1 = clv.string.exec(data1, updateTuple9.toExec); var update10 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":0,"value":"H"},"execOrder":13}]; var updateTuple10 = doc1.update(update10); data1 = clv.string.exec(data1, updateTuple10.toExec); var update11 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":8,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":7,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":1,"value":"qe"},"execOrder":14}]; var updateTuple11 = doc1.update(update11); data1 = clv.string.exec(data1, updateTuple11.toExec); var commitTuple6 = doc1.undo(); data1 = clv.string.exec(data1, commitTuple6.toExec); var update12 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":9,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":8,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"y"},"execOrder":15}]; var updateTuple12 = doc1.update(update12); data1 = clv.string.exec(data1, updateTuple12.toExec); var commitTuple7 = doc1.undo(); data1 = clv.string.exec(data1, commitTuple7.toExec); var update13 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":9,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":1,"at":6,"value":"y"},"execOrder":16},{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":0,"at":0,"value":"H"},"execOrder":17}]; var updateTuple13 = doc1.update(update13); data1 = clv.string.exec(data1, updateTuple13.toExec); var commit8 = [{"type":0,"at":11,"value":"e"}]; var commitTuple8 = doc1.commit(commit8); data1 = clv.string.exec(data1, commitTuple8.toExec); var update14 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":0,"at":15,"value":"o"},"execOrder":18}]; var updateTuple14 = doc1.update(update14); data1 = clv.string.exec(data1, updateTuple14.toExec); var commit9 = [{"type":0,"at":15,"value":"rr"}]; var commitTuple9 = doc1.commit(commit9); data1 = clv.string.exec(data1, commitTuple9.toExec); var update15 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1,"3":1,"4":1},"invClusterSize":3},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1,"9":1},"invClusterSize":2}},"size":2},"invCount":0,"load":{"type":0,"at":11,"value":"e"},"execOrder":19}]; var updateTuple15 = doc1.update(update15); data1 = clv.string.exec(data1, updateTuple15.toExec); var update16 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":6,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{"1":1,"3":1,"4":1},"invClusterSize":3},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1,"9":1},"invClusterSize":2}},"size":2},"invCount":0,"load":{"type":0,"at":15,"value":"rr"},"execOrder":20}]; var updateTuple16 = doc1.update(update16); data1 = clv.string.exec(data1, updateTuple16.toExec); }); it("Site d7d749d0-5327-11e7-9905-cf77d4c19b39 operations should be executed without errors", function() { var commit1 = [{"type":0,"at":3,"value":"r"}]; var commitTuple1 = doc2.commit(commit1); data2 = clv.string.exec(data2, commitTuple1.toExec); var update1 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":3,"value":"r"},"execOrder":1}]; var updateTuple1 = doc2.update(update1); data2 = clv.string.exec(data2, updateTuple1.toExec); var commit2 = [{"type":1,"at":5,"value":"o "}]; var commitTuple2 = doc2.commit(commit2); data2 = clv.string.exec(data2, commitTuple2.toExec); var update2 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":11,"value":"tr"},"execOrder":2}]; var updateTuple2 = doc2.update(update2); data2 = clv.string.exec(data2, updateTuple2.toExec); var update3 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":2,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":0,"load":{"type":1,"at":5,"value":"o "},"execOrder":3}]; var updateTuple3 = doc2.update(update3); data2 = clv.string.exec(data2, updateTuple3.toExec); var commit3 = [{"type":0,"at":2,"value":"wq"}]; var commitTuple3 = doc2.commit(commit3); data2 = clv.string.exec(data2, commitTuple3.toExec); var update4 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":1,"at":11,"value":"tr"},"execOrder":4},{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":2,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"ye"},"execOrder":5}]; var updateTuple4 = doc2.update(update4); data2 = clv.string.exec(data2, updateTuple4.toExec); var commit4 = [{"type":0,"at":4,"value":"yrt"}]; var commitTuple4 = doc2.commit(commit4); data2 = clv.string.exec(data2, commitTuple4.toExec); var update5 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"wq"},"execOrder":6}]; var updateTuple5 = doc2.update(update5); data2 = clv.string.exec(data2, updateTuple5.toExec); var commit5 = [{"type":0,"at":10,"value":"qw"}]; var commitTuple5 = doc2.commit(commit5); data2 = clv.string.exec(data2, commitTuple5.toExec); var update6 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":4,"value":"yrt"},"execOrder":7}]; var updateTuple6 = doc2.update(update6); data2 = clv.string.exec(data2, updateTuple6.toExec); var commitTuple6 = doc2.undo(); data2 = clv.string.exec(data2, commitTuple6.toExec); var update7 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":10,"value":"qw"},"execOrder":8}]; var updateTuple7 = doc2.update(update7); data2 = clv.string.exec(data2, updateTuple7.toExec); var commit7 = [{"type":1,"at":10,"value":"rl"}]; var commitTuple7 = doc2.commit(commit7); data2 = clv.string.exec(data2, commitTuple7.toExec); var update8 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":1,"at":10,"value":"qw"},"execOrder":9}]; var updateTuple8 = doc2.update(update8); data2 = clv.string.exec(data2, updateTuple8.toExec); var update9 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":6,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":10,"value":"rl"},"execOrder":10}]; var updateTuple9 = doc2.update(update9); data2 = clv.string.exec(data2, updateTuple9.toExec); var commit8 = [{"type":0,"at":12,"value":"wr"}]; var commitTuple8 = doc2.commit(commit8); data2 = clv.string.exec(data2, commitTuple8.toExec); var update10 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":15,"value":"o"},"execOrder":11}]; var updateTuple10 = doc2.update(update10); data2 = clv.string.exec(data2, updateTuple10.toExec); var update11 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":7,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":12,"value":"wr"},"execOrder":12}]; var updateTuple11 = doc2.update(update11); data2 = clv.string.exec(data2, updateTuple11.toExec); var commit9 = [{"type":0,"at":1,"value":"qe"}]; var commitTuple9 = doc2.commit(commit9); data2 = clv.string.exec(data2, commitTuple9.toExec); var update12 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":0,"value":"H"},"execOrder":13}]; var updateTuple12 = doc2.update(update12); data2 = clv.string.exec(data2, updateTuple12.toExec); var commit10 = [{"type":0,"at":6,"value":"y"}]; var commitTuple10 = doc2.commit(commit10); data2 = clv.string.exec(data2, commitTuple10.toExec); var update13 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":8,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":7,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":1,"value":"qe"},"execOrder":14}]; var updateTuple13 = doc2.update(update13); data2 = clv.string.exec(data2, updateTuple13.toExec); var commitTuple11 = doc2.undo(); data2 = clv.string.exec(data2, commitTuple11.toExec); var update14 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":9,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":8,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"y"},"execOrder":15}]; var updateTuple14 = doc2.update(update14); data2 = clv.string.exec(data2, updateTuple14.toExec); var update15 = [{"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":9,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":1,"at":6,"value":"y"},"execOrder":16}]; var updateTuple15 = doc2.update(update15); data2 = clv.string.exec(data2, updateTuple15.toExec); var update16 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":0,"at":0,"value":"H"},"execOrder":17}]; var updateTuple16 = doc2.update(update16); data2 = clv.string.exec(data2, updateTuple16.toExec); var update17 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":0,"at":15,"value":"o"},"execOrder":18}]; var updateTuple17 = doc2.update(update17); data2 = clv.string.exec(data2, updateTuple17.toExec); var update18 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1,"3":1,"4":1},"invClusterSize":3},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1,"9":1},"invClusterSize":2}},"size":2},"invCount":0,"load":{"type":0,"at":11,"value":"e"},"execOrder":19}]; var updateTuple18 = doc2.update(update18); data2 = clv.string.exec(data2, updateTuple18.toExec); var update19 = [{"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":6,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{"1":1,"3":1,"4":1},"invClusterSize":3},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1,"9":1},"invClusterSize":2}},"size":2},"invCount":0,"load":{"type":0,"at":15,"value":"rr"},"execOrder":20}]; var updateTuple19 = doc2.update(update19); data2 = clv.string.exec(data2, updateTuple19.toExec); }); it("Server operations should be executed without errors", function() { function updateServer(op) { var server = new clv.string.Document(null, serverData.execOrder, serverData.context); server.update(serverData.ops); var serverTuple = server.update(op); serverData.data = clv.string.exec(serverData.data, serverTuple.toExec); serverData.context = server.getContext(); serverData.ops.push(op); serverData.execOrder = server.getExecOrder(); } var serverUpdate0 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":3,"value":"r"},"execOrder":1}; updateServer(serverUpdate0); var serverUpdate1 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":11,"value":"tr"},"execOrder":2}; updateServer(serverUpdate1); var serverUpdate2 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":2,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":0,"load":{"type":1,"at":5,"value":"o "},"execOrder":3}; updateServer(serverUpdate2); var serverUpdate3 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":1,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":1,"at":11,"value":"tr"},"execOrder":4}; updateServer(serverUpdate3); var serverUpdate4 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":2,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"ye"},"execOrder":5}; updateServer(serverUpdate4); var serverUpdate5 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"wq"},"execOrder":6}; updateServer(serverUpdate5); var serverUpdate6 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":4,"value":"yrt"},"execOrder":7}; updateServer(serverUpdate6); var serverUpdate7 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":10,"value":"qw"},"execOrder":8}; updateServer(serverUpdate7); var serverUpdate8 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":1,"at":10,"value":"qw"},"execOrder":9}; updateServer(serverUpdate8); var serverUpdate9 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":6,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":10,"value":"rl"},"execOrder":10}; updateServer(serverUpdate9); var serverUpdate10 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":15,"value":"o"},"execOrder":11}; updateServer(serverUpdate10); var serverUpdate11 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":7,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":12,"value":"wr"},"execOrder":12}; updateServer(serverUpdate11); var serverUpdate12 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":0,"value":"H"},"execOrder":13}; updateServer(serverUpdate12); var serverUpdate13 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":8,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":7,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":1,"value":"qe"},"execOrder":14}; updateServer(serverUpdate13); var serverUpdate14 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":9,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":8,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"y"},"execOrder":15}; updateServer(serverUpdate14); var serverUpdate15 = {"siteId":"d7d749d0-5327-11e7-9905-cf77d4c19b39","seqId":9,"context":{"vector":{"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1},"invClusterSize":1},"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":1,"at":6,"value":"y"},"execOrder":16}; updateServer(serverUpdate15); var serverUpdate16 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":4,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":6,"invCluster":{"5":1},"invClusterSize":1}},"size":2},"invCount":1,"load":{"type":0,"at":0,"value":"H"},"execOrder":17}; updateServer(serverUpdate16); var serverUpdate17 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":3,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":0,"at":15,"value":"o"},"execOrder":18}; updateServer(serverUpdate17); var serverUpdate18 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":5,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":4,"invCluster":{"1":1,"3":1,"4":1},"invClusterSize":3},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1,"9":1},"invClusterSize":2}},"size":2},"invCount":0,"load":{"type":0,"at":11,"value":"e"},"execOrder":19}; updateServer(serverUpdate18); var serverUpdate19 = {"siteId":"d7d526f0-5327-11e7-9905-cf77d4c19b39","seqId":6,"context":{"vector":{"d7d526f0-5327-11e7-9905-cf77d4c19b39":{"seqId":5,"invCluster":{"1":1,"3":1,"4":1},"invClusterSize":3},"d7d749d0-5327-11e7-9905-cf77d4c19b39":{"seqId":9,"invCluster":{"5":1,"9":1},"invClusterSize":2}},"size":2},"invCount":0,"load":{"type":0,"at":15,"value":"rr"},"execOrder":20}; updateServer(serverUpdate19); }); it("All sites should have same data with the server", function() { assert.equal(data1, serverData.data, "Site 1 data should be equal to server"); assert.equal(data2, serverData.data, "Site 2 data should be equal to server"); }); });
collaborativejs/collaborative-js
tests/automatic/generated/20/20-ops-0b5d750e-abc3-49d1-b16c-396df33d35db.js
JavaScript
mit
28,699
/** * Log Unobtrusive Extension v0.0.7 * * Used within AngularJS to enhance functionality within the AngularJS $log service. * * @original-author Thomas Burleson * @contributor Layton Whiteley * @contributor A confused individual <ferronrsmith@gmail.com> * @website http://www.theSolutionOptimist.com * (c) 2013 https://github.com/lwhiteley/AngularLogExtender * License: MIT * * Modifications made by @contributor Layton Whiteley: * - Modified to be a full stand-alone Angular Application for reuse * - Has global and feature level activation/disabling for $log * - Created and tested with AngularJS v.1.2.3 */ angular.module("log.ex.uo", []).provider('logEx', ['$provide', function($provide) { // Creates an injector function that can be used for retrieving services as well as for dependency injection var $injector = angular.injector(['ng']); // Used the $injector defined to retrieve the $filterProvider var $filter = $injector.get('$filter'); /** * Used to enable logging globally * @type {boolean} */ var enableGlobally = false; /** * Used to activate logPrefix overriding * @type {boolean} */ var logPrefixOverride = false; /** * Used to force log-ex to use the default log prefix rules * @type {boolean} */ var useDefaultPrefix = false; /** * Used to store custom log prefix rules * @type {null | Function} */ var customLogPrefixFn = null; /** * current browser's user agent * @type {string} */ var userAgent = navigator.userAgent; /** * default log methods available * @type {string[]} */ var defaultLogMethods = ['log', 'info', 'warn', 'debug', 'error', 'getInstance']; /** * list of browsers that support colorify * @type {string[]} */ var colorifySupportedBrowsers = ['chrome', 'firefox']; /** * flag to activate/deactivate default log method colors * @type {boolean} */ var useDefaultColors = true; /** * default colours for each log method * @type {object} */ var defaultLogMethodColors = { log: 'color: green;', info: 'color: blue', warn: 'color: #CC9933;', debug: 'color: brown;', error: 'color: red;' }; /** * publicly allowed methods for the extended $log object. * this give the developer the option of using special features * such as setting a className and overriding log messages. * More Options to come. * @type {string[]} */ var allowedMethods = defaultLogMethods; /** * Trims whitespace at the beginning and/or end of a string * @param {String} value - string to be trimmed * @returns {String} - returns an empty string if the value passed is not of type {String} */ var trimString = function(value) { if (itypeof(value) === 'string') return value.replace(/^\s*/, '').replace(/\s*$/, ''); return ""; }; /** * The itypeof operator returns a string indicating the type of the unevaluated operand. * @param {*} val - object to be evaluated * @returns {String} - returns a string with the type of the evaluated operand */ var itypeof = function(val) { return Object.prototype.toString.call(val).replace(/(\[|object|\s|\])/g, "").toLowerCase(); }; /** * checks if a variable is of @type {boolean} * @param {boolean} value - flag to be evaluated * @returns {boolean} - returns true if evaluated object is a boolean */ var isBoolean = function(value) { return itypeof(value) === 'boolean'; }; /** * This method checks if a variable is of type {string} * and if the string is not an empty string * @param {string} value - string to be evaluated * @returns {*|Boolean|boolean} - returns true if string is not null or empty */ var isValidString = function(value) { return (itypeof(value) === 'string' && trimString(value) !== ""); }; /** * checks if @param1 is a substring of @param2 * @param {string} sub - partial string that may be a sub string * @param {string} full - full string that may have the unevaluated substring * @returns {boolean} - returns true if a substring is found in the ful string */ var isSubString = function(sub, full) { if (itypeof(sub) === 'string' && itypeof(full) === 'string') { if (full.toLowerCase().indexOf(sub.toLowerCase()) != -1) { return true; } } return false; }; /** * The following method checks if useTemplate value is true and * if the log arguments array length is two * @param {boolean} useTemplate - flag that configures the usage of the template engine * @param {*[]} args - list of log arguments that should match pattern creating template strings * @returns {boolean} - returns true if log arguments match template pattern and useTemplate is set to true */ var validateTemplateInputs = function(useTemplate, args) { return isBoolean(useTemplate) && useTemplate && args.length == 2; }; /** * supplant is a string templating engine that replaces patterns * in a string with values from a template object * @param {string} template - string with patterns to be replaced by values * @param {object} values - object with values to replace in template string * @param {RegExp=} pattern - custom regular expression of pattern to replace in template string * @returns {string} - returns formatted string if template and values match the required pattern */ var supplant = function(template, values, /*{RegExp=}*/ pattern) { var criteria1 = itypeof(template) !== 'string' && itypeof(values) !== 'object'; var criteria2 = itypeof(template) !== 'string' || itypeof(values) !== 'object'; if (criteria1 || criteria2) { return Array.prototype.slice.call(arguments); } pattern = itypeof(pattern) === 'regexp' ? pattern : /\{([^\{\}]*)\}/g; return template.replace(pattern, function(a, b) { var p = b.split('.'), r = values; try { for (var s in p) { r = r[p[s]]; } } catch (e) { r = a; } return (typeof r === 'string' || typeof r === 'number') ? r : a; }); }; /** * Checks if the current browser is a part of the supported browser list for adding colors * @returns {boolean} - returns true if the current browser supports colorify */ var isColorifySupported = function() { for (var i = 0; i < colorifySupportedBrowsers.length; i++) { if (isSubString(colorifySupportedBrowsers[i], userAgent)) { return true; } } return false; }; /** * Stores flag to know if current browser is colorify supported * @type {boolean} */ //TODO: Need to refactor this into a self-invoking function var isColorifySupportedBrowser = isColorifySupported(); /** * The following method checks if the log arguments array length is one and the element is a string * @param {*[]} args - unevaluated log method arguments array that should contain only one element of type {string} * @returns {boolean} - returns true if args match the above criteria */ var validateColorizeInputs = function(args) { return (args.length == 1 && itypeof(args[0]) === 'string'); }; /** * The following method does partial validation to ensure css string contains known keys * @param {string} css - css string to be evaluated * @returns {boolean} - returns true if string contains any supported keys */ var containsColorCssKeys = function(css) { return isSubString('color', css) || isSubString('background', css) || isSubString('border', css); }; /** * The following method does partial validation to ensure css string is valid * @param {string} value - css string to be evaluated * @returns {boolean} - returns true if string has css format */ var validateColorCssString = function(value) { return (itypeof(value) === 'string' && isSubString(':', value) && trimString(value).length > 6) && containsColorCssKeys(value); }; /** * The following takes a string a returns an array as parameter if browser is supported * e.g. Expected outcome $log.log('%c Oh my heavens! ', 'background: #222; color: #bada55'); * @param {string} message - string to be coloured * @param {string} colorCSS - css string to apply to message * @param {string} prefix - log prefix to be prepended to message * @returns {*[]} - returns colorify formatted array if all inputs are valid else returns array with the original message */ var colorify = function(message, colorCSS, prefix) { prefix = (itypeof(prefix) === 'string' ? prefix : ''); var canProcess = isColorifySupportedBrowser && validateColorCssString(colorCSS) && itypeof(message) === 'string'; var output = canProcess ? ('' + prefix + message) : message; return canProcess ? (["%c" + output, colorCSS]) : [output]; }; /** * This is the default method responsible for formatting the prefix of all extended $log messages pushed to the console * @see overrideLogPrefix to override the logPrefix * @param {string=} className - name of the component class ($controller, $service etc.) * @returns {string} - formatted string that will be prepended to log outputs */ var defaultLogPrefixFn = function( /**{String=}*/ className) { var separator = " >> ", format = "MMM-dd-yyyy-h:mm:ssa", now = $filter('date')(new Date(), format); return "" + now + ((itypeof(className) !== 'string') ? "" : "::" + className) + separator; }; /** * This method is responsible for generating the prefix of all extended $log messages pushed to the console * @param {string=} className - name of the component class ($controller, $service etc.) * @returns {string} - formatted string that will be prepended to log outputs */ var getLogPrefix = function( /**{String=}*/ className) { var prefix = ''; if ((!isBoolean(useDefaultPrefix) || !useDefaultPrefix) && isBoolean(logPrefixOverride) && logPrefixOverride && angular.isFunction(customLogPrefixFn)) { prefix = customLogPrefixFn(className); } else { prefix = defaultLogPrefixFn(className); } return prefix; }; // Register our $log decorator with AngularJS $provider //scroll down to the Configuration section to set the log settings $provide.decorator('$log', ["$delegate", function($delegate) { /** * Encapsulates functionality to extends $log and expose additional functionality **/ var logEnhancerObj = function() { /** * processUseOverride returns true if the override flag is set. * this is used to activate the override functionality. * @param {boolean} override - unevaluated override flag * @returns {boolean} - returns true if override is a boolean */ var processUseOverride = function(override) { return isBoolean(override); }; /** * processOverride only takes true or false as valid input. * any other input will resolve as true. * this function is used to override the global flag for displaying logs * @param {boolean} override - unevaluated override flag * @returns {boolean} - returns true if override is not equal to false */ var processOverride = function(override) { return override !== false; }; /** * The following method checks if the global enabled flag and the override flag are set as type {boolean} * variables. If both are set it returns the value of the override flag to control $log outputs * @param {boolean} enabled - global flag that activates/deactivates logging * @param {boolean} override - flag that overrides the global enabled flag * @returns {boolean} - returns override if both params are booleans else returns {boolean=} false */ var activateLogs = function(enabled, override) { if (isBoolean(enabled) && isBoolean(override)) { return override; } return false; }; /** * The following method handles printing a message to the console indicating * if a $log instance is using an override. * If logging is disabled globally & an override of true is set, * then a message will be displayed for the specific $log instance * if logging is enabled globally & an override of false is set, * then a message will be displayed for the specific $log instance * @private for internal use only * @param _$log - $log instance * @param useOverride - flag that defines logic to regard using the override * @param _override - flag that overrides the global enabled flag * @param className - name of the component class ($controller, $service etc.) * @param enabled - global flag that activates/deactivates logging */ var printOverrideLogs = function(_$log, useOverride, _override, className, enabled) { var instance = (isValidString(className)) ? className : "this instance"; if (!enabled && useOverride && _override) { _$log.log(getLogPrefix() + "[OVERRIDE] LOGGING ENABLED - $log enabled for " + instance); } else if (enabled && useOverride && !_override) { _$log.log(getLogPrefix() + "[OVERRIDE] LOGGING DISABLED - $log disabled for " + instance); } }; /** * Converts an array to a object literal * @private for internal use only * @param {*[]} arr - array to be transformed to object literal * @returns {{getInstance: (exports.packets.noop|*|container.noop|noop|)}} */ var arrToObject = function(arr) { var result = {}; if (angular.isArray(arr)) { result = { getInstance: angular.noop }; angular.forEach(arr, function(value) { result[value] = angular.noop; }); } return result; }; /** * General purpose method for building $log objects. * This method also provides the capability to specify the log methods to expose * @private for internal use only * @param {Object} oSrc - $log instance * @param {Array=} aMethods - list of $log methods * @param {Function=} func - function that defines rules for custom $log instance * @param {Array=} aParams - parameters to be used in prepareLogFn * @returns {Object} - returns a $log instance */ var createLogObj = function(oSrc, aMethods, /**{Function=}*/ func, /**{*Array=}*/ aParams) { var resultSet = {}, oMethods = arrToObject(aMethods); angular.forEach(defaultLogMethods, function(value) { var res; if (angular.isDefined(aParams)) { var params = []; angular.copy(aParams, params); params.unshift(oSrc[value]); if (isColorifySupportedBrowser && useDefaultColors) { params[5] = validateColorCssString(params[5]) ? params[5] : defaultLogMethodColors[value]; } res = func.apply(null, params); } else { res = oSrc[value]; } resultSet[value] = angular.isUndefined(oMethods[value]) ? angular.noop : res; }); return resultSet; }; /** * Contains functionality for transforming the AngularJS $log * returns extended $log object * @param $log {Object} - original angular $log to be enhanced **/ var enhanceLogger = function($log) { /** * Partial application to pre-capture a logger function * @param {Function} logFn - $log method * @param {*} className - name of the component class ($controller, $service etc.) * @param {boolean} override - flag that overrides the global enable flag * @param {boolean} useOverride - flag that defines logic to consider using the override * @param {string} colorCss - css styles for coloring log methods * @param {boolean} useTemplate - enables/disables the template engine * @returns {Function} - returns function with specific rules for a log metod */ var prepareLogFn = function(logFn, className, override, useOverride, useTemplate, colorCss) { var enhancedLogFn = function() { var activate = (useOverride) ? activateLogs(enabled, override) : enabled; if (activate) { var args = Array.prototype.slice.call(arguments); var prefix = getLogPrefix(className); if (validateTemplateInputs(useTemplate, args)) { var data = (supplant.apply(null, args)); data = (itypeof(data) === 'string') ? [data] : data; args = data; } if (itypeof(colorCss) === 'string' && validateColorizeInputs(args)) { args = colorify(args[0], colorCss, prefix); } else { args.unshift(prefix); } if (logFn) logFn.apply(null, args); } }; // Only needed to support angular-mocks expectations enhancedLogFn.logs = []; return enhancedLogFn; }; /** * Capture the original $log functions; for use in enhancedLogFn() * @type {*} * @private */ var _$log = createLogObj($log, allowedMethods); /** * Support to generate class-specific logger instance with/without className or override * @param {*} className - Name of object in which $log.<function> calls is invoked. * @param {boolean=} override - activates/deactivates component level logging * @param {boolean=} useTemplate - enables/disables the template engine * @param {String=} colorCss - css styles for coloring log methods * @returns {*} $log instance - returns a custom log instance */ var getInstance = function( /*{*=}*/ className, /*{boolean=}*/ override, /*{boolean=}*/ useTemplate, /*{String=}*/ colorCss) { if (isBoolean(className)) { override = className; className = null; } else if (itypeof(className) === 'string') { className = trimString(className); } else { className = null; } var useOverride = processUseOverride(override); override = processOverride(override); printOverrideLogs(_$log, useOverride, override, className, enabled); return createLogObj(_$log, allowedMethods, prepareLogFn, [className, override, useOverride, useTemplate, colorCss]); }; //declarations and functions , extensions /** * Used to enable/disable logging * @type {boolean} */ var enabled = false; /** * Extends the $log object with the transformed native methods * @param $log - $log instance * @param {function} createLogObj - defines transformation rules **/ angular.extend($log, createLogObj($log, allowedMethods, prepareLogFn, [null, false, false, false, null])); /** * Extend the $log with the {@see getInstance} method * @type {getInstance} */ $log.getInstance = getInstance; /** * The following method enable/disable logging globally * @param {boolean} flag - boolean flag specifying if log should be enabled/disabled */ $log.enableLog = function(flag) { enabled = flag; }; /** * The following returns the status of the {@see enabled} * @returns {boolean} - returns global enabled flag */ $log.logEnabled = function() { return enabled; }; return $log; }; //---------------------------------------// /** * The following function exposes the $decorated logger to allow the defaults to be overridden * @param $log - $log instance * @returns {*} - returns $log instance fitted for external configurations and regular use */ var exposeSafeLog = function($log) { return createLogObj($log, allowedMethods); }; // add public methods to logEnhancerObj this.enhanceLogger = enhanceLogger; this.exposeSafeLog = exposeSafeLog; }; //=======================================================================// // Configuration Section //=======================================================================// var logEnhancer = new logEnhancerObj(); logEnhancer.enhanceLogger($delegate); // ensure false is being passed for production deployments // set to true for local development $delegate.enableLog(enableGlobally); if ($delegate.logEnabled()) { $delegate.log("CONFIG: LOGGING ENABLED GLOBALLY"); } return logEnhancer.exposeSafeLog($delegate); } ]); // Provider functions that will be exposed to allow overriding of default $logProvider functionality /** * Used externally to enable/disable logging globally * @param {boolean} flag - flag that sets whether logging is enabled/disabled */ var enableLogging = function(flag) { enableGlobally = isBoolean(flag) ? flag : false; }; /** * Configure which log functions can be exposed at runtime * @param {*[]} arrMethods - list of methods that can be used */ var restrictLogMethods = function(arrMethods) { if (angular.isArray(arrMethods)) { // TODO: should do validation on this to ensure valid properties are passed in allowedMethods = arrMethods; } }; /** * Modify the default log prefix * @param {Function} logPrefix - function that defines the rule for a custom log prefix */ var overrideLogPrefix = function(logPrefix) { if (angular.isFunction(logPrefix)) { // TODO : Validation of the function to ensure it's of the correct format etc customLogPrefixFn = logPrefix; logPrefixOverride = true; } }; /** * Turns off default coloring of logs * @param {boolean} flag - flag that configures disabling default log colors */ var disableDefaultColors = function(flag) { useDefaultColors = (isBoolean(flag) && flag) ? false : true; }; /** * Used to set a custom color to a specific $log method * @param {String} methodName - method name of the log method to assign a custom color * @param {String} colorCss - css string that defines what colour to be set for the specified log method */ var setLogMethodColor = function(methodName, colorCss) { if (itypeof(methodName) === 'string' && defaultLogMethodColors.hasOwnProperty(methodName) && validateColorCssString(colorCss)) { defaultLogMethodColors[methodName] = colorCss; } }; /** * Used to set custom colors to multiple $log method * @param {object} overrides - object that defines log method color overrides */ var overrideLogMethodColors = function(overrides) { if (itypeof(overrides) === 'object') { angular.forEach(overrides, function(colorCss, method) { setLogMethodColor(method, colorCss); }); } }; /** * Used to force default log prefix functionality * @param {boolean} flag - when passed true, it forces log-ex to use the default log prefix */ var useDefaultLogPrefix = function(flag) { if (isBoolean(flag)) { useDefaultPrefix = flag; } }; /** * Default $get method necessary for provider to work * @type {Function} */ this.$get = function() { return { name: 'Log Unobtrusive Extension', version: '0.0.7', enableLogging: enableLogging, restrictLogMethods: restrictLogMethods, overrideLogPrefix: overrideLogPrefix, disableDefaultColors: disableDefaultColors, setLogMethodColor: setLogMethodColor, overrideLogMethodColors: overrideLogMethodColors, useDefaultLogPrefix: useDefaultLogPrefix }; }; // add methods to $provider this.enableLogging = enableLogging; this.overrideLogPrefix = overrideLogPrefix; this.restrictLogMethods = restrictLogMethods; this.disableDefaultColors = disableDefaultColors; this.setLogMethodColor = setLogMethodColor; this.overrideLogMethodColors = overrideLogMethodColors; this.useDefaultLogPrefix = useDefaultLogPrefix; } ]);
lwhiteley/angular-fullstack-custom
app/components/bower_components/angular-logex/dist/log-ex-unobtrusive.js
JavaScript
mit
30,435
'use strict'; var express = require('express'); var mongoose = require('mongoose'); var passport = require('passport'); var passportStrat = require('./lib/passport_strat'); var userRoutes = require('./routes/user_routes'); var characterRoutes = require('./routes/character_routes'); var app = express(); var port = process.env.PORT || 3000; app.use(express.static(__dirname + '/build')); mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/jsgame_dev'); // Security init app.set('appSecret', process.env.SECRET || 'loot!loot!loot!loot!'); app.use(passport.initialize()); passportStrat(passport); // Routes var userRouter = express.Router(); var characterRouter = express.Router(); userRoutes(userRouter, passport, app.get('appSecret')); characterRoutes(characterRouter, passport, app.get('appSecret')); app.use('/api/v1', userRouter); app.use('/api/v1', characterRouter); // Server init app.listen(port, function() { console.log('Server listening on port ' + port + '.'); }); // ------------------- // add socket io // ------------------- ////var app = require('express')(); // leave commented out // var http = require('http').Server(app); // var io = require('socket.io')(http); // io.on('connection', function(socket){ // console.log('a user connected'); // socket.on('char stats', function(msg){ // console.log('message: ' + msg); // io.emit('char stats2', "via the server " + msg); // }); // }); // http.listen(2999, function(){ // console.log('listening on *:2999'); // }); // -----end of add socket io --------------
cf-js-game/wagoge
server.js
JavaScript
mit
1,571
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const user_1 = require("./../../models/user"); const role_1 = require("./../../models/role"); exports.listRoles = (req, res, next) => tslib_1.__awaiter(this, void 0, void 0, function* () { try { const roles = yield role_1.default.query().eager('users').omit(user_1.default, ['password']); return res.send(roles); } catch (error) { return next(error); } }); function getRole(req, res, next) { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { const role = yield role_1.default.query().findById(req.params.id); return res.send(role); } catch (error) { return next(error); } }); } exports.getRole = getRole; function getRoleUsers(req, res, next) { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { const role = yield role_1.default.query() .findById(req.params.id) .eager('users') .omit(user_1.default, ['password']); return res.send(role); } catch (error) { return next(error); } }); } exports.getRoleUsers = getRoleUsers; //# sourceMappingURL=role.controller.js.map
thoughtbit/node-web-starter
bear-ts-express/build/server/src/routes/role/role.controller.js
JavaScript
mit
1,351
var mongoose = require('mongoose'); var instructorSchema = new mongoose.Schema({ name: { type: String, required: true}, location: String, skills: String, email: String, profit:String }); var Instructorlist = mongoose.model('instructorlist', instructorSchema); module.exports = Instructorlist;
Schedulizer/kellie_app
models/inst_to_sel.js
JavaScript
mit
343
/*************************************************************************************/ /* @copyright Original work Copyright (c) 2014 Djordje Ungar */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining a copy */ /* of this software and associated documentation files (the "Software"), to deal */ /* in the Software without restriction, including without limitation the rights */ /* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */ /* copies of the Software, and to permit persons to whom the Software is */ /* furnished to do so, subject to the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be included in */ /* all copies or substantial portions of the Software. */ /* */ /* @author Djordje Ungar (djordje@ungar.rs) */ /* @source https://github.com/ArtBIT/PluginManager.js */ /*************************************************************************************/ (function(window) { /** * Plugin is basically a sub-application. Adding a plugin to a * PluginManager allows it to communicate with other plugins that * belong to that manager. */ function Plugin() { this.init = function () { return; }; this.addedTo = function (manager) { this.manager = manager; this.init(); }; } /** * PluginManager is a container for plugins. It has a simple * built-in pub-sub functionality that allows the plugins to * communicate with one another. */ function PluginManager() { this.plugins = []; this.listeners = {}; this.history = {}; } PluginManager.prototype = { /** * Register the plugin with the manager. */ add: function (plugin) { if (!(plugin instanceof Plugin)) { throw new Error("Must be instance of Plugin"); } plugin.addedTo(this); this.plugins.push(plugin); return this; }, /** * Remove the specified plugin from the manager. */ remove: function (plugin) { if (!(plugin instanceof Plugin)) { throw new Error("Must be instance of Plugin"); } var i = this.plugins.length; while (i--) { if (plugin === this.plugins[i]) { this.plugins.splice(i, 1); break; } } return this; }, /** * Bind a callback to an event */ on: function (eventType, callback) { if (!(eventType && callback && typeof callback === 'function')) { return; } this.listeners[eventType] = this.listeners[eventType] || []; this.listeners[eventType].push(callback); return this; }, /** * Unbind the callback from the event */ off: function (eventType, callback) { var targets = this.listeners[eventType] || []; var i = targets.length; while (i--) { if (targets[i] === callback) { targets.splice(i, 1); } } return this; }, /** * Trigger a specific event */ trigger: function (eventType) { var args = Array.prototype.slice.call(arguments, 1), targets = this.listeners[eventType] || [], i = 0; this.record(eventType, args); for (i = 0; i < targets.length; i++) { if (typeof targets[i] === 'function') { targets[i].apply(targets[i], args); } } return this; }, /** * Record the event to the history so that it can be played back * to the late bound plugins */ record: function (eventType, args) { if (!this.history.hasOwnProperty(eventType)) { this.history[eventType] = []; } this.history[eventType].push(args); }, /** * Replay the history to this particular callback */ replay: function (eventType, callback) { var i, len, args; if (Object.prototype.toString.call(eventType) === '[object Array]') { for (i = 0, len = eventType.length; i < len; i++) { this.replay(eventType[i], callback); } return; } if (this.history.hasOwnProperty(eventType)) { for (i = 0, len = this.history[eventType].length; i < len; i++) { args = this.history[eventType][i]; args.unshift(eventType); callback.apply(callback, args); } } } }; window.Plugin = Plugin; window.PluginManager = PluginManager; })(window);
ArtBIT/PluginManager.js
src/js/pluginmanager.js
JavaScript
mit
5,508
module.exports = { appName: 'App Name', apiUrl: 'http://localhost:5000/', traktKey: '308c2f00192ab0a459d3e9056d715387d388105d9a485d66915a3f358dd809cd', fanartKey: 'b8ee1a96cf8e3037da593aa0593f682d', pageLimit: 18, holder: 'https://raw.githubusercontent.com/butterproject/butter-desktop/master/src/app/images/posterholder.png' };
SCThijsse/angularjs-single-page
app/config/app.constants.js
JavaScript
mit
341
class ehome_mcxasyncremoteplayer { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = ehome_mcxasyncremoteplayer;
mrpapercut/wscript
testfiles/COMobjects/JSclasses/eHome.McxAsyncRemotePlayer.js
JavaScript
mit
589
"use strict"; var nconf = require("nconf").argv().env(); var kue = require('kue'); // Create Kue connection var jobs = kue.createQueue({ prefix: nconf.get("KUE_PREFIX"), redis: { port: nconf.get("REDIS_PORT_6379_TCP_PORT"), host: nconf.get("REDIS_PORT_6379_TCP_ADDR"), db: nconf.get("REDIS_DATABASE") } }); var jobType = nconf.get("job"); var data = {}; if (nconf.get("idFile")) { data.idFile = nconf.get("idFile") } if (nconf.get("mimeType")) { data.mimeType = nconf.get("mimeType") } console.log(jobType, data); var job = jobs .create(jobType, data) .save( function(err){ if( !err ) console.log( "Job soumis : "+job.id ); }); job.on('complete', function(result){ console.log("Result du job: "+result); process.exit(); }); job.on('failed', function(){ console.log("Job failed"); process.exit(); });
rednetio/docker-kue-debugger
launcher.js
JavaScript
mit
847
//main functions for apps (redirect, cookies handling, tab handling) (function($) { /* *FIXME : NOTHING TO DO HERE!! need this hackto do this because $.cookie not working here ?? */ function readCookie(sName) { var cookContent = document.cookie, cookEnd, i, j; var sName = sName + "="; for (i=0, c=cookContent.length; i<c; i++) { j = i + sName.length; if (cookContent.substring(i, j) == sName) { cookEnd = cookContent.indexOf(";", j); if (cookEnd == -1) { cookEnd = cookContent.length; } return decodeURIComponent(cookContent.substring(j, cookEnd)); } } return null; } // Function that handle session expiration with redirect $.fn.dynamicForm = function (options) { options = $.extend({ itemsCount: 0, modelSelector: null, subClasses: [], label: 'Item #', advancedLayout: true, hasTinyMCE: false, tableMode: false, labels: null, bind: null },options); var self = this; if( options.modelSelector == null ) { console.log('Error you must have a modelSelector option'); return; } // Initialize the widget // 1- Add the button bar var btnBarHtml = '<div class="clearfix panel-box-navigation fileupload-buttonbar" style="padding-top:3px;">'; btnBarHtml += '<div class="span btn-bar">'; btnBarHtml += '<button class="btn btn-xs btn-success add">'; btnBarHtml += '<i class="icon-plus icon-white"></i><span>Add</span></button>'; btnBarHtml += '<button class="btn btn-xs btn-warning clear"><i class="icon-ban-circle icon-white"></i><span>Clear</span></button>'; btnBarHtml += '</div></div>'; var container = ""; if(options.tableMode == false) { container = '<div class="form-data"></div>'; } else { if( options.labels == null ) { console.log('Error you must have a column labels option for tableMode'); return; } container = '<div class="form-data"><table class="table table-stripped"><thead><tr>'; $.each(options.labels,function(index,label){ container += '<th>' + label + '</th>'; }); container += '<th></th></tr></thead><tbody class="form-data-body"></tbody></table></div>'; } $(self).append(btnBarHtml); $(self).append(container); /* edit mode if we have data in collections.. */ if($('.collection-data',$(self)) != "undefined") { if(options.tableMode == false) { $('.form-data',$(self)).append($('.collection-data',$(self)).attr('data-values')); } else { $('.form-data-body',$(self)).append($('.collection-data',$(self)).attr('data-values')); } $('.collection-data',$(self)).remove(); } $('.add',$(self)).click(function(e) { e.preventDefault(); e.stopPropagation(); add(); if(options.bind != null) eval(options.bind+'(this)'); return false; }); $('.clear',$(self)).click(function(e) { e.preventDefault(); e.stopPropagation(); clear(); if(options.bind != null) eval(options.bind+'(this)'); return false; }); function clear() { if( confirm('Are you sure ?') ) { if( options.tableMode == false ) { $('.form-data',$(self)).html(''); } else { $('.form-data-body',$(self)).html(''); } options.itemsCount = 0; } } $(self).on('click', '.delete-row', function(e) { e.preventDefault(); e.stopPropagation(); if( confirm('Are you sure ?') ) { $(this).parents('tr').remove(); } return false; }); function add() { var html = ""; if( options.tableMode == false ) { html = '<div class="delete-item' + options.itemsCount + '">'; if( options.advancedLayout ) html += '<h6>' + options.label + options.itemsCount + '</h6><div class="well">'; $.each(options.subClasses,function(index,value) { var elem = $('.' + value, $(options.modelSelector) ).attr("data-prototype"); elem = elem.replace(/__name__/g, options.itemsCount); html += elem; }); if( options.advancedLayout ) html += '</div>'; html += '</div>'; $('.form-data',$(self)).append(html); } else { html += '<tr>'; $.each(options.subClasses,function(index,value) { var elem = $('.' + value, $(options.modelSelector) ).attr("data-prototype"); elem = elem.replace(/__name__/g, options.itemsCount); html += '<td>' + elem + '</td>'; }); html += '<td><i class="delete-row cursor-pointer icon icon-trash"></i></td></tr>'; $('.form-data-body',$(self)).append(html); } if( options.hasTinyMCE ) tinyMCE.init(mceOptions); options.itemsCount++; } }; })(jQuery);
UCSLabs/UCSRichUIBundle
Resources/public/js/ucs/jquery.ucs.dynamicForm.js
JavaScript
mit
4,878
/** * DocuSign REST API * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient', 'oauth/Account'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./Account')); } else { // Browser globals (root is window) if (!root.Docusign) { root.Docusign = {}; } } }(this, function(ApiClient, Account) { 'use strict'; /** * The UserInfo model module. * @module model/UserInfo * @version 3.0.0 */ /** * Constructs a new <code>UserInfo</code>. * @alias module:model/UserInfo * @class */ var exports = function() { var _this = this; }; /** * Constructs a <code>UserInfo</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/UserInfo} obj Optional instance to populate. * @return {module:model/UserInfo} The populated <code>UserInfo</code> instance. */ exports.constructFromObject = function(data, obj) { var ApiClient = require('../ApiClient'); if (data) { obj = obj || new exports(); if (data.hasOwnProperty('sub')) { obj['sub'] = ApiClient.convertToType(data['sub'], 'String'); } if (data.hasOwnProperty('email')) { obj['email'] = ApiClient.convertToType(data['email'], 'String'); } if (data.hasOwnProperty('accounts')) { obj['accounts'] = ApiClient.convertToType(data['accounts'], [Account]); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('given_name')) { obj['givenName'] = ApiClient.convertToType(data['given_name'], 'String'); } if (data.hasOwnProperty('family_name')) { obj['familyName'] = ApiClient.convertToType(data['family_name'], 'String'); } if (data.hasOwnProperty('created')) { obj['created'] = ApiClient.convertToType(data['created'], 'String'); } } return obj; } /** * * @member {String} sub */ exports.prototype['sub'] = undefined; /** * * @member {String} email */ exports.prototype['email'] = undefined; /** * @member {module:oauth/Account} accounts */ exports.prototype['accounts'] = undefined; /** * * @member {String} name */ exports.prototype['name'] = undefined; /** * * @member {String} givenName */ exports.prototype['givenName'] = undefined; /** * * @member {String} familyName */ exports.prototype['familyName'] = undefined; /** * * @member {String} created */ exports.prototype['created'] = undefined; return exports; }));
docusign/docusign-node-client
src/oauth/UserInfo.js
JavaScript
mit
3,366
define({ "_widgetLabel": "Розумний редактор", "_featureAction_SmartEditor": "Розумний редактор", "noEditPrivileges": "Ваш обліковий запис не має дозволу створювати або змінювати дані.", "widgetActive": "Активний", "widgetNotActive": "Не активний", "pressStr": "Натиснути ", "ctrlStr": " CTRL ", "snapStr": " для активації замикання", "noAvailableTempaltes": "Немає доступних шаблонів", "editorCache": " - Кеш-пам’ять редактора", "presetFieldAlias": "Поле", "presetValue": "Значення за замовчуванням", "usePresetValues": " Використовувати значення за замовчуванням (тільки нові об'єкти)", "editGeometry": " Редагувати геометрію", "savePromptTitle": "Зберегти об'єкт", "savePrompt": "Бажаєте зберегти поточний об'єкт?", "deletePromptTitle": "Видалити об'єкт", "deleteAttachment": "Видалити прикріплення", "deletePrompt": "Бажаєте видалити вибраний об'єкт?", "attachmentLoadingError": "Помилка при завантаження прикріплень", "attachmentSaveDeleteWarning": "Попередження: зміни до прикріплень зберігаються автоматично", "autoSaveEdits": "Автоматично зберігає новий об'єкт", "addNewFeature": "Створити новий об'єкт", "featureCreationFailedMsg": "Неможливо створити новий запис/об'єкт", "relatedItemTitle": "Пов’язана таблиця/шар", "relatedFeatureCount": "${layerTitle} з ${featureCount} об’єктів", "createNewFeatureLabel": "Створити новий об’єкт для ${layerTitle}", "invalidRelationShipMsg": "Переконайтесь, що поле первинного ключа: '${parentKeyField}' містить дійсне значення", "pendingFeatureSaveMsg": "Збережіть редагування об'єкту перш ніж створювати пов’язаний об'єкт.", "attachmentsRequiredMsg": "(*) Потрібні прикріплення.", "coordinatePopupTitle": "Перемістити об'єкт у місце розташування XY", "coordinatesSelectTitle": "Система координат:", "mapSpecialReferenceDropdownOption": "Просторова прив'язка карти", "latLongDropdownOption": "Широта/довгота", "xAttributeTextBoxLabel": "X-координата:", "yAttributeTextBoxLabel": "Y-координата:", "latitudeTextBoxLabel": "Широта:", "longitudeTextBoxLabel": "Довгота:", "presetGroupFieldsLabel": "'${groupName}' буде застосовано до наступних полів шару:", "presetGroupNoFieldsLabel": "'${groupName}' не має жодних пов’язаних полів", "groupInfoLabel": "Відомості про групу для '${groupName}'", "editGroupInfoIcon": "Редагувати значення групи для ${groupName}", "filterEditor": { "all": "Всі", "noAvailableTempaltes": "Немає доступних шаблонів", "searchTemplates": "Пошук шаблонів", "filterLayerLabel": "Фільтрувати шари" }, "invalidConfiguration": "Віджет не налаштовано або шари у конфігурації більше не присутні у карті. Відкрийте додаток у режимі розробника та повторно налаштуйте віджет.", "geometryServiceURLNotFoundMSG": "Неможливо отримати URL сервісу геометрії", "clearSelection": "Очистити", "refreshAttributes": "Оновити атрибути об'єкту", "automaticAttributeUpdatesOn": "Автоматичне оновлення атрибутів об'єкту: УВІМКН.", "automaticAttributeUpdatesOff": "Автоматичне оновлення атрибутів об'єкту: ВИМКН.", "moveSelectedFeatureToGPS": "Перемістити вибраний об'єкт у поточне місце розташування GPS", "moveSelectedFeatureToXY": "Перемістити вибраний об'єкт у місце розташування XY", "mapNavigationLocked": "Навігація по карті: заблоковано", "mapNavigationUnLocked": "Навігація по карті: розблоковано", "copyFeatures": { "title": "Копіювати об'єкти", "createFeatures": "Створити об'єкти", "createSingleFeature": "Створити 1 мультигеометричний об'єкт", "noFeaturesSelectedMessage": "Об'єкти не вибрано", "selectFeatureToCopyMessage": "Виберіть об'єкти для копіювання.", "multipleFeatureSaveWarning": "Примітка: При створенні кількох об’єктів шляхом копіювання об’єкту всі об’єкти будуть одразу збережені" }, "addingFeatureError": "Помилка під час додавання вибраних об'єктів в шарі. Спробуйте знову.", "addingFeatureErrorCount": "Не вдалося копіювати '${copyFeatureErrorCount}' об'єктів.", "selectingFeatureError": "Помилка під час вибору об'єктів в шарі. Спробуйте знову.", "customSelectOptionLabel": "Виберіть об'єкти для копіювання", "noFeatureSelectedMessage": "Об'єкти не вибрано.", "multipleFeatureSaveMessage": "Всі об'єкти будуть зразу збережені. Бажаєте продовжити?", "relativeDates": { "dateTypeLabel": "Тип дати", "valueLabel": "Значення", "fixed": "Фіксований", "current": "Поточний", "past": "Попереднє", "future": "Майбутнє", "popupTitle": "Вибрати значення", "hintForFixedDateType": "Підказка: Указані дата і час будуть використані як попередньо задані значення за замовчуванням.", "hintForCurrentDateType": "Підказка: Поточні дата і час будуть використані як попередньо задані значення за замовчуванням.", "hintForPastDateType": "Підказка: Попередньо задане значення за замовчуванням отримується відніманням указаного значення від поточних дати й часу.", "hintForFutureDateType": "Підказка: Попередньо задане значення за замовчуванням отримується додаванням указаного значення до поточних дати й часу.", "noDateDefinedTooltip": "Дані не визначені", "relativeDateWarning": "Для збереження заданого значення за замовчуванням повинне бути задане значення дати або часу." } });
tmcgee/cmv-wab-widgets
wab/2.15/widgets/SmartEditor/nls/uk/strings.js
JavaScript
mit
7,617
/** * Created by wyf on 2017/4/20. */ import { SET_RUNTIME_VARIABLE } from '../constants'; export function setRuntimeVariable({ name, value }) { return { type: SET_RUNTIME_VARIABLE, payload: { name, value, }, }; }
yvanwangl/UniversalBlog
src/actions/index.js
JavaScript
mit
230
'use strict'; import style from './chessboard.css'; var ChessBoard = function(boardId, config) { var self = this; var options = { fen: 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR', resize: true, orientation: 'w', minSquareSize: 20, maxSquareSize: 64 }; for (var key in config) { options[key] = config[key]; } var boardBorderWidth, squareSize, boardWidthFix, selectedSquares = []; var board = {}; var promotion = { pieces: [], selectedElement: null }; function calcSquare(row, column) { return String.fromCharCode(97 + column) + row; } function createBoard() { var boardElement = document.getElementById(boardId); boardElement.classList.add('chessboard'); if (options.orientation === 'b') { boardElement.classList.add('flipped'); } board.element = boardElement; for (var r = 8; r >= 1; r--) { var rowElement = document.createElement('div'); board[r] = { element: rowElement }; for (var c = 0; c < 8; c++) { var squareElement = document.createElement('div'); if ((r + c) % 2 === 0) { squareElement.className = 'white square'; } else { squareElement.className = 'black square'; } squareElement.setAttribute('data-square', calcSquare(r, c)); if (options.onSquareClick) { squareElement.addEventListener('click', onSquareClick); } board[r][c] = { element: squareElement, piece: null }; rowElement.appendChild(squareElement); } boardElement.appendChild(rowElement); } } function createPromotionPiece(piece) { var pieceElement = document.createElement('div'); pieceElement.className = 'square ' + piece; pieceElement.setAttribute('data-piece', piece); promotion.pieces.push({ piece: piece, element: pieceElement }); return pieceElement; } function createPromotionPieces(color) { var piecesWrapper = document.createElement('div'); piecesWrapper.className = 'pieces'; piecesWrapper.appendChild(createPromotionPiece(color + 'Q')); piecesWrapper.appendChild(createPromotionPiece(color + 'R')); piecesWrapper.appendChild(createPromotionPiece(color + 'N')); piecesWrapper.appendChild(createPromotionPiece(color + 'B')); if (color === 'w') { promotion.whitePiecesWrapper = piecesWrapper; } else { promotion.blackPiecesWrapper = piecesWrapper; } } function createPromotion() { // Pieces createPromotionPieces('w'); createPromotionPieces('b'); // Promote button var promoteButton = document.createElement('button'); var promoteButtonText = document.createTextNode('Promote'); promoteButton.appendChild(promoteButtonText); promotion.promoteButton = promoteButton; var promoteButtonWrapper = document.createElement('div'); promoteButtonWrapper.appendChild(promoteButton); promotion.promoteButtonWrapper = promoteButtonWrapper; // Promotion wrapper var promotionWrapper = document.createElement('div'); promotionWrapper.className = 'promotion-wrapper'; promotionWrapper.appendChild(promotion.whitePiecesWrapper); promotionWrapper.appendChild(promotion.blackPiecesWrapper); promotionWrapper.appendChild(promoteButtonWrapper); promotion.wrapper = promotionWrapper; // Promotion overlay var overlay = document.createElement('div'); overlay.className = 'promotion-overlay'; promotion.overlay = overlay; overlay.appendChild(promotionWrapper); board.element.appendChild(overlay); // Set click handlers for (var i = 0, len = promotion.pieces.length; i < len; i++) { promotion.pieces[i].element.addEventListener('click', onPromotionPieceClick); } promoteButton.addEventListener('click', onPromotionButtonClick); } function onPromotionPieceClick(event) { var clickedElement = event.target; // Selected piece clicked if (clickedElement === promotion.selectedElement) { return; } // First time piece is selected if (promotion.selectedElement === null) { promotion.selectedElement = clickedElement; clickedElement.classList.add('selected'); promotion.promoteButton.disabled = false; return; } // Selecting another piece promotion.selectedElement.classList.remove('selected'); promotion.selectedElement = clickedElement; clickedElement.classList.add('selected'); } function onPromotionButtonClick() { var piece = promotion.selectedElement.getAttribute('data-piece'); var shortPiece = String.fromCharCode(piece.charCodeAt(1) + 32); promotion.overlay.style.display = 'none'; if (promotion.callback) { promotion.callback(shortPiece); } } function calcSquareSize() { var parentStyle = getComputedStyle(board.element.parentNode); var parentWidth = parseInt(parentStyle.width) - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight); squareSize = Math.floor((parentWidth - 2 * boardBorderWidth) / 8); squareSize = Math.min(squareSize, options.maxSquareSize); squareSize = Math.max(squareSize, options.minSquareSize); } function setBoardSize() { calcSquareSize(); var squareSizePx = squareSize + 'px'; var rowWidthPx = (8 * squareSize) + 'px'; var backgroundSizePx = (6 * squareSize) + 'px'; // Update board elements board.element.style.width = (8 * squareSize) + boardWidthFix + 'px'; for (var r = 8; r >= 1; r--) { board[r].element.style.width = rowWidthPx; board[r].element.style.height = squareSizePx; for (var c = 0; c < 8; c++) { board[r][c].element.style.width = squareSizePx; board[r][c].element.style.height = squareSizePx; board[r][c].element.style.backgroundSize = backgroundSizePx; board[r][c].element.style.backgroundPosition = backgroundPosition(board[r][c].piece); } } // Update promotion elements promotion.wrapper.style.width = (4 * squareSize) + 'px'; promotion.wrapper.style.height = (2 * squareSize) + 'px'; promotion.wrapper.style.marginTop = (3 * squareSize) + 'px'; promotion.whitePiecesWrapper.style.height = squareSizePx; promotion.blackPiecesWrapper.style.height = squareSizePx; for (var i = 0, len = promotion.pieces.length; i < len; i++) { var piece = promotion.pieces[i].piece; var element = promotion.pieces[i].element; element.style.width = squareSizePx; element.style.height = squareSizePx; element.style.backgroundSize = backgroundSizePx; element.style.backgroundPosition = backgroundPosition(piece); } promotion.promoteButtonWrapper.style.height = squareSizePx; promotion.promoteButtonWrapper.style.lineHeight = squareSizePx; promotion.promoteButton.style.fontSize = squareSize / 2.5 + 'px'; } function backgroundPosition(piece) { switch (piece) { case 'wP': return '0 0'; case 'wB': return -1 * squareSize + 'px 0'; case 'wN': return -2 * squareSize + 'px 0'; case 'wR': return -3 * squareSize + 'px 0'; case 'wQ': return -4 * squareSize + 'px 0'; case 'wK': return -5 * squareSize + 'px 0'; case 'bP': return '0 ' + -1 * squareSize + 'px'; case 'bB': return -1 * squareSize + 'px ' + -1 * squareSize + 'px'; case 'bN': return -2 * squareSize + 'px ' + -1 * squareSize + 'px'; case 'bR': return -3 * squareSize + 'px ' + -1 * squareSize + 'px'; case 'bQ': return -4 * squareSize + 'px ' + -1 * squareSize + 'px'; case 'bK': return -5 * squareSize + 'px ' + -1 * squareSize + 'px'; } } function getBoardSquare(square) { var c = square[0].charCodeAt(0) - 97; var r = +square[1]; return board[r][c]; } this.selectSquare = function(square) { if (selectedSquares.indexOf(square) > -1) { return; } var boardSquare = getBoardSquare(square); boardSquare.element.classList.add('selected'); selectedSquares.push(square); }; this.unselectSquare = function(square) { var index = selectedSquares.indexOf(square); if (index === -1) { return; } var boardSquare = getBoardSquare(square); boardSquare.element.classList.remove('selected'); selectedSquares.splice(index, 1); }; this.unselectAllSquares = function() { for (var i = 0, len = selectedSquares.length; i < len; i++) { var boardSquare = getBoardSquare(selectedSquares[i]); boardSquare.element.classList.remove('selected'); } selectedSquares = []; }; function onSquareClick(event) { var clickedSquare = event.target.getAttribute('data-square'); options.onSquareClick(clickedSquare, selectedSquares); } function clearSquare(square) { var boardSquare = getBoardSquare(square); var piece = boardSquare.piece; if (piece !== null) { boardSquare.element.classList.remove(piece); } boardSquare.piece = null; } function repeatChar(char, count) { for (var result = ''; result.length < count;) { result += char; } return result; } function putPiece(square, piece) { var boardSquare = getBoardSquare(square); var currentPiece = boardSquare.piece; if (currentPiece !== null) { boardSquare.element.classList.remove(currentPiece); } boardSquare.element.classList.add(piece); boardSquare.element.style.backgroundPosition = backgroundPosition(piece); boardSquare.piece = piece; } function calcPieceFromFenPiece(fenPiece) { var fenPieceCharCode = fenPiece.charCodeAt(0); if (fenPieceCharCode >= 97) { // Black return 'b' + String.fromCharCode(fenPieceCharCode - 32); } else { // White return 'w' + fenPiece; } } this.setPosition = function(fen) { var fenFields = fen.split(' '); var rows = fenFields[0].split('/'); for (var r = 0; r < 8; r++) { rows[r] = rows[r].replace(/\d/g, function(number) { return repeatChar('.', +number); }); for (var c = 0; c < 8; c++) { var square = calcSquare(8 - r, c); if (rows[r][c] === '.') { clearSquare(square); } else { putPiece(square, calcPieceFromFenPiece(rows[r][c])); } } } }; this.askPromotion = function(color, callback) { promotion.callback = callback; promotion.whitePiecesWrapper.style.display = (color === 'w' ? 'block' : 'none'); promotion.blackPiecesWrapper.style.display = (color === 'b' ? 'block' : 'none'); promotion.promoteButton.disabled = true; if (promotion.selectedElement !== null) { promotion.selectedElement.classList.remove('selected'); } promotion.selectedElement = null; promotion.overlay.style.display = 'block'; }; createBoard(); createPromotion(); setTimeout(function() { // Without setTimeout, boxSizing is not set yet. var boardStyle = getComputedStyle(board.element); // Assumption: all 4 borders have the same width boardBorderWidth = parseInt(boardStyle.borderTopWidth); if (boardStyle.boxSizing === 'border-box') { boardWidthFix = 2 * boardBorderWidth; } else { boardWidthFix = 0; } setBoardSize(); self.setPosition(options.fen); }); if (options.resize) { window.addEventListener('resize', setBoardSize); } }; export default ChessBoard;
abhineet97/webrtc-chess
app/lib/chessboard/chessboard.js
JavaScript
mit
11,523
(function(window) { 'use strict'; var App = window.App || {}; function Cart(cartId, db) { this.cartId = cartId; this.db = db; } Cart.prototype.createOrder = function (order) { console.log('Adding order for ' + order.emailAddress); return this.db.add(order.emailAddress, order); } Cart.prototype.deliverOrder = function (customerId) { console.log('Delivering order for ' + customerId); return this.db.remove(customerId); } Cart.prototype.printOrders = function (printFn) { return this.db.getAll() .then(function (orders) { var customerIdArray = Object.keys(orders); console.log(this.cartId + ' has pending orders:'); customerIdArray.forEach(function (id) { console.log(orders[id]); if (printFn) { printFn(orders[id]); } }.bind(this)); }.bind(this)); }; App.Cart = Cart; window.App = App; })(window);
ggrumbley/ggrumbley.github.io
projects/grumblebucks/scripts/cart.js
JavaScript
mit
943
/** * Created by joonkukang on 2014. 1. 12.. */ var sigmoid = R.NN.sigmoid; HiddenLayer = module.exports = function (settings) { this.input = settings['input']; var a = 1. / settings['nIn']; settings['W'] = settings['W'] || R.randomM(settings['nIn'],settings['nOut'],-a,a); settings['b'] = settings['b'] || R.newV(settings['nOut']); settings['activation'] = settings['activation'] || sigmoid; this.W = settings['W']; this.b = settings['b']; this.activation = settings['activation']; } HiddenLayer.prototype.output = function(input) { this.input = input || this.input; return this.linearOutput(this.input).map1(this.activation); }; HiddenLayer.prototype.linearOutput = function(input) { // before activation this.input = input || this.input; var linearOutput = R.addMV(R.mdot(this.input, this.W), this.b); return linearOutput; } HiddenLayer.prototype.backPropagate = function (input) { // example+num * nOut matrix if(typeof input === 'undefined') throw new Error("No BackPropagation Input.") var linearOutput = input.mdot(this.W.tr()); return linearOutput; } HiddenLayer.prototype.sampleHgivenV = function(input) { this.input = input || this.input; var hMean = this.output(); var hSample = R.NN.binarySample(hMean); // Gibb's random sampling return hSample; }
ccckmit/rlab
plugin/neural/hiddenLayer.js
JavaScript
mit
1,297
/** Create by Huy: codocmm@gmail.com ~ nqhuy2k6@gmail.com 07/31/2015 */ define(["../data/client"], function (client) { return function () { var me = this; me.getPages = function () { return client.pages }; me.getPageDefinitions = function (page) { return client.pageDefinitions[page] } } });
cmasv2/client
app/services/client.js
JavaScript
mit
366
import jwt from 'jsonwebtoken'; import Bcrypt from 'bcrypt'; import joi from 'joi'; import _ from 'lodash'; import {doc2jsonApi} from '../utils'; import Boom from 'boom'; var routes = { /** * sign up a new user */ signUp: { method: 'POST', path: '/', config: { validate: { payload: { email: joi.string().email().required(), login: joi.string().required(), password: joi.string().required() } }, pre: [ { assign: 'checkEmail', method: function(request, reply) { let {db, payload} = request; db.User.first({email: payload.email}).then((fetchedUser) => { if (fetchedUser) { return reply.conflict('email is taken'); } reply(true); }).catch((err) => { return reply.badImplementation(err); }); } }, { assign: 'checkLogin', method: function(request, reply) { let {db, payload} = request; db.User.first({login: payload.login}).then((fetchedUser) => { if (fetchedUser) { return reply.conflict('login is taken'); } reply(true); }).catch((err) => { return reply.badImplementation(err); }); } } ] }, handler: function(request, reply) { let {db, payload, apiBaseUri} = request; let secret = request.server.settings.app.secret; let user = db.User.create(payload); let encryptedPassword = Bcrypt.hashSync(user.get('password'), 10); user.set('password', encryptedPassword); user.save().then((savedUser) => { let userPojo = _.pick(savedUser.attrs(), ['_id', '_type', 'login', 'email']); delete userPojo.password; let token = jwt.sign( {email: payload.email, userId: userPojo._id}, secret, {expiresIn: 60 * 180} ); let base64Token = new Buffer(token).toString('base64'); let clientRootUrl = request.server.settings.app.clientRootUrl; var envelope = { from: request.server.settings.app.email, to: user.get('email'), subject: 'Email verification', // html: { // path: 'email-verification.html' // }, text: `Click on the following link to verify your email: ${clientRootUrl}/verify-email?token=${base64Token} ` // context: { // token: base64Token // } }; var Mailer = request.server.plugins.mailer; Mailer.sendMail(envelope, function (mailError) { if (mailError) { return reply.badImplementation(mailError); } let jsonApiData = { data: doc2jsonApi(db.User, savedUser.attrs(), apiBaseUri) }; delete jsonApiData.data.attributes.password; return reply.created(jsonApiData).type('application/vnd.api+json'); }); }).catch((saveErr) => { return reply.badImplementation(saveErr); }); } }, /** * Verify the user email */ verifyEmail: { method: 'GET', path: '/verify-email/{token}', config: { validate: { params: { token: joi.string().required() } } }, handler: function(request, reply) { let db = request.db; let token = request.params.token; let secret = request.server.settings.app.secret; new Promise((resolve, reject) => { jwt.verify(token, secret, function(err, decoded) { if (err) { return reject(Boom.badRequest(err.message));//reply.badRequest(err.message); } return resolve(decoded); }); }).then((decoded) => { return db.User.first({email: decoded.email}); }).then((user) => { if (!user) { throw Boom.badRequest('email not found in database'); } user.set('emailVerified', true); return user.save(); }).then((savedUser) => { if (savedUser) { return reply.ok('the email has been verified'); } }).catch((error) => { if (error.isBoom) { return reply(error); } else { return reply.badImplementation(error); } }); } }, /** * Request an access token. * The user must be authenticated by a simple auth (username, password) */ requestAcessToken: { method: 'GET', path: '/', config: { auth: 'simple' }, handler: function(request, reply) { let secret = request.server.settings.app.secret; let token = jwt.sign(request.auth.credentials, secret); reply.ok({token: token}); } }, /** * Add a scope to a user */ addUserScope: { method: 'POST', path: '/{userId}/scope/{scope}', config: { auth: { strategy: 'token', access: { scope: 'admin' } }, validate: { params: { userId: joi.string().required(), scope: joi.string().required() } }, pre: [ { assign: 'user', method: function(request, reply) { let db = request.db; let userId = request.params.userId; db.User.first({_id: userId}).then((user) => { if (!user) { return reply.notFound('user not found'); } return reply(user); }).catch((err) => { return reply.badImplementation(err); }); } } ] }, handler: function(request, reply) { var scope = request.params.scope; var user = request.pre.user; user.push('scope', scope); user.save().then(() => { return reply.ok(`${scope} added to user ${user._id}`); }).catch((err) => { return reply.badImplementation(err); }); } }, /** * Remove a scope from a user */ removeUserScope: { method: 'DELETE', path: '/{userId}/scope/{scope}', config: { auth: { strategy: 'token', access: { scope: 'admin' } }, validate: { params: { userId: joi.string().required(), scope: joi.string().required() } }, pre: [ { assign: 'user', method: function(request, reply) { let db = request.db; let userId = request.params.userId; db.User.first({_id: userId}).then((user) => { if (!user) { return reply.notFound('user not found'); } return reply(user); }).catch((err) => { return reply.badImplementation(err); }); } } ] }, handler: function(request, reply) { var scope = request.params.scope; var user = request.pre.user; user.pull('scope', scope); user.save().then(() => { return reply.ok(`${scope} removed from user ${user._id}`); }).catch((err) => { return reply.badImplementation(err); }); } }, /** * Request admin access token from a sudo user * (the returned token is valid for one hour) */ sudo: { method: 'POST', path: '/sudo', config: { auth: { strategy: 'token', access: { scope: ['sudo'] } } }, handler: function(request, reply) { let secret = request.server.settings.app.secret; let credentials = request.auth.credentials; // add the admin scope to the user credentials.scope.push('admin'); let token = jwt.sign( credentials, secret, {expiresIn: 60 * 60} ); reply.ok({token: token}); } }, /* * Revoke admin access token from a sudo user * (the returned token is valid for one hour) */ unsudo: { method: 'DELETE', path: '/sudo', config: { auth: { strategy: 'token', access: { scope: ['sudo', 'admin'] } }, pre: [ {assign: 'scopeCheck', method: function(request, reply) { let scope = request.auth.credentials.scope; if (scope.indexOf('sudo') === -1) { return reply.forbidden('only a sudo user can remove his access'); } reply(true); }} ] }, handler: function(request, reply) { let secret = request.server.settings.app.secret; let credentials = request.auth.credentials; // remove 'admin' from scope credentials.scope = _.without(credentials.scope, 'admin'); let token = jwt.sign( credentials, secret ); reply.ok({token: token}); } }, /** * Request a token to change the password */ passwordRequest: { method: 'POST', path: '/password-request', config: { validate: { payload: { email: joi.string().email().required() } }, pre: [ { assign: 'user', method: function(request, reply) { let {db, payload} = request; db.User.first({email: payload.email}).then((user) => { if (!user) { return reply.notFound('email not found'); } return reply(user); }).catch((err) => { return reply.badImplementation(err); }); } }, { assign: 'resetToken', method: function(request, reply) { let now = new Date(); let rand = Math.floor(Math.random() * 10000); let token = parseInt(rand).toString(36) + parseInt(now.getTime()).toString(36); reply(token); } } ] }, handler: function(request, reply) { let secret = request.server.settings.app.secret; let {email} = request.payload; let {user, resetToken} = request.pre; user.set('passwordResetToken', resetToken); user.save().then(() => { let token = jwt.sign( {email: email, token: resetToken}, secret, {expiresIn: 60 * 180} ); let base64Token = new Buffer(token).toString('base64'); let clientRootUrl = request.server.settings.app.clientRootUrl; var envelope = { from: request.server.settings.app.email, to: user.get('email'), subject: 'Password reset', // html: { // path: 'password-reset.html' // }, text: `Click on the following link to reset your password: ${clientRootUrl}/password-reset?token=${base64Token} ` // context: { // token: base64Token // } }; var Mailer = request.server.plugins.mailer; Mailer.sendMail(envelope, function (mailError) { if (mailError) { return reply.badImplementation(mailError); } reply.ok('the password reset token has been send by email'); }); }).catch((err) => { return reply.badImplementation(err); }); } }, /** * Change the user password using the password token */ passwordReset: { method: 'POST', path: '/password-reset', config: { validate: { payload: { token: joi.string().required(), password: joi.string().required() } }, pre: [ { assign: 'resetToken', method: function(request, reply) { let secret = request.server.settings.app.secret; jwt.verify(request.payload.token, secret, function(err, decoded) { if (err) { return reply.badRequest(err.message); } return reply(decoded.token); }); } }, { assign: 'user', method: function(request, reply) { let {db} = request; db.User.first({passwordResetToken: request.pre.resetToken}).then((user) => { if (!user) { return reply.badRequest('Cannot find a match. The token may have been used already.'); } return reply(user); }).catch((err) => { return reply.badImplementation(err); }); } } ] }, handler: function(request, reply) { let {password} = request.payload; let user = request.pre.user; let encryptedPassword = Bcrypt.hashSync(password, 10); user.set('password', encryptedPassword); user.unset('passwordResetToken'); user.save().then(() => { return reply.ok('the password has been reset'); }).catch((err) => { return reply.badImplementation(err); }); } } }; export default routes;
namlook/eurekajs
src/contrib/auth-routes.js
JavaScript
mit
16,446
//= require_tree . jQuery.fn.hjq_data_table = function(annotations) { this.dataTable(this.hjq('getOptions', annotations)); };
Hobo/hobo_data_tables
vendor/assets/javascripts/hobo_data_tables.js
JavaScript
mit
130
/* global describe, it, before */ /* eslint-disable import/no-extraneous-dependencies, func-names */ const chai = require('chai'); const join = require('path').join; const execSync = require('child_process').execSync; const fs = require('fs'); const assert = chai.assert; chai.use(require('chai-fs')); describe('Sass Export Data', function() { this.timeout(5000); let output = ''; before(() => { try { output = execSync('npm run test:compile', { cwd: __dirname, encoding: 'utf8', }); // console.log(output); } catch (e) { console.error('Could not run command beforehand.', e); } }); fs.readdirSync(join(__dirname, './basics/expected')) .filter(file => file.endsWith('json')) .forEach(file => { it(`Creates JSON from Sass Vars in ${file}`, () => { assert.deepEqual( JSON.parse( fs.readFileSync(join(__dirname, './basics/dest/', file), 'utf8'), ), JSON.parse( fs.readFileSync( join(__dirname, './basics/expected/', file), 'utf8', ), ), `JSON files do not match.\n\n${output}`, ); }); }); });
bolt-design-system/bolt
packages/build-tools/plugins/sass-export-data/tests/sass-export-data.test.js
JavaScript
mit
1,209
/* ************************************ */ /* Define helper functions */ /* ************************************ */ function addID() { jsPsych.data.addDataToLastTrial({exp_id: 'stop_signal_with_cued_task_switching'}) } function evalAttentionChecks() { var check_percent = 1 if (run_attention_checks) { var attention_check_trials = jsPsych.data.getTrialsOfType('attention-check') var checks_passed = 0 for (var i = 0; i < attention_check_trials.length; i++) { if (attention_check_trials[i].correct === true) { checks_passed += 1 } } check_percent = checks_passed / attention_check_trials.length } jsPsych.data.addDataToLastTrial({"att_check_percent": check_percent}) return check_percent } function assessPerformance() { /* Function to calculate the "credit_var", which is a boolean used to credit individual experiments in expfactory. */ var experiment_data = jsPsych.data.getTrialsOfType('stop-signal') var missed_count = 0 var trial_count = 0 var rt_array = [] var rt = 0 var correct = 0 var all_trials = 0 //record choices participants made var choice_counts = {} choice_counts[-1] = 0 choice_counts[77] = 0 choice_counts[90] = 0 for (var i = 0; i < experiment_data.length; i++) { if (experiment_data[i].trial_id == 'test_trial') { all_trials += 1 key = experiment_data[i].key_press choice_counts[key] += 1 if (experiment_data[i].stop_signal_condition == 'go'){ trial_count += 1 } if ((experiment_data[i].stop_signal_condition == 'go') && (experiment_data[i].rt != -1)){ rt = experiment_data[i].rt rt_array.push(rt) if (experiment_data[i].key_press == experiment_data[i].correct_response){ correct += 1 } } else if ((experiment_data[i].stop_signal_condition == 'stop') && (experiment_data[i].rt != -1)){ rt = experiment_data[i].rt rt_array.push(rt) } else if ((experiment_data[i].stop_signal_condition == 'go') && (experiment_data[i].rt == -1)){ missed_count += 1 } } } //calculate average rt var avg_rt = -1 if (rt_array.length !== 0) { avg_rt = math.median(rt_array) } //calculate whether response distribution is okay var responses_ok = true Object.keys(choice_counts).forEach(function(key, index) { if (choice_counts[key] > all_trials * 0.85) { responses_ok = false } }) var accuracy = correct / trial_count var missed_percent = missed_count/trial_count credit_var = (missed_percent < 0.25 && avg_rt > 200 && responses_ok && accuracy > 0.60) jsPsych.data.addDataToLastTrial({final_credit_var: credit_var, final_missed_percent: missed_percent, final_avg_rt: avg_rt, final_responses_ok: responses_ok, final_accuracy: accuracy}) } var randomDraw = function(lst) { var index = Math.floor(Math.random() * (lst.length)) return lst[index] } var getInstructFeedback = function() { return '<div class = centerbox><p class = center-block-text>' + feedback_instruct_text + '</p></div>' } var getCategorizeFeedback = function(){ curr_trial = jsPsych.progress().current_trial_global - 1 trial_id = jsPsych.data.getDataByTrialIndex(curr_trial).trial_id if ((trial_id == 'practice_trial') && (jsPsych.data.getDataByTrialIndex(curr_trial).stop_signal_condition != 'stop')){ if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press == jsPsych.data.getDataByTrialIndex(curr_trial).correct_response){ return '<div class = fb_box><div class = center-text><font size = 20>Correct!</font></div></div>' } else if ((jsPsych.data.getDataByTrialIndex(curr_trial).key_press != jsPsych.data.getDataByTrialIndex(curr_trial).correct_response) && (jsPsych.data.getDataByTrialIndex(curr_trial).key_press != -1)){ return '<div class = fb_box><div class = center-text><font size = 20>Incorrect</font></div></div>' } else if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press == -1){ return '<div class = fb_box><div class = center-text><font size = 20>Respond Faster!</font></div></div>' } } else if ((trial_id == 'practice_trial') && (jsPsych.data.getDataByTrialIndex(curr_trial).stop_signal_condition == 'stop')){ if (jsPsych.data.getDataByTrialIndex(curr_trial).rt == -1){ return '<div class = fb_box><div class = center-text><font size = 20>Correct!</font></div></div>' } else if (jsPsych.data.getDataByTrialIndex(curr_trial).rt != -1){ return '<div class = fb_box><div class = center-text><font size = 20>There was a star.</font></div></div>' } } } // Task Specific Functions var getKeys = function(obj) { var keys = []; for (var key in obj) { keys.push(key); } return keys } var genStims = function(n) { stims = [] for (var i = 0; i < n; i++) { var number = randomDraw('12346789') var color = 'white' var stim = { number: parseInt(number), color: color } stims.push(stim) } return stims } //Sets the cue-target-interval for the cue block var setCTI = function() { return CTI //randomDraw([100, 900]) } var getCTI = function() { return CTI } var getFeedback = function() { return '<div class = bigbox><div class = picture_box><p class = block-text><font color="white">' + feedback_text + '</font></p></div></div>' } /* Index into task_switches using the global var current_trial. Using the task_switch and cue_switch change the task. If "stay", keep the same task but change the cue based on "cue switch". If "switch new", switch to the task that wasn't the current or last task, choosing a random cue. If "switch old", switch to the last task and randomly choose a cue. */ var setStims = function() { var tmp; switch (task_switches[current_trial].task_switch){ case "na": tmp = curr_task curr_task = randomDraw(getKeys(tasks)) cue_i = randomDraw([0, 1]) break case "stay": if (curr_task == "na") { tmp = curr_task curr_task = randomDraw(getKeys(tasks)) } if (task_switches[current_trial].cue_switch == "switch") { cue_i = 1 - cue_i } break case "switch": task_switches[current_trial].cue_switch = "switch" cue_i = randomDraw([0, 1]) if (last_task == "na") { tmp = curr_task curr_task = randomDraw(getKeys(tasks).filter(function(x) { return (x != curr_task) })) last_task = tmp } else { tmp = curr_task curr_task = getKeys(tasks).filter(function(x) { return (x != curr_task) })[0] last_task = tmp } break case "switch_old": cue_i = randomDraw([0, 1]) task_switches[current_trial].cue_switch = "switch" if (last_task == "na") { tmp = curr_task curr_task = randomDraw(getKeys(tasks).filter(function(x) { return (x != curr_task) })) last_task = tmp } else { tmp = curr_task curr_task = last_task last_task = tmp } break } curr_cue = tasks[curr_task].cues[cue_i] curr_stim = stims[current_trial] stop_signal_condition = task_switches[current_trial].stop_type current_trial = current_trial + 1 CTI = setCTI() } var getCue = function() { var cue_html = '<div class = upperbox><div class = center-text>' + curr_cue + '</div></div>'+ '<div class = lowerbox><div class = fixation>+</div></div>' return cue_html } var getStim = function() { var stim_html = '<div class = upperbox><div class = center-text>' + curr_cue + '</div></div>'+ '<div class = lowerbox><div class = gng_number><div class = cue-text>'+ preFileType + curr_stim.number + fileTypePNG + '</div></div></div>' return stim_html } var getSSType = function(){ return stop_signal_condition } var getStopStim = function(){ var stim_html = '<div class = starbox>'+ preFileTypeStar + 'stop' + fileTypePNG + '</div>' return stim_html } function getSSD(){ var trial_num = current_trial - 1 //current_trial has already been updated with setStims, so subtract one to record data var task_switch = task_switches[trial_num] if (task_switch.task_switch == 'switch'){ return SSD_switch } else if (task_switch.task_switch == 'stay'){ return SSD_stay } } //Returns the key corresponding to the correct response for the current // task and stim var getResponse = function() { switch (curr_task) { case 'color': if (curr_stim.color == 'orange') { correct_response = response_keys.key[0] if(stop_signal_condition == "stop"){ correct_response = -1 } return correct_response } else { correct_response = response_keys.key[1] if(stop_signal_condition == "stop"){ correct_response = -1 } return correct_response } break; case 'magnitude': if (curr_stim.number > 5) { correct_response = response_keys.key[0] if(stop_signal_condition == "stop"){ correct_response = -1 } return correct_response } else { correct_response = response_keys.key[1] if(stop_signal_condition == "stop"){ correct_response = -1 } return correct_response } break; case 'parity': if (curr_stim.number % 2 === 0) { correct_response = response_keys.key[0] if(stop_signal_condition == "stop"){ correct_response = -1 } return correct_response } else { correct_response = response_keys.key[1] if(stop_signal_condition == "stop"){ correct_response = -1 } return correct_response } } } /* Append gap and current trial to data and then recalculate for next trial*/ var appendData = function() { var curr_trial = jsPsych.progress().current_trial_global var trial_id = jsPsych.data.getDataByTrialIndex(curr_trial).trial_id var trial_num = current_trial - 1 //current_trial has already been updated with setStims, so subtract one to record data var task_switch = task_switches[trial_num] if (trial_id == "practice_trial"){ currBlock = practiceCount } else if (trial_id == "test_trial"){ currBlock = testCount } jsPsych.data.addDataToLastTrial({ cue: curr_cue, stim_color: curr_stim.color, stim_number: curr_stim.number, task: curr_task, task_condition: task_switch.task_switch, cue_condition: task_switch.cue_switch, stop_signal_condition: stop_signal_condition, current_trial: current_trial, current_block: currBlock, CTI: CTI, SSD_stay: SSD_stay, SSD_switch: SSD_switch }) if ((trial_id == 'test_trial') || (trial_id == 'practice_trial')){ jsPsych.data.addDataToLastTrial({correct_response: correct_response}) if ((jsPsych.data.getDataByTrialIndex(curr_trial).key_press == -1) && (jsPsych.data.getDataByTrialIndex(curr_trial).stop_signal_condition == 'stop') && (SSD_stay < maxSSD) && (jsPsych.data.getDataByTrialIndex(curr_trial).task_condition == 'stay')){ jsPsych.data.addDataToLastTrial({stop_acc: 1}) SSD_stay+=50 } else if ((jsPsych.data.getDataByTrialIndex(curr_trial).key_press != -1) && (jsPsych.data.getDataByTrialIndex(curr_trial).stop_signal_condition == 'stop') && (SSD_stay > minSSD) && (jsPsych.data.getDataByTrialIndex(curr_trial).task_condition == 'stay')){ jsPsych.data.addDataToLastTrial({stop_acc: 0}) SSD_stay-=50 } if ((jsPsych.data.getDataByTrialIndex(curr_trial).key_press == -1) && (jsPsych.data.getDataByTrialIndex(curr_trial).stop_signal_condition == 'stop') && (SSD_switch < maxSSD) && (jsPsych.data.getDataByTrialIndex(curr_trial).task_condition == 'switch')){ jsPsych.data.addDataToLastTrial({stop_acc: 1}) SSD_switch+=50 } else if ((jsPsych.data.getDataByTrialIndex(curr_trial).key_press != -1) && (jsPsych.data.getDataByTrialIndex(curr_trial).stop_signal_condition == 'stop') && (SSD_switch > minSSD) && (jsPsych.data.getDataByTrialIndex(curr_trial).task_condition == 'switch')){ jsPsych.data.addDataToLastTrial({stop_acc: 0}) SSD_switch-=50 } if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press == correct_response){ jsPsych.data.addDataToLastTrial({ correct_trial: 1, }) } else if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press != correct_response){ jsPsych.data.addDataToLastTrial({ correct_trial: 0, }) } } } /* ************************************ */ /* Define experimental variables */ /* ************************************ */ // generic task variables var run_attention_checks = true var attention_check_thresh = 0.45 var sumInstructTime = 0 //ms var instructTimeThresh = 0 ///in seconds var credit_var = 0 var fileTypePNG = '.png"></img>' var preFileType = '<img class = center src="/static/experiments/stop_signal_with_cued_task_switching/images/' var preFileTypeStar = '<img class = star src="/static/experiments/stop_signal_with_cued_task_switching/images/' var accuracy_thresh = 0.75 var rt_thresh = 1000 var missed_thresh = 0.10 var maxStopCorrect = 0.70 var minStopCorrect = 0.30 var maxStopCorrectPractice = 1 var minStopCorrectPractice = 0 var practice_thresh = 3 // 3 blocks of 12 var CTI = 150 // task specific variables var response_keys = {key: [77,90], key_name: ["M","Z"]} var choices = response_keys.key var practice_length = 24 var exp_len = 240 var numTrialsPerBlock = 48 //48 must be divisible by 12 var numTestBlocks = exp_len / numTrialsPerBlock var SSD_stay = 350 var SSD_switch = 350 var maxSSD = 1000 var minSSD = 0 //set up block stim. correct_responses indexed by [block][stim][type] var tasks = { parity: { task: 'parity', cues: ['Parity', 'Odd-Even'] }, magnitude: { task: 'magnitude', cues: ['Magnitude', 'High-Low'] } } /* color: { task: 'color', cues: ['Color', 'Orange-Blue'] }, */ var task_switch_types = ["stay", "switch"] var cue_switch_types = ["stay", "switch"] var stop_types = ["go","go","stop"] var task_switches_arr = [] for (var t = 0; t < task_switch_types.length; t++) { for (var c = 0; c < cue_switch_types.length; c++) { for (var s = 0; s < stop_types.length; s++){ task_switches_arr.push({ task_switch: task_switch_types[t], cue_switch: cue_switch_types[c], stop_type: stop_types[s] }) } } } var task_switches = jsPsych.randomization.repeat(task_switches_arr, practice_length / 12) task_switches.unshift({task_switch: 'na', cue_switch: 'na', stop_type: jsPsych.randomization.repeat(["go","go","stop"],1).pop()}) var practiceStims = genStims(practice_length + 1) var testStims = genStims(numTrialsPerBlock + 1) var stims = practiceStims var curr_task = randomDraw(getKeys(tasks)) var last_task = 'na' //object that holds the last task, set by setStims() var curr_cue = 'na' //object that holds the current cue, set by setStims() var cue_i = randomDraw([0, 1]) //index for one of two cues of the current task var curr_stim = 'na' //object that holds the current stim, set by setStims() var current_trial = 0 var currBlock = 0 var exp_stage = 'practice' // defines the exp_stage, switched by start_test_block var task_list = '<ul style = "font-size: 23px">'+ '<li><i>Odd-Even</i> or <i>Parity</i>: ' + response_keys.key_name[1] + ' if odd and ' + response_keys.key_name[0] + ' if even.</li>'+ '<li><i>High-Low</i> or <i>Magnitude</i>: ' + response_keys.key_name[1] + ' if <5 and ' + response_keys.key_name[0] + ' if >5.</li>'+ '</ul>' var prompt_task_list = '<ul style = "text-align:left; font-size: 23px">'+ '<li><i>Odd-Even</i> or <i>Parity</i>: ' + response_keys.key_name[1] + ' if odd and ' + response_keys.key_name[0] + ' if even.</li>'+ '<li><i>High-Low</i> or <i>Magnitude</i>: ' + response_keys.key_name[1] + ' if <5 and ' + response_keys.key_name[0] + ' if >5.</li>'+ '<li>Do not respond if there is a star!</li>'+ '</ul>' //PRE LOAD IMAGES HERE var pathSource = "/static/experiments/stop_signal_with_cued_task_switching/images/" var numbersPreload = ['1','2','3','4','6','7','8','9'] var images = [] for(i=0;i<numbersPreload.length;i++){ images.push(pathSource + numbersPreload[i] + '.png') } images.push(pathSource + 'stop.png') jsPsych.pluginAPI.preloadImages(images); /* ************************************ */ /* Set up jsPsych blocks */ /* ************************************ */ // Set up attention check node var attention_check_block = { type: 'attention-check', data: { trial_id: "attention_check" }, timing_response: 180000, response_ends_trial: true, timing_post_trial: 200 } var attention_node = { timeline: [attention_check_block], conditional_function: function() { return run_attention_checks } } //Set up post task questionnaire var post_task_block = { type: 'survey-text', data: { exp_id: "stop_signal_with_cued_task_switching", trial_id: "post task questions" }, questions: ['<p class = center-block-text style = "font-size: 20px">Please summarize what you were asked to do in this task.</p>', '<p class = center-block-text style = "font-size: 20px">Do you have any comments about this task?</p>'], rows: [15, 15], timing_response: 360000, columns: [60,60] }; /* define static blocks */ var feedback_instruct_text = 'Welcome to the experiment. This experiment will take around 15 minutes. Press <i>enter</i> to begin.' var feedback_instruct_block = { type: 'poldrack-text', data: { trial_id: "instruction" }, cont_key: [13], text: getInstructFeedback, timing_post_trial: 0, timing_response: 180000 }; /// This ensures that the subject does not read through the instructions too quickly. If they do it too quickly, then we will go over the loop again. var instructions_block = { type: 'poldrack-instructions', data: { trial_id: "instruction" }, pages: [ '<div class = centerbox>'+ '<p class = block-text>In this experiment you will have to respond to a sequence of numbers by pressing the "M" and "Z" keys. How you respond to the numbers will depend on the current task, which can change every trial.</p><p class = block-text>On some trials you will have to indicate whether the number is odd or even, and on other trials you will indicate whether the number is higher or lower than 5. Each trial will start with a cue telling you which task to do on that trial.</p>'+ '</div>', '<div class = centerbox>'+ '<p class = block-text>The cue before the number will be a word indicating the task. There will be four different cues indicating two different tasks. The cues and tasks are described below:</p>' + task_list + '</div>', '<div class = centerbox>' + '<p class = block-text>On some trials, a star will appear around the number. The star will appear with, or shortly after the number appears.</p>'+ '<p class = block-text>If you see a star appear, please try your best to make no response on that trial.</p>'+ '<p class = block-text>If the star appears on a trial, and you try your best to withhold your response, you will find that you will be able to stop sometimes but not always.</p>'+ '<p class = block-text>Please do not slow down your responses in order to wait for the star. Continue to respond as quickly and accurately as possible.</p>'+ '</div>', '<div class = centerbox>' + '<p class = block-text>We will start practice when you finish instructions. Please make sure you understand the instructions before moving on. You will be given a reminder of the rules for practice. <i>This will be removed for test!</i></p>'+ '<p class = block-text>To avoid technical issues, please keep the experiment tab (on Chrome or Firefox) <i>active and in full-screen mode</i> for the whole duration of each task.</p>'+ '</div>' ], allow_keys: false, show_clickable_nav: true, timing_post_trial: 1000 }; var instruction_node = { timeline: [feedback_instruct_block, instructions_block], /* This function defines stopping criteria */ loop_function: function(data) { for (i = 0; i < data.length; i++) { if ((data[i].trial_type == 'poldrack-instructions') && (data[i].rt != -1)) { rt = data[i].rt sumInstructTime = sumInstructTime + rt } } if (sumInstructTime <= instructTimeThresh * 1000) { feedback_instruct_text = 'Read through instructions too quickly. Please take your time and make sure you understand the instructions. Press <i>enter</i> to continue.' return true } else if (sumInstructTime > instructTimeThresh * 1000) { feedback_instruct_text = 'Done with instructions. Press <i>enter</i> to continue.' return false } } } var end_block = { type: 'poldrack-text', data: { trial_id: "end", }, text: '<div class = centerbox><p class = center-block-text>Thanks for completing this task!</p><p class = center-block-text>Press <i>enter</i> to continue.</p></div>', cont_key: [13], timing_response: 180000, on_finish: function(){ assessPerformance() evalAttentionChecks() } }; var start_practice_block = { type: 'poldrack-text', timing_response: 180000, data: { trial_id: "practice_intro" }, text: '<div class = centerbox><p class = center-block-text>Starting with some practice. </p><p class = center-block-text>Press <i>enter</i> to continue.</p></div>', cont_key: [13] }; var start_test_block = { type: 'poldrack-text', timing_response: 180000, data: { trial_id: "test_intro" }, text: '<div class = centerbox>'+ '<p class = block-text>Practice completed. Starting test.</p>'+ '<p class = block-text>The cue before the number will be a word indicating the task. There will be four different cues indicating 2 different tasks. The cues and tasks are described below:</p>' + task_list + '<p class = block-text>Do not make a response if a star appears.</p>'+ '<p class = block-text>Press <i>enter</i> to begin.</p>'+ '</div>', on_finish: function() { current_trial = 0 stims = testStims task_switches = jsPsych.randomization.repeat(task_switches_arr, numTrialsPerBlock / 12) task_switches.unshift({task_switch: 'na', cue_switch: 'na', stop_type: jsPsych.randomization.repeat(["go","go","stop"],1).pop()}) feedback_text = 'Starting a test block.' }, timing_post_trial: 1000 } /* define practice and test blocks */ var setStims_block = { type: 'call-function', data: { trial_id: "set_stims" }, func: setStims, timing_post_trial: 0 } var fixation_block = { type: 'poldrack-single-stim', stimulus: '<div class = upperbox><div class = fixation>+</div></div><div class = lowerbox><div class = fixation>+</div></div>', is_html: true, choices: 'none', data: { trial_id: "fixation" }, timing_post_trial: 0, timing_stim: 500, timing_response: 500, prompt: '<div class = promptbox>' + prompt_task_list + '</div>', on_finish: function() { jsPsych.data.addDataToLastTrial({ exp_stage: exp_stage }) } } var cue_block = { type: 'poldrack-single-stim', stimulus: getCue, is_html: true, choices: 'none', data: { trial_id: 'cue' }, timing_response: getCTI, timing_stim: getCTI, timing_post_trial: 0, prompt: '<div class = promptbox>' + prompt_task_list + '</div>', on_finish: function() { jsPsych.data.addDataToLastTrial({exp_stage: exp_stage}) appendData() } }; var feedback_text = 'Welcome to the experiment. This experiment will take around 15 minutes. Press <i>enter</i> to begin.' var feedback_block = { type: 'poldrack-single-stim', data: { trial_id: "practice-stop-feedback" }, choices: [13], stimulus: getFeedback, timing_post_trial: 0, is_html: true, timing_response: 180000, response_ends_trial: true, }; var practice_block = { type: 'stop-signal', stimulus: getStim, SS_stimulus: getStopStim, SS_trial_type: getSSType, data: { "trial_id": "practice_trial" }, is_html: true, choices: choices, timing_stim: 1000, //1000 timing_response: 2000, //2000 response_ends_trial: false, SSD: getSSD, timing_SS: 500, //500 timing_post_trial: 0, prompt: '<div class = promptbox>' + prompt_task_list + '</div>', on_finish: function(){ getResponse() appendData() } }; var categorize_block = { type: 'poldrack-single-stim', data: { trial_id: "practice-stop-feedback" }, choices: 'none', stimulus: getCategorizeFeedback, timing_post_trial: 0, is_html: true, timing_stim: 500, //500 prompt: '<div class = promptbox>' + prompt_task_list + '</div>', timing_response: 500, //500 response_ends_trial: false, }; var test_block = { type: 'stop-signal', stimulus: getStim, SS_stimulus: getStopStim, SS_trial_type: getSSType, is_html: true, choices: choices, data: { trial_id: 'test_trial', exp_stage: 'test' }, SSD: getSSD, timing_SS: 500, //500 timing_post_trial: 0, timing_response: 2000, //2000 timing_stim: 1000, //1000 on_finish: function(data) { appendData() correct_response = getResponse() correct = false if (data.key_press === correct_response) { correct = true } jsPsych.data.addDataToLastTrial({ 'correct_response': correct_response, 'correct': correct }) } } var practiceTrials = [] practiceTrials.push(feedback_block) practiceTrials.push(instructions_block) for (var i = 0; i < practice_length + 1; i++) { var practice_fixation_block = { type: 'poldrack-single-stim', stimulus: '<div class = upperbox><div class = fixation>+</div></div><div class = lowerbox><div class = fixation>+</div></div>', is_html: true, choices: 'none', data: { trial_id: "fixation" }, timing_post_trial: 0, timing_stim: 500, //500 timing_response: 500, //500 prompt: '<div class = promptbox>' + prompt_task_list + '</div>', on_finish: function() { jsPsych.data.addDataToLastTrial({ exp_stage: exp_stage }) } } var practice_cue_block = { type: 'poldrack-single-stim', stimulus: getCue, is_html: true, choices: 'none', data: { trial_id: 'cue' }, timing_response: getCTI, //getCTI timing_stim: getCTI, //getCTI timing_post_trial: 0, prompt: '<div class = promptbox>' + prompt_task_list + '</div>', on_finish: function() { jsPsych.data.addDataToLastTrial({exp_stage: exp_stage}) appendData() } }; practiceTrials.push(setStims_block) practiceTrials.push(practice_fixation_block) practiceTrials.push(practice_cue_block); //magnitide/high-low or parity/odd-even practiceTrials.push(practice_block); //where the number stim for that trial appears (and getStopStim) practiceTrials.push(categorize_block); } var practiceCount = 0 var practiceNode = { timeline: practiceTrials, loop_function: function(data) { practiceCount += 1 task_switches = jsPsych.randomization.repeat(task_switches_arr, practice_length / 12) task_switches.unshift({task_switch: 'na', cue_switch: 'na', stop_type: jsPsych.randomization.repeat(["go","go","stop"],1).pop()}) practiceStims = genStims(practice_length + 1) current_trial = 0 var total_trials = 0 var sum_responses = 0 var total_sum_rt = 0 var go_trials = 0 var go_correct = 0 var go_rt = 0 var sum_go_responses = 0 var stop_trials = 0 var stop_correct = 0 var stop_rt = 0 var sum_stop_responses = 0 for (var i = 0; i < data.length; i++){ if (data[i].trial_id == "practice_trial"){ total_trials+=1 if (data[i].stop_signal_condition == 'go'){ go_trials+=1 if (data[i].rt != -1){ total_sum_rt += data[i].rt go_rt += data[i].rt sum_go_responses += 1 if (data[i].key_press == data[i].correct_response){ go_correct += 1 } } } else if (data[i].stop_signal_condition == 'stop'){ stop_trials+=1 if (data[i].rt != -1){ total_sum_rt += data[i].rt stop_rt += data[i].rt sum_stop_responses += 1 } if (data[i].rt == -1){ stop_correct += 1 } } } } var accuracy = go_correct / go_trials var missed_responses = (go_trials - sum_go_responses) / go_trials var ave_rt = go_rt / sum_go_responses var stop_acc = stop_correct / stop_trials console.log('stop_acc = ' + stop_acc) console.log('stop_correct = ' + stop_correct) console.log('stop_trials = ' + stop_trials) feedback_text = "<br>Please take this time to read your feedback and to take a short break! Press enter to continue" if ((accuracy > accuracy_thresh) && (stop_acc < maxStopCorrectPractice) && (stop_acc > minStopCorrectPractice)){ feedback_text += '</p><p class = block-text>Done with this practice. Press Enter to continue.' testStims = genStims(numTrialsPerBlock + 1) task_switches = jsPsych.randomization.repeat(task_switches_arr, numTrialsPerBlock / 12) task_switches.unshift({task_switch: 'na', cue_switch: 'na', stop_type: jsPsych.randomization.repeat(["go","go","stop"],1).pop()}) return false } else { if (accuracy < accuracy_thresh){ feedback_text += '</p><p class = block-text>We are going to try practice again to see if you can achieve higher accuracy. Remember: <br>' + prompt_task_list } if (missed_responses > missed_thresh){ feedback_text += '</p><p class = block-text>You have not been responding to some trials. Please respond on every trial that requires a response.' } if (ave_rt > rt_thresh) { feedback_text += '</p><p class = block-text>You have been responding too slowly.' } if (stop_acc === maxStopCorrectPractice){ feedback_text += '</p><p class = block-text>You have been responding too slowly. Please respond as quickly and accurately to each stimulus that requires a response.' } if (stop_acc === minStopCorrectPractice){ feedback_text += '</p><p class = block-text>You have not been stopping your response when stars are present. Please try your best to stop your response if you see a star.' } if (practiceCount == practice_thresh){ feedback_text += '</p><p class = block-text>Done with this practice.' testStims = genStims(numTrialsPerBlock + 1) task_switches = jsPsych.randomization.repeat(task_switches_arr, numTrialsPerBlock / 12) task_switches.unshift({task_switch: 'na', cue_switch: 'na', stop_type: jsPsych.randomization.repeat(["go","go","stop"],1).pop()}) return false } feedback_text += '</p><p class = block-text>Redoing this practice. Press Enter to continue.' return true } } } var testTrials = [] testTrials.push(feedback_block) testTrials.push(attention_node) for (var i = 0; i < numTrialsPerBlock + 1; i++) { var fixation_block = { type: 'poldrack-single-stim', stimulus: '<div class = upperbox><div class = fixation>+</div></div><div class = lowerbox><div class = fixation>+</div></div>', is_html: true, choices: 'none', data: { trial_id: "fixation" }, timing_post_trial: 0, timing_stim: 500, //500 timing_response: 500, //500 on_finish: function() { jsPsych.data.addDataToLastTrial({ exp_stage: exp_stage }) } } var cue_block = { type: 'poldrack-single-stim', stimulus: getCue, is_html: true, choices: 'none', data: { trial_id: 'cue' }, timing_response: getCTI, //getCTI timing_stim: getCTI, //getCTI timing_post_trial: 0, on_finish: function() { jsPsych.data.addDataToLastTrial({exp_stage: exp_stage}) appendData() } }; testTrials.push(setStims_block) testTrials.push(fixation_block) testTrials.push(cue_block); //1 of the 4 cues testTrials.push(test_block); //a number (1-9) (and getStopStim) } var testCount = 0 var testNode = { timeline: testTrials, loop_function: function(data) { testCount += 1 task_switches = jsPsych.randomization.repeat(task_switches_arr, numTrialsPerBlock / 12) task_switches.unshift({task_switch: 'na', cue_switch: 'na', stop_type: jsPsych.randomization.repeat(["go","go","stop"],1).pop()}) testStims = genStims(numTrialsPerBlock + 1) current_trial = 0 var total_trials = 0 var sum_responses = 0 var total_sum_rt = 0 var go_trials = 0 var go_correct = 0 var go_rt = 0 var sum_go_responses = 0 var stop_trials = 0 var stop_correct = 0 var stop_rt = 0 var sum_stop_responses = 0 for (var i = 0; i < data.length; i++){ if (data[i].trial_id == "test_trial"){ total_trials+=1 if (data[i].stop_signal_condition == 'go'){ go_trials+=1 if (data[i].rt != -1){ total_sum_rt += data[i].rt go_rt += data[i].rt sum_go_responses += 1 if (data[i].key_press == data[i].correct_response){ go_correct += 1 } } } else if (data[i].stop_signal_condition == 'stop'){ stop_trials+=1 if (data[i].rt != -1){ total_sum_rt += data[i].rt stop_rt += data[i].rt sum_stop_responses += 1 } if (data[i].rt == -1){ stop_correct += 1 } } } } var accuracy = go_correct / go_trials var missed_responses = (go_trials - sum_go_responses) / go_trials var ave_rt = go_rt / sum_go_responses var stop_acc = stop_correct / stop_trials feedback_text = "<br>Please take this time to read your feedback and to take a short break! Press enter to continue" feedback_text += "</p><p class = block-text>You have completed: "+testCount+" out of "+numTestBlocks+" blocks of trials." if (accuracy < accuracy_thresh){ feedback_text += '</p><p class = block-text>Your accuracy is too low. Remember: <br>' + prompt_task_list } if (missed_responses > missed_thresh){ feedback_text += '</p><p class = block-text>You have not been responding to some trials. Please respond on every trial that requires a response.' } if (ave_rt > rt_thresh) { feedback_text += '</p><p class = block-text>You have been responding too slowly.' } if (stop_acc > maxStopCorrect){ feedback_text += '</p><p class = block-text>You have been responding too slowly. Please respond as quickly and accurately to each stimulus that requires a response.' } if (stop_acc < minStopCorrect){ feedback_text += '</p><p class = block-text>You have not been stopping your response when stars are present. Please try your best to stop your response if you see a star.' } if (testCount == numTestBlocks){ feedback_text += '</p><p class = block-text>Done with this test. Press Enter to continue.<br> If you have been completing tasks continuously for an hour or more, please take a 15-minute break before starting again.' return false } else { return true } } } /* create experiment definition array */ var stop_signal_with_cued_task_switching_experiment = []; stop_signal_with_cued_task_switching_experiment.push(practiceNode); stop_signal_with_cued_task_switching_experiment.push(feedback_block); stop_signal_with_cued_task_switching_experiment.push(start_test_block) stop_signal_with_cued_task_switching_experiment.push(testNode); stop_signal_with_cued_task_switching_experiment.push(feedback_block); stop_signal_with_cued_task_switching_experiment.push(post_task_block) stop_signal_with_cued_task_switching_experiment.push(end_block)
expfactory/expfactory-experiments
stop_signal_with_cued_task_switching/experiment.js
JavaScript
mit
35,241
function defaultEqualityCheck(a, b) { return a === b } function defaultMemoize(func, equalityCheck = defaultEqualityCheck) { let lastArgs = null let lastResult = null return (...args) => { if (lastArgs !== null && args.every((value, index) => equalityCheck(value, lastArgs[index]))) { return lastResult } lastArgs = args lastResult = func(...args) return lastResult } } function pick(obj, fn) { return Object.keys(obj).reduce((result, key) => { if (fn(obj[key])) { result[key] = obj[key] } return result }, {}) } export function combineReducers(reducers) { var finalReducers = pick(reducers, (val) => typeof val === 'function') return (state = {}, action) => mapValues(finalReducers, (reducer, key) => reducer(state[key], action) ) } export function mapValues(obj, fn) { return Object.keys(obj).reduce((result, key) => { result[key] = fn(obj[key], key) return result }, {}) } function parseArgs(args) { if ( args.length == 1) { return { reducerDependencies: {}, reducer: args[0], reducerMemoizer: defaultMemoize // TODO allow customization } } else if ( args.length == 2) { return { reducerDependencies: args[0], reducer: args[1], reducerMemoizer: defaultMemoize } } else { throw new Error('Bad usage') // TODO better errors } } function wrapState(state,dependencies) { return { value: state, __dependencies: dependencies } } function unwrapState(state) { if ( state != null && typeof state === 'object' && Object.keys(state).length === 2 && state.__dependencies && typeof state.value !== 'undefined' ) { return state.value } else { return state } } export function createReducer() { const { reducerDependencies,reducer,reducerMemoizer } = parseArgs(arguments) const hasDependencies = Object.keys(reducerDependencies).length > 0 if ( !hasDependencies ) { return reducerMemoizer(reducer) } const reducerDependenciesReducer = reducerMemoizer(combineReducers(reducerDependencies)) const liftedReducer = (state = { value: undefined, __dependencies: undefined }, action) => { const { value, __dependencies } = state const nextDependenciesState = reducerDependenciesReducer(__dependencies,action) const nextDependenciesStatesUnwrapped = mapValues(nextDependenciesState,depState => unwrapState(depState)) const nextReducerState = reducer(value,action,nextDependenciesStatesUnwrapped) if ( nextReducerState != null && typeof nextReducerState === 'object' && typeof nextReducerState.__dependencies !== 'undefined') { throw new Error('A reducer that depends on other reducers should not return an object with the __dependencies' + ' attribute as it is a reserved attribute name used by the library') } return wrapState(nextReducerState,nextDependenciesState) } return reducerMemoizer(liftedReducer) }
slorber/rereduce
src/index.js
JavaScript
mit
2,970
/** * Created by zhaopengsong on 2016/12/30. */ /** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Platform, TouchableOpacity, Image, WebView } from 'react-native'; var ShopDetail = React.createClass({ getInitialState(){ return{ detailUrl:this.props.url+'?uuid=5C7B6342814C7B496D836A69C872202B5DE8DB689A2D777DFC717E10FC0B4271&utm_term=6.6&utm_source=AppStore&utm_content=5C7B6342814C7B496D836A69C872202B5DE8DB689A2D777DFC717E10FC0B4271&version_name=6.6&userid=160495643&utm_medium=iphone&lat=23.134709&utm_campaign=AgroupBgroupD100Ghomepage_shoppingmall_detailH0&token=b81UqRVf6pTL4UPLLBU7onkvyQoAAAAAAQIAACQVmmlv_Qf_xR-hBJVMtIlq7nYgStcvRiK_CHFmZ5Gf70DR47KP2VSP1Fu5Fc1ndA&lng=113.373890&f=iphone&ci=20&msid=0FA91DDF-BF5B-4DA2-B05D-FA2032F30C6C2016-04-04-08-38594', detailurl :'https://'+'www.baidu.com', } }, render() { // alert(this.props.url); return ( <View style={styles.container}> {/*导航*/} {this.renderNavBar()} <WebView automaticallyAdjustContentInsets={true} source={{uri:this.state.detailurl}} javaScriptEnabled={true} domStorageEnabled={true} decelerationRate="normal" startInLoadingState={true} /> </View> ); }, // 导航条 renderNavBar(){ return( <View style={styles.navOutViewStyle}> <TouchableOpacity onPress={()=>{this.props.navigator.pop()}} style={styles.leftViewStyle}> <Image source={{uri: 'icon_camera_back_normal'}} style={styles.navImageStyle}/> </TouchableOpacity> <Text style={{color:'white', fontSize:16, fontWeight:'bold'}}>购物中心详情</Text> <TouchableOpacity onPress={()=>{alert('点了!')}} style={styles.rightViewStyle}> <Image source={{uri: 'icon_mine_setting'}} style={styles.navImageStyle}/> </TouchableOpacity> </View> ) } }); const styles = StyleSheet.create({ container: { flex:1 }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, navImageStyle:{ width:Platform.OS == 'ios' ? 28: 24, height:Platform.OS == 'ios' ? 28: 24, }, leftViewStyle:{ // 绝对定位 position:'absolute', left:10, bottom:Platform.OS == 'ios' ? 15:13 }, rightViewStyle:{ // 绝对定位 position:'absolute', right:10, bottom:Platform.OS == 'ios' ? 15:13 }, navOutViewStyle:{ height: Platform.OS == 'ios' ? 64 : 44, backgroundColor:'rgba(255,96,0,1.0)', // 设置主轴的方向 flexDirection:'row', // 垂直居中 ---> 设置侧轴的对齐方式 alignItems:'center', // 主轴方向居中 justifyContent:'center' }, }); // 输出组件类 module.exports = ShopDetail;
HAPENLY/ReactNative-Source-code-Demo
BuyDemo/Component/Home/ZPshopCenterDetail.js
JavaScript
mit
3,263
var app = angular.module('myApp'); //ui-bootstrap app.controller( "resultsController",function($scope, $window, HttpServiceJsonp, searchResults, $routeParams, $timeout){ $scope.searchResultsWithGroups = searchResults.searchResultsWithGroups; $scope.searchResults = searchResults; $scope.sortType = "topOverlap"; $scope.terms_list = ""; if($scope.searchResultsWithGroups.length > 0){ for(var i=0; i< $scope.searchResultsWithGroups[0].geneSuperList.length; i++){ $scope.terms_list += $scope.searchResultsWithGroups[0].geneSuperList[i]["queryTerm"] + ","; } $scope.terms_list = $scope.terms_list.substring(0, $scope.terms_list.length - 1); } $scope.plotlyData = { "passThisDataAlong": {}, "passThisLayoutAlong": {}, "heatmapFullHeight": 1000, "heatmapFullWidth": 1000 }; $scope.info = { esIdInputVal: "", showVis: false, selectedConditionData: {"condition_item": {"cosmic_id": "1234", "gene": "ABC"}}, selectedConditionTissue: "Tissue", selectedConditionDisease: "Disease" }; $scope.showgraphSidebar = false; $scope.toggleSidebar = function() { $scope.showgraphSidebar = !$scope.showgraphSidebar; } $scope.searchAnalysis = { "results": "" }; $scope.showMoreResults = { 'genes': false, 'pathways': false, 'drugs': false, 'phenotypes': false, 'proteins': false, 'diseases': false, 'genomes': false, 'unknowns': false, 'smallScreen': true, 'drug_limit_direct_hits': 5, 'pagingClusterPage': 1, 'pagingConditionPage': 1, 'pagingAuthorPage': 1 }; $scope.$watch(function(){return searchResults.searchResultsWithGroups}, function(NewValue, OldValue){ //console.log(NewValue + ' ' + OldValue); $scope.searchResultsWithGroups = NewValue; $scope.terms_list = ""; if($scope.searchResultsWithGroups.length > 0){ for(var i=0; i< $scope.searchResultsWithGroups[0].geneSuperList.length; i++){ $scope.terms_list += $scope.searchResultsWithGroups[0].geneSuperList[i]["queryTerm"] + ","; } $scope.terms_list = $scope.terms_list.substring(0, $scope.terms_list.length - 1); } },true); $scope.pythonHost = python_host_global; //use variable from env.js $scope.showPeople = false; $scope.spinner = { 'heatmaploading': false, 'tmp1': true }; $scope.openPlotlyExternal = function(){ var hiddenForm = $('<div id="hiddenform" '+ 'style="display:none;">'+ '<form action="https://plot.ly/external" '+ 'method="post" target="_blank">'+ '<input type="text" '+ 'name="data" /></form></div>') .appendTo('body'); var graphData = JSON.stringify($scope.getPlotlyGraph()); hiddenForm.find('input').val(graphData); hiddenForm.find('form').submit(); hiddenForm.remove(); return false; }; var searchResultsCallback = function(){ $scope.searchResultsWithGroups = searchResults.searchResultsWithGroups; } $scope.hydratePeople = function(term, emphasizeInfoArray){ $scope.showPeople = !$scope.showPeople; //alert(term); if(showPeople){ var url = $scope.pythonHost + "/api/get/people/genecenter/lazysearch/hydrate/" + term + "?callback=JSON_CALLBACK"; var myrequest = HttpServiceJsonp.jsonp(url) .success(function (result) { emphasizeInfoArray = result; alert(emphasizeInfoArray); }).finally(function () { }).error(function (data, status, headers, config) { alert(data + ' - ' + status + ' - ' + headers); }); } }; $scope.getPlotlyGraph = function(){ return { data: $scope.plotlyData.passThisDataAlong, layout: $scope.passThisLayoutAlong }; }; $scope.resizeDirective = function() { $timeout(function() { rescale(); }, 200); } $scope.resizeHeatMap = function() { var heatMapDiv = $('#heatmap').width($scope.plotlyData.heatmapFullWidth).height($scope.plotlyData.heatmapFullHeight); var update = { width: $scope.plotlyData.heatmapFullWidth, // or any new width height: $scope.plotlyData.heatmapFullHeight // " " }; Plotly.relayout('heatmap', update); } $scope.heatmapTabClick3 = function(esId, heatmap_title) { //AVCLoiXeOvM8reJwt0oQ $('#heatmapIsLoading').html('<span class="fa fa-spinner fa-2x fa-pulse"></span>'); var url = $scope.pythonHost + "/nav/elasticsearch/getheatmap3/" + esId + "?callback=JSON_CALLBACK"; $('#heatmap').css( "display", "none" ); var myrequest = HttpServiceJsonp.jsonp(url) .success(function (result) { $('#heatmapIsLoading').html('<h4>Cluster - ' + heatmap_title + '</h4>'); width = 2 * 830; height = 2 * 833; if(height > 800){ height = 570; } $scope.plotlyData.heatmapFullHeight = 22 * result.yValues.length + 180; if(width > 800){ width = 570; } $scope.plotlyData.heatmapFullWidth = 22 * result.xValues.length + 100; $('#heatmap').width(width).height(height); var xValues = result.xValues; var yValues = result.yValues; var zValues = result.zValues; var colorscaleValue = [ [0, '#ee4035'], [1, '#0392cf'] ]; var data = [{ x: xValues, y: yValues, z: zValues, type: 'heatmap', autocolorscale: false, //zsmooth: 'fast', colorscale: 'Picnic', zmax: 1.0, zmin: -1.0 }]; var layout = { title: '', annotations: [], xaxis: { ticks: '', side: 'top', width: 700, height: 700, autosize: true }, yaxis: { ticks: '', ticksuffix: ' ', width: 700, height: 700, autosize: true } }; $scope.plotlyData.passThisDataAlong = data; $scope.passThisLayoutAlong = layout; Plotly.newPlot('heatmap', data, layout, {showLink: false}); $('#heatmap').css( "display", "block" ); }).finally(function () { }).error(function (data, status, headers, config) { alert(data + ' - ' + status + ' - ' + headers); }); }; $scope.getNetworkEnrichment = function(esId){ var url = $scope.pythonHost + "/api/elasticsearch/getclusterenrichmentbyid/" + esId + "?callback=JSON_CALLBACK"; var myrequest = HttpServiceJsonp.jsonp(url) .success(function (result) { $scope.modalData = result; }).finally(function () { }).error(function (data, status, headers, config) { alert(data + ' - ' + status + ' - ' + headers); }); }; $scope.setModalData = function (setThisData) { $scope.modalData = setThisData; }; $scope.getSearchAnalysis = function(){ var url = $scope.pythonHost + "/search/clusters/GATA1,GATA2,GATA3?callback=JSON_CALLBACK"; var myrequest = HttpServiceJsonp.jsonp(url) .success(function (result) { $scope.searchAnalysis.results = result; }).finally(function () { }).error(function (data, status, headers, config) { alert(data + ' - ' + status + ' - ' + headers); }); }; $scope.renderCytoscape = function(geneTitle){ cytoObj = { layout: { name: 'cose', animate: true, randomize: true, numIter: 100, initialTemp: 50, animationDuration: 50}, style: [{ selector: 'node', style: { 'content': 'data(shortName)', 'text-wrap': 'wrap','width': 'mapData(score, 5, 70, 20, 50)', 'height': 'mapData(score, 5, 70, 20, 50)', 'text-valign': 'center','color': 'white', 'text-outline-width': 2, 'background-color': 'mapData(score, 5, 20, #034261, #79cbf2)', 'text-outline-color': 'mapData(score, 5, 20, #034261, #79cbf2)', 'font-size': 6} } ], elements: [], container: document.getElementById('cy') }; var cytoObj2 = { elements: [ {"data": {"shortName": "LOC100188947", "id": "LOC100188947;HECTD2:10-93169999", "score": 0.5}, "group": "nodes"}, {"data": {"shortName": "MAEA", "id": "MAEA:4-1309340", "score": 0.4}, "group": "nodes"} ] }; var geneId = $routeParams.id; //var url2 = $scope.pythonHost + "/nav/elasticsearch/cytoscape/star/" + geneTitle.replace(':','') + "?callback=JSON_CALLBACK"; var url2 = $scope.pythonHost + "/nav/elasticsearch/cytoscape/star/" + geneId.replace(':','') + "?callback=JSON_CALLBACK"; var myrequest = HttpServiceJsonp.jsonp(url2) .success(function (result) { cytoObj['elements'] = result; cy = cytoscape(cytoObj); var options = {}; cy.makeLayout(options); cy.panningEnabled(true); }).finally(function () { }).error(function (data, status, headers, config) { alert(data + ' - ' + status + ' - ' + headers); }); }; $scope.setConditionInfoModal = function(){ var w = angular.element($window); var useThisHeight = w.height() - 75; $('#conditionsModalBody').height(useThisHeight); }; $scope.setIFrameContent = function(setThisParm) { var w = angular.element($window); var useThisHeight = w.height() - 68; var useThisWidth = w.width() - 18; $('#myModalBody').html("<iframe src='about:blank' width='" + useThisWidth + "' height='" + useThisHeight + "' style='height: 100%; width: 100%;' frameborder='0' allowtransparency='true' id='myIFrame' name='contentframe'></iframe>"); $('#myModal').css('height', $scope.info.windowHeight); historySize = window.history.length; var termIdTitle = GetQueryStringParams(setThisParm, "termId"); var itemClicked = GetQueryStringParams(setThisParm, "currentTab"); var title = GetQueryStringParams(setThisParm, "title"); if(termIdTitle.length > 35) { termIdTitle = termIdTitle.substring(0, 34) + "..."; } var modalTitle = "&nbsp;&nbsp;&nbsp;&nbsp;" + termIdTitle + " &nbsp;&nbsp"; if($scope.currentTab === "PEOPLE_GENE") { modalTitle = modalTitle + "<small><a href='https://www.google.com/webhp?hl=en#safe=off&hl=en&q=" + termIdTitle + "' target='_blank'>Author information</a> (opens in a new window)</small>"; } else if(itemClicked === "CONDITION"){ modalTitle = "&nbsp;&nbsp;&nbsp;&nbsp;" + title + " &nbsp;&nbsp"; } else if(itemClicked != "PEOPLE_GENE"){ modalTitle = "&nbsp;&nbsp;&nbsp;&nbsp;" + termIdTitle + " &nbsp;&nbsp"; } $('#myModalLabel').html(modalTitle); //$('.modal').on('shown.bs.modal',function(){ //correct here use 'shown.bs.modal' event which comes in bootstrap3 // $(this).find('iframe').attr('src',"/partials/" + setThisParm); //}); $timeout(function() { $("#myModalBody").find('iframe').attr('src',"partials/" + setThisParm); //var myTemp = $("#myClusterModalBody").find('iframe').attr('src'); }, 200); }; $scope.setExternalIFrameContent = function(setThisParm) { $('#myModalBody').html("<iframe src='about:blank' width='100%' height='600' frameborder='0' allowtransparency='true' id='myIFrame' name='contentframe'></iframe>"); historySize = window.history.length; var termIdTitle = GetQueryStringParams(setThisParm, "termId"); if(termIdTitle.length > 35) { termIdTitle = termIdTitle.substring(0, 34) + "..."; } var modalTitle = "&nbsp;&nbsp;&nbsp;&nbsp;" + termIdTitle + " &nbsp;&nbsp"; if($scope.currentTab == "PEOPLE_GENE") { modalTitle = modalTitle + "<small><a href='https://www.google.com/webhp?hl=en#safe=off&hl=en&q=" + termIdTitle + "' target='_blank'>Author information</a> (opens in a new window)</small>"; } $('#myModalLabel').html(modalTitle); //$('.modal').on('shown.bs.modal',function(){ //correct here use 'shown.bs.modal' event which comes in bootstrap3 // $(this).find('iframe').attr('src',"/partials/" + setThisParm); //}); $timeout(function() { $("#myModalBody").find('iframe').attr('src',setThisParm); //var myTemp = $("#myClusterModalBody").find('iframe').attr('src'); }, 200); }; $scope.setClusterIFrameContent = function(setThisParm, esId, overlapGenes) { var w = angular.element($window); var useThisHeight = w.height() - 68; var useThisWidth = w.width() - 18; $('#myClusterModalBody').html("<iframe src='about:blank' width='" + useThisWidth + "' height='" + useThisHeight + "' style='overflow-x: hidden; overflow-y: hidden;' frameborder='0' allowtransparency='true' id='myIFrame' name='contentframe'></iframe>"); $('#myClusterModal').css('height', $scope.info.windowHeight); historySize = window.history.length; var termIdTitle = GetQueryStringParams(setThisParm, "termId"); //var overlapGenes = GetQueryStringParams(setThisParm, "geneList"); //$('#esIdInput').val(esId); searchResults.info.esIdInput = esId; searchResults.info.overlap = overlapGenes; searchResults.info.winHeight = useThisHeight; //$scope.info.esIdInputVal = esId; console.log("searchResultsController"); if(termIdTitle.length > 35) { termIdTitle = termIdTitle.substring(0, 34) + "..."; } var modalTitle = "&nbsp;&nbsp;&nbsp;&nbsp;<span style='white-space: nowrap;'>" + termIdTitle + "</span> &nbsp;&nbsp"; $('#modalTitle').html(modalTitle); // $('.modal').on('shown.bs.modal',function(){ //correct here use 'shown.bs.modal' event which comes in bootstrap3 // $(this).find('iframe').attr('src',setThisParm); // }); $timeout(function() { $("#myClusterModalBody").find('iframe').attr('src',"partials/" + setThisParm); //var myTemp = $("#myClusterModalBody").find('iframe').attr('src'); }, 200); }; function GetQueryStringParams(sPageURL, sParam) { var queryTerms = sPageURL.split('?'); if(queryTerms.length > 1){ var sURLVariables = queryTerms[1].split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam) { return sParameterName[1]; } } } else { return "" } } });
ucsd-ccbb/Oncolist
src/frontEndUI/Prod/js/appResultsCtrl.js
JavaScript
mit
15,448
var $ = {}; var TweenMax = {}; var PIXI = {}; var Box2D = {};
mkvster/funny-rain
test/src/libStub.js
JavaScript
mit
62
var should = require("should"), sinon = require("sinon"); require("../DeepAssoc.js"); describe('Consoloid.Base.DeepAssoc', function() { var env, assoc; beforeEach(function() { env = new Consoloid.Test.Environment(); }); describe('#constructor()', function() { it('should accept initial value in value option', function() { assoc = env.create('Consoloid.Base.DeepAssoc', { value: { foo: 'bar' } }); assoc.value .should.eql({ foo: 'bar' }); }); }); describe('#get(path, defaultValue)', function() { beforeEach(function() { assoc = env.create('Consoloid.Base.DeepAssoc', { value: { foo: 'bar', test: { deep: { item: 'testValue' } }, to: { be: { or: { not: { to: 'be' } } } } } }); }); it('should return value on path', function() { assoc.get('test/deep/item') .should.equal('testValue'); assoc.get('foo') .should.equal('bar'); assoc.get('to/be/or/not/to') .should.equal('be'); }); it('should return default value when path does not exist', function() { assoc.get('nonexistent/path', 'defval') .should.equal('defval'); }); it('should use delimiter given in constructor', function() { assoc = env.create('Consoloid.Base.DeepAssoc', { delimiter: '.', value: { foo: 'bar', test: { deep: { item: 'testValue' } } } }); assoc.get('test.deep.item') .should.equal('testValue'); }); describe('should return complete value object', function() { beforeEach(function() { assoc = env.create('Consoloid.Base.DeepAssoc', { value: { foo: 'bar' } }); }); it('for / path', function() { assoc.get('/') .should.eql({ foo: 'bar' }); }); it('for empty path', function() { assoc.get('') .should.eql({ foo: 'bar' }); }); }); it('should throw error when path is not a string', function() { assoc = env.create('Consoloid.Base.DeepAssoc', { }); (function() { assoc.get({}); }) .should.throwError(/path must be a string/); }); }); describe('#set(path, value)', function() { beforeEach(function() { assoc = env.create('Consoloid.Base.DeepAssoc', {}); }); it('should set value on path', function() { assoc.set('test/path', { something: 'interesting'}); assoc.get('test/path/something') .should.equal('interesting'); assoc.set('test/other', 'value'); assoc.get('test/other') .should.equal('value'); }); it('should throw error when item on path is not object', function() { assoc.set('test/path', { something: 'interesting'}); (function() { assoc.set('test/path/something/bad/path', 'error'); }) .should.throwError(/is not an object/); (function() { assoc.set('test/path/something/bad', 'error'); }) .should.throwError(/is not an object/); }); }); describe('#require(path, type)', function() { beforeEach(function() { assoc = env.create('Consoloid.Base.DeepAssoc', { value: { str: 'string', bool0: true, bool1: false, obj0: {}, obj1: env.create('Consoloid.Base.Object', {}) }}); }); it('should return string when string is required', function() { assoc.require('str', 'string') .should.be.type('string'); }); it('should return boolean when boolean is required', function() { assoc.require('bool0', 'bool') .should.be.type('boolean'); assoc.require('bool1', 'boolean') .should.be.type('boolean'); }); it('should return object when object is required', function() { assoc.require('obj0', 'Object') .should.be.type('object'); assoc.require('obj1', 'Consoloid.Base.Object') .should.be.type('object'); }); it('should require object when type is not given', function() { assoc.require('obj0') .should.be.type('object'); assoc.require('obj1') .should.be.type('object'); }); it('should throw error when string is not present but required', function() { (function() { assoc.require('obj0', 'string'); }) .should.throwError(/is not a string/); }); it('should throw error when boolean is not present but required', function() { (function() { assoc.require('obj0', 'bool'); }) .should.throwError(/is not a boolean/); }); it('should throw error when object is not present but required', function() { (function() { assoc.require('bool0', 'Object'); }) .should.throwError(/is not an object with required class/); }); }); describe('#remove(path, notRequired)', function(){ beforeEach(function() { assoc = env.create('Consoloid.Base.DeepAssoc', { value: { foo: 'bar', test: { deep: { item: 'testValue' } } } }); }); it('should remove the whole content is the path is empty', function(){ assoc.remove(''); assoc.get('foo', 'removed').should.be.eql('removed'); assoc.get('test/deep/item', 'removed').should.be.eql('removed'); assoc.set('new/value', 'foo'); assoc.get('new/value').should.be.eql('foo'); }); it('should remove the content of the path', function(){ assoc.remove('test/deep'); assoc.get('test/deep/item', 'removed').should.be.eql('removed'); assoc.get('test/deep', 'removed').should.be.eql('removed'); assoc.get('test', 'notRemoved').should.be.eql({}); assoc.get('foo', 'notRemoved').should.be.eql('bar'); }); it('should return the removed value', function(){ assoc.remove('test/deep').should.be.eql({item: 'testValue'}); }); it('should throw exception if the removable element is not exists', function(){ (function(){ should.strictEqual(assoc.remove('test/korte')); }).should.throw(); (function(){ should.strictEqual(assoc.remove('alma/korte')); }).should.throw(); }); it('should not throw exception if the removable element is not exists and the notRequired argument is true', function(){ should.strictEqual(assoc.remove('test/korte', true)); should.strictEqual(assoc.remove('alma/korte', true)); }); }); describe('#merge(object)', function(){ it('should extend the current value object with the given object', function(){ assoc = env.create('Consoloid.Base.DeepAssoc', { value: {foo: 'bar', foo2: 'bar2', obj: {subFoo: 'bar'}}}); assoc.merge({foo: 'alma', foo3: 'bar3', obj: {subFoo2: 'bar2' }}); assoc.get('foo').should.be.eql('alma'); assoc.get('foo2').should.be.eql('bar2'); assoc.get('foo3').should.be.eql('bar3'); assoc.get('obj/subFoo').should.be.eql('bar'); assoc.get('obj/subFoo2').should.be.eql('bar2'); }); }); afterEach(function() { env.shutdown(); }); });
agmen-hu/consoloid-framework
Consoloid/Base/test/DeepAssocTest.js
JavaScript
mit
7,244
if (!Array.slice){ Array.slice = function(enumerable,a,b){ return Array.prototype.slice.call(enumerable,a,b) } }
deadlyicon/STDLIB.js
src/Array/slice.js
JavaScript
mit
121
const mysql = require('mysql'); // 与数据库交互 const jsonfile = require('jsonfile'); // 生成 json 文件 const schedule = require('node-schedule'); // 定时任务 const path = require('path'); const config = require('./config'); // 使用连接池,提升性能 let pool = mysql.createPool(config.mysql); // 查询语句 let sql = { queryList: 'SELECT * FROM demo_info', queryId: 'SELECT * FROM demo_info WHERE id=?', insertInfo: 'INSERT INTO demo_info(title, type, content, tag, image, previewUrl, pageUrl, packageUrl, time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' }; // 向前台返回JSON方法的简单封装 let sendMsg = function (res, ret) { if(typeof ret === 'undefined') { res.json({ code:'1', msg: '操作失败' }); } else { res.json(ret); } }; jsonfile.spaces = 4; module.exports = { queryList: function() { // 查询首页列表数据 pool.getConnection(function(err, connection) { // 建立连接,查询数据库 connection.query(sql.queryList, function(err, ret) { if(err) throw err; let file = path.join(__dirname, '/cache/list.json'); // 定时执行查询任务并缓存数据 schedule.scheduleJob('0 * * * * *', function() { jsonfile.writeFile(file, ret, function(err) { console.log('查询数据完成'); }) }); connection.release(); // 释放连接 }); }); }, queryId: function(req, res) { // 指定 ID 查询数据 let {id} = req.body; pool.getConnection(function(err, connection) { connection.query(sql.queryId, id, function(err, ret) { if(err) throw err; if(ret.length > 0) { res.json(ret); } else { res.json({"msg": 0}); } connection.release(); }); }); }, insertInfo: function(req, res) { let {title, type, content, tag, image, previewUrl, pageUrl, packageUrl, time} = req.body; pool.getConnection(function(err, connection) { connection.query(sql.insertInfo, [title, type, content, tag, image, previewUrl, pageUrl, packageUrl, time], function(err, ret) { if(err) throw err; res.json({"msg": 1}); connection.release(); }); }); } }
varxzy/demo-center
Server/business.js
JavaScript
mit
2,545
test('Open Menu 1', function() { var menu1 = $(menu).find('li:nth-child(1)'); ok(menu1[0], "Menu option 'Menu Link 2'"); equal(menu1.children('a').attr('href'), 'http://menu1.domain.com', "Target URL 'http://menu1.domain.com' is expected"); ok(menu1.hasClass('menu_hover_off'), "<li> contains required class 'menu_hover_off' by default"); ok(menu1.trigger('mouseover'), "Mouse event 'over'"); ok(menu1.hasClass('menu_hover_on'), "<li> contains required class 'menu_hover_on'"); var submenu = menu1.children('ul'); ok(!submenu[0], 'Submenu elements are not expected'); ok(menu1.trigger('mouseout'), "Mouse event 'out'"); ok(menu1.hasClass('menu_hover_off'), "<li> contains required class 'menu_hover_off'"); }); test('Open Menu 2', function() { var menu2 = $(menu).find('li:nth-child(2)'); ok(menu2[0], "Menu option 'Menu Link 2'"); equal(menu2.children('a').attr('href'), 'http://menu2.domain.com', "Target URL 'http://menu2.domain.com' is expected"); ok(menu2.hasClass('menu_hover_off'), "<li> contains required class 'menu_hover_off' by default"); ok(menu2.trigger('mouseover'), "Mouse event 'over'"); ok(menu2.hasClass('menu_hover_on'), "<li> contains required class 'menu_hover_on'"); var submenu = menu2.children('ul'); ok(!submenu[0], 'Submenu elements are not expected'); ok(menu2.trigger('mouseout'), "Mouse event 'out'"); ok(menu2.hasClass('menu_hover_off'), "<li> contains required class 'menu_hover_off'"); }); test('Open Menu 3', function() { var menu3 = $(menu).find('li:nth-child(3)'); ok(menu3[0], "Menu option 'Menu List A'"); ok(!menu3.children('a').attr('href'), "Target URL is not expected"); ok(menu3.hasClass('menu_hover_off'), "<li> contains required class 'menu_hover_off' by default"); ok(menu3.trigger('mouseover'), "Mouse event 'over'"); stop(); setTimeout(function() { ok(menu3.hasClass('menu_hover_on'), "<li> contains required class 'menu_hover_on'"); ok(menu3.hasClass('submenu_hover_on'), "<li> contains required class 'submenu_hover_on'"); var submenuA = menu3.children('ul'); ok(submenuA[0], 'Submenu elements are expected'); ok(menu3.prop('visible'), "'Menu List A' options are visible"); ok(submenuA.hasClass('menu_list'), "<ul> contains required class 'menu_list'"); var menuA_sub1 = submenuA.find('li:nth-child(1)'), menuA_sub2 = submenuA.find('li:nth-child(2)'), menuA_sub3 = submenuA.find('li:nth-child(3)'); ok(menuA_sub1[0], "Menu option 'Item 1A'"); ok(menuA_sub1.trigger('mouseover'), "Mouse event 'mouseover'"); equal(menuA_sub1.children('a').attr('href'), 'http://item1A.domain.com', "Target URL 'http://item1A.domain.com' is expected"); ok(menuA_sub2[0], "Menu option 'Item 2A'"); ok(menuA_sub2.trigger('mouseover'), "Mouse event 'mouseover'"); equal(menuA_sub2.children('a').attr('href'), 'http://item2A.domain.com', "Target URL 'http://item2A.domain.com' is expected"); ok(menuA_sub3[0], "Menu option 'Menu List B'"); start(); ok(menuA_sub3.trigger('mouseover'), "Mouse event 'over'"); stop(); setTimeout(function() { ok(menuA_sub3.hasClass('submenu'), "<li> contains required class 'submenu'"); ok(menuA_sub3.hasClass('submenu_hover_on'), "<li> contains required class 'submenu_hover_on'"); var submenuB = menuA_sub3.children('ul'); ok(submenuB[0], 'Submenu elements are expected'); ok(menu3.prop('visible'), "Options are visible"); ok(submenuB.hasClass('menu_list'), "<ul> contains required class 'menu_list'"); var menuB_sub1 = submenuB.find('li:nth-child(1)'), menuB_sub2 = submenuB.find('li:nth-child(2)'); ok(menuB_sub1[0], "Menu option 'Item 1B'"); ok(menuB_sub1.trigger('mouseover'), "Mouse event 'over'"); equal(menuB_sub1.children('a').attr('href'), 'http://item1B.domain.com', "Target URL 'http://item1B.domain.com' is expected"); ok(menuB_sub2[0], "Menu option 'Item 2B'"); ok(menuB_sub2.trigger('mouseover'), "Mouse event 'mouseover'"); equal(menuB_sub2.children('a').attr('href'), 'http://item2B.domain.com', "Target URL 'http://item2B.domain.com.com' is expected"); start(); ok(menuA_sub3[0], "Menu option 'Menu List B'"); ok(menuA_sub3.trigger('mouseout'), "Mouse event 'out'"); stop(); setTimeout(function() { ok(menuA_sub3.hasClass('submenu_hover_off'), "<li> contains required class 'submenu_hover_off'"); ok(!submenuB.prop('visible'), 'Submenu B options are not visible'); start(); ok(menu3[0], "Menu option 'Menu List A'"); ok(menu3.trigger('mouseout'), "Mouse event 'out'"); stop(); setTimeout(function() { ok(menu3.hasClass('menu_hover_off'), "<li> contains required class 'menu_hover_off'"); start(); }, 500); }, 500); }, 100); }, 100); });
nuxy/EZ-Menu
test/plugin/events.js
JavaScript
mit
4,941
for(var i = 1; i <= 100; i++){ // start at 1; run code until reached 100, stop when reached 101; add 1 if(i % 3 == 0 && i % 5 == 0){ // if i = divisible by 3 and divisible by 5 log FizzBuzz console.log("FizzBuzz"); } else if(i % 3 == 0) { // if i = a multiple of 3 only, log Fizz console.log("Fizz"); } else if (i % 5 == 0) { // if i = a multiple of 5 only, log Buzz console.log("Buzz"); } else { // in any other case log i (the integer) console.log(i); } } /* Note to self: --- interesting Eloquent JavaScript solution --- for (var n = 1; n <= 100; n++) { var output = ""; if (n % 3 == 0) output += "Fizz"; if (n % 5 == 0) output += "Buzz"; console.log(output || n); } --- a second interesting solution: --- for (var i = 1; i <= 100; i++) { var f = i % 3 == 0, b = i % 5 == 0; console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i); } --- a third interesting solution: --- for(i=0;i<100;)console.log((++i%3?'':'Fizz')+(i%5?'':'Buzz')||i) */
InekeScheffers/NYCDA-individual-assignments
09-27-2016-FizzBuzz/FizzBuzz_Ineke.js
JavaScript
mit
992
document.getElementById('video-player').innerHTML = '<video id="special"></video> <div id="media-controls"> <div class="control"> <div id="play-pause" onclick="togglePlay();" class="control-button"> <i id="play-icon" class="ion-play"></i> </div> <div id="volume" onclick="togglePlay();" class="control-button"> <i id="vol-icon" class="ion-volume-medium"></i> </div> <div id="fullscreen" onclick="toggleFullscreen();" class="control-button"> <i class="ion-android-expand"></i> </div> </div> <div id="progress"> <progress value="0" max="100" id="progBar"></progress> </div> </div>' video = document.getElementById('special'); video.src = "../app/video/video.mp4"; //// Create JQuery link if it's needed. if (!window.jQuery) { var script = document.createElement('script'); script.src = '../app/jquery-3.2.1.min.js'; document.getElementsByTagName('head')[0].appendChild(script); } //// Create link to video style. var css = document.createElement('link'); css.href = '../app/style/style.css'; css.rel = 'stylesheet'; document.getElementsByTagName('head')[0].appendChild(css); //// Create link to Ionic icons css. var font = document.createElement('link'); font.href = '../app/icons/ionicons.min.css'; font.rel = 'stylesheet'; document.getElementsByTagName('head')[0].appendChild(font); window.onload = function() { //// Update progressbar ever .2 sec. progressBar = document.getElementById('progBar'); setInterval(function() { updateProgress(); }, 200); //// Make progressbar clickable to jump progress. progressBar.addEventListener('click', function (e) { var value_clicked = e.offsetX * this.max / this.offsetWidth; progressBar.setAttribute("value", value_clicked); video.currentTime = value_clicked; }); //// Make media-controls same width/height as video width/height. $("#special").bind("loadedmetadata", function () { var width = this.offsetWidth; var height = this.offsetHeight; document.getElementById('media-controls').setAttribute('style','width: ' + width + 'px; height:' + height + 'px;'); }); //// Show/Disappear mediacontrols on hover. $('#video-player').hover( function() { $('#media-controls').stop().animate({ opacity: 1 }, 100); }, function() { $('#media-controls').stop().animate({ opacity: 0 }, 1000); } ); } function togglePlay() { var icon = document.getElementById('play-icon'); if (video.paused || video.ended) { icon.className = 'ion-pause'; video.play(); } else { icon.className = 'ion-play'; video.pause(); } } function toggleFullscreen() { if (video.requestFullscreen) { video.requestFullscreen(); } else if (video.webkitRequestFullscreen) { video.webkitRequestFullscreen(); } else if (video.mozRequestFullScreen) { video.mozRequestFullScreen(); } else if (video.msRequestFullscreen) { video.msRequestFullscreen(); } } function updateProgress() { progressBar.setAttribute("max", video.duration); progressBar.setAttribute("value", video.currentTime); }
LordVissie/Special-VideoPlayer
app/main.js
JavaScript
mit
3,179