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-flexberry-designer/controllers/fd-interface-edit-form/new';
Flexberry/ember-flexberry-designer
app/controllers/fd-interface-edit-form/new.js
JavaScript
mit
91
var today = new Date(); console.log(today);
johnvoon/launch_school
210/lesson5/date_ex1.js
JavaScript
mit
43
var RocketBoots = { isInitialized : false, readyFunctions : [], components : {}, loadedScripts: [], version: {full: "0.7.0", major: 0, minor: 7, patch: 0, codeName: "sun-master"}, _autoLoadRequirements: true, _initTimer : null, _MAX_ATTEMPTS : 300, _BOOTING_ELEMENT_ID : "booting-up-rocket-boots", _: null, // Lodash $: null, // jQuery //==== Classes Component : function(c){ this.fileName = c; this.name = null; this.isLoaded = false; this.isInstalled = false; }, //==== General Functions log : console.log, loadScript : function(url, callback){ //console.log("Loading script", url); // http://stackoverflow.com/a/7719185/1766230 var o = this; var s = document.createElement('script'); var r = false; var t; s.type = 'text/javascript'; s.src = "scripts/" + url + ".js"; s.className = "rocketboots-script"; s.onload = s.onreadystatechange = function() { //console.log( this.readyState ); //uncomment this line to see which ready states are called. if ( !r && (!this.readyState || this.readyState == 'complete') ) { r = true; o.loadedScripts.push(url); if (typeof callback == "function") callback(); } }; t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s, t); return this; }, //==== Component Functions hasComponent: function (componentClass) { if (typeof RocketBoots[componentClass] == "function") { return true; } else { return false; } }, installComponent : function (options, callback, attempt) { // options = { fileName, classNames, requirements, description, credits } var o = this; var mainClassName = (typeof options.classNames === 'object' && options.classNames.length > 0) ? options.classNames[0] : (options.classNames || options.className); var componentClass = options[mainClassName]; var requirements = options.requirements; var fileName = options.fileName; var callbacks = []; var i; // Setup array of callbacks if (typeof callback === 'function') { callbacks.push(callback); } if (typeof options.callback === 'function') { callbacks.push(options.callback); } if (typeof options.callbacks === 'object') { callbacks.concat(options.callbacks); } // Check for possible errors if (typeof mainClassName !== 'string') { console.error("Error installing component: mainClassName is not a string", mainClassName, options); console.log("options", options); return; } else if (typeof componentClass !== 'function') { console.error("Error installing component: class name", mainClassName, "not found on options:", options); console.log("options", options); return; } //console.log("Installing", fileName, " ...Are required components", requirements, " loaded?", o.areComponentsLoaded(requirements)); if (!o.areComponentsLoaded(requirements)) { var tryAgainDelay, compTimer; if (typeof attempt === "undefined") { attempt = 1; } else if (attempt > o._MAX_ATTEMPTS) { console.error("Could not initialize RocketBoots: too many attempts"); return false; } else { attempt++; } if (o._autoLoadRequirements) { console.log(fileName, "requires component(s)", requirements, " which aren't loaded. Autoloading..."); o.loadComponents(requirements); tryAgainDelay = 100 * attempt; } else { console.warn(fileName, "requires component(s)", requirements, " which aren't loaded."); tryAgainDelay = 5000; } compTimer = window.setTimeout(function(){ o.installComponent(options, callback, attempt); }, tryAgainDelay); } else { if (typeof o.components[fileName] == "undefined") { o.components[fileName] = new o.Component(fileName); } /* for (i = 0; i < callbacks.length; i++) { if (typeof callbacks[i] === "function") { callbacks[i](); } } */ o.components[fileName].name = mainClassName; o.components[fileName].isInstalled = true; o.components[fileName].callbacks = callbacks; // TODO: Add description and credits //o.components[fileName].description = ""; //o.components[fileName].credits = ""; o[mainClassName] = componentClass; } return this; }, getComponentByName: function (componentName) { var o = this; for (var cKey in o.components) { if (o.components[cKey].name == componentName) { return o.components[cKey]; } }; return; }, areComponentsLoaded: function (componentNameArr) { var o = this, areLoaded = true; if (typeof componentNameArr !== 'object') { return areLoaded; } for (var i = 0; i < componentNameArr.length; i++) { if (!o.isComponentInstalled(componentNameArr[i])) { areLoaded = false; } }; return areLoaded; }, isComponentInstalled: function (componentName) { var comp = this.getComponentByName(componentName); return (comp && comp.isInstalled); }, loadComponents : function(arr, path){ var o = this; var componentName; path = (typeof path === 'undefined') ? "rocketboots/" : path; for (var i = 0, al = arr.length; i < al; i++){ componentName = arr[i]; if (typeof o.components[componentName] == "undefined") { o.components[componentName] = new o.Component(componentName); o.loadScript(path + arr[i], function(){ o.components[componentName].isLoaded = true; }); } else { //console.warn("Trying to load", componentName, "component that already exists."); } } return this; }, loadCustomComponents : function (arr, path) { path = (typeof path === 'undefined') ? "" : path; return this.loadComponents(arr, path); }, areAllComponentsLoaded : function(){ var o = this; var componentCount = 0, componentsInstalledCount = 0; for (var c in o.components) { // if (o.components.hasOwnProperty(c)) { do stuff } componentCount++; if (o.components[c].isInstalled) componentsInstalledCount++; } console.log("RB Components Installed: " + componentsInstalledCount + "/" + componentCount); return (componentsInstalledCount >= componentCount); }, //==== Ready and Init Functions ready : function(callback){ if (typeof callback == "function") { if (this.isInitialized) { callback(this); } else { this.readyFunctions.push(callback); } } else { console.error("Ready argument (callback) not a function"); } return this; }, runReadyFunctions : function(){ var o = this; // Loop over readyFunctions and run each one var f, fn; for (var i = 0; o.readyFunctions.length > 0; i++){ f = o.readyFunctions.splice(i,1); fn = f[0]; fn(o); } return this; }, init : function(attempt){ var o = this; // TODO: allow dependecies to be injected rather than forcing them to be on the window scope var isJQueryUndefined = (typeof $ === "undefined"); var isLodashUndefined = (typeof _ === "undefined"); var areRequiredScriptsMissing = isJQueryUndefined || isLodashUndefined; if (typeof attempt === "undefined") { attempt = 1; } else if (attempt > o._MAX_ATTEMPTS) { console.error("Could not initialize RocketBoots: too many attempts"); return false; } else { attempt++; } //console.log("RB Init", attempt, (areRequiredScriptsMissing ? "Waiting on required objects from external scripts" : "")); if (!isJQueryUndefined) { o.$ = $; o.$('#' + o._BOOTING_ELEMENT_ID).show(); } if (!isLodashUndefined) { o._ = _; o.each = o.forEach = _.each; } function tryAgain () { // Clear previous to stop multiple inits from happening window.clearTimeout(o._initTimer); o._initTimer = window.setTimeout(function(){ o.init(attempt); }, (attempt * 10)); } // On first time through, do some things if (attempt === 1) { // Create "rb" alias if (typeof window.rb !== "undefined") { o._rb = window.rb; } window.rb = o; // Aliases o.window = window; o.document = window.document; // Load default components // TODO: make this configurable this.loadComponents(["Game"]); // Load required scripts if (isJQueryUndefined) { o.loadScript("libs/jquery-2.2.4.min", function(){ //o.init(1); }); } if (isLodashUndefined) { o.loadScript("libs/lodash.min", function(){ }); } } if (o.areAllComponentsLoaded() && !areRequiredScriptsMissing) { console.log("RB Init - All scripts and components are loaded.", o.loadedScripts, "\nRunning component callbacks..."); // TODO: These don't necessarily run in the correct order for requirements o.each(o.components, function(component){ o.each(component.callbacks, function(callback){ console.log("Callback for", component.name); callback(); // TODO: Make this run in the right context? }); }); console.log("RB Init - Running Ready functions.\n"); o.$('#' + o._BOOTING_ELEMENT_ID).hide(); o.runReadyFunctions(); o.isInitialized = true; return true; } tryAgain(); return false; } }; RocketBoots.init();
Lukenickerson/rocketboots
scripts/rocketboots/core.js
JavaScript
mit
8,886
({ baseUrl: "../linesocial/public/js", paths: { jquery: "public/js/libs/jquery-1.9.1.js" }, name: "main", out: "main-built.js" })
jackygrahamez/LineSocialPublic
build.js
JavaScript
mit
157
/* exported Qualifications */ function Qualifications(skills, items) { var requirements = { 'soldier': { meta: { passPercentage: 100 }, classes: { 'Heavy Assault': { certifications: [ { skill: skills.heavyAssault.flakArmor, level: 3 } ], equipment: [] }, 'Light Assault': { certifications: [ { skill: skills.lightAssault.flakArmor, level: 3 } ], equipment: [] }, 'Engineer': { certifications: [ { skill: skills.engineer.flakArmor, level: 3 }, { skill: skills.engineer.nanoArmorKit, level: 4 }, { skill: skills.engineer.tankMine, level: 1 } ], equipment: [] }, 'Medic': { certifications: [ { skill: skills.medic.flakArmor, level: 3 }, { skill: skills.medic.medicalApplicator, level: 4 } ], equipment: [] }, 'Infiltrator': { certifications: [ { skill: skills.infiltrator.flakArmor, level: 3 } ], equipment: [] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.advancedMobileStation, level: 1 } ], equipment: [] }, 'Squad Leader': { certifications: [ { skill: skills.squadLeader.priorityDeployment, level: 0 } ], equipment: [] } } }, 'veteran': { meta: { passPercentage: 100 }, classes: { 'Heavy Assault': { certifications: [ { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.antiVehicleGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 1 } ], equipment: [] }, 'Light Assault': { certifications: [ { skill: skills.lightAssault.c4, level: 2 }, { skill: skills.lightAssault.drifterJumpJets, level: 2 } ], equipment: [] }, 'Engineer': { certifications: [ { skill: skills.engineer.nanoArmorKit, level: 6 }, { skill: skills.engineer.claymoreMine, level: 2 }, { skill: skills.engineer.tankMine, level: 2 }, { skill: skills.engineer.ammunitionPackage, level: 3 }, { skill: skills.engineer.stickyGrenade, level: 1 } ], equipment: [ items.weapon.trac5s, items.engineer.avManaTurret ] }, 'Medic': { certifications: [ { skill: skills.medic.medicalApplicator, level: 6 }, { skill: skills.medic.nanoRegenDevice, level: 6 } ], equipment: [] }, 'Infiltrator': { certifications: [ { skill: skills.infiltrator.advancedEquipmentTerminalHacking, level: 3 } ], equipment: [] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.vehicleAmmoDispenser, level: 1 }, { skill: skills.sunderer.blockadeArmor, level: 3 }, { skill: skills.sunderer.gateShieldDiffuser, level: 2 } ], equipment: [] }, 'Squad Leader': { certifications: [ { skill: skills.squadLeader.priorityDeployment, level: 2 } ], equipment: [] } } }, 'medic': { meta: { passPercentage: 100 }, classes: { 'Loadout: Offensive Medic': { certifications: [ { skill: skills.medic.grenadeBandolier, level: 2 }, { skill: skills.medic.naniteReviveGrenade, level: 1 }, { skill: skills.medic.nanoRegenDevice, level: 6 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [] }, 'Loadout: Defensive Medic': { certifications: [ { skill: skills.medic.flakArmor, level: 4 }, { skill: skills.medic.naniteReviveGrenade, level: 1 }, { skill: skills.medic.regenerationField, level: 5 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [] } } }, 'engineer': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry MANA Turret': { certifications: [ { skill: skills.engineer.flakArmor, level: 4 }, { skill: skills.engineer.claymoreMine, level: 2 } ], equipment: [ items.weapon.trac5s ] }, 'Loadout: Anti-Vehicle MANA Turret': { certifications: [ { skill: skills.engineer.flakArmor, level: 4 }, { skill: skills.engineer.tankMine, level: 2 }, { skill: skills.engineer.avManaTurret, level: 1 } ], equipment: [ items.weapon.trac5s, items.engineer.avManaTurret ] } } }, 'lightAssault': { meta: { passPercentage: 100 }, classes: { 'Loadout: Bounty Hunter': { certifications: [ { skill: skills.lightAssault.flakArmor, level: 4 }, { skill: skills.lightAssault.jumpJets, level: 6 }, { skill: skills.lightAssault.flashGrenade, level: 1 } ], equipment: [] }, 'Loadout: Death From Above': { certifications: [ { skill: skills.lightAssault.grenadeBandolier, level: 2 }, { skill: skills.lightAssault.drifterJumpJets, level: 5 }, { skill: skills.lightAssault.smokeGrenade, level: 1 } ], equipment: [] } } }, 'infiltrator': { meta: { passPercentage: 100 }, classes: { 'Loadout: Close Quarters': { certifications: [ { skill: skills.infiltrator.flakArmor, level: 4 }, { skill: skills.infiltrator.grenadeBandolier, level: 2 }, { skill: skills.infiltrator.reconDetectDevice, level: 6 }, { skill: skills.infiltrator.claymoreMine, level: 2 }, { skill: skills.infiltrator.empGrenade, level: 1 } ], equipment: [ items.weapon.ns7pdw ] }, 'Loadout: Assassin': { certifications: [ { skill: skills.infiltrator.ammunitionBelt, level: 3 }, { skill: skills.infiltrator.motionSpotter, level: 5 }, { skill: skills.infiltrator.claymoreMine, level: 2 }, { skill: skills.infiltrator.decoyGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [ items.weapon.rams ] } } }, 'heavyAssault': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry': { certifications: [ { skill: skills.heavyAssault.grenadeBandolier, level: 2 }, { skill: skills.heavyAssault.flakArmor, level: 4 }, { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.concussionGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [ items.weapon.decimator ] }, 'Loadout: Anti-Armor': { certifications: [ { skill: skills.heavyAssault.flakArmor, level: 4 }, { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.c4, level: 1 }, { skill: skills.heavyAssault.antiVehicleGrenade, level: 1 } ], equipment: [ items.weapon.skep, items.weapon.grounder ] } } }, 'maxUnit': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry': { certifications: [ { skill: skills.max.kineticArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftMercy, items.max.rightMercy ] }, 'Loadout: Anti-Armor': { certifications: [ { skill: skills.max.flakArmor, level: 5 }, { skill: skills.max.kineticArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftPounder, items.max.rightPounder ] }, 'Loadout: Anti-Air': { certifications: [ { skill: skills.max.flakArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftBurster, items.max.rightBurster ] } } }, 'basicTanks': { meta: { passPercentage: 100 }, classes: { 'Prowler': { certifications: [ { skill: skills.prowler.anchoredMode, level: 1 } ], equipment: [ items.prowler.walker ] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.vehicleAmmoDispenser, level: 1 }, { skill: skills.sunderer.gateShieldDiffuser, level: 2 } ], equipment: [] } } }, 'sunderer': { meta: { passPercentage: 100 }, classes: { 'Sunderer': { certifications: [ { skill: skills.sunderer.mineGuard, level: 4 }, { skill: skills.sunderer.blockadeArmor, level: 4 }, { skill: skills.sunderer.gateShieldDiffuser, level: 3 }, { skill: skills.sunderer.naniteProximityRepairSystem, level: 6 } ], equipment: [] } } }, 'prowler': { meta: { passPercentage: 100 }, classes: { 'Prowler': { certifications: [ { skill: skills.prowler.anchoredMode, level: 4 }, { skill: skills.prowler.mineGuard, level: 4 } ], equipment: [ items.prowler.p2120ap, items.prowler.halberd ] } } }, 'lightning': { meta: { passPercentage: 100 }, classes: { 'Lightning': { certifications: [ { skill: skills.lightning.reinforcedTopArmor, level: 1 } ], equipment: [ items.lightning.skyguard ] } } }, 'harasser': { meta: { passPercentage: 100 }, classes: { 'Harasser': { certifications: [ { skill: skills.harasser.fireSuppressionSystem, level: 4 }, { skill: skills.harasser.compositeArmor, level: 4 }, { skill: skills.harasser.turbo, level: 5 } ], equipment: [ items.harasser.halberd ] } } }, 'commander': { meta: { passPercentage: 100 }, classes: { 'Squad Leader': { certifications: [ { skill: skills.squadLeader.commandCommChannel, level: 1 }, { skill: skills.squadLeader.requestReinforcements, level: 1 }, { skill: skills.squadLeader.rallyPointGreen, level: 1 }, { skill: skills.squadLeader.rallyPointOrange, level: 1 }, { skill: skills.squadLeader.rallyPointPurple, level: 1 }, { skill: skills.squadLeader.rallyPointYellow, level: 1 }, { skill: skills.squadLeader.priorityDeployment, level: 4 } ], equipment: [] } } } }, echoHavoc = qual('Echo Havoc', null, null, true), max = qual('MAX', echoHavoc, requirements.maxUnit), heavyAssault = qual('Heavy Assault', max, requirements.heavyAssault), echoCovertOps = qual('Echo Covert Ops', null, null, true), infiltrator = qual('Infiltrator', echoCovertOps, requirements.infiltrator), lightAssault = qual('Light Assault', infiltrator, requirements.lightAssault), echoSpecialist = qual('Echo Specialist', null, null, true), engineer = qual('Engineer', echoSpecialist, requirements.engineer), combatMedic = qual('Combat Medic', engineer, requirements.medic), commander = qual('Commander', null, requirements.commander, true), sunderer = qual('Sunderer', [ echoSpecialist, echoCovertOps, echoHavoc ], requirements.sunderer), harasser = qual('Harasser', null, requirements.harasser), lightning = qual('Lightning', harasser, requirements.lightning), prowler = qual('Prowler', lightning, requirements.prowler), basicTanks = qual('Basic Tanks', [ sunderer, prowler ], requirements.basicTanks), veteran = qual('Veteran', [ combatMedic, lightAssault, heavyAssault, commander ], requirements.veteran, true), soldier = qual('Soldier', [ veteran, basicTanks ], requirements.soldier, true); addParentRelationships(soldier); return soldier; function qual(name, child, certs, isRank) { var obj = {}; obj.name = name; if (child) { if ($.isArray(child)) { obj.child = child; } else { obj.child = [ child ]; } } if (certs) { obj.cert = certs; } if (isRank) { obj.isRank = true; } return obj; } function addParentRelationships(rank, parent) { if (parent) { if (rank.parent) { rank.parent.push(parent); } else { rank.parent = [ parent ]; } } if (rank.child) { $.each(rank.child, function() { addParentRelationships(this, rank); }); } } }
stevenbenner/ps2-equipment-check
js/qualifications.js
JavaScript
mit
12,343
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const ConfigLoader = require( 'easy/core/ConfigLoader' ) const EventsEmitter = require( 'events' ) /** * @class Database */ class Database { /** * @constructor */ constructor( config ) { this._config = config this.stateEmitter = new EventsEmitter() this.name = config.config.name this.init() } /** * init - init attributes */ init() { this._instance = null this._connector = this._config.connector this.resetProperties() } /** * Reset instance and connected state * * @memberOf Database */ resetProperties() { this._connected = false this._connectionError = null } /** * load - load database config */ async start() { await this.connect() } /** * restart - restart database component */ async restart() { this.resetProperties() await this.start() } /** * connect - connect database to instance */ async connect() { const { instance, connected, error } = await this.config.connector() const oldConnected = this.connected this.instance = instance this.connected = connected this.connectionError = error if ( this.connected !== oldConnected ) { this.stateEmitter.emit( 'change', this.connected ) } if ( error ) { throw new Error( error ) } } /** * Reset database connection and instance * * @memberOf Database */ disconnect() { const oldConnected = this.connected this.resetProperties() if ( this.connected !== oldConnected ) { this.stateEmitter.emit( 'change', this.connected ) } } /** * verifyConnectionHandler - handler called by daemon which indicates if database still available or not * * @returns {Promise} * * @memberOf Database */ verifyConnectionHandler() { return this.config.verifyConnectionHandler() } /** * Branch handler on database state events * * @param {Function} handler * * @memberOf Database */ connectToStateEmitter( handler ) { this.stateEmitter.on( 'change', handler ) } /** * get - get database instance * * @returns {Object} */ get instance() { return this._instance } /** * set - set database instance * * @param {Object} instance * @returns {Object} */ set instance( instance ) { this._instance = instance return this._instance } /** * get - get database connection state * * @returns {Object} */ get connected() { return this._connected } /** * set - set database connection state * * @param {boolean} connected * @returns {Database} */ set connected( connected ) { this._connected = connected return this } /** * get - get database configurations * * @returns {Object} */ get config() { return this._config } /** * Get connection error * * @readonly * * @memberOf Database */ get connectionError() { return this._connectionError } /** * Set connection error * * @returns {Database} * * @memberOf Database */ set connectionError( error ) { this._connectionError = error return this } } module.exports = Database
MadDeveloper/easy.js
easy/database/Database.js
JavaScript
mit
3,837
import {writeFile} from 'fs-promise'; import {get, has, merge, set} from 'lodash/fp'; import flatten from 'flat'; import fs from 'fs'; import path from 'path'; const data = new WeakMap(); const initial = new WeakMap(); export default class Config { constructor(d) { data.set(this, d); initial.set(this, Object.assign({}, d)); } clone() { return Object.assign({}, data.get(this)); } get(keypath) { return get(keypath, data.get(this)); } has(keypath) { return has(keypath, data.get(this)); } inspect() { return data.get(this); } merge(extra) { data.set(this, merge(data.get(this), extra)); } set(keypath, value) { return set(keypath, data.get(this), value); } async save() { const out = this.toString(); return await writeFile(`.boilerizerc`, out); } toJSON() { const keys = Object.keys(flatten(data.get(this), {safe: true})); const init = initial.get(this); let target; try { const filepath = path.join(process.cwd(), `.boilerizerc`); // Using sync here because toJSON can't have async functions in it // eslint-disable-next-line no-sync const raw = fs.readFileSync(filepath, `utf8`); target = JSON.parse(raw); } catch (e) { if (e.code !== `ENOENT`) { console.error(e); throw e; } target = {}; } return keys.reduce((acc, key) => { if (!has(key, init) || has(key, target)) { const val = this.get(key); acc = set(key, val, acc); } return acc; }, target); } toString() { return JSON.stringify(this, null, 2); } }
ianwremmel/boilerize
src/lib/config.js
JavaScript
mit
1,639
// Karma configuration // Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'], plugins: [ 'karma-mocha', 'karma-chai', 'karma-sinon-chai', 'karma-chrome-launcher', 'karma-phantomjs-launcher', 'karma-jquery', 'karma-chai-jquery', 'karma-mocha-reporter' ], // list of files / patterns to load in the browser files: [ 'bower/angular/angular.js', 'bower/angular-sanitize/angular-sanitize.js', 'bower/angular-mocks/angular-mocks.js', 'dist/ac-components.min.js', 'test/unit/**/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
avalanche-canada/ac-components
karma-dist-minified.conf.js
JavaScript
mit
2,019
export default function _isString(obj) { return toString.call(obj) === '[object String]' }
jrpool/js-utility-underscore
src/objects/_isString.js
JavaScript
mit
93
var class_mock = [ [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "MOCK_METHOD0", "class_mock.html#ae710f23cafb1a2f17772e8805d6312d2", null ], [ "MOCK_METHOD1", "class_mock.html#ada59eea6991953353f332e3ea1e74444", null ], [ "MOCK_METHOD1", "class_mock.html#a2db4d82b6f92b4e462929f651ac4c3b1", null ], [ "MOCK_METHOD1", "class_mock.html#ae73b4ee90bf6d84205d2b1c17f0b8433", null ], [ "MOCK_METHOD1", "class_mock.html#a2cece30a3ea92b34f612f8032fe3a0f9", null ], [ "MOCK_METHOD1", "class_mock.html#ac70c052254fa9816bd759c006062dc47", null ], [ "MOCK_METHOD1", "class_mock.html#ae2379efbc030f1adf8b032be3bdf081d", null ], [ "MOCK_METHOD1", "class_mock.html#a3fd62026610c5d3d3aeaaf2ade3e18aa", null ], [ "MOCK_METHOD1", "class_mock.html#a890668928abcd28d4d39df164e7b6dd8", null ], [ "MOCK_METHOD1", "class_mock.html#a50e2bda4375a59bb89fd5652bd33eb0f", null ] ];
bhargavipatel/808X_VO
docs/html/class_mock.js
JavaScript
mit
1,000
import PartyBot from 'partybot-http-client'; import React, { PropTypes, Component } from 'react'; import cssModules from 'react-css-modules'; import styles from './index.module.scss'; import Heading from 'grommet/components/Heading'; import Box from 'grommet/components/Box'; import Footer from 'grommet/components/Footer'; import Button from 'grommet/components/Button'; import Form from 'grommet/components/Form'; import FormField from 'grommet/components/FormField'; import FormFields from 'grommet/components/FormFields'; import NumberInput from 'grommet/components/NumberInput'; import CloseIcon from 'grommet/components/icons/base/Close'; import Dropzone from 'react-dropzone'; import Layer from 'grommet/components/Layer'; import Header from 'grommet/components/Header'; import Section from 'grommet/components/Section'; import Paragraph from 'grommet/components/Paragraph'; import request from 'superagent'; import Select from 'react-select'; import { CLOUDINARY_UPLOAD_PRESET, CLOUDINARY_NAME, CLOUDINARY_KEY, CLOUDINARY_SECRET, CLOUDINARY_UPLOAD_URL } from '../../constants'; import Immutable from 'immutable'; import _ from 'underscore'; class ManageTablesPage extends Component { constructor(props) { super(props); this.handleMobile = this.handleMobile.bind(this); this.closeSetup = this.closeSetup.bind(this); this.onDrop = this.onDrop.bind(this); this.addVariant = this.addVariant.bind(this); this.submitSave = this.submitSave.bind(this); this.submitDelete = this.submitDelete.bind(this); this.state = { isMobile: false, tableId: props.params.table_id || null, confirm: false, name: '', variants: [], organisationId: '5800471acb97300011c68cf7', venues: [], venueId: '', events: [], eventId: '', selectedEvents: [], tableTypes: [], tableTypeId: undefined, tags: 'table', image: null, prevImage: null, isNewImage: null, prices: [] }; } componentWillMount() { if (this.state.tableId) { this.setState({variants: []}); } } componentDidMount() { if (typeof window !== 'undefined') { window.addEventListener('resize', this.handleMobile); } let options = { organisationId: this.state.organisationId }; this.getVenues(options); // IF TABLE ID EXISTS if(this.props.params.table_id) { let tOptions = { organisationId: this.state.organisationId, productId: this.props.params.table_id } this.getTable(tOptions); } } componentWillUnmount() { if (typeof window !== 'undefined') { window.removeEventListener('resize', this.handleMobile); } } handleMobile() { const isMobile = window.innerWidth <= 768; this.setState({ isMobile, }); }; getVenues = (options) => { PartyBot.venues.getAllInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({venueId: body[0]._id}); let ttOptions = { organisationId: this.state.organisationId, venue_id: this.state.venueId } // this.getEvents(ttOptions); this.getTableTypes(ttOptions); } this.setState({venues: body, events: []}); } }); } getEvents = (options) => { PartyBot.events.getEventsInOrganisation(options, (err, response, body) => { if(!err && response.statusCode == 200) { if(body.length > 0) { this.setState({eventId: body[0]._id}); } body.map((value, index) =>{ this.setState({events: this.state.events.concat({ _event: value._id, name: value.name, selected: false })}); }); } }); } getTableTypes = (options) => { PartyBot.tableTypes.getTableTypesInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({tableTypes: body}); let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: body[0]._id } PartyBot.tableTypes.getTableType(params, (aerr, aresponse, abody) => { let events = abody._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: body[0]._id, events: _.flatten(events) }); }); } } }); } getTable = (options) => { PartyBot.products.getProductsInOrganisation(options, (error, response, body) => { if(response.statusCode == 200) { this.setState({ name: body.name, image: { preview: body.image }, prevImage: { preview: body.image }, variants: body.prices.map((value, index) => { return { _event: value._event, price: value.price } }) }); } }); } onVenueChange = (event) => { let id = event.target.value; this.setState({ venueId: id, events: [], variants: []}); let options = { organisationId: this.state.organisationId, venue_id: id }; this.getTableTypes(options); // this.getEvents(options); } onEventChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: event.target.value, price: item.price}); this.setState( { variants: mutated.toArray() } ); } onPriceChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: item._event, price: event.target.value}); this.setState( { variants: mutated.toArray() } ); } closeSetup(){ this.setState({ confirm: false }); this.context.router.push('/tables'); } addVariant() { // will create then get? var newArray = this.state.variants.slice(); newArray.push({ _event_id: [], description: "", image: null, imageUrl: "" }); this.setState({variants:newArray}) } removeVariant(index, event){ // delete variant ID let variants = Immutable.List(this.state.variants); let mutated = variants.remove(index); // let selectedEvents = Immutable.List(this.state.selectedEvents); // let mutatedEvents = selectedEvents.remove(index); this.setState({ variants: mutated.toJS(), }); } onEventAdd = (index, selectedEvents) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('_event_id', selectedEvents); let newClone = cloned.set(index, anIndex); let selectedEventState = Immutable.List(this.state.selectedEvents); let newSelectedEventState = selectedEventState.set(index, selectedEvents); this.setState({selectedEvents: newSelectedEventState.toJS(), variants: newClone.toJS()}); } setDescrpiption = (index, event) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('description', event.target.value); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS()}); } onDrop = (index, file) => { this.setState({ isBusy: true }); let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file[0]); console.log('dragged'); upload.end((err, response) => { if (err) { } else { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('image', file[0]); anIndex = anIndex.set('imageUrl', response.body.secure_url); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS(), isBusy: false}); } }); } onTypeChange = (event) => { var id = event.target.value; let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: id } PartyBot.tableTypes.getTableType(params, (err, response, body) => { let events = body._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: id, variants: [], events: _.flatten(events) }); }); } setName = (event) => { this.setState({name: event.target.value}); } getTypeOptions = () => { return this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; }); } getTableVariants = () => { return this.state.variants.map((value, index) => { return ( <Box key={index} separator="all"> <FormField label="Event" htmlFor="events" /> <Select name="events" options={this.state.events.filter((x) => { let a = _.contains(_.uniq(_.flatten(this.state.selectedEvents)), x); return !a; })} value={value._event_id} onChange={this.onEventAdd.bind(this, index)} multi={true} /> <FormField label="Description" htmlFor="tableTypedescription"> <input id="tableTypedescription" type="text" onChange={this.setDescrpiption.bind(this, index)} value={value.description}/> </FormField> <FormField label="Image"> {value.image ? <Box size={{ width: 'large' }} align="center" justify="center"> <div> <img src={value.image.preview} width="200" /> </div> <Box size={{ width: 'large' }}> <Button label="Cancel" onClick={this.onRemoveImage.bind(this)} plain={true} icon={<CloseIcon />}/> </Box> </Box> : <Box align="center" justify="center" size={{ width: 'large' }}> <Dropzone multiple={false} ref={(node) => { this.dropzone = node; }} onDrop={this.onDrop.bind(this, index)} accept='image/*'> Drop image here or click to select image to upload. </Dropzone> </Box> } <Button label="Remove" onClick={this.removeVariant.bind(this, index)} primary={true} float="right"/> </FormField> </Box>) }); // return this.state.variants.map( (item, index) => { // return <div key={index}> // <FormField label="Event" htmlFor="tableName"> // <select id="tableVenue" onChange={this.onEventChange.bind(this, item, index)} value={item._event||this.state.events[0]._event}> // { // this.state.events.map( (value, index) => { // return (<option key={index} value={value._event}>{value.name}</option>) // }) // } // </select> // </FormField> // <FormField label="Price(Php)" htmlFor="tablePrice"> // <input type="number" onChange={this.onPriceChange.bind(this, item, index)} value={item.price}/> // </FormField> // <Footer pad={{"vertical": "small"}}> // <Heading align="center"> // <Button className={styles.eventButton} label="Update" primary={true} onClick={() => {}} /> // <Button className={styles.eventButton} label="Remove" onClick={this.removeVariant.bind(this, index)} /> // </Heading> // </Footer> // </div>; // }); } onDrop(file) { this.setState({ image: file[0], isNewImage: true }); } onRemoveImage = () => { this.setState({ image: null, isNewImage: false }); } handleImageUpload(file, callback) { if(this.state.isNewImage) { let options = { url: CLOUDINARY_UPLOAD_URL, formData: { file: file } }; let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file); upload.end((err, response) => { if (err) { console.error(err); } if (response.body.secure_url !== '') { callback(null, response.body.secure_url) } else { callback(err, ''); } }); } else { callback(null, null); } } submitDelete (event) { event.preventDefault(); let delParams = { organisationId: this.state.organisationId, productId: this.state.tableId }; PartyBot.products.deleteProduct(delParams, (error, response, body) => { if(!error && response.statusCode == 200) { this.setState({ confirm: true }); } else { } }); } submitSave() { event.preventDefault(); this.handleImageUpload(this.state.image, (err, imageLink) => { if(err) { console.log(err); } else { let updateParams = { name: this.state.name, organisationId: this.state.organisationId, productId: this.state.tableId, venueId: this.state.venueId, table_type: this.state.tableTypeId, image: imageLink || this.state.prevImage.preview, prices: this.state.variants }; PartyBot.products.update(updateParams, (errors, response, body) => { if(response.statusCode == 200) { this.setState({ confirm: true }); } }); } }); } submitCreate = () => { event.preventDefault(); console.log(this.state); let params = {}; // this.handleImageUpload(this.state.image, (err, imageLink) => { // if(err) { // console.log(err); // } else { // let createParams = { // name: this.state.name, // organisationId: this.state.organisationId, // venueId: this.state.venueId, // tags: this.state.tags, // table_type: this.state.tableTypeId, // image: imageLink, // prices: this.state.variants // }; // PartyBot.products.create(createParams, (errors, response, body) => { // if(response.statusCode == 200) { // this.setState({ // confirm: true // }); // } // }); // } // }); } render() { const { router, } = this.context; const { isMobile, } = this.state; const { files, variants, } = this.state; return ( <div className={styles.container}> <link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css"/> {this.state.confirm !== false ? <Layer align="center"> <Header> Table successfully created. </Header> <Section> <Button label="Close" onClick={this.closeSetup} plain={true} icon={<CloseIcon />}/> </Section> </Layer> : null } <Box> {this.state.tableId !== null ? <Heading align="center"> Edit Table </Heading> : <Heading align="center"> Add Table </Heading> } </Box> <Box size={{ width: 'large' }} direction="row" justify="center" align="center" wrap={true} margin="small"> <Form> <FormFields> <fieldset> <FormField label="Venue" htmlFor="tableVenue"> <select id="tableVenue" onChange={this.onVenueChange} value={this.state.venueId}> {this.state.venues.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label="Table Type" htmlFor="tableType"> <select id="tableType" onChange={this.onTypeChange} value={this.state.tableTypeId}> {this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label=" Name" htmlFor="tableName"> <input id="tableName" type="text" onChange={this.setName} value={this.state.name}/> </FormField> { //Dynamic Price/Event Component this.getTableVariants() } <Button label="Add Event" primary={true} onClick={this.addVariant} /> </fieldset> </FormFields> <Footer pad={{"vertical": "medium"}}> { this.state.tableId !== null ? <Heading align="center"> <Button label="Save Changes" primary={true} onClick={this.submitSave} /> <Button label="Delete" primary={true} onClick={this.submitDelete} /> </Heading> : <Heading align="center"> <Button label="Create Table" primary={true} onClick={this.submitCreate} /> </Heading> } </Footer> </Form> </Box> </div> ); } } ManageTablesPage.contextTypes = { router: PropTypes.object.isRequired, }; export default cssModules(ManageTablesPage, styles);
JaySmartwave/palace-bot-sw
app/src/pages/ManageTablesPage/index.js
JavaScript
mit
17,890
export const ic_restaurant_menu_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm12.05-3.19c1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47c1.53.71 3.68.21 5.27-1.38z"},"children":[]}]};
wmira/react-icons-kit
src/md/ic_restaurant_menu_twotone.js
JavaScript
mit
464
"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBefore(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["always-single-line"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a { background-size: 0 ,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0 ,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\n}", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\r\n}", description: "CRLF", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never-single-line"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a { background-size: 0,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0 ,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0 ,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\n}", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\r\n}", description: "CRLF", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, } ], })
hudochenkov/stylelint
lib/rules/value-list-comma-space-before/__tests__/index.js
JavaScript
mit
5,084
var test = require('tap').test; var CronExpression = require('../lib/expression'); test('Fields are exposed', function(t){ try { var interval = CronExpression.parse('0 1 2 3 * 1-3,5'); t.ok(interval, 'Interval parsed'); CronExpression.map.forEach(function(field) { interval.fields[field] = []; t.throws(function() { interval.fields[field].push(-1); }, /Cannot add property .*?, object is not extensible/, field + ' is frozen'); delete interval.fields[field]; }); interval.fields.dummy = []; t.same(interval.fields.dummy, undefined, 'Fields is frozen'); t.same(interval.fields.second, [0], 'Second matches'); t.same(interval.fields.minute, [1], 'Minute matches'); t.same(interval.fields.hour, [2], 'Hour matches'); t.same(interval.fields.dayOfMonth, [3], 'Day of month matches'); t.same(interval.fields.month, [1,2,3,4,5,6,7,8,9,10,11,12], 'Month matches'); t.same(interval.fields.dayOfWeek, [1,2,3,5], 'Day of week matches'); } catch (err) { t.error(err, 'Interval parse error'); } t.end(); });
harrisiirak/cron-parser
test/fields.js
JavaScript
mit
1,093
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, fillIn } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | inputs/text-input', function (hooks) { setupRenderingTest(hooks); hooks.beforeEach(async function () { this.config = { value: '123 hello', name: 'myInput', disabled: false, autocomplete: 'name', texts: { placeholder: 'Your name', }, }; await render(hbs`<Inputs::TextInput @config={{config}} />`); }); test('it renders', async function (assert) { assert.dom('textarea').hasAttribute('name', 'myInput'); assert.dom('textarea').hasAttribute('autocomplete', 'name'); assert.dom('textarea').hasAttribute('placeholder', 'Your name'); }); test('it updates value', async function (assert) { assert.dom('textarea').hasValue('123 hello'); this.set('config.value', 'hello?'); assert.dom('textarea').hasValue('hello?'); await fillIn('textarea', 'bye!'); assert.equal(this.config.value, 'bye!'); }); test('it can be disabled', async function (assert) { assert.dom('textarea').isNotDisabled(); this.set('config.disabled', true); assert.dom('textarea').isDisabled(); }); test('it supports presence validations', async function (assert) { assert.dom('textarea').doesNotHaveAttribute('required'); this.set('config.validations', { required: true }); assert.dom('textarea').hasAttribute('required'); }); });
nibynic/ember-form-builder
tests/integration/components/inputs/text-input-test.js
JavaScript
mit
1,560
#!/usr/bin/env node var listCommand = []; require('./listCommand')(listCommand) var logDetail = (str) => { console.log(' > '+str); } var printHelp = () => { var txtHelp = ""; var h = ' '; var t = ' '; txtHelp += "\n"+h+"Usage : rider [command] \n"; txtHelp += "\n"+h+"Command List : \n"; var maxText = 0; if(listCommand == undefined){ logDetail("not found help detail"); return; } Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; if(maxText < item.name.length+item.params.length) maxText = item.name.length+item.params.length+4; }); var maxT = Math.ceil(maxText/4); Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; var x = (item.name.length+item.params.length+4)/4; x = Math.ceil(x); var space = '\t'; for (var i = 0; i < maxT-x-1; i++) { space += '\t'; } var txt = ""; if(item.params.length > 0){ space += '\t'; txt = '\t'+item.name +" [" +item.params+"] " + space +item.desc+"\n"; }else{ txt = '\t'+item.name + space +item.desc+"\n"; } txtHelp +=txt; txtHelp +"\n"; }); console.log(txtHelp); process.exit(0); } var parseParams = (params, cb) => { if(params.length < 3){ return cb(true); } cb(false); } var checkCommand = (cmd) => { var foundCmd = false; Object.keys(listCommand).forEach((keyName) => { if(keyName == cmd){ foundCmd = true; return; } }); return !foundCmd; } var runCommand = (params, cb) => { var opt = params[2]; var objRun = listCommand[opt]; if(objRun != undefined && objRun != null){ objRun.runCommand(params, cb); } } var main = () => { console.log(">> Rider ... "); var params = process.argv; parseParams(params, (err) => { if(err){ printHelp(); return; } var opt = params[2]; if(opt == "-h" || opt == "--help"){ printHelp(); return; } if(checkCommand(opt)){ printHelp(); return; } runCommand(params, () => { process.exit(0); }); }); } // -- call main function -- main();
khajer/rider.js
cli.js
JavaScript
mit
2,029
import React from "react"; import $ from "jquery"; import "bootstrap/dist/js/bootstrap.min"; import "jquery-ui/ui/widgets/datepicker"; import { postFulltimeEmployer, postParttimeEmployer, putFullTimeEmployer, putParttimeEmployer } from "../actions/PostData"; import DropDownBtn from "../components/DropDownBtn"; import {parseBirthdayForServer} from "../utils/Utils"; import {connect} from "react-redux"; class ModalEmployer extends React.Component { componentWillReceiveProps = (nextProps) => { if (nextProps.data) { this.setState(nextProps.data); if (nextProps.data.day_salary) { this.setState({ type: 'congNhat' }) } else { this.setState({ type: 'bienChe' }) } } if (nextProps.data == null) { this.setState(this.emptyObject) } } emptyObject = { "salary_level": "", "name": "", "month_salary": "", "phone": "", "birthday": "", "allowance": "", "department_id": this.props.departments.length > 0 ? this.props.departments[0].id : "", day_salary: "", } onClickSave = () => { let data = { "name": this.state.name, "phone": this.state.phone, "birthday": parseBirthdayForServer(this.state.birthday), "department_id": this.state.department_id, } if (this.state.type === "bienChe") { data.salary_level = this.state.salary_level; data.month_salary = this.state.month_salary; data.allowance = this.state.allowance; if (this.props.data) { putFullTimeEmployer(this.props.data.id, data, this.props.fetchEmployers); } else { postFulltimeEmployer(data, this.props.fetchEmployers); } } if (this.state.type === "congNhat") { data.day_salary = this.state.day_salary; if (this.props.data) { putParttimeEmployer(this.props.data.id, data, this.props.fetchEmployers); } else { postParttimeEmployer(data, this.props.fetchEmployers) } } $('#create').modal('toggle'); } constructor(props) { super(props); this.state = Object.assign(this.emptyObject, {type: null}) } onChangeText = (event) => { this.setState({ [event.target.name]: event.target.value }) } clickType = (type) => { this.setState({ type }) } componentDidMount = () => { $('#datepicker').datepicker({ uiLibrary: 'bootstrap4', iconsLibrary: 'fontawesome', onSelect: (dateText) => { this.setState({ birthday: dateText }) }, dateFormat: 'dd/mm/yy' }); } renderExtraForm = () => { if (this.state.type) { switch (this.state.type) { case "bienChe": return <div> <label htmlFor="id">Lương tháng</label> <div className="input-group"> <input onChange={this.onChangeText} name="month_salary" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.month_salary}/> </div> <label htmlFor="id">Bậc lương</label> <div className="input-group"> <input onChange={this.onChangeText} name="salary_level" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.salary_level}/> </div> <label htmlFor="id">Phụ cấp</label> <div className="input-group"> <input onChange={this.onChangeText} name="allowance" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.allowance}/> </div> </div> break; case "congNhat": return <div> <label htmlFor="id">Lương ngày</label> <div className="input-group"> <input name="day_salary" value={this.state.day_salary} onChange={this.onChangeText} type="text" className="form-control" id="id" aria-describedby="basic-addon3"/> </div> </div> break; } } } onSelectDepartment = (item) => { this.setState({ department_id: item.id }) } renderDropDownBtn = () => { if (this.props.departments.length > 0) { return ( <DropDownBtn onChange={this.onSelectDepartment} default data={this.props.departments}></DropDownBtn> ) } } render() { return ( <div className="modal fade" id="create" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLabel">Thêm nhân viên</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <label htmlFor="name">Tên nhân viên</label> <div className="input-group"> <input onChange={this.onChangeText} value={this.state.name} name="name" type="text" className="form-control" id="name" aria-describedby="basic-addon3"/> </div> <label htmlFor="datepicker">Ngày tháng năm sinh</label> <div className="input-group date" data-provide="datepicker"> <input onClick={this.onChangeText} onChange={this.onChangeText} value={this.state.birthday} name="birthday" type="text" className="form-control" id="datepicker"/> </div> <label htmlFor="phone">Số điện thoại</label> <div className="input-group"> <input onChange={this.onChangeText} value={this.state.phone} name="phone" type="text" className="form-control" id="phone" aria-describedby="basic-addon3"/> </div> <div className="btn-group"> <label htmlFor="name" className="margin-R10">Chọn phòng ban</label> {this.renderDropDownBtn()} </div> <div className="btn-group btn-middle align-middle"> { (() => { if (this.props.data) { if (this.props.data.day_salary === null) { return (<button className="btn btn-primary" id="bien-che">Nhân viên Biên chế </button>) } else { return ( <button className="btn btn-info" id="cong-nhat">Nhân viên Công nhật </button> ) } } else { let arr = []; arr.push(<button onClick={this.clickType.bind(this, "bienChe")} className="btn btn-primary" id="bien-che">Nhân viên Biên chế </button>); arr.push(<button onClick={this.clickType.bind(this, "congNhat")} className="btn btn-info" id="cong-nhat">Nhân viên Công nhật </button>); return arr; } })() } </div> { this.renderExtraForm() } </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-dismiss="modal">Hủy</button> <button onClick={this.onClickSave} type="button" className="btn btn-primary">Lưu</button> </div> </div> </div> </div> ) } } const mapStateToProps = state => { return { departments: state.app.departments } } export default connect(mapStateToProps)(ModalEmployer)
liemnt/quanlynv
quanlynhanvien/src/components/ModalEmployer.js
JavaScript
mit
10,454
define('exports@*', [], function(require, exports, module){ exports.a = 1; });
kaelzhang/neuron
test/mod/exports/*/exports.js
JavaScript
mit
84
jQuery(document).ready(function(){ jQuery('.carousel').carousel() var FPS = 30; var player = $('#player') var pWidth = player.width(); $window = $(window) var wWidth = $window.width(); setInterval(function() { update(); }, 1000/FPS); function update() { if(keydown.space) { player.shoot(); } if(keydown.left) { console.log('go left') player.css('left', '-=10'); } if(keydown.right) { console.log('go right') var x = player.position().left; if(x + pWidth > wWidth) { player.css('left', '0') } else if(x < 0 ) { var p = wWidth + x - pWidth; var t = p + 'px' player.css('left', t) } else { player.css('left', '+=10'); } } } $('') })
ni5ni6/chiptuna.com
js/main.js
JavaScript
mit
739
'use strict'; // Configuring the Articles module angular.module('about').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('mainmenu', 'About Us', 'about', 'left-margin', '/about-us', true, null, 3); } ]);
spiridonov-oa/people-ma
public/modules/about/config/about.client.config.js
JavaScript
mit
257
export default function closest(n, arr) { let i let ndx let diff let best = Infinity let low = 0 let high = arr.length - 1 while (low <= high) { // eslint-disable-next-line no-bitwise i = low + ((high - low) >> 1) diff = arr[i] - n if (diff < 0) { low = i + 1 } else if (diff > 0) { high = i - 1 } diff = Math.abs(diff) if (diff < best) { best = diff ndx = i } if (arr[i] === n) break } return arr[ndx] }
octopitus/rn-sliding-up-panel
libs/closest.js
JavaScript
mit
493
/** * 斐波那契数列 */ export default function fibonacci(n){ if(n <= 2){ return 1; } let n1 = 1, n2 = 1, sn = 0; for(let i = 0; i < n - 2; i ++){ sn = n1 + n2; n1 = n2; n2 = sn; } return sn; }
lomocc/react-boilerplate
src/utils/fibonacci.js
JavaScript
mit
230
import * as UTILS from '@utils'; const app = new WHS.App([ ...UTILS.appModules({ position: new THREE.Vector3(0, 40, 70) }) ]); const halfMat = { transparent: true, opacity: 0.5 }; const box = new WHS.Box({ geometry: { width: 30, height: 2, depth: 2 }, modules: [ new PHYSICS.BoxModule({ mass: 0 }) ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.mesh, ...halfMat }), position: { y: 40 } }); const box2 = new WHS.Box({ geometry: { width: 30, height: 1, depth: 20 }, modules: [ new PHYSICS.BoxModule({ mass: 10, damping: 0.1 }) ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.softbody, ...halfMat }), position: { y: 38, z: 12 } }); const pointer = new WHS.Sphere({ modules: [ new PHYSICS.SphereModule() ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.mesh }) }); console.log(pointer); pointer.position.set(0, 60, -8); pointer.addTo(app); box.addTo(app); box2.addTo(app).then(() => { const constraint = new PHYSICS.DOFConstraint(box2, box, new THREE.Vector3(0, 38, 1) ); app.addConstraint(constraint); constraint.enableAngularMotor(10, 20); }); UTILS.addPlane(app, 250); UTILS.addBasicLights(app); app.start();
WhitestormJS/whs.js
examples/physics/Constraints/DofConstraint/script.js
JavaScript
mit
1,332
import React from 'react' import { PlanItineraryContainer } from './index' const PlanMapRoute = () => { return ( <div> <PlanItineraryContainer /> </div> ) } export default PlanMapRoute
in-depth/indepth-demo
src/shared/views/plans/planItinerary/PlanItineraryRoute.js
JavaScript
mit
206
const path = require('path'); module.exports = { lazyLoad: true, pick: { posts(markdownData) { return { meta: markdownData.meta, description: markdownData.description, }; }, }, plugins: [path.join(__dirname, '..', 'node_modules', 'bisheng-plugin-description')], routes: [{ path: '/', component: './template/Archive', }, { path: '/posts/:post', dataPath: '/:post', component: './template/Post', }, { path: '/tags', component: './template/TagCloud', }], };
benjycui/bisheng
packages/bisheng-theme-one/src/index.js
JavaScript
mit
536
// Init ES2015 + .jsx environments for .require() require('babel-register'); var express = require('express'); var fluxexapp = require('./fluxexapp'); var serverAction = require('./actions/server'); var fluxexServerExtra = require('fluxex/extra/server'); var app = express(); // Provide /static/js/main.js fluxexServerExtra.initStatic(app); // Mount test page at /test app.use('/product', fluxexServerExtra.createMiddlewareByAction(fluxexapp, serverAction.samplePage)); // Start server app.listen(process.env.TESTPORT || 3000); console.log('Fluxex started! Go http://localhost:3001/product?id=124');
zordius/fluxex
examples/01-history-api/server.js
JavaScript
mit
604
define(function(){ return {"乙":"乚乛", "人":"亻", "刀":"刂", "卩":"㔾", "尢":"尣𡯂兀", "巛":"巜川", "己":"已巳", "彐":"彑", "心":"忄", "手":"扌", "攴":"攵", "无":"旡", "歹":"歺", "水":"氵氺", "爪":"爫", "火":"灬", "":"户", "牛":"牜", "犬":"犭", "玉":"王", "疋":"", "目":"", "示":"礻", "玄":"𤣥", "糸":"糹", "网":"冈", "艸":"艹", "竹":"", "衣":"衤", "襾":"西覀", "老":"", "聿":"", "肉":"⺼", "言":"訁", "足":"", "辵":"辶", "邑":"⻏", "阜":"阝", "金":"釒", "長":"镸", "食":"飠", "金":"釒", "廾":"廾", "爿":"丬"}; });
yapcheahshen/ksanapc
node_webkit/jslib/cjk/radicalvariants.js
JavaScript
mit
688
"use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var qs = require("querystring"); var partial = require("lodash.partial"); var endpoints = require("./stats-endpoints"); var dicts = require("./dicts"); var translateKeys = require("./util/translate-keys"); var transport = require("./get-json"); var translate = partial(translateKeys, dicts.jsToNbaMap); var stats = Object.create({ setTransport: function setTransport(_transport) { transport = _transport; }, getTransport: function getTransport() { return transport; } }); Object.keys(endpoints).forEach(function (key) { stats[key] = makeStatsMethod(endpoints[key]); }); function makeStatsMethod(endpoint) { return function statsMethod(query, callback) { if (typeof query === "function") { callback = query; query = {}; } if (typeof callback !== "function") { throw new TypeError("Must pass a callback function."); } var params = _extends({}, endpoint.defaults, translate(query)); transport(endpoint.url, params, function (err, response) { if (err) return callback(err); if (response == null) return callback(); // response is something like "GameID is required" if (typeof response === "string") return callback(new Error(response)); if (endpoint.transform) return callback(null, endpoint.transform(response)); callback(null, response); }); }; } module.exports = stats;
weixiyen/nba
lib/stats.js
JavaScript
mit
1,662
import React from 'react'; import ErrorIcon from './ErrorIcon'; export const symbols = { 'ErrorIcon -> with filled': <ErrorIcon filled={true} />, 'ErrorIcon -> without filled': <ErrorIcon filled={false} /> };
seekinternational/seek-asia-style-guide
react/ErrorIcon/ErrorIcon.iconSketch.js
JavaScript
mit
214
/* * The MIT License (MIT) * * Copyright (c) 2015 maldicion069 * * 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. */ 'use strict'; exports.init = function(req, res){ //res.write("joder\n"); //res.write(req.csrfToken()); //res.end(); req.app.db.models.Experiment.find({}) .select("tableList name uploadedBy dateDevelopment id name neuronType") // Hay que sacar también nombre y tipo D= .exec(function(err, exps) { if(err) { res.send("Error"); } else { console.log(exps); res.render('account/experiments/compare/stage1', { code: req.csrfToken(), experiments: exps }); } }); }; /** * Esta función sirve para que, dado * */ exports.second = function(req, res) { console.log("BODY: " + req.body.fcbklist_value); if(req.body.fcbklist_value.length < 2) { res.redirect("/account/experiments/compare/"); } else { //res.send(req.body); var orArray = []; req.body.fcbklist_value.forEach(function(idExp) { orArray.push({_id: idExp}); }); console.log(orArray); req.app.db.models.Experiment.find({$or: orArray}) .select("tableList name createdBy dateDevelopment id") //.populate("tableList", "id") .populate("createdBy", "username") .exec(function(err, exps) { console.log(err); console.log(JSON.stringify(exps)); res.render("account/experiments/compare/stage2", { experiments: exps, code: req.csrfToken() }); }); } //["54514c6a4650426d2a9bf056","5451853c745acc0a412abf68"] // Con esta lista de ids, lo que hacemos es sacar: // 1. Cada experimento con: // name uploadedBy dateDevelopment id // y el identificador de cada tabla del experimento. // 2. Con esos datos, montamos algo guay con radio button. }; /** * En este método recibimos los id's de los experimentos * y la tabla seleccionada * Por cada tabla, sacamos las columnas comunes entre ellas e * imprimimos los gráficos de una vez */ exports.third = function(req, res) { var peticiones = req.body.tab; console.log(peticiones); var arr = []; /*var mapMatch = { "a": null, "b": null, "c": null, "Datos2": null }*/ var params = req.app.utility.variables; var tabs = []; var headersPaths = []; var data = {}; // To save the return to view var Set = req.app.utility.Set; var commons = new Set(); var async = require('async'); async.series([ // First read data from database and save function(callback){ console.log("ejecuto 1"); async.each(peticiones, function(tabid, call) { console.log(tabid); req.app.db.models.TableExperiment.findById(tabid).populate("assignedTo", "name neuronType createdBy dateDevelopment description").exec(function(err, tab) { var username = ""; async.series({ first: function(call2) { console.log("Paso 1"); console.log("Jodeeer, " + tab.assignedTo.createdBy); /*console.log(tab); async.each(tab, function(tab_, call3) { console.log("Buscamos username " + tab_); req.app.db.models.User.findById(tab_.createdBy._id).select("username").exec(function(err, user) { console.log("USER : " + user); tab.createdBy = user.username; call3(); }); });*/ req.app.db.models.User.findById(tab.assignedTo.createdBy).select("username").exec(function(err, user) { console.log("USER : " + user); tab["username"] = user.username; username = user.username; //tab.username = user.username; call2(); }); }, second: function(call2) { console.log("Paso 2"); // TODO: Controlar "err" var tab_ = {}; tab_.assignedTo = { _id: tab.assignedTo._id, username: username, createdBy: tab.assignedTo.createdBy, name: tab.assignedTo.name, neuronType: tab.assignedTo.neuronType, dateDevelopment: tab.assignedTo.dateDevelopment, description: tab.assignedTo.description }; tab_.id = tab._id; tab_.matrix = tab.matrix; tab_.headers = tab.headers; /* assignedTo: { _id: 545bde715e4a5d4a4089ad21, createdBy: 545bde535e4a5d4a4089ad1f, name: 'Mi physiological', neuronType: 'PHYSIOLOGICAL' }, _id: 545bde715e4a5d4a4089ad52, __v: 0, matrix: */ console.log("SECOND : " + tab_); // Añadimos la tabla al sistema //console.log("Añado " + tab); tabs.push(tab_); // Recorro las cabeceras y genero un mapa con k(header) y v(position) var mapMatch = {}; console.log(tab.headers); tab.headers.forEach(function(header, pos) { if(params.contains(header)) { mapMatch[header] = pos; } }); //console.log("Añado " + JSON.stringify(mapMatch)); headersPaths.push(mapMatch); // Guardamos el mapeo call2(); } }, function(err, results) { call(); }); }); }, function(err) { callback(); }); }, // Filter columns that I use to compare table's experiment function(callback) { console.log("Tengo : " + tabs.length); console.log("Tengo : " + headersPaths.length); // Guardamos todos los valores de "params" en "data" data.headers = {}; params.get().forEach(function(value) { data.headers[value] = [];//undefined; }); console.log(JSON.stringify(data)); // Creamos el attr "exps" dentro de "data" data.exps = []; // Ahora por cada experimento, cargamos los datos correspondientes headersPaths.forEach(function(headerPath, index) { console.log("--------- Empezamos a recorrer con header " + headerPath + " ---------"); var posHeader = 0; Object.keys(headerPath).forEach(function(key) { console.log(key + " <=> " + headerPath[key]); //tabs.forEach(function(tab, ii) { tabs[index].matrix.forEach(function(matrix, area) { //console.log("Header: " + key + "\tNº Tab: " + ii + "\tArea: " + area); data.headers[key][area] = data.headers[key][area] || [0]; // Si existe se queda igual, si no, se añade array data.headers[key][area].push(matrix.data[posHeader]); }); //}); /*var infoData = []; tabs[index].matrix.forEach(function(matrix, area) { infoData.push(matrix.data[posHeader]); }); //console.log(infoData); console.log("Inserta del index " + posHeader); data.headers[key].push(infoData);*/ posHeader++; }); // Volcamos la información del experimento asociado a cada tabla data.exps.push(tabs[index].assignedTo); }); console.log("----------------------"); console.log("----------------------"); //console.log(data); console.log("----------------------"); console.log("----------------------"); /*async.each(arr, function(tab, call) { tab.headers.forEach(function(header, position) { //if(mapMatch[header] != undefined) { if(header in tab.mapMatch) { tab.mapMatch[header] = position; } }); // Remove all columns that not contains in mapMatch //tab.mapMatch.forEach(function(position) { //}); call(); });*/ callback(); } ], // finish callback function(err, results){ console.log("FIN: " + arr.length); console.log(params.intersect(commons)); //res.send(data); /*var ret = { data: data }; res.send(ret);*/ console.log("----------------------"); console.log("----------------------"); console.log("----------------------"); console.log("----------------------"); console.log(JSON.stringify(data)); res.render("account/experiments/compare/stage3", { data: data, code: req.csrfToken(), id: 0 }); }); }; // TODO: No funciona bien T.T /*exports.downloadHTML = function(req, res) { phantom = require('phantom') phantom.create(function(ph){ ph.createPage(function(page) { page.open("http://www.google.com", function(status) { page.render('google.pdf', function(){ console.log('Page Rendered'); ph.exit(); }); }); }); }); };*/
maldicion069/HBPWebNodeJs
views/account/experiments/compare/stages.js
JavaScript
mit
9,900
import QUnit from 'qunit'; import { registerDeprecationHandler } from '@ember/debug'; let isRegistered = false; let deprecations = new Set(); let expectedDeprecations = new Set(); // Ignore deprecations that are not caused by our own code, and which we cannot fix easily. const ignoredDeprecations = [ // @todo remove when we can land https://github.com/emberjs/ember-render-modifiers/pull/33 here /Versions of modifier manager capabilities prior to 3\.22 have been deprecated/, /Usage of the Ember Global is deprecated./, /import .* directly from/, /Use of `assign` has been deprecated/, ]; export default function setupNoDeprecations({ beforeEach, afterEach }) { beforeEach(function () { deprecations.clear(); expectedDeprecations.clear(); if (!isRegistered) { registerDeprecationHandler((message, options, next) => { if (!ignoredDeprecations.some((regex) => message.match(regex))) { deprecations.add(message); } next(message, options); }); isRegistered = true; } }); afterEach(function (assert) { // guard in if instead of using assert.equal(), to not make assert.expect() fail if (deprecations.size > expectedDeprecations.size) { assert.ok( false, `Expected ${expectedDeprecations.size} deprecations, found: ${[...deprecations] .map((msg) => `"${msg}"`) .join(', ')}` ); } }); QUnit.assert.deprecations = function (count) { if (count === undefined) { this.ok(deprecations.size, 'Expected deprecations during test.'); } else { this.equal(deprecations.size, count, `Expected ${count} deprecation(s) during test.`); } deprecations.forEach((d) => expectedDeprecations.add(d)); }; QUnit.assert.deprecationsInclude = function (expected) { let found = [...deprecations].find((deprecation) => deprecation.includes(expected)); this.pushResult({ result: !!found, actual: deprecations, message: `expected to find \`${expected}\` deprecation. Found ${[...deprecations] .map((d) => `"${d}"`) .join(', ')}`, }); if (found) { expectedDeprecations.add(found); } }; }
kaliber5/ember-bootstrap
tests/helpers/setup-no-deprecations.js
JavaScript
mit
2,205
module.exports = function(grunt) { // Add our custom tasks. grunt.loadTasks('../../../tasks'); // Project configuration. grunt.initConfig({ mochaTest: { options: { reporter: 'spec', grep: 'tests that match grep', invert: true }, all: { src: ['*.js'] } } }); // Default task. grunt.registerTask('default', ['mochaTest']); };
quantumlicht/collarbone
node_modules/grunt-mocha-test/test/scenarios/invertOption/Gruntfile.js
JavaScript
mit
425
"use strict"; define("ace/mode/asciidoc_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var AsciidocHighlightRules = function AsciidocHighlightRules() { var identifierRe = "[a-zA-Z\xA1-\uFFFF]+\\b"; this.$rules = { "start": [{ token: "empty", regex: /$/ }, { token: "literal", regex: /^\.{4,}\s*$/, next: "listingBlock" }, { token: "literal", regex: /^-{4,}\s*$/, next: "literalBlock" }, { token: "string", regex: /^\+{4,}\s*$/, next: "passthroughBlock" }, { token: "keyword", regex: /^={4,}\s*$/ }, { token: "text", regex: /^\s*$/ }, { token: "empty", regex: "", next: "dissallowDelimitedBlock" }], "dissallowDelimitedBlock": [{ include: "paragraphEnd" }, { token: "comment", regex: '^//.+$' }, { token: "keyword", regex: "^(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION):" }, { include: "listStart" }, { token: "literal", regex: /^\s+.+$/, next: "indentedBlock" }, { token: "empty", regex: "", next: "text" }], "paragraphEnd": [{ token: "doc.comment", regex: /^\/{4,}\s*$/, next: "commentBlock" }, { token: "tableBlock", regex: /^\s*[|!]=+\s*$/, next: "tableBlock" }, { token: "keyword", regex: /^(?:--|''')\s*$/, next: "start" }, { token: "option", regex: /^\[.*\]\s*$/, next: "start" }, { token: "pageBreak", regex: /^>{3,}$/, next: "start" }, { token: "literal", regex: /^\.{4,}\s*$/, next: "listingBlock" }, { token: "titleUnderline", regex: /^(?:={2,}|-{2,}|~{2,}|\^{2,}|\+{2,})\s*$/, next: "start" }, { token: "singleLineTitle", regex: /^={1,5}\s+\S.*$/, next: "start" }, { token: "otherBlock", regex: /^(?:\*{2,}|_{2,})\s*$/, next: "start" }, { token: "optionalTitle", regex: /^\.[^.\s].+$/, next: "start" }], "listStart": [{ token: "keyword", regex: /^\s*(?:\d+\.|[a-zA-Z]\.|[ixvmIXVM]+\)|\*{1,5}|-|\.{1,5})\s/, next: "listText" }, { token: "meta.tag", regex: /^.+(?::{2,4}|;;)(?: |$)/, next: "listText" }, { token: "support.function.list.callout", regex: /^(?:<\d+>|\d+>|>) /, next: "text" }, { token: "keyword", regex: /^\+\s*$/, next: "start" }], "text": [{ token: ["link", "variable.language"], regex: /((?:https?:\/\/|ftp:\/\/|file:\/\/|mailto:|callto:)[^\s\[]+)(\[.*?\])/ }, { token: "link", regex: /(?:https?:\/\/|ftp:\/\/|file:\/\/|mailto:|callto:)[^\s\[]+/ }, { token: "link", regex: /\b[\w\.\/\-]+@[\w\.\/\-]+\b/ }, { include: "macros" }, { include: "paragraphEnd" }, { token: "literal", regex: /\+{3,}/, next: "smallPassthrough" }, { token: "escape", regex: /\((?:C|TM|R)\)|\.{3}|->|<-|=>|<=|&#(?:\d+|x[a-fA-F\d]+);|(?: |^)--(?=\s+\S)/ }, { token: "escape", regex: /\\[_*'`+#]|\\{2}[_*'`+#]{2}/ }, { token: "keyword", regex: /\s\+$/ }, { token: "text", regex: identifierRe }, { token: ["keyword", "string", "keyword"], regex: /(<<[\w\d\-$]+,)(.*?)(>>|$)/ }, { token: "keyword", regex: /<<[\w\d\-$]+,?|>>/ }, { token: "constant.character", regex: /\({2,3}.*?\){2,3}/ }, { token: "keyword", regex: /\[\[.+?\]\]/ }, { token: "support", regex: /^\[{3}[\w\d =\-]+\]{3}/ }, { include: "quotes" }, { token: "empty", regex: /^\s*$/, next: "start" }], "listText": [{ include: "listStart" }, { include: "text" }], "indentedBlock": [{ token: "literal", regex: /^[\s\w].+$/, next: "indentedBlock" }, { token: "literal", regex: "", next: "start" }], "listingBlock": [{ token: "literal", regex: /^\.{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "constant.numeric", regex: '<\\d+>' }, { token: "literal", regex: '[^<]+' }, { token: "literal", regex: '<' }], "literalBlock": [{ token: "literal", regex: /^-{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "constant.numeric", regex: '<\\d+>' }, { token: "literal", regex: '[^<]+' }, { token: "literal", regex: '<' }], "passthroughBlock": [{ token: "literal", regex: /^\+{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: identifierRe + "|\\d+" }, { include: "macros" }, { token: "literal", regex: "." }], "smallPassthrough": [{ token: "literal", regex: /[+]{3,}/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: /^\s*$/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: identifierRe + "|\\d+" }, { include: "macros" }], "commentBlock": [{ token: "doc.comment", regex: /^\/{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "doc.comment", regex: '^.*$' }], "tableBlock": [{ token: "tableBlock", regex: /^\s*\|={3,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "tableBlock", regex: /^\s*!={3,}\s*$/, next: "innerTableBlock" }, { token: "tableBlock", regex: /\|/ }, { include: "text", noEscape: true }], "innerTableBlock": [{ token: "tableBlock", regex: /^\s*!={3,}\s*$/, next: "tableBlock" }, { token: "tableBlock", regex: /^\s*|={3,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "tableBlock", regex: /\!/ }], "macros": [{ token: "macro", regex: /{[\w\-$]+}/ }, { token: ["text", "string", "text", "constant.character", "text"], regex: /({)([\w\-$]+)(:)?(.+)?(})/ }, { token: ["text", "markup.list.macro", "keyword", "string"], regex: /(\w+)(footnote(?:ref)?::?)([^\s\[]+)?(\[.*?\])?/ }, { token: ["markup.list.macro", "keyword", "string"], regex: /([a-zA-Z\-][\w\.\/\-]*::?)([^\s\[]+)(\[.*?\])?/ }, { token: ["markup.list.macro", "keyword"], regex: /([a-zA-Z\-][\w\.\/\-]+::?)(\[.*?\])/ }, { token: "keyword", regex: /^:.+?:(?= |$)/ }], "quotes": [{ token: "string.italic", regex: /__[^_\s].*?__/ }, { token: "string.italic", regex: quoteRule("_") }, { token: "keyword.bold", regex: /\*\*[^*\s].*?\*\*/ }, { token: "keyword.bold", regex: quoteRule("\\*") }, { token: "literal", regex: quoteRule("\\+") }, { token: "literal", regex: /\+\+[^+\s].*?\+\+/ }, { token: "literal", regex: /\$\$.+?\$\$/ }, { token: "literal", regex: quoteRule("`") }, { token: "keyword", regex: quoteRule("^") }, { token: "keyword", regex: quoteRule("~") }, { token: "keyword", regex: /##?/ }, { token: "keyword", regex: /(?:\B|^)``|\b''/ }] }; function quoteRule(ch) { var prefix = /\w/.test(ch) ? "\\b" : "(?:\\B|^)"; return prefix + ch + "[^" + ch + "].*?" + ch + "(?![\\w*])"; } var tokenMap = { macro: "constant.character", tableBlock: "doc.comment", titleUnderline: "markup.heading", singleLineTitle: "markup.heading", pageBreak: "string", option: "string.regexp", otherBlock: "markup.list", literal: "support.function", optionalTitle: "constant.numeric", escape: "constant.language.escape", link: "markup.underline.list" }; for (var state in this.$rules) { var stateRules = this.$rules[state]; for (var i = stateRules.length; i--;) { var rule = stateRules[i]; if (rule.include || typeof rule == "string") { var args = [i, 1].concat(this.$rules[rule.include || rule]); if (rule.noEscape) { args = args.filter(function (x) { return !x.next; }); } stateRules.splice.apply(stateRules, args); } else if (rule.token in tokenMap) { rule.token = tokenMap[rule.token]; } } } }; oop.inherits(AsciidocHighlightRules, TextHighlightRules); exports.AsciidocHighlightRules = AsciidocHighlightRules; }); define("ace/mode/folding/asciidoc", ["require", "exports", "module", "ace/lib/oop", "ace/mode/folding/fold_mode", "ace/range"], function (require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function () {}; oop.inherits(FoldMode, BaseFoldMode); (function () { this.foldingStartMarker = /^(?:\|={10,}|[\.\/=\-~^+]{4,}\s*$|={1,5} )/; this.singleLineHeadingRe = /^={1,5}(?=\s+\S)/; this.getFoldWidget = function (session, foldStyle, row) { var line = session.getLine(row); if (!this.foldingStartMarker.test(line)) return ""; if (line[0] == "=") { if (this.singleLineHeadingRe.test(line)) return "start"; if (session.getLine(row - 1).length != session.getLine(row).length) return ""; return "start"; } if (session.bgTokenizer.getState(row) == "dissallowDelimitedBlock") return "end"; return "start"; }; this.getFoldWidgetRange = function (session, foldStyle, row) { var line = session.getLine(row); var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; if (!line.match(this.foldingStartMarker)) return; var token; function getTokenType(row) { token = session.getTokens(row)[0]; return token && token.type; } var levels = ["=", "-", "~", "^", "+"]; var heading = "markup.heading"; var singleLineHeadingRe = this.singleLineHeadingRe; function getLevel() { var match = token.value.match(singleLineHeadingRe); if (match) return match[0].length; var level = levels.indexOf(token.value[0]) + 1; if (level == 1) { if (session.getLine(row - 1).length != session.getLine(row).length) return Infinity; } return level; } if (getTokenType(row) == heading) { var startHeadingLevel = getLevel(); while (++row < maxRow) { if (getTokenType(row) != heading) continue; var level = getLevel(); if (level <= startHeadingLevel) break; } var isSingleLineHeading = token && token.value.match(this.singleLineHeadingRe); endRow = isSingleLineHeading ? row - 1 : row - 2; if (endRow > startRow) { while (endRow > startRow && (!getTokenType(endRow) || token.value[0] == "[")) { endRow--; } } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } } else { var state = session.bgTokenizer.getState(row); if (state == "dissallowDelimitedBlock") { while (row-- > 0) { if (session.bgTokenizer.getState(row).lastIndexOf("Block") == -1) break; } endRow = row + 1; if (endRow < startRow) { var endColumn = session.getLine(row).length; return new Range(endRow, 5, startRow, startColumn - 5); } } else { while (++row < maxRow) { if (session.bgTokenizer.getState(row) == "dissallowDelimitedBlock") break; } endRow = row; if (endRow > startRow) { var endColumn = session.getLine(row).length; return new Range(startRow, 5, endRow, endColumn - 5); } } } }; }).call(FoldMode.prototype); }); define("ace/mode/asciidoc", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/asciidoc_highlight_rules", "ace/mode/folding/asciidoc"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var AsciidocHighlightRules = require("./asciidoc_highlight_rules").AsciidocHighlightRules; var AsciidocFoldMode = require("./folding/asciidoc").FoldMode; var Mode = function Mode() { this.HighlightRules = AsciidocHighlightRules; this.foldingRules = new AsciidocFoldMode(); }; oop.inherits(Mode, TextMode); (function () { this.type = "text"; this.getNextLineIndent = function (state, line, tab) { if (state == "listblock") { var match = /^((?:.+)?)([-+*][ ]+)/.exec(line); if (match) { return new Array(match[1].length + 1).join(" ") + match[2]; } else { return ""; } } else { return this.$getIndent(line); } }; this.$id = "ace/mode/asciidoc"; }).call(Mode.prototype); exports.Mode = Mode; });
IonicaBizau/arc-assembler
clients/ace-builds/src/mode-asciidoc.js
JavaScript
mit
13,207
import React, { Component } from 'react'; class Main extends Component { render() { return ( <main className='Main'> <h1 className='Main-headline'>Web solutions focused on<br/>Simplicity & Reliability.</h1> <h2 className='Main-subhead'>Bleeding edge technology paired with amazing <em>talent</em> and <em>creativity</em>.</h2> <a href='#' className='Main-button'>Work With Us</a> </main> ); } } export default Main;
qubed-inc/qubed-io
src/Main/index.js
JavaScript
mit
466
'use strict'; angular.module('main', ['ngRoute', 'ngResource', 'ui.route', 'main.system', 'main.index', 'main.events']); angular.module('main.system', []); angular.module('main.index', []); angular.module('main.events', []); 'use strict'; //Setting HTML5 Location Mode angular.module('main').config(['$locationProvider', function ($locationProvider) { $locationProvider.hashPrefix('!'); } ]); 'use strict'; angular.module('main.system') .factory('Global', [ function () { var obj = this; obj._data = { app: window.app || false }; return obj._data; } ]); 'use strict'; angular.element(document).ready(function() { //Fixing facebook bug with redirect if (window.location.hash === '#_=_') window.location.hash = '#!'; //Then init the app angular.bootstrap(document, ['main']); }); 'use strict'; angular.module('main').config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: '/views/index.html' }) .otherwise({ redirectTo: '/' }); } ]); 'use strict'; angular.module('main.index') .controller('IndexCtrl', ['$scope', '$routeParams', '$http', '$location', 'Global', 'Event', function ($scope, $routeParams, $http, $location, Global, Event) { $scope.global = Global; $scope.getEvents = function(){ Event.query(function(data){ $scope.events = data; }); }; $scope.init = function(){ $scope.getEvents(); }; } ]); 'use strict'; angular.module('main.events') .factory('Event', [ '$resource', function ($resource) { return $resource("/api/events/:id"); } ]);
NevadaCountyHackers/hackers-web-app
public/dist/app.js
JavaScript
mit
1,912
/** * StaticText.js * Text that cannot be changed after loaded by the game */ import GamePiece from './GamePiece.js'; import Info from './Info.js'; import Text from './Text.js'; export default class StaticText extends Text { constructor (config) { super(config); this.static = true; } }
javisaurusrex/zookillsoccer
modules/js/StaticText.js
JavaScript
mit
305
import React from 'react'; import { string, node } from 'prop-types'; import classNames from 'classnames'; const TileAction = ({ children, className, ...rest }) => { return ( <div className={classNames('tile-action', className)} {...rest}> {children} </div> ); }; /** * TileAction property types. */ TileAction.propTypes = { className: string, children: node }; /** * TileAction default properties. */ TileAction.defaultProps = {}; export default TileAction;
Landish/react-spectre-css
src/components/TileAction/TileAction.js
JavaScript
mit
489
M.profile("generators"); function* forOfBlockScope() { let a = [1, 2, 3, 4, 5, 6, 7, 8]; let b = [10, 11, 12, 13, 14, 15, 16]; const funs = []; for (const i of a) { let j = 0; funs.push(function* iter() { yield `fo1: ${i} ${j++}`; }); } for (var i of a) { var j = 0; funs.push(function* iter() { yield `fo2: ${i} ${j++}`; }); } for (const i of a) { for (let j of b) { funs.push(function* iter() { yield `fo3: ${i} ${j++}`; }); } } for (const i of a) { for (let j of b) { yield `fo4: ${j}`; funs.push(function* iter() { yield `fo5: ${i} ${j++}`; }); } } for (const i of a) { yield `fo6: ${i}`; for (let j of b) { funs.push(function* iter() { yield `fo7: ${i} ${j++}`; }); } } for (const i of a) { yield `fo8 ${i}`; for (let j of b) { yield `fo9: ${i}`; funs.push(function* iter() { yield `fo10: ${i} ${j++}`; }); } } for (const i of funs) yield* i(); funs.length = 0; for (const i of a) { funs.push(function* iter() { yield `fo11: ${i}`; }); } for (const i of a) { yield `fo12 ${i}`; funs.push(function* iter() { yield `fo13 ${i}`; }); } let k = 0; for (const i of a) { yield `fo14 ${i} ${k} {m}`; let m = k; k++; if (k === 3) continue; if (k === 5) break; funs.push(function* iter() { yield `fo15 ${i} ${k} {m}`; }); } k = 0; up1: for (const i of a) { let m = k; k++; for (const j of b) { let n = m; m++; if (k === 3) continue up1; if (k === 5) break up1; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo18: ${i} ${j} ${k} ${m} ${n}`; }); } } k = 0; up2: for (const i of a) { let m = 0; k++; yield `fo16: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; if (k === 3) continue up2; if (k === 5) break up2; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo18: ${i} ${j} ${k} ${m} ${n}`; }); } } k = 0; up3: for (const i of a) { let m = 0; k++; for (const j of b) { let n = m; m++; yield `fo19 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) { continue up3; } if (k === 5) break up3; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo20: ${i} ${j} ${k} ${m} ${n}`; }); } } bl1: { let k = 0; yield `fo21: ${i} ${k}`; up4: for (const i of a) { let m = 0; k++; yield `fo22: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo23 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up4; if (k === 5) break bl1; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo24: ${i} ${j} ${k} ${m} ${n}`; }); } } } bl2: { let k = 0; yield `fo25`; up5: for (const i of a) { let m = 0; k++; yield `fo26: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo27 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up5; if (k === 5) break bl2; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo28: ${i} ${j} ${k} ${m} ${n}`; }); } } } bl3: { let k = 0; up6: for (const i of a) { let m = 0; k++; yield `fo29: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo30 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up6; if (k === 5) { for (const i of funs) yield* i(); return `r: ${i} ${j} ${k} ${m} ${n}`; } if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo31: ${i} ${j} ${k} ${m} ${n}`; }); } } } }
awto/effectfuljs
packages/core/test/samples/for-of-stmt/closures-in.js
JavaScript
mit
4,231
/* * Webpack development server configuration * * This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if * the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload. */ 'use strict'; import webpack from 'webpack'; import path from 'path'; import autoprefixer from 'autoprefixer'; const API_URL = process.env['__API_URL__'] || 'http://localhost:3001/'; //eslint-disable-line export default { output: { path: path.join(__dirname, '.tmp'), filename: 'bundle.js', publicPath: '/static/' }, devtool: 'eval-source-map', entry: [ 'whatwg-fetch', 'webpack-dev-server/client?http://0.0.0.0:3000', 'webpack/hot/only-dev-server', 'react-hot-loader/patch', './src/index.js' ], module: { preLoaders: [{ test: /\.(js|jsx)$/, exclude: [/node_modules/, /vendor/], loader: 'eslint-loader' }], loaders: [{ test: /\.(js|jsx)$/, include: path.join(__dirname, 'src'), loader: 'babel-loader' }, { test: /\.scss/, loader: 'style-loader!css-loader!postcss-loader!sass-loader' }, { test: /\.json/, loader: 'json-loader' }, { test: /\.(png|jpg|ttf|svg|eot|woff|woff2)/, loader: 'url-loader?limit=8192' }] }, postcss: [ autoprefixer({ browsers: 'last 2 versions' }) ], plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin({ __DEV__: true, __DEVTOOLS__: false, __API_URL__: `\'${API_URL}\'` }) ] };
RiddleMan/giant-privacy-spy
client/webpack.config.js
JavaScript
mit
1,796
// This code will add an event listener to each anchor of the topbar after being dynamically replaced by "interchange" $("body").on("click", function(event){ // If the active element is one of the topbar's links continues if($(event.target).hasClass("topbarLink")) { // The parent li element of the current active link is stored var activeLink = $(event.target).parent(); // Takes each link and checks if its parent li element is active, removing "active" class if so. $("#topNavContent li:not(.divider)").each(function(){ // If the li element has nested li's with links they are checked also. if($(this).hasClass("has-dropdown")){ var dropdownList = $(this).children(".dropdown").children().not(".divider"); dropdownList.each(function(){ if($(this).hasClass("active")){ $(this).removeClass("active"); } }); } // The direct li element's "active" class is removed if($(this).hasClass("active")){ $(this).removeClass("active"); } }); // After having all topbar li elements deactivated, "active" class is added to the currently active link's li parent if(!$(activeLink).hasClass("active")){ $(activeLink).addClass("active"); } } }); // This variable is used to know if this script will be loaded at the time of checking it in the JS manager activeLinkActivatorLoaded = true;
joseAyudarte91/aterbe_web_project
js/commons/activateCurrentLink.js
JavaScript
mit
1,381
const elixir = require('laravel-elixir'); elixir((mix) => { // Mix all Sass files into one mix.sass('app.scss'); // Mix all vendor scripts together mix.scripts( [ 'jquery/dist/jquery.min.js', 'bootstrap-sass/assets/javascripts/bootstrap.min.js', 'bootstrap-sass/assets/javascripts/bootstrap/dropdown.js' ], 'resources/assets/js/vendor.js', 'node_modules' ); // Mix all script files into one mix.scripts( ['vendor.js', 'app.js'], 'public/js/app.js' ); // Copy vendor assets to public mix.copy('node_modules/bootstrap-sass/assets/fonts/bootstrap/','public/fonts/bootstrap') .copy('node_modules/font-awesome/fonts', 'public/fonts'); }); /* var elixir = require('laravel-elixir'); elixir(function(mix) { // Mix all scss files into one css file mix.sass([ 'charts.scss', 'app.scss' ], 'public/css/app.css'); // Mix all chart JS files into a master charts file mix.scriptsIn( 'resources/assets/js/charts', 'public/js/charts.js' ); // Mix common JS files into one file mix.scripts([ 'app.js' ], 'public/js/app.js'); }); */
jamesgifford/perfectlydopey
gulpfile.js
JavaScript
mit
1,236
import {Map} from 'immutable'; export function getInteractiveLayerIds(mapStyle) { let interactiveLayerIds = []; if (Map.isMap(mapStyle) && mapStyle.has('layers')) { interactiveLayerIds = mapStyle.get('layers') .filter(l => l.get('interactive')) .map(l => l.get('id')) .toJS(); } else if (Array.isArray(mapStyle.layers)) { interactiveLayerIds = mapStyle.layers.filter(l => l.interactive) .map(l => l.id); } return interactiveLayerIds; }
RanaRunning/rana
web/src/components/MapGL/utils/style-utils.js
JavaScript
mit
480
var textDivTopIndex = -1; /** * Creates a div that contains a textfiled, a plus and a minus button * @param {String | undefined} textContent string to be added to the given new textField as value * @returns new div */ function createTextDiv( textContent ) { textDivTopIndex++; var newTextDiv = document.createElement("DIV"); newTextDiv.className = "inputTextDiv form-group row"; newTextDiv.id = "uriArray"+textDivTopIndex; newTextDiv.setAttribute("index", textDivTopIndex); //newTextDiv.innerHTML = "hasznaltauto.hu url:"; //textfield that asks for a car uri and its align-responsible container var textField = document.createElement("INPUT"); textField.id = uriInputFieldIdPrefix + textDivTopIndex; textField.type = "url"; textField.name = "carUri"+textDivTopIndex; textField.className = "form-control"; textField.placeholder = "hasznaltauto.hu url"; textField.value = (textContent === undefined) ? "" : textContent; //all textfield has it, but there is to be 10 at maximum so the logic overhead would be greater(always the last one should have it) than this efficiency decrease addEvent( textField, "focus", addOnFocus); var textFieldAlignerDiv = document.createElement("DIV"); textFieldAlignerDiv.className = "col-xs-10 col-sm-10 col-sm-10"; textFieldAlignerDiv.appendChild(textField); //add a new input field, or remove current var inputButtonMinus = document.createElement("BUTTON"); inputButtonMinus.className = "btn btn-default btn-sm col-xs-1 col-sm-1 col-md-1 form-control-static"; inputButtonMinus.type = "button"; //avoid submit, which is default for buttons on forms inputButtonMinus.innerHTML = "-"; inputButtonMinus.id = "inputButtonMinus" + textDivTopIndex; newTextDiv.appendChild(textFieldAlignerDiv); newTextDiv.appendChild(inputButtonMinus); currentInputUriCount++; return newTextDiv } function addOnFocus(event) { if ( isLastField(event.target) && currentInputUriCount < 10 ) { var addedTextDiv = createTextDiv(); formElement.insertBefore(addedTextDiv, sendButtonDiv); event.stopPropagation(); } } function isLastField(field) { textDivTopIndex = 0; $(".inputTextDiv").each(function(index) { textDivTopIndex = ( $(this).attr("index") > textDivTopIndex ) ? $(this).attr("index") : textDivTopIndex; }); return textDivTopIndex == field.parentElement.parentElement.getAttribute("index") || currentInputUriCount === 1; }
amdor/skyscraper_fes
DOMBuilder/InputElementBuilder.js
JavaScript
mit
2,501
'use strict'; /** * Stripe library * * @module core/lib/c_l_stripe * @license MIT * @copyright 2016 Chris Turnbull <https://github.com/christurnbull> */ module.exports = function(app, db, lib) { return { /** * Donate */ donate: function(inObj, cb) { var number, expiry, cvc, currency; try { number = parseInt(inObj.body.number); var exp = inObj.body.expiry.split('/'); expiry = { month: parseInt(exp[0]), year: parseInt(exp[1]) }; cvc = parseInt(inObj.body.cvc); currency = inObj.body.currency.toLowerCase(); } catch (e) { return cb([{ msg: 'Invalid details.', desc: 'Payment has not been made' }], null); } // stripe supported zero-decimal currencies var zeroDecimal = { BIF: 'Burundian Franc', CLP: 'Chilean Peso', DJF: 'Djiboutian Franc', GNF: 'Guinean Franc', JPY: 'Japanese Yen', KMF: 'Comorian Franc', KRW: 'South Korean Won', MGA: 'Malagasy Ariary', PYG: 'Paraguayan Guaraní', RWF: 'Rwandan Franc', VND: 'Vietnamese Đồng', VUV: 'Vanuatu Vatu', XAF: 'Central African Cfa Franc', XOF: 'West African Cfa Franc', XPF: 'Cfp Franc' }; var amount = inObj.body.amount; if (!zeroDecimal.hasOwnProperty(currency.toUpperCase())) { // all other supoprted currencies are decimal amount = amount * 100; } var stripeData = { amount: amount, currency: currency.toLowerCase(), description: 'Donation from ' + inObj.body.name, source: { number: number, exp_month: expiry.month, exp_year: expiry.year, cvc: cvc, object: 'card', customer: inObj.body.customer, email: inObj.body.email } }; lib.core.stripe.charges.create(stripeData, function(err, charge) { if (err) { return cb(err, null); } // save to database etc... return cb(null, [charge]); }); } }; };
christurnbull/MEANr-api
src/core/lib/c_l_stripePay.js
JavaScript
mit
2,158
/* artifact generator: C:\My\wizzi\v5\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js primary source IttfDocument: c:\my\wizzi\v5\plugins\wizzi-core\src\ittf\root\legacy.js.ittf */ 'use strict'; module.exports = require('wizzi-legacy-v4');
wizzifactory/wizzi-core
legacy.js
JavaScript
mit
259
#!/bin/env node 'use strict'; var winston = require('winston'), path = require('path'), mcapi = require('mailchimp-api'), Parser = require('./lib/parser'), ApiWrapper = require('./lib/api-wrapper'); var date = new Date(); date = date.toJSON().replace(/(-|:)/g, '.'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level: 'silly'}); winston.add(winston.transports.File, { filename: path.join('./', 'logs', 'sxla' + date + '.log'), level: 'silly', timestamp: true }); winston.info('*********** APPLICATION STARTED ***********'); var apiKey = process.env.MAILCHIMP_SXLA_API_KEY; var listId = process.env.MAILCHIMP_SXLA_LIST_ID; winston.debug('apiKey: ', apiKey); winston.debug('listId: ', listId); var api = new ApiWrapper(mcapi, apiKey, listId, winston); var parser = new Parser(winston); parser.parseCsv(__dirname + '/data/soci14-15.csv', function (data) { api.batchSubscribe(data); });
napcoder/sxla-mailchimp-importer
app.js
JavaScript
mit
959
module.exports = { normalizeEntityName: function() {}, afterInstall: function() { this.addBowerPackageToProject('jsoneditor'); } };
jayphelps/ember-jsoneditor
blueprints/ember-jsoneditor/index.js
JavaScript
mit
143
import AMD from '../../amd/src/amd.e6'; import Core from '../../core/src/core.e6'; import Event from '../../event/src/event.e6'; import Detect from '../../detect/src/detect.e6'; import Module from '../../modules/src/base.es6'; import ModulesApi from '../../modules/src/api.e6'; window.Moff = new Core(); window.Moff.amd = new AMD(); window.Moff.event = new Event(); window.Moff.Module = new Module(); window.Moff.detect = new Detect(); window.Moff.modules = new ModulesApi();
kfuzaylov/moff
packages/loader/src/loader.e6.js
JavaScript
mit
477
/** * Module dependencies */ const express = require('express'); const cluster = require('cluster'); const numCPUs = require('os').cpus().length; const compression = require('compression'); const helmet = require('helmet'); const hpp = require('hpp'); const config = require('./config'); const api = require('./api'); const pages = require('./app'); /** * Create app and router */ const app = express(); /** * Set express trust proxy */ app.set('trust proxy', true); /** * Set static directory */ app.use(express.static(__dirname + '/public')); /** * Add middlewares */ app.use(compression()); app.use(helmet()); app.use(hpp()); /** * Ping route */ app.get('/ping', (req, res) => res.send('Pong')); /** * Add router */ app.use('/api', api); /** * Mount template router */ app.use('/', pages); /** * Port */ const port = process.env.PORT || config.server.port; /** * Cluster */ if (cluster.isMaster) { for (let i = 0; i < numCPUs; i += 1) { cluster.fork(); } cluster.on('online', (worker) => { console.log(`Worker ${worker.process.pid} is online`); }); cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died`); console.log('Starting a new worker'); cluster.fork(); }); } else { app.listen(port, '0.0.0.0', () => { console.log(`App listening on port ${port}.`); }); } /** * Handle unhandled exceptions */ process.on('unhandledException', err => console.log(err.toString())); /** * Expose app */ module.exports = app;
pazguille/haysubte
index.js
JavaScript
mit
1,517
'use strict'; /* * * angular-socialshare v0.0.2 * * ♡ CopyHeart 2014 by Dayanand Prabhu http://djds4rce.github.io * * Copying is an act of love. Please copy. * */ angular.module('djds4rce.angular-socialshare', []) .factory('$FB', ['$window', function($window) { return { init: function(fbId) { if (fbId) { this.fbId = fbId; $window.fbAsyncInit = function() { FB.init({ appId: fbId, channelUrl: 'app/channel.html', status: true, xfbml: true }); }; (function(d) { var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) { return; } js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); } else { throw ("FB App Id Cannot be blank"); } } }; }]).directive('facebook', ['$http', function($http) { return { scope: { callback: '=', shares: '=' }, transclude: true, template: '<div class="facebookButton">' + '<div class="pluginButton">' + '<div class="pluginButtonContainer">' + '<div class="pluginButtonImage">' + '<button type="button">' + '<i class="pluginButtonIcon img sp_plugin-button-2x sx_plugin-button-2x_favblue"></i>' + '</button>' + '</div>' + '<span class="pluginButtonLabel">Share</span>' + '</div>' + '</div>' + '</div>' + '<div class="facebookCount">' + '<div class="pluginCountButton pluginCountNum">' + '<span ng-transclude></span>' + '</div>' + '<div class="pluginCountButtonNub"><s></s><i></i></div>' + '</div>', link: function(scope, element, attr) { attr.$observe('url', function() { if (attr.shares && attr.url) { $http.get('https://api.facebook.com/method/links.getStats?urls=' + attr.url + '&format=json', {withCredentials: false}).success(function(res) { var count = (res[0] && res[0].total_count) ? res[0].total_count.toString() : 0; var decimal = ''; if (count.length > 6) { if (count.slice(-6, -5) != "0") { decimal = '.' + count.slice(-6, -5); } count = count.slice(0, -6); count = count + decimal + 'M'; } else if (count.length > 3) { if (count.slice(-3, -2) != "0") { decimal = '.' + count.slice(-3, -2); } count = count.slice(0, -3); count = count + decimal + 'k'; } scope.shares = count; }).error(function() { scope.shares = 0; }); } element.unbind(); element.bind('click', function(e) { FB.ui({ method: 'share', href: attr.url }, function(response){ if (scope.callback !== undefined && typeof scope.callback === "function") { scope.callback(response); } }); e.preventDefault(); }); }); } }; }]).directive('facebookFeedShare', ['$http', function($http) { return { scope: { callback: '=', shares: '=' }, transclude: true, template: '<div class="facebookButton">' + '<div class="pluginButton">' + '<div class="pluginButtonContainer">' + '<div class="pluginButtonImage">' + '<button type="button">' + '<i class="pluginButtonIcon img sp_plugin-button-2x sx_plugin-button-2x_favblue"></i>' + '</button>' + '</div>' + '<span class="pluginButtonLabel">Share</span>' + '</div>' + '</div>' + '</div>' + '<div class="facebookCount">' + '<div class="pluginCountButton pluginCountNum">' + '<span ng-transclude></span>' + '</div>' + '<div class="pluginCountButtonNub"><s></s><i></i></div>' + '</div>', link: function(scope, element, attr) { attr.$observe('url', function() { if (attr.shares && attr.url) { $http.get('https://api.facebook.com/method/links.getStats?urls=' + attr.url + '&format=json', {withCredentials: false}).success(function(res) { var count = res[0] ? res[0].total_count.toString() : 0; var decimal = ''; if (count.length > 6) { if (count.slice(-6, -5) != "0") { decimal = '.' + count.slice(-6, -5); } count = count.slice(0, -6); count = count + decimal + 'M'; } else if (count.length > 3) { if (count.slice(-3, -2) != "0") { decimal = '.' + count.slice(-3, -2); } count = count.slice(0, -3); count = count + decimal + 'k'; } scope.shares = count; }).error(function() { scope.shares = 0; }); } element.unbind(); element.bind('click', function(e) { FB.ui({ method: 'feed', link: attr.url, picture: attr.picture, name: attr.name, caption: attr.caption, description: attr.description }, function(response){ if (scope.callback !== undefined && typeof scope.callback === "function") { scope.callback(response); } }); e.preventDefault(); }); }); } }; }]).directive('twitter', ['$timeout', function($timeout) { return { link: function(scope, element, attr) { var renderTwitterButton = debounce(function() { if (attr.url) { $timeout(function() { element[0].innerHTML = ''; twttr.widgets.createShareButton( attr.url, element[0], function() {}, { count: attr.count, text: attr.text, via: attr.via, size: attr.size } ); }); } }, 75); attr.$observe('url', renderTwitterButton); attr.$observe('text', renderTwitterButton); } }; }]).directive('linkedin', ['$timeout', '$http', '$window', function($timeout, $http, $window) { return { scope: { shares: '=' }, transclude: true, template: '<div class="linkedinButton">' + '<div class="pluginButton">' + '<div class="pluginButtonContainer">' + '<div class="pluginButtonImage">in' + '</div>' + '<span class="pluginButtonLabel"><span>Share</span></span>' + '</div>' + '</div>' + '</div>' + '<div class="linkedinCount">' + '<div class="pluginCountButton">' + '<div class="pluginCountButtonRight">' + '<div class="pluginCountButtonLeft">' + '<span ng-transclude></span>' + '</div>' + '</div>' + '</div>' + '</div>', link: function(scope, element, attr) { var renderLinkedinButton = debounce(function() { if (attr.shares && attr.url) { $http.jsonp('https://www.linkedin.com/countserv/count/share?url=' + attr.url + '&callback=JSON_CALLBACK&format=jsonp').success(function(res) { scope.shares = res.count.toLocaleString(); }).error(function() { scope.shares = 0; }); } $timeout(function() { element.unbind(); element.bind('click', function() { var url = encodeURIComponent(attr.url).replace(/'/g, "%27").replace(/"/g, "%22") $window.open("//www.linkedin.com/shareArticle?mini=true&url=" + url + "&title=" + attr.title + "&summary=" + attr.summary); }); }); }, 100); attr.$observe('url', renderLinkedinButton); attr.$observe('title', renderLinkedinButton); attr.$observe('summary', renderLinkedinButton); } }; }]).directive('gplus', [function() { return { link: function(scope, element, attr) { var googleShare = debounce(function() { if (typeof gapi == "undefined") { (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/platform.js'; po.onload = renderGoogleButton; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); } else { renderGoogleButton(); } }, 100); //voodo magic var renderGoogleButton = (function(ele, attr) { return function() { var googleButton = document.createElement('div'); var id = attr.id || randomString(5); attr.id = id; googleButton.setAttribute('id', id); element.innerHTML = ''; element.append(googleButton); if (attr.class && attr.class.indexOf('g-plusone') != -1) { window.gapi.plusone.render(id, attr); } else { window.gapi.plus.render(id, attr); } } }(element, attr)); attr.$observe('href', googleShare); } }; }]).directive('tumblrText', [function() { return { link: function(scope, element, attr) { var tumblr_button = document.createElement("a"); var renderTumblrText = debounce(function() { tumblr_button.setAttribute("href", "https://www.tumblr.com/share/link?url=" + encodeURIComponent(attr.url) + "&name=" + encodeURIComponent(attr.name) + "&description=" + encodeURIComponent(attr.description)); tumblr_button.setAttribute("title", attr.title || "Share on Tumblr"); tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;"); element[0].innerHTML = ''; element.append(tumblr_button); }, 100); attr.$observe('url', renderTumblrText); attr.$observe('name', renderTumblrText); attr.$observe('description', renderTumblrText); } } }]).directive('tumblrQoute', [function() { return { link: function(scope, element, attr) { var tumblr_button = document.createElement("a"); var renderTumblrQoute = debounce(function() { tumblr_button.setAttribute("href", "https://www.tumblr.com/share/quote?quote=" + encodeURIComponent(attr.qoute) + "&source=" + encodeURIComponent(attr.source)); tumblr_button.setAttribute("title", attr.title || "Share on Tumblr"); tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;"); element[0].innerHTML = ''; element.append(tumblr_button); }, 100); attr.$observe('qoute', renderTumblrQoute); attr.$observe('source', renderTumblrQoute); } } }]).directive('tumblrImage', [function() { return { link: function(scope, element, attr) { var tumblr_button = document.createElement("a"); var renderTumblrImage = debounce(function() { tumblr_button.setAttribute("href", "https://www.tumblr.com/share/photo?source=" + encodeURIComponent(attr.source) + "&caption=" + encodeURIComponent(attr.caption) + "&clickthru=" + encodeURIComponent(attr.clickthru)); tumblr_button.setAttribute("title", attr.title || "Share on Tumblr"); tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;"); element[0].innerHTML = ''; element.append(tumblr_button); }, 100); attr.$observe('source', renderTumblrImage); attr.$observe('caption', renderTumblrImage); attr.$observe('clickthru', renderTumblrImage); } } }]).directive('tumblrVideo', [function() { return { link: function(scope, element, attr) { var tumblr_button = document.createElement("a"); var renderTumblrVideo = debounce(function() { tumblr_button.setAttribute("href", "https://www.tumblr.com/share/video?embed=" + encodeURIComponent(attr.embedcode) + "&caption=" + encodeURIComponent(attr.caption)); tumblr_button.setAttribute("title", attr.title || "Share on Tumblr"); tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;"); element[0].innerHTML = ''; element.append(tumblr_button); }, 100); attr.$observe('embedcode', renderTumblrVideo); attr.$observe('caption', renderTumblrVideo); } } }]).directive('pintrest', ['$window', '$timeout', function($window, $timeout) { return { template: '<a href="{{href}}" data-pin-do="{{pinDo}}" data-pin-config="{{pinConfig}}"><img src="//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png" /></a>', link: function(scope, element, attr) { var pintrestButtonRenderer = debounce(function() { var pin_button = document.createElement("a"); pin_button.setAttribute("href", '//www.pinterest.com/pin/create/button/?url=' + encodeURIComponent(attr.href) + '&media=' + encodeURIComponent(attr.img) + '&description=' + encodeURIComponent(attr.description)); pin_button.setAttribute("pinDo", attr.pinDo || "buttonPin"); pin_button.setAttribute("pinConfig", attr.pinConfig || "beside"); element[0].innerHTML = ''; element.append(pin_button); $timeout(function() { $window.parsePins(element); }); }, 100); attr.$observe('href', pintrestButtonRenderer); attr.$observe('img', pintrestButtonRenderer); attr.$observe('description', pintrestButtonRenderer); } } }]); //Simple Debounce Implementation //http://davidwalsh.name/javascript-debounce-function function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; //http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript /** * RANDOM STRING GENERATOR * * Info: http://stackoverflow.com/a/27872144/383904 * Use: randomString(length [,"A"] [,"N"] ); * Default: return a random alpha-numeric string * Arguments: If you use the optional "A", "N" flags: * "A" (Alpha flag) return random a-Z string * "N" (Numeric flag) return random 0-9 string */ function randomString(len, an) { an = an && an.toLowerCase(); var str = "", i = 0, min = an == "a" ? 10 : 0, max = an == "n" ? 10 : 62; for (; i++ < len;) { var r = Math.random() * (max - min) + min << 0; str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48); } return str; }
khiettran/gofar
public/scripts/libs/bower/angular-socialshare.js
JavaScript
mit
14,491
angular.module('myApp.toDoController', []). controller('ToDoCtrl', ['$scope', '$state', '$http', '$route', function ($scope, $state, $http, $route) { $scope.$state = $state; $scope.addToDo = function() { // Just in case... if ($scope.toDoList.length > 50) { alert("Exceeded to-do limit!!!"); return; } if (!$scope.newToDoName || !$scope.newToDoDesc) { alert("Please fill out both fields!"); return; } var newToDo = { 'todo': $scope.newToDoName, 'description': $scope.newToDoDesc }; $http.post('/to-dos/add-to-do', newToDo). success(function(data, status, headers, config) { }). then(function(answer){ $scope.newToDoName = ''; $scope.newToDoDesc = ''; getToDos(); }); }; $scope.editToDoId = ''; $scope.editToDo = function(toDo) { // Set the ID of the todo being edited $scope.editToDoId = toDo._id; // Reset the to do list in case we were editing other to dos getToDos(); }; $scope.confirmEditToDo = function() { // Get the data from the ToDo of interest var toDoToEdit = ''; for (var i=0; i<$scope.toDoList.length; i++) { if ($scope.toDoList[i]._id === $scope.editToDoId){ toDoToEdit = { "todo" : $scope.toDoList[i].todo, "description" : $scope.toDoList[i].description }; break; } } if (!toDoToEdit) { alert("Could not get edited to-do!"); return; } else if (!toDoToEdit.todo || !toDoToEdit.description) { alert("Please fill out both fields!"); return; } $http.put('/to-dos/update-to-do/' + $scope.editToDoId, toDoToEdit). success(function(data, status, headers, config) { $scope.editToDoId = ''; }). then(function(answer){ getToDos(); }); }; $scope.deleteToDo = function(toDo) { var confirmation = confirm('Are you sure you want to delete?'); if (!confirmation){ return; } $http.delete('/to-dos/delete-to-do/' + toDo._id). success(function(data, status, headers, config) { }). then(function(answer){ getToDos(); }); }; $scope.cancelEditToDo = function() { $scope.editToDoId = ''; getToDos(); }; var getToDos = function() { $http.get('/to-dos/to-dos').success(function(data, status, headers, config) { $scope.toDoList = data; }); }; // Execute these functions on page load angular.element(document).ready(function () { getToDos(); }); }]);
The-Lando-System/personal-website
app/to-do/toDoController.js
JavaScript
mit
2,424
import CommuniqueApp from './communique-app'; CommuniqueApp.open();
kramerc/communique
lib/browser/main.js
JavaScript
mit
68
module.exports = [ 'babel-polyfill', 'react', 'react-redux', 'react-router', 'react-dom', 'redux', 'redux-thunk', 'seamless-immutable', 'react-router-redux', 'history', 'lodash', 'styled-components', 'prop-types', ];
CheerfulYeti/React-Redux-Starter-Kit
webpack.vendor.js
JavaScript
mit
243
import nextConnect from 'next-connect' import auth from '../../middleware/auth' import { deleteUser, updateUserByUsername } from '../../lib/db' const handler = nextConnect() handler .use(auth) .get((req, res) => { // You do not generally want to return the whole user object // because it may contain sensitive field such as !!password!! Only return what needed // const { name, username, favoriteColor } = req.user // res.json({ user: { name, username, favoriteColor } }) res.json({ user: req.user }) }) .use((req, res, next) => { // handlers after this (PUT, DELETE) all require an authenticated user // This middleware to check if user is authenticated before continuing if (!req.user) { res.status(401).send('unauthenticated') } else { next() } }) .put((req, res) => { const { name } = req.body const user = updateUserByUsername(req, req.user.username, { name }) res.json({ user }) }) .delete((req, res) => { deleteUser(req) req.logOut() res.status(204).end() }) export default handler
flybayer/next.js
examples/with-passport-and-next-connect/pages/api/user.js
JavaScript
mit
1,087
!function(a){var b,c,d;return a.localStorage||(c={setItem:function(a,b,c){var d,e;return null==c&&(c=!1),d=c?-1:30,e=new Date,e.setDate(e.getDate()+d),document.cookie=""+a+"="+escape(b)+"; expires="+e.toUTCString()},getItem:function(a){return document.cookie.indexOf(-1!==""+a+"=")?unescape(document.cookie.split(""+a+"=")[1].split(";")[0].replace("=","")):!1},removeItem:function(a){return this.setItem(a,"",!0)}}),d=localStorage||c,b=function(){function a(b){return this.key=b,this instanceof a?this:new a(this.key)}return a.prototype.key=null,a.prototype.get=function(){var a,b;a=d.getItem(this.key);try{return JSON.parse(a)}catch(c){return b=c,a}},a.prototype.set=function(a){var b;try{JSON.parse(a)}catch(c){b=c,a=JSON.stringify(a)}return d.setItem(this.key,a),this},a.prototype.remove=function(){return d.removeItem(this.key),this},a}(),a.Wafer=b}(window);
calebrash/wafer
dist/wafer.min.js
JavaScript
mit
862
import { injectReducer } from 'STORE/reducers' export default store => ({ path : 'checkHistoryList.html', getComponent(nextState, cb) { require.ensure([], (require) => { const CheckHistoryList = require('VIEW/CheckHistoryList').default const reducer = require('REDUCER/checkHistoryList').default injectReducer(store, { key: 'checkHistoryList', reducer }) cb(null, CheckHistoryList) }, 'checkHistoryList') } })
OwlAford/IFP
src/routes/main/checkHistoryList.js
JavaScript
mit
449
;(function() { angular.module('app.core') .config(config); /* @ngInject */ function config($stateProvider, $locationProvider, $urlRouterProvider) { $stateProvider /** * @name landing * @type {route} * @description First page for incoming users, and for default routing * for all failed routes. */ .state('landing', { url: '/', templateUrl: '/html/modules/landing/landing.html', controller: 'LandingController', controllerAs: 'vm' }) /** * @name home * @type {route} * @description User landing page, the main display. */ .state('home', { url: '', abstract: true, views: { '': { templateUrl: 'html/modules/home/template.html' }, 'current-routes@home': { templateUrl: 'html/modules/layout/current-routes.html', controller: 'CurrentRoutesController', controllerAs: 'vm' }, 'add-routes@home': { templateUrl: 'html/modules/layout/add-routes.html', controller: 'AddRoutesController', controllerAs: 'vm' } } }) .state('home.home', { url: '/home', authenticate: true, views: { 'container@home': { templateUrl: 'html/modules/home/welcome.html' } } }) .state('home.new-route', { url: '/new-route/:route', authenticate: true, views: { 'container@home': { templateUrl: 'html/modules/routes/new-route.html', controller: 'NewRouteController', controllerAs: 'vm' } } }) /** * @name editRoute * @type {route} * @description View for editing a specific route. Provides options * to edit or delete the route. */ .state('home.edit-route', { url: '/routes/{route:.*}', authenticate: true, views: { 'container@home': { templateUrl: '/html/modules/routes/edit-routes.html', controller: 'EditRoutesController', controllerAs: 'vm', } } }) /** * @name Docs * @type {route} * @description View for the project documentation * */ .state('docs',{ url:'', abstract: true, views: { '': { templateUrl: '/html/modules/docs/docs.html' }, 'doc-list@docs': { templateUrl: '/html/modules/docs/docs-list.html', controller: 'DocsController', controllerAs: 'vm' } } }) .state('docs.docs', { url: '/docs', views: { 'container@docs': { templateUrl: '/html/modules/docs/current-doc.html' } } }) .state('docs.current-doc', { url: '/docs/:doc', views: { 'container@docs': { templateUrl: function($stateParams) { return '/html/modules/docs/pages/' + $stateParams.doc + '.html'; } } } }) .state('home.analytics', { url: '/analytics/{route:.*}', authenticate: true, views: { 'container@home': { templateUrl: '/html/modules/analytics/analytics.html', controller: 'AnalyticsController', controllerAs: 'vm' } } }); // default uncaught routes to landing page $urlRouterProvider.otherwise('/'); // enable HTML5 mode $locationProvider.html5Mode(true); } }).call(this);
radiant-persimmons/mockr
src/client/app/core/config/routes.config.js
JavaScript
mit
3,748
import Route from '@ember/routing/route'; import { A } from '@ember/array'; import { hash } from 'rsvp'; import EmberObject from '@ember/object' export default Route.extend({ model: function() { return hash({ exampleModel: EmberObject.create(), disableSubmit: false, selectedLanguage: null, selectOptions: A([ {label: 'French', value: 'fr'}, {label: 'English', value: 'en'}, {label: 'German', value: 'gr'} ]), radioOptions: A([ {label: 'Ruby', value: 'ruby'}, {label: 'Javascript', value: 'js'}, {label: 'Cold Fusion', value: 'cf'} ]) }); }, actions: { submit: function() { window.alert('You triggered a form submit!'); }, toggleErrors: function() { var model = this.get('currentModel').exampleModel; if(model.get('errors')) { model.set('errors', null); }else{ var errors = { first_name: A(['That first name is wrong']), last_name: A(['That last name is silly']), language: A(['Please choose a better language']), isAwesome: A(['You must be awesome to submit this form']), bestLanguage: A(['Wrong, Cold Fusion is the best language']), essay: A(['This essay is not very good']) }; model.set('errors', errors); } }, toggleSelectValue: function() { if(this.get('currentModel.exampleModel.language')) { this.set('currentModel.exampleModel.language', null); }else{ this.set('currentModel.exampleModel.language', 'fr'); } }, toggleSubmit: function() { if(this.get('currentModel.disableSubmit')) { this.set('currentModel.disableSubmit', false); }else{ this.set('currentModel.disableSubmit', true); } }, toggleCheckbox: function() { if(this.get('currentModel.exampleModel.isAwesome')) { this.set('currentModel.exampleModel.isAwesome', false); } else { this.set('currentModel.exampleModel.isAwesome', true); } }, toggleRadio: function() { if(this.get('currentModel.exampleModel.bestLanguage')) { this.set('currentModel.exampleModel.bestLanguage', null); }else{ this.set('currentModel.exampleModel.bestLanguage', 'js'); } } } });
Emerson/ember-form-master-2000
tests/dummy/app/routes/application.js
JavaScript
mit
2,343
import lowerCaseFirst from 'lower-case-first'; import {handles} from 'marty'; import Override from 'override-decorator'; function addHandlers(ResourceStore) { const {constantMappings} = this; return class ResourceStoreWithHandlers extends ResourceStore { @Override @handles(constantMappings.getMany.done) getManyDone(payload) { super.getManyDone(payload); this.hasChanged(); } @Override @handles(constantMappings.getSingle.done) getSingleDone(payload) { super.getSingleDone(payload); this.hasChanged(); } @handles( constantMappings.postSingle.done, constantMappings.putSingle.done, constantMappings.patchSingle.done ) changeSingleDone(args) { // These change actions may return the inserted or modified object, so // update that object if possible. if (args.result) { this.getSingleDone(args); } } }; } function addFetch( ResourceStore, { actionsKey = `${lowerCaseFirst(this.name)}Actions` } ) { const {methodNames, name, plural} = this; const {getMany, getSingle} = methodNames; const refreshMany = `refresh${plural}`; const refreshSingle = `refresh${name}`; return class ResourceStoreWithFetch extends ResourceStore { getActions() { return this.app[actionsKey]; } [getMany](options, {refresh} = {}) { return this.fetch({ id: `c${this.collectionKey(options)}`, locally: () => this.localGetMany(options), remotely: () => this.remoteGetMany(options), refresh }); } [refreshMany](options) { return this[getMany](options, {refresh: true}); } localGetMany(options) { return super[getMany](options); } remoteGetMany(options) { return this.getActions()[getMany](options); } [getSingle](id, options, {refresh} = {}) { return this.fetch({ id: `i${this.itemKey(id, options)}`, locally: () => this.localGetSingle(id, options), remotely: () => this.remoteGetSingle(id, options), refresh }); } [refreshSingle](id, options) { return this[getSingle](id, options, {refresh: true}); } localGetSingle(id, options) { return super[getSingle](id, options); } remoteGetSingle(id, options) { return this.getActions()[getSingle](id, options); } fetch({refresh, ...options}) { if (refresh) { const baseLocally = options.locally; options.locally = function refreshLocally() { if (refresh) { refresh = false; return undefined; } else { return this::baseLocally(); } }; } return super.fetch(options); } }; } export default function extendStore( ResourceStore, { useFetch = true, ...options } ) { ResourceStore = this::addHandlers(ResourceStore, options); if (useFetch) { ResourceStore = this::addFetch(ResourceStore, options); } return ResourceStore; }
taion/flux-resource-marty
src/store.js
JavaScript
mit
3,040
$('.js-toggle-menu').click(function(e){ e.preventDefault(); $(this).siblings().toggle(); }); $('.nav--primary li').click(function(){ $(this).find('ul').toggleClass('active'); });
sudojesse/sdb
js/main.js
JavaScript
mit
182
function solve(message) { let tagValidator = /^<message((?:\s+[a-z]+="[A-Za-z0-9 .]+"\s*?)*)>((?:.|\n)+?)<\/message>$/; let tokens = tagValidator.exec(message); if (!tokens) { console.log("Invalid message format"); return; } let [match, attributes, body] = tokens; let attributeValidator = /\s+([a-z]+)="([A-Za-z0-9 .]+)"\s*?/g; let sender = ''; let recipient = ''; let attributeTokens = attributeValidator.exec(attributes); while (attributeTokens) { if (attributeTokens[1] === 'to') { recipient = attributeTokens[2]; } else if (attributeTokens[1] === 'from') { sender = attributeTokens[2]; } attributeTokens = attributeValidator.exec(attributes); } if (sender === '' || recipient === '') { console.log("Missing attributes"); return; } body = body.replace(/\n/g, '</p>\n <p>'); let html = `<article>\n <div>From: <span class="sender">${sender}</span></div>\n`; html += ` <div>To: <span class="recipient">${recipient}</span></div>\n`; html += ` <div>\n <p>${body}</p>\n </div>\n</article>`; console.log(html); } solve(`<message from="John Doe" to="Alice">Not much, just chillin. How about you?</message>`); /* solve( `<message to="Bob" from="Alice" timestamp="1497254092">Hey man, what's up?</message>`, `<message from="Ivan Ivanov" to="Grace">Not much, just chillin. How about you?</message>` ); */
kalinmarkov/SoftUni
JS Core/JS Fundamentals/Exams/03. XML Messenger.js
JavaScript
mit
1,486
'use strict'; const test = require('ava'); const hashSet = require('../index'); const MySet = hashSet(x => x); test('should not change empty set', t => { const set = new MySet(); set.clear(); t.is(set.size, 0); }); test('should clear set', t => { const set = new MySet(); set.add(1); set.clear(); t.is(set.size, 0); });
blond/hash-set
test/clear.js
JavaScript
mit
356
'use strict'; const path = require('path'); const jwt = require('jsonwebtoken'); const AuthConfig = require(path.resolve('./config')).Auth; const jwtSecret = AuthConfig.jwt.secret; const tokenExpirePeriod = AuthConfig.jwt.tokenExpirePeriod; function generateToken(payLoad) { const isObject = (typeof payLoad === 'object'); if (payLoad) { if (isObject) { return new Promise((resolve, reject) => { jwt.sign(payLoad, jwtSecret, { expiresIn: tokenExpirePeriod }, (error, token) => { if (error) { reject(error); } else { resolve(token); } }); }) } else { const error = new TypeError('Token Payload Must Be An Object'); return Promise.reject(error); } } else { const error = new Error('Token Payload Should Not Be Empty'); return Promise.reject(error); } } function verifyToken(token) { if (token) { return new Promise((resolve, reject) => { jwt.verify(token, jwtSecret, (error, decodedToken) => { if (error) { reject(error); } else { resolve(decodedToken); } }); }) } else { const error = new Error('Token Should Not Be Empty'); return Promise.reject(error); } } module.exports = { generate: generateToken, verify: verifyToken };
shivarajnaidu/uv-token-based-auth-with-nodejs-passportjs-mysql
app/lib/token.js
JavaScript
mit
1,542
/*! Slidebox.JS - v1.0 - 2013-11-30 * http://github.com/trevanhetzel/slidebox * * Copyright (c) 2013 Trevan Hetzel <trevan.co>; * Licensed under the MIT license */ slidebox = function (params) { // Carousel carousel = function () { var $carousel = $(params.container).children(".carousel"), $carouselItem = $(".carousel li"), $triggerLeft = $(params.leftTrigger), $triggerRight = $(params.rightTrigger), total = $carouselItem.length, current = 0; var moveLeft = function () { if ( current > 0 ) { $carousel.animate({ "left": "+=" + params.length + "px" }, params.speed ); current--; } }; var moveRight = function () { if ( current < total - 2 ) { $carousel.animate({ "left": "-=" + params.length + "px" }, params.speed ); current++; } }; // Initiliaze moveLeft on trigger click $triggerLeft.on("click", function () { moveLeft(); }); // Initiliaze moveRight on trigger click $triggerRight.on("click", function () { moveRight(); }); // Initiliaze moveLeft on left keypress $(document).keydown(function (e){ if (e.keyCode == 37) { moveLeft(); } }); // Initiliaze moveRight on right keypress $(document).keydown(function (e){ if (e.keyCode == 39) { moveRight(); } }); }, // Lightbox lightbox = function () { var trigger = ".carousel li a"; // Close lightbox when pressing esc key $(document).keydown(function (e){ if (e.keyCode == 27) { closeLightbox(); } }); $(document) // Close lightbox on any click .on("click", function () { closeLightbox(); }) // If clicked on a thumbnail trigger, proceed .on("click", trigger, function (e) { var $this = $(this); // Prevent from clicking through e.preventDefault(); e.stopPropagation(); // Grab the image URL dest = $this.attr("href"); // Grab the caption from data attribute capt = $this.children("img").data("caption"); enlarge(dest, capt); /* If clicked on an enlarged image, stop propagation so it doesn't get the close function */ $(document).on("click", ".lightbox img", function (e) { e.stopPropagation(); }); }); closeLightbox = function () { $(".lightbox-cont").remove(); $(".lightbox").remove(); }, enlarge = function (dest, capt) { // Create new DOM elements $("body").append("<div class='lightbox-cont'></div><div class='lightbox'></div>"); $(".lightbox").html(function () { return "<img src='" + dest + "'><div class='lightbox-caption'>" + capt + "</div>"; }); } } // Initialize functions carousel(); lightbox(); };
trevanhetzel/slidebox
slidebox.js
JavaScript
mit
3,369
import test from 'ava'; import Server from '../../src/server'; import IO from '../../src/socket-io'; test.cb('mock socket invokes each handler with unique reference', t => { const socketUrl = 'ws://roomy'; const server = new Server(socketUrl); const socket = new IO(socketUrl); let handlerInvoked = 0; const handler3 = function handlerFunc() { t.true(true); handlerInvoked += 1; }; // Same functions but different scopes/contexts socket.on('custom-event', handler3.bind(Object.create(null))); socket.on('custom-event', handler3.bind(Object.create(null))); // Same functions with same scope/context (only one should be added) socket.on('custom-event', handler3); socket.on('custom-event', handler3); // not expected socket.on('connect', () => { socket.join('room'); server.to('room').emit('custom-event'); }); setTimeout(() => { t.is(handlerInvoked, 3, 'handler invoked too many times'); server.close(); t.end(); }, 500); }); test.cb('mock socket invokes each handler per socket', t => { const socketUrl = 'ws://roomy'; const server = new Server(socketUrl); const socketA = new IO(socketUrl); const socketB = new IO(socketUrl); let handlerInvoked = 0; const handler3 = function handlerFunc() { t.true(true); handlerInvoked += 1; }; // Same functions but different scopes/contexts socketA.on('custom-event', handler3.bind(socketA)); socketB.on('custom-event', handler3.bind(socketB)); // Same functions with same scope/context (only one should be added) socketA.on('custom-event', handler3); socketA.on('custom-event', handler3); // not expected socketB.on('custom-event', handler3.bind(socketB)); // expected because bind creates a new method socketA.on('connect', () => { socketA.join('room'); socketB.join('room'); server.to('room').emit('custom-event'); }); setTimeout(() => { t.is(handlerInvoked, 4, 'handler invoked too many times'); server.close(); t.end(); }, 500); });
thoov/mock-socket
tests/issues/65.test.js
JavaScript
mit
2,017
import React from 'react' import PropTypes from 'prop-types' import VelocityTrimControls from './VelocityTrimControls' import Instrument from '../../images/Instrument' import styles from '../../styles/velocityTrim' import { trimShape } from '../../reducers/velocityTrim' const handleKeyDown = (event, item, bank, userChangedTrimEnd) => { let delta = 0 event.nativeEvent.preventDefault() switch (event.key) { case 'ArrowUp': delta = 1 break case 'ArrowDown': delta = -1 break case 'PageUp': delta = 5 break case 'PageDown': delta = -5 break case 'Enter': delta = 100 break case 'Escape': delta = -100 break default: break } if (delta !== 0) { delta += item.trim if (delta < 0) delta = 0 if (delta > 100) delta = 100 userChangedTrimEnd(item.note, delta, bank) } } const VelocityTrim = (props) => { const { item, bank, selected, playNote, selectTrim, userChangedTrimEnd } = props const { note, trim, group, name } = item return ( <section tabIndex={note} onKeyDown={e => handleKeyDown(e, item, bank, userChangedTrimEnd)} onMouseUp={() => (selected ? null : selectTrim(note))} className={selected ? styles.selected : ''} role="presentation" > <div className={styles.header} onMouseUp={() => playNote(note, Math.round(127 * (trim / 100)), bank)} role="button" tabIndex={note} > <div>{note}</div> <div>{group}</div> <div>{Instrument(group)}</div> </div> <div className={styles.noteName} title={name} > {name} </div> <VelocityTrimControls {...props} /> </section> ) } VelocityTrim.propTypes = { item: trimShape.isRequired, selected: PropTypes.bool.isRequired, playNote: PropTypes.func.isRequired, selectTrim: PropTypes.func.isRequired, userChangedTrimEnd: PropTypes.func.isRequired, bank: PropTypes.number.isRequired, } export default VelocityTrim
dkadrios/zendrum-stompblock-client
src/components/trims/VelocityTrim.js
JavaScript
mit
2,066
/** * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval * @author James Allardice */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("./utils/ast-utils"); const { getStaticValue } = require("eslint-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "disallow the use of `eval()`-like methods", category: "Best Practices", recommended: false, url: "https://eslint.org/docs/rules/no-implied-eval" }, schema: [], messages: { impliedEval: "Implied eval. Consider passing a function instead of a string." } }, create(context) { const EVAL_LIKE_FUNCS = Object.freeze(["setTimeout", "execScript", "setInterval"]); const GLOBAL_CANDIDATES = Object.freeze(["global", "window", "globalThis"]); /** * Checks whether a node is evaluated as a string or not. * @param {ASTNode} node A node to check. * @returns {boolean} True if the node is evaluated as a string. */ function isEvaluatedString(node) { if ( (node.type === "Literal" && typeof node.value === "string") || node.type === "TemplateLiteral" ) { return true; } if (node.type === "BinaryExpression" && node.operator === "+") { return isEvaluatedString(node.left) || isEvaluatedString(node.right); } return false; } /** * Checks whether a node is an Identifier node named one of the specified names. * @param {ASTNode} node A node to check. * @param {string[]} specifiers Array of specified name. * @returns {boolean} True if the node is a Identifier node which has specified name. */ function isSpecifiedIdentifier(node, specifiers) { return node.type === "Identifier" && specifiers.includes(node.name); } /** * Checks a given node is a MemberExpression node which has the specified name's * property. * @param {ASTNode} node A node to check. * @param {string[]} specifiers Array of specified name. * @returns {boolean} `true` if the node is a MemberExpression node which has * the specified name's property */ function isSpecifiedMember(node, specifiers) { return node.type === "MemberExpression" && specifiers.includes(astUtils.getStaticPropertyName(node)); } /** * Reports if the `CallExpression` node has evaluated argument. * @param {ASTNode} node A CallExpression to check. * @returns {void} */ function reportImpliedEvalCallExpression(node) { const [firstArgument] = node.arguments; if (firstArgument) { const staticValue = getStaticValue(firstArgument, context.getScope()); const isStaticString = staticValue && typeof staticValue.value === "string"; const isString = isStaticString || isEvaluatedString(firstArgument); if (isString) { context.report({ node, messageId: "impliedEval" }); } } } /** * Reports calls of `implied eval` via the global references. * @param {Variable} globalVar A global variable to check. * @returns {void} */ function reportImpliedEvalViaGlobal(globalVar) { const { references, name } = globalVar; references.forEach(ref => { const identifier = ref.identifier; let node = identifier.parent; while (isSpecifiedMember(node, [name])) { node = node.parent; } if (isSpecifiedMember(node, EVAL_LIKE_FUNCS)) { const parent = node.parent; if (parent.type === "CallExpression" && parent.callee === node) { reportImpliedEvalCallExpression(parent); } } }); } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { CallExpression(node) { if (isSpecifiedIdentifier(node.callee, EVAL_LIKE_FUNCS)) { reportImpliedEvalCallExpression(node); } }, "Program:exit"() { const globalScope = context.getScope(); GLOBAL_CANDIDATES .map(candidate => astUtils.getVariableByName(globalScope, candidate)) .filter(globalVar => !!globalVar && globalVar.defs.length === 0) .forEach(reportImpliedEvalViaGlobal); } }; } };
pvamshi/eslint
lib/rules/no-implied-eval.js
JavaScript
mit
5,435
import NodeFunction from '../core/NodeFunction.js'; import NodeFunctionInput from '../core/NodeFunctionInput.js'; const declarationRegexp = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i; const propertiesRegexp = /[a-z_0-9]+/ig; const pragmaMain = '#pragma main'; const parse = ( source ) => { const pragmaMainIndex = source.indexOf( pragmaMain ); const mainCode = pragmaMainIndex !== - 1 ? source.substr( pragmaMainIndex + pragmaMain.length ) : source; const declaration = mainCode.match( declarationRegexp ); if ( declaration !== null && declaration.length === 5 ) { // tokenizer const inputsCode = declaration[ 4 ]; const propsMatches = []; let nameMatch = null; while ( ( nameMatch = propertiesRegexp.exec( inputsCode ) ) !== null ) { propsMatches.push( nameMatch ); } // parser const inputs = []; let i = 0; while ( i < propsMatches.length ) { const isConst = propsMatches[ i ][ 0 ] === 'const'; if ( isConst === true ) { i ++; } let qualifier = propsMatches[ i ][ 0 ]; if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) { i ++; } else { qualifier = ''; } const type = propsMatches[ i ++ ][ 0 ]; let count = Number.parseInt( propsMatches[ i ][ 0 ] ); if ( Number.isNaN( count ) === false ) i ++; else count = null; const name = propsMatches[ i ++ ][ 0 ]; inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) ); } // const blockCode = mainCode.substring( declaration[ 0 ].length ); const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : ''; const type = declaration[ 2 ]; const presicion = declaration[ 1 ] !== undefined ? declaration[ 1 ] : ''; const headerCode = pragmaMainIndex !== - 1 ? source.substr( 0, pragmaMainIndex ) : ''; return { type, inputs, name, presicion, inputsCode, blockCode, headerCode }; } else { throw new Error( 'FunctionNode: Function is not a GLSL code.' ); } }; class GLSLNodeFunction extends NodeFunction { constructor( source ) { const { type, inputs, name, presicion, inputsCode, blockCode, headerCode } = parse( source ); super( type, inputs, name, presicion ); this.inputsCode = inputsCode; this.blockCode = blockCode; this.headerCode = headerCode; } getCode( name = this.name ) { const headerCode = this.headerCode; const presicion = this.presicion; let declarationCode = `${ this.type } ${ name } ( ${ this.inputsCode.trim() } )`; if ( presicion !== '' ) { declarationCode = `${ presicion } ${ declarationCode }`; } return headerCode + declarationCode + this.blockCode; } } export default GLSLNodeFunction;
jpweeks/three.js
examples/jsm/renderers/nodes/parsers/GLSLNodeFunction.js
JavaScript
mit
2,740
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var router_1 = require('@angular/router'); var app_service_1 = require("./app-service"); var AppComponent = (function () { function AppComponent(breadCrumbSvc, _router) { this.breadCrumbSvc = breadCrumbSvc; this._router = _router; this.breadCrumbSvc.setBreadCrumb('Project Dashboard'); } AppComponent.prototype.navigateHome = function () { this._router.navigate(['home']); ; }; AppComponent = __decorate([ core_1.Component({ selector: 'ts-app', templateUrl: '/app/app-component.html' }), __metadata('design:paramtypes', [app_service_1.BreadcrumbService, router_1.Router]) ], AppComponent); return AppComponent; }()); exports.AppComponent = AppComponent;
mail2yugi/ProjectTodoList
src/app/app.component.js
JavaScript
mit
1,606
/** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++i < length) { array[i] = source[i]; } return array; } module.exports = arrayCopy;
gdgzdar/2048
node_modules/karma/node_modules/lodash/internal/arrayCopy.js
JavaScript
mit
442
export default (callback) => { setTimeout(() => { callback(); setTimeout(() => { callback(); }, 3000); }, 3000); }
csxiaoyaojianxian/JavaScriptStudy
13-自动化测试&mock数据/01-jest入门/09-mock-timer.js
JavaScript
mit
158
'use strict' const reduce = Function.bind.call(Function.call, Array.prototype.reduce); const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable); const concat = Function.bind.call(Function.call, Array.prototype.concat); const keys = Reflect.ownKeys; if (!Object.values) { Object.values = (O) => reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []); } if (!Object.entries) { Object.entries = (O) => reduce(keys(O), (e, k) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [ [k, O[k]] ] : []), []); } //from //https://medium.com/@_jh3y/throttling-and-debouncing-in-javascript-b01cad5c8edf#.jlqokoxtu //or //https://remysharp.com/2010/07/21/throttling-function-calls function debounce(callback, delay) { let timeout; return function() { const context = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(() => callback.apply(context, args), delay); }; }; function throttle(func, limit) { let inThrottle, lastFunc, throttleTimer; return function() { const context = this, args = arguments; if (inThrottle) { clearTimeout(lastFunc); return lastFunc = setTimeout(function() { func.apply(context, args); inThrottle = false; }, limit); } else { func.apply(context, args); inThrottle = true; return throttleTimer = setTimeout(() => inThrottle = false, limit); } }; }; /*END POLIFILL*/
vitaliiznak/game-fluky_colors
polifill.js
JavaScript
mit
1,634
var htmlparser = require('htmlparser2'); var _ = require('lodash'); var ent = require('ent'); module.exports = sanitizeHtml; function sanitizeHtml(html, options) { var result = ''; if (!options) { options = sanitizeHtml.defaults; } else { _.defaults(options, sanitizeHtml.defaults); } // Tags that contain something other than HTML. If we are not allowing // these tags, we should drop their content too. For other tags you would // drop the tag but keep its content. var nonTextTagsMap = { script: true, style: true }; var allowedTagsMap = {}; _.each(options.allowedTags, function(tag) { allowedTagsMap[tag] = true; }); var selfClosingMap = {}; _.each(options.selfClosing, function(tag) { selfClosingMap[tag] = true; }); var allowedAttributesMap = {}; _.each(options.allowedAttributes, function(attributes, tag) { allowedAttributesMap[tag] = {}; _.each(attributes, function(name) { allowedAttributesMap[tag][name] = true; }); }); var depth = 0; var skipMap = {}; var skipText = false; var parser = new htmlparser.Parser({ onopentag: function(name, attribs) { var skip = false; if (!_.has(allowedTagsMap, name)) { skip = true; if (_.has(nonTextTagsMap, name)) { skipText = true; } skipMap[depth] = true; } depth++; if (skip) { // We want the contents but not this tag return; } result += '<' + name; if (_.has(allowedAttributesMap, name)) { _.each(attribs, function(value, a) { if (_.has(allowedAttributesMap[name], a)) { result += ' ' + a; if ((a === 'href') || (a === 'src')) { if (naughtyHref(value)) { return; } } if (value.length) { // Values are ALREADY escaped, calling escapeHtml here // results in double escapes result += '="' + value + '"'; } } }); } if (_.has(selfClosingMap, name)) { result += " />"; } else { result += ">"; } }, ontext: function(text) { if (skipText) { return; } // It is NOT actually raw text, entities are already escaped. // If we call escapeHtml here we wind up double-escaping. result += text; }, onclosetag: function(name) { skipText = false; depth--; if (skipMap[depth]) { delete skipMap[depth]; return; } if (_.has(selfClosingMap, name)) { // Already output /> return; } result += "</" + name + ">"; } }); parser.write(html); parser.end(); return result; function escapeHtml(s) { if (s === 'undefined') { s = ''; } if (typeof(s) !== 'string') { s = s + ''; } return s.replace(/\&/g, '&amp;').replace(/</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;'); } function naughtyHref(href) { // So we don't get faked out by a hex or decimal escaped javascript URL #1 href = ent.decode(href); // Browsers ignore character codes of 32 (space) and below in a surprising // number of situations. Start reading here: // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab href = href.replace(/[\x00-\x20]+/, ''); // Case insensitive so we don't get faked out by JAVASCRIPT #1 var matches = href.match(/^([a-zA-Z]+)\:/); if (!matches) { // No scheme = no way to inject js (right?) return false; } var scheme = matches[1].toLowerCase(); return (!_.contains(['http', 'https', 'ftp', 'mailto' ], scheme)); } } // Defaults are accessible to you so that you can use them as a starting point // programmatically if you wish sanitizeHtml.defaults = { allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ], allowedAttributes: { a: [ 'href', 'name', 'target' ], // We don't currently allow img itself by default, but this // would make sense if we did img: [ 'src' ] }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ] };
effello/cms
node_modules/apostrophe/node_modules/sanitize-html/index.js
JavaScript
mit
4,431
(function(){ 'use strict' angular .module("jobDetail") .service("jobDetailService",jobDetailService); jobDetailService.$inject = ['apiService','apiOptions']; function jobDetailService(apiService,apiOptions) { var jobId; this.getJobDetail=function(jobId) { // return "ok"; return apiService.get("job/"+jobId); }; }; })();
dozgunyal/ang-oboy
app/job-detail/job-detail.service.js
JavaScript
mit
351
var STATE_START = 0; var STATE_END = 1; var STATE_GROUND = 2; var STATE_FOREST = 3; var STATE_WATER = 4; function Cell(col, row) { this.col = col; this.row = row; this.state = STATE_GROUND; } Cell.prototype.draw = function() { stroke(66); switch (this.state) { case STATE_START: Color.Material.light_green[5].fill(); break; case STATE_END: Color.Material.red[5].fill(); break; case STATE_GROUND: Color.Material.green[5].fill(); break; case STATE_FOREST: Color.Material.green[9].fill(); break; case STATE_WATER: Color.Material.light_blue[5].fill(); break; default: fill(255, 0, 0); } rect(this.col * scl, this.row * scl, scl, scl); }; Cell.prototype.incrementState = function(bool) { if (bool) { // Cycle from 0 to 1 this.state = (++this.state > 1) ? 0 : this.state; } else { // Cycle from 2 to 4 this.state = (++this.state < 2 || this.state > 4) ? 2 : this.state; } //this.state = (++this.state > 4) ? 0 : this.state; //loop(); };
dylandevalia/dylan.devalia.com
old/pathfinding/cell.js
JavaScript
mit
996
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('baApp.services', []). value('version', '0.1');
alnutile/drag-and-drop-page
app/js/services.js
JavaScript
mit
183
var fs = require('fs'); var join = require('path').join; var iconv = require('iconv-lite'); var debug = require('debug')('ip'); var util = require('util'); var EventEmitter = require('events').EventEmitter; var thunkify = require('thunkify-wrap'); function IpUtil(ipFile, encoding, isLoad) { if (typeof encoding === 'function') { isLoad = encoding; encoding = null; } this.ipFile = joinDirectory(process.cwd(), ipFile); this.ipList = []; if (encoding && encoding.toLowerCase().indexOf('utf') > -1) { this.filter = function(buf) { return buf.toString(); }; } else { this.filter = function(buf) { return iconv.decode(new Buffer(buf), 'gbk'); }; } this.isLoad = isLoad || function(){ return true; }; this.init(); } util.inherits(IpUtil, EventEmitter); IpUtil.prototype.init = function() { var that = this; var isLoad = this.isLoad; debug('begin parse ipfile %s', this.ipFile); if (!fs.existsSync(this.ipFile)) { debug('not found ip file!'); that.emit('error', 'ipfile_not_found'); return; } var ipMap = this.ipMap = {}; var ipList = this.ipList; var getLine = readLine(this.ipFile, this.filter); var result = getLine.next(); var line; var lineNum = 0; var counter = 1; var _readLine = function () { if (result.done) { that.emit('loaded'); return; } // 避免ip读取独占cpu. if (counter % 100000 === 0) { counter = 1; setImmediate(_readLine); return; } counter++; lineNum++; line = result.value; if (!line || !line.trim()) { result = getLine.next(); _readLine(); return; } var tokens = line.split(',', 6); if (tokens.length !== 6) { debug('第%d行格式不正确: %s', lineNum, line); result = getLine.next(); _readLine(); return; } var startIp = ip2Long(tokens[0]); var endIp = ip2Long(tokens[1]); if (!startIp || !endIp) { debug('第%d行格式不正确: %s', lineNum, line); result = getLine.next(); _readLine(); return; } var country = getValue(tokens[2]); var province = getValue(tokens[3]); var city = getValue(tokens[4]); var address = getValue(tokens[5]); // 针对国家、省份、城市解析的统一判空修改 // 首先对特殊值的解析 if ('IANA' === country) { country = 'IANA'; province = 'IANA'; city = 'IANA'; } if ('局域网' === country) { country = '局域网'; province = '局域网'; city = '局域网'; } if('国外' === country) { country = '国外'; province = '国外'; city = '国外'; } if('中国' === country && ('中国' === province || '中国' === city)) { country = '中国'; province = '中国'; city = '中国'; } if (!isLoad(country, province, city)) { result = getLine.next(); setImmediate(_readLine); return; } ipMap[startIp] = { startIp: startIp, endIp: endIp, country: country, province: province, city: city, address: address }; ipList.push(startIp); result = getLine.next(); setImmediate(_readLine); }; _readLine(); var sortIp = function () { //debug(this.ipMap) debug('完成IP库的载入. 共载入 %d 条IP纪录', ipList.length); ipList.sort(function(a, b) { return a - b; }); debug('ip 索引排序完成.'); that.emit('done'); }; this.on('loaded', sortIp); }; function getValue(val) { if (!val) { return null; } val = val.trim(); if (val === 'null') { return null; } return val; } IpUtil.prototype.getIpInfo = function(ip) { if (!isIp(ip)) { return null; } if (typeof ip === 'string') { ip = ip2Long(ip); } var ipStart = this.locatStartIP(ip); debug('开始获取 ip 信息: %d', ipStart); var ipInfo = this.ipMap[ipStart]; debug('查找IP, %s 成功.', long2IP(ip)); if (ipInfo.endIp < ip) { debug('在IP库中找不到IP[%s]', long2IP(ip)); return null; } return ipInfo; }; IpUtil.prototype.refreshData = function() { }; /** * 查找ip对应的开始IP地址。如果IP库中正好有以该ip开始的IP信息,那么就是返回这个ip。 * 如果没有,则应该是比这个ip小的最大的start * @param ip * @return */ IpUtil.prototype.locatStartIP = function(ip) { debug('开始查找IP: %d', ip); var centerIP = 0; var centerIndex = 0; // 当前指针位置 var startIndex = 0; // 起始位置 var endIndex = this.ipList.length - 1; // 结束位置 var count = 0; // 循环次数 while (true) { debug('%d. start = %d, end = %d', count++, startIndex, endIndex); // 中间位置 centerIndex = Math.floor((startIndex + endIndex) / 2); centerIP = this.ipList[centerIndex]; if (centerIP < ip) { // 如果中间位置的IP小于要查询的IP,那么下一次查找后半段 startIndex = centerIndex; } else if (centerIP > ip) { // 如果中间位置的IP大于要查询的IP,那么下一次查找前半段 endIndex = centerIndex; } else { // 如果相等,那么已经找到要查询的IP break; } if (startIndex + 1 === endIndex) { // 如果开始指针和结束指针相差只有1,那么说明IP库中没有正好以该ip开始的IP信息 // 只能返回IP信息的start ip比这个ip小的最大的那条IP信息的start ip if (centerIP > ip) { centerIP = this.ipList[centerIndex - 1]; } break; } } debug('对应的IP开始地址为: %d', centerIP, centerIndex); return centerIP; }; /** * a,b,c ==> a/b/c * a,b,/tmp ==> /tmp * /a/b, c ==> /a/b/c */ function joinDirectory() { var dirs = [].slice.call(arguments, 1); var dir; for (var i = 0, len = dirs.length; i < len; i++) { dir = dirs[i]; if (/^\//.test(dir)) { // 发现根目录, 直接返回. return dir; } } return join.apply(null, [].slice.call(arguments)); } function ip2Long(ip) { if (!isIp(ip)) { return 0; } var segs = ip.split('.'); var iplong =(parseInt(segs[0]) << 24 | parseInt(segs[1]) << 16 | parseInt(segs[2]) << 8 | parseInt(segs[3])) >>> 0; return iplong; } var IP_REGEXP = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/; function isIp(str) { if (!str) { return false; } str = str.trim(); return IP_REGEXP.test(str); /** var tokens = str.split('.'); if (tokens.length !== 4) { return false; } for (var i = 0, len = tokens.length; i < len; i++) { if (parseInt(tokens[i]) > 255 || parseInt(tokens[i]) < 0) { return false; } } return true; **/ } function long2IP(ipLong) { var ip = [ipLong >> 24]; ip.push((ipLong & 16711680) >> 16); ip.push((ipLong & 65280) >> 8); ip.push(ipLong & 255); return ip.join('.'); } function *readLine(file, filter) { var buffer = fs.readFileSync(file); var i = 0, len = 0 || buffer.length; debug('load file succ', len); // 换行符. var nl = require('os').EOL.charCodeAt(0); var buf = []; while(i < len) { if (buffer[i] !== nl) { buf.push(buffer[i]); } else { yield filter(new Buffer(buf)); buf = []; } i++; } } module.exports = IpUtil; module.exports.isIP = isIp; module.exports.ip2Long = ip2Long; module.exports.long2Ip = long2IP; module.exports.getIpUtil = function *(ipFile, encoding, ipFilter) { var iputil = new IpUtil(ipFile, encoding, ipFilter); var end = thunkify.event(iputil, ['done', 'error']); yield end(); return iputil; };
leoner/iputil
index.js
JavaScript
mit
7,755
/* Noble cread UART service example This example uses Sandeep Mistry's noble library for node.js to read and write from Bluetooth LE characteristics. It looks for a UART characteristic based on a proprietary UART service by Nordic Semiconductor. You can see this service implemented in Adafruit's BLEFriend library. created 30 Nov 2015 by Tom Igoe */ var noble = require('noble'); //noble library var util = require('util'); // utilities library // make an instance of the eventEmitter library: var EventEmitter = require('events').EventEmitter; // constructor function, so you can call new BleUart(): var BleUart = function (uuid) { var service = '6e400001b5a3f393e0a9e50e24dcca9e'; // the service you want var receive, transmit; // transmit and receive BLE characteristics var self = this; // reference to the instance of BleUart self.connected = false; // whether the remote peripheral's connected self.peripheral; // the remote peripheral as an object EventEmitter.call(self); // make a copy of EventEmitter so you can emit events if (uuid) { // if the constructor was called with a different UUID, service = uuid; // then set that as the service to search for } // The scanning function: function scan(state) { if (state === 'poweredOn') { // if the radio's on, scan for this service noble.startScanning([service], false); } // emit a 'scanning' event: self.emit('scanning', state); } // the connect function: self.connect = function(peripheral) { self.peripheral = peripheral; peripheral.connect(); // start connection attempts // the connect function. This is local to the discovery function // because it needs to know the peripheral to discover services: function discover() { // once you know you have a peripheral with the desired // service, you can stop scanning for others: noble.stopScanning(); // get the service you want on this peripheral: peripheral.discoverServices([service],explore); } // called only when the peripheral has the service you're looking for: peripheral.on('connect', discover); // when a peripheral disconnects, run disconnect: peripheral.on('disconnect', self.disconnect); } // the services and characteristics exploration function: // once you're connected, this gets run: function explore(error, services) { // this gets run by the for-loop at the end of the // explore function, below: function getCharacteristics(error, characteristics) { for (var c in characteristics) { // loop over the characteristics if (characteristics[c].notify) { // if one has the notify property receive = characteristics[c]; // then it's the receive characteristic receive.notify(true); // turn on notifications // whenever a notify event happens, get the result. // this handles repeated notifications: receive.on('data', function(data, notification) { if (notification) { // if you got a notification self.emit('data', String(data)); // emit a data event } }); } if (characteristics[c].write) { // if a characteristic has a write property transmit = characteristics[c]; // then it's the transmit characteristic } } // end of getCharacteristics() // if you've got a valid transmit and receive characteristic, // then you're truly connected. Emit a connected event: if (transmit && receive) { self.connected = true; self.emit('connected', self.connected); } } // iterate over the services discovered. If one matches // the UART service, look for its characteristics: for (var s in services) { if (services[s].uuid === service) { services[s].discoverCharacteristics([], getCharacteristics); return; } } } // the BLE write function. If there's a valid transmit characteristic, /// then write data out to it as a Buffer: self.write = function(data) { if (transmit) { transmit.write(new Buffer(data)); } } // the BLE disconnect function: self.disconnect = function() { self.connected = false; } // when the radio turns on, start scanning: noble.on('stateChange', scan); // if you discover a peripheral with the appropriate service, connect: noble.on('discover', self.connect); } util.inherits(BleUart, EventEmitter); // BleUart inherits all the EventEmitter properties module.exports = BleUart; // export BleUart
evejweinberg/SuperHeroAutoPilot
ble-uart.js
JavaScript
mit
4,710
var db = require('mongoose'); var Log = require('log'), log = new Log('info'); var clienttracking = require('./clienttracking.js'); var mapreduce = require('./mapreduce.js'); var io = null; exports.server = require('./adnoceserver.js'); exports.setDatabase = function(databaseConfiguration, callback) { var port = databaseConfiguration.port || '27017'; var opts = databaseConfiguration.options || {}; db.connect('mongodb://'+databaseConfiguration.host+':'+port+'/'+databaseConfiguration.name, opts, function(){ log.info('adnoce core - creating database connection to "%s" on host "%s:%s", status: %s', databaseConfiguration.name, databaseConfiguration.host, port, db.connection.readyState); if (db.connection.readyState != 1) { log.error('adnoce core - database connection not ready yet'); } if (typeof(callback) === 'function') callback(db); }); } exports.setServerSocketIO = function(io_, path_) { var path = path_ || '/adnoce'; io = io_.of(path).authorization(function (handshakeData, callback) { // @TODO: auth (e.g. ip-based on handshakeData.address) callback(null, true); }).on('connection', socketConnection); clienttracking.setSocketIO(io); } var socketConnection = function(socket_) { log.info('adnoce core - server socket client "%s" connected to endpoint "%s"', socket_.handshake.address.address, socket_.flags.endpoint); } exports.clientTrackingScript = function(req, res) { res.set({'Content-Type': 'application/javascript', 'Cache-Control': 'no-cache'}); res.send(200, clienttracking.getClientTrackingScript(req)); var additionalData = req.adnoceData || {}; additionalData.adnocetype = 1; clienttracking.processRequest(req, additionalData); }; exports.clientTrackingScriptUpdate = function(req, res) { res.set({'Content-Type': 'text/plain', 'Cache-Control': 'no-cache'}); if (!req.param('p')) res.send(400, '0'); else { res.send(200, '1'); var additionalData = req.adnoceData || {}; if (req.param('t')) additionalData.adnocetype = req.param('t'); clienttracking.updateSessionData(req.sessionID, req.param('p'), additionalData); } }; exports.addEvent = function(type, name, sessionId, additionalData) { clienttracking.addEvent(type, name, sessionId, additionalData); }; exports.MapReduce = mapreduce.MapReduce; var pushServerHealth = function(serverOSObject) { io.emit('health', {uptime: serverOSObject.uptime(), load: serverOSObject.loadavg(), memory: {total: serverOSObject.totalmem(), free: serverOSObject.freemem()}}); } exports.pushServerHealth = pushServerHealth;
hkonitzer/adnoce
lib/adnoce.js
JavaScript
mit
2,627
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-spec-reporter', '@angular-devkit/build-angular/plugins/karma', ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, reporters: ['spec'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
erento/angular-lazy-responsive-images
projects/angular-lazy-responsive-images/karma.conf.js
JavaScript
mit
688
'use strict'; const util = require('util'); const colors = require('colors/safe'); Object.entries({ info: colors.blue, warn: colors.yellow, error: colors.red }).map(([method, color]) => { const _ = global.console[method]; global.console[method] = (...args) => { if (args.length) { let msg = args.shift(); if ('string' == typeof msg) { msg = color(msg); } args.unshift(msg); } _(...args); }; });
cravler/whaler
lib/console.js
JavaScript
mit
509
require.ensure([], function(require) { require("./73.async.js"); require("./147.async.js"); require("./294.async.js"); require("./588.async.js"); }); module.exports = 589;
skeiter9/javascript-para-todo_demo
webapp/node_modules/webpack/benchmark/fixtures/589.async.js
JavaScript
mit
171
<rtl code> var m = function (){ function T(){ this.a = []; } var r = new T(); var a = RTL$.makeArray(3, 0); var dynamicInt = []; var dynamicString = []; var dynamicChar = []; var dynamicByte = []; var dynamicRecord = []; var dynamicArrayOfStaticArrayInt = []; var i = 0; var s = ''; var byte = 0; function assignDynamicArrayFromStatic(){ var static$ = RTL$.makeArray(3, 0); var dynamic = []; Array.prototype.splice.apply(dynamic, [0, Number.MAX_VALUE].concat(static$)); } function returnOuterArray(){ return a.slice(); } function passArrayBeRef(a/*VAR ARRAY * OF INTEGER*/){ var static$ = RTL$.makeArray(3, 0); a[0] = 1; a[0] = a[1]; Array.prototype.splice.apply(a, [0, Number.MAX_VALUE].concat(static$)); Array.prototype.splice.apply(a, [0, Number.MAX_VALUE].concat(dynamicInt)); } function passArrayOfRecordsByRef(a/*VAR ARRAY * OF T*/){ var result = []; RTL$.copy(result, a, {array: {record: {a: {array: null}}}}); } function passArrayOfArraysByRef(a/*VAR ARRAY *, 3 OF INTEGER*/){ var result = []; RTL$.copy(result, a, {array: {array: null}}); } function arrayOfRecords(){ var $scope1 = $scope + ".arrayOfRecords"; function T(){ } var a = []; a.push(new T()); } function arrayOfArrays(){ var aa = []; function f(){ var a = []; return a; } aa.push(f()); } function optimizeTemporartArrayReturn(){ function f(){ var a = []; return a; } return f(); } function optimizeLocalArrayReturn(){ var a = []; return a; } function optimizeLocalArrayReturnWhenStatic(){ var a = RTL$.makeArray(3, 0); return a; } function cannotOptimizeArgArrayReturn(a/*ARRAY OF INTEGER*/){ return a.slice(); } function cannotOptimizeVarArgArrayReturn(a/*VAR ARRAY OF INTEGER*/){ return a.slice(); } function cannotOptimizeVarArgDynamicArrayReturn(a/*VAR ARRAY * OF INTEGER*/){ return a.slice(); } function arrayOfMaps(){ var aa = []; function f(){ var a = {}; return a; } aa.push(f()); } dynamicInt.push(3); dynamicInt.push(i); dynamicInt.push(byte); dynamicString.push("abc"); dynamicString.push("\""); dynamicString.push(s); dynamicChar.push(34); dynamicByte.push(byte); dynamicByte.push(i & 0xFF); dynamicRecord.push(RTL$.clone(r, {record: {a: {array: null}}}, T)); dynamicArrayOfStaticArrayInt.push(a.slice()); RTL$.assert(dynamicInt.indexOf(i) != -1); RTL$.assert(dynamicChar.indexOf(34) != -1); dynamicInt.splice(i, 1); dynamicInt.splice(0, Number.MAX_VALUE); passArrayBeRef(dynamicInt); passArrayOfRecordsByRef(dynamicRecord); passArrayOfArraysByRef(dynamicArrayOfStaticArrayInt); }();
vladfolts/oberonjs
test/expected/eberon/dynamic_array.js
JavaScript
mit
2,536
var expect = require('chai').expect; var assert = require('chai').assert; var sinon = require('sinon'); var Config = require('../lib/config'); describe('config', function() { describe('#constructor', function() { it('creates a new object with the config defaults', function() { sinon.spy(Config.prototype, 'set'); var options = {}; var config = new Config(options); assert(Config.prototype.set.calledWith(options)); Config.prototype.set.restore(); }); it('call .set with any passed options', function() { var config = new Config(); expect(config.source).to.equal('.'); expect(config.destination).to.equal('_site'); }); }); describe('#set', function() { it('merges the passed options with the config defaults', function() { var config = new Config(); config.set({ source: './foo', destination: './bar', fizz: 'buzz' }); expect(config.source).to.equal('./foo'); expect(config.destination).to.equal('./bar'); // a default expect(config.env).to.equal('production'); // a new value expect(config.fizz).to.equal('buzz'); }); it('always includes certain default, even if overridden', function() { var config = new Config(); config.set({ excludeFiles: ['foo'], watchExcludes: ['bar'] }); expect(config.excludeFiles).to.deep.equal([ 'foo', '.*', '_*', '_*/**/*', 'package.json', 'bower_components', 'node_modules' ]); expect(config.watchExcludes).to.deep.equal([ 'bar', 'node_modules', config.destination ]); }); }); });
philipwalton/ingen
test/config-test.js
JavaScript
mit
1,739
import Vue from 'vue'; import VueForm from 'vue-form'; Vue.use(VueForm, { validators: { 'step': function(value, stepValue) { return stepValue === `any` || Number(value) % Number(stepValue) === 0; }, 'data-exclusive-minimum': function(value, exclusiveMinimum) { return Number(value) > Number(exclusiveMinimum); }, 'data-exclusive-maximum': function(value, exclusiveMaximum) { return Number(value) < Number(exclusiveMaximum); }, 'complete-range': function(range) { return range === null || (range[0] !== null && range[1] !== null); }, 'valid-range': function(range) { if (range === null) { // allowed range return true; } if (range[0] === null || range[1] === null) { // let complete-range validator handle this return true; } if (Number.isNaN(range[0]) || Number.isNaN(range[1])) { // let number validator handle this return true; } return range[0] <= range[1]; }, 'categories-not-empty': function(categories) { return categories.length > 0; }, 'complete-dimensions': function(dimensions) { return dimensions === null || (dimensions[0] !== null && dimensions[1] !== null && dimensions[2] !== null); }, 'start-with-uppercase-or-number': function(value) { return /^[\dA-Z]/.test(value); }, 'no-mode-name': function(value) { return !/\bmode\b/i.test(value); }, 'no-fine-channel-name': function(value) { if (/\bfine\b|\d+[\s_-]*bit/i.test(value)) { return false; } return !/\bLSB\b|\bMSB\b/.test(value); }, 'entity-complete': function(value, attributeValue, vnode) { const component = vnode.componentInstance; if (component.hasNumber) { return component.selectedNumber !== `` && component.selectedNumber !== null; } return true; }, 'entities-have-same-units': function(value, attributeValue, vnode) { return vnode.componentInstance.hasSameUnit; }, 'valid-color-hex-list': function(value) { return /^\s*#[\da-f]{6}(?:\s*,\s*#[\da-f]{6})*\s*$/i.test(value); }, 'max-file-size': function(file, attributeValue) { if (typeof file === `object`) { let maxSize = Number.parseInt(attributeValue, 10); if (attributeValue.includes(`M`)) { maxSize *= 1000 * 1000; } else if (attributeValue.includes(`k`)) { maxSize *= 1000; } return file.size <= maxSize; } return true; }, }, });
FloEdelmann/open-fixture-library
ui/plugins/vue-form.js
JavaScript
mit
2,583
var resources = require('jest'), util = require('util'), models = require('../../models'), async = require('async'), common = require('./../common'), calc_thresh = require('../../tools/calc_thresh.js'), GradeActionSuggestion = require('./grade_action_suggestion_resource.js'), ActionSuggestion = require('./ActionSuggestionResource.js'), og_action = require('../../og/og.js').doAction; //Authorization var Authoriztion = function() {}; util.inherits(Authoriztion,resources.Authorization); //Authorization.prototype.edit_object = function(req,object,callback){ // //check if user already grade this action // var flag = false; // // models.GradeAction.find({"action_id": object.action_id}, function(err, objects){ // if (err){ // callback(err, null); // }else{ // for (var i = 0; i < objects.length; i++){ // if(req.session.user_id == objects[i].user_id){ // flag = true; // break; // } // } // if (flag){ // callback({message:"user already grade this action",code:401}, null); // }else{ // callback(null, object); // } // } // }) //}; var GradeActionResource = module.exports = common.GamificationMongooseResource.extend({ init:function(){ this._super(models.GradeAction,'grade_action', null); // GradeResource.super_.call(this,models.Grade); this.allowed_methods = ["get", "put", "post"]; this.authorization = new Authoriztion(); this.authentication = new common.SessionAuthentication(); this.filtering = {action_id: { exact:null, in:null }}; }, create_obj:function(req,fields,callback) { var self = this; var g_grade_obj; var new_grade = null; var counter = 0; var threshold; var admin_threshold; var action_thresh; var action_obj; var proxy_power = req.user.num_of_given_mandates ? 1 + req.user.num_of_given_mandates * 1/9 : 1; var base = self._super; fields.proxy_power = proxy_power; fields.user_id = req.user._id; async.waterfall([ function(cbk){ base.call(self, req, fields, cbk); }, //find actions function(grade_obj, cbk){ g_grade_obj = grade_obj; models.Action.findById(grade_obj.action_id, cbk); }, // 2) calculate action grade + set notifications for all users of proxy function(action, cbk){ action_obj = action; async.parallel([ //2.1 set notifications for all users of proxy function(cbk1){ cbk1(null, null); }, // 2.2 calculate action grade function(cbk1){ //cant grade your own action action_thresh = Number(action.admin_threshold_for_accepting_change_suggestions) || action.threshold_for_accepting_change_suggestions admin_threshold = action.admin_threshold_for_accepting_change_suggestions; calculateActionGrade(g_grade_obj.action_id, function(err, _new_grade, evaluate_counter, _threshold){ new_grade = _new_grade; counter = evaluate_counter; threshold = _threshold cbk1(err, threshold); }); }, //2.3 add user to be part of the action function(cbk1){ if (! _.any(action.users, function(user){ return user.user_id + "" == req.user.id})){ var new_user = {user_id: req.user._id, join_date: Date.now()}; models.Action.update({_id: action._id}, {$addToSet:{users: new_user}}, function(err, num){cbk1(err, num)}); }else{ cbk1(null, null); } } ],function(err, args){ cbk(err, args[1]); }) }, // 3) find suggestion object //calculate all change suggestion all over again and check if they approved function(threshold, cbk){ models.ActionSuggestion.find({action_id: g_grade_obj.action_id}, {"_id":1}, function(err, results) { cbk(err, results); }); }, // 4) calculate suggestion grades function(suggestions, cbk){ var real_threshold async.forEach(suggestions, function(suggestion, itr_cbk){ GradeActionSuggestion.calculateActionSuggestionGrade(suggestion._id, g_grade_obj.action_id, null, null, action_thresh, null, null,function(err, obj){ //check if suggestion is over the threshold real_threshold = Number(suggestion.admin_threshold_for_accepting_the_suggestion) || suggestion.threshold_for_accepting_the_suggestion; if(suggestion.agrees && suggestion.agrees.length > real_threshold){ //approveSuggestion.exec() ActionSuggestion.approveSuggestion(suggestion._id, function(err, obj1){ itr_cbk(err, obj1); }) }else itr_cbk(err, obj); });} , function(err){ cbk(err); }); }, // 5) publish to facebook function (cbk) { og_action({ action: 'rank', object_name:'action', object_url : '/actions/' + action_obj.id, fid : req.user.facebook_id, access_token:req.user.access_token, user:req.user }); cbk(); }, // update actions done by user function(cbk){ models.User.update({_id:user._id},{$set: {"actions_done_by_user.grade_object": true}}, function(err){ cbk(err); }); } ], // Final) set gamification details, return object function(err, args){ req.gamification_type = "grade_action"; req.token_price = common.getGamificationTokenPrice('grade_action') > -1 ? common.getGamificationTokenPrice('grade_action') : 0; callback(err, {new_grade: new_grade, evaluate_counter: counter, grade_id: g_grade_obj._id || 0}); }) }, update_obj: function(req, object, callback){ var g_grade; var self = this; var suggestions = []; var action_thresh; var proxy_power = req.user.num_of_given_mandates ? 1 + req.user.num_of_given_mandates * 1/9 : 1; var iterator = function(suggestion, itr_cbk){ GradeActionSuggestion.calculateActionSuggestionGrade(suggestion._id, object.action_id, null, null, action_thresh, null, null,function(err, sugg_new_grade, sugg_total_counter){ if(!err){ suggestions.push({ _id: suggestion._id, grade: sugg_new_grade, evaluators_counter: sugg_total_counter }) } itr_cbk(err, 0); }); } object.proxy_power = proxy_power; self._super(req, object, function(err, grade_object){ if(err){ callback(err, null); }else{ var new_grade, evaluate_counter; async.waterfall([ function(cbk){ g_grade = grade_object; calculateActionGrade(object.action_id, function(err, _new_grade, _evaluate_counter){ new_grade = _new_grade; evaluate_counter = _evaluate_counter; cbk(err, 0); }); }, //get action threshold so i can update every suggestion threshold function(obj, cbk){ models.Action.findById(object.action_id, function(err, result){ cbk(err, result) }); }, function(action_obj,cbk){ async.parallel([ //set notifications for all users of proxy function(cbk1){ //Todo - set notifications // models.User.find({"proxy.user_id": req.user._id}, function(err, slaves_users){ // async.forEach(slaves_users, function(slave, itr_cbk){ // notifications.create_user_proxy_vote_or_grade_notification("proxy_graded_discussion", // discussion_obj._id, slave._id, req.user._id, // null, null, g_grade.evaluation_grade, // function(err){ // itr_cbk(err); // }) // }, function(err){ // cbk1(err); // }) // }) cbk1(null); }, //calculate all change suggestion all over again function(cbk1){ action_thresh = Number(action_obj.admin_threshold_for_accepting_change_suggestions) || action_obj.threshold_for_accepting_change_suggestions; models.ActionSuggestion.find({action_id: grade_object.action_id}, {"_id":1}, function(err, results) { cbk1(err, results); }); } ], function(err, args){ cbk(err, args[1]); } ) }, function(suggestions, cbk){ async.forEach(suggestions, iterator, cbk); } ], function(err){ callback(err, {new_grade: new_grade, evaluate_counter: evaluate_counter, suggestions: suggestions,grade_id: g_grade._id || 0}) }) } }); } }); function calculateActionGrade(action_id, callback){ var count; var grade_sum; var new_grade; var threshold; async.waterfall([ function(cbk){ models.GradeAction.find({action_id: action_id}, {"evaluation_grade":1, "proxy_power":1}, cbk); }, function(grades, cbk){ count = grades.length; if(count){ //calculate grade_sum with take proxy power in consideration grade_sum = _.reduce(grades, function(memo, grade){return memo + Number(grade.evaluation_grade * (grade.proxy_power || 1)); }, 0); //calculate count with take proxy power in consideration count = _.reduce(grades, function(memo, grade){return memo + Number(grade.proxy_power || 1)}, 0); new_grade = grade_sum / count; //calculate threshhold here threshold = calc_thresh.calculating_thresh(count, new_grade) || 50; models.Action.update({_id: action_id}, {$set: {grade: new_grade, evaluate_counter: count, threshold_for_accepting_change_suggestions: threshold}}, cbk); }else{ cbk({message: "you have to grade before changing the grade" , code: 401}); } } ],function(err, args){ callback(err, new_grade, count, threshold); }) }
saarsta/sheatufim
api/actions/GradeActionResource.js
JavaScript
mit
12,565
/** * This Control enables to render a Scene with a Screen Space Ambient Occlusion (SSAO) effect. * * @namespace GIScene * @class Control.SSAO * @constructor * @extends GIScene.Control */ GIScene.Control.SSAO = function() { //inherit GIScene.Control.call(this); var scenePass; var ssaoEffect; var fxaaEffect; var depthTarget; var depthShader; var depthUniforms; var depthMaterial; var depthCam; var activeCam; var updateDepthCam = function() { // if(depthCam !== undefined && depthCam.parent !== undefined){ // this.scene.camera.remove(depthCam); // } //depthCam activeCam = (this.scene.camera instanceof THREE.CombinedCamera)? ( (this.scene.camera.inPerspectiveMode)? this.scene.camera.cameraP : this.scene.camera.cameraO ) : this.scene.camera; depthCam = activeCam.clone(); this.scene.camera.add(depthCam); // depthCam = new THREE.PerspectiveCamera(); // //POSITION // depthCam.fov = activeCam.fov; // depthCam.aspect = activeCam.aspect; depthCam.near = 0.1; depthCam.far = 1000; depthCam.updateProjectionMatrix(); //console.log(depthCam); //updateSsaoUniforms();//mca }.bind(this); var updateSsaoUniforms = function() { ssaoEffect.uniforms[ 'tDepth' ].value = depthTarget; ssaoEffect.uniforms[ 'size' ].value.x = this.scene.canvas.width; ssaoEffect.uniforms[ 'size' ].value.y = this.scene.canvas.height; ssaoEffect.uniforms[ 'cameraNear' ].value = depthCam.near; ssaoEffect.uniforms[ 'cameraFar' ].value = depthCam.far; }.bind(this); var onBeforeRender = function() { // activeCam = (this.scene.camera instanceof THREE.CombinedCamera)? // ( (this.scene.camera.inPerspectiveMode)? this.scene.camera.cameraP : this.scene.camera.cameraO ) // : // this.scene.camera; // activeCam = this.scene.camera.cameraP.clone(); // this.scene.root.overrideMaterial = depthMaterial;//new THREE.MeshDepthMaterial({blending: THREE.NoBlending}); // activeCam.near = 0.1; // activeCam.far = 1500; // activeCam.updateProjectionMatrix(); this.scene.renderer.clearTarget(depthTarget,true, true, false); //color, depth, stencil this.scene.renderer.render(this.scene.root, depthCam, depthTarget); // activeCam.near = this.scene.config.near; // activeCam.far = this.scene.config.far; // activeCam.updateProjectionMatrix(); this.scene.root.overrideMaterial = null; // // this.scene.root.overrideMaterial = null; }.bind(this); var onChangedProjection = function(event) { console.log("chPrj2",activeCam); updateDepthCam(); }; var onResize = function() { updateDepthCam(); depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); updateSsaoUniforms(); fxaaEffect.uniforms[ 'resolution' ].value.set( 1 / this.scene.canvas.width, 1 / this.scene.canvas.height ); }.bind(this); this.activate_ = function() { if(!this.isActive){ scenePass = new THREE.RenderPass( this.scene.root, this.scene.camera ); ssaoEffect = new THREE.ShaderPass( THREE.SSAOShader ); depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); depthShader = THREE.ShaderLib[ "depthRGBA" ]; depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); depthMaterial.blending = THREE.NoBlending; this.scene.addEventListener('beforeRender', onBeforeRender); // function(){ // // this.scene.root.overrideMaterial = depthMaterial;//new THREE.MeshDepthMaterial({blending: THREE.NoBlending}); // this.scene.camera.cameraP.near = 0.1; // this.scene.camera.cameraP.far = 1500; // this.scene.camera.cameraP.updateProjectionMatrix(); // this.scene.renderer.clearTarget(depthTarget,true, true, true); // this.scene.renderer.render(this.scene.root, this.scene.camera, depthTarget); // // this.scene.camera.cameraP.near = this.scene.config.near; // this.scene.camera.cameraP.far = this.scene.config.far; // this.scene.camera.cameraP.updateProjectionMatrix(); // this.scene.root.overrideMaterial = null; // // }.bind(this) // ); ssaoEffect.uniforms[ 'tDepth' ].value = depthTarget; ssaoEffect.uniforms[ 'size' ].value.x = this.scene.canvas.width; ssaoEffect.uniforms[ 'size' ].value.y = this.scene.canvas.height; ssaoEffect.uniforms[ 'cameraNear' ].value = this.scene.camera.near; ssaoEffect.uniforms[ 'cameraFar' ].value = this.scene.camera.far; ssaoEffect.uniforms[ 'onlyAO' ].value = 1; ssaoEffect.renderToScreen = true; this.scene.effectComposer.addPass(scenePass); this.scene.effectComposer.addPass(ssaoEffect); } //call super class method GIScene.Control.prototype.activate.call(this); }; this.activate = function() { if(!this.isActive){ //depth map depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); depthShader = THREE.ShaderLib[ "depthRGBA" ]; depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); depthMaterial.blending = THREE.NoBlending; //depthCam updateDepthCam(); //define passes scenePass = new THREE.RenderPass( this.scene.root, this.scene.camera ); ssaoEffect = new THREE.ShaderPass( THREE.SSAOShader ); fxaaEffect = new THREE.ShaderPass( THREE.FXAAShader ); updateSsaoUniforms(); ssaoEffect.renderToScreen = true; fxaaEffect.uniforms[ 'resolution' ].value.set( 1 / this.scene.canvas.width, 1 / this.scene.canvas.height ); fxaaEffect.renderToScreen = false; //add beforeRender Event this.scene.addEventListener('beforeRender2', onBeforeRender); //be sure, there are no other passes active //add passes this.scene.effectComposer.passes = [scenePass, fxaaEffect, ssaoEffect]; // this.scene.effectComposer.addPass(scenePass); // this.scene.effectComposer.addPass(ssaoEffect); //add other events window.addEventListener('resize', onResize, false); this.scene.camera.addEventListener('changedProjection', onChangedProjection); //call super class method GIScene.Control.prototype.activate.call(this); } }; this.deactivate = function() { if(this.isActive){ //remove passes this.scene.effectComposer.passes = []; //remove depthCam this.scene.camera.remove(depthCam); //remove Events this.scene.removeEventListener('beforeRender2', onBeforeRender); window.removeEventListener('resize', onResize, false); this.scene.camera.removeEventListener('changedProjection', onChangedProjection); //call super class method GIScene.Control.prototype.deactivate.call(this); } }; }; GIScene.Control.SSAO.prototype = Object.create(GIScene.Control.prototype);
GIScience/GIScene.js
lib/GIScene/Control/SSAO.js
JavaScript
mit
7,334
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M20 15H4c-.55 0-1 .45-1 1s.45 1 1 1h16c.55 0 1-.45 1-1s-.45-1-1-1zm0-5H4c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-1c0-.55-.45-1-1-1zm0-6H4c-.55 0-1 .45-1 1v2c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm.5 15h-17c-.28 0-.5.22-.5.5s.22.5.5.5h17c.28 0 .5-.22.5-.5s-.22-.5-.5-.5z" }), 'LineWeightRounded');
AlloyTeam/Nuclear
components/icon/esm/line-weight-rounded.js
JavaScript
mit
447
import {normalize, resolve} from "path"; import {existsSync, readFileSync} from "fs"; import {sys, ScriptSnapshot, resolveModuleName, getDefaultLibFilePath} from "typescript"; export function createServiceHost(options, filenames, cwd) { const normalizePath = (path) => resolve(normalize(path)); const moduleResolutionHost = createModuleResolutionHost(); const files = {}; // normalized filename => {version, snap, text} filenames.forEach(filename => files[normalizePath(filename)] = null); return { getDirectories: sys.getDirectories, directoryExists: sys.directoryExists, readDirectory: sys.readDirectory, getDefaultLibFileName: getDefaultLibFilePath, fileExists(filename) { filename = normalizePath(filename); return filename in files || sys.fileExists(filename); }, readFile(filename) { return readFileSync(normalizePath(filename), "utf-8"); }, getCompilationSettings() { return options; }, getCurrentDirectory() { return cwd; }, getScriptFileNames() { return Object.keys(files); }, getScriptVersion(filename) { const f = files[normalizePath(filename)]; return f ? f.version.toString() : ""; }, getScriptSnapshot(filename) { let f = files[normalizePath(filename)]; if(!f) { f = this.addFile(filename, this.readFile(filename)); } return f.snap; }, resolveModuleNames(moduleNames, containingFile) { return moduleNames.map(name => this.resolveModuleName(name, containingFile)); }, getNewLine() { return options.newLine || sys.newLine; }, // additional methods containsFile(filename) { return normalizePath(filename) in files; }, resolveModuleName(moduleName, containingFile) { const {resolvedModule} = resolveModuleName(moduleName, containingFile, options, moduleResolutionHost); if(resolvedModule) { resolvedModule.resolvedFileName = normalizePath(resolvedModule.resolvedFileName); resolvedModule.originalFileName = resolvedModule.resolvedFileName; } return resolvedModule; }, addFile(filename, text) { filename = normalizePath(filename); const snap = ScriptSnapshot.fromString(text); snap.getChangeRange = () => {}; let file = files[filename]; if(!file) { file = {version: 0}; files[filename] = file; } ++file.version; file.snap = snap; file.text = text; return file; }, }; } function createModuleResolutionHost() { return { fileExists(filename) { return existsSync(filename); }, readFile(filename) { return readFileSync(filename, "utf-8") }, }; }
tsne/rollup-plugin-tsc
src/servicehost.js
JavaScript
mit
2,558
import path from 'path'; import {runScheduler} from './scheduler'; import logger from '../util/logger'; import dotenv from 'dotenv'; import {loadConfig} from '../../config'; import {initQueue} from './pipeline.queue'; logger.info(" _____ _ _ _ _ _ _ _ _ "); logger.info("| | |_|___| | | |_| |_|_|"); logger.info("| --| | | | | | | | '_| |"); logger.info("|_____|_|_|_|_|_____|_|_,_|_|"); logger.info('ClinWiki data pipeline starting...'); const envPath = path.resolve(process.cwd()+'/../', '.env'); logger.info('Loading .env from '+envPath); dotenv.config({ path: envPath }); loadConfig(); logger.info('Initializing pipeline queue'); initQueue(); logger.info('Running...'); runScheduler();
clinwiki-org/clinwiki
api/src/pipeline/worker.js
JavaScript
mit
747
define(['js/util'], function (util) { "use strict"; var sf2 = {}; sf2.createFromArrayBuffer = function(ab) { var that = { riffHeader: null, sfbk: {} }; var ar = util.ArrayReader(ab); var sfGenerator = [ "startAddrsOffset", // 0 "endAddrsOffset", // 1 "startloopAddrsOffset", // 2 "endloopAddrsOffset", // 3 "startAddrsCoarseOffset", // 4 "modLfoToPitch", // 5 "vibLfoToPitch", // 6 "modEnvToPitch", // 7 "initialFilterFc", // 8 "initialFilterQ", // 9 "modLfoToFilterFc", // 10 "modEnvToFilterFc", // 11 "endAddrsCoarseOffset", // 12 "modLfoToVolume", // 13 "unused1", "chorusEffectsSend", // 15 "reverbEffectsSend", // 16 "pan", // 17 "unused2", "unused3", "unused4", "delayModLFO", // 21 "freqModLFO", // 22 "delayVibLFO", // 23 "freqVibLFO", // 24 "delayModEnv", // 25 "attackModEnv", // 26 "holdModEnv", // 27 "decayModEnv", // 28 "sustainModEnv", // 29 "releaseModEnv", // 30 "keynumToModEnvHold", // 31 "keynumToModEnvDecay", // 32 "delayVolEnv", // 33 "attackVolEnv", // 34 "holdVolEnv", // 35 "decayVolEnv", // 36 "sustainVolEnv", // 37 "releaseVolEnv", // 38 "keynumToVolEnvHold", // 39 "keynumToVolEnvDecay", // 40 "instrument", // 41: PGEN Terminator "reserved1", "keyRange", // 43 "velRange", // 44 "startloopAddrsCoarseOffset", // 45 "keynum", // 46 "velocity", // 47 "initialAttenuation", // 48 "reserved2", "endloopAddrsCoarseOffset", // 50 "coarseTune", // 51 "fineTune", // 52 "sampleID", // 53: IGEN Terminator "sampleModes", // 54 "reserved3", "scaleTuning", // 56 "exclusiveClass", // 57 "overridingRootKey", // 58 "unused5", "endOper" ]; that.parseHeader = function () { // read RIFF header that.riffHeader = parseHeader(); that.size = that.riffHeader.length + 8; // read level1 header ar.seek(that.riffHeader.headPosition); that.sfbk = {}; that.sfbk.ID = ar.readStringF(4); // read level2 header that.sfbk.INFO = parseHeader(); // read level3 header // 3.1 INFO ar.seek(that.sfbk.INFO.headPosition); that.sfbk.INFO.ID = ar.readStringF(4); that.sfbk.INFO.child = {}; while(ar.position() < that.sfbk.INFO.headPosition + that.sfbk.INFO.length) { var head = parseHeader(); that.sfbk.INFO.child[head.ID] = head; } // 3.2 sdta ar.seek(that.sfbk.INFO.headPosition + that.sfbk.INFO.padLength); that.sfbk.sdta = parseHeader(); ar.seek(that.sfbk.sdta.headPosition); that.sfbk.sdta.ID = ar.readStringF(4); that.sfbk.sdta.child = {}; while(ar.position() < that.sfbk.sdta.headPosition + that.sfbk.sdta.length) { head = parseHeader(); that.sfbk.sdta.child[head.ID] = head; } // 3.3 pdta ar.seek(that.sfbk.sdta.headPosition + that.sfbk.sdta.padLength); that.sfbk.pdta = parseHeader(); ar.seek(that.sfbk.pdta.headPosition); that.sfbk.pdta.ID = ar.readStringF(4); that.sfbk.pdta.child = {}; while(ar.position() < that.sfbk.pdta.headPosition + that.sfbk.pdta.length) { head = parseHeader(); that.sfbk.pdta.child[head.ID] = head; } // read level4 data // 4.1 PHDR data var phdr = that.sfbk.pdta.child.phdr; phdr.data = []; ar.seek(phdr.headPosition); while(ar.position() < phdr.headPosition + phdr.length) { var data = {}; data.presetName = ar.readStringF(20); data.preset = ar.readUInt16(); data.bank = ar.readUInt16(); data.presetBagNdx = ar.readUInt16(); data.library = ar.readUInt32(); data.genre = ar.readUInt32(); data.morphology = ar.readUInt32(); phdr.data.push(data); } // set placeholder that.sfbk.pdta.child.pbag.data = []; that.sfbk.pdta.child.pgen.data = []; that.sfbk.pdta.child.pmod.data = []; that.sfbk.pdta.child.inst.data = []; that.sfbk.pdta.child.ibag.data = []; that.sfbk.pdta.child.igen.data = []; that.sfbk.pdta.child.imod.data = []; that.sfbk.pdta.child.shdr.data = []; }; that.readPreset = function(n) { var phdr = that.sfbk.pdta.child.phdr; var pbag = that.sfbk.pdta.child.pbag; var r = { presetName: phdr.data[n].presetName, preset: phdr.data[n].preset, bank: phdr.data[n].bank, gen: [], mod: [] } // PBAGs var pgen_global = { keyRange: { lo: 0, hi: 127 }, velRange: { lo: 1, hi: 127 } }; var pmod_global = []; for(var i = phdr.data[n].presetBagNdx; i < phdr.data[n + 1].presetBagNdx; i++) { var pbag0 = parsePBAG1(ar, pbag, i); var pbag1 = parsePBAG1(ar, pbag, i + 1); var pmod = readPMOD1(pbag0.modNdx, pbag1.modNdx, pmod_global); var pmod_local = Array.prototype.concat(pmod_global, pmod); var pgen = readPGEN1(pbag0.genNdx, pbag1.genNdx, pgen_global, pmod_local); if(pgen["instrument"] === undefined) { pgen_global = pgen; pmod_global = pmod; } else { r.gen = Array.prototype.concat(r.gen, pgen.instrument.ibag.igen); r.mod = Array.prototype.concat(r.mod, pgen.instrument.ibag.imod); } // r.mod.push(readPMOD1(pbag0.modNdx, pbag1.modNdx)); } return r; }; that.enumPresets = function() { var p = []; var phdr = that.sfbk.pdta.child.phdr; phdr.data.forEach(function(ph) { p.push(ph.presetName); }); return p; }; that.readSDTA = function(pos) { ar.seek(that.sfbk.sdta.child.smpl.headPosition + pos * 2); return ar.readInt16() / 32768; } that.readSDTAChunk = function(b, e) { return new Int16Array(new Uint8Array(ar.subarray( that.sfbk.sdta.child.smpl.headPosition + b * 2, that.sfbk.sdta.child.smpl.headPosition + e * 2 )).buffer); } var readPGEN1 = function(b, e, g, gm) { var pgen = that.sfbk.pdta.child.pgen; var global = _.O(g, true); var global_m = _.O(gm, true); var result = _.O(g, true); if(b != e) { for(var i = b; i < e; i++) { var r = parsePGEN1(ar, pgen, i); if(r.inst == "instrument") { global = _.O(result, true); result[r.inst] = readINST1(r.genAmount, global, global_m); } else { result[r.inst] = r.genAmount; } } } return result; }; var readPMOD1 = function(b, e, g) { var pmod = that.sfbk.pdta.child.pmod; var result = _.O(g, true); if(b != e) { for(var i = b; i < e; i++) { result.push(parseMOD1(ar, pmod, i)); } } return result; }; var readINST1 = function(i, g, gm) { var inst = that.sfbk.pdta.child.inst; var ibag = that.sfbk.pdta.child.ibag; var inst0 = parseINST1(ar, inst, i); var inst1 = parseINST1(ar, inst, i + 1); var r = { "instName": inst0.instName }; var global = _.O(g, true); var global_m = _.O(gm, true); // IBAGs r.ibag = { igen: [], imod: [] }; for(var i = inst0.instBagNdx; i < inst1.instBagNdx; i++) { var ibag0 = parseIBAG1(ar, ibag, i); var ibag1 = parseIBAG1(ar, ibag, i + 1); var igen = readIGEN1(ibag0.instGenNdx, ibag1.instGenNdx, global); var imod = readIMOD1(ibag0.instModNdx, ibag1.instModNdx, global_m); if(igen["sampleID"] === undefined) { // global parameter global = igen; global_m = imod; } else { r.ibag.igen.push(igen); r.ibag.imod.push(imod); } } return r; } var readIGEN1 = function(b, e, g) { var igen = that.sfbk.pdta.child.igen; var result = _.O(g, true); for(var i = b; i < e; i++) { var r = parseIGEN1(ar, igen, i); result[r.inst] = r.genAmount; if(r.inst == "sampleID") { result.shdr = readSHDR1(r.genAmount); } } return result; }; var readIMOD1 = function(b, e, g) { var imod = that.sfbk.pdta.child.imod; var result = _.O(g, true); if(b != e) { for(var i = b; i < e; i++) { result.push(parseMOD1(ar, imod, i)); } } return result; }; var readSHDR1 = function(i) { var shdr = that.sfbk.pdta.child.shdr; var r = parseSHDR1(ar, shdr, i); r.end -= r.start; r.startloop -= r.start; r.endloop -= r.start; r.sample = new Float32Array(r.end); ar.seek(that.sfbk.sdta.child.smpl.headPosition + r.start * 2) for(var j = 0; j < r.end; j++) { r.sample[j] = ar.readInt16() / 32768; } r.start = 0; return r; }; var parseHeader = function(){ var h = {}; h.ID = ar.readStringF(4); h.length = ar.readUInt32(); h.padLength = h.length % 2 == 1 ? h.length + 1 : h.length; h.headPosition = ar.position(); ar.seek(ar.position() + h.padLength); return h; }; var parsePBAG1 = function(ar, root, i) { ar.seek(root.headPosition + i * 4); var data = {}; data.genNdx = ar.readUInt16(); data.modNdx = ar.readUInt16(); root.data[i] = data; return data; }; var parsePGEN1 = function(ar, root, i) { ar.seek(root.headPosition + i * 4); var data = {}; data.genOper = ar.readUInt16(); data.inst = sfGenerator[data.genOper]; if(data.inst == 'keyRange' || data.inst == 'velRange' || data.inst == 'keynum' || data.inst == 'velocity') { data.genAmount = {}; data.genAmount.lo = ar.readUInt8(); data.genAmount.hi = ar.readUInt8(); } else { data.genAmount = ar.readInt16(); } root.data[i] = data; return data; }; var parseMOD1 = function(ar, root, i) { ar.seek(root.headPosition + i * 10); var data = {}; data.modSrcOper = { }; data.modSrcOper.index = ar.readUInt8(); data.modSrcOper.type = ar.readUInt8(); data.modDestOper = ar.readUInt16(); data.modDestInst = sfGenerator[data.modDestOper]; data.modAmount = ar.readInt16(); data.modAmtSrcOper = {}; data.modAmtSrcOper.index = ar.readUInt8(); data.modAmtSrcOper.type = ar.readUInt8(); data.modTransOper = ar.readUInt16(); root.data[i] = data; return data; }; var parseINST1 = function(ar, root, i) { ar.seek(root.headPosition + i * 22); var data = {}; data.instName = ar.readStringF(20); data.instBagNdx = ar.readUInt16(); root.data.push(data); return data; }; var parseIBAG1 = function(ar, root, i) { ar.seek(root.headPosition + i * 4); var data = {}; data.instGenNdx = ar.readUInt16(); data.instModNdx = ar.readUInt16(); root.data.push(data); return data; }; var parseIGEN1 = function(ar, root, i) { ar.seek(root.headPosition + i * 4); var data = {}; data.genOper = ar.readUInt16(); data.inst = sfGenerator[data.genOper]; if(data.inst == 'keyRange' || data.inst == 'velRange' || data.inst == 'keynum' || data.inst == 'velocity') { data.genAmount = {}; data.genAmount.lo = ar.readUInt8(); data.genAmount.hi = ar.readUInt8(); } else { data.genAmount = ar.readInt16(); } root.data.push(data); return data; }; var parseSHDR1 = function(ar, root, i) { ar.seek(root.headPosition + i * 46); var data = {}; data.sampleName = ar.readStringF(20); data.start = ar.readUInt32(); data.end = ar.readUInt32(); data.startloop = ar.readUInt32(); data.endloop = ar.readUInt32(); data.sampleRate = ar.readUInt32(); data.originalPitch = ar.readUInt8(); data.pitchCorrection = ar.readInt8(); data.sampleLink = ar.readUInt16(); data.sampleType = ar.readUInt16(); root.data.push(data); return data; }; return that; } return sf2; });
ruly-rudel/tipsound
js/sf2.js
JavaScript
mit
16,386
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // @ignoreDep @angular/compiler-cli const ts = require("typescript"); const path = require("path"); const fs = require("fs"); const { __NGTOOLS_PRIVATE_API_2, VERSION } = require('@angular/compiler-cli'); const resource_loader_1 = require("./resource_loader"); class ExtractI18nPlugin { constructor(options) { this._compiler = null; this._compilation = null; this._compilerOptions = null; this._angularCompilerOptions = null; this._setupOptions(options); } _setupOptions(options) { if (!options.hasOwnProperty('tsConfigPath')) { throw new Error('Must specify "tsConfigPath" in the configuration of @ngtools/webpack.'); } // TS represents paths internally with '/' and expects the tsconfig path to be in this format this._tsConfigPath = options.tsConfigPath.replace(/\\/g, '/'); // Check the base path. const maybeBasePath = path.resolve(process.cwd(), this._tsConfigPath); let basePath = maybeBasePath; if (fs.statSync(maybeBasePath).isFile()) { basePath = path.dirname(basePath); } if (options.hasOwnProperty('basePath')) { basePath = path.resolve(process.cwd(), options.basePath); } let tsConfigJson = null; try { tsConfigJson = JSON.parse(fs.readFileSync(this._tsConfigPath, 'utf8')); } catch (err) { throw new Error(`An error happened while parsing ${this._tsConfigPath} JSON: ${err}.`); } const tsConfig = ts.parseJsonConfigFileContent(tsConfigJson, ts.sys, basePath, null, this._tsConfigPath); let fileNames = tsConfig.fileNames; if (options.hasOwnProperty('exclude')) { let exclude = typeof options.exclude == 'string' ? [options.exclude] : options.exclude; exclude.forEach((pattern) => { const basePathPattern = '(' + basePath.replace(/\\/g, '/') .replace(/[\-\[\]\/{}()+?.\\^$|*]/g, '\\$&') + ')?'; pattern = pattern .replace(/\\/g, '/') .replace(/[\-\[\]{}()+?.\\^$|]/g, '\\$&') .replace(/\*\*/g, '(?:.*)') .replace(/\*/g, '(?:[^/]*)') .replace(/^/, basePathPattern); const re = new RegExp('^' + pattern + '$'); fileNames = fileNames.filter(x => !x.replace(/\\/g, '/').match(re)); }); } else { fileNames = fileNames.filter(fileName => !/\.spec\.ts$/.test(fileName)); } this._rootFilePath = fileNames; // By default messages will be generated in basePath let genDir = basePath; if (options.hasOwnProperty('genDir')) { genDir = path.resolve(process.cwd(), options.genDir); } this._compilerOptions = tsConfig.options; this._angularCompilerOptions = Object.assign({ genDir }, this._compilerOptions, tsConfig.raw['angularCompilerOptions'], { basePath }); this._basePath = basePath; this._genDir = genDir; // this._compilerHost = new WebpackCompilerHost(this._compilerOptions, this._basePath); this._compilerHost = ts.createCompilerHost(this._compilerOptions, true); this._program = ts.createProgram(this._rootFilePath, this._compilerOptions, this._compilerHost); if (options.hasOwnProperty('i18nFormat')) { this._i18nFormat = options.i18nFormat; } if (options.hasOwnProperty('locale')) { if (VERSION.major === '2') { console.warn("The option '--locale' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._locale = options.locale; } if (options.hasOwnProperty('outFile')) { if (VERSION.major === '2') { console.warn("The option '--out-file' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._outFile = options.outFile; } } apply(compiler) { this._compiler = compiler; compiler.plugin('make', (compilation, cb) => this._make(compilation, cb)); compiler.plugin('after-emit', (compilation, cb) => { this._donePromise = null; this._compilation = null; compilation._ngToolsWebpackXi18nPluginInstance = null; cb(); }); } _make(compilation, cb) { this._compilation = compilation; if (this._compilation._ngToolsWebpackXi18nPluginInstance) { return cb(new Error('An @ngtools/webpack xi18n plugin already exist for ' + 'this compilation.')); } if (!this._compilation._ngToolsWebpackPluginInstance) { return cb(new Error('An @ngtools/webpack aot plugin does not exists ' + 'for this compilation')); } this._compilation._ngToolsWebpackXi18nPluginInstance = this; this._resourceLoader = new resource_loader_1.WebpackResourceLoader(compilation); this._donePromise = Promise.resolve() .then(() => { return __NGTOOLS_PRIVATE_API_2.extractI18n({ basePath: this._basePath, compilerOptions: this._compilerOptions, program: this._program, host: this._compilerHost, angularCompilerOptions: this._angularCompilerOptions, i18nFormat: this._i18nFormat, locale: this._locale, outFile: this._outFile, readResource: (path) => this._resourceLoader.get(path) }); }) .then(() => cb(), (err) => { this._compilation.errors.push(err); cb(err); }); } } exports.ExtractI18nPlugin = ExtractI18nPlugin; //# sourceMappingURL=/users/mikkeldamm/forked-repos/angular-cli/src/extract_i18n_plugin.js.map
mikkeldamm/angular-cli
dist/@ngtools/webpack/src/extract_i18n_plugin.js
JavaScript
mit
6,184
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ /** * @overview */ /** * Creates a folder properties dialog. * @class * This class represents a folder properties dialog. * * @param {DwtControl} parent the parent * @param {String} className the class name * * @extends DwtDialog */ ZmFolderPropsDialog = function(parent, className) { className = className || "ZmFolderPropsDialog"; var extraButtons; if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { extraButtons = [ new DwtDialog_ButtonDescriptor(ZmFolderPropsDialog.ADD_SHARE_BUTTON, ZmMsg.addShare, DwtDialog.ALIGN_LEFT) ]; } DwtDialog.call(this, {parent:parent, className:className, title:ZmMsg.folderProperties, extraButtons:extraButtons, id:"FolderProperties"}); this._tabViews = []; this._tabKeys = []; this._tabInUse = []; this._tabKeyMap = {}; if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { this.registerCallback(ZmFolderPropsDialog.ADD_SHARE_BUTTON, this._handleAddShareButton, this); } this.setButtonListener(DwtDialog.OK_BUTTON, new AjxListener(this, this._handleOkButton)); this.setButtonListener(DwtDialog.CANCEL_BUTTON, new AjxListener(this, this._handleCancelButton)); this._folderChangeListener = new AjxListener(this, this._handleFolderChange); this._createView(); }; ZmFolderPropsDialog.prototype = new DwtDialog; ZmFolderPropsDialog.prototype.constructor = ZmFolderPropsDialog; // Constants ZmFolderPropsDialog.ADD_SHARE_BUTTON = ++DwtDialog.LAST_BUTTON; ZmFolderPropsDialog.SHARES_HEIGHT = "9em"; // Tab identifiers ZmFolderPropsDialog.TABKEY_PROPERTIES = "PROPERTIES_TAB"; ZmFolderPropsDialog.TABKEY_RETENTION = "RETENTION_TAB"; // Public methods ZmFolderPropsDialog.prototype.toString = function() { return "ZmFolderPropsDialog"; }; ZmFolderPropsDialog.prototype.getTabKey = function(id) { var index = this._tabKeyMap[id]; return this._tabKeys[index]; }; /** * Pops-up the properties dialog. * * @param {ZmOrganizer} organizer the organizer */ ZmFolderPropsDialog.prototype.popup = function(organizer) { this._organizer = organizer; for (var i = 0; i < this._tabViews.length; i++) { this._tabViews[i].setOrganizer(organizer); } // On popup, make the property view visible var tabKey = this.getTabKey(ZmFolderPropsDialog.TABKEY_PROPERTIES); this._tabContainer.switchToTab(tabKey, true); organizer.addChangeListener(this._folderChangeListener); this._handleFolderChange(); if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { var isShareable = ZmOrganizer.SHAREABLE[organizer.type]; var isVisible = (!organizer.link || organizer.isAdmin()); this.setButtonVisible(ZmFolderPropsDialog.ADD_SHARE_BUTTON, isVisible && isShareable); } DwtDialog.prototype.popup.call(this); }; ZmFolderPropsDialog.prototype.popdown = function() { if (this._organizer) { this._organizer.removeChangeListener(this._folderChangeListener); this._organizer = null; } DwtDialog.prototype.popdown.call(this); }; // Protected methods ZmFolderPropsDialog.prototype._getSeparatorTemplate = function() { return ""; }; ZmFolderPropsDialog.prototype._handleEditShare = function(event, share) { share = share || Dwt.getObjectFromElement(DwtUiEvent.getTarget(event)); var sharePropsDialog = appCtxt.getSharePropsDialog(); sharePropsDialog.popup(ZmSharePropsDialog.EDIT, share.object, share); return false; }; ZmFolderPropsDialog.prototype._handleRevokeShare = function(event, share) { share = share || Dwt.getObjectFromElement(DwtUiEvent.getTarget(event)); var revokeShareDialog = appCtxt.getRevokeShareDialog(); revokeShareDialog.popup(share); return false; }; ZmFolderPropsDialog.prototype._handleResendShare = function(event, share) { AjxDispatcher.require("Share"); share = share || Dwt.getObjectFromElement(DwtUiEvent.getTarget(event)); // create share info var tmpShare = new ZmShare({object:share.object}); tmpShare.grantee.id = share.grantee.id; tmpShare.grantee.email = (share.grantee.type == "guest") ? share.grantee.id : share.grantee.name; tmpShare.grantee.name = share.grantee.name; if (tmpShare.object.isRemote()) { tmpShare.grantor.id = tmpShare.object.zid; tmpShare.grantor.email = tmpShare.object.owner; tmpShare.grantor.name = tmpShare.grantor.email; tmpShare.link.id = tmpShare.object.rid; } else { tmpShare.grantor.id = appCtxt.get(ZmSetting.USERID); tmpShare.grantor.email = appCtxt.get(ZmSetting.USERNAME); tmpShare.grantor.name = appCtxt.get(ZmSetting.DISPLAY_NAME) || tmpShare.grantor.email; tmpShare.link.id = tmpShare.object.id; } tmpShare.link.name = share.object.name; tmpShare.link.view = ZmOrganizer.getViewName(share.object.type); tmpShare.link.perm = share.link.perm; if (share.grantee.type == "guest") { // Pass action as ZmShare.NEW even for resend for external user tmpShare._sendShareNotification(tmpShare.grantee.email, tmpShare.link.id, "", ZmShare.NEW); } else { tmpShare.sendMessage(ZmShare.NEW); } appCtxt.setStatusMsg(ZmMsg.resentShareMessage); return false; }; ZmFolderPropsDialog.prototype._handleAddShareButton = function(event) { var sharePropsDialog = appCtxt.getSharePropsDialog(); sharePropsDialog.popup(ZmSharePropsDialog.NEW, this._organizer, null); }; ZmFolderPropsDialog.prototype._handleOkButton = function(event) { // New batch command, stop on error var batchCommand = new ZmBatchCommand(null, null, true); var saveState = { commandCount: 0, errorMessage: [] }; for (var i = 0; i < this._tabViews.length; i++) { if (this._tabInUse[i]) { // Save all in use tabs this._tabViews[i].doSave(batchCommand, saveState); } } if (saveState.errorMessage.length > 0) { var msg = saveState.errorMessage.join("<br>"); var dialog = appCtxt.getMsgDialog(); dialog.reset(); dialog.setMessage(msg, DwtMessageDialog.WARNING_STYLE); dialog.popup(); } else if (saveState.commandCount > 0) { var callback = new AjxCallback(this, this.popdown); batchCommand.run(callback); } else { this.popdown(); } }; ZmFolderPropsDialog.prototype._handleError = function(response) { // Returned 'not handled' so that the batch command will preform the default // ZmController._handleException return false; }; ZmFolderPropsDialog.prototype._handleCancelButton = function(event) { this.popdown(); }; ZmFolderPropsDialog.prototype._handleFolderChange = function(event) { var organizer = this._organizer; // Get the components that will be hidden or displayed var tabBar = this._tabContainer.getTabBar(); var tabKey = this.getTabKey(ZmFolderPropsDialog.TABKEY_RETENTION); var retentionTabButton = this._tabContainer.getTabButton(tabKey); var retentionIndex = this._tabKeyMap[ZmFolderPropsDialog.TABKEY_RETENTION]; if ((organizer.type != ZmOrganizer.FOLDER) || organizer.link) { // Not a folder, or shared - hide the retention view (and possibly the toolbar) this._tabInUse[retentionIndex] = false; if (this._tabViews.length > 2) { // More than two tabs, hide the retention tab, leave the toolbar intact tabBar.setVisible(true); retentionTabButton.setVisible(false); } else { // Two or fewer tabs. Hide the toolbar, just let the properties view display standalone // (On popup, the display defaults to the property view) tabBar.setVisible(false); } } else { // Using the retention tab view - show the toolbar and all tabs this._tabInUse[retentionIndex] = true; retentionTabButton.setVisible(true); tabBar.setVisible(true); } for (var i = 0; i < this._tabViews.length; i++) { if (this._tabInUse[i]) { // Update all in use tabs to use the specified folder this._tabViews[i]._handleFolderChange(event); } } if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { this._populateShares(organizer); } }; ZmFolderPropsDialog.prototype._populateShares = function(organizer) { this._sharesGroup.setContent(""); var displayShares = this._getDisplayShares(organizer); var getFolder = false; if (displayShares.length) { for (var i = 0; i < displayShares.length; i++) { var share = displayShares[i]; if (!(share.grantee && share.grantee.name)) { getFolder = true; } } } if (getFolder) { var respCallback = new AjxCallback(this, this._handleResponseGetFolder, [displayShares]); organizer.getFolder(respCallback); } else { this._handleResponseGetFolder(displayShares); } this._sharesGroup.setVisible(displayShares.length > 0); }; ZmFolderPropsDialog.prototype._getDisplayShares = function(organizer) { var shares = organizer.shares; var displayShares = []; if ((!organizer.link || organizer.isAdmin()) && shares && shares.length > 0) { AjxDispatcher.require("Share"); var userZid = appCtxt.accountList.mainAccount.id; // if a folder was shared with us with admin rights, a share is created since we could share it; // don't show any share that's for us in the list for (var i = 0; i < shares.length; i++) { var share = shares[i]; if (share.grantee) { var granteeId = share.grantee.id; if ((share.grantee.type != ZmShare.TYPE_USER) || (share.grantee.id != userZid)) { displayShares.push(share); } } } } return displayShares; }; ZmFolderPropsDialog.prototype._handleResponseGetFolder = function(displayShares, organizer) { if (organizer) { displayShares = this._getDisplayShares(organizer); } if (displayShares.length) { var table = document.createElement("TABLE"); table.className = "ZPropertySheet"; table.cellSpacing = "6"; for (var i = 0; i < displayShares.length; i++) { var share = displayShares[i]; var row = table.insertRow(-1); var nameEl = row.insertCell(-1); nameEl.style.paddingRight = "15px"; var nameText = share.grantee && share.grantee.name; if (share.isAll()) { nameText = ZmMsg.shareWithAll; } else if (share.isPublic()) { nameText = ZmMsg.shareWithPublic; } else if (share.isGuest()){ nameText = nameText || (share.grantee && share.grantee.id); } nameEl.innerHTML = AjxStringUtil.htmlEncode(nameText); var roleEl = row.insertCell(-1); roleEl.style.paddingRight = "15px"; roleEl.innerHTML = ZmShare.getRoleName(share.link.role); this.__createCmdCells(row, share); } this._sharesGroup.setElement(table); var width = Dwt.DEFAULT; var height = displayShares.length > 5 ? ZmFolderPropsDialog.SHARES_HEIGHT : Dwt.CLEAR; var insetElement = this._sharesGroup.getInsetHtmlElement(); Dwt.setScrollStyle(insetElement, Dwt.SCROLL); Dwt.setSize(insetElement, width, height); } this._sharesGroup.setVisible(displayShares.length > 0); }; ZmFolderPropsDialog.prototype.__createCmdCells = function(row, share) { var type = share.grantee.type; if (type == ZmShare.TYPE_DOMAIN || !share.link.role) { var cell = row.insertCell(-1); cell.colSpan = 3; cell.innerHTML = ZmMsg.configureWithAdmin; return; } var actions = [ZmShare.EDIT, ZmShare.REVOKE, ZmShare.RESEND]; var handlers = [this._handleEditShare, this._handleRevokeShare, this._handleResendShare]; for (var i = 0; i < actions.length; i++) { var action = actions[i]; var cell = row.insertCell(-1); // public shares have no editable fields, and sent no mail var isAllShare = share.grantee && (share.grantee.type == ZmShare.TYPE_ALL); if (((isAllShare || share.isPublic() || share.isGuest()) && (action == ZmShare.EDIT)) || ((isAllShare || share.isPublic()) && action == ZmShare.RESEND)) { continue; } var link = document.createElement("A"); link.href = "#"; link.innerHTML = ZmShare.ACTION_LABEL[action]; Dwt.setHandler(link, DwtEvent.ONCLICK, handlers[i]); Dwt.associateElementWithObject(link, share); cell.appendChild(link); } }; ZmFolderPropsDialog.prototype.addTab = function(index, id, tabViewPage) { if (!this._tabContainer || !tabViewPage) { return null; } this._tabViews[index] = tabViewPage; this._tabKeys[index] = this._tabContainer.addTab(tabViewPage.getTitle(), tabViewPage); this._tabInUse[index] = true; this._tabKeyMap[id] = index; return this._tabKeys[index]; }; ZmFolderPropsDialog.prototype._initializeTabView = function(view) { this._tabContainer = new DwtTabView(view, null, Dwt.STATIC_STYLE); //ZmFolderPropertyView handle things such as color and type. (in case you're searching for "color" and can't find in this file. I know I did) this.addTab(0, ZmFolderPropsDialog.TABKEY_PROPERTIES, new ZmFolderPropertyView(this, this._tabContainer)); this.addTab(1, ZmFolderPropsDialog.TABKEY_RETENTION, new ZmFolderRetentionView(this, this._tabContainer)); // setup shares group if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { this._sharesGroup = new DwtGrouper(view, "DwtGrouper ZmFolderPropSharing"); this._sharesGroup.setLabel(ZmMsg.folderSharing); this._sharesGroup.setVisible(false); this._sharesGroup.setScrollStyle(Dwt.SCROLL); view.getHtmlElement().appendChild(this._sharesGroup.getHtmlElement()); } }; // This creates the tab views managed by this dialog, the tabToolbar, and // the share buttons and view components ZmFolderPropsDialog.prototype._createView = function() { this._baseContainerView = new DwtComposite({parent:this, className:"ZmFolderPropertiesDialog-container "}); this._initializeTabView(this._baseContainerView); this.setView(this._baseContainerView); };
nico01f/z-pec
ZimbraWebClient/WebRoot/js/zimbraMail/share/view/dialog/ZmFolderPropsDialog.js
JavaScript
mit
14,081
var coords; var directionsDisplay; var map; var travelMode; var travelModeElement = $('#mode_travel'); // Order of operations for the trip planner (each function will have detailed notes): // 1) Calculate a user's route, with directions. // 2) Run a query using the route's max and min bounds to narrow potential results. // 3) Just because a marker is in the area of the route, it doesn't mean that it's on the route. // Use RouteBoxer to map sections of the route to markers, if applicable. Display only those markers on the map. // 4) The directions panel also isn't linked to a section of the route. // Use RouteBoxer to map a direction (turn left, right, etc) to part of the route. // 5) Build the custom directions panel by looping though each leg of the trip, finding the corresponding RouteBoxer // section, and use that to get markers for that section only. $(document).ready(function () { $('.active').toggleClass('active'); $('#trip-planner').toggleClass('active'); }); // Run these functions after setting geolocation. All except setFormDateTime() are dependent on geolocation to run. initGeolocation().then(function (coords) { map = mapGenerator(coords); setDirectionsDisplay(map); formListener(); }); // Instantiate directions methods on map. function setDirectionsDisplay(map) { directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); } // Listener for if the mode of travel is changed from an empty default to either bicycling or walking. function formListener() { travelModeElement.change(function(){ // Launch route calculation, markers, and directions panel. calcRoute(); }); } // Once the mode of travel is selected, start calculating routes and get marker data. function calcRoute() { var directionsService = new google.maps.DirectionsService(); var start = $('#start').val(); var end = $('#end').val(); travelMode = travelModeElement.val(); var request = { origin: start, destination: end, travelMode: google.maps.TravelMode[travelMode] }; directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); // Remove existing markers from the map and map object. removeMarkers(true); queryResults = getMarkers(response); // Check if results are along the route. if (queryResults.objects.length > 0) { // Filter the query results further by comparing coords with each route section. narrowResults(queryResults.objects, response); // If no query results, set the marker count to 0 and generate the directions panel. } else { response.routes[0].legs[0]['marker_count'] = 0; generateDirectionsPanel(response); } } }); } // Get markers near a route. This is done by getting the boundaries for the route as a whole and using those // as query params. function getMarkers(response){ var userType; if (travelMode == "BICYCLING") { userType = 1; } else { userType = 2; } // Build the query string, limiting the results for cyclists and pedestrians. var queryString = '/api/v1/hazard/?format=json&?user_type=' + userType; // Get the maximum and minimum lat/lon bounds for the route. // This will narrow the query to a box around the route as a whole. var routeBounds = getBounds(response.routes[0].bounds); // TODO(zemadi): Look up alternatives for building the querystring. //Build the querystring. Negative numbers require different greater/less than logic, // so testing for that here. if (routeBounds.lat1 >= 0 && routeBounds.lat2 >= 0) { queryString += '&lat__gte=' + routeBounds.lat1 + '&lat__lte=' + routeBounds.lat2; } else { queryString += '&lat__gte=' + routeBounds.lat2 + '&lat__lte=' + routeBounds.lat1; } if (routeBounds.lon1 >= 0 && routeBounds.lon2 >= 0) { queryString += '&lon__gte=' + routeBounds.lon1 + '&lon__lte=' + routeBounds.lon2; } else { queryString += '&lon__gte=' + routeBounds.lon2 + '&lon__lte=' + routeBounds.lon1; } return httpGet(queryString); } // Function to get coordinate boundaries from the Directions route callback. function getBounds(data) { var coordinateBounds = {}; var keyByIndex = Object.keys(data); coordinateBounds['lat1'] = data[keyByIndex[0]]['k']; coordinateBounds['lat2'] = data[keyByIndex[0]]['j']; coordinateBounds['lon1'] = data[keyByIndex[1]]['k']; coordinateBounds['lon2'] = data[keyByIndex[1]]['j']; return coordinateBounds; } // Reduce the query results further by checking if they're actually along a route. // In order for a data point to be on the route, the coordinates need to be between the values of a box in routeBoxer. // RouteBoxer chops up a route into sections and returns the upper and lower boundaries for that section of the route. // Refer to: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/routeboxer/docs/examples.html function narrowResults(queryResults, directionsResponse) { // Variables needed for routeBoxer. var path = directionsResponse.routes[0].overview_path; var rboxer = new RouteBoxer(); var boxes = rboxer.box(path, .03); // Second param is a boundary in km from the route path. //Variables to hold mapData and match a marker to a specific section of the route. var mapData = {'objects': []}; // Object to hold routeBoxer index to markers map. var mapBoxesAndMarkers = {}; // For each section of the route, look through markers to see if any fit in the section's boundaries. // Using a for loop here because routeBoxer returns an array. for (var j = 0, b=boxes.length; j < b; j++) { // For each section of the route, record the index as a key and create an empty array to hold marker values. mapBoxesAndMarkers[j] = []; queryResults.forEach(function(result) { // If a marker is between the latitude and longitude bounds of the route, add it to the map and // the route-marker dict. var currentResult = new google.maps.LatLng(result.lat, result.lon); if (boxes[j].contains(currentResult)) { mapData.objects.push(result); mapBoxesAndMarkers[j].push(result); } }); } if (mapData.objects.length > 0) { // Add new markers to the map. markerGenerator(map, mapData); // Add the count of valid markers to the directionsResponse object, which is used to generate // the directions panel. If there are no markers, add 'None'. directionsResponse.routes[0].legs[0]['marker_count'] = mapData.objects.length; } else { directionsResponse.routes[0].legs[0]['marker_count'] = 'None'; } mapDirectionsToBoxes(boxes, directionsResponse, mapBoxesAndMarkers); } // Directions information also needs to be mapped to a section of the route. function mapDirectionsToBoxes(boxes, directionsResponse, mapBoxesAndMarkers){ var directions = directionsResponse.routes[0].legs[0].steps; // go through each step and set of lat lngs per step. directions.forEach(function(direction) { var routeBoxesinDirection = []; for (var l = 0, b=boxes.length; l < b; l++) { direction.lat_lngs.forEach(function(lat_lng) { // If the index isn't already in the array and the box contains the current route's lat and long, add the // index. if (routeBoxesinDirection.indexOf(l) === -1 && boxes[l].contains(lat_lng)) { routeBoxesinDirection.push(l); } }); } // Once we're done looping over route boxes for the current direction, lookup markers that have the same bounds. // A direction can have multiple route boxes so a list is being used here. direction['markers'] = []; routeBoxesinDirection.forEach(function(box) { if (mapBoxesAndMarkers[box].length > 0) { // Use the route box to look up arrays of markers to add to the directions object. direction['markers'].push.apply(direction['markers'], mapBoxesAndMarkers[box]); } }); }); generateDirectionsPanel(directionsResponse); } function generateDirectionsPanel(directionsResponse) { var directionsPanel = $('#directions-panel'); var directionsPanelHtml = $('#directions-panel-template').html(); var newSearchTrigger = $('#new-search-trigger'); var template = Handlebars.compile(directionsPanelHtml); var compiledDirectionsPanel = template(directionsResponse.routes[0].legs[0]); if (directionsPanel[0].children.length > 0) { directionsPanel[0].innerHTML = compiledDirectionsPanel; } else { directionsPanel.append(compiledDirectionsPanel); } // Close the trip planner form and display the directions panel. $('#trip-planner-form').addClass('closed'); directionsPanel.removeClass('closed'); newSearchTrigger.removeClass('hidden'); // Listen for a new search event, which shows the form and closes the directions panel. newSearchTrigger.click(function(){ directionsPanel.addClass('closed'); newSearchTrigger.addClass('hidden'); $('#trip-planner-form').removeClass('closed'); }); }
codeforsanjose/CycleSafe
app/static/js/trip_planner.js
JavaScript
mit
9,596
define(['backbone', 'marionette', 'mustache', 'jquery', 'text!templates/ctrldialog.html'], function(Backbone, Marionette, Mustache, $, template) { return Marionette.ItemView.extend({ initialize: function(options) { if (!options.icon_name) { options.icon_name = 'bird'; } this.model = new Backbone.Model( options ); this.render(); }, template: function(serialized_model) { return Mustache.render(template, serialized_model); }, ui: { 'ok': '.btn-ok', 'cancel': '.btn-cancel', 'dialog': '.dialog', 'close': '.dialog-close' }, events: { 'tap @ui.ok': 'onOk', 'tap @ui.cancel': 'onCancel', 'tap @ui.close': 'onCancel' }, onOk: function(ev) { this.trigger('ok'); this.destroy(); }, onCancel: function(ev) { this.trigger('cancel'); this.destroy(); }, onRender: function() { $('body').append(this.$el); this.ui.dialog.css({ 'marginTop': 0 - this.ui.dialog.height()/2 }); this.ui.dialog.addClass('bounceInDown animated'); }, onDestory: function() { this.$el.remove(); this.model.destroy(); }, className: 'dialogContainer' }); });
yoniji/ApeRulerDemo
app/modules/ctrls/CtrlDialogView.js
JavaScript
mit
1,645
import { InvalidArgumentError } from '../errors/InvalidArgumentError'; import { NotImplementedError } from '../errors/NotImplementedError'; import mustache from 'mustache'; import '../utils/Function'; // The base class for a control export class Control { // The constructor of a control // id: The id of the control // template: The template used for rendering the control // localCSS: An object whose properties are CSS class names and whose values are the localized CSS class names // The control will change the matching CSS class names in the templates. constructor(id, template, localCSS) { if (typeof id !== 'string' || !isNaN(id)) { throw new InvalidArgumentError('Cannot create the control because the id is not a string'); } if (id.length < 1) { throw new InvalidArgumentError('Cannot create the control because the id is not a non-empty string'); } if (null === template || undefined === template) { throw new InvalidArgumentError('Cannot create the control because the template cannot be null or undefined'); } if (typeof template !== 'string') { throw new InvalidArgumentError('Cannot create the control because the template is not a string'); } this.id = id; this.template = template; if (template && localCSS) { // localize the CSS class names in the templates for (const oCN in localCSS) { const nCN = localCSS[oCN]; this.template = this.template .replace(new RegExp(`class="${oCN}"`, 'gi'), `class="${nCN}"`) .replace(new RegExp(`class='${oCN}'`, 'gi'), `class='${nCN}'`); } } this.controls = {}; } // Adds a child control to the control // control: The Control instance addControl(control) { if (!(control instanceof Control)) { throw new InvalidArgumentError('Cannot add sub-control because it is invalid'); } this.controls[control.id] = control; } // Removes a child control from the control // val: Either a controlId or a Control instance removeControl(val) { if (val instanceof Control) { delete this.controls[val.id]; } else { delete this.controls[val]; } } // Renders the control (and all its contained controls) // data: The object that contains the data to substitute into the template // eventObj: Event related data for the event that caused the control to render render(data, eventObj) { if (this.controls) { const controlData = {}; for (let controlId in this.controls) { const control = this.controls[controlId]; controlData[control.constructor.getConstructorName()] = {}; controlData[control.constructor.getConstructorName()][control.id] = control.render(data, eventObj); } for (let key in controlData) { data[key] = controlData[key]; } } return mustache.render(this.template, data); } // This method is invoked so the control can bind events after the DOM has been updated // domContainerElement: The DOM container element into which the control was rendered // eventObj: Event related data for the event that caused the control to render onDOMUpdated(domContainerElement, eventObj) { if (this.onDOMUpdatedNotification) { this.onDOMUpdatedNotification(domContainerElement, eventObj); } if (this.controls) { for (let controlId in this.controls) { const control = this.controls[controlId]; control.onDOMUpdated(domContainerElement, eventObj); } } } // The Control classes that extend this type can add custom logic here to be executed after the domContainerElement // has been updated // domContainerElement: The DOM container element into which the control was rendered // eventObj: Event related data for the event that caused the control to render onDOMUpdatedNotification(domContainerElement, eventObj) { } };
kmati/affront
lib/Control/index.js
JavaScript
mit
3,736
'use strict'; /* jasmine specs for filters go here */ describe('filter', function() { });
LeoAref/angular-seed
test/unit/filtersSpec.js
JavaScript
mit
93
!function(n){}(jQuery); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5iYWRyYWZ0LnNjcmlwdC5qcyJdLCJuYW1lcyI6WyIkIiwialF1ZXJ5Il0sIm1hcHBpbmdzIjoiQ0FJQSxTQUFBQSxLQUVBQyIsImZpbGUiOiJuYmFkcmFmdC5zY3JpcHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBmaWxlXG4gKiBDdXN0b20gc2NyaXB0cyBmb3IgdGhlbWUuXG4gKi9cbihmdW5jdGlvbiAoJCkge1xuICBcbn0pKGpRdWVyeSk7XG4iXSwic291cmNlUm9vdCI6Ii9zb3VyY2UvIn0=
eganr/nba-draft-lookup
themes/nbadraft/assets/js/nbadraft.script.js
JavaScript
mit
419
/** * Most of this code is adapated from https://github.com/qimingweng/react-modal-dialog */ import React from 'react'; import ReactDOM from 'react-dom'; import EventStack from './EventStack'; import PropTypes from 'prop-types'; const ESCAPE = 27; /** * Get the keycode from an event * @param {Event} event The browser event from which we want the keycode from * @returns {Number} The number of the keycode */ const getKeyCodeFromEvent = event => event.which || event.keyCode || event.charCode; // Render into subtree is necessary for parent contexts to transfer over // For example, for react-router const renderSubtreeIntoContainer = ReactDOM.unstable_renderSubtreeIntoContainer; export class ModalContent extends React.Component { constructor(props) { super(props); this.handleGlobalClick = this.handleGlobalClick.bind(this); this.handleGlobalKeydown = this.handleGlobalKeydown.bind(this); } componentWillMount() { /** * This is done in the componentWillMount instead of the componentDidMount * because this way, a modal that is a child of another will have register * for events after its parent */ this.eventToken = EventStack.addListenable([ ['click', this.handleGlobalClick], ['keydown', this.handleGlobalKeydown] ]); } componentWillUnmount() { EventStack.removeListenable(this.eventToken); } shouldClickDismiss(event) { const { target } = event; // This piece of code isolates targets which are fake clicked by things // like file-drop handlers if (target.tagName === 'INPUT' && target.type === 'file') { return false; } if (!this.props.dismissOnBackgroundClick) { if (target !== this.refs.self || this.refs.self.contains(target)) { return false; } } else { if (target === this.refs.self || this.refs.self.contains(target)) { return false; } } return true; } handleGlobalClick(event) { if (this.shouldClickDismiss(event)) { if (typeof this.props.onClose === 'function') { this.props.onClose(event); } } } handleGlobalKeydown(event) { if (getKeyCodeFromEvent(event) === ESCAPE) { if (typeof this.props.onClose === 'function') { this.props.onClose(event); } } } render() { return ( <div ref="self" className={'liq_modal-content'}> {this.props.showButton && this.props.onClose ? ( <button onClick={this.props.onClose} className={'liq_modal-close'} data-test="close_modal_button"> <span aria-hidden="true">{'×'}</span> </button> ) : null} {this.props.children} </div> ); } } ModalContent.propTypes = { showButton: PropTypes.bool, onClose: PropTypes.func, // required for the close button className: PropTypes.string, children: PropTypes.node, dismissOnBackgroundClick: PropTypes.bool }; ModalContent.defaultProps = { dismissOnBackgroundClick: true, showButton: true }; export class ModalPortal extends React.Component { componentDidMount() { // disable scrolling on body document.body.classList.add('liq_modal-open'); // Create a div and append it to the body this._target = document.body.appendChild(document.createElement('div')); // Mount a component on that div this._component = renderSubtreeIntoContainer( this, this.props.children, this._target ); // A handler call in case you want to do something when a modal opens, like add a class to the body or something if (typeof this.props.onModalDidMount === 'function') { this.props.onModalDidMount(); } } componentDidUpdate() { // When the child component updates, we have to make sure the content rendered to the DOM is updated to this._component = renderSubtreeIntoContainer( this, this.props.children, this._target ); } componentWillUnmount() { /** * Let this be some discussion about fading out the components on unmount. * Right now, there is the issue that if a stack of components are layered * on top of each other, and you programmatically dismiss the bottom one, * it actually takes some time for the animation to catch up to the top one, * because each modal doesn't send a dismiss signal to its children until * it itself is totally gone... */ // TODO: REMOVE THIS - THINK OUT OF THE BOX const done = () => { // Modal will unmount now // Call a handler, like onModalDidMount if (typeof this.props.onModalWillUnmount === 'function') { this.props.onModalWillUnmount(); } // Remove the node and clean up after the target ReactDOM.unmountComponentAtNode(this._target); document.body.removeChild(this._target); document.body.classList.remove('liq_modal-open'); }; // A similar API to react-transition-group if ( this._component && typeof this._component.componentWillLeave === 'function' ) { // Pass the callback to be called on completion this._component.componentWillLeave(done); } else { // Call completion immediately done(); } } render() { return null; } // This doesn't actually return anything to render } ModalPortal.propTypes = { onClose: PropTypes.func, // This is called when the dialog should close children: PropTypes.node, onModalDidMount: PropTypes.func, // optional, called on mount onModalWillUnmount: PropTypes.func // optional, called on unmount }; export class ModalBackground extends React.Component { constructor(props) { super(props); this.state = { // This is set to false as soon as the component has mounted // This allows the component to change its css and animate in transparent: true }; } componentDidMount() { // Create a delay so CSS will animate requestAnimationFrame(() => this.setState({ transparent: false })); } componentWillLeave(callback) { this.setState({ transparent: true, componentIsLeaving: true }); // There isn't a good way to figure out what the duration is exactly, // because parts of the animation are carried out in CSS... setTimeout(() => { callback(); }, this.props.duration); } render() { const { transparent } = this.state; const overlayStyle = { opacity: transparent ? 0 : 0.6 }; const containerStyle = { opacity: transparent ? 0 : 1 }; return ( <div className={'liq_modal-background'} style={{ zIndex: this.props.zIndex }}> <div style={overlayStyle} className={'liq_modal-background__overlay'} /> <div style={containerStyle} className={'liq_modal-background__container'}> {this.props.children} </div> </div> ); } } ModalBackground.defaultProps = { duration: 300, zIndex: 1100 // to lay above tooltips and the website header }; ModalBackground.propTypes = { onClose: PropTypes.func, duration: PropTypes.number.isRequired, zIndex: PropTypes.number.isRequired, children: PropTypes.node }; export default { ModalPortal, ModalBackground, ModalContent };
LIQIDTechnology/liqid-react-components
src/components/Modal/Components.js
JavaScript
mit
8,193
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var util = require('util'); var session = require('express-session'); var passport = require('passport'); module.exports = (app, url, appEnv, User) => { app.use(session({ secret: process.env.SESSION_SECRET, name: 'freelancalot', proxy: true, resave: true, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser((user, done) => { var id = user.get('id'); console.log('serializeUser: ' + id) done(null, id); }); passport.deserializeUser((id, done) => { User.findById(id).then((user) => { done(null, user); }) }); var googleOAuth = appEnv.getService('googleOAuth'), googleOAuthCreds = googleOAuth.credentials; passport.use(new GoogleStrategy({ clientID: googleOAuthCreds.clientID, clientSecret: googleOAuthCreds.clientSecret, callbackURL: util.format("http://%s%s", url, googleOAuthCreds.callbackPath) }, (token, refreshToken, profile, done) => { process.nextTick(() => { User.findOrCreate({ where: { googleId: profile.id }, defaults: { name: profile.displayName, email: profile.emails[0].value, photo: profile.photos[0].value } }) .spread((user, created) => { done(null, user); }) }); })); app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] })); app.get('/auth/google/callback', passport.authenticate('google', { successRedirect: '/' })); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); }
lorentzlasson/node-angular-starter
auth.js
JavaScript
mit
2,087