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
4df51546b2bd29a2dd3a5b11eeca80a157f6ffb1
Remove command log in ebook convert
lib/generate/ebook/index.js
lib/generate/ebook/index.js
var util = require("util"); var path = require("path"); var Q = require("q"); var _ = require("lodash"); var exec = require('child_process').exec; var fs = require("fs"); var parse = require("../../parse"); var BaseGenerator = require("../page"); /* * This generator inherits from the single page generator * and convert the page output to ebook */ var Generator = function() { BaseGenerator.apply(this, arguments); // Options for eBook generation this.options = _.defaults(this.options, { extension: "epub" }); }; util.inherits(Generator, BaseGenerator); Generator.prototype.finish = function() { var that = this; return BaseGenerator.prototype.finish.apply(this) .then(function() { var d = Q.defer(); if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) { that.options.cover = path.join(that.options.output, "cover.jpg"); } var _options = { "--cover": that.options.cover }; var command = [ "ebook-convert", path.join(that.options.output, "index.html"), path.join(that.options.output, "index."+that.options.extension), _.chain(_options) .map(function(value, key) { if (value == null) return null; return key+"="+value; }) .compact() .value() .join(" ") ].join(" "); console.log(command); exec(command, function (error, stdout, stderr) { if (error) { if (error.code == 127) { error.message = "Need to install ebook-convert from Calibre"; } else { error.message = error.message + " "+stdout; } return d.reject(error); } d.resolve(); }); return d.promise; }); }; module.exports = Generator;
JavaScript
0.000001
@@ -1468,39 +1468,8 @@ );%0A%0A - console.log(command);%0A%0A
d303af1e3023b3da09a4359bdc347e01e18469a8
remove the demo button when clicked
src/coming-soon/demo/index.js
src/coming-soon/demo/index.js
import '../../polyfill' import $ from 'jquery' import co from 'co' import SamplingMaster from '../../sampling-master' import readBlob from '../../read-blob' import ctx from 'audio-context' import Compiler from 'bms/compiler' import Timing from 'bms/timing' import Notes from 'bms/notes' export function main(element) { function handler() { alert('Please drag a BMS file along with ALL samples into this page!') return false } $(element).text('Technical Demo').on('click', handler) $('body') .on('dragover', () => false) .on('drop', e => { $(element).off('click', handler) let dndLoader = new DndLoader(e.originalEvent.dataTransfer.files) go(dndLoader, element) return false }) } class DndLoader { constructor(files) { this._files = [].slice.call(files) console.log(this._files) } file(name) { for (let file of this._files) { if (file.name.toLowerCase() === name.toLowerCase()) { return Promise.resolve(file) } } return Promise.reject(new Error('unable to find ' + name)) } get fileList() { return Promise.resolve(this._files.map(f => f.name)) } } function go(loader, element) { let master = new SamplingMaster(ctx) co(function*() { log('Loading file list') let list = yield loader.fileList let bmsFile = list.filter(f => f.match(/\.bm.$/i))[0] log('Loading ' + bmsFile) let bms = yield loader.file(bmsFile) let text = yield readBlob(bms).as('text') let chart = Compiler.compile(text).chart var timing = Timing.fromBMSChart(chart) var notes = Notes.fromBMSChart(chart) log('Loading samples') var samples = yield loadSamples(notes, chart) log('Click to play!') $(element).on('click', function() { var num = 0 master.unmute() for (let note of notes.all()) { setTimeout(() => { let sample = samples[note.keysound] if (!sample) { console.log('warn: unknown sample ' + note.keysound) return } let span = document.createElement('span') let c = num++ span.style.fontSize = '1vw' span.style.textAlign = 'center' span.style.display = 'block' span.style.position = 'absolute' span.style.left = (c % 40) * 2.5 + '%' span.style.top = (~~(c / 40) % 10) * 3 + 'ex' span.innerHTML = '[' + note.keysound + '] ' document.body.appendChild(span) let instance = sample.play() instance.onstop = function() { document.body.removeChild(span) } }, timing.beatToSeconds(note.beat) * 1000) } return false }) }).done() function log(t) { element.textContent = t } function loadSamples(notes, chart) { var samples = {} var promises = [] let completed = 0 for (let note of notes.all()) { let keysound = note.keysound if (!(keysound in samples)) { samples[keysound] = null promises.push( loadKeysound(chart.headers.get('wav' + keysound)) .then(blob => master.sample(blob)) .then(sample => samples[keysound] = sample) .catch(e => console.error('Unable to load ' + keysound + ': ' + e)) .tap(() => log('[loaded ' + (++completed) + '/' + promises.length + ' samples]')) ) } } return Promise.all(promises).then(() => samples) } function loadKeysound(name) { if (typeof name !== 'string') return Promise.reject(new Error('Empty name')) return loader.file(name) .catch(() => loader.file(name.replace(/\.\w+$/, '.ogg'))) .catch(() => loader.file(name.replace(/\.\w+$/, '.mp3'))) .catch(() => loader.file(name.replace(/\.\w+$/, '.wav'))) } }
JavaScript
0.000001
@@ -1742,24 +1742,50 @@ unction() %7B%0A + $(element).remove()%0A var nu
b7f6ed98736b48aedc47cac87f585538792e7a2c
Add gravity.
src/main.js
src/main.js
window.addEventListener('load', main); function initialWorld(width, height) { var sheet = new SpriteSheet(document.getElementById('pasi'), 4); return { keys: {left: false, right: false}, gamma: 0, width: width, height: height, g: 1, pasi: new Pasi({ spriteSheet: sheet, x: width / 2, y: height - sheet.spriteHeight, nLeapTicks: 4, speed: 4, jumpSpeed: 12, gammaFactor: 1 }), platformGenerator: new PlatformGenerator(width, width / 2, height) }; } function main() { var config = { width: 180, height: 240, fps: 20, g: 1 }; startGame(document.getElementById('mainCanvas'), config, draw, update, [ { name: 'keydown', fn: keydown }, { name: 'keyup', fn: keyup }, { name: 'deviceorientation', fn: orientation } ], [], initialWorld(config.width, config.height)); } function draw(ctx, world) { ctx.clearRect(0, 0, world.width, world.height); world.platformGenerator.platforms.forEach(function(platform) { platform.draw(ctx); }); world.pasi.draw(ctx); } function update(world) { if (world.keys.right) { world.pasi.vx = world.pasi.speed; } else if (world.keys.left) { world.pasi.vx = -world.pasi.speed; } else { world.pasi.vx = world.pasi.gammaFactor * world.gamma; } world.pasi.x += world.pasi.vx; world.pasi.y += world.pasi.vy; world.pasi.wrap(world.width); world.pasi.update(); world.platformGenerator.generatePlatforms(world.height, 0); } function keydown(e, world) { if (e.keyCode === 39) { world.keys.right = true; } else if (e.keyCode === 37) { world.keys.left = true; } } function keyup(e, world) { if (e.keyCode === 39) { world.keys.right = false; } else if (e.keyCode === 37) { world.keys.left = false; } } function orientation(e, world) { world.gamma = e.gamma; }
JavaScript
0.000875
@@ -698,30 +698,16 @@ fps: 20 -,%0A g: 1 %0A %7D;%0A @@ -1538,16 +1538,46 @@ pasi.vy; +%0A world.pasi.vy += world.g; %0A%0A wo
04be1b40eb58ae4026a81814aefcbd1dac0863f3
remove image save from memes create
routes/api/meme.js
routes/api/meme.js
var db = require('../../models'); module.exports.addMeme = function(req, res) { //TODO create meme // res.sendStatus(503) db.meme_texts.create({text:req.body.top}).then(function(top_text) { db.meme_texts.create({text:req.body.bottom}).then(function(bottom_text) { db.images.create({filename:req.body.image}).then(function(images) { db.memes.create({image_id:images.id,top_text_id:top_text.id,bottom_text_id:bottom_text.id}).then(function(memes) { memes.setImages(images); memes.setTopText(top_text); memes.setBottomText(bottom_text); res.json({memes: memes}); }).catch(function(err) { console.log("meme fail"); res.status(400).send(err); }); }).catch(function(err) { console.log("image fail"); res.status(400).send(err); }); }).catch(function(err) { console.log("bottom text fail"); res.status(400).send(err); }); }).catch(function(err) { console.log("top text fail"); res.status(400).send(err); }); }; module.exports.getAllMemes = function(req, res) { db.memes.findAll().then(function(memes) { res.json({memes: memes}); }).catch(function(err) { res.status(400).send(err); }); };
JavaScript
0
@@ -294,50 +294,28 @@ -db.images.create(%7Bfilename:req.body.image%7D + db.memes.create( ).th @@ -330,18 +330,18 @@ ion( -imag +mem es) %7B%0A +%0A @@ -356,122 +356,164 @@ -db.memes.create(%7Bimage_id:images.id,top_text_id:top_text.id,bottom_text_id:bottom_text.id%7D).then(function(memes) %7B + // the image here should be the id of an already existing/ newly uploaded image,%0A // i.e. this image id should already be saved in db %0A @@ -549,14 +549,22 @@ ges( +req.body. image -s );%0A @@ -836,32 +836,32 @@ 400).send(err);%0A + @@ -868,147 +868,8 @@ %7D);%0A - %7D).catch(function(err) %7B%0A console.log(%22image fail%22);%0A res.status(400).send(err);%0A %7D);%0A
451f913e7f01f5d28b8dfb215ea550dc76aa2620
add a hard fetch functino to the cacheables
src/main.js
src/main.js
/* * ncksllvn * a bunch of cool classes for Backbone that I kept finding myself using. * just include this file after Backbone */ ~function(){ Backbone.HistoryWith404 = (function(){ var routers = []; HistoryWith404 = Backbone.History.extend({ loadUrl: (function(loadUrl){ return function(){ var match = loadUrl.apply(this, arguments), fragment = this.fragment; if ( !match ){ _.chain(routers).compact().all(function(router){ router && router.trigger('statusCode:404', fragment); }); } return match; } })( Backbone.History.prototype.loadUrl ) }); Backbone.RouterWith404 = Backbone.Router.extend({ constructor: (function(superConstructor){ return function(){ superConstructor.apply(this, arguments); routers.push(this); }; })(Backbone.Router) }); return HistoryWith404; })(); Backbone.Cacheable = Backbone.Cacheable || {}; Backbone.Cacheable.cachedFetch = function(fetch){ return function(options){ var _this = this, options = options || {}, callback; if ( !this.cache ){ this.cache = fetch.call( this, { success: function(){ _this.cache.outcome = 'success', _this.cache.callbackArgs = arguments; if (options.success) options.success.apply(window, arguments); }, error: function(){ _this.cache.outcome = 'error', _this.cache.callbackArgs = arguments; if (options.error) options.error.apply(window, arguments); } }); } else{ callback = options[ this.cache.outcome ]; if ( callback ) callback.apply(window, this.cache.callbackArgs); } return this.cache; }; }; _.extend( Backbone.Cacheable, { Collection: Backbone.Collection.extend({ fetch: Backbone.Cacheable.cachedFetch( Backbone.Collection.prototype.fetch ) }), Model: Backbone.Model.extend({ fetch: Backbone.Cacheable.cachedFetch( Backbone.Model.prototype.fetch ) }) }); }();
JavaScript
0
@@ -426,17 +426,17 @@ guments) -, +; %0A @@ -448,19 +448,19 @@ - +var fragmen @@ -1417,15 +1417,36 @@ this -, %0A +;%0A var callback;%0A @@ -1480,34 +1480,8 @@ %7C %7B%7D -,%0A callback ;%0A @@ -2388,24 +2388,117 @@ %7D;%0A %0A + function hardFetch()%7B%0A delete this.cache;%0A return this.fetch();%0A %7D%0A %0A _.extend @@ -2659,32 +2659,66 @@ rototype.fetch ) +,%0A hardFetch: hardFetch %0A %7D),%0A @@ -2845,16 +2845,50 @@ .fetch ) +,%0A hardFetch: hardFetch %0A
40414bf42c88fea14cf8973011bb53ea8e951867
Update main.js
src/main.js
src/main.js
var MediumEditorMultiPlaceholders = MediumEditor.Extension.extend({ name: 'multi_placeholder', init: function() { this.placeholderElements = []; this.initPlaceholders(this.placeholders, this.placeholderElements); this.watchChanges(); }, initPlaceholders: function (placeholders, elements) { this.getEditorElements().forEach(function (editor) { this.placeholders.map(function(placeholder) { // Create the placeholder element var el = document.createElement(placeholder.tag); el.appendChild(document.createElement('br')); el.setAttribute('data-placeholder', placeholder.text); elements.push(el); // Append it to Medium Editor element editor.appendChild(el); this.updatePlaceholder(el); }, this); }, this); }, destroy: function () { this.getEditorElements().forEach(function (editor) { editor.querySelectorAll('[data-placeholder]').map(function(el) { el.removeAttribute('data-placeholder'); }, this); }, this); }, showPlaceholder: function (el) { if (el) { el.classList.add('medium-editor-placeholder'); } }, hidePlaceholder: function (el) { if (el) { el.classList.remove('medium-editor-placeholder'); } }, updatePlaceholder: function (el) { // if one of these element ('img, blockquote, ul, ol') are found inside the given element, we won't display the placeholder if (el.textContent === '') { return this.showPlaceholder(el); } this.hidePlaceholder(el); }, updateAllPlaceholders: function() { this.placeholderElements.map(function(el){ this.updatePlaceholder(el); }, this); }, watchChanges: function() { this.subscribe('editableInput', this.updateAllPlaceholders.bind(this)); this.subscribe('externalInteraction', this.updateAllPlaceholders.bind(this)); } });
JavaScript
0.000001
@@ -1388,138 +1388,8 @@ ) %7B%0A - // if one of these element ('img, blockquote, ul, ol') are found inside the given element, we won't display the placeholder%0A
981a6de910883594fb96a0fc3a13362ef615ba42
Allow downloading of hidden apps
routes/download.js
routes/download.js
var express = require('express'); var mongoose = require('mongoose'); var router = express.Router(); const Application = mongoose.model('Application'); const Version = mongoose.model('Version'); const Dependency = mongoose.model('Dependency'); const DependencyVersion = mongoose.model('DependencyVersion'); const escapeStringRegexp = require('escape-string-regexp'); var queryPromise = function (params) { var query = { hidden: false, nightly: false, released: { $ne : false } }; if (params.filename) { query.filename = filenameToInsensitive(params.filename); } var promise = Promise.resolve(query); if (params.app) { promise = promise .then(result => Application.findOne({ id: params.app }, '_id')) .then(app => { query.app = app._id; return query; }); } if (params.deptype && params.depver) { promise = promise .then(r => Dependency.findOne({name: params.deptype }, '_id')) .then(dep => DependencyVersion.findOne({ type: dep._id, version: params.depver }, '_id')) .then(function(depVer) { query.compatible = depVer._id; return query; }); } return promise; }; var downloadFile = function(req, res, next) { return queryPromise(req.params) .then(query => Version.findOne(query, 'apk filename downloads').sort({ sortingCode : -1})) .then(version => { var options = { root: __dirname.replace("routes", ""), headers: { 'Content-Type': 'application/vnd.android.package-archive', 'Content-Disposition': 'attachment; filename="' + version.filename + '"' } }; res.sendFile(version.apk, options); return version; }) .then(version => { version.downloads++; version.save((err, result) => { if (err) console.error("Failed updating download count for " + version); }); return version; }) .catch(catcher(req, res)); }; var getMeta = function(req, res, next) { return queryPromise(req.params) .then(query => Version.findOne(query, 'name compatible') .populate({ path: 'compatible', select: 'version type', options: { sort: {version: -1} }, populate: { path: 'type', select: 'name' } }) .sort({ sortingCode : -1}) ) .then((version) => { var response = { version: version.name, compatible: {} }; version.compatible.forEach((v) => { if (!response.compatible[v.type.name]) { response.compatible[v.type.name] = []; } response.compatible[v.type.name].push(v.version) }); res.set('Content-Type', 'application/json'); res.send(response); /* res.send();*/ return version; }) .catch(catcher(req, res)); }; var catcher = function(req, res) { return (err) => { console.error("Failed on path: " + req.path + " with err: " + err); res.sendStatus(404); return value; } }; var filenameToInsensitive = function(filename) { return new RegExp("^" + escapeStringRegexp(filename) + "$", "i"); }; router.get('/', function(req, res, next) { var query = {hidden: false, nightly: false}; if (req.session.admin) { query = {nightly: false}; } Application.find({hidden: {$ne: true}}) .select("_id") .then(apps => { query.app = { $in : apps }; return Version.find(query) .select('name filename app changelog') .sort({_id: -1}) .populate({path: 'app', select: 'id title hidden' }) .limit(10); }) .then(apps => { return res.render('download', {versions: apps}); }) .catch(next); }); router.get('/:filename', downloadFile); router.get('/:filename/meta', getMeta); router.get('/:app/latest', downloadFile); router.get('/:app/:filename', downloadFile); router.get('/:app/latest/meta', getMeta); router.get('/:app/:filename/meta', getMeta); router.get('/:deptype/:depver/:filename', downloadFile); router.get('/:deptype/:depver/:filename/meta', getMeta); router.get('/:app/:deptype/:depver/latest', downloadFile); router.get('/:app/:deptype/:depver/:filename', downloadFile); router.get('/:app/:deptype/:depver/latest/meta', getMeta); router.get('/:app/:deptype/:depver/:filename/meta', getMeta); module.exports = router;
JavaScript
0
@@ -418,23 +418,8 @@ = %7B - hidden: false, nig @@ -2728,16 +2728,44 @@ + err);%0A +%09%09console.error(err.stack);%0A %09%09res.se
7919c64ee0422f1655cc0b013e92a475406e2485
Add currentUser to public api
server/public/scripts/services/auth.factory.js
server/public/scripts/services/auth.factory.js
app.factory('AuthFactory', ['$http', '$firebaseAuth', function($http, $firebaseAuth){ console.log('AuthFactory running'); var auth = $firebaseAuth(); var currentUser; var loggedIn = false; var userStatus = {}; function logIn(userType) { return auth.$signInWithPopup("google").then(function(firebaseUser) { // console.log("Firebase Authenticated as: ", firebaseUser.user.displayName); // console.log('firebaseUser.user.email: ', firebaseUser.user.email); currentUser = firebaseUser.user; // console.log('currentUser: ', currentUser); // console.log('firebaseUser: ', firebaseUser); console.log('USER TYPE:', userType); if(currentUser) { getUser(currentUser, userType); } }); } function getUser(currentUser, userType){ currentUser.getToken().then(function(idToken){ console.log('ID TOKEN:', idToken); $http({ method: 'GET', url: '/users.route', headers: { id_token: idToken, type: userType } }) .then(function(response) { // console.log(response.data); userStatus.userType = response.data.userType; console.log(userStatus); }); userStatus.isLoggedIn = true; // console.log(userStatus); }); } auth.$onAuthStateChanged(function(firebaseUser){ // firebaseUser will be null if not logged in currentUser = firebaseUser; console.log("CURRENT USER", currentUser); if(currentUser) { getUser(currentUser); } else { userStatus.isLoggedIn = false; } console.log('User is logged in:', userStatus.isLoggedIn); }); function logOut() { return auth.$signOut().then(function() { currentUser = undefined; userStatus.isLoggedIn = false; userStatus.userType = "None"; console.log('logged out'); console.log('currentUser: ', currentUser); }); } // TODO: Have Oliver explain what these variables are var publicApi = { auth: auth, userStatus: userStatus, logIn: function(userType) { return logIn(userType); }, logOut: function() { return logOut(); } }; return publicApi; }]);
JavaScript
0.000001
@@ -1169,16 +1169,68 @@ erType;%0A + userStatus.newUser = response.data.newUser;%0A @@ -2088,16 +2088,46 @@ Status,%0A + currentUser: currentUser,%0A logI
f95a4c97f6902f11f89b1f772fb74bbab3ffcfe3
use utils.find() (#482)
lib/graph-service-worker.js
lib/graph-service-worker.js
var debug = require('debug')('bankai.graph-service-worker') var findup = require('@choojs/findup') var assert = require('assert') var path = require('path') var browserify = require('browserify') var watchify = require('watchify') var tinyify = require('tinyify') var brfs = require('brfs') var ttyError = require('./tty-error') var exorcise = require('./exorcise') var utils = require('./utils') var filenames = [ 'service-worker.js', 'sw.js' ] module.exports = node function node (state, createEdge) { var entry = state.metadata.entry var self = this var unwatch assert.equal(typeof entry, 'string', 'bankai.service-worker: state.metadata.entries should be type string') var basedir = state.metadata.dirname if (state.metadata.watch && !state.metadata.watchers.serviceWorker) { state.metadata.watchers.serviceWorker = true debug('watching ' + basedir + ' for ' + filenames.join(', ')) unwatch = utils.watch(basedir, filenames, parse) this.on('close', function () { debug('closing file watcher') if (unwatch) unwatch() }) } parse() function parse () { find(basedir, filenames, function (err, filename) { if (err) { state.metadata.serviceWorker = 'service-worker.js' return createEdge('bundle', Buffer.from(''), { mime: 'application/javascript' }) } // Expose what the original file name of the service worker was state.metadata.serviceWorker = path.basename(filename) var b = browserify(browserifyOpts([ filename ])) if (state.metadata.watch && !state.metadata.watchers.serviceWorker) { if (unwatch) unwatch() // File now exists, no need to have double watchers state.metadata.watchers.serviceWorker = true debug('watchify: watching ' + filename) b = watchify(b) b.on('update', function () { debug('watchify: update detected in ' + filename) bundleScripts() }) self.on('close', function () { debug('closing file watcher') b.close() }) } var env = Object.assign({}, process.env, fileEnv(state)) b.transform(brfs) if (!state.metadata.watch) b.plugin(tinyify, { env: env }) bundleScripts() function bundleScripts () { b.bundle(function (err, bundle) { if (err) { delete err.stream err = ttyError('service-worker', 'browserify.bundle', err) return self.emit('error', 'scripts', 'browserify.bundle', err) } var mapName = 'bankai-service-worker.js.map' exorcise(bundle, mapName, function (err, bundle, map) { if (err) return self.emit('error', 'service-worker', 'exorcise', err) createEdge(mapName, map, { mime: 'application/json' }) createEdge('bundle', bundle, { mime: 'application/javascript' }) }) }) } }) } } function browserifyOpts (entries) { assert.ok(Array.isArray(entries), 'browserifyOpts: entries should be an array') return { debug: true, entries: entries, packageCache: {}, cache: {} } } function find (rootname, arr, done) { if (!arr.length) return done(new Error('Could not find files')) var filename = arr[0] var newArr = arr.slice(1) findup(rootname, filename, function (err, dirname) { if (err) return find(rootname, newArr, done) done(null, path.join(dirname, filename)) }) } function fileEnv (state) { var script = [ `${state.scripts.bundle.hash.toString('hex').slice(0, 16)}/bundle.js` ] var style = [`${state.styles.bundle.hash.toString('hex').slice(0, 16)}/bundle.css`] var assets = split(state.assets.list.buffer) var doc = split(state.documents.list.buffer) var manifest = ['/manifest.json'] var files = [].concat(script, style, assets, doc, manifest) files = files.filter(function (file) { return file }) return { STYLE_LIST: style, SCRIPT_LIST: script, ASSET_LIST: assets, DOCUMENT_LIST: doc, MANIFEST_LIST: manifest, FILE_LIST: files } function split (buf) { var str = String(buf) return str.split(',') } }
JavaScript
0.000002
@@ -57,47 +57,8 @@ r')%0A -var findup = require('@choojs/findup')%0A var @@ -1075,16 +1075,22 @@ ) %7B%0A +utils. find(bas @@ -3171,321 +3171,8 @@ %0A%7D%0A%0A -function find (rootname, arr, done) %7B%0A if (!arr.length) return done(new Error('Could not find files'))%0A var filename = arr%5B0%5D%0A var newArr = arr.slice(1)%0A findup(rootname, filename, function (err, dirname) %7B%0A if (err) return find(rootname, newArr, done)%0A done(null, path.join(dirname, filename))%0A %7D)%0A%7D%0A%0A func
7abd123275cde53317e55bfa78c10d7b6bf9a970
print x-varnish header
rpc-service/app.js
rpc-service/app.js
var timers = require('timers'), http = require('http'), querystring = require('querystring'), async = require('async'), express = require('express'); var services = require('./services'), servicesParser = require('./services/parser'); var app = express(), argv = require('minimist')(process.argv.slice(2)); var servicesIndex = servicesParser.parseServices(argv.services); function getRandomTimeForDelay() { // wait between 0 - 1.5 records before delivering any results back return (Math.random() * 1.5).toFixed(2) * 1000; } app.get('/:serviceName/:indentLevel?', function (req, res) { var indentLevel = req.params.indentLevel ? parseInt(req.params.indentLevel) : 0, service = services.findService('/' + req.params.serviceName, servicesIndex); var randomTimeInSeconds, date; date = new Date(); if (service) { console.log(Array(30).join('-')); console.log(date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds(), Array(indentLevel * 3).join(' '), service.label, '->', service.url); if (service.children) { var funcs = [], urlParams = (indentLevel + 1); for (var i = 0; i < service.children.urls.length; i++) { funcs.push(function(path) { return function (next) { http.get('http://' + argv.address +':'+ argv['proxy-port'] + path, function (res) { timers.setTimeout(function() { next(); }, getRandomTimeForDelay()); }); }; }( service.children.urls[i]) ); } //console.log('>> flow', '-', service.children.flow); if (service.children.flow === 'serial') { async.series(funcs, function (err, results) { res.send(); }); } else if (service.children.flow === 'parallel') { async.parallel(funcs, function (err, results) { res.send(); }); } } else { timers.setTimeout(function() { res.send(); }, getRandomTimeForDelay()); } } else { res.status(404).send(); } }); var server = app.listen(argv.port, argv.address, function() { var address = server.address().address, port = server.address().port; console.log(argv.service + ' server listening at http://%s:%d', address, port); console.log(''); });
JavaScript
0.000001
@@ -1278,24 +1278,89 @@ n (next) %7B%0A%0A + console.log('x-varnish', req.headers%5B'x-varnish'%5D);%0A%0A
62ece412f9eff2e427231234a380abf8b79dd47e
add proptypes to context
src/components/ContextMenu.js
src/components/ContextMenu.js
import React from 'react'; import { SprkLink } from '@sparkdesignsystem/spark-react'; import { Link } from 'gatsby'; import classnames from 'classnames'; function ContextMenu({context, setContext, className, autoNav}) { return ( <div className="docs-context-menu"> <ul className={className}> <li> <SprkLink additionalClasses={classnames({'docs-context-menu__item--active': context==='installing-spark'})} onClick={(e) => {if (!autoNav) {e.preventDefault();} setContext('installing-spark');}} variant="simple" element={Link} to="/installing-spark">Installing Spark</SprkLink> </li> <li> <SprkLink additionalClasses={classnames({'docs-context-menu__item--active': context==='using-spark'})} onClick={(e) => {if (!autoNav) {e.preventDefault();} setContext('using-spark');}} variant="simple" element={Link} to="/using-spark">Using Spark</SprkLink> </li> <li> <SprkLink additionalClasses={classnames({'docs-context-menu__item--active': context==='principles'})} onClick={(e) => {if (!autoNav) {e.preventDefault();} setContext('principles');}} element={Link} variant='simple' to="/principles/design-principles">Principles</SprkLink> </li> </ul> </div> ); } export default ContextMenu;
JavaScript
0.000002
@@ -146,16 +146,52 @@ snames'; +%0Aimport PropTypes from 'prop-types'; %0A%0Afuncti @@ -206,16 +206,17 @@ xtMenu(%7B + context, @@ -246,16 +246,17 @@ autoNav + %7D) %7B%0A r @@ -396,36 +396,87 @@ nalClasses=%7B -classnames(%7B +%0A classnames(%0A %7B%0A 'docs-contex @@ -505,19 +505,21 @@ context + === + 'install @@ -532,76 +532,207 @@ ark' -%7D)%7D%0A onClick=%7B(e) =%3E %7Bif (!autoNav) %7Be.preventDefault();%7D +,%0A %7D,%0A )%0A %7D%0A onClick=%7B%0A (e) =%3E %7B%0A if (!autoNav) %7B%0A e.preventDefault();%0A %7D%0A set @@ -751,33 +751,61 @@ talling-spark'); -%7D +%0A %7D%0A %7D%0A va @@ -879,18 +879,70 @@ ng-spark -%22%3E +/setting-up-your-environment%22%0A %3E%0A Installi @@ -941,32 +941,43 @@ Installing Spark +%0A %3C/SprkLink%3E%0A @@ -1046,36 +1046,87 @@ nalClasses=%7B -classnames(%7B +%0A classnames(%0A %7B%0A 'docs-contex @@ -1155,19 +1155,21 @@ context + === + 'using-s @@ -1177,203 +1177,365 @@ ark' -%7D)%7D%0A onClick=%7B(e) =%3E %7Bif (!autoNav) %7Be.preventDefault();%7D setContext('using-spark');%7D%7D%0A variant=%22simple%22%0A element=%7BLink%7D%0A to=%22/using-spark%22%3EUsing Spark +,%0A %7D,%0A )%0A %7D%0A onClick=%7B%0A (e) =%3E %7B%0A if (!autoNav) %7B%0A e.preventDefault();%0A %7D%0A setContext('using-spark');%0A %7D%0A %7D%0A variant=%22simple%22%0A href=%22#nogo%22%0A %3E%0A Using Spark%0A %3C/Sp @@ -1624,20 +1624,53 @@ es=%7B -classnames(%7B +%0A classnames(%0A %7B 'doc @@ -1707,19 +1707,21 @@ context + === + 'princip @@ -1728,41 +1728,103 @@ les' -%7D)%7D%0A onClick=%7B(e) =%3E %7B + %7D,%0A )%0A %7D%0A onClick=%7B%0A (e) =%3E %7B%0A if ( @@ -1834,16 +1834,17 @@ toNav) %7B + e.preven @@ -1854,16 +1854,17 @@ fault(); + %7D setCon @@ -1882,17 +1882,31 @@ iples'); -%7D +%0A %7D%0A @@ -1907,37 +1907,24 @@ -element=%7BLink %7D%0A @@ -1937,16 +1937,16 @@ ant= -' +%22 simple -' +%22 %0A @@ -1958,108 +1958,268 @@ -to=%22/principles/design-principles%22%3EPrinciples%3C/SprkLink%3E%0A %3C/li%3E%0A %3C/ul%3E%0A %3C/div%3E%0A );%0A%7D +href=%22#nogo%22%0A %3E%0A Principles%0A %3C/SprkLink%3E%0A %3C/li%3E%0A %3C/ul%3E%0A %3C/div%3E%0A );%0A%7D%0A%0AContextMenu.propTypes = %7B%0A context: PropTypes.string,%0A setContext: PropTypes.func,%0A className: PropTypes.string,%0A autoNav: PropTypes.bool,%0A%7D; %0A%0Aex
8579b2a7788b9b172f9658ea91daf66f31cfeb46
fix logincontainer styling
src/components/Login/index.js
src/components/Login/index.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { PENDING } from 'constants'; import Loader from 'components/Loader'; import styled from 'styled-components'; import LoginButton from './LoginButton'; const Wrapper = styled.div` width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center; flex-direction: column; background: ${props => props.theme.colors.primaryBackground} color: ${props => props.theme.colors.primaryText} `; const LoginContainer = styled.div` ` const SubTitle = styled.h2` margin-top: 10px; font-size: 14px; `; class Login extends PureComponent { static propTypes = { status: PropTypes.string.isRequired, onLoginClicked: PropTypes.func.isRequired, }; render() { const { status } = this.props; return ( <Wrapper> {status === PENDING ? <Loader /> : <LoginContainer> <LoginButton onLoginClicked={this.props.onLoginClicked} /> </LoginContainer> } </Wrapper> ); } } export default Login;
JavaScript
0.000001
@@ -152,16 +152,53 @@ oader';%0A +import %7B prop %7D from 'styled-tools';%0A import s @@ -225,24 +225,24 @@ omponents';%0A - import Login @@ -441,35 +441,26 @@ ound: $%7Bprop -s =%3E props. +(' theme.colors @@ -477,17 +477,20 @@ ckground -%7D +')%7D; %0A color @@ -501,19 +501,10 @@ prop -s =%3E props. +(' them @@ -527,117 +527,11 @@ Text -%7D%0A%60;%0A%0Aconst LoginContainer = styled.div%60%0A%60%0A%0Aconst SubTitle = styled.h2%60%0A margin-top: 10px;%0A font-size: 14px +')%7D ;%0A%60; @@ -826,30 +826,19 @@ %3C -LoginContainer +div %3E%0A @@ -918,22 +918,11 @@ %3C/ -LoginContainer +div %3E%0A
0fad53e5caca31c420c0b73f1dd96176e55b7ce1
allow env var for public key
src/main.js
src/main.js
"use strict"; const express = require("express"); const app = express(); const jwt = require("express-jwt"); const fs = require("fs"); const path = require("path"); const secret = fs.readFileSync(path.resolve("ookla-extracts.pem")); app.use(jwt({ secret, algorithms: ["RS256"] })); app.get("/", (req, res) => { res.send(`JWT VERIFIED! PAYLOAD: \n ${JSON.stringify(req.user)}`); }); app.listen(8000);
JavaScript
0.000001
@@ -168,33 +168,18 @@ nst -secret = fs.readFileSync( +keypath = path @@ -208,16 +208,158 @@ ts.pem%22) +;%0A%0Alet secret;%0Afs.access(keypath, fs.constants.R_OK, (err) =%3E %7B%0A secret = err ? secret = fs.readFileSync(keypath) : process.env.PUBLIC_KEY;%0A%7D );%0A%0Aapp.
6b49a7a15a0e6a41936a1b79aae3ff00657bfd56
Use optimisticResponse as a function
src/main.js
src/main.js
import RQL from "react-relay/lib/RelayQL" import RelayQuery from "react-relay/lib/RelayQuery" import RelayMetaRoute from "react-relay/lib/RelayMetaRoute" import RelayStore from "react-relay/lib/RelayStore" import RelayStoreData from "react-relay/lib/RelayStoreData" import RelayDefaultNetworkLayer from "react-relay/lib/RelayDefaultNetworkLayer" import RelayNetworkLayer from "react-relay/lib/RelayNetworkLayer" import RelayMutation from "react-relay/lib/RelayMutation" import GraphQL from "react-relay/lib/GraphQL" import GraphQLStoreQueryResolver from "react-relay/lib/GraphQLStoreQueryResolver" import GraphQLFragmentPointer from "react-relay/lib/GraphQLFragmentPointer" import curry from "./util/curry" const storeData = RelayStoreData.getDefaultInstance() export const RelayQL = RQL export function setEndpoint(endpoint) { RelayNetworkLayer.injectNetworkLayer(new RelayDefaultNetworkLayer(endpoint)) } export const query = curry((q, variables) => { return (fragment) => { const baseQuery = new GraphQL.Query( q.fieldName, (q.calls[0] && q.calls[0].value) || null, q.fields, [fragment], q.metadata, q.name ) const rootQuery = RelayQuery.Root.create( baseQuery, RelayMetaRoute.get(q.name), variables || {} ) return { root: rootQuery, base: baseQuery, variables } } }) export const observe = curry((q, opts, fragment, onValue) => { const {root, base: {name}, variables} = q(fragment) const options = opts || {} let resolver = null, request = null request = options.forceFetch === true ? RelayStore.forceFetch({[name]: root}, handleStatusChange) : RelayStore.primeCache({[name]: root}, handleStatusChange) return function unsubscribe() { if (request) { request.abort() request = null } if (resolver) { resolver.reset() resolver = null } } function handleStatusChange(status) { if (status.ready) { // get fragment pointers from query const fp = GraphQLFragmentPointer.createForRoot( storeData.getQueuedStore(), root ) const relayFragment = RelayQuery.Fragment.create( fragment, RelayMetaRoute.get(name), variables ) const graphqlFP = relayFragmentToGraphQLFP(fp, relayFragment) const handleUpdate = () => { if (resolver) { const val = resolver.resolve(graphqlFP) onValue(val) } } resolver = new GraphQLStoreQueryResolver(graphqlFP, handleUpdate) handleUpdate() } // TODO: error handling } function relayFragmentToGraphQLFP(rootFP, relayFragment) { const ids = getFragmentIds(rootFP, relayFragment) return new GraphQLFragmentPointer(ids, relayFragment) } function getFragmentIds(fp, relayFragment) { const fid = relayFragment.getConcreteFragmentID() if (relayFragment.isPlural()) { return fp.reduce((acc, it) => [...acc, ...it[fid].getDataIDs()], []) } else { return fp[fid].getDataID() } } }) class ReleiMutation extends RelayMutation { constructor(opts) { super({}) this.releiOpts = opts } getMutation() { return this.releiOpts.mutation } getVariables() { return this.releiOpts.variables } getFatQuery() { return this.releiOpts.fatQuery } getConfigs() { return this.releiOpts.configs(this.releiOpts.ctx) } } class ReleiOptimisticMutation extends ReleiMutation { constructor(mutation, opts) { super(mutation, opts) } getOptimisticResponse() { return this.releiOpts.optimisticResponse } } export const mutate = curry((opts, ctx, variables) => { const {mutation, fatQuery, configs, optimisticResponse} = opts if (!(mutation && fatQuery && configs)) { throw new Error( "Mandatory options missing! The following options must be given:\n" + " * mutation\n" + " * fatQuery\n" + " * configs" ) } const options = {...opts, ctx, variables} const releiMutation = optimisticResponse ? new ReleiOptimisticMutation(options) : new ReleiMutation(options) RelayStore.update(releiMutation) })
JavaScript
0.000106
@@ -3442,38 +3442,56 @@ Configs() %7B%0A -return +const %7Bctx, variables%7D = this.releiOpts. @@ -3493,17 +3493,20 @@ Opts -.configs( +%0A return this @@ -3517,18 +3517,37 @@ eiOpts.c -tx +onfigs(ctx, variables )%0A %7D%0A%7D%0A @@ -3687,24 +3687,68 @@ esponse() %7B%0A + const %7Bctx, variables%7D = this.releiOpts%0A return t @@ -3779,16 +3779,32 @@ Response +(ctx, variables) %0A %7D%0A%7D%0A%0A
c94a91f2ff0e02a1a17da5d8fc458c45f71fd635
Add menu option to disable #gifbar hashtag.
src/main.js
src/main.js
var path = require('path'); var events = require('events'); var fs = require('fs'); var electron = require('electron'); var app = electron.app; var Tray = electron.Tray; var Menu = electron.Menu; var globalShortcut = electron.globalShortcut; var BrowserWindow = electron.BrowserWindow; global.sharedObject = { hideNSFW: true }; var extend = require('extend'); var Positioner = require('electron-positioner'); var options = { width: 436, height: 600, tooltip: 'GifBar', 'always-on-top': true, preloadWindow: true }; create(options); function create (opts) { if (typeof opts === 'undefined') opts = {dir: app.getAppPath()}; if (typeof opts === 'string') opts = {dir: opts}; if (!opts.dir) opts.dir = app.getAppPath(); if (!(path.isAbsolute(opts.dir))) opts.dir = path.resolve(opts.dir); if (!opts.index) opts.index = 'file://' + path.join(opts.dir, 'index.html'); if (!opts['window-position']) opts['window-position'] = (process.platform === 'win32') ? 'trayBottomCenter' : 'trayCenter'; if (typeof opts['show-dock-icon'] === 'undefined') opts['show-dock-icon'] = false; // set width/height on opts to be usable before the window is created opts.width = opts.width || 400; opts.height = opts.height || 400; opts.tooltip = opts.tooltip || ''; app.on('ready', appReady); app.on('will-quit', willQuit); var shortcut = 'CommandOrControl+Alt+G'; var menubar = new events.EventEmitter(); menubar.app = app; // Set / get options menubar.setOption = function (opt, val) { opts[opt] = val; }; menubar.getOption = function (opt) { return opts[opt]; }; return menubar; function appReady () { if (app.dock && !opts['show-dock-icon']) app.dock.hide(); var iconPath = opts.icon || path.join(opts.dir, 'IconTemplate.png'); if (!fs.existsSync(iconPath)) iconPath = path.join(__dirname, 'IconTemplate.png'); // default cat icon var cachedBounds; // cachedBounds are needed for double-clicked event menubar.tray = opts.tray || new Tray(iconPath); menubar.tray.on('click', clicked); menubar.tray.on('double-click', clicked); menubar.tray.on('right-click', showDetailMenu); menubar.tray.setToolTip(opts.tooltip); if (opts.preloadWindow || opts['preload-window']) { createWindow(); } globalShortcut.register(shortcut, function() { if (menubar.window && menubar.window.isVisible()) return hideWindow(); showWindow(cachedBounds); }); menubar.showWindow = showWindow; menubar.hideWindow = hideWindow; menubar.emit('ready'); function clicked (e, bounds) { if (e.altKey || e.shiftKey || e.ctrlKey || e.metaKey) return hideWindow(); if (menubar.window && menubar.window.isVisible()) return hideWindow(); cachedBounds = bounds || cachedBounds; showWindow(cachedBounds); } function createWindow () { menubar.emit('create-window'); var defaults = { show: false, frame: false }; var winOpts = extend(defaults, opts); menubar.window = new BrowserWindow(winOpts); menubar.positioner = new Positioner(menubar.window); if (!opts['always-on-top']) { menubar.window.on('blur', hideWindow); } else { menubar.window.on('blur', emitBlur); } if (opts['show-on-all-workspaces'] !== false) { menubar.window.setVisibleOnAllWorkspaces(true); } menubar.window.on('close', windowClear); menubar.window.loadURL(opts.index); menubar.emit('after-create-window'); } function showWindow (trayPos) { if (!menubar.window) { createWindow();; } menubar.emit('show'); if (trayPos && trayPos.x !== 0) { // Cache the bounds cachedBounds = trayPos; } else if (cachedBounds) { // Cached value will be used if showWindow is called without bounds data trayPos = cachedBounds; } // Default the window to the right if `trayPos` bounds are undefined or null. var noBoundsPosition = null; if ((trayPos === undefined || trayPos.x === 0) && opts['window-position'].substr(0, 4) === 'tray') { noBoundsPosition = (process.platform === 'win32') ? 'bottomRight' : 'topRight'; } var position = menubar.positioner.calculate(noBoundsPosition || opts['window-position'], trayPos); var x = (opts.x !== undefined) ? opts.x : position.x; var y = (opts.y !== undefined) ? opts.y : position.y; menubar.window.setPosition(x, y); menubar.window.show(); menubar.emit('after-show'); // Send an event that we have shown the window menubar.window.webContents.send('after-show'); return; } function hideWindow () { if (!menubar.window) return; menubar.emit('hide'); menubar.window.hide(); menubar.emit('after-hide'); } function windowClear () { delete menubar.window; menubar.emit('after-close'); } function emitBlur () { menubar.emit('focus-lost'); } function showDetailMenu () { var contextMenu = Menu.buildFromTemplate([ { label: 'Hide NSFW', type: 'checkbox', checked: global.sharedObject.hideNSFW, click: function() { global.sharedObject.hideNSFW = !global.sharedObject.hideNSFW; } }, { type: 'separator' }, { label: 'Toggle DevToools', accelerator: 'Alt+Command+I', click: function() { menubar.window.show(); menubar.window.toggleDevTools(); } }, { label: 'Quit', accelerator: 'Command+Q', selector: 'terminate:', } ]); menubar.tray.popUpContextMenu(contextMenu); } } function willQuit() { globalShortcut.unregister(shortcut); } }
JavaScript
0
@@ -319,24 +319,51 @@ deNSFW: true +,%0A includeHashTag: true, %0A%7D;%0A%0Avar ext @@ -6039,32 +6039,385 @@ %7B%0A + label: 'Append #gifbar on copy',%0A type: 'checkbox',%0A checked: global.sharedObject.includeHashTag,%0A click: function() %7B%0A global.sharedObject.includeHashTag = !global.sharedObject.includeHashTag;%0A %7D%0A %7D,%0A %7B%0A @@ -7090,8 +7090,9 @@ %0A %7D%0A%7D +%0A
121cbd6ee87d99dbcfcad490955733438d2fd26e
Fix incorrect use of $.extend()
modules/ui/mw.echo.ui.ActionMenuPopupWidget.js
modules/ui/mw.echo.ui.ActionMenuPopupWidget.js
( function () { /** * Action menu popup widget for echo items. * * We don't currently have anything that properly answers the complete * design for our popup menus in OOUI, so this widget serves two purposes: * 1. The MenuSelectWidget is intended to deliver a menu that relates * directly to its anchor, so its sizing is dictated by whatever anchors * it. This is not what we require, so we have to override the 'click' event * to reset the width of the menu. * 2. It abstracts the behavior of the item menus for easier management * in the item widget itself (which is fairly large) * * @class * @extends OO.ui.ButtonWidget * * @constructor * @param {Object} [config] Configuration object * @cfg {jQuery} [$overlay] A jQuery element functioning as an overlay * for popups. * @cfg {Object} [horizontalPosition='auto'] How to position the menu, see OO.ui.FloatableElement. * By default, 'start' will be tried first, and if that doesn't fit, 'end' will be used. */ mw.echo.ui.ActionMenuPopupWidget = function MwEchoUiActionMenuPopupWidget( config ) { config = config || {}; // Parent constructor mw.echo.ui.ActionMenuPopupWidget.super.call( this, config ); this.$overlay = config.$overlay || this.$element; // Menu this.customMenuPosition = ( config.horizontalPosition || 'auto' ) !== 'auto'; this.menu = new OO.ui.MenuSelectWidget( $.extend( { $floatableContainer: this.$element, horizontalPosition: this.customMenuPosition ? config.horizontalPosition : 'start', classes: [ 'mw-echo-ui-actionMenuPopupWidget-menu' ], widget: this } ) ); this.$overlay.append( this.menu.$element ); // Events this.connect( this, { click: 'onAction' } ); this.getMenu().connect( this, { remove: 'decideToggle', add: 'decideToggle', clear: 'decideToggle' } ); // Initialization this.$element .addClass( 'mw-echo-ui-actionMenuPopupWidget' ); }; /* Setup */ OO.inheritClass( mw.echo.ui.ActionMenuPopupWidget, OO.ui.ButtonWidget ); /** * Handle the button action being triggered. * * @private */ mw.echo.ui.ActionMenuPopupWidget.prototype.onAction = function () { // HACK: If config.horizontalPosition isn't set, first try 'start', then 'end' if ( !this.customMenuPosition ) { this.menu.setHorizontalPosition( 'start' ); } this.menu.toggle(); if ( !this.customMenuPosition && this.menu.isClipped() ) { this.menu.setHorizontalPosition( 'end' ); } }; /** * Decide whether the menu should be visible, based on whether it is * empty or not. */ mw.echo.ui.ActionMenuPopupWidget.prototype.decideToggle = function () { this.toggle( !this.getMenu().isEmpty() ); }; /** * Get the widget's action menu * * @return {OO.ui.MenuSelectWidget} Menu */ mw.echo.ui.ActionMenuPopupWidget.prototype.getMenu = function () { return this.menu; }; }() );
JavaScript
0.001194
@@ -1401,18 +1401,8 @@ get( - $.extend( %7B%0A%09 @@ -1601,18 +1601,16 @@ this%0A%09%09%7D - ) );%0A%09%09th
0003d73413199922e94bc420f19a8d84f5a7dc2c
Add placeholder.
src/CardNumberInput.js
src/CardNumberInput.js
import React from 'react'; import InputMask from 'inputmask-core'; const ENTER_KEY = 'Enter'; const BACKSPACE_KEY = 'Backspace'; const KEYCODE_Y = 89; const KEYCODE_Z = 90; class CardNumberInput extends React.Component { constructor() { super(); this.state = { isValid: false, text: '' } this.handlePaste = this.handlePaste.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); this.handleChange = this.handleChange.bind(this); } componentWillMount() { const selection = this.props.value ? this.props.value.length : 0; let options = { pattern: '11-1111-11-11111', placeholderChar: ' ', value: this.props.value, selection: { start: selection, end: selection } } this.mask = new InputMask(options); const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, () => triggerOnchange(this.state, this.props)); } componentWillReceiveProps(nextProps) { if (this.props.value !== nextProps.value) { const selection = nextProps.value ? nextProps.value.length : 0; this.mask.setValue(nextProps.value); this.mask.setSelection({ start: selection, end: selection }) const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, () => triggerOnchange(this.state, this.props)); } } handleChange(event) { const maskValue = this.mask.getValue() const elementValue = event.target.value; if (elementValue !== maskValue) { // Cut or delete operations will have shortened the value if (elementValue.length < maskValue.length) { const sizeDiff = maskValue.length - elementValue.length this.mask.setSelection(getElementSelection(event.target)); this.mask.selection.end = this.mask.selection.start + sizeDiff this.mask.backspace() } const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, () => triggerOnchange(this.state, this.props)); } } handlePaste(event) { event.preventDefault(); this.mask.setSelection(getElementSelection(event.target)); if (this.mask.paste(event.clipboardData.getData('text'))) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, () => triggerOnchange(this.state, this.props)); } } handleKeyDown(event) { if (isUndoEvent(event)) { event.preventDefault() if (this.mask.undo()) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, () => triggerOnchange(this.state, this.props)); } return; } else if (isRedoEvent(event)) { event.preventDefault() if (this.mask.redo()) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, () => triggerOnchange(this.state, this.props)); } return; } if (event.key === BACKSPACE_KEY) { event.preventDefault(); this.mask.setSelection(getElementSelection(event.target)); if (this.mask.backspace()) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, () => triggerOnchange(this.state, this.props)); } } } handleKeyPress(event) { if (event.metaKey || event.altKey || event.ctrlKey || event.key === ENTER_KEY) { return } event.preventDefault(); this.mask.setSelection(getElementSelection(event.target)); if (this.mask.input(event.key)) { const value = getDisplayMaskValue(this.mask); this.setState({ text: value, isValid: isValidValue(value, this.mask) }, () => triggerOnchange(this.state, this.props)); } } render() { return <input type="text" size={this.mask.pattern.length} maxLength={this.mask.pattern.length} onChange={this.handleChange} onPaste={this.handlePaste} onKeyDown={this.handleKeyDown} onKeyPress={this.handleKeyPress} value={this.state.text} /> } } CardNumberInput.propTypes = { value: React.PropTypes.string, onChange: React.PropTypes.func } function getElementSelection(element) { return { start: element.selectionStart, end: element.selectionEnd } } function getDisplayMaskValue(mask) { return mask .getValue() .slice(0, mask.selection.end); } function isValidValue(value, mask) { return value && value !== mask.emptyValue && value.length === mask.pattern.length; } function triggerOnchange(state, props) { if (props.onChange) { props.onChange({ text: state.text, isValid: state.isValid }); } } function isUndoEvent(event) { return (event.ctrlKey || event.metaKey) && event.keyCode === (event.shiftKey ? KEYCODE_Y : KEYCODE_Z); } function isRedoEvent(event) { return (event.ctrlKey || event.metaKey) && event.keyCode === (event.shiftKey ? KEYCODE_Z : KEYCODE_Y); } export default CardNumberInput;
JavaScript
0
@@ -173,16 +173,53 @@ Z = 90;%0D +%0Aconst PATTERN = '11-1111-11-11111';%0D %0A%0D%0Aclass @@ -729,34 +729,23 @@ attern: -'11-1111-11-11111' +PATTERN ,%0D%0A @@ -4444,16 +4444,64 @@ %22text%22%0D%0A + placeholder=%7BPATTERN.replace(/1/g, 'X')%7D%0D%0A si
f9c15ef6b639b32a04c9b717eacf9dfab94a65c6
Fix click from inside to outside for modal backdrop
src/components/modal/Modal.js
src/components/modal/Modal.js
import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import cx from 'classnames'; import findNodeHandle from 'react-native-web/dist/cjs/exports/findNodeHandle'; import ModalContext from './ModalContext'; import ModalBody from './ModalBody'; import ModalFooter from './ModalFooter'; import ModalHeader from './ModalHeader'; import ModalTitle from './ModalTitle'; import { MODAL_SIZES } from '../../utils/constants'; import BaseView from '../../utils/rnw-compat/BaseView'; import useModal from './useModal'; const propTypes = { children: PropTypes.node.isRequired, visible: PropTypes.bool.isRequired, size: PropTypes.oneOf(MODAL_SIZES), backdrop: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['static'])]), scrollable: PropTypes.bool, centered: PropTypes.bool, onToggle: PropTypes.func.isRequired, }; const Modal = React.forwardRef((props, ref) => { const { visible, size, backdrop = true, scrollable = false, centered = false, onToggle, ...elementProps } = props; const modal = useModal(visible, onToggle); // Return null if not mounted. if (!modal.mounted || !modal.visible) { return null; } const dialogClasses = cx( // constant classes 'modal-dialog', // variable classes size === 'sm' && 'modal-sm', size === 'lg' && 'modal-lg', size === 'xl' && 'modal-xl', scrollable && 'modal-dialog-scrollable', centered && 'modal-dialog-centered', ); const modalElement = ( <BaseView key="modal" ref={(element) => { modal.ref.current = findNodeHandle(element); }} accessible accessibilityRole="dialog" aria-labelledby={modal.identifier} aria-modal="true" // For now we need onClick here, because onMouseDown would also toggle the modal when the user clicks on a scrollbar. onClick={(event) => { if (backdrop === 'static') { return; } if (event.target === modal.ref.current) { modal.setVisible(false); } }} onKeyUp={(event) => { if (event.key === 'Escape') { event.preventDefault(); if (backdrop === 'static') { return; } modal.setVisible(false); } }} essentials={{ className: 'modal show' }} > <BaseView accessibilityRole="document" essentials={{ className: dialogClasses }} > <ModalContext.Provider value={modal}> <BaseView {...elementProps} ref={ref} essentials={{ className: 'modal-content' }} /> </ModalContext.Provider> </BaseView> </BaseView> ); if (!backdrop) { return ReactDOM.createPortal(modalElement, document.body); } const backdropElement = ( <BaseView key="modal-backdrop" essentials={{ className: 'modal-backdrop show' }} /> ); return ReactDOM.createPortal([modalElement, backdropElement], document.body); }); Modal.displayName = 'Modal'; Modal.propTypes = propTypes; Modal.Context = ModalContext; Modal.Body = ModalBody; Modal.Footer = ModalFooter; Modal.Header = ModalHeader; Modal.Title = ModalTitle; export default Modal;
JavaScript
0
@@ -5,16 +5,28 @@ rt React +, %7B useRef %7D from 'r @@ -1113,16 +1113,104 @@ Toggle); +%0A const waitingForMouseUp = useRef(false);%0A const ignoreBackdropClick = useRef(false); %0A%0A // R @@ -2073,24 +2073,76 @@ if ( +%0A ignoreBackdropClick.current %7C%7C%0A event.target @@ -2146,77 +2146,370 @@ get -=== modal.ref.current) %7B%0A modal.setVisible(false);%0A %7D +!== event.currentTarget%0A ) %7B%0A ignoreBackdropClick.current = false;%0A return;%0A %7D%0A%0A modal.setVisible(false);%0A %7D%7D%0A onMouseUp=%7B(event) =%3E %7B%0A if (waitingForMouseUp.current && event.target === modal.ref.current) %7B%0A ignoreBackdropClick.current = true;%0A %7D%0A%0A waitingForMouseUp.current = false; %0A @@ -2564,17 +2564,17 @@ ent.key -= +! == 'Esca @@ -2578,24 +2578,51 @@ scape') %7B%0A + return;%0A %7D%0A%0A even @@ -2642,18 +2642,16 @@ ult();%0A%0A - @@ -2681,34 +2681,32 @@ c') %7B%0A - return;%0A @@ -2701,31 +2701,27 @@ rn;%0A - %7D%0A%0A - moda @@ -2741,26 +2741,16 @@ false);%0A - %7D%0A %7D%7D @@ -2856,16 +2856,100 @@ cument%22%0A + onMouseDown=%7B() =%3E %7B%0A waitingForMouseUp.current = true;%0A %7D%7D%0A
ad8b3d5cb24784d3c9e461365309ad38b20faaa0
Update mariogolf.min.js
js/mariogolf.min.js
js/mariogolf.min.js
(function(w,u){w.MarioGolf=function(c){var t=[],S=SyntaxError,m={c:c,R:'',i:'',s:[],r:{R:0,I:0,P:0,L:0,Z:0},v:{},o:''},R=function(B){};if(!c||!c.match(/(?:^|[\r\n])([MLPBTYK]+)\|(?:(.*)\|)?([OQ|\-1RNM])(?:$|[\r\n])/))throw new S('Expecting identifier, got '+(c?'invalid program':'0-length code')+'.','code',0);else if((t[0]=c[1].matches(/\{(?=([^"]*"[^"]*")*[^"]*$)/g))!=(t[1]=c[1].matches(/\}(?=([^"]*"[^"]*")*[^"]*$)/g)))throw new S( 'Missing "' + ( tmp[0] < tmp[1] ? '{' : '}' ) + '" before the last identifier.', 'code', 0 );return {run:function(i){m={c:m.c,R:'',i:i,s:[],r:{R:0,I:0,P:0,L:0,Z:0},v:{},o:''};return R(m.c);},getStack:function(){return m.s;},getReturn:function(){return m.R;},getVars:function(){return m.v;},getOutput:function(){return m.o;}}};})([]['slice']['constructor']('return this;')());
JavaScript
0
@@ -615,15 +615,18 @@ urn +m.R= R(m.c) -; %7D,ge @@ -653,17 +653,16 @@ turn m.s -; %7D,getRet @@ -686,17 +686,16 @@ turn m.R -; %7D,getVar @@ -717,17 +717,16 @@ turn m.v -; %7D,getOut @@ -750,17 +750,16 @@ turn m.o -; %7D%7D%7D;%7D)(%5B @@ -802,10 +802,9 @@ is;')()) -; %0A
8201874e3f3ec2139c3a8d1d7a0d0711526ae7af
Update gpioctrl
libs/gpioctrl.js
libs/gpioctrl.js
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd. * * 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. */ 'use strict' const settings = require('./settings') const EventEmitter = require('events') const util = require('util') const fs = require('fs') const Gpio = require('onoff').Gpio /** * GpioCtrl - GPIO Controller * * Events * - 'pressed' or 'on' * - 'released' or 'off' * * Methods * - setOn * - setOff * - setStatus (status) */ function GpioCtrl (pin, isInput) { EventEmitter.call(this) this.pin = pin this.isInput = isInput this.handle = null if (pin === 0) { console.log('GPIO pin(virtual) opened') return } try { fs.accessSync('/sys/class/gpio/export', fs.F_OK | fs.W_OK) } catch (e) { console.error('GPIO pin(' + pin + ') open failed') return } if (isInput === true) { this.handle = new Gpio(pin, 'in', 'both') const self = this this.handle.watch((err, value) => { if (err) { console.log(err) } if (value === 0) { self.emit('pressed') self.emit('on') } else { self.emit('released') self.emit('off') } }) } else { this.handle = new Gpio(pin, 'out') } } util.inherits(GpioCtrl, EventEmitter) GpioCtrl.prototype.setOn = function () { if (this.pin === 0) { this.emit('on') return } if (this.handle && this.isInput === false) { this.handle.writeSync(1) this.emit('on') } else { console.error('setOn() failed') } } GpioCtrl.prototype.setOff = function () { if (this.pin === 0) { this.emit('off') return } if (this.handle && this.isInput === false) { this.handle.writeSync(0) this.emit('off') } else { console.error('setOff() failed') } } GpioCtrl.prototype.setStatus = function (status) { if (status === 1) { this.setOn() } else if (status === 0) { this.setOff() } } /** * Available GPIO Controls * */ let ctrls = { SW403: null, SW404: null, LED400: null, LED401: null, /** * Virtual GPIO Controller * Only Master-node can control the RemoteGpio module */ RemoteGpio: { LED400: new GpioCtrl(0), LED401: new GpioCtrl(0) } } if (settings.config.use.virtual_gpio) { ctrls.SW403 = new GpioCtrl(0, true) ctrls.SW404 = new GpioCtrl(0, true) ctrls.LED400 = new GpioCtrl(0, false) ctrls.LED401 = new GpioCtrl(0, false) } else { ctrls.SW403 = new GpioCtrl(settings.config.gpio.sw403, true) ctrls.SW404 = new GpioCtrl(settings.config.gpio.sw404, true) ctrls.LED400 = new GpioCtrl(settings.config.gpio.led400, false) ctrls.LED401 = new GpioCtrl(settings.config.gpio.led401, false) } /* link each button to led */ ctrls.SW403.on('pressed', function () { ctrls.LED400.setOn() }) ctrls.SW403.on('released', function () { ctrls.LED400.setOff() }) ctrls.SW404.on('pressed', function () { ctrls.LED401.setOn() }) ctrls.SW404.on('released', function () { ctrls.LED401.setOff() }) module.exports = ctrls
JavaScript
0.000001
@@ -1077,16 +1077,39 @@ e = null +%0A this.prev_value = -1 %0A%0A if ( @@ -1526,16 +1526,154 @@ %7D%0A%0A + if (self.prev_value === value) %7B%0A console.log('ignore invalid input')%0A return%0A %7D%0A%0A self.prev_value = value%0A%0A if
0c9ba236f42ab99489863256ca9dcded069508c0
Call code generation stub
backend.js
backend.js
// takes an IR function object and returns a list of Scratch blocks module.exports.compileFunction = function(func) { console.log("Compiling "+JSON.stringify(func)+"..."); var blockList = []; // add a procdef var spec = func.funcName; var inputs = []; var defaults = []; for(var i = 0; i < func.paramList.length; ++i) { if(func.paramList[i][1]) inputs.push(func.paramList[i][1]); else inputs.push("param"+i); defaults.push(defaultForType(func.paramList[i][0])); spec += " "+specifierForType(func.paramList[i][0]); } blockList.push(["procDef", spec, inputs, defaults, false]); for(var i = 0; i < func.code.length; ++i) { console.log(func.code[i]); } return blockList; } // fixme: stub function defaultForType(type) { console.log(type); return 0; } // fixme: stub function specifierForType(type) { return "%s"; }
JavaScript
0
@@ -673,24 +673,117 @@ c.code%5Bi%5D);%0A +%09%09if(code%5Bi%5D.type == %22call%22) %7B%0A%09%09%09// calling a (potentially foreign) function%0A%09%09%09// stub%0A%09%09%7D%0A %09%7D%0A%0A%09return
f9ae66f837cf3958584ffd664252dac1e65c2887
modify logic. @[email protected]
src/containers/test/QATest.js
src/containers/test/QATest.js
/** * @Author: [email protected] * @Date: 2017.3.1 下午 3:33 * @Desc: 公共组件 - QATest * @Name: QATest.js * @LifeCycle:http://www.tuicool.com/articles/nu6zInB */ import React, {Component, PropTypes} from "react"; import {Dimensions, ListView, StyleSheet, Text, View} from "react-native"; import {Actions} from "react-native-router-flux"; import TitleBar from "../../components/bar/TitleBar"; import Icon from "react-native-vector-icons/FontAwesome"; import * as actions from "../../../common/actions"; import {bindActionCreators} from "redux"; import {connect} from "react-redux"; const {height, width} = Dimensions.get('window'); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); class QATest extends Component { /** * 父组件传入的属性值 * @type {{style: *, account: *, name: *, isTrue: *, callback: *}} */ static propTypes = { style: View.propTypes.style, account: PropTypes.number, name: PropTypes.string, isTrue: PropTypes.bool, callback: PropTypes.func, }; /** * 父组件传入的数据 * @type {{data: {}}} */ static defaultProps = { data: {} }; /** * 构造函数 * @param props * @param context */ constructor(props, context) { console.log("QATest constructor()"); super(props, context); this.state = {}; } /** * 当前组件渲染次数 * @type {number} */ renderCount = 0; /** * 组件加载前 * 生命周期中仅被调用1次,可以使用SetState */ componentWillMount() { console.log("QATest componentWillMount()"); } /** * 组件加载后 * 生命周期中仅被调用1次,可以使用SetState * 用于网络请求和页面渲染 */ componentDidMount() { console.log("QATest componentDidMount()"); //this.props.actions.getQATestScenesList(); } /** * 父组件属性值变更监听 * 可以使用SetState * @param newProps */ componentWillReceiveProps(newProps) { console.log("QATest componentWillReceiveProps():, newProps"); } /** * 属性值/状态值变更后,是否需要刷新页面 * @param nextProps 是即将被设置的属性,旧的属性还是可以通过 this.props 来获取。 * @param nextState 表示组件即将更新的状态值。 * @returns {boolean} 默认true, 返回值决定是否需要更新组件,如果 true 表示需要更新,继续走后面的更新流程。 */ shouldComponentUpdate(nextProps, nextState) { let isUpdate = (this.props != nextProps) || (this.state != nextState); console.log("QATest shouldComponentUpdate():" , isUpdate); return isUpdate; } /** * 如果组件状态或者属性改变,并且shouldComponentUpdate返回为 true * @param nextProps 更新之后的属性 * @param nextState 更新之后的状态 */ componentWillUpdate(nextProps, nextState) { console.log("QATest componentWillUpdate()"); } /** * 更新完成界面之后通知 * @param prevProps 更新之前的属性 * @param prevState 更新之前的状态 * @returns {boolean} */ componentDidUpdate(prevProps, prevState) { console.log("QATest componentDidUpdate()"); } /** * 组件即将卸载前调用 * 在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等。 */ componentDidUnMount() { console.log("QATest componentDidUnMount()"); } onPress = ()=> { }; renderRow(rowData, sectionId, rowId) { return ( <View style={QATestStyles.btnList}> <Icon.Button name="star" backgroundColor="#aaa" onPress={() => { try { Actions[rowId]() } catch (e) { alert(e.message) } }}> <Text style={{fontFamily: 'Arial', fontSize: 15}}>{rowData}</Text> </Icon.Button> </View> ) } /** * 组件更新 * @returns {XML} */ render() { this.renderCount++; console.log("QATest render() renderCount:" , this.renderCount); return ( <View style={[QATestStyles.container,this.props.style]}> <TitleBar label="品质测试" labelStyle={{backgroundColor:"transparent",color:"black"}} leftView={<Icon.Button name="list-ul" size={25} color="#166AF6" backgroundColor="transparent" onPress={()=>{alert("click android logo")}}/>} rightView={<Icon.Button name="undo" size={25} color="#999" backgroundColor="transparent" onPress={()=>{alert("click share icon")}}/>} style={{height: 45}}/> <Text onPress={()=>{this.onPress()}}>{JSON.stringify(config)}</Text> <ListView enableEmptySections={true} dataSource={ds.cloneWithRows(this.props.state.data.test)} renderRow={this.renderRow} /> </View> ); } } const QATestStyles = StyleSheet.create({ container: { flex:1, }, scrollView: { width:width, height:height*2 }, btnList: { margin: 3, } }); /** * 把this.state关联到this.props.state * @param state * @returns {{state: *}} */ function mapStateToProps(state) { return { state: state.router } } /** * 把actions.user_info, dispatch通过type关联到一起 * @param dispatch * @returns {{actions: (A|B|M|N)}} */ function mapDispatchToProps(dispatch) { console.log("HomePage actions:, actions"); return { actions: bindActionCreators(actions, dispatch), } } /** * 把mapStateToProps, mapDispatchToProps绑定到MainRouter组件上 */ export default connect(mapStateToProps, mapDispatchToProps)(QATest);
JavaScript
0.000009
@@ -2282,16 +2282,18 @@ +// let isUp @@ -2351,24 +2351,72 @@ nextState);%0A + let isUpdate = this.state != nextState;%0A cons
9ff086fb8e16bd966ce6b1e4882aa09bf9192de3
change session variable
IssueTrackingSystem/app/template/user/userController.js
IssueTrackingSystem/app/template/user/userController.js
(function () { "use strict"; IssueTrackingSystem.controller('User', ['$scope', '$location', 'authentication', '$sessionStorage', function ($scope, $location, authentication, $sessionStorage) { $scope.loginUserInSystem = function (user) { authentication.loginUser(user) .then(function (loggedUser) { $sessionStorage.isAuthenticated = true; $sessionStorage.access_token = loggedUser.access_token; $sessionStorage.token_type = loggedUser.token_type; $sessionStorage.user = loggedUser.userName; $location.path('/'); }); }; $scope.registerUserInSystem = function (user) { authentication.registerUser(user) .then(function (registeredUser) { $sessionStorage.isAuthenticated = true; $sessionStorage.access_token = registeredUser.access_token; $sessionStorage.token_type = registeredUser.token_type; $sessionStorage.user = registeredUser.userName; $location.path('/'); }); }; $scope.logoutUser = function () { authentication.logout(); $location.path('/login'); }; }]); }());
JavaScript
0.000001
@@ -483,24 +483,29 @@ loggedUser. +data. access_token @@ -566,24 +566,29 @@ loggedUser. +data. token_type;%0A @@ -631,16 +631,20 @@ age.user +name = logge @@ -645,24 +645,29 @@ loggedUser. +data. userName;%0A @@ -697,32 +697,37 @@ location.path('/ +login ');%0A @@ -1052,16 +1052,21 @@ redUser. +data. access_t @@ -1139,16 +1139,21 @@ redUser. +data. token_ty @@ -1200,16 +1200,20 @@ age.user +name = regis @@ -1222,16 +1222,21 @@ redUser. +data. userName @@ -1278,16 +1278,24 @@ .path('/ +register ');%0A @@ -1445,34 +1445,35 @@ ation.path('/log -in +out ');%0A
19f60c48324a7454bfa127a623d638464c91632e
discard small images, less than 128 width or height
js/processImages.js
js/processImages.js
var IMAGES = new Array(0); /******************************************************************************/ function printImageSize(url, imageOverlay) { var image = new Image(); image.name = url; image.src = url; image.onload = function() { var size = this.width + 'x' + this.height; imageOverlay.append('<br/>Size: ' + size); }; } function backgroundHasURL(string) { var re = /(url\()(.*)(\))/; var array = re.exec(string); if(array) { var url = array[2]; return url; } return false; } function storeImage(url) { if(! url) return; var imgWrap = $('<div/>').attr('class', 'imageWrap'); var img = $('<img/>').attr('class', 'theImage') .attr('src', url) .appendTo(imgWrap); var imageOverlay = $('<div/>').attr('class', 'imageOverlay') .appendTo(imgWrap); var openLink = $('<a/>').attr('href', url) .attr('target', '_blank') .html('open') .appendTo(imageOverlay); printImageSize(url, imageOverlay); IMAGES.push(imgWrap); } function findBackgroundImage(element) { if($(element).attr('class') == 'spaceball') /* Flickr mask. */ return; var background = $(element).css('background'); var url = backgroundHasURL(background); storeImage(url); } function getImagesPanel() { var title = $('<a/>').attr('id', 'title') .attr('href', "http://github.com/givanse/cr24Sauce") .attr('target', '_blank') .html('cr24Sauce'); var imagesPanel = $('<div/>').attr('id', 'imagesPanel') .attr('class', 'ui-widget-content') .append(title) .append(IMAGES); imagesPanel.draggable(); return imagesPanel; } $(document).ready(function() { /* google.com */ $('div').each(function(index, element) { findBackgroundImage(element); }); /* flickr.com */ $('div#allsizes-photo img').each(function(index, img) { var url = $(img).attr('src'); storeImage(url); }); /* google.com */ $('meta').each(function(index, element) { var property = $(element).attr('property'); if(property != 'og:image') return; var url = $(element).attr('content'); storeImage(url); }); var imagesPanel = getImagesPanel(); var wrapper = $('<div/>').attr('id', 'cr24SauceWrapper') .append(imagesPanel); $(document.body).append(wrapper); }); /* EOF */
JavaScript
0
@@ -113,34 +113,56 @@ unction -printImageSize(url +onloadAddToOverlayImageSize(imageWrapper , imageO @@ -167,16 +167,21 @@ eOverlay +, url ) %7B%0A @@ -240,32 +240,37 @@ mage.src = url;%0A + %0A image.onload @@ -281,24 +281,255 @@ unction() %7B%0A + var minimumSize = 128;%0A if(this.width %3C= minimumSize %7C%7C this.height %3C= minimumSize) %7B%0A imageWrapper.parentNode.removeChild(imageWrapper);%0A return;%0A %7D%0A %0A @@ -958,19 +958,24 @@ var -img +theImage = $('%3Ci @@ -1228,16 +1228,21 @@ var open +Image Link = $ @@ -1432,26 +1432,46 @@ -printImageSize(url +onloadAddToOverlayImageSize(imgWrap%5B0%5D , im @@ -1472,32 +1472,37 @@ 0%5D, imageOverlay +, url );%0A%0A IMAGES.p @@ -1522,252 +1522,8 @@ %0A%7D%0A%0A -function findBackgroundImage(element) %7B%0A if($(element).attr('class') == 'spaceball') /* Flickr mask. */%0A return;%0A%0A var background = $(element).css('background');%0A var url = backgroundHasURL(background);%0A storeImage(url); %0A%7D%0A%0A func @@ -2083,34 +2083,51 @@ () %7B%0A /* -google.com +DIVs with background images */%0A $('d @@ -2175,13 +2175,111 @@ -findB +if($(element).attr('class') == 'spaceball') /* Flickr mask, skip. */%0A return;%0A%0A var b ackg @@ -2283,21 +2283,20 @@ ckground -Image + = $ (element @@ -2300,43 +2300,119 @@ ent) -;%0A %7D +.css('background' );%0A -%0A -/* flickr.com */ +var url = backgroundHasURL(background);%0A storeImage(url); %0A %7D);%0A %0A %0A @@ -2556,13 +2556,14 @@ /* -googl +youtub e.co
20493c549aa8f93d272375852899e69f669c5b21
Reverted to 9a49a6f7e6dbdad6d07ab6850847a9d254eeccb6
js/types/TNumber.js
js/types/TNumber.js
// Copyright 2016, University of Colorado Boulder /** * * @author Sam Reid (PhET Interactive Simulations) * @author Andrew Adare */ define( function( require ) { 'use strict'; // modules var assertTypeOf = require( 'PHET_IO/assertions/assertTypeOf' ); var phetioNamespace = require( 'PHET_IO/phetioNamespace' ); var phetioInherit = require( 'PHET_IO/phetioInherit' ); var TObject = require( 'PHET_IO/types/TObject' ); var validUnits = [ 'amperes', 'becquerels', 'centimeters', 'coulombs', 'degrees Celsius', 'farads', 'grams', 'gray', 'henrys', 'henries', 'hertz', 'joules', 'katals', 'kelvins', 'liters', 'liters/second', 'lumens', 'lux', 'meters', 'moles', 'moles/liter', 'nanometers', 'newtons', 'ohms', 'pascals', 'percent', 'radians', 'seconds', 'siemens', 'sieverts', 'steradians', 'tesla', 'unitless', 'volts', 'watts', 'webers' ]; var TNumber = function( units, options ) { assert && assert( units, 'All TNumbers should specify units' ); assert && assert( validUnits.indexOf( units ) >= 0, units + ' is not recognized as a valid unit of measurement' ); options = _.extend( { type: 'FloatingPoint', // either 'FloatingPoint' | 'Integer' min: -Infinity, // TODO: remove min and max in favor of keeping range only max: Infinity, range: new Range( -Infinity, Infinity ), // No defaultValue stepSize: null, // This will be used for slider increments values: null // null | {Number[]} if it can only take certain possible values, specify them here, like [0,2,8] // TODO: enforce that values is of Array type }, options ); return phetioInherit( TObject, 'TNumber(' + units + ')', function( instance, phetioID ) { TObject.call( this, instance, phetioID ); assertTypeOf( instance, 'number' ); }, {}, { units: units, type: options.type, min: options.range.min, max: options.range.max, values: options.values, stepSize: options.stepSize, defaultValue: options.range.defaultValue, documentation: 'Wrapper for the built-in JS number type (floating point, but also represents integers)', fromStateObject: function( stateObject ) { return stateObject; }, toStateObject: function( value ) { return value; } } ); }; phetioNamespace.register( 'TNumber', TNumber ); return TNumber; } );
JavaScript
0.998455
@@ -1355,225 +1355,31 @@ ity, - // TODO: remove min and max in favor of keeping range only%0A max: Infinity,%0A range: new Range( -Infinity, Infinity ), // No defaultValue%0A stepSize: null, // This will be used for slider increments +%0A max: Infinity, %0A @@ -1498,75 +1498,8 @@ ,8%5D%0A - // TODO: enforce that values is of Array type%0A @@ -1520,25 +1520,24 @@ ions%0A );%0A -%0A return p @@ -1786,22 +1786,16 @@ options. -range. min,%0A @@ -1810,22 +1810,16 @@ options. -range. max,%0A @@ -1849,90 +1849,8 @@ es,%0A - stepSize: options.stepSize,%0A defaultValue: options.range.defaultValue,%0A
890d25e8f9b483e0ff3fab4af5d1c244ae00e32c
Add decodeDict, all tests pass
bencode.js
bencode.js
/* Future possibilities: * It would be cool if this thing * actually emitted pieces of bdecoded * shit along the way. eg, the * torrent client could listen for the infohash * key, name key, and update its internal * data while it's still parsing the rest * of the file. * * This would also allow only one copy of * the data to be in memory, + the size of a chunk. */ // In order to make it not be recursive, we simply can setTimeout 0 callback our way through. var fs = require('fs'), Q = require('q'), is = require('is-js'), async = require('async'); exports.bdecode = function(fileOrData, callback) { // Todo, stream instead of read all data at once, especially if it's a file. Allow stream as an argument return Q.fcall(function() { if(Buffer.isBuffer(fileOrData)) { return fileOrData.toString(); } else if(typeof fileOrData == 'string') { return fileOrData; } else { // Doesn't work, async fs.readFile(fileOrData, function(err, res) { if(err) throw new Error(err); return res.toString(); }); } }) .then(bdecodeData); }; function bdecodeData(val) { var deferred = Q.defer(); var out = []; var myNdx = 0; async.whilst( function() { return myNdx < val.length; }, function(callback) { decodeElement(val, myNdx) .then(function(val) { out.push(val.obj); myNdx = val.ndx; callback(null); }) .fail(callback); }, function(err) { if(err) deferred.fail(err); else deferred.resolve(out); } ); return deferred.promise; } function decodeInt(str, ndx) { var deferred = Q.defer(); //assert(str[ndx] == 'i'); ndx++; var num = 0; for(; str[ndx] !== 'e'; ndx++) { num *= 10; num += parseInt(str[ndx], 10); } ndx++; // 'e' deferred.resolve({ndx: ndx, obj: num}); return deferred.promise; } function decodeStr(str, ndx) { var deferred = Q.defer(); var out = ''; var strlen = 0; for(; str[ndx] !== ':'; ndx++) { strlen *= 10; strlen += parseInt(str[ndx], 10); } ndx++; //bypass : for(var i = 0; i < strlen; i++, ndx++) { out += str[ndx]; } deferred.resolve({ndx: ndx, obj: out}); return deferred.promise; } function decodeList(str, ndx) { var deferred = Q.defer(); //assert(str[ndx] === 'l') ndx++; // 'l' var list = []; async.whilst( function() { return str[ndx] !== 'e'; }, function(cb) { decodeElement(str, ndx) .then(function(res) { list.push(res.obj); ndx = res.ndx; cb(null); }) .fail(function(err) { cb(err); }); }, function(err) { if(err) deferred.fail(err); else deferred.resolve({ndx: ndx + 1, obj: list}); // +1 because of the 'e' } ); return deferred.promise; } // Return format: {ndx: newNdx, obj: objDecoded} function decodeElement(str, ndx) { if(str[ndx] === 'i') { return decodeInt(str, ndx); } else if(str[ndx] === 'l') { return decodeList(str, ndx); } else if(str[ndx] === 'd') { return decodeDict(str, ndx); } else { return decodeStr(str, ndx); } }
JavaScript
0
@@ -2838,16 +2838,627 @@ ise;%0A%7D%0A%0A +function decodeDict(str, ndx) %7B%0A var deferred = Q.defer();%0A //assert(str%5Bndx%5D == 'd')%0A ndx++; //d%0A var dict = %7B%7D;%0A async.whilst(%0A function() %7B%0A return str%5Bndx%5D !== 'e';%0A %7D,%0A function(cb) %7B%0A decodeElement(str, ndx)%0A .then(function(keyRes) %7B%0A decodeElement(str, keyRes.ndx)%0A .then(function(valRes) %7B%0A ndx = valRes.ndx;%0A dict%5BkeyRes.obj%5D = valRes.obj;%0A cb(null);%0A %7D);%0A %7D);%0A %7D,%0A function(err) %7B%0A if(err) deferred.fail(err);%0A else deferred.resolve(%7Bndx: ndx + 1, obj: dict%7D);%0A %7D%0A );%0A%0A return deferred.promise;%0A%7D%0A%0A // Retur
0cd1962fe040cbb2035aab186401e7d8296f7afc
fix live cat
bin/cat.js
bin/cat.js
var stdout = require('stdout-stream') var multistream = require('multistream') var eos = require('end-of-stream') module.exports = function(dat, opts, cb) { if (!opts) opts = {} if (!opts.f && !opts.json) opts.json = true var readStream = dat.createReadStream(opts) if (opts.live) { var changes = dat.createChangesReadStream({ since: dat.storage.change, data: true, decode: true, live: true }) var format = through.obj(function(data, enc, cb) { cb(null, data.value) }) readStream = multistream([readStream, pump(changes, format, ldj.serialize())]) } readStream.pipe(stdout) eos(readStream, cb) }
JavaScript
0.000003
@@ -106,16 +106,112 @@ stream') +%0Avar through = require('through2')%0Avar ldj = require('ldjson-stream')%0Avar pump = require('pump') %0A%0Amodule
9c6ab78be95eb1f40361e286d95f358eaf430237
Refactor nuts.js for new refactored apiFactories
src/nuts.js
src/nuts.js
'use strict' // Resolve document // - extract template tags from html document // - add templates into schemas archive // - add filters into filters archive // - add behaviours into behaviours archive // - set behaviours into templates // - make partials (with extend.js) // - retrieve data from regular html and generate and assign instances // - enjoy import { addTemplatesFactory, addBehaviourFactory, addFiltersFactory, addFilterFactory, setBehavioursFactory } from './api-factories.js' let api = {}, schemas = new Map(), behaviours = new Map(), filtersArchive = new Map(), queue = [] function resolveDocument () { setBehaviours() } function next () { if (queue.length) { queue.shift()() } else { resolveDocument() } } let addTemplates = addTemplatesFactory(schemas, next), addBehaviour = addBehaviourFactory(behaviours, next), addFilter = addFilterFactory(filtersArchive, next), addFilters = addFiltersFactory(filtersArchive, next), setBehaviours = setBehavioursFactory(behaviours, schemas, next) api.addTemplates = function (templates) { queue.push(() => addTemplates(templates)) return api } api.addBehaviour = function (templateName, behaviour) { queue.push(() => addBehaviour(templateName, behaviour)) return api } api.addFilter = function (filterName, filter) { queue.push(() => addFilter(filterName, filter)) return api } api.addFilters = function (filters) { queue.push(() => addFilters(filters)) return api } api.resolve = function (callback) { queue.push(() => resolveDocument(callback)) } export default api
JavaScript
0
@@ -361,129 +361,28 @@ ort -%7B%0A addTemplatesFactory,%0A addBehaviourFactory,%0A addFiltersFactory,%0A addFilterFactory,%0A setBehavioursFactory%0A%7D +apiFactories from '. /api @@ -377,16 +377,21 @@ from '. +./src /api-fac @@ -677,115 +677,44 @@ let -addTemplates = addTemplatesFactory(schemas, next),%0A addBehaviour = addBehaviourFactory(behaviours, next) +%7B%0A addTemplates,%0A addBehaviour ,%0A @@ -724,18 +724,21 @@ ddFilter +,%0A -= addFilt @@ -743,156 +743,82 @@ lter -Factory(filtersArchive, next),%0A addFilters = addFiltersFactory(filtersArchive, next),%0A setBehaviours = setBehavioursFactory(behaviours, schema +s,%0A setBehaviours%0A %7D = apiFactories(schemas, filtersArchive, behaviour s, n
b2951b8d70c717d05921526e8b84e9c8307131f2
Use cluestr token.
lib/provider-google-contact/handlers/upload.js
lib/provider-google-contact/handlers/upload.js
'use strict'; var request = require('request'); var async = require('async'); var retrieve = require('../helpers/retrieve.js'); var Token = require('../models/token.js'); var config = require('../../../config/configuration.js'); var CluestrOauth = require('../helpers/cluestr-oauth.js'); var cluestrOauth = new CluestrOauth(config.cluestr_id, config.cluestr_secret); // Upload `contacts` onto cluestr, then call `cb`. var account_upload = function(contacts, accessToken, cb) { cluestrOauth.setAccessToken(accessToken); var stack = contacts.map(function(contact) { // Build contact "the right way" contact = { identifier: contact.id, metadatas: contact }; return async.apply(cluestrOauth.sendDocument, contact); }); // Skip when testing if(process.env.NODE_ENV === 'test') { return cb(); } async.parallel(stack, cb); }; // Sync all contacts from all users to Cluestr. // Note: only the contacts modified since last run will be uploaded module.exports = function (cb) { var updateTokenAccess = function(token, date, cb) { token.lastAccess = date; token.save(function(err) { if(err) { throw err; } cb(); }); }; Token.find({}, function(err, tokens) { if(err) { throw err; } // Build query stack var stack = []; tokens.forEach(function(token) { stack.push(function(cb) { // Download contacts datas, and upload them retrieve(token.googleToken, token.lastAccess, function(contacts) { // Once the users have been retrieved, // Store the current date -- we'll write this onto token.lastAccess if the upload runs smoothly. var currentDate = new Date(); account_upload(contacts, '', function() { updateTokenAccess(token, currentDate, cb); }); }); }); }); // Real run async.parallel(stack, cb); }); };
JavaScript
0
@@ -1756,10 +1756,26 @@ ts, -'' +token.cluestrToken , fu
2540243a15d8db5770507df84aeabfddb4b253bc
Add logging in case pass invocation fails.
src/pass.js
src/pass.js
"use strict"; const { spawn } = require("sdk/system/child_process"); const { env } = require('sdk/system/environment'); module.exports = { /** * Test if the pass utility is installed and configured. * * @returns Promise - A promise that resolves if the utility is in use, * rejects otherwise. */ isAvailable: function() { return this._spawn(); }, /** * Retrieves an updated list of passwords from 'pass'. * * @returns Promise - A promise that resolves with an array of item names or * rejects if an error occurs. */ listPasswords: function() { return this._spawn().then(output => { return output.split("\n") .filter(item => item.startsWith("|-- ")) // only take the toplevel items .map(item => item.split("|-- ")[1]); }); }, /** * Spawns the pass utility with given parameters. * * @param {Array} parameters - The command line parameters to call 'pass' with. * * @returns Promise - A promise that resolves with the stdout contents if the * process exits with status 0 and rejects with stderr contents if the exit * status is non-zero. */ _spawn: function(parameters) { try { let stdout = ""; let stderr = ""; let process = spawn("/usr/bin/pass", parameters || [], { env: { "PATH": env.PATH, "HOME": env.HOME, } }); process.stdout.on("data", s => stdout += s); process.stderr.on("data", s => stderr += s); return new Promise((resolve, reject) => { process.on("close", status => { if (status === 0) { resolve(stdout); } else { reject(stderr); } }); }); } catch (e) { return Promise.reject(e); } } };
JavaScript
0
@@ -1650,16 +1650,216 @@ else %7B%0A + console.error(%22pass exited with code %22 + status);%0A console.log(%22stdout:%22);%0A console.log(stdout);%0A console.log(%22stderr:%22);%0A console.log(stderr);%0A
65ca6012c16f532406213fd4450ec470280772d4
clean up cli
bin/cli.js
bin/cli.js
#!/usr/bin/env node var path = require('path'); var utils = require('../lib/utils'); var Env = require('../lib/env'); // parse argv (TODO: yargs!) var argv = require('minimist')(process.argv.slice(2), { alias: { help: 'h', verbose: 'v' } }); /** * Run generate */ function run(cb) { var baseEnv = createEnv(path.resolve(__dirname, '..')); var Generate = require(baseEnv.module.path); // pre-process command line arguments var args = utils.expandArgs(argv); var base = new Generate(); base.env = baseEnv; base.fn = baseEnv.config.fn; base.option(args); var env = createEnv(process.cwd()); var config = env.config.fn; var app = null; // we have an instance of `Generate` if (utils.isObject(config) && config.isGenerate) { app = config; app.env = env; app.option(args); app.register('base', base.fn, env); app.parent = base; // we have a "generator" function } else { app = new Generate(); app.env = env; app.option(args); app.register('base', base.fn, env); app.parent = base; // register local `generator.js` if it exists if (typeof config === 'function') { app.fn = config; app.register(env.config.alias, config, env); // console.log(app.generators[env.config.alias]) } } /** * Support `--emit` for debugging * Examples: * * # emit views as they're loaded * $ --emit view * * # emit errors * $ --emit error */ if (args.emit && typeof args.emit === 'string') { app.on(args.emit, console.log.bind(console)); } /** * Listen for generator configs, and register them * as they're emitted */ app.env.on('config', function(name, env) { app.register(name, env.config.fn, env); }); app.env.resolve('generate-*/generator.js', { cwd: utils.gm }); cb(null, app); } /** * Run generators and their tasks */ run(function(err, app) { if (err) throw err; app.on('error', function(err) { console.error(err); }); app.build(argv, function(err, cb) { if (err) { console.error(err); process.exit(1); } utils.timestamp('finished'); process.exit(0); }); }); function createEnv(cwd) { var env = new Env('generator.js', 'generate', cwd);; env.module.path = utils.tryResolve('generate'); return env; }
JavaScript
0
@@ -669,24 +669,33 @@ null;%0A%0A // + If true, we have an @@ -854,35 +854,32 @@ 'base', base -.fn , env);%0A app.pare @@ -870,36 +870,22 @@ v);%0A +%0A - app.parent = base;%0A%0A // +// If true, we @@ -1023,41 +1023,15 @@ base -.fn , env); -%0A app.parent = base; %0A%0A @@ -1196,59 +1196,8 @@ v);%0A - // console.log(app.generators%5Benv.config.alias%5D)%0A
5d9d93f86d3b5e67b136891f3fab29e6a1f2e8ce
command line program output valid JSON
bin/cmd.js
bin/cmd.js
#!/usr/bin/env node var fs = require('fs') var parseTorrent = require('../') function usage () { console.error('Usage: parse-torrent /path/to/torrent') } var torrentPath = process.argv[2] if (!torrentPath) { return usage() } try { var parsedTorrent = parseTorrent(fs.readFileSync(torrentPath)) } catch (err) { console.error(err.message + '\n') usage() } delete parsedTorrent.info delete parsedTorrent.infoBuffer console.dir(parsedTorrent)
JavaScript
0.999817
@@ -434,22 +434,52 @@ ole. -dir(parsedTorrent +log(JSON.stringify(parsedTorrent, undefined, 2) )
2df6e68dc3b28153070a627ff1f2332d971d8427
Standardify cmd.js
bin/cmd.js
bin/cmd.js
#!/usr/bin/env node var opts = require('../options.js') require('standard-engine').cli(opts) process.on('exit', function (status) { if (status === 0) { console.log(require('fs').readFileSync(__dirname + '/../seal.ans').toString()) }else{ console.log('The president cannot endorse this code.') } })
JavaScript
0.999903
@@ -239,12 +239,14 @@ %0A %7D + else + %7B%0A
09586f1bdaa050e484f8a4068bf2e0d49faccb50
Fix getter and setter to use object instead of D3 map.
src/plot.js
src/plot.js
/* * Generic plot class to hold attributes and allow the creation of concrete * plots from a single set of data and parameters. * */ viz.Plot = function(data, attrs) { // TODO Track the type of data? if (data === undefined) { throw "missing parameter: data"; } if (attrs === undefined) { attrs = {} } this._attrs = viz.util.extend( viz.plots.defaultAttrs, attrs); this._attrs.selection = d3.select(this._attrs.selector) .append('svg'); this._attrs.plotData = data; // Create scales // TODO This shouldn't be here in case data aren't just xy var xMin = d3.min(data, function(d) { return d.x; }); var xMax = d3.max(data, function(d) { return d.x; }); var xDim = xMax - xMin; this._attrs.xScale = d3.scale[this._attrs.xScaleType]() .domain([xMin - this._attrs.xOffset * xDim, xMax + this._attrs.xOffset * xDim]) .range([this._attrs.plotPadding[3], this._attrs.plotWidth - this._attrs.plotPadding[1]]); var yMin = d3.min(data, function(d) { return d.y; }); var yMax = d3.max(data, function(d) { return d.y; }); var yDim = yMax - yMin; this._attrs.yScale = d3.scale[this._attrs.yScaleType]() .domain([yMin - this._attrs.yOffset * yDim, yMax + this._attrs.yOffset * yDim]) .range([this._attrs.plotHeight - this._attrs.plotPadding[2], this._attrs.plotPadding[0]]); } viz.Plot.prototype = { setAttr: function(a, v) { this._attr.set(a, v) return this; }, getAttr: function(a) { return this._attrs.get(a); }, updateAttrs: function(attrs) { this._attrs = viz.util.extend(this._attrs, attrs); return this; }, attr: function(a, v) { if (v === undefined) { return this.getAttr(a); } else { return this.setAttr(a, v); } }, create: function(type) { return new (viz.plots.registered[type])(this._data, this._attrs); } } viz.plots.defaultAttrs = { selector: "body", // Title plotTitle: undefined, plotTitleSize: 22, plotTitleFontFamily: "sans-serif", // Subtitle plotSubtitle: undefined, plotSubtitleSize: 16, plotSubtitleFontFamily: "sans-serif", // Dimensions plotWidth: 600, plotHeight: 300, plotPadding: [50, 50, 50, 50], xOffset: 0.25, yOffset: 0.25, // Grid lines xGridLines: undefined, yGridLines: undefined, gridLines: 10, xGridLineWidth: undefined, yGridLineWidth: undefined, gridLineWidth: 1, xGridLineColor: undefined, yGridLineColor: undefined, gridLineColor: "#000", xGridLineType: undefined, yGridLineType: undefined, gridLineType: "dotted", // Scales xScaleType: 'linear', yScaleType: 'linear', // Axes xAxis: undefined, yAxis: undefined, axes: undefined, xAxisTicks: undefined, yAxisTicks: undefined, axesTicks: undefined, xAxisTickSize: undefined, yAxisTickSize: undefined, axesTickSize: 5, xAxisTickWidth: undefined, yAxisTickWidth: undefined, axesTickWidth: 1, xAxisTickColor: undefined, yAxisTickColor: undefined, axesTickColor: '#000', xAxisTickType: undefined, yAxisTickType: undefined, axesTickType: 'solid', xAxisLineWidth: undefined, yAxisLineWidth: undefined, axesLineWidth: undefined, xAxisLineColor: undefined, yAxisLineColor: undefined, axesLineColor: undefined, xAxisLineType: undefined, yAxisLineType: undefined, axesLineType: undefined, } /* * Concrete plots can inject their own custom attribute defaults to avoid * having to deal with them separately. Overriding global defaults is not * allowed. * */ viz.plots.registered = {}; viz.plots.register(name, plotClass) { viz.plots.defaultAttrs = viz.util.merge( plotClass.defaultAttrs, viz.plots.defaultAttrs); viz.plots.registered[name] = plotClass; }
JavaScript
0
@@ -1552,18 +1552,17 @@ attr -.set(a, v) +s%5Ba%5D = v; %0A @@ -1643,15 +1643,11 @@ ttrs -.get(a) +%5Ba%5D ;%0A
cb7b61f9d3f1cf15e0a6d4e9f5905ebb11786660
Fix post attachment
src/post.js
src/post.js
import moment from 'moment' export function postAttachment (post, extended) { let { commentsCount, postLikesCount, spoiler, nsfw, createdAt, editedAt, user, targetUser, targetGroup, media } = post let text = '' let fields = [] let title_link = process.env.KITSU_HOST + '/posts/' + post.id let title = 'Post by ' + user.name title += targetUser ? `to ${targetUser.name}` : '' title += targetGroup ? `to ${targetGroup.name}` : '' let fallback = title + ' - ' + title_link nsfw = (targetGroup && targetGroup.nsfw) || nsfw if (nsfw) { text += ':smirk: [NSFW]' fallback += '\n[NSFW]' } if (spoiler) { text += '\n:exclamation: [SPOILER]' fallback += '\n[SPOILER]' if (media) { text += ` - <https://kitsu.io/${media.type}/${media.slug}|${media.canonicalTitle}>` fallback += ` - ${media.canonicalTitle}` } } if (!spoiler && !nsfw && post.content) { text = post.content fallback += `\n${post.content}` } if (commentsCount) { fields.push({ title: ':speech_balloon: Comments', value: commentsCount, short: true }) fallback += `\nComments: ${commentsCount}` } if (postLikesCount) { fields.push({ title: ':heart: Likes', value: postLikesCount, short: true }) fallback += `\nLikes: ${postLikesCount}` } if (createdAt) { let time = moment.utc(createdAt).fromNow() fields.push({ title: ':clock3: Posted', value: time, short: true }) fallback += `\nPosted: ${time}` } if (editedAt) { let time = moment.utc(editedAt).fromNow() fields.push({ title: ':pencil2: Edited', value: time, short: true }) fallback += `\nEdited: ${time}` } let attachment = { color: '#F65440', mrkdwn_in: ['text'], callback_id: post.id, title, title_link, text, thumb_url: user.avatar ? user.avatar.medium : null, fields, fallback, footer: 'Kitsu API', footer_icon: 'https://kitsu-slack.herokuapp.com/icon.png', ts: moment().unix() // actions: [{ // name: 'post', // text: '', // type: 'button' // }] } return attachment }
JavaScript
0
@@ -392,24 +392,25 @@ rgetUser ? %60 + to $%7BtargetU @@ -451,16 +451,17 @@ roup ? %60 + to $%7Btar @@ -746,135 +746,379 @@ '%0A +%7D%0A%0A if ( -media) %7B%0A text += %60 - %3Chttps://kitsu.io/$%7Bmedia.type%7D/$%7Bmedia.slug%7D%7C$%7Bmedia.canonical +!spoiler && !nsfw && post.content) %7B%0A text = post.content%0A fallback += %60%5Cn$%7Bpost.content%7D%60%0A %7D%0A%0A if (media) %7B%0A let type = media.type.charAt(0).toUpperCase() + media.type.slice(1)%0A let mediaTitle = (type === 'Anime' ? ':tv: ' : ':orange_book: ') + type%0A fields.push(%7B%0A title: media Title -%7D%3E%60 +, %0A -fallback += %60 - +value: %60%3Chttps://kitsu.io/$%7Btype%7D/$%7Bmedia.slug%7D%7C $%7Bme @@ -1140,121 +1140,87 @@ tle%7D -%60 +%3E%60, %0A -%7D%0A %7D%0A%0A if (!spoiler && !nsfw && post.content) %7B%0A text = post.content%0A fallback += %60%5Cn$%7Bpost.content + short: true%0A %7D)%0A fallback += %60%5Cn$%7Btype%7D: $%7Bmedia.canonicalTitle %7D%60%0A
ddd49d0111e5ef1a645aee7b3101c6569b366351
Improve CLI
bin/cli.js
bin/cli.js
#!/usr/bin/env node var blake = require('../lib/blake.js') ;(function () { var arg = process.argv.splice(2) , isValid = !(arg && arg.length >= 2) if (isValid) { return console.error('Usage: blake source_directory target_directory [source_file ...]'); } var source = arg.shift() , target = arg.shift() , files = arg blake(source, target, files, function (err) { if (err) return console.error(err) console.log('blake OK') }).on('item', function (item) { console.log('blake WRITE %s', item.path) }) })()
JavaScript
0.000004
@@ -272,109 +272,43 @@ %0A -var source = arg.shift()%0A , target = arg.shift()%0A , files = arg%0A%0A%0A blake(source, target, files +blake(arg.shift(), arg.shift(), arg , fu @@ -378,22 +378,16 @@ le.log(' -blake OK')%0A %7D @@ -413,24 +413,24 @@ on (item) %7B%0A + console. @@ -437,26 +437,8 @@ log( -'blake WRITE %25s', item
ca117fa990fdce0863ffbd9ffa52b2c9afc284d4
validate all translations exist
modules/gui-react/frontend/config-overrides.js
modules/gui-react/frontend/config-overrides.js
module.exports = function override(config, env) { // const fs = require('fs') // const _ = require('lodash') // const flat = require('flat') // const locales = fs.readdirSync('src/locale').filter((name) => /^[^\\.]/.test(name)) // const messages = {} // // locales.map((locale) => // messages[locale] = require(`locale/${locale}/translations.json`) // ) // // _.chain(locales) // .map((locale) => require(`locale/${locale}/translations.json`)) // .map((messages) => // _.chain(flat.flatten(messages)) // .pickBy(_.identity) // .keys() // .value()) // .tap(console.log) // .intersectionBy() // .tap(console.log) // .value() configureCssModuleLoader(config.module.rules) return config; function configureImportsLoaders(importsLoaders) { Object.keys(importsLoaders).forEach(path => config.module.rules = (config.module.rules || []).concat({ test: require.resolve(path), enforce: 'pre', use: 'imports-loader?' + importsLoaders[path] }) ) } /** * Find the /\.css$/ matching rule with a css-loader. * Exclude /\.module\.css$/. * Clone it to match /\.module\.css$/, and enable module support. */ function configureCssModuleLoader(o) { if (o instanceof Array) return o.find((item, i) => { if (item instanceof Object && 'test' in item && String(item.test) === '/\\.css$/') { const cssLoader = findCssLoader(item) if (cssLoader) { const loaders = o const globalCssConfig = item const moduleCssConfig = JSON.parse(JSON.stringify(globalCssConfig)) globalCssConfig.exclude = /\.module\.css$/ moduleCssConfig.test = /\.module\.css$/ loaders.splice(i, 0, moduleCssConfig) const cssModuleLoader = findCssLoader(moduleCssConfig) cssModuleLoader.options.modules = true cssModuleLoader.options.localIdentName = '[name]__[local]___[hash:base64:5]' return globalCssConfig } else return null } else configureCssModuleLoader(item) }) else if (o instanceof Object) return Object.keys(o).find((key) => configureCssModuleLoader(o[key])) else return null } function findCssLoader(o) { if (o instanceof Array) { return o .map((item) => findCssLoader(item)) .filter((item) => item) .find((item) => item) } else if (o instanceof Object) { if ('loader' in o && o.loader.indexOf('/css-loader/') > -1) return o else return Object.keys(o).map((key) => findCssLoader(o[key])) .filter((item) => item) .find((item) => item) } else return null } }
JavaScript
0.000298
@@ -777,16 +777,664 @@ ()%0A %0A + const fs = require('fs')%0A const _ = require('lodash')%0A const flat = require('flat')%0A const locales = fs.readdirSync('src/locale').filter((name) =%3E /%5E%5B%5E%5C%5C.%5D/.test(name))%0A %0A const keys = _.chain(locales)%0A .map((locale) =%3E require(%60./src/locale/$%7Blocale%7D/translations%60))%0A .map((messages) =%3E%0A _.chain(flat.flatten(messages))%0A .pickBy(_.identity)%0A .keys()%0A .value())%0A .value()%0A %0A const incompleteKeys = _.difference(_.union(...keys), _.intersection(...keys))%0A if (incompleteKeys)%0A throw %60Missing translations: %5Cn$%7BincompleteKeys.join('%5Cn')%7D%60 %0A%0A co @@ -1498,9 +1498,8 @@ nfig -; %0A%0A
5919c08b761629e411b39b4ea648e77e63a1dde9
Update text.js
src/text.js
src/text.js
(function(Two) { var root = this; var getComputedMatrix = Two.Utils.getComputedMatrix; var _ = Two.Utils; var canvas = (root.document ? root.document.createElement('canvas') : { getContext: _.identity }); var ctx = canvas.getContext('2d'); var Text = Two.Text = function(message, x, y, styles) { Two.Shape.call(this); this._renderer.type = 'text'; this._renderer.flagFill = _.bind(Text.FlagFill, this); this._renderer.flagStroke = _.bind(Text.FlagStroke, this); this.value = message; if (_.isNumber(x)) { this.translation.x = x; } if (_.isNumber(y)) { this.translation.y = y; } if (!_.isObject(styles)) { return this; } _.each(Two.Text.Properties, function(property) { if (property in styles) { this[property] = styles[property]; } }, this); }; _.extend(Two.Text, { Properties: [ 'value', 'family', 'size', 'leading', 'alignment', 'linewidth', 'style', 'weight', 'decoration', 'baseline', 'opacity', 'visible', 'fill', 'stroke' ], FlagFill: function() { this._flagFill = true; }, FlagStroke: function() { this._flagStroke = true; }, MakeObservable: function(object) { Two.Shape.MakeObservable(object); _.each(Two.Text.Properties.slice(0, 12), Two.Utils.defineProperty, object); Object.defineProperty(object, 'fill', { enumerable: true, get: function() { return this._fill; }, set: function(f) { if (this._fill instanceof Two.Gradient || this._fill instanceof Two.LinearGradient || this._fill instanceof Two.RadialGradient || this._fill instanceof Two.Texture) { this._fill.unbind(Two.Events.change, this._renderer.flagFill); } this._fill = f; this._flagFill = true; if (this._fill instanceof Two.Gradient || this._fill instanceof Two.LinearGradient || this._fill instanceof Two.RadialGradient || this._fill instanceof Two.Texture) { this._fill.bind(Two.Events.change, this._renderer.flagFill); } } }); Object.defineProperty(object, 'stroke', { enumerable: true, get: function() { return this._stroke; }, set: function(f) { if (this._stroke instanceof Two.Gradient || this._stroke instanceof Two.LinearGradient || this._stroke instanceof Two.RadialGradient || this._stroke instanceof Two.Texture) { this._stroke.unbind(Two.Events.change, this._renderer.flagStroke); } this._stroke = f; this._flagStroke = true; if (this._stroke instanceof Two.Gradient || this._stroke instanceof Two.LinearGradient || this._stroke instanceof Two.RadialGradient || this._stroke instanceof Two.Texture) { this._stroke.bind(Two.Events.change, this._renderer.flagStroke); } } }); Object.defineProperty(object, 'clip', { enumerable: true, get: function() { return this._clip; }, set: function(v) { this._clip = v; this._flagClip = true; } }); } }); _.extend(Two.Text.prototype, Two.Shape.prototype, { // Flags // http://en.wikipedia.org/wiki/Flag _flagValue: true, _flagFamily: true, _flagSize: true, _flagLeading: true, _flagAlignment: true, _flagBaseline: true, _flagStyle: true, _flagWeight: true, _flagDecoration: true, _flagFill: true, _flagStroke: true, _flagLinewidth: true, _flagOpacity: true, _flagVisible: true, _flagClip: false, // Underlying Properties _value: '', _family: 'sans-serif', _size: 13, _leading: 17, _alignment: 'center', _baseline: 'middle', _style: 'normal', _weight: 500, _decoration: 'none', _fill: '#000', _stroke: 'transparent', _linewidth: 1, _opacity: 1, _visible: true, _clip: false, remove: function() { if (!this.parent) { return this; } this.parent.remove(this); return this; }, clone: function(parent) { var parent = parent || this.parent; var clone = new Two.Text(this.value); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Text.Properties, function(property) { clone[property] = this[property]; }, this); if (parent) { parent.add(clone); } return clone; }, toObject: function() { var result = { translation: this.translation.toObject(), rotation: this.rotation, scale: this.scale }; _.each(Two.Text.Properties, function(property) { result[property] = this[property]; }, this); return result; }, noStroke: function() { this.stroke = 'transparent'; return this; }, noFill: function() { this.fill = 'transparent'; return this; }, /** * A shim to not break `getBoundingClientRect` calls. TODO: Implement a * way to calculate proper bounding boxes of `Two.Text`. */ getBoundingClientRect: function(shallow) { var matrix, border, l, x, y, i, v; var left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity; // TODO: Update this to not __always__ update. Just when it needs to. this._update(true); matrix = !!shallow ? this._matrix : getComputedMatrix(this); v = matrix.multiply(0, 0, 1); return { top: v.x, left: v.y, right: v.x, bottom: v.y, width: 0, height: 0 }; }, flagReset: function() { this._flagValue = this._flagFamily = this._flagSize = this._flagLeading = this._flagAlignment = this._flagFill = this._flagStroke = this._flagLinewidth = this._flagOpaicty = this._flagVisible = this._flagClip = this._flagDecoration = this._flagBaseline = false; Two.Shape.prototype.flagReset.call(this); return this; } }); Two.Text.MakeObservable(Two.Text.prototype); })((typeof global !== 'undefined' ? global : this).Two);
JavaScript
0.000002
@@ -25,19 +25,99 @@ root = t -his +ypeof window != 'undefined' ? window : typeof global != 'undefined' ? global : null ;%0A var
36a48a4f32629e3b283a44ec4ea8af91194f7d48
Add partition function.
src/udon.js
src/udon.js
Udon = (typeof Udon === 'undefined') ? {} : Udon; Udon.foldl = function(fn, z, xs) { var len = xs.length, i; for (i = 0; i < len; i++) z = fn(z, xs[i]); return z; }; Udon.foldr = function(fn, z, xs) { var i = xs.length; while (i--) z = fn(xs[i], z); return z; }; Udon.map = function(fn, xs) { var ys = [], i = xs.length; while (i--) ys[i] = fn(xs[i]); return ys; }; Udon.filter = function(fn, xs) { var ys = [], len = xs.length, i, e; for (i = 0; i < len; i++) { e = xs[i]; if (fn(e)) ys.push(e); } return ys; }; Udon.unfoldr = function(step, seed) { var output = [], result; while (result = step(seed)) { output.push(result[0]); seed = result[1]; } return output; }; Udon.zipWith = function(fn, xs, ys) { var xsl = xs.length, ysl = ys.length, len = xsl > ysl ? ysl : xsl, zs = [], i; for (i = 0; i < len; i++) zs[i] = fn(xs[i], ys[i]); return zs; }; Udon.zip = function(xs, ys) { return Udon.zipWith(function(x, y) { return [x, y]; }); };
JavaScript
0.000001
@@ -575,24 +575,226 @@ urn ys;%0A%7D;%0A%0A +Udon.partition = function(fn, xs) %7B%0A var ts = %5B%5D, fs = %5B%5D, len = xs.length, i, e;%0A for (i = 0; i %3C len; i++) %7B%0A e = xs%5Bi%5D;%0A (fn(e) ? ts : fs).push(e);%0A %7D%0A return %5Bts, fs%5D;%0A%7D;%0A%0A Udon.unfoldr
ae1f5c9e67920fe1f4b76e87493a2e822e872c9e
Check for primitiveness before attempting to define a property
src/util.js
src/util.js
"use strict"; var global = require("./global.js"); var ASSERT = require("./assert.js"); var es5 = require("./es5.js"); var haveGetters = (function(){ try { var o = {}; es5.defineProperty(o, "f", { get: function () { return 3; } }); return o.f === 3; } catch (e) { return false; } })(); var canEvaluate = (function() { //Cannot feature detect CSP without triggering //violations //So assume CSP if environment is browser. This is reasonable //because promise throughput doesn't matter in browser and //promisifcation is mostly interesting to node.js anyway if (typeof window !== "undefined" && window !== null && typeof window.document !== "undefined" && typeof navigator !== "undefined" && navigator !== null && typeof navigator.appName === "string" && window === global) { return false; } return true; })(); function deprecated(msg) { if (typeof console !== "undefined" && console !== null && typeof console.warn === "function") { console.warn("Bluebird: " + msg); } } var errorObj = {e: {}}; //Try catch is not supported in optimizing //compiler, so it is isolated function tryCatch1(fn, receiver, arg) { ASSERT(typeof fn === "function"); try { return fn.call(receiver, arg); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch2(fn, receiver, arg, arg2) { ASSERT(typeof fn === "function"); try { return fn.call(receiver, arg, arg2); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatchApply(fn, args, receiver) { ASSERT(typeof fn === "function"); try { return fn.apply(receiver, args); } catch (e) { errorObj.e = e; return errorObj; } } //Un-magical enough that using this doesn't prevent //extending classes from outside using any convention var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function asString(val) { return typeof val === "string" ? val : ("" + val); } function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return !isPrimitive(value); } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(asString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function notEnumerableProp(obj, name, value) { var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } var wrapsPrimitiveReceiver = (function() { return this !== "string"; }).call("string"); function thrower(r) { throw r; } var ret = { thrower: thrower, isArray: es5.isArray, haveGetters: haveGetters, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, canEvaluate: canEvaluate, deprecated: deprecated, errorObj: errorObj, tryCatch1: tryCatch1, tryCatch2: tryCatch2, tryCatchApply: tryCatchApply, inherits: inherits, withAppended: withAppended, asString: asString, maybeWrapAsError: maybeWrapAsError, wrapsPrimitiveReceiver: wrapsPrimitiveReceiver }; module.exports = ret;
JavaScript
0
@@ -3279,24 +3279,62 @@ e, value) %7B%0A + if (isPrimitive(obj)) return obj;%0A var desc
2170ae38de7eac67e28765844b8e511650a3d755
revert revivier
src/util.js
src/util.js
import CircularJSON from 'circular-json-es6' function cached (fn) { const cache = Object.create(null) return function cachedFn (str) { const hit = cache[str] return hit || (cache[str] = fn(str)) } } var classifyRE = /(?:^|[-_\/])(\w)/g export const classify = cached((str) => { return str.replace(classifyRE, toUpper) }) const camelizeRE = /-(\w)/g export const camelize = cached((str) => { return str.replace(camelizeRE, toUpper) }) function toUpper (_, c) { return c ? c.toUpperCase() : '' } export function inDoc (node) { if (!node) return false var doc = node.ownerDocument.documentElement var parent = node.parentNode return doc === node || doc === parent || !!(parent && parent.nodeType === 1 && (doc.contains(parent))) } /** * Stringify/parse data using CircularJSON. */ export const UNDEFINED = '__vue_devtool_undefined__' export function stringify (data) { return CircularJSON.stringify(data, replacer) } function replacer (key, val) { if (val === undefined) { return UNDEFINED } else { return sanitize(val) } } export function parse (data) { return CircularJSON.parse(data, (k, v) => { if (v === UNDEFINED) { return undefined } else { return v } }) } /** * Sanitize data to be posted to the other side. * Since the message posted is sent with structured clone, * we need to filter out any types that might cause an error. * * @param {*} data * @return {*} */ function sanitize (data) { if ( !isPrimitive(data) && !Array.isArray(data) && !isPlainObject(data) ) { // handle types that will probably cause issues in // the structured clone return Object.prototype.toString.call(data) } else { return data } } export function isPlainObject (obj) { return Object.prototype.toString.call(obj) === '[object Object]' } function isPrimitive (data) { if (data == null) { return true } const type = typeof data return ( type === 'string' || type === 'number' || type === 'boolean' || data instanceof RegExp ) }
JavaScript
0.000001
@@ -1145,109 +1145,8 @@ data -, (k, v) =%3E %7B%0A if (v === UNDEFINED) %7B%0A return undefined%0A %7D else %7B%0A return v%0A %7D%0A %7D )%0A%7D%0A
bc2d25c3f39c9e5167098abef24d5dc99a32a01b
write test for getAttendees function
getAttendees/solution.js
getAttendees/solution.js
JavaScript
0
@@ -0,0 +1,474 @@ +function getAttendees(peopleInvited, responses)%7B%0A %0A%7D%0A%0A%0A%0A// test%0Avar people = %5B'Easter Bunny', 'Tooth Fairy', 'Frosty the Snowman', %0A 'Jack Frost', 'Cupid', 'Father Time'%5D;%0Avar responses = %5B %0A %7Bname: 'Easter Bunny', response: 'declined'%7D, %0A %7Bname: 'Jack Frost', response: 'declined'%7D, %0A %7Bname: 'Tooth Fairy', response: 'accepted'%7D %0A %5D%0A%0Aconsole.log(getAttendees(people, responses) === %5B'Tooth Fairy', 'Frosty the Snowman', 'Cupid', 'Father Time'%5D)%0A
c1a819259c8a7b218ef8fdb0de597e325d340259
Fix manifest task logging
lib/tasks/ManifestTask.js
lib/tasks/ManifestTask.js
var inherits = require('util').inherits, Task = require('./Task'), gulp = require('gulp'), manifest = require('gulp-manifest'), Promise = require('bluebird'); var ManifestTask = function (buildHelper) { Task.call(this, buildHelper); }; inherits(ManifestTask, Task); ManifestTask.prototype.command = "manifest"; ManifestTask.prototype.availableToModule = false; ManifestTask.prototype.action = function () { if (!this._buildHelper.isRelease() || !this._buildHelper.options.manifest) return Promise.resolve(); gulp.src(this._buildHelper.getDistDirectory() + '**/*') .pipe(manifest(this._buildHelper.options.manifest)) .pipe(gulp.dest(this._buildHelper.getDistDirectory())); }; module.exports = ManifestTask;
JavaScript
0.000195
@@ -528,24 +528,31 @@ olve();%0A +return gulp.src(thi
f72c6d7f98e25a6daf8fb9c19c43c0ed2c0b47b2
Change event name
lib/jquery.imagesequence.js
lib/jquery.imagesequence.js
var ImageSequence = function (target, options) { target.imagesequence = this; this.target = target; this.src = options.src; this.width = options.width; this.height = options.height; this.image = new Image(); this.step = 1; this.loop = false; this.running = false; if (options.loop) { this.loop = true; } this.autoplay = false; if (options.autoplay) { this.autoplay = true; } if (options.rewind) { this.step = -1; } this.shouldPlay = this.autoplay; var _this = this; var animation-ended = new Event('animation-ended'); this.init = function () { if(_this.sequence) { _this.sequencer(); } else { _this.image.src = _this.src; _this.target.html(_this.image); } _this.currentFrame = 0; _this.target.css('overflow','hidden'); }; this.run = function () { _this.running = true; setTimeout(function () { if(_this.shouldPlay){ _this.nextFrame(); _this.run(); } }, 40); // This needs to be replaced by a callback of sorts. setTimeout(function () { _this.running = false; }, 200); }; this.play = function () { _this.step = 1; _this.shouldPlay = true; if(_this.running === false) { _this.run(); } }; this.pause = function () { _this.step = 0; }; this.rewind = function () { _this.step = -1; _this.shouldPlay = true; if(_this.running === false) { _this.run(); } }; this.drawCurrentFrame = function () { var targetWidth = _this.target.width(); var targetHeight = _this.target.height(); var scaleX = targetWidth / _this.width; var scaleY = targetHeight / _this.height; var scale = Math.max(scaleX, scaleY); var frameWidth = _this.width * scale; var frameHeight = _this.height * scale; var x = (targetWidth - frameWidth) / 2; var y = (targetHeight - frameHeight) / 2; // Animation x -= _this.currentFrame * frameWidth; $(_this.image).css({ 'transform' : "translate3d(" + x + "px,"+ y +"px,0) scale(" + scale + ", " + scale + ")", 'transform-origin' : 'left top' }); }; /* Not necessarily 1, 2, 3... Can be 8, 7, 6... Could also be 0, 5, 10, 15... */ this.nextFrame = function () { _this.currentFrame = _this.currentFrame + _this.step; if (_this.currentFrame >= _this.countFrames()) { // On the right, end of sequence if (_this.loop) { _this.currentFrame -= _this.countFrames(); } else { _this.currentFrame = _this.countFrames() - 1; _this.shouldPlay = false; document.dispatchEvent(animation-ended); } } else if (_this.currentFrame < 0) { // On the left, beginning of sequence if(_this.loop){ _this.currentFrame += _this.countFrames(); } else { _this.currentFrame = 0; _this.shouldPlay = false; } } _this.drawCurrentFrame(); }; this.countFrames = function () { return _this.image.naturalWidth / _this.width; }; this.init(); if(_this.autoplay){ this.run(); } }; if($) { $.fn.imagesequence = function (options) { return new ImageSequence(this, options); }; }
JavaScript
0.000134
@@ -521,26 +521,25 @@ ar animation --e +E nded = new E
47424588d6fc75cc67cf17d3456bedf5c868d380
Fix module path in shared data (#3556)
shared-data/js/modules.js
shared-data/js/modules.js
// @flow import moduleSpecs from '../module/schemas/1.json' export type ModuleType = 'magdeck' | 'tempdeck' // use a name like 'magdeck' to get displayName for app export function getModuleDisplayName(name: ModuleType): string { const displayName = moduleSpecs[name].displayName return displayName }
JavaScript
0
@@ -41,14 +41,18 @@ ule/ -schema +definition s/1.
cb142102fd6753d3b0705829a3dbec8afbb4d481
Update generateUUID to match latest version in StackOverflow
lib/utils/generateUUID.js
lib/utils/generateUUID.js
// Maybe look into a more legit solution later // node-uuid doesn't work with old IE's // Source: http://stackoverflow.com/a/8809472 module.exports = function generateUUID () { var d = new Date().getTime() var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0 d = Math.floor(d / 16) return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16) }) return uuid }
JavaScript
0
@@ -201,16 +201,171 @@ tTime()%0A + if (global.performance && typeof global.performance.now === 'function') %7B%0A d += global.performance.now() // use high-precision timer if available%0A %7D%0A var uu @@ -548,17 +548,17 @@ (r & 0x -7 +3 %7C 0x8))
f360011cd0bcfbee7d9df0e470326ae93f34c9d2
fix for sql attacks on column names
sequel/lib/utils.js
sequel/lib/utils.js
/** * Helper functions */ var _ = require('lodash'); // Module Exports var utils = module.exports = {}; /** * Safe hasOwnProperty */ utils.object = {}; /** * Safer helper for hasOwnProperty checks * * @param {Object} obj * @param {String} prop * @return {Boolean} * @api public */ var hop = Object.prototype.hasOwnProperty; utils.object.hasOwnProperty = function(obj, prop) { return hop.call(obj, prop); }; /** * Escape Name * * Wraps a name in quotes to allow reserved * words as table or column names such as user. */ utils.escapeName = function escapeName(name, escapeCharacter) { return '' + escapeCharacter + name + escapeCharacter; }; /** * Map Attributes * * Takes a js object and creates arrays used for parameterized * queries in postgres. */ utils.mapAttributes = function(data, options) { var keys = [], // Column Names values = [], // Column Values params = [], // Param Index, ex: $1, $2 i = 1; // Flag whether to use parameterized queries or not var parameterized = options && utils.object.hasOwnProperty(options, 'parameterized') ? options.parameterized : true; // Get the escape character var escapeCharacter = options && utils.object.hasOwnProperty(options, 'escapeCharacter') ? options.escapeCharacter : '"'; // Determine if we should escape the inserted characters var escapeInserts = options && utils.object.hasOwnProperty(options, 'escapeInserts') ? options.escapeInserts : false; Object.keys(data).forEach(function(key) { var k = escapeInserts ? (options.escapeCharacter + key + options.escapeCharacter) : key; keys.push(k); var value = utils.prepareValue(data[key]); values.push(value); if(parameterized) { params.push('$' + i); } else { if(value === null || value === undefined) { params.push('null'); } else { params.push(value); } } i++; }); return({ keys: keys, values: values, params: params }); }; /** * Prepare values * * Transform a JS date to SQL date and functions * to strings. */ utils.prepareValue = function(value) { // Cast dates to SQL if (_.isDate(value)) { value = utils.toSqlDate(value); } // Cast functions to strings if (_.isFunction(value)) { value = value.toString(); } // Store Arrays as strings if (Array.isArray(value)) { value = JSON.stringify(value); } // Store Buffers as hex strings (for BYTEA) if (Buffer.isBuffer(value)) { value = '\\x' + value.toString('hex'); } return value; }; /** * Escape Strings */ utils.escapeString = function(value) { if(!_.isString(value)) return value; value = value.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) { switch(s) { case "\0": return "\\0"; case "\n": return "\\n"; case "\r": return "\\r"; case "\b": return "\\b"; case "\t": return "\\t"; case "\x1a": return "\\Z"; default: return "\\"+s; } }); return value; }; /** * JS Date to UTC Timestamp * * Dates should be stored in Postgres with UTC timestamps * and then converted to local time on the client. */ utils.toSqlDate = function(date) { return date.toUTCString(); };
JavaScript
0
@@ -602,42 +602,290 @@ %7B%0A -return '' + escapeCharacter + name +var regex = new RegExp(escapeCharacter, 'g');%0A var replacementString = '' + escapeCharacter + escapeCharacter;%0A var replacementDot = '' + escapeCharacter + '.' + escapeCharacter;%0A return '' + escapeCharacter + name.replace(regex, replacementString).replace(/%5C./g, replacementDot) + e
ff50875e7eef36d719251c72b71f495971e51b90
Fix saml.js for #905
server/auth/saml.js
server/auth/saml.js
var passport = require('passport'); var SamlStrategy = require('passport-saml').Strategy; var SAML = require('passport-saml').SAML; var fs = require('fs'); var logger = require("../utils/logger"); var path = require('path'); var setCredentials = function () { var entitiesJSON = global.saml_config; for (key in entitiesJSON) { logger.log2('verbose', 'Generating metadata for SAML provider "%s"', key) var objectJSON = entitiesJSON[key]; var strategyConfigOptions = {}; strategyConfigOptions.callbackUrl = global.applicationHost.concat("/passport/auth/saml/" + key + "/callback"); if (objectJSON.hasOwnProperty('entryPoint')) { strategyConfigOptions.entryPoint = objectJSON['entryPoint']; } if (objectJSON.hasOwnProperty('issuer')) { strategyConfigOptions.issuer = objectJSON['issuer']; } if (objectJSON.hasOwnProperty('identifierFormat')) { strategyConfigOptions.identifierFormat = objectJSON['identifierFormat']; } if (objectJSON.hasOwnProperty('cert')) { strategyConfigOptions.cert = objectJSON['cert']; } else { logger.log2('warn', '"cert" property is not present. Provider "%s" will not work', key) return } if (objectJSON.hasOwnProperty('skipRequestCompression')) { strategyConfigOptions.skipRequestCompression = objectJSON['skipRequestCompression']; } if (objectJSON.hasOwnProperty('authnRequestBinding')) { strategyConfigOptions.authnRequestBinding = objectJSON['authnRequestBinding']; } if (objectJSON.hasOwnProperty('additionalAuthorizeParams')) { strategyConfigOptions.additionalAuthorizeParams = objectJSON['additionalAuthorizeParams']; } if(objectJSON.hasOwnProperty('forceAuthn')){ strategyConfigOptions.forceAuthn = objectJSON['forceAuthn']; } if(objectJSON.hasOwnProperty('providerName')){ strategyConfigOptions.providerName = objectJSON['providerName']; } if(objectJSON.hasOwnProperty('signatureAlgorithm')){ strategyConfigOptions.signatureAlgorithm = objectJSON['signatureAlgorithm']; } if(objectJSON.hasOwnProperty('requestIdExpirationPeriodMs')){ strategyConfigOptions.requestIdExpirationPeriodMs = objectJSON['requestIdExpirationPeriodMs']; } else { strategyConfigOptions.requestIdExpirationPeriodMs = 3600000; } strategyConfigOptions.decryptionPvk = fs.readFileSync('/etc/certs/passport-sp.key', 'utf-8'); strategyConfigOptions.passReqToCallback = true; strategyConfigOptions.validateInResponseTo = true; var strategy = new SamlStrategy(strategyConfigOptions, function (req, profile, done) { logger.log2('verbose', 'profile: %s', profile) var idp = req.originalUrl.replace("/passport/auth/saml/","").replace("/callback",""); var mapping = global.saml_config[idp].reverseMapping; logger.log2('debug', 'SAML reponse in body:\n%s', req.body.SAMLResponse) var userProfile = { id: profile[mapping["id"]] || '', memberOf: profile[mapping["memberOf"]] || '', name: profile[mapping["name"]] || '', username: profile[mapping["username"]] || '', email: profile[mapping["email"]], givenName: profile[mapping["givenName"]] || '', familyName: profile[mapping["familyName"]] || '', provider: profile[mapping["provider"]] || '' }; return done(null, userProfile); }); passport.use(key, strategy); var idpMetaPath = path.join(__dirname, '..', 'idp-metadata'); if (!fs.existsSync(idpMetaPath)) { fs.mkdirSync(idpMetaPath); } fs.truncate(path.join(idpMetaPath, key + '.xml'), 0, function (err) { }); var decryptionCert = fs.readFileSync('/etc/certs/passport-sp.crt', 'utf-8'); var metaData = strategy.generateServiceProviderMetadata(decryptionCert); logger.log2('debug', 'Metadata is:\n%s', metaData) fs.writeFile(path.join(idpMetaPath, key + '.xml'), metaData, function (err) { if (err) { logger.log2('error', 'Failed saving %s', path.join(idpMetaPath, key + '.xml')) logger.log2('error', err) } else { logger.log2('info', '%s saved successfully', path.join(idpMetaPath, key + '.xml')) } }) } }; module.exports = { passport: passport, setCredentials: setCredentials };
JavaScript
0.000005
@@ -3723,16 +3723,54 @@ %5D%5D %7C%7C '' +,%0A providerKey: key %0A
5bdf9ada301fd2a3d17d9f27352220429bc79753
add some made up data
Topics/Checklists/checklists/checklist1.js
Topics/Checklists/checklists/checklist1.js
[1,"Pre-pilot"], [2,"Are the conceptual / structural issues identified in the early questionnaire design process sufficiently explored?"], [2,"How might the composition of the focus (gender, age, religion, caste/socioeconomic status) affect responses?"], [2,"Try to get at how potential respondents think about the key indicators you are trying to measure"], [2,"Do you have a translator providing simultaneous translation? If not, does the amount of note-taking correspond to the amount of discussion?"], [1,"Survey Design"], [2,"Do the questions make sense to the respondent?"], [3,"Watch how the respondent reacts to each question – any confusion? How is the reaction time?"], [3,"Are there questions that require explanation by enumerator, or clarification from respondent?"], [3,"Follow-up with the enumerator (and possibly the respondent) on questions that seemed problematic: is the issue translation? Phrasing? Conceptual? Cultural?"], [2,"Are answer options comprehensive?"], [3,"Ensure that all ‘other’ responses are specified and recorded"], [2,"Is the enumerator following the scripted translations?"], [3,"If not, ask the enumerator to note any translation issues to discuss with the team."], [3,"If you do not speak the language, you can still note if interviewer’s questions were noticeably longer/shorter than the written question."], [1,"Interview flow and timing"], [2,"How is the flow of the interview?"], [3,"Any pauses? (likely areas where interviewers need more instructions)"], [3,"Are there times when the respondent looks bored? Uncomfortable? Losing interest?"], [2,"Could the order of modules be improved? The order of questions within modules?"], [2,"How long does the interview take?"], [3,"Check length of each module by noting start and stop time."], [3,"Expect that pilot interviews will take much longer than actual interviews (likely twice as long) – interviewers are expected to do extra probing, take qualitative notes, and record open-ended responses, and the survey instrument may not yet flow well"]
JavaScript
0.000105
@@ -1,543 +1,104 @@ %5B1,%22 -Pre-pilot%22%5D,%0A %5B2,%22Are the conceptual / structural issues identified in the early questionnaire design process sufficiently explored?%22%5D,%0A %5B2,%22How might the composition of the focus (gender, age, religion, caste/socioeconomic status) affect responses?%22%5D,%0A %5B2,%22Try to get at how potential respondents think about the key indicators you are trying to measure%22%5D,%0A %5B2,%22Do you have a translator providing simultaneous translation? If not, does the amount of note-taking correspond to the amount of discussion?%22%5D,%0A +Thanksgiving preperations%22%5D,%0A%5B2,%22Buy turkey%22%5D,%0A%5B2,%22Buy booze%22%5D,%0A%5B3,%22Buy beer%22%5D,%0A%5B3,%22Buy Wine%22%5D,%0A %5B1,%22 @@ -110,31 +110,24 @@ y Design%22%5D,%0A - %5B2,%22Do the q @@ -164,33 +164,24 @@ pondent?%22%5D,%0A - %5B3,%22Watch ho @@ -263,33 +263,24 @@ on time?%22%5D,%0A - %5B3,%22Are ther @@ -364,33 +364,24 @@ pondent?%22%5D,%0A - %5B3,%22Follow-u @@ -527,31 +527,24 @@ ultural?%22%5D,%0A - %5B2,%22Are answ @@ -568,33 +568,24 @@ hensive?%22%5D,%0A - %5B3,%22Ensure t @@ -636,31 +636,24 @@ recorded%22%5D,%0A - %5B2,%22Is the e @@ -698,33 +698,24 @@ lations?%22%5D,%0A - %5B3,%22If not, @@ -789,33 +789,24 @@ he team.%22%5D,%0A - %5B3,%22If you d @@ -938,21 +938,16 @@ ion.%22%5D,%0A - %5B1,%22Inte @@ -967,31 +967,24 @@ d timing%22%5D,%0A - %5B2,%22How is t @@ -1008,33 +1008,24 @@ terview?%22%5D,%0A - %5B3,%22Any paus @@ -1084,33 +1084,24 @@ uctions)%22%5D,%0A - %5B3,%22Are ther @@ -1172,31 +1172,24 @@ nterest?%22%5D,%0A - %5B2,%22Could th @@ -1262,23 +1262,16 @@ les?%22%5D,%0A - %5B2,%22How @@ -1299,33 +1299,24 @@ ew take?%22%5D,%0A - %5B3,%22Check le @@ -1373,270 +1373,4 @@ %22%5D,%0A - %5B3,%22Expect that pilot interviews will take much longer than actual interviews (likely twice as long) %E2%80%93 interviewers are expected to do extra probing, take qualitative notes, and record open-ended responses, and the survey instrument may not yet flow well%22%5D%0A
773f5a792127f705c4d1eace26a3c588650102c5
convert console logs to embark logger and this baby is ready to rock
lib/modules/fuzzer/index.js
lib/modules/fuzzer/index.js
const utils = require('web3-utils'); const _ = require('underscore'); // generates random inputs based on the inputs of an ABI class ContractFuzzer { constructor(embark) { //this.abi = abi; this.embark = embark; this.logger = embark.logger; this.events = embark.events; this.registerConsoleCommand(); } // main function to call, takes in iteration number and a contract and returns a map object // composed of method names -> fuzzed inputs. generateFuzz(iterations, contract) { let fuzzMap = {}; for (let i = 0; i < iterations; i++) contract.abiDefinition.filter((x) => x.inputs && x.inputs.length != 0).forEach((abiMethod) => { let name = abiMethod.type === "constructor" ? "constructor" : abiMethod.name; console.log("name"); let inputTypes = abiMethod.inputs.map(input => input.type); console.log("INPUT TYPES:", inputTypes); let fuzzedInputs = _.map(inputTypes, this.getTypeFuzz.bind(this)); console.log("FUZZED INPUTS:", fuzzedInputs); fuzzMap[name] = fuzzedInputs; console.log("FUZZ KEYS SO FAR:", Object.keys(fuzzMap)); console.log("FUZZ VALS SO FAR:", Object.values(fuzzMap)); }); console.log("FUZZ:", Object.keys(fuzzMap), Object.values(fuzzMap)); return fuzzMap; } getTypeFuzz(typeString) { const self = this; console.log("TYPESTRING:", typeString); // Group 0: uint256[3] // Group 1: uint256 // Group 2: uint // Group 3: 256 // Group 4: [3] // Group 5: 3 let regexObj = typeString.match(/((bool|int|uint|bytes|string|address)([0-9]*)?)(\[([0-9]*)\])*$/); console.log("REGEX OBJ:", regexObj); let type = regexObj[1]; console.log("type:", type); let kind = regexObj[2]; console.log("kind:", kind); let size = regexObj[3]; console.log("size:", size); let array = regexObj[4]; console.log("array:", array); let arraySize = regexObj[5]; console.log("array size:", arraySize); switch(true) { case array !== undefined: { // if it's a dynamic array pick a number between 1 and 256 for length of array let length = arraySize === undefined || arraySize === null || arraySize === '' ? Math.floor((Math.random() * 256) + 1) : arraySize; console.log("LENGTH: ", length); return self.generateArrayOfType(length, type); } case kind == "bool": return self.generateRandomBool(); case kind == "uint" || kind == "int": return self.generateRandomInt(size); case kind === "bytes" && size !== undefined: return self.generateRandomStaticBytes(size); case kind === "string" || kind === "bytes": return self.generateRandomDynamicType(); case kind === "address": return self.generateRandomAddress(); default: throw new Error("Couldn't find proper ethereum abi type"); } } generateRandomBool() { return _.sample([true, false]); } generateArrayOfType(length, type) { var arr = []; for (var i = 0; i < length; i++) { arr.push(this.getTypeFuzz(type)); } console.log("Final Array:", arr); return arr; } generateRandomDynamicType() { return Math.random().toString(36).slice(2); } generateRandomStaticBytes(size) { return utils.randomHex(size); } generateRandomInt(size) { return utils.toBN(utils.randomHex(size / 8)); } generateRandomAddress() { return utils.randomHex(20); } registerConsoleCommand() { const self = this; self.embark.registerConsoleCommand((cmd, _options) => { let splitCmd = cmd.split(' '); let cmdName = splitCmd[0]; let contractName = splitCmd[1]; let iterations = splitCmd[2] === undefined ? 1 : splitCmd[2]; if (cmdName === 'fuzz') { self.events.request('contracts:contract', contractName, (contract) => { self.logger.info("-- fuzzed vals for " + contractName); this.generateFuzz(iterations, contract); }); return ""; } return false; }); } } module.exports = ContractFuzzer;
JavaScript
0
@@ -502,24 +502,47 @@ contract) %7B%0A + const self = this;%0A let fuzz @@ -780,39 +780,8 @@ me;%0A - console.log(%22name%22);%0A @@ -850,59 +850,8 @@ e);%0A - console.log(%22INPUT TYPES:%22, inputTypes);%0A @@ -937,308 +937,120 @@ -console.log(%22FUZZED INPUTS:%22, fuzzedInputs);%0A fuzzMap%5Bname%5D = fuzzedInputs;%0A console.log(%22FUZZ KEYS SO FAR:%22, Object.keys(fuzzMap));%0A console.log(%22FUZZ VALS SO FAR:%22, Object.values(fuzzMap));%0A %7D);%0A console.log(%22FUZZ:%22, Object.keys(fuzzMap), Object.values(fuzzMap) +fuzzMap%5Bname%5D = fuzzedInputs;%0A %7D);%0A for (let key in fuzzMap) self.logger.info(key + %22:%22 + fuzzMap%5Bkey%5D );%0A @@ -1128,52 +1128,8 @@ is;%0A - console.log(%22TYPESTRING:%22, typeString);%0A @@ -1366,362 +1366,148 @@ -console.log(%22REGEX OBJ:%22, regexObj);%0A let type = regexObj%5B1%5D;%0A console.log(%22type:%22, type);%0A let kind = regexObj%5B2%5D;%0A console.log(%22kind:%22, kind);%0A let size = regexObj%5B3%5D;%0A console.log(%22size:%22, size);%0A let array = regexObj%5B4%5D;%0A console.log(%22array:%22, array);%0A let arraySize = regexObj%5B5%5D;%0A console.log(%22array size:%22, arraySize) +let type = regexObj%5B1%5D;%0A let kind = regexObj%5B2%5D;%0A let size = regexObj%5B3%5D;%0A let array = regexObj%5B4%5D;%0A let arraySize = regexObj%5B5%5D ;%0A @@ -1789,49 +1789,8 @@ ze;%0A - console.log(%22LENGTH: %22, length);%0A @@ -2536,24 +2536,16 @@ th; i++) - %7B%0A arr.pus @@ -2575,52 +2575,8 @@ ));%0A - %7D%0A console.log(%22Final Array:%22, arr);%0A
454a186199a943593144b09bb10edef5e8620013
Delete one proofreader activity
src/scripts/services/v2/proofreaderActivity.js
src/scripts/services/v2/proofreaderActivity.js
'use strict'; /* Usage: * * ProofreaderActivity.get(id).then(function (proofreaderActivity) { * return proofreaderActivity.getRules(); * }).then(function (rules) { * // do something here * }); * */ module.exports = angular.module('quill-grammar.services.firebase.proofreaderActivity', [ 'firebase', 'underscore', require('./../../../../.tmp/config.js').name, ]) /*@ngInject*/ .factory('ProofreaderActivity', function (firebaseUrl, $firebaseObject, _, $q, $firebaseArray) { function ProofreaderModel(data) { if (data) { _.extend(this, data); } return this; } ProofreaderModel.ref = new Firebase(firebaseUrl + '/passageProofreadings'); // 'Class' methods ProofreaderModel.getById = function (id) { return $firebaseObject(ProofreaderModel.ref.child(id)).$loaded().then(function (data) { // Determine whether the activity exists. // This is a hack because $firebaseObject does not give access // to the DataSnapshot object where we'd normally call exists(). if (!data.passage) { return $q.reject(new Error('Error loading activity: activity with ID ' + id + ' does not exist.')); } return new ProofreaderModel(data); }); }; /* * Get all Proofreader Activities from Firebase */ ProofreaderModel.getAllFromFB = function () { return $firebaseArray(ProofreaderModel.ref).$loaded(); }; /* * Add one Proofreader Activity to Firebase */ ProofreaderModel.addToFB = function (pa) { return $firebaseArray(ProofreaderModel.ref).$add(pa); }; /* * Update one Proofreader Activity to Firebase */ ProofreaderModel.updateToFB = function (id, pa) { return $firebaseObject(ProofreaderModel.ref).$loaded().then(function (pas) { pas[id] = pa; return pas.$save(); }); }; return ProofreaderModel; });
JavaScript
0.000001
@@ -1809,16 +1809,275 @@ ;%0A %7D;%0A%0A + /*%0A * Delete one Proofreader Activity from Firebase%0A */%0A ProofreaderModel.deleteByIdFromFB = function (id) %7B%0A return $firebaseObject(ProofreaderModel.ref).$loaded().then(function (pas) %7B%0A pas%5Bid%5D = null;%0A return pas.$save();%0A %7D);%0A %7D;%0A%0A return
f1b5d8ccce0de3da962a7517bb076e16e571efa7
Fix the bug when caller jump to browser in launchApp()
src/sectv-tizen/applicationProxy.js
src/sectv-tizen/applicationProxy.js
'use strict'; module.exports = { exit: function (success, fail, args) { tizen.application.getCurrentApplication().exit(); }, launchApp: function (success, fail, args) { try { var paramAppId = args[0].appId; var paramData = args[0].data; var appCtrlDataAry = []; for(var keyName in paramData) { var temp = new tizen.ApplicationControlData(keyName, [paramData[keyName]]); appCtrlDataAry.push(temp); } var appCtrl = new tizen.ApplicationControl(null, null, null, null, appCtrlDataAry); tizen.application.launchAppControl(appCtrl, paramAppId, success, fail, null); } catch (e) { var error = new Error(); error.name = e.name; setTimeout(function() { fail(error); }, 0); } }, getRequestedAppInfo: function (success, fail, args) { try { var reqAppCtrl = tizen.application.getCurrentApplication().getRequestedAppControl(); var reqCallerAppId = reqAppCtrl.callerAppId; var reqAppCtrlDataAry = reqAppCtrl.appControl.data; var appCtrlDataObj = {}; for(var i = 0; i < reqAppCtrlDataAry.length; i++) { var key = reqAppCtrlDataAry[i].key; var value = (reqAppCtrlDataAry[i].value)[0]; appCtrlDataObj[key] = value; } setTimeout(function() { success({callerAppId: reqCallerAppId, data: appCtrlDataObj}); }, 0); } catch(e) { var error = new Error(); error.name = e.name; setTimeout(function() { fail(error); }, 0); } } }; require('cordova/exec/proxy').add('toast.application', module.exports);
JavaScript
0.000002
@@ -523,29 +523,393 @@ -var a +if(paramAppId == 'org.tizen.browser') %7B // Jump to browser%0A var browserAppCtrl = new tizen.ApplicationControl(null, (appCtrlDataAry%5B0%5D.value)%5B0%5D, null, null, appCtrlDataAry);%0A tizen.application.launchAppControl(browserAppCtrl, paramAppId, success, fail, null);%0A %7D%0A else %7B // Jump to widget%0A var widgetA ppCtrl = new @@ -979,32 +979,36 @@ y);%0A + + tizen.applicatio @@ -1026,17 +1026,23 @@ Control( -a +widgetA ppCtrl, @@ -1067,32 +1067,46 @@ s, fail, null);%0A + %7D%0A %7D%0A
1de16b0d58273ce1b1d6a4078b1a28073e00b9a6
Remove use of ternary operator
src/server/services/updateMeters.js
src/server/services/updateMeters.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/. */ const _ = require('lodash'); const Meter = require('../models/Meter'); const Reading = require('../models/Reading'); const readMamacData = require('./readMamacData'); const log = require('../log'); /** * Pulls new data for all the meters in the database. * This assumes that every meter is a MAMAC meter with a valid IP address. */ async function updateAllMeters() { const time = new Date(); log(`Getting meter data ${time.toISOString()}`); try { const allMeters = await Meter.getAll(); const metersToUpdate = allMeters.filter(m => m.enabled && m.type === Meter.type.MAMAC); // Do all the network requests in parallel, then throw out any requests that fail after logging the errors. const readingInsertBatches = _.filter(await Promise.all( metersToUpdate .map(readMamacData) .map(p => p.catch(err => { const uri = err.options !== undefined ? err.options.uri : '[NO URI AVAILABLE]'; log(`ERROR ON REQUEST TO ${uri}, ${err.message}`, 'error'); return null; })) ), elem => elem !== null); // Flatten the batches (an array of arrays) into a single array. const allReadingsToInsert = [].concat(...readingInsertBatches); await Reading.insertOrUpdateAll(allReadingsToInsert); log('Update finished'); } catch (err) { log(`Error updating all meters: ${err}`, 'error'); } } module.exports = updateAllMeters;
JavaScript
0.00022
@@ -1037,20 +1037,18 @@ %09%09%09%09 -cons +le t uri = err. @@ -1043,16 +1043,47 @@ t uri = +'%5BNO URI AVAILABLE%5D';%0A%09%09%09%09%09if ( err.opti @@ -1104,9 +1104,10 @@ ned -? +&& err @@ -1123,31 +1123,60 @@ uri -: '%5BNO URI AVAILABLE%5D'; +!== undefined) %7B%0A%09%09%09%09%09%09uri = err.options.uri;%0A%09%09%09%09%09%7D %0A%09%09%09
6cb1b9c9638b1027e8c3113c80e4804ca61a4f6a
Update login.controller.js
SmallBI_FrontEnd2/app/scripts/login/login.controller.js
SmallBI_FrontEnd2/app/scripts/login/login.controller.js
(function () { 'use strict'; angular.module('SmallBIApp') .controller('loginController', loginController); function loginController(AuthService) { var vm = this; vm.dadosLogin = {}; angular.extend(vm, { login: login }); function login() { AuthService.signin(vm.dadosLogin).then( function () { }, function () { }); } function activate() { } activate(); } })();
JavaScript
0.000001
@@ -341,57 +341,55 @@ on ( +result ) %7B%0A -%0A -%7D, function () %7B%0A%0A %7D);%0A %7D%0A%0A + console.log(result);%0A %7D, fun @@ -394,24 +394,16 @@ unction -activate () %7B%0A%0A @@ -408,26 +408,19 @@ -%7D%0A%0A activate(); + %7D);%0A %7D %0A %7D
5ef0db4821584e1fe555904809839de97ddeee5a
test stack methods
javascript/basics/stacks.js
javascript/basics/stacks.js
JavaScript
0.000001
@@ -0,0 +1,1770 @@ +// Stacks%0A%0A/*%0AStack is an ordered collection of itmes that follows LIFO (last in first out)%0Aprinciple. The addition of new items andthe removal of existing items%0Aoccurs at the same end.%0A%0AThe end of the stack is known as the top and the opposite is known as the base%0A%0ANewest elements are near the top and the oldest elements are near the base%0A%0AStacks used by compilers in programming languages and by computer memory%0Ato store variables and method calls%0A*/%0A%0A%0A/* IF we were to build a stack class in javascript, what properties and%0Amethods would we need to include?%0A%0A1) We would need an array to store the elements of the stack%0A2) Push to add new items to the top of the stack%0A3) pop to remove the top item from the stack (and to return removed element)%0A4) peek to return the top element from the stack (w/o modifying it)%0A5) isEmpty which will return true if stack is empty and false if not%0A6) clear which will remove all the elements in the stack%0A7) size which will return how many elements the stack contains%0A*/%0A%0A%0Afunction Stack()%7B%0A%0A var items = %5B%5D;%0A%0A this.push = function(element)%7B%0A items.push(element);%0A %7D;%0A%0A this.pop = function()%7B%0A return items.pop();%0A %7D;%0A%0A this.peek = function()%7B%0A return items%5Bitems.length-1%5D;%0A %7D;%0A%0A this.isEmpty = function()%7B%0A return items.length === 0;%0A %7D;%0A%0A this.size = function()%7B%0A return items.length;%0A %7D;%0A%0A this.clear = function()%7B%0A items = %5B%5D;%0A %7D;%0A%0A this.print = function()%7B%0A console.log(items.toString());%0A %7D;%0A%7D%0A%0A// using the stack class%0A%0Avar stack = new Stack();%0A%0Aconsole.log(stack.isEmpty());%0A%0Astack.push(5);%0Astack.push(8);%0A%0Aconsole.log(stack.peek());%0Astack.print();%0A%0Astack.push(11);%0A%0Aconsole.log(stack.size());%0Aconsole.log(stack.isEmpty());%0A%0Astack.push(15);%0A%0Astack.pop();%0Astack.pop();%0A%0Astack.print();%0A
36b69ad667b3930b4ac6f8cd60dba9ef468d84e8
allow hidden inputs
javascript/display_logic.js
javascript/display_logic.js
(function($) { //$.entwine('ss', function($) { $('.field').entwine({ getFormField: function() { return this.find('[name='+this.getFieldName()+']'); }, getFieldName: function() { return this.attr('id'); }, getFieldValue: function() { return this.getFormField().val(); }, evaluateEqualTo: function(val) { return this.getFieldValue() === val; }, evaluateNotEqualTo: function(val) { return this.getFieldValue() !== val; }, evaluateLessThan: function(val) { num = parseFloat(val); return this.getFieldValue() < num; }, evaluateGreaterThan: function(val) { num = parseFloat(val); return parseFloat(this.getFieldValue()) > num; }, evaluateLessThan: function(val) { num = parseFloat(val); return parseFloat(this.getFieldValue()) < num; }, evaluateContains: function(val) { return this.getFieldValue().match(val) !== null; }, evaluateStartsWith: function(val) { return this.getFieldValue().match(new RegExp('^'+val)) !== null; }, evaluateEndsWith: function(val) { return this.getFieldValue().match(new RegExp(val+'$')) !== null; }, evaluateEmpty: function() { return $.trim(this.getFieldValue()).length === 0; }, evaluateNotEmpty: function() { return !this.evaluateEmpty(); }, evaluateBetween: function(minmax) { v = parseFloat(this.getFieldValue()); parts = minmax.split("-"); if(parts.length === 2) { return v > parseFloat(parts[0]) && v < parseFloat(parts[1]); } return false; }, evaluateChecked: function() { return this.getFormField().is(":checked"); } }); $('.field.display-logic').entwine({ onmatch: function () { masters = this.getMasters(); for(m in masters) { this.closest('form').find('#'+masters[m]).addClass("display-logic-master"); } }, getLogic: function() { return $.trim(this.find('.display-logic-eval').text()); }, parseLogic: function() { js = this.getLogic(); result = eval(js); return result; }, getMasters: function() { return this.data('display-logic-masters').split(","); } }); $('.field.optionset').entwine({ getFormField: function() { f = this._super().filter(":checked"); return f; } }); $('.field.optionset.checkboxset').entwine({ evaluateHasCheckedOption: function(val) { this.find(':checkbox').filter(':checked').each(function() { return $(this).val() === val || $(this).getLabel() === val; }) }, evaluateHasCheckedAtLeast: function(num) { return this.find(':checked').length >= num; }, evaluateHasCheckedLessThan: function(num) { return this.find(':checked').length <= num; } }); $('.field input[type=checkbox]').entwine({ getLabel: function() { return this.closest('form').find('label[for='+this.attr('id')+']'); } }) $('.field.display-logic.display-logic-display').entwine({ testLogic: function() { this.toggle(this.parseLogic()); } }); $('.field.display-logic.display-logic-hide').entwine({ testLogic: function() { this.toggle(!this.parseLogic()); } }); $('.field.display-logic-master :text, .field.display-logic-master select').entwine({ onmatch: function() { this.closest(".field").notify(); }, onchange: function() { this.closest(".field").notify(); } }); $('.field.display-logic-master :checkbox, .field.display-logic-master :radio').entwine({ onmatch: function() { this.closest(".field").notify(); }, onclick: function() { this.closest(".field").notify(); } }); $('.field.display-logic-master').entwine({ Listeners: null, notify: function() { $.each(this.getListeners(), function() { $(this).testLogic(); }); }, getListeners: function() { if(l = this._super()) { return l; } var self = this; var listeners = []; this.closest("form").find('.display-logic').each(function() { masters = $(this).getMasters(); for(m in masters) { if(masters[m] == self.attr('id')) { listeners.push($(this)); break; } } }); this.setListeners(listeners); return this.getListeners(); } }); $('.field.display-logic-master.checkboxset').entwine({ }) $('.field.display-logic *').entwine({ getHolder: function() { return this.closest('.display-logic'); } }); //}) })(jQuery);
JavaScript
0.000001
@@ -317,32 +317,35 @@ function(val) %7B +%09%09%09 %0A%09%09%09return this. @@ -3125,16 +3125,53 @@ r :text, + .field.display-logic-master :hidden, .field.
1dd94d3d6af38f82e0a4f491d1d0ed5ace7b8586
remove spacing
src/data/generate-timeline.js
src/data/generate-timeline.js
var fs = require('fs'); var db = require('../db/content-provider'); var timelineUtils = require('../utils/timeline-utils'); var generateTimelineCommits = function(outputFilename) { db.loadDatabase({}, function() { var commits = db.getCollection('commits'); var githubCommits = timelineUtils.getCommitsPerDay(commits, 'github'); var bitbucketCommits = timelineUtils.getCommitsPerDay(commits, 'bitbucket'); var allCommits = githubCommits.concat(bitbucketCommits); var sortedCommitsByDate = allCommits.sort(function(first, second) { return new Date(first.date) - new Date(second.date); }); var jsonData = sortedCommitsByDate.reduce(function(acc, item) { var currentDate = item.date; if (acc[currentDate] != null) { acc[currentDate] += item.num_commits; } else { acc[currentDate] = item.num_commits; } return acc; }, {}); fs.writeFileSync(outputFilename, JSON.stringify(jsonData)); }); } module.exports = { generateTimelineCommits: generateTimelineCommits };
JavaScript
0.032069
@@ -13,25 +13,24 @@ uire('fs');%0A -%0A var db = req
1c7865498777bc1b7de0dfb76bd16c0d1bf25d12
fix text format (integration tests)
test/integration/features/step_definitions/view.js
test/integration/features/step_definitions/view.js
'use strict'; module.exports = function () { this.World = require('../support/world.js').World; this.Given(/^я нахожусь на экране "([^"]*)"$/, function (viewName) { var that = this; return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) { that.currentView = element; }); }); this.Then(/^система отобразит экран "([^"]*)"$/, function (viewName) { var that = this; return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) { that.currentView = element; }); }); this.Then(/^система отобразит модальное окно "([^"]*)"$/, function (viewName) { var that = this; return this.driver.findElement(this.by.xpath(this.selectors.XPATH.ModalView.header(viewName))).then(function (element) { that.currentView = element; }); }); this.When(/^я закрою текущее модальное окно$/, function () { var selector = this.selectors.XPATH.ModalView.closeButton(); var xpath = this.by.xpath(selector); var that = this; return this.driver.findElements(xpath) .then(function (elements) { var lastModalViewCloseButton = that._.last(elements); return lastModalViewCloseButton.click(); }); }); this.Then(/^система отобразит окно-сообщение "([^"]*)"$/, function (message) { var selector = this.selectors.XPATH.ModalView.message(); var xpath = this.by.xpath(selector); var that = this; message = message.replace(/''/g, '"'); // TODO: Выполнять без setTimeout return this.driver.findElement(xpath).then(function (messageBox) { return new Promise(function (resolve, reject) { setTimeout(function () { messageBox.getText().then(function (text) { text = that.helpers.ignoreNumbers(text.trim(), message); try { that.assert.equal(text, message); resolve(); } catch (err) { reject(err); } }); }, 500); }); }); }); this.When(/^я нажму в окне-сообщении на кнопку "([^"]*)"$/, function (buttonText) { var selector = this.selectors.XPATH.ModalView.messageBoxButton(buttonText); var xpath = this.by.xpath(selector); return this.driver.findElement(xpath) .then(function (button) { button.click(); return new Promise(function (resolve) { setTimeout(resolve, 1000); }); }); }); };
JavaScript
0.000001
@@ -1975,20 +1975,23 @@ -text +message = that.
49304b081643bd0cb72ef7b394df8f3795907d94
Return array of blocks from convertInlines().
lib/reader/markdown-json.js
lib/reader/markdown-json.js
var assert = require('assert'); module.exports = function parse(str) { var json = JSON.parse(str); assert(json.shift() === "MARKDOWN"); var blocks = convertBlocks(json, 0); return ['text'].concat(blocks); }; var convertBlocks = function(blocks, level) { var result = []; blocks.forEach(function(block) { var type = block.shift(); switch (type) { case 'PARA': case 'PLAIN': result.push(['para', { 'level': level }].concat(convertInlines(block))); break; case 'H1': case 'H2': case 'H3': case 'H4': case 'H5': case 'H6': var headingLevel = parseInt(type.substr(1)) - 4; headingLevel = headingLevel > -1 ? -1 : headingLevel; result.push(['heading', { 'level': headingLevel }].concat(convertInlines(block))); break; case 'BULLETLIST': result = result.concat(convertList(block, level)); break; case 'LIST': case 'HEADINGSECTION': result = result.concat(convertBlocks(block, level)); break; default: // extract just text in the worst case result.push(['para', { 'level': level }].concat(convertInlines(block))); } }); return result; }; var convertList = function(items, level) { var result = []; items.forEach(function(item) { assert(item.shift() === 'LISTITEM'); var blocks = convertBlocks(item, level+1); assert(blocks.length > 0); blocks[0][0] = 'bulleted'; blocks[0][1].level = level; result = result.concat(blocks); }); return result; }; var convertInlines = function(inlines) { inlines = extractInlines(inlines); inlines = normalizeInlines(inlines); return inlines; }; var extractInlines = function(inlines) { var result = []; inlines.forEach(function(inline) { if (! Array.isArray(inline)) // ignore objects, e.g. { "URL": "something" } return; var type = inline.shift(); switch (type) { case 'STR': assert(inline.length === 1); result.push(['plain', inline[0]]); break; case 'SPACE': assert(inline.length === 1); result.push(['plain', ' ']); break; default: // extract just text in the worst case if (inline.length === 1 && typeof inline[0] == 'string') result.push(['plain', inline[0]]); else result = result.concat(extractInlines(inline)); } }); return result; }; var normalizeInlines = function(inlines) { if (inlines.length === 0) return []; var result = [inlines.shift()]; while (inlines.length > 0) { var current = inlines.shift(); if (current[0] === 'break') { result.push(current); continue; } var last = result[result.length-1]; if (last[0] == current[0] || (current[0] === 'plain' && current[1] === ' ' && inlines.length > 0 && last[0] === inlines[0][0] && last[0] !== 'break')) { // append text assert(typeof last[1] === 'string'); last[1] += current[1]; } else { result.push(current); } } return result; };
JavaScript
0
@@ -420,42 +420,17 @@ sult -.push(%5B'para', %7B 'level': level %7D%5D + = result .con @@ -445,33 +445,39 @@ ertInlines(block -) +, level ));%0A brea @@ -713,42 +713,184 @@ -result.push(%5B'heading', %7B ' +var convertedBlocks = convertInlines(block, level);%0A assert(convertedBlocks.length %3E 0);%0A convertedBlocks%5B0%5D%5B0%5D = 'heading';%0A convertedBlocks%5B0%5D%5B1%5D. level -': + = hea @@ -894,27 +894,49 @@ headingLevel - %7D%5D +;%0A result = result .concat(conv @@ -934,39 +934,32 @@ ncat(convert -Inlines(b +edB lock -)) +s );%0A b @@ -1262,42 +1262,17 @@ sult -.push(%5B'para', %7B 'level': level %7D%5D + = result .con @@ -1295,17 +1295,23 @@ es(block -) +, level ));%0A @@ -1715,24 +1715,31 @@ tion(inlines +, level ) %7B%0A inline @@ -1815,23 +1815,62 @@ return +%5B%5B'para', %7B 'level': level %7D%5D.concat( inlines +)%5D ;%0A%7D;%0A%0Ava
62869c145e117b328ab281459792c5a94ee244fc
Add schema to `global-require` rule (fixes #3923)
lib/rules/global-require.js
lib/rules/global-require.js
/** * @fileoverview Rule for disallowing require() outside of the top-level module context * @author Jamund Ferguson * @copyright 2015 Jamund Ferguson. All rights reserved. */ "use strict"; var ACCEPTABLE_PARENTS = [ "AssignmentExpression", "VariableDeclarator", "MemberExpression", "ExpressionStatement", "CallExpression", "ConditionalExpression", "Program", "VariableDeclaration" ]; module.exports = function(context) { return { "CallExpression": function(node) { if (node.callee.name === "require") { var isGoodRequire = context.getAncestors().every(function(parent) { return ACCEPTABLE_PARENTS.indexOf(parent.type) > -1; }); if (!isGoodRequire) { context.report(node, "Unexpected require()."); } } } }; };
JavaScript
0
@@ -895,8 +895,36 @@ %7D;%0A%7D;%0A%0A +module.exports.schema = %5B%5D;%0A
b95471370c3434ee262a91e415976b734b45a3ec
build list view: add link to vsc url
public/app/builds/builds.list-controller.js
public/app/builds/builds.list-controller.js
'use strict'; angular.module('OpenTMIControllers') .controller('BuildListController', ['$scope', 'Builds', '$stateParams', '$log', function ($scope, Builds, $stateParams, $log) { $log.info('init BuildListController') var linkCellTemplate = '<div class="ngCellText" ng-class="col.colIndex()">' + '<a href="#/duts/builds/{{ row.entity.id }}">{{ row.entity[col.field] }}</a>' + '</div>'; var dlCellTemplate = '<div class="ngCellText" ng-class="col.colIndex()">' + '<a target="new" href="api/v0/duts/builds/{{ row.entity._id }}/files/0/download">{{ COL_FIELD }}</a>' + '</div>'; var defaultCellTemplate = '<div class="ui-grid-cell-contents"><span>{{COL_FIELD}}</span></div>'; $scope.columns = [ { field: 'cre.time', width:200, displayName: 'Date' }, { field: 'target.os', width:100, displayName: 'OS' }, //{ field: 'target.type', width:80, displayName: 'Type' }, { field: 'target.hw.model', width:150, displayName: 'Target' }, { field: 'configuration.name', width:150, displayName: 'Configuration' }, { field: 'configuration.toolchain.name', width:100, displayName: 'Toolchain' }, { field: 'files[0].name', width:250, cellTemplate: dlCellTemplate, displayName: 'File' }, { field: 'name', displayName: 'Name' } ]; $scope.gridOptions = { columnDefs: $scope.columns, enableColumnResizing: true, enableFiltering: true, enableRowSelection: true, //showFooter: true, exporterMenuCsv: true, enableGridMenu: true }; function doUpdateList(q) { if(!q) q = {}; Builds.query({q: JSON.stringify(q), f: "_id name target files configuration cre.time"}) .$promise.then( function(builds){ $log.info(builds); $scope.dataBuilds = builds; $scope.$root.$broadcast('buildListStatus', status); }); } $scope.gridOptions.data = 'dataBuilds'; doUpdateList(); /* $scope.$on('tcFilter', function(event, data) { var q = {} data.tags.forEach( function(tag){ if( !q.$or ) q.$or = []; q.$and.push( {target: {"$regex": ("/"+tag+"/"), "$options":"i"}} ); }); doUpdateList(q); });*/ $scope.gridOptions.onRegisterApi = function(gridApi){ //set gridApi on scope $scope.gridApi = gridApi; }; }]) /* .filter('mapStatus', function() { var statusHash = { 'released': 'released', 'develop': 'develop', 'maintenance': 'maintenance', 'unknown': 'unknown' }; return function(input) { if (!input){ return ''; } else { return statusHash[input]; } }; })*/ ;
JavaScript
0
@@ -374,22 +374,8 @@ ef=%22 -#/duts/builds/ %7B%7B r @@ -384,18 +384,26 @@ .entity. -id +vcs%5B0%5D.url %7D%7D%22%3E%7B%7B @@ -666,16 +666,68 @@ FIELD %7D%7D + (%7B%7B(row.entity.files%5B0%5D.size/1024).toFixed(0)%7D%7D kB) %3C/a%3E' +%0A @@ -883,18 +883,16 @@ umns = %5B - %0A %7B @@ -1009,74 +1009,8 @@ %7D,%0A - //%7B field: 'target.type', width:80, displayName: 'Type' %7D,%0A @@ -1038,33 +1038,33 @@ .model', width:1 -5 +0 0, displayName: @@ -1283,10 +1283,10 @@ dth: -25 +30 0, c @@ -1359,16 +1359,48 @@ 'name', + cellTemplate: linkCellTemplate, display @@ -1420,17 +1420,16 @@ %7D%0A %5D; - %0A $sc @@ -1728,16 +1728,16 @@ q = %7B%7D;%0A - Bu @@ -1818,16 +1818,20 @@ cre.time + vcs %22%7D)%0A
59e3f87a3d09f4b6d656179008c90e78ffe5a4e1
add notes for resizing (#2313)
packages/docs/pages/plugin/resizeable/index.js
packages/docs/pages/plugin/resizeable/index.js
import React, { Component } from 'react'; // eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import simpleExampleCode from '!!raw-loader!../../../components/Examples/resizeable/SimpleResizeableEditor'; // eslint-disable-next-line import/no-unresolved import simpleExampleEditorStylesCode from '!!raw-loader!../../../components/Examples/resizeable/SimpleResizeableEditor/editorStyles.module.css'; // eslint-disable-next-line import/no-unresolved import simpleExampleColorBlockCode from '!!raw-loader!../../../components/Examples/resizeable/SimpleResizeableEditor/colorBlockPlugin'; import Container from '../../../components/Container/Container'; import AlternateContainer from '../../../components/AlternateContainer/AlternateContainer'; import Heading from '../../../components/Heading/Heading'; import styles from './styles.module.css'; import Code from '../../../components/Code/Code'; // eslint-disable-next-line import/no-duplicates import SimpleResizeableEditor from '../../../components/Examples/resizeable/SimpleResizeableEditor'; import PluginPageFrame from '../../../components/PluginPageFrame/PluginPageFrame'; export default class App extends Component { render() { return ( <PluginPageFrame> <Container> <Heading level={2}>Resizeable</Heading> <Heading level={3}>Prerequisite</Heading> <p> This plugin exposes a decorator for blocks. You can use it in combination with any kind of plugin that manages a Draft.js block e.g. image or video. Keep in mind the plugin must accept a decorator for the block. The `Simple Resizeable Example` further down contains an example plugin rendering a colored div. In addition this plugin only works in combination with the @draft-js-plugins/focus. </p> <Heading level={3}>Usage</Heading> <p> Hover with the mouse on the right side of the block and drag it to resize. At which edge resize is possible is configurable. </p> <Heading level={3}>Supported Environment</Heading> <ul className={styles.list}> <li className={styles.listEntry}>Desktop: Yes</li> <li className={styles.listEntry}>Mobile: No</li> <li className={styles.listEntry}>Screen-reader: No</li> </ul> </Container> <AlternateContainer> <Heading level={2}>Getting Started</Heading> <Code code="npm install @draft-js-plugins/editor" /> <Code code="npm install @draft-js-plugins/focus" /> <Code code="npm install @draft-js-plugins/resizeable" /> </AlternateContainer> <Container> <Heading level={2}>Configuration Parameters</Heading> </Container> <Container> <Heading level={2}>Simple Resizeable Example</Heading> <SimpleResizeableEditor /> <Code code={simpleExampleCode} name="SimpleResizeableEditor.js" /> <Code code={simpleExampleColorBlockCode} name="colorBlockPlugin.js" /> <Code code={simpleExampleEditorStylesCode} name="editorStyles.css" /> </Container> </PluginPageFrame> ); } }
JavaScript
0
@@ -1163,16 +1163,74 @@ eFrame'; +%0Aimport ExternalLink from '../../../components/Link/Link'; %0A%0Aexport @@ -2758,24 +2758,858 @@ izeable%22 /%3E%0A + %3CHeading level=%7B3%7D%3ENotes%3C/Heading%3E%0A %3Cp%3E%0A This plugin needs to read and write the size information to the%0A resized HTML element. Therefore the resized component needs to use%7B' '%7D%0A %3CExternalLink href=%22https://reactjs.org/docs/forwarding-refs.html%22%3E%0A forwarding ref%0A %3C/ExternalLink%3E%0A . As reported in issue%7B' '%7D%0A %3CExternalLink href=%22https://github.com/draft-js-plugins/draft-js-plugins/issues/2272#issuecomment-909642353%22%3E%0A #2272%0A %3C/ExternalLink%3E%7B' '%7D%0A in some cases it might be usefult to wrap the ref with%7B' '%7D%0A %3CExternalLink href=%22https://reactjs.org/docs/hooks-reference.html#useimperativehandle%22%3E%0A useImperativeHandle%0A %3C/ExternalLink%3E%0A .%0A %3C/p%3E%0A %3C/Al
0bafaef884f063e5a3184440778b6526ac6ff597
test for LD data with real dates
test/client/e2e/learning-design-scenarios.js
test/client/e2e/learning-design-scenarios.js
'use strict'; /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */ describe('Learning Design', function() { it('Logged in user can see all learning designs', function() { var existingUserName = testUsers.getUserName; var existingUserPassword = testUsers.getUserPassword; browser().navigateTo('/login'); input('username').enter(existingUserName); input('password').enter(existingUserPassword); element('#loginButton').click(); sleep(2); // Verify results expect(repeater('#ldlist .ld-item').count()).toBeGreaterThan(5); // Logout element('#userActionsMenu').click(); element('#logoutLink').click(); }); it('Clicking on Learning Design displays detail view',function() { var existingUserName = testUsers.getUserName; var existingUserPassword = testUsers.getUserPassword; browser().navigateTo('/login'); input('username').enter(existingUserName); input('password').enter(existingUserPassword); element('#loginButton').click(); sleep(2); // Click on first result element('#ldlist .ld-item:nth-child(1) .ld-center a').click(); sleep(2); // Verify detail view // This is brittle because order by last edit date where all dates are same is unpredictable expect(browser().location().url()).toBe('/ld/28'); expect(binding('learningDesign.ld_name')).toBe('Learning Design Title Demo 28'); expect(binding('learningDesign.ld_students_profile')).toBe('20 studenti adolescenti di livello B1'); // Logout element('#userActionsMenu').click(); element('#logoutLink').click(); }); });
JavaScript
0
@@ -1310,18 +1310,17 @@ Be('/ld/ -28 +1 ');%0A @@ -1398,10 +1398,9 @@ emo -28 +1 ');%0A
a5ae5afbb3506946449ed11404cc38c29cb5816c
Rename slidemodeenter event handler.
lib/shower/shower.Player.js
lib/shower/shower.Player.js
/** * @file Slides player. */ shower.modules.define('shower.Player', [ 'Emitter', 'util.bound', 'util.extend' ], function (provide, EventEmitter, bound, extend) { /** * @class * @name shower.Player * * Control slides. * * @param {Shower} shower Shower. */ function Player(shower) { this.events = new EventEmitter({ context: this, parent: shower.events }); this._shower = shower; this._showerListeners = null; this._playerListeners = null; this._currentSlideNumber = -1; this._currentSlide = null; this.init(); } extend(Player.prototype, /** @lends shower.Player.prototype */ { init: function () { this._showerListeners = this._shower.events.group() .on('slideadd', this._onSlideAdd, this) .on('slideremove', this._onSlideRemove, this) .on('slidemodeenter', this._onContainerSlideModeEnter, this); this._playerListeners = this.events.group() .on('prev', this._onPrev, this) .on('next', this._onNext, this); document.addEventListener('keydown', bound(this, '_onKeyDown')); }, destroy: function () { this._showerListeners.offAll(); this._playerListeners.offAll(); document.removeEventListener('keydown', bound(this, '_onKeyDown')); this._currentSlide = null; this._currentSlideNumber = null; this._shower = null; }, /** * Go to next slide. * * @returns {shower.Player} */ next: function () { this.events.emit('next'); return this; }, /** * Go to previous slide. * * @returns {shower.Player} */ prev: function () { this.events.emit('prev'); return this; }, /** * Go to first slide. * * @returns {shower.Player} */ first: function () { this.go(0); return this; }, /** * Go to last slide. * * @returns {shower.Player} */ last: function () { this.go(this._shower.getSlidesCount() - 1); return this; }, /** * Go to custom slide by index. * * @param {number | Slide} index Slide index to activate. * @returns {shower.Player} */ go: function (index) { // If go by slide istance. if (typeof index !== 'number') { index = this._shower.getSlideIndex(index); } var slidesCount = this._shower.getSlidesCount(); var currentSlide = this._currentSlide; if (index != this._currentSlideNumber && index < slidesCount && index >= 0) { if (currentSlide && currentSlide.isActive()) { currentSlide.deactivate(); } currentSlide = this._shower.get(index); this._currentSlide = currentSlide; this._currentSlideNumber = index; if (!currentSlide.isActive()) { currentSlide.activate(); } this.events.emit('activate', { index: index, slide: currentSlide }); } return this; }, /** * @returns {Slide} Current active slide. */ getCurrentSlide: function () { return this._currentSlide; }, /** * @returns {Number} Current active slide index. */ getCurrentSlideIndex: function () { return this._currentSlideNumber; }, _onPrev: function () { this._changeSlide(this._currentSlideNumber - 1); }, _onNext: function () { this._changeSlide(this._currentSlideNumber + 1); }, /** * @ignore * @param {number} index Slide index. */ _changeSlide: function (index) { this.go(index); }, _onSlideAdd: function (e) { var slide = e.get('slide'); slide.events .on('activate', this._onSlideActivate, this); }, _onSlideRemove: function (e) { var slide = e.get('slide'); slide.events .off('activate', this._onSlideActivate, this); }, _onSlideActivate: function (e) { var slide = e.get('slide'); var slideNumber = this._shower.getSlideIndex(slide); this.go(slideNumber); }, _onKeyDown: function (e) { if (!this._shower.isHotkeysEnabled() || /^(?:button|input|select|textarea)$/i.test(e.target.tagName)) { return; } this.events.emit('keydown', { event: e }); switch (e.which) { case 33: // PgUp case 38: // Up case 37: // Left case 72: // H case 75: // K if (e.altKey || e.ctrlKey || e.metaKey) { return; } e.preventDefault(); this.prev(); break; case 34: // PgDown case 40: // Down case 39: // Right case 76: // L case 74: // J if (e.altKey || e.ctrlKey || e.metaKey) { return; } e.preventDefault(); this.next(); break; case 36: // Home e.preventDefault(); this.first(); break; case 35: // End e.preventDefault(); this.last(); break; case 9: // Tab (Shift) case 32: // Space (Shift) if (e.altKey || e.ctrlKey || e.metaKey) { return; } e.preventDefault(); if (e.shiftKey) { this.prev(); } else { this.next(); } break; } }, _onContainerSlideModeEnter: function () { if (!this._currentSlide) { this.go(0); } } }); provide(Player); });
JavaScript
0
@@ -985,25 +985,16 @@ this._on -Container SlideMod @@ -6518,17 +6518,8 @@ _on -Container Slid
b622de228124bb06597df47daa3d17cdba1fa5ce
Make bordem functional
boredom.js
boredom.js
#!/usr/bin/nodejs 'use strict'; // // Required Modules // var fs = require('fs'), path = require('path'), process = require('process'), _ = require('lodash'), child_process = require('child_process'); // // Find all images in current directory // var images = []; console.log('Looking for boring images in ' + process.cwd()); _.forEach(fs.readdirSync(process.cwd()), function (node) { var matches = node.match(/.*\.(jpeg|jpg)$/); if (matches) { images.push(node); } }); if (images.length < 2) { console.log('Failure! There need to be at least 2 images in the current directory'); process.exit(50); } // // Process all images, looking for "boring" images that // have few pixel changes. // for (var i=1; i < images.length; i++) { (function () { var delta, output, prev = images[i-1], curr = images[i]; output = child_process.spawnSync('compare', [ '-metric', 'AE', '-fuzz', '50%', prev, curr ]); delta = parseInt(output); // output = child_process.spawnSync('compare', { // '-metric', 'MAE', // prev, curr // }); // deltaMAE = parseInt(output); if (delta < 1000) { // this image is boring, rename it as such var oldName = curr.match(/^(.+)\.(jpeg|jpg)$/), newName = oldName[1] + '-BORING.' + oldName[2]; fs.renameSync( path.join(process.cwd(), curr), path.join(process.cwd(), newName) ); } })(); } // for(...)
JavaScript
0.00125
@@ -610,16 +610,51 @@ 50);%0A%7D%0A%0A +var TOTAL_IMAGES = images.length;%0A%0A //%0A// Pr @@ -734,16 +734,64 @@ ges.%0A//%0A +var boringImages = %5B%5D,%0A%09%09prevImage = images%5B0%5D;%0A for (var @@ -800,29 +800,28 @@ =1; i %3C -images.length +TOTAL_IMAGES ; i++) %7B @@ -837,16 +837,83 @@ on () %7B%0A +%09%09console.log('Analyzing ' + (i+1) + '/' + TOTAL_IMAGES + '...');%0A%0A %09%09var de @@ -924,37 +924,25 @@ %0A%09%09%09 -outpu +resul t,%0A%09%09%09 -prev = images%5Bi-1%5D +output ,%0A%09%09 @@ -963,21 +963,21 @@ %5Bi%5D;%0A%0A%09%09 -outpu +resul t = chil @@ -1042,18 +1042,18 @@ fuzz', ' +3 5 -0 %25',%0A%09%09%09p @@ -1059,21 +1059,94 @@ prev +Image , curr -%0A%09%09%5D);%0A +, '/dev/null'%0A%09%09%5D, %7B%0A%09%09%09'encoding': 'utf8'%0A%09%09%7D);%0A%0A%09%09output = result.output; %0A%09%09d @@ -1171,139 +1171,74 @@ tput +%5B2%5D );%0A%0A -//%09%09output = child_process.spawnSync('compare', %7B%0A//%09%09%09'-metric', 'MAE',%0A//%09%09%09prev, curr%0A//%09%09%7D);%0A//%09%09deltaMAE = parseInt(output +%09%09console.log(prevImage + ' -%3E ' + curr + ' delta: ', delta );%0A%0A @@ -1255,19 +1255,17 @@ a %3C -100 +5 0) %7B%0A%09%09%09 // t @@ -1264,257 +1264,124 @@ %0A%09%09%09 -// this image is boring, rename it as such%0A%09%09%09var oldName = curr.match(/%5E(.+)%5C.(jpeg%7Cjpg)$/),%0A%09%09%09%09newName = oldName%5B1%5D + '-BORING.' + oldName%5B2%5D;%0A%0A%09%09%09fs.renameSync(%0A%09%09%09%09path.join(process.cwd(), curr),%0A%09%09%09%09path.join(process.cwd(), newName)%0A%09%09%09) +boringImages.push(curr);%0A%09%09%7D else %7B%0A%09%09%09// save this image as the previously updated image%0A%09%09%09prevImage = curr ;%0A%09%09%7D%0A +%0A %09%7D)( @@ -1397,8 +1397,364 @@ or(...)%0A +%0A//%0A// Rename all boring images%0A//%0Aconsole.log('Found ' + boringImages.length + ' boring images');%0A_.forEach(boringImages, function (boringImage) %7B%0A%09var oldName = boringImage.match(/%5E(.+)%5C.(jpeg%7Cjpg)$/),%0A%09%09newName = oldName%5B1%5D + '-BORING.' + oldName%5B2%5D;%0A%0A%09fs.renameSync(%0A%09%09path.join(process.cwd(), boringImage),%0A%09%09path.join(process.cwd(), newName)%0A%09);%0A%7D);%0A
ef165d140cabbd0257a7e281ce17169b70934951
fix bugs: .play, .setActive
lib/shower/shower.Player.js
lib/shower/shower.Player.js
/** * @fileOverview * Slides player. */ modules.define('shower.Player', [ 'event.Emitter', 'util.extend', 'util.bind' ], function (provide, EventEmitter, extend, bind) { /** * @name shower.Player * @constructor * @param {Shower} shower */ function Player (shower) { this.events = new EventEmitter(); this._shower = shower; this._currentSlideNumber = 0; this._currentSlide = null; this._playerLoop = null; this._init(); } extend(Player.prototype, /** @lends shower.Player.prototype */ { /** * Next slide. * @returns {shower.Player} */ next: function () { this._changeSlide(this._currentSlideNumber + 1); this.events.fire('next'); return this; }, /** * Prev slide. * @returns {shower.Player} */ prev: function () { this._changeSlide(this._currentSlideNumber - 1); this.events.fire('prev'); return this; }, /** * Play slideshow. * @param {Object} [options] Play options. * @param {Number} [options.timeout = 2000] * @param {Number} [options.startIndex = 0] * @param {Number} [options.stopIndex] */ play: function (options) { options = extend({ timeout: 2000, startIndex: 0, stopIndex: this._shower.getSlidesCount() }, options || {}); if (this._playerLoop) { this.stop(); } this.setActive(options.startIndex); this._playerLoop = setInterval(bind(function () { if (this._currentSlideNumber == options.stopIndex) { this.stop(); } else { this.next(); } }, this), options.timeout); this.events.fire('play'); }, /** * Stop slideshow. */ stop: function () { if (this._playerLoop) { stopInterval(this._playerLoop); this._playerLoop = null; } this.events.fire('stop'); }, /** * @param {Number} index Slide index to activate. * @returns {shower.Player} */ setActive: function (index) { var slidesCount = this._shower.getSlidesCount(); if (index < slidesCount && index >= 0) { if (this._currentSlide) { this.setInavtive(this._currentSlideNumber); } this._currentSlide = this._shower.get(index); this._currentSlide.setActive(); this._currentSlideNumber = index; this.events.fire('activate', { index: index }); } return this; }, /** * @returns {Slide} Current slide. */ getCurrentSlide: function () { return this._currentSlide; }, /** * @returns {Number} Current slide index. */ getCurrentSlideIndex: function () { return this._currentSlideNumber; }, /** * @ignore * Init player state. */ _init: function () { // get active slide // check init data }, /** * @ignore * @param {Number} index Slide index. */ _changeSlide: function (index) { this.setActive(index); this._currentSlideNUmber = index; this.events.fire('slidechange'); }, _playSlides: function () { this.next(); } }); provide(Player); });
JavaScript
0.000003
@@ -183,24 +183,38 @@ %7B%0A%0A /**%0A + * @class%0A * @name @@ -232,28 +232,8 @@ yer%0A - * @constructor%0A @@ -679,32 +679,93 @@ : function () %7B%0A + if (this._shower.getSlidesCount() %3C index) %7B%0A this @@ -813,32 +813,36 @@ 1);%0A + this.events.fire @@ -850,16 +850,142 @@ 'next'); +%0A %7D else %7B%0A if (this._playerLoop) %7B%0A this.stop();%0A %7D%0A %7D %0A%0A @@ -1912,213 +1912,24 @@ ind( -function () %7B%0A if (this._currentSlideNumber == options.stopIndex) %7B%0A this.stop();%0A %7D else %7B%0A this.next();%0A %7D%0A %7D +this._playSlides , th @@ -2133,20 +2133,21 @@ -stop +clear Interval @@ -2486,17 +2486,69 @@ sCount() -; +,%0A currentSlide = this._currentSlide;%0A %0A @@ -2613,22 +2613,16 @@ if ( -this._ currentS @@ -2653,49 +2653,33 @@ -this +currentSlide .setIna -v +c tive( -this._currentSlideNumber );%0A @@ -2703,38 +2703,32 @@ -this._ currentSlide = t @@ -2759,38 +2759,32 @@ -this._ currentSlide.set @@ -2784,32 +2784,84 @@ ide.setActive(); +%0A%0A this._currentSlide = currentSlide; %0A @@ -3726,54 +3726,8 @@ x);%0A - this._currentSlideNUmber = index;%0A @@ -3830,20 +3830,212 @@ -this.next(); +if (this._currentSlideNumber == options.stopIndex) %7B%0A this.stop();%0A %7D else %7B%0A this.next();%0A %7D%0A %7D,%0A%0A _deactivate: function (slideNumber) %7B%0A %0A
120b1dc6ff997a361b404824a09587ef8f9d12ba
Update doc.js
source/javascripts/doc.js
source/javascripts/doc.js
//= require mice //= require mice/jquery //= require_tree . // ZeroClipboard ZeroClipboard.config( { moviePath: '/images/ZeroClipboard.swf' } ); $(function(){ });
JavaScript
0.000001
@@ -9,16 +9,23 @@ ire mice +/jquery %0A//= req @@ -25,39 +25,32 @@ //= require mice -/jquery %0A//= require_tre @@ -140,16 +140,16 @@ ' %7D );%0A%0A - $(functi @@ -155,11 +155,213 @@ ion()%7B%0A%0A + if($(%22body.mobile%22).size())%7B%0A $(document).scroll(function() %7B%0A console.log('scroll')%0A //$('#window').contents().find('body').html($('#typography').next().next().text())%0A %7D);%0A %7D%0A //%0A%0A %7D);
b1a5ff630ac4822bddc961941e33688821dd3cab
use tabs instead of spaces
public/js/controllers/projects/templates.js
public/js/controllers/projects/templates.js
define(['controllers/projects/taskRunner'], function () { app.registerController('ProjectTemplatesCtrl', ['$scope', '$http', '$uibModal', 'Project', '$rootScope', '$window', function ($scope, $http, $modal, Project, $rootScope, $window) { $http.get(Project.getURL() + '/keys?type=ssh').success(function (keys) { $scope.sshKeys = keys; $scope.sshKeysAssoc = {}; keys.forEach(function (k) { if (k.removed) k.name = '[removed] - ' + k.name; $scope.sshKeysAssoc[k.id] = k; }); }); $http.get(Project.getURL() + '/inventory').success(function (inv) { $scope.inventory = inv; $scope.inventoryAssoc = {}; inv.forEach(function (i) { if (i.removed) i.name = '[removed] - ' + i.name; $scope.inventoryAssoc[i.id] = i; }); }); $http.get(Project.getURL() + '/repositories').success(function (repos) { $scope.repos = repos; $scope.reposAssoc = {}; repos.forEach(function (i) { if (i.removed) i.name = '[removed] - ' + i.name; $scope.reposAssoc[i.id] = i; }); }); $http.get(Project.getURL() + '/environment').success(function (env) { $scope.environment = env; $scope.environmentAssoc = {}; env.forEach(function (i) { if (i.removed) i.name = '[removed] - ' + i.name; $scope.environmentAssoc[i.id] = i; }); }); function getHiddenTemplates() { try { return JSON.parse($window.localStorage.getItem('hidden-templates') || '[]'); } catch(e) { return []; } } function setHiddenTemplates(hiddenTemplates) { $window.localStorage.setItem('hidden-templates', JSON.stringify(hiddenTemplates)); } $scope.hasHiddenTemplates = function() { return getHiddenTemplates().length > 0; } $scope.reload = function () { $http.get(Project.getURL() + '/templates?sort=alias&order=asc').success(function (templates) { var hiddenTemplates = getHiddenTemplates(); for (var i = 0; i < templates.length; i++) { var template = templates[i]; if (hiddenTemplates.indexOf(template.id) !== -1) { template.hidden = true; } } $scope.templates = templates; }); } $scope.remove = function (template) { $http.delete(Project.getURL() + '/templates/' + template.id).success(function () { $scope.reload(); }).error(function () { swal('error', 'could not delete template..', 'error'); }); } $scope.add = function () { var scope = $rootScope.$new(); scope.keys = $scope.sshKeys; scope.inventory = $scope.inventory; scope.repositories = $scope.repos; scope.environment = $scope.environment; $modal.open({ templateUrl: '/tpl/projects/templates/add.html', scope: scope }).result.then(function (opts) { var tpl = opts.template; $http.post(Project.getURL() + '/templates', tpl).success(function () { $scope.reload(); }).error(function (_, status) { swal('error', 'could not add template:' + status, 'error'); }); }); } $scope.update = function (template) { var scope = $rootScope.$new(); scope.tpl = template; scope.keys = $scope.sshKeys; scope.inventory = $scope.inventory; scope.repositories = $scope.repos; scope.environment = $scope.environment; $modal.open({ templateUrl: '/tpl/projects/templates/add.html', scope: scope }).result.then(function (opts) { if (opts.remove) { return $scope.remove(template); } var tpl = opts.template; $http.put(Project.getURL() + '/templates/' + template.id, tpl).success(function () { $scope.reload(); }).error(function (_, status) { swal('error', 'could not add template:' + status, 'error'); }); }).closed.then(function () { $scope.reload(); }); } $scope.run = function (tpl) { $modal.open({ templateUrl: '/tpl/projects/createTaskModal.html', controller: 'CreateTaskCtrl', resolve: { Project: function () { return Project; }, Template: function () { return tpl; } } }).result.then(function (task) { var scope = $rootScope.$new(); scope.task = task; scope.project = Project; $modal.open({ templateUrl: '/tpl/projects/taskModal.html', controller: 'TaskCtrl', scope: scope, size: 'lg' }); }) } $scope.showAll = function() { $scope.allShown = true; } $scope.hideHidden = function() { $scope.allShown = false; } $scope.hideTemplate = function(template) { var hiddenTemplates = getHiddenTemplates(); if (hiddenTemplates.indexOf(template.id) === -1) { hiddenTemplates.push(template.id); } setHiddenTemplates(hiddenTemplates); template.hidden = true; } $scope.showTemplate = function(template) { var hiddenTemplates = getHiddenTemplates(); var i = hiddenTemplates.indexOf(template.id); if (i !== -1) { hiddenTemplates.splice(i, 1); } setHiddenTemplates(hiddenTemplates); delete template.hidden; } $scope.copy = function (template) { var tpl = angular.copy(template); tpl.id = null; var scope = $rootScope.$new(); scope.tpl = tpl; scope.keys = $scope.sshKeys; scope.inventory = $scope.inventory; scope.repositories = $scope.repos; scope.environment = $scope.environment; $modal.open({ templateUrl: '/tpl/projects/templates/add.html', scope: scope }).result.then(function (opts) { var tpl = opts.template; $http.post(Project.getURL() + '/templates', tpl).success(function () { $scope.reload(); }).error(function (_, status) { swal('error', 'could not add template:' + status, 'error'); }); }); } $scope.reload(); }]); });
JavaScript
0.000004
@@ -1595,20 +1595,18 @@ );%0A%09%09%7D%0A%0A - +%09%09 $scope.h @@ -1642,14 +1642,11 @@ ) %7B%0A - +%09%09%09 retu @@ -1685,12 +1685,10 @@ 0;%0A - +%09%09 %7D%0A%0A%09
15f0ec63706ac570f689b06dad498c904c9b3999
Fix avatar border clipping on android (#6791)
shared/common-adapters/avatar.render.native.js
shared/common-adapters/avatar.render.native.js
// @flow import Icon from './icon' import React, {PureComponent} from 'react' import {globalColors} from '../styles' import {ClickableBox, NativeImage, Box} from './index.native' import type {AvatarSize} from './avatar' import type {IconType} from './icon' type ImageProps = { onLoadEnd: () => void, opacity: ?number, size: AvatarSize, url: string, } type Props = { borderColor: ?string, children: any, followIconStyle: ?Object, followIconType: ?IconType, followIconSize: number, loadingColor: ?string, onClick?: ?(() => void), opacity: ?number, size: AvatarSize, style?: ?Object, url: ?string, } type State = { loaded: boolean, } // Android doesn't handle background colors border radius setting const backgroundOffset = 1 const Background = ({loaded, loadingColor, size}) => ( <Box style={{ backgroundColor: loaded ? globalColors.white : loadingColor || globalColors.lightGrey, borderRadius: size / 2, bottom: backgroundOffset, left: backgroundOffset, position: 'absolute', right: backgroundOffset, top: backgroundOffset, }} /> ) class UserImage extends PureComponent<void, ImageProps, void> { render () { const {url, size, onLoadEnd, opacity = 1} = this.props return ( <NativeImage source={url} onLoadEnd={onLoadEnd} style={{ borderRadius: size / 2, bottom: 0, height: size, left: 0, opacity, position: 'absolute', right: 0, top: 0, width: size, }} /> ) } } const borderOffset = -1 const borderSize = 2 // Layer on top to extend outside of the image const Border = ({borderColor, size}) => ( <Box style={{ borderColor, borderRadius: size / 2, borderWidth: borderSize, bottom: borderOffset, left: borderOffset, position: 'absolute', right: borderOffset, top: borderOffset, }} /> ) class AvatarRender extends PureComponent<void, Props, State> { state: State = { loaded: false, } _mounted: boolean = false _onLoadOrError = () => { if (this._mounted) { this.setState({loaded: true}) } } componentWillReceiveProps (nextProps: Props) { if (this.props.url !== nextProps.url) { this.setState({loaded: false}) } } componentDidMount () { this._mounted = true } componentWillUnmount () { this._mounted = false } render () { const {url, onClick, style, size, loadingColor, borderColor, opacity, followIconType, followIconStyle, followIconSize, children} = this.props return ( <ClickableBox onClick={onClick} feedback={false}> <Box style={{ height: size, position: 'relative', width: size, ...style, }}> <Background loaded={this.state.loaded} loadingColor={loadingColor} size={size} /> {!!url && <UserImage opacity={opacity} onLoadEnd={this._onLoadOrError} size={size} url={url} /> } {!!borderColor && <Border borderColor={borderColor} size={size} />} {followIconType && <Icon type={followIconType} style={{...followIconStyle, width: followIconSize, height: followIconSize}} />} {children} </Box> </ClickableBox> ) } } export default AvatarRender
JavaScript
0
@@ -1960,24 +1960,54 @@ rderOffset,%0A + margin: borderSize / 2,%0A %7D%7D%0A /%3E%0A
2df4315176d1a0bac0489db2250c7f6dc1003a46
fix zoom when initial distance is 0
packages/core/3d/controller/OrbitController.js
packages/core/3d/controller/OrbitController.js
import Matrix4 from '../../math/Matrix4.js'; import GestureObserver from '../../input/GestureObserver.js'; export default class OrbitController { constructor({ matrix = new Matrix4(), domElement = window, pan = 0, tilt = 0, invertRotation = true, distance = 1, distanceMin = 0, distanceMax = Infinity, tiltMin = -Infinity, tiltMax = Infinity, tiltDisabled = false, panMin = -Infinity, panMax = Infinity, panDisabled = false, rotationEasing = .1, rotationVelocity = .005, zoomEasing = .1, zoomVelocity = .1, zoomDisabled = false, }) { this.matrix = matrix; this.invertRotation = invertRotation; this.distanceMax = distanceMax; this.distanceMin = distanceMin; this.zoomEasing = zoomEasing; this.tiltMax = tiltMax; this.tiltMin = tiltMin; this.tiltDisabled = tiltDisabled; this.panMax = panMax; this.panMin = panMin; this.panDisabled = panDisabled; this.rotationEasing = rotationEasing; this.rotationVelocity = rotationVelocity; this.zoomDisabled = zoomDisabled; this.zoomVelocity = zoomVelocity; this.baseMatrix = new Matrix4(this.matrix); this._distance = distance; this._tilt = tilt; this._pan = pan; this._panEased = this._pan; this._tiltEased = this._tilt; this._distanceEased = this._distance; this._multiTouchMode = false; domElement.addEventListener('wheel', (event) => { if (this.zoomDisabled) return; this._distance *= 1 + event.deltaY * this.zoomVelocity * .01; this._distance = Math.max(this.distanceMin, Math.min(this.distanceMax, this._distance)); }, { passive: true }); const gestureObserver = new GestureObserver((gesture) => { if (!this.panDisabled) { this._pan += (this.invertRotation ? -1 : 1) * gesture.movementX * rotationVelocity; this._pan = Math.max(this.panMin, Math.min(this.panMax, this._pan)); } if (!this.tiltDisabled) { this._tilt += (this.invertRotation ? 1 : -1) * gesture.movementY * rotationVelocity; this._tilt = Math.max(this.tiltMin, Math.min(this.tiltMax, this._tilt)); } if (!this.zoomDisabled) { this._distance /= 1 + gesture.movementScale * this.zoomVelocity * .01; this._distance = Math.max(this.distanceMin, Math.min(this.distanceMax, this._distance)); } }); gestureObserver.observe(domElement); this.update(); } get pan() { return this._pan; } set pan(value) { this._pan = value; this._panEased = value; } get tilt() { return this._tilt; } set tilt(value) { this._tilt = value; this._tiltEased = value; } get distance() { return this._distance; } set distance(value) { this._distance = value; this._distanceEased = value; } get panEased() { return this._panEased; } get tiltEased() { return this._tiltEased; } get distanceEased() { return this._distanceEased; } update() { this._tiltEased += (this._tilt - this._tiltEased) * this.rotationEasing; this._panEased += (this._pan - this._panEased) * this.rotationEasing; this._distanceEased += (this._distance - this._distanceEased) * this.zoomEasing; this.matrix.identity(); this.matrix.rotateY(this._panEased); this.matrix.rotateX(-this._tiltEased); const sinPan = Math.sin(this._panEased); const cosPan = Math.cos(this._panEased); const cosTilt = Math.cos(this._tiltEased); const sinTilt = Math.sin(this._tiltEased); this.matrix.x = this._distanceEased * sinPan * cosTilt; this.matrix.y = sinTilt * this._distanceEased; this.matrix.z = this._distanceEased * cosPan * cosTilt; this.matrix.multiply(this.baseMatrix); } }
JavaScript
0.998891
@@ -1514,11 +1514,44 @@ nce -* = +Math.max(this._distance, .001) * ( 1 + @@ -1580,32 +1580,33 @@ omVelocity * .01 +) ;%0A this._di
31da815083ceca6a459d71586037b07d31e46d22
Add micro-optimization for fancy-header example to avoid painting
examples/fancy-header/index.js
examples/fancy-header/index.js
/* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var React = require('react'); var Scroller = require('../../src/scroller'); var ScrollItem = require('../../src/scroll-item'); var Lorem = require('../lorem'); var Header = require('./header'); var FancyHeader = React.createClass({ getContentSize: function (items, scroller) { return { width: items.content.rect.width, height: items.content.rect.height + items.background.rect.height }; }, render: function () { return ( <Scroller viewport scrollingX={false} scrollingY={true} getContentSize={this.getContentSize}> <ScrollItem name="background" scrollHandler={handler}> <div className="background"> </div> </ScrollItem> <ScrollItem name="white" scrollHandler={handler}> <div className="white"> <Header /> </div> </ScrollItem> <ScrollItem name="transparent" scrollHandler={handler}> <div className="transparent"> <Header /> </div> </ScrollItem> <ScrollItem name="content" scrollHandler={handler}> <Lorem /> </ScrollItem> </Scroller> ); } }); /* Notice: It's a Scrollable best practice to use plain functions instead of React bound methods. Read more about why on the minimal example. */ function handler(x, y, self, items, scroller) { var transitionPixels = 100; var ratio = 6; var headerPos = Math.max(transitionPixels - y, 0) / ratio; if (y < 0) { headerPos = transitionPixels / ratio; } switch (self.props.name) { case "content": return { zIndex: 3, y: -y + items.background.rect.height, }; case "white": return { opacity: Math.min(1/transitionPixels * y, 1), zIndex: 5, y: headerPos, }; case "transparent": return { zIndex: 4, y: headerPos, }; case "background": return { scale: Math.max(1, 1 - (y / 400)), zIndex: 2, y: Math.min(0, -y), }; default: // during development, if I create a new <ScrollItem> this is handy // as it will sticky this element to the bottom of the <Scroller> return { zIndex: 10, y: scroller.rect.height - self.rect.height, }; } } module.exports = FancyHeader;
JavaScript
0
@@ -1826,16 +1826,201 @@ -opacity: +// this rounding to 0.001 and 0.9999 should not be needed.%0A // some browsers were causing re-paint. So I will leave this here%0A // as documentation%0A opacity: Math.max(0.001, Mat @@ -2049,17 +2049,23 @@ ls * y, -1 +0.9999) ),%0A
5b42df392c9176b03939108f710012830a84d83c
increase timeout for cloud tests
config/protractor.conf.js
config/protractor.conf.js
// An example configuration file. exports.config = { // Spec patterns are relative to the location of the spec file. They may // include glob patterns. specs: ['../test/e2e/**/*.js'], // Options to be passed to Jasmine-node. jasmineNodeOpts: { showColors: true, // Use colors in the command line report. defaultTimeoutInterval: 60000 }, baseUrl: 'http://localhost:8080', //local build: chrome chromeOnly: true, capabilities: { 'browserName': 'chrome' } };
JavaScript
0.000001
@@ -345,9 +345,10 @@ al: -6 +12 0000
0591eb395069a28fa93f8c2fa501e56061ffc624
Fix old query results showing up in develop (#6159)
packages/gatsby/src/utils/websocket-manager.js
packages/gatsby/src/utils/websocket-manager.js
const path = require(`path`) const { store } = require(`../redux`) const fs = require(`fs`) const getCachedPageData = (pagePath, directory) => { const { jsonDataPaths, pages } = store.getState() const page = pages.find(p => p.path === pagePath) const dataPath = jsonDataPaths[page.jsonName] if (typeof dataPath === `undefined`) return undefined const filePath = path.join( directory, `public`, `static`, `d`, `${dataPath}.json` ) const result = JSON.parse(fs.readFileSync(filePath, `utf-8`)) return { result, path: pagePath, } } const getRoomNameFromPath = path => `path-${path}` class WebsocketManager { constructor() { this.isInitialised = false this.activePaths = new Set() this.pageResults = new Map() this.staticQueryResults = new Map() this.websocket this.programDir this.init = this.init.bind(this) this.getSocket = this.getSocket.bind(this) this.emitPageData = this.emitPageData.bind(this) this.emitStaticQueryData = this.emitStaticQueryData.bind(this) } init({ server, directory }) { this.programDir = directory this.websocket = require(`socket.io`)(server) this.websocket.on(`connection`, s => { let activePath = null // Send already existing static query results this.staticQueryResults.forEach((result, id) => { this.websocket.send({ type: `staticQueryResult`, payload: { id, result }, }) }) this.pageResults.forEach((result, path) => { this.websocket.send({ type: `pageQueryResult`, payload: result, }) }) const leaveRoom = path => { s.leave(getRoomNameFromPath(path)) const leftRoom = this.websocket.sockets.adapter.rooms[ getRoomNameFromPath(path) ] if (!leftRoom || leftRoom.length === 0) { this.activePaths.delete(path) } } s.on(`registerPath`, path => { s.join(getRoomNameFromPath(path)) activePath = path this.activePaths.add(path) if (this.pageResults.has(path)) { this.websocket.send({ type: `pageQueryResult`, payload: this.pageResults.get(path), }) } else { const result = getCachedPageData(path, this.programDir) this.pageResults.set(path, result) this.websocket.send({ type: `pageQueryResult`, payload: this.pageResults.get(path), }) } }) s.on(`disconnect`, s => { leaveRoom(activePath) }) s.on(`unregisterPath`, path => { leaveRoom(path) }) }) this.isInitialised = true } getSocket() { return this.isInitialised && this.websocket } emitStaticQueryData(data) { this.staticQueryResults.set(data.id, data.result) if (this.isInitialised) { this.websocket.send({ type: `staticQueryResult`, payload: data }) } } emitPageData(data) { if (this.isInitialised) { this.websocket.send({ type: `pageQueryResult`, payload: data }) } this.pageResults.set(data.path, data) } } const manager = new WebsocketManager() module.exports = manager
JavaScript
0.000031
@@ -3131,20 +3131,18 @@ et(data. -path +id , data)%0A
df3c0d64dac7a7e9ae106b920e35c731d29a1e5d
Fix typo in help message
bin/autometa.js
bin/autometa.js
#!/usr/bin/env node var program = require('commander'); var autometa = require('../lib/autometa.js'); var package = require('../package.json'); var templates = []; var overwrite = false; program .version(package.version, '-v, --version') .usage('[options] <Excel spreadsheet>') .option('-f, --force', 'overwrite existing files') .option('-p, --print-templates-dirs', 'print templates direcotries') .option('-o, --output <filename>', 'set output file name of first\n' + ' sheet manually', String) .option('-r, --register-templates <files>', 'register template files', String) .option('-t, --set-template-id <Template ID>', 'set a Template ID manually', String); program.on('--help', function () { console.log(" Environment variable:"); console.log(" AUTOMETA_TEMPLATES Set \":\"-separeted list of directories,"); console.log(" If you want to change templates directory."); }); program.parse(process.argv); if(process.version === 'v0.10.31') { var msgs = [ "node v0.10.31 is known to crash on OSX and Linux, refusing to proceed.", "see https://github.com/joyent/node/issues/8208 for the relevant node issue" ]; msgs.forEach(function(m) { console.error(m); }); process.exit(1); } // if specified template option if(program.setTemplateId) { if(!autometa.setTemplateID(program.setTemplateId)){ console.error("Failed to set the Template ID."); process.exit(1); } } // if specified force option if(program.force) { overwrite = true; } // if specified register option if(program.registerTemplates) { templates.push(program.registerTemplates); templates = templates.concat(program.args); autometa.registerTemplates(templates,overwrite); process.exit(0); } // if specified print-templates-dirs option if(program.printTemplatesDirs) { console.log(autometa.getTemplatesDirs()); process.exit(0); } if(!program.args.length) { // No filename found program.help(); } else { // Filename found if(autometa.generateFile(program.args[0],program.output,overwrite)) { // Success to generate file process.exit(0); } else { console.error("Failed to generate file."); process.exit(1); } }
JavaScript
0.001912
@@ -396,10 +396,10 @@ irec -o t +o ries @@ -851,17 +851,17 @@ %5C%22-separ -e +a ted list
806e4927c9d83c009aed3dbeea12e69c50103ddb
fix reverse-proxy example require path (#1067)
examples/http/reverse-proxy.js
examples/http/reverse-proxy.js
/* reverse-proxy.js: Example of reverse proxying (with HTTPS support) Copyright (c) 2015 Alberto Pose <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var http = require('http'), net = require('net'), httpProxy = require('http-proxy'), url = require('url'), util = require('util'); var proxy = httpProxy.createServer(); var server = http.createServer(function (req, res) { util.puts('Receiving reverse proxy request for:' + req.url); proxy.web(req, res, {target: req.url, secure: false}); }).listen(8213); server.on('connect', function (req, socket) { util.puts('Receiving reverse proxy request for:' + req.url); var serverUrl = url.parse('https://' + req.url); var srvSocket = net.connect(serverUrl.port, serverUrl.hostname, function() { socket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node-Proxy\r\n' + '\r\n'); srvSocket.pipe(socket); socket.pipe(srvSocket); }); }); // Test with: // curl -vv -x http://127.0.0.1:8213 https://www.google.com // curl -vv -x http://127.0.0.1:8213 http://www.google.com
JavaScript
0
@@ -1261,24 +1261,34 @@ = require(' +../../lib/ http-proxy')
01b733405c58539ac889112de8500e1752e4d852
set document state of new objects
graphql/directives.js
graphql/directives.js
const { parse } = require('graphql/language'); const capitalize = require('lodash/upperFirst'); const { list, one, write, addInputTypes } = require('./utils'); const hasDirective = (ast, model, directive) => { const schema = ast.definitions.find(({ name }) => name && name.value === model); return schema.directives.filter(({ name }) => name && name.value === 'state').length; }; module.exports = ({ adapter, resolvers }) => ({ // Type collection: { name: 'mongodb', description: 'Marks a type as a relative.', resolveStatic: { enter(node) { const type = parse(` type ___Model { id: String } `).definitions[0]; node.fields = node.fields.concat(type.fields); }, }, }, tags: { name: 'mongodb', description: 'Marks a type as a relative.', resolveStatic: { enter(node) { const type = parse(` type ___Model { tags: [String] } `).definitions[0]; node.fields = node.fields.concat(type.fields); }, }, }, state: { name: 'state', description: 'Marks a type as a relative.', resolveStatic: { enter(node) { const type = parse(` type ___Model { state: DOCUMENT_STATE } `).definitions[0]; node.fields = node.fields.concat(type.fields); }, }, hooks: { before: (args, { model, isMutation, returnType }, { ast }) => { if (!isMutation && returnType.toString().indexOf('[') === 0 && hasDirective(ast, model, 'state')) { const query = (args.query || {}); if (!query.state) { query.state = { eq: 'PUBLISHED' }; args.query = query; } return args; } }, }, }, stamp: { name: 'stamp', description: 'Marks a type as a relative.', resolveStatic: { enter(node) { const type = parse(` type ___Stamps { createdAt: DateTime updatedAt: DateTime createdBy: User @relation updatedBy: User @relation } `).definitions[0]; node.fields = node.fields.concat(type.fields); }, leave(node) { resolvers.Query = resolvers.Query || {}; resolvers.Mutation = resolvers.Mutation || {}; resolvers[node.name.value] = resolvers[node.name.value] || {}; }, }, }, // Field relation: { // aggregation name: 'relation', description: 'Marks a type as a relative.', resolveStatic: { enter(node, directive, { resolvers, parent, ancestors, ast }) { const parentName = ancestors[ancestors.length - 1].name.value; const isList = node.type.kind === 'ListType'; const type = isList ? node.type.type : node.type; const collectionName = type.name.value; if (directive.arguments.find(x => x.name.value === 'ignore')) return; if (!resolvers[parentName]) resolvers[parentName] = {}; // one-to-one / one-to-many if (!isList) { const idType = parse(` type ___Field { ${node.name.value}Id: String } `).definitions[0]; idType.fields.forEach(field => parent.push(field)); // one-to-many property set (parent -> [children]) if (directive.arguments.length > 0) { const property = directive.arguments.find(x => x.name.value === 'property'); const relationType = directive.arguments.find(x => x.name.value === 'type'); if (property && relationType && relationType.value.value) { const relIsList = relationType.value.value === 'one-to-many'; const propType = relIsList ? parse(` type ___Field { ${property.value.value}: [${parentName}] } `).definitions[0] : parse(` type ___Field { ${property.value.value}: ${parentName} } `).definitions[0]; const def = ast.definitions.find(x => x.name && x.name.value === node.type.name.value); propType.fields.forEach(field => def.fields.push(field)); resolvers[parentName][property.value.value] = relIsList ? list(collectionName, property.value.value, node.name.value) : one(collectionName, property.value.value, node.name.value); } } } else { addInputTypes(collectionName, ast); const argType = parse(` type Query { func(query: ${collectionName}Query, sort: ${collectionName}Sort, limit: Int, skip: Int): [${collectionName}] } `).definitions[0].fields[0]; argType.arguments.forEach(field => node.arguments.push(field)); const idType = parse(` type ___Field { ${node.name.value}Ids: [String] } `).definitions[0]; idType.fields.forEach(field => parent.push(field)); } resolvers[parentName][node.name.value] = isList ? list(collectionName, node.name.value) : one(collectionName, node.name.value); }, }, }, // Query/Mutation query: { name: 'query', description: 'Marks a type as a relative.', resolveStatic: { enter2(node, directive, { ast }) { const isList = node.type.kind === 'ListType'; const type = isList ? node.type.type : node.type; const collectionName = type.name.value; addInputTypes(collectionName, ast); const field = isList ? parse(` type Query { func(query: ${collectionName}Query, sort: ${collectionName}Sort, limit: Int, skip: Int): [${collectionName}] } `).definitions[0].fields[0] : parse(` type Query { func(id: String, query: ${collectionName}Query): ${collectionName} } `).definitions[0].fields[0]; node.arguments = node.arguments.concat(field.arguments); resolvers.Query[node.name.value] = isList ? list(collectionName) : one(collectionName); }, }, }, mutate: { name: 'mutate', description: 'Marks a type as a relative.', resolveStatic: { enter2(node, directive, { ast }) { const type = node.type; const collectionName = type.name.value; const field = parse(` type Mutation { func(id: String, input: ${capitalize(type.name.value)}Input, operationType: OPERATION_TYPE): ${type.name.value} } `).definitions[0].fields[0]; node.arguments = node.arguments.concat(field.arguments); resolvers.Mutation[node.name.value] = write(collectionName, node.name.value); }, }, }, });
JavaScript
0.000002
@@ -1775,24 +1775,161 @@ ;%0A %7D%0A + else if (isMutation && args.input && !args.input.state) %7B%0A args.input.state = 'DRAFT';%0A return args;%0A %7D%0A %7D,%0A
416340fa161f679a2d844b0660a9d016b765f6cd
Move require into conditional.
bin/eslint_d.js
bin/eslint_d.js
#!/usr/bin/env node 'use strict'; function start() { require('../lib/launcher')(); } var cmd = process.argv[2]; if (cmd === 'start') { start(); } else if (cmd === '-v' || cmd === '--version') { console.log('v%s (eslint_d v%s)', require('eslint/package.json').version, require('../package.json').version); } else if (cmd === '-h' || cmd === '--help') { var options = require('../lib/options'); console.log(options.generateHelp()); } else { var client = require('../lib/client'); if (cmd === 'restart') { client.stop(function () { process.nextTick(start); }); } else { var commands = ['stop', 'status', 'restart']; if (commands.indexOf(cmd) === -1) { var concat = require('concat-stream'); var useStdIn = (process.argv.indexOf('--stdin') > -1); if (useStdIn) { process.stdin.pipe(concat({ encoding: 'string' }, function (text) { client.lint(process.argv.slice(2), text); })); } else { client.lint(process.argv.slice(2)); } } else { client[cmd](process.argv.slice(3)); } } }
JavaScript
0
@@ -701,53 +701,8 @@ ) %7B%0A - var concat = require('concat-stream');%0A @@ -777,24 +777,71 @@ useStdIn) %7B%0A + var concat = require('concat-stream');%0A proc
581debb28e82e5f97db4d8d1066c249157f44c77
Fix test
lib/tests/step.with.spec.js
lib/tests/step.with.spec.js
var chai = require('chai') var sinon = require('sinon') var expect = chai.expect chai.use(require('sinon-chai')) chai.use(require('chai-properties')) var controllers = require('../autoBlock') describe('step .with', () => { var sandbox beforeEach(() => { sandbox = sinon.sandbox.create() }) afterEach(() => { sandbox.restore() }) it('object notation', (done) => { var one = sinon.stub().callsArgWith(1, null, 'alpha') var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'}) var three = (results, cb) => { expect(results).to.have.properties({ a: 'alpha', b: { c: 'delta' } }) cb() } var final = (err, response) => { expect(err).to.not.exist done() } var controller = { data: { event: { foo: 'bar' } }, done: final } controller.block = { 'one': { func: one }, 'two': { func: two }, 'three': { func: three, with: { 'a': 'one', 'b.c': 'two.beta' } } } controllers.run(controller) }) it('array notation', (done) => { var one = sinon.stub().callsArgWith(1, null, 'alpha') var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'}) var three = (a, b, cb) => { expect(a).to.eql('alpha') expect(b).to.eql('delta') cb() } var final = (err, response) => { expect(err).to.not.exist done() } var controller = { data: { event: { foo: 'bar' } }, done: final } controller.block = { 'one': { func: one }, 'two': { func: two }, 'three': { func: three, with: ['one', 'two.beta'] } } controllers.run(controller) }) it('missing', (done) => { var one = sinon.stub().callsArgWith(1, null, 'alpha') var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'}) var three = (results, cb) => { expect(results).to.have.properties({ a: 'alpha', b: { c: 'delta' } }) cb() } var final = (err, response) => { expect(err).to.not.exist done() } var controller = { data: { event: { foo: 'bar' } }, done: final } controller.block = { 'one': { func: one }, 'two': { func: two }, 'three': { func: three, with: { 'a': 'one', 'b.c': 'two.beta' } } } controllers.run(controller) }) })
JavaScript
0.000004
@@ -2077,36 +2077,16 @@ rties(%7B%0A - a: 'alpha',%0A @@ -2512,32 +2512,38 @@ 'a': 'one +.alpha ',%0A 'b.
d0a2bf189d41f3074b0c48f516e52bfb8901590c
Fix `error on missing` argument so it works from CLI (#43)
bin/exorcist.js
bin/exorcist.js
#!/usr/bin/env node 'use strict'; var minimist = require('minimist') , fs = require('fs') , path = require('path') , exorcist = require('../') ; function onerror(err) { console.error(err.toString()); process.exit(err.errno || 1); } function usage() { var usageFile = path.join(__dirname, 'usage.txt'); fs.createReadStream(usageFile).pipe(process.stdout); return; } (function damnYouEsprima() { var argv = minimist(process.argv.slice(2) , { boolean: [ 'h', 'help', 'e', 'error-on-missing' ] , string: [ 'url', 'u', 'root', 'r', 'base', 'b' ] }); if (argv.h || argv.help) return usage(); var mapfile = argv._.shift(); if (!mapfile) { console.error('Missing map file'); return usage(); } var url = argv.url || argv.u , root = argv.root || argv.r , base = argv.base || argv.b , errorOnMissing = argv.errorOnMissing || argv.e; mapfile = path.resolve(mapfile); process.stdin .pipe(exorcist(mapfile, url, root, base, errorOnMissing)) .on('error', onerror) .on('missing-map', console.error.bind(console)) .pipe(process.stdout); })()
JavaScript
0
@@ -930,16 +930,44 @@ %7C argv.e + %7C%7C argv%5B'error-on-missing'%5D ;%0A%0Amapfi
68788bbc78967fbd7593424e5dd8a797f9b5ff1e
Remove unused channelList property
app/components/canvas-channel-list/component.js
app/components/canvas-channel-list/component.js
import Ember from 'ember'; const { computed } = Ember; export default Ember.Component.extend({ localClassNames: ['canvas-channel-list'], isEditingChannels: false, canvasChannels: computed('channelIds.[]', 'channels.[]', function() { return this.get('channelIds') .map(id => this.get('channels').findBy('id', id)) .compact(); }), channelList: computed('canvasChannels.[]', function() { return this.get('canvasChannels') .mapBy('name') .join(', '); }), selectedChannels: computed(function() { return this.get('canvasChannels'); }), actions: { persistChannels() { this.set('isEditingChannels', false); this.get('updateCanvasChannels')(this.get('selectedChannels')); } } });
JavaScript
0
@@ -372,169 +372,8 @@ ),%0A%0A - channelList: computed('canvasChannels.%5B%5D', function() %7B%0A return this.get('canvasChannels')%0A .mapBy('name')%0A .join(', ');%0A %7D),%0A%0A se
1b9de49b794f201f78cf1ae1b017cf4defcfe1a3
Update tests
test/specs/style_manager/model/Properties.js
test/specs/style_manager/model/Properties.js
import Editor from 'editor/model/Editor'; describe('StyleManager properties logic', () => { let obj; let em; let domc; let dv; let cssc; let sm; let cmp; let rule1; let rule2; beforeEach(() => { em = new Editor({ mediaCondition: 'max-width', avoidInlineStyle: true, styleManager: { custom: true }, }); domc = em.get('DomComponents'); cssc = em.get('CssComposer'); dv = em.get('DeviceManager'); sm = em.get('SelectorManager'); obj = em.get('StyleManager'); em.get('PageManager').onLoad(); cmp = domc.addComponent(`<div class="cls"></div>`); [rule1, rule2] = cssc.addRules(` .cls { color: red; } @media (max-width: 992px) { .cls { color: blue; } } `); }); afterEach(() => { obj = null; em.destroy(); }); describe('Composite type', () => { const sectorTest = 'sector-test'; const propTest = 'padding'; const propInTest = 'padding-top'; let compTypeProp; let compTypePropInn; beforeEach(() => { obj.addSector(sectorTest, { properties: [ { extend: propTest, detached: true, }, ], }); compTypeProp = obj.getProperty(sectorTest, propTest); compTypePropInn = compTypeProp.getProperty(propInTest); em.setSelected(cmp); obj.__upSel(); }); test('Property exists', () => { expect(compTypeProp).toBeTruthy(); expect(compTypeProp.getProperties().length).toBe(4); }); test('Has inner property', () => { expect(compTypePropInn).toBeTruthy(); }); test('Inner property has no value', () => { expect(compTypeProp.hasValue()).toBe(false); expect(compTypePropInn.hasValue()).toBe(false); }); test('Rule selected', () => { expect(obj.getLastSelected()).toBe(rule1); }); test('Updating inner property, it reflects on the rule', () => { compTypePropInn.upValue('55%'); const style = rule1.getStyle(); const otherProps = Object.keys(style).filter(p => p.indexOf('padding') >= 0 && p !== propInTest); expect(style[propInTest]).toBe('55%'); expect(compTypeProp.hasValue()).toBe(true); expect(compTypePropInn.hasValue()).toBe(true); otherProps.forEach(prop => expect(style[prop]).toBe('')); }); }); });
JavaScript
0.000001
@@ -2306,16 +2306,26 @@ (prop =%3E + %7B%0A expect( @@ -2345,16 +2345,141 @@ toBe('') +;%0A if (prop !== propTest) %7B%0A expect(compTypeProp.getProperty(prop).hasValue()).toBe(false);%0A %7D%0A %7D );%0A %7D
062ca1371a76457e27dda33d6803dfa239775ba8
add log option to CLI
bin/gen-docs.js
bin/gen-docs.js
#!/usr/bin/env node var path = require('canonical-path'); var myArgs = require('optimist') .usage('Usage: $0 path/to/mainPackage [path/to/other/packages ...]') .demand(1) .argv; var Dgeni = require('dgeni'); // Extract the paths to the packages from the command line arguments var packagePaths = myArgs._; // Require each of these packages and then create a new dgeni using them var packages = packagePaths.map(function(packagePath) { if ( packagePath.indexOf('.') === 0 ) { packagePath = path.resolve(packagePath); } return require(packagePath); }); var dgeni = new Dgeni(packages); // Run the document generation dgeni.generate().then(function() { console.log('Finished generating docs'); }).done();
JavaScript
0.000001
@@ -152,19 +152,33 @@ ges ...%5D + %5B--log level%5D ')%0A - .deman @@ -578,16 +578,284 @@ );%0A%7D);%0A%0A +var logLevel = myArgs.log %7C%7C myArgs.l;%0Aif ( logLevel ) %7B%0A // Add CLI package (to override settings from other packages)%0A packages.push(new Dgeni.Package('cli-package', %5B'base'%5D).config(function(log) %7B%0A // override log settings%0A log.level = logLevel;%0A %7D));%0A%7D%0A%0A var dgen @@ -989,16 +989,16 @@ docs');%0A - %7D).done( @@ -999,8 +999,9 @@ .done(); +%0A
efd37987aa1f518e6bcdd1f1d252b3d73b4f69fa
Remove iit
test/unit/core/directives/uiGridCell.spec.js
test/unit/core/directives/uiGridCell.spec.js
describe('uiGridCell', function () { var gridCell, $scope, $compile, $timeout, GridColumn, recompile, grid, uiGridConstants; beforeEach(module('ui.grid')); beforeEach(inject(function (_$compile_, $rootScope, _$timeout_, _GridColumn_, gridClassFactory, _uiGridConstants_) { $scope = $rootScope; $compile = _$compile_; $timeout = _$timeout_; GridColumn = _GridColumn_; uiGridConstants = _uiGridConstants_; $scope.grid = gridClassFactory.createGrid(); $scope.col = new GridColumn({name: 'col1', cellClass: 'testClass'}, 0, $scope.grid); $scope.col.cellTemplate = '<div class="ui-grid-cell-contents">{{COL_FIELD}}</div>'; //override getCellValue $scope.grid.getCellValue = function (row, col) { return 'val'; }; $scope.rowRenderIndex = 2; $scope.colRenderIndex = 2; recompile = function () { gridCell = angular.element('<div ui-grid-cell/>'); $compile(gridCell)($scope); $scope.$digest(); }; })); describe('compile and link tests', function () { it('should have a value', inject(function () { recompile(); expect(gridCell).toBeDefined(); expect(gridCell.text()).toBe('val'); })); it('should have the cellClass class', inject(function () { recompile(); var displayHtml = gridCell.html(); expect(gridCell.hasClass('testClass')).toBe(true); })); it('should get cellClass from function, and remove it when data changes', inject(function () { $scope.col.cellClass = function (grid, row, col, rowRenderIndex, colRenderIndex) { if (rowRenderIndex === 2 && colRenderIndex === 2) { if ( col.noClass ){ return ''; } else { return 'funcCellClass'; } } }; recompile(); var displayHtml = gridCell.html(); expect(gridCell.hasClass('funcCellClass')).toBe(true); $scope.col.noClass = true; $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); expect(gridCell.hasClass('funcCellClass')).toBe(false); })); /* Not a valid test - track by col.name it('should notice col changes and update cellClass', inject(function () { $scope.col.cellClass = function (grid, row, col, rowRenderIndex, colRenderIndex) { if (rowRenderIndex === 2 && colRenderIndex === 2) { if ( col.noClass ){ return ''; } else { return 'funcCellClass'; } } }; recompile(); var displayHtml = gridCell.html(); expect(gridCell.hasClass('funcCellClass')).toBe(true); $scope.col = new GridColumn({name: 'col2'}, 0, $scope.grid); $scope.$digest(); expect(gridCell.hasClass('funcCellClass')).toBe(false); })); */ }); // Don't run this on IE9. The behavior looks correct when testing interactively but these tests fail if (!navigator.userAgent.match(/MSIE\s+9\.0/)) { iit("should change a column's class when its uid changes", inject(function (gridUtil, $compile, uiGridConstants) { // Reset the UIDs (used by columns) so they're fresh and clean gridUtil.resetUids(); // Set up a couple basic columns $scope.gridOptions = { columnDefs: [{ field: 'name', width: 100 }, { field: 'age', width: 50 }], data: [ { name: 'Bob', age: 50 } ] }; // Create a grid elements var gridElm = angular.element('<div ui-grid="gridOptions" style="width: 400px; height: 300px"></div>'); // Compile the grid and attach it to the document, as the widths won't be right if it's unattached $compile(gridElm)($scope); document.body.appendChild(gridElm[0]); $scope.$digest(); // Get the first column and its root column class var firstCol = $(gridElm).find('.ui-grid-cell').first(); var firstHeaderCell = $(gridElm).find('.ui-grid-header-cell').first(); var classRegEx = new RegExp('^' + uiGridConstants.COL_CLASS_PREFIX); var class1 = _(firstCol[0].className.split(/\s+/)).find(function(c) { return classRegEx.test(c); }); // The first column should be 100px wide because we said it should be expect(firstCol.outerWidth()).toEqual(100, 'first cell is 100px, counting border'); expect(firstHeaderCell.outerWidth()).toEqual(100, "header cell is 100px, counting border"); // Now swap the columns in the column defs $scope.gridOptions.columnDefs = [{ field: 'age', width: 50 }, { field: 'name', width: 100 }]; $scope.$digest(); $timeout.flush(); var firstColAgain = $(gridElm).find('.ui-grid-cell').first(); var firstHeaderCellAgain = $(gridElm).find('.ui-grid-header-cell').first(); var class2 = _(firstColAgain[0].className.split(/\s+/)).find(function(c) { return classRegEx.test(c); }); // The column root classes should have changed expect(class2).not.toEqual(class1); // The first column should now be 50px wide expect(firstColAgain.outerWidth()).toEqual(50, 'first cell again is 50px, counting border'); expect(firstHeaderCellAgain.outerWidth()).toEqual(50, 'header cell again is 50px, counting border'); // ... and the last column should now be 100px wide var lastCol = $(gridElm).find('.ui-grid-cell').last(); var lastHeaderCell = $(gridElm).find('.ui-grid-header-cell').last(); expect(lastCol.outerWidth()).toEqual(100, 'last cell again is 100px, counting border'); expect(lastHeaderCell.outerWidth()).toEqual(100, 'last header cell again is 100px, counting border'); angular.element(gridElm).remove(); })); } });
JavaScript
0.000009
@@ -2946,17 +2946,16 @@ ) %7B%0A -i it(%22shou
7efbf96dce846af83a08f6d4ae1c59cc94559237
Send JWT token as string instead of an object
examples/server/node/server.js
examples/server/node/server.js
/** * (c) 2014 Sahat Yalkabov <[email protected]> * License: MIT */ var _ = require('lodash'); var bcrypt = require('bcryptjs'); var bodyParser = require('body-parser'); var crypto = require('crypto'); var express = require('express'); var logger = require('morgan'); var jwt = require('jwt-simple'); var methodOverride = require('method-override'); var moment = require('moment'); var mongoose = require('mongoose'); var path = require('path'); var userSchema = new mongoose.Schema({ email: { type: String, unique: true, lowercase: true }, password: String, facebook: { id: Number, email: String, firstName: String, lastName: String, displayName: String, link: String, locale: String }, google: String, twitter: String }); userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.genSalt(10, function(err, salt) { if (err) return next(err); bcrypt.hash(user.password, salt, function(err, hash) { if (err) return next(err); user.password = hash; next(); }); }); }); userSchema.methods.comparePassword = function(candidatePassword, done) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return done(err); done(null, isMatch); }); }; var User = mongoose.model('User', userSchema); function ensureAuthenticated(req, res, next) { if (req.headers.authorization) { var token = req.headers.authorization.split(' ')[1]; try { var decoded = jwt.decode(token, app.get('tokenSecret')); if (decoded.exp <= Date.now()) { res.send(400, 'Access token has expired'); } else { User.findById(decoded.prn, '-password', function(err, user) { req.user = user; return next(); }); } } catch (err) { return next(); } } else { return res.send(401); } } function getJwtToken(user) { var payload = { prn: user._id, exp: moment().add('days', 7).valueOf() }; return jwt.encode(payload, app.get('tokenSecret')); } mongoose.connect('localhost'); var app = express(); app.set('port', process.env.PORT || 3000); app.set('tokenSecret', 'keyboard cat'); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(methodOverride()); app.use(express.static(path.join(__dirname, '../../client'))); app.use(express.static(path.join(__dirname, '../../..'))); app.post('/auth/login', function(req, res, next) { User.findOne({ email: req.body.email }, function(err, user) { if (!user) return res.send(401, 'User does not exist'); user.comparePassword(req.body.password, function(err, isMatch) { if (!isMatch) return res.send(401, 'Invalid email and/or password'); var token = getJwtToken(user); res.send({ token: token }); }); }); }); app.post('/auth/signup', function(req, res, next) { var user = new User({ email: req.body.email, password: req.body.password }); user.save(function(err) { if (err) return next(err); res.send(200); }); }); app.post('/auth/facebook', function(req, res, next) { var profile = req.body.profile; var signedRequest = req.body.signedRequest; var encodedSignature = signedRequest.split('.')[0]; var payload = signedRequest.split('.')[1]; var appSecret = '298fb6c080fda239b809ae418bf49700'; var expectedSignature = crypto.createHmac('sha256', appSecret).update(payload).digest('base64'); expectedSignature = expectedSignature.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); if (encodedSignature !== expectedSignature) { return res.send(400, 'Bad signature'); } User.findOne({ 'facebook.id': profile.id }, function(err, existingUser) { if (existingUser) return res.send(existingUser); var user = new User(); user.facebook.id = profile.id; user.facebook.email = profile.email; user.facebook.firstName = profile.first_name; user.facebook.lastName = profile.last_name; user.facebook.displayName = profile.name; user.facebook.link = profile.link; user.facebook.locale = profile.locale; user.save(function(err) { if (err) return next(err); res.send(user); }); }); }); app.get('/api/me', ensureAuthenticated, function(req, res) { res.send(req.user); }); app.use(function(err, req, res, next) { console.error(err.stack); res.send(500, { error: err.message }); }); app.listen(app.get('port'), function() { console.log('Express server listening on port ' + app.get('port')); });
JavaScript
0
@@ -3676,16 +3676,17 @@ );%0A %7D%0A%0A +%0A User.f @@ -4194,24 +4194,61 @@ next(err);%0A + var token = getJwtToken(user);%0A res.se @@ -4250,20 +4250,21 @@ es.send( -user +token );%0A %7D
05c8404c626391ce054072991e8f702e9517c0d0
Fix #254 use https module for xhr requests within node if needed
lib/transport/driver/xhr.js
lib/transport/driver/xhr.js
'use strict'; var EventEmitter = require('events').EventEmitter , inherits = require('inherits') , http = require('http') , URL = require('url-parse') ; var debug = function() {}; if (process.env.NODE_ENV !== 'production') { debug = require('debug')('sockjs-client:driver:xhr'); } function XhrDriver(method, url, payload, opts) { debug(method, url, payload); var self = this; EventEmitter.call(this); var parsedUrl = new URL(url); var options = { method: method , hostname: parsedUrl.hostname.replace(/\[|\]/g, '') , port: parsedUrl.port , path: parsedUrl.pathname + (parsedUrl.query || '') , headers: opts && opts.headers , agent: false }; this.req = http.request(options, function(res) { res.setEncoding('utf8'); var responseText = ''; res.on('data', function(chunk) { debug('data', chunk); responseText += chunk; self.emit('chunk', 200, responseText); }); res.once('end', function() { debug('end'); self.emit('finish', res.statusCode, responseText); self.req = null; }); }); this.req.on('error', function(e) { debug('error', e); self.emit('finish', 0, e.message); }); if (payload) { this.req.write(payload); } this.req.end(); } inherits(XhrDriver, EventEmitter); XhrDriver.prototype.close = function() { debug('close'); this.removeAllListeners(); if (this.req) { this.req.abort(); this.req = null; } }; XhrDriver.enabled = true; XhrDriver.supportsCORS = true; module.exports = XhrDriver;
JavaScript
0
@@ -120,16 +120,45 @@ 'http')%0A + , https = require('https')%0A , URL @@ -704,16 +704,81 @@ e%0A %7D;%0A%0A + var protocol = parsedUrl.protocol === 'https:' ? https : http;%0A this.r @@ -782,20 +782,24 @@ s.req = -http +protocol .request
5e070701c578ccfb2fc0c31d4106b331f5a132ca
Fix this scope
lib/transports/websocket.js
lib/transports/websocket.js
'use strict'; var util = require('util'); var WildEmitter = require('wildemitter'); var async = require('async'); var WS = (require('faye-websocket') && require('faye-websocket').Client) ? require('faye-websocket').Client : window.WebSocket; var WS_OPEN = 1; function WSConnection(sm, stanzas) { var self = this; WildEmitter.call(this); self.sm = sm; self.closing = false; self.stanzas = { Open: stanzas.getDefinition('open', 'urn:ietf:params:xml:ns:xmpp-framing', true), Close: stanzas.getDefinition('close', 'urn:ietf:params:xml:ns:xmpp-framing', true), StreamError: stanzas.getStreamError() }; self.sendQueue = async.queue(function (data, cb) { if (self.conn) { if (typeof data !== 'string') { data = data.toString(); } data = new Buffer(data, 'utf8').toString(); self.emit('raw:outgoing', data); if (self.conn.readyState === WS_OPEN) { self.conn.send(data); } } cb(); }, 1); self.on('connected', function () { self.send(self.startHeader()); }); self.on('raw:incoming', function (data) { var stanzaObj, err; data = data.trim(); if (data === '') { return; } try { stanzaObj = stanzas.parse(data); } catch (e) { err = new this.stanzas.StreamError({ condition: 'invalid-xml' }); self.emit('stream:error', err, e); self.send(err); return self.disconnect(); } if (stanzaObj._name === 'openStream') { self.hasStream = true; self.stream = stanzaObj; return self.emit('stream:start', stanzaObj.toJSON()); } if (stanzaObj._name === 'closeStream') { self.emit('stream:end'); return self.disconnect(); } if (!stanzaObj.lang && self.stream) { stanzaObj.lang = self.stream.lang; } self.emit('stream:data', stanzaObj); }); } util.inherits(WSConnection, WildEmitter); WSConnection.prototype.connect = function (opts) { var self = this; self.config = opts; self.hasStream = false; self.closing = false; self.conn = new WS(opts.wsURL, 'xmpp'); self.conn.onerror = function (e) { e.preventDefault(); self.emit('disconnected', self); }; self.conn.onclose = function () { self.emit('disconnected', self); }; self.conn.onopen = function () { self.sm.started = false; self.emit('connected', self); }; self.conn.onmessage = function (wsMsg) { self.emit('raw:incoming', new Buffer(wsMsg.data, 'utf8').toString()); }; }; WSConnection.prototype.startHeader = function () { return new this.stanzas.Open({ version: this.config.version || '1.0', lang: this.config.lang || 'en', to: this.config.server }); }; WSConnection.prototype.closeHeader = function () { return new this.stanzas.Close(); }; WSConnection.prototype.disconnect = function () { if (this.conn && !this.closing && this.hasStream) { this.closing = true; this.send(this.closeHeader()); } else { this.hasStream = false; this.stream = undefined; if (this.conn.readyState === WS_OPEN) { this.conn.close(); } this.conn = undefined; } }; WSConnection.prototype.restart = function () { var self = this; self.hasStream = false; self.send(this.startHeader()); }; WSConnection.prototype.send = function (data) { this.sendQueue.push(data); }; module.exports = WSConnection;
JavaScript
0.000101
@@ -1494,28 +1494,28 @@ err = new -this +self .stanzas.Str
25668c2c8c1ebbb7571dab393de11c6eb264a727
Split token generation between access and refresh
lib/utils/tokenGenerator.js
lib/utils/tokenGenerator.js
/** * Created by Gerard on 12/11/2014. */ module.exports.generateToken = function (options, client_id, user_id, token_fields, token_options) { token_options = token_options || {}; var issued_at = new Date(); var expires_at = new Date(issued_at.getSeconds() + (options.token_expiration || 3600)); var plainAccessToken = { type: 'accesstoken', user_id: user_id, client_id: client_id, issued_at: issued_at.toISOString(), expires_at: expires_at.toISOString(), custom_fields: token_fields }; var refreshToken = null; if (options.refresh_token) { var plainRefreshToken = { type: 'refreshtoken', user_id: user_id, client_id: client_id, custom_fields: token_fields }; refreshToken = options.serializer.stringify(plainRefreshToken); } var out = mergeObjects(token_options, { access_token: options.serializer.stringify(plainAccessToken), refresh_token: refreshToken, issued_at: issued_at, expires_in: options.token_expiration || 3600 }); return out; }; var mergeObjects = function () { var obj = {}, i = 0, il = arguments.length, key; for (; i < il; i++) { for (key in arguments[i]) { if (arguments[i].hasOwnProperty(key)) { obj[key] = arguments[i][key]; } } } return obj; };
JavaScript
0.000002
@@ -1,47 +1,44 @@ -/**%0A * Created by Gerard on 12/11/2014.%0A */ +var serializer = require('serializer');%0A %0Amod @@ -83,16 +83,25 @@ options, + user_id, client_ @@ -104,23 +104,36 @@ ent_id, -user_id +client_secret, scope , token_ @@ -353,83 +353,36 @@ n = -%7B%0A type: 'a +generateA ccess -t +T oken -',%0A user_id: user_id,%0A client_id: +(user_id, cli @@ -388,24 +388,16 @@ ient_id, -%0A issued_ @@ -402,103 +402,28 @@ d_at -: issued_at.toISOString(),%0A expires_at: expires_at.toISOString(),%0A custom_fields: +, expires_at, scope, tok @@ -431,22 +431,17 @@ n_fields -%0A %7D +) ;%0A%0A v @@ -533,85 +533,37 @@ n = -%7B%0A type: 'r +generateR efresh -t +T oken -',%0A user_id: user_id,%0A +(user_id, cli @@ -572,17 +572,17 @@ t_id -: +, client_ id,%0A @@ -581,38 +581,22 @@ ent_ -id,%0A custom_fields: +secret, scope, tok @@ -604,26 +604,17 @@ n_fields -%0A %7D +) ;%0A @@ -1261,12 +1261,844 @@ turn obj;%0A%7D; +%0A%0Avar generateAccessToken = function (user_id, client_id, issued_at, expires_at, scope, token_fields) %7B%0A var plainAccessToken = %7B%0A type: 'access_token',%0A user_id: user_id,%0A client_id: client_id,%0A issued_at: issued_at.toISOString(),%0A expires_at: expires_at.toISOString(),%0A scope: scope,%0A custom_fields: token_fields%0A %7D;%0A return plainAccessToken;%0A%7D;%0A%0Avar generateRefreshToken = function (user_id, client_id, client_secret, scope, token_fields) %7B%0A var plainRefreshToken = %7B%0A type: 'refresh_token',%0A user_id: user_id,%0A client_id: client_id,%0A client_secret: client_secret,%0A scope: scope,%0A custom_fields: token_fields%0A %7D;%0A return plainRefreshToken;%0A%7D;%0A%0Avar generateCode = function () %7B%0A return serializer.randomString(128);%0A%7D;
3b3bfff0d5ac8add656b50e66f9dc6317db7a1f7
Fix element-list specs
spec/element-list-spec.js
spec/element-list-spec.js
'use babel' import ListElement from '../lib/elements/list' import {createSuggestion} from './common' describe('Intentions list element', function() { it('has a complete working lifecycle', function() { const element = new ListElement() const suggestions = [ createSuggestion('Suggestion 1', jasmine.createSpy('suggestion.selected.0'), 'someClass', 'someIcon'), createSuggestion('Suggestion 2', jasmine.createSpy('suggestion.selected.1')) ] let dispose = jasmine.createSpy('suggestion.dispose') let rendered = element.render(suggestions, dispose) expect(rendered.refs.list.children.length).toBe(2) expect(rendered.refs.list.children[0].textContent).toBe('Suggestion 1') expect(rendered.refs.list.children[1].textContent).toBe('Suggestion 2') expect(rendered.refs.list.children[0].children[0].className).toBe('someClass icon icon-someIcon') expect(element.suggestionsIndex).toBe(-1) element.moveDown() expect(element.suggestionsIndex).toBe(0) expect(element.getActive().title).toBe(rendered.refs.list.children[0].textContent) element.moveDown() expect(element.suggestionsIndex).toBe(1) expect(element.getActive().title).toBe(rendered.refs.list.children[1].textContent) element.moveUp() expect(element.suggestionsIndex).toBe(0) expect(element.getActive().title).toBe(rendered.refs.list.children[0].textContent) element.moveUp() expect(element.suggestionsIndex).toBe(1) expect(element.getActive().title).toBe(rendered.refs.list.children[1].textContent) rendered.refs.list.children[1].children[0].dispatchEvent(new MouseEvent('click', { bubbles: true })) expect(suggestions[1].selected).toHaveBeenCalled() expect(dispose).toHaveBeenCalled() }) })
JavaScript
0
@@ -13,16 +13,17 @@ %0Aimport +%7B ListElem @@ -25,16 +25,17 @@ tElement +%7D from '. @@ -472,23 +472,24 @@ let -dispose +selected = jasmi @@ -513,23 +513,24 @@ gestion. -dispose +selected ')%0A l @@ -571,23 +571,24 @@ stions, -dispose +selected )%0A%0A e @@ -1022,35 +1022,61 @@ ect(element. -getActive() +suggestions%5Belement.suggestionsIndex%5D .title).toBe @@ -1205,35 +1205,61 @@ ect(element. -getActive() +suggestions%5Belement.suggestionsIndex%5D .title).toBe @@ -1386,35 +1386,61 @@ ect(element. -getActive() +suggestions%5Belement.suggestionsIndex%5D .title).toBe @@ -1575,19 +1575,45 @@ ent. -getActive() +suggestions%5Belement.suggestionsIndex%5D .tit @@ -1796,23 +1796,8 @@ ect( -suggestions%5B1%5D. sele @@ -1822,48 +1822,27 @@ lled -()%0A expect(dispose).toHaveBeenCalled( +With(suggestions%5B1%5D )%0A
f2024f59854208f991dadf6137bad8e7edd2f93d
Fix a spec
spec/linter-clang-spec.js
spec/linter-clang-spec.js
"use babel"; describe("The Clang Provider for AtomLinter", () => { beforeEach(() => { provider = require("../lib/main").provideLinter(); waitsForPromise(() => { return atom.packages.activatePackage("linter-clang") }); }); describe("finds issue with the code", () => { describe("in 'missing_import.c'", () => { waitsForPromise(() => { return atom.workspace.open("./files/missing_import.c").then((editor) => { console.log(editor); }); }); }); }); });
JavaScript
0.000004
@@ -1,9 +1,9 @@ -%22 +' use babe @@ -7,10 +7,9 @@ abel -%22; +' %0A%0Ade @@ -15,17 +15,17 @@ escribe( -%22 +' The Clan @@ -26,17 +26,17 @@ e Clang -P +p rovider @@ -49,17 +49,17 @@ omLinter -%22 +' , () =%3E @@ -64,33 +64,15 @@ %3E %7B%0A -%0A -beforeEach(() =%3E %7B%0A +const pro @@ -87,17 +87,17 @@ require( -%22 +' ../lib/m @@ -99,17 +99,17 @@ lib/main -%22 +' ).provid @@ -121,112 +121,8 @@ er() -;%0A%0A waitsForPromise(() =%3E %7B%0A return atom.packages.activatePackage(%22linter-clang%22)%0A %7D);%0A %7D);%0A %0A d @@ -129,17 +129,17 @@ escribe( -%22 +' finds is @@ -155,17 +155,17 @@ the code -%22 +' , () =%3E @@ -174,22 +174,22 @@ -describe(%22in ' +it('works in %22 miss @@ -204,10 +204,10 @@ rt.c -' %22 +' , () @@ -235,26 +235,24 @@ romise(() =%3E - %7B %0A ret @@ -252,15 +252,8 @@ -return atom @@ -272,10 +272,21 @@ pen( -%22. +__dirname + ' /fil @@ -308,24 +308,22 @@ rt.c -%22 +' ).then( -( editor -) =%3E @@ -353,17 +353,16 @@ (editor) -; %0A @@ -368,34 +368,28 @@ %7D) -; %0A -%7D); +) %0A %7D) -; %0A %7D) -; %0A%7D) -; %0A
024a5076264feed9cd366902f349d4609358f33f
Add failing test case that illustrates the need for α-reduction: same variable is both free and bound in the same expression
spec/interpreter.spec.js
spec/interpreter.spec.js
import { Interpreter, Variable, Func, Application } from './lib/lambda' describe('interpreter', () => { let interpreter; beforeEach(() => { interpreter = new Interpreter(); }); const test = (fixtures) => fixtures.forEach(([expr, expected, comment = '']) => { it(`should interpret ${expr} ${comment}`, () => { expect(interpreter.eval(expr).toString()).toEqual(expected); }); }) describe('β-normal form: no further β-reduction is possible', () => { test([ [ new Variable('x'), 'x', 'variable' ], [ new Func('x', new Variable('y') ), '(λx.y)', 'function' ], [ new Application( new Variable('x'), new Variable('y') ), '(xy)', 'application' ] ]); }); describe('one β-reduction until β-normal form', () => { test([ [ new Application( new Func('x', new Variable('y') ), new Variable('z') ), 'y', 'body of the function is a free variable' ], [ new Application( new Func('x', new Variable('x') ), new Variable('z') ), 'z', 'identity function' ], [ new Application( new Func('x', new Application( new Variable('x'), new Variable('y') ) ), new Variable('y') ), '(yy)', 'body of the function is an application' ], [ new Application( new Func('x', new Func('y', new Application( new Variable('y'), new Variable('x') ) ) ), new Variable('z') ), '(λy.(yz))', 'body of the function is a function' ], [ new Application( new Func('x', new Application( new Variable('y'), new Variable('x') ) ), new Func('t', new Variable('t') ) ), '(y(λt.t))', 'argument is a function' ], [ new Application( new Func('x', new Application( new Variable('y'), new Variable('x') ) ), new Application( new Variable('f'), new Variable('g') ) ), '(y(fg))', 'argument is an application' ], [ new Application( new Func('x', new Func('y', new Func('z', new Variable('x') ) ) ), new Func('t', new Variable('g') ) ), '(λy.(λz.(λt.g)))', 'body is a deeply nested expression, argument a function' ], [ new Application( new Func('x', new Application( new Variable('z'), new Func('y', new Application( new Variable('h'), new Func('z', new Variable('x') ) ) ) ) ), new Func('t', new Variable('g') ) ), '(z(λy.(h(λz.(λt.g)))))', 'body contains nested applications, argument a function' ], [ new Application( new Func('x', new Variable('x') ), new Func('x', new Variable('x') ) ), '(λx.x)', 'identity applied to identity reduces to identity' ] ]); }); describe('several β-reductions', () => { test([ [ new Application( new Func('x', new Application( new Variable('x'), new Variable('y') ) ), new Func('t', new Variable('t') ) ), 'y', 'several β-reductions' ], [ new Application( new Func('x', new Variable('y') ), new Application( new Func('x', new Application( new Variable('x'), new Variable('x') ) ), new Func('x', new Application( new Variable('x'), new Variable('x') ) ) ) ), 'y', 'several pathes to do β-reduction, leftmost redex is reduced first' ], [ new Application( new Application( new Func('x', new Func('y', new Variable('x') ) ), new Func('x', new Variable('x') ) ), new Application( new Func('x', new Application( new Variable('x'), new Variable('x') ) ), new Func('x', new Application( new Variable('x'), new Variable('x') ) ) ) ), '(λx.x)', 'several pathes to do β-reduction, several β-reductions, leftmost redex is reduced first' ], [ new Application( new Application( new Func('x', new Func('y', new Variable('x') ) ), new Func('x', new Variable('x') ) ), new Func('x', new Application( new Variable('x'), new Variable('x') ) ) ), '(λx.x)', 'two reductions to identity' ] ]); }); describe('infinite loop detection', () => { it(`should detect`, () => { const expr = new Application( new Func('x', new Application( new Variable('x'), new Variable('x') ) ), new Func('x', new Application( new Variable('x'), new Variable('x') ) ) ); const errorMessage = 'Potential infinite loop detected while evaluating ((λx.(xx))(λx.(xx))), aborting...'; expect(() => interpreter.eval(expr)).toThrowError(errorMessage); }); describe('several reductions before going into loop', () => { it(`should detect`, () => { const expr = new Application( new Application( new Func('x', new Func('y', new Variable('x') ) ), new Application( new Func('x', new Application( new Variable('x'), new Variable('x') ) ), new Func('x', new Application( new Variable('x'), new Variable('x') ) ) ) ), new Func('x', new Variable('x') ) ); const errorMessage = 'Potential infinite loop detected while evaluating (((λx.(λy.x))((λx.(xx))(λx.(xx))))(λx.x)), aborting...'; expect(() => interpreter.eval(expr)).toThrowError(errorMessage); }); }); }); //TODO: Also store the history of evaluation //TODO: Variable name overshadows a variable from an enclosing context: α-reduction is needed to rename the variables //TODO: Implementation detail: α-reduction to avoid same variable name //TODO: Evaluate f(Yf) one reduction and Yf two reductions: Y-combinator applied to a function, should reduce to the same term });
JavaScript
0.001269
@@ -7455,55 +7455,8 @@ );%0A%0A - //TODO: Also store the history of evaluation%0A // @@ -7644,16 +7644,489 @@ le name%0A + describe('%CE%B1-reduction, ensuring freedome of substitution', () =%3E %7B%0A%0A test(%5B%0A %5B%0A new Application(%0A new Func('y',%0A new Func('x',%0A new Application(%0A new Variable('y'),%0A new Variable('x')%0A )%0A )%0A ),%0A new Variable('x')%0A ),%0A '(%CE%BBt.xt)', 'same variable is both free and bound'%0A %5D%0A %5D)%0A %7D);%0A%0A //TODO: Also store the history of evaluation%0A //TODO
aa26eba678a6dd634a9165c7eb07b258cfb9cbfd
Jasmine, not Mocha
spec/path-watcher-spec.js
spec/path-watcher-spec.js
/** @babel */ import {it, beforeEach, afterEach, promisifySome} from './async-spec-helpers' import tempCb from 'temp' import fsCb from 'fs-plus' import path from 'path' import {CompositeDisposable} from 'event-kit' import {watchPath, stopAllWatchers} from '../src/path-watcher' tempCb.track() const fs = promisifySome(fsCb, ['writeFile', 'mkdir', 'symlink', 'appendFile', 'realpath']) const temp = promisifySome(tempCb, ['mkdir']) describe('watchPath', function () { let subs beforeEach(function () { subs = new CompositeDisposable() }) afterEach(async function () { subs.dispose() await stopAllWatchers() }) function waitForChanges (watcher, ...fileNames) { const waiting = new Set(fileNames) let fired = false const relevantEvents = [] return new Promise(resolve => { const sub = watcher.onDidChange(events => { for (const event of events) { if (waiting.delete(event.path)) { relevantEvents.push(event) } } if (!fired && waiting.size === 0) { fired = true resolve(relevantEvents) sub.dispose() } }) }) } describe('watchPath()', function () { it('resolves the returned promise when the watcher begins listening', async function () { const rootDir = await temp.mkdir('atom-fsmanager-test-') const watcher = await watchPath(rootDir, {}, () => {}) expect(watcher).to.be.a('PathWatcher') }) it('reuses an existing native watcher and resolves getStartPromise immediately if attached to a running watcher', async function () { const rootDir = await temp.mkdir('atom-fsmanager-test-') const watcher0 = await watchPath(rootDir, {}, () => {}) const watcher1 = await watchPath(rootDir, {}, () => {}) expect(watcher0.native).toBe(watcher1.native) }) it("reuses existing native watchers even while they're still starting", async function () { const rootDir = await temp.mkdir('atom-fsmanager-test-') const [watcher0, watcher1] = await Promise.all([ watchPath(rootDir, {}, () => {}), watchPath(rootDir, {}, () => {}) ]) expect(watcher0.native).toBe(watcher1.native) }) it("doesn't attach new watchers to a native watcher that's stopping", async function () { const rootDir = await temp.mkdir('atom-fsmanager-test-') const watcher0 = await watchPath(rootDir, {}, () => {}) const native0 = watcher0.native watcher0.dispose() const watcher1 = await watchPath(rootDir, {}, () => {}) expect(watcher1.native).not.toBe(native0) }) it('reuses an existing native watcher on a parent directory and filters events', async function () { const rootDir = await temp.mkdir('atom-fsmanager-test-').then(fs.realpath) const rootFile = path.join(rootDir, 'rootfile.txt') const subDir = path.join(rootDir, 'subdir') const subFile = path.join(subDir, 'subfile.txt') await fs.mkdir(subDir) // Keep the watchers alive with an undisposed subscription const rootWatcher = await watchPath(rootDir, {}, () => {}) const childWatcher = await watchPath(subDir, {}, () => {}) expect(rootWatcher.native).toBe(childWatcher.native) expect(rootWatcher.native.isRunning()).toBe(true) const firstChanges = Promise.all([ waitForChanges(rootWatcher, subFile), waitForChanges(childWatcher, subFile) ]) await fs.writeFile(subFile, 'subfile\n', {encoding: 'utf8'}) await firstChanges const nextRootEvent = waitForChanges(rootWatcher, rootFile) await fs.writeFile(rootFile, 'rootfile\n', {encoding: 'utf8'}) await nextRootEvent }) it('adopts existing child watchers and filters events appropriately to them', async function () { const parentDir = await temp.mkdir('atom-fsmanager-test-').then(fs.realpath) // Create the directory tree const rootFile = path.join(parentDir, 'rootfile.txt') const subDir0 = path.join(parentDir, 'subdir0') const subFile0 = path.join(subDir0, 'subfile0.txt') const subDir1 = path.join(parentDir, 'subdir1') const subFile1 = path.join(subDir1, 'subfile1.txt') await fs.mkdir(subDir0) await fs.mkdir(subDir1) await Promise.all([ fs.writeFile(rootFile, 'rootfile\n', {encoding: 'utf8'}), fs.writeFile(subFile0, 'subfile 0\n', {encoding: 'utf8'}), fs.writeFile(subFile1, 'subfile 1\n', {encoding: 'utf8'}) ]) // Begin the child watchers and keep them alive const subWatcher0 = await watchPath(subDir0, {}, () => {}) const subWatcherChanges0 = waitForChanges(subWatcher0, subFile0) const subWatcher1 = await watchPath(subDir1, {}, () => {}) const subWatcherChanges1 = waitForChanges(subWatcher1, subFile1) expect(subWatcher0.native).not.toBe(subWatcher1.native) // Create the parent watcher const parentWatcher = await watchPath(parentDir, {}, () => {}) const parentWatcherChanges = waitForChanges(parentWatcher, rootFile, subFile0, subFile1) expect(subWatcher0.native).toBe(parentWatcher.native) expect(subWatcher1.native).toBe(parentWatcher.native) // Ensure events are filtered correctly await Promise.all([ fs.appendFile(rootFile, 'change\n', {encoding: 'utf8'}), fs.appendFile(subFile0, 'change\n', {encoding: 'utf8'}), fs.appendFile(subFile1, 'change\n', {encoding: 'utf8'}) ]) await Promise.all([ subWatcherChanges0, subWatcherChanges1, parentWatcherChanges ]) }) }) })
JavaScript
0.999509
@@ -1445,17 +1445,31 @@ cher -).to.be.a +.constructor.name).toBe ('Pa
91defd47ce8589cd19024d91db28d4af87d57c37
Disable TLS verification in tests
spec/support/bootstrap.js
spec/support/bootstrap.js
// This file is executed before all specs and before all other handlers // Enable typescript compilation for .ts files require('ts-node/register'); // Patch jasmine so that async tests can just return promises (or use the async keyword) and do not need to call done() global.jasmineRequire = {}; // jasmine-promise expects this be there and patches it, but it is not required require('jasmine-promises');
JavaScript
0
@@ -396,12 +396,88 @@ promises');%0A +%0A// to get through firewall%0Aprocess.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';%0A
6a4c3f75400111a0a79d17159f47936ca81b1174
Add test for changing ajax type
packages/ember-uploader/tests/uploader_test.js
packages/ember-uploader/tests/uploader_test.js
var Uploader, file; module("Ember.Uploader", { setup: function() { if (typeof WebKitBlobBuilder === "undefined") { file = new Blob(['test'], { type: 'text/plain' }); } else { var builder; builder = new WebKitBlobBuilder(); builder.append('test'); file = builder.getBlob(); } Uploader = Ember.Uploader.extend({ url: '/test', }); } }); test("has a url of '/test'", function() { var uploader = Uploader.create(); equal(uploader.url, '/test'); }); test("uploads to the given url", function() { expect(1); var uploader = Uploader.create({ url: '/upload', file: file }); uploader.on('didUpload', function(data) { start(); equal(data, 'OK'); }); uploader.upload(file); stop(); }); test("emits progress event", function() { expect(1); var uploader = Uploader.create({ url: '/upload', file: file }); uploader.on('progress', function(e) { start(); equal(e.percent, 100); }); uploader.upload(file); stop(); });
JavaScript
0
@@ -501,24 +501,164 @@ est');%0A%7D);%0A%0A +test(%22has an ajax request of type 'PUT'%22, function() %7B%0A var uploader = Uploader.create(%7Btype: 'PUT'%7D);%0A equal(uploader.type, 'PUT');%0A%7D);%0A%0A test(%22upload
eb745bf52fb2f01f52aae8638c22744affa2de1b
Add repos
ci/setup.js
ci/setup.js
#!/usr/bin/env node const { join } = require('path') const { execSync } = require('child_process') const fs = require('fs') const mkdirp = require('mkdirp') process.chdir(join(__dirname, '..')) mkdirp.sync('repos') let repos = [ 'ever-increasing-faith', 'faith-that-prevails', 'andrew-murray-humility', 'first-clement', 'pilgrims-progress', 'incarnation', 'christian-pilgrim' ] let cloned = fs.readdirSync('repos') repos.forEach(repo => { if (cloned.includes(repo)) { return } let command = `git clone https://github.com/christian-classics-jp/${repo}.git` console.log('>', command) let out = execSync(command, { cwd: join(__dirname, '../repos') }).toString() console.log(out) })
JavaScript
0.000001
@@ -385,16 +385,36 @@ pilgrim' +,%0A 'wesley-sermons' %0A%5D%0A%0Alet
12cef48639f316c35087c7d92f46bc6b5300f3ad
Remove Verdict (#95)
javascripts/custom-repos.js
javascripts/custom-repos.js
// Opt-in repos (case sensitive) // - These are all children of Shopify and visible at https://github.com/Shopify var optInRepos = [ 'FunctionalTableData', 'Intro_to_GraphQL_Powered_by_Shopify', 'active_fulfillment', 'active_merchant', 'active_shipping', 'active_utils', 'app_profiler', 'asset_cloud', 'browser_sniffer', 'connect-googleapps', 'draggable', 'dukpt', 'ejson2env', 'embedded-app-example', 'go-lua', 'goluago', 'goreferrer', 'grizzly_ber', 'identity_cache', 'js-buy-sdk', 'kubeaudit', 'liquid', 'magnet', 'minesweeper', 'money', 'omniauth-shopify-oauth2', 'packwerk', 'polaris-react', 'polaris-icons', 'pyreferrer', 'rails_parallel', 'rotoscope', 'rubocop-sorbet', 'sarama', 'semian', 'shipit-engine', 'shopify-css-import', 'shopify-fulfillment-integration', 'shopify_api', 'shopify_app', 'shopify_django_app', 'shopify_python_api', 'shopify_theme', 'skeleton-theme', 'slate', 'splunk-auth-proxy', 'spoom', 'starter-theme', 'statsd-instrument', 'superdb', 'sync_app_demo', 'sysv_mq', 'tapioca', 'themekit', 'theme-scripts', 'toxiproxy', 'toxiproxy-ruby', 'tslint-config-shopify', 'turbograft', 'twine', 'verdict', 'voucher', 'vouch4cluster', 'wolverine', 'promise-kotlin', 'promise-swift', 'android-testify', 'krane', 'quilt', 'graphql-tools-web' ]; // Add custom repos by full_name. Take the org/user and repo name // - e.g. batmanjs/batman from https://github.com/batmanjs/batman var customRepos = []; // Custom repo language, different than that defined by GitHub var customRepoLanguage = { liquid: 'Liquid', 'starter-theme': 'Liquid', 'skeleton-theme': 'Liquid', shopify_theme: 'Ruby', 'Shopify-Developer-Book': 'Ruby', 'offsite-gateway-sim': 'Ruby', 'shopify.github.com': 'JavaScript', rotoscope: 'C' }; // Custom repo avatars. Dimensions should be 40x40 // - Be sure a custom repo doesn't have the same name as a Shopify one, or a one will be overridden var customRepoAvatar = { slate: '/images/repo-avatars/slate.svg', draggable: '/images/repo-avatars/draggable.png', superdb: '/images/repo-avatars/super-debugger.gif' };
JavaScript
0
@@ -1232,21 +1232,8 @@ e',%0A - 'verdict',%0A 'v
222cf4f1ede04542efbac128da268102c43b4592
Fix Settings unit tests
specs/lib/SettingsSpec.js
specs/lib/SettingsSpec.js
'use strict'; var nconf = require('nconf'); var Settings = require('../../lib/Settings'); describe('loadRepositoriesSettings', function () { beforeEach(function () { spyOn(nconf, 'env').and.returnValue(nconf); }); it('returns rejected Promise when config does not have `secret`', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/noSecret.json') .then(function () { done.fail(); }) .catch(function () { done(); }); }); it('returns rejected Promise when config does not have `repositories`', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/noRepositories.json') .then(function () { done.fail(); }) .catch(function () { done(); }); }); it('returns rejected Promise when `repositories` do not have names', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/noRepositoryNames.json') .then(function () { done.fail(); }) .catch(function (err) { if (/repositories/.test(err)) { return done(); } done.fail(err); }); }); it('returns rejected Promise when `repositories` do not have `gitHubToken`s', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/noGitHubToken.json') .then(function () { done.fail(); }) .catch(function (err) { if (/gitHubToken/.test(err)) { return done(); } done.fail(err); }); }); it('returns rejected Promise when repositories don\'t have a user prepended', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/noUserBeforeRepository.json') .then(function () { done.fail(); }) .catch(function (err) { if (/must be in the form/.test(err)) { return done(); } done.fail(err); }); }); it('removes `/` from `thirdPartyFolders` that begin with `/`', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/slashWithThirdPartyFolders.json') .then(function () { expect(Settings.repositories['one'].thirdPartyFolders).toEqual(['ThirdParty/']); done(); }) .catch(function (err) { done.fail(err); }); }); it('appends `/` to `thirdPartyFolders that don\'t end with `/`', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/noEndSlashThirdPartyFolders.json') .then(function () { expect(Settings.repositories['one'].thirdPartyFolders).toEqual(['ThirdParty/']); done(); }) .catch(function (err) { done.fail(err); }); }); it('splits `thirdPartyFolders`', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/multipleThirdPartyFolders.json') .then(function () { expect(Settings.repositories['one'].thirdPartyFolders).toEqual(['ThirdParty/', 'AnotherFolder/']); done(); }) .catch(function (err) { done.fail(err); }); }); it('sets `bumpStalePullRequests` `url` correctly', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/bumpStalePullRequests_noUrl.json') .then(function () { expect(Settings.repositories['one'].bumpStalePullRequestsUrl).toEqual('https://api.github.com/repos/a/one/pulls'); done(); }) .catch(function (err) { done.fail(err); }); }); it('correctly loads values', function (done) { Settings.loadRepositoriesSettings('./specs/data/config/noError.json') .then(function () { expect(Settings.repositories.one.gitHubToken).toEqual('bar'); expect(Settings.repositories.one.someVal).toBe(true); expect(Settings.repositories.two.gitHubToken).toEqual('bar2'); expect(Settings.repositories.two.someVal).toEqual(false); expect(Settings.port).toEqual(10); expect(Settings.listenPath).toEqual('/foo'); expect(Settings.secret).toEqual('foo'); done(); }) .catch(function (err) { done.fail(err); }); }); });
JavaScript
0.000001
@@ -2431,32 +2431,84 @@ n(function () %7B%0A + console.log(Settings.repositories);%0A @@ -2529,32 +2529,34 @@ s.repositories%5B' +a/ one'%5D.thirdParty @@ -2977,32 +2977,34 @@ s.repositories%5B' +a/ one'%5D.thirdParty @@ -3395,24 +3395,26 @@ positories%5B' +a/ one'%5D.thirdP @@ -3851,16 +3851,18 @@ tories%5B' +a/ one'%5D.bu @@ -4275,20 +4275,25 @@ sitories -. +%5B'a/ one +'%5D .gitHubT @@ -4362,12 +4362,17 @@ ries -. +%5B'a/ one +'%5D .som @@ -4433,20 +4433,25 @@ sitories -. +%5B'a/ two +'%5D .gitHubT @@ -4521,12 +4521,17 @@ ries -. +%5B'a/ two +'%5D .som
c7318a66efc0db4a36081a6047d0998012178a85
Add tests to ensure wildcard functionality and avoiding KEYS call New test to check wildcard keys still fetch multiple results. New test to check that a non-wildcard call does not call KEYS.
test/get.js
test/get.js
(function () { 'use strict'; var path = require('path'); var assert = require('assert'); var mocha = require('mocha'); var should = require('should'); var prefix = process.env.EX_RE_CA_PREFIX || 'erct:'; var host = process.env.EX_RE_CA_HOST || 'localhost'; var port = process.env.EX_RE_CA_PORT || 6379; var _name = 'test1'; var _body = 'test1 test1 test1'; var _type = 'text/plain'; var cache = require('../')({ prefix: prefix, host: host, port: port }); describe ( 'get', function () { var error, results; it ( 'should be a function', function () { cache.get.should.be.a.Function; }); it ( 'should callback', function (done) { cache.get(null, function ($error, $results) { error = $error; results = $results; done(); }); }); it ( 'should not have error', function () { should(error).be.null; }); it ( 'should be an array', function () { results.should.be.an.Array; }); it ( ' - entry which has a property name which a string', function () { results.forEach(function (result) { result.name.should.be.a.String; }); }); it ( ' - entry which has a property body which a string', function () { results.forEach(function (result) { result.body.should.be.a.String; }); }); it ( ' - entry which has a property type which a string', function () { results.forEach(function (result) { result.type.should.be.a.String; }); }); it ( ' - entry which has a property touched which is a number which resolves to date', function () { results.forEach(function (result) { Number(result.touched).should.be.a.Number; new Date(Number(result.touched)) .should.be.a.Date; }); }); }); })();
JavaScript
0
@@ -1893,16 +1893,1432 @@ %7D);%0A%0A + it ( 'should support wildcard gets', function (done) %7B%0A cache.add('wildkey1', 'abc',%0A function ($error, $name, $entry) %7B%0A cache.add('wildkey2', 'def',%0A function ($error, $name, $entry) %7B%0A cache.get('wildkey*', function ($error, $results) %7B%0A $results.should.be.an.Array;%0A $results.should.have.a.lengthOf(2);%0A done();%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A%0A it ( 'should support specific gets without calling keys', function (done) %7B%0A%0A // wrap the call to keys, so we can see if it's called%0A var callCount = 0;%0A var wrap = function(fn)%7B%0A return function()%7B%0A console.log('What!?');%0A callCount++;%0A return fn.apply(this, arguments);%0A %7D;%0A %7D;%0A%0A cache.client.keys = wrap(cache.client.keys);%0A%0A cache.add('wildkey1', 'abc',%0A function ($error, $name, $entry) %7B%0A cache.add('wildkey2', 'def',%0A function ($error, $name, $entry) %7B%0A cache.get('wildkey1', function ($error, $results) %7B%0A try %7B%0A $results.should.be.an.Array;%0A $results.should.have.a.lengthOf(1);%0A callCount.should.equal(0);%0A done();%0A %7D catch (e) %7B%0A done(e);%0A %7D%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A%0A%7D
0e9d3b220ea40eee6ac2c8d5ee3bf923d6310116
mutation.attributeName is a string
angupoly.js
angupoly.js
angular.module('angupoly', []) .directive('angupoly', function($rootScope, $parse) { return { priority : 42, restrict : 'A', compile : function(tElement, tAttr) { var conf = $rootScope.$eval(tAttr.angupoly); var assignables = {}; var paths = {}; var needsMutationObserver; Object.keys(conf).forEach(function(attrName) { var path = conf[attrName], parse = $parse(path); if (parse.assign) { assignables[attrName] = parse.assign; needsMutationObserver = true; } paths[attrName] = path; }); return function(scope, element) { var el = element[0]; // from angular scope to attribute // http://www.polymer-project.org/platform/node_bind.html for (var attrName in paths) { el.bind(attrName, new PathObserver(scope, paths[attrName])); } if (needsMutationObserver) { // from attribute to angular scope // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver // http://caniuse.com/mutationobserver new MutationObserver(function(mutations) { var mutation, updates, i = 0; while ((mutation = mutations[i++])) { for (var attrName in assignables) { if (mutation.attributeName.indexOf(attrName) !== -1) { assignables[attrName](scope, mutation.target[attrName]); updates = true; } } } if (updates) { scope.$apply(); } }).observe(el, {attributes:true}); } }; } }; });
JavaScript
0.999818
@@ -1385,33 +1385,21 @@ Name -.indexOf(attrName) !== -1 + === attrName ) %7B%0A
4ccc256bd4a9a94073a00aa5eddcb9af7597e9b7
Remove reference on localhost in the web socket sample
samples/src/main/resources/assets/socket.js
samples/src/main/resources/assets/socket.js
(function() { var Sock = function() { var socket; if (!window.WebSocket) { window.WebSocket = window.MozWebSocket; } if (window.WebSocket) { socket = new WebSocket("ws://localhost:9000/assets/websocket"); socket.onopen = onopen; socket.onmessage = onmessage; socket.onclose = onclose; } else { alert("Your browser does not support Web Socket."); } function onopen(event) { getTextAreaElement().value = "Web Socket opened!"; } function onmessage(event) { appendTextArea(event.data); } function onclose(event) { appendTextArea("Web Socket closed"); } function appendTextArea(newData) { var el = getTextAreaElement(); el.value = el.value + '\n' + newData; } function getTextAreaElement() { return document.getElementById('responseText'); } function send(event) { event.preventDefault(); if (window.WebSocket) { if (socket.readyState == WebSocket.OPEN) { var msg = {}; msg.message = event.target.message.value; socket.send(JSON.stringify(msg)); //socket.send(event.target.message.value); } else { alert("The socket is not open."); } } } document.forms.inputform.addEventListener('submit', send, false); } window.addEventListener('load', function() { new Sock(); }, false); })();
JavaScript
0
@@ -199,69 +199,138 @@ -socket = new WebSocket(%22ws://localhost:9000/assets/websocket%22 +// compute url.%0A var url = %22ws://%22 + window.location.host + %22/assets/websocket%22;%0A socket = new WebSocket(url );%0A
6a55931504f50247cc882da7ba835d4d29c3e896
change var def for older js
lib/nodemda/meta/meta-validator.js
lib/nodemda/meta/meta-validator.js
/* Copyright (C) 2016 by Joel Kozikowski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict"; var metaModel = require('../meta/meta-model.js'); var winston = require('winston'); (function(meta){ var warnCount = 0; var errorCount = 0; meta.validate = function(metaModel) { warnCount = 0; errorCount = 0; winston.info("Validating model..."); var logWarn = function(typeName, metaObj, msg) { let msg = "WARN: " + typeName + " " + metaObj._name + msg; winston.warn(msg); warnCount++; }; var logError = function(typeName, metaObj, msg) { let msg = "ERROR: " + typeName + " " + metaObj._name + msg; winston.error(msg); errorCount++; }; var isMissing = function(obj) { return (obj === undefined || obj === null || (typeof(obj) === "string" && obj.length === 0)); }; metaModel.classes.forEach(function(metaClass) { if (metaClass.getPackageName().length === 0) { logWarn("Class", metaClass, " has no package specified. Code will be in root of project."); } if (metaClass._stereotypes.length === 0) { logWarn("Class", metaClass, " has no stereotypes. No class code will be generated."); } metaClass.attributes.forEach(function(metaAttribute) { if (isMissing(metaAttribute._type)) { logError("Attribute", metaAttribute, " on class " + metaClass._name + " has no data type defined."); } }); metaClass.operations.forEach(function(metaOperation) { metaOperation.parameters.forEach(function (metaParameter) { if (isMissing(metaParameter._type)) { logError("Paramter", metaParameter, " in operation " + metaOperation._name + " of class " + metaClass._name + " has no data type"); } }); }); }); var logLevel; if (errorCount > 0) { logLevel = "error"; } else if (warnCount > 0) { logLevel = "warn"; } else { logLevel = "info"; } winston.log(logLevel, "Validation completed: " + errorCount + " errors, " + warnCount + " warnings"); return (errorCount === 0); }; })(metaModel);
JavaScript
0.000008
@@ -1299,16 +1299,27 @@ nt = 0;%0A +%09%09var msg;%0A %09%09%0A%09%09win @@ -1407,28 +1407,24 @@ , msg) %7B%0A%09%09%09 -let msg = %22WARN: @@ -1572,12 +1572,8 @@ %0A%09%09%09 -let msg