commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
565484126dc07d331266a2d66ac93295490ab30a
Add "backward" argument to checkIfPunctuator fn
lib/token-helper.js
lib/token-helper.js
/** * Returns token by range start. Ignores () * * @param {JsFile} file * @param {Number} range * @param {Boolean} [backward=false] Direction * @returns {Object} */ exports.getTokenByRangeStart = function(file, range, backward) { var tokens = file.getTokens(); // get next token var tokenPos = file.getTokenPosByRangeStart(range); var token = tokens[tokenPos]; // we should check for "(" if we go backward var parenthesis = backward ? '(' : ')'; // if token is ")" -> get next token // for example (a) + (b) // next token ---^ // we should find (a) + (b) // ------------------^ if (token && token.type === 'Punctuator' && token.value === parenthesis ) { var pos = backward ? token.range[0] - 1 : token.range[1]; tokenPos = file.getTokenPosByRangeStart(pos); token = tokens[tokenPos]; } return token; }; /** * Returns true if token is punctuator * * @param {Object} token * @param {String} punctuator * @returns {Boolean} */ exports.tokenIsPunctuator = function(token, punctuator) { return token && token.type === 'Punctuator' && token.value === punctuator; }; /** * Find previous operator by range start * * @param {JsFile} file * @param {Number} range * @param {String} operator * @returns {Boolean|Object} */ exports.findOperatorByRangeStart = function(file, range, operator) { var tokens = file.getTokens(); var index = file.getTokenPosByRangeStart(range); while (index) { if (tokens[ index ].value === operator) { return tokens[ index ]; } index--; } return false; }; /** * Returns token or false if there is a punctuator in a given range * * @param {JsFile} file * @param {Number} range * @param {String} operator * @returns {Object|Boolean} */ exports.checkIfPunctuator = function(file, range, operator) { var part = this.getTokenByRangeStart(file, range); if (this.tokenIsPunctuator(part, operator)) { return part; } return false; }
JavaScript
0.000177
@@ -1800,32 +1800,79 @@ tring%7D operator%0A + * @param %7BBoolean%7D %5Bbackward=false%5D Direction%0A * @returns %7BObj @@ -1938,32 +1938,42 @@ range, operator +, backward ) %7B%0A var part @@ -2008,24 +2008,34 @@ (file, range +, backward );%0A%0A if ( @@ -2123,9 +2123,10 @@ false;%0A%7D +; %0A
b8a68040b31c9a7d849112e5f49b4aa20eb1513d
add validators & rename field to property (mapper definition are compliant with JSON Schema)
main.js
main.js
var cb = require('couchbase'); var q = require('q'); var extend = require('extend'); var util = require('util'); var EventEmitter = require('events').EventEmitter; /** * The manager class */ var manager = function(options) { // parent constructor call EventEmitter.call(this); // Handles default options this.options = extend(true, { // list of behaviour handlers behaviours: ['index', 'required', 'unique'] // factories , factory: { mapper: require(__dirname + '/src/mapper')(this), record: require(__dirname + '/src/record'), resultset: require(__dirname + '/src/resultset'), field: require(__dirname + '/src/field') } }, options ); // registers behaviours for(var i = 0; i < this.options.behaviours.length; i++) { var behaviour = this.options.behaviours[i]; if (behaviour instanceof String) { this.options.behaviours[i] = require( behaviour[0] == '.' || behaviour[0] == '/' ? behaviour : __dirname + '/src/behaviours/' + behaviour )(this); } } // registers events if (this.options.hasOwnProperty('on')) { for(var event in this.options.on) { this.on(event, this.options.on[event]); } } // connects to couchbase if (this.options.hasOwnProperty('couchbase')) { this.connect(this.options.couchbase).done(); } // declare registered mappers this.mappers = {}; if(this.options.hasOwnProperty('mappers')) { for(var name in this.options.mappers) { this.declare(name, this.options.mappers[name]); } } }; util.inherits(manager, EventEmitter); /** * Connects to couchbase */ manager.prototype.connect = function(options) { var result = q.defer(); var self = this; this.cb = new cb.Connection(options || {}, function(err) { if (err) { result.reject(err); self.emit('error', err); self.cb = null; } else { result.resolve(self); self.emit('connect', self); } }); return result.promise; }; /** * Declare a new mapper */ manager.prototype.declare = function(namespace, options) { if (this.mappers.hasOwnProperty(namespace)) { throw new Error( 'Namespace [' + namespace + '] is already defined !' ); } return new this.options.factory.mapper(namespace, options); }; /** * Gets a mapper */ manager.prototype.get = function(namespace) { if (!this.mappers.hasOwnProperty(namespace)) { throw new Error('Namespace [' + namespace + '] is undefined !'); } return this.mappers[namespace]; }; /** * Checks if the mapper is defined */ manager.prototype.has = function(namespace) { return this.mappers.hasOwnProperty(namespace); }; module.exports = manager;
JavaScript
0
@@ -433,17 +433,274 @@ unique'%5D +,%0A // list of property types validators%0A validators: %7B%0A 'string': 'string',%0A 'number': 'number',%0A 'object': 'object', %0A 'date': 'date', %0A 'boolean': 'boolean', %0A 'array': 'array'%0A %7D, %0A - @@ -930,17 +930,17 @@ -field: +property: r @@ -968,13 +968,16 @@ src/ -field +property ')%0A @@ -1277,16 +1277,16 @@ = '/' ?%0A - @@ -1363,24 +1363,365 @@ ;%0A %7D%0A %7D%0A + // register validators%0A for(var i in this.options.validators) %7B%0A var validator = this.options.validators%5Bi%5D;%0A if (validator instanceof String) %7B%0A this.options.validators%5Bi%5D = require(%0A validator%5B0%5D == '.' %7C%7C validator%5B0%5D == '/' ?%0A validator : __dirname + '/src/validators/' + validator%0A )(this);%0A %7D%0A %7D%0A // registe
fe668776bc02097b5b54ef8b9267bb62c1e562bb
Fix tool startup activation (#84)
src/main/javascript/Client.js
src/main/javascript/Client.js
/** * Main map client class * * Typical use case is to call the method configure(config) where config is a valid configuration object (usually parsed from JSON). */ Ext.define('OpenEMap.Client', { requires: ['GeoExt.data.MapfishPrintProvider', 'OpenEMap.Gui', 'OpenEMap.config.Parser', 'OpenEMap.form.ZoomSelector', 'OpenEMap.OpenLayers.Control.ModifyFeature', 'OpenEMap.OpenLayers.Control.DynamicMeasure'], version: '1.0.4', /** * OpenLayers Map instance * * @property {OpenLayers.Map} */ map: null, /** * Overlay used by drawing actions * * StyleMap can be overridden if more specific styling logic is required. * * Here is an example that changes style on scale: * * var style = new OpenLayers.Style(); * * var ruleLow = new OpenLayers.Rule({ * symbolizer: { * pointRadius: 10, * fillColor: 'green', * fillOpacity: 1 * }, * maxScaleDenominator: 10000 * }); * * var ruleHigh = new OpenLayers.Rule({ * symbolizer: { * pointRadius: 10, * fillColor: 'red', * fillOpacity: 1 * }, * minScaleDenominator: 10000 * }); * * style.addRules([ruleLow, ruleHigh]); * * var styleMap = new OpenLayers.StyleMap(style); * mapClient.drawLayer.styleMap = styleMap; * * Here is an example style to display labels for features with attribute property "type" == "label": * * var labels = new OpenLayers.Rule({ * filter: new OpenLayers.Filter.Comparison({ * type: OpenLayers.Filter.Comparison.EQUAL_TO, * property: "type", * value: "label", * }), * symbolizer: { * label: "${label}" * } * }); * * See [OpenLayers documentation][1] on feature styling for more examples. * * [1]: http://docs.openlayers.org/library/feature_styling.html * * @property {OpenLayers.Layer.Vector} */ drawLayer: null, /** * Clean up rendered elements */ destroy: function() { if (this.map) { this.map.controls.forEach(function(control) { control.destroy(); }); this.map.controls = null; } if (this.gui) this.gui.destroy(); }, /** * Configure map * * If this method is to be used multiple times, make sure to call destroy before calling it. * * @param {Object} config Map configuration object * @param {Object} options Additional MapClient options * @param {Object} options.gui Options to control GUI elements. Each property in this object is * essentially a config object used to initialize an Ext JS component. If a property is undefined or false * that component will not be initialized except for the map component. If a property is a defined * but empty object the component will be rendered floating over the map. To place a component into a * predefined html tag, use the config property renderTo. * @param {Object} options.gui.map If undefined or false MapClient will create the map in a full page viewport * @param {Object} options.gui.layers Map layers tree list * @param {Object} options.gui.baseLayers Base layer switcher intended to be used as a floating control * @param {Object} options.gui.searchCoordinate Simple coordinate search and pan control * @param {Object} options.gui.objectConfig A generic form to configure feature attributes similar to a PropertyList * @param {Object} options.gui.zoomTools Zoom slider and buttons intended to be used as a floating control * @param {Object} options.gui.searchFastighet Search "fastighet" control * * For more information about the possible config properties for Ext JS components see Ext.container.Container. */ configure: function(config, options) { options = Ext.apply({}, options); this.initialConfig = Ext.clone(config); Ext.tip.QuickTipManager.init(); var parser = Ext.create('OpenEMap.config.Parser'); this.map = parser.parse(config); this.gui = Ext.create('OpenEMap.Gui', { config: config, gui: options.gui, map: this.map, orginalConfig: this.initialConfig }); this.mapPanel = this.gui.mapPanel; this.drawLayer = this.gui.mapPanel.drawLayer; }, /** * @param {String=} Name of layout to use (default is to use first layout as reported by server) * @return {String} JSON encoding of current map for MapFish Print module */ encode: function(layout) { return JSON.stringify(this.mapPanel.encode(layout)); }, /** * Helper method to add GeoJSON directly to the draw layer * * @param {string} geojson */ addGeoJSON: function(geojson) { var format = new OpenLayers.Format.GeoJSON(); var feature = format.read(geojson, "Feature"); this.drawLayer.addFeatures([feature]); }, /** * Allows you to override the sketch style at runtime * * @param {OpenLayers.StyleMap} styleMap */ setSketchStyleMap: function(styleMap) { this.map.controls.forEach(function(control) { if (control instanceof OpenLayers.Control.DrawFeature) { control.handler.layerOptions.styleMap = styleMap; if (control.handler.layer) { control.handler.layer.styleMap = styleMap; } } }); }, /** * Enable additional labels for polygon edges * NOTE: deactivation not yet implemented * @param style hash of style properties that will override a default label style */ toggleEdgeLabels: function(style) { var styleOverride = style || {}; var drawLabels = function() { var createEdgeLabels = function(feature) { var geometry = feature.geometry; if (geometry.CLASS_NAME != "OpenLayers.Geometry.Polygon") return []; var linearRing = geometry.components[0]; var edgeLabels = linearRing.components.slice(0, linearRing.components.length-1).map(function(point, i) { var start = linearRing.components[i].clone(); var end = linearRing.components[i+1].clone(); var lineString = new OpenLayers.Geometry.LineString([start, end]); var centroid = lineString.getCentroid({weighted: true}); var style = Ext.applyIf(Ext.clone(styleOverride), { label: lineString.getLength().toFixed(2).toString() + " m", strokeColor: "#000000", strokeWidth: 3, labelAlign: 'cm' }); var feature = new OpenLayers.Feature.Vector(centroid, null, style); return feature; }); return edgeLabels; } this.labelLayer.destroyFeatures(); var edgeLabelsArrays = this.drawLayer.features.map(createEdgeLabels); if (edgeLabelsArrays.length > 0) { var edgeLabels = edgeLabelsArrays.reduce(function(a, b) { return a.concat(b); }); this.labelLayer.addFeatures(edgeLabels); } }; if (this.labelLayer == null) { this.labelLayer = new OpenLayers.Layer.Vector(); this.map.addLayer(this.labelLayer); this.drawLayer.events.on({ "featuremodified": drawLabels, "vertexmodified": drawLabels, "featuresadded": drawLabels, "featuresremoved": drawLabels, scope: this }); } else { // TODO: disable edge labels } drawLabels.apply(this); } });
JavaScript
0
@@ -4677,16 +4677,128 @@ wLayer;%0A + %0A if (this.gui.controlToActivate) %7B%0A this.gui.controlToActivate.activate();%0A %7D%0A %7D,%0A
588bdfe2e3a908b10d09995ebef0508e9518d88a
Simplify logic
main.js
main.js
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 2, maxerr: 50 */ /*global define, brackets, CodeMirror */ define(function (require, exports, module) { 'use strict'; var LanguageManager = brackets.getModule("language/LanguageManager"); var regex = { keywords: /^(Feature| {2}(Scenario|In order to|As|I)| {4}(Given|When|Then|And))/ }; CodeMirror.defineMode("gherkin", function () { return { startState: function () { return { allowFeature: true, allowScenario: false, allowSteps: false }; }, token: function (stream, state) { if (stream.sol()) { stream.eatSpace(); // LINE COMMENT if (stream.match(/^#.*/)) { return "comment"; // FEATURE } else if (state.allowFeature && stream.match(/^Feature:/)) { state.allowScenario = true; state.allowSteps = false; return "keyword"; // SCENARIO } else if (state.allowScenario && stream.match(/^Scenario:/)) { state.allowSteps = true; return "keyword"; // STEPS } else if (state.allowSteps && stream.match(/^(Given|When|Then|And|But)/)) { return "keyword"; // Fall through } else { stream.skipToEnd(); } } else { // Fall through stream.skipToEnd(); } return null; } }; }); LanguageManager.defineLanguage("gherkin", { name: "Gherkin", mode: "gherkin", fileExtensions: ["feature"] }); });
JavaScript
0.033914
@@ -663,38 +663,8 @@ ) %7B%0A - if (stream.sol()) %7B%0A @@ -687,18 +687,16 @@ ace();%0A%0A - @@ -711,18 +711,16 @@ COMMENT%0A - @@ -749,34 +749,32 @@ /)) %7B%0A - return %22comment%22 @@ -772,26 +772,24 @@ %22comment%22;%0A%0A - // F @@ -795,34 +795,32 @@ FEATURE%0A - %7D else if (state @@ -867,34 +867,32 @@ /)) %7B%0A - state.allowScena @@ -905,34 +905,32 @@ true;%0A - - state.allowSteps @@ -941,34 +941,32 @@ alse;%0A - return %22keyword%22 @@ -960,34 +960,32 @@ urn %22keyword%22;%0A%0A - // SCENA @@ -988,34 +988,32 @@ CENARIO%0A - %7D else if (state @@ -1062,34 +1062,32 @@ /)) %7B%0A - state.allowSteps @@ -1097,34 +1097,32 @@ true;%0A - - return %22keyword%22 @@ -1128,26 +1128,24 @@ %22;%0A%0A - // STEPS%0A @@ -1145,26 +1145,24 @@ EPS%0A - - %7D else if (s @@ -1228,34 +1228,32 @@ /)) %7B%0A - return %22keyword%22 @@ -1255,34 +1255,32 @@ word%22;%0A%0A - // Fall through%0A @@ -1283,26 +1283,24 @@ ugh%0A - - %7D else %7B%0A @@ -1300,95 +1300,8 @@ e %7B%0A - stream.skipToEnd();%0A %7D%0A %7D else %7B%0A // Fall through%0A
d58017c57e892aa52adffa0ed472d0a3151aab70
Call notSoSimpleDemo from main
main.js
main.js
var SignalPath = require("./SignalPath"); var Transceiver = require("./Transceiver"); var Hub = require("./Hub"); var Switch = require("./Switch"); var Host = require("./Host"); var Frame = require("./Frame"); function simpleDemo() { var pc1 = new Host("PC1", "FC:AA:AA:00:00:00"); var pc2 = new Host("PC2", "FC:AA:AA:00:00:01"); var cable1 = new SignalPath(); pc1.port.attach(cable1); pc2.port.attach(cable1); pc1.transmitLayer2(pc2.macAddress, "Hi PC2, I'm PC1"); pc2.transmitLayer2("FC:AA:AA:12:34:56", "Hi PC1, I'm PC2"); } function notSoSimpleDemo() { var pc1 = new Host("PC1", "FC:AA:AA:00:00:00"); var pc2 = new Host("PC2", "FC:AA:AA:00:00:01"); var pc3 = new Host("PC3", "FC:AA:AA:00:00:02"); var hub1 = new Hub("Hub1", 4); var switch1 = new Switch("Switch1", 4); var cable1 = new SignalPath(); var cable2 = new SignalPath(); var cable3 = new SignalPath(); var cable4 = new SignalPath(); pc1.port.attach(cable1); hub1.ports[0].attach(cable1); pc2.port.attach(cable2); switch1.ports[0].attach(cable2); hub1.ports[3].attach(cable3); switch1.ports[3].attach(cable3); pc3.port.attach(cable4); switch1.ports[1].attach(cable4); pc1.transmitLayer2(pc2.macAddress, "hi world"); pc3.transmitLayer2(pc1.macAddress, "hi universe"); pc1.transmitLayer2(pc3.macAddress, "hi multiverse"); } simpleDemo();
JavaScript
0
@@ -1432,17 +1432,22 @@ ); %0A%7D%0A%0A -s +notSoS impleDem
a820c4b96220e39d82f724bc6262673d5cd206c5
Resolve relative paths and log creating of dirs
main.js
main.js
var nconf = require('nconf') fs = require('fs') async = require('async') log4js = require('log4js') path = require('path') var mainLogger = log4js.getLogger("main"); var tasks = {} async.series( [ loadConfig, loadTasks, executeTasks ] ); function loadConfig(cb) { mainLogger.info("Loading config.."); nconf.file({ file: 'config.json' }); cb(); } function loadTasks(cb) { mainLogger.info("Loading tasks.."); var loaderLogger = log4js.getLogger("taskLoader"); var sharedConfig = nconf.get("shared"); fs.readdir('./tasks', function (err, files) { if(err) { loaderLogger.error("Could not load tasks: " + err); return cb(err); } loaderLogger.info("Found %s tasks!", files.length); async.each(files, function (file, cb) { var task = require('./tasks/' + file); var taskname = task.name; var taskconfig = getTaskConfig(taskname); if(nconf.get("backup:tasks").indexOf(taskname) == -1) { loaderLogger.warn("Ignoring task '%s'", taskname); return cb(); } async.reject(task.requiredConfig, function (key, cb) { var taskVal = nconf.get("tasks:" + taskname + ":" + key); var sharedVal = nconf.get("shared:" + key); var isValid = isValidConfig(taskVal) || isValidConfig(sharedVal); cb(isValid); }, function (results) { var validConfig = results.length == 0; if(validConfig) { tasks[taskname] = task; loaderLogger.info("Task '%s' successfully loaded", taskname); } else { loaderLogger.error( "The following config-entries for task '%s' were not found: %s", taskname, results.join(', ') ); } cb(validConfig ? null : "missing-config"); } ); }, cb); } ); } function isValidConfig(val) { return (val && val.length != 0); } function executeTasks(cb) { mainLogger.info("Executing %s tasks..", Object.keys(tasks).length); var executeLogger = log4js.getLogger("taskExecutor"); var mainDestination = path.join(nconf.get("backup:destination"), "backup-" + Date.now()); createDirIfNotExists(mainDestination); async.eachSeries(Object.keys(tasks), function (taskname, cb) { var task = tasks[taskname]; var config = getTaskConfig(taskname); var destination = path.join(mainDestination, taskname); var taskLogger = log4js.getLogger(taskname); createDirIfNotExists(destination); executeLogger.info("Executing Task '%s'..", taskname); task.execute(config, destination, taskLogger, function (err) { if(!err) executeLogger.info("Task '%s' was executed successfully!", taskname); else executeLogger.error("Task '%s' failed to execute: %s", taskname, err); cb(); }); }, function () { executeLogger.info("All tasks executed."); cb(); } ) } function getTaskConfig(taskname) { var config = nconf.get("tasks:" + taskname); var sharedConfig = nconf.get("shared"); for (var attr in sharedConfig) config[attr] = sharedConfig[attr]; return config; } function createDirIfNotExists(dir) { if (!fs.existsSync(dir)) fs.mkdir(dir); }
JavaScript
0
@@ -2395,20 +2395,23 @@ = path. -join +resolve (nconf.g @@ -3540,16 +3540,58 @@ (dir)%0A%7B%0A + mainLogger.debug(%22Creating dir:%22, dir);%0A if (!f
c4bb689abb1f9410e33fa060608edddcb64a4750
add "module exports" header comment
lib/node-gyp.js
lib/node-gyp.js
module.exports = exports = gyp /** * Module dependencies. */ var fs = require('graceful-fs') , path = require('path') , nopt = require('nopt') , log = require('npmlog') , child_process = require('child_process') , EE = require('events').EventEmitter , inherits = require('util').inherits , commands = [ // Module build commands 'build' , 'clean' , 'configure' , 'rebuild' // Development Header File management commands , 'install' , 'list' , 'remove' ] , aliases = { 'ls': 'list' , 'rm': 'remove' } // differentiate node-gyp's logs from npm's log.heading = 'gyp' /** * The `gyp` function. */ function gyp () { return new Gyp } function Gyp () { var self = this // set the dir where node-gyp dev files get installed // TODO: make this *more* configurable? // see: https://github.com/TooTallNate/node-gyp/issues/21 var homeDir = process.env.HOME || process.env.USERPROFILE if (!homeDir) { throw new Error( "node-gyp requires that the user's home directory is specified " + "in either of the environmental variables HOME or USERPROFILE" ); } this.devDir = path.resolve(homeDir, '.node-gyp') this.commands = {} commands.forEach(function (command) { self.commands[command] = function (argv, callback) { log.verbose('command', command, argv) return require('./' + command)(self, argv, callback) } }) } inherits(Gyp, EE) exports.Gyp = Gyp var proto = Gyp.prototype /** * Export the contents of the package.json. */ proto.package = require('../package') /** * nopt configuration definitions */ proto.configDefs = { help: Boolean // everywhere , arch: String // 'configure' , debug: Boolean // 'build' , directory: String // bin , make: String // 'build' , msvs_version: String // 'configure' , ensure: Boolean // 'install' , solution: String // 'build' (windows only) , proxy: String // 'install' , nodedir: String // 'configure' , loglevel: String // everywhere , python: String // 'configure' , 'dist-url': String // 'install' , jobs: String // 'build' , thin: String // 'configure' } /** * nopt shorthands */ proto.shorthands = { release: '--no-debug' , C: '--directory' , debug: '--debug' , j: '--jobs' , silly: '--loglevel=silly' , verbose: '--loglevel=verbose' } /** * expose the command aliases for the bin file to use. */ proto.aliases = aliases /** * Parses the given argv array and sets the 'opts', * 'argv' and 'command' properties. */ proto.parseArgv = function parseOpts (argv) { this.opts = nopt(this.configDefs, this.shorthands, argv) this.argv = this.opts.argv.remain.slice() var commands = this.todo = [] // create a copy of the argv array with aliases mapped var argv = this.argv.map(function (arg) { // is this an alias? if (arg in this.aliases) { arg = this.aliases[arg] } return arg }, this) // process the mapped args into "command" objects ("name" and "args" props) argv.slice().forEach(function (arg) { if (arg in this.commands) { var args = argv.splice(0, argv.indexOf(arg)) argv.shift() if (commands.length > 0) { commands[commands.length - 1].args = args } commands.push({ name: arg, args: [] }) } }, this) if (commands.length > 0) { commands[commands.length - 1].args = argv.splice(0) } // support for inheriting config env variables from npm var npm_config_prefix = 'npm_config_' Object.keys(process.env).forEach(function (name) { if (name.indexOf(npm_config_prefix) !== 0) return var val = process.env[name] if (name === npm_config_prefix + 'loglevel') { log.level = val } else { // add the user-defined options to the config name = name.substring(npm_config_prefix.length) this.opts[name] = val } }, this) if (this.opts.loglevel) { log.level = this.opts.loglevel } log.resume() } /** * Spawns a child process and emits a 'spawn' event. */ proto.spawn = function spawn (command, args, opts) { opts || (opts = {}) if (!opts.silent && !opts.customFds) { opts.customFds = [ 0, 1, 2 ] } var cp = child_process.spawn(command, args, opts) log.info('spawn', command) log.info('spawn args', args) return cp } /** * Returns the usage instructions for node-gyp. */ proto.usage = function usage () { var usage = [ '' , ' Usage: node-gyp <command> [options]' , '' , ' where <command> is one of:' , commands.map(function (c) { return ' - ' + c + ' - ' + require('./' + c).usage }).join('\n') , '' , ' for specific command usage and options try:' , ' $ node-gyp <command> --help' , '' , 'node-gyp@' + this.version + ' ' + path.resolve(__dirname, '..') , 'node@' + process.versions.node ].join('\n') return usage } /** * Version number getter. */ Object.defineProperty(proto, 'version', { get: function () { return this.package.version } , enumerable: true })
JavaScript
0.000001
@@ -1,8 +1,37 @@ +%0A/**%0A * Module exports.%0A */%0A%0A module.e
c6848d158090a7b5d3ba78fa024c8456c6933c4c
Allow for the parse module to send badges
lib/notifier.js
lib/notifier.js
/*! * node-notifier * Copyright(c) 2014 Madhusudhan Srinivasa <[email protected]> * MIT Licensed */ /** * Module dependencies. */ var fs = require('fs') , path = require('path') , parallel = require('lll'); /** * Initialize notifier * * @api public */ var Notifier = function (config) { if (config) { this.config = config; if (!this.config.service || (this.config.service != 'sendgrid' && this.config.service != 'postmark')) { throw new Error('Please specify which service you want to use - sendgrid or postmark'); } this.config.service = this.config.service.toLowerCase(); // Default template type // Helps when using ejs or any other templates if (!this.config.tplType) this.config.tplType = 'jade'; if (config.email && !config.tplPath && !fs.exists(config.tplPath)) { throw new Error('Please provide correct path to the templates.'); } } } /** * Expose */ module.exports = Notifier; /** * Notifier config * * @param {Object} config * @return {Notifier} * @api public */ Notifier.prototype.use = function (config) { var self = this; if (!config) return Object.keys(config).forEach(function (key) { self.config[key] = config[key]; }); return this; }; /** * Send the specified notification * * @param {String} action * @param {Object} notification * @param {Function} cb * @return {Notifier} * @api public */ Notifier.prototype.send = function (action, notification, cb) { var config = this.config; var self = this; var args = []; if (this.config.actions.indexOf(action) === -1) { throw new Error('The action \'' + action + '\' is not specified in notifier config'); } // check if the object specified has all the required fields if (config.email) { var template = config.tplPath + '/' + action + '.' + config.tplType; var exists = fs.existsSync(template); if (!exists) { throw new Error('Please specify a path to the template'); } } if (typeof cb !== 'function') cb = function () {}; // send apn if (config.APN) { args.push(function (fn) { self.APN(notification, fn); }); } // send mails if (config.email) { args.push(function (fn) { self.mail(notification, template, fn); }); } // Execute the callback only once // Make sure the mail and APN are sent in parallel parallel(args, cb); return this; }; /** * Process the template * * Note that this method can be overridden so that you can use your preffered * templating language. Default is jade * * @param {String} tplPath * @param {Object} locals * @return {String} * @api public */ Notifier.prototype.processTemplate = function (tplPath, locals) { var Jade = require('jade'); var tpl = require('fs').readFileSync(tplPath, 'utf8'); var html = Jade.compile(tpl, { filename: tplPath }); return html(locals); }; /** * Send email via postmark * * @param {Object} obj * @api public */ Notifier.prototype.mail = function (obj, template, cb) { var options var html = this.processTemplate(template, obj.locals) if (!this.config.key) { throw new Error('Please provide the service key'); } if(!/\@/.test(obj.to) || !/\@/.test(obj.from)) { throw new Error('Please specify proper to and from address'); } if (this.config.service === 'postmark') { var postmark = require('postmark')(this.config.key) options = { 'From': obj.from, 'To': obj.to, 'Subject': obj.subject, 'HtmlBody': html }; } else if (this.config.service === 'sendgrid') { var SendGrid = require('sendgrid').SendGrid; var sendgrid = new SendGrid(this.config.sendgridUser, this.config.key); options = { 'to': obj.to, 'from': obj.from, 'subject': obj.subject, 'html': html }; } // as you don't want to send emails while development or testing if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') { // don't log during tests if (process.env.NODE_ENV !== 'test') { console.log(options); } cb(); return options; } else { if (this.config.service === 'sendgrid') sendgrid.send(options, cb) else postmark.send(options, cb) } }; /** * Send Apple Push Notification * * @param {Object} obj * @api public */ Notifier.prototype.APN = function (obj, cb) { if (!this.config.parseAppId || !this.config.parseApiKey) { throw new Error('Please specify parse app id and app key'); } var channels = obj.parseChannels || this.config.parseChannels; if (!channels) { throw new Error('Please specify the parse channels.'); } if (!Array.isArray(channels)) { throw new Error('Channels should be an array'); } var Parse = require('node-parse-api').Parse; var app = new Parse(this.config.parseAppId, this.config.parseApiKey); var notification = { channels: channels, data: { alert: obj.alert || obj.subject, route: obj.route } }; app.sendPush(notification, cb); };
JavaScript
0
@@ -4997,16 +4997,92 @@ %7D%0A %7D;%0A + if (obj.badge !== undefined) %7B%0A notification.data.badge = obj.badge%0A %7D %0A app.s
45ab24d56fb0983d30c7d54c030ffeaab565276e
Enable reload of the mainWindow in the menu (also cmd+r or ctrl+r)
main.js
main.js
// Module to create native browser window, // Module to control application life, // Module to create native application menus and context menus. const {BrowserWindow, app, Menu} = require('electron') const path = require('path') const url = require('url') const DEBUG = false; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow function createMenu(){ var template = null; if (process.platform === 'darwin') { template = [{ label: "Application", submenu: [ { label: "Quit", accelerator: "Command+Q", click: function() { app.quit(); }} ]}, { label: "Edit", submenu: [ { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" }, ]} ]; } if(template != null)Menu.setApplicationMenu(Menu.buildFromTemplate(template)); else console.log('Menu is null, platform not supported'); }; function createWindow () { // Create the browser window. mainWindow = new BrowserWindow({width: 390, height: 530, titleBarStyle: 'hidden', resizable:false}) // and load the index.html of the app. mainWindow.loadURL(url.format({ pathname: path.join(__dirname, '/app/view/index.html'), protocol: 'file:', slashes: true })) // Open the DevTools. if(DEBUG) mainWindow.webContents.openDevTools() // Create the Application's main menu createMenu(); // Emitted when the window is closed. mainWindow.on('closed', function () { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null }) } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow) // Quit when all windows are closed. app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', function () { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow() } }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here.
JavaScript
0
@@ -805,16 +805,18 @@ %22Copy%22, + acceler @@ -857,16 +857,123 @@ py:%22 %7D,%0A + %7B label: %22Reload%22, accelerator: %22CmdOrCtrl+R%22, click: function() %7BmainWindow.reload();%7D %7D,%0A
539464a468461a63b386d6ec1d827339025eedff
Handle the directory paths in a FIFO manner
lib/parallel.js
lib/parallel.js
/** * The MIT License (MIT) * Copyright (c) 2016 GochoMugo <[email protected]> * Copyright (c) 2016 Forfuture, LLC < [email protected]> * * Handle parallel handling of directories. */ exports.Handler = class Handler { /** * Construct a new handler. * * @param {Object} globals * @param {Function} exec(dirpath, next) - executed for each directory * @param {Function} empty() - executed whenever the queue is empty. * * NOTE: the `empty()` function is executed each single time, when * parallelism is NOT limited. This is because the directories are NOT * queued up. */ constructor(globals, exec, empty) { this._globals = globals; this._hooks = { exec: exec, empty: empty, }; this._queue = []; this._pending = 0; } // Add a directory to the queue enqueue(dir) { // Avoid any overhead, should we be allowed to do max // parallelism possible if (this._globals.options.parallel <= 0) { this._run(dir); return this; } this._queue.push(dir); this._next(); return this; } // Handle the next directory, if possible _next() { if (this._queue.length === 0) { this._hooks.empty(); return this; } if (this._pending >= this._globals.options.parallel) return this; this._run(); return this; } // Execute the associated function, for the next directory _run(dirpath) { var self = this; dirpath = dirpath || this._queue.pop(); this._pending++; this._hooks.exec(dirpath, function() { self._pending--; self._next(); }); return this; } }
JavaScript
0
@@ -183,16 +183,835 @@ tories.%0A + *%0A * Notes:%0A * ------%0A *%0A * The order of the paths in executing the attached function on the handler%0A * is important as we need parent directories to be created before%0A * child directories are considered. The used walker enqueues directories%0A * as it finds them, directories are added to the queue as the walker%0A * goes deeper in the directory structure. Therefore, this queue should%0A * be considered a FIFO structure.%0A *%0A * Implementing parallelism will require handling the paths in a tree%0A * fashion, with a breadth-first manner i.e. the parent directories%0A * are created first.%0A * Also, we may need to use separate FTP connections to handle multiple%0A * directories simultaneously. See https://github.com/forfuturellc/ftpush/issues/1%0A * and https://github.com/sergi/jsftp/issues/66 for more information%0A * on this.%0A */%0A%0A%0Aex @@ -2453,11 +2453,13 @@ eue. -pop +shift ();%0A
98a52690159ee1529f5d9054eb415c74e0fe64b3
allow 0 as a valid protocol value
lib/pcsclite.js
lib/pcsclite.js
var events = require('events'); var bt = require('buffertools'); /* Make sure we choose the correct build directory */ var bindings = require('bindings')('pcsclite'); var PCSCLite = bindings.PCSCLite; var CardReader = bindings.CardReader; inherits(PCSCLite, events.EventEmitter); inherits(CardReader, events.EventEmitter); var parse_readers_string = function(readers_str) { var pos; var readers = []; var ini = 0; while ((pos = bt.indexOf(readers_str.slice(ini), '\0')) > 0) { readers.push(readers_str.slice(ini, ini + pos).toString()); ini += pos + 1; } return readers; }; /* * It returns an array with the elements contained in a that aren't contained in b */ function diff(a, b) { return a.filter(function(i) { return b.indexOf(i) === -1; }); }; module.exports = function() { var readers = {}; var p = new PCSCLite(); process.nextTick(function() { p.start(function(err, data) { if (err) { return p.emit('error', err); } var names = parse_readers_string(data); var current_names = Object.keys(readers); var new_names = diff(names, current_names); var removed_names = diff(current_names, names); new_names.forEach(function(name) { var r = new CardReader(name); r.on('_end', function() { r.removeAllListeners('status'); r.emit('end'); delete readers[name]; }); readers[name] = r; r.get_status(function(err, state, atr) { if (err) { return r.emit('error', err); } var status = { state : state }; if (atr) { status.atr = atr; } r.emit('status', status); r.state = state; }); p.emit('reader', r); }); removed_names.forEach(function(name) { readers[name].close(); }); }); }); return p; }; CardReader.prototype.connect = function(options, cb) { if (typeof options === 'function') { cb = options; options = undefined; } options = options || {}; options.share_mode = options.share_mode || this.SCARD_SHARE_EXCLUSIVE; options.protocol = options.protocol || this.SCARD_PROTOCOL_T0 | this.SCARD_PROTOCOL_T1; if (!this.connected) { this._connect(options.share_mode, options.protocol, cb); } else { cb(); } }; CardReader.prototype.disconnect = function(disposition, cb) { if (typeof disposition === 'function') { cb = disposition; disposition = undefined; } if (typeof disposition !== 'number') { disposition = this.SCARD_UNPOWER_CARD; } if (this.connected) { this._disconnect(disposition, cb); } else { cb(); } }; CardReader.prototype.transmit = function(data, res_len, protocol, cb) { if (!this.connected) { return cb(new Error("Card Reader not connected")); } this._transmit(data, res_len, protocol, cb); }; CardReader.prototype.control = function(data, control_code, res_len, cb) { if (!this.connected) { return cb(new Error("Card Reader not connected")); } var output = new Buffer(res_len); this._control(data, control_code, output, function(err, len) { if (err) { return cb(err); } cb(err, output.slice(0, len)); }); }; // extend prototype function inherits(target, source) { for (var k in source.prototype) { target.prototype[k] = source.prototype[k]; } }
JavaScript
0.00001
@@ -2458,20 +2458,32 @@ LUSIVE;%0A +%0A +if (typeof options. @@ -2492,16 +2492,33 @@ otocol = +== 'undefined' %7C%7C options @@ -2527,18 +2527,54 @@ rotocol -%7C%7C +=== null) %7B%0A options.protocol = this.SC @@ -2614,16 +2614,22 @@ OCOL_T1; +%0A %7D %0A%0A if
e2a8cf10936703d17702b3bf962161c2b97571b6
fix in meteor collision
main.js
main.js
(function () { "use strict"; var CommandEnum = com.dgsprb.quick.CommandEnum; var Quick = com.dgsprb.quick.Quick; var GameObject = com.dgsprb.quick.GameObject; var Scene = com.dgsprb.quick.Scene; var gameScene; var buildings = []; // use tiles intead? function fireMissile(targetX, targetY) { var target = new GameObject(); target.setPosition(targetX, targetY); target.setColor("White"); target.setSize(3); target.setExpiration(60); gameScene.add(target); var missile = new GameObject(); missile.setPosition(Quick.getCanvasCenterX(), Quick.getCanvasHeight()-20); missile.setColor("Red"); missile.targetX = targetX; missile.targetY = targetY; missile.setSolid(); missile.setSize(4); missile.setExpiration(60); missile.setSpeedToPoint(10, target); missile.setDelegate({ "update": function() { if (missile.getY()<=missile.targetY) { missile.expire(); target.expire(); createExplosion(missile.targetX, missile.targetY); } }, "onCollision": function(gameObject) { if (gameObject.hasTag("meteor")) { gameObject.expire(); missile.expire(); createExplosion(missile.getX(), missile.getY()); } } }); gameScene.add(missile); } function createExplosion(x, y) { var explosion = new GameObject(); explosion.setColor("Red"); explosion.setSolid(); explosion.setPosition(x, y); explosion.setExpiration(70); explosion.setDelegate({ "update": function() { var center = explosion.getCenter(); explosion.increase(1, 1); explosion.setCenter(center.getX(), center.getY()); } }); gameScene.add(explosion); } function createMeteor() { var meteor = new GameObject(); meteor.setSize(6); meteor.setColor("Yellow"); meteor.setSolid(); meteor.addTag("meteor"); meteor.setX(Quick.random(Quick.getCanvasWidth())+1); var target = buildings[Quick.random(buildings.length-1)].getCenter(); meteor.setSpeedToPoint(Quick.random(2)+1, target); meteor.setExpiration(1000); meteor.setDelegate({ "onCollision": function(gameObject) { if (gameObject.hasTag("building")) { gameObject.expire(); meteor.expire(); createExplosion(gameObject.getX(), gameObject.getY()); } else if (gameObject.hasTag("meteor")) { meteor.bounceX(); } }, "update": function() { if (Quick.random(6)==0) { var trail = new GameObject(); trail.setSize(4); trail.setColor("Gray"); trail.setPosition(meteor.getX(), meteor.getY()); trail.setExpiration(40); meteor.setLayerIndex(0); gameScene.add(trail); } if (meteor.getY() > Quick.getCanvasHeight()) meteor.expire(); }, "offBoundary": function() { meteor.expire(); } }); gameScene.add(meteor); } function main() { Quick.setName("Missile Commander"); gameScene = new Scene(); Quick.init(function () { return gameScene }); var background = new GameObject(); background.setColor("Black"); background.setHeight(Quick.getCanvasHeight()); background.setWidth(Quick.getCanvasWidth()); gameScene.add(background); for (var i=0; i<7; i++) { var building = new GameObject(); building.setSize(20); building.setColor(i==3 ? "Orange" : "Green"); building.setSolid(); building.addTag("building"); building.setPosition((Quick.getCanvasWidth()/8)*(i+1), Quick.getCanvasHeight()-20); gameScene.add(building); buildings.push(building); } var pointer = Quick.getPointer() var cursor = new GameObject(); cursor.setColor("Orange"); cursor.setSize(5); cursor.setCenter(cursor.getCenter()); cursor.setDelegate({ "update" : function() { var position = pointer.getPosition(); cursor.setPosition(position.getX(), position.getY()); if (pointer.getPush()) //createExplosion(position.getX(), position.getY()); fireMissile(position.getX(), position.getY()); if (Quick.random(30)==0) createMeteor() } }); gameScene.add(cursor); } main(); })();
JavaScript
0.002834
@@ -1333,24 +1333,57 @@ setSolid();%0A +%09%09explosion.addTag(%22explosion%22);%0A %09%09explosion. @@ -2229,24 +2229,95 @@ ct.getY());%0A +%09%09%09%09%7D else if (gameObject.hasTag(%22explosion%22)) %7B%0A%09%09%09%09%09meteor.expire();%0A %09%09%09%09%7D else i
ebfeed2721b85dfd61e3353801b298c8cc356a85
add transactionID
lib/protocol.js
lib/protocol.js
var command_state = require('./command-state.js'), nconf = require('nconf'); nconf.env() .file({"file": "./lib/epp-config.json"}); var state; module.exports = function() { return { "processMessage": function processMessage(m) { if (state) { if (m.command) { //state.clientResponse = m.callback; var command = m.command; var data = m.data; var transactionId = m.transactionId; state.command(command, data, transactionId, function(responseData) { // send response back to parent process //console.log("Would send back with response: ", responseData); process.send(responseData); }); } } else { // Initialise a connection instance with registry configuration. var registry = m.registry; var registryConfig = nconf.get(registry); state = command_state(registry, registryConfig); // Initialise the connection stream. Upon connection, attempt // to login. state.connection.initStream(function() { console.log("Got connection"); setTimeout(function() { state.command('login', { "login": registryConfig.login, "password": registryConfig.password }, function(data) { console.log("Log in callback received: ", data); }); }, 2000); }); } } }; };
JavaScript
0.000002
@@ -1558,16 +1558,32 @@ %7D, + 'iwmn-login-1', %0A
94d7e9262e4e9ca0f64c91750dae1c531ef62646
Add uglify
main.js
main.js
#!/usr/bin/env node var fs = require("fs"); var path = require("path"); var webpack = require("webpack"); var version = JSON.parse(fs.readFileSync("./package.json")).version; console.log("react-beaker " + version + "\n"); var command = process.argv[2]; var context = process.argv[3] && path.resolve(process.argv[3]); if (!command || !context || ["watch", "build", "publish"].indexOf(command) < 0) { help(); process.exit(1); } var entriesDir = context + "/js/entries/"; var entry = {}; fs.readdirSync(entriesDir).map(function(filename) { entry[filename.replace(/\.[^\.]+$/, "")] = entriesDir + filename; }); var compiler = webpack({ context: context, resolve: { extensions: ["", ".js", ".jsx"], alias: { "react": process.cwd() + "/alias/react.js", "react-dom": process.cwd() + "/alias/react-dom.js", "react-router": process.cwd() + "/alias/react-router.js", "redux": process.cwd() + "/alias/redux.js" } }, entry: entry, output: { path: context + "/dist", filename: "[name].js" }, module: { loaders: [{ test: /\.jsx$/, exclude: /node_modules/, loader: "babel", query: { presets: ["react", "es2015"] } }] } }); function buildReactCore() { webpack({ context: process.cwd(), entry: "./react-core.js", output: { path: context + "/dist", filename: "react-core.js" } }).run(function(){}); } function watch() { buildReactCore(); compiler.watch({poll: true}, function(err, stats) { console.log(stats.toString({colors: true})); }); } function build() { buildReactCore(); compiler.run(function(err, stats) { console.log(stats.toString({colors: true})); }); } function publish() { buildReactCore(); compiler.run(function(err, stats) { console.log(stats.toString({colors: true})); }); } function help() { console.error("Usage:"); console.error(" react-beaker watch <source dir>"); console.error(" react-beaker build <source dir>"); console.error(" react-beaker publish <source dir>"); } if (command === "watch") watch(); if (command === "build") build(); if (command === "publish") publish();
JavaScript
0.000007
@@ -1299,17 +1299,130 @@ %7D%5D%0A %7D +,%0A plugins: command === %22publish%22 ? %5B%0A new webpack.optimize.UglifyJsPlugin(%7Bminimize: true%7D)%0A %5D : %5B%5D %0A - %7D);%0A%0Afun @@ -1624,24 +1624,98 @@ s%22%0A %7D +,%0A plugins: %5Bnew webpack.optimize.UglifyJsPlugin(%7Bminimize: true%7D)%5D %0A %7D).run( @@ -2042,155 +2042,8 @@ %0A%7D%0A%0A -function publish() %7B%0A buildReactCore();%0A compiler.run(function(err, stats) %7B%0A console.log(stats.toString(%7Bcolors: true%7D));%0A %7D);%0A%7D%0A%0A func @@ -2357,19 +2357,17 @@ blish%22) -publish +build ();%0A
88f3766b16d2f4160b84daf2277b2aff6ce11de4
Fix exception in beautify when url is undefined
lib/parser/beautify_url.js
lib/parser/beautify_url.js
// Decode url and collapse its long parts // 'use strict'; var mdurl = require('mdurl'); var punycode = require('punycode'); function elide_text(text, max) { var chars = punycode.ucs2.decode(text); if (chars.length >= max) { return punycode.ucs2.encode(chars.slice(0, max - 1)).replace(/…$/, '') + '…'; } return text; } function text_length(text) { return punycode.ucs2.decode(text).length; } // Replace long parts of the urls with elisions. // // This algorithm is similar to one used in chromium: // https://chromium.googlesource.com/chromium/src.git/+/master/chrome/browser/ui/elide_url.cc // // 1. Chop off path, e.g. // "/foo/bar/baz/quux" -> "/foo/bar/…/quux" -> "/foo/…/quux" -> "/…/quux" // // 2. Get rid of 2+ level subdomains, e.g. // "foo.bar.baz.x.com" -> "…bar.baz.x.com" -> "…baz.x.com" -> "…x.com" // // 3. Truncate the rest of the url // // If at any point of the time url becomes small enough, return it // function elide_url(url, max) { var url_str = mdurl.format(url); var query_length = ((url.search || '') + (url.hash || '')).length; // Maximum length of url without query+hash part // var max_path_length = max + query_length - 2; // Here and below this `if` condition means: // // Assume that we can safely truncate querystring at anytime without // readability loss up to "?". // // So if url without hash/search fits, return it, eliding the end // e.g. "example.org/path/file?q=12345" -> "example.org/path/file?q=12..." // if (text_length(url_str) <= max_path_length) { return elide_text(url_str, max); } // Try to elide path, e.g. "/foo/bar/baz/quux" -> "/foo/.../quux" // if (url.pathname) { var components = url.pathname.split('/'); var filename = components.pop(); if (filename === '' && components.length) { filename = components.pop() + '/'; } while (components.length > 1) { components.pop(); url.pathname = components.join('/') + '/…/' + filename; url_str = mdurl.format(url); if (text_length(url_str) <= max_path_length) { return elide_text(url_str, max); } } } // Elide subdomains up to 2nd level, // e.g. "foo.bar.example.org" -> "...bar.example.org", // if (url.hostname) { var subdomains = url.hostname.split('.'); // If it starts with "www", just remove it // if (subdomains[0] === 'www' && subdomains.length > 2) { subdomains.shift(); url.hostname = subdomains.join('.'); url_str = mdurl.format(url); if (text_length(url_str) <= max_path_length) { return elide_text(url_str, max); } } while (subdomains.length > 2) { subdomains.shift(); url.hostname = '…' + subdomains.join('.'); url_str = mdurl.format(url); if (text_length(url_str) <= max_path_length) { return elide_text(url_str, max); } } } return elide_text(mdurl.format(url), max); } // Decode hostname/path and trim url // - url_str - url to decode // - max_length - maximum allowed length for this url // function beautify_url(url_str, max_length) { var url = mdurl.parse(url_str, true); // urls without host and protocol, e.g. "example.org/foo" if (!url.protocol && !url.slashes && !url.hostname) { url = mdurl.parse('//' + url_str, true); } try { if (url.hostname) { url.hostname = punycode.toUnicode(url.hostname); } } catch (e) {} // Decode url-encoded characters // if (url.auth) { url.auth = mdurl.decode(url.auth); } if (url.hash) { url.hash = mdurl.decode(url.hash); } if (url.search) { url.search = mdurl.decode(url.search); } if (url.pathname) { url.pathname = mdurl.decode(url.pathname); } // Omit protocol if it's http, https or mailto // if (url.protocol && url.protocol.match(/^(https?|mailto):$/)) { url.protocol = null; url.slashes = null; } else if (url.slashes) { url.slashes = null; } return elide_url(url, max_length); } module.exports = beautify_url;
JavaScript
0.000069
@@ -3062,24 +3062,98 @@ x_length) %7B%0A + if (typeof url_str === 'undefined' %7C%7C url_str === null) %7B return ''; %7D%0A%0A var url = @@ -3164,23 +3164,31 @@ l.parse( +String( url_str +) , true);
e36fb59b74132cea6c39531a3ab213d96532623e
fix lint issue
test/configs/backstop_features.js
test/configs/backstop_features.js
const ENGINE = 'puppet'; const SCRIPT_PATH = 'puppet'; const URL = 'https://garris.github.io/BackstopJS'; module.exports = { id: `${ENGINE}_backstop_features`, viewports: [ { label: 'phone', width: 320, height: 480 }, { label: 'tablet', width: 1024, height: 768 } ], onBeforeScript: `${SCRIPT_PATH}/onBefore.js`, onReadyScript: `${SCRIPT_PATH}/onReady.js`, scenarios: [ { label: 'Simple', url: `${URL}/index.html`, }, { label: 'pkra bug test', url: `${URL}/index.html`, selectors: ['#pkratest', '.logoBlock'] }, { label: 'delay', url: `${URL}/index.html?delay`, delay: 5000, selectors: ['.moneyshot'] }, { label: 'readyEvent', url: `${URL}/index.html?delay`, readyEvent: '_the_lemur_is_ready_to_see_you', selectors: ['.moneyshot'] }, { label: 'readySelector', url: `${URL}/index.html?delay`, readySelector: '._the_lemur_is_ready_to_see_you', selectors: ['.moneyshot'] }, { label: 'noDelay', url: `${URL}/index.html?delay`, selectors: ['.moneyshot'] }, { label: 'expanded', url: `${URL}/index.html`, selectors: ['p'], selectorExpansion: true, delay: 1000 }, { label: 'notExpanded', url: `${URL}/index.html`, selectors: ['p'], delay: 1000 }, { label: 'expect', url: `${URL}/index.html`, selectors: ['p'], selectorExpansion: true, expect: 7 }, { label: 'magicSelectors', url: `${URL}/index.html`, selectors: ['document', 'viewport'] }, { label: 'hideSelectors', url: `${URL}/index.html`, hideSelectors: ['.logo-link', 'p'] }, { label: 'removeSelectors', url: `${URL}/index.html`, removeSelectors: ['.logo-link', 'p'] }, { label: 'notFound', url: `${URL}/index.html`, selectors: ['.monkey'] }, { label: 'notVisible', url: `${URL}/index.html`, selectors: ['#noShow'] }, { label: 'cookies', cookiePath: 'backstop_data/cookies.json', url: `${URL}/index.html?cookie`, selectors: ['.moneyshot'] }, // { // label: 'customReadyScript', // onReadyScript: `${SCRIPT_PATH}/overrideCSS.js`, // url: `${URL}/index.html`, // selectors: ['.moneyshot'] // }, // { // label: 'redirect', // url: `${URL}/index.html`, // onReadyScript: `${SCRIPT_PATH}/redirect.js`, // selectors: ['.moneyshot'] // }, { label: 'hover', url: `${URL}/index.html?click`, hoverSelector: '#theLemur', postInteractionWait: 1000, selectors: ['.moneyshot'] }, { label: 'click', url: `${URL}/index.html?click`, clickSelector: '#theLemur', postInteractionWait: '._the_lemur_is_ready_to_see_you', selectors: ['.moneyshot'] }, { label: 'scrollToSelector', url: `${URL}/test/configs/special_cases/scrollToSelector.html`, scrollToSelector: '.lemurFace', selectors: ['.lemurFace'] }, { label: 'misMatchThreshold_requireSameDimensions', url: `${URL}/index.html`, referenceUrl: 'https://garris.github.io/BackstopJS/?cookie', selectors: ['.moneyshot'], misMatchThreshold: 6.0, requireSameDimensions: false }, { label: 'misMatchThreshold_realNumberDifference', url: `${URL}/index.html`, referenceUrl: 'https://garris.github.io/BackstopJS/?cookie', selectors: ['.moneyshot'], misMatchThreshold: 0.01, requireSameDimensions: true }, { label: 'scenarioSpecificViewports', url: `${URL}/index.html`, selectors: ['document', 'viewport'], viewports: [ { label: 'Galaxy-S5', width: 360, height: 640 } ] }, { label: 'scenarioSpecificViewports-withEmptyViewports', url: `${URL}/index.html`, viewports: [] }, { label: 'scenarioSpecificViewports-withMultipleViewports', url: `${URL}/index.html`, viewports: [ { label: 'Pixel-2', width: 411, height: 731 }, { label: 'Pixel2-XL', width: 411, height: 823 }, { label: 'iPhone-X', width: 375, height: 812 }, { label: 'iPad-Pro', width: 1024, height: 1366 } ] }, { label: 'scenarioSpecificViewports-withExpandSelector', url: `${URL}/index.html`, selectors: ['p'], selectorExpansion: true, viewports: [ { label: 'Pixel-2', width: 411, height: 731 }, { label: 'Pixel2-XL', width: 411, height: 823 }, { label: 'iPhone-X', width: 375, height: 812 }, { label: 'iPad-Pro', width: 1024, height: 1366 } ] }, { label: 'keyPressSelector', url: `${URL}/examples/featureTests/index.html`, keyPressSelectors: [ { selector: 'input[placeholder="Email"]', keyPress: '[email protected]' }, { selector: 'input[placeholder="Password"]', keyPress: '1234' } ], selectors: ['div[id=navbar]'], viewports: [ { label: 'Desktop', width: 800, height: 300 } ] } ], paths: { bitmaps_reference: 'backstop_data/bitmaps_reference', bitmaps_test: 'backstop_data/bitmaps_test', engine_scripts: 'backstop_data/engine_scripts', html_report: 'backstop_data/html_report', ci_report: 'backstop_data/ci_report' }, report: ['browser', 'json'], engine: ENGINE, engineOptions: { args: ['--no-sandbox'] }, asyncCaptureLimit: 10, asyncCompareLimit: 50, debug: false, debugWindow: false };
JavaScript
0.000003
@@ -483,25 +483,24 @@ /index.html%60 -, %0A %7D,%0A
9ff42bfa62ca568ce3b2146c3dc832af1006f84a
Remove console.log
client/src/GameState.js
client/src/GameState.js
function GameState() { } GameState.prototype.connectWebsocket = function() { var ws = new WebSocket('ws://localhost:1337', 'echo-protocol'); var that = this; this.ws = ws; this.wsReady = false; var that = this; ws.addEventListener('open', function(e) { that.wsReady = true; }); ws.addEventListener('message', function(e) { that.state = JSON.parse(e.data); console.log(that.state); }); }; GameState.prototype.init = function() { this.bg = loadImage('res/bg.png'); this.vignette = loadImage('res/vignette.png'); this.connectWebsocket(); }; GameState.prototype.pause = function() { }; GameState.prototype.resume = function() { var that = this; this.elements = [ [function() { }, {x: 7.5, y: 4, w: 1, h: 1}], [function() { that.audioButton.toggleActivated(); }, {x: 15, y: 0, w: 1, h: 1}] ]; this.audioButton = new AudioButton(); }; GameState.prototype.render = function(ctx) { ctx.save(); var scaler = 16 * GU / this.bg.width + 0.01 + 0.01 * Math.sin(t / 125); ctx.translate(CENTER.x * GU, CENTER.y * GU); ctx.scale(scaler, scaler); ctx.translate(-this.bg.width / 2, -this.bg.height / 2); ctx.drawImage(this.bg, 0, 0); ctx.restore(); ctx.save(); scaler = 16 * GU / this.vignette.width; ctx.scale(scaler, scaler); ctx.drawImage(this.vignette, 0, 0); ctx.restore(); ctx.fillStyle = 'blue'; ctx.fillStyle = 'red'; if(this.state) { for(var i = 0; i < this.state.length; i++) { var player = this.state[i]; ctx.fillRect(player.x * GU, player.y * GU, GU / 4, GU / 4); } } this.audioButton.render(); }; GameState.prototype.update = function() { var that = this; var buttons = { MOVE_UP: 1, MOVE_DOWN: 2, MOVE_LEFT: 3, MOVE_RIGHT: 4, FIRE: 5, ALTERNATE_FIRE: 6 }; if(this.wsReady) { var inputs = []; if (KEYS[87]) { // W inputs.push(buttons.MOVE_UP); } if (KEYS[83]) { // S inputs.push(buttons.MOVE_DOWN); } if (KEYS[65]) { // A inputs.push(buttons.MOVE_LEFT); } if (KEYS[68]) { // D inputs.push(buttons.MOVE_RIGHT); } this.ws.send(JSON.stringify({ type: 'inputs', inputs: [ KEYS[87], // W KEYS[83], // S KEYS[65], // A KEYS[68], // D false, false ] })); } };
JavaScript
0.000004
@@ -378,37 +378,8 @@ a);%0A - console.log(that.state);%0A %7D)
44ab3a1addabecf75baf9c6ab7eef68ac3deac89
fix bug where it looked for a build "attempt+1" times
lib/util/jenkins.js
lib/util/jenkins.js
/* * Copyright 2012 Rackspace * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var url = require('url'); var util = require('util'); var request = require('request'); var logmagic = require('logmagic'); var async = require('async'); var TREE_FILTER = 'depth=1&tree=builds[actions[lastBuiltRevision[SHA1]],' + 'result,building,timestamp,url,fullDisplayName,number]'; /** * Jenkins Client. * @constructor * @param {Object} options, including: * url: Jenkins server URL * username, password: Credentials * delay: polling interval in milliseconds * attempts: number of polling attempts to wait for builds to appear */ function Jenkins(options, log) { var parsed = url.parse(options.url); parsed['auth'] = util.format('%s:%s', options.username, options.password); this._url = url.format(parsed); this._options = options; this.log = log || logmagic.local('jenkins'); } /** * Ensure that a revision is built on Jenkins by polling until its completion. * * @param {String} builder The Jenkins project to build * @param {?String} Branch The branch to build. Defaults to master. * @param {String} revision The full SHA1 of the revision to build * @param {Function} callback The completion callback(err, build) */ Jenkins.prototype.ensureRevisionBuilt = function(builder, branch, revision, callback) { var self = this; var build = null; var polling = false; var attempts = 0; function getLastBuild(callback) { self.getRevision(builder, revision, function(err, last_build) { if (err) { return callback(err, null); } if (!build || build.building === false) { attempts++; } build = last_build; callback(null, build); }); } function pollJenkins(asyncCallback) { var errorMsg; if (attempts > self._options.attempts) { errorMsg = util.format('ERROR: Jenkins did not report a build after checking %s times', attempts) return asyncCallback(new Error(errorMsg), null); } setTimeout(getLastBuild, self._options.delay, asyncCallback); } function isBuilt() { return self.isBuildComplete(build) } getLastBuild(function(err, retrievedBuild) { if (err) { callback(err); } else if (retrievedBuild && self.isBuildComplete(build)) { callback(null, retrievedBuild); } else { async.until(isBuilt, pollJenkins, function(err) { callback(err, build); }); } }); } /** * Determines whether a build object with attributes .building and .result * is complete. * * @param build {Object=} Build object, or null * @return True if the build is complete, False otherwise */ Jenkins.prototype.isBuildComplete = function(build) { if (!build) { this.log.info('Jenkins does not yet show a build for this revision'); return false; } else if (build.building === true) { this.log.infof('"${name}" is building', { name: build.fullDisplayName, startedAt: new Date(build.timestamp).toISOString(), url: build.url }); return false; } else { if (this.isBuildSuccessful(build)) { this.log.info('Build succeeded!', build); } else { this.log.infof('Build finished, but status was ${status}', { status: build.result }); } return true; } }; /** * Determines whether a given build ended with a 'SUCCESS' status * * @param build {Object} Build object with a .result attribute * @return True if the build was successful */ Jenkins.prototype.isBuildSuccessful = function(build) { return (build.result === 'SUCCESS') } /** * Begin a build of the given revision on Jenkins. * * @param builder {String} Jenkins project to build * @param {?String} Branch The branch to build. Defaults to master. * @param revision {String} Full SHA1 to build * @param callback {Function} callback(err, http.ClientResponse, body) to be * run when the response is received. */ Jenkins.prototype.build = function(builder, branch, revision, callback) { var options = { url: util.format('%s/job/%s/buildWithParameters', this._url, builder), qs : {'REV': revision} } this.log.infof('Forcing build of revision ${rev}', { rev: revision, options: options }); request.get(options, callback); } /** * Use the Jenkins API to find the most recent build with the given revision. * * @param builder {String} Jenkins project to use when looking for build * @param revision {String} SHA1 of build to look for * @param callback {Function} callback(err, build) to run when build is found. * build is null if there was no such build. */ Jenkins.prototype.getRevision = function(builder, revision, callback) { var url = util.format('%s/job/%s/api/json?%s', this._url, builder, TREE_FILTER), self = this; request.get(url, function(err, response, body) { var i, build, buildSha; self.log.infof('Got builds from Jenkins, looking for SHA1 ${rev}...', { rev: revision }); if (err) { return callback(err); } try { body = JSON.parse(body); } catch (e) { return callback(e); } for (i = 0; i < body.builds.length; i++) { build = body.builds[i]; buildSha = self._getBuildSHA(build); if (revision === buildSha) { return callback(null, build); } } callback(); }); } /** * Convenience method to find the SHA1 of a Jenkins build * (it's buried in the object). * * @param build {Object} Jenkins build * @return {String} SHA1 of the build */ Jenkins.prototype._getBuildSHA = function (build) { var actions = build.actions, action, i; for (i=0; i < build.actions.length; i++) { action = actions[i]; if (action.hasOwnProperty('lastBuiltRevision')) { return action.lastBuiltRevision.SHA1; } } }; exports.Jenkins = Jenkins;
JavaScript
0
@@ -2349,16 +2349,17 @@ tempts %3E += self._o
920898f6958af6c212d0025f391c678b887aef3f
fix screenshot request regexp
lib/reporter.js
lib/reporter.js
import process from 'process' import events from 'events' import Allure from 'allure-js-commons' import Step from 'allure-js-commons/beans/step' function isEmpty (object) { return !object || Object.keys(object).length === 0 } const LOGGING_HOOKS = ['"before all" hook', '"after all" hook'] /** * Initialize a new `Allure` test reporter. * * @param {Runner} runner * @api public */ class AllureReporter extends events.EventEmitter { constructor (baseReporter, config, options = {}) { super() this.baseReporter = baseReporter this.config = config this.options = options this.allures = {} const { epilogue } = this.baseReporter this.on('end', () => { epilogue.call(baseReporter) }) this.on('suite:start', (suite) => { const allure = this.getAllure(suite.cid) const currentSuite = allure.getCurrentSuite() const prefix = currentSuite ? currentSuite.name + ' ' : '' allure.startSuite(prefix + suite.title) }) this.on('suite:end', (suite) => { this.getAllure(suite.cid).endSuite() }) this.on('test:start', (test) => { const allure = this.getAllure(test.cid) allure.startCase(test.title) const currentTest = allure.getCurrentTest() currentTest.addParameter('environment-variable', 'capabilities', JSON.stringify(test.runner[test.cid])) currentTest.addParameter('environment-variable', 'spec files', JSON.stringify(test.specs)) if (test.featureName && test.scenarioName) { currentTest.addLabel('feature', test.featureName) currentTest.addLabel('story', test.scenarioName) } // Analytics labels More: https://github.com/allure-framework/allure2/blob/master/Analytics.md currentTest.addLabel('language', 'javascript') currentTest.addLabel('framework', 'wdio') }) this.on('test:pass', (test) => { this.getAllure(test.cid).endCase('passed') }) this.on('test:fail', (test) => { const allure = this.getAllure(test.cid) const status = test.err.type === 'AssertionError' ? 'failed' : 'broken' if (!allure.getCurrentTest()) { allure.startCase(test.title) } else { allure.getCurrentTest().name = test.title } while (allure.getCurrentSuite().currentStep instanceof Step) { allure.endStep(status) } allure.endCase(status, test.err) }) this.on('test:pending', (test) => { this.getAllure(test.cid).pendingCase(test.title) }) this.on('runner:command', (command) => { const allure = this.getAllure(command.cid) if (!this.isAnyTestRunning(allure)) { return } allure.startStep(`${command.method} ${command.uri.path}`) if (!isEmpty(command.data)) { this.dumpJSON(allure, 'Request', command.data) } }) this.on('runner:result', (command) => { const allure = this.getAllure(command.cid) if (!this.isAnyTestRunning(allure)) { return } if (command.requestOptions.uri.path.match(/\/wd\/hub\/session\/[^/]*\/screenshot/) && command.body.value) { allure.addAttachment('Screenshot', Buffer.from(command.body.value, 'base64')) } else if (command.body) { this.dumpJSON(allure, 'Response', command.body) } allure.endStep('passed') }) this.on('hook:start', (hook) => { const allure = this.getAllure(hook.cid) if (!allure.getCurrentSuite() || LOGGING_HOOKS.indexOf(hook.title) === -1) { return } allure.startCase(hook.title) }) this.on('hook:end', (hook) => { const allure = this.getAllure(hook.cid) if (!allure.getCurrentSuite() || LOGGING_HOOKS.indexOf(hook.title) === -1) { return } allure.endCase('passed') if (allure.getCurrentTest().steps.length === 0) { allure.getCurrentSuite().testcases.pop() } }) this.on('allure:feature', ({ cid, featureName }) => { const allure = this.getAllure(cid) const test = allure.getCurrentTest() test.addLabel('feature', featureName) }) this.on('allure:addEnvironment', ({ cid, name, value }) => { const allure = this.getAllure(cid) const test = allure.getCurrentTest() test.addParameter('environment-variable', name, value) }) this.on('allure:addDescription', ({ cid, description, type }) => { const allure = this.getAllure(cid) const test = allure.getCurrentTest() test.setDescription(description, type) }) this.on('allure:attachment', ({cid, name, content, type}) => { if (content == null) { return } var allure = null allure = this.getAllure(cid) if (allure == null) { return } if (type === 'application/json') { this.dumpJSON(allure, name, content) } else { allure.addAttachment(name, content, type) } }) this.on('allure:story', ({ cid, storyName }) => { const test = this.getAllure(cid).getCurrentTest() test.addLabel('story', storyName) }) } static feature (featureName) { AllureReporter.tellReporter('allure:feature', { featureName }) } static addEnvironment (name, value) { AllureReporter.tellReporter('allure:addEnvironment', { name, value }) } static addDescription (description, type) { AllureReporter.tellReporter('allure:addDescription', { description, type }) } static createAttachment (name, content, type = 'text/plain') { AllureReporter.tellReporter('allure:attachment', {name, content, type}) } static story (storyName) { AllureReporter.tellReporter('allure:story', { storyName }) } static tellReporter (event, msg = {}) { process.send({ event, ...msg }) } getAllure (cid) { if (this.allures[cid]) { return this.allures[cid] } const allure = new Allure() allure.setOptions({ targetDir: this.options.outputDir || 'allure-results' }) this.allures[cid] = allure return this.allures[cid] } isAnyTestRunning (allure) { return allure.getCurrentSuite() && allure.getCurrentTest() } dumpJSON (allure, name, json) { allure.addAttachment(name, JSON.stringify(json, null, ' '), 'application/json') } } export default AllureReporter
JavaScript
0.000001
@@ -3428,17 +3428,8 @@ (/%5C/ -wd%5C/hub%5C/ sess
ec774487c362a4e99feccc5ae69c2ecea203aa81
Remove redundant runner:screenshot listener
lib/reporter.js
lib/reporter.js
import events from 'events' import Allure from 'allure-js-commons' import Step from 'allure-js-commons/beans/step' function isEmpty (object) { return !object || Object.keys(object).length === 0 } const LOGGING_HOOKS = ['"before all" hook', '"after all" hook'] /** * Initialize a new `Allure` test reporter. * * @param {Runner} runner * @api public */ class AllureReporter extends events.EventEmitter { constructor (baseReporter, config, options = {}) { super() this.baseReporter = baseReporter this.config = config this.options = options this.allures = {} const { epilogue } = this.baseReporter this.on('end', () => { epilogue.call(baseReporter) }) this.on('suite:start', (suite) => { const allure = this.getAllure(suite.cid) const currentSuite = allure.getCurrentSuite() const prefix = currentSuite ? currentSuite.name + ' ' : '' allure.startSuite(prefix + suite.title) }) this.on('suite:end', (suite) => { this.getAllure(suite.cid).endSuite() }) this.on('test:start', (test) => { const allure = this.getAllure(test.cid) allure.startCase(test.title) const currentTest = allure.getCurrentTest() currentTest.addParameter('environment-variable', 'capabilities', JSON.stringify(test.runner[test.cid])) currentTest.addParameter('environment-variable', 'spec files', JSON.stringify(test.specs)) }) this.on('test:pass', (test) => { this.getAllure(test.cid).endCase('passed') }) this.on('test:fail', (test) => { const allure = this.getAllure(test.cid) const status = test.err.type === 'AssertionError' ? 'failed' : 'broken' if (!allure.getCurrentTest()) { allure.startCase(test.title) } else { allure.getCurrentTest().name = test.title } while (allure.getCurrentSuite().currentStep instanceof Step) { allure.endStep(status) } allure.endCase(status, test.err) }) this.on('test:pending', (test) => { this.getAllure(test.cid).pendingCase(test.title) }) this.on('runner:command', (command) => { const allure = this.getAllure(command.cid) if (!this.isAnyTestRunning(allure)) { return } allure.startStep(`${command.method} ${command.uri.path}`) if (!isEmpty(command.data)) { this.dumpJSON(allure, 'Request', command.data) } }) this.on('runner:result', (command) => { const allure = this.getAllure(command.cid) if (!this.isAnyTestRunning(allure)) { return } if (!command.requestOptions.uri.path.match(/\/wd\/hub\/session\/[^/]*\/screenshot/) && command.body) { this.dumpJSON(allure, 'Response', command.body) } allure.endStep('passed') }) this.on('runner:screenshot', (command) => { const allure = this.getAllure(command.cid) allure.addAttachment('screenshot-' + command.filename, Buffer.from(command.data, 'base64')) }) this.on('hook:start', (hook) => { const allure = this.getAllure(hook.cid) if (!allure.getCurrentSuite() || LOGGING_HOOKS.indexOf(hook.title) === -1) { return } allure.startCase(hook.title) }) this.on('hook:end', (hook) => { const allure = this.getAllure(hook.cid) if (!allure.getCurrentSuite() || LOGGING_HOOKS.indexOf(hook.title) === -1) { return } allure.endCase('passed') if (allure.getCurrentTest().steps.length === 0) { allure.getCurrentSuite().testcases.pop() } }) this.on('allure:feature', ({ cid, featureName }) => { const allure = this.getAllure(cid) const test = allure.getCurrentTest() test.addLabel('feature', featureName) }) this.on('allure:addEnvironment', ({ cid, name, value }) => { const allure = this.getAllure(cid) const test = allure.getCurrentTest() test.addParameter('environment-variable', name, value) }) this.on('allure:addDescription', ({ cid, description, type }) => { const allure = this.getAllure(cid) const test = allure.getCurrentTest() test.setDescription(description, type) }) this.on('allure:attachment', ({cid, name, content, type}) => { if (content == null) { return } var allure = null allure = this.getAllure(cid) if (allure == null) { return } if (type === 'application/json') { this.dumpJSON(allure, name, content) } else { allure.addAttachment(name, content, type) } }) this.on('allure:story', ({ cid, storyName }) => { const test = this.getAllure(cid).getCurrentTest() test.addLabel('story', storyName) }) } getAllure (cid) { if (this.allures[cid]) { return this.allures[cid] } const allure = new Allure() allure.setOptions({ targetDir: this.options.outputDir || 'allure-results' }) this.allures[cid] = allure return this.allures[cid] } isAnyTestRunning (allure) { return allure.getCurrentSuite() && allure.getCurrentTest() } dumpJSON (allure, name, json) { allure.addAttachment(name, JSON.stringify(json, null, ' '), 'application/json') } } export default AllureReporter
JavaScript
0.000002
@@ -2929,17 +2929,16 @@ if ( -! command. @@ -3023,16 +3023,22 @@ and.body +.value ) %7B%0A @@ -3053,107 +3053,124 @@ -this.dumpJSON(allure, 'Response', command.body)%0A %7D%0A%0A allure.endStep('passed') +allure.addAttachment('Screenshot', Buffer.from(command.body.value, 'base64'))%0A %7D else if (command.body) %7B %0A @@ -3166,36 +3166,32 @@ body) %7B%0A -%7D)%0A%0A this.on( @@ -3191,46 +3191,50 @@ his. -on('runner:screenshot +dumpJSON(allure, 'Response ', -( command -) =%3E %7B +.body) %0A @@ -3246,154 +3246,46 @@ -const allure = this.getAllure(command.cid)%0A%0A allure.addAttachment('screenshot-' + command.filename, Buffer.from(command.data, 'base64') +%7D%0A%0A allure.endStep('passed' )%0A
54058ffa1591fb6fe92b2b50e59722070b28a629
update hooks
lib/hooks/index.js
lib/hooks/index.js
var async = require('async'); var hooks = {}; hooks.list = {}; hooks.on = function weAddEventListener(eventName, callback) { if(!hooks.list[eventName]){ hooks.list[eventName] = []; } hooks.list[eventName].push(callback); }; /** * Trigger one wejs event ( works like hooks ) and runs all functions added in this event * After run one [event]-after-succes or a [event]-after-error event * * @param {string} eventName name of the event to trigger * @param {object} data Data to passa for event listeners * @param {Function} cb Callback * @return {null} */ hooks.trigger = function weTriggerEvent(eventName, data, cb) { if (!hooks.list[eventName]) return cb(); async.each(hooks.list[eventName], function(functionToRun, next){ functionToRun(data, next); }, cb ); }; module.exports = hooks;
JavaScript
0.000001
@@ -814,17 +814,16 @@ );%0A%7D;%0A%0A -%0A module.e
7e16d0feb49b2ff1ee829868d20f052f058c06aa
put back test cases that feature run-to-run randomness:
test/image/compare_pixels_test.js
test/image/compare_pixels_test.js
var fs = require('fs'); var path = require('path'); var constants = require('../../tasks/util/constants'); var getOptions = require('../../tasks/util/get_image_request_options'); // packages inside the image server docker var request = require('request'); var test = require('tape'); var gm = require('gm'); var TOLERANCE = 1e-6; // pixel comparison tolerance var BASE_TIMEOUT = 500; // base timeout time var BATCH_SIZE = 5; // size of each test 'batch' var touch = function(fileName) { fs.closeSync(fs.openSync(fileName, 'w')); }; // make artifact folders if(!fs.existsSync(constants.pathToTestImagesDiff)) { fs.mkdirSync(constants.pathToTestImagesDiff); } if(!fs.existsSync(constants.pathToTestImages)) { fs.mkdirSync(constants.pathToTestImages); } var userFileName = process.argv[2]; // run the test(s) if(!userFileName) runAll(); else runSingle(userFileName); function runAll() { test('testing mocks', function(t) { var allMocks = fs.readdirSync(constants.pathToTestImageMocks); /* * Some test cases exhibit run-to-run randomness; * skip over these few test cases for now. * * More info: * https://github.com/plotly/plotly.js/issues/62 * * 41 test cases are removed: * - font-wishlist (1 test case) * - all gl2d (38) * - gl3d_bunny-hull (1) * - polar_scatter (1) */ var mocks = allMocks.filter(function(mock) { return !( mock === 'font-wishlist.json' || mock.indexOf('gl2d') !== -1 || mock === 'gl3d_bunny-hull.json' || mock === 'polar_scatter.json' ); }); var cnt = 0; function testFunction() { testMock(mocks[cnt++], t); } t.plan(mocks.length); for(var i = 0; i < mocks.length; i++) { setTimeout(testFunction, BASE_TIMEOUT * Math.floor(i / BATCH_SIZE) * BATCH_SIZE); } }); } function runSingle(userFileName) { test('testing single mock: ' + userFileName, function(t) { t.plan(1); testMock(userFileName, t); }); } function testMock(fileName, t) { var figure = require(path.join(constants.pathToTestImageMocks, fileName)); var bodyMock = { figure: figure, format: 'png', scale: 1 }; var imageFileName = fileName.split('.')[0] + '.png'; var savedImagePath = path.join(constants.pathToTestImages, imageFileName); var diffPath = path.join(constants.pathToTestImagesDiff, 'diff-' + imageFileName); var savedImageStream = fs.createWriteStream(savedImagePath); var options = getOptions(bodyMock, 'http://localhost:9010/'); function checkImage() { var options = { file: diffPath, highlightColor: 'purple', tolerance: TOLERANCE }; /* * N.B. The non-zero tolerance was added in * https://github.com/plotly/plotly.js/pull/243 * where some legend mocks started generating different png outputs * on `npm run test-image` and `npm run test-image -- mock.json`. * * Note that the svg outputs for the problematic mocks were the same * and playing around with the batch size and timeout durations * did not seem to affect the results. * * With the above tolerance individual `npm run test-image` and * `npm run test-image -- mock.json` give the same result. * * Further investigation is needed. */ gm.compare( savedImagePath, path.join(constants.pathToTestImageBaselines, imageFileName), options, onEqualityCheck ); } function onEqualityCheck(err, isEqual) { if(err) { touch(diffPath); return console.error(err, imageFileName); } if(isEqual) { fs.unlinkSync(diffPath); } t.ok(isEqual, imageFileName + ' should be pixel perfect'); } request(options) .pipe(savedImageStream) .on('close', checkImage); }
JavaScript
0
@@ -459,16 +459,17 @@ 'batch'%0A +%0A var touc @@ -1034,388 +1034,209 @@ /* -%0A * Some test cases exhibit run-to-run randomness;%0A * skip over these few test cases for now.%0A *%0A * More info:%0A * https://github.com/plotly/plotly.js/issues/62%0A *%0A * 41 test cases are removed:%0A * - font-wishlist (1 test case)%0A * - all gl2d (38)%0A * - gl3d_bunny-hull (1)%0A * - polar_scatter (1) + Test cases:%0A *%0A * - font-wishlist%0A * - all gl2d%0A *%0A * don't behave consistently from run-to-run and/or%0A * machine-to-machine; skip over them.%0A * %0A @@ -1415,108 +1415,8 @@ = -1 - %7C%7C%0A mock === 'gl3d_bunny-hull.json' %7C%7C%0A mock === 'polar_scatter.json' %0A
6467f6bc3854f8ca0ee3cfe5fe16b5a28ac32ef4
Fix rattling when image appearance
main.js
main.js
'use restrict'; document.addEventListener('DOMContentLoaded', function (event) { var sourceUri = 'https://www.pixiv.net/ranking.php?mode=daily&format=json&content=illust'; var promiseList = []; for (var i = 1; i <= 3; i++) { var p = axios.get(sourceUri + '&p=' + i); promiseList.push(p); } Promise.all(promiseList).then(function (values) { var items = []; var illustrations = []; values.forEach(function (response) { if (response.status === 200) { // Extracting illustration info response.data.contents.forEach(function (content) { illustrations.push({ 'illustrationId': content.illust_id, 'illustrationUrl': content.url, 'illustrationTitle': content.title, 'userName': content.user_name, }); }); } }); // Shuffle. illustrations = shuffle(illustrations); // Inserting elements to a New tab page body. illustrations.forEach(function (illust) { items.push(createGalleryItem( illust.illustrationId, illust.illustrationUrl, illust.illustrationTitle, illust.userName )); }); items.forEach(function (item) { document.querySelector('#gallery').appendChild(item); }); }).catch(function (response) { console.log(response); }); }); function createIllustrationElement(imageUrl, title, author) { var img = new Image(); img.src = imageUrl; img.addEventListener('load', function (e) { e.target.classList.add('loaded'); }); img.alt = author + ' / ' + title; return img; } function createGalleryItem(illustrationId, imageUrl, title, author) { var linkUrl = 'https://www.pixiv.net/i/' + illustrationId; var img = createIllustrationElement(imageUrl, title, author); var anchor = document.createElement('a'); anchor.setAttribute('href', linkUrl); anchor.appendChild(img); return anchor; } function shuffle(array) { var n = array.length, t, i; while (n) { i = Math.floor(Math.random() * n--); t = array[n]; array[n] = array[i]; array[i] = t; } return array; }
JavaScript
0.000003
@@ -397,24 +397,25 @@ tions = %5B%5D;%0A +%0A values.f @@ -1191,37 +1191,257 @@ -items.forEach(function (item) +// Wait for image loading%0A return Promise.all(items.map((item) =%3E %7B%0A return new Promise((resolve) =%3E %7B%0A item.img.onload = item.img.onerror = () =%3E resolve(item);%0A %7D);%0A %7D));%0A %7D)%0A .then((items) =%3E %7B%0A items.forEach((item) =%3E %7B%0A @@ -1492,24 +1492,31 @@ ndChild(item +.anchor );%0A %7D);%0A @@ -1513,16 +1513,118 @@ %0A %7D); +%0A%0A setTimeout(() =%3E %7B%0A items.forEach((item) =%3E item.img.classList.add('loaded'));%0A %7D, 125); %0A %7D).ca @@ -1800,98 +1800,8 @@ rl;%0A - img.addEventListener('load', function (e) %7B%0A e.target.classList.add('loaded');%0A %7D);%0A im @@ -2176,22 +2176,29 @@ return +%7B anchor +, img%7D ;%0A%7D%0A%0Afun
a3f8170a98382b56f56726e42d45c80b3898e831
Add importing from geojson
lib/import-data.js
lib/import-data.js
var fs = require('fs') var importGeo = require('./import-geo') var concat = require('concat-stream') var shp = require('gtran-shapefile') var path = require('path') module.exports = function (osm, name, done) { var ext = path.extname(name) if (ext === '.geojson') { console.log('geojson import', name) concat(fs.createReadStream(name), function (geojson) { if (err) return done(err) return importGeo(osm, geojson, done) }) } else if (ext === '.shp') { shp.toGeoJson(name).then(function (geojson) { return importGeo(osm, geojson, done) }) } }
JavaScript
0
@@ -272,133 +272,167 @@ -console.log('geojson import', name)%0A concat(fs.createReadStream(name), function (geojson) %7B%0A if (err) return done(err +var readStream = fs.createReadStream(name)%0A readStream.on('error', done)%0A readStream.pipe(concat(function (geojson) %7B%0A var data = JSON.parse(geojson )%0A @@ -449,39 +449,36 @@ importGeo(osm, -geojson +data , done)%0A %7D)%0A @@ -471,24 +471,25 @@ done)%0A %7D) +) %0A %7D%0A else
acd26c7b49d7309ef240bed4125633469365ba1e
Fix attr-validate error code
lib/rules/attr-validate.js
lib/rules/attr-validate.js
var Issue = require('../issue'); module.exports = { name: 'attr-validate', on: ['tag'], desc: 'If set, attributes in a tag must be well-formed.' }; module.exports.lint = function (ele, opts) { var attrRegex = /^(\s*[^ "'>=\^]+(\s*=\s*(("[^"]*")|('[^']*')|([^ \t\n"']+)))?)*\s*$/, open = ele.open.slice(ele.name.length); return attrRegex.test(open) ? [] : new Issue('E043', ele.openLineCol); };
JavaScript
0.000005
@@ -396,9 +396,9 @@ 'E04 -3 +9 ', e
7cd200b5f0a6eceecce3030710ef1b8d729c96eb
Add support for {before,after} style initializer dependencies
lib/initializer.js
lib/initializer.js
var glob = require("glob"); var path = require("path"); var _ = require("lodash"); var sequencify = require("sequencify"); var Promise = require("bluebird"); var requireAll = require("./util/require-all"); var Initializer = function(name, dep, fun) { if(typeof fun === 'undefined') { fun = dep; dep = []; } this.name = name; this.dep = dep; this.fun = fun; }; Initializer.registered = { "startup": {}, "shutdown": {} }; Initializer.add = function(phase, name, dep, fun) { Initializer.registered[phase][name] = new Initializer(name, dep, fun); }; // util functions /** * Loads all initializers, returnin an array of Initializer objects founder undereath * `dir`/initializers. * * @param {String} dir the directory to search underneath * @return {Array} an array of Initializer objects */ Initializer.loadAll = function(dir) { var searchPath = path.join(dir, "/**/*.js"); return _.values(requireAll(searchPath)); }; Initializer.run = function(stex, phase) { var seq = sequence(Initializer.registered[phase]); var initializers = _.map(seq, function(name){ return Initializer.registered[phase][name]; }); var runInitializer = function(initializer) { return initializer.fun.call(null, stex); }; var reducer = function(prev, initializer) { return prev.then(function() { return initializer.fun.call(null, stex); }); }; return _.reduce(initializers, reducer, Promise.resolve(true)) .catch(function(err) { console.error("Error running initializers!"); console.error(err); console.error(err.stack); process.exit(1); }); }; function sequence(initializers) { if(_.isEmpty(initializers)) { return ; } initializers = _.cloneDeep(initializers); var results = []; var names = _.pluck(initializers, 'name'); sequencify(initializers, names, results, []); return results; } module.exports = Initializer;
JavaScript
0.000001
@@ -260,26 +260,462 @@ name -, dep, fun) %7B +) %7B%0A this.name = name;%0A this.dep = %5B%5D;%0A this.fun = null;%0A%7D;%0A%0AInitializer.prototype.addDep = function(name) %7B%0A this.dep.push(name);%0A%7D;%0A%0AInitializer.prototype.setFun = function(fun) %7B%0A if(this.fun) %7B%0A throw new Error(%22Cannot overwrite initializer function for: %22 + this.name);%0A %7D%0A%0A this.fun = fun;%0A%7D;%0A%0AInitializer.registered = %7B%0A %22startup%22: %7B%7D,%0A %22shutdown%22: %7B%7D%0A%7D;%0A%0AInitializer.add = function(phase, name, dep, fun) %7B%0A var before, after;%0A %0A if + (typ @@ -781,126 +781,348 @@ %0A%0A -this.name = name +if (_.isPlainObject(dep)) %7B%0A before = dep.before %7C%7C %5B%5D ;%0A + -this.dep = dep;%0A this.fun = fun;%0A%7D;%0A%0AInitializer.registered = %7B%0A %22startup%22: %7B%7D,%0A %22shutdown%22: %7B%7D + after = dep.after %7C%7C %5B%5D;%0A %7D else %7B%0A after = dep %7C%7C %5B%5D;%0A %7D%0A%0A var init = Initializer.get(phase, name);%0A%0A _.each(after, function(dep) %7B init.addDep(dep); %7D);%0A _.each(before, function(dep) %7B Initializer.get(phase, dep).addDep(name); %7D);%0A%0A init.setFun(fun);%0A%0A return init; %0A%7D;%0A @@ -1126,35 +1126,35 @@ %7D;%0A%0AInitializer. -add +get = function(phas @@ -1160,31 +1160,95 @@ se, name -, dep, fun) %7B%0A +) %7B%0A var init = Initializer.registered%5Bphase%5D%5Bname%5D;%0A%0A if(!init) %7B%0A init = Initial @@ -1298,27 +1298,37 @@ zer(name -, dep, fun) +);%0A %7D%0A%0A return init ;%0A%7D;%0A%0A// @@ -1958,32 +1958,102 @@ (initializer) %7B%0A + if(!initializer.fun) %7B%0A return Promise.resolve();%0A %7D%0A %0A return initi @@ -2172,33 +2172,36 @@ %7B%0A return -i +runI nitializer.fun.c @@ -2194,36 +2194,28 @@ tializer -.fun.call(null, stex +(initializer );%0A %7D
cb1ea722fbf50d90cc1f353042437efcdc862aad
remove unused import
lib/runtime/application.js
lib/runtime/application.js
import express from 'express'; import Promise from 'bluebird'; import { log } from '../utils'; import DAG from 'dag-map'; import routerDSL from 'router-dsl'; import Error from './error'; import Engine from './engine'; import blackburn from 'blackburn'; import assign from 'lodash/object/assign'; /** * Application instances are little more than specialized Engines, designed to * kick off the loading, mounting, and launching stages of booting up. * * @title Application */ export default Engine.extend({ init() { this._super(...arguments); this.router = express.Router(); this.mount(); }, mount() { this.mountConfig(); this.mountInitializers(); this.mountMiddleware(); this.mountRoutes(); this.injectServices(); }, mountConfig() { this.config = this._config(this.environment); this.eachEngine((engine) => { engine._config(this.environment, this.config); }, { childrenFirst: false }); }, mountInitializers() { let initializers = this._initializers; this.eachEngine((engine) => { initializers.push(...engine._initializers); }); let initializerGraph = new DAG(); initializers.forEach((initializer) => { initializerGraph.addEdges(initializer.name, initializer.initializer, initializer.before, initializer.after); }); this.initializers = []; initializerGraph.topsort(({ value }) => { this.initializers.push(value); }); }, mountMiddleware() { this._middleware(this.router, this); this.eachEngine((engine) => { engine._middleware(this.router, this); }); }, mountRoutes() { this._routes.call(routerDSL); this.eachEngine((engine) => { engine._routes.call(routerDSL); }); }, start() { let port = this.config.server.port; return this.runInitializers() .then(() => { return this.startServer(port); }).then(() => { this.log(`${ this.pkg.name }@${ this.pkg.version } server up on port ${ port }`); }).catch(() => { this.log('Problem starting app ...'); }); }, runInitializers() { return Promise.resolve(this.initializers) .each((initializer) => { return initializer(this); }); }, startServer(port) { return new Promise((resolve) => { this.server = express(); this.server.use(blackburn({ adapters: this.container.lookupType('adapters'), serializers: this.container.lookupType('serializers') })); this.server.use(this.router); this.server.listen(port, resolve); }); }, log(level) { if (this.environment !== 'test' || level === 'error') { log.apply(this, arguments); } }, handlerForAction(actionPath) { let Action = this.container.lookup('actions/' + actionPath); return function invokeActionForRoute(req, res, next) { let services = this.container.lookupType('services'); let action = new Action(assign({}, services, { container: this.container, request: req, response: res, next })); action._run(); }; } });
JavaScript
0.000001
@@ -155,37 +155,8 @@ l';%0A -import Error from './error';%0A impo
645672a93198dbc2d59b3174668a6d8e7a860a86
Fix error
lib/sanitize.js
lib/sanitize.js
/* ======================================================================== * DBH-PG: utilities for sanitize inputs. * ======================================================================== * Copyright 2014 Sapienlab, Rodrigo González and Contributors. * Licensed under MIT LICENSE * ======================================================================== */ exports.escape = function escape(str) { // thanks: // https://github.com/felixge/node-mysql/blob/1d4cb893a9906890554016c398dccb4271e66808/lib/protocol/SqlString.js#L46-L56 // Copyright (c) 2012 Felix Geisendörfer ([email protected]) and contributors // MIT License return str.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) { switch(s) { case "\0": return "\\0"; case "\n": return "\\n"; case "\r": return "\\r"; case "\b": return "\\b"; case "\t": return "\\t"; case "\x1a": return "\\Z"; default: return "\\" + s; } }); } exports.array = function sanitizeArray(array, whitelist) { var sanitized = [], whiteValue; array.forEach(function sanitizeArrayForEach(key) { whiteValue = sanitizeScalar(key, whitelist[key]); if (whiteValue) { sanitized.push(whiteValue); } }); return sanitized; } exports.object = function sanitizeObject(object, whitelist) { var sanitized = {}, whiteValue, key; for(key in object) { if (object.hasOwnProperty(key) && whitelist[key]) { whiteValue = sanitizeScalar(key, whitelist[key]); if (whiteValue) { sanitized[whiteValue] = object[key]; } } } return sanitized; } exports.sort = function sanitizeSort(sort, whitelist) { var sanitized = [], whiteValue; sort.forEach(function sanitizeArrayForEach(sortRule) { whiteValue = sanitizeScalar(sortRule.attr, whitelist[sortRule.attr]); if (whiteValue) { sanitized.push({ attr: whiteValue, asc: sortRule.asc }); } }); return sanitized; } exports.scalar = sanitizeScalar = function sanitizeScalar(value, whiteValue) { if (!whiteValue) { return false; } var whiteType = typeof whiteValue; if (whiteType === 'string') { return whiteValue; } if (whiteType === 'function') { return checkWhitelist(value, whiteValue(value)); } return value; }
JavaScript
0.000004
@@ -2407,22 +2407,22 @@ urn -checkWhitelist +sanitizeScalar (val
a834a28ac87251d0201ae8fa8e09851be3180317
clean up logging
main.js
main.js
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * 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. * */ (function () { "use strict"; var fs = require("fs"), resolve = require("path").resolve, mkdirp = require("mkdirp"), convert = require("./lib/convert"), xpm2png = require("./lib/xpm2png"); var assetGenerationDir = null; function getUserHomeDirectory() { return process.env[(process.platform === "win32") ? "USERPROFILE" : "HOME"]; } var _generator = null; function savePixmap(pixmap, filename) { _generator.publish("assets.dump", filename); var args = ["-", "-size", pixmap.width + "x" + pixmap.height, "png:-"]; var proc = convert(args, _generator._photoshop._applicationPath); var fileStream = fs.createWriteStream(filename); var stderr = ""; proc.stderr.on("data", function (chunk) { stderr += chunk; }); xpm2png(pixmap, proc.stdin.end.bind(proc.stdin)); proc.stdout.pipe(fileStream); proc.stderr.on("close", function () { if (stderr) { _generator.publish("assets.error", "error from ImageMagick: " + stderr); } }); } function handleImageChanged(message) { if (message.documentID && message.layerEvents) { message.layerEvents.forEach(function (e) { _generator.getPixmap(e.layerID, 100).then( function (pixmap) { if (assetGenerationDir) { savePixmap( pixmap, resolve(assetGenerationDir, message.documentID + "-" + e.layerID + ".png") ); } }, function (err) { _generator.publish("assets.getPixmap", "Error: " + err); }); }); } } function init(generator) { _generator = generator; _generator.subscribe("photoshop.event.imageChanged", handleImageChanged); // create a place to save assets var homeDir = getUserHomeDirectory(); if (homeDir) { var newDir = resolve(homeDir, "Desktop", "generator-assets"); mkdirp(newDir, function (err) { if (err) { _generator.publish( "assets.error", "Could not create directory '" + newDir + "', no assets will be dumped" ); } else { assetGenerationDir = newDir; } }); } else { _generator.publish("assets.error", "Could not locate home directory in env vars, no assets will be dumped"); } } exports.init = init; }());
JavaScript
0
@@ -1673,13 +1673,32 @@ ts.d -ump%22, +ebug.dump%22, %22dumping %22 + fil @@ -2244,24 +2244,32 @@ assets.error +.convert %22, %22error fr @@ -2969,16 +2969,22 @@ %22assets. +error. getPixma @@ -3540,16 +3540,21 @@ ts.error +.init %22,%0A @@ -3827,23 +3827,61 @@ ish( -%22assets.error%22, +%0A %22assets.error.init%22,%0A %22Co @@ -3948,16 +3948,29 @@ dumped%22 +%0A );%0A
beb2d1fc98b5894dbd9b67cea10aa3ecc0e7a3e0
add platform
lib/saucelabs-launchers.js
lib/saucelabs-launchers.js
var browsers = { chrome_latest_linux: { browserName: 'chrome', platform: 'Linux', version: 'latest' }, chrome_latest_windows: { browserName: 'chrome', platform: 'Windows 10', version: 'latest' }, chrome_latest_osx: { browserName: 'chrome', platform: 'OS X 10.11', version: 'latest' }, chrome_latest_1: { browserName: 'chrome', version: 'latest-1' }, chrome_latest_2: { browserName: 'chrome', version: 'latest-2' }, chrome_latest_3: { browserName: 'chrome', version: 'latest-3' }, chrome_latest_4: { browserName: 'chrome', version: 'latest-4' }, firefox_latest_linux: { browserName: 'firefox', platform: 'Linux', version: 'latest' }, firefox_latest_windows: { browserName: 'firefox', platform: 'Windows 10', version: 'latest' }, firefox_latest_osx: { browserName: 'firefox', platform: 'OS X 10.11', version: 'latest' }, firefox_latest_1: { browserName: 'firefox', version: 'latest-1' }, firefox_latest_2: { browserName: 'firefox', version: 'latest-2' }, firefox_latest_3: { browserName: 'firefox', version: 'latest-3' }, firefox_latest_4: { browserName: 'firefox', version: 'latest-4' }, firefox_latest_5: { browserName: 'firefox', version: 'latest-5' }, firefox_latest_6: { browserName: 'firefox', version: 'latest-6' }, // Safari latest safari_latest: { browserName: 'safari', version: 'latest', platform: 'OS X 10.11' }, safari_8: { browserName: 'safari', version: '8', platform: 'OS X 10.10' }, /* safari_7: { browserName: 'safari', version: '7.1.7', platform: 'OS X 10.9' }, */ safari_6: { browserName: 'safari', version: '6', platform: 'OS X 10.8' }, internet_explorer_11: { browserName: 'internet explorer', version: '11', platform: 'Windows 8.1' }, internet_explorer_10: { browserName: 'internet explorer', version: '10', platform: 'Windows 8' }, internet_explorer_9: { browserName: 'internet explorer', version: '9', platform: 'Windows 7' }, microsoftedge_latest: { browserName: 'microsoftedge', platform: 'Windows 10', version: 'latest' }, opera_12: { browserName: 'opera', platform: 'Windows 7', version: '12.12' } }; Object.keys(browsers).forEach(function(key) { browsers[key].base = 'SauceLabs'; }); module.exports = browsers;
JavaScript
0.0004
@@ -366,32 +366,55 @@ Name: 'chrome',%0A + platform: 'Linux',%0A version: 'la @@ -417,24 +417,24 @@ 'latest-1'%0A - %7D,%0A chrom @@ -466,32 +466,55 @@ Name: 'chrome',%0A + platform: 'Linux',%0A version: 'la @@ -566,32 +566,55 @@ Name: 'chrome',%0A + platform: 'Linux',%0A version: 'la @@ -670,24 +670,47 @@ : 'chrome',%0A + platform: 'Linux',%0A version: @@ -1091,32 +1091,55 @@ ame: 'firefox',%0A + platform: 'Linux',%0A version: 'la @@ -1193,32 +1193,55 @@ ame: 'firefox',%0A + platform: 'Linux',%0A version: 'la @@ -1295,32 +1295,55 @@ ame: 'firefox',%0A + platform: 'Linux',%0A version: 'la @@ -1397,32 +1397,55 @@ ame: 'firefox',%0A + platform: 'Linux',%0A version: 'la @@ -1499,32 +1499,55 @@ ame: 'firefox',%0A + platform: 'Linux',%0A version: 'la @@ -1577,24 +1577,24 @@ latest_6: %7B%0A - browserN @@ -1605,24 +1605,47 @@ 'firefox',%0A + platform: 'Linux',%0A version:
11a7cb7925e32253dc0f4e76b9d2589efb3b2f35
Read package version directly from package.json.
main.js
main.js
var assert = require("assert"); var path = require("path"); var Q = require("q"); var slice = Array.prototype.slice; var Watcher = require("./lib/watcher").Watcher; var BuildContext = require("./lib/context").BuildContext; var ModuleReader = require("./lib/reader").ModuleReader; var BundleWriter = require("./lib/writer").BundleWriter; var Pipeline = require("./lib/pipeline").Pipeline; var util = require("./lib/util"); function Brigade() { var self = this; assert.ok(self instanceof Brigade); self.callbacks = { source: [], module: [], bundle: [] }; } var Bp = Brigade.prototype; Bp.cliBuildP = function() { var program = require("commander"); program.version("0.3.1") .option("-s, --schema <file>", "Schema file") .option("-o, --output-dir <directory>", "Output directory") .option("-c, --config <file>", "JSON configuration file [/dev/stdin]") .option("-w, --watch", "Continually rebuild") .parse(process.argv.slice(0)); var workingDir = process.cwd(); var schemaFile = path.normalize(path.join(workingDir, program.schema)); var sourceDir = path.dirname(schemaFile); var outputDir = path.normalize(path.join(workingDir, program.outputDir)); var watcher = new Watcher( sourceDir, program.watch ).on("changed", function(file) { if (program.watch) { log.err(util.yellow(file + " changed; rebuilding...")); rebuild(); } }); var inputP = Q.all([ watcher, util.mkdirP(outputDir), util.readJsonFileP(schemaFile), getConfigP(workingDir, program.config) ]); var buildP = this.buildP.bind(this); function rebuild() { if (rebuild.ing) return; rebuild.ing = true; inputP.spread(buildP).then(function(tree) { rebuild.ing = false; log.out(JSON.stringify(tree)); })["catch"](function(err) { rebuild.ing = false; log.err(util.red(err.stack)); }); } rebuild(); }; // TODO Move this into lib/util.js. var log = { out: function(text) { process.stdout.write(text + "\n"); }, err: function(text) { process.stderr.write(text + "\n"); } }; function getConfigP(workingDir, configFile) { configFile = path.normalize(configFile || "/dev/stdin"); if (configFile.charAt(0) !== "/") configFile = path.join(workingDir, configFile); if (configFile === "/dev/stdin") { log.err(util.yellow( "Expecting configuration from STDIN (pass --config <file> " + "if stuck here)...")); return util.readJsonFromStdinP(); } return util.readJsonFileP(configFile); } Bp.buildP = function(watcher, outputDir, schema, config) { assert.ok(watcher instanceof Watcher); var cbs = this.callbacks; var context = new BuildContext(config, watcher, outputDir); var reader = new ModuleReader(context, cbs.source, cbs.module); var writer = new BundleWriter(context, cbs.bundle); var pipeline = new Pipeline(context, reader, writer); return pipeline.setSchema(schema).getTreeP(); }; function defCallback(name) { Bp[name] = function(callback) { var cbs = this.callbacks[name]; assert.ok(cbs instanceof Array); slice.call(arguments, 0).forEach(function(callback) { assert.strictEqual(typeof callback, "function"); cbs.push(callback); }); return this; }; exports[name] = function() { var api = new Brigade; process.nextTick(api.cliBuildP.bind(api)); return api[name].apply(api, arguments); }; } defCallback("source"); defCallback("module"); defCallback("bundle"); exports.Brigade = Brigade;
JavaScript
0
@@ -417,16 +417,111 @@ til%22);%0A%0A +var versionP = util.readJsonFileP(%0A path.join(__dirname, %22package.json%22)%0A).get(%22version%22);%0A%0A function @@ -732,32 +732,39 @@ ildP = function( +version ) %7B%0A var prog @@ -816,15 +816,15 @@ ion( -%220.3.1%22 +version )%0A @@ -3706,24 +3706,25 @@ rigade;%0A +%0A process. @@ -3719,51 +3719,91 @@ -process.nextTick(api.cliBuildP.bind(api) +versionP.then(function(version) %7B%0A api.cliBuildP(version);%0A %7D );%0A +%0A
9f5815ec04366f25f4b3b4fc1b0a74eae795eec8
allow any scroll direction
lib/scroll-through-time.js
lib/scroll-through-time.js
'use babel'; import { CompositeDisposable } from 'atom'; function getListener (direction) { let previousScroll = 0 let timeout return function (e) { if (Math.abs(e.deltaX) < Math.abs(e.deltaY)) { return } previousScroll += e.deltaX clearTimeout(timeout) timeout = setTimeout(() => previousScroll = 0, 50) if (previousScroll > 50) { previousScroll -= 50 let editor if (editor = atom.workspace.getActiveTextEditor()) { editor[direction ? 'undo' : 'redo']() } } else if (previousScroll < -50) { previousScroll += 50 let editor if (editor = atom.workspace.getActiveTextEditor()) { editor[direction ? 'redo' : 'undo']() } } } } export default { config: { autoToggle: { title: 'Auto Toggle', description: 'Toggle on start.', type: 'boolean', default: true }, direction: { title: 'Scroll direction', description: 'Check: Right to left to undo; Unchecked: Right to left to redo', type: 'boolean', default: true } }, subscriptions: null, listener: null, active: false, activate(state) { this.listener = getListener(this.getConfig('direction')) this.subscriptions = new CompositeDisposable(); this.subscriptions.add(atom.commands.add('atom-workspace', { 'scroll-through-time:toggle': () => this.toggle(), 'scroll-through-time:enable': () => this.toggle(true), 'scroll-through-time:disable': () => this.toggle(false) })); if (this.getConfig('autoToggle') || state.active) { this.toggle(true) } atom.config.onDidChange('my-package.myKey', () => { this.removeListener() this.listener = getListener(this.getConfig('direction')) this.setupListener() }) }, deactivate() { this.active = false this.removeListener() this.subscriptions.dispose(); }, serialize() { return { active: this.active }; }, setupListener() { window.addEventListener( 'mousewheel', this.listener, {passive: true} ) }, removeListener() { window.removeEventListener('mousewheel', this.listener) }, toggle(force) { this.active = typeof force !== 'undefined' ? force : !this.active return ( this.active ? this.setupListener() : this.removeListener() ); }, getConfig (config) { return atom.config.get(`scroll-through-time.${config}`) } };
JavaScript
0
@@ -87,16 +87,196 @@ tion) %7B%0A + let mainAxis = direction == 'left' %7C%7C direction == 'right' ? 'X' : 'Y'%0A let crossAxis = mainAxis == 'X' ? 'Y' : 'X'%0A let reversed = direction == 'right' %7C%7C direction == 'down'%0A let pr @@ -348,23 +348,36 @@ th.abs(e -. +%5B' delta -X +' + mainAxis%5D ) %3C Math @@ -386,26 +386,50 @@ bs(e -. +%5B' delta -Y)) %7B +' + crossAxis%5D)) %7B%0A return +%0A %7D%0A @@ -454,15 +454,28 @@ += e -. +%5B' delta -X +' + mainAxis%5D %0A @@ -698,33 +698,32 @@ editor%5B -direction +reversed ? 'undo' : @@ -897,25 +897,24 @@ editor%5B -direction +reversed ? 'redo @@ -1173,71 +1173,197 @@ -description: 'Check: Right to left to undo; Unchecked: R +type: 'string',%0A default: 'left',%0A enum: %5B%0A %7Bvalue: 'left', description: 'Scroll left to undo, right to redo'%7D,%0A %7Bvalue: 'right', description: 'Scroll r ight to + undo, lef @@ -1372,24 +1372,25 @@ to redo' +%7D ,%0A type: 'b @@ -1385,44 +1385,154 @@ -type: 'boolean',%0A default: true + %7Bvalue: 'up', description: 'Scroll up to undo, down to redo'%7D,%0A %7Bvalue: 'down', description: 'Scroll down to undo, up to redo'%7D,%0A %5D, %0A @@ -1622,70 +1622,8 @@ ) %7B%0A - this.listener = getListener(this.getConfig('direction'))%0A%0A @@ -1934,147 +1934,109 @@ -if ( this. -getConfig('autoToggle') %7C%7C state.active) %7B%0A this.toggle(true)%0A %7D%0A%0A atom.config.onDidChange('my-package.myKey', ( +subscriptions.add(%0A atom.config.observe('scroll-through-time.direction', (newValue ) =%3E %7B%0A + @@ -2061,24 +2061,26 @@ ner()%0A + + this.listene @@ -2099,70 +2099,144 @@ ner( -this.getConfig('direction'))%0A this.setupListener( +newValue)%0A this.setupListener()%0A %7D));%0A%0A if (this.getConfig('autoToggle') %7C%7C state.active) %7B%0A this.toggle(true )%0A %7D -) %0A %7D
0b00c09dbad2084484c6c9a0b82c18e483c1115d
append full rendered queue if any more items needed
lib/scroller.js
lib/scroller.js
var pull = require('pull-stream') var Pause = require('pull-pause') var Value = require('mutant/value') var onceIdle = require('mutant/once-idle') var computed = require('mutant/computed') module.exports = Scroller function Scroller (scroller, content, render, cb) { var toRenderCount = Value(0) var toAppendCount = Value(0) var queueLength = computed([toRenderCount, toAppendCount], (a, b) => a + b) var pause = Pause(function () {}) var running = true var appendQueue = [] function appendLoop () { var distanceFromBottom = scroller.scrollHeight - (scroller.scrollTop + scroller.clientHeight) while (appendQueue.length && distanceFromBottom < scroller.clientHeight) { content.appendChild(appendQueue.shift()) } toAppendCount.set(appendQueue.length) if (queueLength() < 5) { // queue running low, resume stream pause.resume() } if (running || queueLength()) { window.requestAnimationFrame(appendLoop) } } var stream = pull( pause, pull.drain(function (msg) { toRenderCount.set(toRenderCount() + 1) onceIdle(() => { var element = render(msg) appendQueue.push(element) toRenderCount.set(toRenderCount() - 1) }) if (queueLength() > 5) { pause.pause() } }, function (err) { running = false cb ? cb(err) : console.error(err) }) ) stream.queue = queueLength appendLoop() return stream }
JavaScript
0
@@ -618,37 +618,12 @@ -while (appendQueue.length && +if ( dist @@ -660,24 +660,61 @@ ntHeight) %7B%0A + while (appendQueue.length) %7B%0A conten @@ -748,16 +748,24 @@ hift())%0A + %7D%0A %7D%0A%0A
34d1038e34fbdfe41acbf0a1b370feefe360d5a4
Change var to const
main.js
main.js
const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; var Menu = electron.Menu; const path = require('path'); const os = require('os'); const autoUpdater = electron.autoUpdater; const appVersion = require('./package.json').version; //electron.crashReporter.start(); var mainWindow = null; var procStarted = false; var subpy = null; var mainAddr; try { autoUpdater.setFeedURL('https://pokemon-go-updater.mike.ai/feed/channel/all.atom'); } catch (e) {} autoUpdater.on('update-downloaded', function(){ mainWindow.webContents.send('update-ready'); }); app.on('window-all-closed', function() { if (subpy) { subpy.kill('SIGINT'); } app.quit(); }); app.on('ready', function() { mainWindow = new BrowserWindow({width: 800, height: 600}); mainWindow.loadURL('file://' + __dirname + '/login.html'); var template = [{ label: "Application", submenu: [{ label: "About Application", selector: "orderFrontStandardAboutPanel:" }, { type: "separator" }, { label: "Quit", accelerator: "Command+Q", click: function() { app.quit(); } }] }, { label: "Edit", submenu: [{ label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" }, { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" }, { type: "separator" }, { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" }, { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" }, { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" }, { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }] }]; Menu.setApplicationMenu(Menu.buildFromTemplate(template)); mainWindow.on('closed', function() { mainWindow = null; if (subpy) { subpy.kill('SIGINT'); } }); }); function logData(str){ console.log(str); // if(mainWindow){ // mainWindow.webContents.executeJavaScript('console.log(unescape("'+escape(str)+'"))'); // } } ipcMain.on('startPython', function(event, auth, code, lat, long) { if (!procStarted) { logData('Starting Python process...'); startPython(auth, code, lat, long); } procStarted = true; }); ipcMain.on('getServer', function(event) { event.sender.send('server-up', mainAddr); }); ipcMain.on('installUpdate', function(event) { autoUpdater.quitAndInstall(); }); function startPython(auth, code, lat, long) { mainWindow.loadURL('file://' + __dirname + '/main.html'); //mainWindow.openDevTools(); // Find open port var portfinder = require('portfinder'); portfinder.getPort(function (err, port) { logData('Got open port: ' + port); // Run python web server var cmdLine = [ './example.py', '--auth_service', auth, '--token', code, '--location', lat + ',' + long, '--auto_refresh', '10', '--step-limit', '7', //'--display-pokestop', '--display-gym', '--port', port, '--parent_pid', process.pid ]; // console.log(cmdLine); logData('Maps path: ' + path.join(__dirname, 'map')); logData('python ' + cmdLine.join(' ')) var pythonCmd = 'python'; if (os.platform() == 'win32') { pythonCmd = path.join(__dirname, 'pywin', 'python.exe'); } subpy = require('child_process').spawn(pythonCmd, cmdLine, { cwd: path.join(__dirname, 'map') }); subpy.stdout.on('data', (data) => { logData(`Python: ${data}`); }); subpy.stderr.on('data', (data) => { logData(`Python: ${data}`); }); var rq = require('request-promise'); mainAddr = 'http://localhost:' + port; var openWindow = function(){ mainWindow.webContents.send('server-up', mainAddr); mainWindow.webContents.executeJavaScript( 'serverUp("'+mainAddr+'")'); mainWindow.on('closed', function() { mainWindow = null; subpy.kill('SIGINT'); procStarted = false; }); }; var startUp = function(){ rq(mainAddr) .then(function(htmlString){ logData('server started!'); openWindow(); }) .catch(function(err){ //console.log('waiting for the server start...'); startUp(); }); }; startUp(); }); };
JavaScript
0.000006
@@ -137,19 +137,21 @@ pcMain;%0A -var +const Menu =
6765a5b6787903b0b622092680a5d008f85c7b2e
Improve the ngdoc comments generator.
lib/services.js
lib/services.js
var fs = require('fs'); var ejs = require('ejs'); ejs.filters.q = function(obj) { return JSON.stringify(obj, null, 2 ); }; module.exports = function generateServices(app, ngModuleName, apiUrl) { ngModuleName = ngModuleName || 'lbServices'; apiUrl = apiUrl || '/'; var models = describeModels(app); var servicesTemplate = fs.readFileSync( require.resolve('./services.template'), { encoding: 'utf-8' } ); return ejs.render(servicesTemplate, { moduleName: ngModuleName, models: models, urlBase: apiUrl.replace(/\/+$/, '') }); }; function describeModels(app) { var result = {}; app.handler('rest').adapter.getClasses().forEach(function(c) { var name = c.name; if (!c.ctor) { // Skip classes that don't have a shared ctor // as they are not LoopBack models console.error('Skipping %j as it is not a LoopBack model', name); return; } // The URL of prototype methods include sharedCtor parameters like ":id" // Because all $resource methods are static (non-prototype) in ngResource, // the sharedCtor parameters should be added to the parameters // of prototype methods. c.methods.forEach(function fixArgsOfPrototypeMethods(method) { var ctor = method.restClass.ctor; if (!ctor || method.sharedMethod.isStatic) return; method.accepts = ctor.accepts.concat(method.accepts); }); result[name] = c; }); buildScopes(result); return result; } var SCOPE_METHOD_REGEX = /^prototype.__([^_]+)__(.+)$/; function buildScopes(models) { for (var modelName in models) { buildScopesOfModel(models, modelName); } } function buildScopesOfModel(models, modelName) { var modelClass = models[modelName]; modelClass.scopes = {}; modelClass.methods.forEach(function(method) { buildScopeMethod(models, modelName, method); }); return modelClass; } // reverse-engineer scope method // defined by loopback-datasource-juggler/lib/scope.js function buildScopeMethod(models, modelName, method) { var modelClass = models[modelName]; var match = method.name.match(SCOPE_METHOD_REGEX); if (!match) return; var op = match[1]; var scopeName = match[2]; var modelPrototype = modelClass.sharedClass.ctor.prototype; var targetClass = modelPrototype[scopeName]._targetClass; if (modelClass.scopes[scopeName] === undefined) { if (!targetClass) { console.error( 'Warning: scope %s.%s is missing _targetClass property.' + '\nThe Angular code for this scope won\'t be generated.' + '\nPlease upgrade to the latest version of' + '\nloopback-datasource-juggler to fix the problem.', modelName, scopeName); modelClass.scopes[scopeName] = null; return; } if (!findModelByName(models, targetClass)) { console.error( 'Warning: scope %s.%s targets class %j, which is not exposed ' + '\nvia remoting. The Angular code for this scope won\'t be generated.', modelName, scopeName, targetClass); modelClass.scopes[scopeName] = null; return; } modelClass.scopes[scopeName] = { methods: {}, targetClass: targetClass }; } else if (modelClass.scopes[scopeName] === null) { // Skip the scope, the warning was already reported return; } var apiName = scopeName; if (op == 'get') { // no-op, create the scope accessor } else if (op == 'delete') { apiName += '.destroyAll'; } else { apiName += '.' + op; } method.deprecated = 'Use ' + modelName + '.' + apiName + '() instead.'; // build a reverse record to be used in ngResource // Product.__find__categories -> Category.::find::product::categories var reverseName = '::' + op + '::' + modelName + '::' + scopeName; var reverseMethod = Object.create(method); reverseMethod.name = reverseName; delete reverseMethod.deprecated; reverseMethod.internal = 'Use ' + modelName + '.' + apiName + '() instead.'; var reverseModel = findModelByName(models, targetClass); reverseModel.methods.push(reverseMethod); var scopeMethod = Object.create(method); scopeMethod.name = reverseName; delete scopeMethod.deprecated; modelClass.scopes[scopeName].methods[apiName] = scopeMethod; } function findModelByName(models, name) { for (var n in models) { if (n.toLowerCase() == name.toLowerCase()) return models[n]; } }
JavaScript
0
@@ -3489,16 +3489,155 @@ p;%0A %7D%0A%0A + // Names of resources/models in Angular start with a capital letter%0A var ngModelName = modelName%5B0%5D.toUpperCase() + modelName.slice(1);%0A method @@ -3651,33 +3651,35 @@ ated = 'Use ' + -m +ngM odelName + '.' + @@ -4048,25 +4048,27 @@ = 'Use ' + -m +ngM odelName + ' @@ -4281,23 +4281,16 @@ Name;%0A -delete scopeMet @@ -4299,24 +4299,32 @@ d.deprecated + = false ;%0A modelCla
60d2936a3900ae589704105513ef8fdcd6f08b70
Define prototype methods instead of creating new instance methods for each `Levenshtein`
lib/levenshtein.js
lib/levenshtein.js
(function(root, factory){ if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { define(function(){ return factory(root); }); } else if (typeof module == 'object' && module && module.exports) { module.exports = factory(root); } else { root.Levenshtein = factory(root); } }(this, function(root){ var forEach; // Generics if ( ! Array.forEach ) { forEach = function ( array, iterator, context ) { iterator = context ? iterator.bind( context ) : iterator Array.prototype.forEach.call( array, iterator ) } } else { forEach = Array.forEach; } // Levenshtein distance return function Levenshtein( str_m, str_n ) { var previous, current, matrix // Instance methods this.valueOf = function() { return this.distance } this.toString = this.inspect = function inspect ( no_print ) { var max, buff, sep, rows max = matrix.reduce( function( m, o ) { return Math.max( m, o.reduce( Math.max, 0 ) ) }, 0 ) buff = Array( ( max + '' ).length ).join( ' ' ) sep = [] while ( sep.length < (matrix[0] && matrix[0].length || 0) ) sep[ sep.length ] = Array( buff.length + 1 ).join( '-' ) sep = sep.join( '-+' ) + '-' rows = matrix.map( function( row ) { var cells cells = row.map( function( cell ) { return ( buff + cell ).slice( - buff.length ) }) return cells.join( ' |' ) + ' ' }) return rows.join( "\n" + sep + "\n" ) } this.getMatrix = function () { return matrix } // Constructor matrix = [] // Sanity checks if ( str_m == str_n ) return this.distance = 0 else if ( str_m == '' ) return this.distance = str_n.length else if ( str_n == '' ) return this.distance = str_m.length else { // Danger Will Robinson previous = [ 0 ] forEach( str_m, function( v, i ) { i++, previous[ i ] = i } ) matrix[0] = previous forEach( str_n, function( n_val, n_idx ) { current = [ ++n_idx ] forEach( str_m, function( m_val, m_idx ) { m_idx++ if ( str_m.charAt( m_idx - 1 ) == str_n.charAt( n_idx - 1 ) ) current[ m_idx ] = previous[ m_idx - 1 ] else current[ m_idx ] = Math.min ( previous[ m_idx ] + 1 // Deletion , current[ m_idx - 1 ] + 1 // Insertion , previous[ m_idx - 1 ] + 1 // Subtraction ) }) previous = current matrix[ matrix.length ] = previous }) return this.distance = current[ current.length - 1 ] } } }));
JavaScript
0
@@ -668,23 +668,16 @@ tance%0A -return function @@ -748,867 +748,8 @@ // -Instance methods%0A this.valueOf = function() %7B%0A return this.distance%0A %7D%0A%0A this.toString = this.inspect = function inspect ( no_print ) %7B var max, buff, sep, rows%0A max = matrix.reduce( function( m, o ) %7B%0A return Math.max( m, o.reduce( Math.max, 0 ) )%0A %7D, 0 )%0A buff = Array( ( max + '' ).length ).join( ' ' )%0A%0A sep = %5B%5D%0A while ( sep.length %3C (matrix%5B0%5D && matrix%5B0%5D.length %7C%7C 0) )%0A sep%5B sep.length %5D = Array( buff.length + 1 ).join( '-' )%0A sep = sep.join( '-+' ) + '-'%0A%0A rows = matrix.map( function( row ) %7B var cells%0A cells = row.map( function( cell ) %7B%0A return ( buff + cell ).slice( - buff.length )%0A %7D)%0A return cells.join( ' %7C' ) + ' '%0A %7D)%0A%0A return rows.join( %22%5Cn%22 + sep + %22%5Cn%22 )%0A %7D%0A%0A this.getMatrix = function () %7B%0A return matrix%0A %7D%0A%0A // Cons @@ -756,24 +756,39 @@ tructor%0A +matrix = this._ matrix = %5B%5D%0A @@ -1842,13 +1842,945 @@ %7D%0A %7D%0A +%0A Levenshtein.prototype.toString = Levenshtein.prototype.inspect = function inspect ( no_print ) %7B var matrix, max, buff, sep, rows%0A matrix = this.getMatrix()%0A max = matrix.reduce( function( m, o ) %7B%0A return Math.max( m, o.reduce( Math.max, 0 ) )%0A %7D, 0 )%0A buff = Array( ( max + '' ).length ).join( ' ' )%0A%0A sep = %5B%5D%0A while ( sep.length %3C (matrix%5B0%5D && matrix%5B0%5D.length %7C%7C 0) )%0A sep%5B sep.length %5D = Array( buff.length + 1 ).join( '-' )%0A sep = sep.join( '-+' ) + '-'%0A%0A rows = matrix.map( function( row ) %7B var cells%0A cells = row.map( function( cell ) %7B%0A return ( buff + cell ).slice( - buff.length )%0A %7D)%0A return cells.join( ' %7C' ) + ' '%0A %7D)%0A%0A return rows.join( %22%5Cn%22 + sep + %22%5Cn%22 )%0A %7D%0A%0A Levenshtein.prototype.getMatrix = function () %7B%0A return this._matrix.slice()%0A %7D%0A%0A Levenshtein.prototype.valueOf = function() %7B%0A return this.distance%0A %7D%0A%0A return Levenshtein%0A%0A %7D));%0A
96ff3fed798a725e5e25c062a3baf23f0974d8ce
bump timeouts for windows
test/spec/LiveDevelopment-test.js
test/spec/LiveDevelopment-test.js
/* * Copyright 2012 Adobe Systems Incorporated. All Rights Reserved. */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */ /*global define: false, describe: false, it: false, xit: false, expect: false, beforeEach: false, afterEach: false, waitsFor: false, waits: false, runs: false, $: false*/ define(function (require, exports, module) { 'use strict'; var SpecRunnerUtils = require("./SpecRunnerUtils.js"), NativeApp = require("utils/NativeApp"), LiveDevelopment, //The following are all loaded from the test window Inspector, DocumentManager; var testPath = SpecRunnerUtils.getTestPath("/spec/LiveDevelopment-test-files"), testWindow, allSpacesRE = /\s+/gi; function fixSpaces(str) { return str.replace(allSpacesRE, " "); } describe("Live Development", function () { beforeEach(function () { SpecRunnerUtils.createTestWindowAndRun(this, function (w) { testWindow = w; LiveDevelopment = testWindow.brackets.test.LiveDevelopment; Inspector = testWindow.brackets.test.Inspector; DocumentManager = testWindow.brackets.test.DocumentManager; }); SpecRunnerUtils.loadProjectInTestWindow(testPath); }); afterEach(function () { LiveDevelopment.close(); SpecRunnerUtils.closeTestWindow(); }); describe("CSS Editing", function () { it("should establish a browser connection for an opened html file", function () { //verify we aren't currently connected expect(Inspector.connected()).toBeFalsy(); //open a file var htmlOpened = false; runs(function () { SpecRunnerUtils.openProjectFiles(["simple1.html"]).fail(function () { expect("Failed To Open").toBe("simple1.html"); }).always(function () { htmlOpened = true; }); }); waitsFor(function () { return htmlOpened; }, "htmlOpened FILE_OPEN timeout", 1000); //start the connection runs(function () { LiveDevelopment.open(); }); waitsFor(function () { return Inspector.connected(); }, "Waiting for browser", 10000); runs(function () { expect(Inspector.connected()).toBeTruthy(); }); }); it("should should not start a browser connection for an opened css file", function () { //verify we aren't currently connected expect(Inspector.connected()).toBeFalsy(); //open a file var opened = false; runs(function () { SpecRunnerUtils.openProjectFiles(["simple1.css"]).fail(function () { expect("Failed To Open").toBe("simple1.css"); }).always(function () { opened = true; }); }); waitsFor(function () { return opened; }, "FILE_OPEN timeout", 1000); //start the connection runs(function () { LiveDevelopment.open(); }); //we just need to wait an arbitrary time since we can't check for the connection to be true waits(5000); runs(function () { expect(Inspector.connected()).toBeFalsy(); }); }); it("should push changes through the browser connection", function () { var localText, browserText; //verify we aren't currently connected expect(Inspector.connected()).toBeFalsy(); var htmlOpened = false; runs(function () { SpecRunnerUtils.openProjectFiles(["simple1.html"]).fail(function () { expect("Failed To Open").toBe("simple1.html"); }).always(function () { htmlOpened = true; }); }); waitsFor(function () { return htmlOpened; }, "htmlOpened FILE_OPEN timeout", 1000); //start the connection runs(function () { LiveDevelopment.open(); }); waitsFor(function () { return Inspector.connected(); }, "Waiting for browser", 10000); var cssOpened = false; runs(function () { SpecRunnerUtils.openProjectFiles(["simple1.css"]).fail(function () { expect("Failed To Open").toBe("simple1.css"); }).always(function () { cssOpened = true; }); }); waitsFor(function () { return cssOpened; }, "cssOpened FILE_OPEN timeout", 1000); runs(function () { var curDoc = DocumentManager.getCurrentDocument(); localText = curDoc.getText(); localText += "\n .testClass { color:#090; }\n"; curDoc.setText(localText); }); //add a wait for the change to get pushed, then wait to get the result waits(250); var doneSyncing = false; runs(function () { var liveDoc = LiveDevelopment.getLiveDocForPath(testPath + "/simple1.css"); liveDoc.getSourceFromBrowser().done(function (text) { browserText = text; }).always(function () { doneSyncing = true; }); }); waitsFor(function () { return doneSyncing; }, "Browser to sync changes", 10000); runs(function () { expect(fixSpaces(browserText)).toBe(fixSpaces(localText)); }); }); it("should push in memory css changes made before the session starts", function () { var localText, browserText; //verify we aren't currently connected expect(Inspector.connected()).toBeFalsy(); var cssOpened = false; runs(function () { SpecRunnerUtils.openProjectFiles(["simple1.css"]).fail(function () { expect("Failed To Open").toBe("simple1.css"); }).always(function () { cssOpened = true; }); }); waitsFor(function () { return cssOpened; }, "cssOpened FILE_OPEN timeout", 1000); runs(function () { var curDoc = DocumentManager.getCurrentDocument(); localText = curDoc.getText(); localText += "\n .testClass { color:#090; }\n"; curDoc.setText(localText); }); var htmlOpened = false; runs(function () { SpecRunnerUtils.openProjectFiles(["simple1.css", "simple1.html"]).fail(function () { expect("Failed To Open").toBe("simple1.html"); }).always(function () { htmlOpened = true; }); }); waitsFor(function () { return htmlOpened; }, "htmlOpened FILE_OPEN timeout", 1000); //start the connection runs(function () { LiveDevelopment.open(); }); waitsFor(function () { return Inspector.connected(); }, "Waiting for browser", 10000); //wait again for the final changes to load waits(250); var doneSyncing = false; runs(function () { var liveDoc = LiveDevelopment.getLiveDocForPath(testPath + "/simple1.css"); liveDoc.getSourceFromBrowser().done(function (text) { browserText = text; }).always(function () { doneSyncing = true; }); }); waitsFor(function () { return doneSyncing; }, "Browser to sync changes", 10000); runs(function () { expect(fixSpaces(browserText)).toBe(fixSpaces(localText)); }); }); }); }); });
JavaScript
0
@@ -5822,33 +5822,33 @@ waits( -2 +3 50);%0A @@ -8486,17 +8486,17 @@ waits( -2 +3 50);%0A
b801f3525b0bdb7f63bc33f6ccc09da69528f2c0
Add .ts to watching and slight refactoring
lib/tasks/watch_sources.js
lib/tasks/watch_sources.js
var mappingDefaults = { styles: ['css', 'less', 'scss', 'sass', 'styl'], scripts: ['js', 'jsx', 'es6', 'es', 'coffee'], templates: ['jade', 'pug', 'json', 'html', 'htm'], images: ['jpg', 'jpeg', 'png', 'svg'], sprites: ['svg'] } module.exports = function(gulp, config, watch) { var mapping = require('lodash').merge({}, mappingDefaults, config.mapping || {}) var fileExtensions = ['css','styl','scss','sass','less','js','jsx','es6','es','coffee','jade','pug','json','html','htm'] var mappingRegEx = {} Object.keys(mapping).forEach(function(key) { mappingRegEx[key] = [] mappingRegEx[key] = mapping[key].map(function(i) { var ext = '.' + i.replace(/^\./, '') // remove . from the beginning of the string if(fileExtensions.indexOf(key) == -1) { fileExtensions.push(ext.substring(1)) } return new RegExp(ext + '$') }) }) return function(done) { var c = require('better-console') c.info('Watching sources for change and recompilation...') var log = require('better-console') var minimatch = require('minimatch') var path = require('path') var runcmd = require('../helpers/runcmd') var glob = '**/*.{' + fileExtensions.join() + '}' var subtractPaths = require('../helpers/subtractPaths') var distFolderRelative = subtractPaths(config.dist_folder, config.dir) var globDist = distFolderRelative + '/**/*.*' var completeHandler = function(e) { if(config.hooks && config.hooks.watch) { log.info('~ watch hook: ' + config.hooks.watch) runcmd(config.hooks.watch, config.dir, function() { log.info('/>') }) } } var changeHandler = function(filepath) { // Filter dist sources if (minimatch(filepath, globDist)) { return } config._lastChanged = filepath var handlers = [] Object.keys(mappingRegEx).forEach(function (key) { mappingRegEx[key].forEach(function(regexp) { if(filepath.match(regexp)) { handlers.push(key) } }) }) if (!handlers.length) { c.warn('! unknown extension', path.extname(filepath), filepath) return } handlers.forEach(function(handler) { gulp.start(handler, completeHandler) }) } watch(glob, changeHandler) done() } }
JavaScript
0
@@ -112,16 +112,22 @@ 'coffee' +, 'ts' %5D,%0A%09temp @@ -394,105 +394,8 @@ = %5B -'css','styl','scss','sass','less','js','jsx','es6','es','coffee','jade','pug','json','html','htm' %5D%0A%09v
cacad4dbc0121293d72c51ede138d0e7d881a603
handle non-existing property with error
test/spec/adapter/cmof/builder.js
test/spec/adapter/cmof/builder.js
var _ = require('lodash'), fs = require('fs'), path = require('path'); var CmofParser = require('cmof-parser'); var Helper = require('../../../helper'); function Builder() { var desc; var hooks = { 'preSerialize': [] }; function getPackage() { var elementsById = desc.byId; return elementsById['_0']; } function findProperty(properties, name) { var property = _.find(properties, function(d) { return d.name === name; }); return property && { property: property, idx: properties.indexOf(property) }; } function reorderProperties(desc, propertyNames) { var properties = desc.properties; var last; _.forEach(propertyNames, function(name) { var descriptor = findProperty(properties, name); if (last && descriptor) { // remove from old position properties.splice(descriptor.idx, 1); // update descriptor position descriptor.idx = last.idx + 1; // add at new position properties.splice(descriptor.idx, 0, descriptor.property); } last = descriptor; }); } function swapProperties(desc, prop1, prop2) { var props = desc.properties; function findProperty(name) { return _.find(props, function(d) { return d.name === name; }); } var p1 = findProperty(prop1); var p2 = findProperty(prop2); var idx1 = props.indexOf(p1); var idx2 = props.indexOf(p2); props[idx1] = p2; props[idx2] = p1; } function exportTo(file) { var pkg = getPackage(); var str = JSON.stringify(pkg, null, ' '); _.forEach(hooks.preSerialize, function(fn) { str = fn(str); }); fs.writeFileSync(file, str); } function preSerialize(fn) { hooks.preSerialize.push(fn); } function rename(oldType, newType) { preSerialize(function(str) { return str.replace(new RegExp(oldType, 'g'), newType); }); } function alter(elementName, extension) { var elementParts = elementName.split('#'); var elementsById = desc.byId; var element = elementsById[elementParts[0]]; if (!element) { throw new Error('[transform] element <' + elementParts[0] + '> does not exist'); } if (elementParts[1]) { var property = _.find(element.properties, function(p) { return p.name === elementParts[1]; }); if (!property) { throw new Error('[transform] property <' + elementParts[0] + '#' + elementParts[1] + '> does not exist'); } if (_.isFunction(extension)) { extension.call(element, property); } else { _.extend(property, extension); } } else { if (_.isFunction(extension)) { extension.call(element, element); } else { _.extend(element, extension); } } } function cleanIDs() { preSerialize(function(str) { // remove "id": "Something" lines return str.replace(/,\n\s+"id": "[^"]+"/g, ''); }); } function cleanAssociations() { preSerialize(function(str) { // remove "association": "Something" lines return str.replace(/,\n\s+"association": "[^"]+"/g, ''); }); } function parse(file, postParse, done) { new CmofParser({ clean: true }).parseFile(file, function(err, _desc) { if (err) { done(err); } else { desc = _desc; try { postParse(getPackage(), desc); done(null); } catch (e) { done(e); } } }); } function write(dest) { var dir = path.dirname(dest); Helper.ensureDirExists(dir); } this.parse = parse; this.alter = alter; this.rename = rename; this.reorderProperties = reorderProperties; this.swapProperties = swapProperties; this.cleanIDs = cleanIDs; this.cleanAssociations = cleanAssociations; this.exportTo = exportTo; } module.exports = Builder;
JavaScript
0.000001
@@ -795,16 +795,9 @@ if ( -last && +! desc @@ -802,24 +802,118 @@ scriptor) %7B%0A + throw new Error('property %3C' + name + '%3E does not exist');%0A %7D%0A%0A if (last) %7B%0A // r
69205277857dd32760088207faddf183bdf7fbf1
refactor .get(), start on .start()
lib/timelines/timelines.js
lib/timelines/timelines.js
'use strict'; var EventHandler = require('./../utilities/event-handler'); // var TimelineHelper = require('./../utilities/TimelineHelper'); function Timelines(timelineGroups) { EventHandler.apply(this); this._timelineGroups = timelineGroups || {}; this._currentTimeline = null; } Timelines.prototype = Object.create(EventHandler.prototype); Timelines.prototype.constructor = Timelines; Timelines.prototype.get = function(timelineName) { this._currentTimeline = timelineName; return this; } Timelines.prototype.start = function() { console.log(this._currentTimeline, 'starting...'); } module.exports = Timelines;
JavaScript
0.000038
@@ -68,16 +68,70 @@ dler');%0A +var converter = require('best-timelineUI').converter;%0A // var T @@ -222,16 +222,24 @@ neGroups +, states ) %7B%0A @@ -264,16 +264,17 @@ (this);%0A +%0A this @@ -314,16 +314,44 @@ %7C%7C %7B%7D;%0A + this._states = states;%0A%0A this @@ -376,16 +376,54 @@ = null;%0A + this._currentTimelineName = null;%0A %7D%0A%0ATimel @@ -558,16 +558,20 @@ function + get (timelin @@ -578,16 +578,17 @@ eName) %7B +; %0A thi @@ -607,16 +607,84 @@ meline = + this._timelineGroups%5BtimelineName%5D;%0A this._currentTimelineName = timelin @@ -746,16 +746,22 @@ function + start () %7B%0A @@ -765,58 +765,494 @@ -console.log(this._currentTimeline, 'starting...'); +var convertedTimeline = converter.sweetToSalty(this._currentTimeline);%0A var stateTimelines = convertedTimeline.states;%0A%0A var state = '__' + this._currentTimelineName + 'Time'%0A var duration = convertedTimeline.duration;%0A%0A // set time state of timeline equal to duration%0A this._states.set(state, duration, %7Bduration: duration%7D);%0A%0A // loops through each individual state timeline%0A for (var state in stateTimelines) %7B%0A var timeline = stateTimelines%5Bstate%5D;%0A %7D %0A%7D%0A%0A
7ca4323668a09b477f2477a7f5d4879a49a788ca
add init cb
lib/lite-server.js
lib/lite-server.js
'use strict'; /** * lite-server : Simple server for angular/SPA projects * * Simply loads some default browser-sync config that apply to SPAs, * applies custom config overrides from user's own local `bs-config.{js|json}` file, * and launches browser-sync. */ var browserSync = require('browser-sync').create(); var path = require('path'); var _ = require('lodash'); var config = require('./config-defaults'); module.exports = function start(opts) { opts = opts || {}; opts.argv = opts.argv || process.argv; opts.console = opts.console || console; // Load configuration var argv = require('minimist')(opts.argv.slice(2)); var bsConfigName = argv.c || argv.config || 'bs-config'; // Load optional browser-sync config file from user's project dir var bsConfigPath = path.resolve(bsConfigName); var overrides = {}; try { overrides = require(bsConfigPath); } catch (err) { if (err.code && err.code === 'MODULE_NOT_FOUND') { opts.console.info( 'Did not detect a `bs-config.json` or `bs-config.js` override file.' + ' Using lite-server defaults...' ); } else { throw(err); } } _.merge(config, overrides); // Fixes browsersync error when overriding middleware array if (config.server.middleware) { config.server.middleware = _.compact(config.server.middleware); } opts.console.log('** browser-sync config **'); opts.console.log(config); // Run browser-sync browserSync.init(config); }
JavaScript
0.000363
@@ -445,16 +445,20 @@ art(opts +, cb ) %7B%0A @@ -1534,13 +1534,42 @@ t(config -) +, cb);%0A%0A return browserSync ;%0A%7D%0A
a0692c5ba000aacbe2e7731dfd030bdbb535118b
Fix app starts
lib/solenoid.js
lib/solenoid.js
var fs = require('fs'), os = require('os'), path = require('path'), spawn = require('child_process').spawn, mkdirp = require('mkdirp'), async = require('async'), pkgcloud = require('pkgcloud'), semver = require('semver'), useradd = require('useradd'); function noop() {} // // Starts an application. // exports.start = function (options, callback) { async.parallel([ async.apply(fetch, options), async.apply(createUser, options) ], function (err) { if (err) { return callback(err); } async.series([ async.apply(unpack, options), async.apply(readPackageJSON, options), async.apply(findEngine, options), async.apply(startApp, options) ], callback); }); }; exports.stop = function (options, callback) { fs.readFile(options.pidFile, 'utf8', function (err, content) { if (err) { return callback(err); } try { process.kill(parseInt(content, 10)); } catch (ex) { return callback(ex); } }); }; var fetch = exports.fetch = function fetch(options, callback) { var client = pkgcloud.storage.createClient(options.storage), tries = 0, maxTries = 5, packedSnapshotPath = path.join(os.tmpDir(), 'snapshot.tgz'); options.packedSnapshotPath = packedSnapshotPath; function doFetch(callback) { ++tries; var stream = client.download({ container: options.storage.container, remote: [ options.app.user, options.app.name, options.app.version ].join('-') + '.tgz' }); stream.pipe(fs.createWriteStream(packedSnapshotPath)) stream.on('error', function (err) { console.error('Error while fetching snapshot: ' + err.message); return tries === maxTries ? callback(err) : doFetch(callback); }); stream.on('end', function () { console.log('Application snapshot fetched.'); callback(); }); } console.log('Fetching application snapshot...'); doFetch(callback); }; // // Create a dedicated user account. // var createUser = exports.createUser = function createUser(options, callback) { console.log('Creating user...'); useradd({ login: 'nodejitsu-' + options.app.user, shell: false, home: false }, callback); }; var unpack = exports.unpack = function unpack(options, callback) { var snapshotPath = path.join(os.tmpDir(), 'snapshot'), child; console.log('Unpacking snapshot...'); options.snapshotPath = snapshotPath; options.packagePath = path.join(snapshotPath, 'package'); mkdirp(snapshotPath, function (err) { if (err) { return callback(err); } child = spawn('tar', ['-xf', options.packedSnapshotPath], { cwd: snapshotPath }); child.on('exit', function (code, signal) { fs.unlink(options.packedSnapshotPath, noop); if (code !== 0) { return callback( new Error('`tar` exited with ' + (code ? 'code ' + code.toString() : 'signal ' + signal.toString() )) ); } return callback(); }); }); }; var readPackageJSON = exports.readPackageJSON = function readPackageJSON(options, callback) { console.log('Reading `package.json`...'); fs.readFile(path.join(options.packagePath, 'package.json'), function (err, data) { if (err) { return callback(new Error('Error while reading `package.json`: ' + err.message)); } try { data = JSON.parse(data); } catch (ex) { return callback(new Error('Error while parsing `package.json`: ' + err.message)); } options['package.json'] = data; callback(); }); }; var findEngine = exports.findEngine = function findEngine(options, callback) { // TODO: support engines other than node var package = options['package.json'], match, node; if (!package.engines || !package.engines.node) { return callback(new Error('node.js version is required')); } node = package.engines.node; if (!semver.validRange(node)) { return callback(new Error(node + ' is not a valid SemVer version')); } fs.readdir(options.engines.node.path, function (err, files) { if (err) { err.message = 'Cannot read engines directory: ' + err.message; return callback(err); } match = semver.maxSatisfying(files, node); if (!match) { err = new Error('No satisfying engine version found.\n' + 'Available versions are: ' + files.join(',')); return callback(err); } options.enginePath = path.join(options.engines.node.path, match); callback(); }); }; var startApp = exports.startApp = function startApp(options, callback) { var args = [], child; console.log('Starting application...'); args = ['start', '-o', 'estragon.log', '--', 'estragon']; options.instruments.forEach(function (instrument) { args.push('-h', instrument.host + ':' + (instrument.port || 8556).toString()); }); args.push('--app-user', options.app.user); args.push('--app-name', options.app.name); args.push('--', options.enginePath, options['package.json'].scripts.start.split(' ')[1]); child = spawn('aeternum', args, { cwd: path.join(options.snapshotPath, 'package') }); fs.writeFile(options.pidFile, child.pid.toString() + '\n', callback); };
JavaScript
0.000001
@@ -4569,19 +4569,34 @@ h, match +, 'bin', 'node' );%0A - call @@ -4703,16 +4703,32 @@ s = %5B%5D,%0A + pid = '',%0A ch @@ -4772,24 +4772,24 @@ tion...');%0A%0A - args = %5B's @@ -4816,16 +4816,39 @@ on.log', + '-p', options.pidFile, '--', ' @@ -5288,66 +5288,73 @@ %0A%0A -fs.writeFile(options.pidFile, child.pid.toString() + '%5Cn', +child.on('error', callback);%0A child.on('exit', function () %7B%0A cal @@ -5350,22 +5350,29 @@ ) %7B%0A callback +();%0A %7D );%0A%7D;%0A
0d1c8e7999523d853fcbc9f9ac2595aec0965806
Remove unnecessary logs.
lib/splitter.js
lib/splitter.js
const EventEmitter = require('events').EventEmitter const clone = require('clone') const utils = require('./utils') const Server = require('./server') function Splitter (configuration) { if (!utils.config.validate(configuration)) { throw new Error('Invalid configuration') } // Private const clonedConfig = clone(configuration) const log = utils.logger.init(configuration) const bootstrapMiddlewares = [] const requestMiddlewares = [] const rules = {} const started = () => log.error('This splitter instance already started') let server // Optimize criteria and handle performance const optimizedConfig = Object.assign( {}, clonedConfig, {upstreams: utils.config.getOptimizedUpstreams(clonedConfig)}, {api: Object.assign({}, clonedConfig.api, {performance: utils.config.getPerformance(clonedConfig.api)})} ) console.log(JSON.stringify(clonedConfig.upstreams[9])) console.log(JSON.stringify(optimizedConfig.upstreams[8])) // Public this.events = new EventEmitter() this.getConfiguration = () => clone(optimizedConfig) this.getLogger = () => log this.bootstrap = (fn) => { validateCallback(fn) bootstrapMiddlewares.push(fn) } this.use = (fn) => { validateCallback(fn) requestMiddlewares.push(fn) } this.addRule = (key, fn) => { validateString(key, 'Rule name') validateCallback(fn) rules[key] = fn } this.start = () => { this.events.emit('applicationStart') server = new Server( this.getConfiguration(), this.events, bootstrapMiddlewares, requestMiddlewares, rules, this.getLogger() ) server.start() // redefine, fire once, and destroy this.start = started } } const isFunction = fn => fn && typeof fn === 'function' const validateCallback = fn => { if (!isFunction(fn)) { throw new Error('Callback isn\'t a function') } } const isString = str => str && typeof str === 'string' const validateString = (str, msg) => { if (!isString(str)) { throw new Error(msg + ' isn\'t a string') } } exports = module.exports = Splitter exports.isConfigurationValid = (configuration) => utils.config.validate(configuration)
JavaScript
0
@@ -847,125 +847,8 @@ %0A ) -%0A console.log(JSON.stringify(clonedConfig.upstreams%5B9%5D))%0A console.log(JSON.stringify(optimizedConfig.upstreams%5B8%5D)) %0A%0A
09cc4135eac1a071fdd5a213a79619bc88a046b4
Add correct button behaviour
main.js
main.js
var express = require('express'), request = require('request'), cheerio = require('cheerio'), app = express(), radiodanClient = require('radiodan-client'), radiodan = radiodanClient.create(), player = radiodan.player.get('main'), port = process.env.PORT || 5000; // var proxy = require('express-http-proxy'); app.use('/radiodan', radiodanClient.middleware({crossOrigin: true}) ); app.listen(port); function extractUrlFromEnclosure(index, item) { return cheerio(item).attr('url'); } function handlePress(){ console.log("powerButton PRESSED"); } var newurl = 'https://huffduffer.com/libbymiller/rss'; var powerButton = radiodan.button.get("power"); powerButton.on("press",handlePress); request(newurl, function (err, data) { var doc = cheerio(data.body); var urls = doc.find('enclosure') .map(extractUrlFromEnclosure) .get(); player.add({ playlist: urls, clear: true }); player.play(); }); function gracefulExit() { console.log('Exiting...'); player.clear().then(process.exit); } process.on('SIGTERM', gracefulExit); process.on('SIGINT' , gracefulExit); app.use(express.static(__dirname + '/static')); console.log('Listening on port '+port);
JavaScript
0.000003
@@ -533,27 +533,28 @@ unction -handlePress +startPlaying ()%7B%0A co @@ -587,16 +587,133 @@ SSED%22);%0A + player.play();%0A%7D%0A%0Afunction stopPlaying() %7B%0A console.log(%22powerButton RELEASED%22);%0A player.pause(%7B value: true %7D);%0A %7D%0A%0Avar n @@ -838,19 +838,61 @@ ss%22, -handlePress + stopPlaying);%0ApowerButton.on(%22release%22, startPlaying );%0A%0A @@ -1122,31 +1122,14 @@ rue%0A + %7D);%0A - player.play();%0A %7D);%0A
0354604c7a6487cc45c57f9c844636eb9bd0820b
Ensure options to be an object
lib/strategy.js
lib/strategy.js
// ============================================================================= // Module dependencies // ============================================================================= var passport = require('passport-strategy'); var jwt = require('jsonwebtoken'); var util = require('util'); // ============================================================================= // Strategy constructor // ============================================================================= function Strategy(options, verify) { if (!options.secretOrPublicKey) throw new TypeError( 'JwtCookieComboStrategy requires a secret or public key' ); if (!verify) throw new TypeError( 'JwtCookieComboStrategy requires a verify callback' ); passport.Strategy.call(this); this.name = 'jwt-cookiecombo'; this._verify = verify; this._jwtVerifyOptions = Object.assign({}, options.jwtVerifyOptions); this._passReqToCallback = options.passReqToCallback || false; this._secretOrPublicKey = options.secretOrPublicKey; } // ============================================================================= // Inherit from passport.Strategy // ============================================================================= util.inherits(Strategy, passport.Strategy); // ============================================================================= // Authenticate request based on the payload of a json web token // ============================================================================= Strategy.prototype.authenticate = function(req, options) { options = options || {}; var jwtString = null; if (req.signedCookies && 'jwt' in req.signedCookies) jwtString = req.signedCookies.jwt; else if (req.headers && 'authorization' in req.headers) jwtString = req.get('authorization'); if (!jwtString) return this.fail({ message: options.badRequestMessage || 'Missing token' }, 400); jwt.verify(jwtString, this._secretOrPublicKey, this._jwtVerifyOptions, (jwt_err, payload) => { if (jwt_err) return this.fail(jwt_err); var verified = (err, user, info) => { if (err) return this.error(err); if (!user) return this.fail(info); this.success(user, info); }; try { if (this._passReqToCallback) this._verify(req, payload, verified); else this._verify(payload, verified); } catch (ex) { return this.error(ex); } }); }; // ============================================================================= // Expose Strategy // ============================================================================= module.exports = Strategy;
JavaScript
0.999888
@@ -509,16 +509,67 @@ erify) %7B +%0A %0A if (typeof options != 'object') options = %7B%7D; %0A%0A if (
faa9b977c9c0ccb3f3221fe93f6b0f4cad49620a
check geojson filesize as well
lib/validators/omnivore.js
lib/validators/omnivore.js
var fs = require('fs'); var uploadLimits = require('mapbox-upload-limits'); var prettyBytes = require('pretty-bytes'); var path = require('path'); var queue = require('queue-async'); var invalid = require('../invalid'); var sniffer = require('mapbox-file-sniff'); module.exports = function validateOmnivore(opts, callback) { var dir = path.dirname(opts.filepath); var ext = path.extname(opts.filepath); var base = path.basename(opts.filepath, ext); var limits; var files = ext === '.shp' ? [ opts.filepath, path.join(dir, base + '.dbf') ] : [ opts.filepath ]; sniffer.quaff(opts.filepath, function(err, filetype) { if (err) return callback(err); if (filetype === 'tif') limits = opts.limits || uploadLimits.tif; else if (filetype === 'csv') limits = opts.limits || uploadLimits.csv; else limits = opts.limits || uploadLimits.omnivoreOther; var q = queue(); files.forEach(function(f) { q.defer(fs.stat.bind(fs), f); }); q.awaitAll(function(err, stats) { if (err) return callback(err); var size = stats.reduce(function(memo, stat) { memo += stat.size; return memo; }, 0); if (size > limits.max_filesize) { return callback(invalid('File is larger than ' + prettyBytes(limits.max_filesize) + '. Too big to process.')); } callback(); }); }); };
JavaScript
0
@@ -812,16 +812,99 @@ ts.csv;%0A + else if (filetype === 'geojson') limits = opts.limits %7C%7C uploadLimits.geojson;%0A else
c867645a1092bfe465017903ee8df4fe0fbdec43
update user model validations
lib/models/user.js
lib/models/user.js
/** * Module dependencies. */ var config = require('lib/config') var mongoose = require('mongoose') var passportLocalMongoose = require('passport-local-mongoose') var gravatar = require('mongoose-gravatar') var regexps = require('lib/regexps') var normalizeEmail = require('lib/normalize-email') var Schema = mongoose.Schema /** * Define `User` Schema */ var UserSchema = new Schema({ firstName: { type: String }, lastName: { type: String }, username: { type: String }, locale: { type: String, enum: config.availableLocales }, email: { type: String, lowercase: true, trim: true, match: regexps.email }, // main email emailValidated: { type: Boolean, default: false }, profiles: { facebook: { type: Object }, twitter: { type: Object } }, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date }, profilePictureUrl: { type: String }, disabledAt: { type: Date }, notifications: { replies: { type: Boolean, default: true }, 'new-topic': { type: Boolean, default: true } }, badge: { type: String, maxlength: 50 }, extra: Schema.Types.Mixed }) /** * Define Schema Indexes for MongoDB */ UserSchema.index({createdAt: -1}) UserSchema.index({firstName: 1, lastName: 1}) UserSchema.index({email: 1}) UserSchema.index({'notifications.replies': 1}) UserSchema.index({'notifications.new-topic': 1}) UserSchema.index({firstName: 'text', lastName: 'text', email: 'text'}) /** * Make Schema `.toObject()` and * `.toJSON()` parse getters for * proper JSON API response */ UserSchema.set('toObject', { getters: true }) UserSchema.set('toJSON', { getters: true }) UserSchema.options.toObject.transform = UserSchema.options.toJSON.transform = function (doc, ret) { // remove the hasn and salt of every document before returning the result delete ret.hash delete ret.salt } /** * -- Model's Plugin Extensions */ UserSchema.plugin(gravatar, { default: 'mm', secure: true }) UserSchema.plugin(passportLocalMongoose, { usernameField: 'email', attemptTooSoonError: 'signin.errors.too-many-attempts', tooManyAttemptsError: 'signin.errors.attempt-too-soon', incorrectPasswordError: 'signin.errors.incorrect-password', incorrectUsernameError: 'signin.errors.incorrect-username' }) /** * -- Model's API Extension */ /** * Get `fullName` from `firstName` and `lastName` * * @return {String} fullName * @api public */ UserSchema.virtual('fullName').get(function () { return this.firstName + ' ' + this.lastName }) /** * Get `displayName` from `firstName`, `lastName` and `<email>` if `config.publicEmails` === true * * @return {String} fullName * @api public */ UserSchema.virtual('displayName').get(function () { var displayName = this.fullName if (config.publicEmails && config.visibility === 'hidden' && this.email) { displayName += ' <' + this.email + '>' } return displayName }) /** * Get `staff` check from configured staff array * * @return {Boolean} staff * @api public */ UserSchema.virtual('staff').get(function () { var staff = config.staff || [] return !!~staff.indexOf(this.email) }) UserSchema.virtual('avatar').get(function () { return this.profilePictureUrl ? this.profilePictureUrl : this.gravatar({ default: 'mm', secure: true }) }) UserSchema.pre('save', function (next) { this.email = normalizeEmail(this.email) next() }) /** * Find `User` by its email * * @param {String} email * @return {Error} err * @return {User} user * @api public */ UserSchema.statics.findByEmail = function (email, cb) { return this.findOne({ email: normalizeEmail(email) }) .exec(cb) } /** * Find `User` by social provider id * * @param {String|Number} id * @param {String} social * @return {Error} err * @return {User} user * @api public */ UserSchema.statics.findByProvider = function (profile, cb) { var path = 'profiles.'.concat(profile.provider).concat('.id') var query = {} query[path] = profile.id return this.findOne(query) .exec(cb) } /** * Expose `User` Model */ module.exports = function initialize (conn) { return conn.model('User', UserSchema) }
JavaScript
0
@@ -408,25 +408,40 @@ type: String - +, maxlength: 100 %7D,%0A lastNam @@ -453,25 +453,40 @@ type: String - +, maxlength: 100 %7D,%0A usernam @@ -498,25 +498,40 @@ type: String - +, maxlength: 100 %7D,%0A locale: @@ -654,16 +654,33 @@ ps.email +, maxlength: 200 %7D, // m
ef14f6c8e8db5d1be017bfa5695deeb7ed885424
Make 'new-topic' notifications true by default
lib/models/user.js
lib/models/user.js
/** * Module dependencies. */ var config = require('lib/config'); var mongoose = require('mongoose'); var mongoUrl = config('mongoUsersUrl') || config('mongoUrl'); var conn = mongoose.createConnection(mongoUrl); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var passportLocalMongoose = require('passport-local-mongoose'); var gravatar = require('mongoose-gravatar'); var regexps = require('lib/regexps'); /** * Define `User` Schema */ var UserSchema = new Schema({ firstName: { type: String } , lastName: { type: String } , username: { type: String } , avatar: { type: String } , email: { type: String, lowercase: true, trim: true, match: regexps.email } // main email , emailValidated: { type: Boolean, default: false } , profiles: { facebook: { type: Object } , twitter: { type: Object } } , createdAt: { type: Date, default: Date.now } , updatedAt: { type: Date } , profilePictureUrl: { type: String } , disabledAt: { type: Date } , notifications: { replies: { type: Boolean, default: true }, "new-topic": { type: Boolean, default: false } } }); /** * Define Schema Indexes for MongoDB */ UserSchema.index({ createdAt: -1 }); UserSchema.index({ firstName: 1, lastName: 1 }); UserSchema.index({'notifications.replies': 1}); UserSchema.index({'notifications.new-topic': 1}); /** * Make Schema `.toObject()` and * `.toJSON()` parse getters for * proper JSON API response */ UserSchema.set('toObject', { getters: true }); UserSchema.set('toJSON', { getters: true }); UserSchema.options.toObject.transform = UserSchema.options.toJSON.transform = function(doc, ret, options) { // remove the hasn and salt of every document before returning the result delete ret.hash; delete ret.salt; } /** * -- Model's Plugin Extensions */ UserSchema.plugin(gravatar, { default: "mm" }); UserSchema.plugin(passportLocalMongoose, { usernameField: 'email', userExistsError: 'There is already a user using %s' }); /** * -- Model's API Extension */ /** * Get `fullName` from `firstName` and `lastName` * * @return {String} fullName * @api public */ UserSchema.virtual('fullName').get(function() { return this.firstName + ' ' + this.lastName; }); /** * Get `staff` check from configured staff array * * @return {Boolean} staff * @api public */ UserSchema.virtual('staff').get(function() { var staff = config.staff || []; return !!~staff.indexOf(this.email); }); /** * Find `User` by its email * * @param {String} email * @return {Error} err * @return {User} user * @api public */ UserSchema.statics.findByEmail = function(email, cb) { return this.findOne({ email: email }) .exec(cb); } /** * Find `User` by social provider id * * @param {String|Number} id * @param {String} social * @return {Error} err * @return {User} user * @api public */ UserSchema.statics.findByProvider = function(profile, cb) { var path = 'profiles.'.concat(profile.provider).concat('.id'); var query = {}; query[path] = profile.id; return this.findOne(query) .exec(cb); } /** * Expose `User` Model */ module.exports = conn.model('User', UserSchema);
JavaScript
0.011906
@@ -1110,28 +1110,27 @@ n, default: -fals +tru e %7D%0A %7D%0A%7D);%0A
89200842f1c992db941c16def3ba40bcf8cb14bc
Add —ignore-scripts when generating yarn.lock
lib/workers/branch/yarn.js
lib/workers/branch/yarn.js
const logger = require('../../logger'); const fs = require('fs'); const cp = require('child_process'); const tmp = require('tmp'); const path = require('path'); module.exports = { generateLockFile, getLockFile, maintainLockFile, }; async function generateLockFile( newPackageJson, npmrcContent, yarnrcContent, cacheFolder ) { logger.debug('Generating new yarn.lock file'); const tmpDir = tmp.dirSync({ unsafeCleanup: true }); let yarnLock; try { fs.writeFileSync(path.join(tmpDir.name, 'package.json'), newPackageJson); if (npmrcContent) { fs.writeFileSync(path.join(tmpDir.name, '.npmrc'), npmrcContent); } if (yarnrcContent) { fs.writeFileSync(path.join(tmpDir.name, '.yarnrc'), yarnrcContent); } logger.debug('Spawning yarn install'); const yarnOptions = ['install']; if (cacheFolder && cacheFolder.length) { logger.debug(`Setting yarn cache folder to ${cacheFolder}`); yarnOptions.push(`--cache-folder ${cacheFolder}`); } const result = cp.spawnSync('yarn', yarnOptions, { cwd: tmpDir.name, shell: true, }); logger.debug(String(result.stdout)); logger.debug(String(result.stderr)); yarnLock = fs.readFileSync(path.join(tmpDir.name, 'yarn.lock')); } catch (error) /* istanbul ignore next */ { try { tmpDir.removeCallback(); } catch (err2) { logger.warn(`Failed to remove tmpDir ${tmpDir.name}`); } throw error; } try { tmpDir.removeCallback(); } catch (err2) { logger.warn(`Failed to remove tmpDir ${tmpDir.name}`); } return yarnLock; } async function getLockFile( packageFile, packageContent, api, cacheFolder, yarnVersion ) { // Detect if a yarn.lock file is in use const yarnLockFileName = path.join(path.dirname(packageFile), 'yarn.lock'); if (!await api.getFileContent(yarnLockFileName)) { return null; } if (yarnVersion === '') { throw new Error(`Need to generate yarn.lock but yarn is not installed`); } // Copy over custom config commitFiles const npmrcContent = await api.getFileContent('.npmrc'); const yarnrcContent = await api.getFileContent('.yarnrc'); // Generate yarn.lock using shell command const newYarnLockContent = await module.exports.generateLockFile( packageContent, npmrcContent, yarnrcContent, cacheFolder ); // Return file object return { name: yarnLockFileName, contents: newYarnLockContent, }; } async function maintainLockFile(inputConfig) { logger.trace({ config: inputConfig }, `maintainLockFile`); const packageContent = await inputConfig.api.getFileContent( inputConfig.packageFile ); const yarnLockFileName = path.join( path.dirname(inputConfig.packageFile), 'yarn.lock' ); logger.debug(`Checking for ${yarnLockFileName}`); let existingYarnLock = await inputConfig.api.getFileContent( yarnLockFileName, inputConfig.branchName ); if (!existingYarnLock) { existingYarnLock = await inputConfig.api.getFileContent(yarnLockFileName); } logger.trace(`existingYarnLock:\n${existingYarnLock}`); if (!existingYarnLock) { return null; } logger.debug('Found existing yarn.lock file'); const newYarnLock = await module.exports.getLockFile( inputConfig.packageFile, packageContent, inputConfig.api, inputConfig.yarnCacheFolder ); logger.trace(`newYarnLock:\n${newYarnLock.contents}`); if (existingYarnLock.toString() === newYarnLock.contents.toString()) { logger.debug('Yarn lock file does not need updating'); return null; } logger.debug('Yarn lock needs updating'); return newYarnLock; }
JavaScript
0
@@ -825,16 +825,36 @@ install' +, '--ignore-scripts' %5D;%0A i
f7f3b48ca87e64f7a9a0b9359e8b3e8e6e15d014
Add the moduleOnly flag
lib/ngts-module.js
lib/ngts-module.js
#!/usr/bin/env node const program = require("commander"); const _ = require("lodash"); const utils = require("./utils"); var dest = ""; program .usage("<module-name> [options]") .arguments("<module-name>") .action(function (moduleName) { cmdModuleName = moduleName; }) .option("-a, --ctrl-alias <alias>", "Sets an alias for the controller. Defaults to vm.") .option("-m, --module-only", "Creates only the module.ts file.") .parse(process.argv); if (typeof cmdModuleName === "undefined") { console.log("You must specify a name for the module."); process.exit(1); } program.ctrlAlias = program.ctrlAlias || "vm"; cmdModuleName = utils.camelCase(cmdModuleName); dest = utils.hyphenate(cmdModuleName.concat("/")); var vals = { appName: utils.camelCase(utils.getAppName()), name: cmdModuleName, pName: utils.pascalCase(cmdModuleName), hName: utils.hyphenate(cmdModuleName), ctrlAlias: program.ctrlAlias, decoratorPath: utils.getDecoratorPath(dest), tplPath: utils.getRelativePath() }; if (program.moduleOnly) { var tpls = utils.readTemplate("module", "_name.ts"); } else { var tpls = utils.readTemplates("module"); } tpls = utils.compileTemplates(tpls, vals, cmdModuleName); utils.writeFiles(tpls, dest);
JavaScript
0
@@ -1048,16 +1048,61 @@ vePath() +,%0A moduleOnly: program.moduleOnly %7C%7C false %0A%7D;%0A%0Aif
8b54bdb7adf10c6e7ae84d664639f3d38ca5885e
Stop zipping stuff outside of node_modules. Fixes #22.
lib/ziputils.js
lib/ziputils.js
/* jshint node: true */ 'use strict'; var async = require('async'); var fs = require('fs'); var path = require('path'); var util = require('util'); var _ = require('underscore'); var zip = require('node-zip'); /* * Given a single buffer or string, create a ZIP file containing it * and return it as a Buffer. */ module.exports.makeOneFileZip = function(dirName, entryName, contents) { var arch = new zip(); if (dirName) { arch.folder(dirName).file(entryName, contents); } else { arch.file(entryName, contents); } return arch.generate({ type: 'nodebuffer', compression: 'DEFLATE' }); }; /* * Turn a whole directory into a ZIP, with entry names relative to the * original directory root. Do it asynchronously and return the result in the * standard (err, result) callback format. */ module.exports.zipDirectory = function(dirName, prefix, cb) { if (typeof prefix === 'function') { cb = prefix; prefix = undefined; } var pf = (prefix ? prefix : '.'); var arch = new zip(); zipDirectory(arch, dirName, pf, function(err) { if (err) { cb(err); } else { var contents = arch.generate({ type: 'nodebuffer', compression: 'DEFLATE' }); cb(undefined, contents); } }); }; function zipDirectory(baseArch, baseName, entryName, done) { // Create an object that is now relative to the last ZIP entry name var arch = baseArch.folder(entryName); fs.readdir(baseName, function(err, files) { if (err) { done(err); return; } // Iterate over each file in the directory async.eachSeries(files, function(fileName, itemDone) { var fn = path.join(baseName, fileName); fs.stat(fn, function(err, stat) { if (err) { itemDone(err); } else if (stat.isDirectory()) { // Recursively ZIP additional directories zipDirectory(arch, fn, fileName, itemDone); } else if (stat.isFile()) { // Aysynchronously read the file and store it in the ZIP. fs.readFile(fn, function(err, contents) { if (err) { itemDone(err); } else { arch.file(fileName, contents); itemDone(); } }); } }); }, function(err) { done(err); }); }); } /* * Given a base directory, produce a list of entries. Each entry has a name, * a fully-qualified path, and whether it is a directory. The base is * assumed to be a "resources" directory, and the "node" resources folder, * if present, will be treated specially using "enumerateNodeDirectory" below. */ module.exports.enumerateResourceDirectory = function(baseDir, remoteNpm) { var fileList = []; var types = fs.readdirSync(baseDir); _.each(types, function(type) { var fullName = path.join(baseDir, type); var stat = fs.statSync(fullName); if (stat.isDirectory()) { visitDirectory(fullName, fileList, '', '', type, (type === 'node'), remoteNpm); } }); return fileList; }; /* * Given a base directory, produce a list of entries. Each entry has a name, * a fully-qualified path, and whether it is a directory. This method has * special handling for the "node_modules" directory, which it will introspect * one level deeper. The result can be used to ZIP up a node.js "reources/node" * directory. */ module.exports.enumerateNodeDirectory = function(baseDir, remoteNpm) { var fileList = []; visitDirectory(baseDir, fileList, '', '', 'node', true, remoteNpm); return fileList; }; // Examine each file in the directory and produce a result that may be // used for resource uploading later. // Skip special files like symbolic links -- we can't handle them. function visitDirectory(dn, fileList, resourceNamePrefix, zipEntryPrefix, resourceType, isNode, remoteNpm) { var files = fs.readdirSync(dn); _.each(files, function(file) { var fullName = path.join(dn, file); var stat = fs.statSync(fullName); if (stat.isFile()) { fileList.push({ fileName: fullName, resourceType: resourceType, resourceName: resourceNamePrefix + file, zipEntryName: zipEntryPrefix + file }); } else if (stat.isDirectory()) { if (isNode && (file === 'node_modules')) { if (remoteNpm !== true) { // Special treatment for node_modules, to break them up into lots of smaller zips. // That is unless we are running NPM remotely. visitDirectory(fullName, fileList, 'node_modules_', 'node_modules/', resourceType, false, remoteNpm); } } else if (!/^\..+/.test(file)) { // Don't push directories that start with a "." like ".git"! fileList.push({ fileName: fullName, resourceType: resourceType, resourceName: resourceNamePrefix + file + '.zip', zipEntryName: zipEntryPrefix + file, directory: true }); } } }); return fileList; }
JavaScript
0
@@ -3334,16 +3334,17 @@ e.js %22re +s ources/n @@ -4677,24 +4677,16 @@ file)) %7B -%0A // Don' @@ -4739,16 +4739,236 @@ %22.git%22!%0A +%0A if (resourceNamePrefix !== 'node_modules_') %7B%0A var prefix = resourceNamePrefix + file + '/';%0A visitDirectory(fullName, fileList, prefix, '', resourceType, false, remoteNpm);%0A %7D else %7B%0A @@ -4975,32 +4975,34 @@ fileList.push(%7B%0A + file @@ -5021,32 +5021,34 @@ me,%0A + resourceType: re @@ -5063,32 +5063,34 @@ pe,%0A + + resourceName: re @@ -5127,32 +5127,34 @@ p',%0A + zipEntryName: zi @@ -5186,16 +5186,18 @@ + + director @@ -5204,24 +5204,34 @@ y: true %7D);%0A + %7D%0A %7D%0A
a9a22c7bf38c9d99205eac61e42c5483712239a1
refresh a little less
app/scripts/services/scheduledCache.js
app/scripts/services/scheduledCache.js
'use strict'; var angular = require('angular'); angular.module('deckApp') .factory('scheduledCache', function($cacheFactory, scheduler, $http) { // returns a cache that is cleared according to the scheduler var that = {}; function disposeAll() { Object.keys(that.schedules).forEach(function(k) { that.schedules[k].dispose(); }); } that.schedules = {}; that.cycles = 1; that.cache = $cacheFactory('scheduledHttp'); that.info = that.cache.info; that.put = function(k, v) { if (that.schedules[k]) { that.schedules[k].dispose(); } that.schedules[k] = scheduler.get() .skip(that.cycles) .subscribe(function() { $http.get(k).success(function(data) { that.cache.remove(k); that.cache.put(k,data); }); }); return that.cache.put(k,v); }; that.get = that.cache.get; that.remove = function(k) { that.cache.remove(k); }; that.removeAll = function() { disposeAll(); that.cache.removeAll(); }; that.destroy = function() { disposeAll(); that.cache.destroy(); delete that.cache; }; return that; });
JavaScript
0
@@ -416,16 +416,17 @@ les = 1 +0 ;%0A%0A t @@ -897,18 +897,16 @@ ;%0A %7D; - %0A%0A th
ac680bef9e6c92ca45eb71d6f6575d63f32fa757
Fix crash when movie had no gallery images
src/components/Movie.js
src/components/Movie.js
import React, { Component, PropTypes } from 'react'; import { Image, ScrollView, StyleSheet, Text, View } from 'react-native'; import moment from 'moment'; require('moment/locale/fi'); const styles = StyleSheet.create({ container: { margin: 20, paddingTop: 65, }, detail: { color: 'white', fontSize: 14, }, detailBold: { color: 'white', fontSize: 14, fontWeight: 'bold', }, originalTitle: { color: 'white', fontSize: 14, fontStyle: 'italic', }, section: { paddingBottom: 10, }, sectionTitle: { flex: 1, paddingBottom: 10, paddingLeft: 10, }, thumbnail: { height: 200, width: 296, }, thumbnailView: { paddingBottom: 10, }, title: { color: 'white', fontSize: 20, }, titleImage: { height: 146, width: 99, padding: 10, }, titleView: { flexDirection: 'row', flex: 1, paddingBottom: 10, }, }); export default class Movie extends Component { getActorList = () => { const actors = this.props.movie.Cast.Actor .map(actor => ` ${actor.FirstName} ${actor.LastName}`); return actors.toString().slice(1); } getDirectorList = () => { if (this.props.movie.Directors.Director.constructor === Array) { const directors = this.props.movie.Directors.Director .map(director => ` ${director.FirstName} ${director.LastName}`); return directors.toString().slice(1); } return ` ${this.props.movie.Directors.Director.FirstName} ${this.props.movie.Directors.Director.LastName}`; } getDuration = () => { const m = moment.duration(parseInt(this.props.movie.LengthInMinutes, 10), 'minutes'); return `${m.hours()} h ${m.minutes()} min`; } setUriAsHttps = () => this.props.movie.Images.EventSmallImagePortrait.replace(/^http:\/\//i, 'https://'); render() { return ( <ScrollView style={styles.container}> <View style={styles.titleView}> <Image style={styles.titleImage} source={{ uri: this.setUriAsHttps() }} /> <View style={styles.sectionTitle}> <Text style={styles.title}> {this.props.movie.Title} </Text> <Text style={styles.originalTitle}> {this.props.movie.OriginalTitle} </Text> <Text style={styles.originalTitle}> {this.props.movie.ProductionYear} </Text> </View> </View> <View style={styles.section}> <Text style={styles.detailBold}>{moment(this.props.show.dttmShowStart).format('HH:mm')} {this.props.show.Theatre} ({this.props.show.TheatreAuditorium})</Text> </View> <View style={styles.section}> <Text style={styles.detail}> Ensi-ilta: <Text style={styles.detailBold}> {moment(this.props.movie.dtLocalRelease).format('D.M.YYYY')}</Text> </Text> <Text style={styles.detail}> Kesto: <Text style={styles.detailBold}>{this.getDuration()}</Text> </Text> <Text style={styles.detail}>Ikäraja: <Text style={styles.detailBold}> {this.props.movie.RatingLabel}</Text> </Text> </View> <View style={styles.section}> <Text style={styles.detail}> Lajityyppi: {this.props.movie.Genres} </Text> <Text style={styles.detail}> Levittäjä: {this.props.movie.LocalDistributorName} </Text> </View> <View style={styles.section}> {this.props.movie.Directors.Director ? <Text style={styles.detail}> Ohjaus: <Text>{this.getDirectorList()}</Text> </Text> : null} {this.props.movie.Cast ? <Text style={styles.detail}> Pääosissa: {this.getActorList()} </Text> : null} </View> <View style={styles.section}> <Text style={styles.detail}> {this.props.movie.ShortSynopsis} </Text> </View> {this.props.movie.Gallery.GalleryImage.map((image, i) => <View key={i} style={styles.thumbnailView}> <Image style={styles.thumbnail} source={{ uri: image.Location }} /></View>)} </ScrollView> ); } } Movie.propTypes = { movie: PropTypes.object.isRequired, show: PropTypes.object.isRequired, };
JavaScript
0.000002
@@ -4113,16 +4113,66 @@ eryImage + ?%0A this.props.movie.Gallery.GalleryImage .map((im @@ -4188,24 +4188,26 @@ %3E%0A + + %3CView key=%7Bi @@ -4242,32 +4242,34 @@ w%7D%3E%0A + %3CImage%0A @@ -4265,32 +4265,34 @@ e%0A + + style=%7Bstyles.th @@ -4300,16 +4300,18 @@ mbnail%7D%0A + @@ -4361,16 +4361,18 @@ + + /%3E%3C/View @@ -4373,16 +4373,23 @@ %3C/View%3E) + : null %7D%0A%0A
2dd515eb1e043afa55bc0159a834e99e7effd30f
add iframe
src/components/comic.js
src/components/comic.js
var h = require('virtual-dom/h') module.exports = function (props) { let number = props.toString() while (number.length < 4) { number = '0' + number } return h('img', {src: `http://www.darthsanddroids.net/comics/darths${number}.jpg`}) }
JavaScript
0.000001
@@ -164,16 +164,31 @@ return +h('div', %5B%0A h('img', @@ -255,11 +255,98 @@ %7D.jpg%60%7D) +,%0A h('iframe', %7Bsrc: %60http://www.darthsanddroids.net/episodes/$%7Bnumber%7D.html%60%7D)%0A %5D) %0A%7D%0A
53ea60caeb815332a2738c0950d9d5710b017021
switch to manage state by react lifecycle, without redux
lib/views/Resume.js
lib/views/Resume.js
import React from 'react' import ReactDom from 'react-dom' import { Provider } from 'react-redux' import { createStore, applyMiddleware } from 'redux' import thunkMiddleware from 'redux-thunk' import { createLogger } from 'redux-logger' import { BrowserRouter } from 'react-router-dom' import JSON5 from 'json5' import routes from './routes' import fetchReducer from './reducers' import Container from './components/Container' import GetConfig from './containers/GetConfig' import '../../style/material.css' import '../../style/resume.css' const bootupData = document.getElementById('bootupData').textContent const Resume = () => { if (bootupData === "") { return( <BrowserRouter> <GetConfig /> </BrowserRouter> ) } else { return( <BrowserRouter> <GetConfig detail={JSON5.parse(bootupData)}/> </BrowserRouter> ) } } const loggerMiddleware = createLogger() let store = createStore( fetchReducer, applyMiddleware( thunkMiddleware, loggerMiddleware, ) ) ReactDom.render( <Provider store={store}> <Resume/> </Provider>, document.getElementById('root') )
JavaScript
0
@@ -48,24 +48,27 @@ 'react-dom'%0A +// import %7B Pro @@ -90,24 +90,27 @@ eact-redux'%0A +// import %7B cre @@ -150,16 +150,19 @@ 'redux'%0A +// import t @@ -195,16 +195,19 @@ -thunk'%0A +// import %7B @@ -318,16 +318,19 @@ json5'%0A%0A +// import r @@ -348,24 +348,27 @@ './routes'%0A%0A +// import fetch @@ -437,24 +437,27 @@ /Container'%0A +// import GetCo @@ -743,25 +743,25 @@ %3C -GetConfig +Container /%3E%0A @@ -869,25 +869,25 @@ %3C -GetConfig +Container detail= @@ -962,16 +962,19 @@ %7D%0A%7D%0A%0A +// const lo @@ -1006,16 +1006,19 @@ gger()%0A%0A +// let stor @@ -1030,24 +1030,27 @@ reateStore(%0A +// fetchRed @@ -1055,20 +1055,23 @@ educer,%0A +// + applyMid @@ -1079,16 +1079,19 @@ leware(%0A +// @@ -1103,24 +1103,27 @@ Middleware,%0A +// logg @@ -1136,22 +1136,28 @@ leware,%0A +// )%0A +// )%0A%0AReact @@ -1171,16 +1171,19 @@ der(%0A + // %3CProvid @@ -1217,20 +1217,24 @@ Resume/%3E +, %0A + // %3C/Provi
a948f2a43040f6d91c31fcadab5bec659db637fb
fix decorations
src/core/decoratable.js
src/core/decoratable.js
import stampit from 'stampit'; import {forEach, defaults} from 'lodash/fp'; import is from 'check-more-types'; const Decoratable = stampit({ props: { delegate: {} }, methods: { decorate (name, func, opts = {}) { if (is.array(name)) { forEach(value => this.decorate(value.name, value.func, value.opts), name); return this; } else if (is.object(name)) { forEach((value, key) => this.decorate(key, value), name); return this; } if (is.not.function(func)) { throw new Error('"func" must be a Function'); } opts = defaults({ args: [], context: this }, opts); this.delegate[name] = func.bind(opts.context, ...opts.args); return this; } } }); export default Decoratable;
JavaScript
0.000001
@@ -36,17 +36,8 @@ rt %7B -forEach, defa @@ -60,16 +60,48 @@ sh/fp';%0A +import %7BforEach%7D from 'lodash';%0A import i @@ -287,16 +287,32 @@ forEach( +name,%0A value =%3E @@ -365,24 +365,8 @@ pts) -,%0A name );%0A @@ -437,16 +437,22 @@ forEach( +name, (value, @@ -488,14 +488,8 @@ lue) -, name );%0A @@ -689,24 +689,108 @@ %7D, opts);%0A + // TODO: given an option, warn the user if a plugin blasts an existing plugin%0A this.d
0358d47357b4b7dcb527e04a20c9ae9f97bc2d1e
clean comment
lib/parse/index.js
lib/parse/index.js
var natural = require('natural'); var norm = require("node-normalizer"); var fs = require("fs"); var path = require("path"); var async = require("async"); var _ = require("underscore"); var checksum = require('checksum'); var mergex = require('deepmerge'); var facts = require("sfacts"); var sort = require("./sort"); var parseContents = require("./parsecontents"); var debug = require("debug")("Parse"); var dWarn = require("debug")("Parse:Warn"); var TfIdf = natural.TfIdf; natural.PorterStemmer.attach(); var topics = {}; var gambits = {}; var replys = {}; module.exports = function(factSystem) { var factSystem = (factSystem) ? factSystem : facts.create("systemDB") var merge = function(part1, part2, cb) { var result = {}; if (!_.isEmpty(part2)) { result = mergex(part1, part2); } else { result = part1; } cb(null, result) } // A path of files to load // Cache is a key:sum of files // callback when finished var loadDirectory = function(path, cache, callback) { var triggerCount = 0; var replyCount = 0; cache = cache || {}; if (_.isFunction(cache)) { callback = cache; cache = {}; } var startTime = new Date().getTime(); walk(path, function(err, files){ norm.loadData(function() { var toLoad = []; var that = this; var sums = {} var itor = function(file, next) { if (file.match(/\.(ss)$/i)) { checksum.file(file, function(err, sum){ sums[file] = sum; if (cache[file]) { if (cache[file] !== sum) { next(true); } else { next(false); } } else { next(true); } }); } else { next(false) } } async.filter(files, itor, function(toLoad){ async.map(toLoad, parseFiles(factSystem), function(err, res) { // for (var i = 0; i < res.length; i++) { // topicFlags = mergex(topicFlags, res[i].topicFlags); // gTopics = mergex(gTopics, res[i].gTopics); // gPrevTopics = mergex(gPrevTopics, res[i].gPrevTopics); // gKeywords = mergex(gKeywords, res[i].gKeywords); // triggerCount = triggerCount += res[i].gTriggerCount; // replyCount = replyCount += res[i].gReplyCount; // } // var data = { // gTopicFlags: topicFlags, // gTopics: gTopics, // gPrevTopics: gPrevTopics, // keywords:gKeywords, // // keywords: JSON.stringify(tfidf), // checksums: sums // } // var tfidf = new TfIdf(); // for (var topicName in gKeywords) { // if (gKeywords[topicName] != undefined) { // var kw = gKeywords[topicName].join(" "); // if (kw) { // debug("Adding ", kw , "to doc"); // tfidf.addDocument(kw.tokenizeAndStem(), topicName); // } // } // } for (var i = 0; i < res.length; i++) { topics = mergex(topics, res[i].topics); gambits = mergex(gambits, res[i].gambits); replys = mergex(replys, res[i].replys) } var data = { topics: topics, gambits: gambits, replys: replys, // keywords: JSON.stringify(tfidf), checksums: sums } var endTime = new Date().getTime(); var topicCount = Object.keys(topics).length; var gambitsCount = Object.keys(gambits).length; var replysCount = Object.keys(replys).length; console.log("Time to Process", (endTime - startTime) / 1000, "seconds"); console.log("Number of topics %s parsed.", topicCount); console.log("Number of gambits %s parsed.", gambitsCount); console.log("Number of replies %s parsed.", replysCount); if (data !== "") { if (topicCount == 0 && triggerCount == 0 && replyCount == 0) { callback(null, {}); } else { callback(null, data); } } else { callback(new Error("No data")); } }); }); }); }); } var parseFiles = function(facts) { return function(fileName, callback) { parseContents(norm)(fs.readFileSync(fileName, 'utf-8'), facts, callback); } } return { loadDirectory: loadDirectory, merge : merge, parseFiles: parseFiles, parseContents: parseContents(norm) } } var walk = function(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.forEach(function(file) { file = dir + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walk(file, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { results.push(file); if (!--pending) done(null, results); } }); }); }); };
JavaScript
0
@@ -1982,770 +1982,8 @@ %7B%0A%0A - // for (var i = 0; i %3C res.length; i++) %7B%0A // topicFlags = mergex(topicFlags, res%5Bi%5D.topicFlags);%0A // gTopics = mergex(gTopics, res%5Bi%5D.gTopics);%0A // gPrevTopics = mergex(gPrevTopics, res%5Bi%5D.gPrevTopics);%0A // gKeywords = mergex(gKeywords, res%5Bi%5D.gKeywords);%0A // triggerCount = triggerCount += res%5Bi%5D.gTriggerCount;%0A // replyCount = replyCount += res%5Bi%5D.gReplyCount;%0A // %7D%0A%0A // var data = %7B%0A // gTopicFlags: topicFlags,%0A // gTopics: gTopics,%0A // gPrevTopics: gPrevTopics,%0A // keywords:gKeywords,%0A // // keywords: JSON.stringify(tfidf),%0A // checksums: sums%0A // %7D%0A%0A @@ -2400,17 +2400,16 @@ // %7D%0A%0A -%0A
1864adb0ff21b4d829a9bd8633a4e7562721aa13
enable encodings per op in write-stream
lib/write-stream.js
lib/write-stream.js
/* Copyright (c) 2012-2013 LevelUP contributors * See list at <https://github.com/rvagg/node-levelup#contributing> * MIT +no-false-attribs License * <https://github.com/rvagg/node-levelup/blob/master/LICENSE> */ var Stream = require('stream').Stream , inherits = require('util').inherits , extend = require('xtend') , concatStream = require('concat-stream') , setImmediate = require('./util').setImmediate , getOptions = require('./util').getOptions function WriteStream (options, db) { Stream.call(this) this._options = getOptions(db, options) this._db = db this._buffer = [] this._status = 'init' this._end = false this.writable = true this.readable = false var ready = function () { if (!this.writable) return this._status = 'ready' this.emit('ready') this._process() }.bind(this) if (db.isOpen()) setImmediate(ready) else db.once('ready', ready) } inherits(WriteStream, Stream) WriteStream.prototype.write = function (data) { if (!this.writable) return false this._buffer.push(data) if (this._status != 'init') this._processDelayed() if (this._options.maxBufferLength && this._buffer.length > this._options.maxBufferLength) { this._writeBlock = true return false } return true } WriteStream.prototype.end = function() { setImmediate(function () { this._end = true this._process() }.bind(this)) } WriteStream.prototype.destroy = function() { this.writable = false this.end() } WriteStream.prototype.destroySoon = function() { this.end() } WriteStream.prototype.add = function(entry) { if (!entry.props) return if (entry.props.Directory) entry.pipe(this._db.writeStream(this._options)) else if (entry.props.File || entry.File || entry.type == 'File') this._write(entry) return true } WriteStream.prototype._processDelayed = function() { setImmediate(this._process.bind(this)) } WriteStream.prototype._process = function() { var buffer , entry , cb = function (err) { if (!this.writable) return if (this._status != 'closed') this._status = 'ready' if (err) { this.writable = false return this.emit('error', err) } this._process() }.bind(this) if (this._status != 'ready' && this.writable) { if (this._buffer.length && this._status != 'closed') this._processDelayed() return } if (this._buffer.length && this.writable) { this._status = 'writing' buffer = this._buffer this._buffer = [] if (buffer.length == 1) { entry = buffer.pop() if (entry.key !== undefined && entry.value !== undefined) this._db.put(entry.key, entry.value, cb) } else { this._db.batch(buffer.map(function (d) { return { type: 'put', key: d.key, value: d.value } }), cb) } if (this._writeBlock) { this._writeBlock = false this.emit('drain') } // don't allow close until callback has returned return } if (this._end && this._status != 'closed') { this._status = 'closed' this.writable = false this.emit('close') } } WriteStream.prototype._write = function (entry) { var key = entry.path || entry.props.path if (!key) return entry.pipe(concatStream(function (err, data) { if (err) { this.writable = false return this.emit('error', err) } if (this._options.fstreamRoot && key.indexOf(this._options.fstreamRoot) > -1) key = key.substr(this._options.fstreamRoot.length + 1) this.write({ key: key, value: data }) }.bind(this))) } WriteStream.prototype.toString = function () { return 'LevelUP.WriteStream' } module.exports.create = function (options, db) { return new WriteStream(options, db) }
JavaScript
0
@@ -2028,16 +2028,48 @@ , entry +%0A , options%0A , self = this %0A%0A , @@ -2749,16 +2749,298 @@ efined)%0A + options = %7B%0A keyEncoding: entry.keyEncoding%0A %7C%7C this._options.keyEncoding%0A , valueEncoding: entry.valueEncoding%0A %7C%7C entry.encoding%0A %7C%7C this._options.valueEncoding%0A %7D%0A @@ -3075,16 +3075,25 @@ y.value, + options, cb)%0A @@ -3165,16 +3165,28 @@ return %7B +%0A type: ' @@ -3189,16 +3189,27 @@ e: 'put' +%0A , key: d @@ -3212,16 +3212,27 @@ y: d.key +%0A , value: @@ -3239,16 +3239,262 @@ d.value +%0A , keyEncoding: d.keyEncoding%0A %7C%7C self._options.keyEncoding%0A , valueEncoding: d.valueEncoding%0A %7C%7C d.encoding%0A %7C%7C self._options.valueEncoding%0A %7D%0A
54a3b3940b4564b1c89122f68bc6a7bcd657ec3b
Remove double-conversion of BG from AR2 reporting
lib/plugins/ar2.js
lib/plugins/ar2.js
'use strict'; var _ = require('lodash'); var rawbg = require('./rawbg')(); function init() { function ar2() { return ar2; } ar2.label = 'AR2'; ar2.pluginType = 'forecast'; var BG_REF = 140; //Central tendency var BG_MIN = 36; //Not 39, but why? var BG_MAX = 400; var WARN_THRESHOLD = 0.05; var URGENT_THRESHOLD = 0.10; var ONE_HOUR = 3600000; var ONE_MINUTE = 60000; var FIVE_MINUTES = 300000; var TEN_MINUTES = 600000; ar2.checkNotifications = function checkNotifications(sbx) { var lastSGVEntry = _.last(sbx.data.sgvs); var result = {}; if (lastSGVEntry && Date.now() - lastSGVEntry.x < TEN_MINUTES) { result = ar2.forcastAndCheck(sbx.data.sgvs); } var usingRaw = false; if (!result.trigger && sbx.extendedSettings.useRaw) { var cal = _.last(sbx.data.cals); if (cal) { var rawSGVs = _.map(_.takeRight(sbx.data.sgvs, 2), function eachSGV (sgv) { var rawResult = rawbg.calc(sgv, cal); //ignore when raw is 0, and use BG_MIN if raw is lower var rawY = rawResult === 0 ? 0 : Math.max(rawResult, BG_MIN); return { x: sgv.x, y: rawY }; }); result = ar2.forcastAndCheck(rawSGVs, true); usingRaw = true; } } if (result.trigger) { var predicted = _.map(result.forecast.predicted, function(p) { return sbx.scaleBg(p.y) } ); var first = _.first(predicted); var last = _.last(predicted); var avg = _.sum(predicted) / predicted.length; var max = _.max([first, last, avg]); var min = _.min([first, last, avg]); var rangeLabel = ''; var eventName = ''; if (max > sbx.scaleBg(sbx.thresholds.bg_target_top)) { rangeLabel = 'HIGH'; eventName = 'high'; if (!result.pushoverSound) { result.pushoverSound = 'climb'; } } else if (min < sbx.scaleBg(sbx.thresholds.bg_target_bottom)) { rangeLabel = 'LOW'; eventName = 'low'; if (!result.pushoverSound) { result.pushoverSound = 'falling'; } } else { rangeLabel = 'Check BG'; } var title = sbx.notifications.levels.toString(result.level) + ', ' + rangeLabel; if (lastSGVEntry.y > sbx.thresholds.bg_target_bottom && lastSGVEntry.y < sbx.thresholds.bg_target_top) { title += ' predicted'; } if (usingRaw) { title += ' w/raw'; } var lines = sbx.prepareDefaultLines(sbx.data.lastSGV()); //insert prediction after the first line lines.splice( usingRaw ? 2 : 1 //if there's raw there will be an extra line after bg now , 0 , [usingRaw ? 'Raw BG' : 'BG', '15m:', sbx.scaleBg(predicted[2]), sbx.unitsLabel].join(' ') ); var message = lines.join('\n'); sbx.notifications.requestNotify({ level: result.level , title: title , message: message , eventName: eventName , pushoverSound: result.pushoverSound , plugin: ar2 , debug: { forecast: { predicted: _.map(result.forecast.predicted, function(p) { return sbx.scaleBg(p.y) } ).join(', ') } , thresholds: sbx.thresholds } }); } }; ar2.forcastAndCheck = function forcastAndCheck(sgvs, usingRaw) { var result = { forecast: ar2.forecast(sgvs) }; if (result.forecast.avgLoss > URGENT_THRESHOLD && !usingRaw) { result.trigger = true; result.level = 2; result.pushoverSound = 'persistent'; } else if (result.forecast.avgLoss > WARN_THRESHOLD) { result.trigger = true; result.level = 1; result.pushoverSound = 'persistent'; } return result; }; ar2.forecast = function forecast(sgvs) { var lastIndex = sgvs.length - 1; var result = { predicted: [] , avgLoss: 0 }; if (lastIndex < 1) { return result; } var current = sgvs[lastIndex].y; var prev = sgvs[lastIndex - 1].y; if (current >= BG_MIN && sgvs[lastIndex - 1].y >= BG_MIN) { // predict using AR model var lastValidReadingTime = sgvs[lastIndex].x; var elapsedMins = (sgvs[lastIndex].x - sgvs[lastIndex - 1].x) / ONE_MINUTE; var y = Math.log(current / BG_REF); if (elapsedMins < 5.1) { y = [Math.log(prev / BG_REF), y]; } else { y = [y, y]; } var n = Math.ceil(12 * (1 / 2 + (Date.now() - lastValidReadingTime) / ONE_HOUR)); var AR = [-0.723, 1.716]; var dt = sgvs[lastIndex].x; for (var i = 0; i <= n; i++) { y = [y[1], AR[0] * y[0] + AR[1] * y[1]]; dt = dt + FIVE_MINUTES; result.predicted[i] = { x: dt, y: Math.max(BG_MIN, Math.min(BG_MAX, Math.round(BG_REF * Math.exp(y[1])))) }; } // compute current loss var size = Math.min(result.predicted.length - 1, 6); for (var j = 0; j <= size; j++) { result.avgLoss += 1 / size * Math.pow(log10(result.predicted[j].y / 120), 2); } } return result; }; return ar2(); } function log10(val) { return Math.log(val) / Math.LN10; } module.exports = init;
JavaScript
0
@@ -2675,28 +2675,16 @@ '15m:', -sbx.scaleBg( predicte @@ -2687,17 +2687,16 @@ icted%5B2%5D -) , sbx.un
4e5de6703e72c3c5b19569b374b405199f018eb8
refactor query
lib/query/index.js
lib/query/index.js
'use strict'; var QUERIES = require('./constant').QUERIES , _ = require('../utils') , filter = require('./filter'); /** UserDefinedFunctions: -query for fn: connection .queryUserDefinedFunctions('dbs/b5NCAA==/colls/b5NCAIu9NwA=/', 'SELECT * FROM root r WHERE r.id=something') .toArray(console.log) - create user defined function: var inPre = { id: 'isIn', body: function(val, array) { return array.some(function(e) { return e == val }) } } connection.createUserDefinedFunction('dbs/b5NCAA==/colls/b5NCAIu9NwA=/', inPre, console.log) - use them: connection .queryDocuments('dbs/b5NCAA==/colls/b5NCAIu9NwA=/', 'SELECT * FROM root r WHERE isIn(3, r.arr)') .toArray(console.log) Operators: connection .queryDocuments('dbs/b5NCAA==/colls/b5NCAIu9NwA=/', 'SELECT * FROM root r WHERE r.age > 2', { enableScanInQuery: true }) .toArray(console.log) */ module.exports = function(object) { /** * @description * The stored UDF function * TODO: should returns as a => { UDF: [...], query: '...' }, if this query contains * one or more UDF function. else, should returns as a query string. */ var udfArray = []; /** * @description * query builder * @param {Object} object * @param {Boolean=} not * @returns {String} */ function query(object, not) { return _.keys(object).map(function(key) { if(key == '$not') return 'NOT(' + query(object[key], true) + ')'; if(key == '$nor') return query({ $not: { $or: object[key] } }); var value = object[key]; if(_.isObject(value)) { var fKey = _.first(_.keys(value)); // get the first key if(QUERIES[fKey]) { var val = QUERIES[fKey] , op = _.isObject(val) ? val.format : val; if(_.isObject(val)) udfArray.push({ id: val.name, body: val.func }); return filter.format(op, key, filter.toString(value[fKey])); } else if(~['$or', '$and'].indexOf(key)) { // if it's a conjunctive operator var cQuery = conjunctive(value, key.replace('$', '').toUpperCase()); // .. OR .. return (value.length > 1) && !not // Wrap with `NOT`, or single condition ? filter.wrap(cQuery, '(', ')') : cQuery; } else throw Error('invalid operator'); } else { return filter.format('r.{0}={1}', key, filter.toString(value)); } }).join(' AND '); } /** * @description * * @param array * @param operator * @returns {*} */ function conjunctive(array, operator) { return array.map(function(el) { var qStr = query(el); return _.keys(el).length > 1 ? filter.wrap(qStr, '(', ')') : qStr; }).join(' ' + operator + ' '); } /** * @returns the query results */ return query(object); };
JavaScript
0.978335
@@ -1378,72 +1378,108 @@ -if(key == '$not') return 'NOT(' + query(object%5Bkey%5D, true) + +var value = object%5Bkey%5D;%0A if(key == '$not') return filter.wrap(query(value, true), 'NOT(', ')' +) ;%0A @@ -1532,56 +1532,18 @@ or: -object%5Bkey%5D %7D %7D);%0A%0A var value = object%5Bkey%5D +value %7D %7D) ;%0A @@ -1616,29 +1616,60 @@ e)); - // get the first key +%0A // if it's a condition operator %7C%7C function %0A @@ -1750,26 +1750,8 @@ p = - _.isObject(val) ? val @@ -1762,16 +1762,16 @@ mat -: +%7C%7C val;%0A -%0A @@ -1917,16 +1917,60 @@ ey%5D));%0A%0A + // if it's a conjunctive operator%0A @@ -2015,42 +2015,8 @@ )) %7B - // if it's a conjunctive operator %0A @@ -2117,42 +2117,8 @@ -return (value.length %3E 1) && !not // W @@ -2149,24 +2149,68 @@ e condition%0A + return (value.length %3E 1) && !not%0A @@ -2322,18 +2322,9 @@ %7D - else %7B%0A +%0A @@ -2389,24 +2389,16 @@ alue));%0A - %7D%0A %7D).j @@ -2816,18 +2816,8 @@ ct);%0A%7D;%0A -%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A
492a42a5ef7c8801f0a397f6a567e1bc02fb1151
Rename variables in SchemaNode
lib/schema-node.js
lib/schema-node.js
const R = require('ramda') const {Maybe, Validation} = require('folktale/data') const {Success, Failure} = Validation const asArray = R.concat([]) const rejectNils = R.reject(R.isNil) const keysToGetters = R.compose(R.map(R.propOr(null)), R.keys) // TODO: Should live elsewhwere const required = (p) => (o) => o.hasOwnProperty(p) ? Success(o) : Failure([{'required': p}]) class SchemaNode { constructor ({env, schemaStack}) { // TODO: I don't think this should ever be empty. Verify. this.schema = R.head(schemaStack) this.env = env let toTypeValidators = R.compose(rejectNils, R.map((t) => env.types[t]), asArray) let toFormatValidators = R.compose(rejectNils, R.map((f) => env.formats[f]), asArray) let toRequiredValidators = R.compose(rejectNils, R.map((p) => required(p)), asArray) let stringConstraints = R.pick(R.keys(env.fieldValidate.string), this.schema) let stringValidators = R.values(R.mapObjIndexed((v, k) => env.fieldValidate.string[k](v), stringConstraints)) let numberConstraints = R.pick(R.keys(env.fieldValidate.number), this.schema) let numberValidators = R.values(R.mapObjIndexed((v, k) => env.fieldValidate.number[k](v, this.schema), numberConstraints)) let typeValidators, formatValidators, requiredValidators typeValidators = this.prop('type').map(toTypeValidators).getOrElse([]) formatValidators = this.prop('format').map(toFormatValidators).getOrElse([]) requiredValidators = this.prop('required').map(toRequiredValidators).getOrElse([]) this._validators = [].concat(typeValidators, formatValidators, requiredValidators, stringValidators, numberValidators) } prop (name) { return Maybe.fromNullable(R.prop(name, this.schema)) } combine (childFns) { let propertyPartials, propertySlice, propertyValidators let notPartials, notSlice, notValidators let count = 0 propertyPartials = this.prop('properties').map(keysToGetters).getOrElse([]) notPartials = this.prop('not').map(() => [ (m) => m.swap() ]).getOrElse([]) propertySlice = R.slice(count, count += propertyPartials.length, childFns) notSlice = R.slice(count, count += notPartials.length, childFns) propertyValidators = R.zipWith(R.compose, propertySlice, propertyPartials) notValidators = R.zipWith(R.compose, notPartials, notSlice) return this.validators.concat(propertyValidators, notValidators) } get validators () { return this._validators } get children () { let properties, not // FIXME Do we ever backtrack? Is schema stack needed? let collectChildren = R.map((s) => ({ env: this.env, schemaStack: [s] })) properties = this.prop('properties').map(R.compose(collectChildren, R.values)).getOrElse([]) not = this.prop('not').map(R.compose(collectChildren, asArray)).getOrElse([]) return [].concat(properties, not) } get isLeaf () { return this.children.length === 0 } } SchemaNode.from = (n) => new SchemaNode(n) module.exports = SchemaNode
JavaScript
0
@@ -825,37 +825,27 @@ t string -Constraints = R.pick( +Keywords = R.keys(e @@ -868,16 +868,66 @@ .string) +%0A let stringConstraints = R.pick(stringKeywords , this.s @@ -1063,32 +1063,23 @@ num -b er -Constraints = R.pick( +icKeywords = R.ke @@ -1106,16 +1106,68 @@ .number) +%0A let numericConstraints = R.pick(numericKeywords , this.s @@ -1180,27 +1180,28 @@ %0A let num -b er +ic Validators = @@ -1284,19 +1284,20 @@ ma), num -b er +ic Constrai @@ -1717,19 +1717,20 @@ ors, num -b er +ic Validato
ba65659797fafba3177d4aab3e3e35541730c423
Update smith-chart.js
lib/smith-chart.js
lib/smith-chart.js
// https://jsfiddle.net/b4ycbo4p/22/ function t (x, y) { return `translate(${x},${y})`; } function genSmithChart ($) { function pos (re, im) { const alfa = Math.atan(im / re); const x = re * (Math.cos(2 * alfa) - 1); const y = -re * Math.sin(2 * alfa); return [x, y]; } function ReLine (props) { const x = props.x; const y = props.y; const r = x; const [x0, y0] = pos(x, y); const flag = (x > y) ? 1 : 0; return $('path', { d: `M ${x0},${y0} A ${r} ${r} 0 ${flag} 0 ${x0},${-y0}` }); } function Re (props) { const r = props.r; return $('g', { transform: t(2 * r, r), className: 'l1' }, props.lines .map(desc => [r / (1 + desc[0]), r / (desc[1])]) .map(desc => $(ReLine, {x: desc[0], y: desc[1]})), $('circle', { cx: -r, r: r }) ); } function ImLine (props) { const y = props.y; const x = props.x; const r = props.r; console.log(y, r); const r0 = Math.abs(y); const r1 = props.r; const r2 = x * r; const sweep = (y > 0) ? 1 : 0; const [x0, y0] = pos(r2, y); const [x1, y1] = pos(r1, y); return $('path', { d: `M ${x0},${y0} A ${r0} ${r0} 0 0 ${sweep} ${x1},${y1}` }); } function Im (props) { const r = props.r; return $('g', { transform: t(2 * r, r), className: 'l1' }, props.lines .map(desc => [r / desc[0], 1 / (1 + desc[1])]) .map(desc => [ $(ImLine, {y: desc[0], x: desc[1], r: r}), $(ImLine, {y: -desc[0], x: desc[1], r: r}) ]), $('line', { x1: 0, y1: 0, x2: -2 * r, y2: 0, className: 'l1' }) ); } return function SmithChart(props) { const r = props.r; return $('div', {}, $('div', {}, 'Smith Chart'), $('div', {}, $('svg', { viewBox: [0, 0, 2 * r + 1, 2 * r + 1], height: r + 1, width: r + 1 }, $('defs', {}, $('style', {}, `.l1 { stroke: black; fill: none; stroke-linecap: round; /* butt; square; */ /* stroke-opacity: 0.1; */ }`) ), $('g', {transform: t(.5, .5)}, $(Re, {r: r, lines: [ [.05, .2], [.1, 1], [.15, .2], [.2, 2], [.3, 1], [.4, 2], [.5, 1], [.6, 2], [.7, 1], [.8, 2], [.9, 1], [1, 5], [1.2, 2], [1.4, 2], [1.6, 2], [1.8, 2], [2, 5], [3, 5], [4, 5], [5, 10], [10, 20], [20, 20] ]}), $(Im, {r: r, lines: [ [.05, .2], [.1, 1], [.15, .2], [.2, 2], [.3, 1], [.4, 2], [.5, 1], [.6, 2], [.7, 1], [.8, 2], [.9, 1], [1, 10], [1.2, 2], [1.4, 2], [1.6, 2], [1.8, 2], [2, 5], [3, 5], [4, 5], [5, 10], [10, 20], [20, 20] ]}) ) ) ) ); }; } module.exports = genSmithChart; // ReactDOM.render( // genSmithChart(React.createElement)({ r: 256 }), // document.getElementById('container') // );
JavaScript
0.000001
@@ -1860,24 +1860,128 @@ $('svg', %7B%0A + xmlns: 'http://www.w3.org/2000/svg',%0A 'xmlns:xlink': 'http://www.w3.org/1999/xlink',%0A %09vie
a4c275b30c4e7fba8322c7bcd4514172a0a62e3e
Fix for usage of create
src/createRepository.js
src/createRepository.js
/** @flow */ import {createModel} from './createModel' import type { InsertQuery, UpdateQuery, Repository, Manager, BaseRecord, TableMetadata, Model, Criteria, SelectQuery } from './types' export function createRepository<T: BaseRecord>(tableName: string, manager: Manager): Repository<T> { const repo = { async getMetadata(): Promise<TableMetadata> { await manager.getMetadataManager().ready() return manager.getMetadataManager().getColumns(tableName) }, find(id: number): Promise<Model<T> | null> { const query: SelectQuery<T> = this.startQuery() .where('id = ?', id) return query .execute() .then((result: Array<T>): Model<T> | null => result.length > 0 ? this.hydrate(result.pop(), true) : null) }, findOneBy(criteria: Criteria): Promise<Model<T> | null> { const query: SelectQuery<T> = this.startQuery() .limit(1) .criteria(criteria) return query .execute() .then((result: Array<T>): Model<T> | null => result.length > 0 ? this.hydrate(result.pop(), true) : null) }, findBy(criteria: Criteria, orderBy?: { [key: string]: string } = {}, limit?: number, offset?: number): Promise<Array<Model<T>>> { const query: SelectQuery<T> = this.startQuery() .criteria(criteria) limit && query.limit(limit) offset && query.offset(offset) return query.execute().then((result: Array<T>): Array<Model<T>> => result.map((entry: T): Model<T> => this.hydrate(entry, true))) }, startQuery(alias: ?string = null): SelectQuery<T> { return manager.startQuery() .select() .from(tableName, alias) .field(alias ? `${alias}.*` : '*') }, create<Q: T>(data: Q): Model<Q> { return this.hydrate(data) }, hydrate(data: T, fetched: boolean = false): Model<T> { return createModel(this, data, fetched) }, insert(data: T): Promise<number> { const query = manager.startQuery().insert() .into(tableName) Object.keys(data).forEach((key: string): InsertQuery => query.set(key, data[key])) return query.execute().then((result: any): number => result.insertId) }, update(selector: number | { [key: string]: any }, changes: { [key: string]: any }): Promise<number> { if (!selector || !changes) { throw new Error('Please check that you provide selector and changes for update') } if (typeof selector !== 'object') { selector = { id: selector } } const query = manager.startQuery().update() .criteria(selector) .table(tableName) Object.keys(changes).forEach((key: string): UpdateQuery => query.set(key, changes[key])) return query.execute().then((result: any): number => result.affectedRows) }, remove(selector: number | { [key: string]: any }): Promise<number> { if (!selector) { throw new Error('Please provide selector for remove') } if (typeof selector !== 'object') { selector = { id: selector } } const query = manager.startQuery().delete() .from(tableName) .criteria(selector) return query.execute().then((result: any): number => result.affectedRows) } } return repo }
JavaScript
0
@@ -1727,17 +1727,24 @@ %3E(data: -Q +any = %7B%7D ): Model
252daa0e1f9c0f000a5f1c60abf3b5bb29a8015b
fix for #53
src/directives/modal.js
src/directives/modal.js
import Load from '../util/load' export default { bind (el, binding, vnode) { Load.call(vnode.context, () => { if (el.nodeName === 'button') { el.setAttribute('data-target', binding.arg) } else { el.setAttribute('href', `#${binding.arg}`) } $(`#${binding.arg}`).modal(binding.value || {}) }) } }
JavaScript
0
@@ -116,16 +116,63 @@ () =%3E %7B%0A + const params = binding.value %7C%7C %7B%7D%0A @@ -265,16 +265,32 @@ ding.arg + %7C%7C params.value )%0A @@ -359,16 +359,32 @@ ding.arg + %7C%7C params.value %7D%60)%0A @@ -439,37 +439,34 @@ .arg -%7D%60).modal(binding.value %7C%7C %7B%7D + %7C%7C params.value%7D%60).modal( )%0A
819cd1d632a84249f8fb551efdb7e101a9b0c021
add e.preventDefault() to span selectstart
src/draggable-number.js
src/draggable-number.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.returnExports = factory(); } }(this, function () { var DraggableNumber = function(elements) { this.elements = elements; this.instances = []; this.init(); }; DraggableNumber.prototype = { constructor: DraggableNumber, init: function () { if (this.elements && this.elements instanceof Array === false && this.elements instanceof NodeList === false) { this.elements = [this.elements]; } for (var i = this.elements.length - 1; i >= 0; i--) { this.instances.push(new DraggableNumber.Element(this.elements[i])); } }, destroy: function () { for (var i = this.instances.length - 1; i >= 0; i--) { this.instances[i].destroy(); } } }; // Set some constants. DraggableNumber.MODIFIER_NONE = 0; DraggableNumber.MODIFIER_LARGE = 1; DraggableNumber.MODIFIER_SMALL = 2; // Utility function to replace .bind(this) since it is not available in all browsers. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; DraggableNumber.Element = function (input) { this.input = input; this.span = document.createElement("span"); this.isDragging = false; this.lastMousePosition = {x: 0, y: 0}; this.value = 0; // Minimum mouse movement before a drag start. this.dragThreshold = 10; // Store the original display style for the input and span. this.inputDisplayStyle = ""; this.spanDisplayStyle = ""; this.init(); }; DraggableNumber.Element.prototype = { constructor: DraggableNumber.Element, init: function () { // Get the inital value from the input. this.value = parseFloat(this.input.value, 10); // Add a span containing the value. Clicking on the span will show the // input. Dragging the span will change the value. this.addSpan(); // Save the original display style of the input and span. this.inputDisplayStyle = this.input.style.display; this.spanDisplayStyle = this.span.style.display; // Hide the input. this.input.style.display = 'none'; // Bind 'this' on event callbacks. this.onMouseUp = __bind(this.onMouseUp, this); this.onMouseMove = __bind(this.onMouseMove, this); this.onMouseDown = __bind(this.onMouseDown, this); this.onInputBlur = __bind(this.onInputBlur, this); this.onInputKeyDown = __bind(this.onInputKeyDown, this); // Add mousedown event handler. this.span.addEventListener('mousedown', this.onMouseDown, false); // Add key events on the input. this.input.addEventListener('blur', this.onInputBlur, false); this.input.addEventListener('keypress', this.onInputKeyDown, false); }, destroy: function () { if (this.span.parentNode) { this.span.parentNode.removeChild(this.span); } }, preventSelection: function (prevent) { var value = 'none'; if (prevent === false) { value = 'all'; } document.body.style['-moz-user-select'] = value; document.body.style['-webkit-user-select'] = value; document.body.style['-ms-user-select'] = value; document.body.style['user-select'] = value; }, addSpan: function () { var inputParent = this.input.parentNode; inputParent.insertBefore(this.span, this.input); this.span.innerHTML = this.value; // Add resize cursor. this.span.style.cursor = "col-resize"; this.span.addEventListener('selectstart', function() { return false; }); }, showInput: function () { this.input.style.display = this.inputDisplayStyle; this.span.style.display = 'none'; this.input.focus(); }, showSpan: function () { this.input.style.display = 'none'; this.span.style.display = this.spanDisplayStyle; }, onInputBlur: function (e) { this.value = parseFloat(this.input.value, 10); this.updateNumber(0); this.showSpan(); }, onInputKeyDown: function (e) { var keyEnter = 13; if (e.charCode == keyEnter) { this.input.blur(); } }, onMouseDown: function (e) { this.preventSelection(true); this.isDragging = false; this.lastMousePosition = {x: e.clientX, y: e.clientY * -1}; document.addEventListener('mouseup', this.onMouseUp, false); document.addEventListener('mousemove', this.onMouseMove, false); }, onMouseUp: function (e) { this.preventSelection(false); // If we didn't drag the span then we display the input. if (this.isDragging === false) { this.showInput(); } this.isDragging = false; document.removeEventListener('mouseup', this.onMouseUp, false); document.removeEventListener('mousemove', this.onMouseMove, false); }, hasMovedEnough: function (newMousePosition, lastMousePosition) { if (Math.abs(newMousePosition.x - lastMousePosition.x) >= this.dragThreshold || Math.abs(newMousePosition.y - lastMousePosition.y) >= this.dragThreshold) { return true; } return false; }, onMouseMove: function (e) { // Get the new mouse position. var newMousePosition = {x: e.clientX, y: e.clientY * -1}; if (this.hasMovedEnough(newMousePosition, this.lastMousePosition)) { this.isDragging = true; } // If we are not dragging don't do anything. if (this.isDragging === false) { return; } // Get the increment modifier. Small increment * 0.1, large increment * 10. var modifier = DraggableNumber.MODIFIER_NONE; if (e.shiftKey) { modifier = DraggableNumber.MODIFIER_LARGE; } else if (e.ctrlKey) { modifier = DraggableNumber.MODIFIER_SMALL; } // Calculate the delta with previous mouse position. var delta = this.getLargestDelta(newMousePosition, this.lastMousePosition); // Get the number offset. var offset = this.getNumberOffset(delta, modifier); // Update the input number. this.updateNumber(offset); // Save current mouse position. this.lastMousePosition = newMousePosition; }, getNumberOffset: function (delta, modifier) { var increment = 1; if (modifier == DraggableNumber.MODIFIER_SMALL) { increment *= 0.1; } else if (modifier == DraggableNumber.MODIFIER_LARGE) { increment *= 10; } // Negative increment if delta is negative. if (delta < 0) { increment *= -1; } return increment; }, updateNumber: function (offset) { this.value += offset; this.input.value = this.value; this.span.innerHTML = this.value; }, getLargestDelta: function (newPosition, oldPosition) { var result = 0; var delta = { x: newPosition.x - oldPosition.x, y: newPosition.y - oldPosition.y, }; if (Math.abs(delta.x) > Math.abs(delta.y)) { return delta.x; } else { return delta.y; } } }; this.DraggableNumber = DraggableNumber; return DraggableNumber; }));
JavaScript
0.000001
@@ -3971,20 +3971,49 @@ unction( +e ) %7B%0A + e.preventDefault();%0A
0295ac003ae02300ebc3069e6141e6610c919d93
Check for night evt type
lib/timeEmitter.js
lib/timeEmitter.js
'use babel'; import EventEmitter from 'events'; export default class TimeEmitter extends EventEmitter { constructor(dayTime, nightTime) { let curTime = new Date(); let msToDay = Math.abs(curTime - dayTime); let msToNight = Math.abs(curTime - nightTime); this.dayTimerId = setTimeout(() => this.emit('day'), msToDay); this.nightTimerId = setTimeout(() => this.emit('night'), msToNight); } snooze(evt, interval) { if (evt === 'day') this.dayTimerId = setTimeout(() => this.emit('day'), interval); else this.nightTimerId = setTimeout(() => this.emit('night'), interval); } dispose() { clearTimeout(this.dayTimerId); clearTimeout(this.nightTimerId); } }
JavaScript
0
@@ -536,16 +536,37 @@ else + if (evt === 'night') %0A t
85dee3ab93f3f8a46f211944cc81c92b8ce52189
Add mock json_decode
tests/js/twig/helpers/BaseTest.js
tests/js/twig/helpers/BaseTest.js
global._ = require('lodash'); global.fs = require('fs'); global.util = require('util'); global.path = require('path'); global.assert = require('chai').assert; global.expect = require('chai').expect; global.sinon = require('sinon'); global.moment = require('moment'); var Asserter = require('./Asserter'); var phpParser = require('phptoast').create(), phpToJS = require('phptojs'), phpRuntime = require('phpruntime/sync'); // Require the sync entrypoint so you can actually read the stack trace var timeNow = new Date('2016-01-01 12:00').getTime(); phpRuntime.install({ functionGroups: [ function (internals) { return { 'count': function (argReference) { var arrayValue = argReference.getValue(); return internals.valueFactory.createInteger(arrayValue.getLength()); }, 'time': function () { return internals.valueFactory.createInteger(timeNow/1000); }, 'date_default_timezone_set': function () { return null; } }; } ], classes: { 'DateTime': function () { function DateTime(time) { this.time = moment(time); } DateTime.prototype.setTimezone = function () {}; DateTime.prototype.__toJS = function () { return this.time.toDate(); }; return DateTime; }, 'DateTimeZone': function () { function DateTimeZone() {} return DateTimeZone; } } }); function BaseTest() { this.testsPath = path.resolve(__dirname + '/../../../unit/Jadu/Pulsar/Twig/Extension/'); this.injectionsPath = path.resolve(__dirname + '/../injections/'); this.asserter = new Asserter(this); } BaseTest.prototype.loadPreInjections = function () { var preInjectionsPath = path.resolve(this.injectionsPath + '/pre/'); var preInjections = fs.readdirSync(preInjectionsPath); var loadedPreInjections = {}; _.each(preInjections, function (injection) { var preInjectionPath = path.resolve(preInjectionsPath + '/' + injection); loadedPreInjections[injection] = fs.readFileSync(preInjectionPath).toString(); }); this.preInjections = loadedPreInjections; }; BaseTest.prototype.loadPostInjections = function () { var postInjectionsPath = path.resolve(this.injectionsPath + '/post/'); var postInjections = fs.readdirSync(postInjectionsPath); var loadedPostInjections = {}; _.each(postInjections, function (injection) { var postInjectionPath = path.resolve(postInjectionsPath + '/' + injection); loadedPostInjections[injection] = fs.readFileSync(postInjectionPath).toString(); }); this.postInjections = loadedPostInjections; }; BaseTest.prototype.loadInjections = function () { this.loadPreInjections(); this.loadPostInjections(); }; BaseTest.prototype.rewriteTest = function (test) { //Strip out the opening php tag test = test.replace(/^[\s]*\<\?php\n/, ''); var preInjections = ''; //Inject all pre injections _.each(this.preInjections, function (preInjection) { preInjections += preInjection; }); test = preInjections + test; //Reattach the opening php tag test = '<?php\n' + test; //Strip the closing brace on the class test = test.replace(/}[\s]*$/, ''); //Inject all post injections _.each(this.postInjections, function (postInjection) { test += postInjection; }); //Remove namespaces test = test.replace('namespace Jadu\\Pulsar\\Twig\\Extension;\n', ''); return test; }; BaseTest.prototype.calculateTestsToRun = function (test) { //Find tests to run by parsing the PHP file. //Uniter does not yet support class reflection. var testsToRun = []; var testNameRegex = /public function test([\S]*)\(\)/g; var testNames; while ((testNames = testNameRegex.exec(test)) !== null) { var testName = testNames[1]; testsToRun.push('test' + testName); } this.testsToRun = testsToRun; }; BaseTest.prototype.setTestName = function (testName) { this.nextTest = testName; }; BaseTest.prototype.run = function () { this.test = this.testName + '.php'; var testInstance = this; this.loadInjections(); var testPath = path.resolve(this.testsPath + '/' + this.test); var test = fs.readFileSync(testPath).toString(); this.calculateTestsToRun(test); test = this.rewriteTest(test); var wrapper = new Function('return ' + phpToJS.transpile(phpParser.parse(test), {bare: true}) + ';')(), module = phpRuntime.compile(wrapper), engine = module(); engine.getStdout().on('data', function (text) { console.log(text); }); engine.getStderr().on('data', function (text) { console.error('Bang:'); console.error(text); }); engine.expose(this.extension, 'javascriptExtension'); engine.expose(this.testName, 'testName'); engine.expose(this.testsToRun, 'tests'); engine.expose(this, 'nameSetter'); engine.expose(this.asserter, 'asserter'); sinon.useFakeTimers(timeNow); describe(this.testName, function () { engine.execute(); }); }; module.exports = BaseTest;
JavaScript
0.000066
@@ -1096,16 +1096,115 @@ n null;%0A + %7D,%0A 'json_decode': function (json) %7B%0A return '';%0A
dfecc7d1bf46262e2ed4872f533d76e6d5882108
use logger.debug
lib/trackfinder.js
lib/trackfinder.js
/* * trackfinder * https://github.com/goliatone/trackfinder * * Copyright (c) 2014 goliatone * Licensed under the MIT license. */ 'use strict'; var express = require('express'), debug = require('debug')('trackfinder'), //TODO: Use gextend! extend = require('extend'), _path = require('path'), fs = require('fs'); var DEFAULTS = { // path:'routes/**/*.js', config: {}, path: 'routes', mountpath: 'using', logger: console, priorityFilter:function(a, b) { return a.priority < b.priority ? -1 : 1; }, verbs: ['get', 'post', 'put', 'patch', 'delete'], filters: [ function(file) { return file === 'index.js'; } ] }; function TrackFinder() {} TrackFinder.DEFAULTS = DEFAULTS; TrackFinder.instance = function() { if (this._instance) return this._instance; this._instance = new TrackFinder(); return this._instance; }; TrackFinder.prototype.setOptions = function(options) { options || (options = {config: {}}); //TODO: Use gextend! extend(true, this, DEFAULTS, options); }; TrackFinder.prototype.addFileFilter = function(filter) { this.filters.push(filter); }; TrackFinder.prototype.filterFile = function(file) { return this.filters.some(function(filter) { return filter(file); }); }; TrackFinder.prototype.find = function() { var files = []; var route, name; //TODO: Figure out how to handle relative paths to doc var directory = _path.resolve(this.path); var fileFound = function(path, file) { if (this.filterFile(file)) return this.logger.info('Filtering', file); name = file.substr(0, file.indexOf('.')); this.logger.debug('scanning file: %s', name); /* * Dynamically include and initialize all route files. */ try { route = require(_path.join(path, name)); route._ref = name; files.push(route); } catch (e) { this.logger.error(e.message, e.stack); } }.bind(this); if (fs.existsSync(directory)) { fs.readdirSync(directory).forEach(fileFound.bind(this, directory)); } else if (fs.existsSync(directory + '.js')) { //TODO: Make this robust. Right now this is a weak solution to have it //working :/ fileFound('', directory + '.js'); } return files; }; TrackFinder.prototype.register = function(app, options) { this.setOptions(options); var config = this.config; var routeFiles = this.find(this.path); routeFiles.sort(this.priorityFilter); debug('LOAD FILES: %s', routeFiles); var router, args, routers = []; routeFiles.forEach(function(route) { args = []; router = express.Router(); debug('route: %s', route._ref); //Route can export namespace if (route.using) args.push(_get(route, this.mountpath)); args.push(router); if (_isFunction(route)) route(router, config, app); if (_isFunction(route.register)) route.register(router, config, app); if (route.routes) { var handler, verb, parameters, bits; Object.keys(route.routes).forEach(function(key) { handler = route.routes[key]; bits = key.split(' '); verb = bits[0].toLowerCase(); parameters = bits[1]; debug('verb %s, parameters %s', verb, parameters); router[verb].call(router, parameters, handler); }); } this.verbs.forEach(function(verb) { if (!_isFunction(route[verb])) return; router[verb].call(router, route.resource, route[verb]); }); app.use.apply(app, args); routers.push(router); }.bind(this)); // console.log('routes', app._router.stack) return routers; }; function _isFunction(fn) { return typeof fn === 'function'; } function _get(obj, prop) { if (typeof obj.prop === 'function'){ return obj[prop].call(obj); } return obj[prop]; } module.exports = TrackFinder.instance();
JavaScript
0.000001
@@ -181,53 +181,8 @@ '),%0A - debug = require('debug')('trackfinder'),%0A @@ -2554,24 +2554,36 @@ ilter);%0A +this.logger. debug('LOAD @@ -2743,24 +2743,36 @@ ();%0A +this.logger. debug('route @@ -3386,16 +3386,28 @@ +this.logger. debug('v
0d576e758332a634b7dac0043657756875dedfd3
Add tests for unreadMessagesClass
tests/unit/models/channel-test.js
tests/unit/models/channel-test.js
import { moduleFor, test } from 'ember-qunit'; moduleFor('model:channel', 'Unit | Model | channel'); test('it exists', function(assert) { let model = this.subject(); assert.ok(!!model); }); test('#slug', function(assert) { var model = this.subject(); model.set('name', '#kosmos-dev'); assert.ok(model.get('slug') === 'kosmos-dev'); }); test('#formattedTopic turns URLs into links', function(assert) { var channel = this.subject(); channel.set('topic', 'visit kosmos.org for more info'); assert.equal(channel.get('formattedTopic').toString(), 'visit <a href="https://kosmos.org" class="linkified" target="_blank" rel="nofollow">kosmos.org</a> for more info'); }); test('#formattedTopic escapes HTML', function(assert) { var channel = this.subject(); channel.set('topic', 'never gonna <marquee>give you up</marquee>'); assert.equal(channel.get('formattedTopic').toString(), 'never gonna &lt;marquee&gt;give you up&lt;/marquee&gt;'); });
JavaScript
0
@@ -336,32 +336,57 @@ mos-dev');%0A%7D);%0A%0A +//%0A// formattedTopic%0A//%0A%0A test('#formatted @@ -975,16 +975,1153 @@ quee&gt;');%0A%7D);%0A +%0A//%0A// unreadMessagesClass%0A//%0A%0Atest('#unreadMessagesClass is null when channel is visible', function(assert) %7B%0A var channel = this.subject();%0A channel.set('unreadMessages', true);%0A channel.set('visible', true);%0A%0A assert.equal(channel.get('unreadMessagesClass'), null);%0A%7D);%0A%0Atest('#unreadMessagesClass is null when channel has no unread messages', function(assert) %7B%0A var channel = this.subject();%0A channel.set('unreadMessages', false);%0A channel.set('visible', false);%0A%0A assert.equal(channel.get('unreadMessagesClass'), null);%0A%7D);%0A%0Atest('#unreadMessagesClass is correct for unread messages', function(assert) %7B%0A var channel = this.subject();%0A channel.set('unreadMessages', true);%0A channel.set('unreadMentions', false);%0A channel.set('visible', false);%0A%0A assert.equal(channel.get('unreadMessagesClass'), 'unread-messages');%0A%7D);%0A%0Atest('#unreadMessagesClass is correct for unread mentions', function(assert) %7B%0A var channel = this.subject();%0A channel.set('unreadMessages', true);%0A channel.set('unreadMentions', true);%0A channel.set('visible', false);%0A%0A assert.equal(channel.get('unreadMessagesClass'), 'unread-mentions');%0A%7D);%0A
b20b30a84f46d6c87bd574dedd882d18272de5ce
add parseSales support for mercenaries
lib/utils/utils.js
lib/utils/utils.js
'use strict'; const moment = require('moment'); const _ = require('lodash'); const rarityfilter = require('./filter/rarityfilter'); const logger = require('../logger'); const config = require('../../config'); module.exports = { /** * @function Parses the raw content of a sales file and returns a JSON array representation of the data for further use * @param {Array} rawSsales - sales array * @param {Object} articleHashMap - A hashmap of all articles mapped by their UUIDs (eg. <UUID> => {name: 'Argus, Herald of Doom', rarity: 'Legendary', ...}) * @returns {Array} - An array of sale objects ready to insert into the database */ parseSales: function(rawSales, articleHashMap) { const sales = [] rawSales.forEach((sale) => { sale.aa = false; // as default // try to map UUID to article const mappedArticle = articleHashMap[sale.uuid]; if (!mappedArticle) { logger.info(`Could not find article for UUID ${sale.uuid}`); return; } /* * First grab all article related data */ sale.name = mappedArticle.name; // CUSTOM NAME MAPPING // As of 2016-09-08 packs are now called '<Set name> <Booster|Primal> Pack', so we should map older names to // the new format if (sale.name.match(/^Set.*(Booster|Primal) Pack$/)) { sale.name = module.exports.mapSetName(sale.name); } // determine more properties if (mappedArticle.rarity === 'Epic') { sale.name = sale.name + ' AA'; sale.aa = true; } // Rarity sale.rarity = mappedArticle.rarity; // Set sale.set = mappedArticle.set_number.split('_').join(' '); // Type const type = mappedArticle.type; if (sale.name.match(/(Booster|Primal) Pack$/)) { sale.type = 'Pack'; } else if (type.indexOf('Equipment') !== -1) { sale.type = 'Equipment'; } else if (type.length !== 0 && type.indexOf("") === -1) { sale.type = 'Card'; } else { sale.type = 'Other'; } sales.push(sale); }); return sales; }, // /** // * @function Finds a numeric value for a string representation of a rarity to sort through it // * @param {string} rarity The rarity to find a numeric representation for // * @returns {integer} An integer representing the given rarity as a number // */ // getNumericRarity: function(rarity) { // switch (rarity) { // case 'Common': // return 2; // case 'Uncommon': // return 3; // case 'Rare': // return 4; // case 'Epic': // return 5; // case 'Legendary': // return 6; // case 'Normal': // return -1; // case 'Primal': // return -2; // default: // return 0; // } // }, capitalizeFirstLetter: function(string) { string = string.trim(); return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); }, mapSetName: function(string) { switch (string) { case 'Set 001 Booster Pack': return 'Shards of Fate Booster Pack'; case 'Set 001 Primal Pack': return 'Shards of Fate Primal Pack'; case 'Set 002 Booster Pack': return 'Shattered Destiny Booster Pack'; case 'Set 002 Primal Pack': return 'Shattered Destiny Primal Pack'; case 'Set 003 Booster Pack': return 'Armies of Myth Booster Pack'; case 'Set 003 Primal Pack': return 'Armies of Myth Primal Pack'; case 'Set 004 Booster Pack': return 'Primal Dawn Booster Pack'; case 'Set 004 Primal Pack': return 'Primal Dawn Primal Pack'; } } };
JavaScript
0
@@ -1819,47 +1819,127 @@ ype. -length !== 0 && type.indexOf(%22%22) === -1 +indexOf(%22Mercenary%22) !== -1) %7B%0A%09%09%09%09sale.type = 'Mercenary';%0A%09%09%09%7D else if (!sale.name.match(/(Stardust%7CTreasure Chest)/) ) %7B%0A @@ -1960,17 +1960,16 @@ = 'Card' -; %0A%09%09%09%7D el
1f3789f1bf0dc1f804d28dbe3912dd356a0adb11
Add view index.
lib/views/index.js
lib/views/index.js
module.exports = {};
JavaScript
0
@@ -11,11 +11,128 @@ orts = %7B +%0A CollectionPaginationView: require('./collection-pagination-view'),%0A CompositeView: require('./composite-view'),%0A%0A %7D;%0A
8a8bc72c392602284bd99e01f8ac1fa63d514594
refactor webpack-cli
lib/webpack-cli.js
lib/webpack-cli.js
const { resolve, parse, join } = require('path'); const { existsSync } = require('fs'); const GroupHelper = require('./utils/group-helper'); const Compiler = require('./utils/compiler'); const webpackMerge = require('webpack-merge'); class WebpackCLI extends GroupHelper { constructor() { super(); this.groupMap = new Map(); this.groups = []; this.processingErrors = []; } setMappedGroups(args, yargsOptions) { const { _all } = args; Object.keys(_all).forEach(key => { this.setGroupMap(key, _all[key], yargsOptions); }); } setGroupMap(key, val, yargsOptions) { const opt = yargsOptions.find(opt => opt.name === key); const groupName = opt.group; const namePrefix = groupName.slice(0, groupName.length - 9).toLowerCase(); if (this.groupMap.has(namePrefix)) { const pushToMap = this.groupMap.get(namePrefix); pushToMap.push({ [opt.name]: val }); } else { this.groupMap.set(namePrefix, [{ [opt.name]: val }]); } } checkDefaults(options, outputOptions) { if (Array.isArray(options)) { return options.map(opt => this.checkDefaults(opt, outputOptions)); } const defaultEntry = 'index'; const possibleFileNames = [ `./${defaultEntry}`, `./${defaultEntry}.js`, `${defaultEntry}.js`, defaultEntry, `./src/${defaultEntry}`, `./src/${defaultEntry}.js`, `src/${defaultEntry}.js` ]; if (options.entry && possibleFileNames.includes(options.entry)) { const absFilename = parse(options.entry); let tmpFileName = options.entry; if (absFilename.ext !== '.js') { tmpFileName += '.js'; } const normalizedEntry = resolve(tmpFileName); if (!existsSync(normalizedEntry)) { const parsedPath = parse(normalizedEntry); const possibleEntries = possibleFileNames.map(f => { return resolve(parsedPath.dir, f); }).filter(e => existsSync(e)); if (possibleEntries.length) { options.entry = possibleEntries[0]; } } } if(outputOptions.devtool) { options.devtool = outputOptions.devtool; } return options; } resolveGroups() { let mode; for (const [key, value] of this.groupMap.entries()) { const fileName = join(__dirname, 'groups', key); const GroupClass = require(fileName); if (key === 'config') { value.push({ mode: mode }); } const GroupInstance = new GroupClass(value); if (key === 'basic') { if (GroupInstance.opts.outputOptions.dev) { mode = 'dev'; } else { mode = 'prod'; } this.groups.push(GroupInstance); } else { this.groups.push(GroupInstance); } } } async runOptionGroups() { let groupResult = { options: {}, outputOptions: {}, processingErrors: [], }; const tmpGroupResult = this.groups.map(Group => Group.run()).filter(e => e); const resolvedResults = await Promise.all(tmpGroupResult); resolvedResults.forEach((e, idx) => { let groupObject = resolvedResults[idx + 1]; if (e.processingErrors) { groupResult.processingErrors = groupResult.processingErrors.concat(...e.processingErrors); } if (!groupObject) { groupObject = { outputOptions: {}, options: {} } } if (!groupObject.outputOptions) { groupObject.outputOptions = {}; } groupResult.outputOptions = Object.assign(groupObject.outputOptions, e.outputOptions); if (Array.isArray(e.options)) { const defaultArrayOptions = e.options.map(arrayConfigObject => { return webpackMerge(groupResult.options, arrayConfigObject); }) groupResult.options = defaultArrayOptions; return; } if (Array.isArray(groupResult.options)) { const defaultArrayOptions = groupResult.options.map(arrayConfigObject => { return webpackMerge(e.options, arrayConfigObject); }) groupResult.options = defaultArrayOptions; return; } groupResult.options = webpackMerge(groupResult.options, e.options); }); const wrappedConfig = require('./utils/zero-config')(groupResult); wrappedConfig.options = this.checkDefaults(wrappedConfig.options, wrappedConfig.outputOptions); return wrappedConfig; } async processArgs(args, yargsOptions) { await this.setMappedGroups(args, yargsOptions); await this.resolveGroups(); const groupResult = await this.runOptionGroups(); return groupResult; } async getCompiler(args, yargsOptions) { const groupResult = await this.processArgs(args, yargsOptions); return await Compiler.getCompiler(groupResult); } async run(args, yargsOptions) { const groupResult = await this.processArgs(args, yargsOptions); const webpack = await Compiler.webpackInstance(groupResult); return webpack; } async runCommand(command, ...args) { // TODO: rename and depreciate init if (command.name === 'create') { command.name = 'init'; } else if (command.name === 'loader') { command.name = 'generate-loader'; } else if (command.name === 'plugin') { command.name = 'generate-plugin'; } return await require('./commands/external').run(command.name, ...args); } runHelp(args) { const HelpGroup = require('./groups/help'); const Commands = require('./utils/commands').names; let command = null; args.forEach(arg => { if (Commands.includes(arg)) command = arg; }); return new HelpGroup().outputHelp(command); } runVersion() { const HelpGroup = require('./groups/help'); return new HelpGroup().outputVersion(); } } module.exports = WebpackCLI;
JavaScript
0.001531
@@ -6237,18 +6237,20 @@ -le +cons t comman @@ -6257,38 +6257,36 @@ d = -null;%0A args.forEach(arg +Object.keys(Commands).map( i =%3E @@ -6303,23 +6303,19 @@ if ( -Command +arg s.includ @@ -6321,28 +6321,73 @@ des( -arg)) command = arg; +Commands%5Bi%5D)) %7B%0A return Commands%5Bi%5D;%0A %7D %0A @@ -6385,32 +6385,35 @@ %7D%0A %7D) +%5B0%5D ;%0A return
a5bf7f15fd175097e6f21aa42dec4bbf04549372
Implement numbered lists formatting.
lib/writer/text.js
lib/writer/text.js
var assert = require('assert'); module.exports = function formatText(text, options) { assert(text.shift() == 'text'); var result = []; text.forEach(function(block) { result.push(formatBlock(block)); }); var output = result.join('\n\n') + '\n'; return output; }; function formatBlock(block) { var type = block.shift(); var attr = block.shift(); var prefix = repeat(' ', attr.level); switch (type) { case 'heading': return formatHeading(formatSpans(block), attr.level); case 'item': return formatSpans(block, prefix, repeat(' ', attr.level - 1) + ' * '); default: return formatSpans(block, prefix); }; }; function formatHeading(text, level) { switch (level) { case 1: return text + '\n' + repeat('=', text.length); case 2: return text + '\n' + repeat('-', text.length); default: return repeat('#', level) + ' ' + text; } }; function formatSpans(spans, prefix, firstPrefix) { prefix = prefix || ''; firstPrefix = firstPrefix || prefix; var maxLen = 80 - prefix.length; var lines = []; var line = ''; spans.forEach(function(span) { if (span[0] == 'break') { lines.push(line.trim() + ' '); line = ''; return; } var words = formatSpan(span).split(/(\S+\s+)/); words.forEach(function (word) { var joined = line + word; if (joined.length <= 80) { line = joined; } else { lines.push(line.trim()); line = word; } }); }); if (line.length > 0) lines.push(line.trim()); return firstPrefix + lines.join('\n' + prefix); }; function formatSpan(span) { var type = span.shift(); var text = span.shift(); assert(span.length == 0); switch (type) { case 'emph': return '*' + escape(text) + '*'; case 'strong': return '**' + escape(text) + '**'; case 'code': return '`' + escape(text) + '`'; case 'linktext': return '[' + escape(text) + ']'; case 'linkref': return '[' + escape(text) + ']'; case 'noteref': return '[^' + escape(text) + ']'; case 'url': return '<' + escape(text) + '>'; default: return escape(text); }; }; function escape(str) { return str. replace(/\\/g,'\\\\'). replace(/\*/g,'\\*'). replace(/`/g,'\\`'). replace(/\[/g,'\\['). replace(/\]/g,'\\]'). replace(/</g,'\\<'). replace(/>/g,'\\>'); }; function repeat(str, times) { return new Array(times+1).join(str); };
JavaScript
0.000001
@@ -134,16 +134,46 @@ t = %5B%5D;%0A + var numbers = %5B0, 0, 0, 0%5D;%0A text.f @@ -230,16 +230,25 @@ ck(block +, numbers ));%0A %7D) @@ -336,24 +336,33 @@ tBlock(block +, numbers ) %7B%0A var ty @@ -450,24 +450,186 @@ tr.level);%0A%0A + if (type === 'numitem') %7B%0A numbers%5Battr.level%5D++;%0A %7D%0A // reset numbers for all levels below%0A for (var i = attr.level+1; i %3C= 3; i++)%0A numbers%5Bi%5D = 0;%0A%0A switch (ty @@ -797,24 +797,233 @@ + ' * ');%0A + case 'numitem':%0A var number = numbers%5Battr.level%5D + '. ';%0A if (number.length %3C 4)%0A number = ' ' + number;%0A return formatSpans(block, prefix, repeat(' ', attr.level - 1) + number);%0A default:
88ff4dd4bfb55e4eb350db79450ccfcb86dc79a6
Fixed a string
modules/moderation/addRole.js
modules/moderation/addRole.js
/* * Copyright (C) 2017 Sankarsan Kampa * https://sankarsankampa.com/contact * * This file is a part of Bastion Discord BOT. * https://github.com/snkrsnkampa/Bastion * * This code is licensed under the SNKRSN Shared License. It is free to * download, copy, compile, use, study and refer under the terms of the * SNKRSN Shared License. You can modify the code only for personal or * internal use only. However, you can not redistribute the code without * explicitly getting permission fot it. * * Bastion BOT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY. See the SNKRSN Shared License for * more details. * * You should have received a copy of the SNKRSN Shared License along * with this program. If not, see <https://github.com/snkrsnkampa/Bastion/LICENSE>. */ const sql = require('sqlite'); sql.open('./data/Bastion.sqlite'); exports.run = (Bastion, message, args) => { if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) return Bastion.log.info('You don\'t have permissions to use this command.'); if (args.length < 1) { return message.channel.sendMessage('', {embed: { color: Bastion.colors.yellow, title: 'Usage', description: `\`${Bastion.config.prefix}${this.help.usage}\`` }}).catch(e => { Bastion.log.error(e.stack); }); } if (!(user = message.mentions.users.first())) { user = message.author; role = args.join(' '); } else { role = args.slice(1).join(' '); } role = message.guild.roles.find('name', role); if (role == null) { return message.channel.sendMessage('', {embed: { color: Bastion.colors.red, description: 'No role found with that name.' }}).catch(e => { Bastion.log.error(e.stack); }); } message.guild.members.get(user.id).addRole(role).then(() => { message.channel.sendMessage('', {embed: { color: Bastion.colors.green, title: 'Role Added', description: `**${user.username}**#${user.discriminator} has now been given **${role.name}** role.`, }}).catch(e => { Bastion.log.error(e.stack); }); sql.get(`SELECT modLog, modLogChannelID, modCaseNo FROM guildSettings WHERE guildID=${message.guild.id}`).then(row => { if (!row) return; if (row.modLog == 'true') { message.guild.channels.get(row.modLogChannelID).sendMessage('', {embed: { color: Bastion.colors.green, title: 'Role Added', description: `Case Number: ${row.modCaseNo}`, fields: [ { name: 'User', value: `${user}`, inline: true }, { name: 'User ID', value: user.id, inline: true }, { name: 'Reason', value: role.name }, { name: 'Responsible Moderator', value: `${message.author}`, inline: true }, { name: 'Moderator ID', value: message.author.id, inline: true } ] }}).then(msg => { sql.run(`UPDATE guildSettings SET modCaseNo=${parseInt(row.modCaseNo)+1} WHERE guildID=${message.guild.id}`).catch(e => { Bastion.log.error(e.stack); }); }).catch(e => { Bastion.log.error(e.stack); }); } }).catch(e => { Bastion.log.error(e.stack); }); }).catch(e => { Bastion.log.error(e.stack); message.channel.sendMessage('', {embed: { color: Bastion.colors.red, description: 'I don\'t have enough permission to do that operation.' }}).catch(e => { Bastion.log.error(e.stack); }); }); }; exports.config = { aliases: ['ar'] }; exports.help = { name: 'addrole', description: 'Adds a mentioned user to the given role. If no user is mentioned, adds you to the given role.', permission: 'Manage Roles', usage: 'addRole [@user-mention] <Role Name>', example: ['addRole @user#001 Role Name', 'addRole Role Name'] };
JavaScript
0.999997
@@ -2919,13 +2919,11 @@ : 'R -eason +ole ',%0D%0A
75235047e35c8c166ca857bb17fd54f2d27ec98b
Remove extra abstraction over cache
init/LoaderImpl.js
init/LoaderImpl.js
(function (global, globalEval) { var Deferred; Deferred = getDeferredImpl; LoaderImpl = function LoaderImpl (parent, options) { // TODO: inherit from parent this._cache = createCache(); }; LoaderImpl.prototype = { global: global, strict: true, "eval": function (source) { return globalEval(source, this.global); }, evalAsync: function (source, callback, errback) { if (!callback) callback = noop; try { callback(this.eval(source)); } catch (ex) { if (arguments.length > 1) errback(ex); else throw ex; } }, // TODO... load: function (idOrArray, callback, errback) { }, "import": function () {}, get: function () {}, has: function () {}, set: function () {}, "delete": function () {} }; System.set('beck/init/LoaderImpl', ToModule(LoaderImpl)); function createCache (seed) { // TODO: inherit from seed var cache = {}; return { get: function (id) { return cache[id]; }, set: function (id, thing) { return cache[id] = thing; }, has: function (id) { return id in cache; } }; } function getDeferredImpl () { Deferred = System.get('beck/lib/Deferred'); return new Deferred(); } function noop () {} }( typeof global == 'object' ? global : this.window || this.global || {}, function () { return (1, eval).call(arguments[1], arguments[0]); } ));
JavaScript
0.000001
@@ -78,21 +78,8 @@ ;%0A%0A%09 -LoaderImpl = func @@ -129,24 +129,30 @@ DO: inherit +cache from parent%0A @@ -162,17 +162,16 @@ his. -_ cache = crea @@ -170,26 +170,14 @@ e = -createCache() +%7B%7D ;%0A%09%7D -; %0A%0A%09L @@ -655,42 +655,63 @@ on ( -) %7B%7D,%0A%09%09has: function () %7B +name) %7B%0A%09%09%09return this.cache%5BString(name)%5D;%0A%09%09 %7D,%0A +%0A %09%09 -set +has : fu @@ -722,200 +722,63 @@ on ( +name ) %7B -%7D, %0A%09%09 -%22delete%22: function () %7B%7D%0A%0A%09%7D;%0A%0A%09System.set('beck/init/LoaderImpl', ToModule(LoaderImpl));%0A%0A%09function createCache (seed) %7B%0A%09%09// TODO: inherit from seed%0A%09%09var cache = %7B%7D;%0A%09%09return %7B%0A%09%09%09g +%09return String(name) in this.cache;%0A%09%09%7D,%0A%0A%09%09s et: @@ -791,41 +791,81 @@ on ( -id) %7B return cache%5Bid%5D; +name, thing) %7B%0A%09%09%09cache%5BString(name)%5D = ToModule(thing);%0A%09%09 %7D,%0A +%0A %09%09 -%09set +%22delete%22 : fu @@ -876,103 +876,115 @@ on ( -id, thing) %7B return cache%5Bid%5D = thing; %7D,%0A%09%09%09has: function (id) %7B return id in cache; %7D%0A%09%09%7D;%0A%09%7D +name) %7B%0A%09%09%09delete cache%5BString(name)%5D;%0A%09%09%7D%0A%0A%09%7D;%0A%0A%09System.set('beck/init/LoaderImpl', ToModule(LoaderImpl)); %0A%0A%09f
9a283637ece1252e2145d5d01c5286a084f97c3c
Remove Cache
sw.js
sw.js
importScripts('serviceworker-cache-polyfill.js'); var CACHE_NAME = 'simple-pwa-v2'; // File want to cache var urlsToCache = [ './', './index.html', './manifest.json', './serviceworker-cache-polyfill.js', './src/assets/img/blank-thumbnail.png', './src/assets/img/favicon.png', './src/assets/img/icon-48.png', './src/assets/img/icon-96.png', './src/assets/img/icon-128.png', './src/assets/img/icon-144.png', './src/assets/img/icon-152.png', './src/assets/img/icon-196.png', './src/assets/img/icon-384.png', './src/vendor/bootstrap/css/bootstrap.min.css', './src/vendor/ionicons/css/ionicons.min.css', './src/vendor/ionicons/fonts/ionicons.ttf', './src/vendor/ionicons/fonts/ionicons.woff', './build/build.css', './build/main.js', // './build/1.js', // './build/2.js' ]; // Set the callback for the install step self.oninstall = function (e) { console.log('[serviceWorker]: Installing...'); // perform install steps e.waitUntil( caches.open(CACHE_NAME) .then(function (cache) { console.log('[serviceWorker]: Cache All'); return cache.addAll(urlsToCache); }) .then(function () { console.log('[serviceWorker]: Intalled And Skip Waiting on Install'); return self.skipWaiting(); }) ); }; self.onfetch = function (e) { console.log('[serviceWorker]: Fetching ' + e.request.url); var raceUrl = 'API/'; if(e.request.url.indexOf(raceUrl) > -1){ e.respondWith( caches.open(CACHE_NAME).then(function (cache) { return fetch(e.request).then(function (res) { cache.put(e.request.url, res.clone()); return res; }).catch(err => { console.log('[serviceWorker]: Fetch Error ' + err); }); }) ); } else if (e.request.url.indexOf('src/assets/img-content') > -1) { e.respondWith( caches.match(e.request).then(function (res) { if(res) return res return fetch(e.request.clone(), { mode: 'no-cors' }).then(function (newRes) { if(!newRes || newRes.status !== 200 || newRes.type !== 'basic') { return newRes; } caches.open(CACHE_NAME).then(function (cache) { cache.put(e.request, newRes.clone()); }).catch(err => { console.log('[serviceWorker]: Fetch Error ' + err); }); return newRes; }); }) ); } else { e.respondWith( caches.match(e.request).then(function (res) { return res || fetch(e.request) }) ); } }; self.onactivate = function (e) { console.log('[serviceWorker]: Actived'); var whiteList = ['simple-pwa-v2']; e.waitUntil( caches.keys().then(function (cacheNames) { return Promise.all( cacheNames.map(function (cacheName) { if (whiteList.indexOf(cacheName) === -1) { return caches.delete(cacheName); } }) ) }).then(function () { console.log('[serviceWorker]: Clients Claims'); return self.clients.claim(); }) ); };
JavaScript
0.000001
@@ -65,28 +65,28 @@ AME = 's -imple-pwa-v2 +tatistika-v1 ';%0A%0A// F @@ -2662,20 +2662,20 @@ %5B's -imple-pwa-v2 +tatistika-v1 '%5D;%0A
a309bd26e83c121c0ac3f150735f5ae2ed347a30
Add import/extensions for TS
ts.js
ts.js
let base = require('./') module.exports = { ...base, parser: '@typescript-eslint/parser', parserOptions: { tsconfigRootDir: process.cwd(), project: ['./tsconfig.json'] }, plugins: [...base.plugins, '@typescript-eslint'], overrides: [ ...base.overrides, { files: ['*.{ts,tsx}'], rules: { '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', '@typescript-eslint/no-unnecessary-type-assertion': 'error', '@typescript-eslint/adjacent-overload-signatures': 'error', '@typescript-eslint/lines-between-class-members': [ 'error', 'always', { exceptAfterSingleLine: true } ], '@typescript-eslint/space-before-function-paren': ['error', 'always'], '@typescript-eslint/strict-boolean-expressions': 'error', '@typescript-eslint/prefer-namespace-keyword': 'error', '@typescript-eslint/no-unnecessary-condition': 'error', '@typescript-eslint/type-annotation-spacing': 'error', '@typescript-eslint/member-delimiter-style': [ 'error', { multiline: { delimiter: 'none' }, singleline: { delimiter: 'comma' } } ], '@typescript-eslint/restrict-plus-operands': 'error', '@typescript-eslint/no-useless-constructor': 'error', '@typescript-eslint/prefer-optional-chain': 'error', '@typescript-eslint/no-dupe-class-members': 'error', '@typescript-eslint/no-use-before-define': [ 'error', { functions: false, classes: false, variables: false } ], '@typescript-eslint/no-empty-interface': 'error', '@typescript-eslint/unified-signatures': 'error', '@typescript-eslint/func-call-spacing': ['error', 'never'], '@typescript-eslint/no-invalid-this': 'error', '@typescript-eslint/no-for-in-array': 'error', '@typescript-eslint/no-var-requires': 'error', '@typescript-eslint/no-explicit-any': 'error', '@typescript-eslint/await-thenable': 'error', '@typescript-eslint/dot-notation': [ 'error', { allowKeywords: true } ], '@typescript-eslint/no-unused-expressions': [ 'error', { allowShortCircuit: true, allowTernary: true, allowTaggedTemplates: true } ], '@typescript-eslint/array-type': 'error', 'lines-between-class-members': 'off', 'no-useless-constructor': 'off', 'no-unused-expressions': 'off', 'no-dupe-class-members': 'off', 'no-use-before-define': 'off', 'func-callspacing': 'off', 'no-invalid-this': 'off', 'no-unused-vars': 'off', 'dot-notation': 'off' } }, { files: '*.test.{ts,tsx}', rules: { '@typescript-eslint/no-explicit-any': 'off' } } ] }
JavaScript
0
@@ -2671,16 +2671,93 @@ rror',%0A%0A + 'import/extensions': %5B'error', 'always', %7B ignorePackages: true %7D%5D,%0A%0A
f67aae59e9928a632494849c57bab3635908e2b7
Add karma
joce/karma.conf.js
joce/karma.conf.js
'use strict'; // Karma configuration module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // Frameworks to use frameworks: ['jasmine'], // 'ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils' // List of files / patterns to load in the browser files: [ <!-- injector:bowerjs --> 'app/lib/jquery/dist/jquery.js', 'app/lib/bootstrap/dist/js/bootstrap.js', 'app/lib/angular/angular.js', 'app/lib/angular-resource/angular-resource.js', 'app/lib/angular-mocks/angular-mocks.js', 'app/lib/angular-cookies/angular-cookies.js', 'app/lib/angular-animate/angular-animate.js', 'app/lib/angular-touch/angular-touch.js', 'app/lib/angular-sanitize/angular-sanitize.js', 'app/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'app/lib/angular-ui-utils/ui-utils.js', 'app/lib/angular-ui-router/release/angular-ui-router.js', <!-- endinjector --> 'app/js/config.js', 'app/js/application.js', 'app/modules/*/*.js', 'app/modules/*/config/*.js', 'app/modules/*/services/*.js', 'app/modules/*/controllers/*.js', 'app/modules/*/directives/*.js', 'app/modules/*/filters/*.js', 'app/modules/*/tests/unit/**/*.js' ], // Test results reporter to use // Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' //reporters: ['progress'], reporters: ['progress'], // 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, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['PhantomJS'], // If browser does not capture in given timeout [ms], kill it captureTimeout: 60000, // Continuous Integration mode // If true, it capture browsers, run tests and exit singleRun: true }); };
JavaScript
0.999609
@@ -1135,24 +1135,76 @@ router.js',%0A + 'app/lib/ngCordova/dist/ng-cordova.js',%0A
5bb04806fbdb085b81266db6b9c24e20c1b4b225
Revert "Kaas"
js/entities/HUD.js
js/entities/HUD.js
/** * a HUD container kaas */ game.HUD = game.HUD || {}; game.HUD.Container = me.ObjectContainer.extend({ init : function () { this.parent(); this.isPersistent = true; this.collidable = false; this.z = Infinity; this.name = "HUD"; this.addButton(); }, remove : function () { me.game.remove(this); }, addButton : function () { this.addChild(new game.HUD.InventoryButton(1024 - 256 , 768 - 128, {spritewidth: 256,spriteheight: 128})); }, addTextfield : function () { this.addChild(new game.HUD.Textfield(1000, 440)); } }); /** * A simple Button to load the inventory */ game.HUD.InventoryButton = me.ObjectEntity.extend({ init : function (x, y, settings) { this.parent(x, y, settings); this.keyLock = true; this.floating = true; this.imgButton = new me.AnimationSheet(this.pos.x, this.pos.y, me.loader.getImage("inventoryButton"), 256, 128); }, update : function () { this.imgButton.setAnimationFrame(0); if (this.containsPoint(me.input.mouse.pos.x, me.input.mouse.pos.y) && me.input.isKeyPressed("mouse/touch") && !this.keyLock) { this.keyLock = true; game.play.HUD.remove(); game.play.addInventory(); me.game.remove(this); } if (!me.input.isKeyPressed("mouse/touch")) { this.keyLock = false; } return true; }, draw : function (context) { this.imgButton.draw(context); } }); game.HUD.Textfield = me.Renderable.extend({ init : function (x, y) { this.parent(new me.Vector2d(x, y), 10, 10 ); this.font = new me.BitmapFont("font", 32); this.font.set("right"); this.textDisplay; this.floating = false; }, update : function () { if(this.textDisplay !== game.data.drawText) { this.textDisplay = game.data.drawText; return true; } return false; }, draw : function (context){ this.font.draw(context, game.data.drawText, this.pos.x , this.pos.y); } });
JavaScript
0
@@ -19,13 +19,8 @@ iner - kaas %0A */
5b7f342cbd8e9e5bae3f4c58cd50f8e5ff3efcab
Update game_manager.js
js/game_manager.js
js/game_manager.js
function GameManager(size, InputManager, Actuator, ScoreManager) { this.size = size; // Size of the grid this.inputManager = new InputManager; this.scoreManager = new ScoreManager; this.actuator = new Actuator; this.startTiles = 2; this.inputManager.on("move", this.move.bind(this)); this.inputManager.on("restart", this.restart.bind(this)); this.inputManager.on("keepPlaying", this.keepPlaying.bind(this)); this.setup(); } // Restart the game GameManager.prototype.restart = function () { this.actuator.continue(); this.setup(); }; // Keep playing after winning GameManager.prototype.keepPlaying = function () { this.keepPlaying = true; this.actuator.continue(); }; GameManager.prototype.isGameTerminated = function () { if (this.over || (this.won && !this.keepPlaying)) { return true; } else { return false; } }; // Set up the game GameManager.prototype.setup = function () { this.grid = new Grid(this.size); this.score = 0; this.over = false; this.won = false; this.keepPlaying = false; // Add the initial tiles this.addStartTiles(); // Update the actuator this.actuate(); }; // Set up the initial tiles to start the game with GameManager.prototype.addStartTiles = function () { for (var i = 0; i < this.startTiles; i++) { this.addRandomTile(); } }; // Adds a tile in a random position GameManager.prototype.addRandomTile = function () { if (this.grid.cellsAvailable()) { var value = Math.random() < 0.9 ? 2 : 4; //var tile = new Tile(this.grid.randomAvailableCell(), value); var tile = new Tile(this.grid.randomAvailableCell(), -1); this.grid.insertTile(tile); } }; // Sends the updated grid to the actuator GameManager.prototype.actuate = function () { if (this.scoreManager.get() < this.score) { this.scoreManager.set(this.score); } this.actuator.actuate(this.grid, { score: this.score, over: this.over, won: this.won, bestScore: this.scoreManager.get(), terminated: this.isGameTerminated() }); }; // Save all tile positions and remove merger info GameManager.prototype.prepareTiles = function () { this.grid.eachCell(function (x, y, tile) { if (tile) { tile.mergedFrom = null; tile.savePosition(); } }); }; // Move a tile and its representation GameManager.prototype.moveTile = function (tile, cell) { this.grid.cells[tile.x][tile.y] = null; this.grid.cells[cell.x][cell.y] = tile; tile.updatePosition(cell); }; // Move tiles on the grid in the specified direction GameManager.prototype.move = function (direction) { // 0: up, 1: right, 2:down, 3: left var self = this; if (this.isGameTerminated()) return; // Don't do anything if the game's over var cell, tile; var vector = this.getVector(direction); var traversals = this.buildTraversals(vector); var moved = false; // Save the current tile positions and remove merger information this.prepareTiles(); // Traverse the grid in the right direction and move tiles traversals.x.forEach(function (x) { traversals.y.forEach(function (y) { cell = { x: x, y: y }; tile = self.grid.cellContent(cell); if (tile) { var positions = self.findFarthestPosition(cell, vector); var next = self.grid.cellContent(positions.next); // Only one merger per row traversal? if (next && next.value === tile.value && !next.mergedFrom) { var merged = new Tile(positions.next, tile.value * 2); merged.mergedFrom = [tile, next]; self.grid.insertTile(merged); self.grid.removeTile(tile); // Converge the two tiles' positions tile.updatePosition(positions.next); // Update the score self.score += merged.value; // The mighty 2048 tile if (merged.value === 2048) self.won = true; } else { self.moveTile(tile, positions.farthest); } if (!self.positionsEqual(cell, tile)) { moved = true; // The tile moved from its original cell! } } }); }); if (moved) { this.addRandomTile(); if (!this.movesAvailable()) { this.over = true; // Game over! } this.actuate(); } }; // Get the vector representing the chosen direction GameManager.prototype.getVector = function (direction) { // Vectors representing tile movement var map = { 0: { x: 0, y: -1 }, // up 1: { x: 1, y: 0 }, // right 2: { x: 0, y: 1 }, // down 3: { x: -1, y: 0 } // left }; return map[direction]; }; // Build a list of positions to traverse in the right order GameManager.prototype.buildTraversals = function (vector) { var traversals = { x: [], y: [] }; for (var pos = 0; pos < this.size; pos++) { traversals.x.push(pos); traversals.y.push(pos); } // Always traverse from the farthest cell in the chosen direction if (vector.x === 1) traversals.x = traversals.x.reverse(); if (vector.y === 1) traversals.y = traversals.y.reverse(); return traversals; }; GameManager.prototype.findFarthestPosition = function (cell, vector) { var previous; // Progress towards the vector direction until an obstacle is found do { previous = cell; cell = { x: previous.x + vector.x, y: previous.y + vector.y }; } while (this.grid.withinBounds(cell) && this.grid.cellAvailable(cell)); return { farthest: previous, next: cell // Used to check if a merge is required }; }; GameManager.prototype.movesAvailable = function () { return this.grid.cellsAvailable() || this.tileMatchesAvailable(); }; // Check for available matches between tiles (more expensive check) GameManager.prototype.tileMatchesAvailable = function () { var self = this; var tile; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { tile = this.grid.cellContent({ x: x, y: y }); if (tile) { for (var direction = 0; direction < 4; direction++) { var vector = self.getVector(direction); var cell = { x: x + vector.x, y: y + vector.y }; var other = self.grid.cellContent(cell); if (other && other.value === tile.value) { return true; // These two tiles can be merged } } } } } return false; }; GameManager.prototype.positionsEqual = function (first, second) { return first.x === second.x && first.y === second.y; };
JavaScript
0.000002
@@ -247,17 +247,18 @@ les = -2 +15 ;%0A%0A thi @@ -1660,18 +1660,20 @@ Cell(), -- 1 +024 );%0A%0A
1dd2012bb36f454767c7f35cade5c634df96d7c3
Update php patterns
js/language/php.js
js/language/php.js
window.Rainbow = window.Rainbow || {}; Rainbow.extend('php', [ { 'name': 'support', 'pattern': /\becho\b/g }, { 'name': 'variable', 'pattern': /\$\w+\b/g }, { 'name': 'keyword.dot', 'pattern': /\./g }, { 'name': 'keyword', 'pattern': /\b(continue|break|require(_once)?|include(_once)?)\b/g }, { 'matches': { 1: 'keyword', 2: { 'name': 'support.class', 'pattern': /\w+/g } }, 'pattern': /(instanceof)\s([^\$].*?)(\)|;)/g }, { 'matches': { 1: 'support.function' }, 'pattern': /\b(apc_(fetch|store)|array|asort|file_get_contents|get_(called_)?class|getenv|in_array|json_(encode|decode)|mt_rand|rand|spl_autoload_register|str(tolower|str|pos|_replace)|trigger_error)(?=\()/g }, { 'name': 'phptag', 'pattern': /(&lt;\?(php)?|\?&gt;)/g }, { 'matches': { 1: 'keyword.namespace', 2: { 'name': 'support.namespace', 'pattern': /\w+/g } }, 'pattern': /\b(namespace\s)(.*?);/g }, { 'matches': { 1: 'keyword.class.description', 2: 'keyword.class', 3: 'meta.class-name', 5: 'keyword.extends', 6: 'meta.parent.class-name' }, 'pattern': /\b(abstract|final)\s(class)\s(\w+)(\s(extends)\s([^\\]*))?\n/g }, { 'name': 'keyword.static', 'pattern': /self::/g }, { 'matches': { 1: 'keyword', 2: 'support.magic' }, 'pattern': /(function)\s(__.*?)(?=\()/g }, { 'matches': { 1: 'keyword.new', 2: { 'name': 'support.class', 'pattern': /\w+/g } }, 'pattern': /\b(new)\s([^\$].*?)(?=\)|\(|;)/g }, { 'matches': { 1: { 'name': 'support.class', 'pattern': /\w+/g } }, 'pattern': /([\w\\]*?)::\b/g }, { 'matches': { 2: { 'name': 'support.class', 'pattern': /\w+/g } }, 'pattern': /(\(|,\s?)([\w\\]*?)(?=\s\$)/g } ]);
JavaScript
0
@@ -339,16 +339,21 @@ e%7Cbreak%7C +case%7C require( @@ -740,20 +740,54 @@ rray -%7Casort +(_sum%7C_rand)?%7Casort%7Ccount%7Cempty%7Cexplode %7Cfile_ +( get_ @@ -795,16 +795,24 @@ ontents%7C +exists)%7C get_(cal @@ -839,16 +839,46 @@ n_array%7C +is_(numeric%7Carray%7Clink)%7Cisset%7C json_(en @@ -903,16 +903,28 @@ nd%7Crand%7C +rmdir%7Cround%7C spl_auto @@ -980,16 +980,29 @@ er_error +%7Cun(link%7Cset) )(?=%5C()/ @@ -1480,9 +1480,9 @@ -5 +4 : 'k @@ -1514,9 +1514,9 @@ -6 +5 : 'm @@ -1587,18 +1587,20 @@ t%7Cfinal) +? %5Cs +? (class)%5C @@ -1612,28 +1612,34 @@ )(%5Cs -( extends -) %5Cs -(%5B%5E%5C%5C%5D*)) +)?(%5B%5Cw%5C%5C%5D*)?%5Cs?%5C%7B ?%5Cn/
547a7623ccc29fac5d9f0fdcfb1c1304e267ad6e
Change lsKeyView to lsKey in SwitchModel
js/mylib/switch.js
js/mylib/switch.js
// ---------------------------------------------------------------- // Switch Class class SwitchModel extends CommonModel { constructor({ template = null, name = 'Common Switch', view = null, lsKeyView = null, triggerSelector = null, switchSelector = null, toggleTimeMs = 500 } = {}) { super({ name: name }); this.INIT_VIEW = true; if (lsKeyView != null) { lsKeyView = `View.${lsKeyView}`; } this.NAME = name; this.view = view; this.LS_KEY_VIEW = lsKeyView; this.TRIGGER_SELECTOR = triggerSelector; this.$TRIGGER_SELECTOR = $(this.TRIGGER_SELECTOR); this.SWITCH_SELECTOR = switchSelector; this.$SWITCH_SELECTOR = $(this.SWITCH_SELECTOR); this.TOGGLE_TIME_MS = toggleTimeMs; this.compile(template); } compile(_template = null) { if (_template != null) { if (this.NAME != 'none') { this.NAME = `${_template.capitalize()} Switch`; } if (this.LS_KEY_VIEW != 'none') { this.LS_KEY_VIEW = `View.${_template}`; } if (this.TRIGGER_SELECTOR != 'none') { this.TRIGGER_SELECTOR = `#switch-${_template}`; this.$TRIGGER_SELECTOR = $(this.TRIGGER_SELECTOR); } if (this.SWITCH_SELECTOR != 'none') { this.SWITCH_SELECTOR = `#${_template}-area`; this.$SWITCH_SELECTOR = $(this.SWITCH_SELECTOR); } } } } class SwitchView extends CommonView { constructor(_model = new SwitchModel()) { super(_model); } setView(_view = null, _speed = this.model.TOGGLE_TIME_MS) { Log.logClassKey('View', this.model.NAME, _view, Log.ARROW_INPUT); if (_view != null) { if (_view) { this.model.$TRIGGER_SELECTOR.addClass(this.model.CURRENT); this.model.$SWITCH_SELECTOR.show(_speed); } else { this.model.$TRIGGER_SELECTOR.removeClass(this.model.CURRENT); this.model.$SWITCH_SELECTOR.hide(_speed); } // save if (this.model.LS_KEY_VIEW != null) { LocalStorage.setItem(this.model.LS_KEY_VIEW, _view); } this.model.view = _view; } } } // ---------------------------------------------------------------- // Controllers class SwitchController extends CommonController { constructor(_obj) { super({ name: _obj.name }); this.model = new SwitchModel(_obj); this.view = new SwitchView(this.model); this.NAME = this.model.name; // Init SwitchView this.initSwitchView(); } initSwitchView() { this.setCurrentView(); this.view.setView(this.model.view, 0); } setCurrentView() { if (this.model.view == null) { if (this.model.LS_KEY_VIEW == null) { this.model.view = this.model.INIT_VIEW; } else { const lsValView = LocalStorage.getItem(this.model.LS_KEY_VIEW); if (lsValView == null) { this.model.view = true; } else if (lsValView == 'true') { this.model.view = true; } else if (lsValView == 'false') { this.model.view = false; } } } } switchView() { Log.logClass('Switch', `${this.NAME} View`); this.setCurrentView(); this.view.setView(!this.model.view); } } class SwitchEvent extends CommonEvent { constructor(_obj) { super(_obj); this.NAME = _obj.name; this.CONTROLLER_SWITCH = new SwitchController(_obj); this.setOnSwitch(); } setOnSwitch() { SetEvent.setOn( 'click', this.CONTROLLER_SWITCH.model.TRIGGER_SELECTOR, () => { this.CONTROLLER_SWITCH.switchView(); } ); } }
JavaScript
0
@@ -210,20 +210,16 @@ lsKey -View = null, @@ -398,20 +398,16 @@ f (lsKey -View != null @@ -421,20 +421,16 @@ lsKey -View = %60View @@ -437,20 +437,16 @@ .$%7BlsKey -View %7D%60;%0A @@ -524,20 +524,16 @@ = lsKey -View ;%0A th
b0bbb95c26577747b66d20fe46034dd1639e184b
add a way to override the subcriptions directory
js/search/utils.js
js/search/utils.js
const ByteArray = imports.byteArray; const Gio = imports.gi.Gio; const GLib = imports.gi.GLib; const AsyncTask = imports.search.asyncTask; /* Returns the current locale's language code, or null if one cannot be found */ function get_current_language () { var locales = GLib.get_language_names(); // we don't care about the last entry of the locales list, since it's // always 'C'. If we get there without finding a suitable language, return // null while (locales.length > 1) { var next_locale = locales.shift(); // if the locale includes a country code or codeset (e.g. "en.utf8"), // skip it if (next_locale.indexOf('_') === -1 && next_locale.indexOf('.') === -1) { return next_locale; } } return null; } function define_enum (values) { return values.reduce((obj, val, index) => { obj[val] = index; return obj; }, {}); } function components_from_ekn_id (ekn_id) { // The URI is of form 'ekn://domain/hash[/resource]'. // Domain is usually empty string, but can contain something for older bundles. // Chop off our constant scheme identifier. let stripped_ekn_id = ekn_id.slice('ekn://'.length); let components = stripped_ekn_id.split('/'); // Pop off the domain component. components.shift(); return components; } function object_path_from_app_id (app_id) { return '/' + app_id.replace(/\./g, '/'); } function get_running_under_flatpak () { let path = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'flatpak-info']); let keyfile = new GLib.KeyFile(); try { keyfile.load_from_file(path, GLib.KeyFileFlags.NONE); } catch (e) { return false; } return true; } // String operations let parenthesize = (clause) => '(' + clause + ')'; let capitalize = (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); let quote = (clause) => '"' + clause + '"'; // number of bytes to read from the stream at a time (chosen rather arbitrarily // to be 8KB) const CHUNK_SIZE = 1024 * 8; // asynchronously read an entire GInputStream function read_stream (stream, cancellable, callback) { let task = new AsyncTask.AsyncTask(stream, cancellable, callback); task.catch_errors(() => { let total_read = ''; let handle_byte_response = task.catch_callback_errors((stream, res) => { let bytes = stream.read_bytes_finish(res); total_read += bytes.get_data().toString(); if (bytes.get_size() !== 0) { stream.read_bytes_async(CHUNK_SIZE, 0, cancellable, handle_byte_response); } else { task.return_value(total_read); } }); stream.read_bytes_async(CHUNK_SIZE, 0, cancellable, handle_byte_response); }); } function read_stream_finish (task) { return task.finish(); } // synchronously read an entire GInputStream function read_stream_sync (stream, cancellable = null) { try { let total_read = ''; let buffer = stream.read_bytes(CHUNK_SIZE, cancellable); while (buffer.get_size() !== 0) { total_read += buffer.get_data().toString(); buffer = stream.read_bytes(CHUNK_SIZE, cancellable); } total_read += buffer.get_data().toString(); return total_read; } catch (error) { logError(error, 'Error reading ' + path); return undefined; } } function string_to_stream(string) { let bytes = ByteArray.fromString(string).toGBytes(); return Gio.MemoryInputStream.new_from_bytes(bytes); } function ensure_directory (dir) { try { dir.make_directory_with_parents(null); } catch (e if e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.EXISTS)) { // Directory already exists, we're good. } } function get_subscriptions_dir () { let path = GLib.build_filenamev([GLib.get_user_data_dir(), 'com.endlessm.subscriptions']); return Gio.File.new_for_path(path); }
JavaScript
0.000019
@@ -3877,61 +3877,490 @@ let -path = GLib.build_filenamev(%5BGLib.get_user_data_dir() +user_data_path;%0A if (get_running_under_flatpak()) %7B%0A // When running under flatpak, GLib.get_user_data_dir() points to the%0A // private home inside the application, not the real home.%0A // Use the absolute path here instead of the utility function.%0A user_data_path = GLib.build_filenamev(%5BGLib.get_home_dir(), '.local', 'share'%5D);%0A %7D else %7B%0A user_data_path = GLib.get_user_data_dir();%0A %7D%0A%0A let path = GLib.build_filenamev(%5Buser_data_path , 'c
c2ad7d266cf2f31080785082380cf647ea3383af
Add span support to UITools
js/window_utils.js
js/window_utils.js
/**** glumal UI tools: For creating a consistent UI across all glumal windows. ****/ var UI = { textbox: function (label_text) { var section = document.createElement("div"); var label = document.createElement("label"); var input = document.createElement("input"); input.setAttribute("type", "text"); label.innerHTML = label_text; section.appendChild(label); section.appendChild(input); return { elem: section, label_elem: label, input_elem: input, label: function (text) { this.label_elem.innerHTML = text; }, onchange: function (evt) { this.input_elem.onpaste = evt; this.input_elem.onkeydown = evt; this.input_elem.onchange = evt; this.input_elem.oninput = evt; }, onclick: function (evt) { this.elem.onclick = evt; }, value: function (text) { if(text) { this.input_elem.value = text; } return this.input_elem.value; } }; }, button: function (button_text) { var button = document.createElement("button"); button.innerHTML = button_text; return { elem: button, onclick: function (evt) { this.elem.onclick = evt; }, label: function (button_text) { this.elem.innerHTML = button_text; } }; }, h1: function (text) { var h1 = document.createElement("h1"); h1.innerHTML = text; return { elem: h1, label: function (text) { this.elem.innerHTML = text; } }; }, h2: function (text) { var h2 = document.createElement("h2"); h2.innerHTML = text; return { elem: h2, label: function (text) { this.elem.innerHTML = text; } }; }, para: function (text) { var p = document.createElement("p"); p.innerHTML = text; return { elem: p, label: function (text) { this.elem.innerHTML = text; } }; }, symbols: function (text) { var s = document.createElement("span"); s.innerHTML = text; s.className = "pict"; return { elem: s, label: function (text) { this.elem.innerHTML = text; } }; } };
JavaScript
0
@@ -2635,21 +2635,276 @@ %0A %7D;%0A + %7D,%0A span: function (text) %7B%0A var s = document.createElement(%22span%22);%0A s.innerHTML = text;%0A return %7B%0A elem: s,%0A label: function (text) %7B%0A this.elem.innerHTML = text;%0A %7D%0A %7D;%0A %7D%0A%7D;%0A
de463c20c9729cfe0694af3c0a63077791e14bc2
update make-command-win.js. update the command to remove the extra slash if it starts with disk
make-command-win.js
make-command-win.js
'use strict'; function makeCommandWin(argv) { var command = 'dir '; if (typeof argv === 'undefined') { argv = {}; } if (argv.isAbsolutePath !== true) { command += '.'; } if (typeof argv.dir === 'string') { command += '/' + argv.dir; } if (typeof argv.name === 'string') { command += '/*.' + argv.name; } if (typeof argv.exclude === 'string') { console.log('exclude is not yet supported for windows'); } command = command.replace(/\//g, '\\'); command += ' /b/s'; return command; } module.exports = makeCommandWin;
JavaScript
0.000017
@@ -549,16 +549,167 @@ /b/s';%0A + if (command.substring(0, 5) === 'dir %5C%5C') %7B%0A //fix for C:%5C... cases%0A command = command.substring(0, 4) + command.substring(5);%0A %7D%0A retu
bac84c011ca023b93bf313f1e255f2fe68a81774
Update comments and order.
assets/javascript/main/main.scripts.js
assets/javascript/main/main.scripts.js
/** * main.script.js * * Custom, additional scripts */ // Executed on DOM ready domready(function () { // Invoke modules Alerts.init(push_message); // Init alerts Expand.init(); // Init expand / collapse FontObserverHandler.init(); // Init font(face)observer NavMain.init(); // Init main navigation // Popup.init(); // Init popup // Invoke plugins // gumshoe.init(); // Init gumshoe (scrollspy) smoothScroll.init(); // Init smoothscroll // Run svg4everybody polyfill (e.g. for IE11) // svg4everybody({ // nosvg: false, // Shiv <svg> and <use> elements and use image fallbacks // polyfill: true // Polyfill <use> elements for external content // }); // Init smoothscroll (with or without hash) new SmoothScroll('a[href*="#"]', { // speed: 500, offset: 32 }); // smoothScrollWithoutHash('a[href*="#"]', { // // speed: 500, // offset: 32 // }); });
JavaScript
0
@@ -100,25 +100,30 @@ ion () %7B%0A%0A%09/ -/ +**%0A%09 * Invoke modu @@ -126,16 +126,22 @@ modules%0A +%09 */%0A%0A %09Alerts. @@ -629,17 +629,22 @@ opup%0A%0A%09/ -/ +**%0A%09 * Invoke @@ -656,212 +656,11 @@ ns%0A%09 -// gumshoe.init(); // Init gumshoe (scrollspy)%0A%09smoothScroll.init(); // Init smoothscroll + */ %0A%0A%09/ @@ -1190,20 +1190,20 @@ set: 32%0A - %09// %7D);%0A %7D);%0A @@ -1198,12 +1198,63 @@ %09// %7D);%0A +%0A%09// Init gumshoe (scrollspy)%0A%09// gumshoe.init();%0A%0A %7D);%0A
9d86563d6833889ceff88dd18b568d9870ebedeb
Update dosamigos-ckeditor.widget.js
assets/js/dosamigos-ckeditor.widget.js
assets/js/dosamigos-ckeditor.widget.js
/** * @copyright Copyright (c) 2014 2amigOS! Consulting Group LLC * @link http://2amigos.us * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ if (typeof dosamigos == "undefined" || !dosamigos) { var dosamigos = {}; } dosamigos.ckEditorWidget = (function ($) { var pub = { registerOnChangeHandler: function (id) { CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () { CKEDITOR.instances[id].updateElement(); $('#' + id).trigger('change'); return false; }); }, registerCsrfImageUploadHandler: function () { yii & $(document).off('click', '.ck_dialog_tabs a:eq(2)').on('click', 'ck_dialog_tabs a:eq(2)', function () { var $form = $('.cke_dialog_ui_input_file iframe').contents().find('form'); if (!$form.find('input[name=_csrf]').length) { var csrfTokenInput = $('<input/>').attr({'type': 'hidden', 'name': yii.getCsrfParam()}).val(yii.getCsrfToken()); $form.append(csrfTokenInput); } }); } }; return pub; })(jQuery);
JavaScript
0
@@ -720,16 +720,17 @@ k', '.ck +e _dialog_ @@ -757,18 +757,20 @@ lick', ' +. ck +e _dialog_ @@ -1213,8 +1213,9 @@ jQuery); +%0A
049a975ad0a522628b2f94a6859c62e2a290177a
fix code style
marionette.modal.js
marionette.modal.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { define(['backbone', 'underscore', 'marionette'], function (Backbone, _, Marionette) { return factory(Backbone, _, Marionette); }); } else if (typeof exports !== 'undefined') { var Backbone = require('backbone'); var _ = require('underscore'); var Marionette = require('marionette'); module.exports = factory(Backbone, _, Marionette); } else { root.Marionette.Modal = factory(root.Backbone, root._, root.Marionette); } }(this, function (Backbone, _, Marionette) { 'use strict'; // default model var ModalModel = Backbone.Model.extend({ defaults: { isActive: false }, isNew: function () { return true; } }); // control collection var ModalCollection = Backbone.Collection.extend({ model: ModalModel, initialize: function () { this.on('destroy', this.onDestroy); }, getActive: function () { return this.findWhere({ isActive: true }); }, hasActive: function () { return this.some(function (model) { return model.get('isActive'); }); }, getGroup: function (model) { var group = model.get('group'); if (group !== void 0) { return this.where({ group: group }); } return []; }, onDestroy: function (model) { var models = this.getGroup(model); if (models.length > 0) { this.remove(models); } this.reactivate(); }, reactivate: function () { var model = this.last(); if (model !== void 0) { model.set('isActive', true); } } }); // overlay var OverlayView = Marionette.ItemView.extend({ template: false, el: '#modal-overlay', events: { 'click': 'onClick' }, toggle: function (state) { if (state) { return this.$el.fadeIn(200); } return this.$el.fadeOut(200); }, onClick: function () { this.trigger('click'); } }); // modal var ModalView = Marionette.LayoutView.extend({ template: _.template('<div class="modal-content-region"></div>'), events: { 'click .js-submit:not(.js-disabled)': 'onSubmit', 'click .js-reject': 'onReject', 'click .js-next': 'onNext', 'click .js-previous': 'onPrevious' }, className: function () { var _className = 'modal'; var className = this.model.get('className'); if (_.isString(className)) { _className += ' ' + className; } return _className; }, modelEvents: { 'change:isActive': 'onChangeActive', 'reject': 'onReject', 'submit': 'onSubmit', 'close': 'closeModal' }, regions: { contentRegion: '.modal-content-region' }, onRender: function () { var View = this.model.get('View'); this.contentRegion.show(new View); this.toggle(this.model.get('isActive')); }, toggle: function (state) { var self = this; var offset = Backbone.$(window).scrollTop(); if (state) { this.$el.show() .css({ top: offset + 'px', opacity: 0 }) .animate({ top: offset + 100 + 'px', opacity: 1 }, 200, 'linear'); } else { this.$el.animate({ top: offset + 'px', opacity: 0 }, 200, 'linear', function () { self.$el.hide(); }); } }, onChangeActive: function (model, value) { this.toggle(value); }, onSubmit: function (event) { var target = event.currentTarget; var self = this; var submitStatus = this.contentRegion.currentView.triggerMethod('submit'); // prevent closing if onSubmit method of child view returns "false" if (submitStatus === false) { return; } target.classList.add('disabled', 'js-disabled'); Backbone.$.when(submitStatus) .done(function () { self.closeModal(); }) .fail(function () { target.classList.remove('disabled', 'js-disabled'); }); }, onReject: function () { var cancelStatus = this.contentRegion.currentView.triggerMethod('reject'); // prevent closing if onReject method of child view returns "false" if (cancelStatus === false) { return; } this.closeModal(); }, onNext: function () { var modalId = this.contentRegion.currentView.triggerMethod('next'); this._toggleModal(modalId); }, onPrevious: function () { var modalId = this.contentRegion.currentView.triggerMethod('previous'); this._toggleModal(modalId); }, _toggleModal: function (modalId) { // prevent switching modals if methods of child view returns "false" if (modalId === false) { return; } var targetModal = this.model.collection.get(modalId); if (targetModal === void 0) { throw new Marionette.Error({ message: 'modal dialog with id "' + modalId + '" not found', name: 'ModalException' }); } this.model.set('isActive', false); targetModal.set('isActive', true); }, closeModal: function () { var self = this; var offset = Backbone.$(window).scrollTop(); this.$el.animate({ top: offset + 'px', opacity: 0 }, 200, 'linear', function () { self.model.destroy(); }); } }); // modal container var ModalContainer = Marionette.CollectionView.extend({ el: '#modal-container', sort: false, childView: ModalView }); // constructor var ModalController = function () { this._settings = {}; // initialize overlay once this.overlay = (new OverlayView).render(); this.collection = new ModalCollection; this.container = new ModalContainer({ collection: this.collection }); this.container.render(); this.listenTo(this.overlay, 'click', this.onReject); this.listenTo(this.container, 'add:child remove:child', this.toggleOverlay); }; // controller methods _.extend(ModalController.prototype, Backbone.Events, { add: function (item) { if (item.isActive) { this.collection.invoke('set', 'isActive', false); } else if (this.collection.length === 0) { item.isActive = true; } this.collection.add(item); }, onReject: function () { var activeModal = this.collection.getActive(); if (activeModal !== void 0) { activeModal.trigger('reject'); } }, onSubmit: function () { var activeModal = this.collection.getActive(); if (activeModal !== void 0) { activeModal.trigger('submit'); } }, toggleOverlay: function () { this.overlay.toggle(this.collection.length > 0); }, configure: function (settings) { if (settings.EA) { this._resetEvents(settings.EA); } }, _resetEvents: function (EA) { if (this._settings.EA) { this.stopListening(this._settings.EA); } this._settings.EA = EA; this.listenTo(EA, 'submit', this.onSubmit); this.listenTo(EA, 'reject', this.onReject); }, close: function (id) { if (id !== void 0) { var model = this.collection.get(id); if (model !== void 0) { model.trigger('close'); } } } }); return new ModalController; }));
JavaScript
0.000022
@@ -21,17 +21,16 @@ tory) %7B%0A -%0A if ( @@ -414,24 +414,33 @@ rionette');%0A + %0A modu
7e90141cc755846ff661a90b1b423cc25614f1f1
Fix stop time notation in timetracking advanced history
src/history-advanced.js
src/history-advanced.js
const timetrack = require('./timetrack'); const Sugar = require('sugar-date'); const calculateDuration = require('./calculateDuration'); module.exports = (pluginContext) => { return (query, env = {}) => { return new Promise((resolve, reject) => { // first trim all spaces query = query.trim(); // Only proceed if we're having a valid date if ((query.match(/^\d{4}-\d{2}-\d{2}$/) === null && query != 'today' && query != 'yesterday') || !Sugar.Date.isValid(Sugar.Date.create(query))) { return resolve([ { icon: 'assets/history.svg', title: 'Search timetracking history', subtitle: `Enter a date (yyyy-mm-dd) or quick filter for "today" or "yesterday"`, value: '' } ]); } // create a date object (kinda strange code for sugar but I couldn't make it work with cleaner code) const startOfDay = new Date(Sugar.Date.format(Sugar.Date.beginningOfDay(Sugar.Date.create(query)))).getTime(); const endOfDay = new Date(Sugar.Date.endOfDay(Sugar.Date.create(query))).getTime(); // load the data from the json file timetrack.loadData(); // Filter the items by day const historyItems = timetrack.getHistory() .filter(entry => { // the entry starts at the given day if (entry.start >= startOfDay && entry.start <= endOfDay) { return true; } // the entry ends at the given day if ('stop' in entry && entry.stop >= startOfDay && entry.stop <= endOfDay) { return true; } // no luck return false; }) .map(entry => { // get the duration of the entry let duration = 'Running'; if ('stop' in entry) { // We use beginningOfDay to support different timezones duration = calculateDuration(entry.start, entry.stop); } // get the project name const project = entry.project || 'No project'; // when did we start? const startDate = Sugar.Date.format(Sugar.Date.create(entry.start), '%I:%M:%S %p'); let stopDate = 'now'; if ('stop' in entry) { stopDate = Sugar.Date.format(Sugar.Date.create(entry.start), '%I:%M:%S %p'); } return { icon: 'assets/history.svg', title: `[${duration}] ${project}`, subtitle: `from ${startDate} till ${stopDate}`, value: `[${duration}] ${project} (from ${startDate} till ${stopDate})` } }); // no items found: send message to the app if (!historyItems.length) { // get the date formatted const day = Sugar.Date.format(Sugar.Date.create(query), '%F'); return resolve([ { icon: 'assets/history.svg', title: `No entries found for ${day}`, value: '' } ]); } resolve(historyItems); }); } }
JavaScript
0.000014
@@ -2716,35 +2716,34 @@ .create(entry.st -art +op ), '%25I:%25M:%25S %25p'
2c918ea4a7d59d0919e79cc5eee1ee91d0d77c7d
remove "release candidate" label
src/js/download-data.js
src/js/download-data.js
angular.module('download-data', []) .value('BRANCHES', [ { branch: '1.6.*', version: '${CDN_VERSION_1_6}', title: '1.6.x (release candidate)', cssClass: 'branch-1-6-x', showOnButton: true }, { branch: '1.5.*', version: '${CDN_VERSION_1_5}', title: '1.5.x (stable)', cssClass: 'branch-1-5-x', showOnButton: true }, { branch: '1.2.*', version: '${CDN_VERSION_1_2}', title: '1.2.x (legacy)', cssClass: 'branch-1-2-x', showOnButton: true }, ]) .value('BUILDS', [ { name: 'Minified' }, { name: 'Uncompressed' }, { name: 'Zip' } ]) .value('DOWNLOAD_INFO', { branchesInfo: "<dl class='dl-horizontal'>"+ " <dt>Beta 1.6.x</dt>"+ " <dd>This is the currently active development branch (<a href='https://github.com/angular/angular.js/tree/master' target='_blank'>master on Github</a>), which receives new features and may contain breaking changes.</dd>"+ " <dt>Stable 1.5.x</dt>"+ " <dd>This is the latest stable branch (<a href='https://github.com/angular/angular.js/tree/v1.5.x' target='_blank'>v1.5.x on Github</a>), with regular bug fixes.</dd>"+ " <dt>Legacy 1.2.x</dt>"+ " <dd>This branch contains a legacy version of AngularJS that supports IE8 (<a href='https://github.com/angular/angular.js/tree/v1.2.x' target='_blank'>v1.2.x on Github</a>)." + " It is not actively developed and will only receive security fixes. It is not recommended for new applications</dd>"+ "</dl>", buildsInfo: "<dl class='dl-horizontal'>"+ " <dt>Minified</dt>"+ " <dd>Minified and obfuscated version of the AngularJS base code. Use this in your deployed application (but only if you can't use Google's CDN)</dd>"+ " <dt>Uncompressed</dt>"+ " <dd>The main AngularJS source code, as is. Useful for debugging and development purpose, but should ideally not be used in your deployed application</dd>"+ " <dt>Zipped</dt>"+ " <dd>The zipped version of the Angular Build, which contains both the builds of AngularJS, as well as documentation and other extras</dd>"+ "</dl>", cdnInfo: "While downloading and using the AngularJS source code is great for development, "+ "we recommend that you source the script from Google's CDN (Content Delivery Network) in your deployed, customer facing app whenever possible. "+ "You get the following advantages for doing so:"+ "<ul>"+ " <li><strong>Better Caching :</strong> If you host AngularJS yourself, your users will have to download the source code atleast once. But if the browser sees that you are referring to Google CDN's version of AngularJS, and your user has visited another app which uses AngularJS, then he can avail the benefits of caching, and thus reduce one download, speeding up his overall experience!</li>"+ " <li><strong>Decreased Latency :</strong> Google's CDN distributes your static content across the globe, in various diverse, physical locations. It increases the odds that the user gets a version of AngularJS served from a location near him, thus reducing overall latency.</li>"+ " <li><strong>Increased Parallelism : </strong>Using Google's CDN reduces one request to your domain. Depending on the browser, the number of parallel requests it can make to a domain is restricted (as low as 2 in IE 7). So it can make a gigantic difference in loading times for users of those browsers.</li>"+ "</ul>", bowerInfo: "Bower is a package manager for client-side JavaScript components.<br><br>"+ "For more info please see: <a href='https://github.com/bower/bower'>https://github.com/bower/bower</a>" });
JavaScript
0
@@ -136,180 +136,14 @@ .x ( -release candidate)',%0A cssClass: 'branch-1-6-x',%0A showOnButton: true%0A %7D,%0A %7B%0A branch: '1.5.*', version: '$%7BCDN_VERSION_1_5%7D',%0A title: '1.5.x (stable +latest )',%0A @@ -168,17 +168,17 @@ ranch-1- -5 +6 -x',%0A
0d4bdf5611f11d51d35d3ecf55617fd1425d104a
Change weather provider URL
src/js/pebble-js-app.js
src/js/pebble-js-app.js
function degToText(deg) { if (deg < 45) { return "NNE"; } else if (deg == 45) { return "NE"; } else if (deg > 45 && deg < 90) { return "ENE"; } else if (deg == 90) { return "E"; } else if (deg > 90 && deg < 135) { return "ESE"; } else if (deg == 135) { return "SE"; } else if (deg > 135 && deg < 180) { return "SSE"; } else if (deg == 180) { return "S"; } else if (deg > 180 && deg < 225) { return "SSW"; } else if (deg == 225) { return "SW"; } else if (deg > 225 && deg < 270) { return "WSW"; } else if (deg == 270) { return "W"; } else if (deg > 270 && deg < 315) { return "WNW"; } else if (deg == 315) { return "NW"; } else if (deg > 315 && deg < 360) { return "NNW"; } else if (deg == 360) { return "N"; } } function fetchData() { var response; var req = new XMLHttpRequest(); req.open('GET', "http://parking.wasabitlabs.com/palermo"); req.onload = function(e) { if (req.readyState == 4) { if(req.status == 200) { response = JSON.parse(req.responseText); var temp_and_level, wind_speed, wind_direction, splited_wind; if (response) { temp_and_level = response.temp + '\u00B0C ' + response.level + 'm'; wind_speed = response.wind_speed; splited_wind = wind_speed.split('|'); wind_speed = splited_wind[1] + 'kt ' + splited_wind[0] + 'Km/h'; wind_direction = response.wind_direction; wind_direction = wind_direction + '\u00B0 ' + degToText(wind_direction); console.log(temp_and_level); console.log(wind_speed); console.log(wind_direction); Pebble.sendAppMessage({ "wind_direction":wind_direction, "wind_speed":wind_speed, "temp_and_level":temp_and_level}); } } else { console.log("Error"); } } }; req.send(null); } Pebble.addEventListener("ready", function(e) { console.log("connect! " + e.ready); fetchData(); console.log(e.type); }); Pebble.addEventListener("appmessage", function(e) { fetchData(); console.log(e.type); console.log(e.payload); console.log("message!"); });
JavaScript
0
@@ -907,15 +907,15 @@ p:// -parking +weather .was
d6acdfdbdef05e6a03704e7e58099229bd1e4caa
Add todo
src/js/utils/modules.js
src/js/utils/modules.js
import _ from 'lodash'; // Returns a random configuration of a module's timetable lessons. // Used when a module is first added. export function randomLessonConfiguration(lessons) { return _(lessons) .groupBy('LessonType') .mapValues((group) => { return _.groupBy(group, 'ClassNo'); }) .mapValues((group) => { return _.sample(group); }) .value(); } // Converts from timetable format to flat array of lessons. // { // [ModuleCode]: { // [LessonType]: [ // { ...Lesson }, // { ...Lesson }, // ], // ... // } // } export function timetableLessonsArray(timetable) { return _.flatMapDepth(timetable, (lessonType) => { return _.values(lessonType); }, 2); } // Groups flat array of lessons by day. // { // Monday: [{ ...Lesson }, { ...Lesson }, ...], // Tuesday: [{ ...Lesson }, { ...Lesson }, ...] // } export function groupLessonsByDay(lessons) { return _.groupBy(lessons, 'DayText'); } // Determines if two lessons of the same day overlap. Only start/end time is being checked export function doLessonsOverlap(lesson1, lesson2) { return lesson1.StartTime < lesson2.EndTime && lesson2.StartTime < lesson1.EndTime; } // Converts a flat array of lessons *within a day* into rows: // Result invariants: // - Each lesson will not overlap with each other. // [ // [{ ...Lesson }, { ...Lesson }, ...], // [{ ...Lesson }, ...], // ] export function arrangeLessonsWithinDay(lessons) { const rows = [[]]; if (_.isEmpty(lessons)) { return rows; } lessons.forEach((lesson) => { for (let i = 0, length = rows.length; i < length; i++) { const rowLessons = rows[i]; // Search through lessons in row to look for available slots. const overlapTests = _.map(rowLessons, (rowLesson) => { return !doLessonsOverlap(rowLesson, lesson); }); if (_.every(overlapTests)) { // Lesson does not overlap with any lessons in the row. Add it to row. rowLessons.push(lesson); return; } } // No existing rows are available to fit this lesson in. Append a new row. rows.push([lesson]); }); return rows; } // Accepts a flat array of lessons and group them by day and rows with each day // for rendering on the timetable. // Clashes in timetable will go onto the next row within that day. // { // Monday: [ // [{ ...Lesson }, { ...Lesson }, ...], // ], // Tuesday: [ // [{ ...Lesson }, { ...Lesson }, { ...Lesson }, ...], // [{ ...Lesson }, { ...Lesson },], // [{ ...Lesson }, ...], // ], // ... // } export function arrangeLessonsForWeek(lessons) { const dayLessons = groupLessonsByDay(lessons); return _.mapValues(dayLessons, (dayLesson) => { return arrangeLessonsWithinDay(dayLesson); }); }
JavaScript
0.000002
@@ -125,16 +125,83 @@ added.%0A +// TODO: Suggest a configuration that does not clash with itself.%0A export f
df213fba3f02c0d2f6c26a77ca7aab1a890782af
add handlebars 'eq' and 'in' helpers
src/js/yunohost/main.js
src/js/yunohost/main.js
(function() { var app = Sammy('#main', function (sam) { /** * Sammy Configuration * */ // Plugins sam.use('Handlebars', 'ms'); Handlebars.registerHelper('ucwords', function(str) { return (str + '').replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function ($1) { return $1.toUpperCase(); }); }); Handlebars.registerHelper('humanSize', function(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes === 0) return 'n/a'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[[i]]; }); Handlebars.registerHelper('humanTime', function(time) { return Math.round(time) + 's'; }); Handlebars.registerHelper('timestampToDate', function(timestamp) { var date = new Date(timestamp * 1000); return date.toLocaleString(); }); Handlebars.registerHelper('bitRate', function(bytes, time) { var sizes = ['b', 'Kb', 'Mb', 'Gb', 'Tb']; if (time === 0) return 'n/a'; var bps = bytes / time * 8; var i = parseInt(Math.floor(Math.log(bps) / Math.log(1024))); return Math.round(bps / Math.pow(1024, i), 2) + ' ' + sizes[[i]] + '/s'; }); Handlebars.registerHelper('t', function(y18n_key) { var result = y18n.t(y18n_key, Array.prototype.slice.call(arguments, 1)); return new Handlebars.SafeString(result); }); // Block helper to add a tooltip to any element Handlebars.registerHelper('tooltip', function(tooltip, options) { return new Handlebars.SafeString( '<span data-toggle="tooltip" title="' + tooltip + '" data-placement="right">' + options.fn(this) + '</span>'); }); // Load tooltips on the page; needed if using tooltips Handlebars.registerHelper('load_tooltips', function() { return new Handlebars.SafeString( '<script>' + '$(document).ready(function(){' + '$(\'[data-toggle="tooltip"]\').tooltip();' + '});' + '</script>'); }); // Look for supported type of storage to use /** * http://sammyjs.org/docs/api/0.7.4/all#Sammy.Store.LocalStorage * LocalStorage is our favorite, as it allows multiple tabs */ var storageType; if (Sammy.Store.isAvailable('local')) { storageType = 'local'; } else if (Sammy.Store.isAvailable('session')) { storageType = 'session'; } else if (Sammy.Store.isAvailable('cookie')) { storageType = 'cookie'; } else { storageType = 'memory'; } // Initialize storage sam.store = new Sammy.Store({name: 'storage', type: storageType}); sam.loaded = false; sam.isInstalledTry = 3; /** * Application bootstrap * */ sam.bind('run', function () { // Store url sam.store.set('url', window.location.hostname + '/yunohost/api'); // Get YunoHost version if (sam.store.get('connected')) { this.api('/version', function(versions) { $('#yunohost-version').html(y18n.t('footer_version', [versions.yunohost.version, versions.yunohost.repo])); }); } // Flash messages var flashMessage = $('#flashMessage'); $('#toggle-btn', flashMessage).click(function(e) { flashMessage.toggleClass('open'); }); $('#clear-btn', flashMessage).click(function(e) { flashMessage.removeClass('open').find('.messages').html(''); $('#slider').removeClass('with-flashMessage'); }); }); /** * Errors */ sam.notFound = function(){ // Redirect to home page on 404. window.location = '#/'; }; }); /** * Translations */ $.getJSON('locales/en.json', function(data){ y18n.translations['en'] = data; y18n.translateInlineHTML(); }); // User defined language if (window.navigator && window.navigator.language) { y18n.locale = window.navigator.language.substr(0, 2); if (y18n.locale !== 'en') { $.getJSON('locales/'+ y18n.locale +'.json', function(data){ y18n.translations[y18n.locale] = data; y18n.translateInlineHTML(); }); } } /** * Run the application */ $(document).ready(function () { // Run Sammy.js application app.run('#/'); }); })();
JavaScript
0.000279
@@ -2347,32 +2347,493 @@ );%0A %7D);%0A%0A + // equality stuff because mustache/Handlebars is lame%0A // source https://stackoverflow.com/a/31632215%0A Handlebars.registerHelper('eq', function(a, b) %7B%0A return a === b;%0A %7D);%0A%0A Handlebars.registerHelper('in', function(a) %7B%0A // skip first one%0A for (var i = 1; i %3C arguments.length; ++i) %7B%0A if (arguments%5Bi%5D == a)%0A return true;%0A %7D%0A return false;%0A %7D);%0A%0A // Look
b0f0efbb4188b57ca2eb180c383f50e672a76a08
Fix derived state 'hasEnabledItem' of ToolGroup.
src/kit/ui/ToolGroup.js
src/kit/ui/ToolGroup.js
import { Component } from 'substance' const DISABLED = { disabled: true } /** * A component that renders a group of tools. * * @param {string} props.name * @param {string} props.style * @param {string} props.theme * @param {boolean} props.hideDisabled * @param {array} props.items array of item specifications * @param {object} props.commandStates command states by name */ export default class ToolGroup extends Component { constructor (...args) { super(...args) this._deriveState(this.props) } willReceiveProps (newProps) { this._deriveState(newProps) } getTheme () { // HACK: falling back to 'light' in a hard-coded way return this.props.theme || 'light' } _deriveState (props) { if (this._isTopLevel) { this._derivedState = this._deriveGroupState(props, props.commandStates) } else { this._derivedState = props.itemState } } render ($$) { const { name, hideDisabled } = this.props let el = $$('div') .addClass(this._getClassNames()) .addClass('sm-' + name) let hasEnabledItem = this._derivedState.hasEnabledItem if (hasEnabledItem || !hideDisabled) { el.append(this._renderLabel($$)) el.append(this._renderItems($$)) } return el } _renderLabel ($$) { // EXPERIMENTAL: showing a ToolGroup label an const { style, label } = this.props if (style === 'descriptive' && label) { const SeparatorClass = this.getComponent('tool-separator') return $$(SeparatorClass, { label }) } } _renderItems ($$) { const { style, hideDisabled, commandStates } = this.props const theme = this.getTheme() const { itemStates } = this._derivedState let els = [] for (let itemState of itemStates) { let item = itemState.item let type = item.type switch (type) { case 'command': { const commandName = item.name let commandState = itemState.commandState if (itemState.enabled || !hideDisabled) { let ToolClass = this._getToolClass(item) els.push( $$(ToolClass, { item, commandState, style, theme }).ref(commandName) ) } break } case 'separator': { let ToolSeparator = this.getComponent('tool-separator') els.push( $$(ToolSeparator, item) ) break } default: { let ToolClass = this._getToolClass(item) els.push( $$(ToolClass, Object.assign({}, item, { commandStates, itemState, theme })).ref(item.name) ) } } } return els } get _isTopLevel () { return false } // ATTENTION: this is only called for top-level tool groups (Menu, Prompt, ) which are ToolDrop _deriveGroupState (group, commandStates) { let itemStates = group.items.map(item => this._deriveItemState(item, commandStates)) let hasEnabledItem = itemStates.some(item => item.enabled) return { item: group, itemStates, hasEnabledItem } } _deriveItemState (item, commandStates) { switch (item.type) { case 'command': { let commandState = commandStates[item.name] || DISABLED return { item, commandState, enabled: !commandState.disabled } } case 'group': case 'dropdown': case 'prompt': case 'switcher': { return this._deriveGroupState(item, commandStates) } case 'separator': { return { item } } default: throw new Error('Unsupported item type') } } _getClassNames () { return 'sc-tool-group' } _getToolClass (item) { // use an ToolClass from toolSpec if configured inline in ToolGroup spec let ToolClass if (item.ToolClass) { ToolClass = item.ToolClass } else { switch (item.type) { case 'command': { // try to use a tool registered by the same name as the command ToolClass = this.getComponent(item.name, 'no-throw') if (!ToolClass) { // using the default tool otherwise ToolClass = this.getComponent('tool') } break } case 'dropdown': { ToolClass = this.getComponent('tool-dropdown') break } case 'group': { ToolClass = this.getComponent('tool-group') break } case 'prompt': { ToolClass = this.getComponent('tool-prompt') break } case 'separator': { ToolClass = this.getComponent('tool-separator') break } // TODO: IMO this is a custom Tool, and should instead be used via ToolClass case 'switcher': { ToolClass = this.getComponent('tool-switcher') break } default: { console.error('Unsupported item type inside ToolGroup:', item.type) } } } return ToolClass } }
JavaScript
0
@@ -3117,16 +3117,39 @@ .enabled + %7C%7C item.hasEnabledItem )%0A re
251da357d6b713137326effb84f67bd7ce818853
Treat False None and True as literals (#1920)
src/languages/python.js
src/languages/python.js
/* Language: Python Category: common */ function(hljs) { var KEYWORDS = { keyword: 'and elif is global as in if from raise for except finally print import pass return ' + 'exec else break not with class assert yield try while continue del or def lambda ' + 'async await nonlocal|10 None True False', built_in: 'Ellipsis NotImplemented' }; var PROMPT = { className: 'meta', begin: /^(>>>|\.\.\.) / }; var SUBST = { className: 'subst', begin: /\{/, end: /\}/, keywords: KEYWORDS, illegal: /#/ }; var STRING = { className: 'string', contains: [hljs.BACKSLASH_ESCAPE], variants: [ { begin: /(u|b)?r?'''/, end: /'''/, contains: [hljs.BACKSLASH_ESCAPE, PROMPT], relevance: 10 }, { begin: /(u|b)?r?"""/, end: /"""/, contains: [hljs.BACKSLASH_ESCAPE, PROMPT], relevance: 10 }, { begin: /(fr|rf|f)'''/, end: /'''/, contains: [hljs.BACKSLASH_ESCAPE, PROMPT, SUBST] }, { begin: /(fr|rf|f)"""/, end: /"""/, contains: [hljs.BACKSLASH_ESCAPE, PROMPT, SUBST] }, { begin: /(u|r|ur)'/, end: /'/, relevance: 10 }, { begin: /(u|r|ur)"/, end: /"/, relevance: 10 }, { begin: /(b|br)'/, end: /'/ }, { begin: /(b|br)"/, end: /"/ }, { begin: /(fr|rf|f)'/, end: /'/, contains: [hljs.BACKSLASH_ESCAPE, SUBST] }, { begin: /(fr|rf|f)"/, end: /"/, contains: [hljs.BACKSLASH_ESCAPE, SUBST] }, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE ] }; var NUMBER = { className: 'number', relevance: 0, variants: [ {begin: hljs.BINARY_NUMBER_RE + '[lLjJ]?'}, {begin: '\\b(0o[0-7]+)[lLjJ]?'}, {begin: hljs.C_NUMBER_RE + '[lLjJ]?'} ] }; var PARAMS = { className: 'params', begin: /\(/, end: /\)/, contains: ['self', PROMPT, NUMBER, STRING] }; SUBST.contains = [STRING, NUMBER, PROMPT]; return { aliases: ['py', 'gyp', 'ipython'], keywords: KEYWORDS, illegal: /(<\/|->|\?)|=>/, contains: [ PROMPT, NUMBER, STRING, hljs.HASH_COMMENT_MODE, { variants: [ {className: 'function', beginKeywords: 'def'}, {className: 'class', beginKeywords: 'class'} ], end: /:/, illegal: /[${=;\n,]/, contains: [ hljs.UNDERSCORE_TITLE_MODE, PARAMS, { begin: /->/, endsWithParent: true, keywords: 'None' } ] }, { className: 'meta', begin: /^[\t ]*@/, end: /$/ }, { begin: /\b(print|exec)\(/ // don’t highlight keywords-turned-functions in Python 3 } ] }; }
JavaScript
0.996872
@@ -303,24 +303,8 @@ l%7C10 - None True False ',%0A @@ -347,16 +347,48 @@ emented' +,%0A literal: 'False None True' %0A %7D;%0A
c701068f310fe784fcc6ee5d59b7920d716091cd
Update registerController.js
js/controllers/registerController.js
js/controllers/registerController.js
/*! Chronicals, v1.0 Created by Kiani Lannoye & Gilles Vandewiele, commissioned by UZ Ghent https://github.com/kianilannoye/Chronicals This file contains the controller to add and modify headaches. */ angular.module('Chronic').config(['$httpProvider', function ($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common["X-Requested-With"]; $httpProvider.defaults.headers.common["Accept"] = "application/json"; $httpProvider.defaults.headers.common["Content-Type"] = "application/json"; $httpProvider.defaults.headers.common["Access-Control-Allow-Origin"] = "*"; $httpProvider.defaults.headers.common = {}; $httpProvider.defaults.headers.post = {}; $httpProvider.defaults.headers.put = {}; $httpProvider.defaults.headers.patch = {}; }]).controller('registerController', function ($scope, dataService, $http) { app.initialize(); ons.ready(function () { $('.hidden').removeClass("hidden"); $('#loadingImg').hide(); ons.disableDeviceBackButtonHandler(); document.addEventListener("deviceready", onDeviceReady, false); // device APIs are available // function onDeviceReady() { document.addEventListener("backbutton", onBackKeyPress, false); } function onBackKeyPress(e) { e.preventDefault(); } }); $scope.transition = function () { //console.log($("body").children()); $("body").children().eq(0).show(); $('body').children().eq(1).hide(); }; $scope.email = ""; $scope.password = ""; $scope.firstname = ""; $scope.lastname = ""; $scope.birthdate = ""; $scope.sex = ""; $scope.status = ""; $scope.employment = ""; $scope.submitRegister = function () { //TODO: check if username already exists and stuff var user = { "firstName": sha3_512($scope.firstname), "lastName": sha3_512($scope.lastname), "birthDate": $scope.birthdate, "email": sha3_512($scope.email), "password": "" + sha3_512($scope.password), "isMale": $scope.sex=="Man", "relation": $scope.status.toUpperCase(), "advice": "", "isEmployed": ($scope.employment == "Beroepsmatig"), "diagnosis": "" }; $http.post('http://tw06v033.ugent.be/Chronic/rest/PatientService/patients', JSON.stringify(user), { headers: { 'Content-Type': 'application/json' } }). success(function (data, status, headers, config) { //console.log("Return van indienen user:" + status); //console.log(data); dataService.clearCache(); dataService.registerUser($scope.firstname, $scope.lastname, data.birthDate, data.isMale, data.relation, data.isEmployed, $scope.email, user.password, data.patientID); alert("Voor beveiligingsredenen is het nodig om enkele gegevens door te sturen naar de dokters van het uz, zodat ze later uw identiteit aan de data kunnen koppelen. Gelieve in het volgende scherm bij het mailtje op versturen te klikken."); /*cordova.plugins.email.open({ to: ["[email protected]"], // email addresses for TO field cc: [], // email addresses for CC field bcc: [], // email addresses for BCC field attachments: [], // file paths or base64 data streams subject: "Register User - Chronic", // subject of the email body: "<h1>Gebruiker is geregistreerd met volgende info:</h1>"+ "<p>Voornaam: "+$scope.firstname+"</p>"+ "<p>Familienaam: "+$scope.lastname+"</p>"+ "<p>Emailhash: "+$scope.email+"</p>"+ "<p>patientID: "+data.patientID+"</p>", // email body (for HTML, set isHtml to true) isHtml: true, // indicats if the body is HTML or plain text }, function(){ location.href = "login.html"; } , this);*/ }). error(function (data, status, headers, config) { if(status==417){ //Cannot parse JSON Object from the body alert("De server kan het object dat meegegeven werd niet verwerken. Vraag raad aan de systeembeheerder of verantwoordelijke."); location.href="register.html"; }else if(status==409){ alert("Deze gebruiker bestaat reeds in de databank. Gelieve een ander email adres te gebruiken. Als u uw wachtwoord bent vergeten kan u terecht bij de systeembeheerder of verantwoordelijke."); location.href="register.html"; }else if(status==500){ //Internal server error alert("Er ging iets mis bij het indienen van uw request. Vraag raad aan de systeembeheerder of verantwoordelijke."); location.href="register.html"; }else if(status==0){ alert("U moet internet hebben voor u kan registreren. Indien u internetverbinding heeft, en het toch niet lukt, raadpleeg dan de systeembeheerder of verantwoordelijke."); }else{ //Some random error happened we didn't anticipate alert("WTF? RARE ERROR.."); } console.log("error creating user: " + status); console.log("data:" + data); //dataService.clearCache(); //location.href = "login.html"; }); } });
JavaScript
0.000001
@@ -2398,18 +2398,17 @@ $http.p -os +u t('http:
6781a08737abb08268aff4da2ac79c6714faf771
Update lockableContainerObject.js
js/object/lockableContainerObject.js
js/object/lockableContainerObject.js
function LockableContainerObject() { 'use strict'; var _MSG_HAS_CONTENTS = "This container already has contents"; var _MSG_INCORRECT_KEY = "The key doesn't match the lock of this container"; var _MSG_LOCKED = 'This container is locked'; var _MSG_NO_CONTENTS = "This container has no contents"; var _NULL_CONTENTS = {}; var _SUBCLASS_COUNTED_LOCKABLE_CONTAINER = [ 'CountedLockableContainer', 'ResetableCountedLockableContainer', 'ResettingCountedLockableContainer' ]; function _directSubclassFactoryFunc(containerType) { if (_isCountedLockableContainer(containerType)) { return CountedLockableContainerObject; } return _lockableContainer.bind(this); }; function _isCountedLockableContainer(containerType) { return _SUBCLASS_COUNTED_LOCKABLE_CONTAINER.indexOf(containerType) >= 0; }; function _lockableContainer() { var args = arguments[0]; this._init(args[1], args[2], args[3]); return { isLocked: this.isLocked.bind(this), lock: this.lock.bind(this), tryPutContents: this.tryPutContents.bind(this), tryTakeContents: this.tryTakeContents.bind(this), tryUnlock: this.tryUnlock.bind(this) }; }; var CALLBACK, KEY; var _contents = _NULL_CONTENTS, _isLocked = false; function _initReadonlys(callback, errback, key) { CALLBACK = callback; this._ERRBACK = errback; KEY = key; }; function _hasNoContents() { return _contents === _NULL_CONTENTS; }; function _putContents(contents) { _contents = contents; }; function _takeContents() { CALLBACK(_contents); _clearContents.call(this); }; function _clearContents() { _contents = _NULL_CONTENTS; }; this._init = function(callback, errback, key) { _initReadonlys.call(this, callback, errback, key); this._initCaches(); }; this.isLocked = function() { return _isLocked; }; this.lock = function() { _isLocked = true; }; this.tryPutContents = function(contents) { if (this.isLocked()) return this._ERRBACK(_MSG_LOCKED); if (_hasNoContents.call(this)) return _putContents.call(this, contents); this._ERRBACK(_MSG_HAS_CONTENTS); }; this.tryTakeContents = function() { if (this.isLocked()) return this._ERRBACK(_MSG_LOCKED); if (_hasNoContents.call(this)) return this._ERRBACK(_MSG_NO_CONTENTS); _takeContents.call(this); }; this.tryUnlock = function(key) { if (this._isCorrectKey(key)) return this._unlock(); this._ERRBACK(_MSG_INCORRECT_KEY); }; this._initCaches = function() { _clearContents.call(this); this._unlock(); }; this._isCorrectKey = function(key) { return key === KEY; }; this._unlock = function() { _isLocked = false; }; LockableContainerUnitTest(this); arguments[arguments.length] = this; return _directSubclassFactoryFunc.call(this, arguments[0])(arguments); };
JavaScript
0.000001
@@ -437,16 +437,17 @@ 'Reset +t ableCoun @@ -946,76 +946,33 @@ -var args = arguments%5B0%5D;%0A this._init(args%5B1%5D, args%5B2%5D, args%5B3 +this._init(arguments%5B0%5D%5B1 %5D);%0A @@ -1277,18 +1277,8 @@ var - CALLBACK, KEY @@ -1368,103 +1368,14 @@ lys( -callback, errback, key) %7B%0A CALLBACK = callback;%0A this._ERRBACK = errback;%0A +key) %7B KEY @@ -1381,20 +1381,16 @@ Y = key; -%0A %7D;%0A%0A @@ -1550,16 +1550,24 @@ ontents( +callback ) %7B%0A @@ -1574,16 +1574,16 @@ -CALLBACK +callback (_co @@ -1724,35 +1724,16 @@ unction( -callback, errback, key) %7B%0A @@ -1768,27 +1768,8 @@ his, - callback, errback, key @@ -1956,16 +1956,25 @@ contents +, errback ) %7B%0A @@ -2001,37 +2001,31 @@ d()) return -this._ERRBACK +errback (_MSG_LOCKED @@ -2112,37 +2112,31 @@ s);%0A -this._ERRBACK +errback (_MSG_HAS_CO @@ -2180,32 +2180,49 @@ ents = function( +callback, errback ) %7B%0A if ( @@ -2241,37 +2241,31 @@ d()) return -this._ERRBACK +errback (_MSG_LOCKED @@ -2313,29 +2313,23 @@ return -this._ERRBACK +errback (_MSG_NO @@ -2363,32 +2363,42 @@ ntents.call(this +, callback );%0A %7D;%0A%0A t @@ -2417,32 +2417,41 @@ k = function(key +, errback ) %7B%0A if ( @@ -2442,28 +2442,24 @@ ) %7B%0A -if ( this._isCorr @@ -2469,24 +2469,18 @@ Key(key) -) return + ? this._u @@ -2490,31 +2490,18 @@ ck() -;%0A this._ERRBACK + : errback (_MS
c291e4d78681b5111b4a2c7f480bd7bf18abc34c
fix typeahead test
js/tests/unit/bootstrap-typeahead.js
js/tests/unit/bootstrap-typeahead.js
$(function () { module("bootstrap-typeahead") test("should be defined on jquery object", function () { ok($(document.body).typeahead, 'alert method is defined') }) test("should return element", function () { ok($(document.body).typeahead()[0] == document.body, 'document.body returned') }) test("should listen to an input", function () { var $input = $('<input />') $input.typeahead() ok($input.data('events').blur, 'has a blur event') ok($input.data('events').keypress, 'has a keypress event') ok($input.data('events').keyup, 'has a keyup event') if ($.browser.webkit || $.browser.msie) { ok($input.data('events').keydown, 'has a keydown event') } else { ok($input.data('events').keydown, 'does not have a keydown event') } }) test("should create a menu", function () { var $input = $('<input />') ok($input.typeahead().data('typeahead').$menu, 'has a menu') }) test("should listen to the menu", function () { var $input = $('<input />') , $menu = $input.typeahead().data('typeahead').$menu ok($menu.data('events').mouseover, 'has a mouseover(pseudo: mouseenter)') ok($menu.data('events').click, 'has a click') }) test("should show menu when query entered", function () { var $input = $('<input />').typeahead({ source: ['aa', 'ab', 'ac'] }) , typeahead = $input.data('typeahead') $input.val('a') typeahead.lookup() ok(typeahead.$menu.is(":visible"), 'typeahead is visible') equals(typeahead.$menu.find('li').length, 3, 'has 3 items in menu') equals(typeahead.$menu.find('.active').length, 1, 'one item is active') typeahead.$menu.remove() }) test("should not explode when regex chars are entered", function () { var $input = $('<input />').typeahead({ source: ['aa', 'ab', 'ac', 'mdo*', 'fat+'] }) , typeahead = $input.data('typeahead') $input.val('+') typeahead.lookup() ok(typeahead.$menu.is(":visible"), 'typeahead is visible') equals(typeahead.$menu.find('li').length, 1, 'has 1 item in menu') equals(typeahead.$menu.find('.active').length, 1, 'one item is active') typeahead.$menu.remove() }) test("should hide menu when query entered", function () { stop() var $input = $('<input />').typeahead({ source: ['aa', 'ab', 'ac'] }) , typeahead = $input.data('typeahead') $input.val('a') typeahead.lookup() ok(typeahead.$menu.is(":visible"), 'typeahead is visible') equals(typeahead.$menu.find('li').length, 3, 'has 3 items in menu') equals(typeahead.$menu.find('.active').length, 1, 'one item is active') $input.blur() setTimeout(function () { ok(!typeahead.$menu.is(":visible"), "typeahead is no longer visible") start() }, 200) typeahead.$menu.remove() }) test("should set next item when down arrow is pressed", function () { var $input = $('<input />').typeahead({ source: ['aa', 'ab', 'ac'] }) , typeahead = $input.data('typeahead') $input.val('a') typeahead.lookup() ok(typeahead.$menu.is(":visible"), 'typeahead is visible') equals(typeahead.$menu.find('li').length, 3, 'has 3 items in menu') equals(typeahead.$menu.find('.active').length, 1, 'one item is active') ok(typeahead.$menu.find('li').first().hasClass('active'), "first item is active") $input.trigger({ type: 'keypress' , keyCode: 40 }) ok(typeahead.$menu.find('li').first().next().hasClass('active'), "second item is active") $input.trigger({ type: 'keypress' , keyCode: 38 }) ok(typeahead.$menu.find('li').first().hasClass('active'), "first item is active") typeahead.$menu.remove() }) test("should set input value to selected item", function () { var $input = $('<input />').typeahead({ source: ['aa', 'ab', 'ac'] }) , typeahead = $input.data('typeahead') , changed = false $input.val('a') typeahead.lookup() $input.change(function() { changed = true }); $(typeahead.$menu.find('li')[2]).mouseover().click() equals($input.val(), 'ac', 'input value was correctly set') ok(!typeahead.$menu.is(':visible'), 'the menu was hidden') ok(changed, 'a change event was fired') typeahead.$menu.remove() }) })
JavaScript
0.000001
@@ -3787,37 +3787,36 @@ type: 'key -press +down '%0A , keyC @@ -3980,21 +3980,20 @@ pe: 'key -press +down '%0A
271dcbd88ce7d248eb903ad30918c45f85604192
Fix Karma failure "Disconnected (1 times)" by increasing timeout
jsapp/test/configs/karma-amd.conf.js
jsapp/test/configs/karma-amd.conf.js
module.exports = function(config) { var path = require('path'); function project(pattern, included, watched, served) { if(included === undefined) { included = false; } if(watched === undefined) { watched = false; } if(served === undefined) { served = true; } return { pattern: pattern, included: !!included, watched: !!watched, served: !!served }; } var _c, componentFiles = [], components = require(path.resolve(__dirname, '../components.js')); for (var _c in components.libs) { componentFiles.push(project(components.libs[_c], 0, 1, 1)); } for (_c in components.serve) { componentFiles.push(project(components.serve[_c], 0, 1, 1)); } config.set({ basePath: path.resolve(__dirname, '../..'), frameworks: ['jasmine', 'requirejs', 'sinon'], files: componentFiles.concat([ project('test/components.js', 0, 0, 1), project('test/amdrunner.coffee', 0, 1, 1), 'test/amdtest-main.js', ]), plugins: [ // jasmine + reporters 'karma-jasmine', 'karma-coverage', 'karma-requirejs', 'karma-junit-reporter', 'karma-growl-reporter', 'karma-sinon', // browser launchers 'karma-phantomjs-launcher', 'karma-chrome-launcher', 'karma-firefox-launcher', // preprocessors 'karma-ng-html2js-preprocessor', ], // exclude: [], // test results reporters: (dots|progress|junit|growl|coverage) reporters: ['progress', 'coverage'], preprocessors: { // '../**/*.js': ['coverage'], '**/*.html': 'ng-html2js', }, ngHtml2JsPreprocessor: { cacheIdFromPath: function(filepath) { var matches = /^\/?(.+\/)*(.+)\.(.+)$/.exec(filepath); return 'templates/' + matches[2] + '.' + matches[3]; } }, port: 9876, colors: true, logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, browsers: ['PhantomJS'], captureTimeout: 60000, browserNoActivityTimeout: 20000, singleRun: true, }); };
JavaScript
0.000113
@@ -2374,17 +2374,17 @@ imeout: -2 +6 0000,%0A
568e937a42f1040607771ba6830460e9386e1647
add embed explore to transifex blacklist
layout/head/app.js
layout/head/app.js
import React from 'react'; import PropTypes from 'prop-types'; import HeadNext from 'next/head'; // Redux import { connect } from 'react-redux'; // Utils import { USERREPORT_BLACKLIST } from 'utils/user-report'; import Package from '../../package.json'; const TRANSIFEX_BLACKLIST = [ '/app/embed/EmbedDashboard', '/app/embed/EmbedMap', '/app/embed/EmbedTable', '/app/embed/EmbedText', '/app/embed/EmbedWidget', '/app/embed/EmbedEmbed', '/app/embed/EmbedDataset', '/app/embed/EmbedSimilarDatasets' ]; class Head extends React.PureComponent { static getStyles() { if (process.env.NODE_ENV === 'production') { // In production, serve pre-built CSS file from /styles/{version}/main.css return <link rel="stylesheet" type="text/css" href={`/styles/${Package.version}/main.css`} />; } // In development, serve CSS inline (with live reloading) with webpack // NB: Not using dangerouslySetInnerHTML will cause problems with some CSS /* eslint-disable */ return <style dangerouslySetInnerHTML={{ __html: require('css/index.scss') }} />; /* eslint-enable */ } getCrazyEgg() { return <script type="text/javascript" src="//script.crazyegg.com/pages/scripts/0069/4623.js" async="async" />; } getUserReport() { const { pathname } = this.props.routes; if (USERREPORT_BLACKLIST.includes(pathname)) { return null; } return ( <script type="text/javascript" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: ` window._urq = window._urq || []; _urq.push(['setGACode', 'UA-67196006-1']); _urq.push(['initSite', '085d5a65-977b-4c3d-af9f-d0a3624e276f']); (function() { var ur = document.createElement('script'); ur.type = 'text/javascript'; ur.async = true; ur.src = ('https:' == document.location.protocol ? 'https://cdn.userreport.com/userreport.js' : 'http://cdn.userreport.com/userreport.js'); var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ur, s); })(); ` }} /> ); } getTransifexSettings() { const { pathname } = this.props.routes; if (TRANSIFEX_BLACKLIST.includes(pathname)) { return null; } return ( <script type="text/javascript" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: ` window.liveSettings = { api_key: '${process.env.TRANSIFEX_LIVE_API}' } ` }} /> ); } getTransifex() { const { pathname } = this.props.routes; if (TRANSIFEX_BLACKLIST.includes(pathname)) { return null; } return <script type="text/javascript" src="//cdn.transifex.com/live.js" />; } getCesium() { const { pathname } = this.props.routes; if (pathname === '/app/pulse' || pathname === '/app/Splash') { return <script src="/static/cesium/cesium.js" />; } return null; } getCesiumStyles() { const { pathname } = this.props.routes; if (pathname === '/app/pulse' || pathname === '/app/Splash') { return <link rel="stylesheet" href="/static/cesium/Widgets/widgets.css" />; } return null; } getAFrame() { const { pathname } = this.props.routes; if (pathname === '/app/SplashDetail') { return <script src="/static/aframe/aframe.min.js" />; } return null; } render() { const { title, description, category } = this.props; return ( <HeadNext> <title>{title ? `${title} | Resource Watch` : 'Resource Watch'}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="author" content="Vizzuality" /> {category && <meta name="addsearch-category" content={category} />} <link rel="icon" href="/static/favicon.ico" /> <link rel="stylesheet" media="screen" href="https://fonts.googleapis.com/css?family=Lato:400,300,700" /> <link rel="stylesheet" media="screen" href="/static/styles/add-search-results.css" /> {/* Mobile Adress background */} {/* Chrome, Firefox OS and Opera */} <meta name="theme-color" content="#c32d7b" /> {/* Windows Phone */} <meta name="msapplication-navbutton-color" content="#c32d7b" /> {/* iOS Safari */} <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> {Head.getStyles()} {this.getCesiumStyles()} {this.getCrazyEgg()} {this.getUserReport()} {this.getTransifexSettings()} {this.getTransifex()} {this.getCesium()} {this.getAFrame()} <script src="https://cdn.polyfill.io/v2/polyfill.min.js" /> </HeadNext> ); } } Head.propTypes = { title: PropTypes.string, // Some pages don't have any title (think embed) description: PropTypes.string.isRequired, routes: PropTypes.object.isRequired, category: PropTypes.string }; export default connect( state => ({ routes: state.routes }), null )(Head);
JavaScript
0
@@ -509,16 +509,40 @@ atasets' +,%0A '/app/embed/explore' %0A%5D;%0A%0Acla