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
cbc7e3d81f6a0c7cbcb62cc57cede833e8653925
Tweak to unbreak bundle
config/prod.js
config/prod.js
const webpackMerge = require('webpack-merge'); const commonConfig = require('./common.js'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); module.exports = function(env){ return webpackMerge(commonConfig(env), { output: { filename: '[name].[chunkhash].js' }, devtool: 'source-map', plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true, debug: false }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ beautify: false, mangle: { screw_ie8: true, keep_fnames: true }, compress: { screw_ie8: true, warnings: false }, comments: false }), new ExtractTextPlugin({ filename: "bundle.[contenthash].css", disable: false }), new HtmlWebpackPlugin({ filename: 'index.html', template: './src/index.html.ejs', inject: false, favicon: './src/assets/favicon.ico', hash: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true } }) ] }) }
JavaScript
0
@@ -409,16 +409,259 @@ e-map',%0A + // Uglify is blowing up trying to further minify mapbox-gl%0A // so for now just do not parse it -- it is already minified.%0A // https://github.com/mapbox/mapbox-gl-js/issues/4359%0A module: %7B%0A noParse: /(mapbox-gl)%5C.js$/,%0A %7D,%0A plug
50daaecac787ace1fa481d56ba8e17d55f5d61cc
Print clients
console/app.js
console/app.js
var app = { token : function() { return localStorage['token']; }, username : function() { return localStorage['username']; }, apiErr : function(resp) { alert(resp.error); }, showPage : function(name) { var currentPage = $('.page-visible'); var currentPageName = currentPage.attr('data-name'); currentPage.removeClass('page-visible'); $('.page[data-name="' + name + '"]').addClass('page-visible'); // Call load and unload if (typeof app.pages[currentPageName]['unload'] === 'function') { app.pages[currentPageName]['unload'](); } if (typeof app.pages[name]['load'] === 'function') { app.pages[name]['load'](); } }, run : function() { /** Login */ if (typeof app.token() !== 'undefined' && app.token() !== null && app.token().length > 0) { app.showPage('home'); } else { app.showPage('login'); } }, ajax : function(url, opts) { if (typeof opts === 'undefined' || opts === null) { opts = {}; } if (typeof opts["headers"] === 'undefined') { opts["headers"] = {}; } opts["headers"]["X-Auth-User"] = app.username(); opts["headers"]["X-Auth-Session"] = app.token(); console.log(opts); return $.ajax(url, opts); }, pages : { home : { load : function() { // @todo finish app.ajax('/clients'); } }, login : { load : function() { $('form#login').submit(function() { $.post('/auth', $(this).serialize(), function(resp) { if (resp.status === 'OK') { localStorage['token'] = resp.session_token; localStorage['username'] = $('form#login input[name="username"]').val(); app.showPage('home'); } else { app.apiErr(resp); } }, 'json'); return false; }); } } } }; $(document).ready(function() { app.run(); });
JavaScript
0
@@ -156,16 +156,164 @@ resp) %7B%0A +%09%09if (resp.error.indexOf('authorized') !== -1) %7B%0A%09%09%09delete localStorage%5B'token'%5D;%0A%09%09%09delete localStorage%5B'username'%5D;%0A%09%09%09app.showPage('login');%0A%09%09%7D%0A %09%09alert( @@ -1285,148 +1285,357 @@ ;%0A%09%09 -console.log(opts);%0A%09%09return $.ajax(url, opts);%0A%09%7D,%0A%0A%09pages : %7B%0A%09%09home : %7B%0A%09%09%09load : function() %7B%0A%09%09%09%09// @todo finish%0A%09%09%09%09app.ajax('/clients' +opts%5B%22dataType%22%5D = 'json';%0A%09%09var x = $.ajax(url, opts);%0A%09%09return x;%0A%09%7D,%0A%0A%09handleResponse : function(resp) %7B%0A%09%09if (resp%5B'status'%5D !== 'OK') %7B%0A%09%09%09app.apiErr(resp);%0A%09%09%7D%0A%09%09return resp;%0A%09%7D,%0A%0A%09pages : %7B%0A%09%09home : %7B%0A%09%09%09load : function() %7B%0A%09%09%09%09app.ajax('/clients').done(function(resp) %7B%0A%09%09%09%09%09var resp = app.handleResponse(resp);%0A%09%09%09%09%09console.log(resp);%0A%09%09%09%09%7D );%0A%09
aecea1524533c36829bc9ebc933a925acb091f74
Check for process.env.PORT before using config.port
config/site.js
config/site.js
module.exports = function(config) { if(!config.port || !_.isNumber(config.port)) throw new Error('Port undefined or not a number'); var domain = 'changethisfool.com'; var c = { defaults: { title: 'Change This Fool', name: 'change-this-fool', protocol: 'http', get host() { return this.port ? this.hostname + ':' + this.port : this.hostname; }, get url () { return this.protocol + '://' + this.host + '/'; } }, development: { hostname: 'localhost', port: process.env.EXTERNAL_PORT || config.port }, testing: { hostname: 'testing.' + domain }, staging: { hostname: 'staging.' + domain }, production: { hostname: domain } }; return _.merge(c.defaults, c[ENV]); };
JavaScript
0.000001
@@ -522,16 +522,36 @@ _PORT %7C%7C + process.env.PORT %7C%7C config.
509375e9fed069829f1c39dae8611090760ce3d3
introduce separate class for Partials
copv2/scope.js
copv2/scope.js
const events = [ 'beforeActivation', 'afterActivation', 'beforeDeactivation', 'afterDeactivation', 'beforeActivationFor', 'afterActivationFor', 'beforeDeactivationFor', 'afterDeactivationFor' ]; export class Scope { constructor() { this.activatedItems = new Set(); this._isActive = false; this._partials = new Set(); // TODO: use a dedicated event listener library this._eventCallbacks = new Map(); for(let eventName of events) { this._eventCallbacks.set(eventName, new Set()); } } // Managing composites add(partial) { this._partials.add(partial); // TODO: adding to an already active scope should activate the partial return this; } remove(partial) { this._partials.delete(partial); return this; } contains(partial) { return this._partials.has(partial); } [Symbol.iterator]() { return this._partials.values() } // Scope Activation activate() { if(!this.isActive()) { this._eventCallbacks.get('beforeActivation').forEach(callback => callback()); this._isActive = true; this._partials.forEach(partial => partial.activate()); this._eventCallbacks.get('afterActivation').forEach(callback => callback()); } return this; } deactivate() { if(this.isActive()) { this._eventCallbacks.get('beforeDeactivation').forEach(callback => callback()); this._isActive = false; this._partials.forEach(partial => partial.deactivate()); this._eventCallbacks.get('afterDeactivation').forEach(callback => callback()); } return this; } isActive() { return this._isActive; } // Activation Hooks on(event, callback) { var callbacks = this._eventCallbacks.get(event); callbacks.add(callback); return this; } off(event, callback) { var callbacks = this._eventCallbacks.get(event); callbacks.delete(callback); return this; } activateFor(obj) { if(!this.isActiveFor(obj)) { this._eventCallbacks.get('beforeActivationFor').forEach(callback => callback(obj)); this.activatedItems.add(obj); this._partials.forEach(partial => partial.activateFor(obj)); this._eventCallbacks.get('afterActivationFor').forEach(callback => callback(obj)); } return this; } deactivateFor(obj) { if(this.isActiveFor(obj)) { this._eventCallbacks.get('beforeDeactivationFor').forEach(callback => callback(obj)); this.activatedItems.delete(obj); this._partials.forEach(partial => partial.deactivateFor(obj)); this._eventCallbacks.get('afterDeactivationFor').forEach(callback => callback(obj)); } return this; } isActiveFor(obj) { return this.activatedItems.has(obj); } }
JavaScript
0
@@ -235,21 +235,145 @@ t class -Scope +Partial %7B%0A activate() %7B%7D%0A deactivate() %7B%7D%0A activateFor() %7B%7D%0A deactivateFor() %7B%7D%0A%7D%0A%0Aexport class Scope extends Partial %7B%0A c @@ -383,24 +383,42 @@ tructor() %7B%0A + super();%0A%0A this @@ -447,24 +447,16 @@ Set();%0A%0A - %0A
272565333a22185dcddc132cb8c7acc3beb41df8
Fix delta of stats
js/osgViewer/stats.js
js/osgViewer/stats.js
/** -*- compile-command: "jslint-cli stats.js" -*- * * Copyright (C) 2010 Cedric Pinson * * GNU LESSER GENERAL PUBLIC LICENSE * Version 3, 29 June 2007 * * Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> * Everyone is permitted to copy and distribute verbatim copies * of this license document, but changing it is not allowed. * * This version of the GNU Lesser General Public License incorporates * the terms and conditions of version 3 of the GNU General Public * License * * Authors: * Cedric Pinson <cedric.pinson@plopbyte.net> * */ var Stats = {}; Stats.Stats = function(canvas) { this.layers = []; this.last_update = undefined; this.canvas = canvas; }; Stats.Stats.prototype = { addLayer: function(color, getter) { if (color === undefined) { color = "rgb(255,255,255)"; } this.layers.push({ previous: 0, color: color, getValue: getter }); }, update: function() { var t = (new Date()).getTime(); if (this.last_update === undefined) { this.last_update = t; } var delta = (t - this.last_update)* 2.0*60.0/1000.0; if (delta < 1.0) { return; } var translate = delta; var c = this.canvas; var width = c.width; var height = c.height; var ctx = c.getContext("2d"); ctx.save(); ctx.globalCompositeOperation="copy"; ctx.mozImageSmoothingEnabled = false; ctx.translate(-delta,0); ctx.drawImage(c, 0, 0, width, height); ctx.restore(); ctx.clearRect(width - delta, 0, delta, height); for (var i = 0, l = this.layers.length; i < l; i++) { var layer = this.layers[i]; var c = this.canvas; var value = layer.getValue(t); var width = c.width; var height = c.height; ctx.lineWidth = 1.0; ctx.strokeStyle = layer.color; ctx.beginPath(); ctx.moveTo(width - delta, height - layer.previous); ctx.lineTo(width, height - value); ctx.stroke(); layer.previous = value; } this.last_update = t; } };
JavaScript
0.000663
@@ -1309,16 +1309,139 @@ %7D%0A%0A + var report = delta - Math.floor(delta);%0A t -= report/(2.0*60.0/1000.0);%0A delta = Math.floor(delta);%0A%0A
b45ff4ab04208b62ac2196006d4c0682c61c1b30
Fix Safari listener binding issue
core/events.js
core/events.js
var registry_ = []; var addEventListener_ = window.addEventListener || function fallbackAddRemoveEventListener_(type, listener) { var target = this; registry_.unshift([target, type, listener, function (event) { event.currentTarget = target; event.preventDefault = function () { event.returnValue = false; }; event.stopPropagation = function () { event.cancelBubble = true; }; event.target = event.srcElement || target; listener.call(target, event); }]); this.attachEvent('on' + type, registry_[0][3]); }; var removeEventListener_ = window.removeEventListener || function fallbackRemoveEventListener_(type, listener) { for (var index = 0, register; (register = registry_[index]); ++index) { if (register[0] == this && register[1] == type && register[2] == listener) { return this.detachEvent('on' + type, registry_.splice(index, 1)[0][3]); } } }; var dispatchEvent_ = window.dispatchEvent || function(eventObject) { return this.fireEvent('on' + (eventObject.type || eventObject.eventType), eventObject); }; var eventListenerInfo = { count: 0 }; function eventListener(target, eventName, cb) { addEventListener_.call(target, eventName, cb, false); eventListenerInfo.count++; return function eventListenerRemove_() { removeEventListener_.call(target, eventName, cb, false); eventListenerInfo.count--; }; } function dispatchEvent(target, evType) { var evObj; if (document.createEvent) { evObj = document.createEvent('HTMLEvents'); evObj.initEvent(evType, true, true); } else { evObj = document.createEventObject(); evObj.eventType = evType; } evObj.eventName = evType; dispatchEvent_.call(target, evObj); } module.exports = { eventListenerInfo: eventListenerInfo, eventListener: eventListener, dispatchEvent: dispatchEvent };
JavaScript
0
@@ -14,19 +14,24 @@ = %5B%5D;%0A%0A -var +function addEven @@ -44,64 +44,89 @@ ner_ - = window.addEventListener %7C%7C function fallbackAddRemove +(target, type, listener) %7B%0A if (target.addEventListener) %7B%0A return target.add Even @@ -126,33 +126,32 @@ addEventListener -_ (type, listener) @@ -154,33 +154,23 @@ ner) - %7B%0A var target = this;%0A%0A +;%0A %7D else %7B%0A re @@ -229,24 +229,26 @@ vent) %7B%0A + event.curren @@ -265,16 +265,18 @@ target;%0A + even @@ -338,24 +338,26 @@ lse; %7D;%0A + event.stopPr @@ -412,24 +412,26 @@ rue; %7D;%0A + event.target @@ -462,16 +462,18 @@ arget;%0A%0A + list @@ -498,16 +498,18 @@ event);%0A + %7D%5D);%0A%0A @@ -510,20 +510,31 @@ %7D%5D);%0A%0A -this + return target .attachE @@ -569,23 +569,32 @@ 0%5D%5B3%5D);%0A -%7D;%0A%0Avar + %7D%0A%7D;%0A%0Afunction removeE @@ -610,59 +610,90 @@ ner_ - = window.removeEventListener %7C%7C function fallbackR +(target, type, listener) %7B%0A if (target.removeEventListener) %7B%0A return target.r emov @@ -706,17 +706,16 @@ Listener -_ (type, l @@ -722,19 +722,31 @@ istener) +;%0A %7D else %7B%0A + for (v @@ -815,16 +815,18 @@ ) %7B%0A + if (regi @@ -837,19 +837,21 @@ %5B0%5D == t -his +arget && regi @@ -902,24 +902,26 @@ %7B%0A + return t his.deta @@ -912,19 +912,21 @@ return t -his +arget .detachE @@ -978,16 +978,24 @@ 0%5D%5B3%5D);%0A + %7D%0A %7D%0A @@ -1000,19 +1000,24 @@ %7D%0A%7D;%0A%0A -var +function dispatc @@ -1027,43 +1027,93 @@ ent_ - = window.dispatchEvent %7C%7C function +(target, eventObject) %7B%0A if (target.dispatchEvent) %7B%0A return target.dispatchEvent (eve @@ -1121,19 +1121,31 @@ tObject) +;%0A %7D else %7B%0A + return @@ -1150,11 +1150,13 @@ rn t -his +arget .fir @@ -1228,16 +1228,20 @@ bject);%0A + %7D%0A %7D;%0A%0Avar @@ -1334,37 +1334,32 @@ ddEventListener_ -.call (target, eventNa @@ -1471,21 +1471,16 @@ istener_ -.call (target, @@ -1847,21 +1847,16 @@ chEvent_ -.call (target,
b2e873f5cce7e56efa6545b91129bf69af24bbd8
Fix jscs issue
tasks/contributors.js
tasks/contributors.js
var cache = require("./cache/contributors") var fs = require("fs") var path = require("path") var gutil = require("gulp-util") var async = require("async") var Promise = require("promise") // var bs64 = require("bs64") var bs64 = false var convertString = require("convert-string") var exec = Promise.denodeify(require("child_process").exec) var glob = Promise.denodeify(require("glob")) var commitsRE = /^(\d+)/ var emailRE = /<(.+)>$/ var readFile = Promise.denodeify(fs.readFile) var writeFile = Promise.denodeify(fs.writeFile) var lodash = require("lodash") var githubApi = new (require("github"))({ version : "3.0.0" }) var sortObjectByKeys = function(obj){ var newObj = {} var keys = Object.keys(obj) keys.sort() keys.forEach(function(key){ newObj[key] = obj[key] }) return newObj } var contributorsMap = function(){ var authors = {} return glob("authors/*.json") .then(function(files){ files.forEach(function(authorFile){ authors[path.basename(authorFile, ".json")] = require("../" + authorFile) }) }) .then(function(){ return readFile("tasks/cache/contributors.cache", {encoding : "utf8"}) }) .then(function(contributors){ // grab contributors cache (base64ified just to do not have unserialized public emails) if(bs64){ contributors = convertString.UTF8.bytesToString(bs64.decode(contributors)) } // console.log(contributors) cache.value = JSON.parse(contributors) }, function(){ cache.value.mapByEmail = {} cache.value.map = {} }) .then(function(){ return exec("git log --pretty=format:'%ae::%an' | sort | uniq") }) .then(function(stdout){ var newUsers = [] , loginCache = {} // update contributorsMap stdout .trim("\n") .split("\n") .forEach(function(line){ var author = line.split("::") if(!cache.value.mapByEmail[author[0]]){ newUsers.push({ email : author[0], name : author[1] }) } }) // only for dev & testing // var username = "xxx", password = "xxx" // githubApi.authenticate({ // type : "basic", // username : username, // password : password // }) // consolidate contributorsMap // => add github username at the end of each line // to retrieve a author login, we just grab a commit from the author email // and we use github api to get this commit info (& so found github username) // all contributors are in cache if(newUsers.length === 0){ return Promise.resolve() } return new Promise(function(resolve){ var parallelsUser = [] newUsers.forEach(function(author){ parallelsUser.push(function(cb){ var email = author.email exec("git log --max-count=1 --pretty=format:%H --author=" + email) .then(function(stdout){ return Promise.denodeify(githubApi.repos.getCommit)({ "user" : "putaindecode", "repo" : "website", "sha" : stdout }) }) .then(function(contributor){ if(!contributor || !contributor.author){ throw "Missing author key from GitHub API response" } if(loginCache[contributor.author.login]){ gutil.log("contributor cached", contributor.author.login) return Promise.resolve(loginCache[contributor.author.login]) } else{ return Promise.denodeify(githubApi.user.getFrom)({"user" : contributor.author.login}) .then(function(githubUser){ loginCache[githubUser.login] = { // see what's available here https://developer.github.com/v3/users/ login : githubUser.login, name : githubUser.name, gravatar_id : githubUser.gravatar_id, url : githubUser.blog ? githubUser.blog.indexOf("http") === 0 ? githubUser.blog : "http://" + githubUser.blog : undefined, location : githubUser.location, hireable : githubUser.hireable } gutil.log("new contributor: ", githubUser.login) return loginCache[githubUser.login] }) } }) .done(function(contributor){ cache.value.mapByEmail[email] = contributor cb() //async done }) }) }) async.parallelLimit(parallelsUser, 20, function(){ // map by login, not email cache.value.map = lodash.transform(cache.value.mapByEmail, function(result, author){ if(!result[author.login]){ result[author.login] = author } }) resolve() }) }) }) .then(function(){ // always update map with values cache.value.map = lodash.merge(cache.value.map, authors) // sort cache.value.map = sortObjectByKeys(cache.value.map) cache.value.mapByEmail = sortObjectByKeys(cache.value.mapByEmail) var contributors = JSON.stringify(cache.value, true, 2) if(bs64){ contributors = bs64.encode(contributors) } gutil.log("Contributors cache updated") return writeFile("tasks/cache/contributors.cache", contributors) }) } var totalContributions = function(){ cache.value.contributions = {} // why ? < /dev/tty // git shortlog thinks that it has to read something from stdin, hence the indefinite wait. return exec("git shortlog --summary --numbered --email < /dev/tty") .then(function(stdout){ stdout .trim("\n") .split("\n") .forEach(function(line){ line = line.trim() var login = cache.value.mapByEmail[line.match(emailRE)[1]].login , contributions = parseInt(line.match(commitsRE)[1], 10) if(!cache.value.contributions[login]){ cache.value.contributions[login] = contributions } else{ cache.value.contributions[login] += contributions } }) }) .then(function(){ // console.log(cache.value.top) gutil.log("Total contributions cached") }) } var filesContributions = function(){ // files contributions cache.value.files = {} return glob("pages/**/*") .then(function(files){ return new Promise(function(resolve){ var parallelFiles = [] files.forEach(function(file){ parallelFiles.push(function(cb){ return exec("git log --pretty=short --follow " + file + " | git shortlog --summary --numbered --no-merges --email") .then(function(stdout){ if(stdout){ cache.value.files[file] = {} stdout .trim("\n") .split("\n") .forEach(function(line){ line = line.trim() cache.value.files[file][cache.value.mapByEmail[line.match(emailRE)[1]].login] = line.match(commitsRE)[1] }) } }, function(stderr){ console.error(stderr) throw stderr }) .done(cb) }) }) async.parallelLimit(parallelFiles, 20, function(){ // console.log(cache.value.files) gutil.log("Contributions map for files done") resolve() }) }) }) } /** * contributors tasks * * reads all pages & create a contributors list * in `tasks/cache/contributors` */ module.exports = function(cb){ if(cache.value !== null){ cb() return } cache.value = {} contributorsMap() .then(totalContributions) .then(filesContributions) .done(function(){ cb() }, function(err){ cb(err) }) }
JavaScript
0.000001
@@ -596,17 +596,16 @@ hub%22))(%7B - version @@ -613,17 +613,16 @@ %223.0.0%22 - %7D)%0A%0Avar
4d2267001ab7cdbeafc5911acbd6ec67a243bc4c
change devServer location
lib/commands/serve.js
lib/commands/serve.js
"use strict"; const inquirer = require("inquirer"); const path = require("path"); const chalk = require("chalk"); const spawn = require("cross-spawn"); const List = require("webpack-addons").List; const processPromise = require("../utils/resolve-packages").processPromise; /** * * Installs WDS using NPM with --save --dev etc * * @param {Object} cmd - arg to spawn with * @returns {Void} */ const spawnNPMWithArg = cmd => spawn.sync("npm", ["install", "webpack-dev-server", cmd], { stdio: "inherit" }); /** * * Installs WDS using Yarn with add etc * * @param {Object} cmd - arg to spawn with * @returns {Void} */ const spawnYarnWithArg = cmd => spawn.sync("yarn", ["add", "webpack-dev-server", cmd], { stdio: "inherit" }); /** * * Find the path of a given module * * @param {Object} dep - dependency to find * @returns {String} string with given path */ const getRootPathModule = dep => path.resolve(process.cwd(), dep); /** * * Prompts for installing the devServer and running it * * @param {Object} args - args processed from the CLI * @returns {Function} invokes the devServer API */ function serve() { let packageJSONPath = getRootPathModule("package.json"); if (!packageJSONPath) { console.log( "\n", chalk.red("✖ Could not find your package.json file"), "\n" ); process.exit(1); } let packageJSON = require(packageJSONPath); /* * We gotta do this, cause some configs might not have devdep, * dep or optional dep, so we'd need sanity checks for each */ let hasDevServerDep = packageJSON ? Object.keys(packageJSON).filter(p => packageJSON[p]["webpack-dev-server"]) : []; if (hasDevServerDep.length) { let WDSPath = getRootPathModule( "node_modules/webpack-dev-server/bin/webpack-dev-server.js" ); if (!WDSPath) { console.log( "\n", chalk.red( "✖ Could not find the webpack-dev-server dependency in node_modules root path" ) ); console.log( chalk.bold.green(" ✔︎"), "Try this command:", chalk.bold.green("rm -rf node_modules && npm install") ); process.exit(1); } return require(WDSPath); } else { process.stdout.write( "\n" + chalk.bold( "✖ We didn't find any webpack-dev-server dependency in your project," ) + "\n" + chalk.bold.green(" 'webpack serve'") + " " + chalk.bold("requires you to have it installed ") + "\n\n" ); return inquirer .prompt([ { type: "confirm", name: "confirmDevserver", message: "Do you want to install it? (default: Y)", default: "Y" } ]) .then(answer => { if (answer["confirmDevserver"]) { return inquirer .prompt( List( "confirmDepType", "What kind of dependency do you want it to be under? (default: devDependency)", ["devDependency", "optionalDependency", "dependency"] ) ) .then(depTypeAns => { const packager = getRootPathModule("package-lock.json") ? "npm" : "yarn"; let spawnAction; if (depTypeAns["confirmDepType"] === "devDependency") { if (packager === "yarn") { spawnAction = _ => spawnYarnWithArg("--dev"); } else { spawnAction = _ => spawnNPMWithArg("--save-dev"); } } if (depTypeAns["confirmDepType"] === "dependency") { if (packager === "yarn") { spawnAction = _ => spawnYarnWithArg(" "); } else { spawnAction = _ => spawnNPMWithArg("--save"); } } if (depTypeAns["confirmDepType"] === "optionalDependency") { if (packager === "yarn") { spawnAction = _ => spawnYarnWithArg("--optional"); } else { spawnAction = _ => spawnNPMWithArg("--save-optional"); } } return processPromise(spawnAction()).then(_ => { // Recursion doesn't work well with require call being cached delete require.cache[require.resolve(packageJSONPath)]; return serve(); }); }); } else { console.log(chalk.bold.red("✖ Serve aborted due cancelling")); process.exitCode = 1; } }) .catch(err => { console.log(chalk.red("✖ Serve aborted due to some errors")); console.error(err); process.exitCode = 1; }); } } module.exports = { serve, getRootPathModule, spawnNPMWithArg, spawnYarnWithArg };
JavaScript
0
@@ -1746,30 +1746,11 @@ ver/ -bin/webpack-dev-server +cli .js%22
f1dac8058f8bb4fa070dcbcff845352b4c845a64
Remove undefined argument.
lib/passport/index.js
lib/passport/index.js
/** * Module dependencies. */ var fs = require('fs') , path = require('path') , util = require('util') , Strategy = require('./strategy') , SessionStrategy = require('./strategies/session') , initialize = require('./middleware/initialize') , authenticate = require('./middleware/authenticate'); /** * `Passport` constructor. * * @api public */ function Passport() { this._key = 'passport'; this._strategies = {}; this._serializers = []; this._deserializers = []; this.use(new SessionStrategy()); }; /** * Utilize the given `strategy` with optional `name`, overridding the strategy's * default name. * * Examples: * * passport.use(new TwitterStrategy(...)); * * passport.use('api', new http.BasicStrategy(...)); * * @param {String|Strategy} name * @param {Strategy} strategy * @return {Passport} for chaining * @api public */ Passport.prototype.use = function(name, strategy) { if (!strategy) { strategy = name; name = strategy.name; } if (!name) throw new Error('authentication strategies must have a name'); this._strategies[name] = strategy; return this; }; /** * Passport's primary initialization middleware. * * This middleware must be in use by the Connect/Express application for * Passport to operate. * * Examples: * * app.configure(function() { * app.use(passport.initialize()); * }); * * @return {Function} middleware * @api public */ Passport.prototype.initialize = function() { return initialize().bind(this); } /** * Middleware that will restore login state from a session. * * Web applications typically use sessions to maintain login state between * requests. For example, a user will authenticate by entering credentials into * a form which is submitted to the server. If the credentials are valid, a * login session is established by setting a cookie containing a session * identifier in the user's web browser. The web browser will send this cookie * in subsequent requests to the server, allowing a session to be maintained. * * If sessions are being utilized, and a login session has been established, * this middleware will populate `req.user` with the current user. * * Note that sessions are not strictly required for Passport to operate. * However, as a general rule, most web applications will make use of sessions. * An exception to this rule would be an API server, which expects each HTTP * request to provide credentials in an Authorization header. * * Examples: * * app.configure(function() { * app.use(connect.cookieParser()); * app.use(connect.session({ secret: 'keyboard cat' })); * app.use(passport.initialize()); * app.use(passport.session()); * }); * * @return {Function} middleware * @api public */ Passport.prototype.session = function() { return this.authenticate('session'); } /** * Middleware that will authenticate a request using the given `strategy` name, * with optional `options` and `callback`. * * Examples: * * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })(req, res); * * passport.authenticate('local', function(err, user) { * if (!user) { return res.redirect('/login'); } * res.end('Authenticated!'); * })(req, res); * * passport.authenticate('basic', { session: false })(req, res); * * app.get('/auth/twitter', passport.authenticate('twitter'), function(req, res) { * // request will be redirected to Twitter * }); * app.get('/auth/twitter/callback', passport.authenticate('twitter'), function(req, res) { * res.json(req.user); * }); * * @param {String} strategy * @param {Object} options * @param {Function} callback * @return {Function} middleware * @api public */ Passport.prototype.authenticate = function(strategy, options, callback) { return authenticate(strategy, options, callback).bind(this); } /** * Middleware that will authorize a third-party account using the given * `strategy` name, with optional `options`. * * If authorization is successful, the result provided by the strategy's verify * callback will be assigned to `req.account`. The existing login session and * `req.user` will be unaffected. * * This function is particularly useful when connecting third-party accounts * to the local account of a user that is currently authenticated. * * Examples: * * passport.authorize('twitter-authz', { failureRedirect: '/account' }); * * @param {String} strategy * @param {Object} options * @return {Function} middleware * @api public */ Passport.prototype.authorize = function(strategy, options) { options = options || {}; options.assignProperty = 'account'; return authenticate(strategy, options, callback).bind(this); } /** * Registers a function used to serialize user objects into the session. * * Examples: * * passport.serializeUser(function(user, done) { * done(null, user.id); * }); * * @api public */ Passport.prototype.serializeUser = function(fn, done) { if (typeof fn === 'function') { return this._serializers.push(fn); } // private implementation that traverses the chain of serializers, attempting // to serialize a user var user = fn; var stack = this._serializers; (function pass(i, err, obj) { // serializers use 'pass' as an error to skip processing if ('pass' === err) { err = undefined; } // an error or serialized object was obtained, done if (err || obj) { return done(err, obj); } var layer = stack[i]; if (!layer) { return done(new Error('failed to serialize user into session')); } try { layer(user, function(e, o) { pass(i + 1, e, o); } ) } catch(e) { return done(e); } })(0); } /** * Registers a function used to deserialize user objects out of the session. * * Examples: * * passport.deserializeUser(function(id, done) { * User.findById(id, function (err, user) { * done(err, user); * }); * }); * * @api public */ Passport.prototype.deserializeUser = function(fn, done) { if (typeof fn === 'function') { return this._deserializers.push(fn); } // private implementation that traverses the chain of deserializers, // attempting to deserialize a user var obj = fn; var stack = this._deserializers; (function pass(i, err, user) { // deserializers use 'pass' as an error to skip processing if ('pass' === err) { err = undefined; } // an error or deserialized user was obtained, done if (err || user) { return done(err, user); } var layer = stack[i]; if (!layer) { return done(new Error('failed to deserialize user out of session')); } try { layer(obj, function(e, u) { pass(i + 1, e, u); } ) } catch(e) { return done(e); } })(0); } /** * Return strategy with given `name`. * * @param {String} name * @return {Strategy} * @api private */ Passport.prototype._strategy = function(name) { return this._strategies[name]; } /** * Export default singleton. * * @api public */ exports = module.exports = new Passport(); /** * Framework version. */ exports.version = '0.1.4'; /** * Expose constructors. */ exports.Passport = Passport; exports.Strategy = Strategy; /** * Expose strategies. */ exports.strategies = {}; exports.strategies.SessionStrategy = SessionStrategy; /** * HTTP extensions. */ require('./http/request');
JavaScript
0.000006
@@ -4781,34 +4781,24 @@ egy, options -, callback ).bind(this)
f9ed83f581c23ca88b05125efa7f6dc0eb17f4f9
simplify infosnow parser
lib/tools/infosnow.js
lib/tools/infosnow.js
var domutil = require('./domutil'); var select = require('../select'); var debug = require('debug')('liftie:resort:infosnow'); function parse(dom) { var nodes = select(dom, '.block table tr'), liftStatus; nodes.some(function (node) { if (domutil.childText(node, 0).split(' ').shift() !== 'Lifts') { return; } liftStatus = domutil.collect(node.parent.parent.parent, '.content table tr .icon[src*="status"]', function (node) { var name, status; name = node.parent.next.next.children[0].data; status = node.attribs.src.split('/').pop().slice(0,-4); return { name: name, status: status }; }); return true; }); debug('Infosnow APGSGA Lift Status:', liftStatus); return liftStatus; } module.exports = parse;
JavaScript
0
@@ -60,24 +60,62 @@ ./select');%0A +var entities = require('./entities');%0A var debug = @@ -491,40 +491,40 @@ -var name, status;%0A%0A name = +return %7B%0A name: entities( node @@ -557,18 +557,21 @@ %5B0%5D.data -;%0A +),%0A st @@ -574,18 +574,17 @@ status - = +: node.at @@ -625,67 +625,8 @@ ,-4) -;%0A return %7B%0A name: name,%0A status: status %0A
39bfe5c847ed546659eb08d2124362dd73b0ef48
fix #134 context menu post creation
javascripts/content_scripts/posting.service.js
javascripts/content_scripts/posting.service.js
/** * @fileOverview Handle the creation and control * of the resource object, which is associated to * the target element. * * This module will broadcast the following internal * messages to other modules: * * posting/internal/targetActivated * when the target element is activated (got * focus or clicked) * * posting/internal/targetDeactivated * when the target element is deactivated * (lost focus) */ /*global SeamlessPosting, Privly */ /*global chrome */ // If Privly namespace is not initialized, initialize it var SeamlessPosting; if (SeamlessPosting === undefined) { SeamlessPosting = {}; } (function () { // If this file is already loaded, don't do it again if (SeamlessPosting.service !== undefined) { return; } /** * Deal with the target element, to create associated * Target resource item and send events * * @type {Object} */ var service = { /** * Whether seamless-posting button is enabled * * @type {Boolean} */ enabled: false, /** * A unique id for the current content context * * @type {String} */ contextId: Math.floor(Math.random() * 0xFFFFFFFF).toString(16) + Date.now().toString(16), /** * The DOM node of the last right click, used * to identify the target when user clicks a * context menu item. * * @type {Node} */ lastRightClientTarget: null }; /** * Create a resource object for the specified target node. * `SeamlessPosting.Target` and `SeamlessPosting.Button` * instance will be created and attached to the newly * created resource object. * * The resource object will be added to the global resource pool, * for being referenced in other modules. * * @param {Element} targetNode The editable element * @return {SeamlessPosting.Resource} */ service.createResource = function (targetNode) { var res = new SeamlessPosting.Resource(); var controllerInstance = new SeamlessPosting.Controller(); var targetInstance = new SeamlessPosting.Target(targetNode); var buttonInstance = new SeamlessPosting.Button(); var tooltipInstance = new SeamlessPosting.Tooltip(); var ttlSelectInstance = new SeamlessPosting.TTLSelect(); res.setInstance('controller', controllerInstance); res.setInstance('target', targetInstance); res.setInstance('button', buttonInstance); res.setInstance('tooltip', tooltipInstance); res.setInstance('ttlselect', ttlSelectInstance); res.attach(); return res; }; /** * Event listener callback, being called when the context menu * of the target is clicked * * @param {Element} target * @param {String} app The app user selected to use */ service.onContextMenuClicked = function (target, app) { if (!SeamlessPosting.util.isElementEditable(target)) { return; } target = SeamlessPosting.util.getOutMostTarget(target); if (target === null) { return; } var res = SeamlessPosting.resource.getByNode('target', target); res.broadcastInternal({ action: 'posting/internal/contextMenuClicked', app: app }); }; /** * Event listener callback, being called when the target element * is activated, for example, by clicking or focusing. * * @param {Event} ev */ service.onActivated = function (ev) { if (!service.enabled) { return; } var target = ev.target; if (!SeamlessPosting.util.isElementEditable(target)) { return; } target = SeamlessPosting.util.getOutMostTarget(target); if (target === null) { return; } var res = SeamlessPosting.resource.getByNode('target', target); if (res === null) { // this target has not been attached any Privly posting stuff res = service.createResource(target); } res.broadcastInternal({ action: 'posting/internal/targetActivated' }); }; /** * Event listener callback, being called when the target element * is deactivated, for example, losing focus. * * @param {Event} ev */ service.onDeactivated = function (ev) { var target = ev.target; if (!SeamlessPosting.util.isElementEditable(target)) { return; } target = SeamlessPosting.util.getOutMostTarget(target); if (target === null) { return; } var res = SeamlessPosting.resource.getByNode('target', target); if (res === null) { // failed to retrive related resource // the DOM structure might be broken by the host page.. // we don't handle this case. return; } res.broadcastInternal({ action: 'posting/internal/targetDeactivated' }); }; /** * Event listener callback, being called when mouse down. This * event listener is used to capture the target element of a * Chrome Extension context menu. * * @param {Event} ev */ service.onMouseDown = function (ev) { if (ev.button === 2) { service.lastRightClientTarget = ev.target; } }; /** * Set up DOM event handlers */ service.addEventListeners = function () { document.addEventListener('click', service.onActivated, false); document.addEventListener('focus', service.onActivated, true); document.addEventListener('blur', service.onDeactivated, true); document.addEventListener('mousedown', service.onMouseDown, true); }; // async execution, to support `document.open()` setTimeout(function () { // Bind event listeners immediately :-) // Event listeners are binded to the document, so it safe // to be executed before `body` being loaded. service.addEventListeners(); }, 0); // Check whether Privly button is enabled Privly.message.messageExtension({ask: 'options/isPrivlyButtonEnabled'}, true) .then(function (enabled) { service.enabled = enabled; }); // Listen messages sent from the background script and forward // them to the resource object Privly.message.addListener(function (message, sendResponse) { if (message.targetContextId !== undefined) { if (service.contextId !== message.targetContextId) { return; } return SeamlessPosting.resource.broadcast(message, sendResponse); } }); // Listen raw chrome messages, to receive clicking context menu // messages if (chrome && chrome.extension && chrome.extension.onRequest) { chrome.extension.onRequest.addListener(function (request) { if (request.type === 'RAW' && request.payload.action === 'posting/contextMenuClicked') { service.onContextMenuClicked(service.lastRightClientTarget, request.payload.app); } }); } SeamlessPosting.service = service; }());
JavaScript
0
@@ -4942,25 +4942,27 @@ rvice.on -MouseDown +ContextMenu = funct @@ -4976,37 +4976,8 @@ ) %7B%0A - if (ev.button === 2) %7B%0A @@ -5019,22 +5019,16 @@ target;%0A - %7D%0A %7D;%0A%0A @@ -5350,17 +5350,19 @@ er(' -mousedown +contextmenu ', s @@ -5374,17 +5374,19 @@ e.on -MouseDown +ContextMenu , tr @@ -6352,25 +6352,23 @@ chrome. -extension +runtime && chro @@ -6374,61 +6374,57 @@ ome. -extension.onRequest) %7B%0A chrome.extension.onRequest +runtime.onMessage) %7B%0A chrome.runtime.onMessage .add @@ -6449,16 +6449,38 @@ (request +, sender, sendResponse ) %7B%0A
ec9b91531abaf7754ce79cbd96b034356ec06382
json can be pluginified
lang/json/json.js
lang/json/json.js
/* * jQuery JSON Plugin * version: 2.1 (2009-08-14) * * This document is licensed as free software under the terms of the * MIT License: http://www.opensource.org/licenses/mit-license.php * * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org * website's http://www.json.org/json2.js, which proclaims: * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that * I uphold. * * It is also influenced heavily by MochiKit's serializeJSON, which is * copyrighted 2005 by Bob Ippolito. */ (function($) { /** jQuery.toJSON( json-serializble ) Converts the given argument into a JSON respresentation. If an object has a "toJSON" function, that will be used to get the representation. Non-integer/string keys are skipped in the object, as are keys that point to a function. json-serializble: The *thing* to be converted. **/ $.toJSON = function(o, replacer, space, recurse) { if (typeof(JSON) == 'object' && JSON.stringify) return JSON.stringify(o, replacer, space); if (!recurse && $.isFunction(replacer)) o = replacer("", o); if (typeof space == "number") space = " ".substring(0, space); space = (typeof space == "string") ? space.substring(0, 10) : ""; var type = typeof(o); if (o === null) return "null"; if (type == "undefined" || type == "function") return undefined; if (type == "number" || type == "boolean") return o + ""; if (type == "string") return $.quoteString(o); if (type == 'object') { if (typeof o.toJSON == "function") return $.toJSON( o.toJSON(), replacer, space, true ); if (o.constructor === Date) { var month = o.getUTCMonth() + 1; if (month < 10) month = '0' + month; var day = o.getUTCDate(); if (day < 10) day = '0' + day; var year = o.getUTCFullYear(); var hours = o.getUTCHours(); if (hours < 10) hours = '0' + hours; var minutes = o.getUTCMinutes(); if (minutes < 10) minutes = '0' + minutes; var seconds = o.getUTCSeconds(); if (seconds < 10) seconds = '0' + seconds; var milli = o.getUTCMilliseconds(); if (milli < 100) milli = '0' + milli; if (milli < 10) milli = '0' + milli; return '"' + year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds + '.' + milli + 'Z"'; } var process = ($.isFunction(replacer)) ? function (k, v) { return replacer(k, v); } : function (k, v) { return v; }, nl = (space) ? "\n" : "", sp = (space) ? " " : ""; if (o.constructor === Array) { var ret = []; for (var i = 0; i < o.length; i++) ret.push(( $.toJSON( process(i, o[i]), replacer, space, true ) || "null" ).replace(/^/gm, space)); return "[" + nl + ret.join("," + nl) + nl + "]"; } var pairs = [], proplist; if ($.isArray(replacer)) { proplist = $.map(replacer, function (v) { return (typeof v == "string" || typeof v == "number") ? v + "" : null; }); } for (var k in o) { var name, val, type = typeof k; if (proplist && $.inArray(k + "", proplist) == -1) continue; if (type == "number") name = '"' + k + '"'; else if (type == "string") name = $.quoteString(k); else continue; //skip non-string or number keys val = $.toJSON( process(k, o[k]), replacer, space, true ); if (typeof val == "undefined") continue; //skip pairs where the value is a function. pairs.push((name + ":" + sp + val).replace(/^/gm, space)); } return "{" + nl + pairs.join("," + nl) + nl + "}"; } }; /** jQuery.evalJSON(src) Evaluates a given piece of json source. **/ $.evalJSON = function(src) { if (typeof(JSON) == 'object' && JSON.parse) return JSON.parse(src); return eval("(" + src + ")"); }; /** jQuery.secureEvalJSON(src) Evals JSON in a way that is *more* secure. **/ $.secureEvalJSON = function(src) { if (typeof(JSON) == 'object' && JSON.parse) return JSON.parse(src); var filtered = src; filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@'); filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); if (/^[\],:{}\s]*$/.test(filtered)) return eval("(" + src + ")"); else throw new SyntaxError("Error parsing JSON, source is not valid."); }; /** jQuery.quoteString(string) Returns a string-repr of a string, escaping quotes intelligently. Mostly a support function for toJSON. Examples: >>> jQuery.quoteString("apple") "apple" >>> jQuery.quoteString('"Where are we going?", she asked.') "\"Where are we going?\", she asked." **/ $.quoteString = function(string) { if (string.match(_escapeable)) { return '"' + string.replace(_escapeable, function (a) { var c = _meta[a]; if (typeof c === 'string') return c; c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + string + '"'; }; var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g; var _meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; })(jQuery);
JavaScript
0.998923
@@ -534,16 +534,38 @@ o.%0A */%0A +steal.then(function()%7B %0A(functi @@ -6702,8 +6702,10 @@ Query);%0A +%7D)
559b02da0ea0b3446ca95750f658928e5d68925f
Support promise-arrays as groups' options
tests/integration/components/power-select/groups-test.js
tests/integration/components/power-select/groups-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import { typeInSearch, clickTrigger } from '../../../helpers/ember-power-select'; import { groupedNumbers } from '../constants'; import { find, findAll, click } from 'ember-native-dom-helpers'; moduleForComponent('ember-power-select', 'Integration | Component | Ember Power Select (Groups)', { integration: true }); test('Options that have a `groupName` and `options` are considered groups and are rendered as such', function(assert) { assert.expect(10); this.groupedNumbers = groupedNumbers; this.render(hbs` {{#power-select options=groupedNumbers onchange=(action (mut foo)) as |option|}} {{option}} {{/power-select}} `); assert.notOk(find('.ember-power-select-dropdown'), 'Dropdown is not rendered'); clickTrigger(); let rootLevelGroups = findAll('.ember-power-select-dropdown > .ember-power-select-options > .ember-power-select-group'); let rootLevelOptions = findAll('.ember-power-select-dropdown > .ember-power-select-options > .ember-power-select-option'); assert.equal(rootLevelGroups.length, 3, 'There is 3 groups in the root level'); assert.equal(rootLevelOptions.length, 2, 'There is 2 options in the root level'); assert.equal(find('.ember-power-select-group-name', rootLevelGroups[0]).textContent.trim(), 'Smalls'); assert.equal(find('.ember-power-select-group-name', rootLevelGroups[1]).textContent.trim(), 'Mediums'); assert.equal(find('.ember-power-select-group-name', rootLevelGroups[2]).textContent.trim(), 'Bigs'); assert.equal(rootLevelOptions[0].textContent.trim(), 'one hundred'); assert.equal(rootLevelOptions[1].textContent.trim(), 'one thousand'); let bigs = [].slice.apply(rootLevelGroups[2].children).filter((e) => e.classList.contains('ember-power-select-options'))[0]; let bigGroups = [].slice.apply(bigs.children).filter((e) => e.classList.contains('ember-power-select-group')); let bigOptions = [].slice.apply(bigs.children).filter((e) => e.classList.contains('ember-power-select-option')); assert.equal(bigGroups.length, 2, 'There is 2 sub-groups in the "bigs" group'); assert.equal(bigOptions.length, 1, 'There is 1 option in the "bigs" group'); }); test('Options that have a `groupName` but NOT `options` are NOT considered groups and are rendered normally', function(assert) { assert.expect(3); this.notQuiteGroups = [ { groupName: 'Lions', initial: 'L' }, { groupName: 'Tigers', initial: 'T' }, { groupName: 'Dogs', initial: 'D' }, { groupName: 'Eagles', initial: 'E' } ]; this.render(hbs` {{#power-select options=notQuiteGroups onchange=(action (mut foo)) as |option|}} {{option.groupName}} {{/power-select}} `); assert.notOk(find('.ember-power-select-dropdown'), 'Dropdown is not rendered'); clickTrigger(); assert.equal(findAll('.ember-power-select-option').length, 4); assert.equal(findAll('.ember-power-select-option')[1].textContent.trim(), 'Tigers'); }); test('When filtering, a group title is visible as long as one of it\'s elements is', function(assert) { assert.expect(3); this.groupedNumbers = groupedNumbers; this.render(hbs` {{#power-select options=groupedNumbers onchange=(action (mut foo)) as |option|}} {{option}} {{/power-select}} `); clickTrigger(); typeInSearch('ve'); let groupNames = [].slice.apply(findAll('.ember-power-select-group-name')).map((e) => e.textContent.trim()); let optionValues = [].slice.apply(findAll('.ember-power-select-option')).map((e) => e.textContent.trim()); assert.deepEqual(groupNames, ['Mediums', 'Bigs', 'Fairly big', 'Really big'], 'Only the groups with matching options are shown'); assert.deepEqual(optionValues, ['five', 'seven', 'eleven', 'twelve'], 'Only the matching options are shown'); typeInSearch('lve'); groupNames = [].slice.apply(findAll('.ember-power-select-group-name')).map((e) => e.textContent.trim()); assert.deepEqual(groupNames, ['Bigs', 'Really big'], 'With no depth level'); }); test('Click on an option of a group select selects the option and closes the dropdown', function(assert) { assert.expect(2); this.groupedNumbers = groupedNumbers; this.render(hbs` {{#power-select options=groupedNumbers selected=foo onchange=(action (mut foo)) as |option|}} {{option}} {{/power-select}} `); clickTrigger(); let option = [].slice.apply(findAll('.ember-power-select-option')).filter((e) => e.textContent.indexOf('four') > -1)[0]; click(option); assert.equal(find('.ember-power-select-trigger').textContent.trim(), 'four', 'The clicked option was selected'); assert.notOk(find('.ember-power-select-options'), 'The dropdown has dissapeared'); }); test('Clicking on the title of a group doesn\'t performs any action nor closes the dropdown', function(assert) { assert.expect(1); this.groupedNumbers = groupedNumbers; this.render(hbs` {{#power-select options=groupedNumbers onchange=(action (mut foo)) as |option|}} {{option}} {{/power-select}} `); clickTrigger(); click(findAll('.ember-power-select-group-name')[1]); assert.ok(find('.ember-power-select-dropdown'), 'The select is still opened'); });
JavaScript
0
@@ -288,16 +288,70 @@ elpers'; +%0Aimport DS from 'ember-data';%0Aimport RSVP from 'rsvp'; %0A%0Amodule @@ -5260,16 +5260,531 @@ l opened');%0A%7D);%0A +%0Atest('it works if the options of a group is an array-proxy', function(assert) %7B%0A let smallOptions = DS.PromiseArray.create(%7B%0A promise: RSVP.resolve(%5B'one', 'two', 'three'%5D)%0A %7D);%0A this.groupedNumbers = %5B%0A %7B groupName: 'Smalls', options: smallOptions %7D,%0A %7B groupName: 'Mediums', options: %5B'four', 'five', 'six'%5D %7D%0A %5D;%0A%0A this.render(hbs%60%0A %7B%7B#power-select options=groupedNumbers onchange=(action (mut foo)) as %7Coption%7C%7D%7D%0A %7B%7Boption%7D%7D%0A %7B%7B/power-select%7D%7D%0A %60);%0A clickTrigger();%0A debugger;%0A%7D);%0A
a109bdbade4485964830e7ceff05a158d529895c
Switch default GitHub URLs to https:// over git://
default-input.js
default-input.js
var fs = require('fs') var path = require('path') var glob = require('glob') // more popular packages should go here, maybe? function isTestPkg (p) { return !!p.match(/^(expresso|mocha|tap|coffee-script|coco|streamline)$/) } function niceName (n) { return n.replace(/^node-|[.-]js$/g, '') } function readDeps (test) { return function (cb) { fs.readdir('node_modules', function (er, dir) { if (er) return cb() var deps = {} var n = dir.length if (n === 0) return cb(null, deps) dir.forEach(function (d) { if (d.match(/^\./)) return next() if (test !== isTestPkg(d)) return next() var dp = path.join(dirname, 'node_modules', d, 'package.json') fs.readFile(dp, 'utf8', function (er, p) { if (er) return next() try { p = JSON.parse(p) } catch (e) { return next() } if (!p.version) return next() deps[d] = config.get('save-prefix') + p.version return next() }) }) function next () { if (--n === 0) return cb(null, deps) } }) }} exports.name = prompt('name', package.name || basename) exports.version = prompt('version', package.version || '0.0.0') if (!package.description) { exports.description = prompt('description') } if (!package.main) { exports.main = function (cb) { fs.readdir(dirname, function (er, f) { if (er) f = [] f = f.filter(function (f) { return f.match(/\.js$/) }) if (f.indexOf('index.js') !== -1) f = 'index.js' else if (f.indexOf('main.js') !== -1) f = 'main.js' else if (f.indexOf(basename + '.js') !== -1) f = basename + '.js' else f = f[0] return cb(null, prompt('entry point', f || 'index.js')) }) } } if (!package.bin) { exports.bin = function (cb) { fs.readdir(path.resolve(dirname, 'bin'), function (er, d) { // no bins if (er) return cb() // just take the first js file we find there, or nada return cb(null, d.filter(function (f) { return f.match(/\.js$/) })[0]) }) } } exports.directories = function (cb) { fs.readdir(dirname, function (er, dirs) { if (er) return cb(er) var res = {} dirs.forEach(function (d) { switch (d) { case 'example': case 'examples': return res.example = d case 'test': case 'tests': return res.test = d case 'doc': case 'docs': return res.doc = d case 'man': return res.man = d } }) if (Object.keys(res).length === 0) res = undefined return cb(null, res) }) } if (!package.dependencies) { exports.dependencies = readDeps(false) } if (!package.devDependencies) { exports.devDependencies = readDeps(true) } // MUST have a test script! var s = package.scripts || {} var notest = 'echo "Error: no test specified" && exit 1' if (!package.scripts) { exports.scripts = function (cb) { fs.readdir(path.join(dirname, 'node_modules'), function (er, d) { setupScripts(d || [], cb) }) } } function setupScripts (d, cb) { // check to see what framework is in use, if any function tx (test) { return test || notest } if (!s.test || s.test === notest) { if (d.indexOf('tap') !== -1) s.test = prompt('test command', 'tap test/*.js', tx) else if (d.indexOf('expresso') !== -1) s.test = prompt('test command', 'expresso test', tx) else if (d.indexOf('mocha') !== -1) s.test = prompt('test command', 'mocha', tx) else s.test = prompt('test command', tx) } return cb(null, s) } if (!package.repository) { exports.repository = function (cb) { fs.readFile('.git/config', 'utf8', function (er, gconf) { if (er || !gconf) return cb(null, prompt('git repository')) gconf = gconf.split(/\r?\n/) var i = gconf.indexOf('[remote "origin"]') if (i !== -1) { var u = gconf[i + 1] if (!u.match(/^\s*url =/)) u = gconf[i + 2] if (!u.match(/^\s*url =/)) u = null else u = u.replace(/^\s*url = /, '') } if (u && u.match(/^git@github.com:/)) u = u.replace(/^git@github.com:/, 'git://github.com/') return cb(null, prompt('git repository', u)) }) } } if (!package.keywords) { exports.keywords = prompt('keywords', function (s) { if (!s) return undefined if (Array.isArray(s)) s = s.join(' ') if (typeof s !== 'string') return s return s.split(/[\s,]+/) }) } if (!package.author) { exports.author = config.get('init.author.name') ? { "name" : config.get('init.author.name'), "email" : config.get('init.author.email'), "url" : config.get('init.author.url') } : prompt('author') } exports.license = prompt('license', package.license || config.get('init.license') || 'ISC')
JavaScript
0.000005
@@ -4120,19 +4120,21 @@ com:/, ' -git +https ://githu
1740ff825ae83255df970bd538bd529c8f531dcf
fix .max-legth to .maxlength
demo/js/index.js
demo/js/index.js
$(function(){ var getUniqueArray = function( array ){ return array.filter(function(elem, pos, self) { return self.indexOf(elem) === pos; }); }; var getUniqueWordListFromSource = function( $target ){ var tmpArray = []; $target.each(function(){ tmpArray.push( $(this).text() ); }); return getUniqueArray( tmpArray ); }; $(function(){ $('.translation').each(function(){ var $this = $(this); $this.find('.target') .on('autosize.resize', function(){ // $(this).trigger('resize'); }) .autosize() .textareaHighlighter({ // maxlength: 150, matches: [ {'className': 'matchHighlight', 'words': getUniqueWordListFromSource( $this.find('.source').find('.match') )}, {'className': 'hogeHighlight', 'words': getUniqueWordListFromSource( $this.find('.source').find('.hoge') )} ] }); }); $('.translation-max').each(function(){ var $this = $(this); $this.find('.target') .autosize() .textareaHighlighter({ matches: [ {'className': 'matchHighlight', 'words': getUniqueWordListFromSource( $this.find('.source').find('.match') )}, {'className': 'hogeHighlight', 'words': getUniqueWordListFromSource( $this.find('.source').find('.hoge') )} ], // maxlength: 150, maxlengthWarning: 'warning', maxlengthElement: $this.find('.max-length') }); }); }); });
JavaScript
0.001667
@@ -1758,17 +1758,16 @@ nd('.max -- length')
c57ca263e9ae3ef65e695038b165270bdec01420
update conceptnet algo outline; need nlp next
scripts/conceptnet.js
scripts/conceptnet.js
var ConceptNet = require('concept-net') var cn = ConceptNet(null, null, '5.4') // refer: https://github.com/commonsense/conceptnet5/wiki // https://github.com/commonsense/conceptnet5/wiki/API // algo to convert input to parameter: // 1. determine language // 2. need uri standardization // // examples // cn.URIstd('en', 'ground beef', function(err, res) { // console.log(res) // }) // cn.URIstd('ja', '車', function(err, res) { // console.log(res) // }) // cn.lookup("/c/ja/自動車", { // limit: 2, // offset: 0, // filter: "core" // }, function(err, res) { // console.log(res) // }) // cn.lookup('/c/en/donut',{ // filter: 'core'}, function(err, res) { // console.log(res) // }) // cn.search({ // start: "/c/en/donut" // }, function(err, res) { // console.log(res) // }) // cn.association("/c/en/cat", { // limit: 4, // filter: "/c/en/dog" // }, function(err, res) { // console.log(res) // })
JavaScript
0
@@ -225,16 +225,61 @@ ameter:%0A +// 0. higher level NLP interface for this KB%0A // 1. de @@ -326,16 +326,256 @@ ization%0A +// 3. determine parameters, and what graph user looks for: either just concept, or assertations, rel. See URI hierarchy https://github.com/commonsense/conceptnet5/wiki/URI-hierarchy%0A// 4. output result parser? e.g. compose into NL sentence%0A // %0A// e
2c97dc22e5a77d16b2770d22e5042a1eb77552e1
add robots.txt file and configuration. #27
site/gatsby-config.js
site/gatsby-config.js
module.exports = { siteMetadata: { title: `AJ Fisher Website`, description: `Personal website of AJFisher - technologist`, author: `@ajfisher`, siteURL: 'https://ajfisher.me' }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `image`, path: `${__dirname}/src/img`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `content`, path: `${__dirname}/src/content`, ignore: [`**/\.*`], }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-transformer-remark`, options: { plugins: [ `gatsby-transformer-remark-tags`, `gatsby-remark-reading-time`, { resolve: `gatsby-remark-relative-images` }, { resolve: `gatsby-remark-images`, options: { maxWidth: 1000, backgroundColor: `none`, quality: 90, withWebp: { quality: 90 }, showCaptions: true, disableBgImage: true }, }, { resolve: `gatsby-remark-responsive-image`, options: { maxWidth: 1000, backgroundColor: `none`, quality: 90, withWebp: { quality: 90 }, showCaptions: true, disableBgImage: true } } ] } }, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, ], }
JavaScript
0
@@ -56,15 +56,26 @@ her -Website +%7C Blog %7C Portfolio %60,%0A @@ -95,18 +95,9 @@ n: %60 -Personal w +W ebsi @@ -1893,24 +1893,55 @@ %7D,%0A %7D,%0A + %60gatsby-plugin-robots-txt%60%0A // this
f816875632fa37c0d2e2a35173123d8e5cf6dbde
fix strange issue with session became null in handleConnect this is somewhat weird case. Not sure exactly, what's happening anyway, we'll do a check and make sure kadira won't crash the app
lib/models/system.js
lib/models/system.js
var os = Npm.require('os'); SystemModel = function () { var self = this; this.startTime = Ntp._now(); this.newSessions = 0; this.sessionTimeout = 1000 * 60 * 30; //30 min try { var usage = Kadira._binaryRequire('usage'); this.usageLookup = Kadira._wrapAsync(usage.lookup.bind(usage)); } catch(ex) { console.error('Kadira: usage npm module loading failed - ', ex.message); } } _.extend(SystemModel.prototype, KadiraModel.prototype); SystemModel.prototype.buildPayload = function() { var metrics = {}; var now = Ntp._now(); metrics.startTime = Kadira.syncedDate.syncTime(this.startTime); metrics.endTime = Kadira.syncedDate.syncTime(now); metrics.sessions = _.keys(Meteor.default_server.sessions).length; metrics.memory = process.memoryUsage().rss / (1024*1024); metrics.newSessions = this.newSessions; this.newSessions = 0; var usage = this.getUsage() || {}; metrics.pcpu = usage.cpu; if(usage.cpuInfo) { metrics.cputime = usage.cpuInfo.cpuTime; metrics.pcpuUser = usage.cpuInfo.pcpuUser; metrics.pcpuSystem = usage.cpuInfo.pcpuSystem; } this.startTime = now; return {systemMetrics: [metrics]}; }; SystemModel.prototype.getUsage = function() { if(this.usageLookup && !this._dontTrackUsage) { try { return this.usageLookup(process.pid, {keepHistory: true}); } catch(ex) { if(/Unsupported OS/.test(ex.message)) { this._dontTrackUsage = true; var message = "kadira: we can't track CPU usage in this OS. " + "But it will work when you deploy your app!" console.warn(message); } else { throw ex; } } } }; SystemModel.prototype.handleSessionActivity = function(msg, session) { if(msg.msg === 'connect' && !msg.session) { this.countNewSession(session); } else if(['sub', 'method'].indexOf(msg.msg) != -1) { if(!this.isSessionActive(session)) { this.countNewSession(session); } } session._activeAt = Date.now(); } SystemModel.prototype.countNewSession = function(session) { if(!isLocalAddress(session.socket)) { this.newSessions++; } } SystemModel.prototype.isSessionActive = function(session) { var inactiveTime = Date.now() - session._activeAt; return inactiveTime < this.sessionTimeout; } // ------------------------------------------------------------------------- // // http://regex101.com/r/iF3yR3/2 var isLocalHostRegex = /^(?:.*\.local|localhost)(?:\:\d+)?|127(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|10(?:\.\d{1,3}){3}|172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2}$/; // http://regex101.com/r/hM5gD8/1 var isLocalAddressRegex = /^127(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|10(?:\.\d{1,3}){3}|172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2}$/; function isLocalAddress (socket) { var host = socket.headers['host']; if(host) return isLocalHostRegex.test(host); var address = socket.headers['x-forwarded-for'] || socket.remoteAddress; if(address) return isLocalAddressRegex.test(address); }
JavaScript
0
@@ -2048,24 +2048,190 @@ (session) %7B%0A + // sometimes, we get session as null due to no reason%0A // so, we don't need crash the apps%0A if(!session %7C%7C !session.socket) %7B%0A return this.newSessions++;%0A %7D%0A%0A if(!isLoca
b2934d1e03c8a571ce32fdc1646a73868708d3a5
Use translated pagination dir in index
scripts/generators.js
scripts/generators.js
var pagination = require('hexo-pagination'); var _ = require('lodash'); hexo.extend.generator.register('category', function(locals) { var config = this.config; var categories = locals.data.categories; if (config.category_generator) { var perPage = config.category_generator.per_page; } else { var perPage = 10; } var result = []; _.each(categories, function(category, title) { _.each(category, function(data, lang) { result = result.concat( pagination(lang + '/' + data.slug, getCategoryByName( locals.categories, data.category).posts, { perPage: perPage, layout: ['category', 'archive', 'index'], format: _c('pagination_dir', lang, config, locals) + '/%d/', data: { lang: lang, title: data.name, category: data.category, alternates: getAlternateCategories(category) } }) ); }); }); return result; }); hexo.extend.generator.register('posts', function(locals) { var posts = locals.posts.sort('-date').toArray(); var length = posts.length; return posts.map(function(post, i) { var layout = post.layout; var path = post.path; if (!layout || layout === 'false') { return { path: path, data: post.content }; } else { if (i) post.prev = posts[i - 1]; if (i < length - 1) post.next = posts[i + 1]; var layouts = ['post', 'page', 'index']; if (layout !== 'post') layouts.unshift(layout); if (post.label && post.lang) { post.alternates = getAlternatePosts(posts, post.label) } return { path: path, layout: layouts, data: post }; } }); }); hexo.extend.generator.register('index', function(locals) { var result = []; var config = this.config; _.forEach(config.language, function(lang, n) { if (n == 0) { result = result.concat( { path: '', data: { redirect: lang }, layout: ['redirect'] } ); } if (lang != 'default') { result = result.concat( pagination(lang, locals.posts.sort('-date').toArray().filter( function(post) { return post.lang == lang; }), { perPage: config.per_page, layout: ['index'], format: '/%d/', data: { lang: lang, title: _c('title', lang, config, locals), alternates: getAlternateIndices(config, locals) } }) ); } }); return result; }); hexo.extend.generator.register('feed', function(locals) { var result = []; var config = this.config; _.forEach(config.language, function(lang) { if (lang != 'default') { result.push( { path: lang + '/feed.xml', data: { title: _c('title', lang, config, locals), lang: lang, posts: locals.posts.sort('-updated').filter(function(post) { return post.lang == lang; }) }, layout: ['rss2'] } ) } }); return result; }); function getCategoryByName(categories, name) { return categories.toArray().filter(function(category) { return category.name == name; })[0]; } function getAlternateCategories(category) { var result = []; _.each(category, function(data, lang) { result.push({ title: data.name, lang: lang, path: lang + '/' + data.slug }); }); return result; } function getAlternatePosts(posts, label) { var alternates = posts.filter(function(post) { return post.label == label; }); var result = []; _.each(alternates, function(post) { result.push({ title: post.title, lang: post.lang, path: post.path }); }); return result; } function getAlternateIndices(config, locals) { var result = []; _.each(config.language, function(lang) { if (lang != 'default') { result.push({ title: _c('title', lang, config, locals), lang: lang, path: lang }); } }); return result; } function _c(string, lang, config, locals) { if (locals.data['config_' + lang] != null) { return path(locals.data['config_' + lang], string) || path(config, string); } return path(config, string); } /** * Retrieve nested item from object/array (http://stackoverflow.com/a/16190716) * @param {Object|Array} obj * @param {String} path dot separated * @param {*} def default value ( if result undefined ) * @returns {*} */ function path(obj, path, def) { var i, len; for (i = 0, path = path.split('.'), len = path.length; i < len; i++) { if (!obj || typeof obj !== 'object') return def; obj = obj[path[i]]; } if (obj === undefined) return def; return obj; }
JavaScript
0
@@ -2143,16 +2143,61 @@ %09format: + _c('pagination_dir', lang, config, locals) + '/%25d/',
8ca4c0e7e621da5fa50e38040139d1e32592cdb8
fix color system <var> styles
docs/src/color-system.js
docs/src/color-system.js
import React from 'react' import PropTypes from 'prop-types' import chroma from 'chroma-js' import colors from 'primer-colors' import titleCase from 'title-case' import {BorderBox, Box, Flex, Heading, Text} from '@primer/components' const gradientHues = ['gray', 'blue', 'green', 'purple', 'yellow', 'orange', 'red'] const {black: BLACK, white: WHITE} = colors export function ColorPalette(props) { return ( <Flex mb={6} className="markdown-no-margin" {...props}> {gradientHues.map(hue => { const color = colors[hue][5] return ( <Box bg={color} p={3} width={200} mr={2} key={hue}> <Text fontWeight="bold" color={overlayColor(color)}> {titleCase(hue)} </Text> </Box> ) })} <BorderBox bg="white" p={3} width={200} borderRadius={0}> <Text fontWeight="bold" color="black"> White </Text> </BorderBox> </Flex> ) } export function ColorVariables(props) { return ( <> <Flex flexWrap="wrap" className="gutter" {...props}> {gradientHues.map(hue => ( <ColorVariable id={hue} hue={hue} key={hue} /> ))} </Flex> <Flex flexWrap="wrap" {...props}> <FadeVariables id="black" hue="black" bg="black" color="white"> <BorderBox border={0} borderRadius={0} borderTop={1} borderColor="gray.5" mt={1}> <Text as="div" fontSize={2} pt={3} mb={0}> Black fades apply alpha transparency to the <Var>$black</Var> variable. The black color value has a slight blue hue to match our grays. </Text> </BorderBox> </FadeVariables> <FadeVariables id="white" hue="white" over={BLACK}> <BorderBox border={0} borderRadius={0} borderTop={1} mt={1}> <Text as="div" fontSize={2} pt={3} mb={0}> White fades apply alpha transparency to the <Var>$white</Var> variable, below these are shown overlaid on a dark gray background. </Text> </BorderBox> </FadeVariables> </Flex> </> ) } export function ColorVariable({hue, ...rest}) { const values = colors[hue] return ( <Flex.Item as={Box} pr={4} mb={6} className="col-6 markdown-no-margin" {...rest}> {/* <Heading as="div">{titleCase(hue)}</Heading> */} <Box bg={`${hue}.5`} my={2} p={3} color="white"> <Heading as="div" pb={3} fontSize={56} fontWeight="light"> {titleCase(hue)} </Heading> <Flex justifyContent="space-between"> <Flex.Item flex="1 1 auto" as={Var}> ${hue}-500 </Flex.Item> <Text fontFamily="mono">{values[5]}</Text> </Flex> </Box> {values.map((value, i) => ( <Swatch name={`${hue}-${i}00`} value={value} key={value} /> ))} </Flex.Item> ) } ColorVariable.propTypes = { hue: PropTypes.oneOf(Object.keys(colors)).isRequired } export function FadeVariables({hue, color, bg, over, children, ...rest}) { const colorValue = colors[hue] const alphas = [15, 30, 50, 70, 85] const values = alphas.map(alpha => { const value = chroma(colorValue) .alpha(alpha / 100) .css() return { name: `${hue}-fade-${alpha}`, textColor: fadeTextColor(value, over), value } }) const boxProps = {color, bg} return ( <Flex.Item as={Box} pr={4} mb={6} width={1 / 2} className="markdown-no-margin" {...rest}> {/* <Heading as="div">{titleCase(hue)}</Heading> */} <Box my={2} p={3} {...boxProps}> <Heading as="div" pb={3} fontSize={56} fontWeight="light"> {titleCase(hue)} </Heading> <Flex justifyContent="space-between"> <Flex.Item flex="1 1 auto" as={Var}> ${hue} </Flex.Item> <Text fontFamily="mono"> {chroma(colorValue).css()} {' / '} {colorValue} </Text> </Flex> {children} </Box> <Box bg={over}> {values.map(swatchProps => ( <Swatch {...swatchProps} key={swatchProps.name} /> ))} </Box> </Flex.Item> ) } FadeVariables.propTypes = { bg: Box.propTypes.color, color: Box.propTypes.color, hue: PropTypes.oneOf(['black', 'white']), over: PropTypes.string } function Swatch(props) { const {name, value, textColor = overlayColor(value), ...rest} = props return ( <Box bg={value} {...rest}> <Text as={Flex} fontSize={1} justifyContent="space-between"> <Box p={3}> <Var color={textColor}>${name}</Var> </Box> <Box p={3}> <Text color={textColor} fontFamily="mono"> {value} </Text> </Box> </Text> </Box> ) } Swatch.propTypes = { name: PropTypes.string.isRequired, textColor: PropTypes.string, value: PropTypes.string.isRequired } function Var(props) { // FIXME: fontStyle should be a prop, right? return <Text as="var" fontWeight="bold" fontFamily="mono" css={{fontStyle: 'normal'}} {...props} /> } function overlayColor(bg) { return chroma(bg).luminance() > 0.5 ? BLACK : WHITE } function fadeTextColor(fg, bg = WHITE) { const rgb = compositeRGB(fg, bg) return overlayColor(rgb) } /** * Composite ("flatten") a foreground RGBA value with an RGB background into an * RGB color for the purposes of measuring contrast or luminance. */ function compositeRGB(foreground, background) { const [fr, fg, fb, fa] = chroma(foreground).rgba() const [br, bg, bb] = chroma(background).rgb() return chroma([(1 - fa) * br + fa * fr, (1 - fa) * bg + fa * fg, (1 - fa) * bb + fa * fb]).css() }
JavaScript
0
@@ -4458,16 +4458,34 @@ =%7Bvalue%7D + color=%7BtextColor%7D %7B...res @@ -4589,34 +4589,16 @@ %3CVar - color=%7BtextColor%7D %3E$%7Bname%7D @@ -4659,75 +4659,33 @@ ext -color=%7BtextColor%7D fontFamily=%22mono%22%3E%0A %7Bvalue%7D%0A +fontFamily=%22mono%22%3E%7Bvalue%7D %3C/Te @@ -4993,19 +4993,21 @@ =%22mono%22 -css +style =%7B%7BfontS
01fd81a1556b574ad03c85dc2cd336cd9bfed60e
add getElementById(weathercon) for icon switch
scripts/javascript.js
scripts/javascript.js
//Geolocation Function is listed below. function geoLocation() { var output = document.getElementById("out"); if (!navigator.geolocation) { output.innerHTML = "<p>Geolocation is not supported by your browser</p>"; return; } function success(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; //output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>'; /* var img = new Image(); img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false"; output.appendChild(img);*/ $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&key=AIzaSyAZch_gAq-6Ja3fUQ8sXStIhyB_dJ0mSgU', function(city) { var address = city.results[2].formatted_address; var userAddressObj = document.getElementById(userAddress); userAddress.innerHTML = "<p>Current condtions for " + address; }); $.ajax({ url: 'https://api.darksky.net/forecast/61f104c5d563f5c8aa29eca3beea2bde/' + latitude + ',' + longitude + "?units=us", dataType: "jsonp", success: function(data) { var temp = data.currently.temperature; var description = data.currently.summary; var hourlyDescription = data.hourly.summary; console.log(data); var current = document.getElementById(conditions); conditions.innerHTML = "<p>It is currently " + Math.round(temp) + " °F" + " and " + description; var hourly = document.getElementById(twentyfour); twentyfour.innerHTML = "<p> Expect " + hourlyDescription; var icon = data.currently.icon; console.log(data.currently.icon); } }); } function error() { output.innerHTML = "Unable to retrieve your location"; } userAddress.innerHTML = "<p>Locating…</p>"; navigator.geolocation.getCurrentPosition(success, error); }
JavaScript
0
@@ -1853,32 +1853,104 @@ lyDescription;%0A%0A + var weatherIcon = document.getElementById(weathercon);%0A%0A @@ -2031,16 +2031,318 @@ .icon);%0A + /* switch (icon) %7B%0A case 'clear-night':%0A return weathercon.innerHTML = '%3Cdiv class=%22sun%22%3E %5C%0A %3Cdiv class=rays%3E';%0A break;%0A default:%0A%0A %7D */%0A
d4261f9b3daf68a982a10a8ddf562e264e81a54c
Add missing return on error
lib/notifications.js
lib/notifications.js
'use strict'; var aws = require('aws-sdk'); var async = require('async'); var bunyan = require('bunyan'); module.exports = function (config, logger) { logger = logger || bunyan.createLogger({name: 'autoscaling-notifications'}); var sns = new aws.SNS(config); var sqs = new aws.SQS(config); var autoScaling = new aws.AutoScaling(config); var snsTopicName = 'sns-topic'; var autoScalingNotificationTypes = { launch: "autoscaling:EC2_INSTANCE_LAUNCH", launch_error: "autoscaling:EC2_INSTANCE_LAUNCH_ERROR", terminate: "autoscaling:EC2_INSTANCE_TERMINATE", terminate_error: "autoscaling:EC2_INSTANCE_TERMINATE_ERROR", test: "autoscaling:TEST_NOTIFICATION" }; function createSnsTopic (topicName, cb) { // The callback will be called with (err, data) where data can contain the TopicArn return sns.createTopic({Name: topicName}, cb); } function subscribeSnsTopicWithSqs (snsTopicArn, sqsQueueArn, cb) { return sns.subscribe({Protocol: 'sqs', TopicArn: snsTopicArn, Endpoint: sqsQueueArn}, cb); } function createSqsQueue (sqsQueueName, attributes, cb) { // The callback will be called with (err, data) where data can contain the QueueUrl if (typeof attributes === 'function') { cb = attributes; attributes = {}; } return sqs.createQueue({QueueName: sqsQueueName, Attributes: attributes}, cb); } function getSqsQueueAttributes (sqsQueueUrl, attributeNames, cb) { // The callback will be called with (err, data) where data con contain a list of // attributes like [QueueArn, MessageRetentionPeriod, Policy, ...] // More here http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#getQueueAttributes-property // You can access them as data.Attributes.QueueArn if (typeof attributeNames ==='function') { cb = attributeNames; attributeNames = ['All']; } return sqs.getQueueAttributes({QueueUrl: sqsQueueUrl, AttributeNames: attributeNames}, cb); } function allowSnsToPublishOnSqs (notificatioName, sqsQueueUrl, sqsQueueArn, snsTopicArn, cb) { var policy = JSON.stringify({ Version: "2012-10-17", Statement: [{ Sid: notificatioName, Effect: "Allow", Principal: "*", Action: "sqs:SendMessage", Resource: sqsQueueArn, Condition: { ArnEquals: { "aws:SourceArn": snsTopicArn } } }] }); var params = { Attributes: { Policy: policy }, QueueUrl: sqsQueueUrl }; sqs.setQueueAttributes(params, cb); } function setupNotificationConfiguration (autoScalingGroupName, snsTopicArn, cb) { // Setup a notification system for autoscaling groups var autoScalingParams = { AutoScalingGroupName: autoScalingGroupName, NotificationTypes: [ autoScalingNotificationTypes.launch, autoScalingNotificationTypes.terminate, autoScalingNotificationTypes.launch_error, autoScalingNotificationTypes.terminate_error ], TopicARN: snsTopicArn }; return autoScaling.putNotificationConfiguration(autoScalingParams, cb); } function getSqsQueueUrl (sqsQueueName, cb) { createSqsQueue(sqsQueueName, function (err, data) { if (err) { cb(err); } cb(null, data.QueueUrl); }); } function setupNotifications (notificatioName, autoScalingGroupName, cb) { async.waterfall([ function snsTopic (cb) { createSnsTopic(notificatioName, function (err, data) { if (err) { return cb(err); } logger.debug('snsTopicData', data); cb(null, {snsTopicArn: data.TopicArn}); }); }, function sqsQueue (notificationData, cb) { createSqsQueue(notificatioName, function (err, data) { if (err) { return cb(err); } logger.debug('sqsQueueData', data); notificationData.sqsQueueUrl = data.QueueUrl; cb(null, notificationData); }); }, function sqsQueueAttributes (notificationData, cb) { getSqsQueueAttributes(notificationData.sqsQueueUrl, function (err, data) { if (err) { return cb(err); } logger.debug('sqsQueueAttributes', data); notificationData.sqsQueueArn = data.Attributes.QueueArn; cb(null, notificationData); }); }, function subscribe (notificationData, cb) { var nData = notificationData; subscribeSnsTopicWithSqs(nData.snsTopicArn, nData.sqsQueueArn, function (err, data) { if (err) { return cb(err); } logger.debug('subscribeSnsTopicWithSqs', data); notificationData.subscriptionArn = data.SubscriptionArn; cb(null, notificationData); }); }, function setupAutoscalingNotification (notificationData, cb) { setupNotificationConfiguration(autoScalingGroupName, notificationData.snsTopicArn, function (err, data) { if (err) { return cb(err); } logger.debug('setupNotification', data); cb(null, notificationData); }); }, function setAutorization (notificationData, cb) { allowSnsToPublishOnSqs( notificatioName, notificationData.sqsQueueUrl, notificationData.sqsQueueArn, notificationData.snsTopicArn, function (err, data) { if (err) { return cb(err); } logger.debug('setAutorizationData', data); cb(null, notificationData); }); } ], function (err, result) { cb(err, result); }); } return { setupNotifications: setupNotifications, getSqsQueueUrl: getSqsQueueUrl }; };
JavaScript
0.000037
@@ -3301,24 +3301,31 @@ ) %7B%0A +return cb(err);%0A
4d626114a13ea932cc704efe269c7c74b15b02e3
Fix offset validation/setup
lib/ntfserver/api.js
lib/ntfserver/api.js
var global = require('./global') var plusWhere = function(where, text) { if (typeof(where) !== 'string') where = '' if (!text) return where return where ? where + ' ' + text + ' ' : ' WHERE ' + text + ' ' } var setupListRequest = function(req, cb) { if (typeof(cb) !== 'function') throw new Error('callback required') if (typeof(req) !== 'object') return cb(new Error('request argument must be an object')) // limit if (typeof(req.limit) !== 'number' || req.limit <= 0) req.limit = 100 if (req.limit > 1000) req.limit = 1000 // page if (typeof(req.page) === 'number') req.offset = req.limit * req.page // offset if (typeof(req.limit) !== 'number' || req.offset < 0) req.offset = 0 } var renderAgent = function(d) { d.url = '/agent/' + d.name return d } var renderSuite = function(d) { d.url = '/suite/' + d.name d.result_url = d.url + '/result' return d } var renderSuiteResult = function(d) { d.ok = d.fail == 0 d.url = '/suite/' + d.suite + '/result/' + d.id d.agent_url = '/agent/' + d.agent return d } exports.getAgentList = function(req, cb) { if (arguments.length == 1) { cb = req; req = {} } setupListRequest(req, cb); if (req.agent_name) req.limit = 1 var args = [] if (req.agent_name) args.push(req.agent_name) args.push(req.limit) args.push(req.offset) var where = '' where = plusWhere(where, (req.agent_name ? 'name = ?' : '')) global.sql.query( 'SELECT name FROM agent' + where + ' ORDER BY name LIMIT ? OFFSET ?', args, function(err, result) { if (err) return cb(err) cb(null, result.map(renderAgent)) }) } exports.getSuiteList = function(req, cb) { if (arguments.length == 1) { cb = req; req = {} } setupListRequest(req, cb); if (req.suite_name) req.limit = 1 var args = [] if (req.suite_name) args.push(req.suite_name) args.push(req.limit) args.push(req.offset) var where = '' where = plusWhere(where, (req.suite_name ? ' name = ?' : '')) global.sql.query( 'SELECT name FROM suite' + where + ' ORDER BY name LIMIT ? OFFSET ?', args, function(err, result) { if (err) return cb(err) cb(null, result.map(renderSuite)) }) } exports.getSuiteResultList = function(req, cb) { if (arguments.length == 1) { cb = req; req = {} } setupListRequest(req, cb); // suite result id if (req.hasOwnProperty('suite_result_id') && typeof(req.suite_result_id) !== 'number') { return cb(new Error('suite_result_id must be number')) } if (req.suite_result_id) req.limit = 1 var args = [req.suite_name] if (req.suite_result_id) args.push(req.suite_result_id) args.push(req.limit) args.push(req.offset) var where = '' where = plusWhere(where, 's.name = ?') where = plusWhere(where, (req.suite_result_id ? ' AND sr.suite_result_id = ?' : '')) global.sql.query( 'SELECT sr.suite_result_id AS id, s.name AS suite, a.name AS agent,' + ' sr.duration AS duration, sr.pass AS pass,' + ' sr.fail AS fail, sr.time AS time' + ' FROM suite_result sr' + ' LEFT JOIN suite s' + ' ON sr.suite_id = s.suite_id' + ' LEFT JOIN agent a' + ' ON sr.agent_id = a.agent_id' + ' ' + where + ' ORDER BY sr.time DESC, sr.suite_result_id DESC' + ' LIMIT ? OFFSET ?', args, function(err, result) { if (err) return cb(err) cb(null, result.map(renderSuiteResult)) }) }
JavaScript
0.000001
@@ -638,36 +638,37 @@ if (typeof(req. -limi +offse t) !== 'number'
5a18e7bc20eea459c4cef4fe41aa94b5c6f87175
Create a user if they don't exist
controllers/hemera/updateSlackProfile.js
controllers/hemera/updateSlackProfile.js
var hemera = require('./index'); var controller; /** * Every time a user posts a message, we update their slack profile so we can stay up to date on their profile * @param {Object} bot * @param {Object} message */ module.exports = function updateSlackProfile(bot, message) { controller = hemerga.getController(); controller.storage.users.get(message.user, function(err, user) { if (err) { return console.error(err); } bot.api.users.info({user: message.user}, function(err, res) { if (err) { return console.error(err); } user.slackUser = res.user; controller.storage.users.save(user, function() {}); }); }); };
JavaScript
0.000006
@@ -297,17 +297,16 @@ = hemer -g a.getCon @@ -597,32 +597,154 @@ %0A %7D%0A%0A + if (!user) %7B%0A user = %7B%0A id: message.user,%0A %7D;%0A %7D%0A%0A user
b4a2fe0f9c5e024b07566d245f9028c18bdf1fe7
increase interval between checkAlive calls
lib/phantomWorker.js
lib/phantomWorker.js
var childProcess = require('child_process'), phantomjs = require("phantomjs"), cluster = require("cluster"), http = require('http'), netCluster = require("net-cluster"), checkPortStatus = require("./checkPortStatus.js"), portScanner = require('portscanner'); var findFreePort = function (host, cb) { var server = netCluster.createServer(); var port = 0; server.on('listening', function () { port = server.address().port; server.close(); }); server.on('close', function () { cb(null, port); }); server.listen(0, host); }; var findFreePortInRange = function (host, portLeftBoundary, portRightBoundary, cb) { //in cluster we don't want ports to collide, so we make a special space for every worker assuming max number of cluster workers is 5 if (cluster.worker) { portLeftBoundary = portLeftBoundary + (((portRightBoundary - portLeftBoundary) / 5) * (cluster.worker.id - 1)); } portScanner.findAPortNotInUse(portLeftBoundary, portRightBoundary, host, function(error, port) { cb(error, port); }) }; var PhantomWorker = module.exports = function (options) { this.options = options; this.isBusy = false; if (options.portLeftBoundary && options.portRightBoundary) { this.findFreePort = function (cb) { findFreePortInRange(options.host, options.portLeftBoundary, options.portRightBoundary, cb); }; } else { this.findFreePort = function (cb) { findFreePort(options.host, cb); }; } }; PhantomWorker.prototype.start = function (cb) { var self = this; this.findFreePort(function (err, port) { if (err) return cb(err); self.port = port; var childArgs = [ '--ignore-ssl-errors=yes', '--web-security=false', '--ssl-protocol=any', self.options.pathToPhantomScript ]; var childOpts = { env: {} }; childOpts.env[self.options.hostEnvVarName] = self.options.host; childOpts.env[self.options.portEnvVarName] = port; //we send host and port as env vars to child process self._childProcess = childProcess.execFile(phantomjs.path, childArgs, childOpts, function (error, stdout, stderr) { }); self.checkAlive(cb); process.stdout.setMaxListeners(0); process.stderr.setMaxListeners(0); self._childProcess.stdout.pipe(process.stdout); self._childProcess.stderr.pipe(process.stderr); }); }; PhantomWorker.prototype.checkAlive = function (cb, shot) { var self = this; shot = shot || 1; checkPortStatus(this.port, this.options.host, function (err, status) { if (!err && status === 'open') { return cb(); } if (shot > 50) { return cb(new Error("Unable to reach phantomjs web server.")); } shot++; setTimeout(function() { self.checkAlive(cb, shot); }, 50); }); }; PhantomWorker.prototype.recycle = function (cb) { var self = this; self._childProcess.kill(); self.start(cb); }; PhantomWorker.prototype.kill = function () { if (this._childProcess) this._childProcess.kill("SIGTERM"); }; PhantomWorker.prototype.execute = function (options, cb) { var self = this; this.isBusy = true; var http_opts = { hostname: this.options.host, port: this.port, path: '/', method: 'POST' }; var req = http.request(http_opts, function (res) { var result = ""; res.on("data", function (chunk) { result += chunk; }); res.on("end", function () { self.isBusy = false; cb(null, result ? JSON.parse(result) : null); }); }); req.setHeader('Content-Type', 'application/json'); var json = JSON.stringify(options); req.setHeader('Content-Length', Buffer.byteLength(json)); req.write(json); req.on("error", function (e) { self.isBusy = false; cb(e); }); req.end(); };
JavaScript
0
@@ -3042,17 +3042,18 @@ %7D, -5 +10 0);%0A
ba3147083f0d41be4835098a77f988b2d49b545c
Add twitter and Facebook links
www/js/controllers/home_controller.js
www/js/controllers/home_controller.js
controllers.controller('HomeCtrl', function($scope, Settings, AdUtil) { function showHomeAd() { if(AdMob){//Because android need this on start up apparently var platform = Settings.getPlatformSettings(); console.log('<GFF> HomeCtrl showHomeAd Banner AdUnit: ' + platform.developerBanner ); AdUtil.showBannerAd( platform.developerBanner ); } } $scope.$on('$ionicView.enter', showHomeAd ); ionic.Platform.ready( showHomeAd );//Because view events do not appear to fire when the view first loads $scope.onEmailTap = function(){ window.open('mailto:support@giveforfreeonline.org', '_system', 'location=yes'); return false; } $scope.onFacebookTap = function(){ window.open('http://www.facebook.com', '_system', 'location=yes'); return false; } $scope.onTwitterTap = function(){ window.open('http://www.twitter.com', '_system', 'location=yes'); return false; } });
JavaScript
0
@@ -716,24 +716,25 @@ w.open('http +s ://www.faceb @@ -736,24 +736,55 @@ facebook.com +/Give-For-Free-643061692510804/ ', '_system' @@ -879,23 +879,20 @@ en('http +s :// -www. twitter. @@ -894,16 +894,30 @@ tter.com +/_giveforfree_ ', '_sys
7651a5abc1c6dbffece4dab59205e219690a61c7
Increase lookup cache for longer client caching
script/background.js
script/background.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 https://mozilla.org/MPL/2.0/. */ "use strict"; // local cache to not request a new resolution on every page navigation var cache = new Cache({trim: 60*3, ttl: 60*15}); // cache to hold the info which IP is used by the client to access a target var requestIPcache = new Cache({trim: 60*5, ttl: 60*60*4}); // request queue var requestQueue = new Cache({trim: 10, ttl: 15}); // Fire if page is loading chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { if (changeInfo.status == "loading") { let domain = df.parseUrl(tab.url); let ipFromRequest = null; if (requestIPcache.has(domain)) { ipFromRequest = requestIPcache.get(domain); } df.domainLookup({tab: tabId, url: tab.url, ip: ipFromRequest }); } }); // Fire if page has loaded chrome.webRequest.onResponseStarted.addListener(function (ret) { let ipFromRequest = null; let domain = df.parseUrl(ret.url); if (typeof ret.ip !== "undefined" && ret.ip != "") { ipFromRequest = ret.ip; } else if (requestIPcache.has(domain)) { ipFromRequest = requestIPcache.get(domain); } df.domainLookup({ tab: ret.tabId, url: ret.url, ip: ipFromRequest }); // cache client obtained IP address to cache for later use if (ipFromRequest != null) { requestIPcache.set(domain, ret.ip); } }, { urls: ["<all_urls>"], types: ["main_frame"] }); // extension started, request data for every open tab to show correct icon // if not done, user has to navigate to a new page for icon to be loaded chrome.windows.getAll({ populate: true }, function (windows) { allTabs(windows); }); function allTabs(windows) { for (let windowID = 0; windowID < windows.length; windowID++) { for (let tab = 0; tab < windows[windowID].tabs.length; tab++) { df.domainLookup({ tab: windows[windowID].tabs[tab].id, url: windows[windowID].tabs[tab].url }); } } } // listen for incoming messages from other views chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) { if (request.type == "popup") { // parse url to a domain let domain = df.parseUrl(request.url); if (typeof request.action === "undefined" || request.action == "get") { if (cache.has(domain)) { sendResponse(cache.get(domain)); } else { // no data is stored, popup should request it directly sendResponse(null) } } else if (request.action == "delete") { cache.delete(domain); } return; } else if (request.type == "resolved") { // get IP address which is used by the client to connect to the target server // parse url to a domain let domain = df.parseUrl(request.url); if (requestIPcache.has(domain)) { sendResponse(requestIPcache.get(domain)); } else { // no data is stored, popup should request it directly sendResponse(null) } return; } // other messages not correctly implemented yet Sentry.withScope(function (scope) { scope.setExtra("request", request); scope.setExtra("sender", sender); Sentry.captureMessage("unknown runtime message"); }); } );
JavaScript
0
@@ -322,9 +322,9 @@ 60* -3 +5 , tt @@ -329,18 +329,18 @@ ttl: 60* -15 +20 %7D);%0A// c
1ff7b1b2bb6d2699449d6f2301afb40582253a6a
Update optimizeCss configuration
webpack/plugins/optimizeCss.js
webpack/plugins/optimizeCss.js
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const cssnano = require('cssnano'); module.exports = (config) => { config.plugins = [ ...config.plugins, new OptimizeCssAssetsPlugin({ assetNameRegExp: /\.css$/g, cssProcessor: cssnano, cssProcessorOptions: require('../postcss/plugins/cssnano')(), canPrint: false, }), ]; return config; };
JavaScript
0
@@ -76,33 +76,100 @@ ');%0A +%0A const -cssnano = require(' +processor = require('cssnano');%0Aconst processorOptions = require('../postcss/plugins/ cssn @@ -173,16 +173,18 @@ ssnano') +() ;%0A%0Amodul @@ -341,23 +341,25 @@ cessor: -cssnano +processor ,%0A @@ -383,47 +383,24 @@ ns: -require('../postcss/plugins/cssnano')() +processorOptions ,%0A
085dc23a09961761413c0a942e460a060192c064
Define additional labels for tags.
webroot/common/ui/js/labels.js
webroot/common/ui/js/labels.js
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ define([ 'underscore' ], function (_) { var Labels = function () { this.get = function (key) { var keyArray, newKey; if (_.has(labelMap, key)) { return labelMap[key]; } else { keyArray = key.split('.'); newKey = keyArray[keyArray.length - 1]; if (keyArray.length > 1 && _.has(labelMap, newKey)) { return labelMap[newKey]; } else { return newKey.charAt(0).toUpperCase() + newKey.slice(1); } } }; this.getInLowerCase = function (key) { var label = this.get(key); return label.toLowerCase(); }; this.getInUpperCase = function (key) { var label = this.get(key); return label.toUpperCase(); }; var labelMap = { //General "id": "ID", 'email': 'Email', "domain": "Domain", "gateway": "Gateway", "ip_address": "IP Address", "status": "Status", "last_update": "Last Updated", //Server "ipmi_address": "IPMI", "ipmi_username": "IPMI Username", "ipmi_password": "IPMI Password", "base_image_id": "Base Image", "package_image_id": "Package", "roles": "Roles", "mac_address": "MAC Address", "interface_name": "Interface Name", "intf_bond": "Interface Bond", "intf_control": "Interface Control", "intf_data": "Interface Data", "compute_non_mgmt_ip": "Compute Non-Management IP", "compute_non_mgmt_gway": "Compute Non-Management Gateway", "static_ip": "Static IP", "host_name": "Host Name", //Tags "datacenter": "Datacenter", "floor": "Floor", "hall": "Hall", "rack": "Rack", "user_tag": "User Defined Tag", //Cluster "cluster_id": "Cluster", "analytics_data_ttl": "Analytics Data TTL", "ext_bgp": "External BGP", "openstack_mgmt_ip": "Openstack Management IP", "openstack_passwd": "Openstack Password", "keystone_tenant": "Keystone Tenant", "subnet_mask": "Subnet Mask", "router_asn": "Router ASN", "multi_tenancy": "Multi Tenancy", "uuid": "UUID", "use_certificates": "Use Certificates", "haproxy": "HA Proxy", "encapsulation_priority": "Encapsulation Priority", "keystone_username": "Keystone Username", "storage_virsh_uuid": "Storage Virsh UUID", "storage_fsid": "Storage FSID", "new_servers": "New Servers", "registered_servers": "Registered Servers", "configured_servers": "Configured Servers", "inprovision_servers": "In-Provision Servers", "provisioned_servers": "Provisioned Servers", "total_servers": "Total Servers", "external_bgp": "External BGP", "database_dir": "Database Dir", "database_token": "Database Token", //Roles "config": "Config", "openstack": "Openstack", "control": "Control", "compute": "Compute", "collector": "Collector", "webui": "Webui", "database": "Database", "assign_roles": "Assign Roles" }; this.TITLE_DETAILS = "Details"; this.TITLE_SERVERS_CONFIG = "Servers Config"; this.TITLE_CONTRAIL = "Contrail"; this.TITLE_STORAGE = "Storage"; this.TITLE_OPENSTACK = "Openstack"; this.TITLE_SYSTEM = "System"; this.TITLE_TAGS = "Tags"; this.TITLE_CONFIGURATIONS = "Configurations"; this.TITLE_SERVER_STATUS = "Server Status"; this.TITLE_STATUS = "Status"; this.TITLE_EDIT_CONFIG = "Edit Config"; this.TITLE_CREATE_CONFIG = "Create Config"; this.TITLE_ADD = "Add"; this.TITLE_REIMAGE = "Reimage"; this.TITLE_FILTER = "Filter"; this.TITLE_SELECT = "Select"; this.TITLE_CONFIRM = 'Confirm'; this.TITLE_PROVISION = "Provision"; this.TITLE_PROVISIONING = "Provisioning"; this.TITLE_TAG = "Tag"; this.TITLE_TAGS = "Tags"; this.TITLE_ROLE = "Role"; this.TITLE_ROLES = "Roles"; this.TITLE_DELETE = "Delete"; this.TITLE_CONFIGURE = 'Configure'; this.TITLE_CREATE = 'Create'; this.TITLE_CLUSTERS = 'Clusters'; this.TITLE_CLUSTER = 'Cluster'; this.TITLE_SERVERS = 'Servers'; this.TITLE_SERVER = 'Server'; this.TITLE_IMAGES = 'Images'; this.TITLE_IMAGE = 'Image'; this.TITLE_PACKAGES = 'Packages'; this.TITLE_PACKAGE = 'Package'; this.SELECT_CLUSTER = 'Select Cluster'; this.TITLE_ADD_CLUSTER = 'Add Cluster'; this.TITLE_DEL_CLUSTER = 'Delete Cluster'; this.TITLE_DEL_CLUSTERS = 'Delete Clusters'; this.TITLE_ADD_SERVER = 'Add Server'; this.TITLE_ADD_SERVERS = 'Add Servers'; this.TITLE_REMOVE_SERVERS = 'Remove Servers'; this.TITLE_ADD_SERVERS_TO_CLUSTER = 'Add Servers to Cluster'; this.TITLE_ADD_TAGS = 'Add Tags'; this.TITLE_ADD_IMAGE = 'Add Image'; this.TITLE_ADD_PACKAGE = 'Add Package'; this.TITLE_PROVISION_CLUSTER = 'Provision Cluster'; this.TITLE_ADD_TO_CLUSTER = 'Add to Cluster'; this.TITLE_REMOVE_FROM_CLUSTER = 'Remove from Cluster'; this.TITLE_REGISTER = 'Register'; this.TITLE_CONFIGURE_SERVER = 'Configure Server'; this.TITLE_CONFIGURE_SERVERS = 'Configure Servers'; this.TITLE_DEL_SERVER = 'Delete Server'; this.TITLE_EDIT_TAGS = 'Edit Tags'; this.TITLE_ASSIGN_ROLES = 'Assign Roles'; this.TITLE_PROVISION_SERVER = 'Provision Server'; this.TITLE_PROVISION_SERVERS = 'Provision Servers'; this.TITLE_SEARCH_SERVERS = 'Search Servers'; this.TITLE_FILTER_SERVERS = 'Filter Servers'; this.TITLE_SELECT_SERVERS = 'Select Servers'; this.TITLE_SELECTED_SERVERS = 'Selected Servers'; this.SELECT_IMAGE = 'Select Image'; this.SELECT_PACKAGE = 'Select Package'; this.SELECT_ROLES = 'Select Roles'; this.SEARCH_ROLES = 'Search Roles'; this.FILTER_TAGS = 'Filter Tags'; this.SEARCH_TAGS = 'Search Tags'; }; return Labels; });
JavaScript
0
@@ -1968,118 +1968,157 @@ %22 -datacenter%22: %22Datacenter%22,%0A %22floor%22: %22Floor%22,%0A %22hall%22: %22Hall%22,%0A %22rack%22: %22Rack +reservedby%22: %22Reserved By%22,%0A %22custom_tag1%22: %22Custom Tag 1%22,%0A %22custom_tag2%22: %22Custom Tag 2%22,%0A %22user_tag%22: %22Custom Tag %22,%0A @@ -2129,28 +2129,30 @@ %22 +c us -er +tom _tag%22: %22 User Def @@ -2147,20 +2147,14 @@ %22: %22 -User Defined +Custom Tag
faa121f04691284ee1990a6464ba1a0773168ac3
add info_only and spec_only options to apis.guru script
scripts/apis-guru.js
scripts/apis-guru.js
const request = require('request'); const async = require('async'); const fs = require('fs'); const path = require('path'); const integrate = require('./integrate'); const args = require('yargs').argv; const APIS_GURU_URL = "https://api.apis.guru/v2/list.json"; const SUFFIXES = [ '.com', '.org', '.net', '.co.uk', '.io', ] const NAME_CHANGES = { "m2010.vg": "magento", "googleapis.com": "google", "citrixonline.com": "citrix", "hetrascertification.net": "hetras", "nrel.gov": "nrel", "posty-api.herokuapp.com": "posty", "microsoft.com": "microsoft_security_updates", } const getName = (apisGuruName) => { let provider = ''; let name = NAME_CHANGES[apisGuruName]; if (!name) { name = apisGuruName.substring(apisGuruName.indexOf(':') + 1); provider = apisGuruName.substring(0, apisGuruName.indexOf(':')); provider = NAME_CHANGES[provider] || provider; SUFFIXES.forEach(suffix => { let regex = new RegExp(suffix.replace(/\./g, '\\.') + '$'); name = name.replace(regex, ''); provider = provider.replace(regex, ''); }); if (provider) name = provider + '_' + name; } name = name.toLowerCase().replace(/\W+/g, '_'); return {provider, name}; } const OUT_DIR = __dirname + '/../integrations/generated'; const DEPRECATED_DIR = __dirname + '/../integrations/deprecated'; request.get(APIS_GURU_URL, {json: true}, (err, resp, body) => { if (err) throw err; let keys = Object.keys(body); if (args.new) { keys = keys.filter(key => { let {provider, name} = getName(key); return !fs.existsSync(OUT_DIR + '/' + name) && !fs.existsSync(DEPRECATED_DIR + '/' + name); }) } if (args.name) { keys = keys.filter(key => { let {provider, name} = getName(key); return name === args.name; }) } async.parallel(keys.map(key => { return acb => { let {name, provider} = getName(key); let info = body[key]; let api = info.versions[info.preferred]; if (args.spec_only) { updateSpec(name, api.swaggerUrl, acb) } else { integrate({ name, openapi: api.swaggerUrl, patch: maybeGetPatch(name) || maybeGetPatch(provider), }, acb); } } }), err => { if (err) throw err; console.log('done'); }) }) function updateSpec(name, url, callback) { request.get(url, {json: true}, (err, resp, newSpec) => { if (err) return callback(err); let specFile = path.join(OUT_DIR, name, 'openapi.json'); let oldSpec = require(specFile); oldSpec.info.title = newSpec.info.title; oldSpec.info.description = newSpec.info.description; oldSpec.info['x-logo'] = newSpec.info['x-logo']; fs.writeFile(specFile, JSON.stringify(oldSpec, null, 2), (err) => { callback(err, oldSpec); }); }) } const maybeGetPatch = (name) => { try { return require('../patches/' + name); } catch (e) { return; } }
JavaScript
0
@@ -1968,24 +1968,111 @@ %5D;%0A if +(args.info_only) %7B%0A updateSpec(name, api.swaggerUrl, true, acb)%0A %7D else if (args.spec_o @@ -2118,16 +2118,23 @@ ggerUrl, + false, acb)%0A @@ -2416,16 +2416,26 @@ me, url, + infoOnly, callbac @@ -2439,16 +2439,126 @@ back) %7B%0A + let specFile = path.join(OUT_DIR, name, 'openapi.json');%0A if (!fs.existsSync(specFile)) return callback();%0A reques @@ -2659,72 +2659,64 @@ spec -File = path.join(OUT_DIR, name, 'openapi.json');%0A let oldSpec +ToWrite = newSpec;%0A if (infoOnly) %7B%0A specToWrite = r @@ -2733,31 +2733,37 @@ cFile);%0A -oldSpec + specToWrite .info.title @@ -2784,31 +2784,37 @@ .title;%0A -oldSpec + specToWrite .info.descri @@ -2851,23 +2851,29 @@ on;%0A -oldSpec + specToWrite .info%5B'x @@ -2906,16 +2906,64 @@ logo'%5D;%0A + %7D else %7B%0A specToWrite = newSpec;%0A %7D%0A fs.w @@ -2996,23 +2996,27 @@ ringify( -oldSpec +specToWrite , null, @@ -3054,15 +3054,19 @@ rr, -oldSpec +specToWrite );%0A
f79d16adf06dfa8faa32d82653d203b20ccc5c17
fix time for reading
lib/public/script.js
lib/public/script.js
var RENDER_NEW_QUOTE_TIMEOUT, LOAD_QUOTE_TIMEOUT; $(function() { History.Adapter.bind(window, 'statechange', function() { clearTimeout(RENDER_NEW_QUOTE_TIMEOUT); clearTimeout(LOAD_QUOTE_TIMEOUT); var quote = History.getState().data; if (quote.id && quote.id != CURRENT_QUOTE.id) renderNewQuote(quote); }); function loadNewQuote() { $.getJSON("quote", {t: new Date().getTime()}) .done(function(quote) { if (hasQuoteOnScreenAlready(quote)) loadNewQuote(); else { clearTimeout(RENDER_NEW_QUOTE_TIMEOUT); RENDER_NEW_QUOTE_TIMEOUT = setTimeout(function() { History.pushState(quote, null, quote.id); }, timeForReading()); } }) .fail(function() { clearTimeout(LOAD_QUOTE_TIMEOUT); LOAD_QUOTE_TIMEOUT = setTimeout(loadNewQuote, 5000); }); } function renderNewQuote(quote) { if (hasQuoteOnScreenAlready(quote)) return; $("blockquote").fadeOut(animationTimeout, function() { $(this).find(".content").html(quote.c).end() .find(".author").html(quote.a).end(); showQuote(quote); }); } function hasQuoteOnScreenAlready(quote) { return $("blockquote").is(":visible") && CURRENT_QUOTE.id == quote.id; } function renderTwitterButton() { var btn = '<a href="https://twitter.com/share" class="twitter-share-button" data-text="I like this quote at programming-quotes.com" data-hashtags="programming" data-url="' + window.location.href + '">Tweet</a>'; $("#tweet-button").empty().html(btn); if (!window.twttr) $.getScript("//platform.twitter.com/widgets.js", function() { twttr.widgets.load(); }); else twttr.widgets.load(); } function renderFacebookButton() { var btn = '<div class="fb-like" data-send="false" data-layout="button_count" data-width="450" data-show-faces="false" data-font="arial"></div>'; $("#fb-button").empty().html(btn); if (!window.FB) $.getScript("//connect.facebook.net/en_US/all.js#xfbml=1", function() { FB.XFBML.parse(); }); else FB.XFBML.parse(); } function showQuote(quote) { $("blockquote").fadeIn(animationTimeout); CURRENT_QUOTE = quote; renderTwitterButton(); renderFacebookButton(); _gaq.push(['_trackPageview']); loadNewQuote(); } function timeForReading() { var averageWPM = 200; var additionalFactor = 1.5; var time = (CURRENT_QUOTE.c + " " + CURRENT_QUOTE.a).split(" ").length * 60 / averageWPM * additionalFactor; return Math.ceil(Math.min(5, time) * 1000); } var animationTimeout = 1000; History.replaceState(CURRENT_QUOTE, null, CURRENT_QUOTE.id); renderNewQuote(CURRENT_QUOTE); });
JavaScript
0.000086
@@ -2565,44 +2565,20 @@ turn - Math.ceil(Math.min(5, time -) * 1000 -) ;%0A
5d988139616610134607e30cb9475b29dabc2e1b
Improve 'git' command
commands/base-basic.js
commands/base-basic.js
/* Basic Commands */ Settings.addPermissions(['say']); exports.commands = { credits: 'about', bot: 'about', about: function () { this.restrictReply(this.trad('about') + ". " + this.trad('author') + ": " + Settings.package.author.name + ". (" + Settings.package.homepage + ")", 'info'); }, git: 'github', github: function () { this.restrictReply(Tools.stripCommands(Settings.package.homepage), 'info'); }, botversion: 'version', version: function () { this.restrictReply(Tools.stripCommands(Settings.package.version), 'info'); }, guide: 'help', botguide: 'help', help: function () { this.restrictReply(this.trad('guide') + ': ' + (Config.botguide || (Settings.package.homepage + "/blob/master/commands/README.md")), 'info'); }, bottime: 'time', time: function () { var f = new Date(); this.restrictReply("**" + this.trad('time') + ":** __" + f.toString() + "__", 'info'); }, uptime: function () { var text = ''; text += '**Uptime:** '; var divisors = [52, 7, 24, 60, 60]; var units = [this.trad('week'), this.trad('day'), this.trad('hour'), this.trad('minute'), this.trad('second')]; var buffer = []; var uptime = ~~(process.uptime()); do { var divisor = divisors.pop(); var unit = uptime % divisor; if (!unit) { units.pop(); uptime = ~~(uptime / divisor); continue; } buffer.push(unit > 1 ? unit + ' ' + units.pop() + 's' : unit + ' ' + units.pop()); uptime = ~~(uptime / divisor); } while (uptime); switch (buffer.length) { case 5: text += buffer[4] + ', '; text += buffer[3] + ', '; text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0]; break; case 4: text += buffer[3] + ', '; text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0]; break; case 3: text += buffer[2] + ', ' + buffer[1] + ', ' + this.trad('and') + ' ' + buffer[0]; break; case 2: text += buffer[1] + ' ' + this.trad('and') + ' ' + buffer[0]; break; case 1: text += buffer[0]; break; } this.restrictReply(text, 'info'); }, seen: function (arg, by, room, cmd) { var text = ''; arg = toId(arg); if (!arg || arg.length > 18) return this.pmReply(this.trad('inv')); if (arg === toId(Bot.status.nickName)) return this.pmReply(this.trad('bot')); if (arg === toId(by)) return this.pmReply(this.trad('self')); if (Settings.seen[arg]) { var dSeen = Settings.seen[arg]; text += '**' + (dSeen.name || arg).trim() + '** ' + this.trad('s1') + ' __' + Tools.getTimeAgo(dSeen.time, this.language).trim() + (this.trad('s2') ? ('__ ' + this.trad('s2')) : '__'); if (dSeen.room) { switch (dSeen.action) { case 'j': text += ', ' + this.trad('j') + ' <<' + dSeen.room + '>>'; break; case 'l': text += ', ' + this.trad('l') + ' <<' + dSeen.room + '>>'; break; case 'c': text += ', ' + this.trad('c') + ' <<' + dSeen.room + '>>'; break; case 'n': text += ', ' + this.trad('n') + ' **' + dSeen.args[0] + '**'; break; } } } else { text += this.trad('n1') + ' ' + arg + ' ' + this.trad('n2'); } this.pmReply(text); }, say: function (arg) { if (!arg) return; if (!this.can('say')) return; this.reply(Tools.stripCommands(arg)); } };
JavaScript
0.99853
@@ -325,32 +325,65 @@ function () %7B%0A%09%09 +if (Settings.package.repository) this.restrictRep @@ -422,24 +422,30 @@ package. -homepage +repository.url ), 'info
80b62ec531677b25b18bc0cd6a35e836d8e2c197
Exit loop using break instead of value change.
chrome/chrome.js
chrome/chrome.js
if (sessionStorage.length == 0) { sessionStorage.setItem('debug', 1); window.location.reload(); } window.addEventListener('load', function (event) { setTimeout(function () { var container = document.createElement('div'); container.setAttribute('class', 'container'); var row = document.createElement('div'); row.setAttribute('class', 'row form-inline'); container.appendChild(row); var col = document.createElement('div'); col.setAttribute('class', 'col-md-12'); row.appendChild(col); var img = document.createElement('img'); img.setAttribute('id', 'microphone'); img.setAttribute('style', 'width: 5.5%;'); img.setAttribute('src', 'https://www.google.com/intl/en/chrome/assets/common/images/content/mic.gif' ); var input = document.createElement('input'); input.setAttribute('id', 'q'); input.setAttribute('style', 'width: 94%;'); input.setAttribute('class', 'form-control'); input.setAttribute('type', 'text'); input.setAttribute('name', 'q'); input.setAttribute('placeholder', 'Speak'); col.appendChild(img); col.appendChild(input); var row2 = document.createElement('div'); row2.setAttribute('class', 'row'); container.appendChild(row2); var col2 = document.createElement('div'); col2.setAttribute('class', 'col-md-12'); row2.appendChild(col2); var parse = document.createElement('div'); parse.setAttribute('class', 'message disabled'); parse.setAttribute('id', 'parse-message'); col2.appendChild(parse); var row3 = document.createElement('div'); row3.setAttribute('class', 'row form-inline'); container.appendChild(row3); var col3 = document.createElement('div'); col3.setAttribute('class', 'col-md-12'); row3.appendChild(col3); var pre = document.createElement('pre'); pre.setAttribute('class', 'disabled'); pre.setAttribute('id', 'output'); pre.innerText = 'Record some speech or type some text to display parser results.'; toolbox.parentNode.insertBefore(container, dialog.parentNode.childNodes[0]); document.getElementById('blockly').style.top = '250px' nodes = toolbox.parentNode.children; var toolboxdiv; for (var i = 0; i < nodes.length; i++) { if (nodes[i].className == 'blocklyToolboxDiv') { toolboxdiv = nodes[i]; i = nodes.length; } } toolboxdiv.style.top = '250px'; var jquery = document.createElement('script'); jquery.src = '//code.jquery.com/jquery-2.1.4.min.js'; document.head.appendChild(jquery); [ 'speech-blocks/core/blocks.js', 'speech-blocks/core/field_types.js', 'speech-blocks/core/where.js', 'speech-blocks/core/translation.js', 'speech-blocks/core/statement_input.js', 'speech-blocks/core/value_input.js', 'speech-blocks/core/successor.js', 'speech-blocks/core/predecessor.js', 'speech-blocks/core/controller.js', 'speech-blocks/core/interpreter.js', 'speech-blocks/grammar/grammar.js', 'speech-blocks/js/jsDump.js' ].forEach(function (src) { var scriptTag = document.createElement('script'); scriptTag.src = chrome.extension.getURL(src); document.head.appendChild(scriptTag); }); setTimeout(function () { var bootstrap = document.createElement('script'); bootstrap.src = '//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js'; document.head.appendChild(bootstrap); var init = document.createElement('script'); init.src = chrome.extension.getURL('init.js'); document.body.appendChild(init); }, 100); }, 100); });
JavaScript
0
@@ -2360,24 +2360,13 @@ -i = nodes.length +break ;%0A
f0fea42311fbe278a161d0b6bbd1f291acbc54f9
Add close to reader stream
lib/reader_stream.js
lib/reader_stream.js
var nsq = require("nsqjs"), Readable = require("stream").Readable, util = require("util"); function ReaderStream(topic, channel, options) { if (!(this instanceof ReaderStream)) { return new ReaderStream(topic, channel, options); } Readable.call(this, { objectMode: true }); var self = this; self.buffer = []; self.reader = new nsq.Reader(topic, channel, options); self.reader.on("discard", function (message) { self.emit("discard", message); }); self.reader.on("error", function (error) { self.emit("error", error); }); self.reader.on("message", function (message) { if (!self.push(message.body)) { self.buffer.push(message.body); } message.finish(); self.read(0); }); self.reader.on("nsqd_connected", function (host, port) { self.emit("nsqd_connected", host, port); }); self.reader.on("nsqd_closed", function (host, port) { self.emit("nsqd_closed", host, port); }); self.reader.connect(); } util.inherits(ReaderStream, Readable); /*jslint unparam:true*/ ReaderStream.prototype._read = function (size) { var buffer = this.buffer, index = 0; while (index < buffer.length && this.push(buffer[index])) { index += 1; } if (index < buffer.length) { this.buffer = this.buffer.slice(index); } }; /*jslint unparam:false*/ module.exports = ReaderStream;
JavaScript
0
@@ -1427,16 +1427,89 @@ alse*/%0A%0A +ReaderStream.prototype.close = function () %7B%0A this.reader.close();%0A%7D%0A%0A module.e
9125215f1a978b574efad4db4c0db814db2d5e36
Change to an arrow function
lib/rebel-request.js
lib/rebel-request.js
class Request { constructor(baseUrl, method, params, payload) { this.xhr = new XMLHttpRequest(); this.baseUrl = baseUrl; this.path = undefined; this.params = params; this.payload = payload; this.method = method; } at(path) { this.path = path || ""; return this.execute(); } execute() { const url = Request.interpolate(this.baseUrl + this.path, this.params) + Request.buildParamString(this.params); return new Promise((resolve, reject) => { this.xhr.open(this.method.toUpperCase(), url); this.xhr.onreadystatechange = function(event) { if (event.target.readyState === 4) { var result = (event.target.responseText.length > 0) ? Request.fromJson(event.target.responseText) : null; if (event.target.status === 200) { resolve(result); } else { reject(result); } } }; if (["post", "put"].indexOf(this.method) > -1) { this.xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8"); } const data = (this.payload !== undefined) ? Request.toJson(this.payload) : ""; this.xhr.send(data); }); } static buildParamString(params) { let paramString = ""; if (params != undefined && Object.keys(params).length > 0) { paramString = "?"; if (typeof params == "object") { for (var key in params) { if (paramString != "?") { paramString += "&"; } paramString += key + "=" + encodeURIComponent(params[key]); } } else { paramString += params; } } return paramString; } static interpolate(url, params) { if (typeof params == "object") { for (var key in params) { const find = "{" + key + "}"; if (url.indexOf(find) > -1) { url = url.replace(find, params[key]); delete params[key]; } } } return url; } static toJson(obj) { let str = ""; if (typeof obj == "object") { try { str = JSON.stringify(obj); } catch (e) { console.error("Invalid JSON object provided. "); } } return str; } static fromJson(str) { let obj = null; if (typeof str == "string") { try { obj = JSON.parse(str); } catch (e) { console.error("Invalid JSON string provided. "); } } return obj; } } class JpRequest { static count; constructor(baseUrl, params) { if (isNaN(JpRequest.count++)) { JpRequest.count = 0; } this.baseUrl = baseUrl; this.path = undefined; this.params = params; } at(path) { this.path = path; return this.execute(); } execute() { const timeout = 5000; let url = this.baseUrl + this.path + Request.buildParamString(this.params); return new Promise((resolve, reject) => { let callback = '__callback' + JpRequest.count++; const timeoutId = window.setTimeout(() => { reject(new Error('Request timeout.')); }, timeout); window[callback] = response => { window.clearTimeout(timeoutId); resolve(Request.fromJson(response)); }; const script = document.createElement('script'); script.src = url + (url.indexOf('?') === -1 ? '?' : '&') + 'callback=' + callback; script.onload = () => { script.remove(); }; document.getElementsByTagName('head')[0].appendChild(script); }); } } export class RebelRequest { constructor(baseUrl, config) { this.baseUrl = baseUrl || ""; this.format = ""; if (config != undefined) { this.format = config.format || ""; } return this; } get(params) { return new Request(this.baseUrl, "get", params); } getJson(params) { return new JpRequest(this.baseUrl, params); } post(payload, params) { return new Request(this.baseUrl, "post", params, payload); } put(payload, params) { return new Request(this.baseUrl, "put", params, payload); } delete(params) { return new Request(this.baseUrl, "delete", params); } }
JavaScript
0.000343
@@ -638,23 +638,18 @@ e = -function (event) + =%3E %7B%0A
61734a19a98eb206a0ac57a1b4e393ed44ff8301
fix token middleware
middleware/session.js
middleware/session.js
var User = require('../proxy').User; var jwt = require('jwt-simple'); var secret = require('../config').secret; var exp = require('../config').expire; var User = require('../proxy/user'); module.exports = { loginRequire: function (req,res,next) { // if(req.session.user){ // next(); // }else{ // // return res.json({status:-1,message:'please login first'}); // User.getUserByLoginName('huangyao',function (err,user) { // req.session.user = user; // next(); // }); // } // console.log(req.get('User-Agent')); var token = req.query.token; if(token){ var uid = jwt.decode(token,secret).uid; // if((new Date()).getTime() - jObject.exp * 1000 > exp){ // return res.json({status:102,message:'token expired'}); // } // console.log('point'); User.getUserById(uid,function (err,user) { if(err){ console.err(err.stack); throw err; } if(!user){ return res.json({status:101,message:'wrong token'}); }else{ req.session.user=user; next(); } }); }else if(!req.session.user){ return res.json({status:100,message:'please login first!'}); }else{ next(); } } };
JavaScript
0.000044
@@ -618,16 +618,41 @@ var +uid;%0A try %7B%0A uid = jw @@ -675,24 +675,113 @@ ecret).uid;%0A + %7D catch (e) %7B%0A return res.json(%7Bstatus:101,message:'wrong token'%7D);%0A %7D%0A // if(
de91c4103165bfd512a0beda018ffdd9a927b6d6
fix crash if missing options
lib/routes/result.js
lib/routes/result.js
var Hapi = require('hapi'); var hoek = require('hoek'); var moment = require('moment'); var storage = require('../storage.js'); var prepare = require('../view.js'); function handler(request, reply) { var id = request.query.id; storage.get(id, function (err, data) { var view; if (!data) { view = { error: true, err: { 'message': 'ID has expired' } }; } else { view = hoek.clone(data); } view.isMobileTarget = view.options.target === 'mobile'; view.isTabletTarget = view.options.target === 'tablet'; view.totalTestRuntime = 15000; if (view.error) { return reply.view('index.html', prepare(view, request, reply)); } if (view.report !== null) { if (view.state.started){ view.formattedStarted = moment(view.state.started).format('MMMM Do YYYY, h:mm:ss a'); } if (view.state.processed){ view.formattedProcessed = moment(view.state.processed).fromNow(); view.totalRuntime = moment(view.state.processed).diff(view.state.started, 'seconds') + ' seconds'; } return reply.view('report.html', prepare(view, request, reply)); } if (view.state.processed === null) { view.runtime = moment().diff(view.time); view.reloadIn = (view.totalTestRuntime - view.runtime); return reply.view('preview.html', prepare(view, request, reply)); } reply.view('index.html', prepare(view, request, reply)); }); } module.exports = { method: 'GET', path: '/result', config: { handler: handler, validate: { query: { id: Hapi.types.String().required(), debug: Hapi.types.Boolean().optional() } } } };
JavaScript
0.000015
@@ -327,25 +327,24 @@ - view = %7B%0A @@ -336,25 +336,24 @@ view = %7B%0A - @@ -389,17 +389,15 @@ - err: %7B%0A - @@ -448,36 +448,34 @@ - %7D%0A - %7D;%0A @@ -491,17 +491,16 @@ else %7B%0A - @@ -527,32 +527,24 @@ e(data);%0A - %7D%0A vie @@ -601,24 +601,27 @@ ';%0A + + view.isTable @@ -665,32 +665,35 @@ blet';%0A + view.totalTestRu @@ -706,16 +706,27 @@ = 15000; +%0A %7D %0A%0A
1f4adc92b938e9795570971dc75ffed21c1fe161
Fix the duplicate check
lib/schemas/index.js
lib/schemas/index.js
const Ajv = require('ajv'); const predefined = require('./predefined'); const ajv = new Ajv({ schemas: predefined }); const buildKey = (type, name) => `${type}:${name}`; const registeredKeys = []; function register (type, name, schema) { const key = buildKey(type, name); if (schema && registeredKeys.findIndex(keys => keys.key === key) !== -1) { ajv.addSchema(schema, key); registeredKeys.push({ type, name, key }); } return (data) => validate(type, name, data); } function validate (type, name, data) { const key = buildKey(type, name); const compiled = ajv.getSchema(key); if (compiled) { const isValid = compiled(data); return { isValid, error: ajv.errorsText(compiled.errors) }; } return { isValid: true }; } function get (type = null, name = null) { if (type && name) { const item = ajv.getSchema(buildKey(type, name)); if (item) { return [{ type, name, schema: item.schema }]; } } else if (type) { return registeredKeys .filter(item => item.type === type) .map(key => ({ key: key.type, type: key.name, schema: ajv.getSchema(key.key) })); } else { return registeredKeys .map(key => ({ key: key.type, type: key.name, schema: ajv.getSchema(key.key) })); } } module.exports = { register, validate, get };
JavaScript
0.000446
@@ -344,9 +344,9 @@ ey) -! += == -
f72f124afc77d67a7421fabab620df7134e024d5
Fix more optionsToSend bugs
lib/sheets/create.js
lib/sheets/create.js
var utils = require('../utils/httpUtils.js'); var _ = require('underscore'); exports.create = function(options) { var optionsToSend = { url: options.apiUrls.sheets, accessToken : options.accessToken, maxRetryTime : options.maxRetryTime, calcRetryBackoff: options.calcRetryBackoff }; var createSheet = function(postOptions, callback) { return utils.post(_.extend(optionsToSend, postOptions), callback); }; var createSheetFromExisting = function(postOptions, callback) { if (postOptions.workspaceId) { return createSheetInWorkspace(postOptions, callback); } else if (postOptions.folderId) { return createSheetInFolder(postOptions, callback); } else { return createSheet(postOptions, callback); } }; var createSheetInFolder = function(postOptions, callback) { optionsToSend.url = options.apiUrls.folders + postOptions.folderId + '/sheets'; return utils.post(_.extend(optionsToSend, postOptions), callback); }; var createSheetInWorkspace = function(postOptions, callback) { optionsToSend.url = options.apiUrls.workspaces + postOptions.workspaceId + '/sheets'; return utils.post(_.extend(optionsToSend, postOptions), callback); }; var copySheet = function(postOptions, callback) { optionsToSend.url = options.apiUrls.sheets + postOptions.sheetId + '/copy'; return utils.post(_.extend(optionsToSend, postOptions), callback); }; return { createSheet : createSheet, createSheetFromExisting : createSheetFromExisting, createSheetInFolder : createSheetInFolder, createSheetInWorkspace : createSheetInWorkspace, copySheet : copySheet }; };
JavaScript
0
@@ -375,32 +375,36 @@ s.post(_.extend( +%7B%7D, optionsToSend, p @@ -836,35 +836,38 @@ ) %7B%0A -optionsToSend.url = +var urlOptions = %7Burl: options @@ -909,32 +909,33 @@ erId + '/sheets' +%7D ;%0A return uti @@ -943,32 +943,36 @@ s.post(_.extend( +%7B%7D, optionsToSend, p @@ -961,32 +961,44 @@ , optionsToSend, + urlOptions, postOptions), c @@ -1082,35 +1082,38 @@ ) %7B%0A -optionsToSend.url = +var urlOptions = %7Burl: options @@ -1169,16 +1169,17 @@ /sheets' +%7D ;%0A re @@ -1195,32 +1195,36 @@ s.post(_.extend( +%7B%7D, optionsToSend, p @@ -1213,32 +1213,44 @@ , optionsToSend, + urlOptions, postOptions), c @@ -1325,27 +1325,30 @@ -optionsToSend.url = +var urlOptions = %7Burl: opt @@ -1398,16 +1398,17 @@ '/copy' +%7D ;%0A re @@ -1432,16 +1432,20 @@ .extend( +%7B%7D, optionsT @@ -1442,32 +1442,44 @@ , optionsToSend, + urlOptions, postOptions), c
28bcffbb0030e94f7a515c2027059ab698c53540
add customizing
resource/modules/utils/windowUtils.jsm
resource/modules/utils/windowUtils.jsm
Modules.VERSION = '2.3.2'; Modules.UTILS = true; Modules.CLEAN = false; // PrivateBrowsing - Private browsing mode aid this.__defineGetter__('PrivateBrowsing', function() { Observers; delete this.PrivateBrowsing; Modules.load('utils/PrivateBrowsing'); return PrivateBrowsing; }); // toCode - allows me to modify a function quickly and safely from within my scripts this.__defineGetter__('toCode', function() { delete this.toCode; Modules.load('utils/toCode'); return toCode; }); // keydownPanel - Panel elements don't support keyboard navigation by default; this object fixes that. this.__defineGetter__('keydownPanel', function() { delete this.keydownPanel; Modules.load('utils/keydownPanel'); return keydownPanel; }); // alwaysRunOnClose[] - array of methods to be called when a window is unloaded. Each entry expects function(aWindow) where // aWindow - (object) the window that has been unloaded this.alwaysRunOnClose = []; Modules.LOADMODULE = function() { // Overlays stuff, no need to load the whole module if it's not needed. // This will be run after removeObject(), so this is just to prevent any leftovers alwaysRunOnClose.push(function(aWindow) { delete aWindow['_OVERLAYS_'+objName]; try { var attr = aWindow.document.documentElement.getAttribute('Bootstrapped_Overlays').split(' '); if(attr.indexOf(objName) == -1) { return; } attr.splice(attr.indexOf(objName), 1); if(attr.length > 0) { aWindow.document.documentElement.setAttribute('Bootstrapped_Overlays', attr.join(' ')); } else { aWindow.document.documentElement.removeAttribute('Bootstrapped_Overlays'); } } catch(ex) {} // Prevent some unforeseen error here }); alwaysRunOnClose.push(removeObject); // This will not happen when quitting the application (on a restart for example), it's not needed in this case Listeners.add(window, 'unload', function(e) { window.willClose = true; // window.closed is not reliable in some cases // We don't use alwaysRunOnClose directly because removeObject() destroys it var tempArr = []; for(var i=0; i<alwaysRunOnClose.length; i++) { tempArr.push(alwaysRunOnClose[i]); } while(tempArr.length > 0) { tempArr.pop()(window); } delete window.willClose; }, false, true); }; Modules.UNLOADMODULE = function() { Modules.clean(); };
JavaScript
0
@@ -18,11 +18,11 @@ '2. -3.2 +4.0 ';%0AM @@ -717,16 +717,649 @@ l; %7D);%0A%0A +// customizing - quick access to whether the window is (or will be) in customize mode or not%0Athis.__defineGetter__('customizing', function() %7B%0A%09// duh%0A%09if(!window.gCustomizeMode) %7B return false; %7D%0A%09%0A%09if(window.gCustomizeMode._handler.isCustomizing() %7C%7C window.gCustomizeMode._handler.isEnteringCustomizeMode) %7B return true; %7D%0A%09%0A%09// this means that the window is still opening and the first tab will open customize mode%0A%09if(window.gBrowser.mCurrentBrowser%0A%09&& window.gBrowser.mCurrentBrowser.__SS_restore_data%0A%09&& window.gBrowser.mCurrentBrowser.__SS_restore_data.url == 'about:customizing') %7B%0A%09%09return true;%0A%09%7D%0A%09%0A%09return false;%0A%7D);%0A%0A // alway
1bfacf40635324d3b141acb15b2f509dc7ea06fb
Add newline
scripts/powerPick.js
scripts/powerPick.js
var _ = require('underscore'); // Credits: https://github.com/documentcloud/underscore-contrib // Sub module: underscore.object.selectors // License: MIT (https://github.com/documentcloud/underscore-contrib/blob/master/LICENSE) // https://github.com/documentcloud/underscore-contrib/blob/master/underscore.object.selectors.js // Will take a path like 'element[0][1].subElement["Hey!.What?"]["[hey]"]' // and return ["element", "0", "1", "subElement", "Hey!.What?", "[hey]"] function keysFromPath(path) { // from http://codereview.stackexchange.com/a/63010/8176 /** * Repeatedly capture either: * - a bracketed expression, discarding optional matching quotes inside, or * - an unbracketed expression, delimited by a dot or a bracket. */ var re = /\[("|')(.+)\1\]|([^.\[\]]+)/g; var elements = []; var result; while ((result = re.exec(path)) !== null) { elements.push(result[2] || result[3]); } return elements; } // Gets the value at any depth in a nested object based on the // path described by the keys given. Keys may be given as an array // or as a dot-separated string. function getPath (obj, ks) { ks = typeof ks == "string" ? keysFromPath(ks) : ks; var i = -1, length = ks.length; // If the obj is null or undefined we have to break as // a TypeError will result trying to access any property // Otherwise keep incrementally access the next property in // ks until complete while (++i < length && obj != null) { obj = obj[ks[i]]; } return i === length ? obj : void 0; } // Based on the origin underscore _.pick function // Credit: https://github.com/jashkenas/underscore/blob/master/underscore.js module.exports = function(object, keys) { var result = {}, obj = object, iteratee; iteratee = function(key, obj) { return key in obj; }; obj = Object(obj); for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; if (iteratee(key, obj)) result[key] = getPath(obj, key); } return result; };
JavaScript
0.000872
@@ -1995,8 +1995,9 @@ lt; %0A%7D; +%0A
7722b3d044759960284e604a3df9943f1b354b95
Update static_server.js
lib/static_server.js
lib/static_server.js
// Designed by rjf var os = require( 'os' ), http = require("http"), url = require("url"), qs = require("querystring"), path = require("path"), fs = require("fs"), ct = 0, port = process.argv[2] || 8888, // 启动端口 port tp = process.argv[3] || 'ftp', // 输出类型 type wp = process.argv[4] || process.cwd(); // 指定目录 dir var contentType = { ftp: 'application/octet-stream', http: { html: 'text/html', js: 'text/javascript', css: 'text/css', gif: 'image/gif', jpg: 'image/jpg', jpeg: 'image/jpeg', png: 'image/png', def: 'application/octet-stream' } }; var contType = contentType[tp] ? contentType[tp] : false; http.createServer(function(request, response) { request.setEncoding('utf8');//请求编码 var uri = qs.unescape( url.parse(request.url).pathname ), filename = path.join(wp, uri); fs.exists(filename, function(exists) { if(!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); return; } fs.stat(filename, function(err,stats) { if (err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } else { if (stats.isDirectory()) { var files = fs.readdirSync(filename); if (files) { if ( uri.lastIndexOf('/') == uri.length -1 ) { uri = uri.substring(0, uri.length-1); } var dir = '/'; if ( uri.lastIndexOf('/') > 0 ) { dir = uri.substring(0, uri.lastIndexOf('/')); } var all = ''; if ( uri.length > 0) { all = '<a href="' + dir + '">../' + '</a></br>'; } uri += '/'; for (var i in files) { all += '<a href="' + uri + qs.escape(files[i]) + '">' + files[i] + '</a></br>'; } all += '</br></br>power by nodejs downloads(' + ct + ')'; response.writeHead(202, {"Content-Type": "text/html; charset=UTF-8"}); response.write( all ); response.end(); } } else { ct++; var t = contType ? contType[filename.replace(/.*\.(\w+)/,'$1')] : false; var hd = { 'Content-Type' : t ? t : contentType['ftp'], 'Content-Length': stats.size }; response.writeHead(200, hd); fs.createReadStream(filename).pipe(response); } } }); }); }).listen(parseInt(port, 10)); console.log("Static file server running at\n => http://localhost:" + port + " type=" + tp + ", workspace=" + wp + "/\nCTRL + C to shutdown");
JavaScript
0.000003
@@ -2082,16 +2082,87 @@ ct + ') +. author %3Ca href=%22http://www.runjf.com%22 target=%22_blank%22%3Eruanjiefeng%3C/a%3E ';%0A
1b25ffe01a88f074ac6b85e689581633fa8bdf12
remove testing
lib/tools/Globals.js
lib/tools/Globals.js
/** * Created by apizzimenti on 1/1/17. */ var Error = require("./Error").Error, chalk = require("chalk"); function paramExist (param, type) { return (typeof(param) == type && param !== undefined && param !== null); } function Location (location) { if (paramExist(location, "object")) { apply(location, this); } } function Weather (w) { if (paramExist(w, "object")) { apply(w, this); } } function apply (give, receive) { for (var prop in give) { if (give.hasOwnProperty(prop)) { receive[prop] = give[prop]; } } } function realTime (timestring) { var date = new Date(timestring), hours = date.getHours(), minutes = date.getMinutes(), suffix = ""; hours = hours > 12 ? hours - 12 : hours; suffix = hours > 12 ? "pm" : "am"; minutes = minutes > 10 ? minutes : "0" + minutes; return hours + ":" + minutes + suffix; } function hotCold (temp, units) { var t, msg = "The temperature parameter does not exist.", e = new Error(msg); if (paramExist(temp, "number")) { t = units? 0 : 32; return (temp > t ? chalk.red(temp) : chalk.blue(temp)); } e.throw(); } function tableContent (content) { return { content: content, hAlign: "center" } } module.exports = { paramExist: paramExist, Location: Location, Weather: Weather, realTime: realTime, hotCold: hotCold, tableContent: tableContent };
JavaScript
0.000001
@@ -1023,67 +1023,8 @@ t,%0A - msg = %22The temperature parameter does not exist.%22,%0A @@ -1045,11 +1045,8 @@ ror( -msg );%0A @@ -1087,25 +1087,16 @@ er%22)) %7B%0A - %0A @@ -1104,16 +1104,17 @@ = units + ? 0 : 32 @@ -1119,17 +1119,8 @@ 32;%0A - %0A @@ -1186,24 +1186,85 @@ %0A %7D%0A %0A + e.message = %22The temperature parameter does not exist.%22;%0A e.throw( @@ -1299,24 +1299,29 @@ (content) %7B%0A + %0A return %7B @@ -1373,24 +1373,25 @@ enter%22%0A %7D +; %0A%7D%0A%0A%0Amodule.
e0b9ffe3111954c000e6b780443bf2efa0571c46
Add error handling
lib/twitter/utils.js
lib/twitter/utils.js
/* * Avocore : twitter/api.js * copyright (c) 2015 Susisu */ "use strict"; function end_module() { module.exports = Object.freeze({ "tweetRandom" : tweetRandom, "replyMentions" : replyMentions, "replyHomeTimeline": replyHomeTimeline, "followBack" : followBack }); } var core = require("../core.js"), actions = require("../actions.js"), api = require("./api.js"); function showDate() { return "[" + (new Date()).toLocaleTimeString() + "] "; } function tweetRandom(keys, file, separator, encoding) { return actions.readFile(file, encoding) .map(function (content) { return content.toString().split(separator); }) .bind(actions.pickRandom) .bind(function (status) { return api.post(keys, "statuses/update", { "status": status }) .then(actions.echo(showDate() + "Tweeted: " + status)) }); } function replyWith(keys, func) { return function (tweet) { var replyText = func(tweet); if (replyText !== undefined) { var status = "@" + tweet["user"]["screen_name"] + " " + replyText; return api.post(keys, "statuses/update", { "status" : status, "in_reply_to_status_id": tweet["id_str"] }) .then(actions.echo(showDate() + "Tweeted: " + status)); } else { return core.pure(undefined); } }; } function maxIdStr(x, y) { if (x.length > y.length) { return x; } else if (x.length < y.length) { return y; } else if (x > y) { return x; } else { return y; } } function replyMentions(keys, screenName, count, sinceId, func) { var params = {}; if (count !== undefined) { params["count"] = count; } if (sinceId !== undefined && sinceId !== "") { params["since_id"] = sinceId; } return api.get(keys, "statuses/mentions_timeline", params) .bind(function (tweets) { tweets = tweets.filter(function (data) { return data["text"] !== undefined && data["id_str"] !== undefined && data["user"] !== undefined && data["user"]["screen_name"] !== undefined && data["user"]["screen_name"] !== screenName; }); var latestIdStr = tweets.map(function (data) { return data["id_str"]; }) .reduce(maxIdStr, "0"); return actions.split(tweets) .bind(replyWith(keys, func)) .discard() .then(core.pure(latestIdStr)); }); } function replyHomeTimeline(keys, screenName, count, sinceId, func) { var params = { "exclude_replies": true }; if (count !== undefined) { params["count"] = count; } if (sinceId !== undefined && sinceId !== "") { params["since_id"] = sinceId; } return api.get(keys, "statuses/home_timeline", params) .bind(function (tweets) { tweets = tweets.filter(function (data) { return data["text"] !== undefined && data["id_str"] !== undefined && data["user"] !== undefined && data["user"]["screen_name"] !== undefined && data["user"]["screen_name"] !== screenName; }); var latestIdStr = tweets.map(function (data) { return data["id_str"]; }) .reduce(maxIdStr, "0"); return actions.split(tweets) .bind(replyWith(keys, func)) .discard() .then(core.pure(latestIdStr)); }); } function followBack(keys, screenName, count) { var params = { "screen_name": screenName }; if (count !== undefined) { params["count"] = count; } return api.get(keys, "followers/list", params) .filter(function (data) { return data["users"] !== undefined; }) .map(function (data) { return data["users"]; }) .bind(actions.split) .filter(function (data) { return data["screen_name"] !== undefined && data["following"] !== undefined; }) .filter(function (data) { return !data["following"]; }) .bind(function (user) { return api.post(keys, "friendships/create", { "screen_name": user["screen_name"], "follow" : true }) .then(actions.echo(showDate() + "Followed: " + user["screen_name"])); }) } end_module();
JavaScript
0.000002
@@ -1070,23 +1070,136 @@ Text - = func(tweet); +;%0A try %7B%0A replyText = func(tweet);%0A %7D%0A catch (error) %7B%0A console.log(error);%0A %7D %0A
5c60a40aa0caa9f323665e453795bea9a0f55d8c
Fix `batch` utility function
lib/utility/batch.js
lib/utility/batch.js
'use strict'; var qs = require('querystring'); /** * Send the given GET calls as a single batch request. * @param {Object} calls An object mapping the endpoint to params. The params can be `null`. * Each object can specify the keys `endpoint` and an object of `params` * @param {Function} cb(err, results) * {Object} results The result of each call, indexed by endpoint name */ module.exports = function batch(calls, cb) { var pages = []; for(var endpoint in calls) { pages.push(endpoint + qs.encode(calls[endpoint])); } this.getBatch({pages: pages}, cb); };
JavaScript
0.000315
@@ -487,29 +487,20 @@ -pages.push(endpoint + +var params = qs. @@ -522,16 +522,114 @@ dpoint%5D) +;%0A var page = endpoint;%0A if (params) %7B%0A page += '?' + params;%0A %7D%0A pages.push(page );%0A %7D%0A @@ -666,8 +666,9 @@ cb);%0A%7D; +%0A
0ca44d7ffb9478b50478c6d940bd3bee7a0c11b3
VersionedMap.delete() should return true/false
lib/versioned-map.js
lib/versioned-map.js
/** * Copyright 2013-2017 Zaid Abdulla * * This file is part of GenieACS. * * GenieACS is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * GenieACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with GenieACS. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; const NONEXISTENT = new Object(); function compareEquality(a, b) { var t = typeof a; if (t === 'number' || (a == null) || t === 'boolean' || t === 'string' || t === 'symbol') return a === b; return JSON.stringify(a) === JSON.stringify(b); } class VersionedMap { constructor() { this._sizeDiff = [0]; this._revision = 0; this.map = new Map(); } get size() { return this.map.size + this._sizeDiff[this.revision]; } get revision() { return this._revision; } set revision(rev) { for (let i = this._sizeDiff.length; i <= rev; ++ i) this._sizeDiff[i] = this._sizeDiff[i - 1]; this._revision = rev; } get(key, rev) { if (rev == null) rev = this._revision var v = this.map.get(key); if (!v) return; for (let i = Math.min(v.length - 1, rev); i >= 0; -- i) if (i in v) if (v[i] === NONEXISTENT) return undefined; else return v[i]; } has(key, rev) { if (rev == null) rev = this._revision var v = this.map.get(key); if (v == null) return false; for (let i = Math.min(v.length - 1, rev); i >= 0; -- i) if (i in v) if (v[i] === NONEXISTENT) return false; else return true; return false; } set(key, value, rev) { if (rev == null) rev = this._revision; var v = this.map.get(key); if (!v) { for (let i = 0; i < rev; ++ i) this._sizeDiff[i] -= 1; v = []; v[rev] = value; this.map.set(key, v); return this; } var old = v[Math.min(rev, v.length - 1)]; if (rev < v.length - 1) { if (compareEquality(value, old)) return else throw new Error('Cannot modify old revisions'); } if (old === NONEXISTENT) ++ this._sizeDiff[rev]; v[rev] = value; } delete(key, rev) { if (rev == null) rev = this._revision; var v = this.map.get(key); if (!v) return false; if (rev < v.length - 1) throw new Error('Cannot modify old revisions'); var old = v[v.length - 1]; if (old === NONEXISTENT) return false; -- this._sizeDiff[rev]; v[rev] = NONEXISTENT; return old; } getRevisions(key) { var v = this.map.get(key); if (!v) return null; var res = {}; for (let i in v) if (v[i] === NONEXISTENT) res.delete |= 1 << i; else res[i] = v[i]; return res; } setRevisions(key, revisions) { var del = 0; var rev = []; var minKey = 999; for (let k in revisions) { if (k === 'delete') del = revisions[k]; else { let r = parseInt(k); minKey = Math.min(minKey, r); for (let i = this._sizeDiff.length; i <= r; ++ i) this._sizeDiff[i] = this._sizeDiff[i - 1]; rev[r] = revisions[k]; } } for (let i = 0; i < minKey; ++ i) -- this._sizeDiff[i]; for (let i = 0; del > 0; del >>= 1, ++ i) if (del & 1) rev[i] = NONEXISTENT; this.map.set(key, rev); } getDiff(key) { var revisions = this.map.get(key); if (!revisions) return []; var current = revisions[revisions.length - 1]; if (current === NONEXISTENT) { if (0 in revisions) return [key, revisions[0]]; else return [key]; } else if (0 in revisions) return [key, revisions[0], current]; else return [key, , current]; } *diff() { for (let pair of this.map) { let current = pair[1][pair[1].length - 1]; if (current === NONEXISTENT) { if (0 in pair[1]) yield [pair[0], pair[1][0]]; else yield [pair[0]]; } else if (0 in pair[1]) yield [pair[0], pair[1][0], current]; else yield [pair[0], , current]; } } collapse(revision) { if (this._sizeDiff.length <= revision) return; this._sizeDiff[revision] = this._sizeDiff[this._sizeDiff.length - 1]; this._sizeDiff.splice(revision + 1, this._sizeDiff.length); for (let pair of this.map) { let k = pair[0]; let v = pair[1]; let last = v[v.length - 1]; if (last === NONEXISTENT) { v.splice(revision, v.length); if (v.some(function(val) { return true; })) v[revision] = NONEXISTENT; else this.map.delete(k); } else { v[revision] = last; v.splice(revision + 1, v.length); } } } } module.exports = VersionedMap;
JavaScript
0.999999
@@ -2630,16 +2630,17 @@ e;%0A %7D%0A%0A +%0A delete @@ -2996,19 +2996,20 @@ return -old +true ;%0A %7D%0A%0A%0A
26987ddcfd1677d30b9e61733eb02a2460cc67ab
Improve ES locale
select2_locale_es.js
select2_locale_es.js
/** * Select2 Spanish translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "No se encontraron resultados"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Por favor adicione " + n + " caracter" + (n == 1? "" : "es"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Por favor elimine " + n + " caracter" + (n == 1? "" : "es"); }, formatSelectionTooBig: function (limit) { return "Solo puede seleccionar " + limit + " elemento" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Cargando más resultados..."; }, formatSearching: function () { return "Buscando..."; } }); })(jQuery);
JavaScript
0
@@ -288,17 +288,20 @@ avor - adicione +, introduzca %22 + @@ -302,33 +302,59 @@ ca %22 + n + %22 car -a +%22 + (n == 1? %22%C3%A1%22 : %22a%22) + %22 cter%22 + (n == 1? @@ -466,16 +466,17 @@ or favor +, elimine @@ -489,17 +489,43 @@ + %22 car -a +%22 + (n == 1? %22%C3%A1%22 : %22a%22) + %22 cter%22 + @@ -607,17 +607,17 @@ eturn %22S -o +%C3%B3 lo puede @@ -842,16 +842,16 @@ %7D);%0A - %7D)(jQuer @@ -853,8 +853,9 @@ jQuery); +%0A
416c70dd03785c2627e9072f3a622165572969fc
clean up some of the implementation of queryCourseDatabase
modules/gob-web/helpers/query-course-database.js
modules/gob-web/helpers/query-course-database.js
import {db} from './db' import {buildQueryFromString} from '@gob/search-queries' import compact from 'lodash/compact' import filter from 'lodash/filter' import map from 'lodash/map' import some from 'lodash/some' import toPairs from 'lodash/toPairs' import fromPairs from 'lodash/fromPairs' import debug from 'debug' const log = debug('web:database') export default function queryCourseDatabase(queryString, baseQuery = {}) { let queryObject = buildQueryFromString(queryString, { words: true, profWords: true, }) let query = {} if ('year' in queryObject || 'semester' in queryObject) { query = queryObject } else { query = {...baseQuery, ...queryObject} } // make sure that all values are wrapped in arrays query = toPairs(query) query = map(query, ([key, val]) => { if (!Array.isArray(val)) { val = [val] } if (some(val, v => v === undefined)) { val = compact(val) } return [key, val] }) query = filter(query, ([_, val]) => val.length) query = fromPairs(query) log('query object', query) return db .store('courses') .query(query) .catch( err => new Error( `course query failed on "${queryString}" with error "${err}"`, ), ) }
JavaScript
0.000004
@@ -1,16 +1,26 @@ +// @flow%0A%0A import %7Bdb%7D from @@ -132,248 +132,85 @@ ort -filter from 'lodash/filter'%0Aimport map from 'lodash/map'%0Aimport some from 'lodash/some'%0Aimport toPairs from 'lodash/toPairs'%0Aimport fromPairs from 'lodash/fromPairs'%0Aimport debug from 'debug'%0Aconst log = debug('web:database')%0A%0Aexport defaul +toPairs from 'lodash/toPairs'%0Aimport fromPairs from 'lodash/fromPairs'%0A%0Aexpor t fu @@ -236,16 +236,18 @@ atabase( +%0A%09 queryStr @@ -249,18 +249,27 @@ ryString -, +: string,%0A%09 baseQuer @@ -269,21 +269,31 @@ aseQuery +: Object = %7B%7D +,%0A ) %7B%0A%09let @@ -386,160 +386,8 @@ %7D)%0A%0A -%09let query = %7B%7D%0A%09if ('year' in queryObject %7C%7C 'semester' in queryObject) %7B%0A%09%09query = queryObject%0A%09%7D else %7B%0A%09%09query = %7B...baseQuery, ...queryObject%7D%0A%09%7D%0A%0A %09// @@ -435,17 +435,29 @@ arrays%0A%09 -q +let filteredQ uery = t @@ -467,35 +467,47 @@ irs( -query)%0A%09query = map(query, +%7B...baseQuery, ...queryObject%7D)%0A%09%09.map( (%5Bke @@ -520,16 +520,17 @@ %5D) =%3E %7B%0A +%09 %09%09if (!A @@ -546,24 +546,25 @@ ray(val)) %7B%0A +%09 %09%09%09val = %5Bva @@ -572,26 +572,27 @@ %5D%0A%09%09 +%09 %7D%0A +%09 %09%09if ( +val. some( -val, v =%3E @@ -615,16 +615,17 @@ )) %7B%0A%09%09%09 +%09 val = co @@ -637,18 +637,20 @@ (val)%0A%09%09 +%09 %7D%0A +%09 %09%09return @@ -665,35 +665,23 @@ al%5D%0A +%09 %09%7D)%0A%09 -query = filter(query, +%09.filter( (%5B_, @@ -702,18 +702,28 @@ length)%0A -%09q +%0A%09let finalQ uery = f @@ -735,38 +735,17 @@ irs( -query)%0A%0A%09log('query object', q +filteredQ uery @@ -787,17 +787,22 @@ %09.query( -q +finalQ uery)%0A%09%09
1f2abd4e448a8c29df583c21ad11f01135ee7fbb
Add support for selecting files and directories of files.
website/app/application/services/select-items-service.js
website/app/application/services/select-items-service.js
(function (module) { module.factory('selectItems', selectItemsService); selectItemsService.$inject = ["$modal"]; function selectItemsService($modal) { return { open: function () { var tabs = { processes: false, files: false, samples: false, reviews: false }; if (arguments.length === 0) { throw "Invalid arguments to service selectItems:open()"; } for (var i = 0; i < arguments.length; i++) { tabs[arguments[i]] = true; } var modal = $modal.open({ size: 'lg', templateUrl: 'application/services/partials/select-items.html', controller: 'SelectItemsServiceModalController', controllerAs: 'ctrl', resolve: { showProcesses: function () { return tabs.processes; }, showFiles: function () { return tabs.files; }, showSamples: function () { return tabs.samples; }, showReviews: function () { return tabs.reviews; } } }); return modal.result; } }; } module.controller('SelectItemsServiceModalController', SelectItemsServiceModalController); SelectItemsServiceModalController.$inject = ['$modalInstance', 'showProcesses', 'showFiles', 'showSamples', 'showReviews', 'Restangular', '$stateParams', 'current']; function SelectItemsServiceModalController($modalInstance, showProcesses, showFiles, showSamples, showReviews, Restangular, $stateParams, current) { var ctrl = this; ctrl.tabs = loadTabs(); ctrl.activeTab = ctrl.tabs[0].name; ctrl.setActive = setActive; ctrl.isActive = isActive; ctrl.ok = ok; ctrl.cancel = cancel; ctrl.processes = []; ctrl.samples = []; ctrl.files = current.project().files; ///////////////////////// function setActive(tab) { ctrl.activeTab = tab; } function isActive(tab) { return ctrl.activeTab === tab; } function ok() { var selectedProcesses = ctrl.processes.filter(function (p) { return p.input || p.output; }); var selectedSamples = ctrl.samples.filter(function (s) { return s.selected; }); $modalInstance.close({ processes: selectedProcesses, samples: selectedSamples }); } function cancel() { $modalInstance.dismiss('cancel'); } function loadTabs() { var tabs = []; if (showProcesses) { tabs.push(newTab('processes', 'fa-code-fork')); Restangular.one('v2').one('projects', $stateParams.id).one('processes').get().then(function (p) { ctrl.processes = p; }); } if (showSamples) { tabs.push(newTab('samples', 'fa-cubes')); Restangular.one('v2').one('projects', $stateParams.id).one('samples').get().then(function (samples) { ctrl.samples = samples; }); } if (showFiles) { tabs.push(newTab('files', 'fa-files-o')); } if (showReviews) { tabs.push(newTab('reviews', 'fa-comment')); } tabs.sort(function compareByName(t1, t2) { if (t1.name < t2.name) { return -1; } if (t1.name > t2.name) { return 1; } return 0; }); return tabs; } function newTab(name, icon) { return { name: name, icon: icon }; } } }(angular.module('materialscommons')));
JavaScript
0
@@ -2861,32 +2861,85 @@ %7D);%0A%0A + var selectedFiles = getSelectedFiles();%0A%0A $mod @@ -3043,31 +3043,870 @@ dSamples -%0A %7D) +,%0A files: selectedFiles%0A %7D);%0A %7D%0A%0A function getSelectedFiles() %7B%0A var files = %5B%5D,%0A treeModel = new TreeModel(),%0A root = treeModel.parse(current.project().files%5B0%5D);%0A // Walk the tree looking for selected files and adding them to the%0A // list of files. Also reset the selected flag so the next time%0A // the popup for files is used it doesn't show previously selected%0A // items.%0A root.walk(%7Bstrategy: 'pre'%7D, function(node) %7B%0A if (node.model.data.selected) %7B%0A node.model.data.selected = false;%0A if (node.model.data._type === 'file') %7B%0A files.push(node.model.data);%0A %7D%0A %7D%0A %7D);%0A return files ;%0A
2caea723c87b1b7726264e7ff03621ad101ec0f9
Add way to quit application via offcanvas menu
main.js
main.js
'use strict'; var app = require('app'); var mainWindow = null; var dribbbleData = null; var menubar = require('menubar') var mb = menubar({ index: 'file://' + __dirname + '/app/index.html', icon: __dirname + '/app/assets/HotshotIcon.png', width: 400, height: 700, 'max-width': 440, 'min-height': 300, 'min-width': 300, preloadWindow: true }); app.on('window-all-closed', function() { app.quit(); }); mb.on('show', function(){ // mb.window.webContents.send('focus'); mb.window.openDevTools(); });
JavaScript
0
@@ -33,16 +33,41 @@ 'app');%0A +var ipc = require('ipc'); %0Avar mai @@ -509,16 +509,18 @@ ocus');%0A +// mb.win @@ -536,17 +536,84 @@ evTools();%0A%7D);%0A%0A +ipc.on('quit-button-clicked', function(event) %7B%0A app.quit();%0A%7D);%0A%0A %0A
c71fdef22de9c53d1271d27fd8691d0dc43c550d
fix suggestion bar issue
client/navbar.js
client/navbar.js
Template.minimal_navbar.helpers({ loggedIn() { return Meteor.user() }, showDesktopMode: window.showDesktopMode, cardListContainerHidden () { if(Session.get('cardListContainerHidden')){ return true; } return false; }, showShowSuggestionsButton (){ return Session.get('curateMode') && this.hasPendingSuggestions(); }, thisDeepstream () { if (FlowRouter.subsReady()) { return Deepstreams.findOne({shortId: Session.get('streamShortId')}); } }, showPreviewEditButton (){ return !this.creationStep || this.creationStep === 'go_on_air'; }, }); Template.minimal_navbar.events({ "click .logout" (e, t) { e.preventDefault(); Meteor.logout(() => { if(window.mainPlayer){ window.resetMainPlayer(); } }); }, 'click .back-button': function(){ if(Session.equals('showSuggestionBrowser', 'suggestions')){ return Session.set('showSuggestionBrowser', null); } if(Session.get('contextMode') == 'curate' ){ return Session.set('contextMode', 'context') } if(Session.get('contextMode') != 'context' ){ return Session.set('contextMode', 'context'); } if(getCurrentContext()){ return clearCurrentContext(); } else if(Session.get('mediaDataType')){ if(Session.get('contextMode') == 'context' ){ Session.set('mediaDataType', null); return Session.set('cardListContainerHidden', true); } if(Session.get('mediaDataType') == 'selectCard'){ Session.set('contextMode', 'curate'); return Session.set('mediaDataType', null); } else { return Session.set('mediaDataType', 'selectCard'); } } else { $('#card-list-container').toggleClass('col-xs-4 col-xs-0'); $('#watch-video-container').toggleClass('col-xs-8 col-xs-12'); return Session.set('cardListContainerHidden', true); } //TO DO, when in search result takes you back from // when on stack click back hides stack. }, 'click .show-cards' () { $('#card-list-container').toggleClass('col-xs-4 col-xs-0'); $('#watch-video-container').toggleClass('col-xs-8 col-xs-12'); return Session.set('cardListContainerHidden', null) }, 'click .show-suggestions'(){ analytics.track('Click show suggestions browser', trackingInfoFromPage()); Session.set('contextMode', 'context'); Session.set('showSuggestionBrowser', 'suggestions'); //Session.set('contextMode', 'suggestions'); Session.set('mediaDataType', null); Session.set('activeContextId', null); }, 'click .preview-deepstream' (e, t){ t.userControlledActiveStreamId.set(null); // so that stream selection doesn't switch // now lets go back to the curate menu Session.set('previousMediaDataType', Session.get('mediaDataType')); Session.set('mediaDataType', null); Session.set('curateMode', false); analytics.track('Curator clicked preview deepstream', trackingInfoFromPage()); }, 'click .return-to-curate' (){ Session.set('curateMode', true); analytics.track('Curator clicked edit deepstream', trackingInfoFromPage()); }, });
JavaScript
0.000001
@@ -2794,24 +2794,72 @@ ataType'));%0A + Session.set('showSuggestionBrowser', null);%0A Session.
a641cf51a7d5fb36ef6ec87220f6005e15c8f27d
Fix padding issue
qml/dublin-bus-api.js
qml/dublin-bus-api.js
var api = (function () { "use strict"; var routeCache = {}; function networkCall(url, callback, errorcallback) { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState === XMLHttpRequest.DONE) { if (request.status === 200) { callback(request.responseText); } else { errorcallback(); } } }; request.open("GET", url, true); request.send(null); } function padNumber(number) { var out, i; out = number.toString(); for (i = 0; i < 5 - out.length; i += 1) { out = "0" + out; } return out; } function checkedBuses(buses) { var i = 0; for (i = 0; i < buses.length; i += 1) { if (buses[i].time < 0) { buses.splice(i, 1); } } if (buses.length > 0) { return true; } return false; } function getStopData(number, callback, errorCallback) { networkCall("http://rtpi.ie/Text/WebDisplay.aspx?stopRef=" + padNumber(number), function (reponse) { var table, i, rows, buses, time, timerow; table = reponse.match(/<table(\s|\S)+\/table>/); if (table && table.length > 1) { rows = table[0].split("</tr>"); buses = []; time = new Date(); for (i = 0; i < rows.length - 1; i += 1) { if (i !== 0) { if (rows[i].split("</td>")[2].match(/\d+:\d+/) === null) { buses.push({ route: rows[i].match(/\d+/)[0], destination: rows[i].split("</td>")[1].replace(/<td[^>]+>/, ""), time: rows[i].split("</td>")[2].match(/\d+/)[0] }); } else { timerow = rows[i].split("</td>")[2].match(/\d+:\d+/)[0].split(":"); buses.push({ route: rows[i].match(/\d+/)[0], destination: rows[i].split("</td>")[1].replace(/<td[^>]+>/, ""), time: (parseInt(timerow[0], 10) * 60 + parseInt(timerow[1], 10)) - (time.getHours() * 60 + time.getMinutes()) }); } } } if (checkedBuses(buses)) { callback(buses); } else { errorCallback(); } } else { errorCallback(); } }, errorCallback); } function grabNumber(href) { var matching = href.match(/\/\d+/)[0]; return parseInt(matching.replace(/\/[0]+/, ""), 10); } function getRouteData(number, callback, errorCallback) { var url = "http://dublinbus-api.heroku.com/stops?routes=" + number; if (routeCache[url] === undefined) { networkCall(url, function(response) { var data = JSON.parse(response).data, i = 0; for (i = 0; i < data.length; i += 1) { data[i].number = grabNumber(data[i].href); } routeCache[url] = data; callback(data); }, errorCallback); } else { callback(routeCache[url]); } } return { getRouteData: getRouteData, getStopData: getStopData }; }());
JavaScript
0.000001
@@ -603,16 +603,32 @@ r out, i +, originalLength ;%0A @@ -650,24 +650,61 @@ toString();%0A + originalLength = out.length;%0A for @@ -720,20 +720,24 @@ %3C 5 - o -ut.l +riginalL ength; i @@ -776,32 +776,58 @@ out;%0A %7D%0A + console.log(out);%0A return o
59f8e23c6789d04d61a54177584f088d68f06f98
Fix countdown
public/js/countdown.js
public/js/countdown.js
var countDown = function(theSelector, time){ var output = ""; var dTime = Date.parse(time); var theDate = Date.parse(new Date()); var difference = dTime - theDate; var milliseconds = difference % 1000; function addZero(number){ if(number <= 9){ number = "0" + number; } return number; } x = difference / 1000; seconds = addZero(parseInt(x % 60)); x /= 60; minutes = addZero(parseInt(x % 60)); x /= 60; hours = addZero(parseInt(x % 24)); x /= 24; days = addZero(parseInt(x)); output += "<span class='days'>" + days + "<small>Días</small></span>"; output += "<span class='hours'>" + hours + "<small>Horas</small></span>"; output += "<span class='minutes'>" + minutes + "<small>Minutos</small></span>"; output += "<span class='seconds'>" + seconds + "<small>Segundos</small></span>"; document.querySelector(theSelector).innerHTML = output; }; var Time = "7/11/2016 18:25:00"; setInterval(function(){ countDown(".jcountTimer", Time); }, 1000);
JavaScript
0.999529
@@ -912,12 +912,12 @@ = %22 -7/11 +6/15 /201
52b9e9552b3d0a13fb769c163707dad945705754
fix so tiles show in order
public/js/dashboard.js
public/js/dashboard.js
$(document).ready(function() { //alert(value.id); var dashboard = $('#dashboard'); var devices = []; $.getJSON('/api/dashboard/' + dashboard[0].dataset.id + '/devices', function(data, status) { devices = data.sort(function(a, b) { var sortStatus = 0; if (parseInt(a.order) < parseInt(b.order)) { sortStatus = -1; } else if (parseInt(a.order) > parseInt(b.order)) { sortStatus = 1; } return sortStatus; }); dashboard.html(""); $('#dashboard').css('background-image', 'url(https://lh4.googleusercontent.com/-N0Ic1VbN2UE/Ui_eJHugZ2I/AAAAAAAAFzg/P9N-QNQisVI/s1280-w1280-c-h720/farm_in_the_prairie.jpg)'); devices.forEach(dev => { $.get('/device/' + dashboard[0].dataset.id + '/' + dev.id, function(data, status) { if (status == "success") { $(dashboard).append(data); showTiles(); } }); }); }); }); $(document.body).on('click', '.tile', function(e) { var id = this.id; console.log(id) console.log("target is: " + e.target.className); var action = $(this).find('.' + e.target.className); var actioncmd = action[0].dataset.action; var actiontoggle = action[0].dataset.command; var actionval = action.val(); switch (actioncmd) { case "switch": //switch is clicked var currentVal = $(action).prop("checked"); var cmd = "toggle"; if (currentVal) { cmd = "on"; } if (!currentVal) { cmd = "off"; } console.log("cmd to send : " + cmd); $.getJSON('/api/devices/' + id + "/" + cmd, function(data, status) { var x = status; }); break; case "setLevel": //setLevel cmd is changed console.log("setLevel to : " + actionval); $.getJSON('/api/devices/' + id + "/" + actioncmd + "/" + actionval, function(data, status) { var x = status; }); break; //TODO: Insert other commands here, remember to set data-action="cmd name" in the object that holds the value and triggers the command. default: console.log("no matching data-action found, is it set in the template?"); break; } }); var showTiles = function() { var tiles = $(".tile, .tile-small, .tile-sqaure, .tile-wide, .tile-large, .tile-big, .tile-super"); $.each(tiles, function() { var tile = $(this); setTimeout(function() { tile.css({ opacity: .85, "-webkit-transform": "scale(1)", "transform": "scale(1)", "-webkit-transition": ".3s", "transition": ".3s" }); }, Math.floor(Math.random() * 500)); }); };
JavaScript
0
@@ -1,16 +1,51 @@ +var tiles = %5B%5D;%0Avar devices = %5B%5D;%0A%0A $(document).read @@ -124,30 +124,8 @@ ');%0A - var devices = %5B%5D;%0A @@ -745,24 +745,43 @@ rie.jpg)');%0A + var i = 1;%0A devi @@ -964,32 +964,55 @@ -$(dashboard).append( +tiles.push(%7B %22order%22: dev.order, %22html%22: data + %7D );%0A @@ -1030,17 +1030,24 @@ -s +finallyS howTiles @@ -1047,17 +1047,43 @@ owTiles( -) +i);%0A i++ ;%0A @@ -3049,8 +3049,363 @@ %7D);%0A%7D; +%0A%0Afunction sortByOrder(x, y) %7B%0A return ((x.order == y.order) ? 0 : ((x.order %3E y.order) ? 1 : -1));%0A%7D%0A%0Avar finallyShowTiles = function(index) %7B%0A if (index %3E= devices.length) %7B%0A var sortedTiles = tiles.sort(sortByOrder);%0A sortedTiles.forEach(tile =%3E %7B%0A $(dashboard).append(tile.html);%0A %7D);%0A showTiles();%0A %7D%0A%7D
4efbc8526fd1ffd8c8120cdbe25089832fcecdbb
fix conflict loginPage.js
public/js/loginPage.js
public/js/loginPage.js
'use strict'; $(document).ready(function() { // LOGIN: sumbit button pressed var textfield = $("input[name=user]"); $('button[type="submit"]').click(function(e) { e.preventDefault(); //little validation just to check username if (textfield.val() != "") { //$("#output").addClass("alert alert-success animated fadeInUp").html("Welcome back " + textfield.val()); $("#output").removeClass(' alert-danger').hide(); /*$("input").css({ "height":"0", "padding":"0", "margin":"0", "opacity":"0" });*/ //change button text $('button[type="submit"]') .addClass("alert alert-success animated fadeInUp").html("Welcome back " + toTitleCase(textfield.val()) + " !") .removeClass("btn-info"); //show avatar $(".avatar").css({ "background-image": "url('http://lorempixel.com/200/200/people')" }); redirect(); /*$('.avatar').load(function() { window.location.href = "/index"; });*/ } else { //remove success mesage replaced with error message $("#output").removeClass(' alert alert-success'); $("#output").addClass("alert alert-danger animated fadeInUp").html("Please enter a username "); } }); }); // function that capitalize the first letter for each word. e.q. victor lin => Victor Lin function toTitleCase(str) { return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); } function redirect() { setTimeout(function(){ window.location="/index"; } , 3000); }
JavaScript
0.000009
@@ -1747,13 +1747,12 @@ , 3000);%0A%7D%0A -%0A
f529257fcf9b29e47346c5399d01b090126f9a4f
solve error
public/js/stargraph.js
public/js/stargraph.js
function callback(response) { var date = new Date(); $("#loader").hide(); var chart = new CanvasJS.Chart("chartContainer", { zoomEnabled: true, title:{ text: "Repo with " + response.data.length + " stars created at " + response.created_at }, data: [ { type: "area", xValueType: "dateTime", dataPoints: response.data } ] }); chart.render(); } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length,c.length); } return ""; } $(document).ready(function() { $("#loader").hide(); var token = getCookie("token"); if (token !== "") { $(".token").hide(); } callback({data:[], created_at: new Date().toISOString()}); $("#form").submit(function(e) { e.preventDefault(); var repo = $("#repo").val(); if (token === "") { token = $("#token").val(); } //console.log(repo, token); $("#loader").show(); $.get("/api?repo=" + repo + "&token=" + token, function(data){ //console.log(data); var obj = JSON.parse(data); //console.log(obj); callback(obj); if (obj.length !== 0) { var lastTimestamp = obj.pop().x; $("#legend").html("Last star on the repository put at: " + new Date(lastTimestamp).toDateString()); } }); }); });
JavaScript
0.000378
@@ -793,33 +793,8 @@ ) %7B%0A - $(%22#loader%22).hide();%0A @@ -1412,16 +1412,21 @@ if (obj. +data. length ! @@ -1473,16 +1473,21 @@ p = obj. +data. pop().x; @@ -1629,17 +1629,59 @@ -%7D +$(%22#loader%22).hide();%0A %7D%0A );%0A %7D
21ef032bd4d63499aa24ce974147986d8157096d
Add additional logging
public/scripts/xmpp.js
public/scripts/xmpp.js
$(window.document).ready(function() { var socket = new Primus('//' + window.document.location.host) socket.on('error', function(error) { console.error(error) }) var handleItems = function(error, items) { if (error) return console.error(error) $('ul.posts').empty() var content items.forEach(function(item) { content = '<li>' content += item.entry.atom.content.content content += '<br/>&nbsp;&nbsp;&nbsp;&nbsp;by ' content += item.entry.atom.author.name content += '</li>' $('ul.posts').append(content) }) } var getNodeItems = function() { socket.send( 'xmpp.buddycloud.retrieve', { node: '/user/team@topics.buddycloud.org/posts', rsm: { max: 5 } }, handleItems ) } var discoverBuddycloudServer = function() { socket.send( 'xmpp.buddycloud.discover', { server: 'channels.buddycloud.org' }, function(error, data) { if (error) return console.error(error) console.log('Discovered Buddycloud server at', data) getNodeItems() } ) } var login = function() { socket.send( 'xmpp.login.anonymous', { jid: '@anon.buddycloud.org' } ) socket.on('xmpp.connection', function(data) { console.log('Connected as', data.jid) discoverBuddycloudServer() }) } socket.on('open', function() { console.log('Connected') login() }) socket.on('timeout', function(reason) { console.error('Connection failed: ' + reason) }) socket.on('end', function() { console.log('Socket connection closed') socket = null }) socket.on('xmpp.error', function(error) { console.error('XMPP-FTW error', error) }) socket.on('xmpp.error.client', function(error) { console.error('XMPP-FTW client error', error) }) })
JavaScript
0
@@ -247,24 +247,72 @@ rror(error)%0A + console.log('Node items received', items)%0A $('ul. @@ -676,32 +676,75 @@ = function() %7B%0A + console.log('Retrieving node items')%0A socket.sen
bc83f7216b79458cf26d16623e1d346994bb21ac
Use ramda
imports/ui/components/header/header.js
imports/ui/components/header/header.js
import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import { Router } from 'meteor/iron:router'; import './header.jade'; Template.header.helpers({ isClubAdmin() { if (Meteor.user().profile.clubAdmin) { return true; } else { return false; } } });
JavaScript
0.000017
@@ -90,43 +90,21 @@ ort -%7B Router %7D from 'meteor/iron:router +R from 'ramda ';%0A%0A @@ -177,34 +177,44 @@ %7B%0A%09%09 -if (Meteor.user(). +return R.equals(R.path(%5B' profile -. +', ' club @@ -222,59 +222,34 @@ dmin -) %7B%0A%09%09%09return true;%0A%09%09%7D else %7B%0A%09%09%09return false;%0A%09%09%7D +'%5D, Meteor.user()), true); %0A%09%7D%0A
ca59baba98e7792effd9e898b00c43f7bd6627e9
remove log
frontend/src/components/partners/profile/overview/partnerOverviewSummary.js
frontend/src/components/partners/profile/overview/partnerOverviewSummary.js
import React from 'react'; import R from 'ramda'; import { browserHistory as history } from 'react-router'; import PropTypes from 'prop-types'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; import Grid from 'material-ui/Grid'; import HeaderList from '../../../common/list/headerList'; import PaddedContent from '../../../common/paddedContent'; import ItemRowCell from '../../../common/cell/itemRowCell'; import ItemRowCellDivider from '../../../common/cell/itemRowCellDivider'; import SpreadContent from '../../../common/spreadContent'; import { formatDateForPrint } from '../../../../helpers/dates'; const labels = { profileSummary: 'Profile summary', updated: 'Last updated: ', partnerName: 'Partner name', partnerId: 'Partner ID', type: 'Type of organization', orgHq: 'Organization\'s HQ', orgHqLocation: ' Location of Organization\'s HQ', country: 'Country', location: 'Location of office', headOfOrganization: 'Head of organization', fullname: 'Full Name', jobTitle: 'Job Title/Position', telephone: 'Telephone', mobile: 'Mobile', fax: 'Fax', email: 'Email', contact: 'Contact Info', sectors: 'Sector and areas of specialization', year: 'Year of registration', populations: 'Populations of concern', experience: 'Years of establishment in country of origin', unExperience: 'UN Experience', budget: 'Annual Budget (current year)', results: 'Key results', mandate: 'Mandate and Mission', viewProfile: 'view profile', }; const fields = (partner, button) => ( <PaddedContent> <ItemRowCellDivider label={labels.partnerName} content={R.prop('name', partner)} /> <ItemRowCellDivider label={labels.partnerId} content={`${R.prop('partnerId', partner)}`} /> <ItemRowCellDivider label={labels.type} content={R.prop('organisationType', partner)} /> {R.prop('hq', partner) && <ItemRowCellDivider label={labels.orgHq} content={R.path(['hq', 'legal_name'], partner)} />} {R.prop('hq', partner) && <ItemRowCellDivider label={labels.orgHqLocation} content={R.path(['hq', 'country_display'], partner)} />} <ItemRowCellDivider label={labels.country} content={R.prop('operationCountry', partner)} /> <ItemRowCellDivider label={labels.location} content={R.prop('location', partner)} /> <ItemRowCellDivider divider label={labels.headOfOrganization} /> <ItemRowCellDivider divider labelSecondary label={labels.fullname} content={R.path(['head', 'fullname'], partner)} /> <ItemRowCellDivider divider labelSecondary label={labels.jobTitle} content={R.path(['head', 'title'], partner)} /> <ItemRowCellDivider divider labelSecondary label={labels.telephone} content={R.path(['head', 'telephone'], partner)} /> <ItemRowCellDivider divider labelSecondary label={labels.mobile} content={R.path(['head', 'mobile'], partner)} /> <ItemRowCellDivider divider labelSecondary label={labels.fax} content={R.path(['head', 'fax'], partner)} /> <ItemRowCellDivider labelSecondary label={labels.email} content={R.path(['head', 'email'], partner)} /> <ItemRowCellDivider label={labels.contact} content={R.prop('contact', partner)} /> <ItemRowCellDivider label={labels.sectors} content={R.prop('sectors', partner)} /> <ItemRowCellDivider label={labels.populations} content={R.prop('population', partner)} /> <ItemRowCellDivider label={labels.year} content={R.prop('yearOfEstablishment', partner)} /> <ItemRowCellDivider label={labels.unExperience} content={R.prop('unExperience', partner)} /> <ItemRowCellDivider label={labels.budget} content={R.prop('budget', partner)} /> <ItemRowCellDivider label={labels.results} content={R.prop('keyResults', partner)} /> <ItemRowCellDivider divider label={labels.mandate} content={R.prop('mandateMission', partner)} /> {button && <Grid container justify="flex-end"> <Grid item> <Button onClick={() => history.push(`/partner/${R.prop('partnerId', partner)}/details`)} color="accent" > {labels.viewProfile} </Button> </Grid> </Grid>} </PaddedContent> ); const summaryHeader = lastUpdate => ( <SpreadContent> <Typography type="headline" >{labels.profileSummary}</Typography> {lastUpdate && <ItemRowCell alignRight label={labels.updated} content={formatDateForPrint(lastUpdate)} />} </SpreadContent> ); const PartnerOverviewSummary = (props) => { const { partner, loading, button } = props; console.log(partner); return ( <HeaderList header={summaryHeader(R.prop('lastUpdate', partner))} loading={loading} > {fields(partner, button)} </HeaderList> ); }; PartnerOverviewSummary.propTypes = { partner: PropTypes.object.isRequired, loading: PropTypes.bool, button: PropTypes.bool, }; PartnerOverviewSummary.defaultProps = { partner: {}, }; export default PartnerOverviewSummary;
JavaScript
0.000001
@@ -4465,31 +4465,8 @@ ps;%0A - console.log(partner); %0A r
1ddb5939321dc304e5539dc5074b0a78c0ee6f6f
Remove snapshots notification.
app/assets/javascripts/nilavu/components/vm-management-snapshots.js.es6
app/assets/javascripts/nilavu/components/vm-management-snapshots.js.es6
import NilavuURL from 'nilavu/lib/url'; import { buildCategoryPanel } from 'nilavu/components/edit-category-panel'; import computed from 'ember-addons/ember-computed-decorators'; import { observes } from 'ember-addons/ember-computed-decorators'; export default buildCategoryPanel('snapshots', { showSnapshotSpinnerVisible: false, takeSnapShotSpinner: false, snapshots: [], sortedSnapshots: Ember.computed.sort('snapshots', 'sortDefinition'), sortBy: 'created_at', // default sort by date reverseSort: true, // default sort in descending order sortDefinition: Ember.computed('sortBy', 'reverseSort', function() { let sortOrder = this.get('reverseSort') ? 'desc' : 'asc'; return [`${this.get('sortBy')}:${sortOrder}`]; }), snapshot_title: function() { return I18n.t("vm_management.snapshots.title"); }.property(), snapshot_description: function() { return I18n.t("vm_management.snapshots.description"); }.property(), snapshot_list_title: function() { return I18n.t("vm_management.snapshots.list_title"); }.property(), content_id: function() { return I18n.t("vm_management.snapshots.content_id"); }.property(), content_name: function() { return I18n.t("vm_management.snapshots.content_name"); }.property(), content_created_at: function() { return I18n.t("vm_management.snapshots.content_created_at"); }.property(), emptySnapshots: function() { return I18n.t("vm_management.snapshots.content_empty"); }.property(), showSpinner: function() { return this.get("showSnapshotSpinnerVisible"); }.property("showSnapshotSpinnerVisible"), showTakeSnapshotSpinner: function() { return this.get("takeSnapShotSpinner"); }.property("takeSnapShotSpinner"), @observes('selectedTab') tabChanged() { if (Ember.isEqual(this.get('selectedTab'), "snapshots")) { this.getSnapshots(); }; }, getSnapshots: function() { var self = this; this.set("showSnapshotSpinnerVisible", true); Nilavu.ajax("/t/" + this.get('model').id + "/snapshots", { type: 'GET' }).then(function(result) { self.set("showSnapshotSpinnerVisible", false); if (result.success) { self.set('snapshots', result.message) } else { self.notificationMessages.error(result.message); } }).catch(function(e) { self.set("showSnapshotSpinnerVisible", false); // self.notificationMessages.error(I18n.t("vm_management.snapshots.list_error")); }); }, snapshotListEmpty: function() { if (Em.isEmpty(this.get('snapshots'))) { return true; } else { return false; } }.property("snapshots"), getData(reqAction) { return { id: this.get('model').id, cat_id: this.get('model').asms_id, name: this.get('model').name, req_action: reqAction, cattype: this.get('model').tosca_type.split(".")[1], category: "snapshot" }; }, actions: { takeSnapshot() { var self = this; this.set('takeSnapShotSpinner', true); Nilavu.ajax('/t/' + this.get('model').id + "/snapshot", { data: this.getData("disksaveas"), type: 'POST' }).then(function(result) { self.set('takeSnapShotSpinner', false); if (result.success) { self.notificationMessages.success(I18n.t("vm_management.take_snapshot_success")); } else { self.notificationMessages.error(I18n.t("vm_management.error")); } }).catch(function(e) { self.set('takeSnapShotSpinner', false); self.notificationMessages.error(I18n.t("vm_management.error")); }); }, } });
JavaScript
0
@@ -3729,32 +3729,35 @@ + // self.notificati @@ -3913,32 +3913,35 @@ );%0A + // self.notificati
677e80519d49dd02e5b80af23ee69b87822c2804
Fix layout for url_select
Resources/views/add_process/url_select.js
Resources/views/add_process/url_select.js
Ti.include('/includes/lib/json.i18n.js'); var win = Ti.UI.currentWindow; var Utils = require('/includes/utils'); var view = Ti.UI.createView({ height: Ti.UI.SIZE }); win.add(view); var lbl_url = Ti.UI.createLabel({ left: 20, width: 280, color: 'white', shadowColor: 'darkGray', shadowOffset: { x: 1, y: 1 }, font: { fontSize: 18 } }); if(win.from == 'url') { lbl_url.setText(I('addProcess.urlSelect.urlTitle')); } else if(win.from == 'pseudo') { lbl_url.setText(I('addProcess.urlSelect.pseudoTitle')); } view.add(lbl_url); var txtfield_url = Ti.UI.createTextField({ height: 35, top: 10, left: 20, width: 280, autocorrect: false, keyboardType: Ti.UI.KEYBOARD_URL, returnKeyType: Ti.UI.RETURNKEY_DONE, borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED, autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE, clearButtonMode: Ti.UI.INPUT_BUTTONMODE_ONFOCUS }); if(win.from == 'url') { txtfield_url.setValue('http://'); } else if(win.from == 'pseudo') { txtfield_url.setHintText('Notch'); } view.add(txtfield_url); var b_next = Ti.UI.createButton({ title: I('addProcess.next') }); b_next.addEventListener('click', function(e) { var url = txtfield_url.getValue(); if(url == '' || url == 'http://') { alert(I('addProcess.urlSelect.blankField')); } else { if(win.from == 'url') { if(url.substring(0, 7) != 'http://') { url = 'http://' + url; } } else if(win.from == 'pseudo') { url = 'http://s3.amazonaws.com/MinecraftSkins/' + url + '.png'; } if(url != null && url.split('.').pop().toLowerCase() == 'png') { var win_process = Ti.UI.createWindow({ title: I('addProcess.process.title'), url: 'processing.js', backgroundImage: Utils.getBGImage(), barColor: Utils.getNavColor(), backgroundRepeat: true, skinUrl: url, skinName: win.skinName, skinDesc: win.skinDesc, from: win.from }); if(Utils.isiPad()) { win_process.masterGroup = win.masterGroup; win_process.prevWins = [win.prevWins[0], win]; win.masterGroup.open(win_process); } else { win_process.container = win.container; win.navGroup.open(win_process); } } else { alert(I('addProcess.urlSelect.invalidUrl')); } } }); win.setRightNavButton(b_next); txtfield_url.focus();
JavaScript
0.000001
@@ -157,16 +157,47 @@ .UI.SIZE +,%0A%09top: 50,%0A%09layout: 'vertical' %0A%7D);%0A%0Awi @@ -634,17 +634,17 @@ %0A%09top: 1 -0 +5 ,%0A%09left:
df80667f18f559d046b4e9e821bf793e1378ce4e
call no longer fails when developer tries to link a nonexistent resource
addLink.js
addLink.js
var parseUrlDocs = require('./parseUrlDocs.js'); var cache = {}; module.exports = (server, options) => { var attachHALObj = require('./attachHALObj.js')(options); var findLink = (method, urlWithoutQuery) => { for (var i = 0; i < server.router.routes[method].length; i++) { var route = server.router.routes[method][i]; if (route.path.exec(urlWithoutQuery)) { var halObj = { // caching is done without the url query part, so we don't put the url in the cache // href: options.prefix + url, rel: route.name, method: method }; // if (route.path.restifyParams) { // halObj.templated = true; // } parseUrlDocs({ chain: server.routes[route.name], halObj: halObj, name: route.name }); return halObj; } } } return (halContainer, response) => { // this function is given to the developer return (method, url, customName) => { method = method.toUpperCase(); var urlWithoutQuery = url.indexOf("?") == -1 ? url : url.substring(0, url.indexOf("?")); cache[method] = cache[method] || {}; if (!cache[method][urlWithoutQuery]) { cache[method][urlWithoutQuery] = findLink(method, urlWithoutQuery) } var result = cache[method][urlWithoutQuery]; result.href = options.prefix + url; if (customName) { result.rel = customName; } attachHALObj(result, halContainer); } } }
JavaScript
0
@@ -1225,58 +1225,230 @@ -cache%5Bmethod%5D%5BurlWithoutQuery%5D = findLink( +var cacheEntry = findLink(method, urlWithoutQuery);%0A if (cacheEntry) %7B%0A cache%5Bmethod%5D%5BurlWithoutQuery%5D = cacheEntry;%0A %7D else %7B%0A console.error(%60addLink.js: no match was found for $%7B method -, +%7D $%7B urlW @@ -1458,17 +1458,48 @@ outQuery -) +%7D%60);%0A return;%0A %7D %0A %7D
ecc35fe0b4a721332f3d6ecfbf71e156db0b3ef7
make dedup more reliable
server/activities.js
server/activities.js
generateActivity = function(type, details){ check(type, String); check(details, Object); if(details.fanout){ throw new Meteor.Error('Fanout should not be set'); } var fullDetails = _.extend({}, details, {type: type}); var dedupDetails = { type: type }; _.each(['actor', 'object', 'target'], function(key){ if(details[key]){ dedupDetails[key +'.id'] = details[key].id; } }); switch(type){ case 'Share': // pass through break; case 'Message': // pass through break; default: // don't allow duplicate activities if(details.content){ dedupDetails.content = details.content } if(Activities.find(dedupDetails, {limit: 1}).count()){ return // if this is a duplicate. stop here. } } Activities.insert(fullDetails); }; generateActivityFeedItem = function(userId, activityId, relevancy){ check(userId, String); check(activityId, String); check(relevancy, Date); return ActivityFeedItems.insert({ uId: userId, aId: activityId, r: relevancy }) }; fanToObject = function(activity){ check(activity.object, Object); generateActivityFeedItem(activity.object.id, activity._id, activity.published); }; fanToObjectAuthor = function(activity){ check(activity.object, Object); var populatedObject; switch (activity.object.type){ case 'Story': populatedObject = Stories.findOne(activity.object.id, {fields: {authorId: 1}}); break; default: throw new Meteor.Error('Object not found in database for activity: ' + activity._id); } if(populatedObject){ generateActivityFeedItem(populatedObject.authorId, activity._id, activity.published); // fan to author } }; fanoutActivity = function(activity){ check(activity, Object); check(activity.published, Date); Activities.update(activity._id, {$set: {fanout: 'in_progress'}}); switch(activity.type){ case 'Favorite': fanToObjectAuthor(activity); break; case 'Follow': fanToObject(activity); sendFollowedYouEmail(activity.object.id, activity.actor.id); break; case 'FollowBack': fanToObject(activity); break; case 'Publish': var author = Meteor.users.findOne(activity.actor.id, {fields: {followers: 1}}); // fan to followers if(author.followers && author.followers.length){ _.each(author.followers, function(follower){ generateActivityFeedItem(follower, activity._id, activity.published); }); sendFollowingPublishedEmail(author.followers, activity.object.id); } break; case 'Share': fanToObjectAuthor(activity); break; case 'ViewThreshold': fanToObjectAuthor(activity); break; default: throw new Error('Activity type not matched for activity: ' + activity._id + ' Type: ' + activity.type); } // if get here, nothing has thrown return Activities.update(activity._id, {$set: {fanout: 'done'}}); };
JavaScript
0.000001
@@ -657,16 +657,28 @@ .content +.toString(); %0A %7D
78c79f23576aebf2b0b2c166e2b30b047e660d30
test 4
complete/1-6/common.js
complete/1-6/common.js
$(function() { $(".menu>a").click(function(e) { $(".menu>a.selected").removeClass(); $(".content").load($(this).addClass("selected").attr("href")); e.preventDefault(); }).first().click(); });
JavaScript
0.000002
@@ -9,17 +9,20 @@ ion() %7B%0A -%09 + $(%22.menu @@ -46,18 +46,24 @@ on(e) %7B%0A -%09%09 + $(%22.menu @@ -91,18 +91,24 @@ lass();%0A -%09%09 + $(%22.cont @@ -166,10 +166,16 @@ ));%0A -%09%09 + e.pr @@ -194,9 +194,12 @@ ();%0A -%09 + %7D).f
d55f6f0bb6a79325f91e38159ad233c26e6b5e71
Remove extra spaces from link title before persisting.
server/api-server.js
server/api-server.js
var express = require('express'); var bodyParser = require('body-parser'); var MetaInspector = require('node-metainspector'); var Datastore = require('nedb'); var app = express(); var db = new Datastore({ filename: 'links.db', autoload: true }); // TODO: Improve CSP // http://enable-cors.org/server_expressjs.html app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.use(bodyParser.json()); app.post('/links/', function(req, res) { var client = new MetaInspector(req.body.url, {}); client.on('fetch', function () { var linkData = { id: Date.now(), url: client.url, title: client.title.replace(/\n/g, ' ').trim(), host: client.host, image: client.image }; db.insert(linkData, function (err, newDoc) { res.json(newDoc); }) }); client.on('error', function (err) { res.statusCode = 404; res.json(err); }); client.fetch(); }); app.get('/links/', function (req, res) { // TODO: Sort by created date instead of ID. db.find({}).sort({ id: -1 }).exec(function (err, links) { if (err) { res.statusCode = 404; res.json(err); }; res.json(links); }); }); var server = app.listen(3001, function () { var host = server.address().address; var port = server.address().port; console.log('API server listening at http://%s:%s', host, port); });
JavaScript
0
@@ -241,16 +241,169 @@ ue %7D);%0A%0A +var sanitizeTitle = function (title) %7B%0A // http://stackoverflow.com/a/7764370/349353%0A return title.replace(/%5Cn/g, ' ').replace(/%5Cs+/g,' ').trim();%0A%7D;%0A%0A // TODO: @@ -926,46 +926,34 @@ le: -client.title.replace(/%5Cn/g, ' ').trim( +sanitizeTitle(client.title ),%0A
c126e1a8bdcae2833486da3ef11ba3fc1a64b295
clean up
server/lib/ilsapi.js
server/lib/ilsapi.js
'use strict'; var _ = require('lodash'); var request = require('request'); var util = require('util'); var settings = require('../config/settings'); // https://catalog.library.edu:54620/PATRONAPI/21913000482538 var ILSApi = { _patronApiFieldMap: { 'REC INFO' : 'recordInfo', 'EXP DATE' : 'expirationDate', 'PCODE1' : 'patronCode1', 'PCODE2' : 'patronCode2', 'PCODE3' : 'patronCode3', 'P TYPE' : 'pType', 'TOT CHKOUT' : 'totalCheckouts', 'TOT RENWAL' : 'totalRenewals', 'CUR CHKOUT' : 'currentCheckouts', 'BIRTH DATE' : 'birthday', 'HOME LIBR' : 'homeLibrary', 'PMESSAGE' : 'patronMessage', 'MBLOCK' : 'mblock', 'REC TYPE' : 'recordType', 'RECORD #' : 'recordNumber', 'REC LENG' : 'recordLength', 'CREATED' : 'createdOn', 'UPDATED' : 'updatedOn', 'REVISIONS' : 'revisions', 'AGENCY' : 'agency', 'CL RTRND' : 'claimedReturned', 'MONEY OWED' : 'moneyOwed', 'CUR ITEMA' : 'currentItemA', 'CUR ITEMB' : 'currentItemB', 'CUR ITEMC' : 'currentItemC', 'CUR ITEMD' : 'currentItemD', 'CIRCACTIVE' : 'lastCircActivityOn', 'NOTICE PREF' : 'noticePreference', 'PATRN NAME' : 'patronName', 'ADDRESS' : 'address', 'TELEPHONE' : 'telephone', 'P BARCODE' : 'patronBarcode', 'EMAIL ADDR' : 'emailAddress', 'PIN' : 'pin', 'HOLD' : 'hold', 'FINE' : 'fine', 'LINK REC' : 'linkedRecord' }, getPatron: function getPatron (record, callback) { // See: http://csdirect.iii.com/sierrahelp/Content/sril/sril_patronapi.html var self = this; var results = {}; console.log(record) var requestOptions = { uri: util.format('https://%s:%d/PATRONAPI/%s/dump', settings.ilsOptions.catalog.hostname, settings.ilsOptions.catalog.patronAPISSLPort, record ), // TODO: hack strictSSL: false, rejectAuthorization: false }; request(requestOptions, function (error, response, body) { if (error) { return callback(error, null); } _.each(body.split('\n'), function (line) { var pos = line.indexOf(']='); if (pos !== -1) { var data = line.substring(pos+2,line.length).match(/(.+)(?=<)/); data = data ? data[0].trim() : undefined; pos = line.indexOf('['); var field = line.substring(0,pos).trim(); results[self._patronApiFieldMap[field]] = data; } }); if (_.size(results) > 0) { return callback(null, results); } return callback('patron not found: ' + record, null); }); } }; module.exports = ILSApi;
JavaScript
0.000001
@@ -8,16 +8,136 @@ rict';%0A%0A +%0A/*%0A * This is a temporary mini ILS API layer and will be replaced by the full%0A * modular API layer in the future.%0A */%0A%0A var _ = @@ -216,16 +216,50 @@ 'util'); +%0Avar cheerio = require('cheerio'); %0A%0Avar se @@ -1938,27 +1938,87 @@ %7B%7D;%0A -console.log( + // TODO: hack%0A record = record.length %3C 14 ? %22211680%22 + record : record -) +; %0A @@ -2875,24 +2875,69 @@ lts) %3E 0) %7B%0A + results%5B'emailAddress'%5D = undefined;%0A retu @@ -3002,22 +3002,1079 @@ llback(' -patron +Patron not found: ' + record, null);%0A %7D);%0A%0A %7D,%0A%0A getBib: function getBib (record, callback) %7B%0A var self = this;%0A var results = %7B%7D;%0A%0A // scrape record from webpac%0A var recordURI = util.format('https://%25s/search~S1/,?%25s',%0A settings.ilsOptions.catalog.hostname,%0A record%0A );%0A%0A var requestOptions = %7B%0A uri: recordURI,%0A // TODO: hack%0A strictSSL: false,%0A rejectAuthorization: false%0A %7D;%0A %0A request(requestOptions, function (error, response, body) %7B%0A if (error) %7B%0A return callback(error, null);%0A %7D%0A%0A var $ = cheerio.load(body);%0A%0A results.recordURI = recordURI;%0A results.bibNumber = record;%0A%0A // scrape isbn%0A // TODO: refactor this...%0A results.isbn = $('td.bibInfoLabel:contains(%22ISBN%22)').next('td').text().split(' ')%5B0%5D;%0A console.log('ISBN: ', results.isbn);%0A%0A // scrape title%0A results.title = $(%22td.bibInfoData %3E strong%22).text();%0A if (results.title) %7B%0A return callback(null, results);%0A %7D%0A %0A return callback('Bib record not fou @@ -4100,24 +4100,27 @@ l);%0A %7D);%0A + %0A %7D%0A%0A%7D;%0A%0Amo
9691869457a0a0983d23d682a12ae2105f91b50d
set smtp mailer auth options only if we have a non-null user
server/lib/mailer.js
server/lib/mailer.js
// // Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi> // // 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 fs = require('fs'), path = require('path'), nodemailer = require('nodemailer'), mailgun = require('nodemailer-mailgun-transport'), htmlToText = require('nodemailer-html-to-text').htmlToText, smtpTransport = require('nodemailer-smtp-transport'), handlebars = require('handlebars'), conf = require('../lib/conf'), log = require('../lib/log'); let templateCache = {}; let transporter; let fromAddress; let senderAddress; setupTransporter(); exports.send = function(templateName, data, address, subject) { let templatePath = path.join(__dirname, '..', templateName); let template = templateCache[templatePath]; if (!template) { template = handlebars.compile(fs.readFileSync(templatePath, 'utf8')); templateCache[templatePath] = template; } log.info(`Sending email to: ${address}`); transporter.sendMail({ from: 'MAS admin <' + fromAddress + '>', sender: senderAddress, to: address, subject: subject, html: template(data) }); }; function setupTransporter() { if (conf.get('mailgun:enabled') === true) { let mailgunAuth = { auth: { api_key: conf.get('mailgun:api_key'), // eslint-disable-line camelcase domain: conf.get('mailgun:domain') } }; transporter = nodemailer.createTransport(mailgun(mailgunAuth)); fromAddress = conf.get('mailgun:from'); senderAddress = conf.get('mailgun:sender'); } else if (conf.get('smtp:enabled') === true) { let smtpOptions = { host: conf.get('smtp:server'), port: conf.get('smtp:port'), auth: { user: conf.get('smtp:user'), pass: conf.get('smtp:password') } }; transporter = nodemailer.createTransport(smtpTransport(smtpOptions)); fromAddress = conf.get('site:admin_email'); senderAddress = fromAddress; } else { transporter = nodemailer.createTransport(); fromAddress = conf.get('site:admin_email'); senderAddress = fromAddress; } transporter.use('compile', htmlToText()); }
JavaScript
0
@@ -2331,25 +2331,24 @@ 'smtp:port') -, %0A @@ -2340,33 +2340,108 @@ t')%0A - +%7D;%0A%0A if (conf.get('smtp:user').length !== 0) %7B%0A smtpOptions. auth -: + = %7B%0A @@ -2529,32 +2529,33 @@ ')%0A %7D +; %0A %7D;%0A%0A @@ -2540,33 +2540,32 @@ %7D;%0A %7D -; %0A%0A transp
5522c80cf05d2477b485956df59cfd903326cb25
Fix the context generation for the layout
server/lib/routes.js
server/lib/routes.js
const _ = require('lodash') const router = require('koa-router')() const view = require('./view') const parallelPromise = require('../../common/lib/parallelPromise') const handlebars = require('../../common/lib/handlebars') const config = require('../../common/config') const serverRoutes = require('../routes') const commonRoutes = require('../../common/routes') const fail = require('./fail') const cache = {} module.exports = () => { _.each(commonRoutes, (genParams, route) => { router.get(route, function *(next) { const that = this const params = genParams(this.params) const cacheKey = params[2] || params[1] // Use cached version if it's around if (cache[cacheKey]) { that.body = cache[cacheKey] return } yield parallelPromise([ view.xhr(params[0], true), params[1]() ]) .then(results => { const content = handlebars.compile(results[0][1])(results[1]) that.body = cache[cacheKey] = handlebars.compile(results[0][0], _.extend(config, results[1]))({ content }) }) .catch(err => fail(err)) }) }) _.each(serverRoutes, (action, route) => { router.get(route, function *(next) { const shouldContinue = yield new Promise((res, rej) => { action(this) .then(() => res(false)) .catch((e) => { if (e) fail(e) if (!e) res(true) }) }) if (shouldContinue) yield next }) }) return router }
JavaScript
0.000193
@@ -882,24 +882,71 @@ esults =%3E %7B%0A + // Compile the content of the layout%0A co @@ -1005,16 +1005,48 @@ lts%5B1%5D)%0A + // Compile the layout%0A @@ -1100,64 +1100,178 @@ ile( -results%5B0%5D%5B0%5D, _.extend(config, results%5B1%5D))(%7B content %7D +%0A results%5B0%5D%5B0%5D%0A )(%0A _.chain(config)%0A .assign(results%5B1%5D)%0A .assign(%7B content %7D)%0A .value()%0A )%0A
ef53b9c673c71526affa97dffe1e44a9d9a366a7
Update api.js
server/routes/api.js
server/routes/api.js
var express = require('express'); //var db = require('../db'); var assert = require('assert'); var mongoose = require('mongoose'); var User = require('../schemas/User'); var Challenge = require('../schemas/Challenge'); var router = express.Router(); // get router instance // Connection URL var db_url = 'mongodb://localhost:27017/openchallenge'; mongoose.connect(db_url); router.get('/', function (req, res, next) { res.send("Ciao chicco!"); }); /** * Challenge api * */ router.post('/newChallenge', function (req, res) { var obj = req.body; User.find({'uid':obj.organizer}).exec(function (err, user) { assert.equal(err,null); var chall = new Challenge({ name: obj.name, picture: obj.picture, description: obj.description, rules: obj.rules, image: obj.image, location: { address: obj.location.address, lat: obj.location.lat, long: obj.location.long }, date: obj.date, organizer: user.organizer, participants: [] }); chall.save(function (err) { if (err) { res.send("Error"); } else { res.send("Saved!"); } }) }); }); router.get('/allChallenges', function (req, res, next) { Challenge.find() .populate('organizer') .exec(function (error, chall) { console.log(JSON.stringify(chall, null, "\t")); res.send(chall); }) }); router.get('/addParticipant/:chall_id/:user_id', function (req, res) { var chall_id = req.params.chall_id; var user_id = req.params.user_id; Challenge.findByIdAndUpdate( chall_id, {$addToSet: {"participants": user_id}}, // do not add if already present {safe: true, upsert: true}, function (err) { if (err) { res.send('err'); console.log(err); } else res.send('you participate now!') } ) }); router.get('/removeParticipant/:chall_id/:user_id', function (req, res) { var chall_id = req.params.chall_id; var user_id = req.params.user_id; Challenge.findByIdAndUpdate( chall_id, {$pull: {"participants": user_id}}, {safe: true, upsert: true}, function (err) { if (err) { res.send('err'); console.log(err); } else res.send('removed!'); } ) }); router.get('/getParticipants/:chall_id', function (req, res, next) { Challenge.findById(req.params.chall_id) .populate('participants') .exec( function (err, chall) { res.send(chall.participants); }) }); /** * User api */ router.post('/newUser', function (req, res, next) { var obj = req.body; var user = new User({ username: obj.username, status: obj.status, rate: 0, gold: 0, silver: 0, bronze: 0, uid: obj.uid }); user.save(function (err) { if (err) res.send("Errore"); else res.send("User " + user.username + " created!"); }) }); router.get('/allUsers', function (req, res) { User.find(function (err, users) { assert.equal(err, null); res.send(users); }); }); /*db.connect(db_url, function (err, done) { if (err) { console.log('[API] db.connect(db_url, ...): Unable to connect to MongoDB.'); process.exit(1); } else { /** GET home page. * * router.get('/', function (req, res, next) { res.send("Hello World!"); }); /** * CHALLENGES APIs * router.post('/newChallenge', function (req, res) { var body_obj = req.body; db.get().collection('challenges').insertOne(body_obj, function (err, result) { assert.equal(err, null); db.get().collection('challenges').find().limit(1).toArray(function (err, docs) { assert.equal(null, err); res.send(docs[0]); }); }); }); router.get('/allChallenges', function (req, res) { db.get().collection('challenges').find().toArray(function (err, docs) { assert.equal(err, null); var count = 0; docs.forEach(function (challenge, i, docs) { db.get().collection('users').findOne({'uid': challenge.organizer}, function (er, item) { count++; assert.equal(er, null) challenge.organizer = item; if (count == docs.length){ res.json(docs); res.send(); } }) }) }); }); /** * USERS APIs * router.post('/newUser', function (req, res) { var body_obj = req.body; db.get().collection('users').insertOne(body_obj, function (err, result) { assert.equal(err, null); res.send("Created user:" + body_obj.nickname); }) }); router.get('/allUsers', function (req, res) { db.get().collection('users').find().toArray(function (err, docs) { assert.equal(err, null); res.json(docs); }); }); } });*/ module.exports = router;
JavaScript
0.000001
@@ -1075,18 +1075,11 @@ ser. -organizer, +_id %0A
8f281e69025305256aaaa8e5d6a6e0e10bce66fe
Refactor code to its own method
lib/assets/javascripts/cartodb3/components/modals/add-analysis/body-view.js
lib/assets/javascripts/cartodb3/components/modals/add-analysis/body-view.js
var _ = require('underscore'); var CoreView = require('backbone/core-view'); var createTemplateTabPane = require('../../tab-pane/create-template-tab-pane'); var tabPaneButtonTemplate = require('./tab-pane-button-template.tpl'); var tabPaneTemplate = require('./tab-pane-template.tpl'); /** * View to select widget options to create. */ module.exports = CoreView.extend({ initialize: function (opts) { if (!opts.modalModel) throw new Error('modalModel is required'); if (!opts.analysisOptionsCollection) throw new Error('analysisOptionsCollection is required'); if (!opts.analysisOptions) throw new Error('analysisOptions is required'); if (!opts.analysesTypes) throw new Error('analysesTypes is required'); if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required'); if (!opts.queryGeometryModel) throw new Error('queryGeometryModel is required'); this._analysesTypes = opts.analysesTypes; this._analysisOptions = opts.analysisOptions; this._analysisOptionsCollection = opts.analysisOptionsCollection; this._layerDefinitionModel = opts.layerDefinitionModel; this._modalModel = opts.modalModel; this._queryGeometryModel = opts.queryGeometryModel; var availableTypes = _.unique(_.keys(this._analysisOptions)); this._tabPaneItems = _.reduce(this._analysesTypes, function (memo, d) { if (_.contains(availableTypes, d.type)) { var tabPaneItem = d.createTabPaneItem(this._analysisOptionsCollection, { modalModel: this._modalModel, analysisOptionsCollection: this._analysisOptionsCollection, layerDefinitionModel: this._layerDefinitionModel, queryGeometryModel: this._queryGeometryModel }); memo.push(tabPaneItem); } return memo; }.bind(this), []); }, render: function () { this.clearSubViews(); var options = { tabPaneOptions: { template: tabPaneTemplate, tabPaneItemOptions: { tagName: 'li', className: 'CDB-NavMenu-item' } }, tabPaneTemplateOptions: { tagName: 'button', className: 'CDB-NavMenu-link u-upperCase', template: tabPaneButtonTemplate } }; var view = createTemplateTabPane(this._tabPaneItems, options); this.addView(view); this.$el.append(view.render().el); return this; } });
JavaScript
0.000003
@@ -1214,24 +1214,667 @@ ometryModel; +%0A%0A this._generateTabPaneItems();%0A %7D,%0A%0A render: function () %7B%0A this.clearSubViews();%0A%0A var options = %7B%0A tabPaneOptions: %7B%0A template: tabPaneTemplate,%0A tabPaneItemOptions: %7B%0A tagName: 'li',%0A className: 'CDB-NavMenu-item'%0A %7D%0A %7D,%0A tabPaneTemplateOptions: %7B%0A tagName: 'button',%0A className: 'CDB-NavMenu-link u-upperCase',%0A template: tabPaneButtonTemplate%0A %7D%0A %7D;%0A%0A var view = createTemplateTabPane(this._tabPaneItems, options);%0A this.addView(view);%0A this.$el.append(view.render().el);%0A return this;%0A %7D,%0A%0A _generateTabPaneItems: function () %7B %0A var ava @@ -2460,572 +2460,8 @@ %0A %7D -,%0A%0A render: function () %7B%0A this.clearSubViews();%0A%0A var options = %7B%0A tabPaneOptions: %7B%0A template: tabPaneTemplate,%0A tabPaneItemOptions: %7B%0A tagName: 'li',%0A className: 'CDB-NavMenu-item'%0A %7D%0A %7D,%0A tabPaneTemplateOptions: %7B%0A tagName: 'button',%0A className: 'CDB-NavMenu-link u-upperCase',%0A template: tabPaneButtonTemplate%0A %7D%0A %7D;%0A%0A var view = createTemplateTabPane(this._tabPaneItems, options);%0A this.addView(view);%0A this.$el.append(view.render().el);%0A return this;%0A %7D%0A %0A%7D);
e450b47170ea9bbca9420eb82ee47bbca5bb45ee
Make prettier happier
source/views/help/wifi-tools.js
source/views/help/wifi-tools.js
// @flow import deviceInfo from 'react-native-device-info' import networkInfo from 'react-native-network-info' import {Platform} from 'react-native' import pkg from '../../../package.json' export const getIpAddress = (): Promise<?string> => new Promise(resolve => { try { networkInfo.getIPAddress(resolve) } catch (err) { resolve(null) } }) export const getPosition = (args: any = {}): Promise<Object> => new Promise((resolve, reject) => { if(Platform.OS === 'ios') { navigator.geolocation.getCurrentPosition(resolve, reject, { ...args, enableHighAccuracy: true, maximumAge: 1000 /* ms */, timeout: 15000 /* ms */, }) } else { navigator.geolocation.getCurrentPosition(resolve, reject) } }) export const collectData = async () => ({ id: deviceInfo.getUniqueID(), brand: deviceInfo.getBrand(), model: deviceInfo.getModel(), deviceKind: deviceInfo.getDeviceId(), os: deviceInfo.getSystemName(), osVersion: deviceInfo.getSystemVersion(), appVersion: deviceInfo.getReadableVersion(), jsVersion: pkg.version, ua: deviceInfo.getUserAgent(), ip: await getIpAddress(), dateRecorded: new Date().toJSON(), }) export const reportToServer = (url: string, data: Object) => fetch(url, {method: 'POST', body: JSON.stringify(data)})
JavaScript
0.000123
@@ -455,16 +455,17 @@ %3E %7B%0A%09%09if + (Platfor
79988e736a3392acc99490a3b824feb32387e97b
Combine checks to simplify
source/views/news/fetch-feed.js
source/views/news/fetch-feed.js
// @flow import {fastGetTrimmedText} from '../../lib/html' import qs from 'querystring' import {AllHtmlEntities} from 'html-entities' import {parseString} from 'xml2js' import pify from 'pify' import type { StoryType, FeedResponseType, RssFeedItemType, WpJsonItemType, WpJsonResponseType, } from './types' const parseXml = pify(parseString) const entities = new AllHtmlEntities() const fetchText = url => fetch(url).then(r => r.text()) export async function fetchRssFeed( url: string, query: Object = {}, ): Promise<StoryType[]> { const responseText = await fetchText(`${url}?${qs.stringify(query)}`) const feed: FeedResponseType = await parseXml(responseText) return feed.rss.channel[0].item.map(convertRssItemToStory) } export async function fetchWpJson( url: string, query: Object = {}, ): Promise<StoryType[]> { const feed: WpJsonResponseType = await fetchJson( `${url}?${qs.stringify(query)}`, ) return feed.map(convertWpJsonItemToStory) } export function convertRssItemToStory(item: RssFeedItemType): StoryType { const authors = item['dc:creator'] || ['Unknown Author'] const categories = item.category || [] const link = (item.link || [])[0] || null const title = entities.decode(item.title[0] || '<no title>') const datePublished = (item.pubDate || [])[0] || null let content = (item['content:encoded'] || item.description || [])[0] || '<No content>' let excerpt = (item.description || [])[0] || content.substr(0, 250) excerpt = entities.decode(fastGetTrimmedText(excerpt)) return { authors, categories, content, datePublished, excerpt, featuredImage: null, link, title, } } export function convertWpJsonItemToStory(item: WpJsonItemType): StoryType { let author = item.author if (item._embedded && item._embedded.author) { let authorInfo = item._embedded.author.find(a => a.id === item.author) author = authorInfo ? authorInfo.name : 'Unknown Author' } else { author = 'Unknown Author' } let featuredImage = null if (item._embedded && item._embedded['wp:featuredmedia']) { let featuredMediaInfo = item._embedded['wp:featuredmedia'].find( m => m.id === item.featured_media && m.media_type === 'image', ) if (featuredMediaInfo) { if (featuredMediaInfo.media_details.sizes) { if (featuredMediaInfo.media_details.sizes.medium_large) { featuredImage = featuredMediaInfo.media_details.sizes.medium_large.source_url } else { featuredImage = featuredMediaInfo.source_url } } else { featuredImage = featuredMediaInfo.source_url } } } return { authors: [author], categories: [], content: item.content.rendered, datePublished: item.date_gmt, excerpt: entities.decode(fastGetTrimmedText(item.excerpt.rendered)), featuredImage: featuredImage, link: item.link, title: entities.decode(item.title.rendered), } }
JavaScript
0.000001
@@ -2274,32 +2274,41 @@ fo) %7B%0A if ( +%0A featuredMediaInf @@ -2328,19 +2328,19 @@ ls.sizes -) %7B + && %0A @@ -2336,28 +2336,24 @@ &&%0A -if ( featuredMedi @@ -2390,22 +2390,27 @@ um_large +%0A ) %7B%0A - @@ -2425,18 +2425,16 @@ Image =%0A - @@ -2501,90 +2501,8 @@ url%0A - %7D else %7B%0A featuredImage = featuredMediaInfo.source_url%0A %7D%0A
c8a1317bf56c81ad44d85080476b0d7ec3778c99
make Flow happy
source/views/streaming/radio.js
source/views/streaming/radio.js
// @flow /** * All About Olaf * KSTO page */ import React from 'react' import { StyleSheet, View, ScrollView, Text, Dimensions, Image, } from 'react-native' import * as c from '../components/colors' import Icon from 'react-native-vector-icons/Ionicons' import Video from 'react-native-video' import {Touchable} from '../components/touchable' import {TabBarIcon} from '../components/tabbar-icon' const kstoStream = 'https://cdn.stobcm.com/radio/ksto1.stream/master.m3u8' const image = require('../../../images/streaming/ksto/ksto-logo.png') type Viewport = { width: number, height: number, } type State = { refreshing: boolean, paused: boolean, streamError: ?Object, viewport: Viewport, } export default class KSTOView extends React.PureComponent<void, void, State> { static navigationOptions = { tabBarLabel: 'KSTO', tabBarIcon: TabBarIcon('radio'), } state = { refreshing: false, paused: true, streamError: null, viewport: Dimensions.get('window'), } componentWillMount() { Dimensions.addEventListener('change', this.handleResizeEvent) } componentWillUnmount() { Dimensions.removeEventListener('change', this.handleResizeEvent) } handleResizeEvent = (event: {window: {width: number}}) => { this.setState(() => ({viewport: event.window})) } changeControl = () => { this.setState(state => ({paused: !state.paused})) } // error from react-native-video onError = (e: any) => { this.setState(() => ({streamError: e, paused: true})) console.log(e) } render() { const sideways = this.state.viewport.width > this.state.viewport.height const logoWidth = Math.min( this.state.viewport.width / 1.5, this.state.viewport.height / 1.75, ) const logoSize = { width: logoWidth, height: logoWidth, } return ( <ScrollView contentContainerStyle={[styles.root, sideways && landscape.root]} > <View style={[styles.logoWrapper, sideways && landscape.logoWrapper]}> <Image source={image} style={[styles.logo, logoSize]} resizeMode="contain" /> </View> <View style={styles.container}> <Title /> <PlayPauseButton onPress={this.changeControl} paused={this.state.paused} /> {!this.state.paused ? <Video source={{uri: kstoStream}} playInBackground={true} playWhenInactive={true} paused={this.state.paused} onError={this.onError} /> : null} </View> </ScrollView> ) } } const Title = () => { return ( <View style={styles.titleWrapper}> <Text selectable={true} style={styles.heading}> St. Olaf College Radio </Text> <Text selectable={true} style={styles.subHeading}> KSTO 93.1 FM </Text> </View> ) } class PlayPauseButton extends React.PureComponent { props: { paused: boolean, onPress: () => any, } render() { const {paused, onPress} = this.props return ( <Touchable style={buttonStyles.button} hightlight={false} onPress={onPress} > <View style={buttonStyles.buttonWrapper}> <Icon style={buttonStyles.icon} name={paused ? 'ios-play' : 'ios-pause'} /> <Text style={buttonStyles.action}> {paused ? 'Listen' : 'Pause'} </Text> </View> </Touchable> ) } } const styles = StyleSheet.create({ root: { }, container: { alignItems: 'center', }, logoWrapper: { alignItems: 'center', justifyContent: 'center', flex: 1, }, logo: { borderRadius: 6, borderColor: c.kstoSecondaryDark, borderWidth: 3, }, titleWrapper: { alignItems: 'center', marginBottom: 20, }, heading: { color: c.kstoPrimaryDark, fontWeight: '600', fontSize: 28, textAlign: 'center', }, subHeading: { marginTop: 5, color: c.kstoPrimaryDark, fontWeight: '300', fontSize: 28, textAlign: 'center', }, }) const landscape = StyleSheet.create({ root: { flex: 1, padding: 20, flexDirection: 'row', alignItems: 'center', }, logoWrapper: { flex: 0, }, }) const buttonStyles = StyleSheet.create({ button: { alignItems: 'center', paddingVertical: 5, backgroundColor: c.denim, width: 200, borderRadius: 8, overflow: 'hidden', }, buttonWrapper: { flexDirection: 'row', }, icon: { color: c.white, fontSize: 30, }, action: { color: c.white, paddingLeft: 10, paddingTop: 7, fontWeight: '900', }, })
JavaScript
0.000001
@@ -607,16 +607,33 @@ ber,%0A%7D%0A%0A +type Props = %7B%7D%0A%0A type Sta @@ -794,20 +794,21 @@ t%3Cvoid, -void +Props , State%3E
21e390649a0848c2382df093316b6810ced9ccd5
Fix example code
lib/node_modules/@stdlib/math/base/dist/binomial/quantile/examples/index.js
lib/node_modules/@stdlib/math/base/dist/binomial/quantile/examples/index.js
'use strict'; var randu = require( '@stdlib/math/base/random/randu' ); var round = require( '@stdlib/math/base/special/round' ); var quantile = require( './../lib' ); var r; var i; var n; var p; var y; for ( i = 0; i < 10; i++ ) { r = randu(); n = round( randu() * 100 ); p = randu(); y = quantile( r, n, p ); console.log( 'r: %d, n: %d, p: %d, Q(r;n,p): %d', r.toFixed( 4 ), n, p.toFixed( 4 ) ); }
JavaScript
0.998089
@@ -400,15 +400,20 @@ xed( 4 ) +,%0A%09%09y %0A%09);%0A%7D%0A
f5fac1df43fd7f34b04126c1a0ae682b102e606c
Update discover apis in discover script
test-data/discover.js
test-data/discover.js
/** * Run `node import.js` to import the test data into the db. */ var weapons = require('./weapons.json'); var asteroid = require('asteroid'); var fs = require('fs'); var path = require('path'); var db = require('../data-sources/oracle'); var modelsDir = path.join(__dirname, '..', 'models'); // tables we care about // TOOD - remove this once oracle is cleaned out var include = [ 'PRODUCT', 'INVENTORY', 'LOCATION', 'CUSTOMER' ]; // discover tables oracle.discoverModelDefinitions(null, function (err, models) { if(err) { console.log(err); } else { models.forEach(function (def) { if(~include.indexOf(def.name)) { console.log('discovering', def.name); oracle.discoverSchema(null, def.name, function (err, schema) { fs.writeFileSync( path.join(modelsDir, schema.name.toLowerCase() + '.json'), JSON.stringify(schema, null, 2) ); }); var template = [ '/** ', ' * Module Dependencies ', ' */ ', ' ', 'var db = require("../data-sources/db"); ', 'var config = require("./{name}.json"); ', ' ', '/** ', ' * {name} Model ', ' */ ', ' ', 'var {name} = module.exports = db.createModel( ', ' "{name}", ', ' config.properties, ', ' config.options ', '); ']; template = template.join('\n').replace(/\{name\}/g, def.name.toLowerCase()); fs.writeFileSync(path.join(modelsDir, def.name.toLowerCase() + '.js'), template); } }); } });
JavaScript
0
@@ -226,22 +226,18 @@ sources/ -oracle +db ');%0Avar @@ -454,22 +454,18 @@ tables%0A -oracle +db .discove @@ -482,22 +482,16 @@ nitions( -null, function @@ -690,22 +690,18 @@ -oracle +db .discove @@ -708,22 +708,16 @@ rSchema( -null, def.name @@ -2052,25 +2052,16 @@ ase());%0A - %0A
71ccde1b4b76ce799a58b9c6a9ba69c322ac1fef
Update eval.js
commands/eval.js
commands/eval.js
const Discord = require('discord.js'); const config = require("./config.json"); exports.run = async (bot, message) => { var embed = new Discord.RichEmbed() .setTitle("Restricted") .setColor("#f45f42") .addField("You are restricted from this command", "Its for the bot owner only!") const randomColor = "#000000".replace(/0/g, function () { return (~~(Math.random() * 16)).toString(16); }); const clean = text => { if(message.author.id !== config.ownerID) return message.channel.send({ embed: embed }); if (typeof(text) === "string") return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203)); else return text; } const args = message.content.split(" ").slice(1); if (!args) return message.reply("Put what args you want") const code = args.join(" "); try { const evaled = client.clean(await eval(code)); if(msg.flags.includes("d")) msg.delete(); if(msg.flags.includes("s")) return; msg.channel.send(`\`\`\`xl\n${evaled}\n\`\`\`` ); } catch(err) { if(msg.flags[0] && msg.flags[0] === 's') return msg.delete(); msg.channel.send(`\`ERROR\` \`\`\`xl\n${client.clean(err)}\n\`\`\``); } };
JavaScript
0.000001
@@ -893,34 +893,38 @@ de));%0A if(m -sg +essage .flags.includes( @@ -949,26 +949,30 @@ ;%0A if(m -sg +essage .flags.inclu @@ -988,34 +988,38 @@ return;%0A m -sg +essage .channel.send(%60%5C @@ -1084,18 +1084,22 @@ if(m -sg +essage .flags%5B0 @@ -1104,18 +1104,22 @@ %5B0%5D && m -sg +essage .flags%5B0 @@ -1145,18 +1145,22 @@ return m -sg +essage .delete(
421350287d3bb6bda66518547739195dcfb62848
Update info.js
commands/info.js
commands/info.js
/* © Copyright Adam Aharony (a.k.a. Cringy Adam) All rights reserved Twitter: @AdamAharony, Discord: @Cringy Adam#4611 */ exports.run = (client, message, args) => { message.delete(); message.channel.send('', { embed: { author: { name: client.user.username }, color: 0x008AF3, title: "CringyBot Selfbot edition info:", description: 'This selfbot is made by Adam Aharony (a.k.a. Cringy Adam).\n(Twitter: @AdamAharony)\nAiming to make the discord experience much better.\nSpecial thanks to Jayden#5395 for helping me with some commands.', timestamp: new Date(), footer: { text: 'CringyBot Selfbot edition', icon_url: client.user.avatarURL } } }); };
JavaScript
0
@@ -498,32 +498,68 @@ by Adam Aharony +(bot origionally from @XeliteXirish (a.k.a. Cringy A
0e07124e7b314fba5e322643f7852c575b354ebb
stop command: check for bosco-service.json first
commands/stop.js
commands/stop.js
var _ = require('lodash'); var async = require('async'); var NodeRunner = require('../src/RunWrappers/Node'); var DockerRunner = require('../src/RunWrappers/Docker'); var runningServices = []; module.exports = { name: 'stop', description: 'Stops all of the microservices (or subset based on regex pattern)', example: 'bosco stop -r <repoPattern>', cmd: cmd } function cmd(bosco, args, next) { var repoPattern = bosco.options.repo; var repoRegex = new RegExp(repoPattern); var repos = bosco.config.get('github:repos'); var initialiseRunners = function(cb) { var runners = [NodeRunner, DockerRunner]; async.map(runners, function loadRunner(runner, lcb) { runner.init(bosco, lcb); }, cb); } var disconnectRunners = function(next) { var runners = [NodeRunner, DockerRunner]; async.map(runners, function loadRunner(runner, cb) { runner.disconnect(cb); }, next); } var stopRunningServices = function(scb) { async.mapSeries(repos, function(repo, cb) { var pkg, svc, repoPath = bosco.getRepoPath(repo), packageJson = [repoPath, 'package.json'].join('/'), boscoService = [repoPath, 'bosco-service.json'].join('/'); if (repo.match(repoRegex)) { if (bosco.exists(packageJson)) { pkg = require(packageJson); if (pkg.scripts && pkg.scripts.start) { // Assume node if (_.contains(runningServices, repo)) { return NodeRunner.stop({name: repo}, cb); } } } if (bosco.exists(boscoService)) { svc = require(boscoService); if (svc.service) { if (svc.service.type == 'docker') { if (_.contains(runningServices, repo)) { return DockerRunner.stop(svc, cb); } } else { // Assume node if (_.contains(runningServices, repo)) { return NodeRunner.stop({name: repo}, cb); } } } } } cb(); }, function() { scb(); }); } var getRunningServices = function(cb) { NodeRunner.listRunning(false, function(err, nodeRunning) { DockerRunner.list(false, function(err, dockerRunning) { dockerRunning = _.map(_.flatten(dockerRunning), function(item) { return item.replace('/',''); }); runningServices = _.union(nodeRunning, dockerRunning); cb(); }) }) } bosco.log('Stop each microservice ' + args); async.series([initialiseRunners, getRunningServices, stopRunningServices, disconnectRunners], function() { if(next) return next(null, runningServices); }); }
JavaScript
0.000001
@@ -1342,406 +1342,8 @@ %7B%0A%0A - if (bosco.exists(packageJson)) %7B%0A pkg = require(packageJson);%0A if (pkg.scripts && pkg.scripts.start) %7B%0A // Assume node%0A if (_.contains(runningServices, repo)) %7B%0A return NodeRunner.stop(%7Bname: repo%7D, cb);%0A %7D%0A %7D%0A %7D%0A%0A @@ -2010,32 +2010,429 @@ %7D%0A%0A + if (bosco.exists(packageJson)) %7B%0A pkg = require(packageJson);%0A if (pkg.scripts && pkg.scripts.start) %7B%0A // Assume node%0A if (_.contains(runningServices, repo)) %7B%0A return NodeRunner.stop(%7Bname: repo%7D, cb);%0A %7D%0A %7D%0A %7D%0A %7D%0A%0A
208975c2f8eb9c3e5ca5cb9a211bb3458a18ac19
include masked account number for email
give/observers/transactions.js
give/observers/transactions.js
import { api } from "../../core/util/rock" import { makeNewGuid } from "../../core/util/guid" import { TransactionReciepts } from "../collections/transactions" const transactions = () => { if (api._ && api._.baseURL) { TransactionReciepts.find().observe({ added: function (Transaction) { /* 1. Create person if they dont exist 2. Create FinancialPaymentDetail 3. Create Transaction 4. Create TransactionDetails 5a. Create FinancialPersonSavedAccounts 5b. Create location for person? 6. Remove record */ let { FinancialPaymentDetail, meta, TransactionDetails, _id } = { ...Transaction } delete Transaction.meta delete Transaction.FinancialPaymentDetail delete Transaction.TransactionDetails delete Transaction._id let { Person, FinancialPersonSavedAccounts } = meta let { PrimaryAliasId, PersonId } = { ...Person } delete Person.PersonId delete Person.PrimaryAliasId // Create Person Person = { ...Person, ...{ Guid: makeNewGuid(), IsSystem: false, Gender: 0, SystemNote: "Created from NewSpring Apollos" } } const isGuest = PersonId ? false : true if (!PersonId) { PersonId = api.post.sync(`People`, Person) PrimaryAliasId = api.get.sync(`People/${PersonId}`).PrimaryAliasId } // Create FinancialPaymentDetail FinancialPaymentDetail = { ...FinancialPaymentDetail, ...{ Guid: makeNewGuid() } } const FinancialPaymentDetailId = api.post.sync(`FinancialPaymentDetails`, FinancialPaymentDetail) if (FinancialPaymentDetailId.status) { return } // Create Transaction Transaction = { ...Transaction, ...{ Guid: makeNewGuid(), AuthorizedPersonAliasId: PrimaryAliasId, CreatedByPersonAliasId: PrimaryAliasId, ModifiedByPersonAliasId: PrimaryAliasId, SourceTypeValueId: api._.rockId ? api._.rockId : 10, FinancialPaymentDetailId: FinancialPaymentDetailId, TransactionDateTime: new Date() } } const TransactionId = api.post.sync(`FinancialTransactions`, Transaction) if (TransactionId.status) { return } // Create TransactionDetails for (let TransactionDetail of TransactionDetails) { TransactionDetail = { ...{}, ...{ AccountId: TransactionDetail.AccountId, Amount: TransactionDetail.Amount, Guid: makeNewGuid(), TransactionId, CreatedByPersonAliasId: PrimaryAliasId, ModifiedByPersonAliasId: PrimaryAliasId } } api.post.sync(`FinancialTransactionDetails`, TransactionDetail) } if (FinancialPersonSavedAccounts) { // Create FinancialPaymentDetail let SecondFinancialPaymentDetail = { ...FinancialPaymentDetail, ...{ Guid: makeNewGuid() } } let SecondFinancialPaymentDetailId = api.post.sync(`FinancialPaymentDetails`, SecondFinancialPaymentDetail) if (SecondFinancialPaymentDetailId.status) { return } // Create FinancialPersonSavedAccounts FinancialPersonSavedAccounts = { ...FinancialPersonSavedAccounts, ...{ Guid: makeNewGuid(), PersonAliasId: PrimaryAliasId, FinancialPaymentDetailId: SecondFinancialPaymentDetailId, CreatedByPersonAliasId: PrimaryAliasId, ModifiedByPersonAliasId: PrimaryAliasId } } if (FinancialPersonSavedAccounts.ReferenceNumber) { api.post.sync(`FinancialPersonSavedAccounts`, FinancialPersonSavedAccounts) } } if (TransactionId && !TransactionId.statusText ) { // taken from https://github.com/SparkDevNetwork/Rock/blob/cb8cb69aff36cf182b5d35c6e14c8a344b035a90/Rock/Transactions/SendPaymentReciepts.cs // setup merge fields const mergeFields = { Person, } let totalAmount = 0 let accountAmounts = [] for (const detail of TransactionDetails) { if (detail.Amount === 0 || !detail.AccountId) { continue } const accountAmount = { AccountId: detail.AccountId, AccountName: detail.AccountName, Amount: detail.Amount, } accountAmounts.push(accountAmount) totalAmount += detail.Amount } mergeFields["TotalAmount"] = totalAmount mergeFields["GaveAnonymous"] = isGuest mergeFields["ReceiptEmail"] = Person.Email mergeFields["ReceiptEmailed"] = true mergeFields["LastName"] = Person.LastName mergeFields["FirstNames"] = Person.NickName || Person.FirstName mergeFields["TransactionCode"] = Transaction.TransactionCode mergeFields["Amounts"] = accountAmounts // remove record TransactionReciepts.remove(_id, (err) => { if (!err) { Meteor.call( "communication/email/send", 14, // Default giving system email PrimaryAliasId, mergeFields, (err, response) => { // async stub } ) } }) } } }) } } export default transactions
JavaScript
0.000003
@@ -5120,16 +5120,116 @@ tAmounts +%0A mergeFields%5B%22AccountNumberMasked%22%5D = FinancialPaymentDetail.AccountNumberMasked.slice(-4) %0A%0A
b94413399fccead24570d63cbbf77da6a7e54174
Change column width on layoutChange
lib/components/artist/related_artists/index.js
lib/components/artist/related_artists/index.js
/* @flow */ 'use strict'; import Relay from 'react-relay'; import React from 'react'; import { ScrollView, StyleSheet, View, Dimensions } from 'react-native'; import colors from '../../../../data/colors'; import SerifText from '../../text/serif'; import ImageView from '../../opaque_image_view'; import RelatedArtist from './related_artist' class RelatedArtists extends React.Component { render() { const artists = this.props.artists; return ( <View style={styles.container}> <SerifText style={styles.heading}>Related Artists</SerifText> <View style={styles.artistContainer}> { this.renderArtists() } </View> </View> ); } renderArtists() { const artists = this.props.artists; var artistViews = artists.map(artist => <RelatedArtist key={artist.id} artist={artist} />); const isPhone = Dimensions.get('window').width < 700; const isPadHorizontal = Dimensions.get('window').width > 1000; // not being used yet const extraRequiredViews = artists.length % (isPhone ? 2 : 3); for (var i = 0; i < extraRequiredViews; i++) { artistViews.push(<RelatedArtist key={'dummy'+i.toString()} artist={null}/>); } return artistViews; } } const styles = StyleSheet.create({ container: { flexDirection: 'column', }, artistContainer: { flexWrap: 'wrap', flexDirection: 'row', justifyContent: 'space-around', marginTop: 20, marginLeft: -10, marginRight: -10, }, heading: { fontSize: 20, } }); export default Relay.createContainer(RelatedArtists, { fragments: { artists: () => Relay.QL` fragment on Artist @relay(plural: true) { id ${RelatedArtist.getFragment('artist')} } ` } })
JavaScript
0
@@ -384,16 +384,689 @@ onent %7B%0A + constructor(props) %7B%0A super(props);%0A this.state = %7B columns: this.columnCount()%7D;%0A this.onLayout = this.onLayout.bind(this);%0A %7D%0A %0A columnCount() %7B%0A const isPhone = Dimensions.get('window').width %3C 700;%0A const isPadHorizontal = Dimensions.get('window').width %3E 1000;%0A return !isPhone ? isPadHorizontal ? 4 : 3 : 2;%0A %7D%0A %0A onLayout(e) %7B%0A console.log('on layout called');%0A this.setState(%7B%0A columns: this.columnCount()%0A %7D);%0A // TODO ensure that on the initial render, and when it calls this callback, setting the state again should not%0A // actually cause another render, as the number of columns should remain the same.%0A %7D%0A%0A render @@ -1066,24 +1066,24 @@ render() %7B%0A - const ar @@ -1106,24 +1106,29 @@ ps.artists;%0A + %0A return ( @@ -1359,17 +1359,16 @@ );%0A %7D%0A%0A -%0A render @@ -1519,155 +1519,8 @@ %3E);%0A - const isPhone = Dimensions.get('window').width %3C 700;%0A const isPadHorizontal = Dimensions.get('window').width %3E 1000; // not being used yet%0A @@ -1567,25 +1567,26 @@ h %25 -(isPhone ? 2 : 3) +this.state.columns ;%0A @@ -1754,16 +1754,18 @@ ;%0A %7D%0A%7D%0A + %0Aconst s
489ccb24fd3135988ab6be59e44cf7567d888bb6
change migration mode 2
lib/modules/migration/lib/manager.migration.js
lib/modules/migration/lib/manager.migration.js
module.exports = function(self,deps){ var preprocessProperties = self.require('lib/properties'); var getAppScheme = self.require('lib/getAppScheme'); var compareDescriptors = self.require('lib/difference'); var g = require('grunt'); var Sync = require('sql-ddl-sync').Sync; var Q = require('q'); var _ = require('underscore'); var currentState; var appState; var dbg = true; var MState; var flagFirst = true; var diff; var mjcDir; var magic = {id: null, run: null}; return { init : function(mDir, dbPath){ mjcDir = mDir; var prms = self.require('lib/migrationState').init(dbPath).then(function(State){ MState = State; return State.lastState(); }).then(function(last){ if(last.getId()) flagFirst = false; currentState = last; if(currentState.err){ if(dbg) console.log(currentState.err); return Q.reject(new Error("Migration module: Errors in last migration state.")); } if(flagFirst) { if(dbg) console.log("First migration - magic function not need."); return Q(); } if(currentState.isSynced()) magic.id = currentState.getId(); else magic.id = currentState.magicId; var mjcPath = mjcDir+magic.id+".js"; var txt = "module.exports = function(){\n"+ "return function(models) {\n"+ "}\n"+ "};\n"; if (!g.file.exists(mjcPath)){ g.file.write(mjcPath, txt); if(dbg) console.log("Magic file created: "+ mjcPath); } else { if(dbg) console.log("Magic file already exists: " + mjcPath); } magic.run = require(mjcPath); return Q(); }); return prms; }, run: function(id){ var diff; var syncingState; var prms = Q(); prms = prms.then(function(){ if(id) return MState.getState(id); return MState.createState().then(function(stt){ appState = stt; appState.setScheme(getAppScheme()); return Q(appState); }); }).then(function(stateTo){ diff = compareDescriptors(currentState.scheme, stateTo.scheme); m.diff = diff; if(!diff.need){ if(dbg) console.log("Nothing to sync."); return Q.reject("Nothing to sync."); } if(!flagFirst && !magic.run ){ if(dbg) console.log("no magic function"); return Q.reject(new Error("no magic function")); } if(currentState.isSynced()){ return MState.createState().then(function(stt){ syncingState = stt; syncingState.setScheme(currentState.getScheme()); syncingState.downStateId = currentState.getId(); }); } syncingState = currentState; return Q(); }).then(function(){ // ddl sync app models; if(dbg) console.log("ddl sync added app models ... "); if(_.keys(diff.ddlSyncAdd).length == 0 ){ if(dbg) console.log("no models to ddl-sync."); return Q(); } return syncingState.ddlSync(diff.ddlSyncAdd).then(function(){ return deps.config.reloadScope(); }); }).then(function(){ // orm sync app models; if(dbg) console.log("orm sync app models ... "); if(_.keys(diff.modelSync).length == 0 ) { if(dbg) console.log("no models to sync."); return Q(); } function one(name){ var df = Q.defer(); m.app.models[name].sync(function(err){ //TODO if(err) df.reject(err); else { if(dbg) console.log("Model "+name+" synced."); df.resolve(); } }); return df.promise; } var _p = Q(); for (var db in diff.modelSync){ var dscr = diff.modelSync[db]; _.each(dscr, function(dsc, mdl){ _p = _p.then(function(){ return one(mdl); }).then(function(){ var _dsc = {}; _dsc[mdl] = dsc; syncingState.changeDescriptor(db, _dsc); return Q(); }); }); _p = _p.then(function(){ return syncingState.save(); }); } return _p; }).then(function(){ // magic if(flagFirst) return Q(); if(dbg) console.log("Magic ... "); if(magic.run) return magic.run(); else return Q(new Error("No magic function")); }).then(function(){ if(dbg) console.log("ddl sync removed app models ... "); if(_.keys(diff.ddlSyncRm).length == 0){ if(dbg) console.log("no models to remove."); return Q(); } return syncingState.ddlSync(diff.ddlSyncRm); }); return prms; } }; };
JavaScript
0
@@ -1887,53 +1887,8 @@ %7D%0A - magic.run = require(mjcPath);%0A @@ -2680,16 +2680,75 @@ %7D +%0A magic.run = require(mjcDir+magic.id+%22.js%22); %0A
c19c070b5cfffa009e705aa8fd318e4677b870b8
Update comment
lib/node_modules/@stdlib/iter/flow/lib/main.js
lib/node_modules/@stdlib/iter/flow/lib/main.js
/** * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * 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. */ /* eslint-disable no-invalid-this, no-restricted-syntax */ 'use strict'; // MODULES // var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' ); var isObject = require( '@stdlib/assert/is-object' ); var isFunction = require( '@stdlib/assert/is-function' ); var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); var objectKeys = require( '@stdlib/utils/keys' ); var iteratorSymbol = require( '@stdlib/symbol/iterator' ); // MAIN // /** * Returns a constructor for creating a fluent interface for chaining together iterator methods. * * @param {Object} methods - an object mapping method names to iterator functions * @throws {TypeError} must provide an object * @throws {TypeError} object property values must be functions * @returns {Function} constructor * * @example * var array2iterator = require( '@stdlib/array/to-iterator' ); * var iterHead = require( '@stdlib/iter/head' ); * var iterSome = require( '@stdlib/iter/some' ); * * // Create a "fluent" interface: * var FluentIterator = iterFlow({ * 'head': iterHead, * 'some': iterSome * }); * * // Create a source iterator: * var arr = array2iterator( [ 0, 0, 1, 1, 1, 0, 0, 1, 0, 1 ] ); * * // Create a new iterator: * var it = new FluentIterator( arr ); * * var bool = it.head( 5 ).some( 3 ); * // returns true * * // Create another source iterator: * arr = array2iterator( [ 0, 0, 1, 0, 1, 0, 0, 1, 0, 1 ] ); * * // Create a new iterator: * it = new FluentIterator( arr ); * * bool = it.head( 5 ).some( 3 ); * // returns false */ function iterFlow( methods ) { var keys; var k; var f; var i; if ( !isObject( methods ) ) { throw new TypeError( 'invalid argument. Must provide an object. Value: `' + methods + '`.' ); } /** * Fluent interface constructor. * * @private * @constructor * @param {Iterator} iterator - source iterator * @throws {TypeError} must provide an iterator * @returns {FluentIterator} a "fluent" iterator */ function FluentIterator( iterator ) { if ( !( this instanceof FluentIterator ) ) { return new FluentIterator( iterator ); } if ( !isIteratorLike( iterator ) ) { throw new TypeError( 'invalid argument. Must provide an iterator. Value: `' + iterator + '`.' ); } setNonEnumerableReadOnly( this, '_source', iterator ); setNonEnumerable( this, '_done', false ); return this; } /** * Returns an iterator protocol-compliant object containing the next iterated value. * * @private * @throws {TypeError} `this` must be a fluent interface iterator * @returns {Object} iterator protocol-compliant object */ setNonEnumerableReadOnly( FluentIterator.prototype, 'next', function next() { if ( !(this instanceof FluentIterator) ) { throw new TypeError( 'invalid invocation. `this` is not a fluent interface iterator.' ); } if ( this._done ) { return { 'done': true }; } return this._source.next(); }); /** * Finishes an iterator. * * @private * @param {*} [value] - value to return * @throws {TypeError} `this` must be a fluent interface iterator * @returns {Object} iterator protocol-compliant object */ setNonEnumerableReadOnly( FluentIterator.prototype, 'return', function finish( value ) { if ( !(this instanceof FluentIterator) ) { throw new TypeError( 'invalid invocation. `this` is not a fluent interface iterator.' ); } this._done = true; if ( arguments.length ) { return { 'value': value, 'done': true }; } return { 'done': true }; }); // If an environment supports `Symbol.iterator`, make the iterator iterable: if ( iteratorSymbol ) { /** * Returns the current iterator. * * ## Notes * * - This method allows the iterator to be iterable and thus able to be consumed, e.g., in `for..of` loops. * * @private * @returns {Iterator} iterator */ setNonEnumerableReadOnly( FluentIterator.prototype, iteratorSymbol, function factory() { // eslint-disable-line max-len return this; }); } /** * Wraps an iterator function as a fluent interface method. * * ## Notes * * - We assume that the provided iterator function has the following function signature: * * ```text * function iterFcn( iterator[, ...args] ) {...} * ``` * * where `iterator` is an input iterator and `args` are additional iterator function arguments (if any). * * @private * @param {Function} iterFcn - iterator function * @returns {Function} method wrapper */ function createMethod( iterFcn ) { return method; /** * Iterator function wrapper. * * @private * @param {...*} [args] - method arguments * @throws {TypeError} `this` must be a fluent interface iterator * @returns {Iterator} iterator */ function method() { var args; var out; var i; if ( !(this instanceof FluentIterator) ) { throw new TypeError( 'invalid invocation. `this` is not a fluent interface iterator.' ); } args = [ this._source ]; for ( i = 0; i < arguments.length; i++ ) { args.push( arguments[ i ] ); } out = iterFcn.apply( null, args ); // If the iterator function returns an iterator, in order to support subsequent chaining, we need to create a new fluent interface instance... if ( isIteratorLike( out ) ) { return new FluentIterator( out ); } return out; } } // Bind the provided iterator functions to the `Iterator` prototype... keys = objectKeys( methods ); for ( i = 0; i < keys.length; i++ ) { k = keys[ i ]; f = methods[ k ]; if ( !isFunction( f ) ) { throw new TypeError( 'invalid argument. Object property values must be functions. Key: `' + k + '`. Value: `' + f + '`.' ); } setNonEnumerableReadOnly( FluentIterator.prototype, k, createMethod( f ) ); // eslint-disable-line max-len } return FluentIterator; } // EXPORTS // module.exports = iterFlow;
JavaScript
0
@@ -6052,18 +6052,19 @@ the -%60Itera +construc tor -%60 pro
e138b2827f184a16722a3f1ae9cbae27f78f3c48
use default table based on database
lib/sails-migrations/helpers/database_tasks.js
lib/sails-migrations/helpers/database_tasks.js
const exec = require('child_process').exec; const _ = require('lodash'); const errors = require('../errors'); const PG_CLIENT_NAME = 'pg'; const MYSQL_CLIENT_NAME = 'mysql'; function DatabaseTasks() {} DatabaseTasks.executeQuery = function (config, query, cb) { //config.debug = true; database = config.connection.database config.connection.database = undefined; //bug in knex, if you pass a db, it will fail to drop/create a db :-( var knex = require('knex')(config); knex.raw(query).then(cb, cb) }; /* * config - * client: 'mysql' or 'postgresql' * database: the database name * user: db user * password: db connection password * host: db host * */ DatabaseTasks.create = function (config, cb) { var database = config.connection.database; DatabaseTasks.executeQuery(config, "CREATE DATABASE \"" + database + "\"", function (err, stdout, stdin) { config.connection.database = database; if (err instanceof Error){ cb(err, config); } else { cb(null, config); } }); }; /* * config - * client: 'mysql' or 'postgresql' * database: the database name * user: db user * password: db connection password * host: db host * */ DatabaseTasks.drop = function (config, cb) { var database = config.connection.database; DatabaseTasks.executeQuery(config, "DROP DATABASE \"" + database + "\"", function (err, stdout, stdin) { config.connection.database = database; if (err instanceof Error){ cb(err, config); } else { cb(null, config); } }); }; module.exports = DatabaseTasks;
JavaScript
0
@@ -169,16 +169,91 @@ ysql';%0A%0A +const clientToDefaultDbTable = %7B%0A 'pg': 'postgres',%0A 'mysql': 'mysql'%0A%7D%0A%0A function @@ -434,17 +434,45 @@ e = -undefined +clientToDefaultDbTable%5Bconfig.client%5D ; //
577edcb75d9e8ca964c05c1276f9ddb037de2a00
FIX the page story for desktop & mobile
lib/ui/src/components/layout/layout.stories.js
lib/ui/src/components/layout/layout.stories.js
import { setInterval, window } from 'global'; import React, { Component, Fragment } from 'react'; import PropTypes from 'prop-types'; import { storiesOf } from '@storybook/react'; import { withKnobs, boolean, number } from '@storybook/addon-knobs'; import { styled } from '@storybook/theming'; import { Desktop } from './desktop'; import { Mobile } from './mobile'; import Sidebar from '../sidebar/Sidebar'; import Panel from '../panel/panel'; import { Preview } from '../preview/preview'; import { panels } from '../panel/panel.stories'; import { previewProps } from '../preview/preview.stories'; import { mockDataset } from '../sidebar/treeview/treeview.mockdata'; const realNavProps = { title: 'Title', url: 'https://example.com', stories: mockDataset.withRoot, menu: [], }; const PlaceholderBlock = styled.div(({ color }) => ({ background: color || 'hotpink', position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', overflow: 'hidden', })); class PlaceholderClock extends Component { state = { count: 1, }; componentDidMount() { this.interval = setInterval(() => { const { count } = this.state; this.setState({ count: count + 1 }); }, 1000); } componentWillUnmount() { const { interval } = this; clearInterval(interval); } render() { const { children, color } = this.props; const { count } = this.state; return ( <PlaceholderBlock color={color}> <h2 style={{ position: 'absolute', bottom: 0, right: 0, color: 'rgba(0,0,0,0.2)', fontSize: '150px', lineHeight: '150px', margin: '-20px', }} > {count} </h2> {children} </PlaceholderBlock> ); } } PlaceholderClock.propTypes = { children: PropTypes.node.isRequired, color: PropTypes.string.isRequired, }; const MockNav = props => ( <PlaceholderClock color="hotpink"> <pre>{JSON.stringify(props, null, 2)}</pre> </PlaceholderClock> ); const MockPreview = props => ( <PlaceholderClock color="deepskyblue"> <pre>{JSON.stringify(props, null, 2)}</pre> </PlaceholderClock> ); const MockPanel = props => ( <PlaceholderClock color="orangered"> <pre>{JSON.stringify(props, null, 2)}</pre> </PlaceholderClock> ); const MockPage = props => ( <PlaceholderClock color="cyan"> <pre>{JSON.stringify(props, null, 2)}</pre> </PlaceholderClock> ); const mockProps = { Nav: MockNav, Preview: MockPreview, Panel: MockPanel, Notifications: () => null, pages: [], options: { isFullscreen: false, showNav: true, showPanel: true, panelPosition: 'right' }, path: '/story/UI-DesktopLayout-noNav', viewMode: 'story', storyId: 'UI-DesktopLayout-noNav', }; const realProps = { Nav: () => <Sidebar {...realNavProps} />, Preview: () => <Preview {...previewProps} />, Notifications: () => null, Panel: () => ( <Panel panels={panels} actions={{ onSelect: () => {}, toggleVisibility: () => {}, togglePosition: () => {} }} selectedPanel="test2" /> ), pages: [], options: { isFullscreen: false, showNav: true, showPanel: true, panelPosition: 'right' }, path: '/story/UI-DesktopLayout-noNav', viewMode: 'story', storyId: 'UI-DesktopLayout-noNav', }; storiesOf('UI|Layout/Desktop', module) .addDecorator(withKnobs) .addDecorator(storyFn => { const mocked = boolean('mock', true); const height = number('height', window.innerHeight); const width = number('width', window.innerWidth); const props = { height, width, ...(mocked ? mockProps : realProps), }; return <div style={{ minHeight: 600, minWidth: 600 }}>{storyFn({ props })}</div>; }) .add('default', ({ props }) => <Desktop {...props} />) .add('no Nav', ({ props }) => ( <Desktop {...props} options={{ ...props.options, showNav: false }} /> )) .add('no Panel', ({ props }) => ( <Desktop {...props} options={{ ...props.options, showPanel: false }} /> )) .add('bottom Panel', ({ props }) => ( <Desktop {...props} options={{ ...props.options, panelPosition: 'bottom' }} /> )) .add('full', ({ props }) => ( <Desktop {...props} options={{ ...props.options, isFullscreen: true }} /> )) .add('no Panel, no Nav', ({ props }) => ( <Desktop {...props} options={{ ...props.options, showPanel: false, showNav: false }} /> )) .add('page', ({ props }) => ( <Desktop {...props} pages={[ { key: 'settings', // eslint-disable-next-line react/prop-types route: ({ children }) => <Fragment>{children}</Fragment>, render: () => <MockPage />, }, ]} viewMode={undefined} /> )); storiesOf('UI|Layout/Mobile', module) .addDecorator(withKnobs) .addDecorator(storyFn => { const mocked = boolean('mock', true); const props = { ...(mocked ? mockProps : realProps), }; return storyFn({ props }); }) .add('initial 0', ({ props }) => <Mobile {...props} options={{ initialActive: 0 }} />) .add('initial 1', ({ props }) => <Mobile {...props} options={{ initialActive: 1 }} />) .add('initial 2', ({ props }) => <Mobile {...props} options={{ initialActive: 2 }} />) .add('page', ({ props }) => ( <Mobile {...props} options={{ initialActive: 1 }} pages={[ { key: 'settings', // eslint-disable-next-line react/prop-types route: ({ children }) => <Fragment>{children}</Fragment>, render: () => <MockPage />, }, ]} viewMode={undefined} /> ));
JavaScript
0.000007
@@ -4839,35 +4839,34 @@ viewMode= -%7Bundefined%7D +%22settings%22 %0A /%3E%0A )) @@ -5729,19 +5729,18 @@ ode= -%7Bundefined%7D +%22settings%22 %0A
f5f0be534aafd4a2bf1acd9b9154537343fff66e
remove problematic plugins from karma's webpack config
config/karma.config.js
config/karma.config.js
var path = require('path'); var webpackConfig = require('./webpack.config.js'); var ROOT_PATH = path.resolve(__dirname, '..'); // add coverage instrumentation to babel config if (webpackConfig && webpackConfig.module && webpackConfig.module.rules) { var babelConfig = webpackConfig.module.rules.find(function (rule) { return rule.loader === 'babel-loader'; }); babelConfig.options = babelConfig.options || {}; babelConfig.options.plugins = babelConfig.options.plugins || []; babelConfig.options.plugins.push('istanbul'); } // Karma configuration module.exports = function(config) { var progressReporter = process.env.CI ? 'mocha' : 'progress'; config.set({ basePath: ROOT_PATH, browsers: ['PhantomJS'], frameworks: ['jasmine'], files: [ { pattern: 'spec/javascripts/test_bundle.js', watched: false }, { pattern: 'spec/javascripts/fixtures/**/*@(.json|.html|.html.raw)', included: false }, ], preprocessors: { 'spec/javascripts/**/*.js?(.es6)': ['webpack', 'sourcemap'], }, reporters: [progressReporter, 'coverage-istanbul'], coverageIstanbulReporter: { reports: ['html', 'text-summary'], dir: 'coverage-javascript/', subdir: '.', fixWebpackSourcePaths: true }, webpack: webpackConfig, webpackMiddleware: { stats: 'errors-only' }, }); };
JavaScript
0
@@ -17,24 +17,58 @@ re('path');%0A +var webpack = require('webpack');%0A var webpackC @@ -103,24 +103,24 @@ onfig.js');%0A - var ROOT_PAT @@ -220,33 +220,16 @@ ckConfig - && webpackConfig .module @@ -499,16 +499,16 @@ %7C%7C %5B%5D;%0A - babelC @@ -550,16 +550,288 @@ l');%0A%7D%0A%0A +// remove problematic plugins%0Aif (webpackConfig.plugins) %7B%0A webpackConfig.plugins = webpackConfig.plugins.filter(function (plugin) %7B%0A return !(%0A plugin instanceof webpack.optimize.CommonsChunkPlugin %7C%7C%0A plugin instanceof webpack.DefinePlugin%0A );%0A %7D);%0A%7D%0A%0A // Karma
99e343de4d6a11ece95be8a9bbd5796796a896d9
change order of inheritance and use return
mail_tracking/static/src/js/discuss/discuss.js
mail_tracking/static/src/js/discuss/discuss.js
odoo.define("mail_tracking/static/src/js/discuss/discuss.js", function (require) { "use strict"; const {attr} = require("mail/static/src/model/model_field.js"); const { registerInstancePatchModel, registerFieldPatchModel, registerClassPatchModel, } = require("mail/static/src/model/model_core.js"); const {one2one, many2one} = require("mail/static/src/model/model_field.js"); registerInstancePatchModel( "mail.messaging_initializer", "mail/static/src/models/messaging_initializer/messaging_initializer.js", { async start() { this._super(...arguments); this.messaging.update({ failedmsg: [ [ "create", { id: "failedmsg", isServerPinned: true, model: "mail.box", name: this.env._t("Failed"), }, ], ], }); }, async _init({ channel_slots, commands = [], current_partner, current_user_id, mail_failures = {}, mention_partner_suggestions = [], menu_id, moderation_channel_ids = [], moderation_counter = 0, needaction_inbox_counter = 0, partner_root, public_partner, public_partners, shortcodes = [], starred_counter = 0, failed_counter = 0, }) { const discuss = this.messaging.discuss; // Partners first because the rest of the code relies on them this._initPartners({ current_partner, current_user_id, moderation_channel_ids, partner_root, public_partner, public_partners, }); // Mailboxes after partners and before other initializers that might // manipulate threads or messages this._initMailboxes({ moderation_channel_ids, moderation_counter, needaction_inbox_counter, starred_counter, failed_counter, }); // Various suggestions in no particular order this._initCannedResponses(shortcodes); this._initCommands(commands); this._initMentionPartnerSuggestions(mention_partner_suggestions); // Channels when the rest of messaging is ready await this.async(() => this._initChannels(channel_slots)); // Failures after channels this._initMailFailures(mail_failures); discuss.update({menu_id}); }, _initMailboxes({ moderation_channel_ids, moderation_counter, needaction_inbox_counter, starred_counter, failed_counter, }) { this.env.messaging.inbox.update({counter: needaction_inbox_counter}); this.env.messaging.starred.update({counter: starred_counter}); this.env.messaging.failedmsg.update({counter: failed_counter}); if (moderation_channel_ids.length > 0) { this.messaging.moderation.update({ counter: moderation_counter, isServerPinned: true, }); } }, } ); registerFieldPatchModel( "mail.messaging", "mail/static/src/models/messaging/messaging.js", { failedmsg: one2one("mail.thread"), } ); registerInstancePatchModel( "mail.thread_cache", "mail/static/src/models/thread_cache/thread_cache.js", { _extendMessageDomain(domain) { const thread = this.thread; if (thread === this.env.messaging.failedmsg) { return domain.concat([["is_failed_message", "=", true]]); } return this._super(...arguments); }, } ); registerFieldPatchModel( "mail.message", "mail/static/src/models/message/message.js", { messagingFailedmsg: many2one("mail.thread", { related: "messaging.failedmsg", }), isFailed: attr({ default: false, }), } ); registerClassPatchModel( "mail.message", "mail/static/src/models/message/message.js", { convertData(data) { const data2 = this._super(data); if ("is_failed_message" in data) { data2.isFailed = data.is_failed_message; } return data2; }, } ); });
JavaScript
0.00083
@@ -608,51 +608,8 @@ ) %7B%0A - this._super(...arguments);%0A @@ -1079,32 +1079,82 @@ %7D);%0A + return this._super(...arguments);%0A %7D,%0A
39bb37227410b30df4154130baf3db109dd21a64
Update share.js
res/js/front/share.js
res/js/front/share.js
new Clipboard("#saveButton"); function saveButton() { $("#saveButton").text("Playlist copied!"); setTimeout(function() { resetSaveButton(); }, 2000); } function resetSaveButton() { if ($(window).width() <= 600) { $("#saveButton").text("Save"); } else { $("#saveButton").text("Save playlist"); } } resetSaveButton(); function shareOnRedditAd() { var i=0; var text = document.getElementById('ad'); text.style.color = 'grey'; function flash() { i++; text.style.color = (text.style.color=='grey') ? 'lightblue':'grey'; if (i == 11) { clearInterval(clr); } } var clr = setInterval(flash, 300); } function shareOnReddit() { var playlistName = $("#playlistNameBox").val(); if (playlistName === "") { playlistName = $("#playlistNameBox").attr("placeholder"); } if (window.location.hash.substr(1).length <= 10000) { window.open("https://www.reddit.com/r/StreamlyReddit/submit?resubmit=true&title=Playlist%20-%20" + playlistName + "&url=https://lnfwebsite.github.io/Streamly/%23" + window.location.hash.substr(1), "_blank"); } else { alert("The playlist you are sharing is too long to automatically post, so please copy your Streamly Playlist URL and paste it into the open Reddit tab (you can copy by clicking the \"Save Playlist\" button).\n\nSorry for this inconvenience."); window.open("https://www.reddit.com/r/StreamlyReddit/submit?resubmit=true&title=Playlist%20-%20" + playlistName + "&url=%5BPaste+shortened+link+here%5D", "_blank"); } }
JavaScript
0
@@ -1,8 +1,585 @@ +/**%0A Copyright 2018 LNFWebsite%0A Licensed under the Apache License, Version 2.0 (the %22License%22);%0A you may not use this file except in compliance with the License.%0A You may obtain a copy of the License at%0A http://www.apache.org/licenses/LICENSE-2.0%0A Unless required by applicable law or agreed to in writing, software%0A distributed under the License is distributed on an %22AS IS%22 BASIS,%0A WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A See the License for the specific language governing permissions and%0A limitations under the License.%0A**/%0A%0A new Clip
c5894dfb9a8770fc82a42314eccdec6a89f914e2
Fix bug that the solution will be undefined when exercise has no solution.
server/static/lecturer/js/store/components/group.js
server/static/lecturer/js/store/components/group.js
/** * Created by Elors on 2017/1/3. * Exercise-Group component */ define(['Exercise'], function () { $(function () { Vue.component('exercise-group', { template: '\ <div class="row store-row content-pane">\ <el-form ref="form" :model="form" label-width="0px" class="page-pane">\ <el-form-item label-width="0px" class="text item-input">\ <el-input v-model="form.title" class="input" id="ex-title"></el-input>\ </el-form-item>\ <el-form-item label-width="0px" class="text item-input">\ <el-input v-model="form.desc" class="input" id="ex-desc"></el-input>\ </el-form-item>\ <transition-group name="list" tag="div">\ <store-exercise\ v-for="(exercise, index) in form.exercises"\ v-bind:list="form.exercises"\ v-bind:exercise="exercise"\ v-bind:index="index"\ :key="index+\'ex\'">\ </store-exercise>\ </transition-group>\ <el-form-item class="item-submit" v-show="shouldShow">\ <el-button type="success" icon="plus" @click="onInsert">新增习题</el-button>\ <el-button type="primary" icon="edit" @click="onSave">保存题组</el-button>\ </el-form-item>\ </el-form>\ </div>\ ', data: function () { return { form: {}, shouldShow: false } }, methods: { loadGroup (data) { let group = this; $.ajax({ async: false, dataType: "json", url: '/lecturer/api/exercise/store?action=group&gid=' + data.id, success: function (json) { if (json && json.ok) { group.form = group.handleData(json); group.shouldShow = true; } } }); }, onInsert () { let model = this.defaultExercise(); this.form.exercises.push(model); }, onSave () { console.log(this.form.exercises) }, handleData (json) { let form = {}; form.id = json.data.id; form.title = json.data.title; form.desc = json.data.desc; let exercises = []; for (question of json.data.questions) { let exercise = {}; exercise.id = question.id; exercise.title = question.title; exercise.analyse = question.analyse; exercise.options = question.options; for (option of question.options) { if (question.solution === option.id) { exercise.solution = option.text; } } exercises.push(exercise); } form.exercises = exercises; return form }, defaultExercise () { return { id: null, title: '', solution: null, analyse: '', options: ['', '', '', ''] } } } }); }); });
JavaScript
0
@@ -2535,16 +2535,52 @@ ptions;%0A + exercise.solution = '';%0A @@ -2935,20 +2935,18 @@ id: -null +'' ,%0A @@ -2988,12 +2988,10 @@ on: -null +'' ,%0A
cce8bc08a8725142b99d480d8f0103f6d714af09
fix for failed test (C:\Program), one more quote
test/api_base.test.js
test/api_base.test.js
'use strict'; var gdal = require('../lib/gdal.js'); var assert = require('chai').assert; var fs = require('fs'); var path = require('path'); if (process.env.GDAL_DATA !== undefined) { throw new Error("Sorry, this test requires that the GDAL_DATA environment option is not set"); } describe('gdal', function() { afterEach(gc); describe('"lastError" property', function() { describe('get()', function() { it('should return null when no previous error', function() { // note: this needs to be the first test run assert.isNull(gdal.lastError); }); it('should return an object normally', function() { gdal._triggerCPLError(); assert.deepEqual(gdal.lastError, { code: gdal.CPLE_AppDefined, level: gdal.CE_Failure, message: 'Mock error' }); }); }); describe('set()', function() { it('should allow reset by setting to null', function() { gdal._triggerCPLError(); assert.equal(!!gdal.lastError, true); gdal.lastError = null; assert.isNull(gdal.lastError); }); it('should throw when not null', function() { assert.throws(function() { gdal.lastError = {}; }, /null/); }); }); }); describe('"version" property', function() { it('should exist', function() { assert.match(gdal.version, /^\d+\.\d+\.\d+[a-zA-Z]*$/); }); }); describe('"config" property', function() { describe('get()', function() { it('should not throw', function() { gdal.config.get('CPL_LOG'); }); }); describe('set()', function() { it('should set option', function() { gdal.config.set('CPL_DEBUG', 'ON'); assert.equal(gdal.config.get('CPL_DEBUG'), 'ON'); gdal.config.set('CPL_DEBUG', null); assert.isNull(gdal.config.get('CPL_DEBUG')); }); }); describe('GDAL_DATA behavior', function() { var data_path = path.resolve(__dirname, '../deps/libgdal/gdal/data'); it('should set GDAL_DATA config option to locally bundled path', function() { assert.equal(gdal.config.get('GDAL_DATA'),data_path); }); it('should respect GDAL_DATA environment over locally bundled path', function(done) { process.env.GDAL_DATA = 'bogus'; var cp = require('child_process'); var command = "\"var gdal = require('./lib/gdal.js'); console.log(gdal.config.get('GDAL_DATA'));\""; var execPath = process.execPath; if (process.platform === 'win32') { // attempt to avoid quoting problem that leads to error like ''C:\Program' is not recognized as an internal or external command' execPath = '"' + execPath + '"'; } cp.exec(execPath + ' ' + ['-e',command].join(' '),{env:{GDAL_DATA:'bogus'}},function(err,stdout,stderr) { if (err) throw err; assert.equal(process.env.GDAL_DATA,stdout.trim()); done(); }) }); }); }); describe('decToDMS()', function() { it('should throw when axis not provided', function() { assert.throws(function() { gdal.decToDMS(12.2); }); }); it('should return correct result', function() { assert.equal(gdal.decToDMS(14.12511, 'lat', 2), ' 14d 7\'30.40"N'); assert.equal(gdal.decToDMS(14.12511, 'lat', 1), ' 14d 7\'30.4"N'); assert.equal(gdal.decToDMS(14.12511, 'long', 2), ' 14d 7\'30.40"E'); assert.equal(gdal.decToDMS(14.12511, 'long', 1), ' 14d 7\'30.4"E'); }); }); });
JavaScript
0
@@ -2371,16 +2371,14 @@ %09%09// - attempt +quotes to @@ -2387,43 +2387,14 @@ oid -quoting problem that leads to error +s lik @@ -2481,16 +2481,17 @@ ath = '%22 +%22 ' + exec
17d95a7737b18369bf76462e4681d033cd8c6560
fix auto-fix coverage
test/auto-fix-func.js
test/auto-fix-func.js
import testRule from 'stylelint-test-rule-tape' import declarationStrictValue, { ruleName } from '../src' const { rule } = declarationStrictValue // eslint-disable-next-line consistent-return, no-unused-vars function autoFixFunc(node, validation, root, config) { const { value, prop } = node if (prop === 'color') { // eslint-disable-next-line default-case switch (value) { case '#fff': // auto-fix by returned value return '$color-white' case 'red': // auto-fix by PostCSS AST tranformation // eslint-disable-next-line no-param-reassign node.value = '$color-red' } } } // autofix by function property testRule(rule, { ruleName, skipBasicChecks: true, fix: true, config: ['color', { autoFixFunc, }], reject: [ { code: '.foo { color: #fff; }', fixed: '.foo { color: $color-white; }', message: `Expected variable or function for "#fff" of "color" (${ruleName})`, line: 1, column: 8, }, { code: '.foo { color: red; }', fixed: '.foo { color: $color-red; }', message: `Expected variable or function for "red" of "color" (${ruleName})`, line: 1, column: 8, }, ], }) // autofix by file exporting function testRule(rule, { ruleName, skipBasicChecks: true, fix: true, config: ['color', { autoFixFunc: './test/helpers/auto-fix-func.js', }], reject: [ { code: '.foo { color: #fff; }', fixed: '.foo { color: $color-white; }', message: `Expected variable or function for "#fff" of "color" (${ruleName})`, line: 1, column: 8, }, { code: '.foo { color: red; }', fixed: '.foo { color: $color-red; }', message: `Expected variable or function for "red" of "color" (${ruleName})`, line: 1, column: 8, }, ], })
JavaScript
0.000256
@@ -104,545 +104,456 @@ rc'%0A -%0Aconst %7B rule %7D = declarationStrictValue%0A%0A// eslint-disable-next-line consistent-return, no-unused-vars%0Afunction autoFixFunc(node, validation, root, config) %7B%0A const %7B value, prop %7D = node%0A%0A if (prop === 'color') %7B%0A // eslint-disable-next-line default-case%0A switch (value) %7B%0A case '#fff':%0A // auto-fix by returned value%0A return '$color-white'%0A%0A case 'red':%0A // auto-fix by PostCSS AST tranformation%0A // eslint-disable-next-line no-param-reassign%0A node.value = '$ +import autoFixFunc from './helpers/auto-fix-func'%0A%0Aconst %7B rule %7D = declarationStrictValue%0A%0Aconst ruleWithContext = (context) =%3E (properties, options) =%3E rule(properties, options, context)%0A%0A// autofix by function property%0AtestRule(ruleWithContext(%7B%0A fix: true,%0A%7D), %7B%0A ruleName,%0A skipBasicChecks: true,%0A%0A config: %5B'color', %7B%0A autoFixFunc,%0A %7D%5D,%0A%0A accept: %5B%0A %7B code: '.foo %7B color: #fff; %7D' %7D,%0A %7B code: '.foo %7B color --red'%0A +: red; %7D' %7D +, %0A -%7D +%5D, %0A%7D +) %0A%0A// @@ -573,32 +573,41 @@ unction property + disabled %0AtestRule(rule, @@ -596,32 +596,61 @@ ed%0AtestRule(rule +WithContext(%7B%0A fix: true,%0A%7D) , %7B%0A ruleName,%0A @@ -669,37 +669,24 @@ hecks: true, -%0A fix: true, %0A%0A config: @@ -706,32 +706,54 @@ autoFixFunc,%0A + disableFix: true,%0A %7D%5D,%0A%0A reject: @@ -1235,16 +1235,45 @@ ule(rule +WithContext(%7B%0A fix: true,%0A%7D) , %7B%0A ru @@ -1305,21 +1305,318 @@ : true,%0A +%0A -fix +config: %5B'color', %7B%0A autoFixFunc: './test/helpers/auto-fix-func.js',%0A %7D%5D,%0A%0A accept: %5B%0A %7B code: '.foo %7B color: #fff; %7D' %7D,%0A %7B code: '.foo %7B color: red; %7D' %7D,%0A %5D,%0A%7D)%0A%0A// autofix by file exporting function disabled%0AtestRule(ruleWithContext(%7B%0A fix: true,%0A%7D), %7B%0A ruleName,%0A skipBasicChecks : true,%0A @@ -1682,32 +1682,54 @@ o-fix-func.js',%0A + disableFix: true,%0A %7D%5D,%0A%0A reject:
c436f91eca5b40fea9a501e1b8d179e31f72e35a
Add check that child is properly attached to parent the other way too...
test/children_test.js
test/children_test.js
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/ /*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/ /*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ (function(el) { test("the third param is to create nested elements", function() { var e = el('p', {}, [el('a')]); ok( e.nodeName.match(/p/i) ); equal( e.childNodes.length, 1, 'the parent element has a child'); ok( e.childNodes[0].nodeName.match(/a/i) ); }); test("if the second param is an array, it's assumed that no attributes were specified", function() { var e = el('p', [el('a')]); equal( e.childNodes.length, 1, 'the parent element has a child'); ok( e.childNodes[0].nodeName.match(/a/i) ); }); test("a string in the children creates a text node", function() { var e = el('p', ["my awesome paragraph"]); equal( e.childNodes.length, 1, 'the parent element has a child'); equal( e.childNodes[0].textContent, 'my awesome paragraph' ); }); test("a string can replace the children array, as a shortcut", function() { var e = el('p', "my awesome paragraph"); equal( e.childNodes.length, 1, 'the parent element has a child'); equal( e.childNodes[0].textContent, 'my awesome paragraph' ); }); }(el));
JavaScript
0
@@ -469,35 +469,43 @@ a child');%0A -ok( +var child = e.childNodes%5B0%5D @@ -496,32 +496,47 @@ e.childNodes%5B0%5D +;%0A ok( child .nodeName.match( @@ -536,32 +536,66 @@ .match(/a/i) );%0A + equal( child.parentNode, e );%0A %7D);%0A%0A test(%22i
502fadc64e885faf27b56c5a740a6ffe658ad398
test fixes
test/commands-spec.js
test/commands-spec.js
var proxyquire = require('proxyquire').noPreserveCache(), Q = require('q'), _ = require('underscore'), Queries = require('../lib/commands/queries'), Utils = require('../lib/commands/utils'), Invoker = require('../lib/commands').Invoker; describe('Invoker', () => { var readline, exit, invoker, db, messages, writer; function mockCommands(invoker, mocks, db, names) { names.forEach(name => { var CommandType = proxyquire('../lib/commands/' + name, mocks); var command = new CommandType(db); invoker.commands = _.map(invoker.commands, cmd => { return (cmd.constructor.name == command.constructor.name) ? command : cmd; }); }); } beforeEach(() => { messages = {}; db = {}; readline = { on: jasmine.createSpy(), pause: jasmine.createSpy() }; mockDbFunc('query'); writer = { write: jasmine.createSpy() }; exit = jasmine.createSpy(); Utils.readFile = jasmine.createSpy().andReturn(readline); var mocks = { './utils': Utils, '../../external/exit': exit }; invoker = new Invoker(db, messages, writer); mockCommands(invoker, mocks, db, ['read', 'quit']); }); function mockDbFunc(func) { db[func] = jasmine.createSpy().andReturn(new Q([])); } it('.help returns commands reference', done => { writer.write.andCallFake(items => { var commands = [ { command: '.help', description: 'Shows this message' }, { command: '.databases', description: 'Lists all the databases' }, { command: '.collections', description: 'Lists all the collections' }, { command: '.read FILENAME', description: 'Execute commands in a file' }, { command: '.storedprocs', description: 'Lists all the stored procedures' }, { command: '.conflicts', description: 'Lists all the conflicts' }, { command: '.triggers', description: 'Lists all the triggers' }, { command: '.functions', description: 'Lists all the user defined functions' }, { command: '.permissions USER', description: 'Lists all the permissions' }, { command: '.attachments DOC', description: 'Lists all the attachments' }, { command: '.users', description: 'Lists all the users' }, { command: '.use db|coll ID', description: 'Switches current database or collection' }, { command: '.quit', description: 'Exit the cli' } ]; commands.forEach(cmd => { expect(_.findWhere(items, cmd)).toBeDefined(); }); expect(items.length).toEqual(commands.length); done(); }); invoker.run('.help'); }); it('.collections runs the listSysObjectsSql query', () => { mockDbFunc('queryCollections'); invoker.run('.collections'); expect(db.queryCollections).toHaveBeenCalledWith(Queries.listSysObjectsSql()); }); it('.databases runs the listSysObjectsSql query', () => { mockDbFunc('queryDatabases'); invoker.run('.databases'); expect(db.queryDatabases).toHaveBeenCalledWith(Queries.listSysObjectsSql()); }); it('.permissions runs the listSysObjectsSql query', () => { mockDbFunc('queryPermissions'); invoker.run('.permissions abc'); expect(db.queryPermissions).toHaveBeenCalledWith('abc', Queries.listSysObjectsSql()); }); it('.attachments runs the listSysObjectsSql query', () => { mockDbFunc('queryAttachments'); invoker.run('.attachments abc'); expect(db.queryAttachments).toHaveBeenCalledWith('abc', Queries.listSysObjectsSql()); }); it('.storedprocs runs the listSysObjectsSql query', () => { mockDbFunc('queryStoredProcedures'); invoker.run('.storedprocs'); expect(db.queryStoredProcedures).toHaveBeenCalledWith(Queries.listSysObjectsSql()); }); it('.triggers runs the listSysObjectsSql query', () => { mockDbFunc('queryTriggers'); invoker.run('.triggers'); expect(db.queryTriggers).toHaveBeenCalledWith(Queries.listSysObjectsSql()); }); it('.conflicts runs the listSysObjectsSql query', () => { mockDbFunc('queryConflicts'); invoker.run('.conflicts'); expect(db.queryConflicts).toHaveBeenCalledWith(Queries.listSysObjectsSql()); }); it('.functions runs the listSysObjectsSql query', () => { mockDbFunc('queryUserDefinedFunctions'); invoker.run('.functions'); expect(db.queryUserDefinedFunctions).toHaveBeenCalledWith(Queries.listSysObjectsSql()); }); it('.users runs the listSysObjectsSql query', () => { mockDbFunc('queryUsers'); invoker.run('.users'); expect(db.queryUsers).toHaveBeenCalledWith(Queries.listSysObjectsSql()); }); it('.use changes db', () => { invoker.run('.use db abc'); expect(db.database).toEqual('abc'); }); it('.use changes coll', () => { invoker.run('.use coll def'); expect(db.collection).toEqual('def'); }); it('.read runs the commands in file', done => { messages.echo = jasmine.createSpy(); invoker.run('.read test'); expect(readline.on).toHaveBeenCalledWith('line', jasmine.any(Function)); lineCallback = _.find(readline.on.argsForCall, args => args[0] == 'line')[1]; db.query.andCallFake(query => { expect(messages.echo).toHaveBeenCalledWith('SELECT *\r\nFROM test'); expect(query).toEqual('SELECT *\r\nFROM test'); done(); return new Q(0); }); lineCallback('SELECT *\\'); lineCallback('FROM test'); }); it('.quit exits the app', () => { invoker.run('.quit'); expect(exit).toHaveBeenCalled(); }); });
JavaScript
0.000001
@@ -884,16 +884,56 @@ pause: + jasmine.createSpy(),%0A close: jasmine @@ -5901,20 +5901,16 @@ return -new Q(0);%0A
a6567d5365a83a20a6fc17ea3c45980c80de0a4b
fix e2e tests
test/e2e/scenarios.js
test/e2e/scenarios.js
'use strict'; /* https://github.com/angular/protractor/blob/master/docs/getting-started.md */ describe('my app', function() { browser.get('index.html'); it('should automatically redirect to /view1 when location hash/fragment is empty', function() { expect(browser.getLocationAbsUrl()).toMatch("/view1"); }); describe('view1', function() { beforeEach(function() { browser.get('index.html#/view1'); }); it('should render view1 when user navigates to /view1', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/partial for view 1/); }); }); describe('view2', function() { beforeEach(function() { browser.get('index.html#/view2'); }); it('should render view2 when user navigates to /view2', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/partial for view 2/); }); }); });
JavaScript
0.00003
@@ -192,21 +192,23 @@ ect to / -view1 +counter when lo @@ -302,21 +302,23 @@ Match(%22/ -view1 +counter %22);%0A %7D) @@ -333,21 +333,23 @@ scribe(' -view1 +counter ', funct @@ -416,21 +416,23 @@ x.html#/ -view1 +counter ');%0A @@ -459,21 +459,23 @@ render -view1 +counter when us @@ -495,13 +495,15 @@ to / -view1 +counter ', f @@ -548,34 +548,32 @@ y.css('%5Bng-view%5D - p ')).first().getT @@ -601,26 +601,9 @@ ch(/ -partial for view 1 +0 /);%0A @@ -631,21 +631,27 @@ scribe(' -view2 +big-counter ', funct @@ -718,21 +718,27 @@ x.html#/ -view2 +big-counter ');%0A @@ -765,21 +765,27 @@ render -view2 +big-counter when us @@ -805,13 +805,19 @@ to / -view2 +big-counter ', f @@ -874,10 +874,8 @@ iew%5D - p ')). @@ -915,26 +915,9 @@ ch(/ -partial for view 2 +0 /);%0A
582c4beeeab3da4bac3b1eb31824bb2240c13140
fix assertion in e2e tests for tokens that never expire
test/e2e/token.e2e.js
test/e2e/token.e2e.js
const { expect } = require('../setup'); const { delay } = require('../lib/mocha-utils'); const matches = require('../lib/capture-matches'); const stripANSI = require('../lib/ansi-strip'); const cli = require('../lib/cli'); const { PASSWORD } = require('../lib/env'); describe('Token Commands', () => { const help = [ 'Manage access tokens (require username/password)', 'Usage: particle token <command>', 'Help: particle help token <command>', '', 'Commands:', ' list List all access tokens for your account', ' revoke Revoke an access token', ' create Create a new access token', '', 'Global Options:', ' -v, --verbose Increases how much logging to display [count]', ' -q, --quiet Decreases how much logging to display [count]' ]; before(async () => { await cli.setTestProfileAndLogin(); }); after(async () => { await cli.logout(); await cli.setDefaultProfile(); }); it('Shows `help` content', async () => { const { stdout, stderr, exitCode } = await cli.run(['help', 'token']); expect(stdout).to.equal(''); expect(stderr.split('\n')).to.include.members(help); expect(exitCode).to.equal(0); }); it('Shows `help` content when run without arguments', async () => { const { stdout, stderr, exitCode } = await cli.run('token'); expect(stdout).to.equal(''); expect(stderr.split('\n')).to.include.members(help); expect(exitCode).to.equal(0); }); it('Shows `help` content when run with `--help` flag', async () => { const { stdout, stderr, exitCode } = await cli.run(['token', '--help']); expect(stdout).to.equal(''); expect(stderr.split('\n')).to.include.members(help); expect(exitCode).to.equal(0); }); it('Creates a token', async () => { const subprocess = cli.run(['token', 'create']); await delay(1000); subprocess.stdin.write(PASSWORD); subprocess.stdin.end('\n'); const { stdout, stderr, exitCode } = await subprocess; const [msg, token] = stripANSI(stdout).split('\n').slice(-2).map(t => t.trim()); expect(msg).to.include('New access token expires on'); expect(token).to.be.a('string').with.lengthOf.at.least(12); expect(stderr).to.equal(''); expect(exitCode).to.equal(0); }); it('Creates a token with an expiration time', async () => { const subprocess = cli.run(['token', 'create', '--expires-in', '3600']); await delay(1000); subprocess.stdin.write(PASSWORD); subprocess.stdin.end('\n'); const { stdout, stderr, exitCode } = await subprocess; const [msg, token] = stripANSI(stdout).split('\n').slice(-2).map(t => t.trim()); expect(msg).to.include('New access token expires on'); expect(token).to.be.a('string').with.lengthOf.at.least(12); expect(stderr).to.equal(''); expect(exitCode).to.equal(0); }); it('Creates a token that does not expire', async () => { const subprocess = cli.run(['token', 'create', '--never-expires']); await delay(1000); subprocess.stdin.write(PASSWORD); subprocess.stdin.end('\n'); const { stdout, stderr, exitCode } = await subprocess; const [msg, token] = stripANSI(stdout).split('\n').slice(-2).map(t => t.trim()); expect(msg).to.include('New access token does not expire'); expect(token).to.be.a('string').with.lengthOf.at.least(12); expect(stderr).to.equal(''); expect(exitCode).to.equal(0); }); it('Revokes a token', async () => { let subprocess = cli.run(['token', 'create'], { reject: true }); await delay(1000); subprocess.stdin.write(PASSWORD); subprocess.stdin.end('\n'); const { stdout: log } = await subprocess; const [, token] = stripANSI(log).split('\n').slice(-2).map(t => t.trim()); expect(token).to.be.a('string').with.lengthOf.at.least(12); subprocess = cli.run(['token', 'revoke', token]); await delay(1000); subprocess.stdin.write(PASSWORD); subprocess.stdin.end('\n'); const { stdout, stderr, exitCode } = await subprocess; const [msg] = stripANSI(stdout).split('\n').slice(-1).map(t => t.trim()); expect(msg).to.include(`successfully deleted ${token}`); expect(stderr).to.equal(''); expect(exitCode).to.equal(0); }); it('Lists tokens', async () => { const subprocess = cli.run(['token', 'list']); await delay(1000); subprocess.stdin.write(PASSWORD); subprocess.stdin.end('\n'); const { stdout, stderr, exitCode } = await subprocess; const tokens = matches(stripANSI(stdout), / Token:\s{6}(.*)/g); expect(tokens).to.have.lengthOf.at.least(3); expect(stderr).to.equal(''); expect(exitCode).to.equal(0); // TODO (mirande): always revoke all tokens upon completion? // await tokens.reduce((promise, t) => { // return promise.then(() => { // console.log('REVOKING:', t); // return cli.run(['token', 'revoke', t], { input: PASSWORD }); // }); // }, Promise.resolve()); }); });
JavaScript
0
@@ -3147,31 +3147,29 @@ s token -does not +never expire +s ');%0A%09%09ex
32ed136f83653db977b47abcfa105eb6e1b13c74
fix try-example yarn install
test/fixtures/util.js
test/fixtures/util.js
'use strict'; const shell = require('shelljs'); const path = require('path'); const glob = require('glob'); const rootDir = path.join(path.resolve(__dirname), '..', '..'); const fs = require('fs-extra'); const silent = true; const getWorkspaceDirs = (absolute = false) => { const rootJson = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json'))); const workspaceDirs = rootJson.workspaces.map(item => glob.sync(item, {cwd: rootDir, absolute: absolute}) ).flat(); return workspaceDirs; }; const getWorkspacePackages = () => { const packages = getWorkspaceDirs(true) .map(item => JSON.parse(fs.readFileSync(path.join(item, 'package.json'))).name); return packages; }; const removeWorkspacePackages = (fromPath) => { const stagePath = fromPath || process.cwd(); const workspacePackages = getWorkspacePackages(); const packageJson = path.join(stagePath, 'package.json'); if (fs.existsSync(packageJson)) { const packageJsonData = JSON.parse(fs.readFileSync(packageJson)); const newPackageJsonData = ["dependencies", "devDependencies"].reduce((acc, depType) => { if (acc[depType]) { acc[depType] = Object.keys(acc[depType]).reduce((depsAcc, dep) => { if (workspacePackages.includes(dep)) { delete depsAcc[dep]; } return depsAcc; }, acc[depType]); } return acc; }, packageJsonData); return fs.writeFileSync(packageJson, JSON.stringify(newPackageJsonData, null, ' ')); } }; const copyExample = (exampleName, stageName) => { const stagePath = path.join(process.cwd(), stageName); fs.copySync(path.join(rootDir, 'examples', exampleName), stagePath); return stagePath; }; const yalcPublishAll = () => { return getWorkspaceDirs().map(dir=>shell.exec(`yalc publish ${dir}`)) }; const yalcAddAll = () => { return getWorkspacePackages().map(pkg=>shell.exec(`yalc add ${pkg}`)) }; const setupStageWithExample = ( stageName, exampleName, symlink=true, yarnlink=false, install=false, test=false ) => { const packagesPath = path.join(rootDir, 'packages'); let silentState = shell.config.silent; // save old silent state let verboseState = shell.config.verbose; // save old silent state shell.config.verbose = !silent; shell.config.silent = silent; const stagePath = copyExample(exampleName, stageName); shell.cd(stagePath); if (install) { shell.exec("yarn install", { env: Object.assign(process.env, {NODE_ENV:"development"}) }); } if (symlink) { fs.ensureSymlinkSync( path.join(rootDir, 'node_modules'), path.join(stagePath, 'node_modules') ); fs.ensureSymlinkSync( path.join(rootDir, 'node_modules', '.bin'), path.join(stagePath, 'node_modules', '.bin') ); fs.ensureSymlinkSync( packagesPath, path.join(stagePath, 'packages') ); } if (yarnlink) { const dirs = fs.readdirSync(packagesPath, { withFileTypes:true }) .map(dir=>{ return dir.isDirectory ? dir.name: dir }); for (const packageName of dirs) { const packagePath = path.join(packagesPath, packageName); shell.cd(packagePath); shell.exec(`yarn link`); shell.cd(stagePath); shell.exec(`yarn link ${packageName}`); if (!silent) console.log(`Linked ${packageName} to ${stagePath}`); } } if (test) { shell.exec("yarn run test", { env: Object.assign(process.env, {CI:"true"}) }); } shell.config.verbose = verboseState; shell.config.silent = silentState; return stagePath; }; module.exports = { getWorkspaceDirs: getWorkspaceDirs, getWorkspacePackages: getWorkspacePackages, removeWorkspacePackages: removeWorkspacePackages, yalcPublishAll: yalcPublishAll, yalcAddAll: yalcAddAll, yalcSetupStageWithExample: ( stageName, exampleName ) => { let silentState = shell.config.silent; // save old silent state let verboseState = shell.config.verbose; // save old silent state shell.config.verbose = true; shell.config.silent = false; yalcPublishAll(); const stagePath = copyExample(exampleName, stageName); removeWorkspacePackages(stagePath); shell.cd(stagePath); shell.exec("yarn install", { env: Object.assign(process.env, {NODE_ENV:"development"}) }); yalcAddAll(); shell.config.verbose = verboseState; shell.config.silent = silentState; return stagePath; }, copyExample: copyExample, setupStage: (stageName) => { const stagePath = path.join(rootDir, stageName); fs.ensureDirSync(stagePath); shell.cd(stagePath); }, setupStageWithFixture: (stageName, fixtureName) => { const stagePath = path.join(rootDir, stageName); fs.copySync(path.join(rootDir, 'test', 'fixtures', fixtureName), stagePath); fs.ensureSymlinkSync( path.join(rootDir, 'node_modules'), path.join(stagePath, 'node_modules') ); fs.ensureSymlinkSync( path.join(rootDir, 'packages'), path.join(stagePath, 'packages') ); shell.cd(stagePath); }, setupStageWithExample: setupStageWithExample, teardownStage: stageName => { shell.cd(rootDir); fs.removeSync(path.join(rootDir, stageName)); }, rootDir, };
JavaScript
0
@@ -4174,32 +4174,51 @@ cd(stagePath);%0A%0A + yalcAddAll();%0A%0A shell.exec(%22 @@ -4297,35 +4297,16 @@ %7D) %7D);%0A%0A - yalcAddAll();%0A%0A shel
4d927fbf159f311ee42eb3850fb41cf95726a4dd
disable 'text-summary' coverage report in Travis
test/karma.travis.es6
test/karma.travis.es6
import karmaCommon from './karma.common'; export default function(config) { config.set({ ...karmaCommon, singleRun: true, logLevel: config.LOG_INFO, reporters: [ 'dots', 'coverage' ], coverageReporter: { ...karmaCommon.coverageReporter, reporters: [ ...karmaCommon.coverageReporter.reporters, { type: 'text-summary' } ] }, customLaunchers: { ChromeTravis: { base: 'Chrome', flags: [ '--no-sandbox' ] } }, browsers: [ 'ChromeTravis', 'Firefox' ] }); }
JavaScript
0.000001
@@ -218,231 +218,8 @@ %5D,%0A - coverageReporter: %7B%0A ...karmaCommon.coverageReporter,%0A reporters: %5B%0A ...karmaCommon.coverageReporter.reporters,%0A %7B type: 'text-summary' %7D%0A %5D%0A %7D,%0A
d48930aedf9c1001f2090e88a4bae5f0fab0e193
Consolidate conditionals
lib/node_modules/@stdlib/math/base/dist/triangular/logcdf/lib/logcdf.js
lib/node_modules/@stdlib/math/base/dist/triangular/logcdf/lib/logcdf.js
'use strict'; // MODULES // var isnan = require( '@stdlib/math/base/assert/is-nan' ); var pow = require( '@stdlib/math/base/special/pow' ); var ln = require( '@stdlib/math/base/special/ln' ); var NINF = require( '@stdlib/math/constants/float64-ninf' ); // MAIN // /** * Evaluates the natural logarithm of the cumulative distribution function (CDF) for a triangular distribution with lower limit `a` and upper limit `b` and mode `c` at a value `x`. * * @param {number} x - input value * @param {number} a - lower limit * @param {number} b - upper limit * @param {number} c - mode * @returns {number} evaluated logCDF * * @example * var y = logcdf( 0.5, -1.0, 1.0, 0.0 ); * // returns ~-0.134 * * @example * var y = logcdf( 0.5, -1.0, 1.0, 0.5 ); * // returns ~-0.288 * * @example * var y = logcdf( -10.0, -20.0, 0.0, -2.0 ); * // returns ~-1.281 * * @example * var y = logcdf( -2.0, -1.0, 1.0, 0.0 ); * // returns Number.NEGATIVE_INFINITY * * @example * var y = logcdf( NaN, 0.0, 1.0, 0.5 ); * // returns NaN * * @example * var y = logcdf( 0.0, NaN, 1.0, 0.5 ); * // returns NaN * * @example * var y = logcdf( 0.0, 0.0, NaN, 0.5 ); * // returns NaN * * @example * var y = logcdf( 2.0, 1.0, 0.0, NaN ); * // returns NaN * * @example * var y = logcdf( 2.0, 1.0, 0.0, 1.5 ); * // returns NaN */ function logcdf( x, a, b, c ) { var denom1; var denom2; if ( isnan( x ) || isnan( a ) || isnan( b ) || isnan( c ) ) { return NaN; } if ( !( a <= c && c <= b ) ) { return NaN; } if ( x <= a ) { return NINF; } denom1 = ( b - a ) * ( c - a ); denom2 = ( b - a ) * ( b - c ); // Case: x > a if ( x <= c ) { return ( 2.0 * ln( x - a ) ) - ln( denom1 ); } // Case: x > c if ( x < b ) { return ln( 1.0 - ( pow( b - x, 2.0 ) / denom2 ) ); } // Case: x >= b return 0.0; } // end FUNCTION logcdf() // EXPORTS // module.exports = logcdf;
JavaScript
0.000023
@@ -1418,59 +1418,32 @@ c ) -%0A%09) %7B%0A%09%09return NaN;%0A%09%7D%0A%09if ( !( a %3C= c && c %3C= b ) + %7C%7C%0A%09%09a %3E c %7C%7C%0A%09%09c %3E b%0A%09 ) %7B%0A @@ -1459,17 +1459,16 @@ NaN;%0A%09%7D%0A -%0A %09if ( x
7818af50ba8fc7299d085e020cb55457ef4699a2
add contacts to services.js
server-ce/services.js
server-ce/services.js
module.exports = [{ name: "web", repo: "https://github.com/sharelatex/web-sharelatex.git", version: "master" }, { name: "real-time", repo: "https://github.com/sharelatex/real-time-sharelatex.git", version: "master" }, { name: "document-updater", repo: "https://github.com/sharelatex/document-updater-sharelatex.git", version: "master" }, { name: "clsi", repo: "https://github.com/sharelatex/clsi-sharelatex.git", version: "master" }, { name: "filestore", repo: "https://github.com/sharelatex/filestore-sharelatex.git", version: "master" }, { name: "track-changes", repo: "https://github.com/sharelatex/track-changes-sharelatex.git", version: "master" }, { name: "docstore", repo: "https://github.com/sharelatex/docstore-sharelatex.git", version: "master" }, { name: "chat", repo: "https://github.com/sharelatex/chat-sharelatex.git", version: "master" }, { name: "tags", repo: "https://github.com/sharelatex/tags-sharelatex.git", version: "master" }, { name: "spelling", repo: "https://github.com/sharelatex/spelling-sharelatex.git", version: "master" }]
JavaScript
0
@@ -1076,11 +1076,118 @@ master%22%0A +%7D, %7B%0A%09name: %22contacts%22,%0A%09repo: %22https://github.com/sharelatex/contacts-sharelatex.git%22,%0A%09version: %22master%22%0A %7D%5D%0A
11acaa40c365a7fa2ab63db27169b3e98a51f8d9
update decision's dimensions
test/spec/xml/read.js
test/spec/xml/read.js
'use strict'; var Helper = require('../../helper'); describe('dmn-moddle - read', function() { var moddle = Helper.createModdle(); function read(xml, root, opts, callback) { return moddle.fromXML(xml, root, opts, callback); } function fromFile(file, root, opts, callback) { var contents = Helper.readFile(file); return read(contents, root, opts, callback); } describe('should import Decisions', function() { describe('dmn', function() { it('Decision', function(done) { // when fromFile('test/fixtures/dmn/decision.part.dmn', 'dmn:Definitions', function(err, result) { var expected = { $type: 'dmn:Decision', id: 'decision', name: 'decision-name' }; // then expect(err).to.be.undefined; expect(result.drgElements[0]).to.jsonEqual(expected); done(err); }); }); }); describe('camunda', function() { it('Extension', function(done) { // when fromFile('test/fixtures/dmn/camunda.dmn', 'dmn:Definitions', function(err, result) { var expected = { $type: 'dmn:Decision', id: 'decision', name: 'Dish', decisionTable: { $type: 'dmn:DecisionTable', id: 'decisionTable', input: [ { $type: 'dmn:InputClause', id: 'input1', label: 'Season', inputVariable: 'currentSeason' } ] } }; // then expect(err).to.be.undefined; expect(result.drgElements[0]).to.jsonEqual(expected); done(err); }); }); }); describe('di', function() { it('simple', function(done) { // when fromFile('test/fixtures/dmn/simple-di.dmn', 'dmn:Definitions', function(err, result) { var expected = [ { $type: 'dmn:BusinessKnowledgeModel', name: 'El menú', id: 'elMenu', extensionElements: { $type: 'dmn:ExtensionElements', values: [ { $type: 'biodi:Bounds', x: 450, y: 250, width: 125, height: 45 }, { $type:'biodi:Edge', source: 'dish-decision', waypoints: [ { $type: 'biodi:Waypoint', x: 450, y: 250 }, { $type: 'biodi:Waypoint', x: 500, y: 10 } ] } ] }, authorityRequirement: [ { $type: 'dmn:AuthorityRequirement', requiredAuthority: { $type: 'dmn:DMNElementReference', href: '#dish-decision' } } ] }, { $type: 'dmn:Decision', id: 'dish-decision', name: 'Dish Decision', extensionElements: { $type: 'dmn:ExtensionElements', values: [ { $type: 'biodi:Bounds', x: 150, y: 10, width: 100, height: 55 } ] } } ]; // then expect(err).to.be.undefined; expect(result.drgElements).to.jsonEqual(expected); done(err); }); }); it('input data', function(done) { // when fromFile('test/fixtures/dmn/input-data.dmn', 'dmn:Definitions', function(err, result) { var expected = [ { $type: 'dmn:InputData', name: 'Weather in Celsius', id: 'temperature_id', extensionElements: { $type: 'dmn:ExtensionElements', values: [ { $type: 'biodi:Bounds', x: 5, y: 270, width: 125, height: 45 } ] }, variable: { $type: 'dmn:InformationItem', typeRef: 'integer', name: 'Weather in Celsius', id: 'temperature_ii' } } ]; // then expect(err).to.be.undefined; expect(result.drgElements).to.jsonEqual(expected); done(err); }); }); }); }); });
JavaScript
0.000003
@@ -3659,17 +3659,17 @@ width: 1 -0 +8 0,%0A @@ -3695,10 +3695,10 @@ ht: -55 +80 %0A
2df528d81a60e1a8a71d5cdc3fb7ac063d235902
Use the async version of readFile
test/special/index.js
test/special/index.js
'use strict'; var _ = require('lodash'); var fs = require('fs'); var hljs = require('../../build'); var jsdom = require('jsdom').jsdom; var utility = require('../utility'); describe('special cases tests', function() { before(function() { var blocks, filename = utility.buildPath('fixtures', 'index.html'), page = fs.readFileSync(filename, 'utf-8'); // Allows hljs to use document global.document = jsdom(page); // Setup hljs environment hljs.configure({ tabReplace: ' ' }); hljs.initHighlighting(); // Setup hljs for non-`<pre><code>` tests hljs.configure({ useBR: true }); blocks = document.querySelectorAll('.code'); _.each(blocks, hljs.highlightBlock); }); require('./explicitLanguage'); require('./customMarkup'); require('./languageAlias'); require('./noHighlight'); require('./subLanguages'); require('./buildClassName'); require('./useBr'); });
JavaScript
0
@@ -243,24 +243,28 @@ re(function( +done ) %7B%0A var @@ -267,24 +267,8 @@ var -blocks,%0A file @@ -321,28 +321,14 @@ ml') -,%0A page = +;%0A%0A fs. @@ -339,12 +339,8 @@ File -Sync (fil @@ -353,20 +353,61 @@ 'utf-8' -) +, function(err, page) %7B%0A var blocks ;%0A%0A + // A @@ -437,16 +437,18 @@ ent%0A + global.d @@ -467,24 +467,26 @@ dom(page);%0A%0A + // Setup @@ -503,24 +503,26 @@ ronment%0A + hljs.configu @@ -549,16 +549,18 @@ ' %7D);%0A + hljs @@ -581,24 +581,26 @@ ing();%0A%0A + // Setup hlj @@ -629,24 +629,26 @@ %60 tests%0A + + hljs.configu @@ -665,24 +665,26 @@ : true %7D);%0A%0A + blocks = @@ -724,16 +724,18 @@ ');%0A + + _.each(b @@ -762,16 +762,42 @@ tBlock); +%0A%0A done(err);%0A %7D); %0A %7D);%0A%0A