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
41645c94ef2e938f5b7577d0ddcb9d885d4445fd
Check api expression at beginning.
commonLib/serverLib/lib/spec.js
commonLib/serverLib/lib/spec.js
'use strict'; let passport = require('passport'); let cookie = require('cookie-signature'); let auth = require('./auth'); let userLib = require('./user')(); let db = require('./databaseConfig'); let logger = require('./logging').getLogger(__filename); let expressWinston = require('express-winston'); let winstonCloudWatch = require('winston-cloudwatch'); let winston = require('winston'); let cookieKey; let cookieSecret; const getLoggingTransport = function (jsonFormat) { let transports = []; if (process.env.NODE_ENV !== 'production') { transports.push(new winston.transports.Console({ format: winston.format.combine(winston.format.colorize(), winston.format.simple()) })); } if (process.env.CLOUD_WATCH_LOG_STREAM_NAME) { transports.push(new winstonCloudWatch({ logGroupName: 'elyoosWebserver', logStreamName: process.env.CLOUD_WATCH_LOG_STREAM_NAME, level: 'info', jsonMessage: jsonFormat, awsRegion: process.env.AWS_REGION })); } return transports; }; module.exports = function (app, nuxt) { app.get('/healthCheck', function (req, res) { res.type('text/plain'); res.send("OK"); }); if (process.env.ROBOT_TEXT_ENABLE_CRAWLER === 'true') { app.get('/robots.txt', function (req, res) { res.type('text/plain'); res.send("User-agent: *\nDisallow: "); }); } else { app.get('/robots.txt', function (req, res) { res.type('text/plain'); res.send("User-agent: *\nDisallow: /"); }); } app.on('middleware:after:session', function () { app.use(passport.initialize()); app.use(passport.session()); //Tell passport to use our newly created local strategy for authentication passport.use(auth.localStrategy()); //Give passport a way to serialize and deserialize a user. In this case, by the user's id. passport.serializeUser(userLib.serialize); passport.deserializeUser(userLib.deserialize); if ('testing' !== process.env.NODE_ENV) { app.use(function (req, res, next) { //Needed because rolling is some how not working req.session.touch(); next(); }); } if (nuxt && nuxt.render) { app.use(function (req, res, next) { if (req.originalUrl.match(/api/) === null) { req.headers.cookie = cookieKey + '=s:' + cookie.sign(req.sessionID, cookieSecret); } req.session.save(async function () { if (req.originalUrl.match(/api/) === null) { try { await nuxt.render(req, res); } catch (err) { logger.error('Nuxt rendering has failed', {error: err}); } } else { next(); } }); }); } }); app.on('middleware:before:router', function () { app.use(expressWinston.logger({ transports: getLoggingTransport(false) })); }); app.on('middleware:after:router', function () { app.use(expressWinston.errorLogger({ transports: getLoggingTransport(true), meta: true, msg: "HTTP {{req.method}} {{req.url}}", expressFormat: true, dynamicMeta: function(req) { return { user: req.user ? req.user : null, body: req.body ? req.body : null, }; } })); }); return { onconfig: function (config, next) { let dbConfig = config.get('databaseConfig'); db.config(dbConfig); let cookieConfig = config.get('middleware').session.module.arguments.find(arg => arg.cookie); cookieKey = cookieConfig.key; cookieSecret = cookieConfig.secret; next(null, config); } }; };
JavaScript
0
@@ -2458,35 +2458,40 @@ ginalUrl.match(/ +%5E%5C/ api +%5C/ /) === null) %7B%0A @@ -2710,19 +2710,24 @@ .match(/ +%5E%5C/ api +%5C/ /) === n
a01a6f9c193473e91fb81ddf86ccd09a17c5893a
update stats doc about templating
src/widgets/stats/stats.js
src/widgets/stats/stats.js
import React from 'react'; import ReactDOM from 'react-dom'; import { bemHelper, prepareTemplateProps, getContainerNode } from '../../lib/utils.js'; import autoHideContainerHOC from '../../decorators/autoHideContainer.js'; import headerFooterHOC from '../../decorators/headerFooter.js'; import StatsComponent from '../../components/Stats/Stats.js'; import cx from 'classnames'; import defaultTemplates from './defaultTemplates.js'; let bem = bemHelper('ais-stats'); /** * Display various stats about the current search state * @function stats * @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget * @param {Object} [options.templates] Templates to use for the widget * @param {string|Function} [options.templates.header=''] Header template * @param {string|Function} [options.templates.body] Body template * @param {string|Function} [options.templates.footer=''] Footer template * @param {Function} [options.transformData] Function to change the object passed to the `body` template * @param {boolean} [options.autoHideContainer=true] Hide the container when no results match * @param {Object} [options.cssClasses] CSS classes to add * @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element * @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element * @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element * @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element * @param {string|string[]} [options.cssClasses.time] CSS class to add to the element wrapping the time processingTimeMs * @return {Object} */ const usage = `Usage: stats({ container, [ template ], [ transformData ], [ autoHideContainer] })`; function stats({ container, cssClasses: userCssClasses = {}, autoHideContainer = true, templates = defaultTemplates, collapsible = false, transformData } = {}) { if (!container) throw new Error(usage); let containerNode = getContainerNode(container); let Stats = headerFooterHOC(StatsComponent); if (autoHideContainer === true) { Stats = autoHideContainerHOC(Stats); } if (!containerNode) { throw new Error(usage); } let cssClasses = { body: cx(bem('body'), userCssClasses.body), footer: cx(bem('footer'), userCssClasses.footer), header: cx(bem('header'), userCssClasses.header), root: cx(bem(null), userCssClasses.root), time: cx(bem('time'), userCssClasses.time) }; return { init({templatesConfig}) { this._templateProps = prepareTemplateProps({ transformData, defaultTemplates, templatesConfig, templates }); }, render: function({results}) { ReactDOM.render( <Stats collapsible={collapsible} cssClasses={cssClasses} hitsPerPage={results.hitsPerPage} nbHits={results.nbHits} nbPages={results.nbPages} page={results.page} processingTimeMS={results.processingTimeMS} query={results.query} shouldAutoHideContainer={results.nbHits === 0} templateProps={this._templateProps} />, containerNode ); } }; } export default stats;
JavaScript
0.000003
@@ -849,32 +849,172 @@ y%5D Body template +, provided with %60hasManyResults%60,%0A * %60hasNoResults%60, %60hasOneResult%60, %60hitsPerPage%60, %60nbHits%60, %60nbPages%60, %60page%60, %60processingTimeMS%60, %60query%60 %0A * @param %7Bstr
e6bf4379708baa7870ca625671c4ba96977d33dd
make sure to unlock account before testing against quorum
packages/truffle/test/scenarios/migrations/quorum.js
packages/truffle/test/scenarios/migrations/quorum.js
const MemoryLogger = require("../memorylogger"); const CommandRunner = require("../commandrunner"); const path = require("path"); const assert = require("assert"); const Reporter = require("../reporter"); const sandbox = require("../sandbox"); const Web3 = require("web3"); describe("migrate with [ @quorum ] interface", () => { if (!process.env.QUORUM) return; let config; let web3; let networkId; const project = path.join(__dirname, "../../sources/migrations/quorum"); const logger = new MemoryLogger(); before(async () => { config = await sandbox.create(project); config.network = "development"; config.logger = logger; config.mocha = { reporter: new Reporter(logger) }; const provider = new Web3.providers.HttpProvider("http://localhost:22000", { keepAlive: false }); web3 = new Web3(provider); networkId = await web3.eth.net.getId(); }); it("runs migrations (sync & async/await)", async () => { try { await CommandRunner.run("migrate", config); } catch (error) { console.log(logger.contents()); throw new Error(error); } const output = logger.contents(); assert(output.includes("2_migrations_sync.js")); assert(output.includes("Deploying 'UsesExample'")); assert(output.includes("3_migrations_async.js")); assert(output.includes("Re-using deployed 'Example'")); assert(output.includes("Replacing 'UsesExample'")); assert(output.includes("PayableExample")); assert(output.includes("1 ETH")); assert(output.includes("Saving migration")); assert(output.includes("Saving artifacts")); const location = path.join( config.contracts_build_directory, "UsesExample.json" ); const artifact = require(location); const network = artifact.networks[networkId]; assert(output.includes(network.transactionHash)); assert(output.includes(network.address)); console.log(output); }).timeout(70000); }).timeout(10000);
JavaScript
0
@@ -898,16 +898,133 @@ etId();%0A + const accounts = await web3.eth.getAccounts();%0A await web3.eth.personal.unlockAccount(accounts%5B0%5D, %22%22, 8000);%0A %7D);%0A%0A
229d9dd8b9baed4245c17e5f8c1dac466efb2b19
fix for bundle exec
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var browserify = require('gulp-browserify'); var mochaPhantomJS = require('gulp-mocha-phantomjs'); var mocha = require('gulp-mocha'); var watch = require('gulp-watch'); var run = require('gulp-run'); var rename = require('gulp-rename'); var gutil = require('gulp-util'); var uglify = require('gulp-uglify'); var coffeelint = require('gulp-coffeelint'); require('shelljs/global'); // css var sass = require('gulp-ruby-sass'); // gulp-sass is also available (faster, feature-less) var minifyCSS = require('gulp-minify-css'); // path stuff var chmod = require('gulp-chmod'); var clean = require('gulp-clean'); var mkdirp = require('mkdirp'); var path = require('path'); var join = path.join; var concat = require('gulp-concat'); var mochaSelenium = require('gulp-mocha-selenium'); // for mocha require('coffee-script/register'); var outputFile = "biojs_vis_msa"; var buildDir = "build"; var browserFile = "browser.js"; var paths = { scripts: ['src/**/*.coffee'], testCoffee: ['./test/phantom/index.coffee'] }; var browserifyOptions = { transform: ['coffeeify'], extensions: ['.coffee'], }; gulp.task('default', ['clean','test','lint','build', 'codo']); gulp.task('test', ['test-mocha','test-phantom'],function () { return true; }); gulp.task('build', ['css','build-browser','build-browser-min'],function () { return true; }); gulp.task('build-browser',['init'], function() { // browserify var fileName = outputFile + ".js"; gulp.src(join(buildDir,fileName)).pipe(clean()); dBrowserifyOptions = {}; for( var key in browserifyOptions ) dBrowserifyOptions[ key ] = browserifyOptions[ key ]; dBrowserifyOptions["debug"] = true; return gulp.src(browserFile) .pipe(browserify(dBrowserifyOptions)) .pipe(rename(fileName)) .pipe(gulp.dest(buildDir)); }); gulp.task('build-browser-min',['init'], function() { // browserify var fileName = outputFile + ".min.js"; gulp.src(join(buildDir,fileName)).pipe(clean()); return gulp.src(browserFile) .pipe(browserify(browserifyOptions)) .pipe(uglify()) .pipe(rename(fileName)) .pipe(gulp.dest(buildDir)); }); gulp.task('build-test', function() { // compiles all coffee tests to one file for mocha gulp.src('./test/all_test.js').pipe(clean()); return gulp.src(paths.testCoffee, { read: false }) .pipe(browserify(browserifyOptions)) .on('error', gutil.log) .on('error', gutil.beep) .pipe(concat('all_test.js')) .pipe(gulp.dest('test')); }); gulp.task('test-phantom', ["build-test"], function () { return gulp .src('./test/index.html') .pipe(mochaPhantomJS()); }); gulp.task('test-mocha', function () { return gulp.src('./test/mocha/**/*.coffee', {read: false}) .pipe(mocha({reporter: 'spec', ui: "qunit", useColors: false, compilers: "coffee:coffee-script/register"})); }); // runs the mocha test in your browser gulp.task('test-mocha-selenium', function () { return gulp.src('./test/mocha/**/*.coffee', {read: false}) .pipe(mochaSelenium({reporter: 'spec', ui: "qunit", compilers: "coffee:coffee-script/register"})); }); gulp.task('lint', function () { gulp.src('./src/**/*.coffee') .pipe(coffeelint("coffeelint.json")) .pipe(coffeelint.reporter()); }); gulp.task('codo', ['init'],function () { run('codo src -o build/doc ').exec(); }); gulp.task('sass',['init'], function () { var opts = checkForSASS(); opts.sourcemap = true; gulp.src('./css/msa.scss') .pipe(sass(opts)) //.pipe(rename('msa.css')) .pipe(chmod(644)) .pipe(gulp.dest(buildDir)); }); gulp.task('css',['sass'], function () { if(checkForSASS() !== undefined){ gulp.src(join(buildDir,"msa.css")) .pipe(minifyCSS()) .pipe(rename('msa.min.css')) .pipe(chmod(644)) .pipe(gulp.dest(buildDir)); } }); gulp.task('watch', function() { // watch coffee files gulp.watch(['./src/**/*.coffee', './test/**/*.coffee'], function() { gulp.run('test'); }); }); // be careful when using this task. // will remove everything in build gulp.task('clean', function() { gulp.src(buildDir).pipe(clean()); gulp.run('init'); }); // just makes sure that the build dir exists gulp.task('init', function() { mkdirp(buildDir, function (err) { if (err) console.error(err) }); }); // ----------------------------------------- // SASS part // check whether there is a way to run SASS function checkForSASS(){ if (exec('sass --help',{silent:true}).code !== 0) { echo('Error: No SASS installed'); var checkBundle = checkBundleExec(); if( checkBundle !== undefined){ return checkBundle; }else{ installBundle(); checkBundleExec(); } } return {}; } function checkBundleExec(){ if (exec('sass --help > /dev/null 2>&1').code !== 0) { return { bundleExec: true }; } else { return undefined; } } function installBundle(){ if(exec("bundle install --path .gems").code !== 0){ echo('Install ruby and bundle'); return false; } return true; }
JavaScript
0
@@ -4881,37 +4881,46 @@ ec(' -sass --help %3E /dev/null 2%3E&1' +bundle exec sass --help',%7Bsilent:true%7D ).co
28db27b361f9c14cae13aad83b1dfaf0318223f9
rewrite async example in es7
examples/async/flyfile.js
examples/async/flyfile.js
export default function* () { yield this.clear("dist") yield this .source("src/*.txt") .filter(s => this.defer(transform)(s, { time: 1000 })) .filter(s => s.toUpperCase()) .target("dist") } function transform (source, options, cb) { setTimeout(() => { cb(null, source.split("").reverse().join("")) }, options.time) }
JavaScript
0.000003
@@ -8,24 +8,30 @@ default +async function * () %7B%0A @@ -26,17 +26,16 @@ tion -* () %7B%0A yiel @@ -30,21 +30,168 @@ () %7B%0A -yield +const transform = (source, options, cb) =%3E %7B%0A setTimeout(() =%3E %7B%0A cb(null, source.split(%22%22).reverse().join(%22%22))%0A %7D, options.time)%0A %7D%0A await this.cl @@ -208,13 +208,13 @@ )%0A -yield +await thi @@ -359,140 +359,4 @@ )%0A%7D%0A -%0Afunction transform (source, options, cb) %7B%0A setTimeout(() =%3E %7B%0A cb(null, source.split(%22%22).reverse().join(%22%22))%0A %7D, options.time)%0A%7D%0A
fa6d6d2bf016fe5a6f1efa3d93d6b5da8c49b2d0
Fix error when translating entire document
src/main.js
src/main.js
/* light-i18n main */ /* jshint browser: true */ // Base function. (function (global) { "use strict"; var languageDialect = (function(lang) { window.location.search.slice(1).split("&").some(function (searchTerm) { if (searchTerm.indexOf("lang=") === 0) { lang = searchTerm.split("=").slice(1).join("="); return true; } }); return lang.toLowerCase(); })(window.navigator.userLanguage || window.navigator.language), language = languageDialect.split("-")[0], translations; function loadTranslations(language, set, base) { var url = (base || "locales/") + language + "/" + (set || "translation") + ".json"; console.info("loading translations from: " + url); return fetch(url, { headers: { "Accept": "application/json" } }).then(function (res) { if (res.ok) { console.log("successfully loaded translations"); return res.json(); } // TODO add error object instead of false return Promise.reject(false); }).catch(function (err) { console.error("Error loading translations: %o", err); }); } function loadAndApplyTranslations(language, ancestor, set, base) { return loadTranslations(language, set, base).then(function (obj) { translate(obj, ancestor); return obj; }); } function applyTranslationToElement(ele, obj) { if(ele.hasAttribute("i18n")) { applyTranslation(ele, ele.getAttribute("i18n"), obj); } } function applyTranslation(ele, path, obj) { var translated = getByPath(obj, path); if (typeof(translated) !== "undefined") { ele.textContent = translated; } else { console.log("Could not translate website: path '%s' not found", path); } } function getLang(ele, threshold) { do { if(ele.lang) { return ele.lang; } } while((ele = ele.parentElement) && ele !== threshold); } function getByPath(obj, path) { return path.split(".").reduce(function (obj, key) { return obj ? obj[key] : undefined; }, obj); } function translate(obj, ancestor) { ancestor = ancestor || document; if(getLang(ancestor) === languageDialect) { if(!ancestor.hasAttribute("i18n")) { [].slice.call(ancestor.querySelectorAll("[lang]:not([lang='" + language + "'])")).forEach(translate.bind(null, obj)); } return; } if(ancestor.hasAttribute("i18n")) { applyTranslationToElement(ancestor, obj); } else { [].slice.call(ancestor.querySelectorAll("[i18n]")).forEach(function(ele) { if(getLang(ele, ancestor) !== languageDialect) { applyTranslationToElement(ele, obj); } }); } } translations = loadAndApplyTranslations(language); global.i18n = { translations: translations, translate: function(ele) { return this.translations.then(function(obj) { translate(obj, ele); return obj; }); }, set language(lang) { lang = String(lang); if(lang !== language) { language = lang; translations = loadAndApplyTranslations(lang); } }, get language() { return language; } }; }(this));
JavaScript
0.000006
@@ -1,71 +1,4 @@ -/* light-i18n main */%0A/* jshint browser: true */%0A// Base function.%0A (fun @@ -776,10 +776,41 @@ res. -ok +status %3E= 200 && res.status %3C 300 ) %7B%0A @@ -825,19 +825,20 @@ console. -log +info (%22succes @@ -1646,11 +1646,12 @@ ole. -log +warn (%22Co @@ -2066,24 +2066,24 @@ ancestor) %7B%0A - ancestor @@ -2105,16 +2105,32 @@ document +.documentElement ;%0A%0A i
da85a4b4ce1973ad8676c1c6a0bd918df4f76080
add getters for text and author on story prototype
js/story_controller.js
js/story_controller.js
/** * Story controller * Used to get process info about a story such as url, title, and type */ HN.Story = (function(){ function HNStory(storyInfo){ this.storyInfo = storyInfo; }; HNStory.prototype.url = function() { //for ask or show HN stories if(this.isLocalHNUrl()){ return HN.askUrl + this.storyInfo['id']; } return this.storyInfo['url']; }; HNStory.prototype.isLocalHNUrl = function(){ if(!this.storyInfo['url']){ return true; } return false; }; /** * gets the url root domain for display with story * http://www.nytimes.com/story becomes (nytimes.com) */ HNStory.prototype.urlRoot = function() { //for ask or show HN stories if(this.isLocalHNUrl()){ return ''; } //removes first part of url (http://www.) var base_url = this.url(); base_url = base_url.replace(/^http(s)?:\/\/(www.)?/, ''); //removes subfolders from url (/index.html) base_url = base_url.replace(/\/.*$/, ''); //removes get requests from url (?q=something) return '(' + base_url.replace(/\?.*$/,'') + ')'; }; HNStory.prototype.title = function(){ return this.storyInfo['title'] || ''; }; HNStory.prototype.storyType = function(){ if(this.type() !== 'story'){ return false; } if(this.isLocalHNUrl()){ if(this.title().substring(0,3).toLowerCase() === 'ask'){ return 'ask'; } return 'show'; } return 'story'; }; HNStory.prototype.type = function(){ return this.storyInfo['type']; }; HNStory.prototype.numComments = function(){ if(!this.storyInfo['descendants']){ return 0; } return this.storyInfo['descendants']; }; HNStory.prototype.getTopLevelCommentsIds = function(){ if(!this.storyInfo['kids']){ return []; } return this.storyInfo['kids']; }; HNStory.prototype.commentsUrl = function(){ // return 'https://news.ycombinator.com/item?id=' + this.storyInfo['id']; return HN.commentsUrl + this.storyInfo['id']; }; return HNStory; })();
JavaScript
0
@@ -1116,24 +1116,186 @@ %7C%7C '';%0A%09%7D;%0A +%09HNStory.prototype.text = function()%7B%0A%09%09return this.storyInfo%5B'text'%5D %7C%7C '';%0A%09%7D;%0A%09HNStory.prototype.author = function()%7B%0A%09%09return this.storyInfo%5B'by'%5D %7C%7C '';%0A%09%7D;%0A %09HNStory.pro
1b351ed17960493126d65fcd0d053f1937a05bd8
add option identifier
client.js
client.js
/** * Installs the Vue-Remote Client * Vue Plugin to utilize the Authority server model * * @module vue-remote/client * @author Justin MacArthur <[email protected]> * @version 1.0.4 * * @param {Object} Vue * @param {Object} [options] */ module.exports.install = function(Vue, options) { Vue.Remote = (function(options) { let Client = null, Handlers = Object.create(null), socketPump = [], pumpInterval = null options = options || {} options.secure = options.secure || false options.host = options.host || "localhost" options.port = options.port || 8080 /** * Connect to Websocket Server */ function connect() { Client = new WebSocket((options.secure ? "wss://" : "ws://") + options.host + ":" + options.port, options.protocol) Client.onopen = openHandler Client.onerror = errorHandler Client.onmessage = messageHandler Client.onclose = closeHandler } /** * Handle Server Connection Event * * @param {Event} open */ function openHandler(open) { console.log("Connected to Web Server") console.log(open) if (options.openHandler) options.openHandler(open) } /** * Handle Server Errors * * @param {Event} error */ function errorHandler(error) { console.log("Error occured") console.log(error) if (options.errorHandler) options.errorHandler(error) } /** * Handle Messages Returned from the Server * * @param {MessageEvent} message * @returns */ function messageHandler(message) { let Json = JSON.parse(message.data), Events = Handlers[Json.identifier] if (Events) { Events.forEach( (Event) => { Event.callback.apply(Event.thisArg, [Json.data]) } ) } } /** * {EventListener} For When the Websocket Client Closes the Connection * * @param {CloseEvent} close */ function closeHandler(close) { if (options.closeHandler) options.closeHandler(close) if (pumpInterval) { window.clearInterval(pumpInterval) pumpInterval = null } Client = null } /** * Attaches Handlers to the Event Pump System * * @param {Boolean} server True/False whether the Server should process the trigger * @param {String} identifier Unique Name of the trigger * @param {Function} callback Function to be called when the trigger is tripped * @param {Object} [thisArg] Arguement to be passed to the handler as `this` */ function attachHandler(identifier, callback, thisArg) { !(Handlers[identifier] || (Handlers[identifier] = [])).push({ callback: callback, thisArg: thisArg }) } /** * Detaches Handlers from the Event Pump System * * @param {String} identifier Unique Name of the trigger * @param {Function} callback Function to be called when the trigger is tripped */ function detachHandler(identifier, callback) { if(arguments.length == 0) { Handlers = Object.create(null) return } let Handler = Handlers[identifier] if(!Handler) return if(arguments.length == 1) { Handlers[identifier] = null return } for(let index = Handler.length - 1; index >= 0 ; index--) { if(Handler[index].callback === callback || Handler[index].callback.fn === callback) { Handler.splice(index, 1) } } } /** * Handles Event Triggers * * @param {String} identifier * @returns */ function emitHandler(identifier) { let args = arguments[1] || [] if(arguments.length > 2) { args = arguments.length > 1 ? [].slice.apply(arguments, [1]) : [] } if(typeof args === "object") { args.identifier = identifier socketPump.push(JSON.stringify(args)) return } socketPump.push( JSON.stringify({ 'identifier': identifier, 'arguments': args }) ) } /** * Sends Messages to the Websocket Server every 250 ms * * @returns */ function pumpHandler() { if (socketPump.length == 0) return if (!Client) connect() if (Client.readyState == WebSocket.OPEN) { socketPump.forEach( (item) => Client.send(item) ) socketPump.length = 0 } } if (!pumpInterval) window.setInterval(pumpHandler, 250) return { connect: connect, disconnect: () => { if (Client) { Client.close() Client = null } }, attach: attachHandler, detach: detachHandler, emit: emitHandler } })(options) Vue.mixin({ created: function() { if (this.$options.remote) { let Handlers = this.$options.remote for (let name in Handlers) { if (Handlers.hasOwnProperty(name) && typeof Handlers[name] === "function") { Vue.Remote.attach(name, Handlers[name], this) } } } }, beforeDestroy: function() { if (this.$options.remote) { let Handlers = this.$options.remote for (let name in Handlers) { if (Handlers.hasOwnProperty(name) && typeof Handlers[name] === "function") { Vue.Remote.detach(name, Handlers[name]) } } } } }); Vue.prototype.$remote = { $on: function(identifier, callback) { Vue.Remote.attach(identifier, callback, this) return this }, $once: function(identifier, callback) { const thisArg = this function once() { Vue.remote.detach(identifier, callback) callback.apply(thisArg, arguments) } once.fn = callback Vue.Remote.attach(identifier, once, thisArg) return thisArg }, $off: function(identifier, callback) { Vue.Remote.detach(identifier, callback, this) return this }, $emit: Vue.Remote.emit }; };
JavaScript
0.000002
@@ -647,16 +647,79 @@ %7C%7C 8080%0A + options.identifier = options.identifier %7C%7C 'identifier' %0A @@ -1983,16 +1983,24 @@ ers%5BJson +%5Boptions .identif @@ -2003,16 +2003,17 @@ ntifier%5D +%5D %0A%0A @@ -2093,24 +2093,153 @@ Event) =%3E %7B%0A + //Event.callback.apply(Event.thisArg, %5BJson.data%5D)%0A //Adapt to all respone format%0A @@ -2283,37 +2283,32 @@ t.thisArg, %5BJson -.data %5D)%0A @@ -7507,8 +7507,9 @@ %7D;%0A%7D; +%0A
1d40145d525a1cc23dff419d0afdf96b21ba19ff
Fix comment typos.
src/Parser/Core/Modules/Items/BFA/Raids/Uldir/ConstructOvercharger.js
src/Parser/Core/Modules/Items/BFA/Raids/Uldir/ConstructOvercharger.js
import React from 'react'; import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import { calculateSecondaryStatDefault} from 'common/stats'; import { formatPercentage, formatNumber } from 'common/format'; import Analyzer from 'Parser/Core/Analyzer'; /** * Construct Overcharger - * Equipe: Your attacks have a chance to increase your Haste by 6 for 10 sec, stacking up to 8 times. */ class ConstructOvercharger extends Analyzer{ statBuff = 0; constructor(...args){ super(...args); this.active = this.selectedCombatant.hasTrinket(ITEMS.CONSTRUCT_OVERCHARGER.id); if(this.active){ this.statBuff = calculateSecondaryStatDefault(355, 33, this.selectedCombatant.getItem(ITEMS.CONSTRUCT_OVERCHARGER.id).itemLevel); } } averageStatGain(){ const averageStacks = this.selectedCombatant.getStackWeightedBuffUptime(SPELLS.TITANIC_OVERCHARGE.id) / this.owner.fightDuration; return averageStacks * this.statBuff; } totalBuffUptime(){ return this.selectedCombatant.getBuffUptime(SPELLS.TITANIC_OVERCHARGE.id)/this.owner.fightDuration; } buffTriggerCount(){ return this.selectedCombatant.getBuffTriggerCount(SPELLS.TITANIC_OVERCHARGE.id); } item(){ return { item: ITEMS.CONSTRUCT_OVERCHARGER, result: ( <dfn data-tip={`Procced ${this.buffTriggerCount()} times.`}> {formatPercentage(this.totalBuffUptime())}% uptime.<br /> {formatNumber(this.averageStatGain())} average Haste. </dfn> ), }; } } export default ConstructOvercharger;
JavaScript
0.000016
@@ -301,17 +301,16 @@ * Equip -e : Your a @@ -360,9 +360,10 @@ by -6 +21 for
928ad11a07d9abdb4935f8ed6fc9c252bb69e2c3
Fix ThComponent classnames ordering (#673)
src/defaultProps.js
src/defaultProps.js
import React from 'react' import classnames from 'classnames' // import _ from './utils' import Pagination from './pagination' const emptyObj = () => ({}) export default { // General data: [], loading: false, showPagination: true, showPaginationTop: false, showPaginationBottom: true, showPageSizeOptions: true, pageSizeOptions: [5, 10, 20, 25, 50, 100], defaultPageSize: 20, showPageJump: true, collapseOnSortingChange: true, collapseOnPageChange: true, collapseOnDataChange: true, freezeWhenExpanded: false, sortable: true, multiSort: true, resizable: true, filterable: false, defaultSortDesc: false, defaultSorted: [], defaultFiltered: [], defaultResized: [], defaultExpanded: {}, // eslint-disable-next-line no-unused-vars defaultFilterMethod: (filter, row, column) => { const id = filter.pivotId || filter.id return row[id] !== undefined ? String(row[id]).startsWith(filter.value) : true }, // eslint-disable-next-line no-unused-vars defaultSortMethod: (a, b, desc) => { // force null and undefined to the bottom a = a === null || a === undefined ? '' : a b = b === null || b === undefined ? '' : b // force any string values to lowercase a = typeof a === 'string' ? a.toLowerCase() : a b = typeof b === 'string' ? b.toLowerCase() : b // Return either 1 or -1 to indicate a sort priority if (a > b) { return 1 } if (a < b) { return -1 } // returning 0, undefined or any falsey value will use subsequent sorts or // the index as a tiebreaker return 0 }, // Controlled State Props // page: undefined, // pageSize: undefined, // sorted: [], // filtered: [], // resized: [], // expanded: {}, // Controlled State Callbacks onPageChange: undefined, onPageSizeChange: undefined, onSortedChange: undefined, onFilteredChange: undefined, onResizedChange: undefined, onExpandedChange: undefined, // Pivoting pivotBy: undefined, // Key Constants pivotValKey: '_pivotVal', pivotIDKey: '_pivotID', subRowsKey: '_subRows', aggregatedKey: '_aggregated', nestingLevelKey: '_nestingLevel', originalKey: '_original', indexKey: '_index', groupedByPivotKey: '_groupedByPivot', // Server-side Callbacks onFetchData: () => null, // Classes className: '', style: {}, // Component decorators getProps: emptyObj, getTableProps: emptyObj, getTheadGroupProps: emptyObj, getTheadGroupTrProps: emptyObj, getTheadGroupThProps: emptyObj, getTheadProps: emptyObj, getTheadTrProps: emptyObj, getTheadThProps: emptyObj, getTheadFilterProps: emptyObj, getTheadFilterTrProps: emptyObj, getTheadFilterThProps: emptyObj, getTbodyProps: emptyObj, getTrGroupProps: emptyObj, getTrProps: emptyObj, getTdProps: emptyObj, getTfootProps: emptyObj, getTfootTrProps: emptyObj, getTfootTdProps: emptyObj, getPaginationProps: emptyObj, getLoadingProps: emptyObj, getNoDataProps: emptyObj, getResizerProps: emptyObj, // Global Column Defaults column: { // Renderers Cell: undefined, Header: undefined, Footer: undefined, Aggregated: undefined, Pivot: undefined, PivotValue: undefined, Expander: undefined, Filter: undefined, // All Columns sortable: undefined, // use table default resizable: undefined, // use table default filterable: undefined, // use table default show: true, minWidth: 100, // Cells only className: '', style: {}, getProps: emptyObj, // Pivot only aggregate: undefined, // Headers only headerClassName: '', headerStyle: {}, getHeaderProps: emptyObj, // Footers only footerClassName: '', footerStyle: {}, getFooterProps: emptyObj, filterMethod: undefined, filterAll: false, sortMethod: undefined, }, // Global Expander Column Defaults expanderDefaults: { sortable: false, resizable: false, filterable: false, width: 35, }, pivotDefaults: { // extend the defaults for pivoted columns here }, // Text previousText: 'Previous', nextText: 'Next', loadingText: 'Loading...', noDataText: 'No rows found', pageText: 'Page', ofText: 'of', rowsText: 'rows', // Components TableComponent: _.makeTemplateComponent('rt-table', 'Table'), TheadComponent: _.makeTemplateComponent('rt-thead', 'Thead'), TbodyComponent: _.makeTemplateComponent('rt-tbody', 'Tbody'), TrGroupComponent: _.makeTemplateComponent('rt-tr-group', 'TrGroup'), TrComponent: _.makeTemplateComponent('rt-tr', 'Tr'), ThComponent: ({ toggleSort, className, children, ...rest }) => ( <div className={classnames(className, 'rt-th')} onClick={e => ( toggleSort && toggleSort(e) )} role="button" tabIndex={0} {...rest} > {children} </div> ), TdComponent: _.makeTemplateComponent('rt-td', 'Td'), TfootComponent: _.makeTemplateComponent('rt-tfoot', 'Tfoot'), FilterComponent: ({ filter, onChange }) => ( <input type="text" style={{ width: '100%', }} value={filter ? filter.value : ''} onChange={event => onChange(event.target.value)} /> ), ExpanderComponent: ({ isExpanded }) => ( <div className={classnames('rt-expander', isExpanded && '-open')}> &bull; </div> ), PivotValueComponent: ({ subRows, value }) => ( <span> {value} {subRows && `(${subRows.length})`} </span> ), AggregatedComponent: ({ subRows, column }) => { const previewValues = subRows .filter(d => typeof d[column.id] !== 'undefined') .map((row, i) => ( // eslint-disable-next-line react/no-array-index-key <span key={i}> {row[column.id]} {i < subRows.length - 1 ? ', ' : ''} </span> )) return ( <span> {previewValues} </span> ) }, PivotComponent: undefined, // this is a computed default generated using // the ExpanderComponent and PivotValueComponent at run-time in methods.js PaginationComponent: Pagination, PreviousComponent: undefined, NextComponent: undefined, LoadingComponent: ({ className, loading, loadingText, ...rest }) => ( <div className={classnames('-loading', { '-active': loading }, className)} {...rest} > <div className="-loading-inner"> {loadingText} </div> </div> ), NoDataComponent: _.makeTemplateComponent('rt-noData', 'NoData'), ResizerComponent: _.makeTemplateComponent('rt-resizer', 'Resizer'), PadRowComponent: () => <span>&nbsp;</span>, }
JavaScript
0
@@ -4702,16 +4702,25 @@ ssnames( +'rt-th', classNam @@ -4724,17 +4724,8 @@ Name -, 'rt-th' )%7D%0A
e4e2724f547b67c31a0a89897c92750db4ca6dc3
Use internal functions
lib/node_modules/@stdlib/ndarray/base/buffer/lib/main.js
lib/node_modules/@stdlib/ndarray/base/buffer/lib/main.js
/** * @license Apache-2.0 * * Copyright (c) 2018 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. */ 'use strict'; // MODULES // var bufferCtors = require( '@stdlib/ndarray/base/buffer-ctors' ); var allocUnsafe = require( '@stdlib/buffer/alloc-unsafe' ); var zeros = require( './zeros.js' ); // MAIN // /** * Returns a zero-filled contiguous linear ndarray data buffer. * * @param {string} dtype - data type * @param {NonNegativeInteger} size - buffer size * @returns {(Array|TypedArray|Buffer|null)} data buffer * * @example * var buf = buffer( 'float64', 3 ); * // returns <Float64Array>[ 0.0, 0.0, 0.0 ] */ function buffer( dtype, size ) { var ctor; var buf; var i; if ( dtype === 'generic' ) { buf = []; for ( i = 0; i < size; i++ ) { buf.push( 0 ); } return buf; } if ( dtype === 'binary' ) { return zeros( allocUnsafe( size ) ); } ctor = bufferCtors( dtype ); if ( ctor ) { return new ctor( size ); } return null; } // EXPORTS // module.exports = buffer;
JavaScript
0
@@ -806,16 +806,863 @@ s' );%0A%0A%0A +// FUNCTIONS //%0A%0A/**%0A* Returns a zero-filled generic array.%0A*%0A* @private%0A* @param %7BNonNegativeInteger%7D size - buffer size%0A* @returns %7BArray%7D zero-filled generic array%0A*/%0Afunction generic( size ) %7B%0A%09var buf;%0A%09var i;%0A%0A%09buf = %5B%5D;%0A%09for ( i = 0; i %3C size; i++ ) %7B%0A%09%09buf.push( 0 );%0A%09%7D%0A%09return buf;%0A%7D%0A%0A/**%0A* Returns a zero-filled binary buffer.%0A*%0A* @private%0A* @param %7BNonNegativeInteger%7D size - buffer size%0A* @returns %7BBuffer%7D zero-filled binary buffer%0A*/%0Afunction binary( size ) %7B%0A%09return zeros( allocUnsafe( size ) );%0A%7D%0A%0A/**%0A* Returns a zero-filled typed array.%0A*%0A* @private%0A* @param %7Bstring%7D dtype - data type%0A* @param %7BNonNegativeInteger%7D size - buffer size%0A* @returns %7B(TypedArray%7Cnull)%7D zero-filled typed array%0A*/%0Afunction typedarray( dtype, size ) %7B%0A%09var ctor = bufferCtors( dtype );%0A%09if ( ctor ) %7B%0A%09%09return new ctor( size );%0A%09%7D%0A%09return null;%0A%7D%0A%0A%0A // MAIN @@ -2009,38 +2009,8 @@ ) %7B%0A -%09var ctor;%0A%09var buf;%0A%09var i;%0A%0A %09if @@ -2041,85 +2041,30 @@ %7B%0A%09%09 -buf = %5B%5D;%0A%09%09for ( i = 0; i %3C size; i++ ) %7B%0A%09%09%09buf.push( 0 );%0A%09%09%7D%0A%09%09return buf +return generic( size ) ;%0A%09%7D @@ -2106,42 +2106,28 @@ urn -zeros( allocUnsafe +binary ( size - ) );%0A%09%7D%0A%09 ctor @@ -2126,94 +2126,40 @@ %09%7D%0A%09 -ctor = bufferCtors( dtype );%0A%09if ( ctor ) %7B%0A%09%09return new ctor( size );%0A%09%7D%0A%09return null +return typedarray( dtype, size ) ;%0A%7D%0A
7091cb60120862ffa60add119a628e7307a5c845
Change code for help videos
src/Umbraco.Web.UI.Client/src/views/common/dialogs/help.controller.js
src/Umbraco.Web.UI.Client/src/views/common/dialogs/help.controller.js
angular.module("umbraco") .controller("Umbraco.Dialogs.HelpController", function ($scope, $location, $routeParams, helpService, userService) { $scope.section = $routeParams.section; $scope.version = Umbraco.Sys.ServerVariables.application.version + " assembly: " + Umbraco.Sys.ServerVariables.application.assemblyVersion; if(!$scope.section){ $scope.section ="content"; } var rq = {}; rq.section = $scope.section; userService.getCurrentUser().then(function(user){ rq.usertype = user.userType; rq.lang = user.locale; if($routeParams.url){ rq.path = decodeURIComponent($routeParams.url); if(rq.path.indexOf(Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath) === 0){ rq.path = rq.path.substring(Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath.length); } if(rq.path.indexOf(".aspx") > 0){ rq.path = rq.path.substring(0, rq.path.indexOf(".aspx")); } }else{ rq.path = rq.section + "/" + $routeParams.tree + "/" + $routeParams.method; } helpService.findHelp(rq).then(function(topics){ $scope.topics = topics; }); helpService.findVideos(rq).then(function(videos){ $scope.videos = videos; angular.forEach($scope.videos, function (obj) { obj.thumbnail = obj.thumbnail.replace(/(\.[\w\d_-]+)$/i, '_thumb$1'); }); }); }); });
JavaScript
0
@@ -1379,174 +1379,8 @@ eos; -%0A%0A %09 angular.forEach($scope.videos, function (obj) %7B%0A %09 obj.thumbnail = obj.thumbnail.replace(/(%5C.%5B%5Cw%5Cd_-%5D+)$/i, '_thumb$1');%0A %09 %7D); %0A
1f6102db47dade5212088e6a5bd321a76c9d9306
clean missing examples
lib/clean.js
lib/clean.js
const { execSync } = require('child_process'); const glob = require('glob'); const { logger: parentLogger } = require('./logger'); const Task = require('./cli-spinner'); const logger = parentLogger.child('clean', 'clean'); module.exports = function clean(envs) { const task = new Task('clean'); const startTime = logger.infoTime('starting'); if (!envs) { execSync('rm -Rf lib-* test/node6'); task.succeed(); logger.infoSuccessTimeEnd(startTime, 'done.'); return; } const diff = glob.sync('lib*').filter(path => !envs.includes(path.substr('lib-'.length))); if (diff.length) { const log = `removing: ${diff.join(',')}`; const subtask = task.subtask(log); logger.warn(log); if (diff.some(diff => diff.startsWith('src'))) { throw new Error('Cannot contains src'); } execSync(`rm -Rf ${diff.join(' ')}`); subtask.done(); } task.succeed(); logger.infoSuccessTimeEnd(startTime, 'done.'); };
JavaScript
0.00031
@@ -394,16 +394,31 @@ st/node6 + examples/node6 ');%0A
dc95474af6ce8e0621aa3ce8fd98c4613670c8b2
Set connection state in sockConn for observability
src/client/js/lib/socketConn.js
src/client/js/lib/socketConn.js
/* -*- js2-basic-offset: 2; indent-tabs-mode: nil; -*- */ /* vim: set ft=javascript ts=2 et sw=2 tw=80; */ "use strict"; require("sockjs"); let Sock = window.SockJS, Genfun = require("genfun"), {addMethod} = Genfun, {clone, init} = require("./proto"), {partial, forEach, contains, without} = require("lodash"); let SocketConn = clone(), onOpen = new Genfun(), onMessage = new Genfun(), onClose = new Genfun(); addMethod(init, [SocketConn], function(conn, url) { conn.url = url; conn.observers = {}; conn.socket = new Sock(url); conn.socket.onopen = partial(notifyObservers, conn, onOpen); conn.socket.onmessage = partial(notifyObservers, conn, onMessage); conn.socket.onclose = partial(notifyObservers, conn, onClose); }); addMethod(onOpen, [], function() {}); addMethod(onMessage, [], function() {}); addMethod(onClose, [], function() {}); function notifyObservers(conn, handler, msg) { if (msg.type === "message") { let data = JSON.parse(msg.data), observers = conn.observers[data.namespace] || (console.warn("Unknown namespace: ", data.namespace), []); forEach(observers, function(obs) { return handler.call(conn, obs, data.data); }); } else { forEach(conn.observers, function(arr) { forEach(arr, function(obs) { return handler.call(conn, obs); }); }); } } function listen(conn, observer, namespace) { if (!conn.observers[namespace]) { conn.observers[namespace] = []; } if (!contains(conn.observers[namespace], observer)) { conn.observers[namespace].push(observer); } } function unlisten(conn, observer) { conn.observers = without(conn.observers, observer); } function send(conn, namespace, data) { conn.socket.send(JSON.stringify({namespace: namespace, data: data})); } module.exports = { SocketConn: SocketConn, onOpen: onOpen, onMessage: onMessage, onClose: onClose, listen: listen, unlisten: unlisten, send: send };
JavaScript
0
@@ -505,16 +505,53 @@ = url;%0A + conn.state = can.compute(%22close%22);%0A conn.o @@ -1274,16 +1274,42 @@ else %7B%0A + conn.state(msg.type);%0A forE
3bbada4e1d63432e470a683b300d57126c5635bf
remove console.log() [#718]
src/dependencies.js
src/dependencies.js
/* This Source Code Form is subject to the terms of the MIT license * If a copy of the MIT license was not distributed with this file, you can * obtain one at http://www.mozillapopcorn.org/butter-license.txt */ define([], function(){ var DEFAULT_DIRS = { "popcorn-js": "../external/popcorn-js", "css": "css" }, VAR_REGEX = /\{([\w\-\._]+)\}/, CSS_POLL_INTERVAL = 10; var DEFAULT_CHECK_FUNCTION = function(){ var index = 0; return function(){ return index++ > 0; }; }; return function( config ){ var _configDirs = config.dirs; function fixUrl( url ){ var match, replacement; while ( VAR_REGEX.test( url ) ) { match = VAR_REGEX.exec( url ); replacement = _configDirs[ match[ 1 ] ] || DEFAULT_DIRS[ match[ 1 ] ] || ""; console.log( match, replacement ); url = url.replace( match[0], replacement ); } return url.replace( "//", "/" ); } var _loaders = { js: function( url, exclude, callback, checkFn ){ checkFn = checkFn || DEFAULT_CHECK_FUNCTION(); url = fixUrl( url ); if( !checkFn() ){ var scriptElement = document.createElement( "script" ); scriptElement.src = url; scriptElement.type = "text/javascript"; document.head.appendChild( scriptElement ); scriptElement.onload = scriptElement.onreadystatechange = callback; } else{ callback(); } }, css: function( url, exclude, callback, checkFn ){ var scriptElement; checkFn = checkFn || function(){ if( !scriptElement ){ return false; } for( var i = 0; i < document.styleSheets.length; ++i ){ if( document.styleSheets[ i ].href === scriptElement.href ){ return true; } } return false; }; url = fixUrl( url ); if( !checkFn() ){ scriptElement = document.createElement( "link" ); scriptElement.rel = "stylesheet"; scriptElement.href = url; document.head.appendChild( scriptElement ); } var interval = setInterval(function(){ if( checkFn() ){ clearInterval( interval ); callback(); } }, CSS_POLL_INTERVAL ); } }; function generateLoaderCallback( items, callback ){ var loaded = 0; return function(){ ++loaded; if( loaded === items.length ){ if( callback ){ callback(); } } }; } function generateNextFunction( items, callback ){ var index = 0; function next(){ if( index === items.length ){ callback(); } else{ Loader.load( items[ index++ ], next ); } } return next; } var Loader = { load: function( items, callback, ordered ){ if( items instanceof Array && items.length > 0 ){ var onLoad = generateLoaderCallback( items, callback ); if( !ordered ){ for( var i = 0; i < items.length; ++i ){ Loader.load( items[ i ], onLoad ); } } else { var next = generateNextFunction( items, callback ); next(); } } else { var item = items; if( _loaders[ item.type ] ){ if( item.url ){ _loaders[ item.type ]( item.url, item.exclude, callback, item.check ); } else{ throw new Error( "Attempted to load resource without url." ); } } else { throw new Error( "Loader type " + item.type + " not found! Attempted: " + item.url ); } } } }; return Loader; }; });
JavaScript
0
@@ -828,51 +828,8 @@ %22%22;%0A - console.log( match, replacement );%0A
1c9edd52c9bb2ba8b57f4a75eb974686a2fea55c
Disable popup notifications
js/prompt.js
js/prompt.js
"use strict"; var FRAME_ID = "#eyebrowse-frame"; var TEMPLATE_HTML = {}; // only request the bubble every BUBBLE_THRESHOLD milliseconds var BUBBLE_THRESHOLD = 5 * 60 * 1000; // 5 minutes var LAST_BUBBLE = Date.now() - BUBBLE_THRESHOLD; // we should initially show the bubble function truncate(str, length) { if (str.length > length) { return str.substring(0, length); } else { return str; } } function createTrackPrompt(url) { return getPromptTemplate("#track-prompt", { "url": new URL(url).hostname, }); } function createLoginPrompt() { return getPromptTemplate("#login-prompt"); } function createBubblePrompt(data, baseUrl) { if (data.active_users.length === 0 && data.message === "") { return null; } var msg = truncate(data.message, 51); if (data.user_url === "") { msg = truncate(data.message, 78); } msg = createMentionTag(msg); var template = getPromptTemplate("#bubble-prompt", { "msg": msg, "user_url": data.user_url, "username": data.username, "about_message": data.about_message, "users": data.active_users }); var images = template.find(".eyebrowse-bubble-user-icon"); for (var i = 0; i < images.length; i++) { $(images[i]).attr("src", data.active_users[i].pic_url); } return template; } function inDefaultBlacklist(url) { var hostname = new URL(url).hostname; if (hostname.indexOf('google.com') > -1) { return true; } return false; } /* Call the eyebrowse server to get an iframe with a prompt Can either be a login or track type prompt. */ function setup(baseUrl, promptType, user, url, protocol) { if ($(FRAME_ID).length) { $(FRAME_ID).css("z-index", 999999999); return; } var frameHtml; if (promptType === "trackPrompt") { if (inDefaultBlacklist(url)) return; frameHtml = createTrackPrompt(url); addFrame(frameHtml); chrome.extension.sendMessage(JSON.stringify({ "action": "nag", "url": window.document.URL })); $("#eyebrowse-allow-btn").click(function() { $(FRAME_ID).remove(); var msg = { "action": "filterlist", "type": "whitelist", "url": url }; chrome.extension.sendMessage(JSON.stringify(msg)); }); $("#eyebrowse-deny-btn").click(function() { $(FRAME_ID).remove(); var msg = { "action": "filterlist", "type": "blacklist", "url": url }; chrome.extension.sendMessage(JSON.stringify(msg)); }); } else if (promptType === "loginPrompt") { frameHtml = createLoginPrompt(); addFrame(frameHtml); $("#eyebrowse-ignore-btn").click(function() { $(FRAME_ID).remove(); var msg = { "action": "ignore" }; chrome.extension.sendMessage(JSON.stringify(msg)); }); } else if (promptType === "bubbleInfo" && protocol === "http:") { // TODO fix with ssl certs for eyebrowse if (LAST_BUBBLE !== -1 && Date.now() - LAST_BUBBLE >= BUBBLE_THRESHOLD) { LAST_BUBBLE = Date.now(); $.ajax({ url: baseUrl + "/ext/bubbleInfo/", type: "POST", data: { "url": url, "csrfmiddlewaretoken": user.csrf, }, success: function(data) { frameHtml = createBubblePrompt(data, baseUrl); addFrame(frameHtml); }, error: function(data) { LAST_BUBBLE = -1; } }); } } } /* * Add the prompt css to the main page */ function addStyle() { if (!$("#eyebrowse-frame-css").length) { var url = chrome.extension.getURL("../css/prompt.css"); var link = $("<link id='eyebrowse-frame-css' href='" + url + "' rel='stylesheet' />")[0]; (document.head || document.body).appendChild(link); } } /* * Helper function which adds a popup frame to the page */ function addFrame(frameHtml) { if (frameHtml === null) { return; } addStyle(); $("body").append(frameHtml); // Remove the element after it fades out. The fading & delay is taken care by CSS $(FRAME_ID).bind("animationend webkitAnimationEnd", function(evt) { if (evt.originalEvent.animationName === "fade") { this.parentNode.removeChild(this); } }); $("#eyebrowse-close-btn").click(function() { $(FRAME_ID).remove(); }); } chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { var protocol = window.location.protocol; var url = document.URL; var action = request.action; if (action === "prompt") { setup(request.baseUrl, request.type, request.user, url, protocol); } });
JavaScript
0.000002
@@ -4984,16 +4984,52 @@ %0A + // disable notifications%0A // setup(r
af60b6f1982acaad51b689a80d21828ff0d04d60
fix sorting after duplication
web/app/assets/javascripts/formeditor/duplicate.js
web/app/assets/javascripts/formeditor/duplicate.js
/* Implements functions that allow duplicating sections and questions. * It works by copying the DOM of that element and adjusting the IDs * for that question/section to an unused one. */ /* @public * Shows/hides the duplication buttons on sections/questions. * @param enable if the buttons should be shown/hidden */ FormEditor.prototype.toggleDuplicating = function(enable) { enable = enable === undefined || enable === null ? $("#duplicate").is(":visible") : enable; if(enable) { $("#duplicate").hide(); $(".duplicate, #cancel-duplicate").show(); } else { $("#duplicate").show(); $(".duplicate, #cancel-duplicate").hide(); } }; /* @public * Duplicates Question. * @param link DOM reference to an element inside the question that * should be duplicated */ FormEditor.prototype.duplicateQuestion = function(link) { var q = $(link).parents(".question"); this.addUndoStep("duplicating question " + q.children("h6").data("db-column")); this.duplicate(q, "Question", "questions"); }; /* @public * Duplicates Section. * @param link DOM reference to an element inside the section that * should be duplicated */ FormEditor.prototype.duplicateSection = function(link) { var s = $(link).parents(".section"); this.addUndoStep("duplicating section " + s.children("h5").data("title")); this.duplicate(s, "Section", "sections"); }; /* @private * Handles copying the DOM element as well as replacing the old IDs with * unused ones. * @param DOM element which should be copied * @param Type/AbstractForm Class of equivalent of DOM element being * copied. Required to determine correct path from the hidden * element (…/rubyobject). * @param Name of the part in the path that preceeds the n-th question * or section. Usually multiple and lower-case of type. E.g. * /pages/0/sections/1/questions/2/ → "sections" if a section * is to be duplicated */ FormEditor.prototype.duplicate = function(elm, type, pathGroup) { var r = new RegExp("/" + pathGroup + "/([0-9]+)/"); // find new, not yet used id var lastPath = elm.parent().find("[type=hidden][value="+type+"][id^='/']").last().attr("id").match(r), oldPath = "/" + pathGroup + "/" + lastPath[1] + "/", pos = parseInt(lastPath[1])+1; while(true) { newPath = "/" + pathGroup + "/" + pos + "/"; var check = document.getElementById(lastPath[0].replace(oldPath, newPath)); if(check === null) break; pos++; } // clone and update id/for attributes var newElm = elm.clone(); newElm.find("[id^='/']").each(function(pos, elm) { $(elm).attr("id", $(elm).attr("id").replace(r, newPath)); }); newElm.find("[for^='/']").each(function(pos, elm) { $(elm).attr("for", $(elm).attr("for").replace(r, newPath)); }); newElm.insertAfter(elm); this.checkDuplicateIds(); };
JavaScript
0.00002
@@ -2833,16 +2833,63 @@ r(elm);%0A + $(%22.sortable-question%22).sortable(%22refresh%22);%0A this.c
364c9f5e3738b42fd48e5dbbfc936753739f27a4
add getTask
scripts/services/task.js
scripts/services/task.js
'use strict'; app.factory('Task', function(FURL, $firebase, Auth) { var ref = new Firebase(FURL); var tasks = $firebase(ref.child('task')).$asArray(); var user = Auth.user; }
JavaScript
0.000001
@@ -176,5 +176,136 @@ r;%0A%0A -%7D +%0A%09var Task = %7B%0A%09%09all: tasks,%0A%0A%09%09getTask: function(taskId) %7B%0A%09%09%09return $firebase(ref.child('tasks').child(taskId));%0A%09%09%7D,%0A%09%09%0A%09%7D;%0A%0A%0A%7D);
e09b38b0317575fce51957b019ccc6e526c3ee53
fix reply instead of embed
src/commands/Ondemand/Arcane.js
src/commands/Ondemand/Arcane.js
'use strict'; const Command = require('../../Command.js'); const EnhancementEmbed = require('../../embeds/EnhancementEmbed.js'); const arcanes = require('../../resources/arcanes.json'); /** * Displays the response time for the bot and checks Warframe's servers to see if they are up */ class Arcane extends Command { /** * Constructs a callable command * @param {Genesis} bot The bot object */ constructor(bot) { super(bot, 'warframe.misc.arcane', 'arcane', 'Get information about an Arcane Enhancement'); this.regex = new RegExp('^arcane(.+)?', 'i'); this.usages = [ { description: 'Get information about an Arcane Enhancement', parameters: ['enhancement name'], }, ]; } /** * Run the command * @param {Message} message Message with a command to handle, reply to, * or perform an action based on parameters. */ run(message) { let arcane = message.strippedContent.match(this.regex)[1]; if (arcane) { arcane = arcane.trim().toLowerCase(); arcanes.forEach((enhancement) => { if (new RegExp(enhancement.regex, 'ig').test(arcane)) { this.messageManager.reply(message, new EnhancementEmbed(enhancement), true, false); } }); } else { this.messageManager.embed(message, new EnhancementEmbed(undefined), true, false); } } } module.exports = Arcane;
JavaScript
0
@@ -1185,21 +1185,21 @@ Manager. -reply +embed (message
abb7fab6fe426539a422b87bb304e3c451c0b9c1
Migrate to bigpipe 0.6
client.js
client.js
pipe.once('dependencies::initialise', function init(pagelet) { 'use strict'; // // We don't need to have any other information from the pagelet then the // placeholders/elements that contain our packages-pagelet placeholders. // pagelet = $(pagelet.placeholders); // // Show more rows when we click on the table footer. // pagelet.on('click', 'tfoot.more a', function click(e) { e.preventDefault(); var button = $(this); button.parents('table').find('tr.gone').fadeIn(); button.parents('tfoot').fadeOut(); }); });
JavaScript
0.000001
@@ -21,17 +21,16 @@ ies: -: initiali se', @@ -25,17 +25,17 @@ initiali -s +z e', func
5d5feee5c694c6583eedec69f1a9ee8795431eec
correct typo
src/app/components/msp/application/confirmation/i18n/data/en/index.js
src/app/components/msp/application/confirmation/i18n/data/en/index.js
module.exports = { pageTitle: '<i class="fa fa-check success" aria-hidden="true"></i> Your application has been submitted.', secondTitle: 'What happens next', nextStep1: "<strong>Important:</strong> Keep your reference number – write it down, or <a>print this page</a> for your records", nextStep2: "Allow 21 business days for your application to be processed", nextStep3: "Once your application is processed, you will get a letter that says whether you’re eligibile for MSP. You may have a <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents/eligibility-and-enrolment/how-to-enrol/coverage-wait-period' target='_blank'>wait period</a>", nextStep4: "Once you receive your first bill, you can get your <a href='http://www2.gov.bc.ca/gov/content/governments/government-id/bc-services-card' target='blank'>BC Services Card</a>. Visit <a href='http://www.icbc.com/Pages/default.aspx'target='_blank'>ICBC <i class='fa fa-external-link' aria-hidden='true'></i></a> or <a href='http://www2.gov.bc.ca/gov/content/governments/organizational-structure/ministries-organizations/ministries/technology-innovation-and-citizens-services/servicebc' target='blank'>Service BC</a> to get one", nextStep5: "When you get your BC Services Card, register for the <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/pharmacare-for-bc-residents/who-we-cover/fair-pharmacare-plan' target='_blank'>FairPharmacare plan</a>. It can help with the cost of prescription drugs and some medical supplies. Registration is free and there are no premiums to pay", nextStep6: "Low income individuals or families who are Canadian or permanent residents qualify for help to pay the monthly fee. <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents/premiums/regular-premium-assistance' target='_blank'>Find out about premium assistance</a", nextStep7: "Keep your personal information up to date. <a href='http://www2.gov.bc.ca/gov/content/governments/government-id/bc-services-card/change-your-personal-information' target='_blank'>Change your name, address or gender</a>", nextStep8: "Living outside the province for more than six months could cause your MSP enrollment to be cancelled. <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents/eligibility-and-enrolment/are-you-eligible' target='_blank'>Learn more about eligibility for MSP</a>", nextStep9: "If you have questions, <a href='http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us' target='_blank'>contact Health Insurance BC</a>" }
JavaScript
0.999967
@@ -466,17 +466,16 @@ e eligib -i le for M
5d9a81b97376bbbb026d0992732fd3f1c134be22
Add `defer` tag to universal script tags, fixes #13
library/webpack-loaders/react-universal-server-loader.js
library/webpack-loaders/react-universal-server-loader.js
const { relative } = require('path') module.exports = ReactUniversalServerLoader function ReactUniversalServerLoader(source, map) { const filename = relative(this.options.context, this.resourcePath) const importPath = relative(this.context, this.resourcePath) const id = filename.replace(/[/\.]/g, '_') return createServerCode({ importPath, scriptSrc: '/' + filename, id }) } function createServerCode({ importPath, scriptSrc, id }) { return `|import Component from './${importPath}' |import { renderToString } from 'react-dom/server' | |export default function WrapWithScript(props) { | const content = renderToString(<Component id='${id}' {...props} />) | return ( | <div> | <div id='${id}' data-props={JSON.stringify(props)} dangerouslySetInnerHTML={{ __html: content }}></div> | <script src='${scriptSrc}'></script> | </div> | ) |} |`.split(/^[ \t]*\|/m).join('') }
JavaScript
0
@@ -892,16 +892,22 @@ %3Cscript +defer src='$%7Bs
551fdff3a3568214e4084bec905963fdb1f0a286
Add alert
src/main/webapp/servlet.js
src/main/webapp/servlet.js
/**Copyright 2019 Google LLC 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 https://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.*/ // call docCount servlet for no of documents in a index const getCount = async (index, fileType) => { const params = new URLSearchParams(); params.append(FILE_NAME, index); params.append(FILE_TYPE, fileType); const response = await fetch(GET_COUNT, { method: POST, body: params }); const count = await response.json(); return count; } // call stackTrace servlet for stack trace of a error const callStackTraceServlet = async (logLineNo, fileName) => { const params = new URLSearchParams(); params.append(LOG_LINE_NUMBER, logLineNo); params.append(FILE_NAME, fileName); const response = await fetch(STACK_TRACE, { method: POST, body: params }); const stackTrace = await response.json(); return stackTrace; } // fetch logs/errors/search results from pagination servlet const callPaginationServlet = async(fileName, fileType, searchString, pageSpecs) => { const params = new URLSearchParams(); params.append(START, pageSpecs.START); params.append(SIZE, pageSpecs.SIZE); params.append(SEARCH_STRING, searchString); params.append(FILE_TYPE, fileType); params.append(FILE_NAME, fileName); const response = await fetch(PAGINATION, { method: POST, body: params }); const fetchedData = await response.json(); return fetchedData; } // delete all the const deleteIndices = async() => {     await fetch(DELETE, {         method: POST }); }
JavaScript
0.000002
@@ -2023,10 +2023,36 @@ OST%0A%7D);%0A + alert(%22Data Deleted%22); %0A%7D
41f8aa268d296b318f0ee241bd6304328905f964
Use console.error instead of alert if XMLHTTP cannot be created
client.js
client.js
var map = null; var legend = document.getElementById('legend'); function initMap() { // Create a map object and specify the DOM element for display. map = new google.maps.Map(document.getElementById('map'), { center: { lat: 38.922239, lng: -95.794675 }, disableDefaultUI: true, styles: styles, zoom: 5 }); map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend); } var styles = [{ "elementType": "geometry", "stylers": [{ "color": "#f5f5f5" }] }, { "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "elementType": "labels.text.fill", "stylers": [{ "color": "#616161" }] }, { "elementType": "labels.text.stroke", "stylers": [{ "color": "#f5f5f5" }] }, { "featureType": "administrative.land_parcel", "stylers": [{ "visibility": "off" }] }, { "featureType": "administrative.land_parcel", "elementType": "labels.text.fill", "stylers": [{ "color": "#bdbdbd" }] }, { "featureType": "administrative.neighborhood", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#eeeeee" }] }, { "featureType": "poi", "elementType": "labels.text", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "labels.text.fill", "stylers": [{ "color": "#757575" }] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [{ "color": "#e5e5e5" }] }, { "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [{ "color": "#9e9e9e" }] }, { "featureType": "road", "stylers": [{ "visibility": "off" }] }, { "featureType": "road", "elementType": "geometry", "stylers": [{ "color": "#ffffff" }] }, { "featureType": "road", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "road.arterial", "elementType": "labels.text.fill", "stylers": [{ "color": "#757575" }] }, { "featureType": "road.highway", "elementType": "geometry", "stylers": [{ "color": "#dadada" }] }, { "featureType": "road.highway", "elementType": "labels.text.fill", "stylers": [{ "color": "#616161" }] }, { "featureType": "road.local", "elementType": "labels.text.fill", "stylers": [{ "color": "#9e9e9e" }] }, { "featureType": "transit.line", "elementType": "geometry", "stylers": [{ "color": "#e5e5e5" }] }, { "featureType": "transit.station", "elementType": "geometry", "stylers": [{ "color": "#eeeeee" }] }, { "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#c9c9c9" }] }, { "featureType": "water", "elementType": "labels.text", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels.text.fill", "stylers": [{ "color": "#9e9e9e" }] } ]; var pointStyles = { 'view': { 'color': '#000000', 'fillColor': '#000000', 'fillOpacity': 0.5, 'radius': 35000, 'pane': 'overlayPane' }, 'commitment': { 'color': 'red', 'fillColor': '#f03', 'fillOpacity': 0.5, 'radius': 75000, 'pane': 'markerPane' } }; var pageviews = 0; var commitments = 0; var lastUpdated = null; // Displays the points data provided. function displayPoints(data) { for (var i = 0; i < data.length; i++) { // Create LatLng object var LatLng = new google.maps.LatLng({ lat: data[i].Coordinates[0], lng: data[i].Coordinates[1] }); var circle = new google.maps.Circle({ fillColor: pointStyles[data[i].Action].fillColor, fillOpacity: pointStyles[data[i].Action].fillOpacity, map: map, center: LatLng, radius: pointStyles[data[i].Action].radius, strokeWeight: 0 }); if (data[i].Action === 'view') { pageviews++; } if (data[i].Action === 'commitment') { commitments++; } } document.getElementById("pageviews").innerText = pageviews; document.getElementById("commitments").innerText = commitments; } function responseCheck() { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { var response = JSON.parse(httpRequest.responseText); displayPoints(response); } else { } } } // Updates map with latest real time data function updateMap() { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } var lastUpdatedString = ''; if (lastUpdated != null) { lastUpdatedString = '?lastupdated=' + lastUpdated; } lastUpdated = new Date() / 1000; // Send API GET request for data httpRequest.onreadystatechange = responseCheck; httpRequest.open('GET', '/rest/live/read' + lastUpdatedString, true); httpRequest.send(); } // https://gist.github.com/KartikTalwar/2306741 function refreshData() { x = 3; // 3 Seconds updateMap(); setTimeout(refreshData, x * 1000); } refreshData(); // execute function
JavaScript
0.000001
@@ -4790,13 +4790,21 @@ -alert +console.error ('Gi
d7097661af13bc30d32c6ca2cee6cdbb40f991b9
fix app to App
src/main.js
src/main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import VueRouter from 'vue-router' import Buefy from 'buefy' import db from 'baqend' import App from './app' import router from './router' db.connect('restless-bolt-1').then(() => { Vue.use(VueRouter, Buefy.default) /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<app/>', components: { App } }) })
JavaScript
0.000198
@@ -259,17 +259,17 @@ from './ -a +A pp'%0Aimpo
8216a0577d58c69b97f46f29994aa3d70256e74c
fix error calculating starting bg position in FF with 'centeredStart' calcType !BUGFIX
src/ui/ParallaxBackground.js
src/ui/ParallaxBackground.js
/* global define, window */ define(['jquery', 'tmclasses/tmclasses'], function(jQuery, tmclasses){ var __ParallaxBackground = tmclasses.create({ init: function(){ this.__parent(arguments); if(this.elm){ this.constructor.window.on('load resize scroll', jQuery.proxy(this._changeHandler, this)); } } ,properties: { elm: undefined ,calcType: 'centeredStart' ,movementRatio: 0.8 ,_changeHandler: function(){ var _viewportHeight = this.constructor.window.height(); var _viewportTop = this.constructor.window.scrollTop(); var _elmHeight = this.elm.outerHeight(); var _elmTop = this.elm.offset().top; var _range = _elmHeight + _viewportHeight; var _calcOffset = _elmTop - _viewportHeight; var _diff = -((_viewportTop - _calcOffset) - _range); var _bgPosition; if(_diff > _range){ _bgPosition = 100; }else if(_diff < 0){ _bgPosition = 0; }else{ _bgPosition = (_diff / _range) * 100; } switch(this.calcType){ case 'centered': _bgPosition = 50 + (_bgPosition - 50) * this.movementRatio; break; case 'centeredStart': if(typeof this._startOffset === 'undefined'){ var _startingPosition = this.elm.css('background-position-y'); if(_startingPosition.indexOf('%') !== -1){ _startingPosition = parseInt(_startingPosition,10); } this._startOffset = -1 * (50 + (_bgPosition - 50) * this.movementRatio - _startingPosition); } _bgPosition = 50 + (_bgPosition - 50) * this.movementRatio + this._startOffset; break; } this.elm.css('background-position', 'center ' + _bgPosition + '%'); } ,_startOffset: undefined } ,statics: { window: jQuery(window) } }); return __ParallaxBackground; });
JavaScript
0
@@ -1241,16 +1241,258 @@ on-y');%0A +%09%09%09%09%09%09%09//-- FF doesn't return the 'background-position-y', derive from regular 'background-position'%0A%09%09%09%09%09%09%09if(typeof _startingPosition === 'undefined')%7B%0A%09%09%09%09%09%09%09%09_startingPosition = this.elm.css('background-position').split(' ')%5B1%5D;%0A%09%09%09%09%09%09%09%7D%0A %09%09%09%09%09%09%09i
d3d46137ffedae3e825d896bc9c30e9f41a7c1c9
Tweak hot reload setup.
src/make-webpack-config.js
src/make-webpack-config.js
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var AdvancedVariables = require('postcss-advanced-variables'); var merge = require('webpack-merge'); var prettyjson = require('prettyjson'); var config = require('../src/utils/config'); module.exports = function(env) { var isProd = env === 'production'; var includes = [ __dirname, config.rootDir ]; var codeMirrorPath = path.join(__dirname, '../node_modules/react-codemirror/node_modules/codemirror'); var webpackConfig = { output: { path: config.styleguideDir, filename: 'build/bundle.js' }, resolve: { root: [ __dirname ], alias: { 'codemirror': codeMirrorPath } }, resolveLoader: { modulesDirectories: [ 'loaders', 'node_modules' ] }, plugins: [ new HtmlWebpackPlugin({ title: config.title, template: './src/templates/index.html', inject: true }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(env) } }) ], module: { loaders: [ { test: /\.js$/, include: includes, loader: 'babel' } ] }, postcss: function() { return [ AdvancedVariables ]; } }; var entryScript = './src/index'; if (isProd) { webpackConfig = merge(webpackConfig, { entry: [ entryScript ], devtool: false, debug: false, cache: false, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, output: { comments: false }, mangle: false }), new webpack.optimize.DedupePlugin(), new ExtractTextPlugin('build/styles.css', { allChunks: true }) ], module: { loaders: [ { test: /\.css$/, include: codeMirrorPath, loader: ExtractTextPlugin.extract('style', 'css') }, { test: /\.css$/, include: includes, loader: ExtractTextPlugin.extract('style', 'css?modules&-minimize&importLoaders=1!postcss') } ] } }); } else { webpackConfig = merge(webpackConfig, { entry: [ 'webpack-hot-middleware/client', entryScript ], debug: true, cache: true, devtool: 'eval-source-map', stats: { colors: true, reasons: true }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.css$/, include: codeMirrorPath, loader: 'style!css' }, { test: /\.css$/, include: includes, loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss' } ] } }); } if (config.updateWebpackConfig) { webpackConfig = config.updateWebpackConfig(webpackConfig, env); } if (config.verbose) { console.log(); console.log('Using Webpack config:'); console.log(prettyjson.render(webpackConfig)); console.log(); } return webpackConfig; };
JavaScript
0
@@ -2349,32 +2349,81 @@ ,%0A%09%09%09plugins: %5B%0A +%09%09%09%09new webpack.optimize.OccurenceOrderPlugin(),%0A %09%09%09%09new webpack.
264a4ea9ad9697ff8468b7350d5a04629ee0f655
fix gulp
gulpfile.js
gulpfile.js
'use strict'; var path = require('path'); var gulp = require('gulp'); var eslint = require('gulp-eslint'); var excludeGitignore = require('gulp-exclude-gitignore'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var nsp = require('gulp-nsp'); var plumber = require('gulp-plumber'); var coveralls = require('gulp-coveralls'); gulp.task('static', function () { return gulp.src('generators/index.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('nsp', function (cb) { nsp({package: path.resolve('package.json')}, cb); }); gulp.task('pre-test', function () { return gulp.src('generators/index.js') .pipe(excludeGitignore()) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()); }); gulp.task('test', ['pre-test'], function (cb) { var mochaErr; gulp.src('test/**/*.js') .pipe(plumber()) .pipe(mocha({reporter: 'spec'})) .on('error', function (err) { mochaErr = err; }) .pipe(istanbul.writeReports()) .on('end', function () { cb(mochaErr); }); }); gulp.task('watch', function () { gulp.watch(['generators/**/*.js', 'test/**'], ['test']); }); gulp.task('coveralls', ['test'], function () { if (!process.env.CI) { return; } return gulp.src(path.join(__dirname, 'coverage/lcov.info')) .pipe(coveralls()); }); gulp.task('prepublish', ['nsp']); gulp.task('default', ['static', 'test', 'coveralls']);
JavaScript
0.000002
@@ -1333,23 +1333,16 @@ %0A %7D%0A%0A -return gulp.src @@ -1346,29 +1346,8 @@ src( -path.join(__dirname, 'cov @@ -1352,16 +1352,19 @@ overage/ +**/ lcov.inf @@ -1366,17 +1366,16 @@ v.info') -) %0A .pi
0c9cf4de35ee5ae57c8201d9e18753c457e30146
Generalize parameter name in validateRelationship function
test/commonValidations.js
test/commonValidations.js
/** * Validate the composition of a path, course, lesson identifier * * @param {Object} jsonData - JSON object containing the data elements. This must be formatted as {"<id>": {...id: "<id>"...}...} * @returns {String[]} invalidIds - Array of invalid id's. Those containing something other than lowercase letters and digits. */ const validateIdComposition = (jsonData) => { const invalidIds = []; Object.keys(jsonData).forEach((itemId) => { if (!itemId.match(/^[0-9a-z]+$/)) { invalidIds.push(itemId); } }); return invalidIds; }; /** * Validate the length of a path, course, lesson identifier * * @param {Object} jsonData - JSON object containing the data elements. This must be formatted as {"<id>": {...id: "<id>"...}...} * @returns {String[]} invalidIds - Array of id's exceeding 16 characters */ const validateIdLength = (jsonData) => { const invalidIds = []; Object.keys(jsonData).forEach((itemId) => { if (itemId.length > 16) { invalidIds.push(itemId); } }); return invalidIds; }; /** * Validate a relationship between two data elements. * * @param {String} childAttrNm - Attribute name in the child JSON object * @param {Object} childJSON - JSON object containing the child data elements. This must be formatted as {"<id>": {...id: "<id>"...}...} * @param {String} parentAttrNm - Attribute name in the child JSON object * @param {Object} parentJSON - JSON object containing the parent data elements. This must be formatted as {"<id>": {...id: "<id>"...}...} * @returns {String[]} invalidIds - Array of id's exceeding 16 characters */ const validateRelationship = (childAttrNm, childJSON, parentAttrNm, parentJSON) => { const invalidIds = []; Object.values(childJSON).forEach((currentPath) => { currentPath[childAttrNm].forEach((itemId) => { if (parentJSON[itemId] === undefined) { invalidIds.push([currentPath[parentAttrNm], itemId]); } }); }); return invalidIds; }; export { validateIdComposition, validateIdLength, validateRelationship };
JavaScript
0.000021
@@ -1746,26 +1746,27 @@ rEach((c -urrentPath +hildElement ) =%3E %7B%0A @@ -1769,26 +1769,27 @@ %7B%0A c -urrentPath +hildElement %5BchildAt @@ -1892,18 +1892,19 @@ h(%5Bc -urrentPath +hildElement %5Bpar
152a0ba7c7f83896f8c69f7c6a12387e1ff8accc
add fill method. which fill DOM cube sides with appropriate values
script.js
script.js
function Cube (element_id) { var _DOM = document.getElementById(element_id); this.DOM = _DOM; var sides = ['front','top','bottom','back','left','right']; for (i in sides) {this[sides[i]]=['z','-y','y','-z','-x','x'][i]} return this; } var cube = new Cube('cube3d') // main cube object
JavaScript
0.000006
@@ -28,17 +28,16 @@ %7B%0D%0A%09var -_ DOM = do @@ -84,17 +84,16 @@ s.DOM = -_ DOM;%0D%0A%0D%0A @@ -226,16 +226,251 @@ %5Bi%5D%7D%0D%0A%0D%0A +%09function fill () %7B // fill DOM cube sides with appropriate values%0D%0A%09%09for (i in sides) %7B%0D%0A%09%09%09var element = document.getElementById(sides%5Bi%5D);%0D%0A%09%09%09var value = this%5Bsides%5Bi%5D%5D;%0D%0A%09%09%09element.innerHTML=value;%0D%0A%09%09%7D%0D%0A%09%7D%0D%0A%09this.fill = fill;%0D%0A%0D%0A %09return @@ -531,8 +531,22 @@ object%09 +%0D%0Acube.fill();
44cb8522ebff01f93cfc0d9aa5172dd1ce800b76
document timeout property of enyo.Async.js
source/ajax/Async.js
source/ajax/Async.js
/** _enyo.Async_ is the base kind for handling asynchronous operations. _enyo.Async_ is an **Object**, not a **Component**; thus, you may not declare an _Async_ in a _components_ block. If you want to use _Async_ as a component, you should probably be using <a href="#enyo.WebService">enyo.WebService</a> instead. An Async object represents a task that has not yet completed. You may attach callback functions to an Async, to be called when the task completes or encounters an error. More information on _Async_ and its usage is available in the <a href="https://github.com/enyojs/enyo/wiki/Async">Async documentation</a> in the Enyo Developer Guide. */ enyo.kind({ name: "enyo.Async", kind: enyo.Object, //* @protected failed: false, context: null, constructor: function() { this.responders = []; this.errorHandlers = []; }, accumulate: function(inArray, inMethodArgs) { var fn = (inMethodArgs.length < 2) ? inMethodArgs[0] : enyo.bind(inMethodArgs[0], inMethodArgs[1]); inArray.push(fn); }, //* @public /** Registers a response function. First parameter is an optional this context for the response method. Second (or only) parameter is the function object. */ response: function(/* [inContext], inResponder */) { this.accumulate(this.responders, arguments); return this; }, /** Registers an error handler. First parameter is an optional this context for the response method. Second (or only) parameter is the function object. */ error: function(/* [inContext], inResponder */) { this.accumulate(this.errorHandlers, arguments); return this; }, //* @protected route: function(inAsync, inValue) { var r = enyo.bind(this, "respond"); inAsync.response(function(inSender, inValue) { r(inValue); }); var f = enyo.bind(this, "fail"); inAsync.error(function(inSender, inValue) { f(inValue); }); inAsync.go(inValue); }, handle: function(inValue, inHandlers) { var r = inHandlers.shift(); if (r) { if (r instanceof enyo.Async) { this.route(r, inValue); } else { // handler can return a new 'value' var v = enyo.call(this.context || this, r, [this, inValue]); // ... but only if it returns something other than undefined v = (v !== undefined) ? v : inValue; // next handler (this.failed ? this.fail : this.respond).call(this, v); } } }, startTimer: function() { this.startTime = enyo.now(); if (this.timeout) { this.timeoutJob = setTimeout(enyo.bind(this, "timeoutComplete"), this.timeout); } }, endTimer: function() { if (this.timeoutJob) { this.endTime = enyo.now(); clearTimeout(this.timeoutJob); this.timeoutJob = null; this.latency = this.endTime - this.startTime; } }, timeoutComplete: function() { this.timedout = true; this.fail("timeout"); }, //* @protected //* Called as part of the async implementation, triggers the handler chain. respond: function(inValue) { this.failed = false; this.endTimer(); this.handle(inValue, this.responders); }, //* @public //* Can be called from any handler to trigger the error chain. fail: function(inError) { this.failed = true; this.endTimer(); this.handle(inError, this.errorHandlers); }, //* Called from an error handler, this method clears the error // condition and resumes calling handler methods. recover: function() { this.failed = false; }, //* Starts the async activity. Overridden in subkinds. go: function(inValue) { enyo.asyncMethod(this, function() { this.respond(inValue); }); return this; } });
JavaScript
0
@@ -666,12 +666,8 @@ de.%0A -%09%0A%0A%0A */%0Ae @@ -718,16 +718,193 @@ Object,%0A +%09published: %7B%0A%09%09/**%0A%09%09%09if set to a non-0 value, this is the number of milliseconds to%0A%09%09%09wait after the _go_ call before failing with the %22timeout%22 error.%0A%09%09*/%0A%09%09timeout: 0%0A%09%7D,%0A %09//* @pr
8ac5517b8a96e0171d359734acaabf5e182ebf6c
Fix undefined variable
website/addons/github/static/github-node-cfg.js
website/addons/github/static/github-node-cfg.js
'use strict'; var $ = require('jquery'); var bootbox = require('bootbox'); var $osf = require('js/osfHelpers'); var GithubConfigHelper = (function() { var updateHidden = function(val) { var repoParts = val.split('/'); $('#githubUser').val($.trim(repoParts[0])); $('#githubRepo').val($.trim(repoParts[1])); }; var displayError = function(msg) { $('#addonSettingsGithub').find('.addon-settings-message') .text('Error: ' + msg) .removeClass('text-success').addClass('text-danger') .fadeOut(100).fadeIn(); }; var createRepo = function() { var $elm = $('#addonSettingsGithub'); var $select = $elm.find('select'); bootbox.prompt('Name your new repo', function(repoName) { // Return if cancelled if (repoName === null) { return; } if (repoName === '') { displayError('Your repo must have a name'); return; } $osf.postJSON( '/api/v1/github/repo/create/', {name: repoName} ).done(function(response) { var repoName = response.user + ' / ' + response.repo; $select.append('<option value="' + repoName + '">' + repoName + '</option>'); $select.val(repoName); updateHidden(repoName); }).fail(function() { displayError('Could not create repository'); }); }); }; $(document).ready(function() { $('#githubSelectRepo').on('change', function() { var value = $(this).val(); if (value) { updateHidden(value); } }); $('#githubCreateRepo').on('click', function() { createRepo(); }); $('#githubImportToken').on('click', function() { $osf.postJSON( nodeApiUrl + 'github/user_auth/', {} ).done(function() { window.location.reload(); }).fail( $osf.handleJSONError ); }); $('#githubCreateToken').on('click', function() { window.location.href = nodeApiUrl + 'github/oauth/'; }); $('#githubRemoveToken').on('click', function() { bootbox.confirm({ title: 'Deauthorize GitHub?', message: 'Are you sure you want to remove this GitHub authorization?', callback: function(confirm) { if(confirm) { $.ajax({ type: 'DELETE', url: nodeApiUrl + 'github/oauth/' }).done(function() { window.location.reload(); }).fail( $osf.handleJSONError ); } } }); }); $('#addonSettingsGithub .addon-settings-submit').on('click', function() { if (!$('#githubRepo').val()) { return false; } }); }); })(); module.exports = GithubConfigHelper;
JavaScript
0.966099
@@ -107,16 +107,68 @@ ers');%0A%0A +var nodeApiUrl = window.contextVars.node.urls.api;%0A%0A var Gith
a411ad2d2c947d1a8727ff46d9f0951a0b7c7c28
disable webrtc
js/qbMain.js
js/qbMain.js
/* * QuickBlox JavaScript SDK * * Main SDK Module * */ var config = require('./qbConfig'); // Actual QuickBlox API starts here function QuickBlox() {} QuickBlox.prototype = { init: function(appId, authKey, authSecret, debug) { if (debug && typeof debug === 'boolean') config.debug = debug; else if (debug && typeof debug === 'object') config.set(debug); // include dependencies var Proxy = require('./qbProxy'), Connection = require('./qbStrophe'), Auth = require('./modules/qbAuth'), Users = require('./modules/qbUsers'), Chat = require('./modules/qbChat'), WebRTC = require('./modules/qbWebRTC'), Content = require('./modules/qbContent'), Location = require('./modules/qbLocation'), Messages = require('./modules/qbMessages'), Data = require('./modules/qbData'); // create Strophe Connection object var conn = new Connection(); this.service = new Proxy(); this.auth = new Auth(this.service); this.users = new Users(this.service); this.chat = new Chat(this.service, conn); this.webrtc = new WebRTC(this.service, conn); this.content = new Content(this.service); this.location = new Location(this.service); this.messages = new Messages(this.service); this.data = new Data(this.service); // Initialization by outside token if (typeof appId === 'string' && !authKey && !authSecret) { this.service.setSession({ token: appId }); } else { config.creds.appId = appId; config.creds.authKey = authKey; config.creds.authSecret = authSecret; } if(console && config.debug) console.log('QuickBlox.init', this); }, createSession: function(params, callback) { this.auth.createSession(params, callback); }, destroySession: function(callback) { this.auth.destroySession(callback); }, login: function(params, callback) { this.auth.login(params, callback); }, logout: function(callback) { this.auth.logout(callback); } }; var QB = new QuickBlox(); QB.QuickBlox = QuickBlox; module.exports = QB;
JavaScript
0.000001
@@ -619,16 +619,19 @@ %0A + // WebRTC @@ -1099,24 +1099,27 @@ , conn);%0A + // this.webrtc
a95cfe5057a06baa7d8756b14d93e0d727bbcec0
Fix linux issue with process.env usage
source/load.entry.js
source/load.entry.js
/** * 中国蚁剑::前端加载模块 * 开写: 2016/04/23 * 更新: 2016/05/10 * 作者: 蚁逅 <https://github.com/antoor> */ 'use strict'; // 添加源码目录到全局模块加载变量,以提供后边加载 const path = require('path'); const Module = require('module').Module; Module.globalPaths.push(path.join(process.env.AS_WORKDIR, 'source')); // 开始加载时间 let APP_START_TIME = +new Date; window.addEventListener('load', () => { /** * 时间格式化函数 * @param {String} format 格式化字符串,如yyyy/mm/dd hh:ii:ss * @return {String} 格式化完毕的字符串 */ Date.prototype.format = function(format) { let o = { "M+" : this.getMonth()+1, "d+" : this.getDate(), "h+" : this.getHours(), "m+" : this.getMinutes(), "s+" : this.getSeconds(), "q+" : Math.floor((this.getMonth()+3)/3), "S" : this.getMilliseconds() } if(/(y+)/.test(format)) { format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4- RegExp.$1.length)) }; for(let k in o) { if(new RegExp("("+ k +")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length==1? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); } } return format; } /** * 加载JS函数 * @param {String} js js地址 * @return {Promise} 返回Promise操作对象 */ function loadJS(js) { return new Promise((res, rej) => { let script = document.createElement('script'); script.src = js; script.onload = res; document.head.appendChild(script); }); } /** * 加载CSS函数 * @param {String} css css地址 * @return {Promise} 返回Promise操作对象 */ function loadCSS(css) { return new Promise((res, rej) => { let style = document.createElement('link'); style.rel = 'stylesheet'; style.href = css; style.onload = res; document.head.appendChild(style); }); } // 开始加载css loadCSS('ant-static://libs/bmenu/bmenu.css') .then(() => loadCSS('ant-static://libs/toastr/toastr.min.css')) .then(() => loadCSS('ant-static://libs/layer/src/skin/layer.css')) .then(() => loadCSS('ant-static://libs/layer/src/skin/layer.ext.css')) .then(() => loadCSS('ant-static://libs/laydate/need/laydate.css')) .then(() => loadCSS('ant-static://libs/laydate/skins/default/laydate.css')) .then(() => loadCSS('ant-static://libs/terminal/css/jquery.terminal.css')) .then(() => loadCSS('ant-static://libs/font-awesome/css/font-awesome.min.css')) .then(() => loadCSS('ant-static://libs/dhtmlx/codebase/dhtmlx.css')) .then(() => loadCSS('ant-static://libs/dhtmlx/skins/mytheme/dhtmlx.css')) .then(() => loadCSS('ant-static://css/index.css')); // 加载js资源 loadJS('ant-static://libs/jquery/jquery.js') .then(() => loadJS('ant-static://libs/ace/ace.js')) .then(() => loadJS('ant-static://libs/ace/ext-language_tools.js')) .then(() => loadJS('ant-static://libs/bmenu/bmenu.js')) .then(() => loadJS('ant-static://libs/toastr/toastr.js')) .then(() => loadJS('ant-static://libs/layer/src/layer.js')) .then(() => loadJS('ant-static://libs/laydate/laydate.js')) .then(() => loadJS('ant-static://libs/terminal/js/jquery.terminal-min.js')) .then(() => loadJS('ant-static://libs/dhtmlx/codebase/dhtmlx.js')) .then(() => { /** * 配置layer弹出层 * @param {[type]} {extend: 'extend/layer.ext.js'} [description] * @return {[type]} [description] */ layer.config({extend: 'extend/layer.ext.js'}); // 加载程序入口 require('app.entry'); // LOGO console.group('LOGO'); console.log( `%c _____ _ _____ _ | _ |___| |_| __|_ _ _ ___ ___ _| | | | | _|__ | | | | . | _| . | |__|__|_|_|_| |_____|_____|___|_| |___|%c ->| Ver: %c${antSword.package.version}%c -+=>| Git: %c${antSword.package.repository['url']}%c -*| End: %c${+new Date - APP_START_TIME}%c/ms `, 'color: #F44336;', 'color: #9E9E9E;', 'color: #4CAF50;', 'color: #9E9E9E;', 'color: #2196F3;', 'color: #9E9E9E;', 'color: #FF9800;', 'color: #9E9E9E;' ); APP_START_TIME = null; console.groupEnd(); }); });
JavaScript
0.000004
@@ -205,16 +205,54 @@ Module;%0A +const %7Bremote%7D = require('electron');%0A Module.g @@ -277,16 +277,23 @@ th.join( +remote. process.
660dc232d161beca09808c9733a4233c95d36a7f
Update character
commit.js
commit.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 if ( process.argv[ 2 ] && process.argv[ 3 ] ) { var inFile = process.argv[ 2 ] var outFile = process.argv[ 3 ] if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ] console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep) var outFD = fs.openSync(outFile, 'w') fs.readFile(inFile, function(err,data) { var length = data.length console.info("Bytes: %s", length) try { child_process.execFileSync('/usr/bin/git', ['add', outFile]) } catch (e) { console.error("Couldn't add %s to git: %s", outFile, e) } var args = ['commit', outFile, '-m', 'Update character'] for (var counter = 0; counter < length; counter++) { fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1) sleep(Math.random() * max_sleep) child_process.execFileSync('/usr/bin/git', args) } }) } function sleep(seconds) { var endTime = new Date().getTime() + (seconds * 1000); while (new Date().getTime() <= endTime) {;} } process.on('exit', function () { var args = ['push'] child_process.execFileSync('/usr/bin/git
JavaScript
0
@@ -1178,28 +1178,29 @@ s.execFileSync('/usr/bin/git +'
6d429321d9a9ab8e5245472f3b59928466e58627
Fix lint
src/utils/transformBundle.js
src/utils/transformBundle.js
import Promise from 'es6-promise/lib/es6-promise/promise.js'; export default function transformBundle ( source, transformers ) { if ( typeof source === 'string' ) { source = { code: source, map: null }; } return transformers.reduce( ( previous, transformer ) => { let result = transformer( previous ) if ( result == null ) return previous; if ( typeof result === 'string' ) { result = { code: result, map: null }; } // `result.map` can only be a string if `result` isn't else if ( typeof result.map === 'string' ) { result.map = JSON.parse( result.map ); } return result; }, source ); // Promisified version // return transformers.reduce( ( promise, transformer ) => { // return promise.then( previous => { // return Promise.resolve( transformer( previous ) ).then( result => { // if ( result == null ) return previous; // if ( typeof result === 'string' ) { // result = { // code: result, // map: null // }; // } // // `result.map` can only be a string if `result` isn't // else if ( typeof result.map === 'string' ) { // result.map = JSON.parse( result.map ); // } // return result; // }); // }); // }, Promise.resolve( source ) ); }
JavaScript
0.000032
@@ -1,8 +1,11 @@ +// import P @@ -313,16 +313,17 @@ evious ) +; %0A%0A%09%09if (
324e04f68bc87c7c0f14bcc6eb5c0ad37ca0d95d
Add parens for clarity
src/components/CommentStream.js
src/components/CommentStream.js
import { connect } from 'react-redux'; import CommentList from './CommentList'; const getVisibleComments = (comments, currentTime) => { return comments .filter((streamedComment) => streamedComment.time <= currentTime) .map((streamedComment) => streamedComment.comment); }; const mapStateToProps = (state) => { return { comments: getVisibleComments(state.commentStream, state.videoContainer.currentTime), }; }; const CommentStream = connect( mapStateToProps )(CommentList); export default CommentStream;
JavaScript
0
@@ -174,32 +174,33 @@ amedComment) =%3E +( streamedComment. @@ -219,16 +219,17 @@ entTime) +) %0A .ma @@ -251,16 +251,17 @@ ent) =%3E +( streamed @@ -276,16 +276,17 @@ comment) +) ;%0A%7D;%0A%0Aco
f69fdcf1dd22a7926b6cab19c4fec288ecb77277
add comment
test/config/karma.unit.js
test/config/karma.unit.js
module.exports = function(karma) { karma.set({ basePath: '../../', frameworks: [ 'jasmine', 'browserify' ], files: [ 'test/spec/**/*Spec.js' ], reporters: [ 'dots' ], browsers: [ 'PhantomJS' ], singleRun: false, autoWatch: true, browserNoActivityTimeout: 30000, // browserify configuration browserify: { debug: true, watch: true }, preprocessors: { 'test/spec/**/*Spec.js': [ 'browserify' ] } }); };
JavaScript
0
@@ -273,16 +273,52 @@ true,%0A%0A + // fixing slow browserify build%0A brow
74f9a52677892cd7486375e8543cb1f7af29de9a
Remove long-outdated logging.
examples/trivial/About.js
examples/trivial/About.js
import React, { Component } from 'react'; import css from './trivial.css'; class About extends Component { componentWillMount() { this.props.mutator.greetingParams.replace({ greeting: 'Hi', name: 'Kurt' }); } handleSubmit(e) { e.preventDefault(); this.props.mutator.greetingParams.replace({ greeting: document.getElementById('g').value, name: document.getElementById('n').value }); } render() { console.log('RENDR ABOUT'); console.log(this.props); let greeting; if (this.props.data.greetingParams ) { greeting = <h3>{this.props.data.greetingParams.greeting} {this.props.data.greetingParams.name}</h3> } else { greeting = <h3>No one here :(</h3> } return <div className={css.root}> {greeting} <form ref='form' onSubmit={this.handleSubmit.bind(this)}> <label className={css.label}>Greeting:</label> <input className={css.textInput} id='g' type='text' /> <label className={css.label}>Person:</label> <input className={css.textInput} id='n' type='text' /> <button className={css.button} type="submit">Greet</button> </form> </div> } } About.manifest = { greetingParams: {} }; export default About;
JavaScript
0.000001
@@ -427,69 +427,8 @@ ) %7B%0A - console.log('RENDR ABOUT');%0A console.log(this.props);%0A
3769e2ebdd6cce15f06c990958a5d4ab90b75e49
Remove old code comments.
src/main.js
src/main.js
import Vue from 'vue' import Resource from 'vue-resource' import { sync } from 'vuex-router-sync' import store from './store' import router from './router' import App from './components/App.vue' // import { domain, fromNow } from './filters' // Google charts window.google.charts.load('current', { 'packages': ['corechart', 'line'] }); // install resource, for http requests Vue.use(Resource) // register filters globally // Vue.filter('fromNow', fromNow) // Vue.filter('domain', domain) // // Vue.directive('progress', { // bind: function () {}, // update: function (value, old) { // // The directive may be called before the element have been upgraded // window.componentHandler.upgradeElement(this.el) // this.el.MaterialProgress.setProgress(value) // } // }) // Vue.directive('mdl', { // bind: function () { // window.componentHandler.upgradeElement(this.el) // } // }) const app = new Vue({ router: router, store: store, el: "#app", template: "<App/>", components: { App } }) app.$store.dispatch('FETCH_WORLDS'); app.$store.dispatch('FETCH_MATCHES'); app.$store.dispatch('FETCH_GLICKO'); app.$store.dispatch('FETCH_PREDICTEDGLICKO'); export { app, router, store } /** * uncomment if want page to go back to top.. * TODO: Maybe animate this? */ /*router.afterEach(function () { console.log('hi') var _router_el = document.getElementById('router_view') _router_el.scrollTop = 0 })*/
JavaScript
0
@@ -191,55 +191,8 @@ vue' -%0A// import %7B domain, fromNow %7D from './filters' %0A%0A// @@ -348,519 +348,8 @@ e)%0A%0A -// register filters globally%0A// Vue.filter('fromNow', fromNow)%0A// Vue.filter('domain', domain)%0A//%0A// Vue.directive('progress', %7B%0A// bind: function () %7B%7D,%0A// update: function (value, old) %7B%0A// // The directive may be called before the element have been upgraded%0A// window.componentHandler.upgradeElement(this.el)%0A// this.el.MaterialProgress.setProgress(value)%0A// %7D%0A// %7D)%0A%0A// Vue.directive('mdl', %7B%0A// bind: function () %7B%0A// window.componentHandler.upgradeElement(this.el)%0A// %7D%0A// %7D)%0A%0A cons @@ -368,18 +368,16 @@ Vue(%7B%0A - - router: @@ -384,18 +384,16 @@ router,%0A - store: @@ -400,18 +400,16 @@ store,%0A - el: %22# @@ -416,18 +416,16 @@ app%22,%0A - - template @@ -436,18 +436,16 @@ App/%3E%22,%0A - compon @@ -462,16 +462,12 @@ p %7D%0A - %7D)%0A%0A - app. @@ -495,26 +495,24 @@ H_WORLDS');%0A - app.$store.d @@ -533,26 +533,24 @@ _MATCHES');%0A - app.$store.d @@ -574,18 +574,16 @@ ICKO');%0A - app.$sto @@ -621,18 +621,16 @@ CKO');%0A%0A - export %7B @@ -655,232 +655,4 @@ e %7D%0A -%0A/**%0A * uncomment if want page to go back to top..%0A * TODO: Maybe animate this?%0A */%0A%0A/*router.afterEach(function () %7B%0A console.log('hi')%0A var _router_el = document.getElementById('router_view')%0A _router_el.scrollTop = 0%0A%7D)*/%0A
c06cda5cbb36e14594dc2aa44d307fa9da2adca1
Add JS HTML methods assignment
week-9/JavaScript/DOM-manipulation/home_page.js
week-9/JavaScript/DOM-manipulation/home_page.js
// DOM Manipulation Challenge // I worked on this challenge [by myself, with: ]. // Add your JavaScript calls to this page: // Release 0: // Release 1: // Release 2: // Release 3: // Release 4: // Release 5:
JavaScript
0
@@ -76,18 +76,16 @@ ith: %5D.%0A -%0A%0A // Add y @@ -119,17 +119,16 @@ s page:%0A -%0A // Relea @@ -137,28 +137,395 @@ 0:%0A -%0A%0A%0A%0A// Release 1:%0A%0A%0A +document.getElementById(%22release-0%22).className = %22done%22;%0A%0A// Release 1:%0Adocument.getElementById(%22release-1%22).style.display = %22none%22;%0A%0A// Release 2:%0Adocument.getElementById(%22release-1%22).style.display = %22none%22;%0A%0A// Release 3:%0Adocument.getElementsByTagName(%22h1%22)%5B0%5D.innerHTML = %22I completed release 2.%22;%0A%0A// Release 4:%0Adocument.getElementById(%22release-3%22).style.backgroundColor = %22#955251%22; %0A%0A// @@ -537,26 +537,163 @@ ase -2:%0A%0A%0A +5:%0Avar change = document.getElementsByClassName(%22release-4%22);%0Afor (var i = 0; i %3C change.length; i++) %7B%0A change%5Bi%5D.style.fontSize = %222em%22;%0A%7D %0A%0A// - Release 3:%0A%0A @@ -692,45 +692,1022 @@ ase -3:%0A%0A%0A%0A%0A// Release 4:%0A%0A%0A%0A%0A// Release 5:%0A%0A +6: %0Avar template = document.getElementById('hidden');%0Adocument.body.appendChild(template.content.cloneNode(true));%0A%0A%0A// What did you learn about the DOM?%0A// %09DOM stands for Document Object Model. It is the term used to describe putting valid objects%0A// %09into HTML. In this assignment we learned how to call and change HTML or CSS variables using%0A// %09javascript objects. These involve changing the appearance or HTML of elements by class, ID,%0A// %09or tag. %0A// What are some useful methods to use to manipulate the DOM?%0A// %09One thing to note is the syntax of what the different elements are. Getting an Element class%0A// %09or tagname returns an array and in order to change all elements of this one has to run a JS %0A// %09loop to select each value of the array to make changes. One can also call specific values by%0A// %09its array position.%0A// %09Another thing is templates, which is an unprocess HTML element that is hidden until told to%0A// %09be appended. With this we can have certain elements only appear when they are called. %0A
edaa19ec8156d47da69968637839b6e71d942524
fix inverted login
modules/github-individual-project/view/handler.js
modules/github-individual-project/view/handler.js
'use strict'; const Octokat = require('../../../lib/server').server.plugins.github.Octokat; module.exports = { redirect: function (request, reply) { if (typeof request.session.get('github-username') === 'string' && typeof request.session.get('github-password') === 'string') { reply().redirect('/recipe/github/login'); } else { reply().redirect('/recipe/github-individual-project/choose-repository'); } }, chooseRepository: function (request, reply) { const Github = new Octokat({ username: request.session.get('github-username'), password: request.session.get('github-password') }); Github.me.repos.fetch().then(function (repos) { reply.view('modules/github-individual-project/view/choose-repository', {repos: repos}); }); }, selectRepository: function (request, reply) { request.session.set({ 'github-individual-project-repo': request.payload.repo }); reply().redirect('/recipe/github-individual-project/choose-students'); } };
JavaScript
0.000012
@@ -332,14 +332,45 @@ thub -/login +-individual-project/choose-repository ');%0A @@ -434,45 +434,14 @@ thub --individual-project/choose-repository +/login ');%0A
4d7a0b8467b8f91bffca85cd917c5e634e159c52
Allow nesting
src/vgps3/loader/loadmask.js
src/vgps3/loader/loadmask.js
/** * Copyright 2012 Victor Berchet. * * VisuGps3 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ /** * @fileoverview Modal overlay used while loading. * @author Victor Berchet <[email protected]> */ goog.provide('vgps3.loadMask'); goog.require('goog.ui.ModalPopup'); goog.require('vgps3.loadMask.templates'); goog.require('goog.soy'); /** * @type {goog.ui.ModalPopup} * @private */ vgps3.loadMask.popup_; /** * Set the message (and show the popup when currently hidden). * * @param {string} message * @param {vgps3.loadMask.Style=} opt_style */ vgps3.loadMask.setMessage = function(message, opt_style) { if (!vgps3.loadMask.popup_) { vgps3.loadMask.popup_ = new goog.ui.ModalPopup(true); } if (!vgps3.loadMask.popup_.isInDocument()) { vgps3.loadMask.popup_.render(); } goog.soy.renderElement( vgps3.loadMask.popup_.getElement(), vgps3.loadMask.templates.wait, {message: message, "class": opt_style} ); if (!vgps3.loadMask.popup_.isVisible()) { vgps3.loadMask.popup_.setVisible(true); } else { vgps3.loadMask.popup_.reposition(); } }; /** * Closes the popup. */ vgps3.loadMask.close = function() { if (vgps3.loadMask.popup_ && vgps3.loadMask.popup_.isInDocument()) { vgps3.loadMask.popup_.setVisible(false); } } /** * CSS classes of the message. * @enum {string} */ vgps3.loadMask.Style = { MESSAGE: 'info', ERROR: 'error' }; /** * @define {string} The src of the image */ vgps3.loadMask.IMG_SRC = 'img/wait.gif'; /** * @define {number} The width of the image */ vgps3.loadMask.IMG_WIDTH = 300; /** * @define {number} The height of the image */ vgps3.loadMask.IMG_HEIGHT = 219;
JavaScript
0
@@ -502,16 +502,117 @@ opup_;%0A%0A +/**%0A * @type %7Bnumber%7D Count the number of nested calls%0A * @private%0A */%0Avgps3.loadMask.opened_ = 0;%0A%0A%0A /**%0A * S @@ -1280,16 +1280,44 @@ ();%0A %7D%0A + vgps3.loadMask.opened_++;%0A %7D;%0A%0A/**%0A @@ -1436,32 +1436,64 @@ _.isInDocument() +& --vgps3.loadMask.opened_ === 0 ) %7B%0A vgps3.lo @@ -1521,24 +1521,65 @@ ble(false);%0A + goog.dispose(vgps3.loadMask.popup_);%0A %7D%0A%7D%0A%0A/**%0A
a8ecdcf4cadb66ee89768e012f82402ee96bafe5
Fix console.err syntax error
codechecks.js
codechecks.js
const { join } = require("path"); const fs = require("fs"); const { codechecks } = require("@codechecks/client"); const CodeChecksReport = require("eth-gas-reporter/lib/codechecksReport"); /** * Consumed by codecheck command when user's .yml lists * `eth-gas-reporter/codechecks`. The reporter dumps collected * data to the project root whenever `process.env.CI` is true. This * file processes it and runs the relevant codechecks routines. * > * > Source: krzkaczor/truffle-codechecks. * > */ module.exports.default = async function gasReporter(options = {}) { let output; let file = "gasReporterOutput.json"; // Load gas reporter output try { output = JSON.parse(fs.readFileSync(file, "utf-8")); } catch (error) { const message = `Error: Couldn't load data from "${file}".\n` + `If you're using codechecks locally make sure you set ` + `the environment variable "CI" to "true" before running ` + `your tests. ( ex: CI=true npm test )`; console.err(message); return; } // Lets monorepo subcomponents individuate themselves output.namespace = options.name ? `${output.namespace}:${options.name}` : output.namespace; // Save new data on the merge commit / push build if (!codechecks.isPr()) { const report = new CodeChecksReport(output.config); report.generate(output.info); try { await codechecks.saveValue(output.namespace, report.newData); console.log(`Successful save: output.namespace was: ${output.namespace}`); } catch (err) { console.log( `If you have a chance, report this incident to the eth-gas-reporter github issues.` ); console.log(`Codechecks errored running 'saveValue'...\n${err}\n`); console.log(`output.namespace was: ${output.namespace}`); console.log(`Saved gas-reporter data was: ${report.newData}`); } return; } // Get historical data for each pr commit output.config.previousData = (await codechecks.getValue(output.namespace)) || null; const report = new CodeChecksReport(output.config); const table = report.generate(output.info); const shortDescription = report.getShortDescription(); // Submit report try { await codechecks.success({ name: "Gas Usage", shortDescription: shortDescription, longDescription: table }); } catch (err) { console.log( `If you have a chance, report this incident to the eth-gas-reporter github issues.` ); console.log(`Codechecks errored running 'success'...\n${err}\n`); console.log(`Short description was: ${shortDescription}`); console.log(`Table was: ${table}`); } };
JavaScript
0.998859
@@ -995,19 +995,19 @@ console. -err +log (message
2681c78c35e2ae5afd14fcf33e4e4c2fa53812a3
add error messages to UI
src/middlewares/callAPI.js
src/middlewares/callAPI.js
// @flow import { push } from "react-router-redux" type param = { dispatch: Function, getState: Function } /** Middleware to simplify code and reduce the need for boilerplate in Redux actions. * This follows the REQUEST, SUCCESS, FAILURE terminology for action names. */ const callAPI = ({ dispatch, getState }: param) => { return (next: Function) => async (action: Object) => { const { types, url, config } = action if (!types || !url) { // normal action: pass it on return next(action) } // make sure types matches expected three item array if ( !Array.isArray(types) || types.length !== 3 || !types.every(type => typeof type === "string") ) { throw new Error("Expected an array of three string types.") } // helper function to print HTTP errors to console // responses are structured in JSONAPI format const printError = (res, json) => { console.error("HTTP Error") console.error( `HTTP Response: ${res.status} Title: ${json.errors[0].title} Detail: ${json.errors[0].detail}` ) } const [requestType, successType, failureType] = types dispatch({ type: requestType, payload: { isFetching: true } }) try { // make sure POST/PATCH requests have appropriate header with JWT if (config.method === "PATCH" || config.method === "POST") { config.headers = { "Content-Type": "application/json", Application: `Bearer: ${getState().auth.token}` } } const res = await fetch(url, config) const contentType = res.headers.get("content-type") if (contentType && contentType.includes("application/vnd.api+json")) { const json = await res.json() if (res.ok) { switch (successType) { case "SAVE_PAGE_SUCCESS": // timeout is needed to show changes after action is passed through setTimeout(() => { dispatch(push(`/information/${json.data.attributes.name}`)) }, 500) break // case "SAVE_INLINE_PAGE_SUCCESS": // setTimeout(() => { // window.location.reload() // }, 500) // break default: return next({ type: successType, payload: { isFetching: false, json } }) } } else { // print console errors if in development mode if (process.env.NODE_ENV !== "production") { printError(res, json) } // dispatch(push("/error")) return next({ type: failureType, payload: { error: json.errors[0].title } }) } } else { // dispatch(push("/error")) return next({ type: failureType, payload: { error: res.body } }) } } catch (error) { if (process.env.NODE_ENV !== "production") { console.error(`Network error: ${error.message}`) } // dispatch(push("/error")) return next({ type: failureType, payload: { error: error.toString() } }) } } } export default callAPI
JavaScript
0.000001
@@ -1089,17 +1089,18 @@ detail%7D%60 +, %0A - )%0A @@ -1246,24 +1246,25 @@ ng: true +, %0A %7D %0A %7D)%0A @@ -1251,24 +1251,25 @@ rue,%0A %7D +, %0A %7D)%0A%0A @@ -1544,16 +1544,17 @@ .token%7D%60 +, %0A @@ -2452,16 +2452,17 @@ json +, %0A @@ -2463,32 +2463,33 @@ %7D +, %0A %7D @@ -2682,27 +2682,24 @@ %7D%0A - // dispatch(pu @@ -2831,16 +2831,17 @@ 0%5D.title +, %0A @@ -2838,32 +2838,33 @@ e,%0A %7D +, %0A %7D)%0A @@ -2889,27 +2889,24 @@ se %7B%0A - // dispatch(pu @@ -3018,16 +3018,17 @@ res.body +, %0A @@ -3023,32 +3023,33 @@ ody,%0A %7D +, %0A %7D)%0A @@ -3195,19 +3195,16 @@ %7D%0A - // dispatc @@ -3320,16 +3320,17 @@ String() +, %0A @@ -3323,32 +3323,33 @@ ing(),%0A %7D +, %0A %7D)%0A %7D%0A
3a1904584f97bb5775d1c5dea6105283223b1513
Fix bug in activity elements publish
app/server/publish.js
app/server/publish.js
import { Projects } from '../lib/collections/projects.js'; import { Settings } from '../lib/collections/settings.js'; import { Activities } from '../lib/collections/activities.js'; import { ActivityElements } from '../lib/collections/activity_elements.js'; import { Flows } from '../lib/collections/flows.js'; import { Contradictions } from '../lib/collections/contradictions.js'; import { Discussions } from '../lib/collections/discussions.js'; // Publish users Meteor.publish('projects', function(userId) { return Projects.find(); }); // Publish users Meteor.publish('usersList', function() { return Meteor.users.find({}, { fields: { 'emails': 1, 'username': 1, 'profile.firstName': 1, 'profile.lastName': 1, 'profile.bio': 1 } }); }); // Publish users, for the tabular Meteor.publishComposite("tabular_users", function (tableName, ids, fields) { check(tableName, String); check(ids, Array); check(fields, Match.Optional(Object)); this.unblock(); // requires meteorhacks:unblock package return { find: function () { this.unblock(); // requires meteorhacks:unblock package return Meteor.users.find({}, { fields: { 'emails': 1, 'username': 1, 'roles': 1, 'profile.firstName': 1, 'profile.lastName': 1, 'profile.bio': 1 } }); }, }; }); // Publish activities, for the tabular Meteor.publishComposite("tabular_activities", function (tableName, ids, fields) { check(tableName, String); check(ids, Array); check(fields, Match.Optional(Object)); this.unblock(); // requires meteorhacks:unblock package return { find: function () { this.unblock(); // requires meteorhacks:unblock package return Activities.find({}, { fields: { 'id': 1, 'contradictionData.title': 1 } }); }, }; }); // Publish flows, for the tabular Meteor.publishComposite("tabular_flows", function (tableName, ids, fields) { check(tableName, String); check(ids, Array); check(fields, Match.Optional(Object)); this.unblock(); // requires meteorhacks:unblock package return { find: function () { this.unblock(); // requires meteorhacks:unblock package return Flows.find({}, { fields: { 'id': 1, 'flowData.title': 1 } }); }, }; }); // Publish contradictions, for the tabular Meteor.publishComposite("tabular_contradictions", function (tableName, ids, fields) { check(tableName, String); check(ids, Array); check(fields, Match.Optional(Object)); this.unblock(); // requires meteorhacks:unblock package return { find: function () { this.unblock(); // requires meteorhacks:unblock package return Contradictions.find({}, { fields: { 'id': 1, 'contradictionData.title': 1 } }); }, }; }); // Publish discussions, for the tabular Meteor.publishComposite("tabular_discussions", function (tableName, ids, fields) { check(tableName, String); check(ids, Array); check(fields, Match.Optional(Object)); this.unblock(); // requires meteorhacks:unblock package return { find: function () { this.unblock(); // requires meteorhacks:unblock package return Discussions.find({}, { fields: { 'id': 1, 'attachedToDescription': 1, 'numberOfComments': 1, 'icon': 1 } }); }, }; }); // Publish settings for the whole app Meteor.publish('settings', function () { return Settings.find(); }); // Publish activities for the whole app Meteor.publish('activities', function() { return Activities.find(); }); // Publish activity elements for the whole app Meteor.publish('activityElements', function() { return ActivityElements.find(); }); // Publish flows for the whole app Meteor.publish('flows', function() { return Flows.find(); }); // Publish contradictions for the whole app Meteor.publish('contradictions', function() { return Contradictions.find(); }); // Publish discussions for the whole app Meteor.publish('discussions', function() { return Discussions.find(); }); // Publish projects for autocomplete forms Meteor.publish("autocompleteProjects", function(selector, options) { Autocomplete.publishCursor(Projects.find(selector, options), this); this.ready(); }); // Publish users for autocomplete forms Meteor.publish("autocompleteUsers", function(selector, options) { Autocomplete.publishCursor(Meteor.users.find(selector, options), this); this.ready(); }); // Publish activities for autocomplete forms Meteor.publish("autocompleteActivities", function(selector, options) { Autocomplete.publishCursor(Activities.find(selector, options), this); this.ready(); }); // Publish activity elements for autocomplete forms Meteor.publish("autocompleteActivityElements", function(selector, options) { Autocomplete.publishCursor(ActivityElements.find(selector, options), this); this.ready(); });
JavaScript
0
@@ -3989,25 +3989,25 @@ sh('activity -E +e lements', fu
a1325c735b568df745494276dade83dc35c50f2d
Improve "empty" generated results when no propName
src/main.js
src/main.js
const _ = require('lodash') const React = require('react') const PropTypes = require('./prop-types') let options let initialized = false const wrapPropTypes = () => { initialized = true // Adds a .type key which allows the type to be derived during the // evaluation process. This is necessary for complex types which // return the result of a generator function, leaving no way to // determine which type instantiated it. const original = _.cloneDeep(PropTypes) _.each(PropTypes, (v, k) => { if (v.isRequired !== undefined) { // Simple type. Just extend the object _.defaultsDeep(PropTypes[k], { type: k, isRequired: { type: k } }) } else { // Complex type. Must extend the creator's return value PropTypes[k] = (arg) => _.defaultsDeep(original[k](arg), { type: k, arg: arg, isRequired: { type: k, arg: arg } }) } }) } const GENERATORS = { // Simple types array: (propName) => [propName], bool: () => true, func: () => () => {}, number: () => 1, object: (propName) => ({ [propName]: propName }), string: (propName) => propName, any: (propName) => propName, element: (propName) => React.createElement('div', propName), node: (propName) => propName, // Complex types arrayOf: (propName, type) => [generateOneProp(type, propName, false)], instanceOf: (propName, klass) => new klass(), objectOf: (propName, type) => ({ key: generateOneProp(type, propName, false) }), oneOf: (propName, values) => _.first(values), oneOfType: (propName, types) => forceGenerateOneProp(_.first(types), propName), shape: (propName, shape) => generateProps(shape, options) } const shouldGenerate = (propType) => { return ( // Generate required props, and this is the required version (options.required && !propType.isRequired) || // Generate optional props, and this is the optional version (options.optional && !!propType.isRequired) ) } const initError = new Error( 'generateProps.init() must be called at the beginning of your test suite' ) const generateOneProp = (propType, propName, wrapInArray = true) => { if (propType.type === undefined && initialized === false) { throw initError } const generate = options.generators[propType.type].bind(this, propName) const arg = propType.arg if (generate) { if (shouldGenerate(propType)) { if (wrapInArray) { return [propName, generate(arg)] } else { return generate(arg) } } } } const forceGenerateOneProp = (propType, propName) => { const generate = GENERATORS[propType.type].bind(this, propName) const arg = propType.arg if (generate) { return generate(arg) } } const generateProps = (arg, opts) => { if (initialized === false) { throw initError } options = _.defaults({}, opts, { required: true, optional: false }) if (opts && opts.generators) { options.generators = _.defaults({}, opts.generators, GENERATORS) } else { options.generators = GENERATORS } let propTypes if (!arg) { throw new TypeError('generateProps expected a propType object or a React Component') } else if (_.isPlainObject(arg.propTypes)) { propTypes = arg.propTypes } else if (_.isPlainObject(arg)) { propTypes = arg } else { throw new TypeError('generateProps expected a propType object or a React Component') } return _(propTypes) .map(generateOneProp) .compact() .fromPairs() .value() } Object.assign(generateProps, { init: wrapPropTypes }) module.exports = generateProps
JavaScript
0.997783
@@ -968,25 +968,24 @@ ame) =%3E -%5B propName %5D,%0A boo @@ -976,16 +976,33 @@ propName + ? %5BpropName%5D : %5B %5D,%0A boo @@ -1078,24 +1078,35 @@ propName) =%3E + propName ? (%7B %5BpropNam @@ -1120,16 +1120,20 @@ pName %7D) +: %7B%7D ,%0A stri @@ -1154,24 +1154,36 @@ =%3E propName + %7C%7C 'string' ,%0A any: (pr @@ -1201,16 +1201,25 @@ propName + %7C%7C 'any' ,%0A elem @@ -1305,16 +1305,26 @@ propName + %7C%7C 'node' ,%0A%0A // @@ -1368,17 +1368,34 @@ ype) =%3E -%5B +%7B%0A const res = generate @@ -1424,17 +1424,48 @@ , false) -%5D +%0A return res ? %5Bres%5D : %5B%5D%0A %7D ,%0A inst
323bf8f2b9903242cf0172c1dc0548834b301272
Handle case where more than one thing can get in the queue
lib/entry.js
lib/entry.js
// A passthrough read/write stream that sets its properties // based on a header, extendedHeader, and globalHeader // // Can be either a file system object of some sort, or // a pax/ustar metadata entry. module.exports = Entry var TarHeader = require("./header.js") , tar = require("../tar") , assert = require("assert").ok , Stream = require("stream").Stream , inherits = require("inherits") , fstream = require("fstream").Abstract function Entry (header, extended, global) { Stream.call(this) this.readable = true this.writable = true this._needDrain = false this._paused = false this._reading = false this._ending = false this._ended = false this._remaining = 0 this._queue = [] this._index = 0 this._queueLen = 0 this._read = this._read.bind(this) this.props = {} this._header = header this._extended = extended || {} // globals can change throughout the course of // a file parse operation. Freeze it at its current state. this._global = {} var me = this Object.keys(global || {}).forEach(function (g) { me._global[g] = global[g] }) this._setProps() } inherits(Entry, Stream, { write: function (c) { if (this._ending) this.error("write() after end()", null, true) if (this._remaining === 0) { this.error("invalid bytes past eof") } // often we'll get a bunch of \0 at the end of the last write, // since chunks will always be 512 bytes when reading a tarball. if (c.length > this._remaining) { c = c.slice(0, this._remaining) } this._remaining -= c.length // put it on the stack. var ql = this._queueLen this._queue.push(c) this._queueLen ++ this._read() // either paused, or buffered if (this._paused || ql > 0) { this._needDrain = true return false } return true } , end: function (c) { if (c) this.write(c) this._ending = true this._read() } , pause: function () { this._paused = true this.emit("pause") } , resume: function () { // console.error(" Tar Entry resume", this.path) this.emit("resume") this._paused = false this._read() return this._queueLen - this._index > 1 } // This is bound to the instance , _read: function () { // console.error(" Tar Entry _read", this.path) if (this._paused || this._reading || this._ended) return // set this flag so that event handlers don't inadvertently // get multiple _read() calls running. this._reading = true // have any data to emit? if (this._index < this._queueLen) { var chunk = this._queue[this._index ++] this.emit("data", chunk) } // check if we're drained if (this._index >= this._queueLen) { this._queue.length = this._queueLen = this._index = 0 if (this._needDrain) { this._needDrain = false this.emit("drain") } if (this._ending) { this._ended = true this.emit("end") } } // if the queue gets too big, then pluck off whatever we can. // this should be fairly rare. var mql = this._maxQueueLen if (this._queueLen > mql && this._index > 0) { mql = Math.min(this._index, mql) this._index -= mql this._queueLen -= mql this._queue = this._queue.slice(mql) } this._reading = false } , _setProps: function () { // props = extended->global->header->{} var header = this._header , extended = this._extended , global = this._global , props = this.props // first get the values from the normal header. var fields = tar.fields for (var f = 0; fields[f] !== null; f ++) { var field = fields[f] , val = header[field] if (typeof val !== "undefined") props[field] = val } // next, the global header for this file. // numeric values, etc, will have already been parsed. ;[global, extended].forEach(function (p) { Object.keys(p).forEach(function (f) { if (typeof p[f] !== "undefined") props[f] = p[f] }) }) // no nulls allowed in path or linkpath ;["path", "linkpath"].forEach(function (p) { if (props.hasOwnProperty(p)) { props[p] = props[p].split("\0")[0] } }) // set date fields to be a proper date ;["mtime", "ctime", "atime"].forEach(function (p) { if (props.hasOwnProperty(p)) { props[p] = new Date(props[p] * 1000) } }) // set the type so that we know what kind of file to create var type switch (tar.types[props.type]) { case "OldFile": case "ContiguousFile": type = "File" break case "GNUDumpDir": type = "Directory" break case undefined: type = "Unknown" break case "Link": case "SymbolicLink": case "CharacterDevice": case "BlockDevice": case "Directory": case "FIFO": default: type = tar.types[props.type] } this.type = type this.path = props.path this.size = props.size // size is special, since it signals when the file needs to end. this._remaining = props.size } , warn: fstream.warn , error: fstream.error })
JavaScript
0.000001
@@ -2537,26 +2537,29 @@ o emit?%0A -if +while (this._inde @@ -2568,32 +2568,49 @@ %3C this._queueLen + && !this._paused ) %7B%0A var ch
f33980d1be4747fc562f227badae79060c9d316d
fix button disable
website/static/js/home-page/ShareWindowDropzone.js
website/static/js/home-page/ShareWindowDropzone.js
var m = require('mithril'); var $osf = require('js/osfHelpers'); var waterbutler = require('js/waterbutler'); var AddProject = require('js/addProjectPlugin'); require('css/quick-project-search-plugin.css'); require('loaders.css/loaders.min.css'); require('css/dropzone-plugin.css'); var Dropzone = require('dropzone'); // Don't show dropped content if user drags outside dropzone window.ondragover = function(e) { e.preventDefault(); }; window.ondrop = function(e) { e.preventDefault(); }; var xhrconfig = function(xhr) { xhr.withCredentials = true; }; var ShareWindowDropzone = { controller: function() { var shareWindowId; var url = $osf.apiV2Url('users/me/nodes/', { query : { 'filter[category]' : 'share window'}}); var promise = m.request({method: 'GET', url : url, config : xhrconfig, background: true}); promise.then(function(result) { shareWindowId = result.data[0].id; }); Dropzone.options.shareWindowDropzone = { clickable: '#shareWindowDropzone', thumbnailWidth: 80, thumbnailHeight: 80, //previewsContainer: "#dropzone-preview", accept: function(file, done) { this.options.url = waterbutler.buildUploadUrl(false,'osfstorage',shareWindowId, file,{}); //this.on('dragend', function(event) { event.getElementById('shareWindowDropzone').style.border = 'solid #333';}); done(); }, sending: function(file, xhr) { //Hack to remove webkitheaders var _send = xhr.send; xhr.send = function() { _send.call(xhr, file); }; } }; $('#shareWindowDropzone').dropzone({ withCredentials: true, url:'placeholder', method:'put', addRemoveLinks: true, uploadMultiple: true, border: '2px dashed #ccc', //previewTemplate: '<div class="text-center dz-filename"><span data-dz-name></span> has been uploaded to your Share Window </div>' previewTemplate: '<div class="dz-preview dz-file-preview" style="display: inline-block;width:50%"><div class="dz-details"><div class="dz-filename"><span data-dz-name></span></div>' + '<div class="dz-size" data-dz-size></div><img data-dz-thumbnail /></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>' + '<div class="dz-success-mark"></div><div class="dz-error-mark"></div><div class="dz-error-message"><span data-dz-errormessage></span></div></div>' }); $('#ShareButton').click(function() { $('#ShareButton').attr('disabled', 'disabled'); setTimeout(enable, 300); $('#shareWindowDropzone').slideToggle(); $('#LinkToShareFiles').slideToggle(); $(this).toggleClass('btn-primary'); }); function enable () { $('#').removeAttr('disabled'); } }, view: function(ctrl, args) { function headerTemplate ( ){ return [ m('h2.col-xs-7', 'Dashboard'), m('m-b-lg.col-xs-3.drop-zone-disp', m('button.btn.btn-primary.m-t-md.f-w-xl #ShareButton', {onclick: function() { }}, 'Upload Public Files'), m('.pull-right', m.component(AddProject, { buttonTemplate : m('button.btn.btn-success.btn-success-high-contrast.m-t-md.f-w-xl[data-toggle="modal"][data-target="#addProjectFromHome"]', {onclick: function() { $osf.trackClick('quickSearch', 'add-project', 'open-add-project-modal'); }}, 'Create new project'), modalID : 'addProjectFromHome', stayCallback : function _stayCallback_inPanel() { document.location.reload(true); }, trackingCategory: 'quickSearch', trackingAction: 'add-project', templatesFetcher: ctrl.templateNodes })))]; } return m('.row', m('.col-xs-12', headerTemplate()), m('div.p-v-xl.text-center.drop-zone-format.drop-zone-invis .pointer .panel #shareWindowDropzone', m('p#shareWindowDropzone', m('h1', 'Drop files to upload'), 'Having trouble? Click anywhere in this box to manually upload a file.')), m('.h4.text-center.drop-zone-invis #LinkToShareFiles', 'Or go to your ', m('a', {href: '/share_window/', onclick: function() {}}, 'Public Files Project'))); } }; module.exports = ShareWindowDropzone;
JavaScript
0.000001
@@ -2630,24 +2630,49 @@ 'disabled') +.css(%22cursor%22, %22pointer%22) ;%0A s @@ -2689,17 +2689,17 @@ enable, -3 +2 00);%0A%0A @@ -2888,16 +2888,27 @@ $('# +ShareButton ').remov
531e32d9d84bb76b16c51b4dffbed1ce5a26f781
fix forgedJWT e2e test
test/e2e/forgedJwtSpec.js
test/e2e/forgedJwtSpec.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ describe('/', () => { describe('challenge "jwtUnsigned"', () => { it('should accept an unsigned token with email [email protected] in the payload ', () => { browser.executeScript('localStorage.setItem("token", "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkYXRhIjp7ImVtYWlsIjoiand0bjNkQGp1aWNlLXNoLm9wIn0sImlhdCI6MTUwODYzOTYxMiwiZXhwIjo5OTk5OTk5OTk5fQ.")') browser.get('/#/') }) protractor.expect.challengeSolved({ challenge: 'Unsigned JWT' }) }) describe('challenge "jwtForged"', () => { it('should accept a token HMAC-signed with public RSA key with email [email protected] in the payload ', () => { browser.executeScript('localStorage.setItem("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImVtYWlsIjoicnNhX2xvcmRAanVpY2Utc2gub3AifSwiaWF0IjoxNTA4NjM5NjEyLCJleHAiOjk5OTk5OTk5OTl9.dFeqI0EGsOecwi5Eo06dFUBtW5ziRljFgMWOCYeA8yw")') browser.get('/#/') }) protractor.expect.challengeSolved({ challenge: 'Forged Signed JWT' }) }) })
JavaScript
0
@@ -781,39 +781,39 @@ %22eyJ -hbGciOiJIUzI1NiIsInR5cCI6IkpXVC +0eXAiOiJKV1QiLCJhbGciOiJIUzI1Ni J9.e @@ -881,86 +881,64 @@ oxNT -A4NjM5NjEyLCJleHAiOjk5OTk5OTk5OTl9.dFeqI0EGsOecwi5Eo06dFUBtW5ziRljFgMWOCYeA8yw +gzMDM3NzExfQ.gShXDT5TrE5736mpIbfVDEcQbLfteJaQUG7Z0PH8Xc8 %22)')
0bfc154b74a5d2d1155231ed5a71270429e29130
Support a wider range of background filter values
modules/ui/sections/background_display_options.js
modules/ui/sections/background_display_options.js
import { event as d3_event, select as d3_select } from 'd3-selection'; import { prefs } from '../../core/preferences'; import { t, localizer } from '../../core/localizer'; import { svgIcon } from '../../svg/icon'; import { uiSection } from '../section'; import { utilDetect } from '../../util/detect'; export function uiSectionBackgroundDisplayOptions(context) { var section = uiSection('background-display-options', context) .title(t('background.display_options')) .disclosureContent(renderDisclosureContent); var _detected = utilDetect(); var _storedOpacity = prefs('background-opacity'); var _minVal = 0.25; var _maxVal = _detected.cssfilters ? 2 : 1; var _sliders = _detected.cssfilters ? ['brightness', 'contrast', 'saturation', 'sharpness'] : ['brightness']; var _options = { brightness: (_storedOpacity !== null ? (+_storedOpacity) : 1), contrast: 1, saturation: 1, sharpness: 1 }; function clamp(x, min, max) { return Math.max(min, Math.min(x, max)); } function updateValue(d, val) { if (!val && d3_event && d3_event.target) { val = d3_event.target.value; } val = clamp(val, _minVal, _maxVal); _options[d] = val; context.background()[d](val); if (d === 'brightness') { prefs('background-opacity', val); } section.reRender(); } function renderDisclosureContent(selection) { var container = selection.selectAll('.display-options-container') .data([0]); var containerEnter = container.enter() .append('div') .attr('class', 'display-options-container controls-list'); // add slider controls var slidersEnter = containerEnter.selectAll('.display-control') .data(_sliders) .enter() .append('div') .attr('class', function(d) { return 'display-control display-control-' + d; }); slidersEnter .append('h5') .text(function(d) { return t('background.' + d); }) .append('span') .attr('class', function(d) { return 'display-option-value display-option-value-' + d; }); slidersEnter .append('input') .attr('class', function(d) { return 'display-option-input display-option-input-' + d; }) .attr('type', 'range') .attr('min', _minVal) .attr('max', _maxVal) .attr('step', '0.05') .on('input', function(d) { var val = d3_select(this).property('value'); updateValue(d, val); }); slidersEnter .append('button') .attr('title', t('background.reset')) .attr('class', function(d) { return 'display-option-reset display-option-reset-' + d; }) .on('click', function(d) { if (d3_event.button !== 0) return; updateValue(d, 1); }) .call(svgIcon('#iD-icon-' + (localizer.textDirection() === 'rtl' ? 'redo' : 'undo'))); // reset all button containerEnter .append('a') .attr('class', 'display-option-resetlink') .attr('href', '#') .text(t('background.reset_all')) .on('click', function() { for (var i = 0; i < _sliders.length; i++) { updateValue(_sliders[i],1); } }); // update container = containerEnter .merge(container); container.selectAll('.display-option-input') .property('value', function(d) { return _options[d]; }); container.selectAll('.display-option-value') .text(function(d) { return Math.floor(_options[d] * 100) + '%'; }); container.selectAll('.display-option-reset') .classed('disabled', function(d) { return _options[d] === 1; }); // first time only, set brightness if needed if (containerEnter.size() && _options.brightness !== 1) { context.background().brightness(_options.brightness); } } return section; }
JavaScript
0
@@ -648,11 +648,8 @@ = 0 -.25 ;%0A @@ -691,9 +691,9 @@ s ? -2 +3 : 1
4d8a6f7b8cd647bd1f6655ef17609bb33359ffa6
update json
script.js
script.js
var schedule = require('node-schedule'); var exec = require('child_process').exec; var buildCMD = 'npm run awesome && npm run build && npm run push'; var j = schedule.scheduleJob('* 2 3 * * *', function(){ console.log('Go!'); try { exec(buildCMD, function(error, stdout, stderr) { if (!error) { console.log(stdout); } }); } catch(e) { console.error(e); } });
JavaScript
0.000001
@@ -180,9 +180,9 @@ ('* -2 +8 3 *
4b6c71fd41902f3471409476dedb0c92ad60a98e
Fix startup
app/server/startup.js
app/server/startup.js
import { CronJob } from "cron"; import prerenderio from "prerender-node"; import timesyncServer from "timesync/server"; import Cloudflare from "cloudflare"; import AcrofeverGameManager from "./imports/AcrofeverGameManager"; import LobbyManager from "./imports/LobbyManager"; import { SendReminderEmails } from "./imports/Emails"; import { UpdateRecurringEvents } from "./imports/Events"; import { DecayUserSigmaForMonth } from "./imports/Rankings"; import PostToTwitter from "./imports/PostToTwitter"; import { Games, Lobbies, Categories, BannedIPs } from "../imports/collections"; import { defaultCategories } from "../imports/statics"; Meteor.startup(function() { // Purge cloudflare cache if (!Meteor.settings.development) { const cf = new Cloudflare({ email: Meteor.settings.cloudflare.email, key: Meteor.settings.cloudflare.key }); cf.zones .purgeCache(settings.cloudflare.zoneId, { purge_everything: true }) .catch(error => console.error(error)); } //Loggly initialisation Logger = new Loggly({ token: Meteor.settings.loggly.token, subdomain: Meteor.settings.loggly.subdomain, auth: { username: Meteor.settings.loggly.username, password: Meteor.settings.loggly.password }, json: true }); //Prerender initialisation const prerenderSettings = Meteor.settings.prerenderio; if (prerenderSettings && prerenderSettings.token && prerenderSettings.host) { prerenderio.set("prerenderToken", prerenderSettings.token); prerenderio.set("host", prerenderSettings.host); prerenderio.set("protocol", "https"); WebApp.rawConnectHandlers.use(prerenderio); } _.each(DefaultLobbies, lobby => { Lobbies.upsert({ name: lobby.name }, { $setOnInsert: lobby }); const insertedLobby = Lobbies.findOne({ name: lobby.name }); if (!insertedLobby.currentGame) { //insert first game const gameId = Games.insert({ type: "acrofever", lobbyId: insertedLobby._id, active: false, currentPhase: "category", currentRound: 0, endTime: null }); Lobbies.update(insertedLobby._id, { $set: { currentGame: gameId }, $push: { games: gameId } }); } else { //game may be in progress, we should end it so timeouts will work properly const game = Games.findOne(insertedLobby.currentGame, { fields: { active: true } }); const active = game && game.active; if (active) { Lobbies.update(insertedLobby._id, { $set: { players: [] } }); LobbyManager.addSystemMessage( insertedLobby._id, "Sorry, the current game was cancelled because of a server restart.", "warning", "Please rejoin the lobby to start a new game." ); AcrofeverGameManager.makeGameInactive(insertedLobby.currentGame); } } }); // Insert all default categories if they don't exist const currentDate = new Date(); _.each(defaultCategories, category => { Categories.upsert( { category }, { $setOnInsert: { category, custom: false, active: true, createdAt: currentDate } } ); }); }); // Block banned IPs Meteor.onConnection(connection => { if ( connection.clientAddress && BannedIPs.findOne({ ip: connection.clientAddress }) ) { console.log("CLOSING CONNECTION FROM " + connection.clientAddress); connection.close(); } }); //start cron jobs const eventRemindersJob = new CronJob({ cronTime: "*/15 * * * *", // every 15 minutes onTick: Meteor.bindEnvironment(SendReminderEmails), start: true, runOnInit: true }); const updateRecurringEventsJob = new CronJob({ cronTime: "1,16,31,46 * * * *", // one minute past every 15 min interval onTick: Meteor.bindEnvironment(UpdateRecurringEvents), start: true }); const postToTwitterJob = new CronJob({ cronTime: "0 */3 * * *", // every 3 hours onTick: Meteor.bindEnvironment(PostToTwitter), start: true, runOnInit: true }); const decayRankingsJob = new CronJob({ cronTime: "0 3 1 * *", // 3am, 1st of every month onTick: Meteor.bindEnvironment(DecayUserSigmaForMonth), start: true }); WebApp.connectHandlers.use("/timesync", timesyncServer.requestHandler);
JavaScript
0.000004
@@ -889,16 +889,23 @@ geCache( +Meteor. settings
08c307dc33ac5c3cd04e23eb2a7ce9985b140631
update footer
src/components/Footer/Footer.js
src/components/Footer/Footer.js
import React, { Component } from 'react' export default () => ( <footer className="pt-3 pb-5 text-center"> <hr /> 저작권 &copy; 2017 niceb5y 모든 권리 보유. </footer> )
JavaScript
0.000001
@@ -133,16 +133,21 @@ py; 2017 +-2018 niceb5y
cfda4edd13359e5c35d2faaab96998fcb7968cdc
move Parse.initialize to top of script.js
js/script.js
js/script.js
$(document).ready(function(){ window.onLoad = function(){ //query //list //destroyAll } $('#classroom-enter').click(function(){ Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1"); event.preventDefault(); var request = $(this).value; //var Classroom = Parse.Object.extend("Classroom"); var search = new Parse.Query(Classroom); search.equalTo("code",request); search.find({ success: function(results){ console.log("YAAASSS!!!!"); }, error: function(error){ console.log("YUFAILSOHARD!?"); } }); }); $('#post').click(function(){ Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1"); var Post = Parse.Object.extend("Post"); var post = new Post(); post.set("question",""); post.set("upvotes", 0); post.set("downvotes", 0); post.set("answered", false); post.save(null, { success: function(Post) { // Execute any logic that should take place after the object is saved. //alert('New object created with objectId: ' + post.id); /************************* Rosemond's Code Goes Here! **************************/ }, error: function(Post, error) { // Execute any logic that should take place if the save fails. // error is a Parse.Error with an error code and message. alert('Failed to create new object, with error code: ' + error.message); } }); var TestObject = Parse.Object.extend("TestObject"); var testObject = new TestObject(); testObject.save({foo: "bar"}).then(function(object) { //alert("yay! it worked"); }); }); });
JavaScript
0.000001
@@ -29,222 +29,222 @@ %7B%0A%0A%09 -window.onLoad = function()%7B%0A%09%09//query%0A%09%09//list%0A%09%09//destroyAll%0A%09%7D%0A%0A%09$('#classroom-enter').click(function()%7B%0A%09%09Parse.initialize(%22HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3%22, %22IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1%22); +Parse.initialize(%22HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3%22, %22IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1%22);%0A%0A%09window.onLoad = function()%7B%0A%09%09//query%0A%09%09//list%0A%09%09//destroyAll%0A%09%7D%0A%0A%09$('#classroom-enter').click(function()%7B %0A%09%09e @@ -624,16 +624,18 @@ on()%7B%0A%09%09 +// Parse.in
5d34a6aad182c4f8fdc93911c245c1fc1df2a5fb
Fix comment
controllers/table-controller.js
controllers/table-controller.js
"use strict"; class TableController { constructor(table, fixtures) { this.table = table; this.fixtures = fixtures; this.tableCopy = []; this.output = []; this.outcomes = [ [3, 0], // home win [1, 1], // draw [0, 3] // home loss ]; } /* * Tie break criteria: * 1. Points * 2. Name * * TODO: Add more realistic criteria like GD / Head-to-Head, GF, GA, etc. * This is also league specific */ tieBreaker(a, b) { if (a.points === b.points) { return a.team.localeCompare(b.team); // alphabetical order (asc) } return b.points - a.points; // points order (desc) } validate() { // TODO make sure the table and fixtures are consistent return true; } validateTable(table) { if (!Array.isArray(table)) { return false; } for (let i=0; i<table.length; i++) { let elem = table[i]; if (!elem.team || (typeof elem.team !== 'string')) { return false; } if (!elem.points || (typeof elem.points !== 'number')) { return false; } } return true; } validateFixtures(fixtures) { if (!Array.isArray(fixtures)) { return false; } for (let i=0; i<fixtures.length; i++) { let fixture = fixtures[i]; if (!fixture.homeTeam || typeof fixture.homeTeam != 'string') { return false; } if (!fixture.awayTeam || typeof fixture.awayTeam != 'string') { return false; } } return true; } initOutput() { this.table.sort(this.tieBreaker); this.tableCopy = JSON.parse(JSON.stringify(this.table)); this.output = []; let output = this.output; this.table.forEach(function(elem, index) { let outputElem = JSON.parse(JSON.stringify(elem)); outputElem.currPos = index + 1; outputElem.highestPos = index + 1; outputElem.lowestPos = index + 1; output.push(outputElem); }); } // Main routine project(index) { if (index >= this.fixtures.length) { return; } let currFixture = this.fixtures[index]; for (let points of this.outcomes) { // TODO trim search tree if this result doesn't affect the table this.recordResult(currFixture, points); this.updatePositions(); this.project(index + 1); this.undoResult(currFixture, points); } } updatePositions() { let output = this.output; this.tableCopy.forEach(function(elem, index) { let outputTeam = output.find(function(outputElem) { return outputElem.team === elem.team; }); let currPos = index + 1; outputTeam.highestPos = Math.min(currPos, outputTeam.highestPos); outputTeam.lowestPos = Math.max(currPos, outputTeam.lowestPos); }); } recordResult(fixture, points) { let homeTeam = this.tableCopy.find(function(elem) { return elem.team === fixture.homeTeam; }); let awayTeam = this.tableCopy.find(function(elem) { return elem.team === fixture.awayTeam; }); homeTeam.points += points[0]; awayTeam.points += points[1]; this.tableCopy.sort(this.tieBreaker); }; undoResult(fixture, points) { let homeTeam = this.tableCopy.find(function(elem) { return elem.team === fixture.homeTeam; }); let awayTeam = this.tableCopy.find(function(elem) { return elem.team === fixture.awayTeam; }); homeTeam.points -= points[0]; awayTeam.points -= points[1]; this.tableCopy.sort(this.tieBreaker); }; } module.exports = TableController;
JavaScript
0
@@ -318,22 +318,8 @@ * 1. - Points%0A * 2. Nam
03966383d2d12c8516afcc20005b7bca767d4cdd
Fix bug with more than 3 children
js/script.js
js/script.js
/*! MIT License | github.com/kingalfred/canvas */ /* * Replace title */ if (document.title === 'Log in to canvas') { document.title = 'King Alfred School Canvas'; } /* * Add "Check Homework button" */ if (window.location.href.indexOf('courses')) { var text = 'Calendar'; var course = window.location.pathname.split('/')[2]; $('#section-tabs').append( `<li class="section"> <a class="settings" href="/calendar?include_contexts=course_${course}"> ${text} </a> </li>` ); } /* * Parent's multiple children */ function addChooseChild() { // Add initial option selector $('#calendar_header').append( ` <select id="calendar_children" onchange="location = this.value;"> <option class="calendar_child">Select Option</option> </select> ` ); // Get user's children $.ajax({ method: 'get', url: 'api/v1/users/self/observees?per_page=50', dataType: 'json' }).then(children => { if (children.length < 1) { $('#calendar_children').remove(); } var counter = 1; // Each child... for (var child of children) { // Add child option $('#calendar_children').append( ` <option class="calendar_child">${child.name}</option> ` ); // Get courses of that child $.ajax({ method: 'get', url: '/api/v1/users/' + child.id + '/courses?per_page=20', dataType: 'json' }).then(courses => { // Create the calendar link var courseLinks = '/calendar?include_contexts='; // Add every course ID to the link for (var course of courses) { courseLinks += `course_${course.id},`; } // Add child option $('.calendar_child').eq(counter).attr('value', courseLinks); counter++; }).fail(err => { throw err; }); } }).fail(err => { throw err; }); }; if (window.location.href.indexOf('calendar')) { addChooseChild(); } /* * Change favicon of beta environment to green icon */ function changeFavicon(img) { var favicon = $('link[rel="shortcut icon"]'); if (!favicon) $('head').append('<link rel="shortcut icon">'); favicon.attr('type', 'image/png'); favicon.attr('href', img); } if (window.location.hostname.indexOf('beta')) { changeFavicon('https://i.imgur.com/DpAI7L4.png'); }
JavaScript
0
@@ -578,260 +578,10 @@ ) %7B%0A -%0A -// Add initial option selector%0A $('#calendar_header').append(%0A %60%0A %3Cselect id=%22calendar_children%22 onchange=%22location = this.value;%22%3E%0A %3Coption class=%22calendar_child%22%3ESelect Option%3C/option%3E%0A %3C/select%3E%0A %60%0A );%0A%0A // Get user's children %0A $ @@ -617,16 +617,17 @@ url: ' +/ api/v1/u @@ -713,124 +713,20 @@ -if (children.length %3C 1) %7B%0A $('#calendar_children').remove();%0A %7D%0A%0A var counter = 1 +var p = %5B%5D ;%0A - // Each child...%0A @@ -730,19 +730,19 @@ for ( -var +let child o @@ -765,192 +765,57 @@ -// Add child option%0A $('#calendar_children').append(%0A %60%0A %3Coption class=%22calendar_child%22%3E$%7Bchild.name%7D%3C/option%3E%0A %60%0A );%0A // Get courses of that child%0A +p.push(new Promise(function(resolve, reject) %7B%0A @@ -821,24 +821,26 @@ $.ajax(%7B%0A + meth @@ -854,24 +854,26 @@ t',%0A + url: '/api/v @@ -923,24 +923,26 @@ 0',%0A + dataType: 'j @@ -946,16 +946,18 @@ 'json'%0A + %7D) @@ -987,35 +987,31 @@ -// Create the calendar link + var listCourses = %5B%5D; %0A @@ -1011,24 +1011,31 @@ %5B%5D;%0A + for ( var courseLi @@ -1036,219 +1036,282 @@ urse -Links = '/calendar?include_contexts=';%0A%0A // Add every course ID to the link%0A for (var course of courses) %7B%0A courseLinks += %60course_$%7Bcourse.id%7D,%60;%0A %7D%0A%0A // Add child option%0A + of courses) %7B%0A listCourses.push(course.id)%0A %7D%0A resolve(%7B%0A name: child.name,%0A courses: listCourses%0A %7D);%0A %7D).fail(err =%3E %7B%0A reject(err);%0A %7D);%0A %7D));%0A %7D%0A Promise.all(p).then(res =%3E %7B%0A @@ -1315,17 +1315,17 @@ $(' -. +# calendar @@ -1329,132 +1329,341 @@ dar_ -child').eq(counter).attr('value', courseLinks);%0A counter++;%0A %7D).fail(err =%3E %7B%0A throw err;%0A %7D); +header').append(%60%0A %3Cselect id=%22calendar_children%22 onchange=%22location = this.value;%22%3E%0A %3Coption class=%22calendar_child%22%3ESelect Child%3C/option%3E%0A $%7B%0A res.map(%0A x =%3E %60%3Coption class=%22calendar_child%22 value=$%7Bx.id%7D%3E$%7Bx.name%7D%3C/option%3E%60%0A )%0A %7D%0A %3C/select%3E%0A %60) %0A %7D +) %0A %7D @@ -1697,17 +1697,19 @@ rr;%0A %7D) -; +%0A %0A%7D;%0A%0Aif
f043f8cdb11c57b215a4846f52e928dec93f8a78
Update popup.js
js/popup.js
js/popup.js
<script type="text/javascript"> function website() { var homepage = window.alert("http://fsoftwarecoorperations.github.io/fsoftware-coorperations.github.io/"); } </script>
JavaScript
0.000001
@@ -158,16 +158,192 @@ o/%22);%0A%7D%0A +function error() %7B %0A var ans = confirm(%22Anything was wrong.%5CnRetry?%22);%0A if (ans == true) %7B%0A window.alert(%22Hello World%22);%0A %7D else %7B%0A window.alert(%22Hello World%22);%0A %7D%0A%7D%0A %3C/script
3757163a34c0096490527a0e512fcdca5fd3a74d
Refactor hashed async.parallel call to handle any number of async requests.
controllers/users/collection.js
controllers/users/collection.js
var request = require('request'), async = require('async'), helpers = require('../../helpers'), _ = require('underscore'); function chronological(granuals) { return _.sortBy(granuals, function(granual) { return parseInt(granual.created_at); }) } function convertTweetsTimeType(tweets) { tweets = _.sample(tweets, [50]); return _.map(tweets, function(tweet) { tweet.created_at = helpers.dateToUnix(tweet.created_at); return tweet; }) } function removeDuplicates(mediaList, attribute) { var seen = {}; return mediaList.filter(function(mediaItem) { var key = mediaItem[''+ attribute +'']; return seen[key] ? false : (seen[key] = true) }); } function stagger(media, tweets) { var staggered = []; media.forEach(function(image, index) { staggered.push(image); if ((index % 2) === 1) staggered.push(tweets.shift()); }); return staggered.concat(tweets); } function requestEndpoints(endpoints, callback) { async.parallel({ first: function(callback) { request(endpoints[0], function(err, res, body) { callback(null, helpers.toJSON(body).media); }); }, second: function(callback) { request(endpoints[1], function(err, res, body) { callback(null, helpers.toJSON(body).media); }); }, third: function(callback) { request(endpoints[2], function(err, res, body) { callback(null, helpers.toJSON(body).media); }); } }, function(err, data) { if (err) { callback(err); return }; callback(err, data.first .concat(data.second, data.third)); }) } function requestEndpoint(endpoint, callback) { request(endpoint, function(err, res, body) { if (err) { callback(err); return }; callback(err, helpers.toJSON(body).tweets); }); } module.exports = (function(){ // GET /users/:id/media?lat=LAT&lng=LNG&time=TIME return function collection(req, res) { var params = helpers.urlParams(req.url); var capsul = { user_id: req.params.id, latitude: params.lat, longitude: params.lng, timestamp: params.time, data: [] } async.parallel({ instagram: function(callback) { var endpoints = require('../media/instagram')(req.url); requestEndpoints(endpoints, function(err, instagramData) { instagramData = removeDuplicates(instagramData, 'created_at'); callback(null, instagramData) }) }, twitter: function(callback) { var endpoint = require('../media/twitter')(req.url) requestEndpoint(endpoint, function(err, twitterData) { callback(null, twitterData) }); } }, function(err, data) { var tweets = chronological(convertTweetsTimeType(data.twitter)); var media = chronological(data.instagram); capsul.data = tweets.length ? stagger(media, tweets) : media res.json(capsul); }); } })()
JavaScript
0
@@ -938,113 +938,50 @@ ion -requestEndpoints(endpoints, callback) %7B%0A async.parallel(%7B%0A first: function(callback) %7B%0A request( +endpointsToRequests(endpoints) %7B%0A return endp @@ -989,13 +989,13 @@ ints -%5B0%5D, +.map( func @@ -1004,105 +1004,29 @@ on(e -rr, res, body) %7B%0A callback(null, helpers.toJSON(body).media);%0A %7D);%0A %7D,%0A second: +ndpoint) %7B%0A return fun @@ -1069,12 +1069,8 @@ oint -s%5B1%5D , fu @@ -1165,55 +1165,100 @@ %7D -, %0A - third: function(callback) %7B%0A r +%7D);%0A%7D%0A%0Afunction requestEndpoints(endpoints, callback) %7B%0A endpoints = endpointsToR equest +s (end @@ -1267,112 +1267,40 @@ ints -%5B2%5D, function(err, res, body) %7B%0A callback(null, helpers.toJSON(body).media);%0A %7D);%0A %7D%0A %7D, +)%0A async.parallel(endpoints, %0A fun @@ -1380,66 +1380,24 @@ rr, -%0A data.first%0A .concat(data.second, data.third +_.flatten(data )) -; %0A %7D
0e8b9dc517702862b44e0d79ea4460b9b07cd95b
Revert "Update error.js"
lib/error.js
lib/error.js
/* * Copyright (c) 2013 Timo Behrmann. All rights reserved. */ var handler = require('node-restify-errors'); module.exports.handle = function (errors, req, res, options, next) { return res.send(new handler.InvalidContentError(errors)); };
JavaScript
0
@@ -63,55 +63,8 @@ */%0A%0A -var handler = require('node-restify-errors');%0A%0A modu @@ -152,49 +152,81 @@ end( -new handler.InvalidContentE +400, %7B%0A status: 'validation failed',%0A e rror -( +s: errors -) +%0A %7D );%0A%7D; -%0A
a8fd3a60069d2cb4728ee0b0003e1ddb96c843c7
add to Clues tab display for any starred Across or Down clues
js/clues.js
js/clues.js
var clues_render_to = 'clues_js'; function render_clues() { document.getElementById(clues_render_to).innerHTML = ''; clue_initial_letters(); clue_lengths(); } function isLetter(str) { return str.length === 1 && str.match(/[a-z]/i); } function clue_initial_letters() { var puzdata = PUZAPP.puzdata; var letters = []; var clue_lists = [puzdata.across_clues, puzdata.down_clues]; for (var j=0; j < clue_lists.length; j++) { clues = clue_lists[j]; for (var key in clues) { if (!clues.hasOwnProperty(key)) continue; // Find the first letter of the clue for (var i=0; i < clues[key].length; i++) { if (isLetter(clues[key].charAt(i))) { letters.push(clues[key].charAt(i).toUpperCase()); break; } } } } document.getElementById(clues_render_to).innerHTML += 'First letters of clues:<br />' + letters.join(' ') + '<br /><br />'; } function clue_lengths() { // Display the number of clues for each length var puzdata = PUZAPP.puzdata; var clue_lists = [puzdata.across_clues, puzdata.down_clues]; var categories = ['1','2','3','4','5','6','7','8','9','>= 10']; var data = []; // Initialize the data for (var i=0; i<categories.length; i++) { data.push(0); } for (var j=0; j < clue_lists.length; j++) { clues = clue_lists[j]; for (var key in clues) { if (!clues.hasOwnProperty(key)) continue; // Find the length of the clue var clue_length = clues[key].split(' ').length; if (clue_length >= 10) clue_length = 10; // Push to "data" data[clue_length-1] += 1; } } data.unshift('Count'); // Plot var chart = c3.generate({ bindto: '#clues0', title: { text: 'Clue length (number of words)' }, data: { columns: [data], type: 'bar', labels: true }, size: { // Chart won't render unless we initialize the size up front width: 340 }, axis: { rotated: true, x: { type: 'category', categories: categories }, y: { label: 'Count' } }, }); CHARTS['clues'].push(chart); }
JavaScript
0
@@ -160,16 +160,37 @@ gths();%0A + starred_clues();%0A %7D%0A%0Afunct @@ -2387,12 +2387,1129 @@ (chart);%0A%7D%0A%0A +function starred_clues() %7B%0A%0A var puzdata = PUZAPP.puzdata;%0A var starred_clues = %5B%5D;%0A var starred_clues = getStringsPreOrPostfixedWith(puzdata.across_clues, '*', 'A');%0A var starred_down = getStringsPreOrPostfixedWith(puzdata.down_clues, '*', 'D');%0A starred_clues.push(starred_down);%0A %0A document.getElementById(clues_render_to).innerHTML += 'Starred clues:%3Cbr /%3E%5Cn%5Cn';%0A%0A if (starred_clues.length == 0) %7B%0A document.getElementById(clues_render_to).innerHTML += '&lt;none&gt;' + '%3Cbr /%3E%5Cn';%0A %7D else %7B%0A for (var i = 0; i %3C starred_clues.length; ++i) %7B%0A document.getElementById(clues_render_to).innerHTML += starred_clues%5Bi%5D + %22%3Cbr /%3E%5Cn%22;%0A %7D%0A document.getElementById(clues_render_to).innerHTML += %22%5Cn%3Cbr /%3E%5Cn%22;%0A %7D%0A%7D%0A%0Afunction getStringsPreOrPostfixedWith(strings, token, type) %7B%0A %0A var retval = %5B%5D;%0A%0A for (var i in strings) %7B%0A if(strings%5Bi%5D.startsWith(token) %7C%7C strings%5Bi%5D.endsWith(token)) %7B%0A // console.log(i + type + %22 %22 + strings%5Bi%5D);%0A retval.push(i + type + %22 %22 + strings%5Bi%5D);%0A %7D%0A %7D%0A%0A return retval;%0A%7D%0A
9a5634bc7acde065455ad490045523eecb5d8aba
Remove listeners before adding them to avoid duplicate listeners
js/script.js
js/script.js
(function(){ // path to the logo images that will be displayed var LOGO_URL; // select the logo url and render the correct page function init() { setLogoUrl(); $(document).ready(function() { resolveLocation(); }) } // set all of the event listeners that are needed function setListeners() { // whenever the url anchor changes, render the correct page $(window).on("hashchange", function() { resolveLocation(); }) // perform a search on the main page when the "Jimmy Search" button is clicked $("#main-search-btn").click(function() { makeSearch(); }) // perform a search when the magnifying glass is clicked on the search results page $("#search-button").click(function() { makeSearch(); }) // perform a search after pressing "enter" with the search box focused $(document).keyup(function(e) { if (e.which == 13 && $("#search-box").is(":focus")) { makeSearch(); } }) } // set LOGO_URL to be the path to a random logo image function setLogoUrl() { var i = Math.floor(Math.random() * (6)) + 1; LOGO_URL = "img/logo" + parseInt(i) + ".png"; } // change the current URL and render the specified Handlebars template. // name should be the name of the Handlebars template, i.e. main.hbs -> "main", // href should typically just be the anchor portion, i.e. "#q=abc", // context should be a JSON object that acts as the context for the template function renderPage(name, href, context) { location.href = href; insertTemplate(name, "body", context); } // insert the Handlebars template into the page. // name should be the name of the Handlebars template, i.e. main.hbs -> "main", // containerSelector should be the jQuery selector for the element that will have // its HTML be set to the Handlebars template // context should be a JSON object that acts as the context for the template function insertTemplate(name, containerSelector, context) { $(containerSelector).html(Templates[name](context)); } // look at the current url. if the anchor component has the form "#q={query}" // then render the search results page for the query. otherwise render the main page. function resolveLocation() { // get the string after the hash var hash = window.location.hash.substr(1); if (hash.substring(0, 2) == "q=" && hash.length > 2) { renderPage("search", window.location.hash, { logoUrl: LOGO_URL }); // set the contents of the search box to be query $("#search-box").val(decodeURIComponent(hash.substring(2))); } else { renderPage("main", "#", { logoUrl: LOGO_URL }); $("#search-box").focus(); } setListeners(); } // if there is a query in the search box, then perform a search function makeSearch() { var query = $("#search-box").val().trim(); if (query) { renderPage("search", "#q=" + encodeURIComponent(query), { logoUrl: LOGO_URL }); // set the contents of the search box to be the query $("#search-box").val(query); } } // let's gooooo init(); }())
JavaScript
0
@@ -417,24 +417,61 @@ orrect page%0A + $(window).off(%22hashchange%22);%0A $(wi @@ -498,32 +498,32 @@ %22, function() %7B%0A - reso @@ -635,16 +635,60 @@ clicked%0A + $(%22#main-search-btn%22).off(%22click%22);%0A @@ -853,24 +853,66 @@ esults page%0A + $(%22#search-button%22).off(%22click%22);%0A $(%22# @@ -975,32 +975,32 @@ h();%0A %7D)%0A - // perfo @@ -1062,16 +1062,50 @@ focused%0A + $(document).off(%22keyup%22);%0A
313fb2e0f3d474d17099ab3b12e44ae04a47fd4f
Remove stray semicolon
gulpfile.js
gulpfile.js
argv = require("yargs").argv; browserSync = require("browser-sync") cache = require("gulp-cached") clip = require("gulp-clip-empty-files") dateFormat = require("dateformat") del = require("del") ghPages = require("gulp-gh-pages") gulp = require("gulp") gutil = require("gulp-util") include = require("gulp-include") literate = require("gulp-writ") minifyCSS = require("gulp-cssnano") minifyJS = require("gulp-uglify") prefix = require("gulp-autoprefixer") removeEmptyLines = require("gulp-remove-empty-lines") rename = require("gulp-rename") replace = require("gulp-replace") runSequence = require("run-sequence") sass = require("gulp-sass") scssLint = require("gulp-scss-lint") shell = require("gulp-shell") slugify = require("underscore.string/slugify") uncss = require("gulp-uncss") messages = { jekyllBuild: "Rebuilding Jekyll...", swiftSuccess: "\u2705 Swift compiled sucessfully!", uncssStart: "Cleaning CSS..." } now = new Date() title = (ref = argv.t) != null ? ref : "Untitled" dashedTitle = slugify(title) sourceFolder = "./source" targetFolder = "./_site" paths = { jekyllFiles: [sourceFolder + "/**/*.html", sourceFolder + "/**/*.md", sourceFolder + "/**/*.yml", sourceFolder + "/**/*.xml", "!" + sourceFolder + "/node_modules/**/*"], sourcePosts: sourceFolder + "/_posts/", sourceScripts: sourceFolder + "/_scripts/", sourceStylesheets: sourceFolder + "/_scss/", targetScripts: targetFolder + "/scripts/", targetStylesheets: targetFolder + "/css/", targetSwift: "./swift/" } gulp.task("default", ["develop"]) gulp.task("develop", function() { runSequence(["watch", "browser-sync"]) }) gulp.task("swift", function() { runSequence(["generate-swift", "run-swift"]) }) gulp.task("build", function() { runSequence("swift", ["generate-css", "minify-scripts", "vendorize-scripts"], ["jekyll-build", "uncss"]) }) gulp.task("rebuild", function() { runSequence("jekyll-build-local", "reload") }) gulp.task("yolo", function() { runSequence("build", "deploy") }) gulp.task("clean", del.bind(null, ["_site"])) gulp.task("watch", ["generate-css", "minify-scripts", "jekyll-build-local"], function() { gulp.watch(paths.sourceStylesheets + "/**/*.scss", ["generate-css"]) gulp.watch(paths.sourceScripts + "/**/*.js", ["minify-scripts"]) gulp.watch(paths.sourceScripts + "/vendor.js", ["vendorize-scripts"]) gulp.watch(paths.jekyllFiles, ["rebuild"]) }) gulp.task("jekyll-build-local", shell.task("bundle exec jekyll build --incremental --config _config.yml,_config.serve.yml", { quiet: true })) gulp.task("jekyll-build", shell.task("bundle exec jekyll build")) gulp.task("reload", function() { browserSync.reload() }) gulp.task("doctor", shell.task("jekyll doctor")) gulp.task("generate-css", function() { gulp.src(paths.sourceStylesheets + "/*.scss") .pipe(sass({ precision: 2 })) .on("error", sass.logError) .pipe(prefix(["last 2 versions", "> 2%", "ie 11", "Firefox ESR"], { cascade: false })) .pipe(cache(paths.targetStylesheets)) .pipe(minifyCSS()) .pipe(gulp.dest(paths.targetStylesheets)) .pipe(browserSync.reload({ stream: true })) }) gulp.task("lint-scss", function() { gulp.src(paths.sourceStylesheets + "/*.scss") .pipe(cache(paths.sourceStylesheets)) .pipe(scssLint({ "config": ".scss-lint.yml", "bundleExec": true })) .pipe(scssLint.failReporter()) .on("error", function(error) { gutil.log(error.message) }) }) gulp.task("uncss", function() { gutil.log(messages.uncssStart) gulp.src(paths.targetStylesheets + "*.css") .pipe(uncss({ html: [targetFolder + "/**/*.html"] })) .pipe(minifyCSS()) .pipe(gulp.dest(paths.targetStylesheets)) }); gulp.task("minify-scripts", function() { gulp.src([paths.sourceScripts + "/*.js", "!" + paths.sourceScripts + "/vendor.js"]) .pipe(cache("minify-scripts")) .pipe(minifyJS()) .pipe(gulp.dest(paths.targetScripts)) .pipe(browserSync.reload({ stream: true })) }) gulp.task("vendorize-scripts", function() { gulp.src(paths.sourceScripts + "/vendor.js") .pipe(include()) .on("error", function(error) { gutil.log(error.message) }) .pipe(cache("vendorize-scripts")) .pipe(minifyJS()) .pipe(gulp.dest(paths.targetScripts)) .pipe(browserSync.reload({ stream: true })) }) gulp.task("browser-sync", function() { browserSync.init(null, { server: { baseDir: targetFolder }, host: "localhost", port: 4000, browser: "Safari Preview" }) }) gulp.task("post", function() { gulp.src(paths.sourcePosts + "_template.md") .pipe(rename(dateFormat(now, "yyyy-mm-dd") + "-" + dashedTitle + ".md")) .pipe(replace(/DATE_PLACEHOLDER/g, dateFormat(now, "yyyy-mm-dd hh:MM:ss o"))) .pipe(replace(/TITLE_PLACEHOLDER/g, title)) .pipe(gulp.dest(paths.sourcePosts)) }) gulp.task("generate-swift", function() { gulp.src([paths.sourcePosts + "*.md", "!" + paths.sourcePosts+ "_template.md"]) .pipe(replace(/(?!\/\/\ \-\>\ Error)\/\/.+/g, "")) .pipe(rename({ extname: ".swift.md" })) .pipe(literate()) .pipe(replace(/(.*\n)\/\/\ \-\>\ Error/g, "// $1")) .pipe(removeEmptyLines()) .pipe(clip()) .pipe(gulp.dest(paths.targetSwift)) }); gulp.task("swift-version", shell.task("swift --version;")) gulp.task("run-swift", ["swift-version"], shell.task("./bin/test >> /dev/null")) gulp.task("swift", ["generate-swift", "run-swift"], function() { gutil.log(messages.swiftSuccess); }) gulp.task("deploy", function() { return gulp.src(targetFolder + "/**/*") .pipe(ghPages({ message: "Deploy // " + Date() })) })
JavaScript
0.999961
@@ -21,17 +21,16 @@ s%22).argv -; %0Abrowser
93a137d86f0d96fea48fd26e63b91eb5f260eca7
Isolate that sucker
test/events/rapid.test.js
test/events/rapid.test.js
const fs = require('fs-extra') const {Fixture} = require('../helper') const {EventMatcher} = require('../matcher'); [false, true].forEach(poll => { describe(`rapid events with poll = ${poll}`, function () { let fixture, matcher beforeEach(async function () { fixture = new Fixture() await fixture.before() await fixture.log() matcher = new EventMatcher(fixture) await matcher.watch([], {poll}) }) afterEach(async function () { await fixture.after(this.currentTest) }) // The polling thread will never be able to distinguish rapid events if (!poll) { it('understands coalesced creation and deletion events', async function () { const deletedPath = fixture.watchPath('deleted.txt') const recreatedPath = fixture.watchPath('recreated.txt') const createdPath = fixture.watchPath('created.txt') await fs.writeFile(deletedPath, 'initial contents\n') await until('file creation event arrives', matcher.allEvents( {action: 'created', kind: 'file', path: deletedPath} )) await fs.unlink(deletedPath) await fs.writeFile(recreatedPath, 'initial contents\n') await fs.unlink(recreatedPath) await fs.writeFile(recreatedPath, 'newly created\n') await fs.writeFile(createdPath, 'and another\n') await until('all events arrive', matcher.orderedEvents( {action: 'deleted', path: deletedPath}, {action: 'created', kind: 'file', path: recreatedPath}, {action: 'deleted', path: recreatedPath}, {action: 'created', kind: 'file', path: recreatedPath}, {action: 'created', kind: 'file', path: createdPath} )) }) it('understands rapid creation and rename events', async function () { const originalPath = fixture.watchPath('created.txt') const finalPath = fixture.watchPath('final.txt') await fs.writeFile(originalPath, 'contents\n') await fs.rename(originalPath, finalPath) if (process.platform === 'darwin') { await until('creation and deletion events arrive', matcher.orderedEvents( {action: 'created', kind: 'file', path: originalPath}, {action: 'deleted', kind: 'file', path: originalPath}, {action: 'created', kind: 'file', path: finalPath} )) } else { await until('creation and rename events arrive', matcher.orderedEvents( {action: 'created', kind: 'file', path: originalPath}, {action: 'renamed', kind: 'file', oldPath: originalPath, path: finalPath} )) } }) } it('correlates rapid file rename events', async function () { const oldPath0 = fixture.watchPath('old-file-0.txt') const oldPath1 = fixture.watchPath('old-file-1.txt') const oldPath2 = fixture.watchPath('old-file-2.txt') const newPath0 = fixture.watchPath('new-file-0.txt') const newPath1 = fixture.watchPath('new-file-1.txt') const newPath2 = fixture.watchPath('new-file-2.txt') await Promise.all( [oldPath0, oldPath1, oldPath2].map(oldPath => fs.writeFile(oldPath, 'original\n')) ) await until('all creation events arrive', matcher.allEvents( {action: 'created', kind: 'file', path: oldPath0}, {action: 'created', kind: 'file', path: oldPath1}, {action: 'created', kind: 'file', path: oldPath2} )) await Promise.all([ fs.rename(oldPath0, newPath0), fs.rename(oldPath1, newPath1), fs.rename(oldPath2, newPath2) ]) if (poll) { await until('all deletion and creation events arrive', matcher.allEvents( {action: 'deleted', kind: 'file', path: oldPath0}, {action: 'deleted', kind: 'file', path: oldPath1}, {action: 'deleted', kind: 'file', path: oldPath2}, {action: 'created', kind: 'file', path: newPath0}, {action: 'created', kind: 'file', path: newPath1}, {action: 'created', kind: 'file', path: newPath2} )) } else { await until('all rename events arrive', matcher.allEvents( {action: 'renamed', kind: 'file', oldPath: oldPath0, path: newPath0}, {action: 'renamed', kind: 'file', oldPath: oldPath1, path: newPath1}, {action: 'renamed', kind: 'file', oldPath: oldPath2, path: newPath2} )) } }) }) })
JavaScript
0.998696
@@ -615,33 +615,45 @@ poll) %7B%0A it -( +.stress(500, 'understands coa
248c0b0cc4a65b7cc648cc7a7dfcf7bfe398c0d8
add fixtures for `get` and `list` routes
test/fixtures/campaign.js
test/fixtures/campaign.js
exports.createMinimal = { payload: { "name": "minimal notification", "live": false, "push_time": "now", "messages": [ { "language": "fr", "title": "Salut le monde !", "body": "Comment ça va ?" } ] }, token: { "campaign_token": "3396955c1a7fe0005d76973fca00b44a" }, replyStats: { "campaign_token": "3396955c1a7fe0005d76973fca00b44a", "detail": [ { "date": "2017-03-02T09:43:17", "sent": 754, "direct_open": 102, "influenced_open": 98, "reengaged": 12, "errors": 0 } ] }, stats: { date: new Date("2017-03-02T09:43:17"), sent: 754, direct_open: 102, influenced_open: 98, open_rate: (102 + 98) / 754, reengaged: 12, errors: 0 }, statusCode: 201 };
JavaScript
0.000002
@@ -993,8 +993,1185 @@ 201%0A%7D;%0A +%0Aexports.get = %7B%0A token: %7B%0A %22campaign_token%22: %223396955c1a7fe0005d76973fca00b44a%22%0A %7D,%0A reply: %7B%0A %22campaign_token%22: %223396955c1a7fe0005d76973fca00b44a%22,%0A %22from_api%22: true,%0A %22dev_only%22: true,%0A %22created_date%22: %222017-03-02T09:43:17%22,%0A %22name%22: %22minimal notification%22,%0A %22live%22: false,%0A %22push_time%22: %222017-03-02T09:43:17%22,%0A %22gcm_collapse_key%22: %22default%22,%0A %22targeting%22: %7B%0A %22segments%22: %5B%0A %22ONE_TIME%22,%0A %22DORMANT%22,%0A %22ENGAGED%22,%0A %22IMPORTED%22,%0A %22NEW%22%0A %5D%0A %7D,%0A %22messages%22: %5B%0A %7B%0A %22title%22: %22Salut le monde !%22,%0A %22body%22: %22Comment %C3%A7a va ?%22%0A %7D%0A %5D%0A %7D,%0A statusCode: 200%0A%7D;%0A%0Aexports.list = %7B%0A reply: %5B%0A %7B%0A %22campaign_token%22: %223396955c1a7fe0005d76973fca00b44a%22,%0A %22from_api%22: true,%0A %22dev_only%22: true,%0A %22created_date%22: %222017-03-02T09:43:17%22,%0A %22name%22: %22minimal notification%22,%0A %22live%22: false,%0A %22push_time%22: %222017-03-02T09:43:17%22%0A %7D%0A %5D,%0A statusCode: 200%0A%7D;%0A
917d28e7483b1595bfebc00dc792c0c67c31cfad
Fixing punctuation
commit.js
commit.js
var child_process = require('child_process') var fs = require('fs'); var max_sleep = 300 var step = 10 //Added a comment that achieves no real goal. //Non-blocking loop //Adjustable step //Status line //Add a rough time indicat
JavaScript
0.999999
@@ -220,8 +220,9 @@ indicat +o
1b3433f9208766f8025ab65833a5431f5feed833
fix whitespace
converter/formats/protractor.js
converter/formats/protractor.js
const locatorBy = function (locatorType) { switch (locatorType) { case "xpath": return "xpath"; case "id": return "id"; case "css selector": return "css"; case "link text": return "linkText"; case "class": return "className"; case "name": return "name"; } }; module.exports = { writeOutput(output) { const appendBefore = ' '; return ` describe('Selenium Test Case', function() { it('should execute test case without errors', function() { ${output.map((s) => `${appendBefore}${s};`).join('\n')} }); });`; }, lineForTyp: { get({url}) { return `browser.get('${url}')`; }, clickElement({locator}) { return `element(by.${locatorBy(locator.type)}('${locator.value}')).click()`; }, setElementText({locator, text}){ return `element(by.${locatorBy(locator.type)}('${locator.value}')).sendKeys('${text}')`; } }, };
JavaScript
0.004694
@@ -19,17 +19,16 @@ function - (locator
07870f6a2deba4bc96a8be0fe20a1bcbb400f11e
update more specific code comments
lib/error.js
lib/error.js
'use strict'; if (!Error.captureStackTrace) throw new Error('Error.captureStackTrace does not exist!'); var util = require('./util'); var BE = require('./base_error'); var v = require('./validator').v; var check = require('./validator').check; var BaseError = BE.BaseError; var Errors = { template: null, }; exports = module.exports = Errors; exports.setErrorStackSeparator = function(separator) { BE.ERROR_STACK_SEPARATOR = separator; }; exports.setErrorStackSeparator('\n==== Pre-Error-Stack ====\n'); exports.setMessageConnector = function(connector) { BE.MESSAGE_CONNECTOR = connector; }; exports.setMessageConnector(' && '); /** * define a subclass of BaseError */ exports.defineError = function(definition, name) { if (!Errors.template) throw new Error('The error template should be defined firstly!'); var E = function() { BaseError.apply(this, arguments); }; util.inherits(E, BaseError); util.each(Errors.template, function(opts, key) { var value = definition[key]; if (value !== undefined) { E.prototype[key] = value; } else { if (opts.required === true) { throw new Error('The key "' + key + '" is required, while definition = ' + JSON.stringify(definition)); } else { value = opts.default; } } }); E.prototype.name = name; Errors[name] = E; return E; }; /** * To determine whether it is your custom error. * * if the error is an instance of the native Error, return `false`. * * @param {*} error * @return {Boolean} * @method isCustomError(err) */ exports.isCustomError = function(err) { return err instanceof BaseError; }; // alias for isCustomError exports.isError = Errors.isCustomError; exports.setTemplate = function(template) { if (util.isObject(template) === false) { throw new Error('template should be an Object!'); } var t = {}; util.each(template, function(params, key) { if (util.isString(params)) { t[key] = { message: params, required: true, }; } else if (util.isObject(params)) { t[key] = check(params, v.definition()); } else { throw new Error('The value of template item should be an object or a string. Actual key=' + key + ' value=' + JSON.stringify(params)); } }); Errors.template = t; }; /** * Assigns own enumerable properties of meta to the err.meta. * * If the err.meta is undefined before assigning, it will be assigned a new object, * and then the own enumerable properties of second parameter will be assigned to err.meta. * If the err.meta is not undefined, it should be a plain object. * * the properties of meta will overwrite the properties of err.meta, if they have same name. * * @side_effect err, err.meta * @param {Error} err the instance of Error class or Error subclass * @param {Object} meta * @method addMeta */ exports.addMeta = function(err, meta) { if (!err.meta) err.meta = {}; util.extend(err.meta, meta); }; /** * initialize module * * @param {Object} params * @param {Object} params.template a template for all error sub-classes * @param {Array<Object>} params.definitions the definitions of error sub-classes * @param {Boolean} [params.lazy=false] if true, params.template and params.definitions could be optional. * Otherwise, template and definitions are required. * @return {Null} * @method init(params) */ exports.init = function(params) { params = util.defaults({}, params, { lazy: false, }); if (params.lazy) return undefined; Errors.setTemplate(params.template); util.each(params.definitions, Errors.defineError); };
JavaScript
0
@@ -350,173 +350,524 @@ s;%0A%0A -exports.setErrorStackSeparator = function(separator) %7B%0A BE.ERROR_STACK_SEPARATOR = separator;%0A%7D;%0Aexports.setErrorStackSeparator('%5Cn==== Pre-Error-Stack ====%5Cn');%0A +/**%0A * set the separator for multi error stacks.%0A *%0A * Default to %22%5Cn==== Pre-Error-Stack ====%5Cn%22%0A *%0A * @param %7BString%7D separator%0A * @method setErrorStackSeparator(separator)%0A */%0Aexports.setErrorStackSeparator = function(separator) %7B%0A BE.ERROR_STACK_SEPARATOR = separator;%0A%7D;%0Aexports.setErrorStackSeparator('%5Cn==== Pre-Error-Stack ====%5Cn');%0A%0A/**%0A * set the connector for multi error messages. Default to %22 && %22%0A *%0A * @param %7BString%7D connector%0A * @return %7BUndefined%7D%0A * @method setMessageConnector(connector)%0A */ %0Aexp @@ -1032,16 +1032,176 @@ seError%0A + *%0A * @param %7BObject%7D definition%0A * @param %7BString%7D name the name of Error Class%0A * @return %7BFunction%7D Error Class%0A * @method defineError(definition, name)%0A */%0Aexpo @@ -2238,17 +2238,21 @@ or;%0A%7D;%0A/ -/ +**%0A * alias f @@ -2268,16 +2268,20 @@ omError%0A + */%0A exports. @@ -2313,16 +2313,109 @@ Error;%0A%0A +/**%0A * @param %7BObject%7D template%0A * @return %7BUndefined%7D%0A * @method setTemplate(template)%0A */%0A exports. @@ -3603,24 +3603,47 @@ bject%7D meta%0A + * @return %7BUndefined%7D%0A * @method a @@ -4193,12 +4193,17 @@ rn %7B -Null +Undefined %7D%0A *
230f3702f788a03b97ab2e8f9914d45a01cb6464
format to lint
src/components/Header/Header.js
src/components/Header/Header.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react' import {defineMessages, FormattedMessage, injectIntl} from 'react-intl' import withStyles from 'isomorphic-style-loader/lib/withStyles' import s from './Header.scss' import {connect} from 'react-redux' import Link from '../Link' import Navigation from '../Navigation' // import LanguageSwitcher from '../LanguageSwitcher' import {FaAngleDown} from 'react-icons/lib/fa' import UserInfo from '../UserInfo' const messages = defineMessages({ brand: { id: 'header.brand', defaultMessage: 'Rate Issues', description: 'Brand name displayed in header' } }) const onUserClick = () => { console.log('testss') } function Header ({displayName, picture}) { const renderUser = (onClick = null) => { if (picture) { return ( <div className={ s.user } > <UserInfo picture={ picture } displayName={ displayName } > </UserInfo> <FaAngleDown color={ 'white' } onClick={ onClick } /> </div> ) } } return ( <div className={ s.root }> <div className={ s.container }> <div className="leftHeader"> <Link className={ s.brand } to="/" > <span className={ s.brandTxt }> <FormattedMessage { ...messages.brand } /> </span> </Link> </div> <div className="rightHeader"> <div className={ s.linkHolder }> { /* <LanguageSwitcher />*/ } <Navigation className={ s.nav } /> { renderUser(onUserClick) } </div> </div> </div> </div> ) } export default connect(state => ({ displayName: state.user.displayName, picture: state.user.picture }))(withStyles(s)(injectIntl(withStyles(s)(Header))))
JavaScript
0.0001
@@ -1146,16 +1146,28 @@ ayName %7D +%0A %3E%0A
83b4745e891fb4cc457501eed78a1bcb1a1cf875
Include more unit test to validate template parse with nested template tags
spec/templateSpec.js
spec/templateSpec.js
/* * templateSpec.js * * Distributed under terms of the MIT license. */ /* global describe, it, expect */ var requirejs = require("requirejs"); requirejs.config({ baseUrl: __dirname + "/../src/", nodeRequire: require }); describe("Setup", function() { it("require", function() { expect(require).not.toBe(null); var css = requirejs("css_parser"); expect(css).not.toBe(null); expect(requirejs("vue")).not.toBe(null); }); }); describe("Parser Templates", function() { var parser = requirejs("template_parser"); it("Simple br", function() { var template = "<templete>" + "<br/></template>"; var result = parser.extractTemplate(template); expect(result).toMatch("<br/>"); }); it("Multiline", function() { var template = "<template>\n" + " <input/> <label>Test</label>\n" + " </template>"; var result = parser.extractTemplate(template); var expected = "'' + \n" + "' <input/> <label>Test</label>' + \n" + "' ' + ''"; expect(result.length).toBe(expected.length); expect(true).toBe(result === expected); }); }); /* vim: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab : */
JavaScript
0
@@ -1218,24 +1218,315 @@ );%0A %7D);%0A%0A + it(%22Multi tamplate tags%22, function () %7B%0A var template = %22%3Ctemplate%3E%3Ctemplate%3E%3Cspan/%3E%3C/template%3E%3C/template%3E%22 ;%0A var result = parser.extractTemplate(template);%0A var expected = %22'%3Ctemplate%3E%3Cspan/%3E%3C/template%3E' + ''%22;%0A%0A expect(result).toEqual(expected);%0A%0A %7D);%0A%0A %7D);%0A/* vim:
61b7194c8ccdd39f07994d64953695ff85e06c61
rename getReadOnly to isReadOnly
nodeserver/src/client/js/WidgetBase/WidgetBase.js
nodeserver/src/client/js/WidgetBase/WidgetBase.js
"use strict"; define(['jquery', 'logManager'], function ( _jquery, logManager) { var WidgetBase; WidgetBase = function (options) { //this.logger --- logger instance for the Widget var loggerName = "WidgetBase", msg = ""; if (options && options[WidgetBase.OPTIONS.LOGGER_INSTANCE_NAME]) { loggerName = options[WidgetBase.OPTIONS.LOGGER_INSTANCE_NAME]; } this.logger = logManager.create(loggerName); //this.$el --- jQuery reference to the DOM container of Widget if (options && options[WidgetBase.OPTIONS.CONTAINER_ELEMENT]) { this.$el = $(options[WidgetBase.OPTIONS.CONTAINER_ELEMENT]); if (this.$el.length === 0) { msg = "Widget's container element can not be found"; this.logger.error(msg); throw (msg); } } else { msg = "Widget's container element is not specified in constructor's 'options' parameter"; this.logger.error(msg); throw (msg); } //by default Widget is in EDIT mode this._isReadOnly = false; }; WidgetBase.OPTIONS = { "CONTAINER_ELEMENT" : "containerElement", "LOGGER_INSTANCE_NAME": "LOGGER_INSTANCE_NAME" }; WidgetBase.READ_ONLY_CLASS = 'read-only'; /************ SET READ-ONLY MODE *************/ WidgetBase.prototype.setReadOnly = function (isReadOnly) { if (this._isReadOnly !== isReadOnly) { this._isReadOnly = isReadOnly; this.logger.debug("ReadOnly mode changed to '" + isReadOnly + "'"); this.onReadOnlyChanged(this._isReadOnly); } }; WidgetBase.prototype.getReadOnly = function () { return this._isReadOnly; }; /* METHOD CALLED WHEN THE WIDGET'S READ-ONLY PROPERTY CHANGES */ WidgetBase.prototype.onReadOnlyChanged = function (isReadOnly) { if (isReadOnly === true) { this.$el.addClass(READ_ONLY_CLASS); } else { this.$el.removeClass(READ_ONLY_CLASS); } }; /***** END OF --- SET READ-ONLY MODE *********/ /************** WIDGET-BASE INTERFACE *******************/ /* METHOD CALLED WHEN THE WIDGET HAS TO CLEAR ITSELF */ WidgetBase.prototype.clear = function () { }; /* METHOD CALLED BEFORE IT WILL BE REMOVED FROM SCREEN */ /* DO THE NECESSARY CLEANUP */ WidgetBase.prototype.destroy = function () { this.clear(); }; /* METHOD CALLED WHEN THE PARENT CONTAINER SIZE HAS CHANGED AND WIDGET SHOULD RESIZE ITSELF ACCORDINGLY */ WidgetBase.prototype.parentContainerSizeChanged = function (newWidth, newHeight) { }; return WidgetBase; });
JavaScript
0
@@ -1755,19 +1755,18 @@ ototype. -get +is ReadOnly
c22da9f952c0a9d112284ae97ae47f00773bf863
stop data from submitting without position
js/script.js
js/script.js
// Require filesystem API (used to save data to file later on) const fs = require('fs'); // ipc is used to open and communicate with the data viewer and other additional windows. const ipc = require('electron').ipcRenderer; const user = require('os').userInfo(); // Define some elements. var pg = { team: document.getElementById('team'), match: document.getElementById('match'), submit: document.getElementById('submit'), reset: document.getElementById('reset'), view: document.getElementById('view'), position: document.getElementById('start-position'), red: document.getElementById('red'), blue: document.getElementById('blue'), color: document.getElementById('team-color') }; var game = { parked: document.getElementById('parked'), }; // Get date for file naming. var d = new Date(); var home = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; var desktopPath = home + (fs.existsSync(home + '/Desktop') ? '/Desktop' : ''); var path = desktopPath + '/scoutdata_' + user.username + '_' + ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'][d.getMonth()] + '_' + d.getDate() + '_' + d.getFullYear() + '.json'; localStorage.desktopPath = desktopPath; // Generate an array of all data inputs in document. // These will be used to generate an object. // Inputs named .special are exempt. These can be used for things like path selection. var tags = document.querySelectorAll('input:not(.special), select:not(.special), textarea'); // Create empty object. var inputs = {}; // Make each element be the value to a key named after its ID. for (tag of tags.values()) inputs[tag.id] = tag; // Add the + and - buttons to a number specific input box for (input in inputs) { if (inputs[input].type === 'number' && !inputs[input].classList.contains('large')) { var increase = document.createElement('button'); increase.textContent = '+'; increase.className = 'increase'; var decrease = document.createElement('button'); decrease.textContent = '-'; decrease.className = 'decrease'; inputs[input].insertAdjacentElement('beforebegin', decrease); inputs[input].insertAdjacentElement('afterend', increase); } } // Submit match data. pg.submit.onclick = function() { if ( // If the user has entered a team number and match number pg.team.value && pg.match.value && pg.color.value && pg.position.value !== 'Position' ) { // Store current match, which will later be incremented by 1 var currentMatch = parseInt(pg.match.value); // Make empty match object var match = {}; // Go through each input in the data object and fill in the data from it for (input in inputs) { // Input the values from each input into the data object. // Need to get different data depending on the type of the input. switch (inputs[input].type) { case 'checkbox': // Set this data point to a boolean of whether or not the checkbox is checked match[input] = inputs[input].checked; break; case 'number': // Make this data point be the parsed integer value of that input match[input] = parseInt(inputs[input].value); break; default: // Just use the raw string data match[input] = inputs[input].value; break; } } // Save the current match and position. The match will later be increased by one. write(match); resetInputs(); pg.match.value = currentMatch + 1; } else { window.alert('You must enter a team number, color, position, and match!'); } }; function write(match) { var data = (fs.existsSync(path) && fs.statSync(path).size > 0) ? JSON.parse(fs.readFileSync(path)) : []; for (var i = 0; i < data.length; i++) { if (data[i].match === match.match && data[i].team === match.team) { if (confirm('Do you want to replace the previous data for this match?')) { data.splice(i--, 1); } } } data.push(match); // Write data to file. // Very occasionally, this will return JSON that uses WYSIWYG-style quotes (“”), rather // than JSON-standard, side-ambiguous, utf-8 quotes (""). This breaks JSON parsing later on. // Since it's as yet unclear why that issue occurs, just replace via regex for now. fs.writeFileSync(path, JSON.stringify(data).replace(/[“”]/, '"')); } // Reset all fields. function resetInputs() { // For each input, reset to default value. for (input in inputs) { // Check if the element's class contains keep if (inputs[input].classList && inputs[input].classList.contains('keep')) continue; // Reset to different values depending on what type of input it is if (inputs[input].type === 'number' && !inputs[input].classList.contains('large')) inputs[input].value = 0; // If it's a small number box else if (inputs[input].type === 'checkbox') inputs[input].checked = false; // Checkbox else if (inputs[input].tagName === 'SELECT') inputs[input].value = 'None'; // Selector else inputs[input].value = ''; } pg.team.focus(); console.log('Reset inputs.'); } pg.red.onclick = function() { if (this.style.background === '') { this.style.background = 'rgb(209, 39, 39)'; pg.blue.style.background = ''; pg.color.value = 'Red'; } else { this.style.background = ''; pg.color.value = ''; } } pg.blue.onclick = function() { if (this.style.background === '') { this.style.background = '#1d7ac8'; pg.red.style.background = ''; pg.color.value = 'Blue'; } else { this.style.background = ''; pg.color.value = ''; } } // When reset button is clicked, trigger reset pg.reset.onclick = function() { if (window.confirm('Really reset inputs?')) resetInputs(); }; // When 'View Data' button is clicked pg.view.onclick = function() { // Store the path to the data document localStorage.path = path; // Tell main.js to open rendered data window ipc.send('renderData'); }; // When user clicks on the screen, check if they clicked on an increase/decrease button onclick = function(e) { // If click was on a decrease button, decrease the value of the adjacent input (but only if it's over 0) if (e.target.className === 'decrease' && e.target.nextElementSibling.value > 0) e.target.nextElementSibling.value = parseInt(e.target.nextElementSibling.value) - 1; // If click was on an increase button, increase the value of the adjacent input. If the button correlates to a rocket input, only increase if it is under the max // if (e.target.className === 'increase') e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1; if (e.target.className === 'increase') { if (e.target.previousElementSibling.hasAttribute('max')) { if (e.target.previousElementSibling.value < e.target.previousElementSibling.attributes.max.value) e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1; } else e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1; } };
JavaScript
0
@@ -2498,16 +2498,8 @@ == ' -Position '%0A
1281ea3973376265e0d25b575110f10bddcb5416
Make jsdoc the default task
gulpfile.js
gulpfile.js
var gulp = require('gulp'), jsdoc = require('gulp-jsdoc'), docsSrcDir = './assets/js/**/*.js', docsDestDir = './docs/js', jsDocTask; jsDocTask = function() { return gulp.src(docsSrcDir) .pipe( jsdoc(docsDestDir, { path: './node_modules/jaguarjs-jsdoc', applicationName: 'Dough JavaScript', cleverLinks: true, copyright: 'Copyright Money Advice Service &copy;', linenums: true, collapseSymbols: false }, { plugins: ['plugins/markdown'], } ) ); }; gulp.task('jsdoc', jsDocTask); gulp.task('watch', function() { jsDocTask(); gulp.watch(docsSrcDir, ['jsdoc']); });
JavaScript
0.998521
@@ -581,16 +581,49 @@ );%0A%7D;%0A%0A +gulp.task('default', %5B'jsdoc'%5D);%0A gulp.tas @@ -645,17 +645,16 @@ cTask);%0A -%0A gulp.tas
e9067acbfbf60adbf648c2c84f6584b275077b7b
Update lib/exfat: Add constants & ExFAT.test()
lib/exfat.js
lib/exfat.js
var EXFAT = module.exports
JavaScript
0
@@ -1,27 +1,1955 @@ var -EXFAT = module.exports +FSError = require( './error' )%0Avar ExFAT = module.exports%0A%0AExFAT.FIRST_DATA_CLUSTER = 2%0AExFAT.LAST_DATA_CLUSTER = 0xFFFFFFF6%0A%0AExFAT.CLUSTER_FREE = 0x00000000 // free cluster%0AExFAT.CLUSTER_BAD = 0xFFFFFFF7 // cluster contains bad sector%0AExFAT.CLUSTER_END = 0xFFFFFFFF // final cluster of file or directory%0A%0AExFAT.STATE_MOUNTED = 2%0A%0AExFAT.ENAME_MAX = 15%0A%0AExFAT.ATTR_RO = 0x01%0AExFAT.ATTR_HIDDEN = 0x02%0AExFAT.ATTR_SYSTEM = 0x04%0AExFAT.ATTR_VOLUME = 0x08%0AExFAT.ATTR_DIR = 0x10%0AExFAT.ATTR_ARCH = 0x20%0A%0AExFAT.FLAG_ALWAYS = ( 1 %3C%3C 0 )%0AExFAT.FLAG_CONTIGUOUS = ( 1 %3C%3C 1 )%0A%0AExFAT.Entry = require( './entry' )%0AExFAT.Node = require( './node' )%0AExFAT.Volume = require( './volume' )%0A%0A/**%0A * Determine whether a boot sector%0A * indicates an ExFAT formatted volume%0A * @param %7BBuffer%7D block%0A * @return %7BBoolean%7D%0A */%0AExFAT.test = function( block ) %7B%0A %0A var vbr = new ExFAT.Volume.BootRecord%0A %0A try %7B%0A vbr.parse( block )%0A %7D catch( err ) %7B%0A return new FSError(%0A FSError.EIO,%0A 'Failed to parse boot sector'%0A )%0A %7D%0A %0A if( vbr.oemName !== 'EXFAT ' )%0A return new FSError(%0A FSError.EIO,%0A 'No exFAT file system found'%0A )%0A %0A if( vbr.sectorBits %3C 9 )%0A return new FSError(%0A FSError.EIO,%0A 'Sector size too small: 2%5E' + vbr.sectorBits + ' bits'%0A )%0A %0A if( vbr.sectorBits + vbr.spcBits %3E 25 )%0A return new FSError(%0A FSError.EIO,%0A 'Cluster size too big: 2%5E' + ( vbr.sectorBits + vbr.spcBits ) + ' bits'%0A )%0A %0A if( vbr.version.major !== 1 %7C%7C vbr.version.minor !== 0 )%0A return new FSError(%0A FSError.EIO,%0A 'Unsupported exFAT version: ' + vbr.version.major + '.' + vbr.version.minor%0A )%0A %0A if( vbr.fatCount !== 1 )%0A return new FSError(%0A FSError.EIO,%0A 'Unsupported FAT count: ' + vbr.fatCount%0A )%0A %0A // TODO: in volume.mount()%0A // - Verify checksum%0A // - FS larger than underlying device (?)%0A // - Upcase table not found%0A // - Cluster bitmap not found%0A %0A%7D %0A
347eabdc8f4aff8507bacc165bd375ffe4a044da
Add test for maths with string
test/helpers/math_test.js
test/helpers/math_test.js
/** * Handlebars Helpers Tests: Math Helpers * http://github.com/assemble/handlebars-helpers * Copyright (c) 2013 Jon Schlinkert, Brian Woodward, contributors * Licensed under the MIT License (MIT). */ // node_modules require('should'); var Handlebars = require('handlebars'); // Local helpers require('../../lib/helpers/helpers-math').register(Handlebars, {}); var context = { value: 5 }; describe('add', function() { describe('{{add value 5}}', function() { it('should return the sum of two numbers.', function() { var source = '{{add value 5}}'; var template = Handlebars.compile(source); template(context).should.equal('10'); }); }); }); describe('subtract', function() { describe('{{subtract value 5}}', function() { it('should return the difference of two numbers.', function() { var source = '{{subtract value 5}}'; var template = Handlebars.compile(source); template(context).should.equal('0'); }); }); }); describe('divide', function() { describe('{{divide value 5}}', function() { it('should return the division of two numbers.', function() { var source = '{{divide value 5}}'; var template = Handlebars.compile(source); template(context).should.equal('1'); }); }); }); describe('multiply', function() { describe('{{multiply value 5}}', function() { it('should return the multiplication of two numbers.', function() { var source = '{{multiply value 5}}'; var template = Handlebars.compile(source); template(context).should.equal('25'); }); }); }); describe('floor', function() { describe('{{floor 5}}', function() { it('should return the value rounded down to the nearest integer.', function() { var source = '{{floor value}}'; var template = Handlebars.compile(source); template(context = { value: 5.6 }).should.equal('5'); }); }); }); describe('ceil', function() { describe('{{ceil 5}}', function() { it('should return the value rounded up to the nearest integer.', function() { var source = '{{ceil value}}'; var template = Handlebars.compile(source); template(context = { value: 5.6 }).should.equal('6'); }); }); }); describe('round', function() { describe('{{round 5}}', function() { it('should return the value rounded to the nearest integer.', function() { var source = '{{round value}}'; var template = Handlebars.compile(source); template(context = { value: 5.69 }).should.equal('6'); }); }); }); describe('sum', function() { describe('{{sum value 67 80}}', function() { it('should return the sum of multiple numbers.', function() { var source = '{{sum value 67 80}}'; var template = Handlebars.compile(source); template(context = { value: 20 }).should.equal('167'); }); }); }); describe('sum', function() { describe('{{sum 1 2 3}}', function() { it('should return the sum of multiple numbers.', function() { var source = '{{sum 1 2 3}}'; var template = Handlebars.compile(source); template().should.equal('6'); }); }); }); describe('sum', function() { describe('{{sum value}}', function() { it('should return the total sum of array.', function() { var source = '{{sum value}}'; var template = Handlebars.compile(source); template(context = { value: [1, 2, 3] }).should.equal('6'); }); }); }); describe('sum', function() { describe('{{sum value 5}}', function() { it('should return the total sum of array and numbers.', function() { var source = '{{sum value 5}}'; var template = Handlebars.compile(source); template(context = { value: [1, 2, 3] }).should.equal('11'); }); }); });
JavaScript
0.00327
@@ -2898,32 +2898,356 @@ %7D);%0A %7D);%0A%7D);%0A%0A +describe('sum', function() %7B%0A describe('%7B%7Bsum %22value%22 10%7D%7D', function() %7B%0A it('should return the sum of multiple numbers.', function() %7B%0A var source = '%7B%7Bsum value 10%7D%7D';%0A var template = Handlebars.compile(source);%0A template(context = %7B%0A value: %2220%22%0A %7D).should.equal('30');%0A %7D);%0A %7D);%0A%7D);%0A%0A describe('sum',
b8f90d21758fc96c16ebf77bbb3aa56fee8bf56c
Allow empty comment text
application/routes.js
application/routes.js
/* These are routes as defined in https://docs.google.com/document/d/1337m6i7Y0GPULKLsKpyHR4NRzRwhoxJnAZNnDFCigkc/edit# Each route implementes a basic parameter/payload validation and a swagger API documentation description */ 'use strict'; const Joi = require('joi'), handlers = require('./controllers/handler'); module.exports = function(server) { //Get discussion with content id id from database and return the entire tree (when not available, return NOT FOUND). Validate id server.route({ method: 'GET', path: '/discussion/{content_kind}/{id}', handler: handlers.getDiscussion, config: { validate: { params: { content_kind: Joi.string().valid('deck', 'slide'), id: Joi.string() }, }, tags: ['api'], description: 'Get a discussion' } }); //Get discussion with content id id from database and return the entire tree (when not available, return NOT FOUND). Validate id server.route({ method: 'GET', path: '/discussion/{id}', handler: handlers.getDiscussion, config: { validate: { params: { id: Joi.string() }, }, tags: ['api'], description: 'Get a discussion (for slides)' } }); //Get the number of comments in a discussion with content id id from database server.route({ method: 'GET', path: '/discussion/count/{content_kind}/{id}', handler: handlers.getDiscussionCount, config: { validate: { params: { content_kind: Joi.string().valid('deck', 'slide'), id: Joi.string() }, }, tags: ['api'], description: 'Get the number of comments in a discussion' } }); //Get all discussions from database and return the entire tree (when not available, return NOT FOUND). server.route({ method: 'GET', path: '/discussion/all', handler: handlers.getAllDiscussions, config: { tags: ['api'], description: 'Get all discussions' } }); //Get comment with id id from database and return it (when not available, return NOT FOUND). Validate id server.route({ method: 'GET', path: '/comment/{id}', handler: handlers.getComment, config: { validate: { params: { id: Joi.string() }, }, tags: ['api'], description: 'Get a comment' } }); //Create new comment (by payload) and return it (...). Validate payload server.route({ method: 'POST', path: '/comment/new', handler: handlers.newComment, config: { validate: { payload: Joi.object().keys({ title: Joi.string(), text: Joi.string(), user_id: Joi.string(), content_id: Joi.string(), content_kind: Joi.string().valid('deck', 'slide'), parent_comment: Joi.string(), is_activity: Joi.boolean() }).requiredKeys('content_id', 'user_id'), }, tags: ['api'], description: 'Create a new comment' } }); //Update comment with id id (by payload) and return it (...). Validate payload server.route({ method: 'PUT', path: '/comment/{id}', handler: handlers.updateComment, config: { validate: { params: { id: Joi.string().alphanum().lowercase() }, payload: Joi.object().keys({ title: Joi.string(), text: Joi.string(), user_id: Joi.string(), content_id: Joi.string(), content_kind: Joi.string().valid('deck', 'slide'), parent_comment: Joi.string(), is_activity: Joi.boolean() }).requiredKeys('content_id', 'user_id'), }, tags: ['api'], description: 'Replace a comment' } }); //Delete comment with id id (by payload) . Validate payload server.route({ method: 'DELETE', path: '/comment/delete', handler: handlers.deleteComment, config: { validate: { payload: { id: Joi.string() }, }, tags: ['api'], description: 'Delete a comment' } }); //Delete discussion with content id id (by payload) . Validate payload server.route({ method: 'DELETE', path: '/discussion/delete', handler: handlers.deleteDiscussion, config: { validate: { payload: { content_id: Joi.string() }, }, tags: ['api'], description: 'Delete a discussion (example id: 8)' } }); };
JavaScript
0.005394
@@ -2668,32 +2668,42 @@ xt: Joi.string() +.allow('') ,%0A user @@ -3410,32 +3410,42 @@ xt: Joi.string() +.allow('') ,%0A user
bfb2995c6d06888d683dffa3a3cd6e4c449c3b0b
Fix incrementing the wrong counter
Terp.js
Terp.js
define(function() { 'use strict'; function Terp() { } var validTerpScripts = new WeakMap(); // modified version of JSON.stringify with specialized whitespace rules function stringifyStepOrBlock(stepOrBlock, indent) { if (typeof stepOrBlock[0] === 'string') { // step mode function stringifyElement(element) { if (typeof element === 'object' && element !== null) { if (!Array.isArray(element)) { throw new SyntaxError('Non-Array objects are not currently supported in TerpScript'); } return stringifyStepOrBlock(element, indent); } return JSON.stringify(element); } return '[' + stepOrBlock.map(stringifyElement).join(', ') + ']'; } if (stepOrBlock.length === 0) return '[ ]'; if (stepOrBlock.length === 1) { indent = indent || ''; var single = stringifyStepOrBlock(stepOrBlock[0], indent); if (!/\n/.test(single)) { return '[ ' + single + ' ]'; } return '[\n' + indent + single + '\n' + indent + ']'; } if (typeof indent !== 'string') { indent = ''; function stringifyStepTop(step) { return stringifyStepOrBlock(step, indent); } return '[\n\n' + stepOrBlock.map(stringifyStepTop).join(',\n') + '\n\n]'; } indent = indent || ''; var newIndent = indent + ' '; function stringifyStep(step) { return stringifyStepOrBlock(step, newIndent); } return '[\n' + newIndent + stepOrBlock.map(stringifyStep).join(',\n' + newIndent) + '\n' + indent + ']'; } var emptyScript = Object.freeze([]); validTerpScripts.set(emptyScript, true); const PARENT_SCOPE = Symbol('scope'); const SCOPE_DEPTH = Symbol('depth'); function toTerpScript(stepOrBlock, okToModify, scope) { if (stepOrBlock.length === 0) return emptyScript; if (stepOrBlock.length === 1 && scope && typeof stepOrBlock[0] === 'string' && stepOrBlock[0] in scope) { return scope[stepOrBlock[0]]; } if (!okToModify) { stepOrBlock = stepOrBlock.slice(); } var scopeDepth = scope ? scope[SCOPE_DEPTH] : 0; var usedScope = false; for (var i = 0; i < stepOrBlock.length; i++) { if (typeof stepOrBlock[i] !== 'object' || stepOrBlock[i] === null || validTerpScripts.has(stepOrBlock[i])) { continue; } if (!Array.isArray(stepOrBlock[i], scope)) { throw new SyntaxError('Non-Array objects are not currently supported in TerpScript'); } stepOrBlock[i] = toTerpScript(stepOrBlock[i], okToModify, scope); if (PARENT_SCOPE in stepOrBlock[i]) { usedScope = true; } if (typeof stepOrBlock[i][0] !== 'string') continue; switch (stepOrBlock[i][0]) { case '</>': if (!scope || scope[SCOPE_DEPTH] !== scopeDepth + 1) { throw new SyntaxError('End-of-Scope step without corresponding Scope step'); } scope = scope[PARENT_SCOPE]; break; case '< >': var newScope = scope ? Object.assign({}, scope) : {}; if (scope) { newScope[PARENT_SCOPE] = scope; newScope[SCOPE_DEPTH] = scope[SCOPE_DEPTH] + 1; } else { newScope[SCOPE_DEPTH] = 0; } for (var j = 1; j < stepOrBlock[i].length; i++) { var scopedName = stepOrBlock[i][j]; if (typeof scopedName !== 'string') { throw new SyntaxError('Scope step parameters must be strings'); } var scopedRef = [scopedName]; scopedRef[PARENT_SCOPE] = newScope; newScope[scopedName] = Object.freeze(scopedRef); } scope = Object.freeze(newScope); break; } } if (usedScope) { stepOrBlock[PARENT_SCOPE] = scope; } else { validTerpScripts.set(stepOrBlock, true); } return Object.freeze(stepOrBlock); } function script(v, isTheOnlyReference) { if (validTerpScripts.has(v)) return v; if (typeof v === 'string') { v = JSON.parse(v); if (!Array.isArray(v)) { throw new SyntaxError('TerpScripts must be contained in an Array'); } return toTerpScript(JSON.parse(v), true); } if (!Array.isArray(v)) { if (typeof v.toJSON !== 'function' || !Array.isArray(v = v.toJSON())) { throw new SyntaxError('TerpScripts must be contained in an Array'); } return toTerpScript(v, true); } return toTerpScript(v, isTheOnlyReference); } Object.assign(Terp, { script: Object.assign(script, { stringify: function(script) { if (typeof script === 'string') { script = JSON.parse(script); if (Array.isArray(script)) { return stringifyStepOrBlock(script); } } else { if (Array.isArray(script)) { return stringifyStepOrBlock(script); } if (typeof script.toJSON === 'function' && Array.isArray(script = script.toJSON())) { return stringifyStepOrBlock(script); } } throw new SyntaxError('TerpScript must be an contained in an Array'); }, empty: emptyScript, }), }); return Terp; });
JavaScript
0.000042
@@ -3327,33 +3327,33 @@ lock%5Bi%5D.length; -i +j ++) %7B%0A
a938613afdc0891b64073323b173c364db519972
RSVP timestamp, boolean
js/rsvp.es6
js/rsvp.es6
/* RSVP Section */ import _ from 'lodash'; import $ from 'jquery'; import {activate, deactivate, isActive, toggle} from "./active.es6"; const MAX_PLUS_NAMES = 4; /* Save info for a guest to Firebase data: { attending: boolean; names: string[]; email: string; address: string; } */ export function saveGuest(data) { var updates = {}; var key = firebase.database().ref().child('guests').push().key; updates['/guests/' + key] = data; return firebase.database().ref().update(updates); } // Takes serialized name-value pairs and forms it for saving function formatData(data) { var names = _(data) .filter((d) => d.name === "guest-name") .map((d) => (d.value || "").trim()) .filter() .value(); return { attending: getValue(data, 'attending'), names: names, email: getValue(data, 'email'), address: getValue(data, 'address') }; } function getValue(data, key) { var obj = _.find(data, (d) => d.name === key); return obj && obj.value; } /* Handle error response */ const saveMsg = "#save-msg"; const errorMsg = "#error-msg"; function onSave() { activate(saveMsg); deactivate(errorMsg); $(rsvpForm).hide(); } function onError(err) { activate(errorMsg); deactivate(saveMsg); if (! err instanceof Error) { err = new Error(err); } try { throw err; } catch (e) { _errs.push(e); } } /* Form elements */ const rsvpForm = "#rsvp-form"; const groupSelector = ".name-group"; const templateClass = "template"; const addGuestBtn = "#add-guest-btn"; const rmGuestBtn = ".rm-action"; const guestTemplate = groupSelector + "." + templateClass; const guestContainer = "#plus-ones"; const submitBtn = "#rsvp-submit-btn"; const requiredSelector = "*[required]:visible"; const emailSelector = "input[type=email]" const errorClass = "has-error"; const attendingYes = '#attending-yes'; const attendingNo = '#attending-no'; const attendingShow = ".attending-show"; const spinner = ".spinner"; export function cloneTemplate() { var newGuest = $(guestTemplate).clone(); newGuest.removeClass(templateClass); $(guestContainer).append(newGuest); newGuest.find(rmGuestBtn).click(function() { $(this).parents(groupSelector).remove(); $(addGuestBtn).prop("disabled", false); }); } export function toggleYesNo() { $(attendingYes).click(function() { $(attendingShow).show(); }); $(attendingNo).click(function() { $(attendingShow).hide(); }); } export function validate() { var hasError = false; $("." + errorClass).removeClass(errorClass); $(rsvpForm).find(requiredSelector).each(function(index, elm) { if (! $(elm).val().trim()) { $(elm).parents('.form-group').first().addClass(errorClass); hasError = true; } }); return !hasError; } export function init() { $(addGuestBtn).click(function(e) { e.preventDefault(); var numChildren = $(guestContainer).children().length; if (numChildren < MAX_PLUS_NAMES) { cloneTemplate(); if (numChildren + 1 >= MAX_PLUS_NAMES) { $(addGuestBtn).prop("disabled", true); } } }); $(submitBtn).click(function(e) { e.preventDefault(); if (validate()) { activate($(submitBtn).find(spinner)); $(submitBtn).prop("disabled", true); var data = $(rsvpForm).serializeArray(); var post = function() { deactivate($(submitBtn).find(spinner)); $(e).prop("disabled", false); }; saveGuest(formatData(data)) .then(onSave, onError) .then(post, post); } }); toggleYesNo(); }
JavaScript
0.999956
@@ -458,16 +458,76 @@ = data;%0A + data.timestamp = firebase.database.ServerValue.TIMESTAMP;%0A return @@ -850,16 +850,26 @@ ending') + === 'yes' ,%0A na
27c42633061780dd3e030ded48155e461eef55d5
Update character
commit.js
commit.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 if ( process.argv[ 2 ] && process.argv[ 3 ] ) { var inFile = process.argv[ 2 ] var outFile = process.argv[ 3 ] if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ] console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep) var outFD = fs.openSync(outFile, 'w') fs.readFile(inFile, function(err,data) { var length = data.length console.info("Bytes: %s", length) try { child_process.execFileSync('/usr/bin/git', ['add', outFile]) } catch (e) { console.error("Couldn't add %s to git: %s", outFile, e) } var args = ['commit', outFile, '-m', 'Update character'] for (var counter = 0; counter < length; counter++) { fs.writeSync(outFD, data
JavaScript
0
@@ -823,12 +823,13 @@ (outFD, data +.
fb5df2ca35a5a33357c674c3db597df182589465
Remove tags in favor of a better solution
src/components/MDX/CovidForm.js
src/components/MDX/CovidForm.js
/** @jsx jsx */ import React, { useEffect } from 'react' //eslint-disable-line import { jsx, Styled } from 'theme-ui' import styled from '@emotion/styled' import PropTypes from 'prop-types' const Modal = styled.div` position: absolute; top: 0; content: ''; transition: all 0.3s; z-index: 2; background: black; width: 100%; height: 100%; opacity: ${props => (props.visible ? '1' : '0')}; visibility: ${props => (props.visible ? 'visible' : 'hidden')}; section { p { line-height: 1.6; margin: 0 0 2em 0; text-align: center; } } ` const Form = styled.form` position: relative; width: 100%; label { padding: 0 16px; } input, textarea { padding: 12px; color: ${props => props.theme.colors.text}; background: ${props => props.theme.colors.secondary}; &::placeholder { color: ${props => props.theme.colors.shadow}; } &:last-child { color: ${props => props.theme.colors.text}; background: ${props => props.theme.colors.shadow}; } } &::invalid { box-shadow: none; } &::required { box-shadow: none; } &::optional { box-shadow: none; } ` const Input = styled.input` margin: 0 0 8px; width: 100%; ` const TextArea = styled.textarea` margin: 0 0 8px; width: 100%; ` const Submit = styled.input` cursor: pointer; transition: 0.2s; width: 100%; font-weight: bold; ` class EmailCapture extends React.Component { constructor(props) { super(props) this.state = { name: '', email: '', restaurant: '', address: '', notes: '', tags: [ { name: 'Covid', }, ], showModal: false, showPrompt: true, } } handleInputChange = event => { const target = event.target const value = target.value const email = target.email const name = target.name const restaurant = target.restaurant const address = target.address const notes = target.notes const tags = [ { name: 'Covid', }, ] this.setState({ [email]: value, [name]: value, [restaurant]: value, [address]: value, [notes]: value, [tags]: value, }) } componentDidMount() { this.handleSubmit = event => { event.preventDefault() this.handleSuccess() window.analytics.identify({ email: this.state.email, name: this.state.name, restaurant: this.state.restaurant, address: this.state.address, notes: this.state.notes, tags: [ { name: 'Covid', }, ], }) } } handleSuccess = () => { this.setState({ email: '', name: '', restaurant: '', address: '', notes: '', tags: [ { name: 'Covid', }, ], showModal: true, showPrompt: false, }) } closeModal = () => { this.setState({ showModal: false, showPrompt: true }) } render(props) { return ( <> <Form name="subscribe" onSubmit={this.handleSubmit} overlay={this.state.visible} onClick={this.closeModal} > <Modal visible={this.state.showModal}> <hr></hr> <Styled.h2 sx={{ fontFamily: 'monospace', color: 'white' }}> Thanks for reaching out. </Styled.h2> <Styled.p sx={{ fontFamily: 'monospace', color: 'white' }}> I'll be in touch. </Styled.p> <Styled.p sx={{ fontFamily: 'monospace', color: 'white' }}> Please note: due to demand, I may not be able to help everyone who requests assistance. Services will be provided on a case-by-case basis. </Styled.p> </Modal> <Styled.p sx={{ fontFamily: 'monospace', color: 'white' }}> * indicates required field </Styled.p> <Input name="name" type="name" placeholder="Name*" value={this.state.name} onChange={this.handleInputChange} required /> <Input name="email" type="email" placeholder="Email*" value={this.state.email} onChange={this.handleInputChange} required /> <Input name="restaurant" type="restaurant" placeholder="Restaurant*" value={this.state.restaurant} onChange={this.handleInputChange} required /> <Input name="address" type="address" placeholder="Address*" value={this.state.address} onChange={this.handleInputChange} required /> <TextArea name="notes" type="notes" placeholder="Notes" value={this.state.notes} onChange={this.handleInputChange} required /> <Submit className="button" name="submit" type="submit" value="Send" /> </Form> </> ) } } EmailCapture.propTypes = { data: PropTypes.object, } export default EmailCapture
JavaScript
0.000002
@@ -1604,77 +1604,8 @@ '',%0A - tags: %5B%0A %7B%0A name: 'Covid',%0A %7D,%0A %5D,%0A @@ -1620,24 +1620,24 @@ dal: false,%0A + showPr @@ -1926,73 +1926,8 @@ tes%0A - const tags = %5B%0A %7B%0A name: 'Covid',%0A %7D,%0A %5D%0A @@ -2062,29 +2062,8 @@ ue,%0A - %5Btags%5D: value,%0A @@ -2607,32 +2607,32 @@ address: '',%0A + notes: '', @@ -2636,77 +2636,8 @@ '',%0A - tags: %5B%0A %7B%0A name: 'Covid',%0A %7D,%0A %5D,%0A
e2a872a1d0558d7b6e5d6e6dbd66be4688d260b0
Add contentEditable to <pre/>
script.js
script.js
function format(flat) { var map = {}; flat.forEach(function(a) { map[a["@id"]] = a; }); var ontology = {}; (function(a) { ontology.version = a["http://www.w3.org/2002/07/owl#versionInfo"][0]["@value"]; ontology.label = a["http://www.w3.org/2000/01/rdf-schema#label"].find(function(a) { return a["@language"] === "ja"; })["@value"]; ontology.comment = a["http://www.w3.org/2000/01/rdf-schema#comment"].find(function(a) { return a["@language"] === "ja"; })["@value"]; })(map["http://imi.go.jp/ns/core/rdf"]); var dig = function(id) { var a = map[id]; var json = { id: id, label: a["http://www.w3.org/2000/01/rdf-schema#label"].find(function(a) { return a["@language"] === "ja"; })["@value"], comment: a["http://www.w3.org/2000/01/rdf-schema#comment"].find(function(a) { return a["@language"] === "ja"; })["@value"] }; json.children = flat.filter(function(a) { return (a["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || []).find(function(b) { return b["@id"] === id; }); }).map(function(a) { return dig(a["@id"]); }); json.properties = (a["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || []).filter(function(b) { return b["@id"].indexOf("_:") === 0; }).map(function(b) { return map[b["@id"]]; }).map(function(b) { var id = b["http://www.w3.org/2002/07/owl#onProperty"][0]["@id"]; var prop = { id: id, min: 0, range: map[id]["http://www.w3.org/2000/01/rdf-schema#range"][0]["@id"] }; if (b["http://www.w3.org/2002/07/owl#maxQualifiedCardinality"]) prop.max = 1; if (b["http://www.w3.org/2002/07/owl#maxCardinality"]) prop.max = 1; return prop; }); return json; }; ontology.root = dig("http://imi.go.jp/ns/core/rdf#概念型"); return ontology; } var defaultInstance = { "http://www.w3.org/2001/XMLSchema#string": "文字列", "http://www.w3.org/2002/07/owl#Thing": "http://example.org/", "http://www.w3.org/2001/XMLSchema#integer": 1234567890, "http://www.w3.org/2001/XMLSchema#nonNegativeInteger": 1234567890, "http://www.w3.org/2001/XMLSchema#date": "2017-05-11", "http://www.w3.org/2001/XMLSchema#time": "00:00:00", "http://www.w3.org/2001/XMLSchema#dateTime": "2017-05-11T00:00:00", "http://www.w3.org/2001/XMLSchema#decimal": 1234.56789, "http://www.w3.org/2001/XMLSchema#double": 10.0e25, "urn:un:unece:uncefact:codelist:standard:ISO:ISO3AlphaCurrencyCode:2012-08-31#ISO3AlphaCurrencyCodeContentType": "YEN" }; fetch("https://imi.go.jp/ns/core/rdf.jsonld").then(function(a) { return a.json(); }).then(function(json) { return new Promise(function(resolve, reject) { jsonld.flatten(json, function(err, flat) { resolve(format(flat)); }); }); }).then(function(ontology) { console.log(ontology); $("#version").text(ontology.version); var render = function(anc) { var a = anc[anc.length - 1]; var div = $("<div class='clazz'/>"); div.attr("id", a.label); $("#menu>ul").append($("<li/>").css("text-indent", (anc.length - 1) + "em").append( $("<a/>").attr("href", "#" + a.label).text(a.label))); var ul = $("<ul/>").appendTo(div); anc.forEach(function(v, i) { var a = $("<a/>").attr("href", "#" + v.label).text(v.label); if (i === anc.length - 1) a = $("<b/>").text(v.label); ul.append($("<li/>").append(a)); }); div.append($("<p/>").text(a.comment)); var compact = function(v) { return v.replace(/.*#/, ""); }; var instance1 = { "@context": "http://imi.go.jp/ns/core/context.jsonld" }; var instance2 = { "@context": "http://imi.go.jp/ns/core/context.jsonld" }; anc.forEach(function(v) { instance1["@type"] = compact(v.id); instance2["@type"] = compact(v.id); v.properties.forEach(function(w) { var val = defaultInstance[w.range] || { "@type": compact(w.range) }; instance1[compact(w.id)] = w.max === 1 ? val : [val]; instance2[compact(w.id)] = val; }); }); div.append($("<button>配列あり</button>").attr("value", JSON.stringify(instance1, null, " "))); div.append($("<button>配列なし</button>").attr("value", JSON.stringify(instance2, null, " "))); div.append($("<pre/>").text(JSON.stringify(instance2, null, " "))); $("#container").append(div); a.children.forEach(function(v) { render(anc.concat(v)); }); }; render([ontology.root]); $("button").click(function() { $(this).parent().find("pre").text($(this).val()); }); });
JavaScript
0
@@ -4339,16 +4339,39 @@ ($(%22%3Cpre + contentEditable='true' /%3E%22).tex
87ea4c854d6a273ad9f32a2e8d03a829059aeb3e
Update YT Native Center Layout/js/script.js
js/script.js
js/script.js
document.body.classList.remove('site-left-aligned'); if(document.getElementById('watch7-video-container').style.backgroundColor == 'rgb(0, 0, 0)')document.body.classList.add('black-video-background')
JavaScript
0
@@ -46,16 +46,52 @@ gned');%0A +var tmp = setInterval(function()%7B%0A if(docum @@ -228,9 +228,62 @@ ground') +;%0A%09if(document.readyState)clearInterval(tmp);%0A%7D,250); %0A
61d4de01c905dde9ad4ad0f6d1e1cf4fbaef8283
no typing text
src/components/Sidebar/index.js
src/components/Sidebar/index.js
import React from 'react' import Logo from './logo' import styled from 'styled-components' import Link from 'gatsby-link' import { TypingText } from '../Intro' import {MobileHide} from '../MobileHide' const Sidebar = ({ className, color, bgColor }) => ( <div className={className}> <Link to="/"> <Logo fill={color || "#000"} hoverfill={color ? '#CCC' : "#0000FF"} /> </Link> <MobileHide> <p>Half of Eight</p> <p><TypingText /></p> </MobileHide> </div> ) const SidebarStyled = styled(Sidebar)` min-width: 250px; width: 15.5%; height: 100%; position: fixed; padding-top: 26px; flex-shrink: 0; flex-grow: 0; text-align: center; font-size: 13px; background-color: ${props => props.bgColor ? props.bgColor : '#fff'}; line-height: 1.7; max-width: 320px; p { color: ${props => props.color ? props.color : '#001d60'}; } ${props => props.color ? `a{ color ${props.color} }` : ''} @media(max-width: 560px){ position: relative; width: 100%; margin: 0 auto; } ` export default SidebarStyled
JavaScript
0.99688
@@ -433,35 +433,8 @@ p%3E %0A - %3Cp%3E%3CTypingText /%3E%3C/p%3E%0A
ada5742a18dd26049a2681d101e6c7b6f2a91dba
use new aliases
gulpfile.js
gulpfile.js
var gulp = require("gulp"); var gutil = require("gulp-util"); var webpack = require("webpack"); var WebpackDevServer = require("webpack-dev-server"); var webpackConfig = require("./webpack.config.js"); // The development server (the recommended option for development) gulp.task("default", ["webpack-dev-server"], function() {}); // Build and watch cycle (another option for development) // Advantage: No server required, can run app from filesystem // Disadvantage: Requests are not blocked until bundle is available, // can serve an old app on refresh gulp.task("build-dev", ["webpack:build-dev"], function() { gulp.watch(["app/**/*"], function(event) { gulp.run("webpack:build-dev"); }); }); // Production build gulp.task("build", ["webpack:build"], function() {}); gulp.task("webpack:build", function(callback) { // modify some webpack config options var myConfig = Object.create(webpackConfig); myConfig.plugins = myConfig.plugins.concat( new webpack.DefinePlugin({ "process.env": { "NODE_ENV": JSON.stringify("production") } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin() ); // run webpack webpack(myConfig, function(err, stats) { if(err) throw new gutil.PluginError("webpack:build", err); gutil.log("[webpack:build]", stats.toString({ colors: true })); callback(); }); }); // modify some webpack config options var myDevConfig = Object.create(webpackConfig); myDevConfig.devtool = "sourcemap"; myDevConfig.debug = true; // create a single instance of the compiler to allow caching var devCompiler = webpack(myDevConfig); gulp.task("webpack:build-dev", function(callback) { // run webpack devCompiler.run(function(err, stats) { if(err) throw new gutil.PluginError("webpack:build-dev", err); gutil.log("[webpack:build-dev]", stats.toString({ colors: true })); callback(); }); }); gulp.task("webpack-dev-server", function(callback) { // modify some webpack config options var myConfig = Object.create(webpackConfig); myConfig.devtool = "eval"; myConfig.debug = true; // Start a webpack-dev-server new WebpackDevServer(webpack(myConfig), { publicPath: "/" + myConfig.output.publicPath, stats: { colors: true } }).listen(8080, "localhost", function(err) { if(err) throw new gutil.PluginError("webpack-dev-server", err); gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html"); }); });
JavaScript
0.000033
@@ -306,31 +306,16 @@ server%22%5D -, function() %7B%7D );%0A%0A// B @@ -637,37 +637,9 @@ %22%5D, -function(event) %7B%0A%09%09gulp.run( +%5B %22web @@ -653,21 +653,17 @@ ild-dev%22 -);%0A%09%7D +%5D );%0A%7D);%0A%0A @@ -722,28 +722,10 @@ ld%22%5D -, function() %7B%7D);%0A%0A%0A +); %0A%0Agu
63e3d946d430b1e4ddf63052365f56d31db193a5
Update index.js
src/components/Sidebar/index.js
src/components/Sidebar/index.js
import React from 'react' import Logo from './logo' import styled from 'styled-components' import Link from 'gatsby-link' import {MobileHide} from '../MobileHide' const Sidebar = ({ className, color, bgColor }) => ( <div className={className}> <Link to="/"> <Logo fill={color || "#000"} hoverfill={color ? '#CCC' : "#0000FF"} /> </Link> <MobileHide> </MobileHide> </div> ) const SidebarStyled = styled(Sidebar)` min-width: 250px; width: 15.5%; height: 100%; position: fixed; padding-top: 26px; flex-shrink: 0; flex-grow: 0; text-align: center; font-size: 13px; background-color: ${props => props.bgColor ? props.bgColor : '#fff'}; line-height: 1.7; max-width: 320px; p { color: ${props => props.color ? props.color : '#001d60'}; } ${props => props.color ? `a{ color ${props.color} }` : ''} @media(max-width: 560px){ position: relative; width: 100%; margin: 0 auto; } ` export default SidebarStyled
JavaScript
0.000002
@@ -366,16 +366,121 @@ Hide%3E%0A + %3Cp%3EFour, simply divided. Three, cut vertically down the middle. Zero, cut horizontally.%3C/p%3E%0A %3C/p%3E %0A %3C/M
081c0fab13e45237b23010275e37a7be900123f0
rename help -> repository to website
src/menu.js
src/menu.js
'use strict'; const electron = require('electron'); const view = require('./menu/view'); module.exports = function menu(page) { const insertCSS = require('./insert-css')(page); function addTheme(label, file) { return { label, file, click() { insertCSS(file); page.reload(); } }; } const tpl = [ view, { label: 'Themes', submenu: [ addTheme('default', 'none'), addTheme('HNU', 'hnu.css'), addTheme('HNU Night mode', 'hnu-night.css'), addTheme('Lost sunset', 'lost-sunset.css'), addTheme('Haxxor', 'haxxor.css') ] }, { label: 'Help', submenu: [ { label: 'Repository', click() { electron.shell.openExternal('https://github.com/bjarneo/HNU'); } } ] } ]; return electron.Menu.buildFromTemplate(tpl); };
JavaScript
0
@@ -875,18 +875,15 @@ l: ' -Repository +Website ',%0A
875147c8d65c425980196b5923b0b7a79282da5d
add new props
src/components/Sidebar/index.js
src/components/Sidebar/index.js
import React from 'react' import Profile from '../Profile' import SocialLinks from '../SocialLinks' import MenuLinks from '../MenuLinks' import * as S from './styled' const Sidebar = () => ( <S.SidebarWrapper> <Profile /> <SocialLinks /> <MenuLinks /> </S.SidebarWrapper> ) export default Sidebar
JavaScript
0
@@ -15,15 +15,51 @@ rom -' +%22 react -' +%22%0Aimport propTypes from %22prop-types%22%0A %0Aimp @@ -75,17 +75,17 @@ le from -' +%22 ../Profi @@ -86,17 +86,17 @@ /Profile -' +%22 %0Aimport @@ -112,17 +112,17 @@ ks from -' +%22 ../Socia @@ -127,17 +127,17 @@ ialLinks -' +%22 %0Aimport @@ -151,17 +151,17 @@ ks from -' +%22 ../MenuL @@ -164,17 +164,17 @@ enuLinks -' +%22 %0A%0Aimport @@ -219,52 +219,251 @@ = ( -) =%3E (%0A %3CS.SidebarWrapper%3E%0A %3CProfile /%3E%0A +%7B%0A site: %7B title, position %7D,%0A isMenuOpen,%0A setIsMenuOpen%0A%7D) =%3E (%0A %3CS.SidebarContainer isMenuOpen=%7BisMenuOpen%7D%3E%0A %3CProfile%0A title=%7Btitle%7D%0A position=%7Bposition%7D%0A isMobileHeader=%7Bfalse%7D%0A /%3E%0A %3CS.SidebarLinksContainer%3E%0A @@ -482,16 +482,18 @@ /%3E%0A + %3CMenuLin @@ -494,22 +494,100 @@ enuLinks +%0A setIsMenuOpen=%7BsetIsMenuOpen%7D%0A isMenuOpen=%7BisMenuOpen%7D%0A /%3E%0A + + %3C/S.Side @@ -593,18 +593,188 @@ ebar -Wrapper%3E%0A) +LinksContainer%3E%0A %3C/S.SidebarContainer%3E%0A)%0A%0ASidebar.propTypes = %7B%0A site: propTypes.shape(%7B%0A title: propTypes.string.isRequired,%0A position: propTypes.string.isRequired,%0A %7D)%0A%7D %0A%0Aex
a02f9adab874e2a4ccc2791b24c3b1ff289a18c5
Add support for CommonJS
js/stone.js
js/stone.js
/* * Copyright (c) 2014, Fabien LOISON <http://flozz.fr> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var Stone = (function(window, undefined) { var catalogs = {}; var locale = null; function LazyString(string, replacements) { this.toString = gettext.bind(this, string, replacements); } function gettext(string, replacements) { var result = string; if (locale && catalogs[locale] && catalogs[locale][string]) { result = catalogs[locale][string]; } if (replacements) { for (var r in replacements) { result = result.replace(new RegExp("\{" + r + "\}", "g"), replacements[r]); } } return result; } function lazyGettext(string, replacements) { return new LazyString(string, replacements); } function addCatalogs(newCatalogs) { for (var locale in newCatalogs) { catalogs[locale] = newCatalogs[locale]; } } function getLocale() { return locale; } function setLocale(l) { locale = l; var ev = null; try { ev = new Event("stonejs-locale-changed"); } catch (e) { // The old-fashioned way... THANK YOU MSIE! ev = document.createEvent("Event"); ev.initEvent("stonejs-locale-changed", true, false); } document.dispatchEvent(ev); } function guessUserLanguage() { var lang = navigator.language || navigator.userLanguage || navigator.systemLanguage || navigator.browserLanguage || null; if (lang) { lang = lang.toLowerCase(); } if (lang && lang.length > 3) { lang = lang.split(";")[0]; lang = lang.split(",")[0]; lang = lang.split("-")[0]; lang = lang.split("_")[0]; if (lang.length > 3) { lang = null; } } return lang || "en"; } return { LazyString: LazyString, gettext: gettext, lazyGettext: lazyGettext, addCatalogs: addCatalogs, getLocale: getLocale, setLocale: setLocale, guessUserLanguage: guessUserLanguage } })(window);
JavaScript
0
@@ -1589,48 +1589,492 @@ */%0A%0A -%0Avar Stone = (function(window, undefined + (function (root, factory) %7B%0A // Assign to module.exports if the environment supports CommonJS.%0A // If root.Stone is already defined/truthy, use a Browser version nonetheless.%0A // %5E Useful for nw.js or atom-shell where you might want to still use the global version.%0A if(typeof module === %22object%22 && module.exports && !root.Stone) %7B%0A module.exports = factory();%0A %0A // Otherwise use a global variable.%0A %7D else %7B%0A root.Stone = factory();%0A %7D%0A %0A %7D(this, function( ) %7B%0A @@ -4180,17 +4180,9 @@ %7D%0A -%0A %7D) -(window );%0A
7f8e47351a5e012588534311d97eaa1cd75bf6cd
Add debouncing canvas resizing
script.js
script.js
JavaScript
0
@@ -0,0 +1,815 @@ +(function() %7B%0A%09'use strict';%0A%0A%09var scaleFactor,%0A%09 canvas = document.getElementById('canvas'),%0A%09 ctx = canvas.getContext('2d'),%0A%09 CANVAS_DEFAULT_WIDTH = 640,%0A%09 CANVAS_DEFAULT_HEIGHT = 480;%0A%0A%09(function initCanvasResizing() %7B%0A%09%09var debounceTmt = null;%0A%0A%09%09function setCanvasSize() %7B%0A%09%09%09var wWidth = window.innerWidth,%0A%09%09%09 wHeight = window.innerHeight;%0A%09%09%09canvas.width = wWidth;%0A%09%09%09canvas.height = wHeight;%0A%09%09%09console.log('Canvas size is set to ' + wWidth + 'x' + wHeight);%0A%0A%09%09%09scaleFactor = Math.min(wWidth/CANVAS_DEFAULT_WIDTH, wHeight/CANVAS_DEFAULT_HEIGHT);%0A%09%09%09console.log('Scale factor is set to ' + scaleFactor);%0A%09%09%7D%0A%0A%09%09window.onresize = function() %7B%0A%09%09%09clearTimeout(debounceTmt);%0A%09%09%09debounceTmt = setTimeout(setCanvasSize, 100);%0A%09%09%7D;%0A%0A%09%09//initial canvas size setting%0A%09%09setCanvasSize();%0A%09%7D)();%0A%7D)();
df4b72b77cf2b8e0ab20680bae748e1a2627f516
Update script.js
js/script.js
js/script.js
(function(window, document, undefined) { window.onload = init; function init() { //get the canvas var canvas = document.getElementById("mapcanvas"); var c = canvas.getContext("2d"); var width = 1280; var height = 720; var blockSize = 16; var leftright = "none"; var updown = "none"; var levelCount = 3; document.getElementById("paintbtn").onclick = paint; function createNext(updown, leftright, prevX, prevY){ switch(updown){ case up: switch(leftright){ case left: //18, 19, 0, 1 break; case right: //3, 4, 5, 6 break; default: //1, 2 ,3 } break; case down: switch(leftright){ case left: //13, 14, 15, 16 break; case right: //8, 9, 10, 11 break; default: //11, 12, 13 } break; default: switch(leftright){ case left: //16, 17, 18 break; case right: //6, 7, 8 break; default: //none } } var newX = 0; var newY = 0; return [newX, newY]; } function drawLevel(x, y){ c.rect(x,y,90,90); for(var i = 0; i< 3; i++){ for(var j = 0; j< 3; j++){ c.rect((width/2) + i*30, (height/2) + j*30, 30, 30); c.stroke(); } } } //paint the map function paint() { var lvlselect = document.getElementById("levelcount"); var dir1 = document.getElementsByName("leftright"); var dir2 = document.getElementsByName("updown"); for(var i = 0, length = dir1.length; i < length; i++){ if (dir1[i].checked) { // do whatever you want with the checked radio leftright = dir1[i].value; // only one radio can be logically checked, don't check the rest break; } } for(var i = 0, length = dir2.length; i < length; i++){ if (dir2[i].checked) { // do whatever you want with the checked radio updown = dir2[i].value; // only one radio can be logically checked, don't check the rest break; } } levelCount = lvlselect.options[lvlselect.selectedIndex].value; alert(updown+","+ leftright+","+ levelCount); var current = 0; var prevX = width/2; var prevY = height/2; drawLevel(prevX, prevY); while(current < levelCount){ var newCords = createNext(updown, leftright, prevX, prevY); var newX = newCords[0]; var newY = newCords[1]; drawLevel(newX, newY); prevX = newX; prevY = newY; current++; } } } })(window, document, undefined);
JavaScript
0.000002
@@ -682,18 +682,23 @@ -// +alert(%22 18, 19, @@ -701,16 +701,19 @@ 19, 0, 1 +%22); %0A @@ -804,18 +804,23 @@ -// +alert(%22 3, 4, 5, @@ -821,16 +821,19 @@ 4, 5, 6 +%22); %0A @@ -921,17 +921,25 @@ -// +alert(%22 1, 2 ,3 +%22); %0A @@ -1113,18 +1113,23 @@ -// +alert(%22 13, 14, @@ -1134,16 +1134,19 @@ , 15, 16 +%22); %0A @@ -1237,18 +1237,23 @@ -// +alert(%22 8, 9, 10 @@ -1256,16 +1256,19 @@ , 10, 11 +%22); %0A @@ -1352,18 +1352,23 @@ -// +alert(%22 11, 12, @@ -1369,16 +1369,19 @@ , 12, 13 +%22); %0A @@ -1549,18 +1549,23 @@ -// +alert(%22 16, 17, @@ -1566,16 +1566,19 @@ , 17, 18 +%22); %0A @@ -1673,17 +1673,25 @@ -// +alert(%22 6, 7, 8 +%22); %0A @@ -1783,14 +1783,22 @@ -// +alert(%22 none +%22); %0A
0a8d45f29f5dfead2db3c3989562e9e93d58347d
update Anchor
src/Anchor/Anchor.js
src/Anchor/Anchor.js
/** * @file Anchor component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import CircularLoading from '../CircularLoading'; import TipProvider from '../TipProvider'; import Theme from '../Theme'; import Util from '../_vendors/Util'; class Anchor extends Component { static Theme = Theme; constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { focused: false }; } clickHandler = e => { const {disabled, isLoading, onClick} = this.props; !disabled && !isLoading && onClick && onClick(e); }; focusHandler = e => { this.setState({ focused: true }, () => { const {onFocus} = this.props; onFocus && onFocus(e); }); }; blurHandler = e => { this.setState({ focused: false }, () => { const {onBlur} = this.props; onBlur && onBlur(e); }); }; render() { const { children, className, style, theme, iconCls, rightIconCls, disabled, isLoading, tip, tipPosition, parentEl, ...restProps } = this.props, {focused} = this.state, anchorClassName = classNames('anchor', { focused: focused, [`theme-${theme}`]: theme, [className]: className }), loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left'; return ( <TipProvider tipContent={tip} parentEl={parentEl} position={tipPosition}> <a {...restProps} className={anchorClassName} style={style} disabled={disabled || isLoading} onClick={this.clickHandler} onFocus={this.focusHandler} onBlur={this.blurHandler}> { isLoading && loadingIconPosition === 'left' ? <CircularLoading className="anchor-icon anchor-icon-left button-loading-icon" size="small"/> : ( iconCls ? <i className={`anchor-icon anchor-icon-left ${iconCls}`} aria-hidden="true"></i> : null ) } {children} { isLoading && loadingIconPosition === 'right' ? <CircularLoading className="anchor-icon anchor-icon-right button-loading-icon" size="small"/> : ( rightIconCls ? <i className={`anchor-icon anchor-icon-right ${rightIconCls}`} aria-hidden="true"></i> : null ) } </a> </TipProvider> ); } } Anchor.propTypes = { className: PropTypes.string, style: PropTypes.object, theme: PropTypes.oneOf(Util.enumerateValue(Theme)), href: PropTypes.string, alt: PropTypes.string, target: PropTypes.string, disabled: PropTypes.bool, readOnly: PropTypes.bool, isLoading: PropTypes.bool, iconCls: PropTypes.string, rightIconCls: PropTypes.string, tip: PropTypes.string, tipPosition: PropTypes.string, onClick: PropTypes.func, onFocus: PropTypes.func, onBlur: PropTypes.func }; Anchor.defaultProps = { theme: Theme.DEFAULT, href: 'javascript:void(0)', target: '_blank', disabled: false, readOnly: false, isLoading: false }; export default Anchor;
JavaScript
0.000002
@@ -286,16 +286,17 @@ vider';%0A +%0A import T @@ -317,17 +317,16 @@ Theme';%0A -%0A import U @@ -564,28 +564,27 @@ %7D%0A%0A -clickHandler +handleClick = e =%3E @@ -714,28 +714,27 @@ %7D;%0A%0A -focusHandler +handleFocus = e =%3E @@ -905,26 +905,25 @@ %7D;%0A%0A -blurH +h andle +Blu r = e =%3E @@ -1250,32 +1250,16 @@ osition, -%0A parentE @@ -1360,195 +1360,8 @@ te,%0A -%0A anchorClassName = classNames('anchor', %7B%0A focused: focused,%0A %5B%60theme-$%7Btheme%7D%60%5D: theme,%0A %5BclassName%5D: className%0A %7D),%0A%0A @@ -1660,23 +1660,189 @@ me=%7B -anchorClassName +classNames('anchor', %7B%0A focused: focused,%0A %5B%60theme-$%7Btheme%7D%60%5D: theme,%0A %5BclassName%5D: className%0A %7D) %7D%0A @@ -1961,20 +1961,19 @@ his. -clickHandler +handleClick %7D%0A @@ -2007,20 +2007,19 @@ his. -focusHandler +handleFocus %7D%0A @@ -2052,18 +2052,17 @@ his. -blurH +h andle +Blu r%7D%3E%0A @@ -3491,24 +3491,54 @@ pTypes = %7B%0A%0A + children: PropTypes.any,%0A%0A classNam @@ -3949,24 +3949,57 @@ es.string,%0A%0A + parentEl: PropTypes.object,%0A%0A onClick:
a782113c70ddb445a36b097d7eaf743383e55300
Fix bad module for templates
gulpfile.js
gulpfile.js
var gulp = require('gulp'), gulpif = require('gulp-if'), concat = require('gulp-concat'), rimraf = require('gulp-rimraf'), templateCache = require('gulp-angular-templatecache'), minifyHtml = require('gulp-minify-html'), es = require('event-stream'), sass = require('gulp-sass'), rename = require('gulp-rename'), ngAnnotate = require('gulp-ng-annotate'), uglify = require('gulp-uglify'), minifyCSS = require('gulp-minify-css'), webserver = require('gulp-webserver'), argv = require('yargs').argv; var paths = { appJavascript: ['app/js/app.js', 'app/js/**/*.js'], appTemplates: 'app/js/**/**.tpl.html', appMainSass: 'app/scss/main.scss', appStyles: 'app/scss/**/*.scss', indexHtml: 'app/index.html', vendorJavascript: ['vendor/js/angular.js', 'vendor/js/**/*.js'], tmpFolder: '.tmp', tmpJavascript: '.tmp/js', tmpCss: '.tmp/css', distFolder: 'dist', distJavascript: 'dist/js', distCss: 'dist/css' }; gulp.task('scripts', function() { return gulp.src(paths.vendorJavascript.concat(paths.appJavascript, paths.appTemplates)) .pipe(gulpif(/html$/, buildTemplates())) .pipe(concat('app.js')) .pipe(gulpif(argv.production, ngAnnotate())) .pipe(gulpif(argv.production, uglify())) .pipe(gulpif(argv.production, gulp.dest(paths.distJavascript), gulp.dest(paths.tmpJavascript))); }); gulp.task('styles', function() { return gulp.src(paths.appMainSass) .pipe(sass()) .pipe(gulpif(argv.production, minifyCSS())) .pipe(rename('app.css')) .pipe(gulpif(argv.production, gulp.dest(paths.distCss), gulp.dest(paths.tmpCss))); }); gulp.task('indexHtml', function() { return gulp.src(paths.indexHtml) .pipe(gulpif(argv.production, gulp.dest(paths.distFolder), gulp.dest(paths.tmpFolder))) }); gulp.task('clean', function() { return gulp.src([paths.tmpFolder, paths.distFolder], {read: false}) .pipe(rimraf()); }); gulp.task('watch', ['webserver'], function() { gulp.watch(paths.appJavascript, ['scripts']); gulp.watch(paths.appTemplates, ['scripts']); gulp.watch(paths.vendorJavascript, ['scripts']); gulp.watch(paths.indexHtml, ['indexHtml']); gulp.watch(paths.appStyles, ['styles']); }); gulp.task('webserver', ['scripts', 'styles', 'indexHtml'], function() { gulp.src(paths.tmpFolder) .pipe(webserver({ port: 5000, proxies: [ { source: '/api', target: 'http://localhost:8080/api' } ] })); }); gulp.task('default', ['scripts', 'styles', 'indexHtml']); function buildTemplates() { return es.pipeline( minifyHtml({ empty: true, spare: true, quotes: true }), templateCache() ); }
JavaScript
0.000001
@@ -1935,16 +1935,17 @@ older))) +; %0A%7D);%0A%0Agu @@ -2831,12 +2831,39 @@ che( +%7B%0A module: 'app'%0A %7D )%0A );%0A%7D @@ -2858,12 +2858,13 @@ %7D)%0A );%0A%7D +%0A
4b97e3c9adf65220e2baa093070b8c4380470bbc
add .only() helper to tests
test/lib/alloc-cluster.js
test/lib/alloc-cluster.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var async = require('async'); var extend = require('xtend'); var CountedReadySignal = require('ready-signal/counted'); var test = require('tape'); var util = require('util'); var TChannel = require('../../channel.js'); var parallel = require('run-parallel'); var debugLogtron = require('debug-logtron'); module.exports = allocCluster; function allocCluster(opts) { opts = opts || {}; var host = 'localhost'; var logger = debugLogtron('tchannel', { enabled: true }); var cluster = { logger: logger, hosts: new Array(opts.numPeers), channels: new Array(opts.numPeers), destroy: destroy, ready: CountedReadySignal(opts.numPeers), assertCleanState: assertCleanState }; var channelOptions = extend({ logger: logger }, opts.channelOptions || opts); for (var i = 0; i < opts.numPeers; i++) { createChannel(i); } return cluster; function assertCleanState(assert, expected) { cluster.channels.forEach(function eachChannel(chan, i) { var chanExpect = expected.channels[i]; if (!chanExpect) { assert.fail(util.format('unexpected channel[%s]', i)); return; } var peers = chan.peers.values(); assert.equal(peers.length, chanExpect.peers.length, util.format( 'channel[%s] should have %s peer(s)', i, chanExpect.peers.length)); peers.forEach(function eachPeer(peer, j) { var peerExpect = chanExpect.peers[j]; if (!peerExpect) { assert.fail(util.format( 'unexpected channel[%s] peer[%s]', i, j)); return; } peer.connections.forEach(function eachConn(conn, k) { var connExpect = peerExpect.connections[k]; if (!connExpect) { assert.fail(util.format( 'unexpected channel[%s] peer[%s] conn[%s]', i, j, k)); return; } Object.keys(connExpect).forEach(function eachProp(prop) { var desc = util.format( 'channel[%s] peer[%s] conn[%s] should .%s', i, j, k, prop); switch (prop) { case 'inReqs': assert.equal(Object.keys(conn.requests.in).length, connExpect.inReqs, desc); break; case 'outReqs': assert.equal(Object.keys(conn.requests.out).length, connExpect.outReqs, desc); break; default: assert.equal(conn[prop], connExpect[prop], desc); } }); }); }); }); } function createChannel(i) { var chan = TChannel(extend(channelOptions)); var port = opts.listen && opts.listen[i] || 0; chan.listen(port, host); cluster.channels[i] = chan; chan.on('listening', chanReady); function chanReady() { var port = chan.address().port; cluster.hosts[i] = util.format('%s:%s', host, port); cluster.ready.signal(cluster); } } function destroy(cb) { parallel(cluster.channels.map(function(chan) { return function(done) { if (!chan.destroyed) chan.quit(done); }; }), cb); } } allocCluster.test = function testCluster(desc, opts, t) { if (typeof opts === 'number') { opts = { numPeers: opts }; } if (typeof opts === 'function') { t = opts; opts = {}; } test(desc, function t2(assert) { allocCluster(opts).ready(function clusterReady(cluster) { assert.once('end', function testEnded() { cluster.destroy(); }); t(cluster, assert); }); }); }; function ClusterPool(setup) { var self = this; self.free = []; self.setup = setup; } ClusterPool.prototype.get = function getCluster(callback) { var self = this; if (self.free.length) { callback(null, self.free.shift()); } else { self.setup(callback); } }; ClusterPool.prototype.release = function release(cluster) { var self = this; self.free.push(cluster); }; ClusterPool.prototype.destroy = function destroy(callback) { var self = this; var free = self.free; self.free = []; async.each(free, function destroyEach(cluster, next) { cluster.destroy(next); }, callback); }; allocCluster.Pool = ClusterPool;
JavaScript
0.000001
@@ -5271,16 +5271,530 @@ %7D);%0A%7D;%0A%0A +allocCluster.test.only = function testClusterOnly(desc, opts, t) %7B%0A if (typeof opts === 'number') %7B%0A opts = %7B%0A numPeers: opts%0A %7D;%0A %7D%0A if (typeof opts === 'function') %7B%0A t = opts;%0A opts = %7B%7D;%0A %7D%0A test.only(desc, function t2(assert) %7B%0A allocCluster(opts).ready(function clusterReady(cluster) %7B%0A assert.once('end', function testEnded() %7B%0A cluster.destroy();%0A %7D);%0A t(cluster, assert);%0A %7D);%0A %7D);%0A%7D;%0A%0A function
970f28e4965a0943e1a2f50df3df90cc59151ab8
use default params
src/components/dialog/dialog.js
src/components/dialog/dialog.js
/** * @function UIDialog * @version 0.0.2 */ import {keyCodes, defaultClassNames} from '../../constants'; export default function UIDialog(userOptions) { let DOM, state = {}; const defaults = { dialog: '.js-dialog', openBtn: '.js-dialog-btn', closeBtn: '.js-dialog-close-btn', isModal: false, showBackdrop: true }; // Combine defaults with passed in options const settings = Object.assign(defaults, userOptions); // Create the backdrop const backdrop = document.createElement('div'); backdrop.classList.add(defaultClassNames.DIALOG_BACKDROP); init(); /** * @function init * @desc Initialises the dialog */ function init() { // Save all DOM queries for future use DOM = { 'page': document.querySelectorAll('body')[0], 'dialog': document.querySelectorAll(settings.dialog)[0], 'openBtn': document.querySelectorAll(settings.openBtn)[0], 'closeBtn': document.querySelectorAll(settings.closeBtn)[0] }; // Check if the dialog exists, return if not if (DOM.dialog === undefined) { return false; } // Remove backdrop if turned off if (!settings.showBackdrop) { DOM.dialog.classList.add(defaultClassNames.NO_BACKDROP); } // Set page attribute DOM.page.setAttribute('data-ui-dialog', 'is-initialised'); // Find dialog and hide if not already hidden DOM.dialog.classList.add(defaultClassNames.IS_HIDDEN); // Attach event listeners DOM.openBtn.addEventListener('click', show, false); DOM.closeBtn.addEventListener('click', hide, false); if (!settings.isModal) { backdrop.addEventListener('click', hide, false); } document.addEventListener('keydown', keyHandler, false); } /** * @function show */ function show() { state.isOpen = true; DOM.dialog.classList.remove(defaultClassNames.IS_HIDDEN); DOM.page.setAttribute('data-current-dialog', settings.dialog); // Add the backdrop to the page DOM.page.appendChild(backdrop); }; /** * @function hide */ function hide() { state.isOpen = false; DOM.dialog.classList.add(defaultClassNames.IS_HIDDEN); DOM.page.removeAttribute('data-current-dialog'); // Remove the backdrop from the page DOM.page.removeChild(backdrop); }; /** * @function keyHandler * @desc Checks to see if escape (key 27) has been pressed and dialog not modal * @param {Event} e */ function keyHandler(e) { if ([keyCodes.ESC_KEY].indexOf(e.which) > -1 && state.isOpen === true && !settings.isModal) { e.preventDefault(); hide(); } } // External API return { show, hide }; }
JavaScript
0.000001
@@ -109,112 +109,26 @@ ;%0A%0A%0A -export default function UIDialog(userOptions) %7B%0A%0A let DOM,%0A state = %7B%7D;%0A%0A const defaults = +const UIDialog = ( %7B%0A @@ -139,25 +139,18 @@ dialog -: += '.js-di @@ -171,24 +171,18 @@ openBtn -: += '.js-di @@ -208,23 +208,18 @@ closeBtn -: += '.js-di @@ -254,16 +254,10 @@ odal -: += fal @@ -280,19 +280,18 @@ Backdrop -: += true%0A @@ -297,115 +297,52 @@ %7D -;%0A%0A // Combine defaults with passed in options%0A const settings = Object.assign(defaults, userOptions) + = %7B%7D) =%3E %7B%0A%0A let DOM,%0A state = %7B%7D ;%0A%0A @@ -769,25 +769,16 @@ ctorAll( -settings. dialog)%5B @@ -831,25 +831,16 @@ ctorAll( -settings. openBtn) @@ -894,25 +894,16 @@ ctorAll( -settings. closeBtn @@ -1103,25 +1103,16 @@ if (! -settings. showBack @@ -1583,25 +1583,16 @@ if (! -settings. isModal) @@ -1945,25 +1945,16 @@ ialog', -settings. dialog); @@ -2612,17 +2612,8 @@ && ! -settings. isMo @@ -2759,7 +2759,33 @@ %7D;%0A -%0A %7D +;%0A%0Aexport default UIDialog; %0A
f437947ee352f21c4b9c598edcb4488ece7a3314
Add support exact and isActive on NavLink
packages/components/components/sidebar/NavItem.js
packages/components/components/sidebar/NavItem.js
import React from 'react'; import PropTypes from 'prop-types'; import { NavLink } from 'react-router-dom'; import Icon from '../icon/Icon'; import NavMenu from './NavMenu'; const NavItem = ({ type, link, text, onClick, icon, list, color, className }) => { const content = ( <> {icon && <Icon fill="light" name={icon} color={color} className="mr1" />} {text} </> ); if (type === 'link') { return ( <li className="navigation__item"> <NavLink className={`navigation__link ellipsis ${className}`} to={link}> {content} </NavLink> {list.length ? <NavMenu list={list} /> : null} </li> ); } if (type === 'text') { return ( <li className="navigation__item"> <span className={`navigation__link ellipsis ${className}`}> {content} {list.length ? <NavMenu list={list} /> : null} </span> </li> ); } if (type === 'button') { return ( <li className="navigation__item"> <button type="button" className={`w100 navigation__link ellipsis ${className}`} onClick={onClick}> {content} </button> {list.length ? <NavMenu list={list} /> : null} </li> ); } return null; }; NavItem.propTypes = { icon: PropTypes.string, color: PropTypes.string, onClick: PropTypes.func, type: PropTypes.oneOf(['link', 'button', 'text']), link: PropTypes.string, text: PropTypes.string, list: PropTypes.arrayOf(PropTypes.object), className: PropTypes.string }; NavItem.defaultProps = { type: 'link', className: '', list: [] }; export default NavItem;
JavaScript
0
@@ -198,16 +198,33 @@ e, link, + isActive, exact, text, o @@ -299,16 +299,66 @@ %3C +div className=%22flex flex-nowrap flex-items-center%22 %3E%0A @@ -435,32 +435,90 @@ %22mr1 -%22 /%3E%7D%0A %7Btext%7D + flex-item-noshrink%22 /%3E%7D%0A %3Cspan className=%22ellipsis inbl%22%3E%7Btext%7D%3C/span%3E %0A @@ -524,16 +524,19 @@ %3C/ +div %3E%0A ); @@ -677,33 +677,24 @@ ation__link -ellipsis $%7BclassName%7D @@ -695,16 +695,50 @@ sName%7D%60%7D + exact=%7Bexact%7D isActive=%7BisActive%7D to=%7Blin @@ -1034,33 +1034,24 @@ ation__link -ellipsis $%7BclassName%7D @@ -1375,25 +1375,16 @@ n__link -ellipsis $%7BclassN @@ -1603,24 +1603,81 @@ opTypes = %7B%0A + isActive: PropTypes.func,%0A exact: PropTypes.bool,%0A icon: Pr
cfbd550ea390d87e2d9bc22c3470b899d8bac8ba
Add more functionality to the FakePebble object.
test/mocks/fake-pebble.js
test/mocks/fake-pebble.js
var FakePebble = (function () { var _Pebble = null; var eventListeners = { ready: [], appmessage: [], webviewclosed: [] }; var eventHandlers = { appmessage: [], notifications: [] }; return { addEventListener: addEventListener, sendAppMessage: sendAppMessage, showSimpleNotificationOnPebble: showSimpleNotificationOnPebble, getAccountToken: getAccountToken, openURL: openURL, reset: reset, inject: inject, restore: restore, on: on }; function addEventListener(event, callback) { if (eventListeners[event]) { eventListeners[event].push(callback); } } function sendAppMessage(message, ack, nack) { var _arguments = Array.prototype.slice.call(arguments); eventHandlers.appmessage.forEach(function (handler) { handler.apply(null, _arguments); }); } function showSimpleNotificationOnPebble(title, text) { var _arguments = Array.prototype.slice.call(arguments); eventHandlers.notifications.forEach(function (handler) { handler.apply(null, _arguments); }); } function getAccountToken() { return ''; } function openURL(url) { } function reset() { eventListeners.ready = []; eventListeners.appmessage = []; eventListeners.webviewclosed = []; eventHandlers.appmessage = []; eventHandlers.notifications = []; } function inject() { if (_Pebble !== null) { return; } if (typeof(Pebble) !== 'undefined') { _Pebble = Pebble; } Pebble = this; } function restore() { if (_Pebble === null) { return; } Pebble = _Pebble; _Pebble = null; } function on(event, callback) { eventHandlers[event].push(callback); } }());
JavaScript
0
@@ -48,16 +48,17 @@ = null;%0A +%0A var ev @@ -136,16 +136,17 @@ %5B%5D%0A %7D;%0A +%0A var ev @@ -199,16 +199,29 @@ cations: + %5B%5D,%0A url: %5B%5D%0A %7D; @@ -1175,16 +1175,99 @@ (url) %7B%0A + eventHandlers.openurl.forEach(function (handler) %7B%0A handler(url);%0A %7D);%0A %7D%0A%0A f
831b61fc877219da3958b552f7f9aa604f62eacc
use externalDocs.url
apis.js
apis.js
$(document).ready(function () { $.ajax({ type: "GET", url: "http://apis-guru.github.io/api-models/api/v1/list.json", dataType: 'json', cache: false, success: function (data) { var fragment = $(document.createDocumentFragment()); $.each(data, function (name, apis) { var preferred = apis.preferred; var api = apis.versions[preferred]; var info = api.info; var contact = info.contact || {}; var logo = info['x-logo'] || {}; var logoUrl = logo.url || 'no-logo.png'; var logoBg = logo.backgroundColor || '#eee'; var card = $( "<div class='col-xs-6 col-sm-4 col-md-3 .col-lg-2'>\ <div class='api-card'>\ <div style='padding: 5px 15px; border-radius: 9px 9px 0 0; background-color: " + logoBg + ";'>\ <div class='logo' style='background-image: url(\"" + logoUrl + "\");'/>\ </div>\ <div class='content'>\ <div class='title'>\ <a href='" + (contact.url || '') + "' target='_blank'>" + info.title + "</a>\ </div>\ <div>" + marked(info.description || '') + "</div>\ </div>\ <div class='footer'>\ <div style='font-size: .8em'>OpenAPI(fka Swagger) 2.0</div>\ <div class='versions'>\ <div style='display: inline-block; vertical-align: bottom;' class='truncate'>" + preferred + "</div>\ <span>\ <a href='" + api.swaggerUrl + "' target='_blank' class='label label-primary'>json</a> \ <a href='" + api.swaggerYamlUrl + "' target='_blank' class='label label-primary'>yaml</a>\ </span>\ </div>\ </div>\ </div>\ </div>"); var versions; var versionsGroup = $( "<div class='btn-group'>\ <button class='btn btn-default btn-xs dropdown-toggle' type='button' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>\ <span class='caret'></span>\ </button>\ <ul class='dropdown-menu'></ul>\ </div>"); card.find('.versions').append(versionsGroup); $.each(apis.versions, function (version, api) { if (version != preferred) { if (!versions) { versions = card.find('.dropdown-menu'); } versions.append( "<li>\ <span>" + version + "</span>\ <span>\ <a href='" + api.swaggerUrl + "' target='_blank' class='label label-primary'>json</a> \ <a href='" + api.swaggerYamlUrl + "' target='_blank' class='label label-primary'>yaml</a>\ </span>\ </li>"); } }); if (!versions) { versionsGroup.css('visibility', 'hidden'); versionsGroup.css('width', '0'); } fragment.append(card); }); $('#list').append(fragment); $('#footer').show(); } }); });
JavaScript
0
@@ -488,36 +488,162 @@ var -contact = info.contact %7C%7C %7B%7D +externalDocs = api.externalDocs %7C%7C %7B%7D;%0A var contact = info.contact %7C%7C %7B%7D;%0A var externalUrl = externalDocs.url %7C%7C contact.url ;%0A @@ -1378,25 +1378,25 @@ f='%22 + ( -contact.u +externalU rl %7C%7C ''
5f2dcd3236654562e108a3041d29ea0dfc095f02
Update script.js
js/script.js
js/script.js
(function(window, document, undefined) { window.onload = init; function init() { //get the canvas var canvas = document.getElementById("mapcanvas"); var c = canvas.getContext("2d"); var width = 512; var height = 288; var blockSize = 16; document.getElementById("startbtn").onclick = paintscreen; //paint the screen function paintscreen() { for(var i = 0; i< 32; i++) { for(var j = 0; j < 18; j++) { paintblock(i, j); } } } //paint a block function paintblock(x, y) { for(var i = 0; i < blockSize; i++) { for(var j = 0; j< blockSize; j++) { if(i == 0 || i == blockSize -1){ c.fillStyle = "#000000"; c.fillRect(i*x, j*y, 1, 1); } if(j == 0 || j == blockSize -1){ c.fillStyle = "#000000"; c.fillRect(i*x, j*y, 1, 1); } } } } } })(window, document, undefined);
JavaScript
0.000002
@@ -372,244 +372,8 @@ %0A - //paint the screen%0A function paintscreen() %7B%0A for(var i = 0; i%3C 32; i++) %7B%0A for(var j = 0; j %3C 18; j++) %7B%0A paintblock(i, j);%0A %7D%0A %7D%0A %7D%0A %0A @@ -965,24 +965,278 @@ %7D%0A %7D%0A + %0A //paint the screen%0A function paintscreen() %7B%0A for(var i = 0; i%3C 32; i++) %7B%0A for(var j = 0; j %3C 18; j++) %7B%0A paintblock(i, j);%0A %7D%0A %7D%0A %7D%0A %0A %0A %7D%0A%7D)(win
37c95e17644503bfbd795663a6513ac1c6bfcf7e
fix top image bug
src/components/gallery/index.js
src/components/gallery/index.js
import React, { Component, PropTypes } from "react"; import ReactDOM from "react-dom"; import ImgFigure from "../imgFigure"; import config from "../../config"; import "./index.less"; const imagesData = require("../../data/imagesData.json"); (array => { array.forEach(item => { item.imageUrl = `${config.resourcePrefix}/${item.fileName}`; }); })(imagesData); /** * 获取区间内的随机值 * @param {number} low 区间最小值 * @param {number} high 区间最大值 * @return {number} 区间内的随机数 */ const getRangeRandom = (low, high) => { return Math.ceil(Math.random() * (high - low) + low); }; class Gallery extends Component { constructor() { super(); this.state = { imgsArrangeArr: [] }; this.constant = { centerPos: { left: 0, right: 0 }, hPosRange: { leftSecX: [0, 0], rightSecX: [0, 0], y: [0, 0] }, vPosRange: { x: [0, 0], topY: [0, 0] } }; } /** * 重新布局所有图片 * @param {number} centerIdx 指定居中排布哪个图片 * @return {null} 无返回 */ rearrange(centerIdx) { const { constant } = this, { centerPos, hPosRange, vPosRange } = constant, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.x, topImgNum = Math.ceil(Math.random() * 2); let { imgsArrangeArr } = this.state, imgsArrangeTopArr = [], topImgSpliceIdx = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIdx, 1), i, j, k, hPosRangeLORX; // 首先居中 centerIdx 的图片 imgsArrangeCenterArr[0].pos = centerPos; // 取出要布局上侧的图片的状态信息 topImgSpliceIdx = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIdx, topImgNum); // 布局位于上侧的图片 imgsArrangeTopArr.forEach((item, idx) => { imgsArrangeTopArr[idx].pos = { top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[0]), left: getRangeRandom(vPosRangeX[0], vPosRangeX[0]) }; }); // 布局左右两侧的图片 for (i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) { // 前半部分布局在左边,后半部分布局在右边 hPosRangeLORX = i < k ? hPosRangeLeftSecX : hPosRangeRightSecX; imgsArrangeArr[i].pos = { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) } } if (imgsArrangeTopArr && imgsArrangeTopArr[0]) { imgsArrangeArr.splice(topImgSpliceIdx, 0, imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIdx, 0, imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr: imgsArrangeArr }); } componentDidMount() { const stageDOM = ReactDOM.findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2), imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0), imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); this.constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH }; // 计算左侧、右侧区域图片排布位置的取值范围 this.constant.hPosRange.leftSecX = [-halfImgW, halfStageW - halfImgW * 3]; this.constant.hPosRange.rightSecX = [halfStageW + halfImgW, stageW - halfImgW]; this.constant.hPosRange.y = [-halfImgH, stageH - halfImgH]; // 计算上侧区域图片排布位置的取值范围 this.constant.vPosRange.topY = [-halfImgH, halfStageH - halfImgH * 3]; this.constant.vPosRange.x = [halfImgW - imgW, halfImgW]; this.rearrange(0); } render() { let controllerUnits = [], imgFigures = []; imagesData.forEach((item, idx) => { if (!this.state.imgsArrangeArr[idx]) { this.state.imgsArrangeArr[idx] = { pos: { left: 0, top: 0 } }; } imgFigures.push(<ImgFigure key={idx} data={item} ref={"imgFigure" + idx} arrange={this.state.imgsArrangeArr[idx]} />); }); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ) } } export default Gallery;
JavaScript
0
@@ -4209,19 +4209,21 @@ = %5Bhalf -Img +Stage W - imgW @@ -4224,27 +4224,29 @@ - imgW, half -Img +Stage W%5D;%0A%0A
2d21719fcdf026e7dbf4f5cbc4136d65a42a8a04
Fix grammar (#33)
src/components/home/Features.js
src/components/home/Features.js
import Inferno from 'inferno' import IconArchitecture from '../icons/IconArchitecture' import IconCompatible from '../icons/IconCompatible' import IconIsomorphic from '../icons/IconIsomorphic' import IconModular from '../icons/IconModular' import IconSize from '../icons/IconSize' import IconSpeed from '../icons/IconSpeed' export default function() { return <div className="container"> <div className="row features-wrapper"> <div className="xs12 lg4 row"> <IconSize/> <div className="desc"> <h2>Tiny Size</h2> <p>Inferno is much smaller in size, 9kb vs 45kb gzip. This means inferno is faster to transfer over the network and much faster to parse.</p> </div> </div> <div className="xs12 lg4 row"> <IconCompatible/> <div className="desc"> <h2>React Compatible</h2> <p>React-like API, concepts and component lifecycle events. Switch over easily with inferno-compat.</p> </div> </div> <div className="xs12 lg4 row"> <IconSpeed/> <div className="desc"> <h2>Insane Performance</h2> <p>One the fastest front-end frameworks for rendering UI in the DOM, making 60 FPS on mobile possible.</p> </div> </div> <div className="xs12 lg4 row"> <IconArchitecture/> <div className="desc"> <h2>One-way Architecture</h2> <p>Component driven + One-way data flow architecture. Bindings also supplied for Redux, MobX or Ceberal.</p> </div> </div> <div className="xs12 lg4 row"> <IconIsomorphic/> <div className="desc"> <h2>Isomorphic</h2> <p>Isomorphic rendering on both client and server, along with fast-booting from server-side renders.</p> </div> </div> <div className="xs12 lg4 row"> <IconModular/> <div className="desc"> <h2>Modular</h2> <p>Highly modular with very little opinion of how things should be done, removing bloat and unecessary overhead.</p> </div> </div> </div> </div> }
JavaScript
0.000027
@@ -1299,16 +1299,19 @@ %3Cp%3EOne +of the fast