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
0bd90e23bbbf555fcf2ea9f64d423330f0f9467e
Use this context
lib/lock.js
lib/lock.js
var DEFAULT_TIMEOUT = 5000; var DEFAULT_RETRY_DELAY = 100; var DEFAULT_MAX_RETRY = 20; var redis = require('redis'); var Lock = module.exports.Lock = function(key, options) { options = options || {}; this.key = key; this.retries = 0; this.maxRetries = options.maxRetries ? options.maxRetries : DEFAULT_MAX_RETRY; this.retryDelay = options.retryDelay ? options.retryDelay : DEFAULT_RETRY_DELAY; this.timeout = options.timeout ? options.timeout : DEFAULT_TIMEOUT; this.rclient = options.rclient ? options.rclient : redis.createClient(); this._locked = false; this._expire = 0; }; Lock.prototype = { _retry : function(delay, callback) { var self = this; if (self._locked) { return; } if(self.retries > self.maxRetries) { return callback(null, null); } setTimeout(function() { self.acquire(callback); }, delay); this.retries++; }, acquire : function(callback) { var self = this; /* holding own expire; */ this._expire = currentUnixTimestamp() + this.timeout + 1; acquire(this.key, this._expire, this.rclient, function(err, locked) { if(err) { return callback(err, null); } if(locked !== true) { return self._retry(self.retryDelay, callback); } self._locked = true; return callback(null, function(callback) { self.release(callback); }); }); }, release : function(callback) { var cb = callback || noop, self = this; if(this._locked) { /* the job took too long */ if (this._expire < currentUnixTimestamp()) { self._locked = false; return cb(null, true); } release(this.key, this.rclient, function(err, ok) { if(err) { return cb(err, null); } self._locked = false; return cb(null, !!ok); }); } else { cb(new Error('Not own the lock'), null); } } }; var noop = function() { }; var currentUnixTimestamp = function() { /* should be secs here :-D */ return Date.now(); }; var acquire = function(key, expire, rclient, callback) { rclient.setnx(key, expire, function(err, ok) { if(err) { return callback(err, false); } if(ok) { return callback(null, true); } rclient.get(key, function(err, result) { var oldTimeout; if(err) { return callback(err, false); } oldTimeout = parseInt(result, 10); /* wrong data or someone deleted */ if(isNaN(oldTimeout)) { return callback(null, false); } /* not expired; can be problem if multiservers with not sync timestamp */ if(oldTimeout > currentUnixTimestamp()) { return callback(null, false); } /* expired */ rclient.getset(key, expire, function(err, result) { var stillOldTimeout; if(err) { return callback(err, false); } stillOldTimeout = parseInt(result, 10); /* ??? */ if(isNaN(stillOldTimeout)) { return callback(null, false); } /* someone was faster */ if(oldTimeout !== stillOldTimeout) { return callback(null, false); } return callback(null, true); }); }); }); }; var release = function(key, rclient, callback) { rclient.del(key, function(err, result) { if(err) { return callback(err, null); } return callback(null, result); }); };
JavaScript
0.999999
@@ -664,20 +664,20 @@ ;%0A%09%09if ( -self +this ._locked @@ -700,20 +700,20 @@ %09%7D%0A%09%09if( -self +this .retries @@ -715,20 +715,20 @@ tries %3E -self +this .maxRetr
7e0a33033e8bd9c2fdafe97536bfaac3272c0be2
WEBKIT_lose_context becomes WEBGL_EXT_lose_context
js/webgldiagdata.js
js/webgldiagdata.js
/** * @preserve Copyright 2011 Ashima Arts. All rights reserved. * Author: David Sheets; Open source under an MIT-style license. * See https://github.com/ashima/webgl-diagnostic/ for more information. */ if (typeof(window["WebGLDiagnostic"])=="undefined") { WebGLDiagnostic = window["WebGLDiagnostic"] = {}; } // type context_id = string WebGLDiagnostic['context_ids'] = [ "webgl","experimental-webgl","moz-webgl","webkit-3d" ]; // type ext = string WebGLDiagnostic['exts'] = [ "OES_texture_float","OES_texture_half_float","WEBKIT_lose_context", "OES_standard_derivatives","OES_vertex_array_object","WEBGL_debug_renderer_info", "WEBGL_debug_shaders"]; // type 'a label = { label: string; v: 'a } WebGLDiagnostic['drivers'] = { "nvidia":{'label':"NVIDIA", 'v':"http://www.nvidia.com/Download/index.aspx"}, "ati":{'label':"ATI", 'v':"http://support.amd.com/us/gpudownload/Pages/index.aspx"}, "osx":{'label':"Apple", 'v':"https://discussions.apple.com/message/16089832#16089832"} }; // type decision = { // platforms: (string, decision) table option; // plugins: decision label list option; // experimental: decision label option; // upgrade: url option; // download: url option; // trouble: url option; // } // platforms, plugins, experimental cannot self-stack // precedence is platforms>plugins>experimental WebGLDiagnostic['decisions'] = { "Chrome" : { 'trouble': "http://www.google.com/support/chrome/bin/answer.py?answer=1220892", 'download': "http://www.google.com/chrome/", 'upgrade': "http://www.google.com/support/chrome/bin/answer.py?answer=95414" }, "Safari" : { 'platforms': { "iPhone/iPod": { 'trouble': "http://www.apple.com/support/iphone/", 'upgrade': "http://www.apple.com/ios/"}, "iPad": { 'trouble': "http://www.apple.com/support/ipad/", 'upgrade': "http://www.apple.com/ios/"}, "Mac": { 'trouble': "https://discussions.apple.com/message/16065326#16065326", 'download': "http://www.apple.com/safari/", 'upgrade': "http://www.apple.com/safari/"} } }, "Opera" : { 'platforms': { "Windows": { 'experimental': { 'label': "Opera Developer Preview", 'v': { 'trouble': "http://my.opera.com/core/blog/2011/02/28/webgl-and-hardware-acceleration-2", 'download': "http://my.opera.com/core/blog/2011/02/28/webgl-and-hardware-acceleration-2"} } } } }, "Explorer" : { 'plugins': [ { 'label': "Google Chrome Frame", 'v': { 'download': "http://code.google.com/chrome/chromeframe/" } }] }, "Firefox" : { 'trouble': "https://support.mozilla.com/en-US/kb/how-do-i-upgrade-my-graphics-drivers", 'download': "http://www.mozilla.com/en-US/firefox/new/", 'upgrade': "http://www.mozilla.com/en-US/firefox/new/" } }; // type browser = { // id: string auto; (* set to the database key automatically *) // string: string option; (* browser string to search *) // subString: string list option; (* list of keywords to search for *) // name: string; (* human-readable browser name with vendor *) // versionSearch: string option; (* optional version prefix *) // prop: object option; (* alternatively, sniff by checking existence of prop *) // p: int auto (* eval priority (smaller is sooner) defaults to 0 *) // } WebGLDiagnostic['browsers'] = { "Chrome" : { 'string': navigator.userAgent, 'subString': ["Chrome"], 'name': "Google Chrome" }, "OmniWeb" : { 'string': navigator.userAgent, 'subString': ["OmniWeb"], 'versionSearch': "OmniWeb/", 'name': "OmniWeb" }, "Safari" : { 'string': navigator.vendor, 'subString': ["Apple"], 'versionSearch': "Version", 'name': "Apple Safari" }, "Android" : { 'string': navigator.userAgent, 'subString': ["Android"], 'name': "Google Android" }, "Opera" : { 'prop': window.opera, 'name': "Opera" }, "iCab" : { 'string': navigator.vendor, 'subString': ["iCab"], 'name': "iCab" }, "Konqueror" : { 'string': navigator.vendor, 'subString': ["KDE"], 'name': "Konqueror" }, "Camino" : { 'string': navigator.vendor, 'subString': ["Camino"], 'name': "Camino" }, // for newer Netscapes (6+) "Netscape" : { 'string': navigator.userAgent, 'subString': ["Netscape","Navigator"], 'versionSearch': "Netscape", 'name': "Netscape Navigator" }, "Explorer" : { 'string': navigator.userAgent, 'subString': ["MSIE"], 'versionSearch': "MSIE", 'name': "Microsoft Internet Explorer" }, "Firefox" : { 'p': 1, 'string': navigator.userAgent, 'subString': ["Firefox"], 'name': "Mozilla Firefox" }, "Mozilla" : { 'p': 2, 'string': navigator.userAgent, 'subString': ["Gecko"], 'versionSearch': "rv", 'name': "Mozilla Suite" }, // for older Netscapes (4-) "OldNetscape" : { 'p': 3, 'string': navigator.userAgent, 'subString': ["Mozilla"], 'versionSearch': "Mozilla", 'name': "Netscape Navigator" } }; // type platform = { // id: string auto; (* set to the database key automatically *) // string: string option; (* browser string to search *) // subString: string list option; (* list of keywords to search for *) // browsers: string list (* list of browser ids with WebGL on this platform *) // } WebGLDiagnostic['platforms'] = { "Windows" : { 'string': navigator.platform, 'subString': ["Win"], 'browsers': ["Chrome","Firefox"] }, "Mac" : { 'string': navigator.platform, 'subString': ["Mac"], 'browsers': ["Chrome","Firefox","Safari"] }, "iPhone/iPod" : { 'string': navigator.userAgent, 'subString': ["iPhone"], 'browsers': ["Firefox"] }, "iPad" : { 'string': navigator.platform, 'subString': ["iPad"], 'browsers': ["Firefox"] }, "Android" : { 'string': navigator.userAgent, 'subString': ["Android"], 'browsers': ["Firefox"] }, "Linux" : { 'string': navigator.platform, 'subString': ["Linux"], 'browsers': ["Firefox","Chrome"] }, "unknown" : { 'string': navigator.platform, 'subString': [], 'browsers': ["Firefox","Chrome","Safari"] } };
JavaScript
0.999283
@@ -532,10 +532,13 @@ %22WEB -KI +GL_EX T_lo
b2606ae1279f56e28e0229cc0f447ed05912863e
Change log message
lib/lock.js
lib/lock.js
var DEFAULT_TIMEOUT = 5000; var DEFAULT_RETRY_DELAY = 50; var DEFAULT_MAX_RETRY = 10; var redis = require('redis'); var rclient = null; var getRedisClient = function() { if (rclient === null) { rclient = redis.createClient(); } return rclient; }; module.exports.setRedisClient = function(client) { rclient = client; }; var Lock = module.exports.Lock = function(key, options) { options = options || {}; this.key = key; this.retries = 0; this.maxRetries = options.maxRetries ? options.maxRetries : DEFAULT_MAX_RETRY; this.retryDelay = options.retryDelay ? options.retryDelay : DEFAULT_RETRY_DELAY; this.timeout = options.timeout ? options.timeout : DEFAULT_TIMEOUT; this.rclient = options.rclient ? options.rclient : getRedisClient(); this._locked = false; this._expire = 0; }; Lock.prototype = { _retry : function(delay, callback) { var self = this; if (this._locked) { return; } if(this.retries >= this.maxRetries) { return callback(null, null); } setTimeout(function() { self.acquire(callback); }, delay); this.retries++; }, acquire : function(callback) { var self = this; acquire(this.key, this.timeout, this.rclient, function(err, expire) { if(err) { return callback(err, null); } if(expire === false) { return self._retry(self.retryDelay, callback); } /* holding own expire; */ self._expire = expire; self._locked = true; return callback(null, function(callback) { self.release(callback); }); }); }, release : function(callback) { var cb = callback || noop, self = this; if(this._locked) { /* the job took too long */ if (this._expire < currentUnixTimestamp()) { self._locked = false; console.warn('Try to release expired lock "' + this.key + '"! consider increase timeout for this job?'); return cb(null, true); } release(this.key, this.rclient, function(err, ok) { if(err) { return cb(err, null); } self._locked = false; return cb(null, !!ok); }); } else { console.warn('Release not owned lock "' + this.key + '"'); cb(new Error('Not owning the lock'), null); } } }; var noop = function() { }; var currentUnixTimestamp = function() { /* should be secs here :-D */ return Date.now(); }; var acquire = function(key, timeout, rclient, callback) { var expire = currentUnixTimestamp() + timeout + 1; rclient.setnx(key, expire, function(err, ok) { if(err) { return callback(err, false); } if(ok) { return callback(null, expire); } rclient.get(key, function(err, result) { var oldTimeout; if(err) { return callback(err, false); } oldTimeout = parseInt(result, 10); /* wrong data or someone deleted */ if(isNaN(oldTimeout)) { return callback(null, false); } /* not expired; can be problem if multiservers with not sync timestamp */ if(oldTimeout > currentUnixTimestamp()) { return callback(null, false); } /* expired */ expire = currentUnixTimestamp() + timeout + 1; rclient.getset(key, expire, function(err, result) { var stillOldTimeout; if(err) { return callback(err, false); } stillOldTimeout = parseInt(result, 10); /* ??? */ if(isNaN(stillOldTimeout)) { return callback(null, false); } /* someone was faster */ if(oldTimeout !== stillOldTimeout) { return callback(null, false); } return callback(null, expire); }); }); }); }; var release = function(key, rclient, callback) { rclient.del(key, function(err, result) { if(err) { return callback(err, null); } return callback(null, result); }); };
JavaScript
0.000001
@@ -2025,25 +2025,22 @@ rn(' -Release not owned +Try to release loc @@ -2059,16 +2059,36 @@ key + '%22 + which is not owning ');%0A%09%09%09c
b06fb194576954e52e59b2e798e0eb79dc6105c8
Use import instead of require
lib/main.js
lib/main.js
/** @babel */ const {Disposable, CompositeDisposable} = require('atom') const ViewURI = 'atom://deprecation-cop' let DeprecationCopView class DeprecationCopPackage { activate () { this.disposables = new CompositeDisposable() this.disposables.add(atom.workspace.addOpener((uri) => { if (uri === ViewURI) { return this.deserializeDeprecationCopView({uri}) } })) this.disposables.add(atom.commands.add('atom-workspace', 'deprecation-cop:view', () => { atom.workspace.open(ViewURI) })) } deactivate () { this.disposables.dispose() const pane = atom.workspace.paneForURI(ViewURI) if (pane) { pane.destroyItem(pane.itemForURI(ViewURI)) } } deserializeDeprecationCopView (state) { if (!DeprecationCopView) { DeprecationCopView = require('./deprecation-cop-view') } return new DeprecationCopView(state) } consumeStatusBar (statusBar) { const DeprecationCopStatusBarView = require('./deprecation-cop-status-bar-view') const statusBarView = new DeprecationCopStatusBarView() const statusBarTile = statusBar.addRightTile({item: statusBarView, priority: 150}) this.disposables.add(new Disposable(() => { statusBarView.destroy() })) this.disposables.add(new Disposable(() => { statusBarTile.destroy() })) } } const instance = new DeprecationCopPackage() export default instance
JavaScript
0
@@ -8,20 +8,21 @@ bel */%0A%0A -cons +impor t %7BDispo @@ -53,25 +53,20 @@ le%7D -= require( +from 'atom' -) +%0A %0Acon
870bfb0d51fa0a5ef96419d8f90c876c7ad3ffb4
Add semicolon
corehq/apps/commtrack/static/commtrack/ko/locations.js
corehq/apps/commtrack/static/commtrack/ko/locations.js
$(function() { var model = new LocationSettingsViewModel(); $('#settings').submit(function() { return model.presubmit(); }); model.load(settings); ko.applyBindings(model, $('#settings').get(0)); }); function LocationSettingsViewModel() { this.loc_types = ko.observableArray(); this.json_payload = ko.observable(); this.loc_types_error = ko.observable(false); this.load = function(data) { this.loc_types($.map(data.loc_types, function(e) { return new LocationTypeModel(e); })); }; this.loc_type_options = function(loc_type) { return this.loc_types().filter(function(type) { return type.name !== loc_type.name }); }; var settings = this; this.remove_loctype = function(loc_type) { settings.loc_types.remove(loc_type); }; this.new_loctype = function() { var new_loctype = new LocationTypeModel({}, this); new_loctype.onBind = function() { var $inp = $(this.$e).find('.loctype_name'); $inp.focus(); setTimeout(function() { $inp.select(); }, 0); }; settings.loc_types.push(new_loctype); }; this.validate = function() { this.loc_types_error(false); var that = this; var valid = true; $.each(this.loc_types(), function(i, e) { if (!e.validate()) { valid = false; } }); var top_level_loc = false; $.each(this.loc_types(), function(i, e) { if (!e.parent_type()) { top_level_loc = true; } }); if (this.loc_types().length && !top_level_loc) { this.loc_types_error(true); valid = false; } if (this.has_cycles()) { this.loc_types_error(true); valid = false; } return valid; }; this.has_cycles = function() { var loc_type_parents = {}; $.each(this.loc_types(), function(i, loc_type) { loc_type_parents[loc_type.pk] = loc_type.parent_type(); }); var already_visited = function(lt, visited) { if (visited.indexOf(lt) !== -1) { return true; } else if (!loc_type_parents[lt]) { return false; } else { visited.push(lt); return already_visited(loc_type_parents[lt], visited); } }; for (var i = 0; i < this.loc_types().length; i++) { var visited = []; loc_type = this.loc_types()[i].pk; if (already_visited(loc_type, visited)) { return true; } } }; this.presubmit = function() { if (!this.validate()) { return false; } payload = this.to_json(); this.json_payload(JSON.stringify(payload)); }; this.to_json = function() { return { loc_types: $.map(this.loc_types(), function(e) { return e.to_json(); }), }; }; } // Make a fake pk to refer to this location type even if the name changes var get_fake_pk = function () { var counter = 0; return function() { counter ++; return "fake-pk-" + counter; }; }(); function LocationTypeModel(data, root) { var name = data.name || ''; var self = this; this.pk = data.pk || get_fake_pk(); this.name = ko.observable(name); this.parent_type = ko.observable(data.parent_type); this.tracks_stock = ko.observable(!data.administrative); this.shares_cases = ko.observable(data.shares_cases); this.view_descendants = ko.observable(data.view_descendants); this.name_error = ko.observable(false); this.validate = function() { this.name_error(false); if (!this.name()) { this.name_error(true); return false; } return true; }; this.to_json = function() { return { pk: this.pk, name: this.name(), parent_type: this.parent_type() || null, administrative: !this.tracks_stock(), shares_cases: this.shares_cases() === true, view_descendants: this.view_descendants() === true }; }; } // TODO move to shared library ko.bindingHandlers.bind_element = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var field = valueAccessor() || '$e'; if (viewModel[field]) { console.log('warning: element already bound'); return; } viewModel[field] = element; if (viewModel.onBind) { viewModel.onBind(bindingContext); } } };
JavaScript
0.999999
@@ -707,16 +707,17 @@ ype.name +; %0A
237289320d622da35b2abb857642bcd38074e10f
Remove need for bind()
js/theme.js
js/theme.js
var jQuery = (typeof(window) != 'undefined') ? window.jQuery : require('jquery'); // Sphinx theme nav state function ThemeNav () { var nav = { navBar: null, win: null, winScroll: false, winResize: false, linkScroll: false, winPosition: 0, winHeight: null, docHeight: null, isRunning: false }; nav.enable = function () { var self = this; if (!self.isRunning) { self.isRunning = true; jQuery(function ($) { self.init($); self.reset(); self.win.on('hashchange', self.reset); // Set scroll monitor self.win.on('scroll', function () { if (!self.linkScroll) { if (!self.winScroll) { self.winScroll = true; requestAnimationFrame(self.onScroll.bind(self)); } } }); // Set resize monitor self.win.on('resize', function () { if (!self.winResize) { self.winResize = true; requestAnimationFrame(self.onResize.bind(self)); } }); self.onResize(); }); }; }; nav.init = function ($) { var doc = $(document), self = this; this.navBar = $('div.wy-side-scroll:first'); this.win = $(window); // Set up javascript UX bits $(document) // Shift nav in mobile when clicking the menu. .on('click', "[data-toggle='wy-nav-top']", function() { $("[data-toggle='wy-nav-shift']").toggleClass("shift"); $("[data-toggle='rst-versions']").toggleClass("shift"); }) // Nav menu link click operations .on('click', ".wy-menu-vertical .current ul li a", function() { var target = $(this); // Close menu when you click a link. $("[data-toggle='wy-nav-shift']").removeClass("shift"); $("[data-toggle='rst-versions']").toggleClass("shift"); // Handle dynamic display of l3 and l4 nav lists self.toggleCurrent(target); self.hashChange(); }) .on('click', "[data-toggle='rst-current-version']", function() { $("[data-toggle='rst-versions']").toggleClass("shift-up"); }) // Make tables responsive $("table.docutils:not(.field-list)") .wrap("<div class='wy-table-responsive'></div>"); // Add expand links to all parents of nested ul $('.wy-menu-vertical ul').not('.simple').siblings('a').each(function () { var link = $(this); expand = $('<span class="toctree-expand"></span>'); expand.on('click', function (ev) { self.toggleCurrent(link); ev.stopPropagation(); return false; }); link.prepend(expand); }); }; nav.reset = function () { // Get anchor from URL and open up nested nav var anchor = encodeURI(window.location.hash); if (anchor) { try { var link = $('.wy-menu-vertical') .find('[href="' + anchor + '"]'); // If we didn't find a link, it may be because we clicked on // something that is not in the sidebar (eg: when using // sphinxcontrib.httpdomain it generates headerlinks but those // aren't picked up and placed in the toctree). So let's find // the closest header in the document and try with that one. if (link.length === 0) { var doc_link = $('.document a[href="' + anchor + '"]'); var closest_section = doc_link.closest('div.section'); // Try again with the closest section entry. link = $('.wy-menu-vertical') .find('[href="#' + closest_section.attr("id") + '"]'); } // If we found a matching link then reset current and re-apply // otherwise retain the existing match if (link.length > 0) { $('.wy-menu-vertical li.toctree-l1 li.current').removeClass('current'); link.closest('li.toctree-l2').addClass('current'); link.closest('li.toctree-l3').addClass('current'); link.closest('li.toctree-l4').addClass('current'); } } catch (err) { console.log("Error expanding nav for anchor", err); } } }; nav.onScroll = function () { this.winScroll = false; var newWinPosition = this.win.scrollTop(), winBottom = newWinPosition + this.winHeight, navPosition = this.navBar.scrollTop(), newNavPosition = navPosition + (newWinPosition - this.winPosition); if (newWinPosition < 0 || winBottom > this.docHeight) { return; } this.navBar.scrollTop(newNavPosition); this.winPosition = newWinPosition; }; nav.onResize = function () { this.winResize = false; this.winHeight = this.win.height(); this.docHeight = $(document).height(); }; nav.hashChange = function () { this.linkScroll = true; this.win.one('hashchange', function () { this.linkScroll = false; }); }; nav.toggleCurrent = function (elem) { var parent_li = elem.closest('li'); parent_li.siblings('li.current').removeClass('current'); parent_li.siblings().find('li.current').removeClass('current'); parent_li.find('> ul li.current').removeClass('current'); parent_li.toggleClass('current'); } return nav; }; module.exports.ThemeNav = ThemeNav(); if (typeof(window) != 'undefined') { window.SphinxRtdTheme = { StickyNav: module.exports.ThemeNav }; }
JavaScript
0.000001
@@ -921,24 +921,37 @@ mationFrame( +function() %7B self.onScrol @@ -951,27 +951,21 @@ onScroll -.bind(self) +(); %7D );%0A @@ -1254,16 +1254,29 @@ onFrame( +function() %7B self.onR @@ -1284,19 +1284,13 @@ size -.bind(self) +(); %7D );%0A
eca11db8c03db3f8ad4aff2ba400ce98dac8d883
fix changed usage
lib/message-registry.js
lib/message-registry.js
/* @flow */ import { CompositeDisposable, Emitter } from 'atom' import debounce from 'lodash/debounce' import type { Disposable, TextBuffer } from 'atom' import { messageKey, updateKeys, createKeyMessageMap, flagMessages, mergeArray } from './helpers' import type { MessagesPatch, Message, Linter } from './types' type Linter$Message$Map = { buffer: ?TextBuffer, linter: Linter, changed: boolean, deleted: boolean, messages: Array<Message>, oldMessages: Array<Message>, } class MessageRegistry { emitter: Emitter messages: Array<Message> messagesMap: Set<Linter$Message$Map> subscriptions: CompositeDisposable debouncedUpdate: () => void constructor() { this.emitter = new Emitter() this.messages = [] this.messagesMap = new Set() this.subscriptions = new CompositeDisposable() this.debouncedUpdate = debounce(this.update, 100, { leading: true }) this.subscriptions.add(this.emitter) } set({ messages, linter, buffer }: { messages: Array<Message>, linter: Linter, buffer: TextBuffer }) { // check if the linter has been already set let found = null for (const entry of this.messagesMap) { if (entry.buffer === buffer && entry.linter === linter) { found = entry break } } if (found) { // found linter found.messages = messages found.changed = true } else { // new linter this.messagesMap.add({ messages, linter, buffer, oldMessages: [], changed: true, deleted: false }) } this.debouncedUpdate() } update() { // the final object sent to UI that contains the messages tagged for adding/removeal. messages is all the kept + added messages const result = { added: [], removed: [], messages: [] } // looping over each linter for (const entry of this.messagesMap) { // if linter is deleted // tag the linter's cache for removal and delete it from the map if (entry.deleted) { mergeArray(result.removed, entry.oldMessages) this.messagesMap.delete(entry) continue } if (!entry.changed) { mergeArray(result.messages, entry.oldMessages) continue } entry.changed = false // All the messages of the linter are new, no need to diff // tag the messages for adding and save them to linter's cache if (!entry.oldMessages.length) { // NOTE: No need to add .key here because normalizeMessages already does that mergeArray(result.added, entry.messages) mergeArray(result.messages, entry.messages) entry.oldMessages = entry.messages continue } // The linter has no messages anymore // tag all of its messages from cache for removal and empty the cache if (!entry.messages.length) { mergeArray(result.removed, entry.oldMessages) entry.oldMessages = [] continue } // In all the other situations: // perform diff checking between the linter's new messages and its cache const { oldMessages } = entry // update the key of oldMessages updateKeys(oldMessages) // create a map from keys to oldMessages const keyMessageMap = createKeyMessageMap(oldMessages) // flag messages as oldKept, oldRemoved, newAdded const flaggedMessages = flagMessages(entry.messages, keyMessageMap) // update the result and cache if (flaggedMessages !== null) { const { oldKept, oldRemoved, newAdded } = flaggedMessages mergeArray(result.added, newAdded) mergeArray(result.removed, oldRemoved) const allThisEntry = newAdded.concat(oldKept) mergeArray(result.messages, allThisEntry) entry.oldMessages = allThisEntry // update chache } } // if any messages is removed or added, then update the UI if (result.added.length || result.removed.length) { this.messages = result.messages this.emitter.emit('did-update-messages', result) } } onDidUpdateMessages(callback: (difference: MessagesPatch) => void): Disposable { return this.emitter.on('did-update-messages', callback) } deleteByBuffer(buffer: TextBuffer) { for (const entry of this.messagesMap) { if (entry.buffer === buffer) { entry.deleted = true } } this.debouncedUpdate() } deleteByLinter(linter: Linter) { for (const entry of this.messagesMap) { if (entry.linter === linter) { entry.deleted = true } } this.debouncedUpdate() } dispose() { this.subscriptions.dispose() } } export default MessageRegistry
JavaScript
0
@@ -2074,35 +2074,209 @@ %7D%0A - if (!entry.changed) %7B +%0A // if the linter is not changed%0A // just use its cache (no added/removed and everything is kept) and skip the rest%0A if (!entry.changed) %7B%0A // TODO When this code acutally runs?! %0A @@ -2355,36 +2355,8 @@ %7D -%0A entry.changed = false %0A%0A
ad73dc7079f9bb118a93c1f938476632b7ba7070
Add Y label
client/views/home/activities/trend/trend.js
client/views/home/activities/trend/trend.js
Template.homeResidentActivityLevelTrend.rendered = function () { // Get reference to template instance var instance = this; instance.autorun(function () { // Get reference to Route var router = Router.current(); // Get current Home ID var homeId = router.params.homeId; // Get data for trend line chart var data = ReactiveMethod.call("getHomeActivityCountTrend", homeId); if (data) { MG.data_graphic({ title: "Count of residents per activity level for each of last seven days", description: "Daily count of residents with inactive, semi-active, and active status.", data: data, x_axis: true, y_accessor: ['inactive', 'semiActive', 'active'], interpolate: 'basic', full_width: true, height: 333, right: 49, target: '#trend-chart', legend: ['Inactive','Semi-active','Active'], colors: ['red', 'gold', 'green'], aggregate_rollover: true }); } }); }
JavaScript
0.000005
@@ -661,32 +661,74 @@ x_axis: true,%0A + y_label: %22Number of residents%22,%0A y_acce @@ -964,17 +964,16 @@ tive'%5D,%0A -%0A
b90b9b93af51fa7335eee77eaf2469b81170c39b
Remove index
backend/www/js/index.js
backend/www/js/index.js
$.ajaxSetup({ async: false }); var activeView = 0, loadedViews = []; $.get("http://127.0.0.1:1338/views", function (ajaxViews) { loadedViews = ajaxViews; $('.nav-sidebar').html(""); loadedViews.forEach(function(view, index){ $(".nav-sidebar").append(`<li data-view="` + index + `"><a href="#" onclick="loadData('` + index + `')">` + view.name + `</a></li>`); }); loadData(0); }); function loadData(index) { $('#findTeamNumber').val($('#findTeamNumber')[0].val()); $('#findEvent').val($('#findEvent')[0].val()); if(!index) index = activeView else activeView = index; $("li[data-view]").removeClass("active"); $("li[data-view=" + index + "]").addClass("active"); $(".main").html(""); loadedViews[index].views.forEach(function(rootView){ $.get("http://127.0.0.1:1338/data/" + rootView.name, function (views) { views.forEach(function (view) { var table = `<h3>` + view.name + `</h3>`; table += `<div class="table-responsive"><table class="table table-striped" id="` + rootView.name + `"><thead><tr>`; view.headers.forEach(function (header) { table += "<th>" + header.text + "</th>"; }); table += `</tr></thead><tbody>`; view.data.forEach(function (datum) { table += `<tr>`; view.headers.forEach(function (header) { var val = getDescendantProp(datum, header.value); table += "<td>" + renderTypes(val) + "</td>"; }); table += `</tr>`; }); table += `</tbody></table></div><hr>` $(".main").append(table); $('table#' + rootView.name).DataTable({ "paging": rootView.disablePaging ? !rootView.disablePaging : true, "searching": rootView.disableSearching ? !rootView.disableSearching : true, "info": rootView.disableInfo ? !rootView.disableInfo : true, "search": { "regex": true }, "lengthMenu": rootView.lengthMenu ? rootView.lengthMenu : null, "order": [], "columnDefs": [ { "searchable": true, "targets": 0 }, // Team Number { "searchable": true, /*"visible": false,*/ "targets": 1 }, // Event Key { "searchable": false, "targets": "_all" }, ] }); }); }); }); } $('#findTeamNumber').bind('input', function() { if($(this).val() == "") $.fn.dataTable.tables( { api: true } ) .columns(0) .search("") .draw(); else $.fn.dataTable.tables( { api: true } ) .columns(0) .search("^" + $(this).val() + "$", true, false, true) .draw(); }); $('#findEvent').bind('input', function() { if($(this).val() == "") $.fn.dataTable.tables( { api: true } ) .columns(1) .search("") .draw(); else $.fn.dataTable.tables( { api: true } ) .columns(1) .search("^" + $(this).val() + "$", true, false, true) .draw(); }); /* http://stackoverflow.com/a/8052100 */ function getDescendantProp(obj, desc) { var arr = desc.split("."); while(arr.length && (obj = obj[arr.shift()])); return obj; } /* http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places */ function renderTypes(num) { const numCast = +(Math.round(num + "e+2") + "e-2"); if(!Number.isNaN(numCast)) return numCast; else return num; }
JavaScript
0.000002
@@ -480,19 +480,16 @@ Number') -%5B0%5D .val()); @@ -532,11 +532,8 @@ nt') -%5B0%5D .val
793b8fd71a46245688e685b2eed667e00a165ea8
Update thing.js
js/thing.js
js/thing.js
var meme = 0; function a(){ var meme = 0 }; function d(){ if (meme > 1) { a() }; if (meme == 1) { notyf.confirm('Okay! <a style="color:white;" href="https://discord.gg/PEW4wx9">Click here!</a>') } else { notyf.confirm('I\'m tilda#4778 (if you wanna join the Discord server, click again'); meme++ } } var loadDeferredStyles = function() { var addStylesNode = document.getElementById("deferred-styles"); var replacement = document.createElement("div"); replacement.innerHTML = addStylesNode.textContent; document.body.appendChild(replacement) addStylesNode.parentElement.removeChild(addStylesNode); }; var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame; if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); }); else window.addEventListener('load', loadDeferredStyles); }
JavaScript
0.000001
@@ -952,8 +952,33 @@ les);%0A%7D%0A +%0Avar notyf = new Notyf()%0A
2a734b6b1935b7d245af59e35fc34b12728054ed
Add support for .css files
lib/node-sass-import.js
lib/node-sass-import.js
'use strict'; var path = require('path'); var resolve = require('resolve'); var glob = require('glob'); var pathParse = require('path-parse'); var pathFormat = require('path-format'); var opts = { exts: '.@(sa|c|sc)ss', pfx: '?(_)' }; var buildSassGlob = function (path) { var parsedPath = pathParse(path); if (parsedPath.ext === '' || opts.exts !== parsedPath.ext) { parsedPath.ext = opts.exts; parsedPath.base = opts.pfx + parsedPath.base + opts.exts; parsedPath.name = opts.pfx + parsedPath.name; } return pathFormat(parsedPath); }; var resolver = function (url, baseDir, done) { resolve(url, { basedir: baseDir, extensions: [ '.scss', '.sass', '.css' ], pathFilter: function (pkg, absPath, relativePath) { var globbedPath = buildSassGlob(absPath); var paths = glob.sync(globbedPath); var resolvedPath = paths && paths[0]; if (resolvedPath) { return path.join(path.dirname(relativePath), path.basename(resolvedPath)); } } }, function (err, file) { if (err) throw err; done({ file: file }); }); }; module.exports = function (url, file, done) { var baseDir = path.dirname(file); var fullPath = path.resolve(baseDir, url); var formattedPath = buildSassGlob(fullPath); glob(formattedPath, function (err, urls) { if (err) throw err; if (urls.length === 0) { glob(fullPath, function (err, dirs) { if (err) throw err; if (dirs.length === 0) { resolver(url, baseDir, done); } if (dirs.length === 1) { resolver(dirs[0], baseDir, done); } }); } if (urls.length === 1) { resolver(urls[0], baseDir, done); } if (urls.length > 1) { console.log(urls); throw new Error('Resolve conflicting files'); } }); };
JavaScript
0
@@ -1051,24 +1051,143 @@ throw err;%0A + %0A // Strip the extension so .css gets evaluated properly as .scss%0A file = file.replace(/%5C.(sa%7Csc%7Cc)ss$/, ''); %0A done(%7B
bd24a72877c38527a71c2da32e762ac3971a93a2
Update API url
lib/main.js
lib/main.js
var version = 0.5; var ddp_server = "localhost"; var ddp_port = 3000; var DDPClient = require("ddp"); var debug_mode = false; var Telismo_instance = function(apiKey) { var self = this; var Telismo_DDP = new DDPClient({ host: ddp_server, port: ddp_port, auto_reconnect: true, auto_reconnect_timer: 500, use_ejson: true }); var connected = false; var _opsqueue = []; var api_ok = false; Telismo_DDP.connect(function(error) { if (error) { if(debug_mode) console.log('Cannot connect to Telismo Server!'); return; } Telismo_DDP.call("api/login", [apiKey], function(err,result) { api_ok = true; }); if(debug_mode) console.log('Connected to Telismo Server'); Telismo_DDP.subscribe('api', [], function() { if(debug_mode) console.log('Ready. When you are ready to end the session please use ctrl+c'); }); connected = true; //Run Queued Tasks for(var i = 0; i < _opsqueue.length; i++) { _opsqueue[i](); delete _opsqueue[i]; } }); var _callbacks = []; Telismo_DDP.on('message', function(msg) { var JSONMessage = JSON.parse(msg); if(JSONMessage.msg == "added" && JSONMessage.collection == "calls") { var doc = JSONMessage.fields; doc._id = JSONMessage.id; if(doc._id in _callbacks) { var callback = _callbacks[doc._id]; if(doc.error) { if(callback) callback({errors: doc.error, status: doc.status}); }else{ if(callback) callback(null, doc.output); } } else { if(doc.error) { if(self.callback) self.callback({errors: doc.error, status: doc.status}); }else{ if(self.callback) self.callback(null, doc); } } } }); this._enqueue = function(method) { _opsqueue.push(method); } this._call = function(params, callback) { Telismo_DDP.call("api/new", [apiKey, params], function(err,result) { if(result && result.success == true) { if(result.id instanceof Array) { for(var i = 0; i<result.id.length; i++) { _callbacks[result.id] = callback } }else{ _callbacks[result.id] = callback; } } }); } this.call = function(params, callback) { var queued = function() { self._call(params, callback); } if(connected) { queued(); }else{ self._enqueue(queued); } } this.list = function() { var result = Telismo_DDP.call("api/list", apiKey, params); if(result && result.success == true) { return result; } return []; } this.calls = function() { return CallDocs; } this.callback = function(callData) { } return this; } var Telismo = function(apiKey) { return new Telismo_instance(apiKey); } module.exports = Telismo;
JavaScript
0.000001
@@ -34,17 +34,19 @@ = %22 -localhost +telismo.com %22;%0Av
a0267dcfe11bbae16d85291dc0d267192b632946
use proper config file at runtime
lib/normalize-config.js
lib/normalize-config.js
const vcs = require('./vcs') let config try { config = require(`${process.cwd()}/bbpr.config`) } catch (e) { try { config = require('../bbpr.config') } catch (e) { try { config = require('../config_presets/reset') } catch (e) { config = {} } } } function normalizeConfig (config) { if (!config.organization) config.organization = { name: vcs.getOrganizationName() } if (!config.organization.name) config.organization.name = vcs.getOrganizationName() if (!config.user) config.user = { name: vcs.getUserName(), password: null, cachePwd: false } if (!config.user.name) config.user.name = vcs.getUserName() if (!config.user.password) config.user.password = null if (!config.user.cachePwd) config.user.cachePwd = false if (!config.demo) config.demo = { shouldPrompt: false, shouldPromptDescription: false, basePath: '' } if (!config.demo.shouldPrompt) config.demo.shouldPrompt = false if (!config.demo.shouldPromptDescription) config.demo.shouldPromptDescription = false if (!config.demo.basePath) config.demo.basePath = '' if (!config.reviewers) config.reviewers = { default: [], potential: [] } if (!Array.isArray(config.reviewers.default) && !config.reviewers.default.every((elem) => typeof elem === 'string')) config.reviewers.default = [] if (!Array.isArray(config.reviewers.potential) && !config.reviewers.potential.every((elem) => typeof elem === 'string')) config.reviewers.potential = [] if (!config.branches) config.branches = { source: { close: true }, dest: { default: 'default' } } if (!config.branches.source) config.branches.source = { close: true } if (!config.branches.dest) config.branches.dest = { default: (vcs.vcs === 'git') ? 'master' : 'default' } if (!config.branches.dest.default || typeof config.branches.dest.default !== 'string') config.branches.dest.default = (vcs.vcs === 'git') ? 'master' : 'default' if (!config.globalVars) config.globalVars = { openFileCommand: '' } if (!config.globalVars.openFileCommand) config.globalVars.openFileCommand = '' return config } module.exports = normalizeConfig(config)
JavaScript
0.000001
@@ -67,21 +67,17 @@ (%60$%7B -process.cwd() +__dirname %7D/bb
ad4d16630b126e73347995ea8dd3f136ddd06e38
make the path to pyls executable configurable
lib/main.js
lib/main.js
const { shell } = require("electron") const { AutoLanguageClient } = require("atom-languageclient") const { detectVirtualEnv, detectPipEnv, replacePipEnvPathVar, sanitizeConfig } = require("./utils") import { createDebuggerProvider, activate as debuggerActivate, dispose as debuggerDispose } from "./debugger/main" // Ref: https://github.com/nteract/hydrogen/blob/master/lib/autocomplete-provider.js#L33 // adapted from http://stackoverflow.com/q/5474008 const PYTHON_REGEX = /(([^\d\W]|[\u00A0-\uFFFF])[\w.\u00A0-\uFFFF]*)|\.$/ class PythonLanguageClient extends AutoLanguageClient { getGrammarScopes() { return ["source.python", "python"] } getLanguageName() { return "Python" } getServerName() { return "pyls" } getRootConfigurationKey() { return "ide-python" } activate() { // Remove deprecated option atom.config.unset("ide-python.pylsPath") super.activate() debuggerActivate() } mapConfigurationObject(configuration) { return { pyls: { configurationSources: configuration.pylsConfigurationSources, rope: sanitizeConfig(configuration.rope), plugins: configuration.pylsPlugins, }, } } async startServerProcess(projectPath) { const venvPath = (await detectPipEnv(projectPath)) || (await detectVirtualEnv(projectPath)) const pylsEnvironment = Object.assign({}, process.env) if (venvPath) { pylsEnvironment["VIRTUAL_ENV"] = venvPath } const python = replacePipEnvPathVar(atom.config.get("ide-python.python"), venvPath) const childProcess = super.spawn(python, ["-m", "pyls"], { cwd: projectPath, env: pylsEnvironment, }) return childProcess } onSpawnError(err) { const description = err.code == "ENOENT" ? `No Python interpreter found at \`${python}\`.` : `Could not spawn the Python interpreter \`${python}\`.` atom.notifications.addError("`ide-python` could not launch your Python runtime.", { dismissable: true, description: `${description}<p>If you have Python installed please set "Python Executable" setting correctly. If you do not please install Python.</p>`, }) } onSpawnClose(code, signal) { if (code !== 0 && signal == null) { atom.notifications.addError("Unable to start the Python language server.", { dismissable: true, buttons: [ { text: "Install Instructions", onDidClick: () => atom.workspace.open("atom://config/packages/ide-python"), }, { text: "Download Python", onDidClick: () => shell.openExternal("https://www.python.org/downloads/"), }, ], description: "Make sure to install `pyls` 0.19 or newer by running:\n" + "```\n" + `${python} -m pip install 'python-language-server[all]'\n` + `${python} -m pip install git+https://github.com/tomv564/pyls-mypy.git\n` + "```", }) } } async getSuggestions(request) { if (!PYTHON_REGEX.test(request.prefix)) return null return super.getSuggestions(request) } deactivate() { debuggerDispose() return Promise.race([super.deactivate(), this.createTimeoutPromise(2000)]) } createTimeoutPromise(milliseconds) { return new Promise((resolve, reject) => { let timeout = setTimeout(() => { clearTimeout(timeout) this.logger.error(`Server failed to shutdown in ${milliseconds}ms, forcing termination`) resolve() }, milliseconds) }) } } const pythonClient = new PythonLanguageClient() pythonClient.createDebuggerProvider = createDebuggerProvider // add the debugger module.exports = pythonClient
JavaScript
0
@@ -1550,16 +1550,78 @@ nvPath)%0A + const pyls = atom.config.get(%22ide-python.pyls%22) %7C%7C %22pyls%22%0A cons @@ -1664,22 +1664,20 @@ %5B%22-m%22, -%22 pyls -%22 %5D, %7B%0A @@ -2913,23 +2913,18 @@ python-l -anguage +sp -server%5B
cd21b283ef2844ec65340d8a2faf04d488246a50
Enable browser polyfill
Brocfile.js
Brocfile.js
// This is the Brocfile. It sets up all the assets from the input JS/CSS/images // and so on and converts them to static assets in the output directory or // preview server. var _ = require('underscore'); var babel = require('broccoli-babel-transpiler'); var browserify = require('broccoli-browserify'); var compileSass = require('broccoli-sass'); var funnel = require('broccoli-funnel'); var jade = require('broccoli-jade'); var mergeTrees = require('broccoli-merge-trees'); var templateBuilder = require('broccoli-template-builder'); var sassDir = 'src/stylesheets'; var scripts = 'src/scripts'; // Covert main.scss stylesheet to app.css stylesheet in output directory var styles = compileSass([sassDir], 'main.scss', 'app.css'); // Process all the JavaScript. // First we use babel to convert the ES6 to ES5 for web browsers. scripts = babel(scripts); // Then use browserify to handle any `require` statements and automatically // insert the required library inline. scripts = browserify(scripts, { entries: ['./app.js'], outputFile: 'app.js' }); // Local assets var assets = funnel('src/images', { destDir: 'images' }); // This builds all the Javascript Templates (JST) into JS files where the // templates have been wrapped in functions using underscore's template system. var templates = templateBuilder('src/scripts/templates', { extensions: ['jst'], outputFile: 'templates.js', compile: function(string) { return _.template(string, { variable: "obj" }).source; } }); // Copy external libraries to output directory // Leaflet var leaflet = funnel('node_modules/leaflet/dist', { destDir: 'scripts', files: ['leaflet.js'] }); var leafletStyles = funnel('node_modules/leaflet/dist', { destDir: 'styles', files: ['leaflet.css'] }); var leafletAssets = funnel('node_modules/leaflet/dist/images', { destDir: '/images' }); // Leaflet Marker Cluster var cluster = funnel('node_modules/leaflet.markercluster/dist', { destDir: 'scripts', files: ['leaflet.markercluster.js'] }); var clusterStyles = funnel('node_modules/leaflet.markercluster/dist', { destDir: 'styles', files: ['MarkerCluster.css', 'MarkerCluster.Default.css'] }); // JQuery var jquery = funnel('node_modules/jquery/dist', { destDir: 'scripts', files: ['jquery.min.js', 'jquery.min.map'] }); // JSON2 var json2 = funnel('node_modules/json2/lib/JSON2/static', { destDir: 'scripts', files: ['json2.js'] }); // JQuery DataTables var dataTables = funnel('node_modules/datatables/media/js', { destDir: 'scripts', files: ['jquery.dataTables.min.js'] }); var dataTablesStyles = funnel('node_modules/datatables/media/css', { destDir: 'styles', files: ['jquery.dataTables.min.css'] }); var dataTablesAssets = funnel('node_modules/datatables/media/images', { destDir: 'images', include: ['*.png'] }); // Proj4 var proj4 = funnel('node_modules/proj4/dist', { destDir: 'scripts' }); // Proj4Leaflet var proj4leaflet = funnel('node_modules/proj4leaflet/src', { destDir: 'scripts' }); // PolarMap.js var polarmap = funnel('node_modules/polarmap/dist', { destDir: 'scripts' }); var polarmapStyles = funnel('node_modules/polarmap/css', { destDir: 'styles', files: ['polarmap.css'] }); // Underscore var underscore = funnel('node_modules/underscore', { destDir: 'scripts', files: ['underscore-min.js', 'underscore-min.map'] }); // Backbone var backbone = funnel('node_modules/backbone', { destDir: 'scripts', files: ['backbone-min.js', 'backbone-min.map'] }); // Marionette var marionette = funnel('node_modules/backbone.marionette/lib', { destDir: 'scripts', files: ['backbone.marionette.js', 'backbone.marionette.map'] }); // Bootstrap var bootstrapStyles = funnel('node_modules/bootstrap/dist/css', { destDir: 'styles' }); // Copy Font Awesome files to output directory var faFonts = funnel('node_modules/font-awesome/fonts', { destDir: 'fonts' }); var faStyles = funnel('node_modules/font-awesome/css', { destDir: 'styles' }); var views = jade('src/views'); module.exports = mergeTrees([styles, scripts, views, templates, assets, leaflet, leafletStyles, leafletAssets, cluster, clusterStyles, jquery, json2, dataTables, dataTablesStyles, dataTablesAssets, proj4, proj4leaflet, polarmap, polarmapStyles, underscore, backbone, marionette, bootstrapStyles, faFonts, faStyles], { overwrite: true });
JavaScript
0
@@ -848,16 +848,43 @@ (scripts +, %7B browserPolyfill: true %7D );%0A// Th
30e3c60e86958b4dea4838dd6d86f9a15a58a707
refactor check for spawning food outside of players
lib/open-coordinates.js
lib/open-coordinates.js
function OpenCoordinates(canvasWidth, canvasHeight) { this.canvasWidth = canvasWidth, this.canvasHeight = canvasHeight } OpenCoordinates.prototype = { create: function(players){ var newCoords = { x: Math.floor(Math.random() * (this.canvasWidth - 10) + 5), y: Math.floor(Math.random() * (this.canvasHeight - 10) + 5) }; var isNotInsidePlayer = false; var canWidth = this.canvasWidth; var canHeight = this.canvasHeight; function checkPlayer(player){ var xDiff = newCoords.x - player.x; var yDiff = newCoords.y - player.y; var distance = Math.sqrt( xDiff*xDiff + yDiff*yDiff); return distance > (player.mass + 20); } while(!isNotInsidePlayer){ isNotInsidePlayer = players.every(checkPlayer); if (!isNotInsidePlayer){ newCoords = { x: Math.floor(Math.random() * (canWidth - 10) + 5), y: Math.floor(Math.random() * (canHeight - 10) + 5) }; } } return newCoords; } }; module.exports = OpenCoordinates;
JavaScript
0
@@ -692,16 +692,19 @@ %7D%0A%0A + // while(! @@ -722,24 +722,27 @@ Player)%7B%0A + // isNotInsi @@ -783,16 +783,19 @@ er);%0A + // if (! @@ -813,24 +813,27 @@ Player)%7B%0A + // newCoor @@ -887,32 +887,35 @@ - 10) + 5),%0A + // @@ -977,19 +977,266 @@ %7D;%0A - %7D +// %7D%0A // %7D%0A%0A while(!isNotInsidePlayer)%7B%0A newCoords = %7B x: Math.floor(Math.random() * (canWidth - 10) + 5),%0A y: Math.floor(Math.random() * (canHeight - 10) + 5) %7D;%0A isNotInsidePlayer = players.every(checkPlayer); %0A %7D%0A
c8fd9d88489eccfb6aab69b2f69e40c5fbde86c3
Remove commented code
src/behaviors/birthdays/birthdays.js
src/behaviors/birthdays/birthdays.js
import Behavior from '../behavior.js'; import authorize from './google-events'; import google from 'googleapis'; import credentials from './client.json'; class Birthdays extends Behavior { constructor(settings) { settings.name = 'Birthdays'; settings.sayInChannel = settings.sayInChannel.replace('#', ''); super(settings); } initialize(bot) { super.initialize(bot); this.scheduleJob('0 16 * * *', () => { this.checkForBirthdays(bot); }); } checkForBirthdays(bot) { this.getBirthdays().then((birthdays) => { const today = new Date(), todaysBirthdays = birthdays[`${today.getMonth() + 1}/${today.getDate()}`], userPromises = []; if (!todaysBirthdays.length) { return; } todaysBirthdays.forEach((person) => { userPromises.push(bot.getUser(person.slackName)); }); Promise.all(userPromises).then((users) => { users.forEach((user, index) => { user.birthdayInfo = todaysBirthdays[index]; }); this.announceBirthday(bot, users).then(() => { this.updateTopic(bot, users); // Karma coming soon via a different behavior. // this.giveKarma(bot, users); }); }); }); } getBirthdays() { return new Promise((resolve) => { authorize(credentials).then((auth) => { const sheets = google.sheets('v4'); sheets.spreadsheets.values.get({ auth, spreadsheetId: '1gNkOqGubDyI2oBCU9MzduS5sd_GK_MfS53sLRhZO_ns', range: 'Form Responses 1!C2:E' }, (err, response) => { if (err) { return; } const birthdays = {}; response.values.forEach((value) => { const person = { birthday: value[0], year: value[1], slackName: value[2] }; if (birthdays[person.birthday]) { birthdays[person.birthday].push(person); } else { birthdays[person.birthday] = [person]; } }); resolve(birthdays); }); }); }); } announceBirthday(bot, users) { let message = `Happy birthday to:`; users.forEach((user, index) => { message += ` <@${user.id}|${user.name}>`; if (user.birthdayInfo.year !== '') { const age = new Date().getFullYear() - user.birthdayInfo.year; message += ` who is ${age} years old`; } if (index === users.length - 1) { message += '!'; } else { message += ','; } }); return bot.say('#beatz-aux-port', message, { icon_emoji: ':cake:' }); } giveKarma(bot, users, message = 'birthday karma') { users.forEach((user) => { bot.say('#beatz-aux-port', `<@${user.id}|${user.name}>++ # ${message}`); }); } updateTopic(bot, users) { const getFunction = false ? 'getChannel' : 'getGroup', topicFunction = false ? 'channels.setTopic' : 'groups.setTopic'; bot[getFunction]('beatz-aux-port').then((channel) => { const slackUsers = []; let topic = channel.topic.value.split('|'), message = ':birthday: Happy birthday '; // Trim whitespace, only include non-happy birthday messages topic = topic.map((item) => { if (!item.toLowerCase().includes('happy birthday')) { return item.trim(); } return ''; }).filter(i => i !== ''); users.forEach((user) => { slackUsers.push(`@${user.name}`); }); if (slackUsers.length > 1) { message += slackUsers.slice(0, -1).join(', ') + ' and ' + slackUsers.slice(-1); } else { message += slackUsers[0]; } message += '!'; topic.splice(1, 0, message); topic = topic.join(' | '); bot._api(topicFunction, { token: bot.token, channel: channel.id, topic }, (error) => { bot.log(topicFunction, true); bot.log(error, true); }); }, (error) => { bot.log(getFunction, true); bot.log(error, true); }); } } export default Birthdays; // authorize(credentials).then((auth) => { // const sheets = google.sheets('v4'); // sheets.spreadsheets.values.get({ // auth, // spreadsheetId: '1gNkOqGubDyI2oBCU9MzduS5sd_GK_MfS53sLRhZO_ns', // range: 'Form Responses 1!C1:E' // }, (err, response) => { // if (err) { // console.log('There was a problem getting the spreadsheet', err); // return; // } // const keys = response.values.shift(); // console.log(_.map(response.values, (value) => { // const obj = {}; // obj[keys[0]] = value[0]; // obj[keys[1]] = value[1]; // obj[keys[2]] = value[2]; // return obj; // })); // }); // });
JavaScript
0
@@ -4177,677 +4177,4 @@ ys;%0A -%0A// authorize(credentials).then((auth) =%3E %7B%0A// const sheets = google.sheets('v4');%0A%0A// sheets.spreadsheets.values.get(%7B%0A// auth,%0A// spreadsheetId: '1gNkOqGubDyI2oBCU9MzduS5sd_GK_MfS53sLRhZO_ns',%0A// range: 'Form Responses 1!C1:E'%0A// %7D, (err, response) =%3E %7B%0A// if (err) %7B%0A// console.log('There was a problem getting the spreadsheet', err);%0A%0A// return;%0A// %7D%0A%0A// const keys = response.values.shift();%0A%0A// console.log(_.map(response.values, (value) =%3E %7B%0A// const obj = %7B%7D;%0A%0A// obj%5Bkeys%5B0%5D%5D = value%5B0%5D;%0A// obj%5Bkeys%5B1%5D%5D = value%5B1%5D;%0A// obj%5Bkeys%5B2%5D%5D = value%5B2%5D;%0A// return obj;%0A// %7D));%0A// %7D);%0A%0A// %7D);%0A
b0f1cd8b30b563e2e6f64b147013d961eabf7883
change units needed by Gas Properties to abbreviations
js/units.js
js/units.js
// Copyright 2018, University of Colorado Boulder /** * These are the units that can be associated with Property instances. * * @author Sam Reid (PhET Interactive Simulations) */ define( function( require ) { 'use strict'; // modules var axon = require( 'AXON/axon' ); var units = { values: [ 'amperes', 'atmospheres', 'milliamperes', 'becquerels', 'centimeters', 'centimeters-squared', 'coulombs', 'degrees Celsius', 'farads', 'kilograms', 'grams', 'gray', 'henrys', 'henries', 'hertz', 'joules', 'katals', 'kelvins', 'kilopascals', 'liters', 'liters/second', 'lumens', 'lux', 'meters', 'meters/second', 'meters/second/second', 'moles', 'moles/liter', 'nanometers', 'newtons', 'newtons/meters', 'newtons-second/meters', 'ohms', 'ohm-centimeters', 'pascals', 'percent', 'picoseconds', 'radians', 'radians/second', 'seconds', 'siemens', 'sieverts', 'steradians', 'tesla', 'view-coordinates/second', 'volts', 'watts', 'webers', // abbreviations -- in time we will replace all full forms with abbreviations only // see https://github.com/phetsims/phet-io/issues/530 'cm', 'nm' ], isValidUnits: function( unit ) { return _.includes( units.values, unit ); } }; axon.register( 'units', units ); return units; } );
JavaScript
0.000001
@@ -326,29 +326,8 @@ s',%0A - 'atmospheres',%0A @@ -340,24 +340,24 @@ liamperes',%0A + 'becqu @@ -622,29 +622,8 @@ s',%0A - 'kilopascals',%0A @@ -960,29 +960,8 @@ t',%0A - 'picoseconds',%0A @@ -1324,23 +1324,171 @@ ' -cm',%0A 'nm' +atm', // atmospheres%0A 'cm', // centimeters%0A '%5Cu00B0C', // degrees Celsius%0A 'kPa', // kilopascals%0A 'nm', // nanometers%0A 'ps' // picoseconds %0A
08dedeadab7651cb47f9698a3b6e1800e506dd8e
ubuntu web browser is not safari
js/utils.js
js/utils.js
/* ----------------------- LOGGING SHORTCUTS -------------------------- */ function log(msg) { if (console && console.log) { console.log(msg); } } function error(msg) { if (console && console.error) { console.error(msg); } } function warn(msg) { if (console && console.warn) { console.warn(msg); } } /* ----------------------- Testing undefined and null value ---------------------- */ function isUndefined(v) { return typeof v === "undefined"; } function isUnset(v) { return (typeof v === "undefined") || (v === null); } /* ----------------------- Testing safari browser ---------------------- */ function isSafari() { return /^((?!chrome|android).)*safari/i.test(navigator.userAgent); } /* ----------------------- LOGGING SHORTCUTS -------------------------- */ /* Extract URL parameters from current location */ function getParameterByName(name, defaultValue) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? (isUnset(defaultValue) ? defaultValue : "") : decodeURIComponent(results[1].replace(/\+/g, " ")); } /* ----------------------- Local storage -------------------------- */ <!-- Begin Cookie Consent plugin by Silktide - http://silktide.com/cookieconsent --> window.cookieconsent_options = { "message":"This website uses cookies to ensure you get the best experience on our website", "dismiss":"Got it!", "learnMore":"More", "link":"doc/#privacy", "target":"_blank", //"container":"#map", "theme":"dark-bottom" }; function canValBeSaved() { return window.hasCookieConsent || (window.location.toString().indexOf("file:") == 0); } function storeVal(name, val) { //log("store " + name + "=" + val); if (canValBeSaved()) { var store = window.localStorage; if (store) { if (val === "") { store.removeItem(name); } else { store.setItem(name, val); } } } } function storeJsonVal(name, val) { if (JSON && JSON.stringify) { v = JSON.stringify(val); storeVal(name, v); } } function getVal(name, defval) { var v = window.localStorage ? window.localStorage.getItem(name) : undefined; return isUnset(v) ? defval : v; } function getJsonVal(name, defval) { var v = getVal(name); var val = v && JSON && JSON.parse ? JSON.parse(v) : undefined; return isUnset(v) ? defval : val; } /* ---------------------- GOOGLE ANALYTICS ------------------------- */ function initGoogleAnalytics(trackingid) { (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', trackingid, 'auto'); ga('send', 'pageview'); } /* ---------------------- EMAIL ------------------------- */ /* * Open a new mail in default mail client with recipent and subject. * It protects the email address from spam robots by splitting the address in several parts, * and only assemblying them when needed for the duration of a click. * * parameters: * - selector: the css selector of the link or button which should open the email * - name: the name part of the recepient email address * - domain: the domain part of the recepient email address * - subject: the subject string of the newly created email * * Attachs a click handler to the html element designated by <selector> * that opens the following URL: * "mailto:<name>@<domain>?subject=<subject> */ function setEmailListener(selector, name, domain, subject) { $(selector).click(function(){ function doEmail(d, i, tail) { location.href = "mailto:" + i + "@" + d + tail; } doEmail(domain, name, "?subject="+subject); return false; }) } /* ------------------------------ Encoding ---------------------------------*/ function n10dLocation() { var res = window.location.toString(); res = res.replace(/\?.*$/,"").replace(/\#.*$/,""); res = res.replace(/^.*:\/\//, "//"); res = res.replace(/index.html$/, ""); res = res.replace(/\/*$/, "/"); return res; } function strxor(s, k) { var enc = ""; var str = ""; // make sure that input is string str = s.toString(); for (var i = 0; i < s.length; i++) { // create block var a = s.charCodeAt(i); // bitwise XOR var b = a ^ k.charCodeAt(i % k.length); enc = enc + String.fromCharCode(b); } return enc; } function strencode(s, k) { return encodeURIComponent(strxor(s, k)) } function strdecode(s1, s2) { var s = (window.location.toString().indexOf("file:") == 0) ? s2: s1; return s ? strxor(decodeURIComponent(s), n10dLocation()) : s; } // Base 64 encoding / decoding function supportsBase64() { return btoa && atob ? true : false; } function b64EncodeUnicode(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { return String.fromCharCode('0x' + p1); })); } function b64DecodeUnicode(str) { return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } function copyToClipboard(msg, text) { window.prompt(msg + "\nCopy to clipboard: Ctrl+C, Enter", text); } /* ---------------------- Start service worker ------------------------*/ if ('serviceWorker' in navigator) { navigator.serviceWorker .register('./service-worker.js') .then(function() { console.log('Service Worker Registered'); }); }
JavaScript
0.999973
@@ -675,16 +675,23 @@ %7Candroid +%7Cubuntu ).)*safa
a8af724a33daeb1149357e27efe7519b410e0e98
update to reflect changes
blag.app.js
blag.app.js
var unmon=require("./lib/unmon.js"); var mds=require("./lib/plug/md.js"); unmon.launch({main:mds.spawnHandler(process.env.PWD+"/md/","unmon")});
JavaScript
0
@@ -86,16 +86,19 @@ ch(%7B +%0A main:mds .spa @@ -97,21 +97,8 @@ :mds -.spawnHandler (pro @@ -125,12 +125,13 @@ %22unmon%22) +%0A %7D);%0A
4e4546ed6a6d51f692b9cd471e8d379a3c1d0c58
use version table to determine which pages a theme's layout is used on
_dsa_mosaic_WEB_cms/forms/WEB_0F_theme_1L_layout.js
_dsa_mosaic_WEB_cms/forms/WEB_0F_theme_1L_layout.js
/** * @properties={typeid:35,uuid:"04fde543-69cc-4de9-af47-7f7c22221f40"} */ var _license_dsa_mosaic_WEB_cms = 'Module: _dsa_mosaic_WEB_cms \ Copyright (C) 2011 Data Mosaic \ MIT Licensed'; /** * * @properties={typeid:24,uuid:"6CC042F4-C204-4D07-9FFC-2D5984DFAE56"} */ function REC_delete() { //there are records using this layout, give a strong warning message if (forms.WEB_0F_theme_1L_page.foundset) { var delRec = plugins.dialogs.showWarningDialog( 'Delete record', 'Some pages reference this layout and deleting it will cause those pages to be orphaned from a layout.\nAre you sure you want to delete this layout?', 'Yes', 'No' ) } else { var delRec = plugins.dialogs.showWarningDialog( 'Delete record', 'Do you really want to delete this record?', 'Yes', 'No' ) } if (delRec == 'Yes') { controller.deleteRecord() } } /** * * @properties={typeid:24,uuid:"DBF7019B-9E07-4637-B4E3-F598E32F4D1A"} */ function REC_on_select() { var fsPage = forms.WEB_0F_theme_1L_page.foundset if (utils.hasRecords(foundset)) { forms.WEB_0F_theme_1L_editable.foundset.loadRecords(web_layout_to_editable) globals.CODE_cursor_busy(true) //TODO: the final part of the query should be b.id_layout (layout lives in version table, but that only returns a few pages) var query = "SELECT DISTINCT c.id_page FROM web_platform a, web_version b, web_page c WHERE \ a.id_platform = b.id_platform AND \ a.id_page = c.id_page AND \ a.id_layout = ?" var dataset = databaseManager.getDataSetByQuery( 'sutra_cms', query, [id_layout.toString()], -1 ) //load correct pages that this is used on fsPage.loadRecords(dataset) globals.CODE_cursor_busy(false) } else { fsPage.clear() } } /** * Handle changed data. * * @param {Object} oldValue old value * @param {Object} newValue new value * @param {JSEvent} event the event that triggered the action * * @returns {Boolean} * * @properties={typeid:24,uuid:"A42DF5D2-BC1F-44CF-9BA7-9CBA87C0FF96"} */ function FLD_data_change__flag_default(oldValue, newValue, event) { // var record = foundset.getRecord(foundset.getSelectedIndex()) // // var dupe = databaseManager.getFoundSet('sutra_cms','web_layout') // // dupe.find() // dupe.id_theme = record.id_theme // dupe.search() // // if (newValue) { // // //fsupdater broken as of 5.1.4?? //// var fsUpdater = databaseManager.getFoundSetUpdater(foundset) //// fsUpdater.setColumn('flag_default',0) //// fsUpdater.performUpdate() //// //// record.flag_default = 1 // // for (var i = 1; i <= dupe.getSize(); i++) { // var recLayout = dupe.getRecord(i) // // if (recLayout.id_layout != record.id_layout) { // recLayout.flag_default = 0 // } // } // // databaseManager.saveData() // } // else { // plugins.dialogs.showErrorDialog( // 'Error', // 'There must be a default layout set' // ) // // record.flag_default = 1 // } // // return true // if (flag_default) { var fsUpdater = databaseManager.getFoundSetUpdater(foundset) fsUpdater.setColumn('flag_default',0) fsUpdater.performUpdate() flag_default = 1 } } /** * Perform the element default action. * * @param {JSEvent} event the event that triggered the action * * @properties={typeid:24,uuid:"31537525-46DE-4A2A-ACC9-9A9125BFBD9A"} */ function REC_new(event) { forms.WEB_0F_theme.ACTION_new_layout() } /** * Perform the element default action. * * @param {JSEvent} event the event that triggered the action * * @properties={typeid:24,uuid:"86CB740F-CD69-4889-9F9A-70743385A0A2"} */ function ACTIONS_list(event) { forms.WEB_0F_theme.LAYOUTS_action_list(event) }
JavaScript
0.000002
@@ -1507,25 +1507,25 @@ page AND %5C%0A%09 -a +b .id_layout =
f0599e489b992554e302ed0c9b4383f4294d1f1b
use path.sep
lib/main.js
lib/main.js
/* eslint-disable no-console */ require('babel-core/register'); const fs = require('fs-extra'); const path = require('path'); const mkdirp = require('mkdirp'); const React = require('react'); const render = require('react-dom/server').renderToStaticMarkup; const MainHTML = require('../src/components/main'); const splitChar = process.platform === 'win32' ? '\\' : '/'; const distDir = path.join(__dirname, '..', 'dist'); const inlineAssetsDir = path.join(distDir, 'assets', 'inline'); const externalAssetsDir = path.join(distDir, 'assets', 'external'); /** * Private functions * */ /** * Creates a new directory * * @param {String} dir * @returns {Promise} */ function makeDir(dir) { return new Promise((resolve, reject) => { mkdirp(dir, (err, made) => err === null ? resolve(made) : reject(err)); }); } /** * Saves a file * * @param {String} filename * @param {String} data * @returns {Promise} */ function saveFile(filename, data) { return new Promise((resolve, reject) => { fs.outputFile(filename, data, err => err === null ? resolve(true) : reject(err)); }); } /** * Synchronously loads a file with utf8 encoding * * @param {String} filename * @returns {String} */ function loadFile(filename) { return fs.readFileSync(filename, 'utf8'); } /** * Get report options by extending base options * with user provided options * * @param {Object} opts * @returns {Object} */ function getOptions(opts) { const userOptions = opts || {}; const baseOptions = { inlineAssets: false, reportDir: path.join('.', 'mochawesome-reports'), reportFilename: 'mochawesome', reportTitle: process.cwd().split(splitChar).pop(), reportPageTitle: 'Mochawesome Report Card' }; const mergedOptions = Object.assign(baseOptions, userOptions); // If reportHtmlFile option was not specifically provided, // create it based on the reportDir and reportFilename options if (!mergedOptions.reportHtmlFile) { mergedOptions.reportHtmlFile = path.join( mergedOptions.reportDir, `${mergedOptions.reportFilename}.html` ); } return mergedOptions; } /** * Get the report assets for inline use * * @param {Object} opts * @returns {Object} */ function getAssets() { return { styles: loadFile(path.join(inlineAssetsDir, 'app.css')), scripts: loadFile(path.join(inlineAssetsDir, 'app.js')) }; } /** * Copy the report assets to the report dir * * @param {Object} opts * @returns {Object} */ function copyAssets(opts) { // Copy the assets to the report location const assetsDir = path.join(opts.reportDir, 'assets'); fs.copySync(externalAssetsDir, assetsDir); } /** * Renders the main report React component * * @param {JSON} data * @param {Object} options * @param {String} styles * @param {String} scripts * @returns {String} html */ function renderHtml(data, options, styles, scripts) { return render(React.createElement(MainHTML, { data, options, styles, scripts })); } /** * Prepare options, assets, and html for saving * * @param {String} data * @param {Object} opts * @returns {Object} */ function prepare(reportData, opts) { // Stringify the data if needed let data = reportData; if (typeof data === 'object') { data = JSON.stringify(reportData); } // Get the options const options = getOptions(opts); console.log(options); let assets = {}; // If options.inlineAssets is true, get the // styles and scripts as strings if (!options.dev) { if (options.inlineAssets) { assets = getAssets(options); } else { // Otherwise copy the files to the assets dir copyAssets(options); } } // Render basic template to string const { styles, scripts } = assets; const html = `<!doctype html>\n${renderHtml(data, options, styles, scripts)}`; return { html, reportFilename: options.reportHtmlFile }; } /** * Exposed functions * */ function create(data, opts) { const { html, reportFilename } = prepare(data, opts); return saveFile(reportFilename, html); } function createSync(data, opts) { const { html, reportFilename } = prepare(data, opts); console.log(reportFilename); fs.outputFileSync(reportFilename, html); } module.exports = { create, createSync };
JavaScript
0.999986
@@ -307,70 +307,8 @@ );%0A%0A -const splitChar = process.platform === 'win32' ? '%5C%5C' : '/';%0A%0A cons @@ -1598,17 +1598,16 @@ lit( -splitChar +path.sep ).po
216bf149566cbf79be78d1587bfa590651d1c503
Fix imusic connector
connectors/v2/imusic.am.js
connectors/v2/imusic.am.js
'use strict'; /* global Connector */ Connector.playerSelector = '#playerBox'; Connector.artistSelector = '#p_songTitle .f_artist'; Connector.trackSelector = '#p_songTitle .f_album'; Connector.isPlaying = function () { return $('#pauseBtn').is(':visible'); };
JavaScript
0
@@ -64,18 +64,21 @@ = ' -# +. player -Box +-block ';%0A%0A
8214d9f8ada8b7d09c7b2369e98fc8e36917dc8d
Test commit for account change
containers/ActorsMovies.js
containers/ActorsMovies.js
import React, { Component } from 'react'; import { Text, Image, View } from 'react-native'; import styles from './styles/ActorsMoviesStyle'; import ActorImage from '../components/ActorImage'; import { StackNagivator } from 'react-navigation'; export default class ActorsMovies extends Component { render() { return ( <Text>Movies</Text> ) } }
JavaScript
0
@@ -335,16 +335,17 @@ t%3EMovies +! %3C/Text%3E%0A
d25dda0fdddfea617a7751842dce5a70fdc712b1
Convert timestamp to moment for latest comparison.
lib/plugins/xdrip-js.js
lib/plugins/xdrip-js.js
'use strict'; var _ = require('lodash'); var moment = require('moment'); var times = require('../times'); var levels = require('../levels'); function init(ctx) { var utils = require('../utils')(ctx); var sensorState = { name: 'xdrip-js' , label: 'Sensor Status' , pluginType: 'pill-status' }; sensorState.getPrefs = function getPrefs(sbx) { return { enableAlerts: sbx.extendedSettings.enableAlerts || false }; }; sensorState.setProperties = function setProperties (sbx) { sbx.offerProperty('sensorState', function setProp ( ) { return sensorState.getStateString(sbx); }); }; sensorState.checkNotifications = function checkNotifications(sbx) { var info = sbx.properties.sensorState; var sensorInfo = info.latest; if (sensorInfo.notification) { var notification = _.extend({}, sensorInfo.notification, { plugin: sensorState , debug: { stateString: sensorInfo.stateString } }); sbx.notifications.requestNotify(notification); } }; sensorState.getStateString = function findLatestState(sbx) { var prefs = sensorState.getPrefs(sbx); var recentHours = 24; var recentMills = sbx.time - times.hours(recentHours).msecs; var result = { seenDevices: { } , latest: null , lastDevice: null , lastState: null , lastStateString: null , lastStateStringShort: null , lastStateTime: null }; function toMoments (status) { return { when: moment(status.mills) , timestamp: status.sensor && status.sensor.timestamp && moment(status.sensor.timestamp) }; } function getDevice(status) { var uri = status.device || 'device'; var device = result.seenDevices[uri]; if (!device) { device = { name: utils.deviceName(uri) , uri: uri }; result.seenDevices[uri] = device; } return device; } var recentData = _.chain(sbx.data.devicestatus) .filter(function (status) { return ('sensor' in status) && sbx.entryMills(status) <= sbx.time && sbx.entryMills(status) >= recentMills; }) .value( ); recentData = _.sortBy(recentData, 'sensor.timestamp'); _.forEach(recentData, function eachStatus (status) { var device = getDevice(status); var moments = toMoments(status); if (status.sensor && (!result.latest || moments.timestamp && moments.timestamp.isAfter(result.latest.timestamp))) { result.latest = status; } }); var sendNotification = false; var sound = 'incoming'; var message; var sensorInfo = result.latest; if (sensorInfo) { sensorInfo.level = levels.NONE; if (sensorInfo.sensor.state != 0x6) { // TODO: determine whether to send a notification sendNotification = true; message = 'Sensor state: ' + sensorInfo.sensor.stateString; sensorInfo.level = levels.WARN; } //allow for 20 minute period after a full hour during which we'll alert the user if (prefs.enableAlerts && sendNotification) { sensorInfo.notification = { title: 'Sensor State: ' + sensorInfo.sensor.stateString , message: message , pushoverSound: sound , level: sensorInfo.level , group: 'xDrip-js' }; } result.lastState = sensorInfo.sensor.state; result.lastStateString = sensorInfo.sensor.stateString; result.lastStateStringShort = sensorInfo.sensor.stateStringShort; result.lastStateTime = moment(sensorInfo.sensor.timestamp); } return result; }; sensorState.updateVisualisation = function updateVisualisation (sbx) { var latest = sbx.properties.sensorState; var sensorInfo = latest.latest; var info = []; _.forIn(latest.seenDevices, function seenDevice (device) { info.push( { label: 'Seen: ', value: device.name } ); }); if (sensorInfo) { var statusClass = null; if (sensorInfo.level === levels.URGENT) { statusClass = 'urgent'; } else if (sensorInfo.level === levels.WARN) { statusClass = 'warn'; } } sbx.pluginBase.updatePillText(sensorState, { value: (sensorInfo && sensorInfo.sensor.stateStringShort) || (sensorInfo && sensorInfo.sensor.stateString) || 'Unknown' , label: 'CGM' , info: info , pillClass: statusClass }); }; return sensorState; } module.exports = init;
JavaScript
0.934637
@@ -2557,16 +2557,83 @@ status;%0A + result.latest.timestamp = moment(status.sensor.timestamp);%0A %7D%0A
c34d46e5436982f3f8703f0cc3a11e3d3b3dc22b
fix case where cache == undefined
lib/make.js
lib/make.js
"use strict"; var _ = require('lodash') , Promise = require('bluebird') , winston = require('winston') , config = require('config') , path = require('path') , url = require('url') , uuid = require('node-uuid') , onFinished = require('on-finished') , tar_fs = require('tar-fs') , createOutputStream = require('create-output-stream') , zlib = require('zlib') , codedb_sdk = require('taskmill-core-codedb-sdk') , make_sdk = require('taskmill-core-make-sdk') , Container = require('./container') , WError = require('verror').WError , VError = require('verror').VError ; let agent_url = config.getUrlObject('agent.url'); class Maker{ constructor(agent) { this.agent = agent; } make(remote, sha, options = {}) { let container = new Container(this.agent.docker, remote, sha); return make(container, remote, sha, options); } static dirname(remote) { let url_parsed = url.parse(remote); return path.join('.disk', url_parsed.hostname, url_parsed.pathname); } static writeFile(filename, blob) { return Promise .fromCallback((cb) => { if (!blob) { return cb(); } let ws = createOutputStream(filename, { flags : 'w' }); ws.end(blob); onFinished(ws, () => cb(undefined, filename)); }); } static writeTar(dirname, stream) { return Promise .fromCallback((cb) => { if (!stream) { return cb(); } let ws = stream.pipe(zlib.createGunzip()).pipe(tar_fs.extract(dirname)); // todo [akamel] are we catching errors on all levels? onFinished(ws, () => cb(undefined, dirname)); }); } static archive(remote, sha, options = {}) { let { token, bearer } = options; return Promise .fromCallback((cb) => { codedb_sdk .archive(remote, { branch : sha, token, bearer, make : true }) .on('response', (response) => { if (response.statusCode != 200) { return cb(new Error(`codedb archive error ${response.statusCode}`)); } cb(undefined, response); }) .on('error', (err) => cb(err)) }); } } function track(container, result) { let kill = () => { return container.sigkill(); }; let monitor = (stats) => { let max_usage = config.get('worker.max-memory') * 1024 * 1024; if (stats.memory_stats.usage > max_usage) { winston.info('kill - memory limit', this.id); return kill(); } let max_idle = config.get('worker.max-idle') * 1000; if (stats.idle > max_idle) { winston.info('kill - idle limit', this.id); return kill(); } make_sdk .set(result, { ttl : 5 }) .catch((err) => { console.error('error extend live container', err, result); }); }; container.on('stats', monitor); container.once('die', () => { make_sdk .del(result.hash) .catch((err) => { console.error('error unset dead container', err, result); }); }); return make_sdk.set(result, { ttl : 5 }); } // process.on("unhandledRejection", function(reason, promise) { // console.error(reason, promise); // }); function make(container, remote, sha, options = {}) { let time = process.hrtime(); let { blob, filename, token, cache, bearer } = options; let single_use = !cache || !!blob; let { key, hash } = make_sdk.key(remote, sha, { single_use }); if (single_use) { return go_make(); } else { return make_sdk .lock(hash) .catch((err) => { throw new WError({ name : 'MAKE_LOCK_TAKEN', cause : err, info : { entity : `${key}`, message : 'lock taken' } }, `lock ${hash} taken`); }) .then((lock) => { console.log('got lock', lock, key, hash); let t = setTimeout(() => { console.log('extend lock', lock, key, hash); make_sdk .extend(lock) .catch((err) => { console.log('stop extend lock', lock, key, hash); // console.error(err); clearTimeout(t); }) }, 1000); return go_make() .finally(() => { // make_sdk.unlock(lock); console.log('stop extend lock', lock, key, hash); clearTimeout(t); }); }); } function go_make() { // mount file to container let disk = Maker.dirname(remote); let blobname = path.join(disk, `${uuid.v4()}.layer`); let tarname = path.join(disk, sha); return Promise .all([ Maker.writeFile(blobname, blob) , Maker.archive(remote, sha, { token, bearer }).then((stream) => { return Maker.writeTar(tarname, stream); }) ]) .spread((blobname, tarname) => { container.mount(tarname, '/mnt/src/'); if (blobname) { container.mount(blobname, path.join('/mnt/src/', filename)); } return container.await(); }) .then((result) => { let { hostname, protocol } = agent_url , { port } = result ; return { key , hash , single_use , remote , sha , protocol : protocol , hostname : hostname , port : port , run_url : url.format({ protocol, hostname, port }) , stats : { time : process.hrtime(time) } }; }) .tap((result) => { return track(container, result); }) .catch((err) => { console.error(err.message); throw err.message; }); } } module.exports = Maker;
JavaScript
0.999535
@@ -3753,14 +3753,25 @@ e = -! +( cache + === false) %7C%7C
31e2010608ba40a2b73c27cab3189e78826879c2
Update mongo-storage.js (#6811)
lib/storage/mongo-storage.js
lib/storage/mongo-storage.js
'use strict'; const MongoClient = require('mongodb').MongoClient; const mongo = { client: null, db: null, }; function init(env, cb, forceNewConnection) { function maybe_connect(cb) { if (mongo.db != null && !forceNewConnection) { console.log('Reusing MongoDB connection handler'); // If there is a valid callback, then return the Mongo-object if (cb && cb.call) { cb(null, mongo); } } else { if (!env.storageURI) { throw new Error('MongoDB connection string is missing. Please set MONGODB_URI environment variable'); } console.log('Setting up new connection to MongoDB'); const timeout = 10 * 1000; const options = { connectTimeoutMS: timeout, socketTimeoutMS: timeout, useNewUrlParser: true, useUnifiedTopology: true, }; const connect_with_retry = async function (i) { mongo.client = new MongoClient(env.storageURI, options); try { await mongo.client.connect(); console.log('Successfully established a connected to MongoDB'); const dbName = mongo.client.s.options.dbName; mongo.db = mongo.client.db(dbName); const result = await mongo.db.command({ connectionStatus: 1 }); const roles = result.authInfo.authenticatedUserRoles; if (roles.length > 0 && roles[0].role == 'readAnyDatabase') { console.error('Mongo user is read only'); cb(new Error('MongoDB connection is in read only mode! Go back to MongoDB configuration and check your database user has read and write access.'), null); } console.log('Mongo user role seems ok:', roles); // If there is a valid callback, then invoke the function to perform the callback if (cb && cb.call) { cb(null, mongo); } } catch (err) { if (err.message && err.message.includes('AuthenticationFailed')) { console.log('Authentication to Mongo failed'); cb(new Error('MongoDB authentication failed! Double check the URL has the right username and password in MONGODB_URI.'), null); return; } if (err.name && err.name === "MongoServerSelectionError") { const timeout = (i > 15) ? 60000 : i * 3000; console.log('Error connecting to MongoDB: %j - retrying in ' + timeout / 1000 + ' sec', err); setTimeout(connect_with_retry, timeout, i + 1); if (i == 1) cb(new Error('MongoDB connection failed! Double check the MONGODB_URI setting in Heroku.'), null); } else { cb(new Error('MONGODB_URI ' + env.storageURI + ' seems invalid: ' + err.message)); } } }; return connect_with_retry(1); } } mongo.collection = function get_collection(name) { return mongo.db.collection(name); }; mongo.ensureIndexes = function ensureIndexes(collection, fields) { fields.forEach(function (field) { console.info('ensuring index for: ' + field); collection.createIndex(field, { 'background': true }, function (err) { if (err) { console.error('unable to ensureIndex for: ' + field + ' - ' + err); } }); }); }; return maybe_connect(cb); } module.exports = init;
JavaScript
0
@@ -660,121 +660,19 @@ nst -timeout = 10 * 1000;%0A const options = %7B%0A connectTimeoutMS: timeout,%0A socketTimeoutMS: timeout, +options = %7B %0A @@ -970,19 +970,18 @@ hed -a connect -ed +ion to @@ -2571,31 +2571,8 @@ _URI - ' + env.storageURI + ' see
a7b799d9d6ebdef54787ed872c39311a1adf0c79
Handle numeric member expressions in Path.prototype.needsParens.
lib/path.js
lib/path.js
var assert = require("assert"); var n = require("./types").namedTypes; function Path(node, parent) { assert.ok(this instanceof Path); n.Node.assert(node); if (parent) { assert.ok(parent instanceof Path); } else { parent = null; } Object.defineProperties(this, { node: { value: node }, parent: { value: parent } }); } var Pp = Path.prototype; Pp.cons = function(child) { return new Path(child, this); }; Pp.needsParens = function() { if (!this.parent) return false; var node = this.node; var parent = this.parent.node; if (n.UnaryExpression.check(node)) return n.MemberExpression.check(parent) && parent.object === node; if (isBinary(node)) { if (n.CallExpression.check(parent) && parent.callee === node) return true; if (n.UnaryExpression.check(parent)) return true; if (n.MemberExpression.check(parent) && parent.object === node) return true; } if (n.AssignmentExpression.check(node) || n.ConditionalExpression.check(node)) { if (n.UnaryExpression.check(parent)) return true; if (isBinary(parent)) return true; if (n.CallExpression.check(parent) && parent.callee === node) return true; if (n.ConditionalExpression.check(parent) && parent.test === node) return true; if (n.MemberExpression.check(parent) && parent.object === node) return true; } return false; // TODO }; function isBinary(node) { return n.BinaryExpression.check(node) || n.LogicalExpression.check(node); } exports.Path = Path;
JavaScript
0
@@ -63,16 +63,65 @@ edTypes; +%0Avar builtIn = require(%22ast-types%22).builtInTypes; %0A%0Afuncti @@ -1095,24 +1095,199 @@ rue;%0A %7D%0A%0A + if (n.Literal.check(node) &&%0A builtIn.number.check(node.value) &&%0A n.MemberExpression.check(parent) &&%0A parent.object === node)%0A return true;%0A%0A if (n.As
e120ecb09a92b2fc47796810ac63a0e1c5ce1d10
Move redirect to end of promise stack
lib/stripe/handlers/index.js
lib/stripe/handlers/index.js
'use strict'; //Inspiration from http://gaarf.info/2013/06/25/securing-stripe-webhooks-with-node-js/ // Remove once finished testing // var cardToFail = { // number: '4000000000000341', // exp_month: 08, // exp_year: 2018, // cvc: 857 // }; var Promise = require('rsvp').Promise; module.exports = function (config) { var stripe = require('stripe')(config.secret); var models = require('../../models'); var stripeTransactions = { 'unhandled': require('./unhandled.js'), 'customer.subscription.deleted': require('./customer.subscription.deleted') }; return { authEvent: function(req, res, next) { if (req.body.object !== 'event') { return res.send(400); // invalid data } stripe.events.retrieve(req.body.id, function(err, event) { // err = invalid event, !event = error from stripe if (err || !event) { return res.send(401); } req.stripeEvent = event; next(); }); }, handleTransaction: function(req, res) { var event = req.stripeEvent; var data = event.data.object; // takes care of unexpected event types var transactionMethod = stripeTransactions[event.type] || stripeTransactions.unhandled; transactionMethod(data, function(err){ if ( !err ) { res.send(200); } }); }, handleSubscription: function(req, res) { var user = req.session.user; var customerOptions = { plan: req.params.plan, card: req.body.stripeToken }; if (!user) { res.flash('error', 'Please login before attempting to signup'); res.redirect('/'); return; } function handleCardError(err) { // error with customer creation res.flash('error', err.message); res.redirect('/'); } function setUserToPro (data) { return new Promise(function(resolve, reject) { models.user.setProAccount(user.name, true, function(err) { if (!err) { req.session.user.pro = true; req.flash(req.flash.NOTIFICATION, 'Welcome to the pro user lounge. Your seat is waiting'); resolve(data); } else { req.flash(req.flash.ERROR, 'Something went wrong, we\'ll work on fixing this ASAP'); reject(err); // TODO :: serious exception - need to make sure once paid they are a PRO } res.redirect('/'); }); }); } function createCustomer (data) { models.customer.setCustomer({ stripeId: data.customer || data.id, user: user.name, plan: customerOptions.plan }); } models.customer.getCustomerByUser(user, function(err, customer) { var chargeForSubscription = customer[0] ? stripe.customers.updateSubscription(customer[0].stripe_id, customerOptions) : // jshint ignore:line stripe.customers.create(customerOptions); chargeForSubscription .then(setUserToPro, handleCardError) .then(createCustomer); }); }, renderSignUp: function(req, res) { if (!req.session.user) { req.flash('error', 'You must sign in before subscribing'); return res.redirect('/'); } res.render('signup', {}); } }; };
JavaScript
0
@@ -2465,39 +2465,8 @@ %7D%0A - res.redirect('/');%0A @@ -2683,16 +2683,68 @@ ns.plan%0A + %7D, function()%7B%0A res.redirect('/');%0A
4614d496ad4f8e7532902d2de2efa4bca3428283
fix for peer
lib/peer.js
lib/peer.js
var _ = require('icebreaker') var Swarm = require('./swarm') var url = require('url') var PeerInfo = require('./peerInfo') var Logger = require('./logger') var DHT = require('./dht') var DB = require('./db') var ms = require('ms') var paramap = require('pull-paramap') var _ = require("icebreaker") function Peer(config) { if (!(this instanceof Peer)) return new Peer(config) this.config = config this.config.info = this.config.info || PeerInfo() this.state = 'ended' this.util = Swarm.util this.id = this.util.encode(config.info.id, config.info.encoding) var _protos = [] var _notify = _.notify() this.events = function () { return _notify.listen() } this.events.combine = require('./combine') this.events.asyncMap = require('icebreaker-network/lib/asyncMap') this.events.map = require('icebreaker-network/lib/map') this.events.on = function (events) { return _(paramap(function (item, cb) { cb(null, item) }), require('icebreaker-network/lib/on')(events)) } this.logger = require('./logger')({ config: this.config, events: this.events, _notify: _notify }) this.start = function (cb) { if (this.state === 'ended') { this.state = 'start' var self = this var swarm = Swarm(this) class t{} var plugins = [DB, DHT].concat(_protos).map(function (plug) { plug = plug(self,_) self.swarm.addProtocol(plug) return plug }) plugins=plugins.filter(function(item){ return 'function' === typeof item }) self.config.listen.filter(function (addr) { return self.swarm.protoNames().indexOf(url.parse(addr).protocol) !== -1 }) .forEach(function (addr) { self.swarm.listen(addr, { timeout: ms('40s') }) }) var combined = self.events.combine.apply(null, [swarm].concat(plugins.slice(0))) self._end = combined.end _(combined, self.events.asyncMap({ ready: function (e, done) { self.state = e.type if (cb) cb(null, e) cb = null done(e) } }), _.drain(_notify, function (err) { self.state = 'ended' _notify.end(err) }) ) } } this.addProtocol = function (protocol) { _protos.push(protocol) } this.stop = function (cb) { var self = this if (this._end === null) return if (self.state != 'ended') _(_notify.listen(), self.events.on({ end: function (err) { if (cb) cb(err) cb = null self.state = 'ended' self._end = null } })) if (self._end != null) { self._end() delete self._end } } } module.exports = Peer
JavaScript
0
@@ -1254,17 +1254,8 @@ -class t%7B%7D %0A
c04795da5e6b0a41c57251c3d3caae1ec6895225
add post.comments() method
lib/post.js
lib/post.js
/** * Module dependencies. */ var Like = require('./like'); var Reblog = require('./reblog'); var debug = require('debug')('wpcom:post'); /** * Post methods * * @param {String} id * @param {String} sid site id * @param {WPCOM} wpcom * @api public */ function Post(id, sid, wpcom){ if (!(this instanceof Post)) return new Post(id, sid, wpcom); this.wpcom = wpcom; this._sid = sid; // set `id` and/or `slug` properties id = id || {}; if ('object' != typeof id) { this._id = id; } else { this._id = id.id; this._slug = id.slug; } } /** * Set post `id` * * @api public */ Post.prototype.id = function(id){ this._id = id; }; /** * Set post `slug` * * @param {String} slug * @api public */ Post.prototype.slug = function(slug){ this._slug = slug; }; /** * Get post * * @param {Object} [query] * @param {Function} fn * @api public */ Post.prototype.get = function(query, fn){ if (!this._id && this._slug) { return this.getBySlug(query, fn); } var path = '/sites/' + this._sid + '/posts/' + this._id; this.wpcom.sendRequest(path, query, null, fn); }; /** * Get post by slug * * @param {Object} [query] * @param {Function} fn * @api public */ Post.prototype.getBySlug = function(query, fn){ var path = '/sites/' + this._sid + '/posts/slug:' + this._slug; this.wpcom.sendRequest(path, query, null, fn); }; /** * Add post * * @param {Object} body * @param {Function} fn * @api public */ Post.prototype.add = function(body, fn){ var path = '/sites/' + this._sid + '/posts/new'; this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn); }; /** * Edit post * * @param {Object} body * @param {Function} fn * @api public */ Post.prototype.update = function(body, fn){ var path = '/sites/' + this._sid + '/posts/' + this._id; this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn); }; /** * Delete post * * @param {Function} fn * @api public */ Post.prototype['delete'] = Post.prototype.del = function(fn){ var path = '/sites/' + this._sid + '/posts/' + this._id + '/delete'; this.wpcom.sendRequest({ path: path, method: 'post' }, null, null, fn); }; /** * Get post likes list * * @param {Object} [query] * @param {Function} fn * @api public */ Post.prototype.likesList = function(query, fn){ var path = '/sites/' + this._sid + '/posts/' + this._id + '/likes'; this.wpcom.sendRequest(path, query, null, fn); }; /** * Search within a site for related posts * * @param {Object} body * @param {Function} fn * @api public */ Post.prototype.related = function(body, fn){ var path = '/sites/' + this._sid + '/posts/' + this._id + '/related'; this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn); }; /** * Create a `Like` instance * * @api public */ Post.prototype.like = function(){ return Like( this._id, this._sid, this.wpcom); }; /** * Create a `Reblog` instance * * @api public */ Post.prototype.reblog = function(){ return Reblog( this._id, this._sid, this.wpcom); }; /** * Expose `Post` module */ module.exports = Post;
JavaScript
0.000024
@@ -87,24 +87,60 @@ ./reblog');%0A +var Comment = require('./comment');%0A var debug = @@ -3057,17 +3057,16 @@ Reblog( - this._id @@ -3081,32 +3081,297 @@ sid, this.wpcom) +;%0A%7D;%0A%0A/**%0A * Return recent comments%0A *%0A * @param %7BObjecy%7D %5Bquery%5D%0A * @param %7BString%7D id%0A * @api public%0A */%0A%0APost.prototype.comments = function(query, fn)%7B%0A var comment = Comment(null, this._id, this._sid, this.wpcom);%0A comment.replies(query, fn);%0A return comment ;%0A%7D;%0A%0A/**%0A * Exp
8d300bb57e8192aba2a55677c8b3ed2460d5ae66
Add missing line break.
test/unit/connectSpec.js
test/unit/connectSpec.js
'use strict'; var expect = require('chai').expect, connect = require('../../lib/connect'); describe('connect', function () { var validTestCases = [ { description: 'return a minimal connection object', input: 'anyhost', expectedConnection: { hosts: [ { host: 'anyhost', port: 27017 } ], options: {} } }, { description: 'ignore the database name and parse everything else', input: 'mongodb://anyuser:withpassword@anyhost:40000,different:1234,host3/anyDB?any=true&another=1', expectedConnection: { auth: { user: 'anyuser', pass: 'withpassword'}, hosts: [ { host: 'anyhost', port: 40000 }, { host: 'different', port: 1234 }, { host: 'host3', port: 27017 } ], options: { another: 1, any: true } } } ], invalidTestCases = [ { description: 'missing hostnames', input: '', expectedErrorMessage: 'Invalid mongodb uri. Missing hostname' } ]; validTestCases.forEach(function (testCase) { it('should ' + testCase.description, function () { var connection = connect(testCase.input); expect(connection).to.have.property('getDb'); expect(connection.getDb).to.be.a('function'); expect(connection.information).to.deep.equal(testCase.expectedConnection); }); }); invalidTestCases.forEach(function (testCase) { it('should throw an error for ' + testCase.description, function () { expect(connect.bind(null, testCase.input)).to.throw(testCase.expectedErrorMessage); }); }); describe('getDb', function () { var connectionString = 'user:pass@host,different:1234/anyDB?any=true&no=1', connection; beforeEach(function () { connection = connect(connectionString); }); it('should return a database representation with a valid connection string', function () { var dbName = 'interestingDb', expectedConnectionString = 'mongodb://user:pass@host:27017,different:1234/' + dbName + '?any=true&no=1'; expect(connection.information).to.not.have.property('db'); expect(connection.getDb(dbName).connectionString).to.equal(expectedConnectionString); }); it('should throw an error if the database name is missing', function () { var expectedErrorMessage = 'Invalid database name provided. Information: '; expect(connection.getDb.bind(null, '')).to.throw(expectedErrorMessage); expect(connection.getDb).to.throw(expectedErrorMessage + 'undefined'); }); it('should throw an error if connection information data is modified', function () { var expectedErrorMessage = 'Cannot assign to read only property', changeConnection = function () { connection.information = {}; }, changeHosts = function () { connection.information.hosts = [] }, changeGetDb = function () { connection.getDb = function () {} }; expect(changeConnection).to.throw(expectedErrorMessage); expect(changeHosts).to.throw(expectedErrorMessage); expect(changeGetDb).to.throw(expectedErrorMessage) }); it('should throw an error if the connection object gets extended', function () { var expectedErrorMessage = 'Can\'t add property something, object is not extensible', addProperty = function () { connection.something = 'new'; }; expect(addProperty).to.throw(expectedErrorMessage); }) }); });
JavaScript
0.000011
@@ -845,16 +845,37 @@ assword' +%0A %7D,%0A
c867563ce5c8e75ed85f578033f5fcd1ab254106
Improve rendering
renderer.js
renderer.js
const { app, globalShortcut } = require('electron').remote; const { state, logs, updateUI } = require('./src/state'); const { init: initWatcher } = require('./src/watcher'); const { init: initSpy } = require('./src/spy'); // initSpy(); initWatcher(); require('./src/render'); // app.on('ready', function () { // // }); // app.on('browser-window-blur', () => { // updateUI({ lastFocus: new Date() }); // });
JavaScript
0.000009
@@ -1,16 +1,19 @@ +// const %7B app, glo @@ -11,24 +11,8 @@ app -, globalShortcut %7D = @@ -263,51 +263,8 @@ );%0A%0A -// app.on('ready', function () %7B%0A//%0A// %7D);%0A %0A//
df697f195870eb2f46cc83e3d1651a2fcd686255
fix merge mistake
src/handler/TouchZoom.js
src/handler/TouchZoom.js
/* * L.Handler.TouchZoom is used internally by L.Map to add touch-zooming on Webkit-powered mobile browsers. */ L.Handler.TouchZoom = L.Handler.extend({ enable: function() { if (!L.Browser.mobileWebkit || this._enabled) { return; } L.DomEvent.addListener(this._map._container, 'touchstart', this._onTouchStart, this); this._enabled = true; }, disable: function() { if (!this._enabled) { return; } L.DomEvent.removeListener(this._map._container, 'touchstart', this._onTouchStart, this); this._enabled = false; }, _onTouchStart: function(e) { if (!e.touches || e.touches.length != 2 || this._map._animatingZoom) { return; } var p1 = this._map.mouseEventToLayerPoint(e.touches[0]), p2 = this._map.mouseEventToLayerPoint(e.touches[1]), viewCenter = this._map.containerPointToLayerPoint(this._map.getSize().divideBy(2)); this._startCenter = p1.add(p2).divideBy(2, true); this._startDist = p1.distanceTo(p2); //this._startTransform = this._map._mapPane.style.webkitTransform; this._moved = false; this._zooming = true; this._centerOffset = viewCenter.subtract(this._startCenter); L.DomEvent.addListener(document, 'touchmove', this._onTouchMove, this); L.DomEvent.addListener(document, 'touchend', this._onTouchEnd, this); L.DomEvent.preventDefault(e); }, _onTouchMove: function(e) { if (!e.touches || e.touches.length != 2) { return; } if (!this._moved) { this._map._mapPane.className += ' leaflet-zoom-anim'; this._map._prepareTileBg(); this._moved = true; } var p1 = this._map.mouseEventToLayerPoint(e.touches[0]), p2 = this._map.mouseEventToLayerPoint(e.touches[1]); this._scale = p1.distanceTo(p2) / this._startDist; this._delta = p1.add(p2).divideBy(2, true).subtract(this._startCenter); /* * Used 2 translates instead of transform-origin because of a very strange bug - * it didn't count the origin on the first touch-zoom but worked correctly afterwards */ this._map._tileBg.style.webkitTransform = [ L.DomUtil.getTranslateString(this._delta), L.DomUtil.getScaleString(this._scale, this._startCenter) ].join(" "); L.DomEvent.preventDefault(e); }, _onTouchEnd: function(e) { if (!this._moved || !this._zooming) { return; } this._zooming = false; var oldZoom = this._map.getZoom(), floatZoomDelta = Math.log(this._scale)/Math.LN2, roundZoomDelta = (floatZoomDelta > 0 ? Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)), zoom = this._map._limitZoom(oldZoom + roundZoomDelta), zoomDelta = zoom - oldZoom, centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale), centerPoint = this._map.getPixelOrigin().add(this._startCenter).add(centerOffset), center = this._map.unproject(centerPoint); L.DomEvent.removeListener(document, 'touchmove', this._onTouchMove); L.DomEvent.removeListener(document, 'touchend', this._onTouchEnd); var finalScale = Math.pow(2, zoomDelta); this._map._runAnimation(center, zoom, finalScale / this._scale, this._startCenter.add(centerOffset)); } }); });
JavaScript
0.000482
@@ -3183,13 +3183,8 @@ %0A%09%7D%0D%0A%7D); -%0A%7D);%0A
d05ff7d23830fdd0bdb4563be1b4284892c3b9c1
Fix read based on tests
lib/read.js
lib/read.js
'use strict'; var fs = require('fs'); var path = require('path'); var through = require('through2'); function read(fn) { var options = arguments.lenght > 1 ? arguments[1] : 'utf8'; return through.obj(function (file, e, cb) { if (options === null || typeof options === 'string') { if (file.stats.isDirectory()) { fs.readdir(file.path, function (err, files) { if (err) { cb(err); return; } fn(files); cb(null, file); }); } else { fs.readFile(file.path, options, function (err, data) { if (err) { cb(err); return; } fn(data); cb(null, file); }); } } else { fn(fs.createReadStream(file.path, options)); cb(null, file); } }); } module.exports = read;
JavaScript
0.000003
@@ -41,39 +41,8 @@ ');%0A -var path = require('path');%0A var @@ -93,26 +93,36 @@ d(fn +, options ) %7B%0A -var +if (! options = ar @@ -121,55 +121,52 @@ ons -= arguments.lenght %3E 1 ? arguments%5B1%5D : +&& options !== null) %7B%0A options = 'utf8'; %0A%0A @@ -161,16 +161,20 @@ 'utf8'; +%0A %7D %0A%0A retu
adc7d744340076ab15dbac916c9ca22e07e589ce
update file /lib/saml.js
lib/saml.js
lib/saml.js
var express = require('express'); var bodyParser = require('body-parser'); var cors = require('cors'); var xml2js = require('xml2js'); var fh = require('fh-mbaas-api'); var parseString = xml2js.parseString; var stripPrefix = xml2js.processors.stripPrefix; var normalize = xml2js.processors.normalize; var path = require('path'); var request = require('request'); function samlRoute() { var saml = new express.Router(); saml.use(cors()); saml.use(bodyParser()); saml.all('/saml/consume', function(req, res){ // Intra-service call to our SAML service to SSO the ID var newUrl = process.env.SAML_SERVICE || 'https://bombardier-e7rjjcdl3f4qadrerth6qa7g-dev.mbaas1.us.feedhenry.com'; return request(path.join(newUrl, req.path)).pipe(res); // return fh.service({ // "guid": process.env.SAML_SERVICE || "e7rjjcdl3f4qadrerth6qa7g", // "path": "/login/callback", // "method": "POST", // "params": req.body // }, function(err, body, serviceResponse) { // if (err) { // // An error occurred // return res.status(500).json({ responseFromSiteminder : res.body, errorFromService : err }); // } // console.log('response from service:'); // console.log(serviceResponse.body); // return res.status(200).json({ responseFromSiteminder : req.body, responseFromService : body }); // }); return res.json({ok : true}); }); saml.post('/saml/login', function(req, res){ function gotResponse(body){ var samlBody = /value\s?=\s?"([a-zA-Z0-9+=\/\s]+)">/g, samlAssertion = samlBody.exec(body); if (!samlAssertion || samlAssertion.length !== 2){ return res.status(401).json({ error : "No SAML assertion found in response" }); } // take the regex'd result, the b64 string samlAssertion = samlAssertion[1]; try{ samlAssertion = new Buffer(samlAssertion, 'base64').toString(); }catch(err){ return res.status(401).json({error : "Error decoding base64 saml assertion"}); } parseString(samlAssertion, { normalize : true, explicitArray : false, attrNameProcessors : [stripPrefix], tagNameProcessors : [stripPrefix, normalize] }, function (err, samlAsJSON) { if (err){ return res.status(500).json({ error : "Error parsing SAML response XML"}); } var assertion = samlAsJSON && samlAsJSON.response && samlAsJSON.response.assertion || samlAsJSON; return res.json(assertion); }); } var request = require('request'), username = req.body.username, password = req.body.password, auth = { user : username, pass : password, sendImmediately : true }; // Step 1 - request the AUTH_URL and get redirected request.get({ url : process.env.SAML_URL, followRedirect : false, followAllRedirects : false, jar : true, headers : { 'Cookie' : 'SMCHALLENGE=YES' } }, function(err, response, body){ if (response && response.statusCode === 200){ return gotResponse(response.body); } if (err || !response.headers || !response.headers.location){ return res.status(500).json(err || 'No redirect found'); } // Step 2 - follow the redirect, picking up cookies along the way as part of the // Federation - Affwebservices basic auth challenge var newUrl = response.headers.location; request.get({ url : newUrl, jar : true }, function(err){ if (err){ return res.status(500).json(err); } // Now that we've picked up all the cookies we need, this is the "money shot". // A reply from this should give us our SAML response. request.get({ url : newUrl, jar : true, auth : auth }, function(err, response, body){ if (err){ return res.status(500).json(err); } if (response.statusCode !== 200){ return res.status(response.statusCode).end(body); } return gotResponse(response.body); }); }); }); }); return saml; } module.exports = samlRoute;
JavaScript
0.000001
@@ -699,23 +699,17 @@ -return request( +newUrl = path @@ -731,16 +731,73 @@ eq.path) +;%0A console.log(newUrl);%0A return request.post(newUrl ).pipe(r
60ac07fbd4e37df13ce33a4c73cfefa866453a22
Add Test send message success test case
test/view.sendmessage.js
test/view.sendmessage.js
'use strict'; var express = require('express'); var request = require('supertest'); var logger = require('log4js').getLogger('Unit-Test'); exports['Test recevie message'] = function(test){ }
JavaScript
0
@@ -134,17 +134,16 @@ est');%0A%0A -%0A exports%5B @@ -152,23 +152,20 @@ est -recevie +send message '%5D = @@ -160,16 +160,24 @@ message + success '%5D = fun @@ -195,6 +195,119 @@ %7B%0A%0A%09 +var sendObject = %7B%0A%09%09message:%7B%0A%09%09%09receiver:'@tester';%0A%09%09%09text:'Hello World!';%0A%09%7D%0A%0A%09time:new Date().getTime();%0A%09%0A%0A%7D %0A -%7D
dd6df46c39301e865364753f2c5e7fbbc4311858
improve generic methods building.
lib/site.js
lib/site.js
/** * Module dependencies. */ var Post = require('./post'); var Media = require('./media'); var debug = require('debug')('wpcom:site'); /** * Resources array */ var resources = [ 'categories', 'comments', 'follows', 'media', 'posts', 'stats', 'tags', 'users' ]; /** * Create a Site instance * * @param {WPCOM} wpcom * @api public */ function Site(id, wpcom){ if (!(this instanceof Site)) return new Site(id, wpcom); this.wpcom = wpcom; debug('set `%s` site id', id); this._id = id; } /** * Require site information * * @param {Object} [query] * @param {Function} fn * @api public */ Site.prototype.get = function(query, fn){ this.wpcom.sendRequest('/sites/' + this._id, query, null, fn); }; /** * List method builder * * @param {String} name * @param {Function} * @api private */ var list = function(resource) { debug('builind `site.%sList()` method', resource); /** * Return the <resources>List method * * @param {Object} [query] * @param {Function} fn * @api public */ return function (query, fn){ this.wpcom.sendRequest('/sites/' + this._id + '/' + resource, query, null, fn); }; }; // walk for each resource and create <resources>List method for (var i = 0; i < resources.length; i++) { Site.prototype[resources[i] + 'List'] = list.call(this, resources[i]); } /** * :POST: * Create a `Post` instance * * @param {String} id * @api public */ Site.prototype.post = function(id){ return Post(id, this._id, this.wpcom); }; /** * :POST: * Add a new blog post * * @param {Object} body * @param {Function} fn * @return {Post} new Post instance */ Site.prototype.addPost = function(body, fn){ var post = Post(null, this._id, this.wpcom); post.add(body, fn); return post; }; /** * :POST: * Delete a blog post * * @param {String} id * @param {Function} fn * @return {Post} remove Post instance */ Site.prototype.deletePost = function(id, fn){ var post = Post(id, this._id, this.wpcom); post.delete(fn); return post; }; /** * :MEDIA: * Create a `Media` instance * * @param {String} id * @api public */ Site.prototype.media = function(id){ return Media(id, this._id, this.wpcom); }; /** * :MEDIA: * Add a media from a file * * @param {Array|String} files * @param {Function} fn * @return {Post} new Post instance */ Site.prototype.addMediaFiles = function(files, fn){ var media = Media(null, this._id, this.wpcom); media.addFiles(files, fn); return media; }; /** * :MEDIA: * Add a new media from url * * @param {Array|String} files * @param {Function} fn * @return {Post} new Post instance */ Site.prototype.addMediaUrls = function(files, fn){ var media = Media(null, this._id, this.wpcom); media.addUrls(files, fn); return media; }; /** * :MEDIA: * Delete a blog media * * @param {String} id * @param {Function} fn * @return {Post} removed Media instance */ Site.prototype.deleteMedia = function(id, fn){ var media = Media(id, this._id, this.wpcom); media.del(fn); return media; }; /** * Expose `Site` module */ module.exports = Site;
JavaScript
0
@@ -256,16 +256,57 @@ stats',%0A + %5B 'statsVisitsList', 'stats/visits' %5D,%0A 'tags' @@ -829,12 +829,15 @@ ng%7D -name +subpath %0A * @@ -899,72 +899,18 @@ ion( -resource) %7B%0A debug('builind %60site.%25sList()%60 method', resource); +subpath) %7B %0A%0A @@ -930,23 +930,19 @@ rn the %3C -resourc +nam es%3EList @@ -1119,24 +1119,23 @@ + '/' + -resource +subpath , query, @@ -1266,76 +1266,270 @@ %7B%0A -Site.prototype%5Bresources%5Bi%5D + 'List'%5D = list.call(this, resources%5Bi%5D +var res = resources%5Bi%5D;%0A var isarr = Array.isArray(res);%0A%0A var name = isarr ? res%5B0%5D : res + 'List';%0A var subpath = isarr ? res%5B1%5D : res;%0A%0A debug('builind %60site.%25s()%60 method in %60%25s%60 sub-path', name, subpath);%0A Site.prototype%5Bname%5D = list.call(this, subpath );%0A%7D
cd66ebcaccae8057f2cfb2c37b59779e1a852fd1
Add ideas for page transformations.
lib/site.js
lib/site.js
var Site , fs = require('fs') , path = require('path') , config = JSON.parse(fs.readFileSync('_config.json', 'utf8')) , glob = require('glob') , minimatch = require('minimatch') , File = require('./file') Site = { build: function() { // var matcher = new Glob('**/*', {dot: true}) // matcher.on('match', function(filename) { // // ignore files or directories at the root // // level that start with an underscore // if (filename[0] == '_') return // // ignore directories // // TODO: consider async // if (!fs.statSync(filename).isFile()) return // // ignore files that have been explicitly excluded // if (config.exclude && config.exclude.some(function(pattern) { // return minimatch(filename, pattern) // })) { // console.log(filename, config.exclude) // return // } // // still here? must be a match // // console.log(filename) // new File(filename) // }) // matcher.on('end', function() { // console.log("matching complete...") // }) glob .sync('**/*', {dot: true}) .forEach(function(filename) { // ignore files or directories at the root // level that start with an underscore if (filename[0] == '_') return // ignore directories // TODO: consider async if (!fs.statSync(filename).isFile()) return // ignore files that have been explicitly excluded if (config.exclude && config.exclude.some(function(pattern) { return minimatch(filename, pattern) })) { console.log(filename, config.exclude) return } // still here? must be a match // console.log(filename) new File(filename) }) }, serve: function(port) { } } module.exports = Site
JavaScript
0
@@ -248,846 +248,8 @@ %7B%0A%0A - // var matcher = new Glob('**/*', %7Bdot: true%7D)%0A%0A // matcher.on('match', function(filename) %7B%0A // // ignore files or directories at the root%0A // // level that start with an underscore%0A // if (filename%5B0%5D == '_') return%0A%0A // // ignore directories%0A // // TODO: consider async%0A // if (!fs.statSync(filename).isFile()) return%0A%0A // // ignore files that have been explicitly excluded%0A // if (config.exclude && config.exclude.some(function(pattern) %7B%0A // return minimatch(filename, pattern)%0A // %7D)) %7B%0A // console.log(filename, config.exclude)%0A // return%0A // %7D%0A%0A // // still here? must be a match%0A // // console.log(filename)%0A // new File(filename)%0A // %7D)%0A%0A // matcher.on('end', function() %7B%0A // console.log(%22matching complete...%22)%0A // %7D)%0A%0A @@ -253,16 +253,16 @@ glob%0A + .s @@ -987,19 +987,362 @@ %7B%0A%0A %7D%0A%0A - %7D%0A%0A +/*%0A%0A Page.addTransformer(function(page) %7B%0A if (page.extension == %22.md%22) %7B%0A return page.renderMarkdown()%0A %7D%0A %7D)%0A%0A Page.addTransformer(function(page) %7B%0A if (page.extension == %22.html%22) %7B%0A return page.renderTempalte()%0A %7D%0A %7D)%0A%0A Site.on(%22beforeBuild%22, function(site) %7B%7D)%0A%0A Site.on(%22afterBuild%22, function(site) %7B%7D)%0A%0A%0A%0A*/%0A%0A module.e
e66f71aabeb4f25c216768a89081fd3b88f60988
Remove unneccessary encoding type.
lib/soap.js
lib/soap.js
/* * Copyright (c) 2011 Vinay Pulim <[email protected]> * MIT Licensed */ var Client = require('./client').Client, Server = require('./server').Server, WSDL = require('./wsdl').WSDL, http = require('./http'), fs = require('fs'), crypto = require('crypto'); var _wsdlCache = {}; function _requestWSDL(url, callback) { var wsdl = _wsdlCache[url]; if (wsdl) { callback(null, wsdl); } else if (!/^http/.test(url)) { fs.readFile(url, 'utf8', function (err, data) { if (err) { callback(err) } else { wsdl = new WSDL(data); _wsdlCache[url] = wsdl; callback(null, wsdl); } }) } else { http.request(url, null, function(err, response) { if (err) { callback(err); } else if (response && response.statusCode == 200){ wsdl = new WSDL(response.body); _wsdlCache[url] = wsdl; callback(null, wsdl); } else { callback(new Error('Invalid WSDL URL: '+url)) } }); } } function createClient(url, callback) { _requestWSDL(url, function(err, wsdl) { callback(err, wsdl && new Client(wsdl)); }) } function listen(server, path, services, xml) { var wsdl = new WSDL(xml || services); return new Server(server, path, services, wsdl); } function WSSecurity(username, password) { this._username = username; this._password = password; } WSSecurity.prototype.toXML = function() { // avoid dependency on date formatting libraries function getDate(d) { function pad(n){return n<10 ? '0'+n : n} return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z'; } var now = new Date(); var created = getDate( now ); var expires = getDate( new Date(now.getTime() + (1000 * 600)) ); // nonce = base64 ( sha1 ( created + random ) ) var nHash = crypto.createHash('sha1'); nHash.update(created + Math.random()); var nonce = nHash.digest('base64'); // digest = base64 ( sha1 ( nonce + created + password ) ) var pwHash = crypto.createHash('sha1'); var rawNonce = new Buffer(nonce || '', 'base64').toString('utf8'); pwHash.update( rawNonce + created + this._password ); var passwordDigest = pwHash.digest('base64'); return "<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" soap:mustUnderstand=\"1\">" + "<wsu:Timestamp wsu:Id=\"Timestamp-"+created+"\">" + "<wsu:Created>"+created+"</wsu:Created>" + "<wsu:Expires>"+expires+"</wsu:Expires>" + "</wsu:Timestamp>" + "<wsse:UsernameToken>" + "<wsse:Username>"+this._username+"</wsse:Username>" + "<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest\">"+passwordDigest+"</wsse:Password>" + "<wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">"+nonce+"</wsse:Nonce>" + "<wsu:Created>"+created+"</wsu:Created>" + "</wsse:UsernameToken>" + "</wsse:Security>" } exports.WSSecurity = WSSecurity; exports.createClient = createClient; exports.listen = listen;
JavaScript
0.000389
@@ -3410,120 +3410,8 @@ once - EncodingType=%5C%22http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary%5C%22 %3E%22+n
57e6351b72d5c1e73f0aad75b54cd8998c0c16dd
Fix graphrows rendering to late as you scrolldown
npactweb/npactweb/static/js/graphs/graph.js
npactweb/npactweb/static/js/graphs/graph.js
angular.module('npact') .controller('npactGraphContainerCtrl', function($scope, $element, $window, $log, $timeout, npactConstants, Utils, GraphConfig, Evt, GraphingCalculator) { 'use strict'; var getWidth = function() { return $element.width() - 15; //from style.css `.graph` }; //The mouse event responders var onPan = function(offset) { GraphConfig.offset += Math.round(offset); $scope.$apply(); }, onZoom = function(opts) { $log.log('Zoom event:', opts); var zoomOpts = angular.extend({}, GraphConfig, opts); //updates `offset`, and `basesPerGraph` angular.extend(GraphConfig, GraphingCalculator.zoom(zoomOpts)); $scope.$apply(); }; //The baseOpts are the graph options that are the same for every graph var baseOpts = { width: getWidth(), onPan: onPan, onZoom: onZoom }; this.graphOptions = function(idx) { // This function builds the specific options for a graph; as // many graph rows will never be drawn this only generates the // object for a row when needed. var start = $scope.graphSpecs[idx]; var opts = { startBase: start, endBase: start + GraphConfig.basesPerGraph}; opts = angular.extend(opts, baseOpts); return opts; }; var draw = function() { $scope.$broadcast(Evt.DRAW); }, redraw = function() { if (!baseOpts.axisTitle || !baseOpts.m) return; //too early to do anything $scope.$broadcast(Evt.REDRAW); }, rebuild = function() { if (!baseOpts.axisTitle || !baseOpts.m) return; //too early to do anything $scope.$broadcast(Evt.REBUILD); }; /*** Watch the config for changes we care about ***/ $scope.$watchCollection( function() { return [GraphConfig.length, GraphConfig.basesPerGraph, GraphConfig.offset, GraphConfig.startBase, GraphConfig.endBase]; }, function() { // basic row geometry changed, repartition and rebuild if(GraphConfig.startBase === undefined || GraphConfig.endBase === undefined || GraphConfig.basesPerGraph === undefined) { return; } $scope.graphSpecs = GraphingCalculator.partition(GraphConfig); $log.log('Partitioned into', $scope.graphSpecs.length, 'rows.'); updateVisibility(); //number of rows might have changed. $timeout(rebuild); }); $scope.$watch(GraphConfig.profileTitle, function(title) { //A profileTitle change indicates different nucleotides: rebuild baseOpts.axisTitle = title; rebuild(); }); $scope.$watch(GraphConfig.activeTracks, function(val) { //Find headers and headerY baseOpts.tracks = val; baseOpts.m = GraphingCalculator.chart(baseOpts); updateRowHeight(baseOpts.m.height); redraw(); }, true); $scope.$watch(function() { return GraphConfig.colorBlindFriendly; }, function(val) { baseOpts.colors = val ? npactConstants.colorBlindLineColors : npactConstants.lineColors; redraw(); }); /*** Scrolling and Graph Visibility management ***/ var $win = angular.element($window), winHeight = $win.height(), slack = 50, // how many pixels outside of viewport to render topOffset = $element.offset().top, topIdx = 0, bottomIdx = 0, graphRowHeight = 0, updateRowHeight = function(height) { $scope.graphHeight = height; //add padding and border from style.css `.graph` graphRowHeight = height + 8 + 8 + 1; updateVisibility(); }, updateVisibility = function() { if(!baseOpts.m) return; var scrollDist = $window.scrollY - topOffset - slack; topIdx = Math.floor(scrollDist / graphRowHeight); bottomIdx = topIdx + Math.ceil(winHeight / graphRowHeight); }, onScroll = function() { updateVisibility(); draw(); }, onResize = function() { winHeight = $win.height(); if(getWidth() !== baseOpts.width) { topOffset = $element.offset().top; baseOpts.width = getWidth(); baseOpts.m = GraphingCalculator.chart(baseOpts); updateVisibility(); redraw(); } else { //If the width didn't change then its the same as scrolling onScroll(); } }; this.visible = function(idx) { return idx >= topIdx && idx <= bottomIdx; }; $win.on('resize', onResize); $win.on('scroll', onScroll); $scope.$on('$destroy', function() { $win.off('resize', onResize); $win.off('scroll', onScroll); }); }) .directive('npactGraphContainer', function(STATIC_BASE_URL) { return { restrict: 'A', scope: {}, templateUrl: STATIC_BASE_URL + 'js/graphs/graph-container.html', controller: 'npactGraphContainerCtrl as ctrl' }; }) .directive('npactGraph', function (Grapher, Evt, GraphingCalculator, $log, $timeout) { 'use strict'; return { restrict: 'A', require: '^npactGraphContainer', link: function($scope, $element, $attrs, ctrl) { var g = null, visible = ctrl.visible, idx = $attrs.idx, el = $element[0], // redraw gets set for all graphs once (e.g. a new track // triggers broadcasts redraw), but only gets cleared as // the currently visible ones are drawn redraw = false, draw = function(force) { if(!redraw || (!force && !visible(idx))) { return null; } var opts = ctrl.graphOptions(idx); //However long it actually takes to draw, we have the //latest options as of this point redraw = false; return (g || (g = new Grapher(el, opts))) .redraw(opts) .catch(function() { //something went wrong, we will still need to redraw this redraw = true; }); }, schedule = function(force) { if(!redraw || (!force && !visible(idx))) { return null; } return $timeout(_.partial(draw, force), 0, false); }, discard = function() { if(g) { g.destroy(); g = null; } }; $scope.$on(Evt.DRAW, _.partial(schedule, false)); $scope.$on(Evt.REDRAW, function() { redraw = true; schedule();}); $scope.$on(Evt.REBUILD, function() { discard(); redraw = true; schedule(); }); $scope.$on('$destroy', discard); $scope.$on('print', function(evt, callback) { var p = schedule(true); if(p) { callback(p.then(function() { return g.replaceWithImage(); })); } else { callback(g.replaceWithImage()); } }); } }; }) .directive('npactExtract', function(STATIC_BASE_URL) { return { restrict: 'A', scope: { extract: '=npactExtract'}, templateUrl: STATIC_BASE_URL + 'js/graphs/extract.html' }; }) ;
JavaScript
0
@@ -3472,17 +3472,17 @@ slack = -5 +2 0, // ho @@ -4101,16 +4101,17 @@ th.ceil( +( winHeigh @@ -4111,16 +4111,25 @@ inHeight + + slack) / graph
c661e51be4d6c7e005a1ba210f84ee666ac636a3
read Content-Type header in camel case, which fixes #2
response.js
response.js
'use strict'; var util = require('util'); var streams = require('memory-streams'); var contentTypes = require('./contentTypes'); /** * An in memory HTTP Response that captures any data written to it * so that it can be easily serialised into a lambda payload * * @callback done called when end is called on this response * * @class * @param done * @constructor */ function LambdaHttpResponse(done) { streams.WritableStream.call(this); this.done = done; this.headers = {}; this.headersSet = false; this.statusCode = 200; this.statusMessage = undefined; } util.inherits(LambdaHttpResponse, streams.WritableStream); LambdaHttpResponse.prototype.setTimeout = function(msecs, callback) {} LambdaHttpResponse.prototype.destroy = function(error) {} LambdaHttpResponse.prototype.setHeader = function(name, value) { this.headers[name] = value; } LambdaHttpResponse.prototype.getHeader = function(name) { return this.headers[name]; } LambdaHttpResponse.prototype.removeHeader = function(name) { delete this.headers[name] } LambdaHttpResponse.prototype.flushHeaders = function() {} LambdaHttpResponse.prototype.writeHead = function(statusCode, reason, obj) { if (typeof reason === 'string') { // writeHead(statusCode, reasonPhrase[, headers]) this.statusMessage = reason; } else { // writeHead(statusCode[, headers]) this.statusMessage = this.statusMessage || ''; obj = reason; } this.statusCode = statusCode; if (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (k) this.setHeader(k, obj[k]); } } } LambdaHttpResponse.prototype.end = function(data, encoding, callback) { LambdaHttpResponse.super_.prototype.end.apply(this, arguments); if(this.done) { this.done(this); } } /** * @callback done called when end is called on this response * @param done * @returns {LambdaHttpResponse} */ function newResponse(done) { return new LambdaHttpResponse(done); } /** * Serialises a LambdaHttpResponse * @param {LambdaHttpResponse} httpResponse * @returns {{headers: Object.<string, string>, statusCode: number, bodyBase64: string}} */ function convert(httpResponse) { var lambdaResponse = { headers: httpResponse.headers, statusCode: httpResponse.statusCode }; var contentTypeHeader = httpResponse.headers['content-type']; if(contentTypeHeader && contentTypes.isText(contentTypeHeader)) { lambdaResponse.body = httpResponse.toBuffer().toString(); } else { lambdaResponse.bodyBase64 = httpResponse.toBuffer().toString('base64'); } if(httpResponse.statusMessage) { lambdaResponse.statusMessage = httpResponse.statusMessage; } return lambdaResponse; } module.exports = { newResponse: newResponse, LambdaHttpResponse: LambdaHttpResponse, convert: convert }
JavaScript
0
@@ -2360,17 +2360,17 @@ rs%5B' -c +C ontent- -t +T ype' @@ -2832,8 +2832,9 @@ onvert%0A%7D +%0A
0fbe4bb846364b2208da9759704b71d00219dfc7
change adding parents
browscap.js
browscap.js
var jsonfile = './browscap.preprocessed.json'; exports.setJson = function (filename) { jsonfile = filename; }; exports.getBrowser = function (userAgent) { var browsers, patterns, re, key, found, matches, browsersindex; patterns = require(jsonfile).patterns; browsers = require(jsonfile).browsers; // Test user agent against each browser regex for (var pattern in patterns) { if (!patterns.hasOwnProperty(pattern)) { continue; } re = new RegExp(pattern.replace(/@/g, ''), 'i'); if (re.test(userAgent)) { key = patterns[pattern]; found = false; matches = userAgent.match(re); if (matches.length === 1) { browsersindex = key; found = true; } else { var matchString = '@' + matches.join('|'); if (key[matchString]) { browsersindex = key[matchString]; found = true; } } if (found && browsers[browsersindex]) { var browser = [userAgent, pattern.toLowerCase().trim()]; var browserData = JSON.parse(browsers[browsersindex]); for (var property in browserData) { if (!browserData.hasOwnProperty(property)) { continue; } browser[property] = browserData[property]; } while (browserData['Parent']) { browserData = JSON.parse(browsers[browserData['Parent']]); for (var propertyParent in browserData) { if (!browserData.hasOwnProperty(propertyParent)) { continue; } browser[propertyParent] = browserData[propertyParent]; } } if (browser['Parent']) { var userAgents = require(jsonfile).userAgents; browser['Parent'] = userAgents[browser['Parent']]; } return browser; } } } return null; };
JavaScript
0.000001
@@ -1320,23 +1320,33 @@ +var browser +Parent Data = J @@ -1426,32 +1426,38 @@ arent in browser +Parent Data) %7B%0A @@ -1464,32 +1464,38 @@ if (!browser +Parent Data.hasOwnPrope @@ -1548,32 +1548,129 @@ %0A %7D%0A%0A + if (browser.hasOwnProperty(propertyParent)) %7B%0A continue;%0A %7D%0A%0A brow @@ -1690,32 +1690,38 @@ arent%5D = browser +Parent Data%5BpropertyPar
f6ce888daee52833d50c7aa3bc22bc258b6b50b5
Add payload endpoint to redis caching
src/middleware/redis.js
src/middleware/redis.js
const url = require('url'); /** * Declare options for Redis with remote server */ let options; if (process.env.REDISCLOUD_URL) { const redisURL = url.parse(process.env.REDISCLOUD_URL); options = { routes: [{ path: '/v2/launches', expire: 30, }, { path: '/v2/launches/(.*)', expire: 30, }, { path: '/v2/parts/(.*)', expire: 6000, }, { path: '/v2', expire: 43200, }, { path: '/v2/info', expire: 43200, }, { path: '/v2/launchpads/(.*)', expire: 43200, }, { path: '/v2/rockets/(.*)', expire: 43200, }, { path: '/v2/capsules/(.*)', expire: 43200, }], redis: { host: redisURL.hostname, port: redisURL.port, options: { password: redisURL.auth.split(':')[1], }, }, }; } else { options = { routes: [{ path: '/v2/launches', expire: 30, }, { path: '/v2/launches/(.*)', expire: 30, }, { path: '/v2/parts/(.*)', expire: 6000, }, { path: '/v2', expire: 43200, }, { path: '/v2/info', expire: 43200, }, { path: '/v2/launchpads/(.*)', expire: 43200, }, { path: '/v2/rockets/(.*)', expire: 43200, }, { path: '/v2/capsules/(.*)', expire: 43200, }], }; } module.exports = options;
JavaScript
0
@@ -982,32 +982,92 @@ e: 30,%0A %7D, %7B%0A + path: '/v2/payloads/(.*)',%0A expire: 30,%0A %7D, %7B%0A path: '/v2
0f1c7e18fae93cec4c563b399f9465a3e5c2be55
rename Cell to CellModel [as it is model]
src/model/cell_model.js
src/model/cell_model.js
export default class Cell { constructor(coordinate) { this.coordinate = coordinate; } static getCoordinateCharacter(coordinate) { return coordinate.charAt(0); } static getCoordinateDigit(coordinate) { return parseInt(coordinate.substring(1)); } }
JavaScript
0
@@ -18,16 +18,21 @@ ass Cell +Model %7B%0A c
b4956188cec7a0cccee5859533a90be8ccfa90df
Update vmConstants.js
lib/util/vmConstants.js
lib/util/vmConstants.js
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // exports = module.exports; var VMConstants = { EXTENSIONS: { TYPE: 'Microsoft.Compute/virtualMachines/extensions', IAAS_DIAG_VERSION: '1.4', LINUX_DIAG_VERSION: '2.0', LINUX_DIAG_NAME: 'LinuxDiagnostic', IAAS_DIAG_NAME: 'IaaSDiagnostics', LINUX_DIAG_PUBLISHER: 'Microsoft.OSTCExtensions', IAAS_DIAG_PUBLISHER: 'Microsoft.Azure.Diagnostics', IAAS_AEM_VERSION: '2.0', IAAS_AEM_NAME: 'AzureCATExtensionHandler', IAAS_AEM_PUBLISHER: 'Microsoft.AzureCAT.AzureEnhancedMonitoring', LINUX_AEM_VERSION: '3.0', LINUX_AEM_NAME: 'AzureEnhancedMonitorForLinux', LINUX_AEM_PUBLISHER: 'Microsoft.OSTCExtensions', DOCKER_PORT: 2376, DOCKER_VERSION_ARM: '1.0', DOCKER_VERSION_ASM: '1.*', DOCKER_NAME: 'DockerExtension', DOCKER_PUBLISHER: 'Microsoft.Azure.Extensions', LINUX_ACCESS_VERSION: '1.1', LINUX_ACCESS_NAME: 'VMAccessForLinux', LINUX_ACCESS_PUBLISHER: 'Microsoft.OSTCExtensions', WINDOWS_ACCESS_VERSION: '2.0', WINDOWS_ACCESS_NAME: 'VMAccessAgent', WINDOWS_ACCESS_PUBLISHER: 'Microsoft.Compute', BGINFO_VERSION: '2.1', BGINFO_NAME: 'BGInfo', BGINFO_PUBLISHER: 'Microsoft.Compute', AZURE_DISK_ENCRYPTION_WINDOWS_EXTENSION_VERSION: '1.0', AZURE_DISK_ENCRYPTION_WINDOWS_EXTENSION_NAME: 'AzureDiskEncryption', AZURE_DISK_ENCRYPTION_WINDOWS_EXTENSION_PUBLISHER: 'Microsoft.Azure.Security', AZURE_DISK_ENCRYPTION_LINUX_EXTENSION_VERSION: '0.1', AZURE_DISK_ENCRYPTION_LINUX_EXTENSION_NAME: 'AzureDiskEncryptionForLinux', AZURE_DISK_ENCRYPTION_LINUX_EXTENSION_PUBLISHER: 'Microsoft.OSTCExtensions', EXTENSION_PROVISIONING_SUCCEEDED: 'Succeeded' }, //VM sizes stated on https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-size-specs/ PREMIUM_STORAGE_VM_SIZES:{ // DS-SERIES STANDARD_DS1: {IOPS: 3200, THROUGHPUT: 32}, STANDARD_DS2: {IOPS: 6400, THROUGHPUT: 64}, STANDARD_DS3: {IOPS: 12800, THROUGHPUT: 128}, STANDARD_DS4: {IOPS: 25600, THROUGHPUT: 256}, STANDARD_DS11: {IOPS: 6400, THROUGHPUT: 64}, STANDARD_DS12: {IOPS: 12800, THROUGHPUT: 128}, STANDARD_DS13: {IOPS: 25600, THROUGHPUT: 256}, STANDARD_DS14: {IOPS: 50000, THROUGHPUT: 512}, //GS-SERIES STANDARD_GS1: {IOPS: 5000, THROUGHPUT: 125}, STANDARD_GS2: {IOPS: 10000, THROUGHPUT: 250}, STANDARD_GS3: {IOPS: 20000, THROUGHPUT: 500}, STANDARD_GS4: {IOPS: 40000, THROUGHPUT: 1000}, STANDARD_GS5: {IOPS: 80000, THROUGHPUT: 2000}, }, PREMIUM_STORAGE_ACCOUNTS:{ P10: {IOPS: 500, THROUGHPUT: 100}, P20: {IOPS: 2300, THROUGHPUT: 150}, P30: {IOPS: 5000, THROUGHPUT: 200}, } }; module.exports = VMConstants;
JavaScript
0
@@ -1017,25 +1017,25 @@ VERSION: '2. -0 +2 ',%0A IAAS_
62c38b758231d5d4c1bf02d07e0d8fac3cb5cd83
Fix to saml request to allow variance in idp authentication method.
lib/util.js
lib/util.js
var zlib = require('zlib'); var crypto = require('crypto'); var xmldom = require('xmldom'); var xmlCrypto = require('xml-crypto'); var xpath = require('xpath'); var _ = require('lodash'); function generateUniqueId() { var chars = "abcdef0123456789"; var uniqueID = ""; for (var i = 0; i < 20; i++) { uniqueID += chars.substr(Math.floor((Math.random()*15)), 1); } return "_" + uniqueID; } module.exports.generateUniqueId = generateUniqueId; module.exports.cleanXML = function(xml) { return xml.replace(/\>\s*\</g, "><"); } module.exports.deflateAndEncode = function(xml, cb) { zlib.deflateRaw(xml, function(err, deflatedXML) { if(err) return cb(err); deflatedXML = deflatedXML.toString("base64"); cb(null, deflatedXML); }); }; module.exports.inflateAndDecode = function(base64, cb) { var decoded = new Buffer(base64, 'base64'); zlib.inflateRaw(decoded, function(err, inflatedXML) { if(err) return cb(err); cb(null, inflatedXML.toString()); }); }; module.exports.decode = function(content, sourceEncoding, targetEncoding) { return Buffer(content, sourceEncoding).toString(targetEncoding); }; function certToPEM(cert) { cert = cert.match(/.{1,64}/g).join('\n'); cert = "-----BEGIN CERTIFICATE-----\n" + cert; cert = cert + "\n-----END CERTIFICATE-----\n"; return cert; } function PEMToCert(pem) { var cert = []; _.each(pem.split("\n"), function(line) { if(line && line.indexOf("----") != 0) cert.push(line); }); return cert.join("\n"); } module.exports.certToPEM = certToPEM; module.exports.PEMToCert = PEMToCert; module.exports.signRequest = function(request, cert) { var signer = crypto.createSign('RSA-SHA1'); signer.update(request); return signer.sign(cert, 'base64'); }; module.exports.verifyResponse = function(doc, xml, cert) { if(!doc) return false; var signature = xmlCrypto.xpath(doc, "//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0]; if(!signature) return false; var sig = new xmlCrypto.SignedXml(); sig.keyInfoProvider = { getKeyInfo: function (key) { return "<X509Data></X509Data>"; }, getKey: function (keyInfo) { return certToPEM(cert); } }; sig.loadSignature(signature.toString()); return sig.checkSignature(xml); }; module.exports.signAuthenticationResponse = function (xml, privateCertPem, cert) { if(!xml) return false; var sig = new xmlCrypto.SignedXml(); sig.addReference("//*[local-name(.)='Assertion']", [ "http://www.w3.org/2000/09/xmldsig#enveloped-signature", "http://www.w3.org/2001/10/xml-exc-c14n#" ]); sig.signingKey = new Buffer(privateCertPem).toString('ascii'); sig.keyInfoProvider = { getKeyInfo: function (key) { return "<X509Data><X509Certificate>" + PEMToCert(cert) + "</X509Certificate></X509Data>"; } }; sig.computeSignature(xml); // need to insert the signature in the assertion var dom = new xmldom.DOMParser(); var signedXmlDom = dom.parseFromString(sig.getOriginalXmlWithIds()); var signatureXmlDom = dom.parseFromString(sig.getSignatureXml()); var subjectElement = signedXmlDom.getElementsByTagName("saml:Subject")[0]; signedXmlDom.documentElement.insertBefore(signatureXmlDom.documentElement, subjectElement); return '<?xml version="1.0" encoding="UTF-8"?>' + "\n" + signedXmlDom.toString(); }; module.exports.generateAuthRequestParams = function(settings, overrides) { overrides = overrides || {}; // these are the parameters to the ejs template return _.defaults(overrides, { "uniqueId" : generateUniqueId(), "issueInstant" : new Date().toISOString(), "version" : "2.0", "protocolBinding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", "assertionConsumerServiceUrl" : settings.sp.assertionConsumerServiceUrl, "spInitiatedRedirectUrl" : settings.idp.spInitiatedRedirectUrl, "issuer" : settings.sp.issuer, "nameIdFormat" : settings.sp.nameIdFormat || "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", "nameIdAllowCreate" : settings.sp.nameIdAllowCreate || "true", "relayState" : null, "requestedAuthenticationContext" : { "comparison" : "exact", "authenticationContextClassRef" : "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" } }); }; module.exports.generateAuthResponseParams = function(settings, overrides) { overrides = overrides || {}; var now = new Date(); // these are the parameters to the ejs template return _.defaults(overrides, { responseId: generateUniqueId(), assertionId: generateUniqueId(), spAssertionId: settings.sp.authRequestId, timestamp: now.toISOString(), notOnOrAfter: settings.conditions.notOnOrAfter, acsUrl: settings.sp.acsUrl, issuer: settings.idp.issuer, nameQualifier: settings.idp.nameQualifier, email: settings.subject.email, sessIndex: settings.subject.sessIdEncrypted, attributes: settings.subject.attributes, conditions: settings.idp.excludeConditions ? null : settings.conditions, excludeInResponseTo: settings.idp.excludeInResponseTo || false }); };
JavaScript
0
@@ -4233,16 +4233,62 @@ ssRef%22 : + settings.idp.authenticationContextClassRef %7C%7C %22urn:oa
59723054908ee377b00277040b8f855d2a32d61d
tweak exam-script
static/js/exam-script.js
static/js/exam-script.js
$(".examTime").each(function() { let fromNow = moment.unix(parseInt($(this).data("time"))); if (moment().isAfter(fromNow)) { $(this).text("done!"); return; } $(this).text(fromNow.fromNow(true)); });
JavaScript
0
@@ -34,23 +34,24 @@ let -fromNow +examTime = momen @@ -115,23 +115,24 @@ isAfter( -fromNow +examTime )) %7B%0A @@ -198,23 +198,24 @@ s).text( -fromNow +examTime .fromNow
9a5975e8815311bf20431dedb29838f347704f8c
Add implicit component name in helper component
src/helpers/component.js
src/helpers/component.js
'use strict'; /*globals Jskeleton, _ */ /* jshint unused: false */ Jskeleton.registerHelper('@component', function(params, env) { // env.enviroment._app; // env.enviroment.channel; //env.enviroment._view, view-controller // params = params || {}; var componentName = params.name, ComponentClass, component, viewInstance = env.enviroment._view, componentData; if (!componentName) { throw new Error('Tienes que definir un nombre de clase'); } //omit component factory name componentData = _.omit(params, 'name'); //inject component dependencies componentData = _.extend(componentData, { _app: env.enviroment._app }); component = Jskeleton.factory.new(componentName, componentData); if (!component || typeof component !== 'object') { throw new Error('No se ha podido crear el componente'); } viewInstance.addComponent(componentName, component); return component.render().$el.get(0); });
JavaScript
0.00812
@@ -141,16 +141,22 @@ ams, env +, args ) %7B%0A @@ -343,16 +343,56 @@ ntName = + typeof args%5B0%5D === 'string' ? args%5B0%5D : params.
fc5e178f2c0f96fd5eb19f544ca25108f5b43f22
bring back popLastObject for readability
lib/util.js
lib/util.js
'use strict'; var reduce = require('lodash.reduce'); exports = module.exports = {}; // dependencies // exports.type = require('utils-type'); exports.clone = require('lodash.clone'); exports.merge = require('lodash.merge'); exports.inherits = require('inherits'); exports.asyncDone = require('async-done'); // assorted // exports.mapFrom = function(argv, args, pos){ var value, index = -1, length = args.length; while(++pos < length){ value = args[pos]; if(value){ argv[++index] = args[pos]; } } }; // lodash may not bind the iterator function... // exports.reduce = function(collection, handle, acc, self){ acc = acc || {}; self = self || acc; return reduce(collection, function iterator(/* arguments */){ handle.apply(self, arguments); return acc; }, acc ); }; exports.classFactory = function(SuperTor){ function createClass(mixin){ mixin = exports.type(mixin).plainObject || {}; if(!exports.type(mixin.create).function){ delete mixin.create; } function Tor(a, b){ if(!(this instanceof Tor)){ return new Tor(a, b); } else if(mixin.create && this.create === mixin.create){ this.create.call(this, SuperTor, a, b); } else { SuperTor.apply(this, arguments); } } exports.inherits(Tor, SuperTor); exports.merge(Tor.prototype, mixin); Tor.create = function create(a, b){ return new Tor(a, b); }; Tor.createClass = exports.classFactory(Tor); return Tor; } return createClass; };
JavaScript
0
@@ -1516,12 +1516,130 @@ teClass;%0A%7D;%0A +%0Aexports.popLastObject = function(calls)%7B%0A return exports.type(calls%5Bcalls.length-1%5D).plainObject && calls.pop();%0A%7D;%0A
341c5bd6be808e26a86056fb88fe4dcb16136fcd
disable label for login page
src/foam/nanos/u2/navigation/TopNavigation.js
src/foam/nanos/u2/navigation/TopNavigation.js
/** * @license * Copyright 2018 The FOAM Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.nanos.u2.navigation', name: 'TopNavigation', extends: 'foam.u2.View', documentation: 'Top navigation bar', requires: [ 'foam.nanos.menu.MenuBar', 'foam.nanos.u2.navigation.BusinessLogoView', 'foam.nanos.u2.navigation.UserView' ], imports: [ 'menuDAO', 'user', 'logo' ], axioms: [ foam.u2.CSS.create({ code: function CSS() {/* ^ { background: #093649; width: 100%; min-width: 992px; height: 60px; color: white; padding-top: 5px; } ^ .topNavContainer { width: 100%; margin: auto; } ^ .menuBar > div > ul { margin-top: 0; padding-left: 0; font-weight: 100; color: #ffffff; } ^ .foam-nanos-menu-MenuBar li { display: inline-block; cursor: pointer; } ^ .menuItem{ display: inline-block; padding: 20px 0 5px 0px; cursor: pointer; border-bottom: 1px solid transparent; -webkit-transition: all .15s ease-in-out; -moz-transition: all .15s ease-in-out; -ms-transition: all .15s ease-in-out; -o-transition: all .15s ease-in-out; transition: all .15s ease-in-out; } ^ .menuItem:hover, ^ .menuItem.hovered { border-bottom: 1px solid white; padding-bottom: 5px; text-shadow: 0 0 0px white, 0 0 0px white; } ^ .selected { border-bottom: 1px solid #1cc2b7 !important; padding-bottom: 5px; text-shadow: 0 0 0px white, 0 0 0px white; } ^ .menuBar{ width: 50%; overflow: auto; white-space: nowrap; margin-left: 60px; } */} }) ], properties: [ { name: 'dao', factory: function() { return this.menuDAO; } } ], methods: [ function initE(){ var self = this; this .addClass(this.myClass()) .start().addClass('topNavContainer') .callIf( this.logo, function(){ this.start({class: 'foam.nanos.u2.navigation.BusinessLogoView'}) .end() }) .start({class: 'foam.nanos.menu.MenuBar'}).addClass('menuBar') .end() .start({class: 'foam.nanos.u2.navigation.UserView'}) .end() .end() } ] });
JavaScript
0
@@ -926,20 +926,16 @@ ports: %5B -%0A 'menuDA @@ -941,20 +941,16 @@ AO', -%0A 'user', %0A @@ -949,21 +949,23 @@ er', -%0A 'log -o'%0A +inSuccess' %5D,%0A @@ -2631,31 +2631,8 @@ ()%7B%0A - var self = this;%0A @@ -2638,18 +2638,16 @@ this%0A - .a @@ -2672,26 +2672,24 @@ ss())%0A - .start().add @@ -2725,17 +2725,13 @@ - .callIf +.show ( th @@ -2740,22 +2740,19 @@ .log -o, function()%7B +inSuccess$) %0A @@ -2756,24 +2756,16 @@ - this .start(%7B @@ -2810,31 +2810,28 @@ essLogoView' + %7D)%0A - .end @@ -2837,23 +2837,8 @@ d()%0A - %7D)%0A @@ -2908,35 +2908,31 @@ r')%0A - - .end()%0A - .sta @@ -2984,28 +2984,24 @@ '%7D)%0A - .end()%0A @@ -2997,33 +2997,34 @@ end()%0A - .end() -%0A +;%0A %7D%0A %5D%0A%7D)
ce2bb0fe162d904ed31bd8d7f91a8648858dea3f
Update oss transformer
packager/transformer.js
packager/transformer.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. * * Note: This is a fork of the fb-specific transform.js */ 'use strict'; const babel = require('babel-core'); const inlineRequires = require('fbjs-scripts/babel/inline-requires'); function transform(src, filename, options) { options = options || {}; const plugins = []; if (options.inlineRequires) { plugins.push([inlineRequires]); } const result = babel.transform(src, { retainLines: true, compact: true, comments: false, filename, plugins: plugins.concat([ // Keep in sync with packager/react-packager/.babelrc 'external-helpers-2', 'syntax-async-functions', 'syntax-class-properties', 'syntax-jsx', 'syntax-trailing-function-commas', 'transform-class-properties', 'transform-es2015-arrow-functions', 'transform-es2015-block-scoping', 'transform-es2015-classes', 'transform-es2015-computed-properties', 'transform-es2015-constants', 'transform-es2015-destructuring', ['transform-es2015-modules-commonjs', {strict: false, allowTopLevelThis: true}], 'transform-es2015-parameters', 'transform-es2015-shorthand-properties', 'transform-es2015-spread', 'transform-es2015-template-literals', 'transform-flow-strip-types', 'transform-object-assign', 'transform-object-rest-spread', 'transform-object-assign', 'transform-react-display-name', 'transform-react-jsx', 'transform-regenerator', ]), sourceFileName: filename, sourceMaps: false, }); return { code: result.code }; } module.exports = function(data, callback) { let result; try { result = transform(data.sourceCode, data.filename, data.options); } catch (e) { callback(e); return; } callback(null, result); }; // export for use in jest module.exports.transform = transform;
JavaScript
0.000001
@@ -463,16 +463,18 @@ ts/babel +-6 /inline-
47ddd3217167c2bb2bda9e67b1cb3fe0cbad9fcb
remove unuse style
src/foam/u2/detail/ChoiceSectionDetailView.js
src/foam/u2/detail/ChoiceSectionDetailView.js
/** * @license * Copyright 2020 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.u2.detail', name: 'ChoiceSectionDetailView', extends: 'foam.u2.detail.AbstractSectionedDetailView', requires: [ 'foam.core.ArraySlot', 'foam.u2.borders.CardBorder', 'foam.u2.detail.SectionView', 'foam.u2.layout.Grid', 'foam.u2.layout.GUnit', 'foam.u2.Tab', 'foam.u2.Tabs', 'foam.u2.view.ChoiceView' ], css: ` ^ .foam-u2-Tabs-content > div { background: white; padding: 14px 16px overflow-x: scroll; white-space: nowrap; } ^ .foam-u2-view-ScrollTableView table { width: 100%; } ^ .foam-u2-Tabs-tabRow { overflow-x: scroll; white-space: nowrap; } ^ .foam-u2-tag-Select { text-align-last:center; } ^ .foam-u2-tag-Select:after { text-align-last:center; } .choicePosition { text-align: center; display: flex; flex-direction: row; justify-content: center; align-items: center; } .action-button { width: 100px; font-size: 20px; font-weight: bold; padding: 5px; border-radius: 10px; } `, properties: [ { class: 'String', name: 'defaultSectionLabel', value: 'Uncategorized' }, { name: 'currentIndex', preSet: function(o,n) { debugger; if ( n < 1 ) return 0; if ( n >= this.newSections.length ) return this.newSections.length - 1; return n; }, value: 0 }, { name: 'newSections', } ], methods: [ function initE() { var self = this; this.SUPER(); this .addClass(this.myClass()) .add(this.slot(function(sections, data) { if ( ! data ) return; var arraySlot = foam.core.ArraySlot.create({ slots: sections.map((s) => s.createIsAvailableFor(self.data$)) }); return self.E() .add(arraySlot.map((visibilities) => { self.newSections = sections.filter((s, i) => { return visibilities[i] }) return this.E() .startContext({ controllerMode: 'EDIT' }) .start().addClass('choicePosition') .start('button').addClass('action-button').add('<').on('click', () => { this.currentIndex -= 1; }).end() .tag(this.ChoiceView, { choices: sections.filter( (s,i) => { return visibilities[i] }).map( (s,i) => [i,s.title] ), data$: self.currentIndex$, }) .start('button').addClass('action-button').add('>').on('click', () => { this.currentIndex += 1; }).end() .end() .endContext() .add(this.slot(function (currentIndex) { return this.E().tag(self.SectionView, { data$: self.data$, section: this.newSections[this.currentIndex], showTitle: true}) })) })) })); } ] });
JavaScript
0.00051
@@ -310,506 +310,142 @@ .u2. -borders.CardBorder',%0A 'foam.u2.detail.SectionView',%0A 'foam.u2.layout.Grid',%0A 'foam.u2.layout.GUnit',%0A 'foam.u2.Tab',%0A 'foam.u2.Tabs',%0A 'foam.u2.view.ChoiceView'%0A %5D,%0A%0A css: %60%0A %5E .foam-u2-Tabs-content %3E div %7B%0A background: white;%0A padding: 14px 16px%0A overflow-x: scroll;%0A white-space: nowrap;%0A %7D%0A%0A %5E .foam-u2-view-ScrollTableView table %7B%0A width: 100%25;%0A %7D%0A%0A %5E .foam-u2-Tabs-tabRow %7B%0A overflow-x: scroll;%0A white-space: nowrap;%0A %7D%0A +detail.SectionView',%0A 'foam.u2.view.ChoiceView'%0A %5D,%0A%0A css: %60%0A %5E .foam-u2-view-ScrollTableView table %7B%0A width: 100%25;%0A %7D %0A @@ -919,108 +919,8 @@ %7B%0A - class: 'String',%0A name: 'defaultSectionLabel',%0A value: 'Uncategorized'%0A %7D,%0A %7B%0A @@ -977,26 +977,8 @@ ) %7B%0A - debugger;%0A @@ -1164,17 +1164,16 @@ ections' -, %0A %7D%0A @@ -2174,32 +2174,33 @@ visibilities%5Bi%5D +; %0A @@ -2285,17 +2285,16 @@ ntIndex$ -, %0A
36798f8fb626dfe8ceb54716b95269eb751d65a2
Test1
Context.js
Context.js
/* 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/. * * Owner: [email protected] * @license MPL 2.0 * @copyright Famous Industries, Inc. 2014 */ define(function(require, exports, module) { var RenderNode = require('./RenderNode'); var EventHandler = require('./EventHandler'); var ElementAllocator = require('./ElementAllocator'); var Transform = require('./Transform'); var Transitionable = require('famous/transitions/Transitionable'); var _originZeroZero = [0, 1]; function _getElementSize(element) { return [element.clientWidth, element.clientHeight]; } /** * The top-level container for a Famous-renderable piece of the document. * It is directly updated by the process-wide Engine object, and manages one * render tree root, which can contain other renderables. * * @class Context * @constructor * @private * @param {Node} container Element in which content will be inserted */ function Context(container) { this.container = container; this._allocator = new ElementAllocator(container); this._node = new RenderNode(); this._eventOutput = new EventHandler(); this._size = _getElementSize(this.container); this._perspectiveState = new Transitionable(0); this._perspective = undefined; this._nodeContext = { allocator: this._allocator, transform: Transform.identity, opacity: 1, origin: _originZeroZero, size: this._size }; this._eventOutput.on('resize', function() { this.setSize(_getElementSize(this.container)); }.bind(this)); } // Note: Unused Context.prototype.getAllocator = function getAllocator() { return this._allocator; }; /** * Add renderables to this Context's render tree. * * @method add * * @param {Object} obj renderable object * @return {RenderNode} RenderNode wrapping this object, if not already a RenderNode */ Context.prototype.add = function add(obj) { return this._node.add(obj); }; /** * Move this Context to another containing document element. * * @method migrate * * @param {Node} container Element to which content will be migrated */ Context.prototype.migrate = function migrate(container) { if (container === this.container) return; this.container = container; this._allocator.migrate(container); }; /** * Gets viewport size for Context. * * @method getSize * * @return {Array.Number} viewport size as [width, height] */ Context.prototype.getSize = function getSize() { return this._size; }; /** * Sets viewport size for Context. * * @method setSize * * @param {Array.Number} size [width, height]. If unspecified, use size of root document element. */ Context.prototype.setSize = function setSize(size) { if (!size) size = _getElementSize(this.container); this._size[0] = size[0]; this._size[1] = size[1]; }; /** * Commit this Context's content changes to the document. * * @private * @method update * @param {Object} contextParameters engine commit specification */ Context.prototype.update = function update(contextParameters) { if (contextParameters) { if (contextParameters.transform) this._nodeContext.transform = contextParameters.transform; if (contextParameters.opacity) this._nodeContext.opacity = contextParameters.opacity; if (contextParameters.origin) this._nodeContext.origin = contextParameters.origin; if (contextParameters.size) this._nodeContext.size = contextParameters.size; } var perspective = this._perspectiveState.get(); if (perspective !== this._perspective) { this.container.style.perspective = perspective ? perspective.toFixed() + 'px' : ''; this.container.style.webkitPerspective = perspective ? perspective.toFixed() : ''; this._perspective = perspective; } this._node.commit(this._nodeContext); }; /** * Get current perspective of this context in pixels. * * @method getPerspective * @return {Number} depth perspective in pixels */ Context.prototype.getPerspective = function getPerspective() { return this._perspectiveState.get(); }; /** * Set current perspective of this context in pixels. * * @method setPerspective * @param {Number} perspective in pixels * @param {Object} [transition] Transitionable object for applying the change * @param {function(Object)} callback function called on completion of transition */ Context.prototype.setPerspective = function setPerspective(perspective, transition, callback) { return this._perspectiveState.set(perspective, transition, callback); }; /** * Trigger an event, sending to all downstream handlers * listening for provided 'type' key. * * @method emit * * @param {string} type event type key (for example, 'click') * @param {Object} event event data * @return {EventHandler} this */ Context.prototype.emit = function emit(type, event) { return this._eventOutput.emit(type, event); }; /** * Bind a callback function to an event type handled by this object. * * @method "on" * * @param {string} type event type key (for example, 'click') * @param {function(string, Object)} handler callback * @return {EventHandler} this */ Context.prototype.on = function on(type, handler) { return this._eventOutput.on(type, handler); }; /** * Unbind an event by type and handler. * This undoes the work of "on". * * @method removeListener * * @param {string} type event type key (for example, 'click') * @param {function} handler function object to remove * @return {EventHandler} internal event handler object (for chaining) */ Context.prototype.removeListener = function removeListener(type, handler) { return this._eventOutput.removeListener(type, handler); }; /** * Add event handler object to set of downstream handlers. * * @method pipe * * @param {EventHandler} target event handler target object * @return {EventHandler} passed event handler */ Context.prototype.pipe = function pipe(target) { return this._eventOutput.pipe(target); }; /** * Remove handler object from set of downstream handlers. * Undoes work of "pipe". * * @method unpipe * * @param {EventHandler} target target handler object * @return {EventHandler} provided target */ Context.prototype.unpipe = function unpipe(target) { return this._eventOutput.unpipe(target); }; module.exports = Context; });
JavaScript
0.999894
@@ -633,17 +633,17 @@ o = %5B0, -1 +0 %5D;%0A%0A
cd066d294ac7f4733e042d52ded4eb194b4d2209
support render base64 image
lib/util.js
lib/util.js
'use strict'; var path = require('path') module.exports = { type: function (r) { return Object.prototype.toString.call(r).match(/\[object ([\w]+)\]/)[1].toLowerCase() }, absoluteURI: function (url) { if (url.startsWith('data:image/')) return url; else if (/^\w+\:\/\//.test(url) || /^\//.test(url) || /^[a-zA-Z]\:/.test(url) ) return url else return path.join(process.cwd(), url) } }
JavaScript
0
@@ -215,72 +215,14 @@ if -(url.startsWith('data:image/')) return url;%0A%09 else if (/%5E%5Cw+ -%5C :%5C/%5C @@ -270,10 +270,38 @@ A-Z%5D -%5C : +/.test(url) %7C%7C /%5Edata:image%5C/ /.te
49811c3004363e6334ccd14c4d4749f1f28ff3de
update files
lib/util.js
lib/util.js
/** * Created by nuintun on 2015/4/27. */ 'use strict'; var path = require('path'); var util = require('util'); var debug = require('debug')('gulp-css'); var plugins = require('./plugins/index'); var gutil = require('@nuintun/gulp-util'); var join = path.join; var colors = gutil.colors; var write = process.stdout.write; /** * rename * * @param {any} path * @param {any} transform * @returns {String} */ function rename(path, transform) { return gutil.rename(path, transform, debug); } /** * transport * * @param {any} vinyl * @param {any} options * @param {any} done * @returns {void} */ function transport(vinyl, options, done) { return gutil.transport(vinyl, options, done, debug); } /** * resolve * * @param {any} relative * @param {any} vinyl * @param {any} wwwroot * @returns {String} */ function resolve(relative, vinyl, wwwroot) { return gutil.resolve(relative, vinyl, wwwroot, debug); } /** * pring * * @returns {void} */ function print() { var message = gutil.apply(util.format, null, gutil.slice.call(arguments)); write(colors.cyan.bold(' gulp-css ') + message + '\n'); } /** * get rename options * * @param transform * @returns {object} */ function initRenameOptions(transform) { if (gutil.isFunction(transform)) { return transform; } transform = transform || {}; if (transform.min) { transform.suffix = '-min'; } if (transform.debug) { transform.suffix = '-debug'; } return transform; } /** * init options * * @param options * @returns {object} */ function initOptions(options) { options = gutil.extend(true, { include: false, // include prefix: null, // css prefix onpath: null, // css resource path callback cache: true, // use memory file cahe wwwroot: '', // web root rename: null // { debug: boolean, min: boolean } }, options); // wwwroot must be string if (!gutil.isString(options.wwwroot)) { gutil.throwError('options.wwwroot\'s value should be string.'); } // init wwwroot options.wwwroot = join(gutil.cwd, options.wwwroot); // init plugins options.plugins = gutil.plugins(options.plugins, plugins); // init rename options.rename = initRenameOptions(options.rename); return options; } /** * transport css dependencies. * * @param vinyl * @param options * @returns {Array} */ function transportCssDeps(vinyl, options) { var deps = []; var remote = []; var include = []; var pkg = vinyl.package || {}; var onpath = options.onpath; var prefix = options.prefix; // init css settings onpath = gutil.isFunction(onpath) ? function(path, property) { return options.onpath(path, property, vinyl.path, options.wwwroot); } : null; prefix = gutil.isFunction(prefix) ? prefix(vinyl.path, options.wwwroot) : prefix; // replace imports and collect dependencies vinyl.contents = new Buffer(css(vinyl.contents, function(id) { var path; // id is not a local file if (!gutil.isLocal(id)) { // cache dependencie id deps.push(id); remote.push(id); } else { // normalize id id = gutil.normalize(id); // if end with /, find index file if (id.substring(id.length - 1) === '/') { id += 'index.css'; } // set path path = id; // rename id id = rename(path, options.rename); // normalize id id = gutil.normalize(id); // debug debug('transport deps: %s', colors.magenta(id)); // get absolute path path = resolve(path, vinyl, options.wwwroot); // cache dependencie id deps.push(id); // cache dependencie absolute path include.push(path); } // include import css file if (options.include) { // delete all import return false; } // onpath callback if (gutil.isString(path = onpath(id, 'import'))) { return path; } // don't make changes return id; }, { prefix: prefix, onpath: onpath })); // cache file dependencies vinyl.package = gutil.extend(pkg, { remote: remote, include: include, dependencies: deps }); return deps; } /** * exports module */ module.exports = { debug: debug, rename: rename, transport: transport, resolve: resolve, print: print, initOptions: initOptions, transportCssDeps: transportCssDeps };
JavaScript
0.000001
@@ -105,24 +105,64 @@ re('util');%0A +var css = require('@nuintun/css-deps');%0A var debug =
29161c70366968b4ebbbc1317298511d61735d32
make sure we only output on exit, if there's a failure
lib/vows.js
lib/vows.js
// // Vows.js - asynchronous event-based BDD for node.js // // usage: // // var vows = require('vows'); // // vows.describe('Deep Thought').addVows({ // "An instance of DeepThought": { // topic: new DeepThought, // // "should know the answer to the ultimate question of life": function (deepThought) { // assert.equal (deepThought.question('what is the answer to the universe?'), 42); // } // } // }).run(); // var sys = require('sys'), events = require('events'), vows = exports; require.paths.unshift(__dirname); // Options vows.options = { Emitter: events.EventEmitter, reporter: require('vows/reporters/dot-matrix'), matcher: /.*/ }; vows.__defineGetter__('reporter', function () { return vows.options.reporter; }); var stylize = require('vows/console').stylize; var console = require('vows/console'); vows.inspect = require('vows/console').inspect; vows.prepare = require('vows/extras').prepare; vows.tryEnd = require('vows/suite').tryEnd; // // Assertion Macros & Extensions // require('./assert/error'); require('./assert/macros'); // // Suite constructor // var Suite = require('vows/suite').Suite; // // This function gets added to events.EventEmitter.prototype, by default. // It's essentially a wrapper around `addListener`, which adds all the specification // goodness. // function addVow(vow) { var batch = vow.batch; batch.total ++; return this.addListener("success", function () { var args = Array.prototype.slice.call(arguments); // If the callback is expecting two or more arguments, // pass the error as the first (null) and the result after. if (vow.callback.length >= 2) { args.unshift(null); } runTest(args); vows.tryEnd(batch); }).addListener("error", function (err) { var exception; if (vow.callback.length >= 2) { runTest([err]); } else { exception = { type: 'promise', error: err }; batch.errored ++; output('errored', exception); } vows.tryEnd(batch); }); function runTest(args) { var exception, topic, status; if (vow.callback instanceof String) { batch.pending ++; return output('pending'); } // Run the test, and try to catch `AssertionError`s and other exceptions; // increment counters accordingly. try { vow.callback.apply(vow.binding || null, args); output('honored', exception); batch.honored ++; } catch (e) { if (e.name && e.name.match(/AssertionError/)) { exception = e.toString(); output('broken', exception); batch.broken ++; } else { exception = e.stack || e.message || e.toString() || e; batch.errored ++; output('errored', exception); } } } function output(status, exception) { if (vow.context && batch.lastContext !== vow.context) { batch.lastContext = vow.context; batch.suite.report(['context', vow.context]); } batch.suite.report(['vow', { title: vow.description, context: vow.context, status: status, exception: exception || null }]); } }; // // On exit, check that all promises have been fired. // If not, report an error message. // process.addListener('exit', function () { var results = { honored: 0, broken: 0, errored: 0, pending: 0, total: 0 }; vows.suites.forEach(function (s) { if ((s.results.total > 0) && (s.results.time === null)) { vows.reporter.report(['error', { error: "Asynchronous Error", suite: s }]); process.exit(1); } s.batches.forEach(function (b) { if (b.status !== 'end') { results.errored ++; results.total ++; vows.reporter.report(['error', { error: "A callback hasn't fired", batch: b, suite: s }]); } Object.keys(results).forEach(function (k) { results[k] += b[k] }); }); }); if (results.total) { sys.puts(console.result(results)); } }); vows.suites = []; // // Create a new test suite // vows.describe = function (subject) { var suite = new(Suite)(subject); this.options.Emitter.prototype.addVow = addVow; this.suites.push(suite); return suite; };
JavaScript
0.000004
@@ -3687,16 +3687,25 @@ tal: 0 %7D +, failure ;%0A%0A v @@ -4006,24 +4006,56 @@ == 'end') %7B%0A + failure = true;%0A @@ -4340,29 +4340,23 @@ if ( -results.total +failure ) %7B%0A
c33e93b7056451ba72ad232b01e9ed2649feed58
Fix coding style in lib/walk.js.
lib/walk.js
lib/walk.js
// Courtesy of [stygstra](https://gist.github.com/514983) var fs = require("fs"); var path = require("path"); module.exports = (function() { function walk(dirname, options, callbacks) { var counter = 0; var walkInternal = function(dirname, options, callbacks) { callbacks = callbacks || {}; options = options || {}; if (typeof callbacks.finished !== 'function') { callbacks.finished = function(){}; } if (typeof callbacks.file !== 'function') { callbacks.file = function(){}; } counter += 1; fs.readdir(dirname, function(err, relnames) { if(err) { callbacks.finished(err); return; } if (!relnames.length) { counter -= 1; if (!counter) callbacks.finished(null); return; } relnames.forEach(function(relname, index, relnames) { var name = path.join(dirname, relname); counter += 1; fs.stat(name, function(err, stat) { if(err) { callbacks.finished(err); return; } if(stat.isDirectory()) { if (name !== '.svn' && name !== '.git') walkInternal(name, options, callbacks); } else { if (!options.mask || name.match(options.mask)) { callbacks.file(name); } } counter -= 1; if(index === relnames.length - 1) counter -= 1; if(counter === 0) { callbacks.finished(null); } }); }); }); }; walkInternal(dirname, options, callbacks); } return walk; })();
JavaScript
0.000001
@@ -450,32 +450,36 @@ !== 'function') + %7B callbacks.fil @@ -567,24 +567,25 @@ es) %7B%0A%09%09%09%09if + (err) %7B%0A%09%09%09%09 @@ -695,16 +695,25 @@ counter) + %7B%0A%09%09%09%09%09 callbac @@ -727,24 +727,31 @@ shed(null);%0A +%09%09%09%09%09%7D%0A %09%09%09%09%09return; @@ -930,16 +930,17 @@ %09%09%09%09%09%09if + (err) %7B%0A @@ -1003,16 +1003,17 @@ %09%09%09%09%09%09if + (stat.is @@ -1074,16 +1074,26 @@ '.git') +%7B%0A%09%09%09%09%09%09%09%09 walkInte @@ -1134,24 +1134,30 @@ %09%09%09%09 -%7D else %7B%0A%09%09%09%09%09%09%09 +%09%7D%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09else if ( @@ -1204,25 +1204,24 @@ )) %7B%0A%09%09%09%09%09%09%09 -%09 callbacks.fi @@ -1230,25 +1230,16 @@ (name);%0A -%09%09%09%09%09%09%09%7D%0A %09%09%09%09%09%09%7D%0A @@ -1267,16 +1267,17 @@ %09%09%09%09%09%09if + (index = @@ -1323,16 +1323,17 @@ %09%09%09%09%09%09if + (counter
ec26f034ad8acf183b68f97a53856d3d5af6d750
enable dynamic namespace
libs/Hub.js
libs/Hub.js
// Imports var _ = require('lodash'); var utils = require('./utils'); // WebSocket Hub Class function Hub (options) { var self = this; options || (options = {}); if(options.io) this.io = options.io; if(!this.io){ return; } this.io.of(this.namespace).on('connection', this._connection.bind(this)); this.initialize.apply(this, arguments); } _.extend(Hub.prototype, { namespace: '/', initialize: function(){}, onConnection: function () { console.log('user connected to namespace :' + this.namespace); }, onDisconnect: function () { console.log('user disconnected from namespace :' + this.namespace); }, _connection: function (socket) { this.socket = socket; this.onConnection(); this._parseRoutes(); socket.on('disconnect', this.onDisconnect.bind(this)); }, _parseRoutes: function () { if(!this.routes) return; this.routes = _.result(this, 'routes'); for (var key in this.routes) { this._parseRoute(key); } }, _parseRoute: function (key) { if(!_.isFunction(this[this.routes[key]])) return; this.socket.on(key, this[this.routes[key]].bind(this)); } }); Hub.extend = utils.extend; module.exports = Hub;
JavaScript
0.000002
@@ -120,29 +120,8 @@ ) %7B%0A - var self = this;%0A @@ -199,25 +199,144 @@ if( -!this.io)%7B return +options.namespace) this.namespace = options.namespace;%0A if(!this.io)%7B throw new Error('Hub class require constructor with io object') ; %7D%0A @@ -508,16 +508,21 @@ e: '/',%0A + %0A init
0687f0efe0a0e00e6087afa98f4bac48644b9934
Update knex production config
knexfile.js
knexfile.js
// Update with your config settings. module.exports = { development: { client: 'postgresql', connection: { database: 'power_ballot_development', user: '', password: '', }, }, staging: { client: 'postgresql', connection: { database: 'my_db', user: 'username', password: 'password', }, pool: { min: 2, max: 10, }, migrations: { tableName: 'knex_migrations', }, }, production: { client: 'postgresql', connection: { database: 'my_db', user: 'username', password: 'password', }, pool: { min: 2, max: 10, }, migrations: { tableName: 'knex_migrations', }, }, }
JavaScript
0
@@ -531,96 +531,32 @@ on: -%7B%0A database: 'my_db',%0A user: 'username',%0A password: 'password',%0A %7D +process.env.DATABASE_URL ,%0A
25c038991403facc6074682b6b065b0799f498e5
debug date time removed. Moubot now runs in real time
callback.js
callback.js
var moment = require('moment'); var helper = require('./helperFunctions'); var settings = require('./settings'); var callback = function(error, response, body){ if (!error && response.statusCode==200) { //We will need the date when deetrmining when to say something //We want Moubot to speak when there is a match and be silent otherwise //-- //-- This needs to be refactored. badly. //-- //-- var RightNow = moment.utc(); //debug only RightNow = moment.utc('2015-08-08T18:15'); var data = JSON.parse(body); //console.log(data); for (index in data.fixtures) { //pick up the match date time and set the flag to utc var matchDateTime = moment(data.fixtures[index].date); matchDateTime.utc(); var matchStatus = data.fixtures[index].status; //let's figure out the match details. this will need refactoring, but let's just get it to work right now var where = helper.homeOrAway(data.fixtures[index]); var opponent = helper.getOpponent(data.fixtures[index]); var homeGoals = helper.getHomeGoals(data.fixtures[index]); var awayGoals = helper.getAwayGoals(data.fixtures[index]); //only comment on the match that is about to start in 5 minutes //also, we don't want to comment on a match we already commented on if (settings.postBeforeTheMatch && (RightNow.to(matchDateTime) == settings.preMatchWindowInMinutes) && !(moment(global.lastPreMatchComment).isSame(moment(matchDateTime)))) { //remember this match date time so we don't keep saying things about it global.lastPreMatchComment = matchDateTime; //say the "upcoming" phrase var output = where + ' match vs. ' + opponent + '. '; output += helper.sayPhrase("upcoming"); //console.log(output); helper.postToSlack(helper.sayPhrase("upcoming")); } //debug help //console.log('Matchday: ' + data.fixtures[index].matchday + ' against ' + opponent + ' (' + where + ') is ' + RightNow.to(matchDateTime)); //console.log('-- Date : ' + matchDateTime.format("dddd, MMMM Do YYYY, h:mm:ss a z")); //post-match banter if (settings.postAfterTheMatch && (RightNow.to(matchDateTime) == settings.postMatchWindowInHours) && !(moment(global.lastPostMatchComment).isSame(moment(matchDateTime)))) { global.lastPostMatchComment = matchDateTime; //let's prepare our won-tied-lost string var winOrLose = helper.interpretOutcome(where, homeGoals, awayGoals); //get the smart-ass phrases and say it //console.log(helper.sayPhrase(winOrLose)); helper.postToSlack(helper.sayPhrase("winOrLose")); } } } else { console.error(); } }; exports.callback = callback;
JavaScript
0
@@ -472,16 +472,18 @@ nly%0A +// RightNow @@ -517,16 +517,17 @@ 8:15');%0A +%0A var
b35917bb206d5bc69fad62f2324221d52d1d7310
Add documentation and semicolons
cangraph.js
cangraph.js
/** * Cangraph * * Graphing and function plotting for the HTML5 canvas. Main function plotting * engine was taken from the link below and modified. * * @link http://www.javascripter.net/faq/plotafunctiongraph.htm */ (function ($) { function Cangraph(canvasId) { var canvas; this.set('canvasId', canvasId); canvas = document.getElementById(this.canvasId); this.set('canvas', canvas); this.setContext(); } Cangraph.prototype.set = function (name, value) { if (!value) { console.log(name, 'is undefined or null!'); return false; } this[name] = value; }; Cangraph.prototype.setContext = function () { var context = this.canvas.getContext('2d'); this.set('context', context); }; Cangraph.prototype.draw = function (fx) { var axes={}; axes.x0 = .5 + .5*this.canvas.width; // x0 pixels from left to x=0 axes.y0 = .5 + .5*this.canvas.height; // y0 pixels from top to y=0 axes.scale = 40; // 40 pixels from x=0 to x=1 axes.doNegativeX = true; this.showAxes(this.context, axes); this.funGraph(this.context, axes, fx, "rgb(11,153,11)", 1); }; Cangraph.prototype.funGraph = function (ctx,axes,func,color,thick) { var xx, yy, dx=4, x0=axes.x0, y0=axes.y0, scale=axes.scale; var iMax = Math.round((ctx.canvas.width-x0)/dx); var iMin = axes.doNegativeX ? Math.round(-x0/dx) : 0; ctx.beginPath(); ctx.lineWidth = thick; ctx.strokeStyle = color; for (var i=iMin;i<=iMax;i++) { xx = dx*i; yy = scale*func(xx/scale); if (i==iMin) ctx.moveTo(x0+xx,y0-yy); else ctx.lineTo(x0+xx,y0-yy); } ctx.stroke(); } Cangraph.prototype.showAxes = function (ctx,axes) { var x0=axes.x0, w=ctx.canvas.width; var y0=axes.y0, h=ctx.canvas.height; var xmin = axes.doNegativeX ? 0 : x0; ctx.beginPath(); ctx.strokeStyle = "rgb(128,128,128)"; ctx.moveTo(xmin,y0); ctx.lineTo(w,y0); // X axis ctx.moveTo(x0,0); ctx.lineTo(x0,h); // Y axis ctx.stroke(); } // Attach object to global namespace this.Cangraph = Cangraph; }).call(this, $);
JavaScript
0.000017
@@ -233,16 +233,169 @@ ($) %7B%0A%0A + /**%0A * Constructor and initialization%0A *%0A * @class Cangraph%0A *%0A * @param %7BString%7D canvasId The canvas element to draw on%0A */%0A func @@ -1909,32 +1909,33 @@ .stroke();%0A %7D +; %0A%0A Cangraph.p @@ -2297,24 +2297,25 @@ oke();%0A %7D +; %0A%0A // Att
10b87d27dc83c7fc996ea8752e18d38dd3462c72
Revert to original script
launcher.js
launcher.js
#!/usr/bin/env node // aquila-server launcher require("shelljs/global"); var config = require("shelljs").config; var path = require("path"); // get args for passing to aquila-server var args = process.argv.slice(2).join(" "); var home = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; var killall_mongod = (process.platform === 'win32') ? 'taskkill /F /IM mongod.exe' : 'killall mongod'; echo("Aquila Server\n"); echo("IMPORTANT: Make sure that the bridge is connected.\n"); // cd to where this file lives cd(__dirname); // Create aquila-server config dir if not exists mkdir("-p", path.join(home, ".aquila-server/data/db")); // Clean old database log // Make command output silent config.silent = true; rm(path.join(home, ".aquila-server/data/mongodb.log")); config.silent = false; // Start MongoDB // for multi platform compatibility: var dbpath = '"' + path.join(home, ".aquila-server/data/db") + '"'; var logpath = '"' + path.join(home, ".aquila-server/data/mongodb.log") + '"'; echo("Starting Database..."); exec("mongod --journal --dbpath " + dbpath + " --logpath " + logpath, { async: true }); // Check for mongo's health var mongoose = require("mongoose"), configManager = require("./configManager"); // Initializa config files: configManager.checkConfigFiles(); var configDB = require(configManager.databasePath); // ID's for the interval timer var intervalID; var intervalIDMongoose; var intervalChosen = 0; // Starts the aquila server var startAquila = function() { echo("Starting Aquila Server..."); exec("node aquila-server.js " + args, function(code, output) { exec(killall_mongod); }); }; // Checks if the database if accepting connections var checkConnectionWithDB = function(callback) { var pingCode = exec("nc -z localhost 27017").code; if (pingCode == 0) { if (intervalChosen == 0) { clearInterval(intervalID); clearInterval(intervalIDMongoose); callback(); } else if (intervalChosen == 1) { clearInterval(intervalIDMongoose); callback(); } } }; // Restores the database's backup in case something went wrong var restoreDatabase = function() { console.log("Restoring database"); exec("mongorestore --drop " + path.join(home, ".aquila-server/backup/aquila-server")); console.log("Database restored"); startAquila(); }; // Connects to mongoose var connectMongoose = function() { intervalChosen == 1; mongoose.connect(configDB.url, function(err, res) { if(err) { console.log("ERROR connecting to database, will try to restore database."); exec("rm -rf " + path.join(home, ".aquila-server/data/*"), function() { // Create aquila-server config dir if not exists mkdir("-p", path.join(home, ".aquila-server/data/db")); console.log("Created new database folder"); exec("mongod --journal --dbpath " + dbpath + " --logpath " + logpath, { async: true }); intervalChosen = 0; intervalID = setInterval(checkConnectionWithDB, 500, restoreDatabase); }); } else { startAquila(); } }); }; intervalIDMongoose = setInterval(checkConnectionWithDB, 500, connectMongoose);
JavaScript
0.000006
@@ -1405,56 +1405,8 @@ ID;%0A -var intervalIDMongoose;%0A%0Avar intervalChosen = 0; %0A%0A// @@ -1818,255 +1818,56 @@ -if (intervalChosen == 0)%0A %7B%0A clearInterval(intervalID);%0A clearInterval(intervalIDMongoose);%0A callback();%0A %7D else if (intervalChosen == 1)%0A %7B%0A clearInterval(intervalIDMongoose);%0A callback();%0A %7D + clearInterval(intervalID);%0A callback(); %0A @@ -2232,31 +2232,8 @@ )%0A%7B%0A - intervalChosen == 1;%0A mo @@ -2751,38 +2751,8 @@ %7D);%0A - intervalChosen = 0;%0A @@ -2900,69 +2900,8 @@ %7D;%0A%0A -intervalIDMongoose = setInterval(checkConnectionWithDB, 500, conn @@ -2915,9 +2915,8 @@ oose +( );%0A -%0A%0A
305118182a6e1bb37b295b47f5f9d8654351a15e
tweak comment
src/mixin/Animatable.js
src/mixin/Animatable.js
/** * @module zrender/mixin/Animatable */ define(function(require) { 'use strict'; var Animator = require('../animation/Animator'); var util = require('../core/util'); var isString = util.isString; var isFunction = util.isFunction; var isObject = util.isObject; var log = require('../core/log'); /** * @alias modue:zrender/mixin/Animatable * @constructor */ var Animatable = function () { /** * @type {Array.<module:zrender/animation/Animator>} * @readOnly */ this.animators = []; }; Animatable.prototype = { constructor: Animatable, /** * 动画 * * @param {string} path The path to fetch value from object, like 'a.b.c'. * @param {boolean} [loop] Whether to loop animation. * @return {module:zrender/animation/Animator} * @example: * el.animate('style', false) * .when(1000, {x: 10} ) * .done(function(){ // Animation done }) * .start() */ animate: function (path, loop) { var target; var animatingShape = false; var el = this; var zr = this.__zr; if (path) { var pathSplitted = path.split('.'); var prop = el; // If animating shape animatingShape = pathSplitted[0] === 'shape'; for (var i = 0, l = pathSplitted.length; i < l; i++) { if (!prop) { continue; } prop = prop[pathSplitted[i]]; } if (prop) { target = prop; } } else { target = el; } if (!target) { log( 'Property "' + path + '" is not existed in element ' + el.id ); return; } var animators = el.animators; var animator = new Animator(target, loop); animator.during(function (target) { el.dirty(animatingShape); }) .done(function () { // FIXME Animator will not be removed if use `Animator#stop` to stop animation animators.splice(util.indexOf(animators, animator), 1); }); animators.push(animator); // If animate after added to the zrender if (zr) { zr.animation.addAnimator(animator); } return animator; }, /** * 停止动画 * @param {boolean} forwardToLast If move to last frame before stop */ stopAnimation: function (forwardToLast) { var animators = this.animators; var len = animators.length; for (var i = 0; i < len; i++) { animators[i].stop(forwardToLast); } animators.length = 0; return this; }, /** * Caution: this method will stop previous animation. * So if do not use this method to one element twice before * animation starts, unless you know what you are doing. * @param {Object} target * @param {number} [time=500] Time in ms * @param {string} [easing='linear'] * @param {number} [delay=0] * @param {Function} [callback] * @param {Function} [forceAnimate] Prevent stop animation and callback * immediently when target values are the same as current values. * * @example * // Animate position * el.animateTo({ * position: [10, 10] * }, function () { // done }) * * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing * el.animateTo({ * shape: { * width: 500 * }, * style: { * fill: 'red' * } * position: [10, 10] * }, 100, 100, 'cubicOut', function () { // done }) */ // TODO Return animation key animateTo: function (target, time, delay, easing, callback, forceAnimate) { // animateTo(target, time, easing, callback); if (isString(delay)) { callback = easing; easing = delay; delay = 0; } // animateTo(target, time, delay, callback); else if (isFunction(easing)) { callback = easing; easing = 'linear'; delay = 0; } // animateTo(target, time, callback); else if (isFunction(delay)) { callback = delay; delay = 0; } // animateTo(target, callback) else if (isFunction(time)) { callback = time; time = 500; } // animateTo(target) else if (!time) { time = 500; } // Stop all previous animations this.stopAnimation(); this._animateToShallow('', this, target, time, delay, easing, callback); // Animators may be removed immediately after start // if there is nothing to animate var animators = this.animators.slice(); var count = animators.length; function done() { count--; if (!count) { callback && callback(); } } // No animators. This should be checked before animators[i].start(), // because 'done' may be executed immediately if no need to animate. if (!count) { callback && callback(); } // Start after all animators created // Incase any animator is done immediately when all animation properties are not changed for (var i = 0; i < animators.length; i++) { animators[i] .done(done) .start(easing, forceAnimate); } }, /** * @private * @param {string} path='' * @param {Object} source=this * @param {Object} target * @param {number} [time=500] * @param {number} [delay=0] * * @example * // Animate position * el._animateToShallow({ * position: [10, 10] * }) * * // Animate shape, style and position in 100ms, delayed 100ms * el._animateToShallow({ * shape: { * width: 500 * }, * style: { * fill: 'red' * } * position: [10, 10] * }, 100, 100) */ _animateToShallow: function (path, source, target, time, delay) { var objShallow = {}; var propertyCount = 0; for (var name in target) { if (!target.hasOwnProperty(name)) { continue; } if (source[name] != null) { if (isObject(target[name]) && !util.isArrayLike(target[name])) { this._animateToShallow( path ? path + '.' + name : name, source[name], target[name], time, delay ); } else { objShallow[name] = target[name]; propertyCount++; } } else if (target[name] != null) { // Attr directly if not has property // FIXME, if some property not needed for element ? if (!path) { this.attr(name, target[name]); } else { // Shape or style var props = {}; props[path] = {}; props[path][name] = target[name]; this.attr(props); } } } if (propertyCount > 0) { this.animate(path, false) .when(time == null ? 500 : time, objShallow) .delay(delay || 0); } return this; } }; return Animatable; });
JavaScript
0
@@ -3249,19 +3249,16 @@ * So -if do not u
87e46fc1e9c84192df4e037809aca289f4d3788b
Add notify on Reset Password
pages/reset-password.js
pages/reset-password.js
'use strict' import { Component } from 'react' import withRedux from 'next-redux-wrapper' import PropTypes from 'prop-types' import Router from 'next/router' import { isLogged } from './../services/auth' import Page from './../layouts/page' import { UiButton, TextInput, Row } from './../components/ui' import { colors, typography } from './../components/ui/theme' import store from './../store/configure-store' import Header from './../components/header' import fetchAccount from './../actions/fetch-account' import resetPassword from './../actions/reset-password' class ResetPassword extends Component { componentDidMount() { const { fetchAccount } = this.props if (isLogged()) { return fetchAccount().then(res => { if (res.error) { Router.push('/profile') } }) } Router.push('/login') } resetPassword() { const { resetPassword } = this.props const userData = { email: this.email } resetPassword(userData) } render() { return ( <Page> <Header logged={isLogged()} user={this.props.user} /> <Row> <h2>Reset your password</h2> <p> Forgot your password? Happens all the time. Enter your email below to reset it. </p> <form> <TextInput label="Email" placeholder="[email protected]" type="email" inputRef={ref => { this.email = ref }} /> <UiButton ui="primary block" type="submit">Reset password</UiButton> </form> </Row> <style jsx>{` h2 { text-align: center; padding-top: 120px; font-size: ${typography.f30}; color: ${colors.grayDark}; margin-bottom: 8px; font-weight: 600; } p { text-align: center; margin-bottom: 50px; font-size: ${typography.f16}; color: ${colors.gray}; } form { max-width: 60%; margin-left: auto; margin-right: auto; } `}</style> </Page> ) } } ResetPassword.propTypes = { fetchAccount: PropTypes.func.isRequired, resetPassword: PropTypes.func.isRequired, user: PropTypes.object } const mapStateToProps = state => { return { user: state.account.data.user } } const mapDispatchToProps = dispatch => { return { fetchAccount: () => dispatch(fetchAccount()), resetPassword: email => dispatch(resetPassword(email)) } } export default withRedux(store, mapStateToProps, mapDispatchToProps)( ResetPassword )
JavaScript
0
@@ -151,16 +151,50 @@ /router' +%0Aimport Alert from 'react-s-alert' %0A%0Aimport @@ -303,16 +303,24 @@ put, Row +, Notify %7D from @@ -644,16 +644,107 @@ onent %7B%0A + constructor() %7B%0A super()%0A%0A this.resetPassword = this.resetPassword.bind(this)%0A %7D%0A%0A compon @@ -917,15 +917,13 @@ h('/ -profile +login ')%0A @@ -949,35 +949,8 @@ %7D -%0A%0A Router.push('/login') %0A %7D @@ -967,20 +967,44 @@ assword( +e ) %7B%0A + e.preventDefault()%0A cons @@ -1107,16 +1107,310 @@ serData) +.then((%7B data, error %7D) =%3E %7B%0A if (data) %7B%0A Alert.success('Instructions sent to your email.')%0A Router.push('/login')%0A %7D%0A%0A if (error) %7B%0A Alert.error(%0A 'We were not able to reset your password at the moment, please contact us.'%0A )%0A %7D%0A %7D) %0A %7D%0A%0A @@ -1694,24 +1694,54 @@ %3Cform + onSubmit=%7Bthis.resetPassword%7D %3E%0A @@ -2051,16 +2051,38 @@ %3C/form%3E +%0A%0A %3CNotify /%3E %0A
a9dce030742385285a243b8769f49c94c5942838
Fix error message typo in useSelector ('You must pass a selector...). (#1581)
src/hooks/useSelector.js
src/hooks/useSelector.js
import { useReducer, useRef, useMemo, useContext, useDebugValue } from 'react' import { useReduxContext as useDefaultReduxContext } from './useReduxContext' import Subscription from '../utils/Subscription' import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect' import { ReactReduxContext } from '../components/Context' const refEquality = (a, b) => a === b function useSelectorWithStoreAndSubscription( selector, equalityFn, store, contextSub ) { const [, forceRender] = useReducer(s => s + 1, 0) const subscription = useMemo(() => new Subscription(store, contextSub), [ store, contextSub ]) const latestSubscriptionCallbackError = useRef() const latestSelector = useRef() const latestStoreState = useRef() const latestSelectedState = useRef() const storeState = store.getState() let selectedState try { if ( selector !== latestSelector.current || storeState !== latestStoreState.current || latestSubscriptionCallbackError.current ) { selectedState = selector(storeState) } else { selectedState = latestSelectedState.current } } catch (err) { if (latestSubscriptionCallbackError.current) { err.message += `\nThe error may be correlated with this previous error:\n${latestSubscriptionCallbackError.current.stack}\n\n` } throw err } useIsomorphicLayoutEffect(() => { latestSelector.current = selector latestStoreState.current = storeState latestSelectedState.current = selectedState latestSubscriptionCallbackError.current = undefined }) useIsomorphicLayoutEffect(() => { function checkForUpdates() { try { const newSelectedState = latestSelector.current(store.getState()) if (equalityFn(newSelectedState, latestSelectedState.current)) { return } latestSelectedState.current = newSelectedState } catch (err) { // we ignore all errors here, since when the component // is re-rendered, the selectors are called again, and // will throw again, if neither props nor store state // changed latestSubscriptionCallbackError.current = err } forceRender() } subscription.onStateChange = checkForUpdates subscription.trySubscribe() checkForUpdates() return () => subscription.tryUnsubscribe() }, [store, subscription]) return selectedState } /** * Hook factory, which creates a `useSelector` hook bound to a given context. * * @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`. * @returns {Function} A `useSelector` hook bound to the specified context. */ export function createSelectorHook(context = ReactReduxContext) { const useReduxContext = context === ReactReduxContext ? useDefaultReduxContext : () => useContext(context) return function useSelector(selector, equalityFn = refEquality) { if (process.env.NODE_ENV !== 'production' && !selector) { throw new Error(`You must pass a selector to useSelectors`) } const { store, subscription: contextSub } = useReduxContext() const selectedState = useSelectorWithStoreAndSubscription( selector, equalityFn, store, contextSub ) useDebugValue(selectedState) return selectedState } } /** * A hook to access the redux store's state. This hook takes a selector function * as an argument. The selector is called with the store state. * * This hook takes an optional equality comparison function as the second parameter * that allows you to customize the way the selected state is compared to determine * whether the component needs to be re-rendered. * * @param {Function} selector the selector function * @param {Function=} equalityFn the function that will be used to determine equality * * @returns {any} the selected state * * @example * * import React from 'react' * import { useSelector } from 'react-redux' * * export const CounterComponent = () => { * const counter = useSelector(state => state.counter) * return <div>{counter}</div> * } */ export const useSelector = /*#__PURE__*/ createSelectorHook()
JavaScript
0.000021
@@ -3063,17 +3063,16 @@ Selector -s %60)%0A %7D
80fd852165aaf0335452c6d02fc54d9e58fa012a
remove leftover refresh token property
lib/actions/token/refresh_token.js
lib/actions/token/refresh_token.js
const _ = require('lodash'); const { InvalidGrantError } = require('../../helpers/errors'); const presence = require('../../helpers/validate_presence'); const instance = require('../../helpers/weak_cache'); module.exports.handler = function getRefreshTokenHandler(provider) { return async function refreshTokenResponse(ctx, next) { presence(ctx, ['refresh_token']); const { RefreshToken, Account, AccessToken, IdToken } = provider; let refreshTokenValue = ctx.oidc.params.refresh_token; let refreshToken = await RefreshToken.find(refreshTokenValue, { ignoreExpiration: true }); ctx.assert(refreshToken, new InvalidGrantError('refresh token not found')); ctx.assert(!refreshToken.isExpired, new InvalidGrantError('refresh token is expired')); ctx.assert(refreshToken.clientId === ctx.oidc.client.clientId, new InvalidGrantError('refresh token client mismatch')); const refreshTokenScopes = refreshToken.scope.split(' '); if (ctx.oidc.params.scope) { const missing = _.difference(ctx.oidc.params.scope.split(' '), refreshTokenScopes); ctx.assert(_.isEmpty(missing), 400, 'invalid_scope', { error_description: 'refresh token missing requested scope', scope: missing.join(' '), }); } const account = await Account.findById(ctx, refreshToken.accountId); ctx.assert(account, new InvalidGrantError('refresh token invalid (referenced account not found)')); if (instance(provider).configuration('refreshTokenRotation') === 'rotateAndConsume') { try { ctx.assert(!refreshToken.consumed, new InvalidGrantError('refresh token already used')); await refreshToken.consume(); refreshToken = new RefreshToken(Object.assign({}, { accountId: refreshToken.accountId, acr: refreshToken.acr, amr: refreshToken.amr, authTime: refreshToken.authTime, claims: refreshToken.claims, onlyPKCE: refreshToken.onlyPKCE, clientId: refreshToken.clientId, grantId: refreshToken.grantId, nonce: refreshToken.nonce, scope: ctx.oidc.params.scope || refreshToken.scope, sid: refreshToken.sid, })); refreshTokenValue = await refreshToken.save(); } catch (err) { await refreshToken.destroy(); throw err; } } const at = new AccessToken({ accountId: account.accountId, claims: refreshToken.claims, clientId: ctx.oidc.client.clientId, grantId: refreshToken.grantId, scope: ctx.oidc.params.scope || refreshToken.scope, sid: refreshToken.sid, }); const accessToken = await at.save(); const { expiresIn } = AccessToken; const token = new IdToken(Object.assign({}, await Promise.resolve(account.claims()), { acr: refreshToken.acr, amr: refreshToken.amr, auth_time: refreshToken.authTime, }), ctx.oidc.client.sectorIdentifier); token.scope = refreshToken.scope; token.mask = _.get(refreshToken.claims, 'id_token', {}); token.set('nonce', refreshToken.nonce); token.set('at_hash', accessToken); token.set('rt_hash', refreshTokenValue); token.set('sid', refreshToken.sid); const idToken = await token.sign(ctx.oidc.client); ctx.body = { access_token: accessToken, expires_in: expiresIn, id_token: idToken, refresh_token: refreshTokenValue, token_type: 'Bearer', }; await next(); }; }; module.exports.parameters = ['refresh_token', 'scope'];
JavaScript
0
@@ -1955,51 +1955,8 @@ ms,%0A - onlyPKCE: refreshToken.onlyPKCE,%0A
85bdacb7cfd5954eada500b7959c4f67a3fe9d1e
Fix truncation + Replace born with abbreviation
lib/components/artist/biography.js
lib/components/artist/biography.js
/* @flow */ 'use strict'; import Relay from 'react-relay'; import React from 'react'; import { View, Text, Dimensions } from 'react-native'; import removeMarkdown from 'remove-markdown'; import Headline from '../text/headline'; import SerifText from '../text/serif'; const sideMargin = Dimensions.get('window').width > 700 ? 50 : 0; class Biography extends React.Component { static propTypes = { artist: React.PropTypes.shape({ bio: React.PropTypes.string, }), }; render() { const artist = this.props.artist; if (!artist.blurb && !artist.bio) { return null; } return ( <View style={{marginLeft: sideMargin, marginRight: sideMargin}}> <Headline style={{ marginBottom: 20 }}>Biography</Headline> { this.blurb(artist) } <SerifText style={{ marginBottom: 40 }}>{artist.bio}</SerifText> </View> ); } blurb(artist) { return artist.blurb ? <SerifText style={{ marginBottom: 20, lineHeight: 25 }} numberOfLines={0}>{removeMarkdown(artist.blurb)}</SerifText> : null; } } export default Relay.createContainer(Biography, { fragments: { artist: () => Relay.QL` fragment on Artist { bio blurb } `, } });
JavaScript
0.000012
@@ -822,20 +822,42 @@ 0 %7D%7D -%3E%7Bart + numberOfLines=%7B0%7D%3E%7Bth is -t .bio +Text() %7D%3C/S @@ -1065,16 +1065,114 @@ ll;%0A %7D%0A + %0A bioText() %7B%0A const bio = this.props.artist.bio;%0A return bio.replace(%22born%22, %22b.%22);%0A %7D%0A %7D%0A%0Aexpor
55772a6bc5b0946a702d9d33451b1a8ffc588eec
Fix prop-type validation problem in StylizedMap
lib/components/map/stylized-map.js
lib/components/map/stylized-map.js
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import Transitive from 'transitive-js' import { getActiveSearch, getActiveItineraries } from '../../util/state' import { isBikeshareStation, itineraryToTransitive } from '../../util/map' const extendedStyles = { segments: { // override the default stroke width 'stroke-width': (display, segment, index, utils) => { switch (segment.type) { case 'CAR': return utils.pixels(display.zoom.scale(), 2, 4, 6) + 'px' case 'WALK': return '5px' case 'BICYCLE': case 'BICYCLE_RENT': return '4px' case 'TRANSIT': // bus segments: if (segment.mode === 3) { return utils.pixels(display.zoom.scale(), 4, 8, 12) + 'px' } // all others: return utils.pixels(display.zoom.scale(), 6, 12, 18) + 'px' } } }, places_icon: { display: function (display, data) { const place = data.owner if ( place.getId() !== 'from' && place.getId() !== 'to' && !isBikeshareStation(place) ) { return 'none' } } } } // extend common transitive styles for stylized map view function mergeTransitiveStyles (base, extended) { const styles = Object.assign({}, base) for (const key in extended) { if (key in base) styles[key] = Object.assign({}, styles[key], extended[key]) else styles[key] = extended[key] } return styles } class StylizedMap extends Component { static propTypes = { activeItinerary: PropTypes.object, routingType: PropTypes.string, toggleLabel: PropTypes.element, transitiveData: PropTypes.object } static defaultProps = { toggleName: 'Stylized' } componentDidMount () { this._transitive = new Transitive({ el: document.getElementById('trn-canvas'), styles: mergeTransitiveStyles( require('./transitive-styles'), extendedStyles ), drawGrid: true, gridCellSize: 200, zoomFactors: [ { minScale: 0, gridCellSize: 300, internalVertexFactor: 1000000, angleConstraint: 45, mergeVertexThreshold: 200 } ] }) this._transitive.render() } componentWillReceiveProps (nextProps) { if (nextProps.transitiveData !== this.props.transitiveData) { this._transitive.updateData(nextProps.transitiveData) this._transitive.render() } if ( // this block only applies for profile trips where active option changed nextProps.routingType === 'PROFILE' && nextProps.activeItinerary !== this.props.activeItinerary ) { if (nextProps.activeItinerary == null) { // no option selected; clear focus this._transitive.focusJourney(null) this._transitive.refresh() } else if (nextProps.transitiveData) { this._transitive.focusJourney( nextProps.transitiveData.journeys[nextProps.activeItinerary] .journey_id ) this._transitive.refresh() } } } render () { return ( <div id='trn-canvas' style={{ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }} /> ) } } // connect to the redux store const mapStateToProps = (state, ownProps) => { const activeSearch = getActiveSearch(state.otp) let transitiveData = null if ( activeSearch && activeSearch.query.routingType === 'ITINERARY' && activeSearch.response && activeSearch.response.plan ) { const itins = getActiveItineraries(state.otp) transitiveData = itineraryToTransitive(itins[activeSearch.activeItinerary]) } else if ( activeSearch && activeSearch.response && activeSearch.response.otp ) { transitiveData = activeSearch.response.otp } return { transitiveData, activeItinerary: activeSearch && activeSearch.activeItinerary, routingType: activeSearch && activeSearch.query && activeSearch.query.routingType } } const mapDispatchToProps = {} export default connect(mapStateToProps, mapDispatchToProps)(StylizedMap)
JavaScript
0.000001
@@ -1603,22 +1603,22 @@ opTypes. -object +number ,%0A ro
2f122acb48b738c26297b2ffb7e29a6619d6ca81
don't need word boundary here
src/gwt/acesupport/acemode/r_highlight_rules.js
src/gwt/acesupport/acemode/r_highlight_rules.js
/* * r_highlight_rules.js * * Copyright (C) 2009-12 by RStudio, Inc. * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ define("mode/r_highlight_rules", function(require, exports, module) { var oop = require("ace/lib/oop"); var lang = require("ace/lib/lang"); var TextHighlightRules = require("ace/mode/text_highlight_rules") .TextHighlightRules; var TexHighlightRules = require("mode/tex_highlight_rules").TexHighlightRules; var RHighlightRules = function() { var keywords = lang.arrayToMap( ("function|if|in|break|next|repeat|else|for|return|switch|while|try|tryCatch|stop|warning|require|library|attach|detach|source|setMethod|setGeneric|setGroupGeneric|setClass|setRefClass") .split("|") ); var buildinConstants = lang.arrayToMap( ("NULL|NA|TRUE|FALSE|T|F|Inf|NaN|NA_integer_|NA_real_|NA_character_|" + "NA_complex_").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { // Roxygen token : "comment.sectionhead", regex : "#+(?!').*(?:----|====|####)\\s*$" }, { // Roxygen token : "comment", regex : "#+'", next : "rd-start" }, { token : "comment", regex : "#.*$" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : '["]', next : "qqstring" }, { token : "string", // multi line string start merge : true, regex : "[']", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+[Li]?\\b" }, { token : "constant.numeric", // number + integer regex : "\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d*)?[iL]?\\b" }, { token : "constant.numeric", // number + integer with leading decimal regex : "\\.\\d+(?:[eE][+\\-]?\\d*)?[iL]?\\b" }, { token : "constant.language.boolean", regex : "(?:TRUE|FALSE|T|F)\\b" }, { token : "identifier", regex : "`.*?`" }, { token : function(value) { if (keywords[value]) return "keyword"; else if (buildinConstants[value]) return "constant.language"; else if (value == '...' || value.match(/^\.\.\d+$/)) return "variable.language"; else return "identifier"; }, regex : "[a-zA-Z.][a-zA-Z0-9._]*\\b" }, { token : "keyword.operator", regex : "%%|>=|<=|==|!=|\\->|<\\-|\\|\\||&&|=|\\+|\\-|\\*|/|\\^|>|<|!|&|\\||~|\\$|:|@" }, { token : "keyword.operator.infix", // infix operators regex : "%.*?%" }, { // Obviously these are neither keywords nor operators, but // labelling them as such was the easiest way to get them // to be colored distinctly from regular text token : "paren.keyword.operator", regex : "[[({]" }, { // Obviously these are neither keywords nor operators, but // labelling them as such was the easiest way to get them // to be colored distinctly from regular text token : "paren.keyword.operator", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", regex : '.+', merge : true } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", regex : '.+', merge : true } ] }; var rdRules = new TexHighlightRules("comment").getRules(); // Make all embedded TeX virtual-comment so they don't interfere with // auto-indent. for (var i = 0; i < rdRules["start"].length; i++) { rdRules["start"][i].token += ".virtual-comment"; } this.addRules(rdRules, "rd-"); this.$rules["rd-start"].unshift({ token: "text", regex: "^", next: "start" }); this.$rules["rd-start"].unshift({ token : "keyword", regex : "@(?!@)[^ ]*" }); this.$rules["rd-start"].unshift({ token : "comment", regex : "@@" }); this.$rules["rd-start"].push({ token : "comment", regex : "[^%\\\\[({\\])}]+" }); }; oop.inherits(RHighlightRules, TextHighlightRules); exports.RHighlightRules = RHighlightRules; });
JavaScript
0.998787
@@ -4002,19 +4002,16 @@ Z0-9._%5D* -%5C%5Cb %22%0A
5cd0710489d3c775d65d4df651a017c79d18836e
Update powerup types
lib/Game.js
lib/Game.js
var winston = require('winston'), entities = require('./Entities.js'), utils = require('./Utils.js'); /* * General game handler */ function Game(client1, client2, game_type) { this.players = []; this.balls = []; this.powerups = []; this.tick = 0; this.tick_duration = 50; this.game_loop = -1; this.start_delay = 3000; this.ended = false; if(game_type == "hardcore"){ this.powerup_types = [ "flip_screen", "beer" ]; } else if(game_type == "classic"){ this.powerup_types = []; } else { this.powerup_types = [ /*'grow_snake', 'shrink_snake', 'freeze_snake',*/ 'ghostify_snake' /*'flip_screen', 'beer'*/ ]; } this.game_type = game_type; winston.info("Game type is", game_type); this.init(client1, client2); } Game.prototype.start = function() { winston.info( 'Starting new game with ' + this.players.length + ' players!' ); // run the game var last_time = Date.now(); var _update = this.update.bind(this); this.game_loop = setInterval(_update, this.tick_duration); } Game.prototype.end = function(msg) { if(this.ended) return; this.ended = true; for(var i in this.players) { var cur = this.players[i]; var other = this.players[(i+1)% 2]; cur.connection.emit("end_game", "Your score: "+cur.score+"<br />"+utils.escapeHtml(other.name)+"'s score: "+other.score); cur.connection.disconnect(); } clearInterval(this.game_loop); winston.info( 'Ending game [' + msg + ']' ); } Game.prototype.get_connections = function() { var conns = []; for(var i in this.players) { var cur = this.players[i]; conns.push(cur.connection); } return conns; } Game.prototype.init = function(client1, client2) { // add two players to the game var p1 = new entities.Player( client1.name, client1.conn, "left" ) var p2 = new entities.Player( client2.name, client2.conn, "right" ) this.players.push(p1); this.players.push(p2); for(var i in this.players) { var cur = this.players[i]; cur.snake.init(this); } // add one ball var ball = new entities.Ball(this, 640/2, 480/2, 3, 3); this.balls.push(ball); // say hello for(var i in this.players) { var cur = this.players[i]; var names = []; for(var j in this.players) { if(i != j) { var other = this.players[j]; names.push(other.name); } } cur.connection.emit( 'ready', { opponent: names[0], game_type: this.game_type, delay: this.start_delay, name: cur.name, side: cur.side }); } } Game.prototype.update = function() { /* * Movement */ // balls for(var i in this.balls) { cur = this.balls[i]; cur.update(1); } // snakes for(var i in this.players) { cur = this.players[i].snake; cur.update(1); } /* * Collisions */ // balls for(var i in this.balls) { cur = this.balls[i]; cur.handle_collisions(); } // snakes for(var i in this.players) { cur = this.players[i].snake; cur.handle_collisions(); } /* * Powerup spawning */ //powerUp Multipiers var powerUpTickMuliplier = 200; var highPowerMultiplier = 10; var isNormalTick = (this.tick % powerUpTickMuliplier) == 0; var isUpTick = (this.tick % (Math.round(powerUpTickMuliplier / highPowerMultiplier))) == 0; if(isNormalTick || (this.game_type == "power" && isUpTick)) { this.spawn_random_powerup(); } this.tick++; } Game.prototype.spawn_random_powerup = function() { if(this.powerup_types.length == 0){ return; } var powerup = new entities.Powerup( Math.round(Math.random()*50+7)*10, Math.round(Math.random()*44+2)*10, this.powerup_types[Math.floor(Math.random()*this.powerup_types.length)], this, 10*1000 ); this.powerups.push(powerup); } /* * Exports */ module.exports.Game = Game;
JavaScript
0
@@ -486,16 +486,44 @@ %22beer%22 +,%0A %22freeze_snake%22 %0A @@ -654,18 +654,16 @@ -/* 'grow_sn @@ -723,18 +723,16 @@ _snake', -*/ %0A @@ -752,16 +752,18 @@ y_snake' +, %0A @@ -767,18 +767,16 @@ -/* 'flip_sc @@ -800,18 +800,16 @@ 'beer' -*/ %0A
95788a331201fba2cfa4c17a5e98ad5e5903faa4
Enable List.contains() to be O(1)
lib/List.js
lib/List.js
'use strict'; class List { constructor (siblingNames) { this.first = this.last = null; this.length = 0; this.siblings = siblingNames || List.defaultSiblings; } append (child) { this.insert(child, null); } contains (child) { return this.indexOf(child) > -1; } indexOf (child) { let next = this.siblings.next; for (let i = 0, c = this.first; c; ++i, c = c[next]) { if (c === child) { return i; } } return -1; } insert (child, before) { if (child === before) { throw new Error('Cannot insert a child before itself'); } let { next, prev } = this.siblings; if (!this.first) { if (before !== null) { throw new Error('Invalid "before" item'); } this.first = this.last = child; child[next] = child[prev] = null; } else if (before) { let p = before[prev]; if (p) { p[next] = child; } else { this.first = child; } child[prev] = p; child[next] = before; before[prev] = child; } else { let p = this.last; p[next] = child; child[prev] = p; child[next] = null; this.last = child; } ++this.length; } remove (child) { let { next, prev } = this.siblings; let nx = child[next]; let pr = child[prev]; if (this.first === child) { if (!(this.first = nx)) { this.last = null; } else { nx[prev] = null; } } else if (this.last === child) { this.last = pr; pr[next] = null; } else { // Too expensive to ensure that child is in this list... nx[prev] = pr; pr[next] = nx; } child[next] = child[prev] = null; --this.length; } } Object.freeze(List.defaultSiblings = { next: 'next', prev: 'prev' }); Object.freeze(List.EMPTY = new List()); module.exports = List;
JavaScript
0.999975
@@ -176,24 +176,190 @@ ultSiblings; +%0A%0A // Since items can be in multiple lists (based on different sibling names),%0A // we need a symbol of our own:%0A this.tagSym = Symbol('ListTag'); %0A %7D%0A%0A @@ -458,28 +458,73 @@ urn -this. +child && child%5Bthis.tagSym%5D === this;%0A %7D%0A%0A indexOf + (child) %3E -1 @@ -523,39 +523,27 @@ ld) -%3E -1; +%7B %0A -%7D%0A%0A i -ndexO f (child ) %7B%0A @@ -530,36 +530,71 @@ if (child -) %7B%0A + && child%5Bthis.tagSym%5D === this) %7B%0A let next @@ -625,16 +625,20 @@ + + for (let @@ -692,24 +692,28 @@ + if (c === ch @@ -711,32 +711,36 @@ (c === child) %7B%0A + @@ -749,16 +749,34 @@ turn i;%0A + %7D%0A @@ -1719,32 +1719,67 @@ ild;%0A %7D%0A%0A + child%5Bthis.tagSym%5D = this;%0A ++this.l @@ -1805,32 +1805,174 @@ emove (child) %7B%0A + if (!child %7C%7C child%5Bthis.tagSym%5D !== this) %7B%0A throw new Error('Cannot remove item; not a member of this list');%0A %7D%0A%0A let %7B ne @@ -2384,77 +2384,8 @@ e %7B%0A - // Too expensive to ensure that child is in this list...%0A @@ -2437,32 +2437,67 @@ nx;%0A %7D%0A%0A + delete child%5Bthis.tagSym%5D;%0A child%5Bne
c637ef8ce922e0ba0bf3828a56b3b71fdc623310
change empty string to false to simplify things a little
pianist.js
pianist.js
/* * Pianist.js - a library that is good with keys * Lee James Machin, 2012 */ var Pianist = (function() { var Pianist; function isEditable(target) { return target.hasAttribute('contenteditable') || ['input', 'textarea'].indexOf(target.tagName.toLowerCase()) > 0; } Pianist = function Pianist() { this.keys = {}; this.listen(); return this; }; Pianist.prototype.add = function add(key, func) { Object.defineProperty(this.keys, key, { enumerable: true, configurable: false, value: func }); }; Pianist.prototype.remove = function remove(key) { delete this.keys[key]; }; Pianist.prototype.listen = function listen() { var _this = this; document.body.addEventListener('keypress', function(evt) { var evt = evt || window.event, charCode = evt.which || evt.keyCode, keyPressed = String.fromCharCode(charCode), modifiers = _this.buildModifierString(evt), target = evt.target || evt.srcElement, key; // make the keypressed lower case if we're dealing with a combo, // as using Shift will change the result and not work. if (modifiers.length > 0) { key = [modifiers, keyPressed].join('+'); } else { key = keyPressed; } if (_this.keys.hasOwnProperty(key) && !isEditable(target)) { return _this.keys[key].call(document.body, evt, key); } }, false); }; Pianist.prototype.buildModifierString = function buildModifierString(evt) { var modifiers = []; if (evt.ctrlKey) { modifiers.push('Ctrl'); } if (evt.altKey) { modifiers.push('Alt'); } return modifiers.length > 0 ? modifiers.join('+') : ''; }; return Pianist; })();
JavaScript
0.000076
@@ -1201,27 +1201,16 @@ odifiers -.length %3E 0 ) %7B%0A @@ -1742,10 +1742,13 @@ ) : -'' +false ;%0A
715083676ab3c79e8e29968e8cffe94f012db5cb
fix format tab application of values supporting if not defined
src/components/edit-format-window.js
src/components/edit-format-window.js
'use strict' // var units = require('../units') var editFormatTabs = require('./edit-format-tabs') var Format = require('../classes/Format') module.exports = openMainWinFunction /** * Make the openMainWin function as a closure * @method * @param {Editor} editor The tinymce active editor instance * @returns {function} openMainWin The openMainWin closure function */ function openMainWinFunction (editor) { return openMainWin /** * Open the main paragraph properties window * @function * @inner * @returns {undefined} */ function openMainWin (format) { var formatTab = editFormatTabs.createFormatTab(format) var marginsTab = editFormatTabs.createMarginsTab(format) // console.log('format', format) editor.windowManager.open({ bodyType: 'tabpanel', title: 'Edit Document Format', body: [ formatTab, marginsTab ], data: { newformat: format.name, orientation: 'portrait', pageHeight: format.height.slice(0, -2), pageWidth: format.width.slice(0, -2), marginTop: format.margins.top.slice(0, -2), marginRight: format.margins.right.slice(0, -2), marginBottom: format.margins.bottom.slice(0, -2), marginLeft: format.margins.left.slice(0, -2) }, onsubmit: onMainWindowSubmit }) function onMainWindowSubmit (evt) { var d = evt.data var formatToApply = { name: 'custom', orientation: d.orientation, height: d.pageHeight + 'mm', // @TODO implement heightUnit width: d.pageWidth + 'mm', // @TODO implement widthUnit (etc...) margins: { bottom: d.marginsBottom + 'mm', left: d.marginsLeft + 'mm', right: d.marginsRig + 'mm', top: d.marginsTop + 'mm' }, header: { border: { color: d.headerBordersColor, style: d.headerBordersStyle, width: d.headerBordersWidth + 'mm' }, height: d.headerHeight + 'mm', margins: { bottom: d.headerMarginsBottom + 'mm', left: d.headerMarginsLeft + 'mm', right: d.headerMarginsRight + 'mm' } }, footer: { border: { color: d.footerBordersColor, style: d.footerBordersStyle, width: d.footerBordersWidth + 'mm' }, height: d.footerHeight + 'mm', margins: { top: d.footerMarginsTop + 'mm', left: d.footerMarginsLeft + 'mm', right: d.footerMarginsRight + 'mm' } }, body: { border: { color: d.bodyBordersColor, style: d.bodyBordersStyle, width: d.bodyBordersWidth + 'mm' } } } editor.plugins.headersfooters.format = new Format('custom', formatToApply) editor.plugins.headersfooters.format.applyToPlugin(editor.plugins.headersfooters) } } }
JavaScript
0
@@ -1315,16 +1315,162 @@ %7D)%0A%0A + /**%0A * Open edit format window submit callback%0A *%0A * @TODO implement heightUnit%0A * @TODO implement widthUnit (etc...)%0A */%0A func @@ -1597,16 +1597,17 @@ tation: +( d.orient @@ -1611,16 +1611,46 @@ entation +) ? d.orientation : 'portrait' ,%0A @@ -1658,16 +1658,33 @@ height: + (d.pageHeight) ? d.pageH @@ -1699,39 +1699,25 @@ 'mm' -, // @TODO implement + : format. height -Unit +, %0A @@ -1727,16 +1727,32 @@ width: + (d.pageWidth) ? d.pageW @@ -1766,47 +1766,24 @@ 'mm' -, // @TODO implement widthUnit (etc...) + : format.width, %0A
9fc0251eeeaea096113743e9ebd68fe50a714118
Fix this.toHTMLAsync call in boilerplate-generator (#9838)
packages/boilerplate-generator/generator.js
packages/boilerplate-generator/generator.js
import { readFile } from 'fs'; import { create as createStream } from "combined-stream2"; import WebBrowserTemplate from './template-web.browser'; import WebCordovaTemplate from './template-web.cordova'; // Copied from webapp_server const readUtf8FileSync = filename => Meteor.wrapAsync(readFile)(filename, 'utf8'); const identity = value => value; function appendToStream(chunk, stream) { if (typeof chunk === "string") { stream.append(Buffer.from(chunk, "utf8")); } else if (Buffer.isBuffer(chunk) || typeof chunk.read === "function") { stream.append(chunk); } } let shouldWarnAboutToHTMLDeprecation = ! Meteor.isProduction; export class Boilerplate { constructor(arch, manifest, options = {}) { const { headTemplate, closeTemplate } = _getTemplate(arch); this.headTemplate = headTemplate; this.closeTemplate = closeTemplate; this.baseData = null; this._generateBoilerplateFromManifest( manifest, options ); } toHTML(extraData) { if (shouldWarnAboutToHTMLDeprecation) { shouldWarnAboutToHTMLDeprecation = false; console.error( "The Boilerplate#toHTML method has been deprecated. " + "Please use Boilerplate#toHTMLStream instead." ); console.trace(); } // Calling .await() requires a Fiber. return toHTMLAsync(extraData).await(); } // Returns a Promise that resolves to a string of HTML. toHTMLAsync(extraData) { return new Promise((resolve, reject) => { const stream = this.toHTMLStream(extraData); const chunks = []; stream.on("data", chunk => chunks.push(chunk)); stream.on("end", () => { resolve(Buffer.concat(chunks).toString("utf8")); }); stream.on("error", reject); }); } // The 'extraData' argument can be used to extend 'self.baseData'. Its // purpose is to allow you to specify data that you might not know at // the time that you construct the Boilerplate object. (e.g. it is used // by 'webapp' to specify data that is only known at request-time). // this returns a stream toHTMLStream(extraData) { if (!this.baseData || !this.headTemplate || !this.closeTemplate) { throw new Error('Boilerplate did not instantiate correctly.'); } const data = {...this.baseData, ...extraData}; const start = "<!DOCTYPE html>\n" + this.headTemplate(data); const { body, dynamicBody } = data; const end = this.closeTemplate(data); const response = createStream(); appendToStream(start, response); if (body) { appendToStream(body, response); } if (dynamicBody) { appendToStream(dynamicBody, response); } appendToStream(end, response); return response; } // XXX Exported to allow client-side only changes to rebuild the boilerplate // without requiring a full server restart. // Produces an HTML string with given manifest and boilerplateSource. // Optionally takes urlMapper in case urls from manifest need to be prefixed // or rewritten. // Optionally takes pathMapper for resolving relative file system paths. // Optionally allows to override fields of the data context. _generateBoilerplateFromManifest(manifest, { urlMapper = identity, pathMapper = identity, baseDataExtension, inline, } = {}) { const boilerplateBaseData = { css: [], js: [], head: '', body: '', meteorManifest: JSON.stringify(manifest), ...baseDataExtension, }; manifest.forEach(item => { const urlPath = urlMapper(item.url); const itemObj = { url: urlPath }; if (inline) { itemObj.scriptContent = readUtf8FileSync( pathMapper(item.path)); itemObj.inline = true; } if (item.type === 'css' && item.where === 'client') { boilerplateBaseData.css.push(itemObj); } if (item.type === 'js' && item.where === 'client' && // Dynamic JS modules should not be loaded eagerly in the // initial HTML of the app. !item.path.startsWith('dynamic/')) { boilerplateBaseData.js.push(itemObj); } if (item.type === 'head') { boilerplateBaseData.head = readUtf8FileSync(pathMapper(item.path)); } if (item.type === 'body') { boilerplateBaseData.body = readUtf8FileSync(pathMapper(item.path)); } }); this.baseData = boilerplateBaseData; } }; // Returns a template function that, when called, produces the boilerplate // html as a string. const _getTemplate = arch => { if (arch === 'web.browser') { return WebBrowserTemplate; } else if (arch === 'web.cordova') { return WebCordovaTemplate; } else { throw new Error('Unsupported arch: ' + arch); } };
JavaScript
0.000006
@@ -1328,16 +1328,21 @@ return +this. toHTMLAs
73ff17f1399c47686c28f9a36d624c0773dd16f2
remove attr multiple
library/CM/FormField/File.js
library/CM/FormField/File.js
/** * @class CM_FormField_File * @extends CM_FormField_Abstract */ var CM_FormField_File = CM_FormField_Abstract.extend({ _class: 'CM_FormField_File', events: { 'click .deleteFile': function(e) { $(e.currentTarget).closest('.preview').remove(); } }, ready: function() { var field = this; var $input = this.$('input[type="file"]'); var dropZoneEnabled = this.$('.dropInfo').length > 0; var allowedExtensions = field.getOption("allowedExtensions"); var allowedExtensionsRegexp = _.isEmpty(allowedExtensions) ? null : new RegExp('\.(' + allowedExtensions.join('|') + ')$', 'i'); var inProgressCount = 0; if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { $input.removeAttr('multiple'); } $input.fileupload({ dataType: 'json', url: cm.getUrl('/upload/' + cm.getSiteId() + '/', {'field': field.getClass()}), dropZone: dropZoneEnabled ? this.$el : null, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, formData: function(form) { return $input; }, send: function(e, data) { inProgressCount++; field.error(null); _.each(data.files, function(file) { if (allowedExtensionsRegexp && !allowedExtensionsRegexp.test(file.name)) { field.error(cm.language.get('{$file} has an invalid extension. Only {$extensions} are allowed.', {file: file.name, extensions: allowedExtensions.join(', ')})); file.error = true; } }); data.files = _.reject(data.files, function(file) { return file.error; }); if (_.isEmpty(data.files)) { data.skipFailMessage = true; return false; } data.$preview = $('<li class="preview"><div class="template"><span class="spinner"></span></div></li>'); field.$('.previews').append(data.$preview); }, done: function(e, data) { if (data.result.success) { while (field.getOption("cardinality") && field.getOption("cardinality") < field.getCountUploaded()) { field.$('.previews .preview').first().remove(); } data.$preview.html(data.result.success.preview + '<input type="hidden" name="' + field.getName() + '[]" value="' + data.result.success.id + '"/>'); } else if (data.result.error) { data.$preview.remove(); field.error(data.result.error.msg); } }, fail: function(e, data) { if (data.$preview) { data.$preview.remove(); } if (!data.skipFailMessage) { field.error('Upload error'); } }, always: function(e, data) { inProgressCount--; if (inProgressCount == 0 && field.getCountUploaded() > 0) { field.trigger("uploadComplete", data.files); } } }); if (dropZoneEnabled) { this.bindJquery($(document), 'dragenter', function() { field.$el.addClass('dragover') }); this.bindJquery($(document), 'drop', function() { field.$el.removeClass('dragover') }); this.bindJquery($(document), 'drop dragover', function(e) { e.preventDefault(); }); } }, /** * @returns {Number} */ getCountUploaded: function() { return this.$('.previews .preview').length; }, reset: function() { this.$('.previews').empty(); } });
JavaScript
0.000158
@@ -627,134 +627,8 @@ 0;%0A%0A -%09%09if ((navigator.userAgent.match(/iPhone/i)) %7C%7C (navigator.userAgent.match(/iPod/i))) %7B%0A%09%09%09$input.removeAttr('multiple');%0A%09%09%7D%0A %0A%09%09$
a68baa0eb2019ed5f7843660cc1e6c8ccbadd5f2
Fix event handler
extensions/google_properties_menu/contentjs/doodles.js
extensions/google_properties_menu/contentjs/doodles.js
var runPacman = function() { $(this).addClass("selected"); $("#choose_game").hide(); $("#pacman_selected").show(); // and send the ROS message sendSwitchROSMessage($(this)); } $('#pacman').click(function(){ runPacman(); }); $('#pacman').addEventListener( 'touchstart', runPacman, true );
JavaScript
0.000042
@@ -243,17 +243,39 @@ );%0A%7D);%0A%0A -$ +document.getElementById ('#pacma
b9b167957d5ad2ae66df9551d53406162ab55f7b
Remove unused variable
src/halresource.spec.js
src/halresource.spec.js
'use strict'; describe('HalResource', function () { beforeEach(module('hypermedia')); // Setup var $log, $q, $rootScope, HalResource, ResourceContext, mockContext, uri, resource; beforeEach(inject(function (_$log_, _$q_, _$rootScope_, _HalResource_, _ResourceContext_) { $log = _$log_; $q = _$q_; $rootScope = _$rootScope_; HalResource = _HalResource_; ResourceContext = _ResourceContext_; mockContext = jasmine.createSpyObj('mockContext', ['get', 'httpGet', 'httpPut', 'httpDelete', 'httpPost']); uri = 'http://example.com'; resource = new HalResource(uri, mockContext); })); // Tests it('is initialized correctly', function () { expect(resource.$uri).toBe(uri); expect(resource.$context).toBe(mockContext); expect(resource.$links).toEqual({}); expect(resource.$syncTime).toBeNull(); expect(resource.$profile).toBeNull(); }); // HTTP it('creates HTTP GET request for HAL data', function () { expect(resource.$getRequest()).toEqual({ method: 'get', url: 'http://example.com', headers: {Accept: 'application/hal+json'} }); }); it('creates HTTP PUT request with JSON data', function () { expect(resource.$putRequest()).toEqual({ method: 'put', url: 'http://example.com', data: resource, headers: {'Content-Type': 'application/json'} }); }); // Updates it('requires a link with the "self" relation in the data', function () { expect(function () { resource.$update({foo: 'bar'}); }).toThrowError("Self link href differs: expected 'http://example.com', was undefined"); }); it('extracts links', function () { mockContext.get.and.returnValue(resource); var links = { self: {href: 'http://example.com'}, profile: {href: 'http://example.com/profile'} }; resource.$update({ foo: 'bar', _links: links }); expect(resource.$links).toEqual(links); expect(resource._links).toBeUndefined(); }); it('extracts and links embedded resources', function () { var resource1 = new HalResource('http://example.com/1', mockContext); mockContext.get.and.callFake(function (uri) { switch (uri) { case resource.$uri: return resource; case resource1.$uri: return resource1; } }); resource.$update({ _links: { self: {href: 'http://example.com'}, profile: {href: 'http://example.com/profile'} }, _embedded: { 'next': { foo: 'bar', _links: { self: {href: 'http://example.com/1'} } } } }); expect(resource.$links.next.href).toBe(resource1.$uri); expect(resource1.foo).toBe('bar'); expect(resource._embedded).toBeUndefined(); }); it('extracts and links embedded resources for custom resource type', function () { var MyResource = function (uri, context) { return HalResource.call(this, uri, context); }; MyResource.prototype = Object.create(HalResource.prototype, { constructor: {value: MyResource} }); var resource2 = new MyResource(uri, mockContext), resource3 = new MyResource('http://example.com/1', mockContext); mockContext.get.and.callFake(function (uri) { switch (uri) { case resource2.$uri: return resource2; case resource3.$uri: return resource3; } }); resource2.$update({ _links: { self: {href: 'http://example.com'}, profile: {href: 'http://example.com/profile'} }, _embedded: { 'next': { foo: 'bar', _links: { self: {href: 'http://example.com/1'} } } } }); expect(mockContext.get).toHaveBeenCalledWith(resource2.$uri, MyResource); expect(mockContext.get).toHaveBeenCalledWith(resource3.$uri, MyResource); }); });
JavaScript
0.000015
@@ -139,25 +139,8 @@ rce, - ResourceContext, moc @@ -240,27 +240,8 @@ rce_ -, _ResourceContext_ ) %7B%0A @@ -342,49 +342,8 @@ e_;%0A - ResourceContext = _ResourceContext_;%0A
f61de394da5abcb22386eda3ee3d7f35056613df
change data source of count for process definitions.
webapps/ui/cockpit/plugins/base/app/views/processesDashboard/process-definitions.js
webapps/ui/cockpit/plugins/base/app/views/processesDashboard/process-definitions.js
'use strict'; var fs = require('fs'); var template = fs.readFileSync(__dirname + '/process-definitions.html', 'utf8'); module.exports = [ 'ViewsProvider', function(ViewsProvider) { ViewsProvider.registerDefaultView('cockpit.processes.dashboard', { id: 'process-definition', label: 'Deployed Process Definitions', template: template, controller: [ '$scope', 'Views', 'camAPI', 'localConf', function($scope, Views, camAPI, localConf) { var getPDIncidentsCount = function(incidents) { if(!incidents) { return 0; } return incidents.reduce(function(sum, incident) { return sum + incident.incidentCount; }, 0); }; var processInstancePlugins = Views.getProviders({ component: 'cockpit.processInstance.view' }); $scope.hasHistoryPlugin = processInstancePlugins.filter(function(plugin) { return plugin.id === 'history'; }).length > 0; var processData = $scope.processData.newChild($scope); $scope.hasReportPlugin = Views.getProviders({ component: 'cockpit.report' }).length > 0; var processDefinitionService = camAPI.resource('process-definition'); $scope.loadingState = 'LOADING'; // only get count of process definitions var countProcessDefinitions = function() { processDefinitionService.count({ latest: true }, function(err, count) { if (err) { $scope.loadingState = 'ERROR'; } $scope.processDefinitionsCount = count; }); }; // get full list of process definitions and related resources var listProcessDefinitions = function() { processDefinitionService.list({ latest: true }, function(err, data) { $scope.processDefinitionData = data.items; $scope.processDefinitionsCount = data.items.length; if (err) { $scope.loadingState = 'ERROR'; } $scope.loadingState = 'LOADED'; processData.observe('processDefinitionStatistics', function(processDefinitionStatistics) { $scope.statistics = processDefinitionStatistics; $scope.statistics.forEach(function(statistic) { var processDefId = statistic.definition.id; var foundIds = $scope.processDefinitionData.filter(function(pd) { return pd.id === processDefId; }); var foundObject = foundIds[0]; if(foundObject) { foundObject.incidents = statistic.incidents; foundObject.incidentCount = getPDIncidentsCount(foundObject.incidents); foundObject.instances = statistic.instances; } }); }); }); }; $scope.processesActions = Views.getProviders({ component: 'cockpit.processes.action'}); $scope.hasActionPlugin = $scope.processesActions.length > 0; $scope.definitionVars = { read: [ 'pd' ] }; var removeActionDeleteListener = $scope.$on('processes.action.delete', function(event, definitionId) { var definitions = $scope.processDefinitionData; for (var i = 0; i < definitions.length; i++) { if (definitions[i].id === definitionId) { definitions.splice(i, 1); break; } } $scope.processDefinitionsCount = definitions.length; }); $scope.$on('$destroy', function() { removeActionDeleteListener(); }); $scope.activeTab = 'list'; $scope.selectTab = function(tab) { $scope.activeTab = tab; }; $scope.activeSection = localConf.get('processesDashboardActive', true); // if tab is not active, it's enough to only get the count of process definitions $scope.activeSection ? listProcessDefinitions() : countProcessDefinitions(); $scope.toggleSection = function toggleSection() { // if tab is not active, it's enough to only get the count of process definitions ($scope.activeSection = !$scope.activeSection) ? listProcessDefinitions() : countProcessDefinitions(); localConf.set('processesDashboardActive', $scope.activeSection); }; }], priority: 0 }); }];
JavaScript
0
@@ -1967,20 +1967,13 @@ ata. -items.length +count ;%0A
b990a87964bc02c943a6687c3546fece9bfe44c8
remove unused import
src/neo/models/Suite.js
src/neo/models/Suite.js
import { action, observable, computed } from "mobx"; import uuidv4 from "uuid/v4"; import SortBy from "sort-array"; import TestCase from "./TestCase"; export default class Suite { id = null; @observable name = null; @observable _tests = []; constructor(id = uuidv4(), name = "Untitled Suite") { this.id = id; this.name = name; this.exportSuite = this.exportSuite.bind(this); } @computed get tests() { return SortBy(this._tests, "name"); } isTest(test) { return (test && test.constructor.name === "TestCase"); } @action.bound setName(name) { this.name = name; } @action.bound addTestCase(test) { if (!this.isTest(test)) { throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`); } else { this._tests.push(test); } } @action.bound removeTestCase(test) { if (!this.isTest(test)) { throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`); } else { this._tests.remove(test); } } @action.bound replaceTestCases(tests) { if (tests.filter(test => !this.isTest(test)).length) { throw new Error("Expected to receive array of TestCase"); } else { this._tests.replace(tests); } } exportSuite() { return { id: this.id, name: this.name, tests: this._tests.map(t => t.id) }; } @action static fromJS = function(jsRep, projectTests) { const suite = new Suite(jsRep.id); suite.setName(jsRep.name); suite._tests.replace(jsRep.tests.map((testId) => projectTests.find(({id}) => id === testId))); return suite; } }
JavaScript
0.000001
@@ -112,43 +112,8 @@ ay%22; -%0Aimport TestCase from %22./TestCase%22; %0A%0Aex
bda49e3a7d7458130b7e5b6966859827a778a36f
Remove non-essential comma
src/js/view/organizers/upperButtonsOrganizer.js
src/js/view/organizers/upperButtonsOrganizer.js
import * as PIXI from "pixi.js"; import {default as h} from "../../helpers"; import {buttonBuilder} from "../builders"; export default function upperButtonsOrganizer( state={ global: {mode: "IDLE", step: 0}, upperButton: {alt: "", status: 0}, } ) { const container = new PIXI.Container(); for(let b of ["ADD", "LDC", "LDV", "NOT", "STV"]) { if(b === state.upperButton.alt) { const button = buttonBuilder(b, state.upperButton.status); container.addChild(button); } else { const button = buttonBuilder(b); container.addChild(button); } } return container; }
JavaScript
0.999998
@@ -245,17 +245,16 @@ atus: 0%7D -, %0A %7D%0A) %7B
d709dca0be6cfc25845960e38e514d40d4afacf1
fix `String#split` `limit` argument conversion
packages/core-js/modules/es.regexp.split.js
packages/core-js/modules/es.regexp.split.js
'use strict'; // @@split logic require('../internals/fix-regexp-well-known-symbol-logic')('split', 2, function (defined, SPLIT, nativeSplit) { var isRegExp = require('../internals/is-regexp'); var internalSplit = nativeSplit; var arrayPush = [].push; var LENGTH = 'length'; if ( 'abbc'.split(/(b)*/)[1] == 'c' || 'test'.split(/(?:)/, -1)[LENGTH] != 4 || 'ab'.split(/(?:ab)*/)[LENGTH] != 2 || '.'.split(/(.?)(.?)/)[LENGTH] != 4 || '.'.split(/()()/)[LENGTH] > 1 || ''.split(/.?/)[LENGTH] ) { var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group // based on es5-shim implementation, need to rework it internalSplit = function (separator, limit) { var string = String(this); if (separator === undefined && limit === 0) return []; // If `separator` is not a regex, use native split if (!isRegExp(separator)) return nativeSplit.call(string, separator, limit); var output = []; var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); var lastLastIndex = 0; var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; // Make `global` and avoid `lastIndex` issues by working with a copy var separatorCopy = new RegExp(separator.source, flags + 'g'); var separator2, match, lastIndex, lastLength, i; // Doesn't need flags gy, but they don't hurt if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); while (match = separatorCopy.exec(string)) { // `separatorCopy.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0][LENGTH]; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG // eslint-disable-next-line no-loop-func if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () { for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined; }); if (match[LENGTH] > 1 && match.index < string[LENGTH]) arrayPush.apply(output, match.slice(1)); lastLength = match[0][LENGTH]; lastLastIndex = lastIndex; if (output[LENGTH] >= splitLimit) break; } if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop } if (lastLastIndex === string[LENGTH]) { if (lastLength || !separatorCopy.test('')) output.push(''); } else output.push(string.slice(lastLastIndex)); return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; }; // Chakra, V8 } else if ('0'.split(undefined, 0)[LENGTH]) { internalSplit = function (separator, limit) { return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit); }; } // `String.prototype.split` method // https://tc39.github.io/ecma262/#sec-string.prototype.split return [function split(separator, limit) { var O = defined(this); var splitter = separator == undefined ? undefined : separator[SPLIT]; return splitter !== undefined ? splitter.call(separator, O, limit) : internalSplit.call(String(O), separator, limit); }, internalSplit]; });
JavaScript
0.000006
@@ -895,16 +895,26 @@ arator)) + %7B%0A return @@ -950,26 +950,75 @@ rator, limit -); + !== undefined ? limit %3E%3E%3E 0 : 4294967295);%0A %7D %0A var o
b3a28290dfa37abb0dd068bdc7555883588980e5
add callbacks to all command.execute functions
src/businessService.js
src/businessService.js
"use strict"; var Command = require('./command'); var BusinessService = function(dataProxy) { //if (!dataProxy instanceof DataProxy) throw 'dataproxy must ..'; if (this instanceof BusinessService) { this.dataProxy = dataProxy; } else { return new BusinessService(dataProxy); } }; BusinessService.prototype = { constructor: BusinessService, getAllCommand: function() { var service = this; var context = {}; return new Command({ onInitializationMethod: function() { service.__onGetAllCommandInitialization(context); }, getRulesMethod: function() { return service.__getRulesForGetAll(context); }, executionMethod: function() { return service.__getAll(context); } }); }, getByIdCommand: function(id) { var service = this; var context = {}; return new Command({ onInitializationMethod: function() { service.__onGetByIdCommandInitialization(id, context); }, getRulesMethod: function() { return service.__getRulesForGetById(id, context); }, executionMethod: function() { return service.__getById(id, context); } }); }, insertCommand: function(data) { var service = this; var context = {}; return new Command({ onInitializationMethod: function() { service.__onInsertCommandInitialization(data, context); }, getRulesMethod: function() { return service.__getRulesForInsert(data, context); }, executionMethod: function(done) { return service.__insert(data, context, done); } }); }, updateCommand: function(data) { var service = this; var context = {}; return new Command({ onInitializationMethod: function() { service.__onUpdateCommandInitialization(data, context); }, getRulesMethod: function() { return service.__getRulesForUpdate(data, context); }, executionMethod: function() { return service.__update(data, context); } }); }, deleteCommand: function(id) { var service = this; var context = {}; return new Command({ onInitializationMethod: function() { service.__onDeleteCommandInitialization(id, context); }, getRulesMethod: function() { return service.__getRulesForDelete(id, context); }, executionMethod: function() { return service.__delete(id, context); } }); }, __getAll: function(context) { return this.dataProxy.getAll(data); }, __getRulesForGetAll: function(context) { return []; }, __onGetAllCommandInitialization: function(context) { }, __getById: function(id, context) { return this.dataProxy.getById(id); }, __getRulesForGetById: function(id, context) { return []; }, __onGetByIdCommandInitialization: function(id, context) { }, __insert: function(data, context, done) { return this.dataProxy.insert(data, done); }, __getRulesForInsert: function(data, context) { return []; }, __onInsertCommandInitialization: function(data, context) { }, __update(data, context) { return this.dataProxy.update(data); }, __getRulesForUpdate: function(data, context) { return []; }, __onUpdateCommandInitialization: function(data, context) { }, __delete(id, context) { return this.dataProxy.delete(id); }, __getRulesForDelete: function(id, context) { return []; }, __onDeleteCommandInitialization: function(id, context) { } }; module.exports = BusinessService;
JavaScript
0.000001
@@ -689,32 +689,36 @@ ethod: function( +done ) %7B%0A retu @@ -736,32 +736,38 @@ __getAll(context +, done );%0A %7D%0A %7D @@ -1121,32 +1121,36 @@ ethod: function( +done ) %7B%0A retu @@ -1173,32 +1173,38 @@ ById(id, context +, done );%0A %7D%0A %7D @@ -2002,32 +2002,36 @@ ethod: function( +done ) %7B%0A retu @@ -2055,32 +2055,38 @@ te(data, context +, done );%0A %7D%0A %7D @@ -2437,32 +2437,36 @@ ethod: function( +done ) %7B%0A retu @@ -2496,16 +2496,22 @@ context +, done ); %0A @@ -2548,32 +2548,38 @@ function(context +, done ) %7B%0A return t @@ -2599,24 +2599,30 @@ .getAll(data +, done ); %0A %7D,%0A%0A @@ -2769,32 +2769,38 @@ tion(id, context +, done ) %7B%0A return t @@ -2823,16 +2823,22 @@ tById(id +, done ); %0A %7D, @@ -3224,32 +3224,38 @@ te(data, context +, done ) %7B%0A return t @@ -3279,16 +3279,22 @@ ate(data +, done ); %0A %7D, @@ -3446,32 +3446,38 @@ lete(id, context +, done ) %7B%0A return t @@ -3499,16 +3499,22 @@ elete(id +, done ); %0A %7D,
7c59974ec7c5f73ea449bf7ca40d07879f892634
fix prefetching dynamic imports from packages They fail because : gets replaced by _ Issue 11157
packages/dynamic-import/dynamic-versions.js
packages/dynamic-import/dynamic-versions.js
// This magic double-underscored identifier gets replaced in // tools/isobuild/bundler.js with a tree of hashes of all dynamic // modules, for use in client.js and cache.js. var versions = __DYNAMIC_VERSIONS__; exports.get = function (id) { var tree = versions; var version = null; id.split("/").some(function (part) { if (part) { // If the tree contains identifiers for Meteor packages with colons // in their names, the colons should not have been replaced by // underscores, but there's a bug that results in that behavior, so // for now it seems safest to be tolerant of underscores here. // https://github.com/meteor/meteor/pull/9103 tree = tree[part] || tree[part.replace(":", "_")]; } if (! tree) { // Terminate the search without reassigning version. return true; } if (typeof tree === "string") { version = tree; return true; } }); return version; }; function getFlatModuleArray(tree) { var parts = [""]; var result = []; function walk(t) { if (t && typeof t === "object") { Object.keys(t).forEach(function (key) { parts.push(key); walk(t[key]); parts.pop(); }); } else if (typeof t === "string") { result.push(parts.join("/")); } } walk(tree); return result; } // If Package.appcache is loaded, preload additional modules after the // core bundle has been loaded. function precacheOnLoad(event) { // Check inside onload to make sure Package.appcache has had a chance to // become available. if (! Package.appcache) { return; } // Prefetch in chunks to reduce overhead. If we call module.prefetch(id) // multiple times in the same tick of the event loop, all those modules // will be fetched in one HTTP POST request. function prefetchInChunks(modules, amount) { Promise.all(modules.splice(0, amount).map(function (id) { return module.prefetch(id); })).then(function () { if (modules.length > 0) { setTimeout(function () { prefetchInChunks(modules, amount); }, 0); } }); } // Get a flat array of modules and start prefetching. prefetchInChunks(getFlatModuleArray(versions), 50); } // Use window.onload to only prefetch after the main bundle has loaded. if (global.addEventListener) { global.addEventListener('load', precacheOnLoad, false); } else if (global.attachEvent) { global.attachEvent('onload', precacheOnLoad); }
JavaScript
0
@@ -1860,16 +1860,18 @@ ) %7B%0A + Promise. @@ -1930,36 +1930,759 @@ + return -module.prefetch(id);%0A +new Promise(function(resolve, reject) %7B%0A module.prefetch(id).then((module)=%3Eresolve(module)).catch((err)=%3E%7B%0A // we probably have a : _ mismatch %0A // what can get wrong if we do the replacement%0A // 1. a package with a name like a_b:package will not resolve%0A // 2. someone falsely imports a_package that does not exist but a package%0A // a:package exists, so this one gets imported and its usage will fail%0A if(id.indexOf('/node_modules/meteor/')===0) %7B%0A module.prefetch('/node_modules/meteor/'+id.replace('/node_modules/meteor/','').replace('_',':')%0A ).then(resolve).catch(reject);%0A %7D else reject(err);%0A %7D)%0A %7D);%0A @@ -2706,24 +2706,26 @@ () %7B%0A + + if (modules. @@ -2734,24 +2734,26 @@ ngth %3E 0) %7B%0A + setT @@ -2783,16 +2783,18 @@ + prefetch @@ -2828,16 +2828,18 @@ + + %7D, 0);%0A @@ -2843,18 +2843,22 @@ ;%0A -%7D%0A + %7D%0A %7D);%0A
288efe898acf95f32cb9b394131a20390db79cac
Fix #383 - Display lifetime in main logo
packages/components/components/logo/MainLogo.js
packages/components/components/logo/MainLogo.js
import React from 'react'; import PropTypes from 'prop-types'; import { useSubscription, Href, useConfig } from 'react-components'; import { Link } from 'react-router-dom'; import { APPS, PLAN_SERVICES, CLIENT_TYPES } from 'proton-shared/lib/constants'; import { getPlanName } from 'proton-shared/lib/helpers/subscription'; import CalendarLogo from './CalendarLogo'; import ContactsLogo from './ContactsLogo'; import MailLogo from './MailLogo'; import VpnLogo from './VpnLogo'; import { classnames } from '../../helpers/component'; const { MAIL, VPN } = PLAN_SERVICES; const { PROTONMAIL, PROTONCONTACTS, PROTONDRIVE, PROTONCALENDAR, PROTONVPN_SETTINGS, PROTONMAIL_SETTINGS } = APPS; /** * MainLogo component * @type any * @param {String} url * @param {Boolean} external true for external link */ const MainLogo = ({ url = '/inbox', external = false, className = '' }) => { const { APP_NAME, CLIENT_TYPE } = useConfig(); const [subscription] = useSubscription(); const classNames = classnames(['logo-container nodecoration flex flex-item-centered-vert', className]); const planName = getPlanName(subscription, CLIENT_TYPE === CLIENT_TYPES.VPN ? VPN : MAIL); const logo = (() => { // we do not have the proper logos for all the products yet. Use mail logo in the meantime if ([PROTONMAIL, PROTONMAIL_SETTINGS, PROTONDRIVE].includes(APP_NAME)) { return <MailLogo planName={planName} />; } if (APP_NAME === PROTONCALENDAR) { return <CalendarLogo planName="beta" />; } if (APP_NAME === PROTONCONTACTS) { return <ContactsLogo planName={planName} />; } if (APP_NAME === PROTONVPN_SETTINGS) { return <VpnLogo planName={planName} />; } return null; })(); if (external) { return ( <Href url={url} target="_self" rel="noreferrer help" className={classNames}> {logo} </Href> ); } return ( <Link to={url} className={classNames}> {logo} </Link> ); }; MainLogo.propTypes = { url: PropTypes.string, className: PropTypes.string, external: PropTypes.bool }; export default MainLogo;
JavaScript
0
@@ -268,16 +268,29 @@ PlanName +, hasLifetime %7D from @@ -1114,16 +1114,73 @@ anName = + hasLifetime(subscription)%0A ? 'Lifetime'%0A : getPlan
97f51801be80bd33761afb8dc36d83703a3df9e2
Remove unused code
src/objectify.jquery.js
src/objectify.jquery.js
/** * Form data into javascript object * @author Jim Krayer <[email protected]> * @version 0.0.2 */ ;(function ($) { var pluginName = "objectify", defaults = { exclusions: [], sanitizations: false }; $.fn.extend({ objectify: function (exclusions, sanitize) { var formData = $(this).serializeArray(); var obj = {}; var key; var name; exclusions = exclusions || []; sanitize = sanitize || false; for (key in formData) { name = formData[key].name; if (exclusions.indexOf(name) > -1) { continue; } if (sanitize && sanitize.hasOwnProperty(name)) { obj[name] = sanitize[name](formData[key].value); continue; } obj[name] = formData[key].value; } return obj; } }); }(jQuery));
JavaScript
0.000006
@@ -97,11 +97,11 @@ n 0. -0.2 +1.0 %0A */ @@ -122,123 +122,8 @@ ) %7B%0A -%0A var pluginName = %22objectify%22,%0A defaults = %7B%0A exclusions: %5B%5D,%0A sanitizations: false%0A %7D;%0A%0A $. @@ -179,24 +179,25 @@ sanitize) %7B%0A +%0A var fo
1a147130c8b084e4a88737f7a9624c8c11980d56
fix applyOptions
src/html2pug/helpers.js
src/html2pug/helpers.js
const jsdom = require('jsdom-little') function __guard__ (value, transform) { return (typeof value !== 'undefined' && value !== null) ? transform(value) : undefined } function __range__ (left, right, inclusive) { let range = [] let ascending = left < right let end = !inclusive ? right : ascending ? right + 1 : right - 1 for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) { range.push(i) } return range } const defaultOptions = () => ({ entOptions: { useNamedReferences: true }, useTabs: false, doNotEncode: false, nspaces: 2 }) const applyOptions = ({ numeric, nspaces, tabs, donotencode, ...options }) => { const newOptions = defaultOptions() if (options.numeric != null) { newOptions.entOptions.useNamedReferences = !options.numeric } if (options.nspaces != null) { newOptions.nspaces = parseInt(options.nspaces) } if (options.tabs != null) { newOptions.useTabs = !!options.tabs } if (options.donotencode != null) { newOptions.doNotEncode = !!options.donotencode } return { ...newOptions, ...options } } function parse (text) { return new Promise((resolve, reject) => { jsdom.env(text, (errors, window) => { if (errors) { reject(errors) } else { resolve(window) } }) }) } const validJadeIdRegExp = /^[\w-]+$/ const validJadeClassRegExp = /^[\w-]+$/ const isValidJadeId = id => { id = id ? id.trim() : '' return id && validJadeIdRegExp.test(id) } const isValidJadeClassName = className => { className = className ? className.trim() : '' return className && validJadeClassRegExp.test(className) } module.exports = { __guard__, __range__, parse, applyOptions, isValidJadeClassName, isValidJadeId }
JavaScript
0.000001
@@ -705,24 +705,16 @@ )%0A if ( -options. numeric @@ -768,24 +768,16 @@ nces = ! -options. numeric @@ -784,24 +784,16 @@ %7D%0A if ( -options. nspaces @@ -833,24 +833,16 @@ arseInt( -options. nspaces) @@ -850,24 +850,16 @@ %7D%0A if ( -options. tabs != @@ -889,24 +889,16 @@ abs = !! -options. tabs %7D%0A @@ -902,24 +902,16 @@ %7D%0A if ( -options. donotenc @@ -956,16 +956,8 @@ = !! -options. dono
464e9ec6ecc06b33e694621314d65775182faf96
Document the input to an attribution function
src/ol/source/Source.js
src/ol/source/Source.js
/** * @module ol/source/Source */ import BaseObject from '../Object.js'; import SourceState from './State.js'; import {abstract} from '../util.js'; import {get as getProjection} from '../proj.js'; /** * A function that returns a string or an array of strings representing source * attributions. * * @typedef {function(import("../PluggableMap.js").FrameState): (string|Array<string>)} Attribution */ /** * A type that can be used to provide attribution information for data sources. * * It represents either * * a simple string (e.g. `'© Acme Inc.'`) * * an array of simple strings (e.g. `['© Acme Inc.', '© Bacme Inc.']`) * * a function that returns a string or array of strings ({@link module:ol/source/Source~Attribution}) * * @typedef {string|Array<string>|Attribution} AttributionLike */ /** * @typedef {Object} Options * @property {AttributionLike} [attributions] Attributions. * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible. * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection. * @property {import("./State.js").default} [state='ready'] State. * @property {boolean} [wrapX=false] WrapX. */ /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. * Base class for {@link module:ol/layer/Layer~Layer} sources. * * A generic `change` event is triggered when the state of the source changes. * @abstract * @api */ class Source extends BaseObject { /** * @param {Options} options Source options. */ constructor(options) { super(); /** * @protected * @type {import("../proj/Projection.js").default} */ this.projection = getProjection(options.projection); /** * @private * @type {?Attribution} */ this.attributions_ = adaptAttributions(options.attributions); /** * @private * @type {boolean} */ this.attributionsCollapsible_ = options.attributionsCollapsible !== undefined ? options.attributionsCollapsible : true; /** * This source is currently loading data. Sources that defer loading to the * map's tile queue never set this to `true`. * @type {boolean} */ this.loading = false; /** * @private * @type {import("./State.js").default} */ this.state_ = options.state !== undefined ? options.state : SourceState.READY; /** * @private * @type {boolean} */ this.wrapX_ = options.wrapX !== undefined ? options.wrapX : false; } /** * Get the attribution function for the source. * @return {?Attribution} Attribution function. */ getAttributions() { return this.attributions_; } /** * @return {boolean} Attributions are collapsible. */ getAttributionsCollapsible() { return this.attributionsCollapsible_; } /** * Get the projection of the source. * @return {import("../proj/Projection.js").default} Projection. * @api */ getProjection() { return this.projection; } /** * @abstract * @return {Array<number>|undefined} Resolutions. */ getResolutions() { return abstract(); } /** * Get the state of the source, see {@link module:ol/source/State~State} for possible states. * @return {import("./State.js").default} State. * @api */ getState() { return this.state_; } /** * @return {boolean|undefined} Wrap X. */ getWrapX() { return this.wrapX_; } /** * @return {Object|undefined} Context options. */ getContextOptions() { return undefined; } /** * Refreshes the source. The source will be cleared, and data from the server will be reloaded. * @api */ refresh() { this.changed(); } /** * Set the attributions of the source. * @param {AttributionLike|undefined} attributions Attributions. * Can be passed as `string`, `Array<string>`, {@link module:ol/source/Source~Attribution}, * or `undefined`. * @api */ setAttributions(attributions) { this.attributions_ = adaptAttributions(attributions); this.changed(); } /** * Set the state of the source. * @param {import("./State.js").default} state State. */ setState(state) { this.state_ = state; this.changed(); } } /** * Turns the attributions option into an attributions function. * @param {AttributionLike|undefined} attributionLike The attribution option. * @return {?Attribution} An attribution function (or null). */ function adaptAttributions(attributionLike) { if (!attributionLike) { return null; } if (Array.isArray(attributionLike)) { return function (frameState) { return attributionLike; }; } if (typeof attributionLike === 'function') { return attributionLike; } return function (frameState) { return [attributionLike]; }; } export default Source;
JavaScript
0.00176
@@ -208,32 +208,86 @@ A function that +takes a %7B@link module:ol/PluggableMap~FrameState%7D and returns a string @@ -289,16 +289,19 @@ tring or +%0A * an arra @@ -332,19 +332,16 @@ g source -%0A * attribu
3814314107f059feaf57c8b829fe811ed86e98aa
update countries microservice
countries/countries.js
countries/countries.js
'use strict'; var _ = require('lodash'); var path = require('path'); var async = require('async'); module.exports = function (options) { var seneca = this; var plugin = 'cd-countries'; var ENTITY_NS = 'cd/countries'; seneca.add({role: plugin, cmd: 'list'}, cmd_list); seneca.add({role: plugin, cmd: 'create'}, cmd_create); seneca.add({role: plugin, cmd: 'update'}, cmd_update); seneca.add({role: plugin, cmd: 'delete'}, cmd_delete); function cmd_list(args, done){ var seneca = this, query; query = args.query ? args.query : {}; seneca.make(ENTITY_NS).list$(query, function(err, response) { if(err){ return done(err); } else { return done(null, response); } }); } function cmd_create(args, done){ var seneca = this, country = args.country; seneca.make$(ENTITY_NS).save$(country, function(err, response) { if(err) return done(err); done(null, response); }); } function cmd_update(args, done){ var seneca = this, country = args.country; seneca.make(ENTITY_NS).save$(country, function(err, response) { if(err) return done(err); done(null, response); }); } function cmd_delete(args, done){ var seneca = this; var id = args.id; seneca.make$(ENTITY_NS).remove$(args.id, done); } return { name: plugin }; };
JavaScript
0
@@ -92,16 +92,44 @@ async'); +%0Avar http = require('http'); %0A%0Amodule @@ -588,170 +588,527 @@ -seneca.make(ENTITY_NS).list$(query, function(err, response) %7B%0A if(err)%7B%0A return done(err);%0A %7D else %7B%0A return done(null, response);%0A %7D +http.get(%22http://api.geonames.org/countryInfoJSON?formatted=true&lang=en&username=davidc&style=full%22, function(res) %7B%0A var countries = '';%0A res.setEncoding('utf8');%0A res.on(%22data%22, function(chunk) %7B%0A countries += chunk;%0A %7D);%0A res.on('end', function() %7B%0A countries = JSON.parse(countries);%0A countries = countries.geonames;%0A countries = _.sortBy(countries, 'countryName');%0A done(null, countries);%0A %7D);%0A %7D).on('error', function(e) %7B%0A done(null, %5B%5D); %0A
564768b953e9800faab835312b78c6b0321286c7
Remove postinstall command from commander too
packages/expo-module-scripts/bin/expo-module.js
packages/expo-module-scripts/bin/expo-module.js
#!/usr/bin/env node 'use strict'; const commander = require('commander'); const process = require('process'); commander // Common scripts .command('configure', `Generate common configuration files`) .command( 'typecheck', `Type check the source TypeScript without emitting JS and watch for file changes` ) .command('build', `Compile the source JS or TypeScript and watch for file changes`) .command('test', `Run unit tests with an interactive watcher`) .command('clean', `Removes compiled files`) // Lifecycle scripts .command('postinstall', `Scripts to run during the "postinstall" phase`) .command('prepare', `Scripts to run during the "prepare" phase`) .command('prepublishOnly', `Scripts to run during the "prepublishOnly" phase`) // Pass-through scripts .command('babel', `Runs Babel CLI with the given arguments`) .command('jest', `Runs Jest with the given arguments`) .command('tsc', `Runs tsc with the given arguments`) .parse(process.argv);
JavaScript
0
@@ -542,83 +542,8 @@ pts%0A - .command('postinstall', %60Scripts to run during the %22postinstall%22 phase%60)%0A .c
fa95c3d2e76cc234dd0e57d217d2287e08c715cd
Allow options on createSandbox + don't try/catch errors on afterAppStart callbacks.
lib/aura.js
lib/aura.js
define([ './base', './aura.extensions', './logger' ], function(base, ExtManager, Logger) { var _ = base.util._, noop = function() {}, freeze = Object.freeze || noop; /** * Aura constructor and main entry point * Loads mediator & widgets extensions by default. */ function Aura(config) { if (!(this instanceof Aura)) { return new Aura(config); } this.ref = _.uniqueId('aura_'); this.config = config || {}; this.extensions = new ExtManager(); this.core = Object.create(base); this.sandbox = Object.create(base); this.sandboxes = {}; this.logger = new Logger(this.ref); this.config.debug = this.config.debug || {}; var debug = this.config.debug; if (debug.enable) { if(debug.components){ debug.components = debug.components.split(' '); }else{ debug.components = []; } this.logger.enable(); this.use('aura/ext/debug'); } this.use('aura/ext/mediator'); this.config.widgets = (this.config.widgets || {}); this.config.widgets.sources = (this.config.widgets.sources || { "default" : "widgets" }); this.use('aura/ext/widgets'); return this; } /** * Creates a brand new sandbox, using the app sandbox object as a prototype * */ Aura.prototype.createSandbox = function(componentName) { var sandbox = Object.create(this.sandbox); sandbox.ref = _.uniqueId('sandbox-'); sandbox.logger = new Logger(sandbox.ref); this.sandboxes[sandbox.ref] = sandbox; var debug = this.config.debug; if(debug.enable && (debug.components.length === 0 || debug.components.indexOf(componentName) !== -1)){ sandbox.logger.enable(); } return sandbox; }; /** * Get a sandbox by its ref * */ Aura.prototype.getSandbox = function(ref) { return this.sandboxes[ref]; }; /** * Tells the app to init with the given extension. * * This method can only be called before the app is actually started. * * @param {String|Object|Function} ref the reference of the extension * @return {Aura} the Aura app object */ Aura.prototype.use = function(ref) { this.extensions.add({ ref: ref, context: this }); return this; }; /** * Adds a new source for widgets * * @param {String} name the name of the source * @param {String} baseUrl the base url for those widgets */ Aura.prototype.registerWidgetsSource = function(name, baseUrl) { if (this.config.widgets.sources[name]) { throw new Error("Widgets source '" + name + "' is already registered"); } this.config.widgets.sources[name] = baseUrl; return this; }; /** * Application start. * Bootstraps the extensions loading process * @return {Promise} a promise that resolves when the app is started */ Aura.prototype.start = function(options) { var app = this; if (app.started) { app.logger.error("Aura already started... !"); return app.extensions.initStatus; } app.logger.log("Starting Aura..."); app.startOptions = options || {}; app.started = true; app.extensions.onReady(function(exts) { // Then we call all the `afterAppStart` provided by the extensions base.util.each(exts, function(i, ext) { if (ext && typeof(ext.afterAppStart) === 'function') { try { ext.afterAppStart(app); } catch(e) { app.logger.error("Error on ", (ext.name || ext) , ".afterAppStart callback: (", e.message, ")", e); } } }); }); // If there was an error in the boot sequence we // reject every body an do some cleanup // TODO: Provide a better error message to the user. app.extensions.onFailure(function() { app.logger.error("Error initializing app...", app.config.name, arguments); app.stop(); }); // Finally... we return a promise that allows // to keep track of the loading process... // return app.extensions.init(); }; /** * Stops the application and unregister its loaded dependencies. * TODO: We need to do a little more cleanup here... * @return {void} */ Aura.prototype.stop = function() { this.started = false; // unregisterDeps(this.ref, Object.keys(allDeps.apps[env.appRef] || {})); }; return Aura; });
JavaScript
0
@@ -1375,16 +1375,25 @@ nentName +, options ) %7B%0A @@ -1741,24 +1741,62 @@ le();%0A %7D%0A + _.extend(sandbox, options %7C%7C %7B%7D);%0A return s @@ -3434,26 +3434,8 @@ ) %7B%0A - try %7B%0A @@ -3468,155 +3468,8 @@ p);%0A - %7D catch(e) %7B%0A app.logger.error(%22Error on %22, (ext.name %7C%7C ext) , %22.afterAppStart callback: (%22, e.message, %22)%22, e);%0A %7D%0A
6d8899a95e02d1cce3e65135c2edfffdee975038
fix another crash
lib/auth.js
lib/auth.js
/* SBHS-Timetable-Node: Countdown and timetable all at once (NodeJS app). * Copyright (C) 2014 James Ye, Simon Shields * * This file is part of SBHS-Timetable-Node. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ /* jshint -W098 */ var request = require('request'), config = require('../config.js'), variables = require('../variables.js'); var secret = config.secret, redirectURI = config.redirectURI, clientID = config.clientID, DEBUG = variables.DEBUG; function httpHeader(res, loc) { 'use strict'; res.writeHead(302, { 'Location': loc }); } module.exports = { 'getAuthCode': function(res, SESSID) { 'use strict'; httpHeader(res, 'https://student.sbhs.net.au/api/authorize?response_type=code&client_id='+encodeURIComponent(clientID) + '&redirect_uri='+encodeURIComponent(redirectURI) + '&scope=all-ro&state='+encodeURIComponent(SESSID) ); res.end(); }, 'getAuthToken': function(res, uri, cb, redir) { 'use strict'; if ('error' in uri.query) { console.warn('[auth] redir to /?denied'); httpHeader(res, '/?denied=true'); res.end(); return; } else if ('code' in uri.query) { var onData = function(err, resp, c) { console.log(c); var z; try { z = JSON.parse(c); } catch (e) { if (redir) { httpHeader(res, '/?loginFailed=true'); res.end(); } if (typeof cb === 'function') { cb(); } return; } var session = global.sessions[res.SESSID]; if (redir) { httpHeader(res, '/?loggedIn=true'); res.end(); } session.accessToken = z.access_token; session.refreshToken = z.refresh_token; session.accessTokenExpires = Date.now() + (1000 * 60 * 60); session.refreshTokenExpires = Date.now() + (1000 * 60 * 60 * 24 * 90); global.sessions[res.SESSID] = session; if (typeof cb === 'function') { cb(); } }; var req = request.post({ 'uri': 'https://student.sbhs.net.au/api/token', 'body': 'grant_type=authorization_code&code='+uri.query.code + '&redirect_uri='+encodeURIComponent(redirectURI) + '&client_id='+encodeURIComponent(clientID) + '&client_secret='+secret + '&state=' + encodeURIComponent(uri.query.state) + '\n', 'headers': { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' } }, onData); } }, 'refreshAuthToken': function(refreshToken, sessID, cb) { 'use strict'; var onData = function (err, res, c) { if (err) { cb(); return; } var z = JSON.parse(c); var session = global.sessions[sessID]; session.accessToken = z.access_token; session.accessTokenExpires = Date.now() + (1000 * 60 * 60); global.sessions[sessID] = session; if (typeof cb === 'function') { cb(); } }; var req = request.post({ 'uri': 'https://student.sbhs.net.au/api/token', 'headers': { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' }, 'body':'grant_type=refresh_token&refresh_token=' + refreshToken + '&redirect_uri='+encodeURIComponent(redirectURI) + '&client_id='+encodeURIComponent(clientID) + '&client_secret='+secret }, onData); }, 'refreshTokenIfNeeded': function(sessID, cb) { 'use strict'; var session = global.sessions[sessID]; if (Date.now() > session.accessTokenExpires) { module.exports.refreshAuthToken(session.refreshToken, sessID, cb); } else { if (DEBUG) { console.log('[auth_debug] ' + Date.now() + ' < ' + session.accessTokenExpires); } if (typeof cb === 'function') { cb(); } } } };
JavaScript
0.000018
@@ -3050,24 +3050,59 @@ %09if (err) %7B%0A +%09%09%09%09if (typeof cb === 'function')%0A%09 %09%09%09%09cb();%0A%09%09 @@ -3116,16 +3116,26 @@ n;%0A%09%09%09%7D%0A +%09%09%09try %7B%0A%09 %09%09%09var z @@ -3152,16 +3152,90 @@ rse(c);%0A +%09%09%09%7D catch (e) %7B%0A%09%09%09%09if (typeof cb === 'function') cb();%0A%09%09%09%09return;%0A%09%09%09%7D%0A %09%09%09var s
746d318364bc8146cf53151f04af74165788b35c
update file /lib/auth.js
lib/auth.js
lib/auth.js
'use strict'; var express = require('express'); var bodyParser = require('body-parser'); var cors = require('cors'); var queryString = require('querystring'); var request = require('request'); function auth() { var router = express.Router(); router.all('/init', function(req, res) { var params = req.body; // params.userId params.password if (params && params.idToken) { console.log('Checking credentials for user ' + params.idToken); initSession(idToken, function(err, result){ if (err) { console.log('Invalid credentials for user ' + params.idToken); res.status(400); res.json({message: 'Invalid credentials'}); return; } else { res.json({ status: 'ok', userId: params.idToken, sessionToken: params.idToken + '_sessiontoken', authResponse: result }); return; } }); } else { res.status(400); res.json({message: 'No Token Provided'}); } }); /** * Validate the user's session info with Google, and create a session object. * This will also create a account object if necessary. * * @param {String} idToken an idToken provided by an Android Client (see : https://developers.google.com/identity/sign-in/android/backend-auth) * @param {Callback} nodeCallback a node callback */ function initSession(idToken, nodeCallback) { //validate with google var options = { url: 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + querystring.escape(idToken), method: 'GET' }; request(options, handleGoogleResponse(idToken, nodeCallback)).end(); } /** * * This callback consumes Google's response, and performs the appropriate * actions on the session. (Set session optionally creating the account). * * @param {type} idToken * @param {type} nodeCallback * @returns session Data on callback if successful, error on callback otherwise */ function handleGoogleResponse(sessionToken, authResponse, nodeCallback) { return function (error, response, body) { //the whole response has been recieved, so we just print it out here if (error) { nodeCallback(e); } else { var resObject = JSON.parse(body); checkAccount(resObject, sessionToken, nodeCallback); } }; } /** * Creates a user if one does not exist * * @param {Sting} Google user Token response (see : https://developers.google.com/identity/sign-in/android/backend-auth#calling-the-tokeninfo-endpoint) * @param {Sting} sessionToken * @param {NodeCallback} nodeCallback * @returns session Data on callback if successful, error on callback otherwise */ function checkAccount(googleUserToken, sessionToken, nodeCallback) { console.log('checkAccountAndCreateSession'); var handleResults = function (error, responseData) { console.log('checkAccountAndCreateSession_callback'); if (error) { return nodeCallback(error, null); } else { if (!responseData || responseData.count === 0) { //no account, must create. createAccount(sessionToken, authResponse, nodeCallback); } else if (responseData.count > 1) { return nodeCallback("error : Too many accounts returned", null); } else { //account exists, set session and return it. setSession(sessionToken, responseData.list[0].fields, nodeCallback); } } }; mbaasApi.db({ "act": "list", "type": 'account', "eq": {"id": googleUserToken.sub}, }, handleResults); } /** * Creates an account and sets the session to that account. * @param {Sting} sessionToken * @param {Object} authResponse * @param {NodeCallback} nodeCallback * @returns session Data on callback if successful, error on callback otherwise */ function createAccountAndSetSession(sessionToken, authResponse, nodeCallback) { authResponse.authToken = ''; mbaasApi.db({ "act": "create", "type": 'account', "fields": [authResponse] }, function (error, data) { console.log('createAccountAndSetSession_cb'); if (error) { return nodeCallback(error); } else { setSession(sessionToken, authResponse, nodeCallback); } }); } return router; } module.exports = auth;
JavaScript
0.000002
@@ -3434,34 +3434,23 @@ unt( -sessionToken, authResponse +googleUserToken , no
44d5a5947376dbfd6226944508f2e8e49fcca225
remove replay retry method
lib/base.js
lib/base.js
const MwPool = require('./mwpool') const assign = require('lodash').assign const middleware = require('./middleware') const Emitter = require('events').EventEmitter module.exports = Base function Base(opts) { Emitter.call(this) this.replays = [] this.opts = opts || {} this.mw = new MwPool } Base.prototype = Object.create(Emitter.prototype) Base.prototype.target = Base.prototype.forward = Base.prototype.forwardTo = function (url, opts) { this.opts.target = url assign(this.opts, opts) return this } Base.prototype.balance = function (urls) { if (Array.isArray(urls)) { this.opts.balance = urls } return this } Base.prototype.options = function (opts) { assign(this.opts, opts) return this } Base.prototype.replay = Base.prototype.replayTo = function (url, opts) { if (typeof url === 'string') { url = { target: url } } this.replays.push(assign({}, url, opts)) return this } Base.prototype.sequential = Base.prototype.replayAfterForward = function (filter) { this.bufferBody(filter) this.opts.replayAfterForward = true return this } Base.prototype.replaySequentially = function (filter) { this.bufferBody(filter) this.opts.replaySequentially = true return this } Base.prototype.retry = function (opts, filter) { this.bufferBody(filter) this.opts.retry = opts return this } Base.prototype.replayRetry = function (opts, filter) { this.bufferBody(filter) this.opts.replayRetry = opts return this } Base.prototype.useFor = function () { this.mw.use.apply(this.mw, arguments) return this } Base.prototype.use = Base.prototype.useIncoming = function () { this.useFor('global', arguments) return this } Base.prototype.useForward = function () { this.useFor('forward', arguments) return this } Base.prototype.useReplay = function () { this.useFor('replay', arguments) return this } Base.prototype.useOutgoing = Base.prototype.useResponse = function () { this.useFor('response', arguments) if (!this._interceptResponse) { this._interceptResponse = true this.use(middleware.responseBody(function (req, res, next) { this.mw.run('response', req, res, next) }.bind(this))) } return this } Base.prototype.bufferBody = Base.prototype.interceptBody = function (filter) { this.use(middleware.requestBody(function (res, res, next) { next() }, filter)) return this } Base.prototype.headers = function (headers) { this.use(middleware.headers(headers)) return this } Base.prototype.timeout = function (ms) { this.opts.timeout = ms return this }
JavaScript
0.000002
@@ -1367,137 +1367,8 @@ %0A%7D%0A%0A -Base.prototype.replayRetry = function (opts, filter) %7B%0A this.bufferBody(filter)%0A this.opts.replayRetry = opts%0A return this%0A%7D%0A%0A Base
f4df561ad3985c4372a41fdb3c2fc1cae7dfff37
handle path without trailing /.
lib/blog.js
lib/blog.js
/** * Copyright 2015, Mapacode Inc. */ 'use strict'; var async = require('async'); var marked = require('marked'); var fs = require('fs'); module.exports = function (path) { var _posts = require(path + '/posts'); var _keyed = {}; _posts.forEach (function (item) { _keyed[item.md] = item; }); return { name: 'blog', read: function (req, resource, params, config, callback) { var md; if(params && params.md) { if (typeof params.md === 'string' ) { md = [params.md]; } else { md = params.md; } async.map ( md, function (item, cb) { fs.readFile(path+item, function (err, data) { if(err) { cb(err, {key: item, value: null}); } else { cb(err, {key: item, value: marked(data.toString())}); } }); }, function (err, results) { var res = {}; var last; if(err) { // 只保留最後一個有問題的。因為在其前面的都是空的。 last = results.pop(); res[last.key] = last.value; } else { results.forEach(function(item) { _keyed[item.key].content = item.value; res[item.key] = _keyed[item.key]; }); } callback(err, res); } ); } else { setTimeout(function () { callback(null, JSON.parse(JSON.stringify(_posts))); }, 10); } } }; };
JavaScript
0
@@ -780,16 +780,20 @@ le(path+ +'/'+ item, fu
b1a508f5ec49b2815108f9335b0a4ee4d0ccf3c1
fix command line usage
lib/core.js
lib/core.js
var transforms = require('./transforms'); var split = require('split'); var yargs = require('yargs'); // TODO: // 1. Issues // 2. Repo List // 3. PRs // 4. Checklist // 5. --data-type=open,oldest module.exports.run = function() { var args, subcommand, data; args = yargs .usage("Usage: $0 <subcommand> <data-type> [--data-typeg=<data-type>[,<data-type>]]") .example("$0 issues open", "list the open issues, less PRs") .example("$0 issues oldest", "list the oldest issue date") .example("$0 tags list", "list all tags for a repo") .example("$0 tags newest", "show the highest semver tag for a repo") .example("$0 repos list", "list all repos for a user") .demand(2) .check(function(args) { subcommand = args['_'][0]; data = args['_'][1]; if( !transforms[subcommand] ){ throw new Error("unsupported subcommand"); } if( !transforms[subcommand].supported[data] ){ throw new Error("unsupported data type"); } }) .argv; process.stdin .pipe(split()) .pipe(new transforms[subcommand]( data )) .pipe(process.stdout); };
JavaScript
0.000759
@@ -107,70 +107,8 @@ TODO -:%0A// 1. Issues%0A// 2. Repo List%0A// 3. PRs%0A// 4. Checklist%0A// 5. --d @@ -267,17 +267,16 @@ ata-type -g =%3Cdata-t
a30542b39ce96669d1c952771ed123ca354ca48a
fix import for non es6
s3router.js
s3router.js
import s3Router from 'react-s3-uploader/s3router' export default s3Router
JavaScript
0.000001
@@ -1,25 +1,29 @@ -import s3Router from +module.exports = require( 'rea @@ -50,29 +50,5 @@ ter' -%0Aexport default s3Router%0A +)
d4836ccad049c5c2fb0424a7785d85618a3315b6
fix wordings
lib/diff.js
lib/diff.js
/** * Diff two list in O(N). * @param {Array} oldList - Original List * @param {Array} newList - List After certain insertions, removes, or moves * @return {Object} - {moves: <Array>} * - moves is a list of actions that telling how to removes and inserts */ function diff(oldList, newList, key) { if (!key) throw new Error("List's items must have keys!") var oldMap = makeMap(oldList, key) var newMap = makeMap(newList, key) var inserts = [] var removes = [] var moves = [] // a simulate list to manipulate var simulateList = oldList.slice(0) var i = 0; // first pass remove all items are not in new map while(i < simulateList.length) { var item = simulateList[i] var itemKey = getItemKey(item, key) if (!newMap.hasOwnProperty(itemKey)) { remove(i) simulateList.splice(i, 1) } else { i++; } } // i is cursor pointing to a item in new list // j is cursor pointing to a item in simulateList var j = i = 0 while(i < newList.length) { var item = newList[i] var itemKey = getItemKey(item, key) var simulateItem = simulateList[j] var simulateItemKey = getItemKey(simulateItem, key) if (itemKey === simulateItemKey) { j++ } else { // new item, just inesrt it if (!oldMap.hasOwnProperty(itemKey)) { insert(i, item) } else { // if remove current simulateItem make item in right place // then just remove it var nextItemKey = getItemKey(simulateList[j + 1], key); if (nextItemKey === itemKey) { remove(i) simulateList.splice(j, 1) j++ // after removing, current j is right, just jump to next one } else { // else insert item insert(i, item) } } } i++ } function remove(index) { var move = {index: index, type: 0}; moves.push(move) } function insert(index, item) { var move = {index: index, item: item, type: 1} moves.push(move) } return {moves: moves} } /** * Convert list to key-item map object. * @param {Array} list * @param {String|Function} key */ function makeMap(list, key) { var map = {} for(var i = 0, len = list.length; i < len; i++) { var item = list[i] var itemKey = getItemKey(item, key); map[itemKey] = i; } return map } function getItemKey(item, key) { if (!item) return void 666 return typeof key === "string" ? item[key] : key(item) } exports.makeMap = makeMap // exports for test exports.diff = diff
JavaScript
0.000027
@@ -261,17 +261,16 @@ o remove -s and ins @@ -272,17 +272,16 @@ d insert -s %0D%0A */%0D%0Af
82f0936c557a7720e920512d679cdc57d1dde8fe
修复路径转为 base64 后处理错误的问题 question/96767
packages/uni-template-compiler/lib/asset-url.js
packages/uni-template-compiler/lib/asset-url.js
const url = require('url') const transformAssetUrls = { audio: 'src', video: ['src', 'poster'], img: 'src', image: 'src', 'cover-image': 'src', // h5 'v-uni-audio': 'src', 'v-uni-video': ['src', 'poster'], 'v-uni-image': 'src', 'v-uni-cover-image': 'src', // nvue 'u-image': 'src', 'u-video': ['src', 'poster'] } function urlToRequire (url) { const returnValue = `"${url}"` // same logic as in transform-require.js const firstChar = url.charAt(0) if (firstChar === '.' || firstChar === '~' || firstChar === '@') { if (firstChar === '~') { const secondChar = url.charAt(1) url = url.slice(secondChar === '/' ? 2 : 1) } const uriParts = parseUriParts(url) if (!uriParts.hash) { // fixed by xxxxxx (v3 template中需要加/) return `require("${url}")` } else { // fixed by xxxxxx (v3 template中需要加/) // support uri fragment case by excluding it from // the require and instead appending it as string; // assuming that the path part is sufficient according to // the above caseing(t.i. no protocol-auth-host parts expected) return `require("${uriParts.path}") + "${uriParts.hash}"` } } return returnValue } /** * vuejs/component-compiler-utils#22 Support uri fragment in transformed require * @param urlString an url as a string */ function parseUriParts (urlString) { // initialize return value /* eslint-disable node/no-deprecated-api */ const returnValue = url.parse('') if (urlString) { // A TypeError is thrown if urlString is not a string // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost if (typeof urlString === 'string') { // check is an uri /* eslint-disable node/no-deprecated-api */ return url.parse(urlString) // take apart the uri } } return returnValue } function rewrite (attr, name, options) { if (attr.name === name) { const value = attr.value // only transform static URLs if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') { if (!options.h5) { // 非 H5 平台 attr.value = attr.value .replace('"@/', '"/') .replace('"~@/', '"/') } // v3,h5 const needRequire = options.service || options.view || options.h5 if (needRequire) { attr.value = urlToRequire(attr.value.slice(1, -1)) if ( options.h5 && options.publicPath === './' && attr.value.startsWith('require("') ) { // require // h5 且 publicPath 为 ./ (仅生产模式可能为./) attr.value = `(${attr.value}).substr(1)` } } return true } } return false } module.exports = { postTransformNode: (node, options) => { if (!node.attrs) { return } const attributes = transformAssetUrls[node.tag] if (!attributes) { return } if (typeof attributes === 'string') { if (node.attrs.some(attr => rewrite(attr, attributes, options))) { if (options.service || options.view) { node.hasBindings = true } } } else if (Array.isArray(attributes)) { attributes.forEach(item => { if (node.attrs.some(attr => rewrite(attr, item, options))) { if (options.service || options.view) { node.hasBindings = true } } }) } } }
JavaScript
0.000009
@@ -2699,16 +2699,25 @@ e%7D). -substr(1 +replace(/%5E%5C%5C./,'' )%60%0D%0A @@ -3499,9 +3499,10 @@ %0D%0A %7D%0D%0A%7D +%0D %0A
a76ce660588cd9db43f09488f7b0e1af49fd5843
Make sentence make more sense
bin/boilerplates/app.js
bin/boilerplates/app.js
/** * app.js * * Use `app.js` to run your app in environments where `sails lift` is not available. * To start the server, run: `node app.js`. * * The same command-line arguments as sails lift are also supported, * e.g.: `node app.js --silent --port=80 --prod` */ // Ensure a "sails" can be located: var sails; try { sails = require('sails'); } catch (e) { console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.'); console.error('You might run `npm install sails` to install sails in this directory.'); console.error(''); console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.'); console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,'); console.error('but if it doesn\'t, the app will run with the global sails instead!'); return; } // Start server sails.lift(require('optimist').argv);
JavaScript
1
@@ -524,17 +524,19 @@ or(' -You might +To do that, run @@ -559,44 +559,8 @@ ils%60 - to install sails in this directory. ');%0A