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
8c029922a3687f6a89127913617c59e45c02d5f3
Fix threshold calculation with ar2 prediction, when using mmol/L
lib/plugins/ar2.js
lib/plugins/ar2.js
'use strict'; var _ = require('lodash'); function init() { function ar2() { return ar2; } ar2.label = 'AR2'; ar2.pluginType = 'forecast'; var WARN_THRESHOLD = 0.05; var URGENT_THRESHOLD = 0.10; var ONE_HOUR = 3600000; var ONE_MINUTE = 60000; var FIVE_MINUTES = 300000; ar2.checkNotifications = function checkNotifications(sbx) { var forecast = ar2.forecast(sbx.data.sgvs); var trigger = false , level = 0 , levelLabel = '' , pushoverSound = null ; if (forecast.avgLoss > URGENT_THRESHOLD) { trigger = true; level = 2; levelLabel = 'Urgent'; pushoverSound = 'persistent'; } else if (forecast.avgLoss > WARN_THRESHOLD) { trigger = true; level = 1; levelLabel = 'Warning'; } if (trigger) { var predicted = _.map(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 = _.max([first, last, avg]); var rangeLabel = ''; if (max > sbx.thresholds.bg_target_top) { rangeLabel = 'HIGH'; if (!pushoverSound) pushoverSound = 'climb' } else if (min < sbx.thresholds.bg_target_bottom) { rangeLabel = 'LOW'; if (!pushoverSound) pushoverSound = 'falling' } else { rangeLabel = ''; } var title = [levelLabel, rangeLabel, 'predicted'].join(' ').replace(' ', ' '); var lines = [ ['Now', sbx.data.lastSGV(), sbx.unitsLabel].join(' ') , ['15m', predicted[2], sbx.unitsLabel].join(' ') ]; var iob = sbx.properties.iob && sbx.properties.iob.display; if (iob) { lines.unshift(['\nIOB:', iob, 'U'].join(' ')); } var message = lines.join('\n'); forecast.predicted = _.map(forecast.predicted, function(p) { return sbx.scaleBg(p.y) } ).join(', '); sbx.notifications.requestNotify({ level: level , title: title , message: message , pushoverSound: pushoverSound , debug: { forecast: forecast , thresholds: sbx.thresholds } }); } }; ar2.forecast = function forecast(sgvs) { var lastIndex = sgvs.length - 1; var result = { predicted: [] , avgLoss: 0 }; if (lastIndex > 0) { // predict using AR model var lastValidReadingTime = sgvs[lastIndex].x; var elapsedMins = (sgvs[lastIndex].x - sgvs[lastIndex - 1].x) / ONE_MINUTE; var BG_REF = 140; var BG_MIN = 36; var BG_MAX = 400; var y = Math.log(sgvs[lastIndex].y / BG_REF); if (elapsedMins < 5.1) { y = [Math.log(sgvs[lastIndex - 1].y / 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.000002
@@ -1155,16 +1155,28 @@ (max %3E +sbx.scaleBg( sbx.thre @@ -1196,16 +1196,17 @@ get_top) +) %7B%0A @@ -1304,16 +1304,28 @@ (min %3C +sbx.scaleBg( sbx.thre @@ -1348,16 +1348,17 @@ _bottom) +) %7B%0A @@ -1605,16 +1605,28 @@ %5B'Now', +sbx.scaleBg( sbx.data @@ -1635,16 +1635,17 @@ astSGV() +) , sbx.un
7efb24a80a512cdacc42ce6b8582da21e7346b6d
add print method
lib/plugins/css.js
lib/plugins/css.js
/** * Created by nuintun on 2015/5/5. */ 'use strict'; var util = require('../util'); var common = require('../common'); function transport(vinyl, options){ var id = common.transportId(vinyl, options); var deps = common.transportCssDeps(vinyl, options); // get code var code = ''; var importStyle = util.parseAlias('import-style', options.alias); // get code deps.forEach(function (id){ code += "require('" + id.replace(/'/g, '\\\'') + "');\n"; }); // push import-style module dependencies deps.push(importStyle); // import import code += "require('" + importStyle.replace(/'/g, '\\\'') + "')('" + vinyl.contents.toString() .replace(/\\/g, '\\\\') // replace ie hack: https://github.com/spmjs/spm/issues/651 .replace(/'/g, '\\\'') + "');"; vinyl.contents = new Buffer(util.wrapModule(id, deps, code)); return vinyl; } /** * Exports module. */ module.exports = util.plugin('css', transport);
JavaScript
0.000016
@@ -856,16 +856,210 @@ ode));%0A%0A + // add import style deps%0A vinyl.package.dependencies.push(importStyle);%0A vinyl.package.include.push(%7B%0A id: importStyle,%0A path: util.resolve(importStyle, vinyl, options.wwwroot)%0A %7D);%0A%0A return
ee67a392e297d455af35bb1242c4d12a0b149eb5
change ReqSocket to round-robin send()s
lib/sockets/req.js
lib/sockets/req.js
/** * Module dependencies. */ var Socket = require('./sock') , queue = require('../plugins/queue') , debug = require('debug')('axon:req'); /** * Expose `ReqSocket`. */ module.exports = ReqSocket; /** * Initialize a new `ReqSocket`. * * @api private */ function ReqSocket() { Socket.call(this); this.pid = process.pid; this.ids = 0; this.callbacks = {}; this.use(queue()); } /** * Inherits from `Socket.prototype`. */ ReqSocket.prototype.__proto__ = Socket.prototype; /** * Emits the "message" event with all message parts * after the null delimeter part. * * @param {net.Socket} sock * @return {Function} closure(msg, multipart) * @api private */ ReqSocket.prototype.onmessage = function(){ var self = this; return function(msg, multipart){ if (!multipart) return debug('expected multipart'); var id = msg.shift(); msg.shift(); var fn = self.callbacks[id]; if (!fn) return debug('missing callback %s', id); fn.apply(null, msg); delete self.callbacks[id]; }; }; /** * Sends `msg` to the remote peers. Appends * the null message part prior to sending. * * @param {Mixed} msg * @api public */ ReqSocket.prototype.send = function(msg){ var sock = this.socks[0] , args = []; if (Array.isArray(msg)) { args = msg; } else { for (var i = 0; i < arguments.length; ++i) { args[i] = arguments[i]; } } if (sock) { if ('function' == typeof args[args.length - 1]) { var fn = args.pop(); fn.id = this.pid + ':' + this.ids++; this.callbacks[fn.id] = fn; args.unshift(fn.id, '\u0000'); } } if (sock) { sock.write(this.pack(args)); } else { debug('no connected peers'); this.enqueue(args); } };
JavaScript
0
@@ -307,16 +307,30 @@ (this);%0A + this.n = 0;%0A this.p @@ -1232,16 +1232,17 @@ var sock +s = this. @@ -1250,10 +1250,67 @@ ocks -%5B0 +%0A , len = socks.length%0A , sock = socks%5Bthis.n++ %25 len %5D%0A
cceb4d3a16573c3ad68b6377b1633254428f0847
Add ignore to defaultOptions
lib/state/state.js
lib/state/state.js
'use strict'; const mergeOptions = require('merge-options'); const init = require('./init'); const debug = require('./debug'); const defaultOptions = { update: false, global: false, cwd: process.cwd(), nodeModulesPath: false, skipUnused: false, ignoreDev: false, forceColor: false, saveExact: false, debug: false, emoji: true, spinner: false, installer: 'npm', globalPackages: {}, cwdPackageJson: {devDependencies: {}, dependencies: {}}, packages: false, unusedDependencies: false, missingFromPackageJson: {} }; function state(userOptions) { const currentStateObject = mergeOptions(defaultOptions, {}); function get(key) { if (!currentStateObject.hasOwnProperty(key)) { throw new Error(`Can't get unknown option "${key}".`); } return currentStateObject[key]; } function set(key, value) { if (get('debug')) { debug('set key', key, 'to value', value); } if (currentStateObject.hasOwnProperty(key)) { currentStateObject[key] = value; } else { throw new Error(`unknown option "${key}" setting to "${JSON.stringify(value, false, 4)}".`); } } function inspectIfDebugMode() { if (get('debug')) { inspect(); } } function inspect() { debug('current state', all()); } function all() { return currentStateObject; } const currentState = { get: get, set: set, all, inspectIfDebugMode }; return init(currentState, userOptions); } module.exports = state;
JavaScript
0.000001
@@ -403,16 +403,32 @@ : 'npm', +%0A ignore: %5B%5D, %0A%0A gl
b6d16b9ff6d7478481eb01a8b486e3cd762031b7
Revert "Use back instead of "this" to avoid problems with "this"."
lib/strong-back.js
lib/strong-back.js
/*! * Strong i18n for express - Simple Backend * Copyright(c) 2011 Tim Shadel * MIT Licensed */ /* Simple implementation of a translation backend provider. Conforms to the basic strong provider API contract. */ /** * Module dependencies. */ var glob = require('glob') , _ = require('underscore') , fs = require('fs'); /** * Expose `back`. */ back = exports = module.exports; var exists = function(obj) { return ("undefined" !== typeof obj && obj !== null); }; /** * API proto. */ back._translations = {}; back.translations_load_path = ['./locales']; back.navigate = function (path) { try { return path.split('.').reduce(function(obj,i){ return obj[i] }, back._translations); } catch (e) { return undefined; } }; back.putAtPath = function (path, value) { var keypath = path.split('.'); var key = keypath.pop(); var self = back; var putPoint = keypath.reduce( function(obj,i) { var result = obj[i]; if (typeof result === "undefined" || result === null) obj[i] = {}; return obj[i] } , self._translations); putPoint[key] = value; }; function merge(a, b){ if (a && b) { for (var key in b) { a[key] = b[key]; } } return a; }; back.mergeAtPath = function (path, object) { self = back; var mergePoint = path.split('.').reduce( function(obj,i) { var result = obj[i]; if (typeof result === "undefined" || result === null) obj[i] = {}; return obj[i] } , self._translations); merge(mergePoint, object); }; /** * Initialize the api using the provided backend implementation. * * @api private */ back.init = function(options, on_done) { var self = this; // Initialize our backing store with no translations. this._translations = {}; if (typeof options !== "undefined" && options !== null) { if (typeof options["translations_dir"] !== "undefined" && options["translations_dir"] !== null) { this.translations_load_path.push( options["translations_dir"] ); } else if (typeof options["translations_load_path"] !== "undefined" && options["translations_load_path"] !== null) { this.translations_load_path = options["translations_load_path"]; } } // Load find the list of translation files available this.load(function(err) { if (err) { console.log("Problem loading translations: " + err); } }); }; back.load = function(callback) { this.eachLoadPath(function(path, namespace) { var pattern = '' + path + '/**/*.json'; var self = back; glob(pattern, function(err, matches) { if (err) { callback(err); } else { // Load the file into the _translations hash for(var i = 0; i < matches.length; i++) { // TODO: load files asynchronously self.loadTranslationFile(matches[i], path, namespace); } callback(null); } }); }); } back.eachLoadPath = function(callback) { for (var i = 0; i < this.translations_load_path.length; i++) { var path_item = this.translations_load_path[i]; if ('string' === typeof path_item) { callback(path_item, null); } else { for (var namespace in path_item) { callback(path_item[namespace], namespace); } } } }; back.toDotPath = function(filename, prefix, namespace) { var extractor = new RegExp("^" + prefix + "\/(.+)_([^_]+)\\.json$"); var match = filename.match(extractor); if (match) { var replacement = '$2/$1'; if (exists(namespace)) { replacement = '$2/' + namespace + '/$1'; } return filename.replace(extractor, replacement).replace(/\//g,'.'); } return filename; } /** * Load the contents of the given file and mount them into the * appropriate spot in the `_translations` hash. * * @api private */ back.loadTranslationFile = function(filename, prefix, namespace) { var contents; try { contents = fs.readFileSync(filename); } catch(e) { console.log('Error reading \'' + filename + '\': ' + e); return; } var dotPath = this.toDotPath(filename, prefix, namespace); var json = JSON.parse(contents); this.mergeAtPath(dotPath, json); }; /** * Load utility functions into scope. */ require('./util');
JavaScript
0
@@ -684,20 +684,20 @@ j%5Bi%5D %7D, -back +this ._transl
0b5f94299b0e37e028da120f6a8ee3e2bfc4768e
Remove try-catch
lib/tessel/list.js
lib/tessel/list.js
var mdns = require('mdns-js'); var _ = require('lodash'); //if you have another mdns daemon running, like avahi or bonjour, uncomment following line mdns.excludeInterface('0.0.0.0'); function list(callback){ // Initial list of Tessels var tessels = []; // Create a Tessel browser var browser = mdns.createBrowser('_tessel._tcp'); // When the browser finds a new device browser.on('update', function (data) { // Check if it's a Tessel if( _.findIndex(tessels, data) > -1){ return; } // Push it to our array tessels.push(data); }); // When the browser becomes ready browser.once('ready', function(){ try { // Start discovering Tessels browser.discover(); } catch(error) { // Return if there was an error return callback && callback(error); } // Otherwise, check back in after two seconds setTimeout(function(){ // Return the discovered Tessels callback && callback(null, tessels) // Stop discovering browser.stop(); // TODO: figure out a way to not make this a hardcoded number of seconds... just keep scanning? }, 2000); return; }) } module.exports = list
JavaScript
0.000018
@@ -178,16 +178,29 @@ 0.0');%0A%0A +%3C%3C%3C%3C%3C%3C%3C HEAD%0A function @@ -1168,16 +1168,17 @@ rn;%0A %7D) +; %0A%7D%0A%0Amodu
feb747c417096c6d0b4adbac32dd68accf22cba4
Update topic_cache.js
lib/topic_cache.js
lib/topic_cache.js
var LRU = require('lru-cache'); var moment = require('moment'); function TopicCache(capacity){ var options_ = { max : capacity, dispose : function (key, val){ val.close(); } } LRU.call(this, options_); var me = this; // cycle timer var timer_ = null; // clear handles of each topic var clearHandles_ = function (){ // remove 5 days before var ts = moment() - moment.duration(5, "days"); me.forEach(function (val, key, cache){ val.clearHandles(ts); }); } this.cycle = function (){ timer_ = setInterval(clearHandles_, moment.duration(1, "days").valueOf()); } this.close = function (){ if (timer_) clearInterval(timer_); } // begin cycle clear this.cycle(); } require('util').inherits(TopicCache, LRU); module.exports = TopicCache;
JavaScript
0.000002
@@ -213,496 +213,8 @@ _);%0A -%09var me = this;%0A%0A%09// cycle timer%0A%09var timer_ = null;%0A%0A%09// clear handles of each topic%0A%09var clearHandles_ = function ()%7B%0A%09%09// remove 5 days before%0A%09%09var ts = moment() - moment.duration(5, %22days%22);%0A%09%09me.forEach(function (val, key, cache)%7B%0A%09%09%09val.clearHandles(ts);%0A%09%09%7D);%0A%09%7D%0A%0A%09this.cycle = function ()%7B%0A%09%09timer_ = setInterval(clearHandles_, moment.duration(1, %22days%22).valueOf());%0A%09%7D%0A%0A%09this.close = function ()%7B%0A%09%09if (timer_)%0A%09%09%09clearInterval(timer_);%0A%09%7D%0A%0A%09// begin cycle clear%0A%09this.cycle();%0A %7D%0Are @@ -283,8 +283,9 @@ icCache; +%0A
e94bcfba4ecb43095f174568f0971e2f53ec5127
Fix regression (cf. #18)
lib/tree-ignore.js
lib/tree-ignore.js
"use babel"; import ignore from "ignore"; import { CompositeDisposable } from "atom"; import $ from "jquery"; let oPackageConfig, fActivate, fDeactivate, _oDisposables, _oAtomIgnoreFileDisposables, _oMutationObserver, _bIsWindowsPlatform = document.body.classList.contains( "platform-win32" ), _oAtomIgnoreFiles, _fUpdate, _fApply, _fTreeViewHasMutated, _fProjectChangedPaths, _fAddAtomIgnoreFiles, _fNormalizePath, _fHandleIgnoreFile, _fUnhideParents; oPackageConfig = { "enabled": { "type": "boolean", "default": true }, "ignoreFileName": { "type": "string", "default": ".atomignore" } }; fActivate = function() { _oDisposables && _oDisposables.dispose(); _oDisposables = new CompositeDisposable(); _oDisposables.add( atom.commands.add( "atom-workspace", { "tree-ignore:toggle": () => { _fApply( !atom.config.get( "tree-ignore.enabled" ) ); }, "tree-ignore:enable": _fApply.bind( null, true ), "tree-ignore:disable": _fApply.bind( null, false ) } ) ); _oDisposables.add( atom.commands.add( ".platform-win32, .platform-linux, .platform-darwin", { "tree-view:toggle": _fUpdate.bind( null ) } ) ); _oMutationObserver = new MutationObserver( _fTreeViewHasMutated ); atom.packages.onDidActivateInitialPackages( () => { _oDisposables.add( atom.project.onDidChangePaths( _fProjectChangedPaths ) ); _fProjectChangedPaths(); atom.config.observe( "tree-ignore.enabled", ( bNewValue ) => { if ( bNewValue !== atom.config.get( "tree-ignore.enabled" ) ) { _fApply( bNewValue ); } } ); _fUpdate( atom.config.get( "tree-ignore.enabled" ) ); } ); }; fDeactivate = function() { _oDisposables && _oDisposables.dispose(); _oAtomIgnoreFileDisposables && _oAtomIgnoreFileDisposables.dispose(); _oMutationObserver.disconnect(); }; _fApply = function( bValue ) { atom.config.set( "tree-ignore.enabled", bValue ); _fUpdate( bValue ); }; _fUpdate = function( bState ) { let oIgnore, oIgnoredItems = {}, sProjectRoot = "", bHandleProject; if ( bState && document.querySelector( ".tree-view" ) ) { _oMutationObserver.observe( document.querySelector( ".tree-view" ), { "childList": true, "subtree": true } ); } else { _oMutationObserver.disconnect(); } $( atom.views.getView( atom.workspace ) ) .find( ".tree-view li.entry .name" ).each( function() { let sPath, $this, bFiltered = false; if ( sPath = ( $this = $( this ) ).data( "path" ) ) { let $parent = $this.parents( "li.entry" ).first(); sPath = _fNormalizePath( sPath ); if ( $parent.hasClass( "directory" ) ) { sPath += "/"; } if ( $parent.hasClass( "project-root" ) ) { sProjectRoot = sPath; oIgnore = _fHandleIgnoreFile( sProjectRoot ); bHandleProject = oIgnore != null; } if ( oIgnore != null ) { sPath = sPath.substring( sProjectRoot.length ); bFiltered = oIgnore.filter( [ sPath ] ).length === 0; if ( bFiltered ) { if ( sPath.endsWith( "/" ) ) { oIgnoredItems[ sPath ] = $parent; } } else { _fUnhideParents( oIgnoredItems, sPath ); } } $parent.toggleClass( "tree-ignore-element", bState && bHandleProject && bFiltered ); } } ); }; _fTreeViewHasMutated = function() { _fUpdate(); }; _fProjectChangedPaths = function() { _fAddAtomIgnoreFiles(); _fUpdate(); }; _fAddAtomIgnoreFiles = function() { let sIgnoreFileName = atom.config.get( "tree-ignore.ignoreFileName" ); _oAtomIgnoreFileDisposables && _oAtomIgnoreFileDisposables.dispose(); _oAtomIgnoreFileDisposables = new CompositeDisposable(); _oAtomIgnoreFiles = {}; atom.project.getDirectories().forEach( ( oDirectory ) => { let oIgnoreFile = oDirectory.getFile( sIgnoreFileName ); _oAtomIgnoreFiles[ _fNormalizePath( `${ oDirectory.getPath() }/` ) ] = oIgnoreFile; _oAtomIgnoreFileDisposables.add( oIgnoreFile.onDidChange( _fUpdate ) ); } ); }; _fNormalizePath = function( sPath ) { if ( _bIsWindowsPlatform ) { return sPath.replace( /\\/g, "/" ); } return sPath; }; _fHandleIgnoreFile = function( sPath ) { let sIgnoreFile = _oAtomIgnoreFiles[ sPath ]; if ( sIgnoreFile == null ) { // New root / project path, look if it has an ignore file return null; // Don't handle this project } if ( !sIgnoreFile.existsSync() ) { return null; // Removed, unhide everything } return ignore().addIgnoreFile( sIgnoreFile.getPath() ); }; _fUnhideParents = function( oIgnoredItems, sPath ) { const getParent = function( sChildPath ) { if ( sChildPath.endsWith( "/" ) ) { return sChildPath.replace( /[^\/]*\/$/, "" ); } return sChildPath.replace( /\/.*?$/, "/" ); }; let sParent = sPath, oItem; while ( sParent.includes( "/" ) ) { sParent = getParent( sParent ); oItem = oIgnoredItems[ sParent ]; if ( oItem != null ) { oItem.removeClass( "tree-ignore-element" ); } } }; export { oPackageConfig as config, fActivate as activate, fDeactivate as deactivate };
JavaScript
0
@@ -395,16 +395,35 @@ edPaths, + _fGetCurrentState, %0A _fA @@ -1750,50 +1750,8 @@ ate( - atom.config.get( %22tree-ignore.enabled%22 ) );%0A @@ -1950,16 +1950,106 @@ ();%0A%7D;%0A%0A +_fGetCurrentState = function() %7B%0A return atom.config.get( %22tree-ignore.enabled%22 );%0A%7D;%0A%0A _fApply @@ -2138,24 +2138,16 @@ fUpdate( - bValue );%0A%7D;%0A%0A_ @@ -2165,24 +2165,16 @@ unction( - bState ) %7B%0A @@ -2263,16 +2263,54 @@ eProject +,%0A bState = _fGetCurrentState() ;%0A%0A i
03f51b6078f378d0eec22e84d8fdf161ecd73398
Fix config merging behavior
lib/utils/index.js
lib/utils/index.js
'use strict'; var _ = require('lodash'); var gravatar = require('gravatar'); module.exports = { gravatar: gravatarDefault, sanitizeProject: sanitizeProject, sanitizeBranch: sanitizeBranch, sanitizeUser: sanitizeUser, timeFromId: timeFromId, defaultSchema: defaultSchema, validateAgainstSchema: validateAgainstSchema, mergePlugins: mergePlugins, mergeConfigs: mergeConfigs, findBranch: findBranch }; function findBranch(branches, name) { var foundBranch = false; branches.some(function (branch) { if (branch.name) { var regEx = new RegExp('^' + branch.name.replace(/\*/g, '.*') + '$'); if (regEx.test(name)) { foundBranch = branch; return true; } } }); return (function discreteBranchFn(name, branch, branches) { //console.log('findBranch('+name+') wants to return '+branch.name); if (branch.name !== name) { //console.warn('Possibly returning unintended branch (expected '+name+' but got '+branch.name+'). attempting to locate discretely named branch '+name+' if it exists.'); var discreteBranch = _.findWhere(branches, {name: name}); if (discreteBranch) { branch = discreteBranch; //console.info("Located discrete branch, instead returning "+branch.name) } else { //console.warn("Unable to find discrete branch "+name+", still returning "+branch.name); } } return branch; }(name, foundBranch, branches)); } // merge plugins from the DB with ones from strider.json. The latter overrides the former function mergePlugins(branch, sjson) { if (!branch) return sjson; if (!sjson) return branch; // if strict_plugins is not turned on, we merge each plugin config instead of overwriting. var plugins = []; var pluginMap = {}; for (var pluginIndex = 0; pluginIndex < sjson.length; pluginIndex++) { plugins.push(sjson[pluginIndex]); pluginMap[sjson[pluginIndex].id] = true; } for (var branchIndex = 0; branchIndex < branch.length; branchIndex++) { if (!pluginMap[branch[branchIndex].id]) plugins.push(branch[branchIndex]); } return plugins; } function mergeConfigs(branch, sjson) { var config = _.extend({}, branch, sjson); if (!sjson.merge_plugins) return config; config.plugins = mergePlugins(branch.plugins, sjson.plugins); return config; } function validateVal(val, schema) { if (schema === String) return val + ''; if (schema === Number) { val = parseFloat(schema); return isNaN(val) ? 0 : val; } if (schema === Boolean) return !!val; if (Array.isArray(schema)) { var ret = []; if (!Array.isArray(val)) return []; for (var i = 0; i < val.length; i++) { ret.push(validateVal(val[i], schema[0])); } return ret; } if (schema.type && !schema.type.type) { val = validateVal(val, schema.type); if (schema.enum && schema.enum.indexOf(val) === -1) { return; } return val; } if ('object' !== typeof schema) return; if ('object' !== typeof val) return {}; // if schema is {}, it's unchecked. if (Object.keys(schema).length === 0) return val; return validateAgainstSchema(val, schema); } function defaultVal(val) { if (val === String) return ''; if (val === Number) return 0; if (val === Boolean) return false; if (!val) return null; if (Array.isArray(val)) return []; if (val.type && !val.type.type) { if (val.default) return val.default; if (val.enum) return val.enum[0]; return defaultVal(val.type); } if ('object' === typeof val) return defaultSchema(val); return null; } function defaultSchema(schema) { var data = {}; for (var key in schema) { data[key] = defaultVal(schema[key]); } return data; } function validateAgainstSchema(obj, schema) { var data = {}; for (var key in obj) { if (!schema[key]) continue; data[key] = validateVal(obj[key], schema[key]); } return data; } function timeFromId(id) { return new Date(parseInt(id.toString().substring(0, 8), 16) * 1000); } function sanitizeBranch(branch) { var plugins = []; for (var i = 0; i < branch.plugins; i++) { plugins.push({id: branch.plugins[i].id, enabled: branch.plugins[i].enabled}); } return { plugins: plugins, public: branch.public, active: branch.active, deploy_on_green: branch.deploy_on_green, deploy_on_pull_request: branch.deploy_on_pull_request, runner: { id: branch.runner && branch.runner.id } }; } function sanitizeUser(user) { for (var i = 0; i < user.accounts.length; i++) { delete user.accounts[i].cache; } return user; } function sanitizeProject(project) { return { _id: project._id, name: project.name, branches: project.branches.map(sanitizeBranch), public: project.public, display_url: project.display_url, display_name: project.display_name, provider: { id: project.provider.id } }; } function gravatarDefault(email) { return gravatar.url(email, { d: 'identicon' }, true); }
JavaScript
0.000002
@@ -2153,49 +2153,595 @@ %7B%0A -var config = _.extend(%7B%7D, branch, sjson); +// Is this still a mongoose document?%0A if (typeof branch.toObject === 'function') %7B%0A branch = branch.toObject();%0A %7D%0A%0A // Copy all properties of the branch configuration to a new object (inherited properties are ignored, there%0A // shouldn't be any anyway). Then override all values with what is defined in the strider.json.%0A // Note that this overrides all plugin configuration.%0A var config = _.assign(%7B%7D, branch, sjson);%0A%0A // If the user requests to have plugin configurations merged (through the merge_plugins setting in the strider.json)%0A // merge the plugin configurations. %0A i @@ -2844,16 +2844,17 @@ ugins);%0A +%0A return
ce1db751d04ed5515e8857d248592a1f84fe2bbc
Make tabs work with back forward buttons.
static/js/billing/helpers.js
static/js/billing/helpers.js
var helpers = (function () { var exports = {}; exports.create_ajax_request = function (url, form_name, stripe_token = null) { var form = $("#" + form_name + "-form"); var form_loading_indicator = "#" + form_name + "_loading_indicator"; var form_input_section = "#" + form_name + "-input-section"; var form_success = "#" + form_name + "-success"; var form_error = "#" + form_name + "-error"; var form_loading = "#" + form_name + "-loading"; var numeric_inputs = ["licenses"]; loading.make_indicator($(form_loading_indicator), {text: 'Processing ...', abs_positioned: true}); $(form_input_section).hide(); $(form_error).hide(); $(form_loading).show(); var data = {}; if (stripe_token) { data.stripe_token = JSON.stringify(stripe_token.id); } form.serializeArray().forEach(function (item) { if (_.contains(numeric_inputs, item.name)) { data[item.name] = item.value; } else { data[item.name] = JSON.stringify(item.value); } }); $.post({ url: url, data: data, success: function () { $(form_loading).hide(); $(form_error).hide(); $(form_success).show(); if (_.contains(["autopay", "invoice"], form_name)) { if ("pushState" in history) { history.pushState("", document.title, location.pathname + location.search); } else { location.hash = ""; } } location.reload(); }, error: function (xhr) { $(form_loading).hide(); $(form_error).show().text(JSON.parse(xhr.responseText).msg); $(form_input_section).show(); }, }); }; exports.format_money = function (cents) { // allow for small floating point errors cents = Math.ceil(cents - 0.001); var precision; if (cents % 100 === 0) { precision = 0; } else { precision = 2; } // TODO: Add commas for thousands, millions, etc. return (cents / 100).toFixed(precision); }; exports.update_charged_amount = function (prices, schedule) { $("#charged_amount").text( exports.format_money(page_params.seat_count * prices[schedule]) ); }; exports.show_license_section = function (license) { $("#license-automatic-section").hide(); $("#license-manual-section").hide(); $("#automatic_license_count").prop('disabled', true); $("#manual_license_count").prop('disabled', true); var section_id = "#license-" + license + "-section"; $(section_id).show(); var input_id = "#" + license + "_license_count"; $(input_id).prop("disabled", false); }; exports.set_tab = function (page) { var hash = window.location.hash; if (hash) { $('#' + page + '-tabs.nav a[href="' + hash + '"]').tab('show'); $('html').scrollTop(0); } $('#' + page + '-tabs.nav-tabs a').click(function () { $(this).tab('show'); window.location.hash = this.hash; $('html').scrollTop(0); }); }; return exports; }()); if (typeof module !== 'undefined') { module.exports = helpers; } window.helpers = helpers;
JavaScript
0
@@ -3031,36 +3031,141 @@ -$(this).tab('show');%0A +window.location.hash = this.hash;%0A %7D);%0A%0A $(window).on('hashchange', function () %7B%0A $('#' + page + '-tabs.nav a%5Bhref=%22' + win @@ -3178,35 +3178,43 @@ cation.hash -= this.hash ++ '%22%5D').tab('show') ;%0A $(
257234c5a41d6ff2c9d619b8c7b846b2bc88e0f8
Fix faulty assistant hint. (#2045)
static/js/views/assistant.js
static/js/views/assistant.js
/** * Smart Assistant. * * A chat-style UI to control things with spoken and written commands. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const API = require('../api'); const App = require('../app'); const Constants = require('../constants'); // eslint-disable-next-line no-unused-vars const AssistantScreen = { /** * Initialise Assistant Screen. */ init: function() { this.messages = document.getElementById('assistant-messages'); this.hint = document.getElementById('assistant-hint'); this.avatar = document.getElementById('assistant-avatar'); this.textInput = document.getElementById('assistant-text-input'); this.textSubmit = document.getElementById('assistant-text-submit'); this.textInput.addEventListener('keyup', this.handleInput.bind(this)); this.textSubmit.addEventListener('click', this.handleSubmit.bind(this)); this.avatar.addEventListener('click', this.handleAvatarClick.bind(this)); this.refreshHint = this.refreshHint.bind(this); }, /** * Show Assistant screen. */ show: function() { document.getElementById('speech-wrapper').classList.add('assistant'); this.messages.scrollTop = this.messages.scrollHeight; if (this.messages.children.length === 0) { this.hint.classList.remove('hidden'); } else { this.hint.classList.add('hidden'); } App.gatewayModel.unsubscribe(Constants.REFRESH_THINGS, this.refreshHint); App.gatewayModel.subscribe( Constants.REFRESH_THINGS, this.refreshHint, true); }, refreshHint: function(things) { const commands = []; things.forEach((thingDescr) => { let types = thingDescr['@type']; if (!types || types.length === 0) { types = [thingDescr.selectedCapability]; } for (const type of types) { switch (type) { case 'OnOffSwitch': commands.push(`Turn the ${thingDescr.name} on`); break; case 'Light': if (thingDescr.properties.level) { commands.push(`Dim the ${thingDescr.name}`); } break; case 'ColorControl': commands.push(`Turn the ${thingDescr.name} red`); break; } } }); if (commands.length > 0) { const command = commands[Math.floor(Math.random() * commands.length)]; this.hint.textContent = `Try commands like "${command}"`; } }, submitCommand: function(text) { const opts = { method: 'POST', cache: 'default', body: JSON.stringify({text}), headers: { Authorization: `Bearer ${API.jwt}`, Accept: 'application/json', 'Content-Type': 'application/json', }, }; return fetch('/commands', opts).then((response) => { return Promise.all([Promise.resolve(response.ok), response.json()]); }).then((values) => { const [ok, body] = values; if (!ok) { let error = 'Sorry, something went wrong.'; if (body.hasOwnProperty('message')) { error = body.message; } throw new Error(error); } let verb, preposition = ''; switch (body.payload.keyword) { case 'make': verb = 'making'; break; case 'change': verb = 'changing'; break; case 'set': verb = 'setting'; preposition = 'to '; break; case 'dim': verb = 'dimming'; preposition = 'by '; break; case 'brighten': verb = 'brightening'; preposition = 'by '; break; case 'turn': case 'switch': default: verb = `${body.payload.keyword}ing`; break; } const value = body.payload.value ? body.payload.value : ''; const message = `OK, ${verb} the ${body.payload.thing} ${preposition}${value}.`; this.displayMessage( message, 'incoming' ); return { message, success: true, }; }).catch((e) => { const message = e.message || 'Sorry, something went wrong.'; this.displayMessage(message, 'incoming'); return { message, success: false, }; }); }, displayMessage: function(text, direction) { this.hint.classList.add('hidden'); const cls = direction === 'incoming' ? 'assistant-message-incoming' : 'assistant-message-outgoing'; const node = document.createElement('div'); node.classList.add(cls); node.innerText = text; this.messages.appendChild(node); this.messages.scrollTop = this.messages.scrollHeight; }, handleInput: function(e) { if (e.keyCode === 13) { const text = e.target.value; this.displayMessage(text, 'outgoing'); this.submitCommand(text); e.target.value = ''; } }, handleSubmit: function() { const text = this.textInput.value; this.displayMessage(text, 'outgoing'); this.submitCommand(text); this.textInput.value = ''; }, handleSpeech: function() { if (this.listening) { this.listening = false; this.stm.stop(); } else { this.stm.listen(); this.listening = true; } }, handleAvatarClick: function() { this.messages.innerHTML = ''; this.hint.classList.remove('hidden'); }, }; module.exports = AssistantScreen;
JavaScript
0.000001
@@ -2082,19 +2082,20 @@ ngDescr. -nam +titl e%7D on%60); @@ -2235,19 +2235,20 @@ ngDescr. -nam +titl e%7D%60);%0A @@ -2362,11 +2362,12 @@ scr. -nam +titl e%7D r
8cb1a21e8cb3a1344a0dcedb147e6a3d089333e6
Add PWD to execute path to be able to execute cmds on Windows.
make.js
make.js
require('shelljs/make'); require('shelljs/global'); // Targets target.all = function () { target.lint(); target.bundle(); target.test(); target.minify(); target.boilerplate(); }; target.highlighter = function () { console.log('Bundling highlighter...'); bundleHighlighter('src/remark/highlighter.js'); }; target.lint = function () { console.log('Linting...'); run('jshint src', {silent: true}); }; target['test-bundle'] = function () { console.log('Bundling tests...'); [ "require('should');", "require('sinon');" ] .concat(find('./test') .filter(function(file) { return file.match(/\.js$/); }) .map(function (file) { return "require('./" + file + "');" }) ) .join('\n') .to('_tests.js'); run('browserify _tests.js', {silent: true}).output.to('out/tests.js'); rm('_tests.js'); }; target.test = function () { target['test-bundle'](); console.log('Running tests...'); run('mocha-phantomjs test/runner.html'); }; target.bundle = function () { console.log('Bundling...'); bundleResources('src/remark/resources.js'); run('browserify src/remark.js', {silent: true}).output.to('out/remark.js'); }; target.boilerplate = function () { console.log('Generating boilerplate...'); generateBoilerplateSingle("boilerplate-single.html"); }; target.minify = function () { console.log('Minifying...'); run('uglifyjs remark.js', {silent: true}).output.to('out/remark.min.js'); }; // Helper functions var path = require('path') , config = require('./package.json').config , ignoredStyles = ['brown_paper', 'school_book', 'pojoaque'] ; function bundleResources (target) { var resources = { DOCUMENT_STYLES: JSON.stringify( less('src/remark.less')) , CONTAINER_LAYOUT: JSON.stringify( cat('src/remark.html')) }; cat('src/resources.js.template') .replace(/%(\w+)%/g, function (match, key) { return resources[key]; }) .to(target); } function bundleHighlighter (target) { var highlightjs = 'vendor/highlight.js/src/' , resources = { HIGHLIGHTER_STYLES: JSON.stringify( ls(highlightjs + 'styles/*.css').reduce(mapStyle, {})) , HIGHLIGHTER_ENGINE: cat(highlightjs + 'highlight.js') , HIGHLIGHTER_LANGUAGES: config.highlighter.languages.map(function (language) { return '{name:"' + language + '",create:' + cat(highlightjs + 'languages/' + language + '.js') + '}'; }).join(',') }; cat('src/highlighter.js.template') .replace(/%(\w+)%/g, function (match, key) { return resources[key]; }) .to(target); } function generateBoilerplateSingle(target) { var resources = { REMARK_MINJS: escape(cat('remark.min.js') // highlighter has a ending script tag as a string literal, and // that causes early termination of escaped script. Split that literal. .replace('"</script>"', '"</" + "script>"')) }; cat('src/boilerplate-single.html.template') .replace(/%(\w+)%/g, function (match, key) { return resources[key]; }) .to(target); } function mapStyle (map, file) { var key = path.basename(file, path.extname(file)) , tmpfile = path.join(tempdir(), 'remark.tmp') ; if (ignoredStyles.indexOf(key) === -1) { ('.hljs-' + key + ' {\n' + cat(file) + '\n}').to(tmpfile); map[key] = less(tmpfile); rm(tmpfile); } return map; } function less (file) { return run('lessc -x ' + file, {silent: true}).output.replace(/\n/g, ''); } function run (command, options) { var result = exec('node_modules/.bin/' + command, options); if (result.code !== 0) { if (!options || options.silent) { console.error(result.output); } exit(1); } return result; }
JavaScript
0
@@ -3680,17 +3680,26 @@ = exec( -' +pwd() + '/ node_mod
29fc4dc09f6e5808acd669508adf1789034c4f1c
use callbacks provided
tutor/src/models/payments.js
tutor/src/models/payments.js
import { BaseModel, identifiedBy, field, hasMany, } from './base'; import { action, observable, when } from 'mobx'; import loadjs from 'loadjs'; let EMBED_URL = ''; @identifiedBy('payments') export default class Payments extends BaseModel { static set embed_js_url(url) { EMBED_URL = url; } @observable isBusy = false; @observable errorMsg = '' @observable element; constructor() { super(); when( () => this.element && EMBED_URL, this.fetch, ); } @action.bound fetch() { this.isBusy = true; loadjs(EMBED_URL, { success: this.createIframe, error: (e) => this.errorMsg = `Unable to request assets: ${e}`, }); } @action.bound createIframe() { const { OSPayments } = window; this.remote = new OSPayments(this.params); this.remote.createIframe(this.element).then(() => { this.isBusy = false; }); } }
JavaScript
0
@@ -62,16 +62,49 @@ /base';%0A +import %7B extend %7D from 'lodash'; %0Aimport @@ -129,16 +129,25 @@ le, when +,computed %7D from @@ -421,16 +421,47 @@ element; +%0A @observable parentCallbacks; %0A%0A cons @@ -468,16 +468,23 @@ tructor( +options ) %7B%0A @@ -492,16 +492,44 @@ uper();%0A + this.options = options;%0A when @@ -595,24 +595,161 @@ );%0A %7D%0A%0A + close() %7B%0A if (this.remote) %7B%0A%0A %7D%0A %7D%0A%0A @computed get callbacks() %7B%0A return extend(%7B%7D, this.parentCallbacks, %7B%0A%0A %7D);%0A %7D%0A%0A @action.bo @@ -751,16 +751,18 @@ on.bound +%0A fetch() @@ -788,17 +788,16 @@ = true;%0A -%0A load @@ -945,16 +945,18 @@ on.bound +%0A createI @@ -1000,16 +1000,17 @@ window;%0A +%0A this @@ -1043,17 +1043,19 @@ his. -param +option s);%0A +%0A @@ -1145,12 +1145,12 @@ %7D);%0A +%0A %7D%0A%0A -%0A %7D%0A
bc85bce345e3037809808bee79717bc370a4b56c
fix mesh buffer dealocation
projects/OG-Web/web-engine/prototype/scripts/lib/four/four.buffer.js
projects/OG-Web/web-engine/prototype/scripts/lib/four/four.buffer.js
/** * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * Please see distribution for license. */ (function () { if (!window.Four) window.Four = {}; if (!Detector) throw new Error('Four.Buffer requires Detector'); /** * Buffer constructor * A buffer stores references to objects that require their webgl buffers cleared together */ window.Four.Buffer = function (renderer, scene) { var buffer = {}; buffer.arr = []; buffer.add = function (object) { buffer.arr.push(object); return object; }; buffer.clear = function (custom) { if (!custom && !buffer.arr.length) return; (function dealobj (val) { if (typeof val === 'object') scene.remove(val); if ($.isArray(val)) val.forEach(function (val) {dealobj(val);}); else if (val instanceof THREE.Mesh) { if (val.geometry) val.geometry.deallocate(); if (val.material) { if (val.material.materials) val.material.materials.forEach(function (val) {val.deallocate();}); else val.material.deallocate(); } } else if (val instanceof THREE.Texture) renderer.deallocateTexture(val); else if (val instanceof THREE.ParticleSystem) renderer.deallocateObject(val); else if (val instanceof THREE.Mesh) renderer.deallocateObject(val); else if (val instanceof THREE.Material) renderer.deallocateMaterial(val); else if (val instanceof THREE.Object3D && Detector.webgl) renderer.deallocateObject(val), dealobj(val.children); }(custom || buffer.arr)); if (!custom) buffer.arr = []; }; return buffer; }; })();
JavaScript
0
@@ -890,383 +890,8 @@ %7D);%0A - else if (val instanceof THREE.Mesh) %7B%0A if (val.geometry) val.geometry.deallocate();%0A if (val.material) %7B%0A if (val.material.materials) val.material.materials.forEach(function (val) %7Bval.deallocate();%7D);%0A else val.material.deallocate();%0A %7D%0A %7D%0A
35b82197ad3d6d56bf093b18d09cdda71f4e7ab5
fix blocke
lib/BlockExtractor.js
lib/BlockExtractor.js
'use strict'; require('classtool'); function spec() { var Block = require('bitcore/Block').class(), networks = require('bitcore/networks'), Parser = require('bitcore/util/BinaryParser').class(), fs = require('fs'), Buffer = require('buffer').Buffer, glob = require('glob'), async = require('async'); function BlockExtractor(dataDir, network) { var self = this; var path = dataDir + '/blocks/blk*.dat'; self.dataDir = dataDir; self.files = glob.sync(path); self.nfiles = self.files.length; if (self.nfiles === 0) throw new Error('Could not find block files at: ' + path); self.currentFileIndex = 0; self.isCurrentRead = false; self.currentBuffer = null; self.currentParser = null; self.network = network === 'testnet' ? networks.testnet: networks.livenet; self.magic = self.network.magic.toString('hex'); } BlockExtractor.prototype.currentFile = function() { var self = this; return self.files[self.currentFileIndex]; }; BlockExtractor.prototype.nextFile = function() { var self = this; if (self.currentFileIndex < 0) return false; var ret = true; self.isCurrentRead = false; self.currentBuffer = null; self.currentParser = null; if (self.currentFileIndex < self.nfiles - 1) { self.currentFileIndex++; } else { self.currentFileIndex=-1; ret = false; } return ret; }; BlockExtractor.prototype.readCurrentFileSync = function() { var self = this; if (self.currentFileIndex < 0 || self.isCurrentRead) return; self.isCurrentRead = true; var fname = self.currentFile(); if (!fname) return; var stats = fs.statSync(fname); var size = stats.size; console.log('Reading Blockfile %s [%d MB]', fname, parseInt(size/1024/1024)); var fd = fs.openSync(fname, 'r'); var buffer = new Buffer(size); fs.readSync(fd, buffer, 0, size, 0); self.currentBuffer = buffer; self.currentParser = new Parser(buffer); }; BlockExtractor.prototype.getNextBlock = function(cb) { var self = this; var b; var magic; async.series([ function (a_cb) { async.whilst( function() { return (!magic); }, function(w_cb) { self.readCurrentFileSync(); if (self.currentFileIndex < 0) return cb(); magic = self.currentParser ? self.currentParser.buffer(4).toString('hex') : null ; if (!self.currentParser || self.currentParser.eof()) { magic = null; if (self.nextFile()) { console.log('Moving forward to file:' + self.currentFile() ); return w_cb(); } else { console.log('Finished all files'); return cb(); } } else { return w_cb(); } }, a_cb); }, function (a_cb) { if (magic !== self.magic) { var e = new Error('CRITICAL ERROR: Magic number mismatch: ' + magic + '!=' + self.magic); return a_cb(e); } // spacer? self.currentParser.word32le(); return a_cb(); }, function (a_cb) { b = new Block(); b.parse(self.currentParser); b.getHash(); return a_cb(); }, ], function(err) { return cb(err,b); }); }; return BlockExtractor; } module.defineClass(spec);
JavaScript
0.000001
@@ -49,16 +49,17 @@ pec() %7B%0A +%0A var Bl
b1597ee6788bf10d72fa49dfdc2e42894f9ffce3
fix tab disabled onClick bug
src/react/Tab.js
src/react/Tab.js
import React from 'react'; class Tab extends React.Component { render() { const {activeTab, tabId, title, onClick, disabled, className = ''} = this.props; const dataTestId = this.props['data-test-id']; return (<li className={activeTab === tabId ? 'sdc-tab sdc-tab-active ' + className : 'sdc-tab ' + className} onClick={onClick} data-test-id={dataTestId} role='tab' disabled={disabled}>{title}</li>); } } export default Tab;
JavaScript
0
@@ -325,16 +325,29 @@ nClick=%7B +!disabled && onClick%7D
e3d3b4141e0ec146e672f0ae255c66eb034401eb
add TODO
src/rest/list.js
src/rest/list.js
"use strict"; import countParser from '../parser/countParser'; import filterParser from '../parser/filterParser'; import orderbyParser from '../parser/orderbyParser'; import skipParser from '../parser/skipParser'; import topParser from '../parser/topParser'; import selectParser from '../parser/selectParser'; export default (req, MongooseModel, options) => { return new Promise((resolve, reject) => { let resData = {}; let query = MongooseModel.find(); let errHandle = (err) => { err.status = 500; return reject(err); }; let err = countParser(resData, MongooseModel, req.query.$count, req.query.$filter); if(err) { return errHandle(err); } err = filterParser(query, req.query.$filter); if(err) { return errHandle(err); } err = orderbyParser(query, req.query.$orderby || options.orderby); if(err) { return errHandle(err); } err = skipParser(query, req.query.$skip, options.maxSkip); if(err) { return errHandle(err); } err = topParser(query, req.query.$top, options.maxTop); if(err) { return errHandle(err); } err = selectParser(query, req.query.$select); if(err) { return errHandle(err); } // TODO // $expand=Customers/Orders // $search query.exec((err, data) => { resData.value = data; return resolve({entity: resData}); }); }); };
JavaScript
0
@@ -546,24 +546,50 @@ r);%0A %7D;%0A%0A +%0A // TODO: use Promise%0A let err
f0b3e9199ccfe2aea3c218a5da72bbf257fe233b
Fix setting api_host
lib/Oriskami/index.js
lib/Oriskami/index.js
var Resource = require("../Resource") , bindingName = "Oriskami/v1 NodeBindings/" , httpTimeout = 120000 /* * Wrapper factory of the Oriskami API client * @token [String] required obtained from admin interface * @version [String] default to 'latest' */ function Oriskami(token, version, resources){ version = version || "*" this._api = { "protocol" : "https" , "timeout" : httpTimeout , "resources" : resources , "api_host" : "api.oriskami.com" , "revokedCerts" : "" , "headers" : { "Accept" : "application/json" , "Content-Type" : "application/json" , "Accept-Version": version.replace("\n","") , "User-Agent" : (bindingName + version).replace("\n","") },"request" : { "port" : "443" , "version" : version , "ciphers" : "DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5" } } this._api.request.host = this._api.api_host this.set("auth", token) } /* * Accessor (GET) function for the Oriskami wrapper * @key [String] name of the private attribute */ Oriskami.prototype.get = function(key ){ return this._api[key] } /* * Accessor (SET) function for the Oriskami wrapper * @key [String] name of the private attribute * @value [String, number, object] attribute value */ Oriskami.prototype.set = function(key, value){ if(key === "timeout") value = value || httpTimeout this._api[key] = value } /* * Extend function to add resources to 'this' running instance * @resource [String] name of the resource to add */ Oriskami.prototype.extend = function(resourceName, resourcePath){ this[resourceName] = new Resource(this, resourceName, resourcePath) } module.exports = Oriskami
JavaScript
0.000005
@@ -1470,25 +1470,100 @@ == %22 -timeout%22) value = +api_host%22) %7B %0A this._api.request.host = value %0A %7D else %7B%0A value = key === %22timeout%22 ? val @@ -1579,17 +1579,27 @@ pTimeout -%0A + : value%0A this._ @@ -1615,16 +1615,20 @@ = value%0A + %7D%0A %7D%0A%0A/*%0A *
a7907b222857976f5f2f23a91e1a8c43d2fdc429
Fix whitespace
ubcpi/static/js/src/ubcpi.js
ubcpi/static/js/src/ubcpi.js
/* Javascript for PeerInstructionXBlock. */ function PeerInstructionXBlock(runtime, element, data) { "use strict"; var handlerUrl = runtime.handlerUrl(element, 'submit_answer'); var submitButton = $('.ubcpi_submit', element); var enableSubmit = function () { $('.ubcpi_submit', element).removeAttr('disabled'); }; $('input[type="radio"]', element).click(function (eventObject) { var clicked = this; var answer = clicked.value; console.log("Submitting ", answer); $.ajax({ type: "POST", url: handlerUrl, data: JSON.stringify({"q": answer}), success: function ( data, textStatus, jqXHR ) { enableSubmit(); }, error: function( jqXHR, textStatus, errorThrown ) { } }); }); $(function ($) { var app = angular.module('ubcpi', []); app.controller('ReviseController', function ($scope) { var isThisIsolated = 0; $scope.test = isThisIsolated; $scope.rnd = Math.random(); $scope.inc = function () { isThisIsolated += 1; $scope.test = isThisIsolated; }; }); angular.bootstrap(element, ['ubcpi']); /* Here's where you'd do things on page load. */ var savedAnswer = data.answer; // Handle null case if( !savedAnswer ) { return; } else { enableSubmit(); } $('input[value="' + savedAnswer + '"]', element).prop( 'checked', 'checked' ); }); }
JavaScript
0.999999
@@ -667,17 +667,16 @@ nction ( - data, te @@ -690,17 +690,16 @@ s, jqXHR - ) %7B%0A @@ -768,18 +768,18 @@ function -( +( jqXHR, t @@ -800,17 +800,16 @@ orThrown - ) %7B%0A @@ -1381,24 +1381,16 @@ answer;%0A - %0A @@ -1420,18 +1420,18 @@ if -( +( !savedAn @@ -1434,17 +1434,16 @@ edAnswer - ) %7B%0A @@ -1584,17 +1584,16 @@ t).prop( - 'checked @@ -1604,17 +1604,16 @@ checked' - );%0A%0A
aa25c46be343327f782dd87aa8847c7d4ba685ba
Add Splice to `mvcc.js`.
mvcc.js
mvcc.js
exports.advance = require('advance') exports.designate = require('designate') exports.dilute = require('dilute') exports.homogenize = require('homogenize') exports.revise = require('revise') exports.riffle = require('riffle') exports.twiddle = require('twiddle')
JavaScript
0
@@ -215,24 +215,59 @@ e('riffle')%0A +exports.splice = require('splice')%0A exports.twid
906d9d0a920c9a93119e3845fc5200ef63c607e5
Transform annotations when joining text nodes.
src/text_node.js
src/text_node.js
"use strict"; var _ = require("underscore"); var Operator = require('substance-operator'); var SRegExp = require("substance-regexp"); var ObjectOperation = Operator.ObjectOperation; var TextOperation = Operator.TextOperation; var Node = require('./node'); // Substance.Text // ----------------- // var Text = function(node, document) { Node.call(this, node, document); }; Text.Prototype = function() { this.getUpdatedCharPos = function(op) { if (op.path[1] === "content") { var lastChange = Operator.Helpers.last(op.diff); if (lastChange.isInsert()) { return lastChange.pos+lastChange.length(); } else if (lastChange.isDelete()) { return lastChange.pos; } } return -1; }; this.getLength = function() { return this.properties.content.length; }; this.insertOperation = function(charPos, text) { return ObjectOperation.Update([this.properties.id, "content"], TextOperation.Insert(charPos, text)); }; this.deleteOperation = function(startChar, endChar) { var content = this.properties.content; return ObjectOperation.Update([this.properties.id, "content"], TextOperation.Delete(startChar, content.substring(startChar, endChar)), "string"); }; this.prevWord = function(charPos) { var content = this.properties.content; // Matches all word boundaries in a string var wordBounds = new SRegExp(/\b\w/g).match(content); var prevBounds = _.select(wordBounds, function(m) { return m.index < charPos; }, this); // happens if there is some leading non word stuff if (prevBounds.length === 0) { return 0; } else { return _.last(prevBounds).index; } }; this.nextWord = function(charPos) { var content = this.properties.content; // Matches all word boundaries in a string var wordBounds = new SRegExp(/\w\b/g).match(content.substring(charPos)); // at the end there might be trailing stuff which is not detected as word boundary if (wordBounds.length === 0) { return content.length; } // before, there should be some boundaries else { var nextBound = wordBounds[0]; return charPos + nextBound.index + 1; } }; this.canJoin = function(other) { return (other instanceof Text); }; this.join = function(doc, other) { var pos = this.properties.content.length; var text = other.content; doc.update([this.id, "content"], [pos, text]); }; }; Text.Prototype.prototype = Node.prototype; Text.prototype = new Text.Prototype(); Text.prototype.constructor = Text; Node.defineProperties(Text.prototype, ["content"]); module.exports = Text;
JavaScript
0
@@ -2463,16 +2463,279 @@ text%5D);%0A + var annotations = doc.indexes%5B%22annotations%22%5D.get(other.id);%0A%0A _.each(annotations, function(anno) %7B%0A doc.set(%5Banno.id, %22path%22%5D, %5Bthis.properties.id, %22content%22%5D);%0A doc.set(%5Banno.id, %22range%22%5D, %5Banno.range%5B0%5D+pos, anno.range%5B1%5D+pos%5D);%0A %7D, this);%0A%0A %7D;%0A%0A%7D;
afe61d61ac4bc63e96024e40b91da9dd4492aeb2
Fix recently introduced errors in setting of Tool#_document.
src/tool/Tool.js
src/tool/Tool.js
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Distributed under the MIT license. See LICENSE file for details. * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * All rights reserved. */ var Tool = this.Tool = ToolHandler.extend(new function() { function viewToArtwork(event, document) { var point = Event.getOffset(event); // TODO: always the active view? return document.activeView.viewToArtwork(point); }; return { beans: true, initialize: function(handlers, doc) { this.base(handlers); // Create events once, so they can be removed easily too. var that = this, curPoint; var dragging = false; this.events = { mousedown: function(event) { curPoint = viewToArtwork(event, that._document); that.onHandleEvent('mouse-down', curPoint, event); if (that.onMouseDown) that._document.redraw(); if (that.eventInterval != null) { this.timer = setInterval(that.events.mousemove, that.eventInterval); } dragging = true; }, mousemove: function(event) { // If the event was triggered by a touch screen device, // prevent the default behaviour, as it will otherwise // scroll the page: if (event && event.targetTouches) event.preventDefault(); var point = event && viewToArtwork(event, that._document); // If there is only an onMouseMove handler, call it when // the user is dragging var onlyMove = !!(!that.onMouseDrag && that.onMouseMove); if (dragging && !onlyMove) { curPoint = point || curPoint; if (curPoint) that.onHandleEvent('mouse-drag', curPoint, event); } else if (!dragging || onlyMove) { that.onHandleEvent('mouse-move', point, event); } if (that.onMouseMove || that.onMouseDrag) that._document.redraw(); }, mouseup: function(event) { if (dragging) { curPoint = null; if (that.eventInterval != null) clearInterval(this.timer); that.onHandleEvent('mouse-up', viewToArtwork(event, that._document), event); if (that.onMouseUp) that._document.redraw(); dragging = false; } }, touchmove: function(event) { that.events.mousemove(event); }, touchstart: function(event) { that.events.mousedown(event); }, touchend: function(event) { that.events.mouseup(event); } }; if (paper.document) { // Remove old events first. if (this._document) Event.remove(this._document.canvas, this.events); this._document = doc || paper.document; Event.add(doc.canvas, this.events); } }, getDocument: function() { return this._document; }, /** * The fixed time delay between each call to the {@link #onMouseDrag} * event. Setting this to an interval means the {@link #onMouseDrag} * event is called repeatedly after the initial {@link #onMouseDown} * until the user releases the mouse. * * Sample code: * <code> * // Fire the onMouseDrag event once a second, * // while the mouse button is down * tool.eventInterval = 1000; * </code> * * @return the interval time in milliseconds */ eventInterval: null }; });
JavaScript
0
@@ -2606,41 +2606,12 @@ %09%7D;%0A -%09%09%09%0A%09%09%09if (paper.document) %7B %0A%09%09%09 -%09 // R @@ -2634,17 +2634,16 @@ first.%0A -%09 %09%09%09if (t @@ -2661,17 +2661,16 @@ nt)%0A%09%09%09%09 -%09 Event.re @@ -2711,17 +2711,16 @@ vents);%0A -%09 %09%09%09this. @@ -2738,29 +2738,10 @@ doc - %7C%7C paper.document ;%0A -%09 %09%09%09E @@ -2775,21 +2775,16 @@ vents);%0A -%09%09%09%7D%0A %09%09%7D,%0A%0A%09%09
5baee5243664d04661576714de599a996447bd52
Remove console.log
src/tool/line.js
src/tool/line.js
(function(d3, fc) { 'use strict'; fc.tool.line = function() { var xScale = d3.time.scale(), yScale = d3.scale.linear(), value = fc.util.fn.identity, keyValue = fc.util.fn.index, label = value, decorate = fc.util.fn.noop, orient = 'horizontal'; var dataJoin = fc.util.dataJoin() .selector('g.annotation') .element('g') .attrs({'class': 'annotation'}); var line = function(selection) { selection.each(function(data) { // the value scale which the annotation 'value' relates to, the crossScale // is the other. Which is which depends on the orienation! var valueScale, crossScale, translation, lineProperty, handleOne, handleTwo, textAttributes = {x: -5, y: -5}; switch (orient) { case 'horizontal': translation = function(a, b) { return 'translate(' + a + ', ' + b + ')'; }; lineProperty = 'x2'; crossScale = xScale; valueScale = yScale; handleOne = 'left-handle'; handleTwo = 'right-handle'; break; case 'vertical': translation = function(a, b) { return 'translate(' + b + ', ' + a + ')'; }; lineProperty = 'y2'; crossScale = yScale; valueScale = xScale; textAttributes.transform = 'rotate(-90)'; handleOne = 'bottom-handle'; handleTwo = 'top-handle'; break; default: throw new Error('Invalid orientation'); } // ordinal axes have a rangeExtent function, this adds any padding that // was applied to the range. This functions returns the rangeExtent // if present, or range otherwise function range(scale) { console.log(scale.rangeExtent ? scale.rangeExtent() : scale.range()); return scale.rangeExtent ? scale.rangeExtent() : scale.range(); } var scaleRange = range(crossScale), // the transform that sets the 'origin' of the annotation containerTransform = function(d) { var transform = valueScale(value(d)); return translation(scaleRange[0], transform); }, scaleWidth = scaleRange[1] - scaleRange[0]; var container = d3.select(this); // Create a group for each line var g = dataJoin(container, data); // create the outer container and line var enter = g.enter() .attr('transform', containerTransform); enter.append('line') .attr(lineProperty, scaleWidth); // create containers at each end of the annotation enter.append('g') .classed(handleOne, true); enter.append('g') .classed(handleTwo, true) .attr('transform', translation(scaleWidth, 0)) .append('text') .attr(textAttributes); // Update // translate the parent container to the left hand edge of the annotation g.attr('transform', containerTransform); // update the elements that depend on scale width g.select('line') .attr(lineProperty, scaleWidth); g.select('g.' + handleTwo) .attr('transform', translation(scaleWidth, 0)); // Update the text label g.select('text') .text(label); decorate(g); }); }; line.xScale = function(x) { if (!arguments.length) { return xScale; } xScale = x; return line; }; line.yScale = function(x) { if (!arguments.length) { return yScale; } yScale = x; return line; }; line.value = function(x) { if (!arguments.length) { return value; } value = d3.functor(x); return line; }; line.keyValue = function(x) { if (!arguments.length) { return keyValue; } keyValue = d3.functor(x); return line; }; line.label = function(x) { if (!arguments.length) { return label; } label = d3.functor(x); return line; }; line.decorate = function(x) { if (!arguments.length) { return decorate; } decorate = x; return line; }; line.orient = function(x) { if (!arguments.length) { return orient; } orient = x; return line; }; return line; }; }(d3, fc));
JavaScript
0.000004
@@ -2192,98 +2192,8 @@ ) %7B%0A - console.log(scale.rangeExtent ? scale.rangeExtent() : scale.range());%0A
8977350ef77a76b61ebc68fe7197a574c293fb85
fix Team Drives anchor
src/views/FAQ.js
src/views/FAQ.js
'use strict'; import React from 'react'; import Warning from '../components/icons/Warning'; export default function FAQ() { return ( <main className="doc"> <h2>FAQ</h2> <a name="top" /> <ul> <li> <a href="#longerThan2Mins"> The copying has been paused longer than 2 minutes and it isn't complete. What do I do? </a> </li> <li> <a href="#copyBetweenDomains"> Can I use this app to copy a folder between domains? </a> </li> <li> <a href="#whenIsItDone">How do I know when it is done?</a> </li> <li> <a href="#notEverythingCopied"> It didn't copy everything - what do I do? </a> </li> <li> <a href="#multipleAccounts"> How do I sign into a different account with this app? </a> </li> <li> <a href="#infiniteLoop"> HELP! The copying is stuck in an infinite loop! What do I do? </a> </li> <li> <a href="#uninstall"> How do I unintall the app and remove all permissions? </a> </li> <li> <a href="#openissue">How do I report a bug in the app?</a> </li> <li> <a href="#teamdrives">Does this app support Team Drives?</a> </li> </ul> <h3> <a name="longerThan2Mins" />The copying has been paused longer than 2 minutes and it isn't complete. What do I do? </h3> <div> When the app stops, you can use the "Resume" button to restart the copying. When selecting the folder to resume, you must select the{' '} <b>in-progress</b> folder, <b>not</b> the original.<br /> <br /> For example, if you are creating a copy of "Folder A" called "Copy of Folder A", you should select "Copy of Folder A" when you resume the copying. Selecting the original folder will return an error. </div> <a href="#top">Top</a> <h3> <a name="copyBetweenDomains" />Can I use this app to copy a folder between domains? </h3> <div> Yes! Follow the steps below: <ol> <li>Log into the account that owns the folder ("Account 1")</li> <li> Share the folder with the domain to which you'd like to copy ("Account 2") </li> <li>Open an private/incognito window and log into Account 2</li> <li> Go to the "Shared with me" section, right click the folder, and select "Add to Drive" </li> <li>Open the app, and select the folder that has been shared</li> <li>Create a copy and Account 2 will now be the owner</li> </ol> </div> <a href="#top">Top</a> <h3> <a name="whenIsItDone" />How do I know when it is done? </h3> <div> You will know it is complete when the Copy Log says "Complete" in cell C2. In addition, the cell will highlight green. </div> <a href="#top">Top</a> <h3> <a name="notEverythingCopied" />It didn't copy everything - what do I do? </h3> <div> Typically this is due to server errors encountered while copying. You should be able to do one of the following to resolve this situation: <ol> <li> Audit the Copy Log for any errors, and manually copy those files </li> <li> Restart the copy process. Typically, it is best if you wait a few hours if you ran into significant copying errors </li> </ol> </div> <a href="#top">Top</a> <h3> <a name="multipleAccounts" />How do I sign into a different account with this app? </h3> <div> There isn't a handy Account Switcher like you'll find in native Google Apps.* However, you can try to use the link at the top of the page which should re-direct you and allow you to sign if from a different account.<br /> <br /> If that fails, I would recommend signing in from another browser, or opening an incognito/private window and accessing the app that way. <br /> <br />*If you think this is a good feature, please feel free to open an{' '} <a className="github-button" href="https://github.com/ericyd/gdrive-copy/issues" aria-label="Issue ericyd/gdrive-copy on GitHub" target="_blank" > <Warning width="1em" height="1em" /> Issue </a>{' '} on Github., or better yet, contribute to the repo! 'Cuz I don't know how to add an Account Switcher, otherwise I would have done it already :) </div> <a href="#top">Top</a> <h3> <a name="infiniteLoop" />HELP! The copying is stuck in an infinite loop! What do I do? </h3> <div> Please use the "Pause" function built into the app and open an{' '} <a className="github-button" href="https://github.com/ericyd/gdrive-copy/issues" aria-label="Issue ericyd/gdrive-copy on GitHub" target="_blank" > <Warning width="1em" height="1em" /> Issue </a>{' '} </div> <a href="#top">Top</a> <h3> <a name="uninstall" />How do I unintall the app and remove all permissions? </h3> <div> To quote{' '} <a href="https://webapps.stackexchange.com/a/30849"> the excellent answer on stackexchange: </a> <ol> <li> Go to <a href="https://accounts.google.com">accounts.google.com</a> </li> <li> Under "Sign-in &amp; security" tab click "Connected apps &amp; sites" </li> <li> Under the section "Apps connected to your account", click on MANAGE APPS: </li> <li>Select app you want &amp; click REMOVE button</li> </ol> </div> <a href="#top">Top</a> <h3> <a name="openissue" />How do I report a bug in the app? </h3> <div> If you have found a bug that is not covered in these FAQs, please open an <a className="github-button" href="https://github.com/ericyd/gdrive-copy/issues" aria-label="Issue ericyd/gdrive-copy on GitHub" target="_blank" > <Warning width="1em" height="1em" /> Issue </a>{' '} on Github. </div> <a href="#top">Top</a> <h3> <a href="#teamdrives" />Does this app support Team Drives? </h3> <div>No.</div> <a href="#top">Top</a> </main> ); }
JavaScript
0
@@ -6774,39 +6774,38 @@ %3Ch3%3E%0A %3Ca -href +name =%22 -# teamdrives%22 /%3EDo
f46a047adc3592555796a3545a4b99acda3226d5
Remove unused r.js configs.
public/js/app.build.js
public/js/app.build.js
({ baseDir: '.', dir: '../../public-build/js', mainConfigFile: 'index.js', modules: [ {name: 'index'}, { name: 'controllers/ViewTimeline', exclude: [ ] }, { name: 'controllers/ViewDashboard' }, { name: 'controllers/ViewEvent', exclude: [ ] } ], optimize: "none", useStrict: true, wrap: false })
JavaScript
0
@@ -105,39 +105,32 @@ 'index'%7D,%0A %7B -%0A name: 'controlle @@ -149,47 +149,16 @@ ine' -,%0A exclude: %5B%0A %5D%0A %7D,%0A %7B %0A @@ -145,39 +145,32 @@ imeline'%7D,%0A %7B -%0A name: 'controlle @@ -190,21 +190,16 @@ ard' -%0A %7D,%0A %7B %0A @@ -194,23 +194,16 @@ %7D,%0A %7B -%0A name: 'c @@ -227,39 +227,8 @@ ent' -,%0A exclude: %5B%0A %5D%0A %7D%0A
8f6c80adc96bab91a5c35359dea1306ffa9d05c2
Fix manufacturer filter bug
public/js/dataparse.js
public/js/dataparse.js
// ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ // ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ // Brannon's sockets magix ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ // ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ // ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ var probeData = { numMacs: 0, macs: {} }; var filter = { manufacturer: "", networks: [], time: {} }; var rawCSV = undefined; var vendorDictionary = {}; createVendorDictionary(); $.ajax({ url: "data/probes.csv", success: function(data) { rawCSV = data; parseCSVToProbeData(); applyFilter(); }, error: function(err){ throw err; } }); var socket = io.connect("http://" + window.location.host); socket.on('probeReceived', function (probe) { // add the probe to our master probeData object addProbe(probe.mac, probe.ssid, probe.timestamp, false); }); function createVendorDictionary() { if (vendor) { for (var i = 0; i < vendor.mapping.length; i++) { if (!vendorDictionary.hasOwnProperty(vendor.mapping[i].mac_prefix)) { vendorDictionary[vendor.mapping[i].mac_prefix] = vendor.mapping[i].vendor_name; } } } } function parseCSVToProbeData() { if (rawCSV != undefined) { var lines = rawCSV.split('\n'); for (var i = 0; i < lines.length; i++) { var probe = lines[i].split(','); if (probe.length == 3) { addProbe(probe[0], probe[1], probe[2], true); } } } } function addProbe(mac, ssid, timestamp, fromCSV) { onBeforeProbeAdded(mac, ssid, timestamp, fromCSV); if (!probeData.macs.hasOwnProperty(mac)) { probeData.macs[mac] = {}; probeData.macs[mac].knownNetworks = []; probeData.macs[mac].lastSeen = 0; probeData.macs[mac].timesSeen = 0; probeData.macs[mac].mac = mac; probeData.numMacs++; } probeData.macs[mac].lastSeen = timestamp; probeData.macs[mac].timesSeen++; if (probeData.macs[mac].knownNetworks.indexOf(ssid) == -1) { probeData.macs[mac].knownNetworks.push(ssid); } onProbeAdded(mac, ssid, timestamp, fromCSV); } function onBeforeProbeAdded(mac, ssid, timestamp, fromCSV) { if(probeData.macs.hasOwnProperty(mac)) { flapButterfly(mac, ssid); } else { makeButterfly(mac, ssid); } } function onProbeAdded(mac, ssid, timestamp, fromCSV) { var time = moment(parseInt(timestamp)).format('YYYY-MM-DD HH:mm:ss'); //$('#dump').prepend(time + ' MAC: ' + mac + ' SSID: ' + ssid + '\n'); } // Filtering ////////////////////////////////////////////////////////////////////////// // update the DOM with butterflies that pass filter function applyFilter() { var macs = getFilteredMacs(); // clear #net $('#net').empty(); if (macs.length > 0) { for (var i = 0; i < macs.length; i++) { makeButterfly( macs[i].mac, macs[i].knownNetworks ); } } else { // no results... } } // resets the global filter var function clearFilter() { filter = { manufacturer: "", networks: [], time: {} }; } // returns an array of macs that pass all filters function getFilteredMacs() { // get an array of filtered mac addresses return _.filter(probeData.macs, function(macObj, mac){ // filter networks if (filter.networks.length > 0 && !_.some(macObj.knownNetworks, function(network){ return _.contains(filter.networks, network) })){ return false; }; // filter manufacturer if (filter.manufacturer != "" && (!vendorDictionary.hasOwnProperty(mac.substring(0, 8)) || vendorDictionary[mac.substring(0, 8)] != filter.manufacturer)) { return false; } // TODO: filter using all collected timestamps if (filter.time.from != undefined && filter.time.to != undefined && !(macObj.lastSeen >= filter.time.from && macObj.lastSeen <= filter.time.to)) { return false; } return true; }); }
JavaScript
0
@@ -3478,18 +3478,16 @@ , mac)%7B%0A -%09%09 %0A%09%09// fi @@ -3778,16 +3778,30 @@ ng(0, 8) +.toUpperCase() ) %7C%7C ven @@ -3833,16 +3833,30 @@ ng(0, 8) +.toUpperCase() %5D != fil
09fd782e5f25dd675107b9972f2b79624f4045d3
add commentlist component
public/scripts/main.js
public/scripts/main.js
// generate sudo UUID var generate = function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; var Post = React.createClass({ loadCommentsFromServer: function() { $.ajax({ url: this.props.url, dataType: 'json', cache: false, success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, handleCommentSubmit: function(comment) { var comments = this.state.data; var newComments = comments.concat([comment]); this.setState({data: newComments}); $.ajax({ url: this.props.url, dataType: 'json', type: 'POST', data: comment, success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, getInitialState: function() { return {data: []}; }, componentDidMount: function() { this.loadCommentsFromServer(); setInterval(this.loadCommentsFromServer, this.props.pollInterval); }, render: function() { var actions = this.handleCommentSubmit; return ( <div className="post"> <h1>Comments</h1> <CommentList data={this.state.data} actions={actions}/> </div> ); } });
JavaScript
0.000001
@@ -1560,12 +1560,559 @@ );%0A %7D%0A%7D);%0A +%0Avar CommentList = React.createClass(%7B%0A%0A%09%0A%09render: function() %7B %0A%09%09var that = this; %0A%09%09var com = %5B%5D; %0A%09%09for (var comment in sorted_comments) %7B%0A %09%09if (current_parent === sorted_comments%5Bcomment%5D.parentid) %7B%09%09%0A %09%09com.push(sorted_comments%5Bcomment%5D); %0A %09%09%7D%0A %09%09current_parent = sorted_comments%5Bcomment%5D.id; %0A %09%09console.log(current_parent)%0A%09%09%7D%0A%09%09%0A%09%09return (%0A%09%09%09%3CComment author=%7Bcomment.author%7D body=%7Bcomment.text%7D key=%7Bindex%7D id=%7Bcomment.id%7D parentid=%7Bcomment.parentid%7D actions=%7Bthat.props.actions%7D%3E%0A%09%09%09%09%7Bcomment.text%7D%0A%09%09%09%3C/Comment%3E %0A%09%09);%0A%09%7D%0A%7D);%0A
1d59a27ae48bd1180e82e2750fb86d5ea9beb479
Fix for adding XR/none rels.
rest/src/main/webapp/app/page/edit/relationships/editRelationship.js
rest/src/main/webapp/app/page/edit/relationships/editRelationship.js
// Edit relationship controller tsApp.controller('EditRelationshipModalCtrl', [ '$scope', '$uibModalInstance', '$uibModal', 'utilService', 'metadataService', 'contentService', 'metaEditingService', 'selected', 'lists', 'user', 'action', function($scope, $uibModalInstance, $uibModal, utilService, metadataService, contentService, metaEditingService, selected, lists, user, action) { console.debug('Entered edit relationship modal control', lists, action); // Scope vars $scope.selected = selected; $scope.lists = lists; $scope.user = user; $scope.action = action; $scope.toConcepts = []; $scope.toConcept = null; $scope.overrideWarnings = false; $scope.selectedRelationshipType = 'RO'; $scope.acceptedRelationshipTypeStrings = [ 'RO', 'RB', 'RN', 'RQ' ]; $scope.acceptedRelationshipTypes = [ { 'key' : '', 'value' : 'XR (none)' } ]; $scope.warnings = []; $scope.errors = []; $scope.selectedWorkflowStatus = 'NEEDS_REVIEW'; $scope.workflowStatuses = [ 'NEEDS_REVIEW', 'READY_FOR_PUBLICATION' ]; $scope.defaultOrder = true; // Callbacks for finder $scope.callbacks = { addComponent : addFinderComponent }; utilService.extendCallbacks($scope.callbacks, metadataService.getCallbacks()); utilService.extendCallbacks($scope.callbacks, contentService.getCallbacks()); // Init modal function initialize() { for (var i = 0; i < $scope.lists.concepts.length; i++) { if ($scope.lists.concepts[i].id != $scope.selected.component.id) { $scope.toConcepts.push($scope.lists.concepts[i]); } } if ($scope.toConcepts.length == 1) { $scope.toConcept = $scope.toConcepts[0]; } // if selected relationship, add to prospective list // set default from_concept if ($scope.selected.relationship) { contentService.getConcept($scope.selected.relationship.toId, $scope.selected.project.id) .then(function(data) { var found = false; for (var i = 0; i < $scope.toConcepts.length; i++) { if ($scope.toConcepts[i].id == data.id) { found = true; } } if (!found) { $scope.toConcepts.push(data); } $scope.toConcept = data; $scope.selectedRelationshipType = $scope.selected.relationship.relationshipType; }); } else { $scope.toConcept = $scope.toConcepts[0]; } // compute accepted relationship types if (!$scope.selected.component.publishable) { $scope.acceptedRelationshipTypeStrings.push('BRO'); $scope.acceptedRelationshipTypeStrings.push('BRN'); $scope.acceptedRelationshipTypeStrings.push('BBT'); } for (var i = 0; i < $scope.selected.metadata.relationshipTypes.length; i++) { if ($scope.acceptedRelationshipTypeStrings .includes($scope.selected.metadata.relationshipTypes[i].key)) { $scope.acceptedRelationshipTypes.push($scope.selected.metadata.relationshipTypes[i]); } } } // Perform insert rel $scope.addRelationship = function() { $scope.errors = []; // Only allow bequeathal to publishable if (!$scope.toConcept.publishable && $scope.selectedRelationshipType.match(/BR./)) { $scope.errors .push("Illegal attempt to create a bequeathal relationship to an unpublishable concept"); return; } var relationship = { assertedDirection : false, fromId : $scope.selected.component.id, fromName : $scope.selected.component.name, fromTerminology : $scope.selected.component.terminology, fromTerminologyId : $scope.selected.component.terminologyId, fromVersion : $scope.selected.component.version, group : null, hierarchical : false, inferred : false, name : null, obsolete : false, published : false, relationshipType : $scope.selectedRelationshipType, additionalRelationshipType : '', stated : false, suppressible : false, terminology : $scope.selected.project.terminology, terminologyId : "", toId : $scope.toConcept.id, toName : $scope.toConcept.name, toTerminology : $scope.toConcept.terminology, toTerminologyId : $scope.toConcept.terminologyId, toVersion : $scope.toConcept.version, type : "RELATIONSHIP", version : $scope.toConcept.version, workflowStatus : $scope.selectedWorkflowStatus }; metaEditingService.addRelationship($scope.selected.project.id, $scope.selected.activityId, $scope.selected.component, relationship, $scope.overrideWarnings).then( // Success function(data) { $scope.warnings = data.warnings; $scope.errors = data.errors; if ($scope.warnings.length > 0) { $scope.overrideWarnings = true; } if ($scope.warnings.length == 0 && $scope.errors.length == 0) { $uibModalInstance.close(); } }, // Error function(data) { utilService.handleDialogError($scope.errors, data); }); }; // select the to concept $scope.selectToConcept = function(concept) { $scope.toConcept = concept; } // Dismiss modal $scope.cancel = function() { $uibModalInstance.dismiss('cancel'); }; // Add finder component function addFinderComponent(data) { // return if concept is already on concept list for (var i = 0; i < $scope.lists.concepts.length; i++) { if ($scope.lists.concepts[i].id == data.id) { return; } } // If full concept, simply push if (data.atoms && data.atoms.length > 0) { $scope.toConcepts.push(data); $scope.selectToConcept(data); return; } // get full concept contentService.getConcept(data.id, $scope.selected.project.id).then( // Success function(data) { // $scope.lists.concepts.push(data); $scope.toConcepts.push(data); }); } // initialize modal initialize(); // end } ]);
JavaScript
0
@@ -818,17 +818,16 @@ N', 'RQ' - %5D;%0A $ @@ -875,24 +875,26 @@ 'key' : ' +XR ',%0A 'va @@ -905,11 +905,8 @@ : ' -XR (non
d235d03e5e35ffdf17d061f6f597327e16ab31ab
add all built docs to source pipeline before deploy
lib/actions/deploy.js
lib/actions/deploy.js
(function() { 'use strict'; var _ = require('lodash'); var chalk = require('chalk'); var lazypipe = require('lazypipe'); var pages = require('gulp-gh-pages'); var wait = require('wait-stream'); var through2 = require('through2'); var flatten = require('../flatten'); var tasks = require('../tasks'); var write = process.stdout.write; var before; var done; module.exports = tasks.create({ name: 'deploy', callback: callback, label: 'deployment' }); function callback(options) { var pipeline = lazypipe(); if (!options.release) { pipeline = pipeline .pipe(tasks.util.filter('deploy.build', 'build/**')) .pipe(flatten, 'build'); } return pipeline .pipe(through2.obj, function(chunk, enc, cb) { if (!before) { if (!options.verbose) { process.stdout.write = _.noop; } before = true; } this.push(chunk); cb(); }) .pipe(pages, {force: options.force}) .pipe(wait, 3000, {once: true}) .pipe(through2.obj, function(chunk, enc, cb) { if (!done) { process.stdout.write = write; done = true; } this.push(chunk); cb(); }); } })();
JavaScript
0
@@ -49,24 +49,63 @@ ('lodash');%0A + var addsrc = require('gulp-add-src')%0A var chalk @@ -757,32 +757,66 @@ return pipeline%0A + .pipe(addsrc, 'build/**')%0A .pipe(th @@ -858,35 +858,8 @@ ) %7B%0A - if (!before) %7B%0A @@ -884,26 +884,24 @@ .verbose) %7B%0A - @@ -935,50 +935,8 @@ op;%0A - %7D%0A%0A before = true;%0A @@ -1204,17 +1204,16 @@ write;%0A -%0A
30d4806b285e83f932670bb45bde0700b6ec1dde
Remove debug
lib/api/controller.js
lib/api/controller.js
'use strict'; var _ = require('lodash'); var r = require('rethinkdb'); var p = require('json-pointer'); var li = require('li'); var qs = require('qs'); var operators = {}; // build simple operators ['eq', 'ne', 'gt', 'lt', 'ge', 'le', 'match'].forEach(function(op) { operators[op] = function(f, row) { var path = Array.isArray(f.path) ? f.path : p.parse(f.path); var cursor = row; path.forEach(function(segment){ cursor = cursor(segment); }); return cursor[op].call(cursor, f.value); }; }); // add the `in` operator operators.in = function(f, row) { var path = Array.isArray(f.path) ? f.path : p.parse(f.path); var cursor = row; path.forEach(function(segment){ cursor = cursor(segment); }); return r.expr(f.value).contains(cursor); }; // add the `contains` operator operators.contains = function(f, row) { var path = Array.isArray(f.path) ? f.path : p.parse(f.path); var cursor = row; path.forEach(function(segment){ cursor = cursor(segment); }); return cursor.contains(f.value); }; // add the `present` operator operators.present = function(f, row) { var path = Array.isArray(f.path) ? f.path : p.parse(f.path); var data = {}; path.forEach(function(segment){ data = data[segment] = {}; }); return row.hasFields(data); }; function parseSorts(sort) { try { sort = JSON.parse(sort); } catch(e){ return []; } if(!Array.isArray(sort)) sort = [sort]; // build the orderBy key return sort.map(function(s){ // parse path var path; try { path = Array.isArray(s.path) ? s.path : p.parse(s.path); } catch(e) { return; } // build sort function var fn = function(row){ path.forEach(function(node) { row = row(node); }); return row.default(null); }; // apply direction return (s.direction === 'desc') ? r.desc(fn) : fn; }) // remove empty functions .filter(function(i){return i;}); } function parseFilters(filters) { try { filters = Array.isArray(filters) ? filters.map(function(f){ return JSON.parse(f); }) : JSON.parse(filters); } catch(e){ return []; } if(!Array.isArray(filters)) filters = [filters]; return filters.map(function(f){ if(!operators[f.op]) return; try { return function(row){ return operators[f.op](f, row); }; } catch(e){ return; } }) // remove empty functions .filter(function(i){return i;}); } module.exports = { parseQuery: function(raw) { var parsed = { skip: 0, limit: 50 }; // search if(typeof raw.search === 'string') { parsed.search = raw.search; } // filter if(raw.filter) { var filter = parseFilters(raw.filter); if(filter.length) parsed.filter = filter; } // sort if(raw.sort) { var sort = parseSorts(raw.sort); if(sort.length) parsed.sort = sort; } // limit if(raw.per_page) { var perPage = parseInt(raw.per_page, 10); if(!isNaN(perPage)) parsed.limit = perPage; } // skip if(raw.page) { var page = parseInt(raw.page, 10); if(page) parsed.skip = (page - 1) * parsed.limit; } return parsed; }, makePageHeaders: function(skip, limit, total, basePath, baseQuery) { var page = Math.ceil(skip / limit) + 1; var pages = { first: 1, last: Math.ceil(total / limit) }; if(skip > 0) pages.prev = page - 1; if(skip < total - limit) pages.next = page + 1; // build each link var links = _.mapValues(pages, function(value){ return basePath + '?' + qs.stringify(_.extend({}, baseQuery, { page: value, per_page: limit } )); }); return { Pages: JSON.stringify(pages), Link: li.stringify(links) }; }, // includes should be in the format {assignments: true, stages: ['2d84ee0c-175b-4ec1-ab32-ae9dd854f5d8']} parseIncludes: function(raw, Model) { if(!raw) return null; try { if(typeof raw === 'string') raw = JSON.parse(raw); } catch(e) {} if(typeof raw === 'string') raw = [raw]; // must be an array if(!Array.isArray(raw)) return null; console.log(raw, Model.collections) // filter out bad includes return _.uniq(raw.filter(function(i){ return typeof i === 'string' && Model.collections[i]; })); } };
JavaScript
0.000001
@@ -3940,47 +3940,8 @@ l;%0A%0A -%09%09console.log(raw, Model.collections)%0A%0A %09%09//
1a0de813fcd705dcfc202a0ba58678111f94de28
fix browser kjur usage.
lib/browser/PayPro.js
lib/browser/PayPro.js
"use strict"; var Key = require('./Key'); var KJUR = require('jsrsasign'); var assert = require('assert'); var PayPro = require('../common/PayPro'); var RootCerts = require('../common/RootCerts'); var asn1 = require('asn1.js'); var rfc3280 = require('asn1.js/rfc/3280'); // Documentation: // http://kjur.github.io/jsrsasign/api/symbols/KJUR.crypto.Signature.html#.sign // http://kjur.github.io/jsrsasign/api/symbols/RSAKey.html PayPro.prototype.x509Sign = function(key) { var pki_type = this.get('pki_type'); var pki_data = this.get('pki_data'); // contains one or more x509 certs pki_data = PayPro.X509Certificates.decode(pki_data); pki_data = pki_data.certificate; var type = pki_type.split('+')[1].toUpperCase(); var buf = this.serializeForSig(); var trusted = pki_data.map(function(cert) { var der = cert.toString('hex'); var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex(der, 'CERTIFICATE'); return RootCerts.getTrusted(pem); }); // XXX Figure out what to do here if (!trusted.length) { // throw new Error('Unstrusted certificate.'); } else { trusted.forEach(function(name) { // console.log('Certificate: %s', name); }); } var rsa = new KJUR.RSAKey(); rsa.readPrivateKeyFromPEMString(key.toString()); key = rsa; var jsrsaSig = new KJUR.crypto.Signature({ alg: type + 'withRSA', prov: 'cryptojs/jsrsa' }); jsrsaSig.init(key); jsrsaSig.updateHex(buf.toString('hex')); var sig = new Buffer(jsrsaSig.sign(), 'hex'); return sig; }; PayPro.prototype.x509Verify = function(key) { var sig = this.get('signature'); var pki_type = this.get('pki_type'); var pki_data = this.get('pki_data'); pki_data = PayPro.X509Certificates.decode(pki_data); pki_data = pki_data.certificate; var buf = this.serializeForSig(); var type = pki_type.split('+')[1].toUpperCase(); var jsrsaSig = new KJUR.crypto.Signature({ alg: type + 'withRSA', prov: 'cryptojs/jsrsa' }); var signedCert = pki_data[0]; var der = signedCert.toString('hex'); var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex(der, 'CERTIFICATE'); jsrsaSig.initVerifyByCertificatePEM(pem); jsrsaSig.updateHex(buf.toString('hex')); var verified = jsrsaSig.verify(sig.toString('hex')); var chain = pki_data; // Verifying the cert chain: // 1. Extract public key from next certificate. // 2. Extract signature from current certificate. // 3. If current cert is not trusted, verify that the current cert is signed // by NEXT by the certificate. // NOTE: XXX What to do when the certificate is revoked? var chainVerified = chain.every(function(cert, i) { var der = cert.toString('hex'); var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex(der, 'CERTIFICATE'); var name = RootCerts.getTrusted(pem); var ncert = chain[i + 1]; // The root cert, check if it's trusted: if (!ncert || name) { if (!ncert && !name) { return false; } chain.length = 0; return true; } var nder = ncert.toString('hex'); var npem = KJUR.asn1.ASN1Util.getPEMStringFromHex(nder, 'CERTIFICATE'); // Get public key from next certificate: var data = new Buffer(nder, 'hex'); var nc = rfc3280.Certificate.decode(data, 'der'); var npubKey = nc.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data; npubKey = KJUR.asn1.ASN1Util.getPEMStringFromHex(npubKey, 'RSA PUBLIC KEY'); // Get signature from current certificate: var data = new Buffer(der, 'hex'); var c = rfc3280.Certificate.decode(data, 'der'); var sig = c.signature.data; var jsrsaSig = new KJUR.crypto.Signature({ alg: type + 'withRSA', prov: 'cryptojs/jsrsa' }); jsrsaSig.initVerifyByPublicKey(npubKey); // Create a To-Be-Signed Certificate to verify using asn1.js: // Fails at Issuer: var tbs = rfc3280.TBSCertificate.encode(c.tbsCertificate, 'der'); jsrsaSig.updateHex(tbs); return jsrsaSig.verify(sig); }); return verified && chainVerified; }; module.exports = PayPro;
JavaScript
0
@@ -3927,16 +3927,32 @@ eHex(tbs +.toString('hex') );%0A%0A
a14bb9458e046e899e73cc189214e222bb962cd5
Remove faulty helpers and add currentRoute to Handlebars helpers.
lib/client/helpers.js
lib/client/helpers.js
function assert (condition, msg) { if (!condition) throw new Error(msg); } function linkTo (url, html) { return '<a href="' + url + '">' + html + '</a>'; } function getParams (routeName, context, options) { var params; switch(arguments.length) { case 3: params = context; break; case 2: options = context; params = _.keys(options.hash).length ? options.hash : this; break; case 1: params = this; break; default: throw new Error('No routeName provided'); } if (params === window) params = []; return params; } if (Handlebars) { Handlebars.registerHelper('linkTo', function (routeName, context, options) { var params = getParams.apply(this, arguments) , html , path; options = arguments[arguments.length-1]; html = options.fn(this); console.log(params); path = Router.path(routeName, params); return new Handlebars.SafeString( linkTo(path, html) ); }); Handlebars.registerHelper('linkToUrl', function (routeName, context, options) { var params = getParams.apply(this, arguments) , html; options = arguments[arguments.length-1]; html = options.fn(this); return new Handlebars.SafeString( linkTo(Router.path(routeName, params), html) ); }); Handlebars.registerHelper('pathFor', function (routeName, context, options) { var params = getParams.apply(this, arguments); return Router.path(routeName, params); }); Handlebars.registerHelper('urlFor', function (routeName, context, options) { var params = getParams.apply(this, arguments); return Router.url(routeName, params); }); }
JavaScript
0
@@ -75,92 +75,8 @@ %0A%7D%0A%0A -function linkTo (url, html) %7B%0A return '%3Ca href=%22' + url + '%22%3E' + html + '%3C/a%3E';%0A%7D%0A%0A func @@ -122,16 +122,16 @@ ions) %7B%0A + var pa @@ -524,710 +524,8 @@ ) %7B%0A - Handlebars.registerHelper('linkTo', function (routeName, context, options) %7B%0A var params = getParams.apply(this, arguments)%0A , html%0A , path;%0A%0A options = arguments%5Barguments.length-1%5D;%0A html = options.fn(this);%0A%0A console.log(params);%0A%0A path = Router.path(routeName, params);%0A%0A return new Handlebars.SafeString(%0A linkTo(path, html)%0A );%0A %7D);%0A%0A Handlebars.registerHelper('linkToUrl', function (routeName, context, options) %7B%0A var params = getParams.apply(this, arguments)%0A , html;%0A options = arguments%5Barguments.length-1%5D;%0A html = options.fn(this);%0A return new Handlebars.SafeString(%0A linkTo(Router.path(routeName, params), html)%0A );%0A %7D);%0A%0A Ha @@ -823,32 +823,32 @@ is, arguments);%0A - return Route @@ -878,11 +878,112 @@ );%0A %7D); +%0A%0A Handlebars.registerHelper('currentRoute', function (options) %7B%0A return Router.current();%0A %7D); %0A%7D%0A
99f0057fbf7b7b418254eafc67cea7fa904200e0
apply expression to commands
lib/commandHandler.js
lib/commandHandler.js
/* * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of iotagent-json * * iotagent-json is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * iotagent-json is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with iotagent-json. * If not, seehttp://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ const async = require('async'); const iotAgentLib = require('iotagent-node-lib'); const iotaUtils = require('./iotaUtils'); const constants = require('./constants'); const transportSelector = require('./transportSelector'); const config = require('./configService'); const context = { op: 'IoTAgentJSON.Commands' }; /** * Generate a function that executes the given command in the device. * * @param {String} apiKey APIKey of the device's service or default APIKey. * @param {Object} device Object containing all the information about a device. * @param {Object} attribute Attribute in NGSI format. * @return {Function} Command execution function ready to be called with async.series. */ function generateCommandExecution(apiKey, device, attribute) { const payload = {}; payload[attribute.name] = attribute.value; const serialized = JSON.stringify(payload); config .getLogger() .debug( context, 'Sending command execution to device [%s] with apikey [%s] and payload [%j] ', apiKey, device.id, attribute ); const executions = transportSelector.createExecutionsForBinding( [apiKey, device, serialized], 'executeCommand', device.transport ); return executions; } /** * Handles a command execution request coming from the Context Broker. This handler should: * - Identify the device affected by the command. * - Send the command to the appropriate MQTT topic. * - Update the command status in the Context Broker. * * @param {String} id ID of the entity for which the command execution was issued. * @param {String} type Type of the entity for which the command execution was issued. * @param {String} service Service ID. * @param {String} subservice Subservice ID. * @param {Array} attributes List of NGSI attributes of type command to execute. */ function commandHandler(id, type, service, subservice, attributes, callback) { config .getLogger() .debug(context, 'Handling MQTT command for device [%s] in service [%s - %s]', id, service, subservice); function concat(previous, current) { previous = previous.concat(current); return previous; } iotAgentLib.getDeviceByName(id, service, subservice, function(error, device) { if (error) { config.getLogger().error( context, "COMMAND-001: Command execution could not be handled, as device for entity [%s] [%s] wasn't found", id, type ); callback(error); } else { iotaUtils.getEffectiveApiKey(device.service, device.subservice, device, function(error, apiKey) { if (error) { callback(error); } else { async.series( attributes.map(generateCommandExecution.bind(null, apiKey, device)).reduce(concat, []), callback ); } }); } }); } /** * Process an update in the state of a command with information coming from the device. * * @param {String} apiKey API Key corresponding to the Devices configuration. * @param {String} deviceId Id of the device to be updated. * @param {Object} device Device object containing all the information about a device. * @param {Object} messageObj JSON object sent using MQTT. */ function updateCommand(apiKey, deviceId, device, messageObj) { const commandList = Object.keys(messageObj); const commandUpdates = []; for (let i = 0; i < commandList.length; i++) { commandUpdates.push( async.apply( iotAgentLib.setCommandResult, device.name, config.getConfig().iota.defaultResource, apiKey, commandList[i], messageObj[commandList[i]], constants.COMMAND_STATUS_COMPLETED, device ) ); } async.series(commandUpdates, function(error) { if (error) { config.getLogger().error( context, "COMMANDS-002: Couldn't update command status in the Context broker " + 'for device [%s] with apiKey [%s]: %s', device.id, apiKey, error ); } else { config .getLogger() .debug( context, 'Single measure for device [%s] with apiKey [%s] successfully updated', device.id, apiKey ); } }); } exports.generateCommandExecution = generateCommandExecution; exports.updateCommand = updateCommand; exports.handler = commandHandler;
JavaScript
0.999945
@@ -1706,28 +1706,473 @@ -const payload = %7B%7D;%0A +let parser = iotAgentLib.dataPlugins.expressionTransformation;%0A%0A const payload = %7B%7D;%0A let command = device && device.commands.find((att) =%3E att.name === attribute.name);%0A if (command && command.expression) %7B%0A // TBD context:%0A // context = entity attrs in a time ?%0A // context = %5B %7B attribute.name, attribute.value %7D %5D%0A payload%5Battribute.name%5D = parser.applyExpression(command.expression, %5Battribute%5D, device);%0A %7D else %7B%0A @@ -2214,16 +2214,22 @@ .value;%0A + %7D%0A cons @@ -3743,32 +3743,33 @@ ervice, function + (error, device) @@ -4162,24 +4162,25 @@ ce, function + (error, apiK @@ -5534,24 +5534,24 @@ );%0A %7D%0A%0A - async.se @@ -5579,16 +5579,17 @@ function + (error)
a36c7c344c48f890a30af53eec19b66180b18907
add a new param, excludes to config-handler
lib/config-handler.js
lib/config-handler.js
var fs = require('fs'), path = require('path'), fsmore = require('../util/fs-more'), lang = require('../util/lang'), REGEX_REPLACE_EXT = /^(.*)(\.[^\.]+)$/i; /** * @param {Object} options { cwd: {string} file: {string} parser: env } */ function ConfigHandler(options){ this.cwd = options.cwd; this.file = options.file; this.env_file = this._filterConfigFile(options.file, options.env); if(options.parser){ this._parser = options.parser; } }; ConfigHandler.prototype = { // upload.json -> upload.alpha.json _filterConfigFile: function(file, env){ return env ? file.replace(REGEX_REPLACE_EXT, function(all, m1, m2){ return m1 + '.' + env + m2; }) : file; }, _parser: function(obj){ return obj; }, getConf: function(config){ config || (config = {}); // get project config this.cwd && lang.merge( config, this._getConfByFile(path.join(this.cwd, this.env_file), path.join(this.cwd, this.file)), false ); // get user config lang.merge( config, this._getConfByFile(path.join('~', this.env_file), path.join('~', this.file)), false ); return config; }, _getConfByFile: function(file, fallback_file){ file = fsmore.stdPath(file); fallback_file = fsmore.stdPath(fallback_file); file = fsmore.isFile(file) ? file : fallback_file && fsmore.isFile(fallback_file) ? fallback : false; return file ? require( file ) : {}; } }; module.exports = ConfigHandler;
JavaScript
0.000001
@@ -434,16 +434,53 @@ s.env);%0A + this.excludes = options.exclude;%0A %0A @@ -1740,22 +1740,26 @@ -return +var conf = file ? @@ -1780,16 +1780,140 @@ ) : %7B%7D;%0A + %0A this.excludes.forEach(function(ex)%7B%0A delete conf%5Bex%5D;%0A %7D);%0A %0A return conf;%0A %7D%0A%7D;
6ec4fb7a44a938397765b8ab245445af0a3d4a92
remove class breaking editor
lib/data-atom-view.js
lib/data-atom-view.js
"use babel"; var DataResultView = require('./data-result-view'); var HeaderView = require('./header-view'); module.exports = class DataAtomView { constructor() { this.createView(); this.queryInput.style.display = 'none'; this.useEditorQuery = true; this.isShowing = false; this.resizeHandle.addEventListener('mousedown', e => this.resizeStarted(e)); } createView() { this.element = document.createElement('section'); this.element.classList.add('data-atom-panel'); this.element.classList.add('tool-panel'); this.element.classList.add('panel'); this.element.classList.add('panel-bottom'); this.element.classList.add('padding'); this.element.classList.add('native-key-bindings'); this.resizeHandle = document.createElement('div'); this.resizeHandle.classList.add('resize-handle'); this.element.appendChild(this.resizeHandle); var header = document.createElement('header'); header.classList.add('header'); header.classList.add('results-header'); this.element.appendChild(header); this.headerView = new HeaderView(this.useEditorQuery); header.appendChild(this.headerView.getElement()); this.queryInput = document.createElement('div'); header.appendChild(this.queryInput); var title = document.createElement('span'); title.classList.add('heading-title'); title.innerText = 'Query:'; this.queryInput.appendChild(title); this.queryEditor = document.createElement('atom-text-editor'); this.queryEditor.classList.add('query-input'); this.queryEditor.style.height = '40px'; this.queryEditor.style.maxHeight = '40px'; // this.queryEditor.getModel().setGrammar('sql'); this.queryInput.appendChild(this.queryEditor); title = document.createElement('span'); title.classList.add('heading-title'); title.innerText = 'Results:'; header.appendChild(title); this.resultsView = new DataResultView(); header.appendChild(this.resultsView[0]); } useEditorAsQuerySource(useEditor) { this.useEditorQuery = useEditor; this.headerView.toggleQuerySource(useEditor); if (useEditor) { this.queryInput.style.display = 'none'; } else { this.queryInput.style.display = 'block'; } } focusQueryInput() { this.queryEditor.focus(); } getQuery() { var editor = atom.workspace.getActiveTextEditor(); return this.useEditorQuery ? (editor.getSelectedText() ? editor.getSelectedText() : editor.getText()) : this.queryEditor.getModel().getText(); } // Tear down any state and detach destroy() { this.detach(); } show() { if (!this.isShowing) this.toggleView(); this.headerHeight = this.headerView.height() + 5; } hide() { if (this.isShowing) this.toggleView(); } toggleView() { if (this.isShowing) { this.element.parentNode.removeChild(this.element); this.isShowing = false; } else { atom.workspace.addBottomPanel({item:this.element}); if (this.resultsView) this.resultsView.updateHeight(this.getHeight() - this.headerView.height()); this.isShowing = true; } } resizeStarted() { var self = this; this.moveHandler = function(e) { self.resizeResultsView(e); }; document.body.addEventListener('mousemove', this.moveHandler); this.stopHandler = function() { self.resizeStopped(); }; document.body.addEventListener('mouseup', this.stopHandler); } resizeStopped() { document.body.removeEventListener('mousemove', this.moveHandler); document.body.removeEventListener('mouseup', this.stopHandler); } resizeResultsView(e) { var height = document.body.offsetHeight - e.pageY - this.headerHeight; this.element.style.height = height + 'px'; if (this.resultsView) this.resultsView.updateHeight(this.getHeight() - this.headerView.height()); atom.commands.dispatch(atom.views.getView(atom.workspace), 'data-atom:result-view-height-changed'); } clear() { // clear results view and show things are happening this.resultsView.clear(); } setState(connection, dbNames, selectedDb, height, useEditorAsQuery) { this.headerView.setConnection(connection); this.headerView.addDbNames(dbNames); this.headerView.setSelectedDbName(selectedDb); this.getHeight(height); if (this.resultsView) this.resultsView.updateHeight(this.getHeight() - this.headerView.height()); this.useEditorAsQuerySource(useEditorAsQuery); } setMessage(message) { this.resultsView.setMessage(message); } setResults(results) { this.resultsView.setResults(results); } addConnection(connectionName) { this.headerView.addConnection(connectionName); } getHeight() { return this.element.offsetHeight; } onConnectionChanged(onConnectionChangedFunc) { return this.headerView.onConnectionChanged(onConnectionChangedFunc); } }
JavaScript
0.000001
@@ -103,16 +103,53 @@ iew');%0A%0A +var %7BTextEditor%7D = require('atom');%0A%0A module.e @@ -708,24 +708,27 @@ dding');%0A + // this.elemen
8b4411d0c6a4827951ec9df1f713561fa8d537d8
Fix jsdom oneliers in platform
lib/delta/platform.js
lib/delta/platform.js
/** * @file: Platform specific implementation and abstractions */ (function(exports) { exports.isBrowser = function() { return typeof window !== 'undefined'; }; /** * Construct and return a DOM document from an xml string */ exports.parseXML = function (text) { if (exports.isBrowser()) { // IE9 (Chakra): http://msdn.microsoft.com/en-us/library/ff975124(v=vs.85).aspx // No support for IE < 9 (not falling back to ActiveX Component). // FF (Gecko): https://developer.mozilla.org/en/DOM/DOMParser // No official documentation for WebKit (Safari, Chromium, Konqueror) // and Opera but recent versions of these browsers provide DomParser. return (new DOMParser()).parseFromString(text,"text/xml"); } else { // Node.js: Use our own implementation around jsdom return require('./xmlToDom.js').parseXmlString(text); } }; /** * Serialize a DOM document into an xml string */ exports.serializeXML = function (doc) { if (exports.isBrowser()) { // IE9 (Chakra): http://msdn.microsoft.com/en-us/library/ff975124(v=vs.85).aspx // No support for IE < 9 // FF (Gecko): https://developer.mozilla.org/en/XMLSerializer // No official documentation for WebKit (Safari, Chromium, Konqueror) // and Opera but recent versions of these browsers provide // XMLSerializer. return (new XMLSerializer()).serializeToString(doc); } else { var domToXml = require('./domToXml.js'); return (new domToXml.XMLSerializer()).serializeToString(doc); } }; /** * Create a new DOM document and return it */ exports.createDocument = function() { if (exports.isBrowser()) { // Supported in modern browsers, IE9 however creates html document // http://www.quirksmode.org/dom/w3c_core.html#miscellaneous return document.implementation.createDocument('', '', null); } else { return new require("jsdom").level(3, 'core').dom.Document(); } } exports.parseJSON = function(data) { return JSON.parse(data); } exports.serializeJSON = function(doc) { return JSON.stringify(doc); } /** * Return an array of the attributes of the given node. */ exports.attributesArray = function(node) { var result, i, n; if (exports.isBrowser()) { result = node.hasAttributes() ? Array.prototype.slice.call(node.attributes) : []; } else { // Need to construct the array manually when using jsdom/node.js result = []; for (i = 0; i < node.attributes.length; i++) { result.push(node.attributes[i]); } } return result; }; }( typeof exports === 'undefined' ? (DeltaJS.platform={}) : exports ));
JavaScript
0.000012
@@ -1622,23 +1622,21 @@ -var domToXml = +return (new ( requ @@ -1659,42 +1659,9 @@ js') -;%0A return (new domToXml +) .XML @@ -2130,16 +2130,17 @@ urn new +( require( @@ -2168,12 +2168,9 @@ re') -.dom +) .Doc
55b2cba86ba0892e6ff58568cf5c611c8da4f55a
Remove click to block user action in favor of right click menu
lib/elements/users.js
lib/elements/users.js
module.exports = Users var h = require('virtual-dom/h') var inherits = require('util').inherits var BaseElement = require('./base-element') var ModalElement = require('modal-element') function Users (target) { BaseElement.call(this, target) var self = this this.showUserMenuFor = false this.lastClickPosition = [0, 0] this.userMenu = new ModalElement(document.body) this.userMenu.centerOnLoad = false this.userMenu.on('load', function (node) { node.childNodes[0].style.top = self.lastClickPosition[1] + 'px' node.childNodes[0].style.left = self.lastClickPosition[0] + 'px' }) } inherits(Users, BaseElement) Users.prototype.render = function (users) { var self = this var now = new Date().getTime() var activeUsers = [] var idleUsers = [] var sortedUsers = Object.keys(users).sort(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) }) idleUsers = sortedUsers.filter(function (username) { var user = users[username] // User is "active" if they sent a message in the last 60 mins (3600000ms) if (now - user.lastActive < 3600000) { activeUsers.push(username) return false } return true }) idleUsers = idleUsers.map(enrichUsers) activeUsers = activeUsers.map(enrichUsers) function enrichUsers (username) { var user = users[username] var className = user.blocked ? 'blocked' : '' return h('li', { className: className }, [ h('button', { onclick: function (e) { e.preventDefault() self.send('toggleBlockUser', username) }, oncontextmenu: function (e) { e.preventDefault() self.showUserMenuFor = username self.lastClickPosition = [e.clientX, e.clientY] self.send('render') } }, [ h('img.avatar', { src: user.avatar }), username ]) ]) } // Build user menu this.userMenu.shown = !!this.showUserMenuFor var ignoreLabel = 'mute user' if (users[this.showUserMenuFor] && users[this.showUserMenuFor].blocked) ignoreLabel = 'unmute user' this.userMenu.render( h('ul', [ h('li', h('a', { href: 'https://github.com/' + this.showUserMenuFor, target: '_blank' }, 'github.com/' + this.showUserMenuFor)), h('li', h('button', { onclick: function (e) { e.preventDefault() self.send('toggleBlockUser', self.showUserMenuFor) } }, ignoreLabel)) ]) ) return [ h('.heading', 'Active Users (' + activeUsers.length + ')'), h('ul.users', [ activeUsers ]), h('.heading', 'Idle Users (' + idleUsers.length + ')'), h('ul.users', [ idleUsers ]) ] }
JavaScript
0
@@ -1456,129 +1456,8 @@ , %7B%0A - onclick: function (e) %7B%0A e.preventDefault()%0A self.send('toggleBlockUser', username)%0A %7D,%0A
6939dda495fc6e682f118bb2965f112013886d9d
remove code not needeed in parameters ingredient user profile
source/web/src/app/components/userProfile/parametersIngredientsUserProfile.controller.js
source/web/src/app/components/userProfile/parametersIngredientsUserProfile.controller.js
/** * Created by sylflo on 11/15/15. */ (function () { 'use strict'; angular.module('NourritureControllers') .controller('ParametersIngredientsUserProfileController', ParametersIngredientsUserProfileController); ParametersIngredientsUserProfileController.$inject = ["$scope", "IngredientService", 'TagsService', 'toastr',"$log", "$mdDialog", "$document"]; function ParametersIngredientsUserProfileController($scope, IngredientService, TagsService, toastr, $log, $mdDialog, $document) { var vm = this; $log.log("innit"); //Vars for Chips vm.tags_ingredient = []; vm.selectedItemChip = null; vm.searchTextChip = null; vm.itemsAutocomplete = []; vm.submit = function () { $log.log("innit"); IngredientService .ingredients .save({ "name": $scope.name, "description": $scope.description, "calories": $scope.calories, "fat": $scope.fat, "carbohydrates": $scope.carbohydrates, "proteins": $scope.proteins, "tags": vm.tags_ingredient }) .$promise .then(vm.IngredientCreateSuccess, vm.IngredientCreateFailure); }; vm.IngredientCreateSuccess = function (data) { $log.log(data.message); toastr.success('You can now access your new ingredient.', 'Ingredient Created!'); }; vm.IngredientCreateFailure = function (data) { $log.log(data.data); var errorMsg = "This is odd..."; if (data.data.errmsg.indexOf("name") > -1) errorMsg = "Seems like the ingredient already exists"; toastr.error(errorMsg, 'Woops...'); }; vm.TagsGetFailure = function (data) { $log.log(data.data); var errorMsg = "This is odd..."; if (data.data.errmsg.indexOf("name") > -1) errorMsg = "Seems like the ingredient already exists"; toastr.error(errorMsg, 'Woops...'); }; vm.TagsGetSuccess = function (data) { $log.log(data); vm.tags_ingredient = data; }; vm.TagsGetNameFailure = function (data) { $log.log(data.data); vm.itemsAutocomplete = []; return (vm.itemsAutocomplete); }; vm.TagsGetNameSuccess = function (data) { $log.log(data); vm.itemsAutocomplete = data; return (vm.itemsAutocomplete); }; //Chips functions vm.transformChip = function (chip) { if (angular.isObject(chip)) return chip; if (angular.isUndefined(chip._id)) return { name: chip } else return { name: chip.name } } vm.getNameTags = function (name) { $log.log("innit"); return (TagsService .tags_name .query({name: name}) .$promise .then(vm.TagsGetNameSuccess, vm.TagsGetNameFailure)); } //Dialog functions vm.infosTagDialog = function (event, tag) { $mdDialog.show({ controller: vm.dialogController, controllerAs: 'infosTag', templateUrl: 'app/templates/dialogTemplates/tagsInfos.tmpl.html', parent: angular.element($document.body), locals: {tag: tag}, bindToController: true, targetEvent: event, clickOutsideToClose: true }) }; //Controller for infosTagDialog vm.dialogController = function ($mdDialog) { var vm = this; vm.hide = function () { $mdDialog.hide(); } } //Dialog functions vm.createTagDialog = function (event) { $mdDialog.show({ controller: vm.CreateTagdialogController, controllerAs: 'createTag', templateUrl: 'app/templates/dialogTemplates/tagsCreate.tmpl.html', parent: angular.element($document.body), bindToController: true, targetEvent: event, clickOutsideToClose: true }) }; //Controller for createTagDialog vm.CreateTagdialogController = function ($mdDialog) { var vm = this; vm.TagCreateSuccess = function (data) { $log.log(data.message); toastr.success('You can now access your new Tag.', 'Tag Created!'); }; vm.TagCreateFailure = function (data) { $log.log(data.data); var errorMsg = "This is odd..."; if (data.data.errmsg.indexOf("name") > -1) errorMsg = "Seems like the tag already exists"; toastr.error(errorMsg, 'Woops...'); }; vm.submit = function () { $log.log("innit"); TagsService .tags .save({"name": vm.name, "description": vm.description, "flag": vm.flag}) .$promise .then(vm.TagCreateSuccess, vm.TagCreateFailure); } vm.hide = function () { $mdDialog.hide(); } } } })();
JavaScript
0.000001
@@ -691,1629 +691,8 @@ %5D;%0A%0A - vm.submit = function () %7B%0A $log.log(%22innit%22);%0A IngredientService%0A .ingredients%0A .save(%7B%0A %22name%22: $scope.name,%0A %22description%22: $scope.description,%0A %22calories%22: $scope.calories,%0A %22fat%22: $scope.fat,%0A %22carbohydrates%22: $scope.carbohydrates,%0A %22proteins%22: $scope.proteins,%0A %22tags%22: vm.tags_ingredient%0A %7D)%0A .$promise%0A .then(vm.IngredientCreateSuccess, vm.IngredientCreateFailure);%0A %7D;%0A%0A vm.IngredientCreateSuccess = function (data) %7B%0A $log.log(data.message);%0A toastr.success('You can now access your new ingredient.', 'Ingredient Created!');%0A %7D;%0A%0A vm.IngredientCreateFailure = function (data) %7B%0A $log.log(data.data);%0A var errorMsg = %22This is odd...%22;%0A if (data.data.errmsg.indexOf(%22name%22) %3E -1)%0A errorMsg = %22Seems like the ingredient already exists%22;%0A toastr.error(errorMsg, 'Woops...');%0A %7D;%0A%0A vm.TagsGetFailure = function (data) %7B%0A $log.log(data.data);%0A var errorMsg = %22This is odd...%22;%0A if (data.data.errmsg.indexOf(%22name%22) %3E -1)%0A errorMsg = %22Seems like the ingredient already exists%22;%0A toastr.error(errorMsg, 'Woops...');%0A %7D;%0A%0A vm.TagsGetSuccess = function (data) %7B%0A $log.log(data);%0A vm.tags_ingredient = data;%0A %7D;%0A%0A vm.TagsGetNameFailure = function (data) %7B%0A $log.log(data.data);%0A vm.itemsAutocomplete = %5B%5D;%0A return (vm.itemsAutocomplete);%0A %7D;%0A%0A vm.TagsGetNameSuccess = function (data) %7B%0A $log.log(data);%0A vm.itemsAutocomplete = data;%0A return (vm.itemsAutocomplete);%0A %7D; %0A%0A @@ -891,24 +891,25 @@ ip%0A %7D +; %0A else%0A @@ -962,24 +962,25 @@ %7D%0A %7D +; %0A%0A vm.get @@ -1198,1922 +1198,9 @@ %7D%0A%0A - //Dialog functions%0A vm.infosTagDialog = function (event, tag) %7B%0A $mdDialog.show(%7B%0A controller: vm.dialogController,%0A controllerAs: 'infosTag',%0A templateUrl: 'app/templates/dialogTemplates/tagsInfos.tmpl.html',%0A parent: angular.element($document.body),%0A locals: %7Btag: tag%7D,%0A bindToController: true,%0A targetEvent: event,%0A clickOutsideToClose: true%0A %7D)%0A %7D;%0A%0A //Controller for infosTagDialog%0A vm.dialogController = function ($mdDialog) %7B%0A var vm = this;%0A%0A vm.hide = function () %7B%0A $mdDialog.hide();%0A %7D%0A %7D%0A%0A //Dialog functions%0A vm.createTagDialog = function (event) %7B%0A $mdDialog.show(%7B%0A controller: vm.CreateTagdialogController,%0A controllerAs: 'createTag',%0A templateUrl: 'app/templates/dialogTemplates/tagsCreate.tmpl.html',%0A parent: angular.element($document.body),%0A bindToController: true,%0A targetEvent: event,%0A clickOutsideToClose: true%0A %7D)%0A %7D;%0A%0A //Controller for createTagDialog%0A vm.CreateTagdialogController = function ($mdDialog) %7B%0A var vm = this;%0A%0A vm.TagCreateSuccess = function (data) %7B%0A $log.log(data.message);%0A toastr.success('You can now access your new Tag.', 'Tag Created!');%0A %7D;%0A%0A vm.TagCreateFailure = function (data) %7B%0A $log.log(data.data);%0A var errorMsg = %22This is odd...%22;%0A if (data.data.errmsg.indexOf(%22name%22) %3E -1)%0A errorMsg = %22Seems like the tag already exists%22;%0A toastr.error(errorMsg, 'Woops...');%0A %7D;%0A%0A vm.submit = function () %7B%0A $log.log(%22innit%22);%0A TagsService%0A .tags%0A .save(%7B%22name%22: vm.name, %22description%22: vm.description, %22flag%22: vm.flag%7D)%0A .$promise%0A .then(vm.TagCreateSuccess, vm.TagCreateFailure);%0A %7D%0A%0A vm.hide = function () %7B%0A $mdDialog.hide();%0A %7D%0A %7D +%0A %0A%0A%0A
3af4146e32259004a6e3e081707b65527a67aae7
disable actions logging;
actor-apps/app-web/src/app/stores/PreferencesStore.js
actor-apps/app-web/src/app/stores/PreferencesStore.js
import { EventEmitter } from 'events'; import ActorAppDispatcher from 'dispatcher/ActorAppDispatcher'; import { ActionTypes } from 'constants/ActorAppConstants'; const CHANGE_EVENT = 'change'; let _isModalOpen = false; class SettingsStore extends EventEmitter { constructor() { super(); } isModalOpen() { return _isModalOpen; } emitChange() { this.emit(CHANGE_EVENT); } addChangeListener(callback) { this.on(CHANGE_EVENT, callback); } removeChangeListener(callback) { this.removeListener(CHANGE_EVENT, callback); } } let SettingsStoreInstance = new SettingsStore(); SettingsStoreInstance.dispatchToken = ActorAppDispatcher.register(action => { console.info(action); switch(action.type) { case ActionTypes.SETTINGS_SHOW: _isModalOpen = true; break; case ActionTypes.SETTINGS_HIDE: _isModalOpen = false; break; default: return; } SettingsStoreInstance.emitChange(); }); export default SettingsStoreInstance;
JavaScript
0.000001
@@ -684,24 +684,26 @@ tion =%3E %7B%0A +// console.info
72ab5eed87265bc24c7bdefccb9104cc1e05e18f
rename dal to locationDal
server/api/locations/location/handlers.js
server/api/locations/location/handlers.js
var templates = require('./templates'); var dal = require('./dal'); var loggers = require('../../../services/logs/loggers'); var config = require('tresdb-config'); var status = require('http-status-codes'); var sanitizeFilename = require('sanitize-filename'); var slugify = require('slugify'); exports.changeGeom = function (req, res, next) { var u, lat, lng; var loc = req.location; if (typeof req.body.lat !== 'number' || typeof req.body.lng !== 'number') { return res.sendStatus(status.BAD_REQUEST); } lat = req.body.lat; lng = req.body.lng; u = req.user.name; dal.changeGeom({ locationId: loc._id, locationName: loc.name, locationGeom: loc.geom, locationLayer: loc.layer, username: u, latitude: lat, longitude: lng, }, function (err) { if (err) { return next(err); } return res.sendStatus(status.OK); }); }; exports.changeName = function (req, res, next) { let newLocName = req.body.newName; if (typeof newLocName !== 'string') { return res.status(status.BAD_REQUEST).send('Invalid name'); } // Remove excess whitespaces and prevent only-whitespace names. newLocName = newLocName.trim(); const minNameLen = 2; const maxNameLen = 120; if (newLocName.length < minNameLen || newLocName.length > maxNameLen) { return res.status(status.BAD_REQUEST).send('Too short or too long name'); } var params = { locationId: req.location._id, locationName: req.location.name, newName: req.body.newName, username: req.user.name, }; dal.changeName(params, function (err) { if (err) { return next(err); } return res.sendStatus(status.OK); }); }; exports.changeTags = function (req, res) { // TODO Remove at some point var msg = 'Tags API is not available anymore. Update your client.'; return res.status(status.GONE).send(msg); }; exports.changeStatus = function (req, res, next) { // Validate status if (typeof req.body.status === 'string') { if (config.locationStatuses.indexOf(req.body.status) < 0) { var msg = 'Invalid location status: ' + req.body.status; return res.status(status.BAD_REQUEST).send(msg); } } else { return res.sendStatus(status.BAD_REQUEST); } // If no change, everything ok already var oldStatus = req.location.status; var newStatus = req.body.status; if (oldStatus === newStatus) { return res.status(status.OK).send('Status not changed. Same already.'); } dal.changeStatus({ locationId: req.location._id, locationName: req.location.name, locationStatus: oldStatus, username: req.user.name, status: newStatus, }, function (err) { if (err) { return next(err); } return res.sendStatus(status.OK); }); }; exports.changeType = function (req, res, next) { // Validate type if (typeof req.body.type === 'string') { if (config.locationTypes.indexOf(req.body.type) < 0) { var msg = 'Invalid location type: ' + req.body.type; return res.status(status.BAD_REQUEST).send(msg); } } else { return res.status(status.BAD_REQUEST).send('Invalid location type'); } // If no change, everything ok already var oldType = req.location.type; var newType = req.body.type; if (oldType === newType) { return res.status(status.OK).send('Type not changed. Same already.'); } dal.changeType({ locationId: req.location._id, locationName: req.location.name, locationType: oldType, username: req.user.name, type: newType, }, function (err) { if (err) { return next(err); } return res.sendStatus(status.OK); }); }; exports.changeThumbnail = (req, res) => { res.sendStatus(status.OK); }; exports.getOne = function (req, res, next) { // Fetch single location with entries and events // eslint-disable-next-line max-statements dal.getOneComplete(req.location._id, function (err, rawLoc) { if (err) { return next(err); } if (!rawLoc) { return res.sendStatus(status.NOT_FOUND); } var responseStr, filename, mime; var format = req.query.format; if (typeof format === 'string') { format = format.toLowerCase(); if (format === 'geojson') { responseStr = templates.geojson(rawLoc, true); mime = 'application/vnd.geo+json'; } if (format === 'gpx') { responseStr = templates.gpx(rawLoc); mime = 'application/gpx+xml'; } if (format === 'kml') { responseStr = templates.kml(rawLoc); mime = 'application/vnd.google-earth.kml+xml'; } if (typeof mime !== 'string') { // This mime type is not found return res.sendStatus(status.NOT_FOUND); } // Name of the file to download. // Slugification is needed after sanitizeFilename because // http headers do not handle non-ascii and non-alpha-numerics well. // See https://stackoverflow.com/q/93551/638546 filename = slugify(sanitizeFilename(rawLoc.name)) + '.' + format; // Set headers res.set('Content-Type', mime); res.set('Content-Disposition', 'attachment; filename=' + filename); return res.send(responseStr); } // else // Log that user has viewed a location. loggers.log(req.user.name + ' viewed location ' + rawLoc.name + '.'); return res.json(rawLoc); }); }; exports.removeOne = function (req, res, next) { // Delete single location dal.removeOne(req.location._id, req.user.name, function (err) { if (err) { return next(err); } return res.sendStatus(status.OK); }); };
JavaScript
0.999991
@@ -38,17 +38,25 @@ ');%0Avar -d +locationD al = req @@ -593,25 +593,33 @@ er.name;%0A%0A -d +locationD al.changeGeo @@ -1562,25 +1562,33 @@ me,%0A %7D;%0A%0A -d +locationD al.changeNam @@ -2491,33 +2491,41 @@ eady.');%0A %7D%0A%0A -d +locationD al.changeStatus( @@ -3392,17 +3392,25 @@ %0A %7D%0A%0A -d +locationD al.chang @@ -3898,17 +3898,25 @@ ments%0A -d +locationD al.getOn @@ -5500,17 +5500,25 @@ tion%0A%0A -d +locationD al.remov
be794c7195925b5334cd70b58f1a6ecb7212a62d
Remove hardcoded value
server/api/resolvers/calendarResolvers.js
server/api/resolvers/calendarResolvers.js
import CalendarModel from '../models/calendar'; import TeacherModel from '../models/teacher'; import GradeModel from '../models/grade'; import UserModel from '../models/user'; import { isAuthenticatedResolver, isAdminResolver } from '../acl'; import { createResolver, and } from 'apollo-resolvers'; import { createError } from 'apollo-errors'; const NameAlreadyExists = createError('NameAlreadyExists', { message: 'Name already exists' }); const AnotherCalendarActive = createError('AnotherCalendarActive', { message: 'Another calendar is already active' }); const checkIfNameAlreadyExists = createResolver((root, { name }) => { if (CalendarModel.findOne({ name })) { throw new NameAlreadyExists(); } }); const findOne = () => { return CalendarModel.findOne({ active: true }); }; const activateCalendar = (root, { _id, active }) => { if (active && CalendarModel.findOne({ active: true })) { throw new AnotherCalendarActive(); } CalendarModel.update({ _id }, { $set: { active } }) === 1; }; export default { Query: { calendar: findOne, calendars: isAuthenticatedResolver.createResolver(CalendarModel.resolverFindAll) }, Mutation: { createCalendar: and(isAdminResolver, checkIfNameAlreadyExists)(CalendarModel.mutationCreate), updateCalendar: and(isAdminResolver, checkIfNameAlreadyExists)(CalendarModel.mutationUpdate), removeCalendar: and(isAdminResolver)(CalendarModel.mutationRemove), activateCalendar: and(isAdminResolver)(activateCalendar), updateCalendarItemInterest: isAuthenticatedResolver.createResolver(CalendarModel.updateCalendarItemInterest), setTeacherInCalendarItem: and(isAdminResolver)(CalendarModel.setTeacherInCalendarItem), removeItemFromCalendar: and(isAdminResolver)(CalendarModel.removeItemFromCalendar), addItemToCalendar: and(isAdminResolver)(CalendarModel.addItemToCalendar) }, Calendar: { grade: ({ grade }) => grade || [] }, CalendarItem: { // _id needs to hava a unique identifier _id: ({ _id, shift, day }) => `${ _id }:${ shift }:${ day }`, teacher: ({ teacher }) => TeacherModel.findOne({ _id: teacher }), grade: ({ _id }, { course }, context) => { if (course) { context.course = course; } else if (context.userId) { context.course = UserModel.findOne(context.userId).profile.course; } return GradeModel.findOne({ _id }); }, userStatus: ({ _id }, args, { userId }) => { if (!userId) { return; } const user = UserModel.findOne({ _id: userId, [`grade.${ _id }`]: { $exists: true } }, { grade: 1 }); if (user) { return user.grade[_id]; } return 'pending'; }, userInterested: ({ _id, shift, day }, args, { userId }) => { if (!userId) { return false; } const key = `${ shift }${ day }-${ _id }`; const user = UserModel.findOne({ _id: userId, ['calendar.2018-2']: key }, { fields: { grade: 1 } }); if (user) { return true; } } } };
JavaScript
0.023907
@@ -729,22 +729,49 @@ = ( -) =%3E %7B%0A%09return +root, args, context) =%3E %7B%0A%09const result = Cal @@ -810,16 +810,68 @@ rue%0A%09%7D); +%0A%0A%09context.calendarId = result._id;%0A%0A%09return result; %0A%7D;%0A%0Acon @@ -2740,32 +2740,44 @@ , args, %7B userId +, calendarId %7D) =%3E %7B%0A%09%09%09if ( @@ -2916,17 +2916,17 @@ d,%0A%09%09%09%09%5B -' +%60 calendar @@ -2930,15 +2930,24 @@ dar. -2018-2' +$%7B calendarId %7D%60 %5D: k
0686c1d048e7e921ec32d0596cbbcf607d129dd1
Throw error objects in snprintf, so we can get usable stacks if we pass the wrong things in
lib/extern/sprintf.js
lib/extern/sprintf.js
/** sprintf() for JavaScript 0.6 Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of sprintf() for JavaScript nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Changelog: 2007.04.03 - 0.1: - initial release 2007.09.11 - 0.2: - feature: added argument swapping 2007.09.17 - 0.3: - bug fix: no longer throws exception on empty paramenters (Hans Pufal) 2007.10.21 - 0.4: - unit test and patch (David Baird) 2010.05.09 - 0.5: - bug fix: 0 is now preceeded with a + sign - bug fix: the sign was not at the right position on padded results (Kamal Abdali) - switched from GPL to BSD license 2010.05.22 - 0.6: - reverted to 0.4 and fixed the bug regarding the sign of the number 0 Note: Thanks to Raphael Pigulla <raph (at] n3rd [dot) org> (http://www.n3rd.org/) who warned me about a bug in 0.5, I discovered that the last update was a regress. I appologize for that. **/ function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return o.join(''); } function sprintf() { var i = 0, a, f = arguments[i++], o = [], m, p, c, x, s = ''; while (f) { if (m = /^[^\x25]+/.exec(f)) { o.push(m[0]); } else if (m = /^\x25{2}/.exec(f)) { o.push('%'); } else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) { if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) { throw('Too few arguments.'); } if (/[^s]/.test(m[7]) && (typeof(a) != 'number')) { throw('Expecting number but found ' + typeof(a)); } switch (m[7]) { case 'b': a = a.toString(2); break; case 'c': a = String.fromCharCode(a); break; case 'd': a = parseInt(a); break; case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break; case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break; case 'o': a = a.toString(8); break; case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break; case 'u': a = Math.abs(a); break; case 'x': a = a.toString(16); break; case 'X': a = a.toString(16).toUpperCase(); break; } a = (/[def]/.test(m[7]) && m[2] && a >= 0 ? '+'+ a : a); c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' '; x = m[5] - String(a).length - s.length; p = m[5] ? str_repeat(c, x) : ''; o.push(s + (m[4] ? a + p : p + a)); } else { throw('Huh ?!'); } f = f.substring(m[0].length); } return o.join(''); } exports.sprintf = sprintf;
JavaScript
0
@@ -2826,16 +2826,26 @@ %09%09%09throw + new Error ('Too fe @@ -2932,16 +2932,26 @@ %09%09%09throw + new Error ('Expect @@ -3825,16 +3825,26 @@ %09%09%09throw + new Error ('Huh ?!
0d6d09c094897b2acb24e9f900858f5c36406f90
fix typo in function name
lib/extractLicense.js
lib/extractLicense.js
module.exports = extractLink /** * Extract license type from registry data for a package * @param {object} json - object fetched from registry with information about 1 package * @returns {string} with license type */ function extractLink(json) { if (typeof json.license === 'string') { return json.license } if (typeof json.license === 'object') { return json.license.type } if (Array.isArray(json.licenses)) { let result = '' for (let i = 0; i < json.licenses.length; i++) { if (i > 0) result += ', ' if (typeof json.licenses[i] === 'string') { result += json.licenses[i] } else { result += json.licenses[i].type } } return result } }
JavaScript
0.99848
@@ -19,18 +19,21 @@ xtractLi -nk +cense %0A%0A/**%0A * @@ -240,10 +240,13 @@ ctLi -nk +cense (jso
abe3f76961debcf3665c15aa69a9744ab0921fc2
use str.replace to fix function
easy-challenges/CamelCase.js
easy-challenges/CamelCase.js
const assert = require('assert'); const CamelCase = (str) => { str.split(/\W/).map((word, i) => { const formatted = word.toLowerCase(); return i ? `${formatted[0].toUpperCase()}${formatted.slice(1)}` : formatted; }).join(''); }; console.log(CamelCase('cats AND*Dogs-are Awesome')); const in1 = 'cats AND*Dogs-are Awesome'; // input const r1 = 'catsAndDogsAreAwesome'; // output const test1 = CamelCase(in1); assert(r1, test1); const in2 = 'a b t d-e-f%g'; // input const r2 = 'aBtDEFG'; // output const test2 = CamelCase(in2); assert(r2, test2);
JavaScript
0.000003
@@ -28,21 +28,24 @@ ert');%0A%0A -const +function CamelCa @@ -50,200 +50,197 @@ Case - = (str) - =%3E %7B%0A -str.split(/%5CW/).map((word, i) =%3E %7B%0A const formatted = word.toLowerCase();%0A return i ? %60$%7Bformatted%5B0%5D.toUpperCase()%7D$%7Bformatted.slice(1)%7D%60 : formatted;%0A %7D).join('');%0A%7D;%0A +return str.replace(/(?:%5E%5Cw%7C%5BA-Z%5D%7C%5Cb%5Cw%7C%5Cs+)/g, (match, index) =%3E %7B%0A if (+match === 0) return '';%0A return index === 0 ? match.toLowerCase() : match.toUpperCase();%0A %7D);%0A%7D%0A%0A// cons
46146678a23a73dae510caec9c08b6a85baa67b9
Remove unnecessary else block
lib/generator/post.js
lib/generator/post.js
'use strict'; var lodash = require('lodash'); module.exports = function(locals) { var posts = locals.posts.sort('-date').toArray(); var length = posts.length; function getAlternatePosts(label) { var alternates = posts.filter(function(post) { return post.label === label; }); var result = []; lodash.each(alternates, function(post) { result.push({ title: post.title, lang: post.lang, path: post.path }); }); return result; } return posts.map(function(post, i) { var layout = post.layout; var path = post.path; var j; var layouts = ['post', 'page', 'index']; if (!layout || layout === 'false') { return { path: path, data: post.content }; } else { if (post.lang !== undefined) { for (j = i - 1; j >= 0 && post.prev === undefined; j--) { if (post.lang === posts[j].lang) { post.prev = posts[j]; } } for (j = i + 1; j < length && post.next === undefined; j++) { if (post.lang === posts[j].lang) { post.next = posts[j]; } } } else { // Default behavior if (i) post.prev = posts[i - 1]; if (i < length - 1) post.next = posts[i + 1]; } if (layout !== 'post') layouts.unshift(layout); if (post.label && post.lang) { post.alternates = getAlternatePosts(post.label); } return { path: path, layout: layouts, data: lodash.extend({ __post: true }, post) }; } }); };
JavaScript
0.000001
@@ -760,34 +760,25 @@ %7D;%0A %7D - else %7B%0A +%0A if (post @@ -802,26 +802,24 @@ ed) %7B%0A - for (j = i - @@ -860,26 +860,24 @@ ned; j--) %7B%0A - if ( @@ -913,26 +913,24 @@ %7B%0A - post.prev = @@ -931,34 +931,32 @@ rev = posts%5Bj%5D;%0A - %7D%0A @@ -951,30 +951,26 @@ %7D%0A - %7D%0A +%7D%0A for (j @@ -1029,26 +1029,24 @@ ) %7B%0A - - if (post.lan @@ -1074,26 +1074,24 @@ %7B%0A - post.next = @@ -1104,30 +1104,26 @@ j%5D;%0A - - %7D%0A - %7D%0A @@ -1122,18 +1122,16 @@ %7D%0A - - %7D else %7B @@ -1131,18 +1131,16 @@ else %7B%0A - // @@ -1159,26 +1159,24 @@ avior%0A - - if (i) post. @@ -1192,26 +1192,24 @@ sts%5Bi - 1%5D;%0A - if (i @@ -1244,26 +1244,24 @@ sts%5Bi + 1%5D;%0A - %7D%0A%0A @@ -1255,26 +1255,24 @@ %0A %7D%0A%0A - if (layout ! @@ -1308,18 +1308,16 @@ yout);%0A%0A - if ( @@ -1345,26 +1345,24 @@ ng) %7B%0A - post.alterna @@ -1402,23 +1402,19 @@ l);%0A - %7D%0A%0A - retu @@ -1410,34 +1410,32 @@ %7D%0A%0A return %7B%0A - path: path @@ -1442,18 +1442,16 @@ ,%0A - layout: @@ -1459,18 +1459,16 @@ ayouts,%0A - da @@ -1495,18 +1495,16 @@ - __post: @@ -1508,18 +1508,16 @@ t: true%0A - %7D, @@ -1527,26 +1527,18 @@ st)%0A - %7D;%0A %7D +; %0A %7D);%0A%7D
399d25788a2607c63669b50056545729718296ab
Add oneWordAvailable method
lib/geo.what3words.js
lib/geo.what3words.js
var http = require('http'), unirest = require('unirest'), _ = require('lodash'); /** * What3Words API wrapper for the API version 1.0. * * @param apiKey The API key to access the What3Words API with * @param options Configuration options * @return Instance of {@link What3Words} */ function What3Words (apiKey, options) { if (!options) { options = {}; } if (!apiKey) { throw new Error('API Key not set'); } this.version = '1.0'; this.apiKey = apiKey; this.endpoint = options.endpoint || 'http://api.what3words.com/'; this.language = options.language || 'en'; this.userAgent = options.userAgent || 'JS Geo::What3Words'; } module.exports = What3Words; /** * Convert GPS co-ordinates into 3 words. * @param {[object]} options Can contain the following properties: * * lang: alternative language, default will be usef if this is not declared. * * position: a string containing lat,long * * full: Return the full response */ What3Words.prototype.positionToWords = function (options, callback) { var language = options.lang || this.language; this.execute('position', {position: options.position, lang: language}, function(response) { if (options.full) { callback(response); } callback(response.words.join('.')); }); }; /** * Convert 3 words or a OneWord into GPS coordinates * @param {[object]} options Can contain the following properties: * * lang: alternative language, default will be usef if this is not declared. * * words: a string containing 3 dot separated words * * full: Return the full response */ What3Words.prototype.wordsToPosition = function (options, callback) { var language = options.lang || this.language; this.execute('w3w', {string: options.words, lang: language}, function(response) { if (options.full) { callback(response); } callback(response.position.join(',')); }); }; /** * Returns a list of the W3W available languages * @param {[object]} options Can contain the following properties: * * full: Return the full response */ What3Words.prototype.getLanguages = function (options, callback) { this.execute('get-languages', {}, function(response) { if (options.full) { callback(response); } callback(_.pluck(response.languages, 'code')); }); }; /** * Sends a given request as a JSON object to the W3W API and finally * calls the given callback function with the resulting JSON object. * * @param {[type]} method W3W API method to call * @param {[type]} params Object containg parameters to call the API with * @param {Function} callback To be called on success */ What3Words.prototype.execute = function (method, params, callback) { var finalParams = _.extend({ key: this.apiKey }, params); unirest.post(this.endpoint + method) .headers({ 'Accept': 'application/json', 'User-Agent': this.userAgent }) .send(finalParams) .end(function (response) { if (response.code !== 200) { throw new Error('Unable to connect to the What3Words API endpoint.'); } else if (response.body.error) { throw new Error(response.body.error + '. Message: ' + response.body.message); } callback(response.body); }); };
JavaScript
0
@@ -718,24 +718,647 @@ at3Words;%0A%0A%0A +/**%0A * Checks if oneWord is available%0A * @param %7B%5Bobject%5D%7D options Can contain the following properties:%0A * * lang: alternative language, default will be usef if this is not declared.%0A * * word: a string containing the oneWord%0A * * full: Return the full response%0A */%0AWhat3Words.prototype.oneWordAvailable = function (options, callback) %7B%0A var language = options.lang %7C%7C this.language;%0A%0A this.execute('oneword-available', %7Bword: options.word, lang: language%7D, function(response) %7B%0A if (options.full) %7B%0A callback(response);%0A %7D%0A%0A callback(response.available);%0A %7D);%0A%7D;%0A%0A%0A /**%0A * Conve
e0dc68db2e866b09ea021202393c44cea1b371f6
remove domain. it sucks hard
lib/helpers/upload.js
lib/helpers/upload.js
"use strict"; var Anyfetch = require('anyfetch'); var path = require('path'); var nodeDomain = require("domain"); var async = require('async'); var save = require('./save'); Anyfetch.setApiUrl(require('../../config.js').apiUrl); var uploadFile = function(filePath, baseIdentifier, creationDate, cb) { var absolutePath = filePath; if(filePath.indexOf(GLOBAL.WATCHED_DIR) === -1) { //if the file path is relative absolutePath = GLOBAL.WATCHED_DIR + filePath; } var domain = nodeDomain.create(); async.waterfall([ function sendFile(cb) { var anyfetch = new Anyfetch(GLOBAL.ACCESS_TOKEN); var title = path.basename(filePath, path.extname(filePath)); title = title.replace(/(_|-|\.)/g, ' '); title = title.charAt(0).toUpperCase() + title.slice(1); // Send a document to anyFetch var document = { identifier: baseIdentifier + filePath, document_type: 'file', creation_date: creationDate, metadata: { title: title } }; var fileConfig = { file: absolutePath, filename: path.basename(filePath), }; var onlyOnce = function(err) { if(!onlyOnce.called) { onlyOnce.called = true; cb(err); } }; onlyOnce.called = false; domain.on('error', onlyOnce); domain.run(function() { anyfetch.sendDocumentAndFile(document, fileConfig, onlyOnce); }); }, function savingInCursor(cb) { console.log("UPPING ", filePath); GLOBAL.CURSOR[filePath] = creationDate; save(cb); }, ], function(err) { domain.exit(); domain.dispose(); if(err) { console.warn('Error while upping', filePath, ': ', err); } cb(); }); }; var deleteFile = function(filePath, baseIdentifier, cb) { if(filePath.indexOf(GLOBAL.WATCHED_DIR) !== -1) { //if the file path is absolute filePath = "/" + path.relative(GLOBAL.WATCHED_DIR, filePath); } async.waterfall([ function deleteFile(cb) { var anyfetch = new Anyfetch(GLOBAL.ACCESS_TOKEN); anyfetch.deleteDocumentByIdentifier(baseIdentifier + filePath, function(err, res) { if(err && res.statusCode === 404) { err = null; } cb(err); }); }, function savingInCursor(cb) { console.log("DELETING", filePath); delete GLOBAL.CURSOR[filePath]; save(cb); }, ], cb); }; module.exports.uploadQueue = async.queue(function worker(task, cb) { uploadFile(task.filePath, task.baseIdentifier, task.creationDate, cb); }, 4); module.exports.deleteQueue = async.queue(function worker(task, cb) { deleteFile(task.filePath, task.baseIdentifier, cb); }, 4); module.exports.uploadFile = uploadFile; module.exports.deleteFile = deleteFile;
JavaScript
0.000135
@@ -476,44 +476,8 @@ %7D%0A%0A - var domain = nodeDomain.create();%0A as @@ -1101,249 +1101,8 @@ %7D;%0A -%0A var onlyOnce = function(err) %7B%0A if(!onlyOnce.called) %7B%0A onlyOnce.called = true;%0A cb(err);%0A %7D%0A %7D;%0A onlyOnce.called = false;%0A%0A domain.on('error', onlyOnce);%0A domain.run(function() %7B%0A @@ -1158,26 +1158,10 @@ ig, -onlyOnce);%0A %7D +cb );%0A @@ -1186,32 +1186,42 @@ savingInCursor( +document, cb) %7B%0A cons @@ -1344,49 +1344,8 @@ ) %7B%0A - domain.exit();%0A domain.dispose();%0A
463125c8190f4a076d957f231f15981cca7f0d74
Add additional time to backoff
lib/helpers/upload.js
lib/helpers/upload.js
'use strict'; var url = require('url'); var https = require('follow-redirects').https; var async = require('async'); var rarity = require('rarity'); var crypto = require('crypto'); var fs = require('fs'); var generateTitle = require('anyfetch-provider').util.generateTitle; /** * Upload file onto AnyFetch. * * * @param {Object} task Data of the task * @param {Object} anyfetchClient Client for upload * @param {Object} accessToken Access token of the current account * @param {Function} cb Callback to call once file has been uploaded. */ module.exports = function(task, anyfetchClient, accessToken, cb) { var path = '/tmp/' + crypto.randomBytes(20).toString('hex'); /* * We don't know what GDrive do when we export file (Google Drive converted files) * And if we don't save this files in tmp files, we have error "400 Bad Request" with NGinx * So, normal files without export links are direct streamed to the API and others pass through a temp file */ async.waterfall([ function requestFile(cb) { var options = url.parse(task.downloadUrl); options.headers = { 'Authorization': 'Bearer ' + accessToken }; // We need to set this header, without we have a socket hang up with direct stream if(!task.exported) { options.headers = {"Connection" : "close"}; } // Google can have random 500 error. So we must do an exponential backoff. // See http://stackoverflow.com/questions/12471180/frequently-http-500-internal-error-with-google-drive-api-drive-files-get var time = 200; function tryRequest(cb) { var req = https.request(options, function(res) { if(res.statusCode !== 500 || time > 10000) { return cb(null, res); } time *= 2; setTimeout(function() { tryRequest(cb); }, time); }); req.on('error', cb); req.end(); } tryRequest(cb); }, function generateStream(res, cb) { if(res.statusCode !== 200) { return cb(new Error('GDrive bad status code : ' + res.statusCode)); } if(!task.exported) { return cb(null, res); } var stream = fs.createWriteStream(path); stream.on('error', cb); res.on('end', function() { cb(null, path); }); res.pipe(stream); }, function sendFile(data, cb) { var fileConfig = function(cb) { cb(null, { file: (task.exported) ? fs.createReadStream(path) : data, filename: task.title }); }; var document = { identifier: task.identifier, actions: { show: task.link }, creation_date: task.createdDate, modification_date: task.modifiedDate, metadata: { title: generateTitle(task.title), path: '/' + task.title, starred: task.starred }, document_type: task.type, user_access: [anyfetchClient.accessToken] }; anyfetchClient.sendDocumentAndFile(document, fileConfig, rarity.slice(1, cb)); }, function deleteTempFile(cb) { if(task.exported) { fs.unlink(path, cb); } else { cb(null); } } ], cb); };
JavaScript
0.000001
@@ -1706,17 +1706,17 @@ time %3E 1 -0 +3 000) %7B%0A
92238a19a9228f8e66d882742960b2b784e73f0e
use buffer, fewer errors but not totaly out of the woods
processing/water/piranha.js
processing/water/piranha.js
var turf = require('turf') var fs = require('fs') // wow. such vars. var tractPolys = JSON.parse(fs.readFileSync(process.argv[2])); var piranhas = JSON.parse(fs.readFileSync(process.argv[3])); var piranhaPolys = {"type":"FeatureCollection","features":[]}; var tractsEaten = {"type":"FeatureCollection","features":[]}; console.log('Processing ' + process.argv[3] + ' with ' + piranhas.features.length + ' water features'); if (piranhas.features.length > 0) { // Isolate the water polygons from all that other osm noise for (var p = 0; p < piranhas.features.length; p++) { if (piranhas.features[p].geometry.type == 'Polygon' || piranhas.features[p].geometry.type == 'MultiPolygon') { piranhaPolys.features.push(piranhas.features[p]); } } try { // expand everything by 50m to catch intersections // piranhaPolys = turf.buffer(piranhaPolys,0.05,'kilometers'); // dissolve the water features piranhaPolys = turf.merge(piranhaPolys); } catch (e) { console.log(e); } // loop through all tracts looking for intersection for (var i = 0; i < tractPolys.features.length; i++) { // chomp water from tract polygon if intersecting if (turf.intersect(piranhaPolys,tractPolys.features[i])) { console.log('Tract ' + tractPolys.features[i].properties.TRACTCE + ' is in the water. Chomping . . .') tractsEaten.features.push(turf.erase(tractPolys.features[i],piranhaPolys)); } // otherwise just write the tract polygon as is else { //console.log('Tract ' + tractPolys.features[i].properties.TRACTCE + ' is dry.') tractsEaten.features.push(tractPolys.features[i]) } } //cut and print to file fs.writeFileSync(process.argv[2], JSON.stringify(tractsEaten)); } else { fs.writeFileSync(process.argv[2], JSON.stringify(tractPolys)); }
JavaScript
0.000001
@@ -790,17 +790,17 @@ hing by -5 +2 0m to ca @@ -820,19 +820,16 @@ ions%0A - // piranha @@ -868,9 +868,9 @@ ,0.0 -5 +2 ,'ki
ee0ffe65835997285bdd5482be7f0b96429f80c8
return this from setJson
lib/model/modelSet.js
lib/model/modelSet.js
'use strict'; const parseRelationsIntoModelInstances = require('./modelParseRelations') .parseRelationsIntoModelInstances; function setJson(model, json, options) { json = json || {}; options = options || {}; if (Object.prototype.toString.call(json) !== '[object Object]') { throw new Error( 'You should only pass objects to $setJson method. ' + '$setJson method was given an invalid value ' + json ); } json = model.$parseJson(json, options); json = model.$validate(json, options); model.$set(json); if (!options.skipParseRelations) { parseRelationsIntoModelInstances(model, json, options); } } function setDatabaseJson(model, json) { json = model.$parseDatabaseJson(json); if (json) { const keys = Object.keys(json); for (let i = 0, l = keys.length; i < l; ++i) { const key = keys[i]; model[key] = json[key]; } } return model; } function setFast(model, obj) { if (obj) { // Don't try to set read-only virtual properties. They can easily get here through `fromJson` // when parsing an object that was previously serialized from a model instance. const readOnlyVirtuals = model.constructor.getReadOnlyVirtualAttributes(); const keys = Object.keys(obj); for (let i = 0, l = keys.length; i < l; ++i) { const key = keys[i]; const value = obj[key]; if ( key.charAt(0) !== '$' && typeof value !== 'function' && (readOnlyVirtuals === null || readOnlyVirtuals.indexOf(key) === -1) ) { model[key] = value; } } } return model; } module.exports = { setFast, setJson, setDatabaseJson };
JavaScript
0.999901
@@ -644,16 +644,33 @@ ns);%0A %7D +%0A%0A return model; %0A%7D%0A%0Afunc
8d5091abe9b29131933861c26f9ac2a617c36331
fix bumber input format
public/backend/js/stock-transfer.js
public/backend/js/stock-transfer.js
function calculateTransferDetails(container) { var rows = container.find('table tbody tr:visible'); var quantity_total = 0; var total_stock_source = 0; var total_stock_destination = 0; var total_stock_source_after = 0; var total_stock_destination_after = 0; rows.each(function() { var row = $(this); var quantity = 0; if (row.find('.line_quantity').val() !== '') { quantity = parseFloat(row.find('.line_quantity').val()); } var stock_source = parseFloat(row.find('.line_stock_source').html()); var stock_destination = parseFloat(row.find('.line_stock_destination').html()); var stock_source_after = stock_source-quantity; var stock_destination_after = stock_destination+quantity; // update line stock source after row.find('.line_stock_source_after').html(stock_source_after); // update line total without tax row.find('.line_stock_destination_after').html(stock_destination_after); // add/remove class html if (stock_source_after < 0) { row.find('.line_stock_source_after').addClass('font-yellow-gold'); } else { row.find('.line_stock_source_after').removeClass('font-yellow-gold'); } // Update quantity total if (quantity) { quantity_total += quantity; } if (stock_source) { total_stock_source += stock_source; } if (stock_destination) { total_stock_destination += stock_destination; } total_stock_source_after += stock_source_after; total_stock_destination_after += stock_destination_after; }); // update total $('.transfer-details .total_transfer').html(formatNumber(quantity_total)); $('.transfer-details .total_stock_source_before').html(formatNumber(total_stock_source)); $('.transfer-details .total_stock_source_after').html(formatNumber(total_stock_source_after)); $('.transfer-details .total_stock_destination_before').html(formatNumber(total_stock_destination)); $('.transfer-details .total_stock_destination_after').html(formatNumber(total_stock_destination_after)); } // Main js execute when loaded page $(document).ready(function() { $('.transfer-details').each(function() { calculateTransferDetails($(this)); }); // Change event on order line $(document).on('change keyup', '.transfer-details input', function(e) { var container = $(this).parents('.transfer-details'); calculateTransferDetails(container); }); // Click event nested remove button $(document).on('click', '.nested-remove-button', function(e) { var container = $(this).parents('.transfer-details'); calculateTransferDetails(container); }); });
JavaScript
0.999232
@@ -444,17 +444,23 @@ ntity = -p +customP arseFloa @@ -535,17 +535,23 @@ ource = -p +customP arseFloa @@ -625,17 +625,23 @@ ation = -p +customP arseFloa @@ -684,32 +684,24 @@ ).html());%0D%0A - %0D%0A va @@ -814,24 +814,16 @@ ntity;%0D%0A - %0D%0A @@ -927,32 +927,24 @@ ce_after);%0D%0A - %0D%0A // @@ -1057,24 +1057,16 @@ fter);%0D%0A - %0D%0A @@ -1320,32 +1320,24 @@ %0A %7D%0D%0A - %0D%0A // @@ -1433,32 +1433,24 @@ %0A %7D%0D%0A - %0D%0A if @@ -1524,32 +1524,24 @@ %0A %7D%0D%0A - %0D%0A if @@ -1634,24 +1634,16 @@ %7D%0D%0A - %0D%0A @@ -2445,36 +2445,32 @@ is));%0D%0A %7D);%0D%0A - %0D%0A // Change @@ -2685,20 +2685,16 @@ %7D);%0D%0A - %0D%0A // @@ -2917,8 +2917,10 @@ %7D);%0D%0A%7D); +%0D%0A
836502f58760c4699b217797c5d942ef22fbdb99
fix typo
public/common/javascripts/object.js
public/common/javascripts/object.js
$(document).ready(function () { // If deepzoom URL is present initiate SeaDragon if ($('a[data-type=zoom]').size() > 0) { // Deepzoom image & viewer var zoomImg = $('a[data-type=zoom]').attr('href'), viewer; Seadragon.Config.imagePath = "/assets/common/javascripts/seadragon/img/"; Seadragon.Config.autoHideControls = false; viewer = new Seadragon.Viewer("zoom-viewer"); viewer.openDzi({ "url":zoomImg, "width":1800, "height":1400, "tileSize":256, "tileOverlap":0, "tileFormat":"jpg"}); } // Endpoint to retrieve related items for this object var mltEndpoint = '/organizations/' + Thing.orgId + '/api/search?id=' + Thing.hubId + '&format=json&mlt=true'; if(jsLabels.objTitle.length && $('#object-title-big').length) { $('#object-title-big').html(jsLabels.objTitle); } // Make the request for the related objects. If this is a Collection or a Museum, then this request will fail. // Use the bad request to change the layout to accomodate a Museum or Collection view definition $.ajax({ type: "GET", url: mltEndpoint, success: function(data){ var rItems = data.result.relatedItems.item, html = '', tmp, org, owner, id, uri; if (rItems) { $('.object-title').toggleClass('hide'); html = '<h5>' + jsLabels.relatedItems + '</h5>'; $.each(rItems, function (i, item) { tmp = item.fields['delving_hubId'].split('_'); org = tmp[0]; owner = tmp[1]; id = tmp[2]; uri = "/" + org + "/" + owner + "/" + id + "?mlt=true"; html += '<div class="media">'; html += '<a class="img" href="' + uri + '" rel="nofollow"><img class="mlt" src="' + item.fields['delving_thumbnail'] + '" alt="' + item.fields['delving_title'] + '" width="80" onerror="showDefaultImg(this)"/></a>'; html += '<div class="bd"><a href="' + uri + '" rel="nofollow"><div class="title">'+item.fields['delving_title'].trunc(40)+'</a></div>'; if (item.fields['dc_creator']) { html += '<div rel="dc:creator"><span>'+jsLabels.creator+':</span> '+item.fields['dc_creator']+'</div>'; } if (item.fields['europeana_collectionTitle']) { html += '<div rel="eruopeana:collectionTitle"><span>'+jsLabels.collection+':</span> '+item.fields['europeana_collectionTitle']+'</div>'; } html += '</div></div>'; }); html += "</ul>"; $('#related-items').html(html); } }, error: function(){ // $('.object-data').removeClass('span8'); } }); });
JavaScript
0.999991
@@ -2525,18 +2525,18 @@ v rel=%22e -r u +r opeana:c
9b10e021903d15c9e03c00226f0f836a03ce33df
Fix error when used with gulp-cucumber
lib/nightwatch-api.js
lib/nightwatch-api.js
'use strict' const _ = require('lodash') const co = require('co') const pify = require('pify') const fs = pify(require('fs'), { include: ['readFile'] }) const hookUtils = require('./hook-utils') const Runner = require.main.require('nightwatch/lib/runner/run') const ClientManager = require.main.require('nightwatch/lib/runner/clientmanager') const ClientRunner = require.main.require('nightwatch/lib/runner/cli/clirunner') const ChildProcess = require.main.require('nightwatch/lib/runner/cli/child-process') const Utils = require.main.require('nightwatch/lib/util/utils') const Protocol = require.main.require('nightwatch/lib/api/protocol') process.on('unhandledRejection', (reason, p) => { console.error('Unhandled Rejection at: Promise', p, 'reason:', reason) }) module.exports = class NightwatchApi { _startSession (options) { this.client = new ClientManager() this.client.init(options) this.client.api('currentEnv', options.currentEnv) this.protocol = Protocol(this.client.get()) } getClientApi () { return this.client.api() } * _closeSession () { yield new Promise((resolve, reject) => { this.client.get().on('nightwatch:finished', function () { resolve() }) this.client.terminate() }) } * takeScreenshot (moduleName, testName) { const filePath = Utils.getScreenshotFileName( {module: moduleName, name: testName}, true, this.client.options.screenshots.path ) yield new Promise((resolve, reject) => { this.protocol.screenshot(false, (response) => { if (response.state !== 'success') { reject(new Error('Creating screenshot was not successful. Response was:\n' + require('util').inspect(response))) } this.client.get().saveScreenshotToFile(filePath, response.value, (err) => { if (err) reject(err) resolve() }) }) }) const content = yield fs.readFile(filePath, 'base64') return { data: new Buffer(content, 'base64'), mimeType: 'image/png' } } addTestModulePaths (modulePaths) { this.modulePaths = modulePaths } addPathConverter (convert, revert) { const self = this const originalClientRunnerGetTestSource = ClientRunner.prototype.getTestSource ClientRunner.prototype.getTestSource = function () { ClientRunner.prototype.getTestSource = originalClientRunnerGetTestSource const originalArgv = _.cloneDeep(this.argv) const originalSettings = _.cloneDeep(this.settings) if (this.argv._source.length) { this.argv._source[0] = convert(this.argv._source[0]) } else if (this.argv.test) { this.argv.test = convert(this.argv.test) } else { this.settings.src_folders = self.modulePaths } self.nightwatchArgv = this.argv self.testSource = ClientRunner.prototype.getTestSource.apply(this, arguments) if (this.parallelMode) { return self.testSource } this.argv = originalArgv this.settings = originalSettings this.settings.src_folders = this.settings.src_folders || [] return ClientRunner.prototype.getTestSource.apply(this, arguments) } hookUtils.addHookBefore(ChildProcess.prototype, 'getArgs', function () { const cliArgs = this.args const testIndex = cliArgs.indexOf('--test') + 1 cliArgs[testIndex] = revert(cliArgs[testIndex]) }) } addHookAfterChildProcesses (hook) { hookUtils.addCallbackedHookAfter(ClientRunner.prototype, 'startChildProcesses', 1, hook) } isRunningInParallel () { return process.env.__NIGHTWATCH_PARALLEL_MODE === '1' } getWorkerIndex () { return process.env.__NIGHTWATCH_ENV_KEY.split('_').pop() } * executeInNightwatchContext (fn, args) { yield new Promise((resolve, reject) => { const nightwatch = this.client.api() this.client.on('error', reject) nightwatch.perform(() => { try { this.client.get().results.lastError = null fn.apply(nightwatch, args) } catch (err) { this.client.removeListener('error', reject) return reject(err) } }) nightwatch.perform(() => { this.client.removeListener('error', reject) const lastError = this.client.get().results.lastError if (lastError) { lastError.stack = [lastError.message, lastError.stack].join('\n') return reject(lastError) } resolve() }) this.client.start() }) } addTestRunner (run) { const self = this const originalRunnerRun = Runner.prototype.run Runner.prototype.run = co.wrap(function * () { const that = this let error let originalTerminate let executionSuccess const originalOptions = _.cloneDeep(this.options) const originalAdditionalOpts = _.cloneDeep(this.additionalOpts) this.additionalOpts.output_folder = false this.options.output = false this.options.tag_filter = undefined this.options.screenshots.enabled = false try { const modules = yield new Promise((resolve, reject) => { Runner .readPaths(self.testSource, that.options) .spread(function (modulePaths, fullPaths) { resolve(modulePaths) }).then(resolve, reject) }) self._startSession(this.options) const client = self.client.get() originalTerminate = client.terminate client.terminate = () => {} executionSuccess = yield * run(modules) } catch (err) { error = err } try { if (self.client) { self.client.get().terminate = originalTerminate yield * self._closeSession() } } catch (err) { error = err } if (typeof process.send === 'function') { process.send(JSON.stringify({ type: 'testsuite_finished', itemKey: process.env.__NIGHTWATCH_ENV_LABEL, moduleKey: 'moduleKey', results: { completed: { ok: 1 } }, errmessages: [] })) } this.additionalOpts = originalAdditionalOpts this.options = originalOptions if (!originalAdditionalOpts.src_folders || !originalAdditionalOpts.src_folders.length || error || !executionSuccess) { return this.doneCb(error || !executionSuccess, {}) } return originalRunnerRun.apply(this, arguments) }) } }
JavaScript
0
@@ -2548,16 +2548,37 @@ ._source + && this.argv._source .length)
44ee80ec8f3aa3964b6f778c2e14cfa16ba8d5db
fix empty term in search
public/js/p3/widget/GlobalSearch.js
public/js/p3/widget/GlobalSearch.js
define([ "dojo/_base/declare", "dijit/_WidgetBase", "dojo/on", "dojo/dom-construct", "dojo/dom-class", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "dojo/text!./templates/GlobalSearch.html", "./Button", "dijit/registry", "dojo/_base/lang", "dojo/dom", "dojo/topic", "dijit/form/TextBox", "dojo/keys", "dijit/_FocusMixin", "dijit/focus" ], function(declare, WidgetBase, on, domConstruct, domClass, Templated, WidgetsInTemplate, template, Button, Registry, lang, dom, Topic, TextBox, keys, FocusMixin, focusUtil){ return declare([WidgetBase, Templated, WidgetsInTemplate, FocusMixin], { templateString: template, constructor: function(){ }, "baseClass": "GlobalSearch", "disabled": false, "value": "", _setValueAttr: function(q){ this.query = q; this.searchInput.set("value", q); }, parseQuery: function(query){ var finalTerms=[] var currentTerm=""; var propertyMatch; var quoted; if (query){ for (var i=0;i<query.length;i++){ var t = query[i]; switch(t){ case ":": propertyMatch = currentTerm; currentTerm=""; console.log("propertyMatch: ", propertyMatch) break; case '"': if (quoted){ if (propertyMatch){ finalTerms.push({property: propertyMatch, term: currentTerm + t}); propertyMatch=false; }else{ finalTerms.push(currentTerm + t); } quoted=false; currentTerm = "" }else{ currentTerm = currentTerm + t; quoted=true; } break; case " ": if (quoted){ currentTerm = currentTerm + t; }else{ if (propertyMatch){ finalTerms.push({property: propertyMatch, term: currentTerm}); propertyMatch=false; }else{ if (currentTerm.match(/[^a-zA-Z\d]/)){ currentTerm = '"' + currentTerm + '"' } finalTerms.push(currentTerm); } currentTerm=""; } break; default: currentTerm = currentTerm + t; } } if (currentTerm){ if (propertyMatch){ finalTerms.push({property: propertyMatch, term: currentTerm}); }else{ if (currentTerm.match(/[^a-zA-Z\d]/)){ currentTerm = '"' + currentTerm + '"' } finalTerms.push(currentTerm); } } var final=[] finalTerms.forEach(function(term){ if (!term) { return; } if (typeof term == 'string'){ final.push("keyword(" + encodeURIComponent(term) + ")"); }else{ final.push("eq(" + encodeURIComponent(term.property) + "," + encodeURIComponent(term.term) + ")"); } }) if (final.length>1){ return "and(" + final.join(",") + ")"; }else{ return final[0]; } } throw Error("No Query Supplied to Query Parser"); }, onKeypress: function(evt){ if(evt.charOrCode == keys.ENTER){ var query = this.searchInput.get('value'); var searchFilter = this.searchFilter.get('value'); if(!query){ return; } console.log("Search Filter: ", searchFilter); var q = this.parseQuery(query); var clear = false; switch(searchFilter){ case "amr": Topic.publish("/navigate", {href: "/view/GenomeList/?and(or(eq(antimicrobial_resistance,%22Intermediate%22),eq(antimicrobial_resistance,%22Resistant%22),eq(antimicrobial_resistance,%22Susceptible%22))," + q + ")"}); clear = true; break; case "everything": Topic.publish("/navigate", {href: "/search/?" + q}); clear = true; break; case "pathways": Topic.publish("/navigate", {href: "/view/PathwayList/?" + q}); clear = true; break; case "sp_genes": Topic.publish("/navigate", {href: "/view/SpecialtyGeneList/?" + q}); clear = true; break; case "genome_features": Topic.publish("/navigate", {href: "/view/FeatureList/?" + q}); clear = true; break; case "genomes": Topic.publish("/navigate", {href: "/view/GenomeList/?" + q}); clear = true; break; default: console.log("Do Search: ", searchFilter, query); } if(clear){ this.searchInput.set("value", ''); } console.log("Do Search: ", searchFilter, query); } }, onClickAdvanced: function(evt){ Topic.publish("/navigate", {href: "/search/"}); }, onInputChange: function(val){ /* val = val.replace(/\ /g, "&"); var dest = window.location.pathname + "?" + val; console.log("New Search Value",val,dest ); Topic.publish("/navigate", {href: dest, set: "query", value: "?"+val}); */ } }); });
JavaScript
0.999221
@@ -2350,16 +2350,17 @@ ar final +t =%5B%5D%0A%0A%09%09%09 @@ -2466,24 +2466,25 @@ %0A%09%09%09%09%09%09final +t .push(%22keywo @@ -2546,16 +2546,17 @@ %09%09%09final +t .push(%22e @@ -2669,16 +2669,17 @@ f (final +t .length%3E @@ -2708,16 +2708,17 @@ + final +t .join(%22, @@ -2755,16 +2755,17 @@ rn final +t %5B0%5D;%0A%09%09%09
9a5d6afaeffa6d99618b21ecd4dcd2f648889819
Update navigation icons in package section
src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js
src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js
(function () { "use strict"; function PackagesOverviewController($scope, $location, $routeParams, localizationService, localStorageService) { //Hack! // if there is a local storage value for packageInstallData then we need to redirect there, // the issue is that we still have webforms and we cannot go to a hash location and then window.reload // because it will double load it. // we will refresh and then navigate there. let packageInstallData = localStorageService.get("packageInstallData"); let packageUri = $routeParams.method; if (packageInstallData) { localStorageService.remove("packageInstallData"); } if (packageInstallData && packageInstallData !== "installed" && packageInstallData.postInstallationPath) { //navigate to the custom installer screen, if it is just "installed" it means there is no custom installer screen $location.path(packageInstallData.postInstallationPath).search("packageId", packageInstallData.id); } else { var vm = this; vm.page = {}; vm.page.labels = {}; vm.page.name = ""; vm.page.navigation = []; packageUri = packageInstallData ? packageInstallData : packageUri; //use the path stored in storage over the one in the current path onInit(); } function onInit() { loadNavigation(); setPageName(); } function loadNavigation() { var labels = ["sections_packages", "packager_installed", "packager_installLocal", "packager_created"]; localizationService.localizeMany(labels).then(function (data) { vm.page.labels.packages = data[0]; vm.page.labels.installed = data[1]; vm.page.labels.install = data[2]; vm.page.labels.created = data[3]; vm.page.navigation = [ { "name": vm.page.labels.packages, "icon": "icon-cloud", "view": "views/packages/views/repo.html", "active": !packageUri || packageUri === "repo", "alias": "umbPackages", "action": function () { $location.path("/packages/packages/repo"); } }, { "name": vm.page.labels.installed, "icon": "icon-box", "view": "views/packages/views/installed.html", "active": packageUri === "installed", "alias": "umbInstalled", "action": function () { $location.path("/packages/packages/installed"); } }, { "name": vm.page.labels.install, "icon": "icon-add", "view": "views/packages/views/install-local.html", "active": packageUri === "local", "alias": "umbInstallLocal", "action": function () { $location.path("/packages/packages/local"); } }, { "name": vm.page.labels.created, "icon": "icon-add", "view": "views/packages/views/created.html", "active": packageUri === "created", "alias": "umbCreatedPackages", "action": function () { $location.path("/packages/packages/created"); } } ]; }); } function setPageName() { localizationService.localize("sections_packages").then(function (data) { vm.page.name = data; }) } } angular.module("umbraco").controller("Umbraco.Editors.Packages.OverviewController", PackagesOverviewController); })();
JavaScript
0
@@ -3085,34 +3085,43 @@ %22icon%22: %22icon- +cloud-uplo a -d d%22,%0A @@ -3582,11 +3582,13 @@ con- -add +files %22,%0A
46f056149d8aa70e8c82913078477f422ebdab37
move dim() here
lib/physics/bounds.js
lib/physics/bounds.js
(function () {"use strict";})(); /** * Created by apizzimenti on 6/29/16. */ /** * @author Anthony Pizzimenti * * @desc Determines whether the immediate top, left, bottom, and right tiles are blocked. * * @param context {object} The context in which a sprite object exists. * * @returns {object} Each property specifies if the immediate top, left, bottom, right, or none of the previous tiles are blocked. * * @see Animal * @see Player */ function determineBounds (context) { var sprite = context.sprite, bounds = {}; sprite.tile.top.blocked ? bounds.top = true : bounds.top = false; sprite.tile.left.blocked ? bounds.left = true : bounds.left = false; sprite.tile.bottom.blocked ? bounds.bottom = true : bounds.bottom = false; sprite.tile.right.blocked ? bounds.right = true : bounds.right = false; bounds.allBounds = bounds.top || bounds.left || bounds.bottom || bounds.right; return bounds; } /** * @author Anthony Pizzimenti * * @desc Checks to see whether the location of the mouse is within physics world bounds. * * @param Mouse {Mouse} Mouse object to check. * * @returns {boolean} Is this location within the physics world bounds? */ function isInBounds (Mouse) { var x = Mouse.threeD.x, y = Mouse.threeD.y, game = Mouse.game, inX = x > game.physics.isoArcade.bounds.backX && x < game.physics.isoArcade.bounds.frontX, inY = y > game.physics.isoArcade.bounds.backY && y < game.physics.isoArcade.bounds.frontY; return inX && inY; }
JavaScript
0
@@ -1538,12 +1538,539 @@ X && inY;%0A%7D%0A +%0A%0A/**%0A * @author Anthony Pizzimenti%0A *%0A * @desc Easy calculation of world boundaries.%0A *%0A * @param tileSize %7Bnumber%7D Size of an individual tile.%0A * @param mapSize %7Bnumber%7D Desired size of the map. The map will be an array of mapSize * mapSize.%0A * @param num %7Bnumber%7D Number used to move world boundaries back num rows.%0A *%0A * @returns %7Bnumber%7D%0A *%0A * @see Map%0A */%0A%0Afunction dim (tileSize, mapSize, num) %7B%0A %0A if (num) %7B%0A return tileSize * (mapSize - (num + 1));%0A %7D else %7B%0A return tileSize - mapSize;%0A %7D%0A%7D
a7eb652436a32133b6ffa3fc2280c336af47faed
Update SPAControllers.js
App/Controllers/SPAControllers.js
App/Controllers/SPAControllers.js
// TODO: code AngularJS Module + Route Config + HTTP GET Resource + Global Service + 4 Controllers here
JavaScript
0
@@ -1,107 +1,2307 @@ -// TODO: code AngularJS Module + Route Config + HTTP GET Resource + Global Service + 4 Controllers here +var oOrchidsApp = angular.module('OrchidsApp', %5B'ngRoute'%5D);%0A%0AoOrchidsApp.config(%5B'$routeProvider', function ($routeProvider) %7B%0A%0A $routeProvider%0A%0A .when('/',%0A %7B%0A templateUrl: %22/App/Views/OrchidsList.html%22,%0A controller: %22OrchidsAllCtl%22%0A %7D)%0A .when('/add',%0A %7B%0A templateUrl: %22/App/Views/OrchidsAdd.html%22,%0A controller: %22OrchidsAddCtl%22%0A %7D)%0A .otherwise(%7B redirectTo: %22/%22 %7D);%0A%0A%7D%5D);%0A%0AoOrchidsApp.controller('OrchidsAllCtl', %5B'$scope', '$http', '$log', function ($scope, $http, $log) %7B%0A%0A $scope.angularClass = %22angular%22;%0A $scope.OrchidsList = %5B%5D;%0A $scope.pageSize = 2;%0A var iCurrentPage = -1;%0A %0A%0A $scope.fnShowOrchids = function (direction) %7B%0A%0A iCurrentPage = iCurrentPage + direction;%0A iCurrentPage = iCurrentPage %3E= 0 ? iCurrentPage : 0;%0A%0A var sURL = %22http://carmelwebapi.somee.com/WebAPI/OrchidsWebAPI/%22 +%0A %22?$skip=%22 +%0A iCurrentPage * $scope.pageSize%0A + %22&$top=%22 +%0A $scope.pageSize;%0A%0A%0A $http.get(sURL).success(function (response) %7B%0A%0A $scope.OrchidsList = response;%0A $log.info(%22OK%22);%0A%0A %7D,%0A function (err) %7B $log.error(err) %7D%0A )%0A %7D%0A%0A $scope.fnShowOrchids(1);%0A%0A%0A%7D%0A%5D);%0A%0AoOrchidsApp.controller('OrchidsAddCtl', %0A %5B'$http', '$scope', '$location', '$log', %0A function ($http, $scope, $location, $log) %7B%0A%0A $scope.Flowers = %5B%22haeckel_orchidae%22, %22Bulbophyllum%22, %22Cattleya%22, %0A %22Orchid Calypso%22, %22Paphiopedilum_concolor%22, %0A %22Peristeria%22, %22Phalaenopsis_amboinensis%22, %22Sobralia%22%5D;%0A%0A $scope.fnAdd = function () %7B%0A%0A var oFlower = %7B %22Title%22: $scope.Orchid.Title, %0A %22Text%22: $scope.Orchid.Text, %0A %22MainPicture%22: $scope.Orchid.MainPicture + '.jpg' %0A %7D;%0A %0A%0A $http(%7B%0A url: 'http://carmelwebapi.somee.com/WebAPI/OrchidsWebAPI/',%0A method: %22POST%22,%0A data: oFlower,%0A headers: %7B 'Content-Type': 'application/json' %7D%0A %7D).success(function (data) %7B %0A $scope.msg = %22New Orchid saved%22;%0A %7D).error(function (err) %7B%0A $log.log(err);%0A %7D);%0A%0A %7D%0A%7D%0A%5D); %0A
2e68fbe9d2054bb913bb01b57be3f759c7657cf4
update electron version
pack.js
pack.js
/* eslint strict: 0, no-shadow: 0, no-unused-vars: 0, no-console: 0 */ 'use strict'; const os = require('os'); const webpack = require('webpack'); const cfg = require('./webpack-config/production.js'); const packager = require('electron-packager'); const del = require('del'); const exec = require('child_process').exec; const argv = require('minimist')(process.argv.slice(2)); const pkg = require('./package.json'); const devDeps = Object.keys(pkg.devDependencies); const appName = pkg.productName; const shouldUseAsar = argv.asar || argv.a || false; const shouldBuildAll = argv.all || false; const DEFAULT_OPTS = { dir: './', name: appName, asar: shouldUseAsar, ignore: [ '/test($|/)', '/tools($|/)', '/release($|/)' ].concat(devDeps.map(name => `/node_modules/${name}($|/)`)) }; const version = argv.version || argv.v; if (version) { DEFAULT_OPTS.version = version; startPack(); } else { // use the same version as the currently-installed electron-prebuilt exec('npm list electron-prebuilt', (err, stdout) => { if (err) { DEFAULT_OPTS.version = '0.36.2'; } else { DEFAULT_OPTS.version = stdout.split('electron-prebuilt@')[1].replace(/\s/g, ''); } startPack(); }); } function startPack() { console.log('start pack...'); webpack(cfg, (err, stats) => { if (err) return console.error(err); del('release') .then(paths => { if (shouldBuildAll) { // build for all platforms const archs = ['ia32', 'x64']; const platforms = ['linux', 'win32', 'darwin']; platforms.forEach(plat => { archs.forEach(arch => { pack(plat, arch, log(plat, arch)); }); }); } else { // build for current platform only pack(os.platform(), os.arch(), log(os.platform(), os.arch())); } }) .catch(err => { console.error(err); }); }); } function pack(plat, arch, cb) { // there is no darwin ia32 electron if (plat === 'darwin' && arch === 'ia32') return; let icon; if (plat === 'darwin') { icon = 'resources/osx/icon.icns'; } else if (plat === 'win32') { icon = 'resources/windows/icon.ico' } else if (plat === 'linux') { icon = 'resources/linux/icon.png'; } const iconObj = {icon}; const opts = Object.assign({}, DEFAULT_OPTS, iconObj, { platform: plat, arch, prune: true, out: `release/${pkg.name}-${plat}-${arch}-${pkg.version}`, "app-version": pkg.version }); packager(opts, cb); } function log(plat, arch) { return (err, filepath) => { if (err) return console.error(err); console.log(`${plat}-${arch} finished!`); }; }
JavaScript
0.000001
@@ -1092,17 +1092,17 @@ = '0.36. -2 +7 ';%0A %7D
09ac62617fe77b00d1968d7d7b948e8bdf842606
fix for font-weight, which always needs a string
lib/properties/all.js
lib/properties/all.js
var toCamelCase = require('to-camel-case'); var type = function (object) { return {}.toString.call(object).match(/\[object (.*?)\]/)[1].toLowerCase(); }; module.exports = function (keys) { keys.forEach(function (key, index, arr) { var value = key.value; if (type(key.value) == 'string') { if (value == "true" || value == "false") { arr[index].value = value == "true"; } else { value = key.value.replace(/px|em/g, ''); if (_isNumeric(value)) { arr[index].value = parseFloat(value); } } } else if (type(key.value) == 'object') { for (var prop in key.value) { if (type(key.value[prop]) == 'string') { value = key.value[prop].replace(/px|em/g, ''); if (_isNumeric(value)) { arr[index].value[prop] = parseInt(value); } } } } arr[index].key = toCamelCase(arr[index].key); }); }; function _isNumeric(num) { return !isNaN(num) }
JavaScript
0.000003
@@ -150,16 +150,82 @@ ();%0A%7D;%0A%0A +var propertiesThatMustBeStrings = %5B%22font-weight%22, %22fontWeight%22%5D;%0A%0A module.e @@ -516,32 +516,94 @@ isNumeric(value) + && propertiesThatMustBeStrings.indexOf(arr%5Bindex%5D.key) === -1 ) %7B%0A%09%09%09%09%09arr%5Bind
7b33be666ac44c918ca744500052954a648b087a
Include extra OPAT referral fields Move add episode to elCID Fix inconsistent form controls for adding a patient refs #277 refs #181 refs #283
opal/static/js/opal/controllers/add_episode.js
opal/static/js/opal/controllers/add_episode.js
angular.module('opal.controllers') .controller('AddEpisodeCtrl', function($scope, $http, $cookieStore, $timeout, $modalInstance, Episode, schema, options, demographics) { $scope.currentTag = $cookieStore.get('opal.currentTag') || 'mine'; $scope.currentSubTag = $cookieStore.get('opal.currentSubTag') || 'all'; // TODO - find a way to reimplement this // $timeout(function() { // dialog.modalEl.find('input,textarea').first().focus(); // }); for (var name in options) { $scope[name + '_list'] = options[name]; }; $scope.episode_category_list = ['OPAT', 'Inpatient', 'Outpatient', 'Review']; // TODO - this is no longer the way location/admission date works. $scope.editing = { date_of_admission: moment().format('DD/MM/YYYY'), tagging: [{}], location: { hospital: 'UCLH' }, demographics: demographics }; $scope.editing.tagging[0][$scope.currentTag] = true; if($scope.currentSubTag != 'all'){ $scope.editing.tagging[$scope.currentSubTag] = true; } $scope.showSubtags = function(withsubtags){ var show = _.some(withsubtags, function(tag){ return $scope.editing.tagging[0][tag] }); return show }; $scope.save = function() { var value; // This is a bit mucky but will do for now // TODO - this is obviously broken now that location is not like this. value = $scope.editing.date_of_admission; if (value) { var doa = moment(value, 'DD/MM/YYYY').format('YYYY-MM-DD'); $scope.editing.date_of_admission = doa; } value = $scope.editing.demographics.date_of_birth; if (value) { var dob = moment(value, 'DD/MM/YYYY').format('YYYY-MM-DD'); $scope.editing.demographics.date_of_birth = dob; } $http.post('episode/', $scope.editing).success(function(episode) { episode = new Episode(episode, schema); $modalInstance.close(episode); }); }; $scope.cancel = function() { $modalInstance.close(null); }; });
JavaScript
0
@@ -1595,38 +1595,24 @@ moment(value -, 'DD/MM/YYYY' ).format('YY @@ -1868,16 +1868,188 @@ b;%0A%09%09%7D%0A%0A + // TODO: Un-hard code this as part of elcid#192%0A if($scope.editing.tagging%5B0%5D.opat)%7B%0A $scope.editing.tagging%5B0%5D.opat_referrals = true;%0A %7D%0A%0A %09%09$http.
e39c23a7f360b0ff5b86ff1543ac811d0aa8cc56
handle marked and pretranslated strings
src/js/pages/network/virtual-network-detail/VirtualNetworkDetail.js
src/js/pages/network/virtual-network-detail/VirtualNetworkDetail.js
import { Trans } from "@lingui/macro"; import mixin from "reactjs-mixin"; import { Link, routerShape } from "react-router"; /* eslint-disable no-unused-vars */ import React from "react"; /* eslint-enable no-unused-vars */ import { StoreMixin } from "mesosphere-shared-reactjs"; import Breadcrumb from "../../../components/Breadcrumb"; import BreadcrumbTextContent from "../../../components/BreadcrumbTextContent"; import Loader from "../../../components/Loader"; import Page from "../../../components/Page"; import RequestErrorMsg from "../../../components/RequestErrorMsg"; import RouterUtil from "../../../utils/RouterUtil"; import TabsMixin from "../../../mixins/TabsMixin"; import VirtualNetworksStore from "../../../stores/VirtualNetworksStore"; const NetworksDetailBreadcrumbs = ({ overlayID, overlay }) => { const crumbs = [ <Breadcrumb key={0} title="Networks"> <BreadcrumbTextContent> <Link to="/networking/networks"> <Trans render="span">Networks</Trans> </Link> </BreadcrumbTextContent> </Breadcrumb> ]; if (overlay) { const name = overlay.getName(); crumbs.push( <Breadcrumb key={1} title={name}> <BreadcrumbTextContent> <Link to={`/networking/networks/${name}`}>{name}</Link> </BreadcrumbTextContent> </Breadcrumb> ); } else { crumbs.push( <Breadcrumb key={1} title={overlayID}> <BreadcrumbTextContent>{overlayID}</BreadcrumbTextContent> </Breadcrumb> ); } return <Page.Header.Breadcrumbs iconID="networking" breadcrumbs={crumbs} />; }; const METHODS_TO_BIND = [ "onVirtualNetworksStoreError", "onVirtualNetworksStoreSuccess" ]; class VirtualNetworkDetail extends mixin(StoreMixin, TabsMixin) { constructor() { super(...arguments); this.state = { errorCount: 0, receivedVirtualNetworks: false }; // Virtual Network Detail Tabs this.tabs_tabs = { "/networking/networks/:overlayName": "Tasks", "/networking/networks/:overlayName/details": "Details" }; this.store_listeners = [ { name: "virtualNetworks", events: ["success", "error"], suppressUpdate: true } ]; METHODS_TO_BIND.forEach(method => { this[method] = this[method].bind(this); }); } componentWillMount() { super.componentWillMount(...arguments); this.updateCurrentTab(); } componentWillReceiveProps(nextProps) { super.componentWillReceiveProps(...arguments); this.updateCurrentTab(nextProps); } updateCurrentTab(nextProps) { const { routes } = nextProps || this.props; const currentTab = RouterUtil.reconstructPathFromRoutes(routes); this.setState({ currentTab }); } onVirtualNetworksStoreError() { const errorCount = this.state.errorCount + 1; this.setState({ errorCount }); } onVirtualNetworksStoreSuccess() { this.setState({ receivedVirtualNetworks: true, errorCount: 0 }); } getErrorScreen() { const breadcrumbs = ( <NetworksDetailBreadcrumbs overlayID={this.props.params.overlayName} /> ); return ( <Page> <Page.Header breadcrumbs={breadcrumbs} /> <RequestErrorMsg /> </Page> ); } getLoadingScreen() { const breadcrumbs = ( <NetworksDetailBreadcrumbs overlayID={this.props.params.overlayName} /> ); return ( <Page> <Page.Header breadcrumbs={breadcrumbs} /> <Loader /> </Page> ); } render() { const { currentTab, errorCount, receivedVirtualNetworks } = this.state; if (errorCount >= 3) { return this.getErrorScreen(); } if (!receivedVirtualNetworks) { return this.getLoadingScreen(); } const tabs = [ { label: "Tasks", callback: () => { this.setState({ currentTab: "/networking/networks/:overlayName" }); this.context.router.push( `/networking/networks/${this.props.params.overlayName}` ); }, isActive: currentTab === "/networking/networks/:overlayName" }, { label: "Details", callback: () => { this.setState({ currentTab: "/networking/networks/:overlayName/details" }); this.context.router.push( `/networking/networks/${this.props.params.overlayName}/details` ); }, isActive: currentTab === "/networking/networks/:overlayName/details" } ]; const overlay = VirtualNetworksStore.getOverlays().findItem(overlay => { return overlay.getName() === this.props.params.overlayName; }); return ( <Page> <Page.Header breadcrumbs={<NetworksDetailBreadcrumbs overlay={overlay} />} tabs={tabs} /> {React.cloneElement(this.props.children, { overlay })} </Page> ); } } VirtualNetworkDetail.contextTypes = { router: routerShape }; module.exports = VirtualNetworkDetail;
JavaScript
0
@@ -7,16 +7,19 @@ %7B Trans +, t %7D from @@ -35,16 +35,58 @@ macro%22;%0A +import %7B withI18n %7D from %22@lingui/react%22;%0A import m @@ -946,32 +946,47 @@ ontent%3E%0A +%3CTrans render=%7B %3CLink to=%22/netwo @@ -1004,72 +1004,28 @@ rks%22 -%3E%0A %3CTrans render=%22span%22%3ENetworks%3C/Trans%3E%0A %3C/Link + /%3E%7D%3ENetworks%3C/Trans %3E%0A @@ -3787,23 +3787,43 @@ label: -%22 +this.props.i18n._(t%60 Tasks -%22 +%60) ,%0A @@ -4149,25 +4149,45 @@ label: -%22 +this.props.i18n._(t%60 Details -%22 +%60) ,%0A @@ -5019,16 +5019,27 @@ ports = +withI18n()( VirtualN @@ -5050,10 +5050,11 @@ rkDetail +) ;%0A
5329cdec2fce57f9ca7473277cc7de5dfd46128c
remove done todo items
lib/recipe/factory.js
lib/recipe/factory.js
'use strict'; var PluginError = require('gulp-util').PluginError; /** * A ConfigurableRecipeFactory lookups or creates recipe function of the signature: `function (done)`. * * @param stuff * @constructor */ function ConfigurableRecipeFactory(stuff, registry) { this.stuff = stuff; this.registry = registry; } ConfigurableRecipeFactory.prototype.flow = function (taskInfo) { return lookup(this.stuff.flows, taskInfo); }; ConfigurableRecipeFactory.prototype.inline = function (taskInfo) { var task; task = taskInfo.parallel || taskInfo.series || taskInfo.task; if (typeof task === 'function') { return task; } }; ConfigurableRecipeFactory.prototype.noop = function () { return function (done) { done(); }; }; ConfigurableRecipeFactory.prototype.plugin = function (taskInfo) { var plugin, type; type = typeof taskInfo.plugin; if (type === 'string' || type === 'function') { plugin = taskInfo.plugin; return runner; } function runner() { var gulp = this.gulp; var config = this.config; var stream = this.upstream || gulp.src(config.src.globs, config.src.options); _load(); return stream.pipe(plugin(config.options)); } function _load() { if (typeof plugin === 'string') { try { plugin = require(plugin); } catch (ex) { throw new PluginError('can not load plugin'); } } } }; // TODO: should report "Starting", "Finished" profile information. ConfigurableRecipeFactory.prototype.reference = function (taskInfo, resolved) { var registry, name, result; // TODO: make sure when defined taskInfo.name, reference becomes that name task's child task. // if (taskInfo.name) {} registry = this.registry; name = taskInfo.parallel || taskInfo.series || taskInfo.task; if (typeof name === 'string') { result = resolve() || pending(); result.displayName = name; result.description = taskInfo.description; return result; } function resolve() { var task, wrapper; task = registry.refer(name, resolved); if (task) { wrapper = function (done) { return task.call(this, done); }; wrapper.config = task.config; return wrapper; } } function pending() { return function (done) { var task; task = this.gulp.task(name); if (typeof task !== 'function') { throw new PluginError(__filename, 'referring task not found: ' + name); } return task.call(this, done); }; } }; /** * if there is configurations not being consumed, then treat them as sub-tasks. */ ConfigurableRecipeFactory.prototype.stream = function (taskInfo) { return lookup(this.stuff.streams, taskInfo); }; /** * if there is a matching recipe, use it and ignore any sub-configs. */ ConfigurableRecipeFactory.prototype.task = function (taskInfo) { return lookup(this.stuff.tasks, taskInfo); }; function lookup(registry, taskInfo) { var name, recipe; name = taskInfo.recipe || taskInfo.name; recipe = registry.lookup(name); if (recipe) { taskInfo.recipe = name; } return recipe; } module.exports = ConfigurableRecipeFactory;
JavaScript
0.000001
@@ -1341,75 +1341,8 @@ %7D;%0A%0A -// TODO: should report %22Starting%22, %22Finished%22 profile information.%0A Conf @@ -1451,130 +1451,8 @@ t;%0A%0A -%09// TODO: make sure when defined taskInfo.name, reference becomes that name task's child task.%0A%09// if (taskInfo.name) %7B%7D%0A%0A %09reg
e5ce1768c3505cc0b934f9648a82c3d5aea9e514
change default preview to 30 rows
askomics/static/js/AskomicsJobsViewManager.js
askomics/static/js/AskomicsJobsViewManager.js
/*jshint esversion: 6 */ let instanceAskomicsJobsViewManager ; /* constructeur de AskomicsGraphBuilder */ class AskomicsJobsViewManager { constructor() { /* Implement a Singleton */ if ( instanceAskomicsJobsViewManager !== undefined ) { return instanceAskomicsJobsViewManager; } this.jobs = []; this.jobGenId=0 ; this.npreview=500 ; /* max data to transfert to IHM */ instanceAskomicsJobsViewManager = this; } createWaitState() { let time = $.now(); let curId = this.jobGenId++; /* Create Job in status wait */ this.jobs.push({ jobid : curId , state : 'wait', tstart : time, start : new Date(time).toLocaleString(), end : '', duration : '', nr : '' , classtr : 'bg-info', //bg-primary,bg-success,bg-warning,bg-danger,bg-info stateToReload : JSON.stringify(new AskomicsGraphBuilder().getInternalState()) }); new AskomicsJobsViewManager().listJobs(); return curId; } changeOkState(id,data) { function addZero(x, n) { while (x.toString().length < n) { x = "0" + x; } return x; } let time = $.now() ; for ( let ij in this.jobs ) { if (this.jobs[ij].jobid === id) { this.jobs[ij].tend = time ; let elp = new Date(this.jobs[ij].tend - this.jobs[ij].tstart); //let h = addZero(elp.getHours(), 2); let m = addZero(elp.getMinutes(), 2); let s = addZero(elp.getSeconds(), 2); let ms = addZero(elp.getMilliseconds(), 3); this.jobs[ij].end = new Date(time).toLocaleString(); this.jobs[ij].state = "Ok"; this.jobs[ij].nr = data.nrow; this.jobs[ij].csv = data.file; this.jobs[ij].duration = m + " m:" + s + " s:" + ms +" ms"; this.jobs[ij].classtr = "bg-success"; this.jobs[ij].datable_preview = new AskomicsResultsView(data).getPreviewResults(this.jobs[ij].stateToReload); } } new AskomicsJobsViewManager().listJobs(); } changeKoState(id,messErr) { for ( let ij in this.jobs ) { if (this.jobs[ij].jobid === id) { this.jobs[ij].end = $.now() ; this.jobs[ij].state = messErr ; this.jobs[ij].duration = this.jobs.end - this.jobs.start ; this.jobs[ij].classtr = "bg-danger"; } } new AskomicsJobsViewManager().listJobs(); } removeJob(index) { let service = new RestServiceJs('del_csv/');//location.href='del_csv/{{this.csv}}'; service.get(this.jobs[index].csv); this.jobs.splice(index, 1); new AskomicsJobsViewManager().listJobs(); } prepareQuery() { // Get JSON to ask for a SPARQL query corresponding to the graph // and launch it according to given parameters. // // :lim: LIMIT values for preview console.log('+++ prepareQuery +++'); var tab = new AskomicsGraphBuilder().buildConstraintsGraph(); return { 'variates' : tab[0], 'constraintesRelations': tab[1], 'constraintesFilters' : tab[2], 'removeGraph' : new AskomicsUserAbstraction().listUnactivedGraph(), 'limit' : this.npreview // number of data preview }; } createJob() { //create state view let curId = new AskomicsJobsViewManager().createWaitState(); let service = new RestServiceJs("sparqlquery"); let jdata = this.prepareQuery(false, false); service.post(jdata,function(data) { hideModal(); if ('error' in data) { //alert(data.error); new AskomicsJobsViewManager().changeKoState(curId,data.error); return; } new AskomicsJobsViewManager().changeOkState(curId,data); }); /* position on job list view */ $("#jobsview").trigger( "click" ); } listJobs() { let source = $('#template-admin-jobs').html(); let template = Handlebars.compile(source); let context = {jobs: this.jobs }; let html = template(context); $("#content_jobsview").empty(); $("#content_jobsview").append(html); for ( let ij in this.jobs ) { if (this.jobs[ij].datable_preview !== undefined ) { let r = $("#results_table_"+ij); r.append( $("<h3></h3>").addClass("header-div") .css("text-align","center") .html("Preview ("+Math.min(this.npreview,this.jobs[ij].nr)+" nrows)") ); r.append(this.jobs[ij].datable_preview); //$("#results").empty(); //$("#results").append(this.jobs[ij].datable_preview); } } } }
JavaScript
0
@@ -380,10 +380,9 @@ iew= -50 +3 0 ;
c9d1504adf2c17157f0b68eed33db004b9f1fccb
update initial data
lib/reducers/emoji.js
lib/reducers/emoji.js
import { ADD_HISTORY } from '../constants/ActionTypes'; const initialState = [ { name: '+1', pattern: ':+1:', image: 'assets/images/emojis/plus1.png', category: 'people', alternatives: [] } ]; const historyLimit = 20; export default function (state = initialState, action = {}) { switch (action.type) { case ADD_HISTORY: const rest = state.filter((needle) => { return needle.name !== action.emoji.name; }); return [ action.emoji, ...rest ].slice(0, historyLimit); default: return state; } }
JavaScript
0.000065
@@ -88,18 +88,24 @@ name: ' -+1 +thumbsup ',%0A p @@ -118,10 +118,16 @@ : ': -+1 +thumbsup :',%0A @@ -163,13 +163,16 @@ jis/ -plus1 +thumbsup .png
9fe0b895acba4be14e510cf074e45752cc54eba6
Revert "fix header"
webapp/components/BuildList.js
webapp/components/BuildList.js
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {Flex, Box} from 'grid-styled'; import BuildListItem from '../components/BuildListItem'; import Panel from '../components/Panel'; import ResultGridHeader from '../components/ResultGridHeader'; export default class BuildList extends Component { static propTypes = { buildList: PropTypes.arrayOf(PropTypes.object).isRequired }; render() { return ( <Panel> <ResultGridHeader> <Flex> <Box flex="1" width={6 / 12} pr={15}> Build </Box> <Box width={1 / 12} style={{textAlign: 'center'}}> Duration </Box> <Box width={1 / 12} style={{textAlign: 'center'}}> Coverage </Box> <Box width={2 / 12} style={{textAlign: 'right'}}> When </Box> </Flex> </ResultGridHeader> <div> {this.props.buildList.map(build => { return ( <BuildListItem key={build.id} build={build} params={this.props.params} /> ); })} </div> </Panel> ); } }
JavaScript
0
@@ -788,32 +788,77 @@ %3C/Box%3E%0A + %3CBox width=%7B2 / 12%7D%3EAuthor%3C/Box%3E%0A %3CBox
cee2165998200d8c9d0f7265b92aa9f9060923d4
Use Heroku for Audio assets
public/js/awpy.js
public/js/awpy.js
var AWPY = { config: { codec: (function() { var audio = new Audio(), result; var extensions = ['mp3', 'ogg', 'aac', 'wav']; [ 'audio/mpeg; codecs="mp3"', 'audio/ogg; codecs="vorbis"', 'audio/mpeg; codecs="mp3"', 'audio/wav; codecs="1"' ].forEach(function(codec, i, list) { result = extensions[i]; if (/probably|maybe/.test(audio.canPlayType(codec))) { list.length = i; } }); return result; }()), browserscope: { key: 'agt1YS1wcm9maWxlcnINCxIEVGVzdBiH_qUKDA' } } }; AWPY.tests = (function() { var list = []; return { init: function(tests) { list = tests; }, run: function(testName, callback) { var single = !!testName; var globalCleanup = function(test) { if (!test.audio) { return; } test.audio.pause(); test.audio.removeAttribute('src'); test.audio.load(); delete test.audio; }; var tests = list.filter(function(test) { return (single ? test.name === testName : true) && !test.finished; }); (function run(tests, i) { var test = tests[i]; var failTimeout = setTimeout(function() { test.finished = true; test.result = false; globalCleanup(test); callback.call(null, test); if (tests[i + 1]) { run(tests, i + 1); } }, 15000); test.assert(function(result) { if (failTimeout) { clearTimeout(failTimeout); } if (!test.finished) { test.finished = true; globalCleanup(test); test.result = result; callback.call(null, test); if (tests[i + 1]) { run(tests, i + 1); } } }); }(tests, 0)); }, get: function(testName) { return list.filter(function(item) { return testName ? item.name === testName : true; }); }, save: function() { var data = {}, newScript, firstScript; this.finished().forEach(function(test) { data[test.name] = test.result ? 1 : 0; }); window._bTestResults = data; $.getJSON( 'http://www.browserscope.org/user/beacon/' + AWPY.config.browserscope.key + '?callback=?' ); }, finished: function() { return list.filter(function(test) { return test.finished; }); } }; }()); AWPY.sound = (function() { var sounds = { mini: { duration: 2.377 }, short: { duration: 227.325 }, long: { duration: 4046.210 } }; Object.keys(sounds).forEach(function(type) { sounds[type].stream_url = function(cache) { return 'http://soundcloud.com/yvg/' + type + '-' + AWPY.config.codec + '/download' + (cache ? '' : '?' + (Math.random() * 1e9 | 0)); }; }); return sounds; }()); // Debugging function AWPY.logEvents = function(audio){ var events = 'loadstart progress suspend abort error emptied stalled loadedmetadata ' + 'loadeddata canplay canplaythrough playing waiting seeking seeked ended durationchange ' + 'timeupdate ratechange volumechange'; events = events.split(' '); events.forEach(function(ev) { audio.addEventListener(ev, function() { console.log(ev + ':' + Date.now()); }, false); }); }; AWPY.UI = { toggleInfo: function() { var info = $('.info-description'); var setCookie = function() { if (!(/awpy=bubble_expiration/).test(document.cookie)) { var date = new Date(); date.setTime( date.getTime() + ( 7*24*60*60*1000 ) ); // expires in 7 days date.toGMTString(); document.cookie = 'awpy=bubble_expiration; expires='+ date +'; path=/'; } }; $('.info-small').live('click', function(event) { event.preventDefault(); event.stopPropagation(); info.toggleClass('hide'); setCookie(); }); $('body').live('click', function(){ info.addClass('hide'); setCookie(); }); if (!(/awpy=bubble_expiration/).test(document.cookie)) { info.removeClass('hide'); } } }
JavaScript
0
@@ -2804,26 +2804,44 @@ p:// -soundcloud.com/yvg +areweplayingyet.herokuapp.com/sounds /' + @@ -2849,17 +2849,17 @@ type + ' -- +. ' + AWPY @@ -2877,22 +2877,8 @@ ec + - '/download' + (ca
e604be2b98f93037884d3b8905971a834e68ea5e
Fix Intercom email can't be blank error (#11)
lib/resources/user.js
lib/resources/user.js
var BaseResource = require('./base'); // var debug = require('debug')('mongodb-js-metrics:resources:app'); module.exports = BaseResource.extend({ id: 'User', props: { userId: { type: 'string', required: true }, name: 'string', email: 'string', twitter: 'string' }, login: function(callback) { var options = { userId: this.userId }; this._send_event(options, callback); } });
JavaScript
0.00001
@@ -261,24 +261,83 @@ email: -'string' +%7Btype: 'any', default: undefined, required: false, allowNull: true%7D ,%0A tw
8d5f2b9279828523c0678e318b2a17e8131689b1
Make ResponseParser easier readable
lib/responseParser.js
lib/responseParser.js
'use strict'; const debug = require('debug')('ResponseParser'); const RemoUserHelper = require('../lib/remoUserHelper'); const remoUserHelper = new RemoUserHelper(); module.exports = class ResponseParser { /** * Creates an object from the response to make sure we assign to real properties * @param {Array} responses responses from the form * @return {Array} descriptive responses as objects */ static create(responses) { debug('Creating responses..'); const groupedByEvents = responses.map((response) => { const eventResponse = ResponseParser.getGeneralEventInfo(response); eventResponse.nps = response[3]; return eventResponse; }) .reduce((acc, response) => { const npsScoreCopy = JSON.parse(JSON.stringify(response.nps)); acc[response.key] = acc[response.key] || response; if (!acc[response.key].scores) { delete acc[response.key].nps; } acc[response.key].scores = acc[response.key].scores || []; acc[response.key].scores.push(npsScoreCopy); return acc; }, {}); return Object.keys(groupedByEvents).map((key) => { return groupedByEvents[key]; }); } static getGeneralEventInfo(response) { return { key: response[1] + '_' + response[2], eventName: response[0], eventDate: response[2], organizerName: response[1], organizerUrl: remoUserHelper.getRepUrlByFullName(response[1]) }; } }
JavaScript
0.000005
@@ -688,46 +688,404 @@ %7D) +.reduce(groupByEvent, %7B%7D);%0A %0A -. re -duce((acc, response) =%3E %7B%0A +turn convertObjectToArray(groupedByEvents);%0A %7D%0A%0A static getGeneralEventInfo(response) %7B%0A return %7B%0A key: response%5B1%5D + '_' + response%5B2%5D,%0A eventName: response%5B0%5D,%0A eventDate: response%5B2%5D,%0A organizerName: response%5B1%5D,%0A organizerUrl: remoUserHelper.getRepUrlByFullName(response%5B1%5D)%0A %7D;%0A %7D%0A%7D%0A%0Afunction groupByEvent(acc, response) %7B%0A co @@ -1146,20 +1146,16 @@ nps));%0A%0A - acc%5Bre @@ -1200,20 +1200,16 @@ ponse;%0A%0A - if (!a @@ -1239,20 +1239,16 @@ ) %7B%0A - - delete a @@ -1275,19 +1275,11 @@ ;%0A - %7D%0A%0A +%7D%0A%0A ac @@ -1335,20 +1335,16 @@ %7C%7C %5B%5D;%0A - acc%5Bre @@ -1382,20 +1382,16 @@ eCopy);%0A - return @@ -1400,23 +1400,51 @@ cc;%0A - %7D, %7B%7D);%0A%0A +%7D%0A%0Afunction convertObjectToArray(object) %7B%0A re @@ -1460,31 +1460,22 @@ ct.keys( -groupedByEvents +object ).map((k @@ -1486,316 +1486,37 @@ =%3E %7B - return groupedByEvents%5Bkey%5D; %7D);%0A %7D%0A%0A static getGeneralEventInfo(response) %7B%0A return %7B%0A key: response%5B1%5D + '_' + response%5B2%5D,%0A eventName: response%5B0%5D,%0A eventDate: response%5B2%5D,%0A organizerName: response%5B1%5D,%0A organizerUrl: remoUserHelper.getRepUrlByFullName(response%5B1%5D)%0A %7D;%0A %7D +%0A return object%5Bkey%5D;%0A %7D); %0A%7D%0A
85249b6de7d1b6d17f3534249fb0eee114cd6595
Handle Errors
assets/js/script.js
assets/js/script.js
$(document).ready(() => { $('#send').on('click', (e) => { let method = document.getElementById('method').value; let query = $('#url').val(); if(query == '' || query == ' '){ console.log('empty'); document.getElementById('code').innerHTML = ''; } else{ if(method == 'get'){ getRequest(query); } else if(method == 'post'){ postRequest(query); } else if(method == 'put'){ putRequest(query); } else { deleteRequest(query); } e.preventDefault(); } }); }); function output(response){ let data = JSON.stringify(response.data, null, "\t"); let headers = JSON.stringify(response.headers, undefined, 2); document.getElementById('code').innerText = data; document.getElementById('headers').innerText = headers; document.getElementById('status').innerText = response.status; } function showLoading(){ document.getElementById('loading').classList.remove('hiddendiv'); } function hideLoading(){ document.getElementById('loading').classList.add('hiddendiv'); } function getRequest(query){ showLoading(); // Make a request for a user with a given ID axios.get(query) .then(function (response) { hideLoading(); console.log(response); output(response); }) .catch(function (error) { console.log(error); hideLoading(); }); } function postRequest(query){ showLoading(); axios.post(query) .then(function (response) { hideLoading(); console.log(response); output(response); }) .catch(function (error) { console.log(error); hideLoading(); }); } function putRequest(query){ showLoading(); axios.put(query) .then(function (response) { hideLoading(); console.log(response); output(response); }) .catch(function (error) { console.log(error); hideLoading(); }); } function deleteRequest(query){ showLoading(); axios.delete(query) .then(function(response) { hideLoading(); output(response); console.log(response); }) .catch(function(error){ console.log(error); hideLoading(); }); }
JavaScript
0
@@ -733,16 +733,472 @@ %22%5Ct%22);%0A + let headers = JSON.stringify(response.headers, undefined, 2);%0A document.getElementById('code').innerText = data;%0A document.getElementById('headers').innerText = headers;%0A document.getElementById('status').innerText = response.status;%0A%7D%0Afunction outputError(error)%7B%0A // document.getElementById('code').innerText = 'Error '+ error.message;%0A // document.getElementById('status').innerText = error.response.status;%0A if (error.response) %7B%0A @@ -1218,32 +1218,38 @@ JSON.stringify( +error. response.headers @@ -1313,28 +1313,47 @@ innerText = -data +'Error '+ error.message ;%0A do @@ -1452,32 +1452,38 @@ s').innerText = +error. response.status; @@ -1475,32 +1475,577 @@ esponse.status;%0A + %7D else if (error.request) %7B%0A // The request was made but no response was received%0A let errorReq = JSON.stringify(error.request, undefined, 2);%0A document.getElementById('code').innerText = errorReq + ' 500 (Internal Server Error)';%0A document.getElementById('status').innerText = '';%0A %7D else %7B%0A // Something happened in setting up the request that triggered an Error%0A console.log('Error', error.message);%0A %7D%0A Materialize.toast('There was an error :(', 4000, 'red')%0A console.log(error.config);%0A %7D%0Afunction showL @@ -2484,32 +2484,35 @@ error) %7B%0A + // console.log(err @@ -2508,32 +2508,107 @@ ole.log(error);%0A + // console.log(error.response.status);%0A outputError(error);%0A hideLoad @@ -2617,33 +2617,32 @@ g();%0A %7D);%0A%7D%0A%0A -%0A function postReq @@ -2848,35 +2848,35 @@ ) %7B%0A -console.log +outputError (error);%0A @@ -2898,33 +2898,32 @@ g();%0A %7D);%0A%7D%0A%0A -%0A function putRequ @@ -3127,35 +3127,35 @@ ) %7B%0A -console.log +outputError (error);%0A @@ -3185,17 +3185,16 @@ %7D);%0A%7D%0A%0A -%0A function @@ -3409,35 +3409,35 @@ r)%7B%0A -console.log +outputError (error);%0A
dd59cb403943e554b0a4459acfaf2af77d25b64c
refactor the function that matches page with color
assets/js/script.js
assets/js/script.js
function clearFilters(){ $(".closing-icon").remove(); $(".active_tag").removeClass('active_tag'); $('.card').show(); } function toggleTags(button, tag){ if(button.attr('class').indexOf('active_tag') > -1){ button.removeClass("active_tag"); button.html(tag); } else { button.html(tag + '<i class="material-icons left closing-icon">close</i>'); button.addClass("active_tag"); } } function addActiveTags(buttons){ var active_tags = []; for(var j=0; j < buttons.length; j++){ current_button = $(buttons[j]); if(current_button.attr('class').indexOf('active_tag') > -1){ active_tags.push(current_button.attr('val')); } } return active_tags; } function showProjects(projects, active_tags){ projects.each(function(i){ var project = $(projects[i]); project.hide(); $.each(active_tags, function(k){ var active_tag = active_tags[k], projectContainsTag = project.attr('tags').indexOf(active_tag) > -1; if(projectContainsTag){ project.show(); } }) }) var activeTagsAreEmpty = active_tags.length === 0; if(activeTagsAreEmpty){ projects.show(); } } function hideCloseIcons(element){ element.children().remove('i'); } $(document).ready(function(){ $(".button-collapse").sideNav({ menuWidth: 200, edge: 'left', closeOnClick: true, draggable: true }); var colors = { 'about': 'rgb(142,85,114)', 'projects': '#F46036', 'algorithms': '#2E294E' }, address = window.location.href.split('/'), pagename = address[address.length - 1]; $('body').css('background-color', colors[pagename]); $('.card-action a').css('color', colors[pagename]); $('nav a').attr('style', 'color: ' + colors[pagename] + ''); $("a:contains('" + pagename + "')").parent().css('background-color', colors[pagename]); $("a:contains('" + pagename + "')").css('color', "white"); $('.tag').click(function(event){ event.preventDefault(); hideCloseIcons($(this)); var button = $(this), tag = $(this).attr('val'), projects = $('.card'), buttons = $('.btn'), active_tags = [], needToClearFilters = tag === "clear-filters"; if(needToClearFilters){ clearFilters(); } else{ toggleTags(button, tag); active_tags = addActiveTags(buttons); showProjects(projects, active_tags); } }) $("#filter").click(function(e){ e.preventDefault(); var text = $('#filter').text(); var options = { "filter": "hide filters", "hide filters": "filter" } // debugger $("#filter").text(options[text]); $("#tags").toggle(200); }) });
JavaScript
0.99975
@@ -1506,23 +1506,25 @@ ,%0A -address +urlString = windo @@ -1542,65 +1542,153 @@ href -.split('/'),%0A pagename = address%5Baddress.length - 1%5D +,%0A color = %22%22;%0A%0A $.each(colors, function(key,val)%7B%0A if(urlString.indexOf(key) %3E -1)%7B%0A color = val;%0A pagename = key;%0A %7D%0A %7D) ;%0A%0A @@ -1723,35 +1723,24 @@ olor', color -s%5Bpagename%5D );%0A $('.car @@ -1766,35 +1766,24 @@ olor', color -s%5Bpagename%5D );%0A $('nav @@ -1817,27 +1817,16 @@ + color -s%5Bpagename%5D + '');%0A @@ -1905,19 +1905,8 @@ olor -s%5Bpagename%5D );%0A @@ -2485,24 +2485,28 @@ nction(e +vent )%7B%0A e .prevent @@ -2497,16 +2497,20 @@ )%7B%0A e +vent .prevent @@ -2554,25 +2554,25 @@ ).text() -; +, %0A -var + options @@ -2572,24 +2572,28 @@ options = %7B%0A + %22filte @@ -2618,16 +2618,20 @@ ,%0A + %22hide fi @@ -2655,25 +2655,15 @@ -%7D%0A -// debugger +%7D;%0A %0A @@ -2719,17 +2719,17 @@ .toggle( -2 +4 00);%0A %7D
afd753b2174ff7ebd2dee08a648c534b0b1a2262
Add specific event handlers to player
static/js/app.js
static/js/app.js
var player = radiodan.player.create(1); var playlists = document.querySelector('.playlists'); var vol = document.querySelector('.volume'); vol.addEventListener('change', function (evt) { console.log('Volume', vol.value); player.volume({ value: vol.value }); }); player.on('message', function (content) { if (content.volume) { console.log('changing volume to ', content.volume); vol.value = content.volume; } console.log(content); if (content.forEach) { playlists.innerHTML = content.map(function (item) { return '<li>' + (item.file || '') + '</li>'; }); } }); var playButton = document.querySelector('.play'); playButton.addEventListener('click', function () { player.play(); }); var pauseButton = document.querySelector('.pause'); pauseButton.addEventListener('click', function () { player.pause({ value: true }); }); var playlistClearButton = document.querySelector('.playlist-clear'); playlistClearButton.addEventListener('click', function () { player.clear(); }); var playlistInput = document.querySelector('.playlist input'); var playlistButton = document.querySelector('.playlist button'); playlistButton.addEventListener('click', function () { if (playlistInput.value == '') { return; } player.add({ playlist: [ playlistInput.value ]}).then( function () { console.log('Done'); playlistInput.value = ''; }, function () { console.error('Couldn\'t add to playlist'); } ); console.log('Loading...'); }); var streams = document.querySelector('.streams'); xhr = createCORSRequest('GET', 'http://bbcservices.herokuapp.com/services.json'); xhr.withCredentials = true; xhr.onload = function() { var json = JSON.parse(xhr.responseText); streams.innerHTML = json.services.map(function (service) { if (service.streams.length > 0) { return '<li><a href="' + service.streams[0].url + '">' + service.title + '</a></li>'; } else { return ''; } }).join(''); }; xhr.send(); function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // Check if the XMLHttpRequest object has a "withCredentials" property. // "withCredentials" only exists on XMLHTTPRequest2 objects. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // Otherwise, check if XDomainRequest. // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Otherwise, CORS is not supported by the browser. xhr = null; } return xhr; }
JavaScript
0.000001
@@ -277,14 +277,13 @@ on(' -messag +volum e', @@ -290,17 +290,16 @@ function - (content @@ -306,34 +306,8 @@ ) %7B%0A - if (content.volume) %7B%0A co @@ -356,18 +356,16 @@ olume);%0A - vol.va @@ -390,65 +390,94 @@ me;%0A - %7D%0A console.log(content);%0A if (content.forEach) %7B%0A +%7D);%0A%0Aplayer.on('playlist', function (content) %7B%0A console.log('changing playlist');%0A - play @@ -528,18 +528,16 @@ ) %7B%0A - return ' @@ -579,17 +579,99 @@ ;%0A - %7D);%0A %7D +%7D);%0A%7D);%0A%0Aplayer.on('player', function (content) %7B%0A console.log('player changed', content); %0A%7D);
517f5f2c98d7d0fc572f6012d9dd3b22abe4aeff
enable bgm
public/js/init.js
public/js/init.js
window.onload = enchantInit; const normalFont = 'Kazesawa, Arial, Helvetica, sans-serif'; const bgImg = '/img/title.png'; const gameImg = '/img/game.png'; const charImg = '/img/chara.png'; const resultImg = '/img/result.png'; const blackImg = '/img/blackbox.png'; const startImg = '/img/start.png'; const readyImg = '/img/ready.png'; const finishImg = '/img/finish.png'; const bombImg = '/img/bomb.png'; const enterButtonImg = '/img/enter_button.png'; const startButtonImg = '/img/start_button.png'; const backButtonImg = '/img/back_button.png'; const nameBoardImg = '/img/name_board.png'; const gameBgm = '/bgm/game1.mp3'; const game2Bgm = '/bgm/game2.mp3'; const game3Bgm = '/bgm/game3.mp3'; const topPageBgm = '/bgm/title.mp3'; const powerup1Bgm = '/bgm/powerup1.mp3'; const resultPageBgm = '/bgm/result.mp3'; const foodSe = '/se/food.mp3'; const sheepDeathSe = '/se/sheep_death.mp3'; const readySe = '/se/ready.mp3'; const startSe = '/se/start.mp3'; const waitingSe = '/se/choise.mp3'; const footStepsSe = '/se/foot_steps.mp3'; const decisionSe = '/se/decision.mp3'; const clearSe = '/se/clear.mp3'; const endSe = '/se/end.mp3'; const powerUpSe = '/se/power_up.mp3'; const wolfDeathSe = '/se/wolf_death.mp3'; const bombSe = '/se/bomb.mp3'; const respawnSe = '/se/respawn.mp3'; // config const pixel = 64; const GAME_OFFSET_X = 480; const GAME_OFFSET_Y = 40; const SHEEP_SPEED = 8; const WOLF_SPEED = 4; const SLOW_SPEED = 2; const MOVE_FRAME_COUNT_LIMIT = 3; // global const DIRS = ['up', 'right', 'down', 'left']; const DX = [0, 1, 0, -1]; const DY = [-1, 0, 1, 0]; let bgmController; let topPage; let playPage; let resultPage; let socket; let myId; // must sync with lib/modules/config.js // for result page const scoreBasePoints = { scoreTimePoint: 1, scoreNormalItemPoint: 50, scorePowerItemPoint: 500, scoreKillPoint: 200 }; enchant.ui.assets = [ 'enchant_assets/pad.png', 'enchant_assets/apad.png', 'enchant_assets/icon0.png', 'enchant_assets/font0.png' ]; enchant.widget.assets = [ 'enchant_assets/listItemBg.png', 'enchant_assets/iconMenuBg.png', 'enchant_assets/button.png', 'enchant_assets/buttonPushed.png', 'enchant_assets/dialog.png', 'enchant_assets/navigationBar.png' ]; enchant.widget._env.font = `12px ${normalFont}`; enchant.widget._env.buttonFont = `12px ${normalFont}`; enchant.widget._env.navigationBarFont = `12px ${normalFont}`; enchant.widget._env.textareaFont = `12px ${normalFont}`; function enchantInit(){ socket = new Socket(); enchant(); var game = new Core(1920, 1080); game.fps = 30; game.preload( bgImg, gameImg, mapImg, charImg, itemImg, resultImg, blackImg, startImg, readyImg, finishImg, bombImg, enterButtonImg, startButtonImg, backButtonImg, nameBoardImg, //img // gameBgm, game2Bgm, game3Bgm, topPageBgm, powerup1Bgm, resultPageBgm,//bgm foodSe, sheepDeathSe, readySe, startSe, waitingSe, footStepsSe, decisionSe, clearSe, endSe, powerUpSe, wolfDeathSe, bombSe, respawnSe//se ); bgmController = new BGMController(game); game.onload = function () { topPage = new TopPage(game); playPage = new PlayPage(game); resultPage = new ResultPage(game); topPage.init(); }; game.start(); // fix margin of main content const mainEle = document.getElementById('enchant-stage'); mainEle.style.left = 0; mainEle.style.top = 0; }
JavaScript
0.000001
@@ -2739,19 +2739,16 @@ /img%0A%09%09%09 -// gameBgm,
d1f8882abe4d7286ae4b81dbbe8001769d228f50
Include reflections
week-7/manipulating_objects.js
week-7/manipulating_objects.js
// Manipulating JavaScript Objects // I worked on this challenge by myself. // There is a section below where you will write your code. // DO NOT ALTER THIS OBJECT BY ADDING ANYTHING WITHIN THE CURLY BRACES! var terah = { name: "Terah", age: 32, height: 66, weight: 130, hairColor: "brown", eyeColor: "brown" } // __________________________________________ // Write your code below. /* Define a variable adam and use object literal notation to assign this variable the value of an object with no properties. Give adam a name property with the value "Adam". Add a spouse property to terah and assign it the value of adam. Change the value of the terah weight property to 125. Remove the eyeColor property from terah. Add a spouse property to adam and assign it the value of terah. Add a children property to terah and use object literal notation to assign this variable to an empty object. Add a carson property to the value of the terah children property. carson should be an object with a property name with the value "Carson". Add a carter property to the value of the terah children property. carter should be an object with a property name with the value "Carter". Add a colton property to the value of the terah children property. colton should be an object with a property name with the value "Colton". Add a children property to adam and assign it the value of terah.children. */ var adam = {} //var adam = new Object() adam.name = "Adam"; terah.spouse = adam; terah.weight = 125; delete terah.eyeColor; //delete terah[eyeColor]; adam.spouse = terah terah.children = {} terah.children.carson = {name: "Carson"} terah.children.carter = {name: "Carter"} terah.children.colton = {name: "Colton"} adam.children = terah.children // __________________________________________ // Reflection: Use the reflection guidelines /* What tests did you have trouble passing? What did you do to make it pass? Why did that work? How difficult was it to add and delete properties outside of the object itself? What did you learn about manipulating objects in this challenge? */ // __________________________________________ // Driver Code: Do not alter code below this line. function assert(test, message, test_number) { if (!test) { console.log(test_number + "false"); throw "ERROR: " + message; } console.log(test_number + "true"); return true; } assert( (adam instanceof Object), "The value of adam should be an Object.", "1. " ) assert( (adam.name === "Adam"), "The value of the adam name property should be 'Adam'.", "2. " ) assert( terah.spouse === adam, "terah should have a spouse property with the value of the object adam.", "3. " ) assert( terah.weight === 125, "The terah weight property should be 125.", "4. " ) assert( terah.eyeColor === undefined || null, "The terah eyeColor property should be deleted.", "5. " ) assert( terah.spouse.spouse === terah, "Terah's spouse's spouse property should refer back to the terah object.", "6. " ) assert( (terah.children instanceof Object), "The value of the terah children property should be defined as an Object.", "7. " ) assert( (terah.children.carson instanceof Object), "carson should be defined as an object and assigned as a child of Terah", "8. " ) assert( terah.children.carson.name === "Carson", "Terah's children should include an object called carson which has a name property equal to 'Carson'.", "9. " ) assert( (terah.children.carter instanceof Object), "carter should be defined as an object and assigned as a child of Terah", "10. " ) assert( terah.children.carter.name === "Carter", "Terah's children should include an object called carter which has a name property equal to 'Carter'.", "11. " ) assert( (terah.children.colton instanceof Object), "colton should be defined as an object and assigned as a child of Terah", "12. " ) assert( terah.children.colton.name === "Colton", "Terah's children should include an object called colton which has a name property equal to 'Colton'.", "13. " ) assert( adam.children === terah.children, "The value of the adam children property should be equal to the value of the terah children property", "14. " ) console.log("\nHere is your final terah object:") console.log(terah)
JavaScript
0
@@ -1930,158 +1930,544 @@ rk?%0A -%0A How difficult was it to add and delete properties outside of the object itself?%0A%0A What did you learn about manipulating objects in this challenge? + I didn't have any tests failed. I have followed each requirement and manipulate the object accordingly.%0A%0A How difficult was it to add and delete properties outside of the object itself?%0A I don't think it was difficult to pass the tests as long as read the requirement carefully and implement it.%0A%0A What did you learn about manipulating objects in this challenge?%0A I learned that you can add properties to the objects such as weight, spouse, children etc. Using the dot notation, you can add a property to an object instance. %0A%0A*/
8cc1aa8fd4ae21f1a6cdc6d5c1985f4be15641ba
Fix array-to-string coercion bug
lib/rules/no-typos.js
lib/rules/no-typos.js
/** * @fileoverview Prevent common casing typos */ 'use strict'; const Components = require('../util/Components'); const docsUrl = require('../util/docsUrl'); // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ const STATIC_CLASS_PROPERTIES = ['propTypes', 'contextTypes', 'childContextTypes', 'defaultProps']; const LIFECYCLE_METHODS = [ 'componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'componentDidUpdate', 'componentWillUnmount', 'render' ]; const PROP_TYPES = Object.keys(require('prop-types')); module.exports = { meta: { docs: { description: 'Prevent common typos', category: 'Stylistic Issues', recommended: false, url: docsUrl('no-typos') }, schema: [] }, create: Components.detect((context, components, utils) => { let propTypesPackageName = null; let reactPackageName = null; function checkValidPropTypeQualfier(node) { if (node.name !== 'isRequired') { context.report({ node: node, message: `Typo in prop type chain qualifier: ${node.name}` }); } } function checkValidPropType(node) { if (node.name && !PROP_TYPES.some(propTypeName => propTypeName === node.name)) { context.report({ node: node, message: `Typo in declared prop type: ${node.name}` }); } } function isPropTypesPackage(node) { // Note: we really do want == with the package names here, // since we need value equality, not identity - and // these values are always string or null. /* eslint-disable eqeqeq */ return ( node.type === 'Identifier' && node.name == propTypesPackageName ) || ( node.type === 'MemberExpression' && node.property.name === 'PropTypes' && node.object.name == reactPackageName ); /* eslint-enable eqeqeq */ } /* eslint-disable no-use-before-define */ function checkValidCallExpression(node) { const callee = node.callee; if (callee.type === 'MemberExpression' && callee.property.name === 'shape') { checkValidPropObject(node.arguments[0]); } else if (callee.type === 'MemberExpression' && callee.property.name === 'oneOfType') { const args = node.arguments[0]; if (args && args.type === 'ArrayExpression') { args.elements.forEach(el => checkValidProp(el)); } } } function checkValidProp(node) { if ((!propTypesPackageName && !reactPackageName) || !node) { return; } if (node.type === 'MemberExpression') { if ( node.object.type === 'MemberExpression' && isPropTypesPackage(node.object.object) ) { // PropTypes.myProp.isRequired checkValidPropType(node.object.property); checkValidPropTypeQualfier(node.property); } else if ( isPropTypesPackage(node.object) && node.property.name !== 'isRequired' ) { // PropTypes.myProp checkValidPropType(node.property); } else if (node.object.type === 'CallExpression') { checkValidPropTypeQualfier(node.property); checkValidCallExpression(node.object); } } else if (node.type === 'CallExpression') { checkValidCallExpression(node); } } /* eslint-enable no-use-before-define */ function checkValidPropObject (node) { if (node && node.type === 'ObjectExpression') { node.properties.forEach(prop => checkValidProp(prop.value)); } } function reportErrorIfClassPropertyCasingTypo(node, propertyName) { if (propertyName === 'propTypes' || propertyName === 'contextTypes' || propertyName === 'childContextTypes') { const propsNode = node && node.parent && node.parent.type === 'AssignmentExpression' && node.parent.right; checkValidPropObject(propsNode); } STATIC_CLASS_PROPERTIES.forEach(CLASS_PROP => { if (propertyName && CLASS_PROP.toLowerCase() === propertyName.toLowerCase() && CLASS_PROP !== propertyName) { context.report({ node: node, message: 'Typo in static class property declaration' }); } }); } function reportErrorIfLifecycleMethodCasingTypo(node) { LIFECYCLE_METHODS.forEach(method => { if (method.toLowerCase() === node.key.name.toLowerCase() && method !== node.key.name) { context.report({ node: node, message: 'Typo in component lifecycle method declaration' }); } }); } return { ImportDeclaration: function(node) { if (node.source && node.source.value === 'prop-types') { // import PropType from "prop-types" propTypesPackageName = node.specifiers[0].local.name; } else if (node.source && node.source.value === 'react') { // import { PropTypes } from "react" reactPackageName = node.specifiers[0].local.name; propTypesPackageName = node.specifiers.length >= 1 ? ( node.specifiers .filter(specifier => specifier.imported && specifier.imported.name === 'PropTypes') .map(specifier => specifier.local.name) ) : null; } }, ClassProperty: function(node) { if (!node.static || !utils.isES6Component(node.parent.parent)) { return; } const tokens = context.getFirstTokens(node, 2); const propertyName = tokens[1].value; reportErrorIfClassPropertyCasingTypo(node, propertyName); }, MemberExpression: function(node) { const propertyName = node.property.name; if ( !propertyName || STATIC_CLASS_PROPERTIES.map(prop => prop.toLocaleLowerCase()).indexOf(propertyName.toLowerCase()) === -1 ) { return; } const relatedComponent = utils.getRelatedComponent(node); if ( relatedComponent && (utils.isES6Component(relatedComponent.node) || utils.isReturningJSX(relatedComponent.node)) ) { reportErrorIfClassPropertyCasingTypo(node, propertyName); } }, MethodDefinition: function (node) { if (!utils.isES6Component(node.parent.parent)) { return; } reportErrorIfLifecycleMethodCasingTypo(node); } }; }) };
JavaScript
0.000455
@@ -1595,214 +1595,8 @@ ) %7B%0A - // Note: we really do want == with the package names here,%0A // since we need value equality, not identity - and%0A // these values are always string or null.%0A /* eslint-disable eqeqeq */%0A @@ -1664,16 +1664,17 @@ .name == += propTyp @@ -1817,16 +1817,17 @@ .name == += reactPa @@ -1849,41 +1849,8 @@ );%0A - /* eslint-enable eqeqeq */%0A @@ -5202,16 +5202,19 @@ ) +%5B0%5D : null;
50aff0201ecdf0b00df767878e3e030cecc9fdde
Change autofocus behaivor
static/js/app.js
static/js/app.js
var app = angular.module('linksave', ['ngResource', 'ngCookies']); app.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/login', { templateUrl: '/static/views/links/login.html', controller: 'LoginController'}) .when('/logout', { templateUrl: '/static/views/links/logout.html', controller: 'LogoutController'}) .when('/register', { templateUrl: '/static/views/links/register.html', controller: 'RegisterController'}) .when('/', { templateUrl: '/static/views/links/list.html', controller: 'MainController'}) .when('/about', { templateUrl: '/static/views/links/about.html'}) .when('/forget', { templateUrl: '/static/views/links/forget.html'}) .when('/settings', { templateUrl: '/static/views/links/settings.html'}) .when('/contact', { templateUrl: '/static/views/links/contact.html'}) .otherwise({ redirectTo: '/'}); }]); app.service('MainService', function($cookies, $rootScope) { this.isLogin = function(scope) { console.log($cookies.token) var is = $cookies.token != undefined; if (is && scope != undefined && scope.user != undefined) $rootScope.isLogin = 'hi ' + scope.user.nick; return is; } }); app.controller('RegisterController', ['$scope', '$http', '$location', 'MainService', function($scope, $http, $location, MainService) { MainService.isLogin($scope); $scope.register = function(user) { $http.post("/api/v1.0/register", user) .success(function(data, status, headers, config) { $location.path("/login"); }).error(function(data, status, headers, config) { $scope.error = data; }); } }]); app.controller('LoginController', ['$scope', '$http', '$location', '$cookies', 'MainService', function($scope, $http, $location, $cookies, MainService) { MainService.isLogin($scope); $scope.login = function(user) { $http.post("/api/v1.0/login", user) .success(function(data, status, headers, config) { $cookies.token = data['token'] $location.path("/"); }).error(function(data, status, headers, config) { if (status == 403) { $location.path("/login"); return } $scope.error = data; }); } }]); app.controller('LogoutController', ['$scope', '$http', '$location', '$cookies', 'MainService', function($scope, $http, $location, $cookies, MainService) { $http.get("/api/v1.0/logout?token=" + $cookies.token) .success(function(data, status, headers, config) { $cookies.token = undefined; $scope.user = undefined; $scope.links = undefined; $location.path("/login"); MainService.isLogin(); }).error(function(data, status, headers, config) { $cookies.token = undefined; $location.path("/login"); MainService.isLogin(); }); }]); app.controller('MainController', ['$scope', '$http', '$location', '$cookies', 'MainService', function($scope, $http, $location, $cookies, MainService) { if (MainService.isLogin()) { } else { $location.path('/login'); return; } if ($scope.user == undefined) { $http.get('/api/v1.0/user?token=' + $cookies.token) .success(function(data, status, headers, config) { $scope.user = data; MainService.isLogin($scope); }).error(function(data, status, headers, config) { if (status == 403) { $location.path("/login"); MainService.isLogin(); return } $scope.error = data; }); } document.getElementById("linkField").focus(); $scope.offset = 0; $scope.dataLoading = false; $scope.update = function(offset) { $http.get("/api/v1.0/links?token=" + $cookies.token + "&offset=" + offset ) .success(function(data, status, headers, config) { $scope.links = data; }).error(function(data, status, headers, config) { if (status == 403) { $location.path("/login"); return } $scope.error = data; }); } $scope.update($scope.offset) $scope.loaded = true; var limit = 4; $scope.next = function() { $scope.offset = $scope.offset + $scope.links.length; if ($scope.offset >= limit) { $scope.isPrev = true; } $scope.update($scope.offset) if ($scope.links.length < limit) { $scope.isNext = false; } } $scope.prev = function() { $scope.offset = $scope.offset - limit; if ($scope.offset <= 0) { $scope.offset = 0; $scope.isPrev = false; } $scope.update($scope.offset); } $scope.isNext = true $scope.isPrev = false $scope.del = function(i) { $http.delete("/api/v1.0/links/" + $scope.links[i]['_id']['$oid'] + "?token=" + $cookies.token) .success(function(data, status, headers, config) { $scope.links.splice(i, 1) }).error(function(data, status, headers, config) { $scope.error = data }); } $scope.add = function(l) { if ($scope.dataLoading) return; l = $.trim(l) if (l == '' || l == undefined || l == null) return $scope.dataLoading = true; $http.post("/api/v1.0/links?token=" + $cookies.token, {link: l}) .success(function(data, status, headers, config) { $scope.links.unshift(data) $scope.dataLoading = false; }).error(function(data, status, headers, config) { $scope.error = data; $scope.dataLoading = false; }); $scope.link = '' }; }]); $(window).focus(function() { document.getElementById("linkField").focus(); });
JavaScript
0.000001
@@ -8312,16 +8312,24 @@ () %7B%0A + var e = documen @@ -8353,27 +8353,50 @@ %22linkField%22) -.focus +;%0A e.focus();%0A e.select ();%0A%7D);%0A%0A
8a9c6334cb468f6e2356575233cabe247c31ab08
Load background even faster first time
static/script.js
static/script.js
var default_opacity = 0.2; var animate_time = 0; var default_animate_time = 1000; var num_images = 152; function fix_resolutions() { var img = $('#imgloader').get(0); var img_ratio = img.naturalWidth / img.naturalHeight; var wnd_ratio = window.innerWidth / window.innerHeight; $("#back").css("background-size", img_ratio > wnd_ratio ? "auto 100%" : "100% auto"); } function set_random_img() { var img = $('#imgloader').attr('src'); var back = $('#back'); back.animate({opacity: 0}, animate_time, 'swing', function() { if(animate_time == 0) { animate_time = default_animate_time; } back.css("background-image", "url('" + img + "')"); fix_resolutions(); back.animate({opacity: default_opacity}, animate_time); }); } function select_random_img() { $('#imgloader').attr('src', "static/imgs/" + (Math.floor(Math.random() * num_images) + 1) + ".jpg"); } $( document ).ready(function() { $('#imgloader').attr('src', '').load(set_random_img); select_random_img(); $(window).resize(fix_resolutions); window.setInterval(select_random_img, 10000); });
JavaScript
0
@@ -534,76 +534,8 @@ ) %7B%0A - if(animate_time == 0) %7B animate_time = default_animate_time; %7D%0A%0A @@ -668,16 +668,84 @@ e_time); +%0A%0A if(animate_time == 0) %7B animate_time = default_animate_time; %7D %0A %7D);%0A%7D
7597b4d3e6fc41a99035ab620ccfa7798e528ce4
fix when there is no authentication running
public/js/main.js
public/js/main.js
define(["app", "marionette", "backbone", "jquery"], function (app, Marionette, Backbone, $) { app.on("menu-actions-render", function (context) { if (app.settings.tenant.isAdmin) { if (app.settings.data.freeze && app.settings.data.freeze.value) { context.result += "<li><a id='releaseFreezeCommand' class='validate-leaving'>Release freeze</a></li>"; context.on("after-render", function ($el) { $($el).find("#releaseFreezeCommand").click(function () { app.settings.saveOrUpdate("freeze", false, function() { window.location.reload(); }); }); }); } else { context.result += "<li><a id='freezeCommand' class='validate-leaving'>Freeze editing</a></li>"; context.on("after-render", function ($el) { $($el).find("#freezeCommand").click(function () { app.settings.saveOrUpdate("freeze", true, function() { window.location.reload(); }); }); }); } } }); });
JavaScript
0.000004
@@ -159,32 +159,56 @@ if ( +!app.settings.tenant %7C%7C app.settings.ten
861f6a28a73839f16f9374f1823a1dd1171052b6
Fix dialing input in the browser
public/js/main.js
public/js/main.js
function setupDialDialog() { var connection; var inCall = false; var $dialog = $('#dialog-dial'); var $input = $dialog.find('.dial-input'); var $status = $dialog.find('.dial-status'); var $doHangup = $dialog.find('.do-hangup'); var $doCall = $dialog.find('.do-call'); var toggleCallStatus = function(){ $doCall.toggle(!inCall); $doHangup.text(inCall? "Hangup" : "Close"); } $dialog.find('.dial-button').click(function(e) { e.preventDefault(); var value = $(e.currentTarget).val(); if (connection) { connection.sendDigits(value); } else { $input.val($dialInput.val()+value); } }); Twilio.Device.setup($dialog.find('input[name=token]').val()); $doCall.click(function() { params = { "tocall" : $input.val()}; connection = Twilio.Device.connect(params); }); $doHangup.click(function() { Twilio.Device.disconnectAll(); }); Twilio.Device.ready(function (device) { console.log("Ready"); $status.text('Ready to start call'); }); Twilio.Device.incoming(function (conn) { if (confirm('Accept incoming call from ' + conn.parameters.From + '?')) { $dialog.addClass('active'); connection = conn; conn.accept(); } }); Twilio.Device.offline(function (device) { console.log("Offline"); $status.text('Offline'); }); Twilio.Device.error(function (error) { console.log("Error", error); $status.text("Error: "+error.message.message); }); Twilio.Device.connect(function (conn) { console.log("Connected"); $status.text("Successfully established call"); inCall = true; toggleCallStatus(); }); Twilio.Device.disconnect(function (conn) { console.log("Disconnected"); if (inCall) $status.text("Call ended"); inCall = false; toggleCallStatus(); }); toggleCallStatus(); } // Click to toggle dialog function setupDialogs() { $('*[data-dialog]').click(function(e) { e.preventDefault(); var dialog = $(e.currentTarget).attr('data-dialog'); $('#dialog-'+dialog).toggleClass('active'); }); $(document).keyup(function(e) { if (e.keyCode == 27) $('.dialog-container').removeClass('active'); }); } // Setup audio player function setupAudioPlayers() { $('.audio-player').each(function() { var $player = $(this); var audio = $player.find('audio').get(0); var $position = $player.find('.position'); var loaded = false; audio.onplaying = function() { $player.addClass('playing'); $player.removeClass('paused'); }; audio.onpause = function() { $player.addClass('playing'); $player.addClass('paused'); }; audio.onended = function() { $player.removeClass('playing'); $player.removeClass('paused'); }; audio.ontimeupdate = function() { var t = audio.currentTime; var msg = ""; msg = Math.floor(t/60)+':'+Math.ceil(t % 60); $position.text(msg); }; $player.find('.do-play').click(function(e) { e.preventDefault(); if (!loaded) { audio.load(); loaded = true; } audio.play(); }); $player.find('.do-pause').click(function(e) { e.preventDefault(); audio.pause(); }); $player.find('.do-stop').click(function(e) { e.preventDefault(); audio.pause(); audio.currentTime = 0; }); }); } // Handle call and sms links in the app function setupLinks() { $('a').click(function(e) { var $a = $(e.currentTarget); var val = decodeURIComponent($a.attr('href')); if (val.indexOf('tel:') === 0) { e.preventDefault(); $('#dialog-dial').addClass('active') .find('.dial-input') .val(val.slice('tel:'.length)); } else if (val.indexOf('sms:') === 0) { e.preventDefault(); $('#dialog-sms').addClass('active') .find('.dial-input') .val(val.slice('tel:'.length)); } }) } $(document).ready(function() { setupDialogs(); setupAudioPlayers(); setupDialDialog(); setupLinks(); });
JavaScript
0.000006
@@ -632,20 +632,9 @@ %7D - else %7B%0A +%0A @@ -653,13 +653,9 @@ al($ -dialI +i nput @@ -665,34 +665,24 @@ l()+value);%0A - %7D%0A %7D);%0A%0A
15d828362aac4fe2da6d4229d31651d6ea00af14
Use pid.codes VID/PID
lib/usb_connection.js
lib/usb_connection.js
var util = require('util'), Duplex = require('stream').Duplex, Promise = require('bluebird'); var haveusb = true; try { var usb = require('usb'); } catch (e) { haveusb = false; console.error('WARNING: No usb controller found on this system.'); } var Daemon = require('./usb/usb_daemon'); var TESSEL_VID = 0x9999; var TESSEL_PID = 0xffff; function USBConnection(device) { Duplex.call(this); this.device = device; this.connectionType = 'USB'; this.epIn = undefined; this.epOut = undefined; } util.inherits(USBConnection, Duplex); USBConnection.prototype.exec = function(command, callback) { var self = this; // Execute the command if (!Array.isArray(command)) { return callback && callback(new Error('Command to execute must be an array of args.')); } // Create a new process Daemon.openProcess(self, function(err, proc) { if (err) { return callback && callback(err); } else { // Format the args into something the USB protocol can understand command = self._processArgsForTransport(command); // Write the bash command proc.control.end(command); // Once the command has been written, call the callback with the resulting process proc.control.once('finish', callback.bind(self, null, proc)); } }); }; USBConnection.prototype._write = function(chunk, enc, callback) { if (this.closed) { callback(new Error('Connection was already closed...')); } else { this.epOut.transfer(chunk, callback); } }; USBConnection.prototype._read = function() { var self = this; if (self.closed) { return self.push(null); } self.epIn.transfer(4096, function(err, data) { if (err) { self.emit('error', err); } else { self.push(data); } }); }; USBConnection.prototype.open = function() { var self = this; return new Promise(function(resolve, reject) { // Try to open connection try { self.device.open(); } catch (e) { if (e.message === 'LIBUSB_ERROR_ACCESS' && process.platform === 'linux') { console.error('Please run `sudo tessel install-drivers` to fix device permissions.\n(Error: could not open USB device.)'); } // Reject if error return reject(e, self); } // Try to initialize interface self.intf = self.device.interface(0); try { self.intf.claim(); } catch (e) { // Reject if error return reject(e, self); } // Set interface settings self.intf.setAltSetting(2, function(error) { if (error) { return reject(error, self); } self.epIn = self.intf.endpoints[0]; self.epOut = self.intf.endpoints[1]; if (!self.epIn || !self.epOut) { return reject(new Error('Device endpoints weren not able to be loaded'), self); } // Map desciptions self.device.getStringDescriptor(self.device.deviceDescriptor.iSerialNumber, function(error, data) { if (error) { return reject(error, self); } self.serialNumber = data; // Register this connection with daemon (keeps track of active remote processes) Daemon.register(self); // If all is well, resolve the promise with the valid connection return resolve(self); }); }); }); }; USBConnection.prototype.end = function(callback) { var self = this; // Tell the USB daemon to end all processes active // on account of this connection Daemon.deregister(this, function(err) { self._close(); if (typeof callback === 'function') { callback(err); } }); }; USBConnection.prototype._close = function(callback) { var self = this; if (self.closed) { return callback && callback(); } self.closed = true; self.intf.release(true, function() { self.device.close(); if (typeof callback === 'function') { callback(); } }.bind(self)); }; USBConnection.prototype._processArgsForTransport = function(command) { if (!Array.isArray(command)) { return; } // For each command command.forEach(function(arg, i) { // If this isn't the last item if (i !== command.length - 1) { // Demarcate the end of an arg with a null byte command[i] += '\0'; } }); // Join all the args into a string command = command.join(''); return command; }; function findConnections() { return new Promise(function(resolve) { var connections = usb.getDeviceList() .map(function(dev) { if ((dev.deviceDescriptor.idVendor === TESSEL_VID) && (dev.deviceDescriptor.idProduct === TESSEL_PID)) { return new USBConnection(dev); } }) .filter(function(x) { return x; }); resolve(connections); }) .map(function(conn) { return conn.open(); }) .catch(function(error, conn) { conn.initError = error; return conn; }); } exports.findConnections = findConnections;
JavaScript
0.000018
@@ -313,19 +313,19 @@ VID = 0x -999 +120 9;%0Avar T @@ -342,12 +342,12 @@ = 0x -ffff +7551 ;%0A%0Af
7871cab71081501845bc3d1248755af3e087e48b
load env vars from /etc/sematext/receivers.config for onprem/multi-region
lib/util/spmconfig.js
lib/util/spmconfig.js
/* * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved * * @licence SPM for NodeJS is free-to-use, proprietary software. * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext) * This source code may not be copied, reverse engineered, or altered for any purpose. * This source code is to be used exclusively by users and customers of Sematext. * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies. */ 'use strict' var flatten = require('flat') var unflatten = require('flat').unflatten var util = require('util') var RC = require('rc-yaml-2') var spmDefaultConfig = { tokens: { spm: process.env.SPM_TOKEN }, maxDbSize: Number(process.env.SPM_MAX_DB_SIZE) || 1024 * 1024 * 24, agentsToLoad: [], maxDataPoints: Number(process.env.SPM_MAX_DATAPOINTS) || 90, recoverInterval: Number(process.env.SPM_RECOVER_INTERVAL_IN_MS) || 10000, collectionInterval: Number(process.env.SPM_COLLECTION_INTERVAL_IN_MS) || 10000, transmitInterval: Number(process.env.SPM_TRANSMIT_INTERVAL_IN_MS) || 15000, maxRetransmitBatchSize: Number(process.env.SPM_MAX_RETRANSMIT_BATCH_SIZE) || 100, spmSenderBulkInsertUrl: process.env.SPM_RECEIVER_URL || 'https://spm-receiver.sematext.com:443/receiver/v1/_bulk', eventsReceiverUrl: process.env.EVENTS_RECEIVER_URL || 'https://event-receiver.sematext.com', dbDir: process.env.SPM_DB_DIR || './spmdb', logger: { dir: process.env.SPM_LOG_DIRECTORY || './spmlogs', level: process.env.SPM_LOG_LEVEL || 'error', console: process.env.SPM_LOG_TO_CONSOLE || false, maxfiles: Number(process.env.SPM_LOG_MAX_FILES) || '2', maxsize: Number(process.env.SPM_LOG_MAX_FILE_SIZE) || '524288', filename: process.env.SPM_LOG_FILE_PREFIX || 'spm', useLogstashFormat: process.env.SPM_LOG_LOGSTASH_FORMAT || false, silent: process.env.SPM_LOG_SILENT || false } } var SpmConfig = function (appType) { var rc = new RC(appType, spmDefaultConfig) util._extend(this, rc) this.rcFlat = flatten(this) return this } SpmConfig.prototype.get = function (flatKey) { return this.rcFlat[flatKey] } SpmConfig.prototype.set = function (flatKey, value) { var kv = {} kv[flatKey] = value kv.object = true var result = unflatten(kv) delete result.object delete this.rcFlat util._extend(this, result) this.rcFlat = flatten(this) return this } module.exports = new SpmConfig(process.env.SPM_AGENT_APP_TYPE || 'spmagent')
JavaScript
0
@@ -657,16 +657,1090 @@ aml-2')%0A +var fs = require('fs')%0A%0A// load SPM receivers from file containing%0A// env vars e.g. SPM_RECEIVER_URL, EVENTS_RECEIVER_URL, LOGSENE_RECEIVER_URL%0A// the file overwrites the actual environment%0A// and is used by Sematext Enterprise or multi-region setups to%0A// setup receiver URLs%0Afunction loadEnvFromFile (fileName) %7B%0A try %7B%0A var receivers = fs.readFileSync(fileName).toString()%0A if (receivers) %7B%0A var lines = receivers.split('%5Cn')%0A %7D%0A // console.log(new Date(), 'loading Sematext receiver URLs from ' + fileName)%0A lines.forEach(function (line) %7B%0A var kv = line.split('=')%0A if (kv.length === 2 && kv%5B1%5D.length %3E 0) %7B%0A process.env%5Bkv%5B0%5D.trim()%5D = kv%5B1%5D.trim()%0A // console.log(kv%5B0%5D.trim() + ' = ' + kv%5B1%5D.trim())%0A %7D%0A %7D)%0A %7D catch (error) %7B%0A // ignore missing file or wrong format%0A // console.error(error.message)%0A %7D%0A%7D%0Avar envFileName = '/etc/sematext/receivers.config'%0A/**%0A if (/win/.test(os.platform()) %7B%0A envFileName = process.env.ProgramData + '%5C%5CSematext%5C%5Creceivers.config'%0A %7D%0A**/%0AloadEnvFromFile(envFileName)%0A%0A var spmD
cce3e66c78661386f93ef40cc84143828e4fc89f
Remove logging
lib/views/EditView.js
lib/views/EditView.js
/** @babel */ /** @jsx etch.dom */ import { CompositeDisposable } from 'atom'; import etch from 'etch'; import changeCase from 'change-case'; import path from 'path'; import { EDIT_URI } from './view-uri'; import manager from '../Manager'; import Project from '../models/Project'; const disposables = new CompositeDisposable(); etch.setScheduler(atom.views); export default class EditView { constructor(props, children) { this.props = props; this.children = children; etch.initialize(this); this.storeFocusedElement(); this.setFocus(); this.element.addEventListener('click', (event) => { if (event.target === this.refs.save) { this.saveProject(); } }); disposables.add(atom.commands.add(this.element, { 'core:save': () => this.saveProject(), 'core:confirm': () => this.saveProject(), })); disposables.add(atom.commands.add('atom-workspace', { 'core:cancel': () => this.close(), })); } getFocusElement() { return this.refs.title; } setFocus() { const focusElement = this.getFocusElement(); if (focusElement) { setTimeout(() => { focusElement.focus(); }, 0); } } storeFocusedElement() { this.previouslyFocusedElement = document.activeElement; } restoreFocus() { if (this.previouslyFocusedElement) { this.previouslyFocusedElement.focus(); } } close() { this.destroy(); } async destroy() { const pane = atom.workspace.paneForURI(EDIT_URI); if (pane) { const item = pane.itemForURI(EDIT_URI); pane.destroyItem(item); } disposables.dispose(); await etch.destroy(this); } saveProject() { const projectProps = { title: this.refs.title.value, paths: atom.project.getPaths(), group: this.refs.group.value, icon: this.refs.icon.value, devMode: this.refs.devMode.checked, }; let message = `${projectProps.title} has been saved.`; if (this.props.project) { // Paths should already be up-to-date, so use // the current paths as to not break possible relative paths. projectProps.paths = this.props.project.getProps().paths; } manager.saveProject(projectProps); if (this.props.project) { message = `${this.props.project.title} has been updated.`; } atom.notifications.addSuccess(message); this.close(); } update(props, children) { this.props = props; this.children = children; } getTitle() { if (this.props.project) { return `Edit ${this.props.project.title}`; } return 'Save Project'; } getIconName() { // eslint-disable-line class-methods-use-this return 'gear'; } getURI() { // eslint-disable-line class-methods-use-this return EDIT_URI; } render() { const defaultProps = Project.defaultProps; const rootPath = atom.project.getPaths()[0]; let props = defaultProps; if (atom.config.get('project-manager.prettifyTitle')) { props.title = changeCase.titleCase(path.basename(rootPath)); } console.log(this.props.project); if (this.props.project && this.props.project.source === 'file') { console.log(this.props.project.getProps()); const projectProps = this.props.project.getProps(); props = Object.assign({}, props, projectProps); } const wrapperStyle = { display: 'flex', alignItems: 'center', justifyContent: 'center', }; const style = { width: '500px', }; return ( <div style={wrapperStyle} className="project-manager-edit padded native-key-bindings"> <div style={style}> <h1 className="block section-heading">{this.getTitle()}</h1> <div className="block"> <label className="input-label">Title</label> <input ref="title" type="text" className="input-text" value={props.title} tabIndex="0" /> </div> <div className="block"> <label className="input-label">Group</label> <input ref="group" type="text" className="input-text" value={props.group} tabIndex="1" /> </div> <div className="block"> <label className="input-label">Icon</label> <input ref="icon" type="text" className="input-text" value={props.icon} tabIndex="2" /> </div> <div className="block"> <label className="input-label" for="devMode">Development mode</label> <input ref="devMode" id="devMode" name="devMode" type="checkbox" className="input-toggle" checked={props.devMode} tabIndex="3" /> </div> <div className="block" style={{ textAlign: 'right' }}> <button ref="save" className="btn btn-primary" tabIndex="4">Save</button> </div> </div> </div> ); } }
JavaScript
0.000001
@@ -3074,44 +3074,8 @@ %7D%0A - console.log(this.props.project); %0A @@ -3145,58 +3145,8 @@ ) %7B%0A - console.log(this.props.project.getProps());%0A
eb054d5270564ccd7be38a525bd94360daf89959
Add notification for when editing or saving a project
lib/views/EditView.js
lib/views/EditView.js
/** @babel */ /** @jsx etch.dom */ import etch from 'etch'; import { EDIT_URI } from './view-uri'; import manager from '../Manager'; import Project from '../models/Project'; etch.setScheduler(atom.views); export default class EditView { constructor(props, children) { this.props = props; this.children = children; etch.initialize(this); this.element.addEventListener('click', (event) => { if (event.target === this.refs.save) { this.saveProject(); } }); atom.commands.add(this.element, { 'core:save': () => this.saveProject(), }); } saveProject() { const projectProps = { title: this.refs.title.value, paths: atom.project.getPaths(), group: this.refs.group.value, icon: this.refs.icon.value, devMode: this.refs.devMode.checked, }; manager.saveProject(projectProps); } update(props, children) { this.props = props; this.children = children; } getTitle() { if (this.props.project) { return `Edit ${this.props.project.title}`; } return 'Save Project'; } getIconName() { return 'gear'; } getURI() { return EDIT_URI; } render() { const defaultProps = Project.defaultProps; let props = defaultProps; if (this.props.project) { const projectProps = this.props.project.getProps(); props = Object.assign(props, projectProps); } const wrapperStyle = { display: 'flex', alignItems: 'center', justifyContent: 'center', }; const style = { width: '500px', }; return ( <div style={wrapperStyle} className="project-manager-edit padded native-key-bindings" > <div style={style}> <h1 className="block section-heading">{this.getTitle()}</h1> <div className="block"> <label className="input-label">Title</label> <input ref="title" type="text" className="input-text" value={props.title} tabIndex="-1" /> </div> <div className="block"> <label className="input-label">Group</label> <input ref="group" type="text" className="input-text" value={props.group} tabIndex="1" /> </div> <div className="block"> <label className="input-label">Icon</label> <input ref="icon" type="text" className="input-text" value={props.icon} tabIndex="2" /> </div> <div className="block"> <label className="input-label" for="devMode">Development mode</label> <input ref="devMode" id="devMode" name="devMode" type="checkbox" className="input-checkbox" checked={props.devMode} tabIndex="3" /> </div> <div className="block" style={{ textAlign: 'right' }}> <button ref="save" className="btn btn-primary">Save</button> </div> </div> </div> ); } }
JavaScript
0
@@ -868,16 +868,219 @@ Props);%0A + let message = %60$%7BprojectProps.title%7D has been saved.%60;%0A if (this.props.project) %7B%0A message = %60$%7Bthis.props.project.title%7D has been update.%60;%0A %7D%0A atom.notifications.addSuccess(message);%0A %7D%0A%0A u @@ -1584,16 +1584,20 @@ .assign( +%7B%7D, props, p
af28b0fa77ceb011aa6b1e7810a553c6d62012af
Update chatbot.js
stuff/chatbot.js
stuff/chatbot.js
exports.bot = function(b){ var bot = '' if(typeof b != "undefined") bot = b else bot = {}; var botStuff = { name: '~RainBot' jokes: { 0: 'The original title for Alien vs. Predator was Alien and Predator vs Chuck Norris. The film was cancelled shortly after going into preproduction. No one would pay nine dollars to see a movie fourteen seconds long.', 1: 'There used to be a street named after Chuck Norris, but it was changed because nobody crosses Chuck Norris and lives.', 2: 'Some magicans can walk on water, Chuck Norris can swim through land.', 3: 'If you were somehow able to land a punch on Chuck Norris your entire arm would shatter upon impact. This is only in theory, since, come on, who in their right mind would try this?', 4: 'Chuck Norris can cut through a hot knife with butter', 5: 'Chuck Norris has never caught a cold. How do we know? Colds still exist.', 6: 'Yo\' Mama is so dumb, she left her car at a stop sign because it never changed to "go."', 7: 'Yo\' Mama is so fat, when she stepped on the scale it said "one at a time"', 8: 'Yo\' Mama so fat, when she sat on an iPhone, she turned it to an iPad', 9: 'Yo\' Mama so stupid, she brought a spoon to the Superbowl.', 10: 'Yo\' mama so ugly that not even goldfish crackers smile back', 11: 'How does a blonde kill a fish? She drowns it.', 12: 'How do you amuse a blonde for hours? Write \'Please turn over\' on both sides of a piece of paper', 13: 'Girl: Why are you so ugly? Boy: I'm you from the future.', 14: '-Someone says something about you or boring -You, Say it to my butt because its the only thing that gives a crap.', 15: 'Me: *randomly walks up to Chinese person*. "Chow tang wong.". Chinese person: *nods, points to the bathroom*.', 16: 'Random Kid,"Haha you failed!" You, "So did your dads condom."', 17: 'Why did the redneck cross the road? He wanted to sleep in the ditch on the other side. ', 18: 'Why did the blind blonde cross the road? She was following her seeing-eye chicken.', 19: 'Why was there so much confusion with the Secret Service after George W. Bush took over the White House? Because President Bill Clinton\'s code name was also "Mr. Bush."', 20: 'Most wives whose husbands fool around have to worry about their husbands getting AIDS from sex. Hillary just has to worry about her husband getting sex from aides.' }, getRandjoke: function(){ //to work on later } }
JavaScript
0.000004
@@ -1452,16 +1452,17 @@ ? Boy: I +%5C 'm you f @@ -2247,17 +2247,16 @@ rom sex. -%0A Hillary @@ -2348,27 +2348,182 @@ ()%7B%0A -//to work on later%0A +return bot.jokes%5BMath.floor%5BMath.random()*20%5D%5D;%0A%7D,%0Asay: function(name,message)%7B%0A return room.add('%7Cc%7C ' + name + '%7C' + message);%0A%7D,%0Aparser: require('./botparser.js')%0Acmds: %7B %7D%0A%7D%0A
f6c8e7ea851b0a6aab1580b96222d5caa848be0a
Fix elements highlight
src/Elements/Highlight.js
src/Elements/Highlight.js
import { evalCss, $, pxToNum, isStr, each, trim } from '../lib/util' export default class Highlight { constructor($container) { this._style = evalCss(require('./Highlight.scss')) this._isShow = false this._appendTpl($container) this._bindEvent() } setEl(el) { this._$target = $(el) this._target = el } show() { this._isShow = true this.render() this._$el.show() } destroy() { evalCss.remove(this._style) } hide() { this._isShow = false this._$el.hide() } render() { let { left, width, top, height } = this._$target.offset() this._$el.css({ left, top: top - window.scrollY, width, height }) let computedStyle = getComputedStyle(this._target, '') let getNumStyle = name => pxToNum(computedStyle.getPropertyValue(name)) let ml = getNumStyle('margin-left'), mr = getNumStyle('margin-right'), mt = getNumStyle('margin-top'), mb = getNumStyle('margin-bottom') this._$margin.css({ left: -ml, top: -mt, width: width + ml + mr, height: height + mt + mb }) let bl = getNumStyle('border-left-width'), br = getNumStyle('border-right-width'), bt = getNumStyle('border-top-width'), bb = getNumStyle('border-bottom-width') let bw = width - bl - br, bh = height - bt - bb this._$padding.css({ left: bl, top: bt, width: bw, height: bh }) let pl = getNumStyle('padding-left'), pr = getNumStyle('padding-right'), pt = getNumStyle('padding-top'), pb = getNumStyle('padding-bottom') this._$content.css({ left: bl + pl, top: bl + pt, width: bw - pl - pr, height: bh - pt - pb }) this._$size .css({ top: -mt - (top - mt < 25 ? 0 : 25), left: -ml }) .html(`${formatElName(this._target)} | ${width} × ${height}`) } _bindEvent() { window.addEventListener( 'scroll', () => { if (!this._isShow) return this.render() }, false ) } _appendTpl($container) { $container.append(require('./Highlight.hbs')()) let $el = (this._$el = $('.eruda-elements-highlight')) this._$margin = $el.find('.eruda-margin') this._$padding = $el.find('.eruda-padding') this._$content = $el.find('.eruda-content') this._$size = $el.find('.eruda-size') } } function formatElName(el) { let { id, className } = el let ret = `<span style="color:#ee78e6">${el.tagName.toLowerCase()}</span>` if (id !== '') ret += `<span style="color:#ffab66">#${id}</span>` let classes = '' if (isStr(className)) { each(className.split(/\s+/g), val => { if (trim(val) === '') return classes += `.${val}` }) } ret += `<span style="color:#8ed3fb">${classes}</span>` return ret }
JavaScript
0.000002
@@ -2166,16 +2166,30 @@ _$el = $ +container.find ('.eruda
ecb0b31263ad75935a82dda29064acc94ea4dbd6
Use TraitStatisticBox rather than StatisticBox. Show uptime rather than number of procs on statistic box.
src/Parser/Hunter/BeastMastery/Modules/Spells/AzeriteTraits/DanceOfDeath.js
src/Parser/Hunter/BeastMastery/Modules/Spells/AzeriteTraits/DanceOfDeath.js
import React from 'react'; import SpellIcon from 'common/SpellIcon'; import Analyzer from 'Parser/Core/Analyzer'; import {formatNumber, formatPercentage} from 'common/format'; import {calculateAzeriteEffects} from 'common/stats'; import StatisticBox from 'Interface/Others/StatisticBox'; import SPELLS from 'common/SPELLS/index'; export function danceOfDeathStats(combatant){ if(!combatant.hasTrait(SPELLS.DANCE_OF_DEATH.id)){ return null; } let agility = 0; for(const rank of combatant.traitsBySpellId[SPELLS.DANCE_OF_DEATH.id]){ const [agi] = calculateAzeriteEffects(SPELLS.DANCE_OF_DEATH.id, rank); agility += agi; } return {agility}; } export const STAT_TRACKER = { agility: (combatant) => danceOfDeathStats(combatant).agility, }; /** * Barbed Shot has a chance equal to your critical strike chance to grant you 314 agility * for 8 sec. */ class DanceOfDeath extends Analyzer{ agility = 0; constructor(...args) { super(...args); const response = danceOfDeathStats(this.selectedCombatant); if (response === null) { this.active = false; return; } this.agility += response.agility; } get uptime(){ return this.selectedCombatant.getBuffUptime(SPELLS.DANCE_OF_DEATH_BUFF.id) / this.owner.fightDuration; } get avgAgility(){ return this.uptime * this.agility; } get numProcs(){ return this.selectedCombatant.getBuffTriggerCount(SPELLS.DANCE_OF_DEATH_BUFF.id); } statistic(){ return ( <StatisticBox icon={<SpellIcon id={SPELLS.DANCE_OF_DEATH.id} />} value={( <React.Fragment> {formatNumber(this.avgAgility)} Agility <br /> {formatNumber(this.numProcs)} Procs </React.Fragment> )} label={"Dance of Death"} tooltip={`Dance of Death granted <b>${this.agility}</b> agility for <b>${formatPercentage(this.uptime)}%</b> of the fight.`} /> ); } } export default DanceOfDeath;
JavaScript
0
@@ -24,50 +24,8 @@ t';%0A -import SpellIcon from 'common/SpellIcon';%0A impo @@ -188,16 +188,21 @@ %0Aimport +Trait Statisti @@ -205,16 +205,37 @@ isticBox +, %7B STATISTIC_ORDER %7D from 'I @@ -250,16 +250,21 @@ /Others/ +Trait Statisti @@ -318,23 +318,13 @@ ;%0A%0A%0A -export function +const dan @@ -341,190 +341,67 @@ tats -(combatant)%7B%0A if(!combatant.hasTrait(SPELLS.DANCE_OF_DEATH.id))%7B%0A return null;%0A %7D%0A let agility = 0;%0A for(const rank of combatant.traitsBySpellId%5BSPELLS.DANCE_OF_DEATH.id%5D)%7B%0A + = traits =%3E Object.values(traits).reduce((obj, rank) =%3E %7B%0A co @@ -408,16 +408,20 @@ nst %5Bagi +lity %5D = calc @@ -475,18 +475,20 @@ ank);%0A - +obj. agility @@ -497,35 +497,50 @@ agi -;%0A %7D%0A return %7Bagility%7D;%0A%7D +lity;%0A return obj;%0A%7D, %7B%0A agility: 0,%0A%7D); %0A%0Aex @@ -578,17 +578,16 @@ gility: -( combatan @@ -587,17 +587,16 @@ ombatant -) =%3E danc @@ -618,16 +618,57 @@ ombatant +.traitsBySpelld%5BSPELLS.DANCE_OF_DEATH.id%5D ).agilit @@ -782,16 +782,135 @@ 8 sec.%0A + *%0A * Example report: https://www.warcraftlogs.com/reports/Nt9KGvDncPmVyjpd#boss=-2&difficulty=0&type=summary&source=9%0A */%0Aclas @@ -1011,103 +1011,89 @@ -const response = danceOfDeathStats(this.selectedCombatant);%0A if (response === null) %7B%0A +this.active = this.selectedCombatant.hasTrait(SPELLS.DANCE_OF_DEATH.id);%0A if(! this @@ -1103,17 +1103,10 @@ tive - = false; +)%7B %0A @@ -1130,33 +1130,130 @@ -this.agility += response. +const %7Bagility%7D = danceOfDeathStats(this.selectedCombatant.traitsBySpellId%5BSPELLS.DANCE_OF_DEATH.id%5D);%0A this.agility = agil @@ -1262,17 +1262,16 @@ y;%0A %7D%0A%0A -%0A get up @@ -1598,16 +1598,21 @@ %0A %3C +Trait Statisti @@ -1628,27 +1628,59 @@ -icon=%7B%3CSpellIcon id +position=%7BSTATISTIC_ORDER.OPTIONAL()%7D%0A trait =%7BSP @@ -1706,12 +1706,8 @@ .id%7D - /%3E%7D %0A @@ -1790,16 +1790,24 @@ gility)%7D + Average Agility @@ -1837,36 +1837,40 @@ rmat -Number(this.numProcs)%7D Procs +Percentage(this.uptime)%7D%25 Uptime %0A
0e25f88dc0f88fff222fdc0adb600e151c612e6b
Format js in shortcode templates script
src/OrchardCore.Modules/OrchardCore.Shortcodes/Assets/js/shortcode-templates.js
src/OrchardCore.Modules/OrchardCore.Shortcodes/Assets/js/shortcode-templates.js
function initializeShortcodesTemplateEditor(categoriesElement, contentElement, usageElement, previewElement, nameElement, hintElement ) { if (contentElement) { CodeMirror.fromTextArea(contentElement, { autoCloseTags: true, autoRefresh: true, lineNumbers: true, lineWrapping: true, matchBrackets: true, styleActiveLine: true, mode: { name: "liquid" } }); } if (usageElement) { var editor = CodeMirror.fromTextArea(usageElement, { autoCloseTags: true, autoRefresh: true, lineNumbers: true, lineWrapping: true, matchBrackets: true, styleActiveLine: true, mode: { name: "htmlmixed" } }); if (previewElement) { editor.on('change', function(e){ $(previewElement).show(); $(previewElement).find('.shortcode-usage').html(e.doc.getValue()); }); } } if (nameElement && previewElement) { $(nameElement).on('keyup paste', function () { $(previewElement).show(); $(previewElement).find('.shortcode-name').html($(this).val()) }); } if (hintElement && previewElement) { $(hintElement).on('keyup paste', function () { $(previewElement).show(); $(previewElement).find('.shortcode-hint').html($(this).val()) }); } if (categoriesElement) { var vueMultiselect = Vue.component('vue-multiselect', window.VueMultiselect["default"]); var vm = new Vue({ el: categoriesElement, components: { 'vue-multiselect': vueMultiselect }, data: function data() { var allCategories = JSON.parse(categoriesElement.dataset.categories || "[]"); var selectedCategories = JSON.parse(categoriesElement.dataset.selectedCategories || "[]"); return { value: selectedCategories, options: allCategories }; }, methods: { getSelectedCategories() { return JSON.stringify(this.value); }, addCategory(category) { this.options.push(category); this.value.push(category); } } }); return vm; } }
JavaScript
0
@@ -1,10 +1,8 @@ -%0A%0A function @@ -126,17 +126,16 @@ tElement - ) %7B%0A @@ -863,20 +863,14 @@ tion + (e) -%7B +%7B %0A @@ -1006,29 +1006,16 @@ %7D); - %0A @@ -1071,16 +1071,18 @@ %7B%0A + $(nameEl @@ -1119,28 +1119,25 @@ ion () %7B - +%0A %0A @@ -1124,31 +1124,24 @@ ) %7B%0A -%0A $(previe @@ -1160,32 +1160,34 @@ ow();%0A + + $(previewElement @@ -1228,24 +1228,26 @@ his).val())%0A + %7D);%0A @@ -1346,27 +1346,16 @@ ion () %7B - %0A @@ -1470,17 +1470,16 @@ %7D); - %0A %7D%0A%0A
269bc273bf6392aa585478ee19d188605bcf1383
update spectra-processor to 0.18.0
eln/libs/SpectraProcessor.js
eln/libs/SpectraProcessor.js
export { SpectraProcessor } from 'https://www.lactame.com/lib/spectra-processor/0.17.0/spectra-processor.js'; // from 'http://localhost:9898/cheminfo-js/spectra-processor/dist/spectra-processor.js';
JavaScript
0.000006
@@ -82,9 +82,9 @@ /0.1 -7 +8 .0/s
faf71b5b7ded7705629d69f20dc32333c6d63e8d
upgrade spectra-processor to 0.6.1
eln/libs/SpectraProcessor.js
eln/libs/SpectraProcessor.js
export { SpectraProcessor } from 'https://www.lactame.com/lib/spectra-processor/0.6.0/spectra-processor.js'; // } from 'http://localhost:9898/cheminfo-js/spectra-processor/dist/spectra-processor.js';
JavaScript
0.000001
@@ -79,17 +79,17 @@ sor/0.6. -0 +1 /spectra
0e11cab79291051a8dfd6cf3d9378eb9a5fb708d
Fix unchained promise
03-oidc-views-accounts/index.js
03-oidc-views-accounts/index.js
'use strict'; // see previous example for the things that are not commented const assert = require('assert'); const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const Provider = require('oidc-provider'); // since dyno metadata is no longer available, we infer the app name from heroku remote we set // manually. This is not specific to oidc-provider, just an easy way of getting up and running if (!process.env.HEROKU_APP_NAME && process.env.X_HEROKU_REMOTE) { process.env.X_HEROKU_REMOTE.match(/\.com\/(.+)\.git/); process.env.HEROKU_APP_NAME = RegExp.$1; } assert(process.env.HEROKU_APP_NAME, 'process.env.HEROKU_APP_NAME missing'); assert(process.env.PORT, 'process.env.PORT missing'); assert(process.env.SECURE_KEY, 'process.env.SECURE_KEY missing, run `heroku addons:create securekey`'); assert.equal(process.env.SECURE_KEY.split(',').length, 2, 'process.env.SECURE_KEY format invalid'); assert(process.env.REDIS_URL, 'process.env.REDIS_URL missing, run `heroku-redis:hobby-dev`'); // require the redis adapter factory/class const RedisAdapter = require('./redis_adapter'); // simple account model for this application, user list is defined like so const Account = require('./account'); const oidc = new Provider(`https://${process.env.HEROKU_APP_NAME}.herokuapp.com`, { // oidc-provider only looks up the accounts by their ID when it has to read the claims, // passing it our Account model method is sufficient, it should return a Promise that resolves // with an object with accountId property and a claims method. findById: Account.findById, // let's tell oidc-provider we also support the email scope, which will contain email and // email_verified claims claims: { // scope: [claims] format openid: ['sub'], email: ['email', 'email_verified'], }, // let's tell oidc-provider where our own interactions will be // setting a nested route is just good practice so that users // don't run into weird issues with multiple interactions open // at a time. interactionUrl(ctx) { return `/interaction/${ctx.oidc.uuid}`; }, features: { // disable the packaged interactions devInteractions: false, claimsParameter: true, clientCredentials: true, discovery: true, encryption: true, introspection: true, registration: true, request: true, requestUri: true, revocation: true, sessionManagement: true, }, }); const keystore = require('./keystore.json'); oidc.initialize({ keystore, clients: [ // reconfigured the foo client for the purpose of showing the adapter working { client_id: 'foo', redirect_uris: ['https://example.com'], response_types: ['id_token token'], grant_types: ['implicit'], token_endpoint_auth_method: 'none', }, ], // configure Provider to use the adapter adapter: RedisAdapter, }).then(() => { oidc.app.proxy = true; oidc.app.keys = process.env.SECURE_KEY.split(','); }).then(() => { // let's work with express here, below is just the interaction definition const expressApp = express(); expressApp.set('trust proxy', true); expressApp.set('view engine', 'ejs'); expressApp.set('views', path.resolve(__dirname, 'views')); const parse = bodyParser.urlencoded({ extended: false }); expressApp.get('/interaction/:grant', async (req, res) => { oidc.interactionDetails(req).then((details) => { console.log('see what else is available to you for interaction views', details); const view = (() => { switch (details.interaction.reason) { case 'consent_prompt': case 'client_not_authorized': return 'interaction'; default: return 'login'; } })(); res.render(view, { details }); }); }); expressApp.post('/interaction/:grant/confirm', parse, (req, res) => { oidc.interactionFinished(req, res, { consent: {}, }); }); expressApp.post('/interaction/:grant/login', parse, (req, res, next) => { Account.authenticate(req.body.email, req.body.password).then((account) => { oidc.interactionFinished(req, res, { login: { account: account.accountId, acr: '1', remember: !!req.body.remember, ts: Math.floor(Date.now() / 1000), }, consent: { // TODO: remove offline_access from scopes if remember is not checked }, }); }).catch(next); }); // leave the rest of the requests to be handled by oidc-provider, there's a catch all 404 there expressApp.use(oidc.callback); // express listen expressApp.listen(process.env.PORT); });
JavaScript
0.000081
@@ -4137,24 +4137,31 @@ =%3E %7B%0A +return oidc.interac
30e548e1a7dfa4bacbebb5dbf6f4a4b154fd59ff
fix scope.showSpinner method does not exists in question ctrl
www/js/controllers/question.js
www/js/controllers/question.js
angular.module('app.controllers').controller('question',function ($scope, $location, questions, $stateParams, layout, iStorageMemory, activity) { var optionsSubview = 'templates/question/options.html'; var resultsSubview = 'templates/question/results.html'; $scope.loading = true; $scope.blockedLoading = false; questions.load($stateParams.id).then(function (question) { $scope.loading = false; $scope.q = question; $scope.shareBody = question.subject; $scope.shareImage = question.share_picture; if (question.is_answered || question.expired) { $scope.subview = resultsSubview; } else { $scope.subview = optionsSubview; } $scope.answer_message = iStorageMemory.get('question-answered-' + $scope.q.id); if (!$scope.answer_message) { $scope.answer_message = question.is_answered ? 'You answered' : ' You did not answer'; } layout.focus($location.search().focus); }, function (error) { $scope.alert(error, function () { $scope.loading = false; }, 'Error', 'OK'); }); $scope.current = null; $scope.data = { comment: '', privacy: 0 }; $scope.selectOption = function (option) { if (option) { $scope.data.option_id = option.id; $scope.current = option; } else { $scope.data.option_id = null; $scope.current = null; } }; $scope.$watch('loading', function(){ if($scope.loading){ $scope.showSpinner(); } else if($scope.loading === false) { $scope.hideSpinner(); } }); }).controller('question.answer-form',function ($scope, $state, iStorageMemory, homeCtrlParams) { $scope.answer = function () { $scope.showSpinner(); $scope.$parent.q.answer($scope.data).then(function () { homeCtrlParams.loaded = false; $scope.hideSpinner(); if ($scope.q.recipients) { iStorageMemory.put('question-answered-' + $scope.$parent.q.id, 'Your response “' + $scope.$parent.current.title + '” was sent to ' + $scope.$parent.q.recipients); } $state.reload(); }, function () { $scope.hideSpinner(); $state.reload(); }); }; }).controller('question.influences',function ($scope, $stateParams, questions, questionCache, loaded, $rootScope) { $scope.q = questionCache.get($stateParams.id); $rootScope.showSpinner(); questions.loadAnswers($stateParams.id).then(function (answers) { $rootScope.hideSpinner(); $scope.answers = answers; }, function(){ $rootScope.hideSpinner(); }); }).controller('question.news',function ($scope, $location, $stateParams, questions, iJoinFilter, activity, layout) { $scope.showSpinner(); questions.load($stateParams.id).then(function (question) { $scope.hideSpinner(); $scope.q = question; $scope.shareBody = question.subject; $scope.shareImage = question.share_picture; layout.focus($location.search().focus); }, function(){ $scope.hideSpinner(); $scope.back(); }); }).controller('question.leader-petition', function ($scope, $state, $stateParams, questions, iJoinFilter, serverConfig, homeCtrlParams, activity, layout) { $scope.data = { privacy: 0, comment: '' }; activity.setEntityRead({id: Number($stateParams.id), type: 'petition'}); $scope.showSpinner(); questions.load($stateParams.id).then(function (question) { $scope.hideSpinner(); $scope.q = question; $scope.data.option_id = question.options[0].id; $scope.shareTitle = question.petition_title; $scope.shareBody = question.petition_body; $scope.shareLink = serverConfig.shareLink + '/petition/' + question.id; $scope.shareImage = question.share_picture; layout.focus($stateParams.focus); }, function(){ $scope.hideSpinner(); $scope.back(); }); $scope.answer = function () { $scope.showSpinner(); $scope.q.answer($scope.data).then(function () { homeCtrlParams.loaded = false; $state.reload(); }, function () { $state.reload(); }); }; $scope.unsign = function () { $scope.showSpinner(); questions.unsignFromPetition($scope.q.id, $scope.q.options[0].id).then($state.reload, $state.reload); homeCtrlParams.loaded = false; }; });
JavaScript
0
@@ -1751,16 +1751,28 @@ rlParams +, $rootScope ) %7B%0D%0A%0D%0A @@ -1806,25 +1806,29 @@ ) %7B%0D%0A%0D%0A $ -s +rootS cope.showSpi @@ -2237,33 +2237,37 @@ on () %7B%0D%0A $ -s +rootS cope.hideSpinner
1fd27dae5e498efb5a12e5eb6350540b25c48696
Fix crash on RC while toggling object status.
Libraries/Components/SwitchAndroid/SwitchAndroid.android.js
Libraries/Components/SwitchAndroid/SwitchAndroid.android.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SwitchAndroid */ 'use strict'; var NativeMethodsMixin = require('NativeMethodsMixin'); var PropTypes = require('ReactPropTypes'); var React = require('React'); var requireNativeComponent = require('requireNativeComponent'); var SWITCH = 'switch'; /** * Standard Android two-state toggle component */ var SwitchAndroid = React.createClass({ mixins: [NativeMethodsMixin], propTypes: { /** * Boolean value of the switch. */ value: PropTypes.bool, /** * If `true`, this component can't be interacted with. */ disabled: PropTypes.bool, /** * Invoked with the new value when the value chages. */ onValueChange: PropTypes.func, /** * Used to locate this view in end-to-end tests. */ testID: PropTypes.string, }, getDefaultProps: function() { return { value: false, disabled: false, }; }, _onChange: function(event) { this.props.onChange && this.props.onChange(event); this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value); // The underlying switch might have changed, but we're controlled, // and so want to ensure it represents our value. this.refs[SWITCH].setNativeProps({on: this.props.value}); }, render: function() { return ( <RKSwitch ref={SWITCH} style={this.props.style} enabled={!this.props.disabled} on={this.props.value} onChange={this._onChange} testID={this.props.testID} onStartShouldSetResponder={() => true} onResponderTerminationRequest={() => false} /> ); } }); var RKSwitch = requireNativeComponent('AndroidSwitch', null); module.exports = SwitchAndroid;
JavaScript
0
@@ -1248,147 +1248,8 @@ ) %7B%0A - this.props.onChange && this.props.onChange(event);%0A this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value);%0A%0A @@ -1430,16 +1430,255 @@ value%7D); +%0A%0A if (this.props.value === event.nativeEvent.value %7C%7C this.props.disabled) %7B%0A return;%0A %7D%0A%0A this.props.onChange && this.props.onChange(event);%0A this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value); %0A %7D,%0A%0A
5097a7af2b23a89aaf0c8c066c7cd3888badbaba
Fix for https://github.com/aldeed/meteor-autoform-select2/issues/3 Update form not displaying values for 'multiple=true' field
autoform-select2.js
autoform-select2.js
AutoForm.addInputType("select2", { template: "afSelect2", valueOut: function () { return this.select2("val"); }, valueConverters: { "number": AutoForm.Utility.stringToNumber, "numberArray": function (val) { if (isArray(val)) { return _.map(val, function (item) { item = $.trim(item); return AutoForm.Utility.stringToNumber(item); }); } return val; }, "boolean": AutoForm.Utility.stringToBool, "booleanArray": function (val) { if (isArray(val)) { return _.map(val, function (item) { item = $.trim(item); return AutoForm.Utility.stringToBool(item); }); } return val; }, "date": AutoForm.Utility.stringToDate, "dateArray": function (val) { if (isArray(val)) { return _.map(val, function (item) { item = $.trim(item); return AutoForm.Utility.stringToDate(item); }); } return val; } }, contextAdjust: function (context) { //can fix issues with some browsers selecting the firstOption instead of the selected option context.atts.autocomplete = "off"; var itemAtts = _.omit(context.atts, 'firstOption'); var firstOption = context.atts.firstOption; // build items list context.items = []; // If a firstOption was provided, add that to the items list first if (firstOption !== false) { context.items.push({ name: context.name, label: (typeof firstOption === "string" ? firstOption : "(Select One)"), value: "", // _id must be included because it is a special property that // #each uses to track unique list items when adding and removing them // See https://github.com/meteor/meteor/issues/2174 _id: "", selected: false, atts: itemAtts }); } // Add all defined options _.each(context.selectOptions, function(opt) { context.items.push({ name: context.name, label: opt.label, value: opt.value, // _id must be included because it is a special property that // #each uses to track unique list items when adding and removing them // See https://github.com/meteor/meteor/issues/2174 _id: opt.value, selected: (opt.value === context.value), atts: itemAtts }); }); return context; } }); Template.afSelect2.helpers({ optionAtts: function afSelectOptionAtts() { var item = this var atts = { value: item.value }; if (item.selected) { atts.selected = ""; } return atts; } }); Template.afSelect2.rendered = function () { // instanciate select2 this.$('select').select2(this.data.atts.select2Options || {}); }; Template.afSelect2.destroyed = function () { this.$('select').select2('destroy'); }; isArray = Array.isArray || function(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; };
JavaScript
0.000001
@@ -2305,16 +2305,120 @@ ected: ( +_.isArray(context.value) ?%0A _.contains(context.value, opt.value) :%0A opt.valu
02c0949ee393140e61c667952c173c5b71c3e4f8
Remove decorators plugin
config/babel-preset.js
config/babel-preset.js
module.exports = { presets: [ [ 'env', { modules: false, useBuiltIns: true, }, ], 'react', ], plugins: [ 'transform-decorators-legacy', 'transform-class-properties', ['transform-object-rest-spread', { useBuiltIns: true }], 'syntax-dynamic-import', ], };
JavaScript
0
@@ -154,43 +154,8 @@ : %5B%0A - 'transform-decorators-legacy',%0A
7cb26bfabd5e67ec161fa06eba37ee22b90e0763
remove incomplete reply delete
lib/site/topic-layout/topic-article/comments/list/replies/list/component.js
lib/site/topic-layout/topic-article/comments/list/replies/list/component.js
import React, {Component} from 'react' import t from 't-component' import Timeago from 'lib/site/timeago' export default function RepliesList (props) { const replies = props.replies || [] return ( <div className={`replies-list ${replies.length === 0 ? 'no-replies' : ''}`}> { replies.map((item, i) => { return ( <Reply key={i} reply={item} user={props.user} forum={props.forum} /> ) }) } </div> ) } class OptionsTooltip extends Component { constructor (props) { super(props) this.state = OptionsTooltip.getInitialState() } static getInitialState () { return { showTooltip: false, loading: false, error: null } } handleToggleTooltip = () => { this.setState({showTooltip: !this.state.showTooltip}) } handleDelete = () => { this.props.onDelete({id: this.props.id}) } render () { return ( <div className='options' onClick={this.handleToggleTooltip}> <button className='arrow'> <i className='icon-arrow-down' /> </button> { this.state.showTooltip && ( <div className='options-tooltip' disabled={this.state.loading}> <button onClick={this.handleDelete}> {t('comment-card.remove-argument')} </button> </div> ) } </div> ) } } function Reply (props) { const {reply, user} = props const userAttrs = user.state.value || {} const isOwner = userAttrs.id === reply.author.id return ( <article className='replies-list-item' id={`comment-${reply.id}`}> <header className='meta'> <img className='avatar' src={reply.author.avatar} alt={reply.author.fullName} /> <h3 className='name'>{reply.author.displayName}</h3> <div className='created-at'> <Timeago date={reply.createdAt} /> </div> { (isOwner || forum.privileges.canEdit) && <OptionsTooltip id={reply.id} onDelete={props.onDelete} commentDeleting={props.commentDeleting} /> } </header> <div className='text' dangerouslySetInnerHTML={{__html: reply.textHtml}} /> </article> ) }
JavaScript
0.000001
@@ -9,60 +9,19 @@ eact -, %7BComponent%7D from 'react'%0Aimport t from 't-componen + from 'reac t'%0Ai @@ -494,1000 +494,8 @@ %0A%7D%0A%0A -%0Aclass OptionsTooltip extends Component %7B%0A constructor (props) %7B%0A super(props)%0A%0A this.state = OptionsTooltip.getInitialState()%0A %7D%0A%0A static getInitialState () %7B%0A return %7B%0A showTooltip: false,%0A loading: false,%0A error: null%0A %7D%0A %7D%0A%0A handleToggleTooltip = () =%3E %7B%0A this.setState(%7BshowTooltip: !this.state.showTooltip%7D)%0A %7D%0A%0A handleDelete = () =%3E %7B%0A this.props.onDelete(%7Bid: this.props.id%7D)%0A %7D%0A%0A render () %7B%0A return (%0A %3Cdiv%0A className='options'%0A onClick=%7Bthis.handleToggleTooltip%7D%3E%0A %3Cbutton className='arrow'%3E%0A %3Ci className='icon-arrow-down' /%3E%0A %3C/button%3E%0A %7B%0A this.state.showTooltip &&%0A (%0A %3Cdiv%0A className='options-tooltip'%0A disabled=%7Bthis.state.loading%7D%3E%0A %3Cbutton onClick=%7Bthis.handleDelete%7D%3E%0A %7Bt('comment-card.remove-argument')%7D%0A %3C/button%3E%0A %3C/div%3E%0A )%0A %7D%0A %3C/div%3E%0A )%0A %7D%0A%7D%0A%0A func @@ -533,14 +533,8 @@ eply -, user %7D = @@ -542,102 +542,8 @@ rops -%0A const userAttrs = user.state.value %7C%7C %7B%7D%0A const isOwner = userAttrs.id === reply.author.id %0A%0A @@ -935,232 +935,8 @@ iv%3E%0A - %7B%0A (isOwner %7C%7C forum.privileges.canEdit) &&%0A %3COptionsTooltip%0A id=%7Breply.id%7D%0A onDelete=%7Bprops.onDelete%7D%0A commentDeleting=%7Bprops.commentDeleting%7D /%3E%0A %7D%0A
168bb213da64201dca96d8aefcd0b836c0c43bc8
fix ctrl-home and end keys being reversed.
plugins/movement.js
plugins/movement.js
module.exports = function (doc, keys, cursor) { var rc = this.config keys.on('keypress', function (ch, key) { if(!key.ctrl) { if(key.name == 'up' ) (doc.isFirstLine() ? doc.start() : doc.up()).move() if(key.name == 'down' ) (doc.isLastLine() ? doc.end() : doc.down()).move() if(key.name == 'left' ) ((doc.isFirst() && !doc.isFirstLine() ? doc.up().end() : doc.left())).move() if(key.name == 'right') ((doc.isLast() && !doc.isLastLine() ? doc.down().start() : doc.right())).move() if(key.name == 'end') doc.end().move() if(key.name == 'home') doc.start().move() } else if ( key.ctrl ) { if(key.name == 'left' ) { //go to start of previous word doc.prev().move() } if(key.name == 'right') { //go to end of next word doc.next().move() } //start of the previous non whitespace line. if(key.name == 'up') doc.prevSection().start().move() //start of the previous non whitespace line. if(key.name == 'down') { if(doc.isLastLine()) doc.end() else doc.nextSection().start() doc.move() } if(key.name == 'end') doc.firstLine().start().move() if(key.name == 'home') doc.lastLine().end().move() } if(key.name == 'pageup') { doc.row = Math.max(doc.row - rc.page, 0) doc.move() } if(key.name == 'pagedown') { doc.row = Math.min(doc.row + rc.page, doc.lines.length - 1) doc.move() } }) }
JavaScript
0
@@ -1243,27 +1243,28 @@ ey.name == ' -end +home ') doc.first @@ -1303,28 +1303,27 @@ ey.name == ' -home +end ') doc.lastL
84781e527ba9fffd28126b0fe77ed38123244aa9
Add debug to prod settings
config/prodSettings.js
config/prodSettings.js
module.exports = { port: 3000, canvas: { apiUrl: 'https://kth.instructure.com/api/v1' }, logging: { log: { level: 'info', src: false }, stdout: { enabled: true }, console: { enabled: false } }, ldap: { client: { url: 'ldaps://ldap.ug.kth.se', timeout: 300000, connectTimeout: 3000, maxConnections: 10, idleTimeout: 300000, checkInterval: 10000, reconnect: true } }, azure: { queueName: 'ug-canvas', csvBlobName: 'lms-csv-prod', msgBlobName: 'lms-msg-prod' }, localFile: { csvDir: '/tmp/' } }
JavaScript
0.000001
@@ -141,12 +141,13 @@ l: ' -info +debug ',%0D%0A
96ef6e25b022245276627b0705b1e1cc7f84f8df
refactor utils/Request
unit/Request.js
unit/Request.js
'use strict'; var Ask = /** @type Ask */ require('../util/Ask'); var Unit = /** @type Unit */ require('./Unit'); var asker = require('asker'); /** * @class Request * @extends Unit * */ var Request = Unit.extend(/** @lends Request.prototype */ { /** * @protected * @memberOf {Request} * @method * * @param {Connect} track * @param {Object} errors * @param {Object} result * @param {Function} done * * @returns {Ask} * */ _createAsk: function (track, errors, result, done) { return new Ask(track, errors, result, done); }, /** * @public * @memberOf {Request} * @method * * @param {Connect} track * @param {Object} errors * @param {Object} result * @param {Function} done * */ data: function (track, errors, result, done) { var ask = this._createAsk(track, errors, result, done.bind(this)); this._options(ask); ask.next(function (res, done) { ask.opts = res; done(null, res); }, function (err) { ask.opts = err; track.agent.emitEvent('sys:req:eoptions', ask); this._onEOPTIONS(ask); }, this); this._setup(ask); ask.next(function (res, done) { track.agent.emit('sys:req:request', ask); done(null, res); }, function (err) { ask.opts = err; track.agent.emit('sys:req:esetup', ask); this._onESETUP(ask); }, this); // там выполнился реквест this._request(ask); ask.next(function (res, done) { ask.data = res; done(null, res); }, function (err) { ask.data = err; track.agent.emitEvent('sys:req:erequest', ask); this._onEREQUEST(ask); }, this); this._parse(ask); ask.next(function (res, done) { ask.data.data = res; done(null, ask.data); }, function (err) { ask.data = err; track.agent.emitEvent('sys:req:erequest', ask); this._onEREQUEST(ask); }, this); ask.next(function (res, done) { track.agent.emitEvent('sys:req:success', ask); done(null, res); }, this); this._template(ask); ask.next(function (res) { ask.done(null, res); }, function (err) { ask.done(err); }); }, /** * @protected * @memberOf {Request} * @method * * @param {Ask} ask * */ _setup: function (ask) { /*eslint no-unused-vars: 0*/ }, /** * @protected * @memberOf {Request} * @method * * @param {Ask} ask * */ _request: function (ask) { ask.next(function (opts, done) { asker(opts, function (err, res) { if ( err ) { done(err); } else { done(null, res); } }); }); }, /** * @protected * @memberOf {Request} * @method * * @param {Object} ask * */ _onEOPTIONS: function (ask) { ask.done(ask.opts); }, /** * @protected * @memberOf {Request} * @method * * @param {Object} ask * */ _onEREQUEST: function (ask) { ask.done(ask.data); }, /** * @protected * @memberOf {Request} * @method * * @param {Object} ask * */ _onESETUP: function (ask) { ask.done(ask.opts); }, /** * @protected * @memberOf {Request} * @method * * @param {Ask} ask * */ _options: function (ask) { ask.next(function (res, done) { done(null, { port: 80, path: '/', method: 'GET', protocol: 'http:' }); }); }, /** * @protected * @memberOf {Request} * @method * * @param {Object} ask * */ _parse: function (ask) { ask.next(function (res, done) { try { done(null, JSON.parse(res.data)); } catch (err) { done(err); } }); }, /** * @protected * @memberOf {Request} * @method * * @param {Object} ask * */ _template: function (ask) { ask.next(function (res, done) { done(null, res); }); } }); module.exports = Request;
JavaScript
0.000001
@@ -1017,32 +1017,91 @@ ask.opts = res;%0A + track.agent.emitEvent('sys:req:options', ask);%0A done @@ -1105,32 +1105,32 @@ one(null, res);%0A - %7D, funct @@ -1388,23 +1388,21 @@ sys:req: -request +setup ', ask); @@ -1596,43 +1596,8 @@ );%0A%0A - // %D1%82%D0%B0%D0%BC %D0%B2%D1%8B%D0%BF%D0%BE%D0%BB%D0%BD%D0%B8%D0%BB%D1%81%D1%8F %D1%80%D0%B5%D0%BA%D0%B2%D0%B5%D1%81%D1%82%0A @@ -1681,32 +1681,92 @@ ask.data = res;%0A + track.agent.emitEvent('sys:req:response', ask);%0A done @@ -2040,32 +2040,89 @@ ata.data = res;%0A + track.agent.emitEvent('sys:req:parse', ask);%0A done @@ -2231,39 +2231,37 @@ Event('sys:req:e -request +parse ', ask);%0A @@ -2278,166 +2278,17 @@ _onE -REQUEST(ask);%0A %7D, this);%0A%0A ask.next(function (res, done) %7B%0A track.agent.emitEvent('sys:req:success', ask);%0A done(null, res +PARSE(ask );%0A @@ -3563,32 +3563,32 @@ unction (ask) %7B%0A - ask.done @@ -3599,32 +3599,212 @@ .opts);%0A %7D,%0A%0A + /**%0A * @protected%0A * @memberOf %7BRequest%7D%0A * @method%0A *%0A * @param %7BObject%7D ask%0A * */%0A _onEPARSE: function (ask) %7B%0A ask.done(ask.data);%0A %7D,%0A%0A /**%0A * @
d8cfaa291f6823597019540acc44d724eed3de59
fix path normalisation
tasks/lib/command-builder.js
tasks/lib/command-builder.js
var p = require('path'), buildPath = function(options){ var sep = p.sep, share = options.share, platform = process.platform, credentials = (platform === 'darwin' ? options.username + ":" + options.password + "@" : ""), bits; // allow the user to specify any kind of path: /path/to/share or \path\to\share if(share.folder.indexOf('/') > 0){ bits = share.folder.split('/'); } else { bits = share.folder.split('\\'); } return sep + sep + p.normalize([ credentials + share.host, bits ].join(sep)); }; module.exports.mount = function(options){ var command = { darwin:[ "mount", "-t " + options['*nix'].fileSystem, buildPath(options), options['*nix'].mountPoint ], linux: [ "mount", "-t " + options['*nix'].fileSystem, buildPath(options), options['*nix'].mountPoint, options.username ? "-o user=" + options.username + ",pass=" + options.password : "" ], win32: [ "net use", options.windows.driveLetter + ":", buildPath(options), options.password ? options.password : "", options.username ? "/user:" + options.username : "" ], // Todo: sunos: [], freebsd: [] }; return command[process.platform]; }; module.exports.unmount = function(options){ var command = { darwin:[ "umount", options['*nix'].mountPoint ], linux: [ "umount", options['*nix'].mountPoint ], win32: [ "net use", options.windows.driveLetter, "/delete" ], // Todo: sunos: [], freebsd: [] }; return command[process.platform]; };
JavaScript
0.000003
@@ -380,9 +380,10 @@ ) %3E -0 +-1 )%7B%0A @@ -569,16 +569,26 @@ bits +.join(sep) %0A %5D.j
38d0ab2fc1ae9901eab82c9a2374062211f8811b
Fix the hasAccount check to work properly on both android and iOS
www/js/control/emailService.js
www/js/control/emailService.js
'use strict'; angular.module('emission.services.email', ['emission.plugin.logger']) .service('EmailHelper', function ($window, $translate, $http, Logger) { const getEmailConfig = function () { return new Promise(function (resolve, reject) { window.Logger.log(window.Logger.LEVEL_INFO, "About to get email config"); var address = []; $http.get("json/emailConfig.json").then(function (emailConfig) { window.Logger.log(window.Logger.LEVEL_DEBUG, "emailConfigString = " + JSON.stringify(emailConfig.data)); address.push(emailConfig.data.address) resolve(address); }).catch(function (err) { $http.get("json/emailConfig.json.sample").then(function (emailConfig) { window.Logger.log(window.Logger.LEVEL_DEBUG, "default emailConfigString = " + JSON.stringify(emailConfig.data)); address.push(emailConfig.data.address) resolve(address); }).catch(function (err) { window.Logger.log(window.Logger.LEVEL_ERROR, "Error while reading default email config" + err); reject(err); }); }); }); } const hasAccount = function() { return new Promise(function(resolve, reject) { $window.cordova.plugins.email.hasAccount(function (hasAct) { resolve(hasAct); }); }); } this.sendEmail = function (database) { Promise.all([getEmailConfig(), hasAccount()]).then(function([address, hasAct]) { var parentDir = "unknown"; if (!hasAct) { alert($translate.instant('email-service.email-account-not-configured')); return; } if (ionic.Platform.isAndroid()) { parentDir = "app://databases"; } if (ionic.Platform.isIOS()) { alert($translate.instant('email-service.email-account-mail-app')); parentDir = cordova.file.dataDirectory + "../LocalDatabase"; } if (parentDir == "unknown") { alert("parentDir unexpectedly = " + parentDir + "!") } window.Logger.log(window.Logger.LEVEL_INFO, "Going to email " + database); parentDir = parentDir + "/" + database; /* window.Logger.log(window.Logger.LEVEL_INFO, "Going to export logs to "+parentDir); */ alert($translate.instant('email-service.going-to-email', { parentDir: parentDir })); var email = { to: address, attachments: [ parentDir ], subject: $translate.instant('email-service.email-log.subject-logs'), body: $translate.instant('email-service.email-log.body-please-fill-in-what-is-wrong') } $window.cordova.plugins.email.open(email, function () { Logger.log("email app closed while sending, "+JSON.stringify(email)+" not sure if we should do anything"); // alert($translate.instant('email-service.no-email-address-configured') + err); return; }); }); }; });
JavaScript
0.000001
@@ -1779,36 +1779,1078 @@ known%22;%0A - if ( +%0A // Check this only for ios, since for android, the check always fails unless%0A // the user grants the %22GET_ACCOUNTS%22 dynamic permission%0A // without the permission, we only see the e-mission account which is not valid%0A //%0A // https://developer.android.com/reference/android/accounts/AccountManager#getAccounts()%0A //%0A // Caller targeting API level below Build.VERSION_CODES.O that%0A // have not been granted the Manifest.permission.GET_ACCOUNTS%0A // permission, will only see those accounts managed by%0A // AbstractAccountAuthenticators whose signature matches the%0A // client. %0A // and on android, if the account is not configured, the gmail app will be launched anyway%0A // on iOS, nothing will happen. So we perform the check only on iOS so that we can%0A // generate a reasonably relevant error message%0A%0A if (ionic.Platform.isIOS() && !hasAct)
fec362ab826a8669d921607b77a33594730b0945
Remove "performance hack" for the user matching
www/js/survey/input-matcher.js
www/js/survey/input-matcher.js
'use strict'; angular.module('emission.survey.inputmatcher', ['emission.plugin.logger']) .factory('InputMatcher', function($translate){ var im = {}; var fmtTs = function(ts_in_secs, tz) { return moment(ts_in_secs * 1000).tz(tz).format(); } var printUserInput = function(ui) { return fmtTs(ui.data.start_ts, ui.metadata.time_zone) + "("+ui.data.start_ts + ") -> "+ fmtTs(ui.data.end_ts, ui.metadata.time_zone) + "("+ui.data.end_ts + ")"+ " " + ui.data.label + " logged at "+ ui.metadata.write_ts; } im.getUserInputForTrip = function(trip, nextTrip, userInputList) { // If there is only one item in the list, return it. // This make it compatible when fake list is given (for Enketo Survey). // As well as optimize the performance. if (userInputList === undefined) { Logger.log("In getUserInputForTrip, no user input, returning []"); return undefined; } if (userInputList.length === 1) { return userInputList[0]; } if (userInputList.length < 20) { console.log("Input list = "+userInputList.map(printUserInput)); } // undefined != true, so this covers the label view case as well var isDraft = trip.isDraft == true; var potentialCandidates = userInputList.filter(function(userInput) { /* console.log("startDelta "+userInput.data.label+ "= user("+fmtTs(userInput.data.start_ts, userInput.metadata.time_zone)+ ") - trip("+fmtTs(userInput.data.start_ts, userInput.metadata.time_zone)+") = "+ (userInput.data.start_ts - trip.start_ts)+" should be positive"); console.log("endDelta = "+userInput.data.label+ "user("+fmtTs(userInput.data.end_ts, userInput.metadata.time_zone)+ ") - trip("+fmtTs(trip.end_ts, userInput.metadata.time_zone)+") = "+ (userInput.data.end_ts - trip.end_ts)+" should be negative"); */ // logic described in // https://github.com/e-mission/e-mission-docs/issues/423 if (isDraft) { if (userInputList.length < 20) { var logStr = "Draft trip: comparing user = "+fmtTs(userInput.data.start_ts, userInput.metadata.time_zone) +" -> "+fmtTs(userInput.data.end_ts, userInput.metadata.time_zone) +" trip = "+fmtTs(trip.start_ts, userInput.metadata.time_zone) +" -> "+fmtTs(trip.end_ts, userInput.metadata.time_zone) +" checks are ("+(userInput.data.start_ts >= trip.start_ts) +" && "+(userInput.data.start_ts <= trip.end_ts) +" || "+(-(userInput.data.start_ts - trip.start_ts) <= 15 * 60) +") && "+(userInput.data.end_ts <= trip.end_ts); console.log(logStr); // Logger.log(logStr); } return (userInput.data.start_ts >= trip.start_ts && userInput.data.start_ts <= trip.end_ts || -(userInput.data.start_ts - trip.start_ts) <= 15 * 60) && userInput.data.end_ts <= trip.end_ts; } else { // we know that the trip is cleaned so we can use the fmt_time // but the confirm objects are not necessarily filled out if (userInputList.length < 20) { var logStr = "Cleaned trip: comparing user = " +fmtTs(userInput.data.start_ts, userInput.metadata.time_zone) +" -> "+fmtTs(userInput.data.end_ts, userInput.metadata.time_zone) +" trip = "+trip.start_fmt_time +" -> "+trip.end_fmt_time +" start checks are "+(userInput.data.start_ts >= trip.start_ts) +" && "+(userInput.data.start_ts <= trip.end_ts) +" end checks are "+(userInput.data.end_ts <= trip.end_ts) +" || "+((userInput.data.end_ts - trip.end_ts) <= 15 * 60)+")"; Logger.log(logStr); } // https://github.com/e-mission/e-mission-docs/issues/476#issuecomment-747222181 const startChecks = userInput.data.start_ts >= trip.start_ts && userInput.data.start_ts <= trip.end_ts; var endChecks = (userInput.data.end_ts <= trip.end_ts || (userInput.data.end_ts - trip.end_ts) <= 15 * 60); if (startChecks && !endChecks) { if (angular.isDefined(nextTrip)) { endChecks = userInput.data.end_ts <= nextTrip.start_ts; Logger.log("Second level of end checks when the next trip is defined("+userInput.data.end_ts+" <= "+ nextTrip.start_ts+") = "+endChecks); } else { // next trip is not defined, last trip endChecks = (userInput.data.end_local_dt.day == userInput.data.start_local_dt.day) Logger.log("Second level of end checks for the last trip of the day"); Logger.log("compare "+userInput.data.end_local_dt.day + " with " + userInput.data.start_local_dt.day + " = " + endChecks); } if (endChecks) { // If we have flipped the values, check to see that there // is sufficient overlap const overlapDuration = Math.min(userInput.data.end_ts, trip.end_ts) - Math.max(userInput.data.start_ts, trip.start_ts) Logger.log("Flipped endCheck, overlap("+overlapDuration+ ")/trip("+trip.duration+") = "+ (overlapDuration / trip.duration)); endChecks = (overlapDuration/trip.duration) > 0.5; } } return startChecks && endChecks; } }); if (potentialCandidates.length === 0) { if (userInputList.length < 20) { Logger.log("In getUserInputForTripStartEnd, no potential candidates, returning []"); } return undefined; } if (potentialCandidates.length === 1) { Logger.log("In getUserInputForTripStartEnd, one potential candidate, returning "+ printUserInput(potentialCandidates[0])); return potentialCandidates[0]; } Logger.log("potentialCandidates are "+potentialCandidates.map(printUserInput)); var sortedPC = potentialCandidates.sort(function(pc1, pc2) { return pc2.metadata.write_ts - pc1.metadata.write_ts; }); var mostRecentEntry = sortedPC[0]; Logger.log("Returning mostRecentEntry "+printUserInput(mostRecentEntry)); return mostRecentEntry; } return im; });
JavaScript
0.999981
@@ -607,185 +607,8 @@ ) %7B%0A - // If there is only one item in the list, return it.%0A // This make it compatible when fake list is given (for Enketo Survey).%0A // As well as optimize the performance.%0A @@ -754,83 +754,8 @@ %7D%0A%0A - if (userInputList.length === 1) %7B%0A return userInputList%5B0%5D;%0A %7D%0A