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
bf5747db8433447954f26aaa9e4fb29fa44b32af
Fix the Windows packaged build, r=vporof (#24)
src/shared/util/spawn.js
src/shared/util/spawn.js
/* Copyright 2016 Mozilla 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. */ import cp from 'child_process'; import colors from 'colour'; export const spawn = (command, main, args, { logger }, options = {}) => new Promise((resolve, reject) => { logger.log('Spawning', colors.cyan(command), colors.blue(main), colors.yellow(args.join(' '))); const child = cp.spawn(command, [main, ...args], { stdio: 'inherit', ...options }); child.on('error', reject); child.on('exit', resolve); return child; });
JavaScript
0
@@ -603,16 +603,67 @@ colour'; +%0Aimport %7B IS_PACKAGED_BUILD %7D from '../build-info'; %0A%0Aexport @@ -874,16 +874,114 @@ ')));%0A%0A + const stdio = process.platform === 'win32' && IS_PACKAGED_BUILD%0A ? 'ignore'%0A : 'inherit';%0A const @@ -1030,27 +1030,16 @@ %7B stdio -: 'inherit' , ...opt
7e6208b0584040c45449faa39e60ccc98bb9acb1
Remove unneeded eslint comment
src/bin.js
src/bin.js
import fs from 'fs'; import path from 'path'; import chalk from 'chalk'; import mri from 'mri'; import glob from 'tiny-glob/sync.js'; import fuzzysearch from 'fuzzysearch'; import enquirer from 'enquirer'; // eslint-disable-next-line import/no-unresolved import degit from './index.js'; import { tryRequire, base } from './utils.js'; const args = mri(process.argv.slice(2), { alias: { f: 'force', c: 'cache', v: 'verbose', m: 'mode' }, boolean: ['force', 'cache', 'verbose'] }); const [src, dest = '.'] = args._; async function main() { if (args.help) { const help = fs .readFileSync(path.join(__dirname, 'help.md'), 'utf-8') .replace(/^(\s*)#+ (.+)/gm, (m, s, _) => s + chalk.bold(_)) .replace(/_([^_]+)_/g, (m, _) => chalk.underline(_)) .replace(/`([^`]+)`/g, (m, _) => chalk.cyan(_)); process.stdout.write(`\n${help}\n`); } else if (!src) { // interactive mode const accessLookup = new Map(); glob(`**/access.json`, { cwd: base }).forEach(file => { const [host, user, repo] = file.split(path.sep); const json = fs.readFileSync(`${base}/${file}`, 'utf-8'); const logs = JSON.parse(json); Object.entries(logs).forEach(([ref, timestamp]) => { const id = `${host}:${user}/${repo}#${ref}`; accessLookup.set(id, new Date(timestamp).getTime()); }); }); const getChoice = file => { const [host, user, repo] = file.split(path.sep); return Object.entries(tryRequire(`${base}/${file}`)).map( ([ref, hash]) => ({ name: hash, message: `${host}:${user}/${repo}#${ref}`, value: `${host}:${user}/${repo}#${ref}` }) ); }; const choices = glob(`**/map.json`, { cwd: base }) .map(getChoice) .reduce( (accumulator, currentValue) => accumulator.concat(currentValue), [] ) .sort((a, b) => { const aTime = accessLookup.get(a.value) || 0; const bTime = accessLookup.get(b.value) || 0; return bTime - aTime; }); const options = await enquirer.prompt([ { type: 'autocomplete', name: 'src', message: 'Repo to clone?', suggest: (input, choices) => choices.filter(({ value }) => fuzzysearch(input, value)), choices }, { type: 'input', name: 'dest', message: 'Destination directory?', initial: '.' }, { type: 'toggle', name: 'cache', message: 'Use cached version?' } ]); const empty = !fs.existsSync(options.dest) || fs.readdirSync(options.dest).length === 0; if (!empty) { const { force } = await enquirer.prompt([ { type: 'toggle', name: 'force', message: 'Overwrite existing files?' } ]); if (!force) { console.error(chalk.magenta(`! Directory not empty — aborting`)); return; } } run(options.src, options.dest, { force: true, cache: options.cache }); } else { run(src, dest, args); } } function run(src, dest, args) { const d = degit(src, args); d.on('info', event => { console.error(chalk.cyan(`> ${event.message.replace('options.', '--')}`)); }); d.on('warn', event => { console.error( chalk.magenta(`! ${event.message.replace('options.', '--')}`) ); }); d.clone(dest).catch(err => { console.error(chalk.red(`! ${err.message.replace('options.', '--')}`)); process.exit(1); }); } main();
JavaScript
0.000002
@@ -202,58 +202,8 @@ er'; -%0A%0A// eslint-disable-next-line import/no-unresolved %0Aimp
bfb30a22f62fc8c63167a3fb13cd5c5f4af9d773
Make JSlint happier
src/VIE.js
src/VIE.js
// ### Handle dependencies // // VIE tries to load its dependencies automatically. // Please note that this autoloading functionality only works on the server. // On browser Backbone needs to be included manually. // Require [underscore.js](http://documentcloud.github.com/underscore/) // using CommonJS require if it isn't yet loaded. // // On node.js underscore.js can be installed via: // // npm install underscore var _ = this._; if (!_ && (typeof require !== 'undefined')) { _ = require('underscore')._; } if (!_) { throw 'VIE requires underscore.js to be available'; } // Require [Backbone.js](http://documentcloud.github.com/backbone/) // using CommonJS require if it isn't yet loaded. // // On node.js Backbone.js can be installed via: // // npm install backbone var Backbone = this.Backbone; if (!Backbone && (typeof require !== 'undefined')) { Backbone = require('backbone'); } if (!Backbone) { throw 'VIE requires Backbone.js to be available'; } // Require [jQuery](http://jquery.com/) using CommonJS require if it // isn't yet loaded. // // On node.js jQuery can be installed via: // // npm install jquery var jQuery = this.jQuery; if (!jQuery && (typeof require !== 'undefined')) { jQuery = require('jquery'); } if (!jQuery) { throw 'VIE requires jQuery to be available'; } var VIE; VIE = function(config){ this.config = (config) ? config : {}; this.services = {}; this.entities = new this.Collection(); this.Entity.prototype.entities = this.entities; this.entities.vie = this; this.Entity.prototype.entityCollection = this.Collection; this.Entity.prototype.vie = this; this.defaultProxyUrl = (this.config.defaultProxyUrl) ? this.config.defaultProxyUrl : "../utils/proxy/proxy.php"; this.Namespaces.prototype.vie = this; this.namespaces = new this.Namespaces( (this.config.defaultNamespace) ? this.config.defaultNamespace : "http://ontology.vie.js/" ); this.Type.prototype.vie = this; this.Types.prototype.vie = this; this.Attribute.prototype.vie = this; this.Attributes.prototype.vie = this; this.types = new this.Types(); this.types.add("Thing"); if (this.config.classic !== false) { // Load Classic API as well this.RDFa = new this.ClassicRDFa(this); this.RDFaEntities = new this.ClassicRDFaEntities(this); this.EntityManager = new this.ClassicEntityManager(this); this.cleanup = function() { this.entities.reset(); }; } }; VIE.prototype.use = function(service, name) { if (!name) { name = service.name; } service.vie = this; service.name = name; if (service.init) { service.init(); } this.services[name] = service; }; VIE.prototype.service = function(name) { if (!this.services[name]) { throw "Undefined service " + name; } return this.services[name]; }; VIE.prototype.getServicesArray = function() { var res = []; _(this.services).each(function(service, i){res.push(service);}); return res; }; // Declaring the ..able classes // Loadable VIE.prototype.load = function(options) { if (!options) { options = {}; } options.vie = this; return new this.Loadable(options); }; // Savable VIE.prototype.save = function(options) { if (!options) { options = {}; } options.vie = this; return new this.Savable(options); }; // Removable VIE.prototype.remove = function(options) { if (!options) { options = {}; } options.vie = this; return new this.Removable(options); }; // Analyzable VIE.prototype.analyze = function(options) { if (!options) { options = {}; } options.vie = this; return new this.Analyzable(options); }; // Findable VIE.prototype.find = function(options) { if (!options) { options = {}; } options.vie = this; return new this.Findable(options); }; if(typeof(exports) !== 'undefined' && exports !== null) { exports.VIE = VIE; }
JavaScript
0.000002
@@ -1343,16 +1343,17 @@ (config) + %7B%0A th @@ -1887,29 +1887,16 @@ pace) ? -%0A this.con @@ -1918,29 +1918,16 @@ space : -%0A %22http://
37f824c25b9f24e4fb2adda56bc88bca60671e64
Remove cache from product detail
src/store/server/ajax.js
src/store/server/ajax.js
import express from 'express' let ajaxRouter = express.Router(); import serverSettings from './settings' import api from 'cezerin-client'; api.init(serverSettings.apiBaseUrl, serverSettings.security.token); const DEFAULT_CACHE_CONTROL = 'public, max-age=600'; ajaxRouter.get('/products', (req, res, next) => { const filter = req.query; filter.enabled = true; api.products.list(filter).then(({status, json}) => { res.status(status).header('Cache-Control', DEFAULT_CACHE_CONTROL).send(json); }) }) ajaxRouter.get('/products/:id', (req, res, next) => { api.products.retrieve(req.params.id).then(({status, json}) => { res.status(status).header('Cache-Control', DEFAULT_CACHE_CONTROL).send(json); }) }) ajaxRouter.get('/cart', (req, res, next) => { const order_id = req.signedCookies.order_id; if (order_id) { api.orders.retrieve(order_id).then(({status, json}) => { res.status(status).send(json); }) } else { res.end(); } }) ajaxRouter.post('/cart/items', (req, res, next) => { const order_id = req.signedCookies.order_id; const item = req.body; if (order_id) { api.orders.addItem(order_id, item).then(({status, json}) => { res.status(status).send(json); }) } else { let ip = req.get('x-forwarded-for') || req.ip; if(ip && ip.includes(', ')) { ip = ip.split(', ')[0]; } if(ip && ip.includes('::ffff:')) { ip = ip.replace('::ffff:', ''); } api.orders.create({ draft: true, referrer_url: req.signedCookies.referrer_url, landing_url: req.signedCookies.landing_url, browser: { ip: ip, user_agent: req.get('user-agent') } }).then(({status, json}) => { res.cookie('order_id', json.id, serverSettings.cartCookieOptions); api.orders.addItem(json.id, item).then(({status, json}) => { res.status(status).send(json); }) }) } }) ajaxRouter.delete('/cart/items/:item_id', (req, res, next) => { const order_id = req.signedCookies.order_id; const item_id = req.params.item_id; if (order_id && item_id) { api.orders.deleteItem(order_id, item_id).then(({status, json}) => { res.status(status).send(json); }) } else { res.end(); } }) ajaxRouter.put('/cart/items/:item_id', (req, res, next) => { const order_id = req.signedCookies.order_id; const item_id = req.params.item_id; const item = req.body; if (order_id && item_id) { api.orders.updateItem(order_id, item_id, item).then(({status, json}) => { res.status(status).send(json); }) } else { res.end(); } }) ajaxRouter.put('/cart/checkout', (req, res, next) => { const order_id = req.signedCookies.order_id; if (order_id) { api.orders.checkout(order_id).then(({status, json}) => { res.clearCookie('order_id'); res.status(status).send(json); }) } else { res.end(); } }); ajaxRouter.put('/cart', (req, res, next) => { const order_id = req.signedCookies.order_id; if (order_id) { api.orders.update(order_id, req.body).then(({status, json}) => { res.status(status).send(json); }) } else { res.end(); } }) ajaxRouter.put('/cart/shipping_address', (req, res, next) => { const order_id = req.signedCookies.order_id; if (order_id) { api.orders.updateShippingAddress(order_id, req.body).then(({status, json}) => { res.status(status).send(json); }) } else { res.end(); } }) ajaxRouter.put('/cart/billing_address', (req, res, next) => { const order_id = req.signedCookies.order_id; if (order_id) { api.orders.updateBillingAddress(order_id, req.body).then(({status, json}) => { res.status(status).send(json); }) } else { res.end(); } }) ajaxRouter.get('/product_categories', (req, res, next) => { api.product_categories.list(req.query).then(({status, json}) => { res.status(status).header('Cache-Control', DEFAULT_CACHE_CONTROL).send(json); }) }) ajaxRouter.get('/product_categories/:id', (req, res, next) => { api.product_categories.retrieve(req.params.id).then(({status, json}) => { res.status(status).header('Cache-Control', DEFAULT_CACHE_CONTROL).send(json); }) }) ajaxRouter.get('/pages/:id', (req, res, next) => { api.pages.retrieve(req.params.id).then(({status, json}) => { res.status(status).header('Cache-Control', DEFAULT_CACHE_CONTROL).send(json); }) }) ajaxRouter.get('/sitemap', (req, res, next) => { const filter = req.query; filter.enabled = true; api.sitemap.retrieve(req.query).then(({status, json}) => { res.status(status).header('Cache-Control', DEFAULT_CACHE_CONTROL).send(json); }) }) ajaxRouter.get('/payment_methods', (req, res, next) => { const filter = { order_id: req.signedCookies.order_id }; api.payment_methods.list(filter).then(({status, json}) => { res.status(status).send(json); }) }) ajaxRouter.get('/shipping_methods', (req, res, next) => { const filter = { order_id: req.signedCookies.order_id }; api.shipping_methods.list(filter).then(({status, json}) => { res.status(status).send(json); }) }) ajaxRouter.get('/countries', (req, res, next) => { api.countries.list().then(({status, json}) => { res.status(status).header('Cache-Control', DEFAULT_CACHE_CONTROL).send(json); }) }) ajaxRouter.all('*', (req, res, next) => { res.status(405).send({'error': 'Method Not Allowed'}); }) ajaxRouter.use(function(err, req, res, next) { if (err) { res.status(500).send({'error': err}); } }); module.exports = ajaxRouter;
JavaScript
0
@@ -253,16 +253,69 @@ ge=600'; +%0Aconst PRODUCTS_CACHE_CONTROL = 'public, max-age=60'; %0A%0AajaxRo @@ -505,39 +505,40 @@ Cache-Control', -DEFAULT +PRODUCTS _CACHE_CONTROL). @@ -670,32 +670,32 @@ us, json%7D) =%3E %7B%0A + res.status(s @@ -705,55 +705,8 @@ us). -header('Cache-Control', DEFAULT_CACHE_CONTROL). send
66bdbe3a207a81247f1377d3afab5dc7fd7756be
fix arg count check
src/cli.js
src/cli.js
var User = require('./user.js'), args = process.argv.slice(2); if (args.length < 2) { console.log('invalid arg count'); return; } switch (args[0]) { case 'user': if (args[1] == 'create') { if (args.length < 4) { console.log('invalid arg count'); return; } return User.create(args[2], args[3]); } if (args[1] == 'remove') { if (args.length < 3) { console.log('invalid arg count'); return; } return User.remove(args[2], args[3]); } break; }
JavaScript
0.000005
@@ -456,17 +456,17 @@ ength %3C -3 +4 ) %7B%0A
f521de3a472502612a107340ab2ca9ebf268ede9
fix --width and --height arguments
src/cli.js
src/cli.js
#!/usr/bin/env node var path = require("path"); var commandLineArgs = require('command-line-args'); var SimpleThumbnailGenerator = require("./simple-thumbnail-generator"); var ThumbnailGeneratorService = require("./thumbnail-generator-service"); var utils = require("./utils"); var Logger = require("./logger"); var optionDefinitions = [ // If provided download the thumbnails for this stream and then quit { name: 'url', alias: 'u', type: String, defaultOption: true }, // If url provided use this file name for the manifest file. { name: 'manifestFileName', alias: 'm', type: String}, // If url provided use this as a prefix for the thumbnail file names. { name: 'outputNamePrefix', type: String, defaultValue: null }, // If provided start a server running on this port listening for commands { name: 'port', alias: 'p', type: Number, defaultValue: null }, // Ping request must be made every pingInterval seconds or thumbnail generation will automatically stop. Defaults to disabled. { name: 'pingInterval', type: Number }, // empty the output directory on startup { name: 'clearOutputDir', type: Boolean, defaultValue: false }, { name: 'outputDir', alias: 'o', type: String, defaultValue: "./output" }, { name: 'tempDir', alias: 't', type: String }, { name: 'secret', alias: 's', type: String }, // The time in seconds to keep thumbnails for before deleting them, once their segments have left the playlist. Defaults to 0. { name: 'expireTime', alias: 'e', type: Number }, // The default interval between thumbnails. If omitted the interval will be calculated automatically using `targetThumbnailCount`. { name: 'interval', alias: 'i', type: Number }, // The default number of thumbnails to generate initially, from the end of the stream. If ommitted defaults to taking thumbnails for the entire stream. { name: 'initialThumbnailCount', type: Number }, // The default number of thumbnails that should be generated over the duration of the stream. Defaults to 30. This will be recalculated if the stream duration changes. { name: 'targetThumbnailCount', alias: 'c', type: Number }, // The default width of the thumbnails to generate (px). If omitted this will be calculated automatically from the height, or default to 150. { name: 'width', alias: 'w', type: Number }, // The default height of the thumbnails to generate (px). If omitted this will be calculated automatically from the width. { name: 'height', alias: 'h', type: Number } ]; var options = commandLineArgs(optionDefinitions); if (options.url && options.port !== null) { throw new Error("Cannot use 'url' and 'port' together."); } if (options.url && options.pingInterval) { throw new Error("Cannot use 'url' and 'pingInterval' together."); } if (options.url && options.secret) { throw new Error("Cannot use 'url' and 'secret' together."); } if (!options.url && options.manifestFileName) { throw new Error("'manifestFileName' can only be used with the 'url' option."); } if (!options.url && options.outputNamePrefix) { throw new Error("'outputNamePrefix' can only be used with the 'url' option."); } if (port !== null && options.port % 1 !== 0) { throw new Error("Port invalid."); } var logger = Logger.get("SimpleThumbnailGeneratorCLI"); var url = options.url; var manifestFileName = url ? options.manifestFileName || "thumbnails.json" : null; var outputNamePrefix = options.outputNamePrefix || null; var port = !url ? options.port || 8080 : null; var pingInterval = options.pingInterval || null; var clearOutputDir = options.clearOutputDir; var outputDir = path.resolve(options.outputDir); var tempDir = options.tempDir ? path.resolve(options.tempDir) : null; var secret = options.secret || null; var expireTime = options.expireTime || 0; var interval = options.interval || null; var initialThumbnailCount = options.initialThumbnailCount || null; var targetThumbnailCount = !interval ? options.targetThumbnailCount || 30 : null; var height = options.height || null; var width = options.width || (options.height ? null : 150); var simpleThumbnailGeneratorOptions = { expireTime: expireTime, manifestFileName: manifestFileName }; var thumbnailGeneratorOptions = { playlistUrl: url, outputDir: outputDir, tempDir: tempDir, interval: interval, initialThumbnailCount: initialThumbnailCount, targetThumbnailCount: targetThumbnailCount, width: width, height: height }; Promise.resolve().then(() => { if (clearOutputDir) { return utils.exists(outputDir).then((exists) => { if (exists) { logger.debug("Clearing output directory."); return utils.emptyDir(outputDir).then(() => { logger.debug("Output directory cleared."); }); } }); } }).then(() => { if (url) { // generate thumbnails for this url and then terminate thumbnailGeneratorOptions.outputNamePrefix = outputNamePrefix; var generator = new SimpleThumbnailGenerator(simpleThumbnailGeneratorOptions, thumbnailGeneratorOptions); var emitter = generator.getEmitter(); emitter.on("error", (err) => { logger.error("Error", err.stack); process.exit(1); }); emitter.on("finished", (err) => { logger.debug("Finished"); process.exit(0); }); } else { new ThumbnailGeneratorService({ secret: secret, port: port, pingInterval: pingInterval }, simpleThumbnailGeneratorOptions, thumbnailGeneratorOptions); } }).catch((err) => { logger.error("Error", err.stack); process.exit(1); });
JavaScript
0.000002
@@ -4344,17 +4344,26 @@ Count,%0A%09 -w +thumbnailW idth: wi @@ -4368,17 +4368,26 @@ width,%0A%09 -h +thumbnailH eight: h @@ -5427,8 +5427,9 @@ (1);%0A%7D); +%0A
fbe3162766d590485a8ebbf82a0076012fcfc350
Test for `set`
test/create.js
test/create.js
'use strict'; var isArray = Array.isArray; module.exports = function (t, a) { var ObservableArray = t(Array) , arr = new ObservableArray('foo', 'bar', 23) , evented = 0, x = {}; a(isArray(arr), true, "Is array"); a(arr instanceof ObservableArray, true, "Subclassed"); a.deep(arr, ['foo', 'bar', 23], "Constructor"); arr.on('change', function () { ++evented; }); arr.pop(); a.deep(arr, ['foo', 'bar'], "Pop: value"); a(evented, 1, "Pop: event"); arr.pop(); arr.pop(); a.deep(arr, [], "Pop: clear"); a(evented, 3, "Pop: event"); arr.pop(); a(evented, 3, "Pop: on empty"); arr.shift(); a(evented, 3, "Shift: on empty"); arr.reverse(); a(evented, 3, "Revere: on empty"); arr.push(); a(evented, 3, "Push: empty"); arr.push(x); a.deep(arr, [x], "Push: value"); a(evented, 4, "Push: event"); arr.reverse(); a(evented, 4, "Reverse: one value"); arr.push(x); a(evented, 5, "Push: another"); arr.reverse(); a(evented, 5, "Reverse: same layout"); arr.push(34); a(evented, 6, "Push: another #2"); arr.reverse(); a(evented, 7, "Reverse: diff"); a.deep(arr, [34, x, x], "Reverse: content"); arr.shift(); a.deep(arr, [x, x], "Shift: content"); a(evented, 8, "Shift: event"); arr.sort(); a(evented, 8, "Sort: no change"); arr.pop(); arr.pop(); arr.push('wed'); arr.push('abc'); arr.push('raz'); a(evented, 13, "Events"); arr.sort(); a.deep(arr, ['abc', 'raz', 'wed'], "Sort: content"); a(evented, 14, "Sort: event"); arr.splice(); a(evented, 14, "Splice: no data"); arr.splice(12); a(evented, 14, "Splice: too far"); arr.splice(1, 0); a(evented, 14, "Splice: no delete"); arr.splice(1, 0, 'foo'); a.deep(arr, ['abc', 'foo', 'raz', 'wed'], "Sort: content"); a(evented, 15, "Splice: event"); arr.unshift(); a(evented, 15, "Unshift: no data"); arr.unshift('elo', 'bar'); a.deep(arr, ['elo', 'bar', 'abc', 'foo', 'raz', 'wed'], "Unshift: content"); a(evented, 16, "Unshift: event"); };
JavaScript
0.000001
@@ -1322,26 +1322,38 @@ 'abc');%0A +%0A %09arr. -push( +set(arr.length, 'raz');%0A
17219abf022ff722a98de9575b07aec7057c172b
Fix build sitemap.xml
src/tasks/sitemap-xml.js
src/tasks/sitemap-xml.js
var _ = require('lodash'), vow = require('vow'), js2xml = require('js2xmlparser'), errors = require('../errors').TaskSitemapXML, logger = require('../logger'), levelDb = require('../providers/level-db'); module.exports = function (target) { logger.info('Start to build "sitemap.xml" file', module); var hosts = target.getOptions['hosts'] || {}; // check if any changes were collected during current synchronization // otherwise we should skip this task if (!target.getChanges().areModified()) { logger.warn('No changes were made during this synchronization. This step will be skipped', module); return vow.resolve(target); } // check if any hosts were configured in application configuration file // otherwise we should skip this task if (!Object.keys(hosts).length) { logger.warn('No hosts were configured for creating sitemap.xml file. This step will be skipped', module); return vow.resolve(target); } // get all nodes from db that have inner urls return levelDb .getByCriteria(function (record) { var key = record.key, value = record.value; if (key.indexOf(target.KEY.NODE_PREFIX) < 0) { return false; } return value.hidden && _.isString(value.url) && !/^(https?:)?\/\//.test(value.url); }, { gte: target.KEY.NODE_PREFIX, lt: target.KEY.PEOPLE_PREFIX, fillCache: true }) .then(function (records) { // convert data set to sitemap format // left only data fields that are needed for sitemap.xml file return records.map(function (record) { return _.pick(record.value, 'url', 'hidden', 'search'); }); }) .then(function (records) { return records.reduce(function (prev, item) { Object.keys(hosts).forEach(function (lang) { if (!item.hidden[lang]) { prev.push(_.extend({ loc: hosts[lang] + item.url }, item.search)); } }); return prev; }, []); }) .then(function (records) { // convert json model to xml format return levelDb.get().put('sitemapXml', js2xml('urlset', { url: records })); }) .then(function () { logger.info('Successfully create sitemap.xml file', module); return vow.resolve(target); }) .fail(function (err) { errors.createError(errors.CODES.COMMON, { err: err }).log(); return vow.reject(err); }); };
JavaScript
0.000007
@@ -355,23 +355,16 @@ ions -%5B' +(). hosts -'%5D %7C%7C %7B%7D ;%0A%0A @@ -1056,25 +1056,22 @@ levelDb -%0A +.get() .getByCr @@ -1105,20 +1105,16 @@ - var key @@ -1127,20 +1127,16 @@ rd.key,%0A - @@ -1166,28 +1166,24 @@ e;%0A%0A - if (key.inde @@ -1225,28 +1225,24 @@ - return false @@ -1247,34 +1247,27 @@ se;%0A - - %7D%0A - +%0A retu @@ -1346,20 +1346,17 @@ e.url);%0A - +%0A %7D, %7B
cdf2a558eec4b351d7742bf2a358f70a73ed21ad
Revert 334b408..8695551
src/app.js
src/app.js
/** * Welcome to Pebble.js! * * This is where you write your app. */ var UI = require('ui'); // fake out configuration information for now var exercises = []; for (var i=0; i < 10; i++) { var name = 'Exercise '+i; var starting = 100; exercises.push({ name: name, reps: [starting, starting+5, starting+10] }); } // menu item for each exercise var items = exercises.map(function(exercise){ return { title: exercise.name, subtitle: exercise.reps.join() }; }); var main = new UI.Menu({ sections: [{ items: items }] }); main.on('select', function(e) { var exercise = exercises[e.itemIndex]; var card = new UI.Card(); card.title(exercise.name); card.subtitle(exercise.reps.join()); card.show(); }); main.show(); // main.on('click', 'up', function(e) { // var menu = new UI.Menu({ // sections: [{ // items: [{ // title: 'Pebble.js', // icon: 'images/menu_icon.png', // subtitle: 'Can do Menus' // }, { // title: 'Second Item', // subtitle: 'Subtitle Text' // }] // }] // }); // menu.on('select', function(e) { // console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex); // console.log('The item is titled "' + e.item.title + '"'); // }); // menu.show(); // }); // main.on('click', 'select', function(e) { // var wind = new UI.Window(); // var textfield = new UI.Text({ // position: new Vector2(0, 50), // size: new Vector2(144, 30), // font: 'gothic-24-bold', // text: 'Text Anywhere!', // textAlign: 'center' // }); // wind.add(textfield); // wind.show(); // }); // main.on('click', 'down', function(e) { // var card = new UI.Card(); // card.title('A Card'); // card.subtitle('Is a Window'); // card.body('The simplest window type in Pebble.js.'); // card.show(); // });
JavaScript
0
@@ -219,30 +219,8 @@ +i;%0A - var starting = 100;%0A ex @@ -258,53 +258,241 @@ -reps: %5Bstarting, starting+5, starting+10%5D%0A %7D +starting: 100,%0A reps: 3,%0A increase: 5%0A %7D);%0A%7D%0A%0Afunction weightsString(exercise)%7B%0A var weights = %5B%5D;%0A for (var i=0; i%3Cexercise.reps; i++)%7B%0A weights.push(exercise.starting+i*exercise.increase);%0A %7D%0A return weights.join(', ' );%0A%7D @@ -621,35 +621,38 @@ btitle: -exercise.reps.join( +weightsString(exercise )%0A %7D;%0A%7D @@ -880,27 +880,30 @@ tle( -exercise.reps.join( +weightsString(exercise ));%0A
10844b0f0430fbd56f64029ca29673c6700f84fa
fix in tests.
test/markup.js
test/markup.js
'use strict' var path = require('path') var helpers = require('yeoman-generator').test var assert = require('yeoman-assert') describe('Markup Features', function () { describe('HTML Project', function () { before('crafting project', function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(__dirname, 'temp')) .withOptions({ 'skip-install': true }) .withPrompts({ clientId: '0987', projectId: '1234', qtyScreens: 6, markupLanguage: 'html', cssProcessor: 'less' }) .on('end', done) }) it('creates expected base files', function () { assert.file([ '.gitignore', '.gitattributes', 'package.json', 'gulpfile.js', 'package.json', '.editorconfig', 'src/screen-1.html', 'src/screen-2.html', 'src/screen-3.html', 'src/screen-4.html', 'src/screen-5.html', 'src/screen-6.html', 'gulp', 'gulp/tasks', 'src/assets/fonts', 'src/assets/icons', 'src/assets/images', 'src/assets/js', 'src/assets/styles', 'src/assets/vendor' ]) }) it('should have the project name on package.json', function () { assert.fileContent('package.json', /"name": "pixel2html-0987-1234"/) }) it('should exists a gulp routine', function () { assert.file(['gulp/tasks/markup.js']) }) it('should have the gulp routine in gulp default\'s task', function () { assert.fileContent('gulpfile.js', /'main:markup'/) assert.noFileContent('gulpfile.js', /'jekyll:build'/) }) }) describe('PUG Project', function () { before('crafting project', function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(__dirname, 'temp')) .withOptions({ 'skip-install': true }) .withPrompts({ clientId: '0987', projectId: '1234', qtyScreens: 6, markupLanguage: 'pug', cssProcessor: 'less' }) .on('end', done) }) describe('Checking base files with dependencies', function () { it('sould exists dependencies on package.json', function () { assert.fileContent('package.json', /"gulp-pug"/) }) }) it('creates expected base files', function () { assert.file([ '.gitignore', '.gitattributes', 'package.json', 'gulpfile.js', 'package.json', '.editorconfig', 'src/pug/index.pug', 'src/pug/screen-2.pug', 'src/pug/screen-3.pug', 'src/pug/screen-4.pug', 'src/pug/screen-5.pug', 'src/pug/screen-6.pug', 'src/pug/layouts/layout-primary.pug', 'src/pug/layouts/general/footer.pug', 'src/pug/layouts/general/menu.pug', 'src/pug/layouts/includes/mixins.pug', 'gulp', 'gulp/tasks', 'src/assets/fonts', 'src/assets/icons', 'src/assets/images', 'src/assets/js', 'src/assets/styles', 'src/assets/vendor' ]) }) it('should have the project name on package.json', function () { assert.fileContent('package.json', /"name": "pixel2html-0987-1234"/) }) it('should exists a gulp routine', function () { assert.file([ 'gulp/tasks/markup.js' ]) assert.fileContent('gulp/tasks/markup.js', /\$\.pug/) }) it('should exists a pipe in the main:markup', function () { assert.fileContent('gulp/tasks/markup.js', /pug\(/) }) it('should have the gulp routine in gulp default\'s task', function () { assert.fileContent('gulpfile.js', /'main:markup'/) assert.noFileContent('gulpfile.js', /'jekyll:build'/) }) }) })
JavaScript
0
@@ -2612,13 +2612,16 @@ pug/ -index +screen-1 .pug
83617243dd5d4c0156ba4cee3c43a6f03369fe7d
Use predefined "global" var in place of "this".
src/end.js
src/end.js
if ( typeof define === "function" && define.amd ) { define(this.sn = sn); } else if ( typeof module === "object" && module.exports ) { module.exports = sn; } else this.sn = sn; }();
JavaScript
0
@@ -161,19 +161,24 @@ ;%0A%09%7D -%0A%09 + else -this +%7B%0A%09%09global .sn @@ -183,13 +183,16 @@ n = sn;%0A +%09%7D%0A %7D();%0A
d91dd9669b7a1c5dd18044e791c6900c14186e36
Fix #158.
src/app.js
src/app.js
var SVG_NS = "http://www.w3.org/2000/svg" export default function (app) { var view = app.view || function () { return "" } var model var actions = {} var subscriptions = [] var hooks = { onError: [], onAction: [], onUpdate: [], onRender: [] } var plugins = [app].concat((app.plugins || []).map(function (plugin) { return plugin(app) })) var node var root var batch = [] for (var i = 0; i < plugins.length; i++) { var plugin = plugins[i] if (plugin.model !== undefined) { model = merge(model, plugin.model) } if (plugin.actions) { init(actions, plugin.actions) } if (plugin.subscriptions) { subscriptions = subscriptions.concat(plugin.subscriptions) } var _hooks = plugin.hooks if (_hooks) { Object.keys(_hooks).forEach(function (key) { hooks[key].push(_hooks[key]) }) } } function onError(error) { for (var i = 0; i < hooks.onError.length; i++) { hooks.onError[i](error) } if (i <= 0) { throw error } } function init(container, group, lastName) { Object.keys(group).forEach(function (key) { if (!container[key]) { container[key] = {} } var name = lastName ? lastName + "." + key : key var action = group[key] var i if (typeof action === "function") { container[key] = function (data) { for (i = 0; i < hooks.onAction.length; i++) { hooks.onAction[i](name, data) } var result = action(model, data, actions, onError) if (result === undefined || typeof result.then === "function") { return result } else { for (i = 0; i < hooks.onUpdate.length; i++) { hooks.onUpdate[i](model, result, data) } model = merge(model, result) render(model, view) } } } else { init(container[key], action, name) } }) } load(function () { root = app.root || document.body.appendChild(document.createElement("div")) render(model, view) for (var i = 0; i < subscriptions.length; i++) { subscriptions[i](model, actions, onError) } }) function load(fn) { if (document.readyState[0] !== "l") { fn() } else { document.addEventListener("DOMContentLoaded", fn) } } function render(model, view) { for (i = 0; i < hooks.onRender.length; i++) { view = hooks.onRender[i](model, view) } patch(root, node, node = view(model, actions), 0) for (var i = 0; i < batch.length; i++) { batch[i]() } batch = [] } function merge(a, b) { var obj = {} var key if (isPrimitive(b) || Array.isArray(b)) { return b } for (key in a) { obj[key] = a[key] } for (key in b) { obj[key] = b[key] } return obj } function isPrimitive(type) { type = typeof type return type === "string" || type === "number" || type === "boolean" } function defer(fn, data) { setTimeout(function () { fn(data) }, 0) } function shouldUpdate(a, b) { return a.tag !== b.tag || typeof a !== typeof b || isPrimitive(a) && a !== b } function createElementFrom(node, isSVG) { var element // There are only two types of nodes. A string node, which is // converted into a Text node or an object that describes an // HTML element and may also contain children. if (typeof node === "string") { element = document.createTextNode(node) } else { element = (isSVG = isSVG || node.tag === "svg") ? document.createElementNS(SVG_NS, node.tag) : document.createElement(node.tag) for (var name in node.data) { if (name === "onCreate") { defer(node.data[name], element) } else { setElementData(element, name, node.data[name]) } } for (var i = 0; i < node.children.length; i++) { element.appendChild(createElementFrom(node.children[i], isSVG)) } } return element } function removeElementData(element, name, value) { element[name] = value element.removeAttribute(name) } function setElementData(element, name, value, oldValue) { if (name === "style") { for (var i in oldValue) { if (!(i in value)) { element.style[i] = "" } } for (var i in value) { element.style[i] = value[i] } } else if (name[0] === "o" && name[1] === "n") { var event = name.substr(2).toLowerCase() element.removeEventListener(event, oldValue) element.addEventListener(event, value) } else if (value === false) { removeElementData(element, name, value) } else { element.setAttribute(name, value) if (element.namespaceURI !== SVG_NS) { if (element.type === "text") { var oldSelStart = element.selectionStart var oldSelEnd = element.selectionEnd } element[name] = value if (oldSelStart >= 0) { element.setSelectionRange(oldSelStart, oldSelEnd) } } } } function updateElementData(element, data, oldData) { for (var name in merge(oldData, data)) { var value = data[name] var oldValue = oldData[name] var realValue = element[name] if (value === undefined) { removeElementData(element, name, value) } else if (name === "onUpdate") { defer(value, element) } else if ( value !== oldValue || typeof realValue === "boolean" && realValue !== value ) { // This prevents cases where the node's data is out of sync with // the element's. For example, a list of checkboxes in which one // of the elements is recycled. setElementData(element, name, value, oldValue) } } } function patch(parent, oldNode, node, index) { var element = parent.childNodes[index] if (oldNode === undefined) { parent.appendChild(createElementFrom(node)) } else if (node === undefined) { // Removing a child one at a time updates the DOM, so we end up // with an index out of date that needs to be adjusted. Instead, // collect all the elements and delete them in a batch. batch.push(parent.removeChild.bind(parent, element)) if (oldNode && oldNode.data && oldNode.data.onRemove) { defer(oldNode.data.onRemove, element) } } else if (shouldUpdate(node, oldNode)) { if (typeof node === "string") { element.textContent = node } else { parent.replaceChild(createElementFrom(node), element) } } else if (node.tag) { updateElementData(element, node.data, oldNode.data) var len = node.children.length, oldLen = oldNode.children.length for (var i = 0; i < len || i < oldLen; i++) { patch(element, oldNode.children[i], node.children[i], i) } } } }
JavaScript
0
@@ -1609,27 +1609,21 @@ esult == -= undefined + null %7C%7C type
3e9139641cec670eb524c8e4aaa87f4605ac621c
Add a test to ensure that "a = (1, 2)" is parsed and printed correctly.
test/parens.js
test/parens.js
var assert = require("assert"); var esprima = require("esprima"); var parse = require("../lib/parser").parse; var Printer = require("../lib/printer").Printer; var NodePath = require("ast-types").NodePath; var util = require("../lib/util"); var n = require("../lib/types").namedTypes; var b = require("../lib/types").builders; var printer = new Printer; function parseExpression(expr) { var ast = esprima.parse(expr); n.Program.assert(ast); ast = ast.body[0]; if (n.ExpressionStatement.check(ast)) return ast.expression; return ast; } function check(expr) { var ast1 = parseExpression(expr); var printed = printer.printGenerically(ast1).code; try { var ast2 = parseExpression(printed); } finally { assert.ok( util.deepEquivalent(ast1, ast2), expr + " printed incorrectly as " + printed ); } } var operators = [ "==", "!=", "===", "!==", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "&", // TODO Missing from the Parser API. "|", "^", "in", "instanceof", "&&", "||" ]; exports.testArithmetic = function(t) { check("1 - 2"); check(" 2 +2 "); operators.forEach(function(op1) { operators.forEach(function(op2) { check("(a " + op1 + " b) " + op2 + " c"); check("a " + op1 + " (b " + op2 + " c)"); }); }); t.finish(); }; exports.testUnary = function(t) { check("(-a).b"); check("(+a).b"); check("(!a).b"); check("(~a).b"); check("(typeof a).b"); check("(void a).b"); check("(delete a.b).c"); t.finish(); }; exports.testBinary = function(t) { check("(a && b)()"); check("typeof (a && b)"); check("(a && b)[c]"); check("(a && b).c"); t.finish(); }; exports.testSequence = function(t) { check("(a, b)()"); check("a(b, (c, d), e)"); check("!(a, b)"); check("a + (b, c) + d"); check("var a = (1, 2), b = a + a;"); check("(a, { b: 2 }).b"); check("[a, (b, c), d]"); check("({ a: (1, 2) }).a"); check("(a, b) ? (a = 1, b = 2) : (c = 3)"); t.finish(); }; exports.testNewExpression = function(t) { check("new (a.b())"); check("new (a.b())(c)"); check("new a.b(c)"); check("+new Date"); check("(new Date).getTime()"); check("new a"); check("(new a)(b)"); check("(new (a.b(c))(d))(e)"); check("(new Date)['getTime']()"); check('(new Date)["getTime"]()'); t.finish(); }; exports.testNumbers = function(t) { check("(1).foo"); check("(-1).foo"); check("+0"); check("NaN.foo"); check("(-Infinity).foo"); t.finish(); }; exports.testAssign = function(t) { check("!(a = false)"); check("a + (b = 2) + c"); check("(a = fn)()"); check("(a = b) ? c : d"); check("(a = b)[c]"); check("(a = b).c"); t.finish(); }; exports.testFunction = function(t) { check("a(function(){}.bind(this))"); check("(function(){}).apply(this, arguments)"); check("function f() { (function(){}).call(this) }"); check("while (true) { (function(){}).call(this) }"); t.finish(); }; exports.testObjectLiteral = function(t) { check("a({b:c(d)}.b)"); check("({a:b(c)}).a"); t.finish(); }; exports.testReprintedParens = function(t) { var code = "a(function g(){}.call(this));"; var ast1 = parse(code); var body = ast1.program.body; // Copy the function from a position where it does not need // parentheses to a position where it does need parentheses. body.push(b.expressionStatement( body[0].expression.arguments[0])); var generic = printer.printGenerically(ast1).code; var ast2 = parse(generic); assert.ok( util.deepEquivalent(ast1, ast2), "generic reprinting failed: " + generic); var reprint = printer.print(ast1).code; var ast3 = parse(reprint); assert.ok( util.deepEquivalent(ast1, ast3), "conservative reprinting failed: " + reprint); t.finish(); }; exports.testNegatedLoopCondition = function(t) { var ast = parse([ "for (var i = 0; i < 10; ++i) {", " console.log(i);", "}" ].join("\n")) var loop = ast.program.body[0]; var test = loop.test; var negation = b.unaryExpression("!", test); assert.strictEqual( printer.print(negation).code, "!(i < 10)" ); loop.test = negation; assert.strictEqual(printer.print(ast).code, [ "for (var i = 0; !(i < 10); ++i) {", " console.log(i);", "}" ].join("\n")); t.finish(); }; exports.testMisleadingExistingParens = function(t) { var ast = parse([ // The key === "oyez" expression appears to have parentheses // already, but those parentheses won't help us when we negate the // condition with a !. 'if (key === "oyez") {', " throw new Error(key);", "}" ].join("\n")); var ifStmt = ast.program.body[0]; ifStmt.test = b.unaryExpression("!", ifStmt.test); var binaryPath = new NodePath(ast).get( "program", "body", 0, "test", "argument"); assert.ok(binaryPath.needsParens()); assert.strictEqual(printer.print(ifStmt).code, [ 'if (!(key === "oyez")) {', " throw new Error(key);", "}" ].join("\n")); t.finish(); }; exports.testDiscretionaryParens = function(t) { var code = [ "if (info.line && (i > 0 || !skipFirstLine)) {", " info = copyLineInfo(info);", "}" ].join("\n"); var ast = parse(code); var rightPath = new NodePath(ast).get( "program", "body", 0, "test", "right"); assert.ok(rightPath.needsParens()); assert.strictEqual(printer.print(ast).code, code); t.finish(); };
JavaScript
0.00078
@@ -2126,16 +2126,41 @@ = 3)%22); +%0A check(%22a = (1, 2)%22); %0A%0A t.
d95e53c8ae63e8c32db4ab94a0db0055b913ee40
Update reason why micro.blog is skipped
test/remote.js
test/remote.js
import test from 'ava' import Ajv from 'ajv' import got from 'got' import schema from '..' const macro = (t, url) => { return got(url, { json: true }).then(res => { const valid = t.context.ajv.validate(schema, res.body) t.true(valid, t.context.ajv.errorsText()) }) } test.beforeEach(t => { t.context.ajv = new Ajv() }) test('shapeof.com', macro, 'http://shapeof.com/feed.json') test('flyingmeat.com', macro, 'http://flyingmeat.com/blog/feed.json') test('maybepizza.com', macro, 'http://maybepizza.com/feed.json') test('daringfireball.net', macro, 'https://daringfireball.net/feeds/json') test('hypercritical.co', macro, 'http://hypercritical.co/feeds/main.json') test('inessential.com', macro, 'http://inessential.com/feed.json') test('manton.org', macro, 'https://manton.org/feed/json') // Item IDs are numbers instead of strings. test.skip('micro.blog', macro, 'https://micro.blog/feeds/manton.json') test('timetable.manton.org', macro, 'http://timetable.manton.org/feed.json') test('therecord.co', macro, 'http://therecord.co/feed.json') test('allenpike.com', macro, 'http://www.allenpike.com/feed.json')
JavaScript
0.000001
@@ -806,47 +806,98 @@ %0A// -Item IDs are numbers instead of strings +%60author.url%60 sometimes is empty.%0A// See https://github.com/brentsimmons/JSONFeed/issues/35 .%0Ate
f46a57919e9d8ddbe48027abb497ebf9214d0aa9
support option '-i' and '--image' to specify rootfs image
bin/makerboard.js
bin/makerboard.js
#!/usr/bin/env node /* QEMU=`which qemu-mipsel-static` if [ ! -x "$QEMU" ]; then echo "No available QEMU utility can be used." echo "Please install it with command:" echo " sudo apt-get install qemu-user-static" exit fi */ var path = require('path'); var fs = require('fs'); var MakerBoard = require('../lib/makerboard'); var unzip = require('unzip2'); var yargs = require('yargs') .usage('Usage: $0 <command> [options]') .command('create', 'Create a new emulation environment') .command('run', 'Run specific emulation') .demand(1, 'require a valid command') .help('help'); var argv = yargs.argv; var command = argv._[0]; if (command === 'create') { var argv = yargs.reset() .usage('Usage: $0 create <path>') .help('help') .example('$0 create <path>', 'Create a new emulation environment') .demand(2, 'require a valid path') .argv; var targetPath = argv._[1].toString(); var firmwareUrl = 'https://s3-ap-southeast-1.amazonaws.com/mtk.linkit/openwrt-ramips-mt7688-root.squashfs'; var downloader = new MakerBoard.Downloader(); downloader.on('finished', function(fwPath) { console.log('Extracting ' + fwPath + '...'); // Extract filesystem var extract = new MakerBoard.Extract(); extract.unsquashFS(fwPath, targetPath, function() { // Initializing simulation var container = new MakerBoard.Container(); container.initEnvironment(targetPath, function() { console.log('Done'); }); }); }); downloader.download(firmwareUrl, false, path.join(__dirname, '..', 'data')); } else if (command === 'run') { var argv = yargs.reset() .usage('Usage: $0 run <path>') .help('help') .example('$0 run <path>', 'Run specific emulation') .demand(2, 'require a valid path') .argv; var targetPath = argv._[1].toString(); var container = new MakerBoard.Container(); container.run(targetPath, function() { console.log('QUIT!'); }); } else { yargs.showHelp(); }
JavaScript
0.000003
@@ -713,32 +713,155 @@ create %3Cpath%3E')%0A +%09%09.option('i', %7B%0A%09%09%09alias: 'image',%0A%09%09%09describe: 'specifying an image to be used',%0A%09%09%09type: 'string'%0A%09%09%7D)%0A%09%09.nargs('i', 1)%0A %09%09.help('help')%0A @@ -852,32 +852,32 @@ %09%09.help('help')%0A - %09%09.example('$0 c @@ -1021,201 +1021,39 @@ );%0A%09 -var firmwareUrl = 'https://s3-ap-southeast-1.amazonaws.com/mtk.linkit/openwrt-ramips-mt7688-root.squashfs';%0A%09var downloader = new MakerBoard.Downloader();%0A%09downloader.on('finished', function(fw +function extract(fwPath, target Path @@ -1104,17 +1104,16 @@ ...');%0A%0A -%0A %09%09// Ext @@ -1394,16 +1394,336 @@ ;%0A%09%09%7D);%0A +%09%7D%0A%0A%09if (fs.existsSync(argv.image)) %7B%0A%09%09extract(argv.image, targetPath);%0A%09%09return;%0A%09%7D%0A%0A%09var firmwareUrl = 'https://s3-ap-southeast-1.amazonaws.com/mtk.linkit/openwrt-ramips-mt7688-root.squashfs';%0A%09var downloader = new MakerBoard.Downloader();%0A%09downloader.on('finished', function(fwPath) %7B%0A%09%09extract(fwPath, targetPath);%0A %09%7D);%0A%09do @@ -1847,32 +1847,32 @@ = yargs.reset()%0A - %09%09.usage('Usage: @@ -1881,24 +1881,34 @@ 0 run %3Cpath%3E + %5Boptions%5D ')%0A%09%09.help('
2783e2e313fa1385a1db0001f38aea2029df7940
Improve docstrings
src/bem.js
src/bem.js
/* * This module provides BEM (Block Element Modifier) related methods * These methods can be used as an abstraction to talk to the DOM * BEM is a CSS methodology separating blocks (block) from elements (__element) and modifiers (--modifier) * BEM examples: alert, alert--warning, form__button, form__button--disabled * @see https://en.bem.info/methodology/key-concepts/ * @module */ /** * BEM class * Contains static methods with BEM abstraction to DOM manipulation * @class */ class BEM { /** * Get a node by BEM (Block Element Modifier) description * @param {string} block The outer block or component * @param {string} [element] An optional element within the outer block * @param {string} [modifier] An optional modifier or (e.g. state or theme) for a block/element * @returns {HTMLElement} */ static getBEMNode(block, element, modifier) { let selector = `.${BEM.getBEMClassName(block, element, modifier)}`; return document.querySelector(selector); } /** * Get multiple nodes by BEM (Block Element Modifier) description * @param {string} block The outer block or component * @param {string} [element] An optional element within the outer block * @param {string} [modifier] An optional modifier or (e.g. state or theme) for a block/element * @returns {NodeList} */ static getBEMNodes(block, element, modifier) { let selector = `.${BEM.getBEMClassName(block, element, modifier)}`; return document.querySelectorAll(selector); } /** * Get a child node by BEM (Block Element Modifier) description * @param {HTMLElement} node The parent node * @param {string} block The outer block or component * @param {string} [element] An optional element within the outer block * @param {string} [modifier] An optional modifier or (e.g. state or theme) for a block/element * @returns {HTMLElement} */ static getChildBEMNode(node, block, element, modifier) { let selector = `.${BEM.getBEMClassName(block, element, modifier)}`; return node.querySelector(selector); } /** * Get a child node by BEM (Block Element Modifier) description * @param {HTMLElement} node The parent node * @param {string} block The outer block or component * @param {string} [element] An optional element within the outer block * @param {string} [modifier] An optional modifier or (e.g. state or theme) for a block/element * @returns {HTMLElement} */ static getChildBEMNodes(node, block, element, modifier) { let selector = `.${BEM.getBEMClassName(block, element, modifier)}`; return node.querySelectorAll(selector); } /** * Get a BEM (Block Element Modifier) class name * @param {string} block The outer block or component * @param {string} [element] An optional element within the outer block * @param {string} [modifier] An optional modifier or (e.g. state or theme) for a block/element * @returns {string} */ static getBEMClassName(block, element, modifier) { let className = block; if (element) { className += `__${element}`; } if (modifier) { className += `--${modifier}`; } return className; } /** * Add an additional class name with a specific modifier (--modifier) to a BEM (Block Element Modifier) element * A modifier class is created for each of the existing class names * Class names containing "--" (modifier pattern) are discarded * Double class names are prevented * @param {HTMLElement} node The block/element to append the class name to (block, block__element) * @param {string} modifier The name of the modifier (--name) * @param {boolean} [exp] Optional: If true: add the modifier */ static addModifier(node, modifier, exp=true) { if (!exp) { return; } [].forEach.call(node.classList, classListItem => { // Discard class names containing "--" (modifier pattern) if (classListItem.match('--')) { return; } let modifierClassName = `${classListItem}--${modifier}`; // Prevent double class names if (node.classList.contains(modifierClassName)) { return; } node.classList.add(modifierClassName); }); } /** * Remove all class names with a specific modifier (--modifier) from a BEM (Block Element Modifier) element * @param {HTMLElement} node The block/element to remove the class names from (block, block__element) * @param {string} modifier The name of the modifier (--name) * @param {boolean} [exp] Optional: If true: remove the modifier */ static removeModifier(node, modifier, exp=true) { if (!exp) { return; } let regex = new RegExp(`[^^\\s]+?--${modifier}\\s?`, 'g'); // Regex matching all class names containing "--" + modifier node.className = node.className.replace(regex, '').trim(); } /** * Toggles between addModifier() and removeModifier() based on the presence of modifier (--modifier) * Block/element names are NOT taken into account while matching * @param {HTMLElement} node The block/element to remove the class names from (block, block__element) * @param {string} modifier The name of the modifier (--name) * @param {boolean} [exp] Optional: If true: add the modifier, if false: remove the modifier */ static toggleModifier(node, modifier, exp=!BEM.hasModifier(node, modifier)) { if (exp) { BEM.addModifier(node, modifier); return; } BEM.removeModifier(node, modifier); } /** * Returns whether node has modifier (--modifier) * Block/element names are NOT taken into account while matching * @param {HTMLElement} node The block/element to check * @param {string} modifier The name of the modifier (--name) * @returns {boolean} */ static hasModifier(node, modifier) { let regex = new RegExp(`--${modifier}(?=\\s|$)`, 'g'); // Regex matching specific modifier return node.className.match(regex); } } export default BEM; export { BEM };
JavaScript
0.000005
@@ -3824,32 +3824,37 @@ m %7Bboolean%7D %5Bexp +=true %5D Optional: If t @@ -4794,32 +4794,37 @@ m %7Bboolean%7D %5Bexp +=true %5D Optional: If t
3a38e4aa5deb756f49054d85512342b2b209396f
Fix assertion in a bot method
src/bot.js
src/bot.js
'use strict'; const { expect } = require('code'); const Rx = require('rx-lite'); const Logger = require('./logger'); const logLevel = process.env.NODE_ENV === 'production' ? 'info' : 'debug'; const slackToken = process.env.SLACK_TOKEN; class Bot { constructor(controller) { this._logger = new Logger(logLevel, ['slack-api']); this._bot = controller .spawn({ token: slackToken }) .startRTM((err, bot, payload) => { if (err) { throw new Error(`Error connecting to Slack: ${err}`); } this._logger.info('Connected to Slack'); }); } getUsers() { return Rx.Observable .fromNodeCallback(this._bot.api.users.list)({}) .map(response => (response || {}).members) .do( users => { this._logger.debug(`Got ${(users || []).length} users on the team`); }, err => { this._logger.error(`Failed to get users on the team: ${err}`); } ); } getChannels() { return Rx.Observable .fromNodeCallback(this._bot.api.channels.list)({}) .map(response => (response || {}).channels) .do( channels => { this._logger.debug(`Got ${(channels || []).length} channels on ' + 'the team`); }, err => { this._logger.error(`Failed to get channels on the team: ${err}`); } ); } sayError(channel) { return this.sayMessage({ channel, text: 'Something went wrong. Please try again or contact @yenbekbay' }); } sayMessage(message) { expect(message).to.be.an.object.and.to.include(['text', 'channel']); return Rx.Observable .fromNodeCallback(this._bot.say)(message) .doOnError(err => this._logger .error(`Failed to send a message to channel ${message.channel}: ${err}`) ); } } module.exports = Bot;
JavaScript
0.001017
@@ -1594,16 +1594,18 @@ n.object +() .and.to.
3edaf73ce8b9eddb926be3ca50c57097a587410e
Remove code for debugging Travis
test/shared.js
test/shared.js
import React from 'react'; import { mount } from 'enzyme'; import { createStore } from 'redux'; import Phone from '../dev-server/Phone'; import App from '../dev-server/containers/App'; import brandConfig from '../dev-server/brandConfig'; import version from '../dev-server/version'; import prefix from '../dev-server/prefix'; import state from './state.json'; console.info(process.env); const apiConfig = { appKey: process.env.appKey, appSecret: process.env.appSecret, server: process.env.server, }; export const getPhone = async () => { const phone = new Phone({ apiConfig, brandConfig, prefix, appVersion: version, }); if (window.authData === null) { await phone.client.service.platform().login({ username: process.env.username, extension: process.env.extension, password: process.env.password }); window.authData = phone.client.service.platform().auth().data(); } else { phone.client.service.platform().auth().setData(window.authData); } state.storage.status = 'module-initializing'; const store = createStore(phone.reducer, state); phone.setStore(store); return phone; }; export const getWrapper = async () => { const phone = await getPhone(); return mount(<App phone={phone} />); }; export const getState = wrapper => wrapper.props().phone.store.getState(); export const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
JavaScript
0.000038
@@ -359,36 +359,8 @@ ';%0A%0A -console.info(process.env);%0A%0A cons
95838bfb121b5a0c4ed38f7a1c8a910a0bf65285
Update simple.js
test/simple.js
test/simple.js
JavaScript
0.000001
@@ -1 +1,3037 @@ %0A +var assert = require('assert');%0Avar global_variable = 'i am global';%0A%0Adescribe('mocha runner', function () %7B%0A this.timeout(0);%0A var describe_variable = 'i am in describe';%0A%0A before('Before all hook', function (done) %7B%0A console.info('before all');%0A //throw new Error('whatever');%0A done();%0A %7D);%0A%0A it('should start log', function (done) %7B%0A console.info('Hello');%0A done();%0A %7D);%0A%0A it('should throw', function () %7B%0A console.error(new Error('test#1'));%0A console.log('sgsdglknsldgnslkdgnlasgndl;asdgnlasdgnasldg0');%0A %7D);%0A%0A it('should return console log text and shows strings diff', function () %7B%0A console.info('test#string');%0A assert.equal('stringA', 'stringB');%0A %7D);%0A%0A it('should return console log text and shows date diff', function () %7B%0A console.info('test#date');%0A assert.equal(new Date(), new Date('01-01-2016'));%0A %7D);%0A%0A it('should return console log text and shows array diff', function () %7B%0A console.info('test#array');%0A assert.equal(%5B'1', '2'%5D, %5B'3', '2'%5D);%0A %7D);%0A%0A it('should compare two objects', function () %7B%0A console.info('test#object');%0A var foo = %7B%0A 'largestCities': %5B%0A 'S%C3%A3o Paulo',%0A 'Buenos Aires',%0A 'Rio de Janeiro',%0A 'Lima',%0A 'Bogot%C3%A1'%0A %5D,%0A 'languages': %5B%0A 'spanish',%0A 'portuguese',%0A 'english',%0A 'dutch',%0A 'french',%0A 'quechua',%0A 'guaran%C3%AD',%0A 'aimara',%0A 'mapudungun'%0A %5D%0A %7D;%0A var bar = %7B%0A 'largestCities': %5B%0A 'S%C3%A3o Paulo',%0A 'Buenos Aires',%0A 'Rio de Janeiro',%0A 'Lima',%0A 'Bogot%C3%A1'%0A %5D,%0A 'languages': %5B%0A 'spanish',%0A 'portuguese',%0A 'ingl%C3%A9s',%0A 'dutch',%0A 'french',%0A 'quechua',%0A 'guaran%C3%AD',%0A 'aimara',%0A 'mapudungun'%0A %5D%0A %7D;%0A assert.deepEqual(foo, bar);%0A %7D);%0A%0A it('should compare true and false', function () %7B%0A var foo = 5;%0A assert.equal(true, false);%0A %7D);%0A%0A describe('Handle console output deeper', function () %7B%0A it('should delay test and pass', function (done) %7B%0A console.info('test with delay');%0A assert.ok(true);%0A setTimeout(done, 1000);%0A %7D);%0A %7D);%0A%0A%0A%0A describe('Handle console output1', function () %7B%0A it('should return console log text', function () %7B%0A console.info('test pass');%0A %7D);%0A %7D);%0A%0A describe('Skip this', function () %7B%0A it.skip('should skip test', function () %7B%0A console.info('test skiped');%0A %7D);%0A %7D);%0A after('after this describe hook', function () %7B%0A console.info('after hook');%0A %7D);%0A%7D);%0A
e9ec6db0078efdc45678a52b75b4d7b1b08678e0
add shortcut -x for --proxy
src/hii.js
src/hii.js
/** * @file * @author zdying */ var __hiipack = require('./global'); var express = require('express'); var path = require('path'); var fs = require('fs'); var fse = require('fs-extra'); var colors = require('colors'); var child_process = require('child_process'); var os = require('os'); var server = require('./server'); var client = require('./client'); var package = require('../package.json'); var program = global.program; try{ fse.copy(path.resolve(__hiipack__.root, 'tmpl', '_cache'), __hiipack__.tmpdir, function(err){ if(err) console.error(err); }); }catch(e){ } // console.log('__hiipack__.root'.bold.magenta, '==>', __hiipack_root__); // console.log('__hiipack__.cwd '.bold.magenta, '==>', __hiipack_cwd__); // console.log(process.env.NODE_PATH); program .version(package.version, '-v, --version') .option('-o, --open', 'open in browser') .option('-p, --port <port>', 'service port', 8800) .option('-r, --registry <registry>', 'npm registry address') .option('-d, --debug', 'print debug log') //TODO add this next version // .option('-U, --uglify', 'uglify javascript') //TODO add this next version // .option('-e, --extract-css', 'extract css from javascript') .option('-D, --detail', 'print debug and error detail log') // .option('-w, --workspace <workspace>', 'workspace', process.cwd()) .option('-t, --type <type>', 'project type: one of react|react-redux|es6|vue|normal|empty', /^(react|react-redux|es6|vue|normal|empty)$/, 'normal') .option('--no-color', 'disable log color') .option('--proxy', 'start the proxy server'); program .command('init <name>') .description('initialize project') .action(function(name){ client.init(name, program.type, program.registry); }); program .command('start') .description('create a local server') .action(function(){ server.start(program.port, program.open, program.proxy); }); program .command('min') .description('compress/obfuscate project files') .action(function(){ client.build(); }); program .command('pack') .description('pack project files') .action(function(){ client.pack(); }); program .command('sync') .description('synchronize the current directory to remote server') .action(function(){ client.sync(); }); program .command('test') .description('run unit test') .action(function(){ client.test(); }); program .command('clear') .description('clear resulting folders of hiipack') .action(function(){ fse.remove('dev'); fse.remove('prd'); fse.remove('ver'); fse.remove('loc'); fse.remove('dll'); // child_process.exec('rm -rdf dll loc dev prd ver') }); program.on('--help', function(){ console.log(' Examples:'); console.log(''); console.log(' $ hii init project_name'); console.log(' $ hii start'); console.log(' $ hii start -p 8800'); console.log(' $ hii pack'); console.log(' $ hii sync'); console.log(' $ hii min'); console.log(''); console.log(' Wiki:'); console.log(''); console.log(' https://github.com/zdying/hiipack/wiki/hiipack-%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E'); }); program.parse(process.argv); if(process.argv.length == 2){ showVersion(); } function showVersion(){ var version = package.version.magenta; var versionLen = version.length; var spaces = new Array(25 - versionLen + 3).join(' '); console.log(''); console.log(' .-----------------------------.'); console.log(' | ' + 'hiipack'.bold + ' ' + version + spaces + ' |'); console.log(' | ' + 'author ', 'zdying@live.com'.yellow.bold + ' |'); console.log(' | ' + 'github.com/zdying/hiipack'.green.underline + ' |'); console.log(' \'-----------------------------\''); console.log(''); }
JavaScript
0.000002
@@ -1364,16 +1364,69 @@ .cwd())%0A + .option('-x, --proxy', 'start the proxy server')%0A .opt @@ -1619,57 +1619,8 @@ or') -%0A .option('--proxy', 'start the proxy server') ;%0A%0Ap
fc9c697bed738906673f210c0bf760b5b0a11047
use files and roots everywhere
src/cli.js
src/cli.js
#!/usr/bin/env node import 'babel-polyfill' import log from 'npmlog' import untildify from 'untildify' // don't log the config until the log level is set import config from './config/default.js' import options from './config/options.js' import saveConfig from './config/save.js' import albums from './command/albums.js' import artists from './command/artists.js' import audit from './command/audit.js' import inspect from './command/inspect.js' import optimize from './command/optimize.js' import pls from './command/pls.js' import unpack from './command/unpack.js' const yargs = require('yargs') .usage('Usage: $0 [options] <command>') .command('albums', 'generate a list of albums from roots') .command('artists', 'generate a list of artists from roots') .command('audit', 'check metadata for inconsistencies') .command('inspect', 'dump all the metadata from a track or album') .command('optimize', 'find the best set of albums to pack a given capacity') .command('pls', 'print a list of albums as a .pls file, sorted by date') .command('unpack', 'unpack a set of zipped files into a staging directory') .options({ S: options.S, loglevel: options.loglevel }) .help('h') .alias('h', 'help') .version(() => require('../package').version) .demand(1) log.level = yargs.argv.loglevel log.verbose('config', config) let argv, command, roots, files switch (yargs.argv._[0]) { case 'albums': argv = yargs.reset() .usage('Usage: $0 [options] albums [-R dir [file...]]') .options({ R: options.R }) .check(argv => { if (argv._.length > 1 || (argv.R && argv.R.length)) return true return 'Must pass 1 or more audio files or directory trees.' }) .argv roots = argv.R.map(r => untildify(r)) log.silly('albums', 'argv', argv) command = albums(argv._.slice(1), argv.R) break case 'artists': options.R.required = '- Must have at least one tree to scan.' argv = yargs.reset() .usage('Usage: $0 artists [-R dir [-R dir...]]') .options({ R: options.R }) .argv roots = argv.R.map(r => untildify(r)) log.silly('artists', 'argv', argv) command = artists(roots) break case 'audit': argv = yargs.reset() .usage('Usage: $0 audit [file [file...]]') .check(argv => { if (argv._.length > 1) return true return 'must pass either 1 or more files containing metadata' }) .argv files = argv._.slice(1).map(f => untildify(f)) log.silly('audit', 'argv', argv) command = audit(files) break case 'inspect': argv = yargs.reset() .usage('Usage: $0 [options] inspect [file [dir...]]') .demand(2) .argv files = argv._.slice(1).map(f => untildify(f)) log.silly('audit', 'argv', argv) command = inspect(files) break case 'optimize': argv = yargs.reset() .usage('Usage: $0 [options] optimize -O blocks [-R dir [file...]]') .options({ B: options.B, O: options.O, R: options.R }) .check(argv => { if (argv._.length > 1 || (argv.R && argv.R.length)) return true return 'Must pass 1 or more audio files or directory trees.' }) .argv files = argv._.slice(1).map(f => untildify(f)) roots = (argv.R || []).map(r => untildify(r)) log.silly('optimize argv', argv) command = optimize(files, roots, argv.B, argv.O) break case 'pls': options.R.required = '- Must have at least one tree to scan.' argv = yargs.reset() .usage('Usage: $0 [options] pls [-R dir [-R dir...]]') .options({ R: options.R }) .argv roots = argv.R.map(r => untildify(r)) log.silly('pls', 'argv', argv) command = pls(roots) break case 'unpack': options.R.describe = 'root directory containing zipped files' argv = yargs.reset() .usage('Usage: $0 [options] unpack [zipfile [zipfile...]]') .options({ R: options.R, P: options.P, s: options.s, archive: options.archive, 'archive-root': options.archiveRoot, playlist: options.playlist }) .check(argv => { if (argv._.length > 1 || (argv.R && argv.R.length && argv.P)) return true return 'Must pass either 1 or more zipfiles, or root and glob pattern.' }) .argv files = argv._.slice(1).map(f => untildify(f)) roots = (argv.R || []).map(r => untildify(r)) log.silly('unpack argv', argv) command = unpack( { files, roots, pattern: argv.P }, argv.s, argv.archive && argv.archiveRoot, argv.playlist ) break default: yargs.showHelp() process.exit(1) } if (argv.saveConfig) command = command.then(() => saveConfig(argv)) command.then(() => { log.silly('packard', 'tracker debugging', log.tracker.debug()) }).catch(e => { log.disableProgress() log.error('packard', e.stack) })
JavaScript
0
@@ -2049,32 +2049,83 @@ .argv%0A + files = argv._.slice(1).map(f =%3E untildify(f))%0A roots = argv @@ -2112,38 +2112,46 @@ f))%0A roots = +( argv.R + %7C%7C %5B%5D) .map(r =%3E untild @@ -2222,31 +2222,20 @@ ums( -argv._.slice(1), argv.R +files, roots )%0A
3e20a04f3bc44dfea4a6e93fa3054c05e1f4b9d9
update email address
src/cli.js
src/cli.js
var program = require('commander'); var fs = require('fs'); var path = require('path'); var pjson = require('../package.json'); var colors = require('colors/safe'); var Runner = require('./runner'); program .version(pjson.version) .option('-c, --conf <config-file>', 'Path to Configuration File') .parse(process.argv); console.log(colors.bold('\nscreener-runner v' + pjson.version + '\n')); if (!program.conf) { console.error('--conf is a required argument. Type --help for more information.'); process.exit(1); } var configPath = path.resolve(process.cwd(), program.conf); if (!fs.existsSync(configPath)) { console.error('Config file path "' + program.conf + '" cannot be found.'); process.exit(1); } var config = require(configPath); if (config === false) { console.log('Config is false. Exiting...'); process.exit(); } Runner.run(config) .then(function(response) { console.log(response); process.exit(); }) .catch(function(err) { console.error(err.message || err.toString()); if (typeof err.annotate === 'function') { console.error('Annotated Error Details:'); console.error(err.annotate()); } console.error('---'); console.error('Exiting Screener Runner'); console.error('Need help? Contact: support@screener.io'); var exitCode = 1; if (config && typeof config.failureExitCode === 'number' && config.failureExitCode > 0) { exitCode = config.failureExitCode; } process.exit(exitCode); });
JavaScript
0.000001
@@ -1268,27 +1268,26 @@ ct: -support@screener.io +help@saucelabs.com ');%0A
e10198543eb2d6ee8764784b44b92187eceb4b1d
Update path to compare page
src/cli.js
src/cli.js
#!/usr/bin/env node import 'babel-polyfill'; import commander from 'commander'; import { getPreviousSha, setPreviousSha } from './previousSha'; import constructReport from './constructReport'; import createDynamicEntryPoint from './createDynamicEntryPoint'; import createWebpackBundle from './createWebpackBundle'; import getSha from './getSha'; import loadCSSFile from './loadCSSFile'; import loadUserConfig from './loadUserConfig'; import packageJson from '../package.json'; import processSnapsInBundle from './processSnapsInBundle'; import uploadReport from './uploadReport'; commander .version(packageJson.version) .usage('[options] <regexForTestName>') .parse(process.argv); const { apiKey, apiSecret, setupScript, webpackLoaders, stylesheets = [], include = '**/@(*-snaps|snaps).@(js|jsx)', targets = {}, //viewerEndpoint = 'http://localhost:4432', viewerEndpoint = 'https://happo.now.sh', } = loadUserConfig(); // const previewServer = new PreviewServer(); // previewServer.start(); (async function() { const sha = await getSha(); const previousSha = getPreviousSha(); console.log('Generating entry point...'); const entryFile = await createDynamicEntryPoint({ setupScript, include }); console.log('Producing bundle...'); const bundleFile = await createWebpackBundle(entryFile, { webpackLoaders }); const cssBlocks = await Promise.all(stylesheets.map(loadCSSFile)); console.log('Executing bundle...'); const snapPayloads = await processSnapsInBundle(bundleFile, { globalCSS: cssBlocks.join('').replace(/\n/g, ''), }); console.log('Generating screenshots...'); const results = await Promise.all(Object.keys(targets).map(async (name) => { const target = targets[name]; const result = await target.execute(snapPayloads); return { name, result, }; })); const snaps = await constructReport(results); await uploadReport({ snaps, sha, endpoint: viewerEndpoint, apiKey, apiSecret, }); setPreviousSha(sha); if (previousSha) { console.log(`${viewerEndpoint}/report?q=${previousSha}..${sha}`); } else { console.log('No previous report found'); } })();
JavaScript
0
@@ -2079,22 +2079,23 @@ dpoint%7D/ -report +compare ?q=$%7Bpre
401c01ad7684bc9451a2987d9a19269a1f9ec2ec
fix English grammar in CLI output when there's only 1 file
src/cli.js
src/cli.js
#!/usr/bin/env node /*eslint-env node */ /*eslint no-process-exit: 0 */ 'use strict'; var fs = require('fs'); var glob = require('glob'); var bootlint = require('./bootlint.js'); var totalErrCount = 0; var totalFileCount = 0; var disabledIds = []; var patterns = process.argv.slice(2); patterns.forEach(function (pattern) { var filenames = glob.sync(pattern); filenames.forEach(function (filename) { var reporter = function (lint) { console.log(filename + ":", lint.id, lint.message); totalErrCount++; }; var html = null; try { html = fs.readFileSync(filename, {encoding: 'utf8'}); } catch (err) { console.log(filename + ":", err); return; } bootlint.lintHtml(html, reporter, disabledIds); totalFileCount++; }); }); console.log("" + totalErrCount + " lint error(s) found across " + totalFileCount + " files."); if (totalErrCount) { process.exit(1); }
JavaScript
0.000042
@@ -947,17 +947,19 @@ + %22 file -s +(s) .%22);%0Aif
2f43aa247e5032ed61112c63ff1461b6d04a8d9d
Remove stray word
react/components/ManageChannel/index.js
react/components/ManageChannel/index.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { compose, graphql } from 'react-apollo'; import { propType } from 'graphql-anywhere'; import { some } from 'underscore'; import styled from 'styled-components'; import mapErrors from 'react/util/mapErrors'; import compactObject from 'react/util/compactObject'; import manageChannelFragment from 'react/components/ManageChannel/fragments/manageChannel'; import manageChannelQuery from 'react/components/ManageChannel/queries/manageChannel'; import updateChannelMutation from 'react/components/ManageChannel/mutations/updateChannel'; import Box from 'react/components/UI/Box'; import ErrorAlert from 'react/components/UI/ErrorAlert'; import Accordion from 'react/components/UI/Accordion'; import Text from 'react/components/UI/Text'; import LoadingIndicator from 'react/components/UI/LoadingIndicator'; import TitledDialog from 'react/components/UI/TitledDialog'; import RadioOptions from 'react/components/UI/RadioOptions'; import { LabelledInput, Label, Input, Textarea } from 'react/components/UI/Inputs'; import ExportChannel from 'react/components/ManageChannel/components/ExportChannel'; import DeleteChannel from 'react/components/ManageChannel/components/DeleteChannel'; import TransferChannel from 'react/components/ManageChannel/components/TransferChannel'; import ChannelVisibilityPulldown from 'react/components/ChannelVisibilityPulldown'; const Container = styled.div` width: 100%; margin: 0 auto 2em auto; `; class ManageChannel extends Component { static propTypes = { data: PropTypes.shape({ loading: PropTypes.bool.isRequired, channel: propType(manageChannelFragment), }).isRequired, updateChannel: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, } state = { mode: 'resting', title: null, description: null, visibility: null, attributeErrors: {}, content_flag: null, errorMessage: '', }; handleInput = fieldName => ({ target: { value: fieldValue } }) => { const { data: { channel: originalChannel } } = this.props; const isEdited = some(originalChannel, (originalValue, key) => fieldName === key && originalValue !== fieldValue); this.setState({ mode: isEdited ? 'submit' : 'resting', [fieldName]: fieldValue, }); } handleTitle = this.handleInput('title') handleDescription = this.handleInput('description') handleVisibility = visibility => this.handleInput('visibility')({ target: { value: visibility } }); handleNSFW = flag => this.handleInput('content_flag')({ target: { value: flag } }); handleSubmit = (e) => { e.preventDefault(); const { onClose, updateChannel, data: { channel: { id } }, } = this.props; const { mode, title, description, visibility, content_flag, } = this.state; if (mode === 'resting') return onClose(); this.setState({ mode: 'submitting' }); const variables = compactObject({ id, title, description, visibility, content_flag, }); return updateChannel({ variables }) .then(({ data: { update_channel: { channel: { href } } } }) => { onClose(); // Slug may have changed so redirect window.location = href; }) .catch((err) => { this.setState({ mode: 'error', ...mapErrors(err), }); }); } handle render() { const { data: { loading } } = this.props; const { mode, attributeErrors, errorMessage, } = this.state; if (loading) return <LoadingIndicator />; const { data: { channel } } = this.props; return ( <TitledDialog title="Edit channel" label={{ resting: 'Done', submit: 'Save', submitting: 'Saving...', deleting: 'Deleting...', error: 'Error', }[mode]} onDone={this.handleSubmit} > <Container> {mode === 'error' && <ErrorAlert isReloadable={false}> {errorMessage} </ErrorAlert> } <Accordion label="Edit name, description, and privacy"> <LabelledInput> <Label>Name</Label> <Input name="title" defaultValue={channel.title} onChange={this.handleTitle} errorMessage={attributeErrors.title} required /> </LabelledInput> <LabelledInput> <Label> Description </Label> <Textarea name="description" defaultValue={channel.description} onChange={this.handleDescription} placeholder="describe your channel here" rows="3" errorMessage={attributeErrors.description} /> </LabelledInput> <LabelledInput> <Label> Privacy </Label> <div> <ChannelVisibilityPulldown value={channel.visibility.toUpperCase()} onChange={this.handleVisibility} /> </div> </LabelledInput> </Accordion> <Accordion label="NSFW?" mode="closed"> <Box m={7}> <Text f={2} mb={7}> Channels marked NSFW will be hidden from explore and profile views for users who have &quot;Show NSFW content&quot; set to false </Text> <RadioOptions value={channel.content_flag.toUpperCase()} onSelect={this.handleNSFW} size="1em"> <RadioOptions.Option value="SAFE"> {() => ( <Text f={3} mb={3}> <strong>No</strong> </Text> )} </RadioOptions.Option> <RadioOptions.Option value="NSFW"> {() => ( <Text f={3} mb={3}> <strong>Yes</strong> </Text> )} </RadioOptions.Option> </RadioOptions> </Box> </Accordion> {channel.can.export && <Accordion label="Export" mode="closed"> <Box m={7}> <ExportChannel id={channel.id} /> </Box> </Accordion> } {channel.can.transfer && <Accordion label="Transfer ownership" mode="closed"> <Box m={7}> <TransferChannel channel={channel} /> </Box> </Accordion> } {channel.can.destroy && <Accordion label="Delete channel" mode="closed"> <Box m={7}> <DeleteChannel id={channel.id} /> </Box> </Accordion> } </Container> </TitledDialog> ); } } export default compose( graphql(manageChannelQuery), graphql(updateChannelMutation, { name: 'updateChannel' }), )(ManageChannel);
JavaScript
0.999407
@@ -3412,18 +3412,8 @@ %7D%0A%0A - handle%0A%0A re
109561225a43b1f487c09a2acf84d955892d5c37
add async harness to CRL
src/crl.js
src/crl.js
(function(){ /* CRL (Cor Runtime Library) */ var hasProp = Object.prototype.hasOwnProperty, slice = Array.prototype.slice; CRL = (typeof CRL === 'undefined' ? {} : CRL); CRL.idSeed = 1; CRL.instancers = []; CRL.nativeTypes = { 'String' : String, 'Number' : Number, 'Boolean' : Boolean, 'RegExp' : RegExp, 'Array' : Array, 'Object' : Object, 'Function' : Function }; CRL.copyObj = function copyObj(from, to, strict) { var name; if (strict) { for (name in from) { if (hasProp.call(from, name)) { to[name] = from[name]; } } } else { for (name in from) { to[name] = from[name]; } } return to; }; CRL.create = function create(Class) { var instancerArgs, args = slice.call(arguments, 1), argc = args.length, i = -1, instancer = this.instancers[argc]; if (! instancer) { instancerArgs = []; while (++i < argc) { instancerArgs.push('args[' + i + ']'); } this.instancers[argc] = instancer = new Function('cls', 'args', 'return new cls(' + instancerArgs.join(',') + ');'); } if (typeof Class === 'function') { return instancer(Class, args); } throw Error('Runtime Error: trying to instanstiate no class'); }; CRL.extend = function extend(Cls, baseCls) { CRL.copyObj(baseCls, Cls, true); function Proto() { this.constructor = Cls; } Proto.prototype = baseCls.prototype; Cls.prototype = new Proto(); } CRL.keys = function keys(obj) { var keys, i, len; if (obj instanceof Array) { i = -1; len = obj.length; keys = []; while (++i < len) { keys.push(i); } } else { if (typeof Object.keys === 'function') { keys = Object.keys(obj); } else { for (i in obj) { if (hasProp.call(obj, i)) { keys.push(i); } } } } return keys; }; CRL.assertType = function assertType(obj, Class) { var type; // Class is a Class? if (typeof Class === 'function') { // object is defined? if (typeof obj !== 'undefined') { if (obj instanceof Class) { return true; } // otherwise find the native type according to "Object.prototype.toString" else { type = Object.prototype.toString.call(obj); type = type.substring(8, type.length - 1); if(hasProp.call(this.nativeTypes, type) && this.nativeTypes[type] === Class) { return true; } } } else { throw 'Trying to assert undefined object'; } } else { throw 'Trying to assert undefined class'; } return false; }; CRL.go = function go(gen) { return gen; } })();
JavaScript
0.000001
@@ -3007,16 +3007,1048 @@ e;%0A%7D;%0A%0A%0A +// Schedule%0Afunction schedule(fn, time) %7B%0A if (time === void 0 && typeof global.setImmediate !== 'undefined') %7B%0A setImmediate(fn);%0A %7D else %7B%0A setTimeout(fn, +time);%0A %7D%0A%7D%0A%0A// Breakpoint%0Afunction Breakpoint(timeout) %7B%0A var me = this;%0A%0A if (!isNaN(me.timeout)) %7B%0A schedule(function()%7B me.resume() %7D, timeout);%0A %7D%0A%0A this.resumed = false;%0A%7D%0A%0ABreakpoint.prototype = %7B%0A resume: function(value, err) %7B%0A this.resumed = true;%0A if (this.doneListeners) %7B%0A this.doneListeners.forEach(function(listener)%7B%0A listener(val, err);%0A %7D);%0A %7D%0A %7D,%0A%0A done: function(fn) %7B%0A if (! this.doneListeners) %7B this.doneListeners = %5B%5D %7D%0A this.doneListeners.push(fn);%0A return this;%0A %7D%0A%7D;%0A%0ABreakpoint.resumeAll = function(array, withValue) %7B%0A while (array.length) %7B%0A array.shift().resume(withValue);%0A %7D%0A%7D%0A%0Afunction isBreakpoint(b) %7B%0A return b instanceof Breakpoint;%0A%7D%0A%0ACRL.Breakpoint = Breakpoint;%0A%0A%0A// Generator Runner%0A CRL.go = @@ -4063,24 +4063,30 @@ n go(gen +f, ctx ) %7B%0A return g @@ -4081,21 +4081,363 @@ -return gen;%0A%7D +var state,%0A gen = genf.apply(ctx);%0A%0A next(gen);%0A%0A function next(gen, value) %7B%0A state = gen.next(value);%0A value = state.value;%0A%0A if (isBreakpoint(value)) %7B%0A value.done(function(value) %7B%0A next(value)%0A %7D)%0A %7D%0A%0A if (! state.done) %7B%0A next(gen, value)%0A %7D%0A %7D%0A%7D%0A %0A%0A%7D)
6f70f049f5e5e4a98eb38352d8f278fa8d77132f
Correct use of `commander` for parsing CLI options
bin/thoughtful.js
bin/thoughtful.js
#!/usr/bin/env node /*! * thoughtful-release <https://github.com/nknapp/thoughtful-release> * * Copyright (c) 2015 Nils Knappmeier. * Released under the MIT license. */ 'use strict' var program = require('commander') program .version(require('../package').version) .command('changelog <release>', 'update the CHANGELOG.md of the module in the current directory') .option('<release>', 'The target release of the changelog (same as for "npm version")') .action((release) => { console.log('Updating changelog') require('../index.js').updateChangelog(process.cwd(), release).done(console.log) }) program.parse(process.argv)
JavaScript
0
@@ -301,18 +301,33 @@ elease%3E' -, +)%0A .description( 'update @@ -656,8 +656,103 @@ s.argv)%0A +%0Aif (process.argv.length === 2) %7B%0A // No args provided: Display help%0A program.outputHelp()%0A%7D%0A
1b3b24a73e34fb953535411d44485f23d02a4fc8
Update gameVersion
public/js/database.js
public/js/database.js
// LoL Cruncher - A Historical League of Legends Statistics Tracker // Copyright (C) 2015 Jason Chu (1lann) 1lanncontact@gmail.com // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // jscs: disable // Database management: Performs back-end AJAX queries for data var gameVersion = 6162 var championsURL = "//ddragon.leagueoflegends.com/cdn/6.20.1/data/en_US/champion.json" var imageURL = "//ddragon.leagueoflegends.com/cdn/6.20.1/img/champion/" var championsDatabase = {} // Database indexed by stringed key, and {name: "Aatrox", image: "Aatrox.png"} var regionsDatabase = {}; // Array indexed by player names and their regions var playersDatabase = []; // Array full of player names, sorted. var storedVersion = localStorage["version"] var lastPlayerUpdate = localStorage["playersUpdate"] if (typeof(onDatabaseLoaded) == "undefined" || !onDatabaseLoaded) { onDatabaseLoaded = function() {} } var parseWrapper = function(content) { try { var ret = JSON.parse(content); return ret; } catch (err) { return false; } } var processDatabase = function(database) { for (key in database.data) { var champion = database.data[key] championsDatabase[champion.key] = { name: champion.name, image: champion.image.full, } } console.log("Champion database built!") localStorage["version"] = gameVersion localStorage["champions"] = JSON.stringify(championsDatabase) onDatabaseLoaded(); } var buildChampionsDatabase = function() { $.get(championsURL, null, null, "json") .done(function(data) { try { processDatabase(data) } catch (err) { console.error(err); alert("Failed to parse champions database! " + "Try refreshing the page, although you may need to report " + "this to me (1lanncontact@gmail.com or /u/1lann on reddit). " + "Error message: " + err.message) } }) .fail(function() { alert("Failed to download champions database! Try refreshing the page.") }) } var checkChampionsDatabase = function() { if (typeof(storedVersion) == "undefined") { console.log("Welcome! Building champion database..."); buildChampionsDatabase(); } else if (parseInt(storedVersion) < gameVersion) { console.log("Downloading champion database update..."); buildChampionsDatabase(); } else { var rawDatabase = localStorage["champions"]; if (typeof(rawDatabase) == "undefined") { console.log("Corrupted champion database? Rebuiliding..."); buildChampionsDatabase(); } else { var output = parseWrapper(rawDatabase) if (typeof(output) != "undefined" && output && Object.keys(output).length > 100) { console.log("Using champion database from local storage"); championsDatabase = output; onDatabaseLoaded(); } else { console.log("Tampered champion database? Rebuiliding..."); buildChampionsDatabase(); } } } } var loadPlayersDatabase = function(database) { if (typeof(database) == "undefined" || !database) { var rawDatabase = localStorage["players"]; if (typeof(rawDatabase) == "undefined") { localStorage.removeItem("players"); localStorage.removeItem("playersUpdate"); alert("Failed to load players database! [1] " + "Try refreshing the page."); return; } expandedDatabase = LZString.decompress(rawDatabase) readDatabase = parseWrapper(expandedDatabase) if (typeof(readDatabase) == "undefined" || !readDatabase) { localStorage.removeItem("players"); localStorage.removeItem("playersUpdate"); alert("Failed to parse players database! [2] " + "Try refreshing the page."); return; } if (typeof(readDatabase.players) == "undefined" || !readDatabase.players || typeof(readDatabase.regions) == "undefined" || !readDatabase.regions) { localStorage.removeItem("players"); localStorage.removeItem("playersUpdate"); alert("Failed to parse players database! [3] " + "Try refreshing the page."); return; } console.log("Loaded players database from local storage") playersDatabase = readDatabase.players; regionsDatabase = readDatabase.regions; } else { // The array is already sorted on the server. I think. playersDatabase = []; regionsDatabase = {}; var parsedDatabase = parseWrapper(database) if (typeof(parsedDatabase) == "undefined" || !parsedDatabase || typeof(parsedDatabase.Players) == "undefined" || !parsedDatabase.Players || typeof(parsedDatabase.Time) == "undefined" || !parsedDatabase.Time) { alert("Failed to parse players database! [4] " + "Try refreshing the page, although you may need to report " + "this to me (1lanncontact@gmail.com or /u/1lann on reddit). "); return; } for (var i = 0; i < parsedDatabase.Players.length; i++) { var name = parsedDatabase.Players[i].summonerName var region = parsedDatabase.Players[i].region if (name in regionsDatabase) { regionsDatabase[name].push(region) } else { regionsDatabase[name] = [region]; playersDatabase.push(name); } } var storeDatabase = { players: playersDatabase, regions: regionsDatabase } var textDatabase = JSON.stringify(storeDatabase); console.log("Stored updated players database") localStorage["playersUpdate"] = parsedDatabase.Time.toString(); localStorage["players"] = LZString.compress(textDatabase); } } var checkPlayersDatabase = function() { if (typeof(lastPlayerUpdate) == "undefined" || typeof(localStorage["players"]) == "undefined") { lastPlayerUpdate = 0; } else { // Check for legacy non-compression var compressionTest = localStorage["players"]; if (compressionTest.indexOf('{"players":') == 0) { localStorage.removeItem("players"); lastPlayerUpdate = 0; } else { // Preload the database from localStorage loadPlayersDatabase(); } } $.post("/players", {"lastupdate": lastPlayerUpdate}, null, "text") .done(function(resp){ if (resp == "error") { alert("Server error while requesting for players database!"); } else if (resp != "false") { loadPlayersDatabase(resp); } }) } checkChampionsDatabase(); checkPlayersDatabase();
JavaScript
0.000001
@@ -897,11 +897,11 @@ = 6 -162 +201 %0Avar
3f7c7299380b8aa138eaeb5d31d10636a57e37ca
Update basic.js
tests/basic.js
tests/basic.js
"use strict"; // this is a test const assert = require('chai').assert; describe("geek value equals 42", () => { let geek = 42; it("should return 42", () => { assert.equal(geek, 42) }); });
JavaScript
0.000001
@@ -179,17 +179,17 @@ l(geek, -4 +3 2)%0A %7D);
a04ca40a1073392c35ff64b2a75bc6fe19cf88fa
add createTemplateElement
src/dom.js
src/dom.js
import {_FEATURE} from './feature'; let shadowPoly = window.ShadowDOMPolyfill || null; /** * Represents the core APIs of the DOM. */ export const _DOM = { Element: Element, SVGElement: SVGElement, boundary: 'aurelia-dom-boundary', addEventListener(eventName: string, callback: Function, capture?: boolean): void { document.addEventListener(eventName, callback, capture); }, removeEventListener(eventName: string, callback: Function, capture?: boolean): void { document.removeEventListener(eventName, callback, capture); }, adoptNode(node: Node) { return document.adoptNode(node, true);//TODO: what is does the true mean? typo? }, createAttribute(name: string): Attr { return document.createAttribute(name); }, createElement(tagName: string): Element { return document.createElement(tagName); }, createTextNode(text) { return document.createTextNode(text); }, createComment(text) { return document.createComment(text); }, createDocumentFragment(): DocumentFragment { return document.createDocumentFragment(); }, createMutationObserver(callback: Function): MutationObserver { return new (window.MutationObserver || window.WebKitMutationObserver)(callback); }, createCustomEvent(eventType: string, options: Object): CustomEvent { return new window.CustomEvent(eventType, options); }, dispatchEvent(evt): void { document.dispatchEvent(evt); }, getComputedStyle(element: Element) { return window.getComputedStyle(element); }, getElementById(id: string): Element { return document.getElementById(id); }, querySelectorAll(query: string) { return document.querySelectorAll(query); }, nextElementSibling(element: Node): Element { if (element.nextElementSibling) { return element.nextElementSibling; } do { element = element.nextSibling; } while (element && element.nodeType !== 1); return element; }, createTemplateFromMarkup(markup: string): Element { let parser = document.createElement('div'); parser.innerHTML = markup; let temp = parser.firstElementChild; if (!temp || temp.nodeName !== 'TEMPLATE') { throw new Error('Template markup must be wrapped in a <template> element e.g. <template> <!-- markup here --> </template>'); } return _FEATURE.ensureHTMLTemplateElement(temp); }, appendNode(newNode: Node, parentNode?: Node): void { (parentNode || document.body).appendChild(newNode); }, replaceNode(newNode: Node, node: Node, parentNode?: Node): void { if (node.parentNode) { node.parentNode.replaceChild(newNode, node); } else if (shadowPoly !== null) { //HACK: IE template element and shadow dom polyfills not quite right... shadowPoly.unwrap(parentNode).replaceChild( shadowPoly.unwrap(newNode), shadowPoly.unwrap(node) ); } else { //HACK: same as above parentNode.replaceChild(newNode, node); } }, removeNode(node: Node, parentNode?: Node): void { if (node.parentNode) { node.parentNode.removeChild(node); } else if (parentNode) { if (shadowPoly !== null) { //HACK: IE template element and shadow dom polyfills not quite right... shadowPoly.unwrap(parentNode).removeChild(shadowPoly.unwrap(node)); } else { //HACK: same as above parentNode.removeChild(node); } } }, injectStyles(styles: string, destination?: Element, prepend?: boolean): Node { let node = document.createElement('style'); node.innerHTML = styles; node.type = 'text/css'; destination = destination || document.head; if (prepend && destination.childNodes.length > 0) { destination.insertBefore(node, destination.childNodes[0]); } else { destination.appendChild(node); } return node; } };
JavaScript
0.000001
@@ -1068,32 +1068,198 @@ ragment();%0A %7D,%0A + createTemplateElement(): HTMLTemplateElement %7B%0A let template = document.createElement('template');%0A return _FEATURE.ensureHTMLTemplateElement(template);%0A %7D,%0A createMutation
ffc727e7806f896ff445bbe31dec25549e217722
add id selector
src/dom.js
src/dom.js
import { toArray } from "./util"; export function $(selector, el = document) { return el.querySelector(selector); } export function $$(selector, el = document) { return toArray(el.querySelectorAll(selector)); } export function replace(el_old, el_new) { el_old.parentNode.replaceChild(el_new, el_old); return el_new; } export function index(el) { let idx = 0; while(el = el.previousElementSibling) idx++; return idx; } export function remove(el) { el.parentNode && el.parentNode.removeChild(el); return el; } export function addClass(el, clazz) { el.classList.add(clazz); return el; } export function toggleClass(el, clazz, force = false) { el.classList.toggle(clazz, force); return el; } export function removeClass(el, clazz) { el.classList.remove(clazz); return el; } export function getAttr(el, name, _default = undefined) { return el && el.hasAttribute(name) ? el.getAttribute(name) : _default; } export function setAttr(el, name, value, append = false) { const attrValue = append ? getAttr(el, name, "") + " " + value : value; el.setAttribute(name, attrValue); return el; } export function hasAttr(el, name) { return el && el.hasAttribute(name); } export function component(name, init, opts = {}) { function parseConfig(el) { const confMatcher = new RegExp(`data-(?:component|${name})-([^-]+)`, "i"); const defaultConf = {}; toArray(el.attributes).forEach(attr => { const match = confMatcher.exec(attr.name); if(confMatcher.test(attr.name)) { defaultConf[match[1]] = attr.value; } }); try { const conf = JSON.parse(el.getAttribute("data-component-conf")); return Object.assign(defaultConf, conf); } catch(e) { return defaultConf; } } opts = opts instanceof HTMLElement ? { root: opts } : opts; return $$(`[data-component~="${name}"]`, opts.root || document) .filter(el => !el.hasAttribute("data-component-ready")) .map((el, index) => { const def = el.getAttribute("data-component").split(" "); const conf = Object.assign({}, init.DEFAULTS || {}, opts.conf || {}, parseConfig(el)); const options = { index, conf, is_type(type) { return def.indexOf(`${name}-${type}`) !== -1; } }; const component = init(el, options); setAttr(el, "data-component-ready", name, true); return component; }); } export default { $, $$, component, replace, index, remove, addClass, toggleClass, removeClass, getAttr, setAttr, hasAttr }
JavaScript
0.000001
@@ -211,24 +211,105 @@ ector));%0A%7D%0A%0A +export function id(name, el = document) %7B%0A return el.getElementById(name);%0A%7D%0A%0A export funct @@ -2729,30 +2729,8 @@ -$, $$, component,%0A repl @@ -2747,16 +2747,42 @@ , remove +,%0A $, $$, id, component ,%0A ad
79551bea7d3c52a7ba7621ab4e1332ce8853f298
update dom
src/dom.js
src/dom.js
var _findInChildren = function ( element, elementToFind ) { for ( var i = 0; i < element.children.length; ++i ) { var childEL = element.children[i]; if ( childEL === elementToFind ) return true; if ( childEL.children.length > 0 ) if ( _findInChildren( childEL, elementToFind ) ) return true; } return false; }; // FIRE.find = function ( elements, elementToFind ) { if ( Array.isArray(elements) || elements instanceof NodeList || elements instanceof HTMLCollection ) { for ( var i = 0; i < elements.length; ++i ) { var element = elements[i]; if ( element === elementToFind ) return true; if ( _findInChildren ( element, elementToFind ) ) return true; } return false; } // if this is a single element if ( elements === elementToFind ) return true; return _findInChildren( elements, elementToFind ); }; // FIRE.getParentTabIndex = function ( element ) { var parent = element.parentElement; while ( parent ) { if ( parent.tabIndex !== null && parent.tabIndex !== undefined && parent.tabIndex !== -1 ) return parent.tabIndex; parent = parent.parentElement; } return 0; }; FIRE.getFirstFocusableChild = function ( element ) { if ( element.tabIndex !== null && element.tabIndex !== undefined && element.tabIndex !== -1 ) { return element; } for ( var i = 0; i < element.children.length; ++i ) { var el = FIRE.getFirstFocusableChild(element.children[i]); if ( el !== null ) return el; } return null; }; // FIRE.getTrimRect = function (img, trimThreshold) { var canvas, ctx; if (img instanceof Image || img instanceof HTMLImageElement) { // create temp canvas canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; ctx = canvas.getContext('2d'); ctx.drawImage( img, 0, 0, img.width, img.height ); } else { canvas = img; ctx = canvas.getContext('2d'); } var pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data; // get trim return _doGetTrimRect(pixels, img.width, img.height, trimThreshold); }; var _dragGhost = null; FIRE.addDragGhost = function ( cursor ) { // add drag-ghost if ( _dragGhost === null ) { _dragGhost = document.createElement('div'); _dragGhost.classList.add('drag-ghost'); _dragGhost.style.position = 'fixed'; _dragGhost.style.zIndex = '999'; _dragGhost.style.left = '0'; _dragGhost.style.top = '0'; _dragGhost.style.width = window.innerWidth + 'px'; _dragGhost.style.height = window.innerHeight + 'px'; _dragGhost.oncontextmenu = function() { return false; }; } _dragGhost.style.cursor = cursor; document.body.appendChild(_dragGhost); }; FIRE.removeDragGhost = function () { if ( _dragGhost !== null ) { _dragGhost.style.cursor = 'auto'; if ( _dragGhost.parentNode !== null ) { _dragGhost.parentNode.removeChild(_dragGhost); } } };
JavaScript
0.000001
@@ -1562,24 +1562,43 @@ ent;%0A %7D%0A%0A + var el = null;%0A for ( va @@ -1647,28 +1647,24 @@ ) %7B%0A -var el = FIRE.ge @@ -1757,24 +1757,174 @@ rn el;%0A %7D +%0A if ( element.shadowRoot ) %7B%0A el = FIRE.getFirstFocusableChild(element.shadowRoot);%0A if ( el !== null )%0A return el;%0A %7D %0A%0A return
55aca83478807452c7e3f8fc79830e3f1c428207
Add missing ;
tests/index.js
tests/index.js
import path from 'path'; import fs from 'fs'; import FeatherPlugin from '../'; const HELPER_DIR = path.join(__dirname, 'helpers'); class MockCompiler { constructor() { this.options = { context: HELPER_DIR }; } plugin(type, fn) { this.fn = fn; } } const compiler = new MockCompiler(); let instance; describe('plugin initialization', () => { it('throws an error if no options are passed', done => { try { new FeatherPlugin(); done('No exception was thrown'); } catch (error) { done(); } }); it('creates the instance', () => { instance = new FeatherPlugin({ template: 'template.ejs', output: 'output.ejs', line: 1, whitelist: ['home'] }); }); it('apply function works', () => { instance.apply(compiler); }); }); describe('template generation', () => { const outputPath = path.resolve(HELPER_DIR, 'output.ejs'); it('generates file', done => { compiler.fn(null, err => { if (err) { return done(err); } fs.exists(outputPath, exists => { if (exists) { done(); } else { done(new Error(`Output file ${outputPath} doesn't exist`)); } }); }); }); it('creates valid content', done => { fs.readFile(outputPath, 'utf8', (err, output) => { if (err) { return done(err); } checkOutput(output, done); }); }) }) function checkOutput(output, done) { fs.readFile(path.resolve(HELPER_DIR, 'expected.ejs'), 'utf8', (err, expected) => { if (err) { return done(err); } if (output === expected) { done(); } else { done(new Error('Contents don\'t match')); } }) }
JavaScript
0.000015
@@ -1712,14 +1712,15 @@ ;%0A %7D%0A %7D) +; %0A%7D
05802698e6ce639440111eddf8fbecf4da3f0098
Add logging/spinner around project validation
src/exp.js
src/exp.js
#!/usr/bin/env node /** * @flow */ import 'instapromise'; import _ from 'lodash-node'; import bunyan from 'bunyan'; import crayon from '@ccheever/crayon'; import glob from 'glob'; import path from 'path'; import simpleSpinner from '@exponent/simple-spinner'; import url from 'url'; import program, { Command } from 'commander'; import { Analytics, Config, Doctor, Logger, NotificationCode, ProjectUtils, } from 'xdl'; import log from './log'; import update from './update'; import urlOpts from './urlOpts'; if (process.env.NODE_ENV === 'development') { require('source-map-support').install(); } Command.prototype.urlOpts = function() { urlOpts.addOptions(this); return this; }; Command.prototype.addUrlOption = function() { urlOpts.addUrlOption(this); return this; }; Command.prototype.asyncAction = function(asyncFn) { return this.action(async (...args) => { try { await checkForUpdateAsync(); } catch (e) {} try { let options = _.last(args).parent; if (options.output === 'raw') { log.config.raw = true; process.env['PM2_SILENT'] = 'true'; } await asyncFn(...args); process.exit(0); } catch (err) { if (err._isCommandError) { log.error(err.message); } else if (err._isApiError) { log.error(crayon.red(err.message)); } else if (err.isXDLError) { log.error(err.message); } else { log.error(err.message); crayon.gray.error(err.stack); } process.exit(1); } }); }; Command.prototype.asyncActionProjectDir = function(asyncFn, skipProjectValidation) { return this.asyncAction(async (projectDir, ...args) => { if (!projectDir) { projectDir = process.cwd(); } else { projectDir = path.resolve(process.cwd(), projectDir); } // needed for validation logging to function ProjectUtils.attachLoggerStream(projectDir, { stream: { write: (chunk) => { if (chunk.level <= bunyan.INFO) { log(chunk.msg); } else if (chunk.level === bunyan.WARN) { log.warn(chunk.msg); } else { log.error(chunk.msg); } }, }, type: 'raw', }); // the existing CLI modules only pass one argument to this function, so skipProjectValidation // will be undefined in most cases. we can explicitly pass a truthy value here to avoid validation (eg for init) if (!skipProjectValidation) { // validate that this is a good projectDir before we try anything else let status = await Doctor.validateLowLatencyAsync(projectDir); if (status === Doctor.FATAL) { throw new Error(`Invalid project directory. See above logs for information.`); } } return asyncFn(projectDir, ...args); }); }; function runAsync() { try { Analytics.setSegmentNodeKey('vGu92cdmVaggGA26s3lBX6Y5fILm8SQ7'); Analytics.setVersionName(require('../package.json').version); _registerLogs(); if (process.env.SERVER_URL) { let serverUrl = process.env.SERVER_URL; if (!serverUrl.startsWith('http')) { serverUrl = `http://${serverUrl}`; } let parsedUrl = url.parse(serverUrl); Config.api.host = parsedUrl.hostname; Config.api.port = parsedUrl.port; } Config.developerTool = 'exp'; program.name = 'exp'; program .version(require('../package.json').version) .option('-o, --output [format]', 'Output format. pretty (default), raw'); glob.sync('commands/*.js', { cwd: __dirname, }).forEach(file => { const commandModule = require(`./${file}`); if (typeof commandModule === 'function') { commandModule(program); } else if (typeof commandModule.default === 'function') { commandModule.default(program); } else { log.error(`'${file}.js' is not a properly formatted command.`); } }); if (process.env.EXPONENT_DEBUG) { glob.sync('debug_commands/*.js', { cwd: __dirname, }).forEach(file => { require(`./${file}`)(program); }); } program.parse(process.argv); let subCommand = process.argv[2]; if (subCommand) { let commands = []; program.commands.forEach(command => { commands.push(command['_name']); let alias = command['_alias']; if (alias) { commands.push(alias); } }); if (!_.includes(commands, subCommand)) { console.log(`"${subCommand}" is not an exp command. See "exp --help" for the full list of commands.`); } } else { program.help(); } } catch (e) { console.error(e); throw e; } } async function checkForUpdateAsync() { let { state, current, latest } = await update.checkForExpUpdateAsync(); let message; switch (state) { case 'up-to-date': break; case 'out-of-date': message = `There is a new version of exp available (${latest}). You are currently using exp ${current} Run \`npm install -g exp\` to get the latest version`; crayon.green.error(message); break; case 'ahead-of-published': // if the user is ahead of npm, we're going to assume they know what they're doing break; default: log.error("Confused about what version of exp you have?"); } } function _registerLogs() { let stream = { stream: { write: (chunk) => { if (chunk.code) { switch (chunk.code) { case NotificationCode.START_LOADING: simpleSpinner.start(); return; case NotificationCode.STOP_LOADING: simpleSpinner.stop(); return; } } if (chunk.level === bunyan.INFO) { log(chunk.msg); } else if (chunk.level === bunyan.WARN) { log.warn(chunk.msg); } else if (chunk.level >= bunyan.ERROR) { log.error(chunk.msg); } }, }, type: 'raw', }; Logger.notifications.addStream(stream); Logger.global.addStream(stream); } // $FlowFixMe if (require.main === module) { (async function() { await runAsync(); })().catch(e => { console.error('Uncaught Error', e); process.exit(1); }); }
JavaScript
0
@@ -2472,24 +2472,109 @@ lidation) %7B%0A + log('Making sure project is setup correctly...');%0A simpleSpinner.start();%0A // val @@ -2835,24 +2835,91 @@ %60);%0A %7D%0A + simpleSpinner.stop();%0A log('Your project looks good!');%0A %7D%0A%0A r
249eb48bfbadbde7b03f9989594188d3a2f621f5
Add some things to the info panel
src/gui.js
src/gui.js
const EventEmitter = require('events'), blessed = require('blessed'), timestamp = require('./util/timestamp'); class GUI extends EventEmitter { constructor(screen) { super(); this.screen = screen; this.chatbox = blessed.box({ label: 'Retrocord Light', left: '0.5%', width: '86%', height: '96%-1', border: { type: 'line' }, style: { border: { fg: 'white' } } }); this.infobox = blessed.textbox({ label: 'Info', left: '86%', width: '14%', height: '96%-1', border: { type: "line" }, style: { border: { fg: "white" } } }); this.consolebox = blessed.log({ parent: this.chatbox, tags: true, scrollable: true, label: '', alwaysScroll: true, scrollbar: { ch: '', inverse: true, }, mouse: true }); this.inputbox = blessed.textbox({ bottom: 0, width: '100%', height: 3, inputOnFocus: true, border: { type: 'line' }, style: { border: { fg: 'grey' } } }); this.infolog = blessed.log({ parent: this.infobox, tags: true, scrollable: true, label: '', alwaysScroll: true, scrollbar: { ch: '', inverse: true, }, mouse: true }); this.awaitingResponse = false; } init() { this.inputbox.key('enter', () => { if (this.awaitingResponse) this.emit('internalInput', this.inputbox.getValue()); else this.emit('input', this.inputbox.getValue()); this.inputbox.clearValue(); this.inputbox.focus(); this.screen.render(); }); this.screen.append(this.chatbox); this.screen.append(this.inputbox); this.screen.append(this.infobox); this.screen.render(); this.inputbox.focus(); } put(text) { this.consolebox.log(text); } puti(txt) { this.infolog.log(txt); } putMessages(messages) { const me = this; messages.forEach(m => { const ts = timestamp(m.createdAt), arrow = (m.author.id == ctx.discord.user.id) ? `{green-fg}{bold}↩{/bold}{/green-fg}` : `{green-fg}{bold}↪{/bold}{/green-fg}`, txt = `${arrow} {yellow-fg}{bold}${ts}{/bold}{/yellow-fg} {white-fg}{bold}${m.author.username}{/bold}{/white-fg} ${m.content}`; me.put(txt); }); } putMessage(message, opt) { return this.putMessages([message], opt); } putTypingStart(channel, user) { this.put(`{blue-fg}{bold}↷{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {green-fg}started{/green-fg} typing.`); } putTypingStop(channel, user) { this.put(`{blue-fg}{bold}↶{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {red-fg}stopped{/red-fg} typing.`); } awaitResponse(text) { this.awaitingResponse = true; return new Promise((resolve) => { this.put(text); this.once('internalInput', (input) => { this.awaitingResponse = false; resolve(input); }); }); } } const screen = blessed.screen({ smartCSR: true, title: 'retrocord', fullUnicode: true, }); const gui = new GUI(screen); module.exports = gui;
JavaScript
0
@@ -106,16 +106,51 @@ estamp') +,%0A Discord = require('discord.js') ;%0A%0Aclass @@ -1507,16 +1507,734 @@ se;%0A %7D%0A + renderInfo() %7B%0A if (global.ctx && ctx.discord && ctx.discord.user) %7B%0A const uname = ctx.discord.user.username,%0A friendCount = ctx.discord.user.friends.array().length,%0A friends = ctx.discord.user.friends.array(),%0A isInDm = ctx.current.channel ? (ctx.current.channel instanceof Discord.DMChannel) : false;%0A let txt = %60%0A %7Byellow-fg%7D%7Bbold%7D$%7Buname%7D%7B/bold%7D%7B/yellow-fg%7D / %7Bwhite-fg%7D%7Bbold%7D$%7BfriendCount%7D%7B/bold%7D%7B/white-fg%7D%0A %60;%0A if (isInDm) %7B%0A txt += %60%5Cn%7Bcenter%7DDM: %7Bwhite-fg%7D%7Bbold%7D$%7Bctx.current.channel.recipient.username%7D%7B/white-fg%7D%7B/bold%7D%7B/center%7D%60;%0A %7D%0A this.infolog.setContent(txt);%0A %7D else %7B%0A this.infolog.setContent('Not logged in :(');%0A %7D%0A %7D %0A init( @@ -2687,16 +2687,131 @@ ocus();%0A + var me = this;%0A me.renderInfo.call(me);%0A setInterval(() =%3E %7B%0A me.renderInfo.call(me);%0A %7D, 1000);%0A %7D%0A pu
23f31e5c8f0d13984e0caa314e67fa2652ebf0d1
use global.environment
tile-server.js
tile-server.js
var Windshaft = require('windshaft'); var _ = require('underscore')._; var fs = require('fs'); var userConfig = require('./config.json'); // Configure pluggable URLs // ========================= // The config object must define grainstore config (generally just postgres connection details), redis config, // a base url and a function that adds 'dbname' and 'table' variables onto the Express.js req.params object. // In this example, the base URL is such that dbname and table will automatically be added to the req.params // object by express.js. req2params can be extended to allow full control over the specifying of dbname and table, // and also allows for the req.params object to be extended with other variables, such as: // // * sql - custom sql query to narrow results shown in map) // * geom_type - specify the geom type (point|polygon) to get more appropriate default styles // * cache_buster - forces the creation of a new render object, nullifying existing metatile caches // * interactivity - specify the column to use in the UTFGrid interactivity layer (defaults to null) // * style - specify map style in the Carto map language on a per tile basis // // the base url is also used for persisiting and retrieving map styles via: // // GET base_url + '/style' (returns a map style) // POST base_url + '/style' (allows specifying of a style in Carto markup in the 'style' form variable). // // beforeTileRender and afterTileRender could be defined if you want yo implement your own tile cache policy. See // an example below // set environment specific variables global.settings = require('config/settings'); //on startup, read the file synchronously var cartoCss = fs.readFileSync(__dirname + '/carto.css','utf-8'); var cacheFolder = __dirname + '/tile_cache/'; var config = { base_url: '/database/:dbname/table/:table', base_url_notable: '/database/:dbname', req2params: function(req, callback){ // no default interactivity. to enable specify the database column you'd like to interact with req.params.interactivity = null; // this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10 req.params = _.extend({}, req.params); _.extend(req.params, req.query); // send the finished req object on callback(null,req); }, grainstore: {datasource: {user:userConfig.database.user,password:userConfig.database.password, host: '127.0.0.1', port: 5432}, styles: {point: cartoCss}, mapnik_version:'2.1.0' }, //see grainstore npm for other options redis: {host: '127.0.0.1', port: 6379}, mapnik: { metatile: 1, bufferSize:64 }, renderCache: { ttl: 60000, // seconds } }; // Initialize tile server on port 4000 var ws = new Windshaft.Server(config); ws.listen(4000); console.log("map tiles are now being served out of: http://localhost:4000" + config.base_url + '/:z/:x/:y.*'); // Specify .png, .png8 or .grid.json tiles.
JavaScript
0.00089
@@ -1579,24 +1579,27 @@ %0Aglobal. -settings +environment = requi
384bf34fd0b42983591b6df552574f3fa5494f94
Fix code style
tinypng-cli.js
tinypng-cli.js
#!/usr/bin/env node var fs = require('fs'); var request = require('request'); var minimatch = require('minimatch'); var glob = require('glob'); var uniq = require('array-uniq'); var chalk = require('chalk'); var pretty = require('prettysize'); var argv = require('minimist')(process.argv.slice(2)); var home = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE; var version = require('./package.json').version; if (argv.v || argv.version) { console.log(version); } else if (argv.h || argv.help) { console.log( 'Usage\n' + ' tinypng <path>\n' + '\n' + 'Example\n' + ' tinypng .\n' + ' tinypng assets/img\n' + ' tinypng assets/img/test.png\n' + ' tinypng assets/img/test.jpg\n' + '\n' + 'Options\n' + ' -k, --key Provide an API key\n' + ' -rw, --width Resize an image to a specified width\n' + ' -rh, --height Resize an image to a specified height\n' + ' -r, --recursive Walk given directory recursively\n' + ' -v, --version Show installed version\n' + ' -h, --help Show help' ); } else { console.log(chalk.underline.bold('TinyPNG CLI')); console.log('v' + version + '\n'); var files = argv._.length ? argv._ : ['.']; var key = ''; var resize = {}; if (argv.k || argv.key) { key = typeof (argv.k || argv.key) === 'string' ? (argv.k || argv.key).trim() : ''; } else if (fs.existsSync(home + '/.tinypng')) { key = fs.readFileSync(home + '/.tinypng', 'utf8').trim(); } if (argv.rw || argv.width) { if(typeof (argv.rw || argv.width) === 'number') { resize.width = (argv.rw || argv.width); } else { console.log(chalk.bold.red('Invalid width specified. Please specify a numeric value only.')); } } if (argv.rh || argv.height) { if(typeof (argv.rh || argv.height) === 'number') { resize.height = (argv.rh || argv.height); } else { console.log(chalk.bold.red('Invalid height specified. Please specify a numeric value only.')); } } if (key.length === 0) { console.log(chalk.bold.red('No API key specified. You can get one at ' + chalk.underline('https://tinypng.com/developers') + '.')); } else { var images = []; files.forEach(function(file) { if (fs.existsSync(file)) { if (fs.lstatSync(file).isDirectory()) { images = images.concat(glob.sync(file + (argv.r || argv.recursive ? '/**' : '') + '/*.+(png|jpg|jpeg)')); } else if(minimatch(file, '*.+(png|jpg|jpeg)', { matchBase: true })) { images.push(file); } } }); var unique = uniq(images); if (unique.length === 0) { console.log(chalk.bold.red('\u2718 No PNG or JPEG images found.')); } else { console.log(chalk.bold.green('\u2714 Found ' + unique.length + ' image' + (unique.length === 1 ? '' : 's')) + '\n'); console.log(chalk.bold('Processing...')); unique.forEach(function(file) { fs.createReadStream(file).pipe(request.post('https://api.tinify.com/shrink', { auth: { 'user': 'api', 'pass': key } }, function (error, response, body) { try { body = JSON.parse(body); } catch(e) { console.log(chalk.red('\u2718 Not a valid JSON response for `' + file + '`')); } if(response !== undefined) { if (response.statusCode === 201) { if (body.output.size < body.input.size) { console.log(chalk.green('\u2714 Panda just saved you ' + chalk.bold(pretty(body.input.size - body.output.size) + ' (' + Math.round(100 - 100 / body.input.size * body.output.size) + '%)') + ' for `' + file + '`')); if(resize.hasOwnProperty('height') || resize.hasOwnProperty('width')) { request.get(body.output.url, { auth: {'user': 'api','pass': key}, json:{'resize':resize}}).pipe(fs.createWriteStream(file)); } else { request.get(body.output.url).pipe(fs.createWriteStream(file)); } } else { console.log(chalk.yellow('\u2718 Couldn’t compress `' + file + '` any further')); } } else { if (body.error === 'TooManyRequests') { console.log(chalk.red('\u2718 Compression failed for `' + file + '` as your monthly limit has been exceeded')); } else if (body.error === 'Unauthorized') { console.log(chalk.red('\u2718 Compression failed for `' + file + '` as your credentials are invalid')); } else { console.log(chalk.red('\u2718 Compression failed for `' + file + '`')); } } } else { console.log(chalk.red('\u2718 Got no response for `' + file + '`')); } })); }); } } }
JavaScript
0.000169
@@ -1646,34 +1646,37 @@ .width) %7B%0A + if + (typeof (argv.rw @@ -1711,24 +1711,28 @@ ) %7B%0A + resize.width @@ -1757,32 +1757,34 @@ v.width);%0A + + %7D else %7B%0A @@ -1768,32 +1768,36 @@ %7D else %7B%0A + console. @@ -1874,32 +1874,34 @@ value only.'));%0A + %7D%0A %7D%0A%0A @@ -1939,18 +1939,21 @@ %7B%0A + if + (typeof @@ -1997,24 +1997,28 @@ ) %7B%0A + resize.heigh @@ -2049,24 +2049,26 @@ ght);%0A + + %7D else %7B%0A @@ -2056,32 +2056,36 @@ %7D else %7B%0A + console. @@ -2167,24 +2167,26 @@ e only.'));%0A + %7D%0A @@ -2683,16 +2683,17 @@ else if + (minimat @@ -3793,24 +3793,25 @@ if + (response != @@ -4238,16 +4238,17 @@ if + (resize.
c3afc8f7661e8edec9a64f87425b61307c2fcec3
Implement checkKey() function
storage.js
storage.js
(function(){ 'use strict'; function Storage(storageAreaName) { var _storageArea = (storageAreaName === 'session') ? window.sessionStorage : window.localStorage; this.isSupported = function() { return typeof _storageArea !== 'undefined'; }; this.set = function(key, val) { if(val === undefined) return; if(typeof val === 'function') return; else if(typeof val === 'object') _storageArea[key] = JSON.stringify(val); else _storageArea[key] = val; }; this.get = function(key) { if(_storageArea[key] === undefined) return null; try { return JSON.parse(_storageArea[key]); } catch(ex) { return _storageArea[key]; } return _storageArea[key]; }; this.exists = function(key) { return _storageArea[key] !== undefined; }; this.clear = function() { if(arguments.length === 0) _storageArea.clear(); else { for(var i=0; i<arguments.length; i++) _storageArea.removeItem(arguments[i]); } }; this.getKeys = function() { var list = []; for(var i in _storageArea) { if(_storageArea.hasOwnProperty(i)) list.push(i); } return list; }; }; window.storage = new Storage(); window.storage.local = new Storage(); window.storage.session = new Storage('session'); return; })();
JavaScript
0.000018
@@ -319,24 +319,52 @@ key, val) %7B%0A + checkKey(key);%0A%0A @@ -377,32 +377,32 @@ === undefined)%0A - @@ -674,32 +674,60 @@ function(key) %7B%0A + checkKey(key);%0A%0A if(_ @@ -1033,32 +1033,60 @@ function(key) %7B%0A + checkKey(key);%0A%0A retu @@ -1652,16 +1652,16 @@ n list;%0A - @@ -1658,24 +1658,239 @@ ;%0A %7D; +%0A%0A function checkKey(key)%0A %7B%0A if(typeof key !== 'string' && typeof key !== 'number')%0A throw new TypeError('Key must be string or numeric');%0A%0A return true;%0A %7D %0A %7D;%0A%0A
94552283b415871c60d491a4c7127749f080cc13
fix duplicated home route
01-Embedded-Login/src/routes.js
01-Embedded-Login/src/routes.js
import React from 'react'; import { Route, BrowserRouter } from 'react-router-dom'; import App from './App'; import Home from './Home/Home'; import Callback from './Callback/Callback'; import Auth from './Auth/Auth'; import history from './history'; const auth = new Auth(); export const makeMainRoutes = () => { return ( <BrowserRouter history={history} component={App}> <div> <Route path="/" render={(props) => <Home auth={auth} {...props} />} /> <Route path="/home" render={(props) => <Home auth={auth} {...props} />} /> <Route path="/callback" render={(props) => <Callback {...props} />} /> </div> </BrowserRouter> ); }
JavaScript
0.000003
@@ -421,36 +421,35 @@ er=%7B(props) =%3E %3C -Home +App auth=%7Bauth%7D %7B..
4bef6ec5940ca5bcc84b16f4015a68dc7821035a
move toJSON at the end [ci skip]
src/pca.js
src/pca.js
'use strict'; const Matrix = require('ml-matrix'); const EVD = Matrix.DC.EVD; const SVD = Matrix.DC.SVD; const Stat = require('ml-stat').matrix; const mean = Stat.mean; const stdev = Stat.standardDeviation; const defaultOptions = { isCovarianceMatrix: false, center: true, scale: false }; class PCA { /** * Creates new PCA (Principal Component Analysis) from the dataset * @param {Matrix} dataset - dataset or covariance matrix * @param {Object} options * @param {boolean} [options.isCovarianceMatrix=false] * @param {boolean} [options.center=true] - should the data be centered (subtract the mean) * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation) * @constructor * */ constructor(dataset, options) { if (dataset === true) { const model = options; this.center = model.center; this.scale = model.scale; this.means = model.means; this.stdevs = model.stdevs; this.U = Matrix.checkMatrix(model.U); this.S = model.S; return; } options = Object.assign({}, defaultOptions, options); this.center = false; this.scale = false; this.means = null; this.stdevs = null; if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset this._computeFromCovarianceMatrix(dataset); return; } var useCovarianceMatrix; if (typeof options.useCovarianceMatrix === 'boolean') { useCovarianceMatrix = options.useCovarianceMatrix; } else { useCovarianceMatrix = dataset.length > dataset[0].length; } if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix dataset = this._adjust(dataset, options); const covarianceMatrix = dataset.transpose().mmul(dataset).div(dataset.rows - 1); this._computeFromCovarianceMatrix(covarianceMatrix); } else { dataset = this._adjust(dataset, options); var svd = new SVD(dataset, { computeLeftSingularVectors: false, computeRightSingularVectors: true, autoTranspose: true }); this.U = svd.rightSingularVectors; const singularValues = svd.diagonal; const eigenvalues = new Array(singularValues.length); for (var i = 0; i < singularValues.length; i++) { eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1); } this.S = eigenvalues; } } /** * Load a PCA model from JSON * @oaram {Object} model * @return {PCA} */ static load(model) { if (model.name !== 'PCA') throw new RangeError('Invalid model: ' + model.name); return new PCA(true, model); } /** * Export the current model to a JSON object * @return {Object} model */ toJSON() { return { name: 'PCA', center: this.center, scale: this.scale, means: this.means, stdevs: this.stdevs, U: this.U, S: this.S, }; } /** * Project the dataset into the PCA space * @param {Matrix} dataset * @return {Matrix} dataset projected in the PCA space */ predict(dataset) { dataset = new Matrix(dataset); if (this.center) { dataset.subRowVector(this.means); if (this.scale) { dataset.divRowVector(this.stdevs); } } return dataset.mmul(this.U); } /** * Returns the proportion of variance for each component * @return {[number]} */ getExplainedVariance() { var sum = 0; for (var i = 0; i < this.S.length; i++) { sum += this.S[i]; } return this.S.map(value => value / sum); } /** * Returns the cumulative proportion of variance * @return {[number]} */ getCumulativeVariance() { var explained = this.getExplainedVariance(); for (var i = 1; i < explained.length; i++) { explained[i] += explained[i - 1]; } return explained; } /** * Returns the Eigenvectors of the covariance matrix * @returns {Matrix} */ getEigenvectors() { return this.U; } /** * Returns the Eigenvalues (on the diagonal) * @returns {[number]} */ getEigenvalues() { return this.S; } /** * Returns the standard deviations of the principal components * @returns {[number]} */ getStandardDeviations() { return this.S.map(x => Math.sqrt(x)); } /** * Returns the loadings matrix * @return {Matrix} */ getLoadings() { return this.U.transpose(); } _adjust(dataset, options) { this.center = !!options.center; this.scale = !!options.scale; dataset = new Matrix(dataset); if (this.center) { const means = mean(dataset); const stdevs = this.scale ? stdev(dataset, means, true) : null; this.means = means; dataset.subRowVector(means); if (this.scale) { for (var i = 0; i < stdevs.length; i++) { if (stdevs[i] === 0) { throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i); } } this.stdevs = stdevs; dataset.divRowVector(stdevs); } } return dataset; } _computeFromCovarianceMatrix(dataset) { const evd = new EVD(dataset, {assumeSymmetric: true}); this.U = evd.eigenvectorMatrix; for (var i = 0; i < this.U.length; i++) { this.U[i].reverse(); } this.S = evd.realEigenvalues.reverse(); } } module.exports = PCA;
JavaScript
0
@@ -3026,352 +3026,8 @@ %7D%0A%0A - /**%0A * Export the current model to a JSON object%0A * @return %7BObject%7D model%0A */%0A toJSON() %7B%0A return %7B%0A name: 'PCA',%0A center: this.center,%0A scale: this.scale,%0A means: this.means,%0A stdevs: this.stdevs,%0A U: this.U,%0A S: this.S,%0A %7D;%0A %7D%0A%0A @@ -4710,24 +4710,368 @@ e();%0A %7D%0A%0A + /**%0A * Export the current model to a JSON object%0A * @return %7BObject%7D model%0A */%0A toJSON() %7B%0A return %7B%0A name: 'PCA',%0A center: this.center,%0A scale: this.scale,%0A means: this.means,%0A stdevs: this.stdevs,%0A U: this.U,%0A S: this.S,%0A %7D;%0A %7D%0A%0A _adjust(
1b6ad0ab5b95bd89d3d55ef1d5d346b9e722ef39
Update index.js
projects/acc/js/index.js
projects/acc/js/index.js
if ('Accelerometer' in window && 'Gyroscope' in window) { //document.getElementById('moApi').innerHTML = 'Generic Sensor API'; let accelerometer = new Accelerometer(); accelerometer.addEventListener('reading', e => MaccelerationHandler(accelerometer, 'moAccel')); accelerometer.start(); let accelerometerWithGravity = new Accelerometer({includeGravity: true}); accelerometerWithGravity.addEventListener('reading', e => MaccelerationHandler(accelerometerWithGravity, 'moAccelGrav')); accelerometerWithGravity.start(); let gyroscope = new Gyroscope(); gyroscope.addEventListener('reading', e => rotationHandler({ alpha: gyroscope.x, beta: gyroscope.y, gamma: gyroscope.z })); gyroscope.start(); intervalHandler('Not available in Generic Sensor API'); } else if ('DeviceMotionEvent' in window) { //document.getElementById('alert').style.display = 'none'; //document.getElementById('moApi').innerHTML = 'Device Motion API'; window.addEventListener('devicemotion', function (eventData) { accelerationHandler(eventData.acceleration, 'moAccel'); MaccelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav'); rotationHandler(eventData.rotationRate); intervalHandler(eventData.interval); }, false); } else { //document.getElementById('alert').style.display = 'none'; //document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available'; } function accelerationHandler(acceleration, targetId) { var info, xyz = "[X, Y, Z]"; info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3)); info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3)); info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3)); //document.getElementById(targetId).innerHTML = info; } function MaccelerationHandler(acceleration, targetId) { var info, xyz = "[X, Y, Z]"; var zz = (acceleration.z && acceleration.z.toFixed(3)); if (zz>10) { x = 1; var timer = setInterval(function change() { if (x === 1) { color = "#ffffff"; x = 2; } else { color = "#000000"; x = 1; } document.body.style.background = color; }, 50); setTimeout(function() { clearInterval(timer); }, 1000); } } function rotationHandler(rotation) { var info, xyz = "[X, Y, Z]"; //info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3)); //info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3)); //info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3)); var xx = (rotation.alpha && rotation.alpha.toFixed(3)); var yy = (rotation.beta && rotation.beta.toFixed(3)); var zz = (rotation.gamma && rotation.gamma.toFixed(3)); var mean = (((xx)^2) + ((yy)^2) + ((zz)^2))*(1/2); //document.getElementById("mean").innerHTML = mean; //document.getElementById("moRotation").innerHTML = info; } function intervalHandler(interval) { //document.getElementById("moInterval").innerHTML = interval; } if (location.href.indexOf('debug') !== -1) { //document.getElementById('alert').style.display = 'none'; }
JavaScript
0.000002
@@ -2283,21 +2283,23 @@ round = -color +#000000 ;%0A
934ed114536c66b7f855f03454664a5e92c363f1
Optimise report link popup code
app/assets/javascripts/instructional_materials.js
app/assets/javascripts/instructional_materials.js
function showInstructionalMaterial(oMaterialTab){ setTableHeaders(1); var oSelectedTab = $$('.selected_tab')[0]; if(oSelectedTab){ oSelectedTab.removeClassName('selected_tab'); oSelectedTab.addClassName('tab'); $(oSelectedTab.id + "_data").hide(); } oMaterialTab.removeClassName('tab'); oMaterialTab.addClassName('selected_tab'); $(oMaterialTab.id + "_data").show(); setTableHeaders(); } function startScroll(direction,size){ oTimer = setInterval(function(){ var scroller = document.getElementById('oTabcontainer'); if (direction == 'l') { scroller.scrollLeft -= size; } else if (direction == 'r') { scroller.scrollLeft += size; } },20); } function stopScroll(){ clearTimeout(oTimer); } function showHideActivityButtons(investigation_id, oLink){ var bVisible = false; $$('.activitybuttoncontainer_'+investigation_id).each(function(oButtonContainer){ oButtonContainer.toggle(); bVisible = bVisible || oButtonContainer.getStyle('display')=='none'; }); var strLinkText = ""; var strExpandCollapseText = ""; if(bVisible){ strLinkText = "Show Activities"; strExpandCollapseText = "+"; } else{ strLinkText = "Hide Activities"; strExpandCollapseText = "-"; } $('oExpandCollapseText_'+investigation_id).update(strExpandCollapseText); oLink.update(strLinkText); } function showHideActivityDetails(investigation_id, oLink, strURL){ setRecentActivityTableHeaders(1,investigation_id); var bVisible = false; $$('.DivHideShowDetail'+investigation_id).each(function(oButtonContainer){ oButtonContainer.toggle(); bVisible = bVisible || oButtonContainer.getStyle('display')=='none'; }); var strLinkText = ""; var strExpandCollapseText = ""; if(bVisible){ strLinkText = "Show detail"; strExpandCollapseText = "+"; } else{ strLinkText = "Hide detail"; strExpandCollapseText = "-"; } $('oExpandCollapseText_'+investigation_id).update(strExpandCollapseText); oLink.update(strLinkText); if($('DivHideShowDetail'+investigation_id).children.length === 0) new Ajax.Request(strURL, {asynchronous:true, evalScripts:true, method:'post'}); setRecentActivityTableHeaders(null,investigation_id); } function setSelectedTab(strTabID){ $(strTabID).simulate('click'); $$('.scrollertab').each(function(oTab){ var strDirection = oTab.hasClassName('tableft')? "l" : "r"; oTab.observe('mouseover',function(){ startScroll(strDirection,5); }); oTab.observe('mouseout',stopScroll); }); } document.observe("dom:loaded", function() { var arrTabs = $$('#oTabcontainer .tab'); arrTabs.each(function(oTab){ oTab.observe('click',function(){ showInstructionalMaterial(oTab); }); }); setTableHeaders(1); if (arrTabs.length > 0) { var strTabID = arrTabs[0].id; setSelectedTab(strTabID); } }); function setTableHeaders(iDefaultWidth) { var iWidth; var iContainerWidth; $$("th.expand_collapse_text").each(function(oTitle){ var oChild = oTitle.childElements()[0]; if(oChild) { iContainerWidth = (oTitle.offsetWidth > 10)? oTitle.offsetWidth-10 : 1; if(iDefaultWidth) iWidth = iDefaultWidth; else iWidth = (oTitle.getStyle('display') == "none")? 1 : iContainerWidth; oChild.setStyle({'display':'none'}); oChild.setStyle({'width':iWidth+'px'}); } }); $$("th.expand_collapse_text > div.progressbar_container").each(function(oTitle){ oTitle.setStyle({'display':''}); }); } function setRecentActivityTableHeaders(iDefaultWidth,offering_id) { var iWidth; var iContainerWidth; $$(".DivHideShowDetail"+ offering_id + " th.expand_collapse_text").each(function(oTitle){ var oChild = oTitle.childElements()[0]; if(oChild) { iContainerWidth = (oTitle.offsetWidth > 0)? oTitle.offsetWidth-10 : 1; if(iDefaultWidth) iWidth = iDefaultWidth; else iWidth = (oTitle.getStyle('display') == "none")? 1 : iContainerWidth; oChild.setStyle({'display':'none'}); oChild.setStyle({'width':iWidth+'px'}); } }); $$("th.expand_collapse_text > div.progressbar_container").each(function(oTitle){ oTitle.setStyle({'display':''}); }); } function openReportLinkPopup(descriptionText) { var oPopUpWindow = new UI.Window({ theme: "lightbox", shadow: true, width: 410, height: 125}); var popupHtml = "<div id='windowcontent' style='padding:10px;padding-left:15px'>" + descriptionText + "</div>" + "<div class='msg_popup_ok_button'>" + "<a href=\"javascript:void(0)\" class=\"button\" onclick=\"oPopUpWindow.destroy();\">Ok</a>" + "</div>"; oPopUpWindow.setContent(popupHtml).show(true).center(); oPopUpWindow.setHeader("Message"); oPopUpWindow.activate(); }
JavaScript
0
@@ -4678,24 +4678,54 @@ %0A %7D);%0A%7D%0A%0A +var g_reportLinkPopup = null;%0A %0Afunction op @@ -4769,24 +4769,25 @@ -var oPopUpWindow +g_reportLinkPopup = n @@ -5180,28 +5180,33 @@ click=%5C%22 -oPopUpWindow +g_reportLinkPopup .destroy @@ -5251,36 +5251,41 @@ /div%3E%22;%0A -oPopUpWindow +g_reportLinkPopup .setContent( @@ -5320,28 +5320,33 @@ ();%0A -oPopUpWindow +g_reportLinkPopup .setHead @@ -5368,31 +5368,48 @@ -oPopUpWindow.activate() +g_reportLinkPopup.activate();%0A return ;%0A%7D%0A
043738313222433026f6e9449c3c003e514d954a
Add timeout to scroll efect
app/assets/javascripts/repositories/row_editor.js
app/assets/javascripts/repositories/row_editor.js
/* globals HelperModule animateSpinner SmartAnnotation Asset */ /* eslint-disable no-unused-vars */ var RepositoryDatatableRowEditor = (function() { const NAME_COLUMN_ID = 'row-name'; const TABLE_ROW = '<tr></tr>'; const TABLE_CELL = '<td></td>'; var TABLE; // Initialize SmartAnnotation function initSmartAnnotation($row) { $row.find('[data-object="repository_cell"]').each(function(el) { if (el.data('atwho')) { SmartAnnotation.init(el); } }); } function validateAndSubmit($table) { let $form = $table.find('.repository-row-edit-form'); let $row = $form.closest('tr'); let valid = true; let directUrl = $table.data('direct-upload-url'); let $files = $row.find('input[type=file]'); $row.find('.has-error').removeClass('has-error').find('span').remove(); // Validations here $row.find('input').each(function() { let dataType = $(this).data('type'); if (!dataType) return; valid = $.fn.dataTable.render[dataType + 'Validator']($(this)); if (!valid) return false; }); if (!valid) return false; // DirectUpload here let uploadPromise = Asset.uploadFiles($files, directUrl); // Submission here uploadPromise .then(function() { animateSpinner(null, true); $form.submit(); return false; }).catch((reason) => { alert(reason); return false; }); return null; } function initAssetCellActions($row) { let fileInputs = $row.find('input[type=file]'); let deleteButtons = $row.find('.file-upload-button>span.delete-action'); fileInputs.on('change', function() { let $input = $(this); let $fileBtn = $input.next('.file-upload-button'); let $label = $fileBtn.find('.label-asset'); $label.text($input[0].files[0].name); $fileBtn.removeClass('new-file'); $fileBtn.removeClass('error'); }); deleteButtons.on('click', function() { let $fileBtn = $(this).parent(); let $input = $fileBtn.prev('input[type=file]'); let $label = $fileBtn.find('.label-asset'); $fileBtn.addClass('new-file'); $label.text(''); $input.val(''); $fileBtn.removeClass('error'); if (!$input.data('is-empty')) { // set hidden field for deletion only if original value has been set on rendering $input .prev('.file-hidden-field-container') .html(`<input type="hidden" form="${$input.attr('form')}" name="repository_cells[${$input.data('col-id')}]" value=""/>`); } }); } function initFormSubmitAction(table) { TABLE = table; let $table = $(TABLE.table().node()); $table.on('ajax:success', '.repository-row-edit-form', function(ev, data) { TABLE.ajax.reload(() => { animateSpinner(null, false); HelperModule.flashAlertMsg(data.flash, 'success'); window.scrollTo({ left: 0, behavior: 'smooth' }); }); }); $table.on('ajax:error', '.repository-row-edit-form', function(ev, data) { animateSpinner(null, false); HelperModule.flashAlertMsg(data.responseJSON.flash, 'danger'); }); } function addNewRow(table) { TABLE = table; let $row = $(TABLE_ROW); const formId = 'repositoryNewRowForm'; let actionUrl = $(TABLE.table().node()).data('createRecord'); let rowForm = $(` <td> <form id="${formId}" class="repository-row-edit-form" action="${actionUrl}" method="post" data-remote="true"> </form> </td> `); // First two columns are always present and visible $row.append(rowForm); $row.append($(TABLE_CELL)); $(TABLE.table().node()).find('tbody').prepend($row); table.columns().every(function() { let column = this; let $header = $(column.header()); if (column.index() < 2) return; if (!column.visible()) return; let columnId = $header.attr('id'); let $cell = $(TABLE_CELL).appendTo($row); if (columnId === NAME_COLUMN_ID) { $.fn.dataTable.render.newRowName(formId, $cell); } else { let dataType = $header.data('type'); if (dataType) { $.fn.dataTable.render['new' + dataType](formId, columnId, $cell, $header); } } }); initSmartAnnotation($row); initAssetCellActions($row); TABLE.columns.adjust(); } function switchRowToEditMode(row) { let $row = $(row.node()); let itemId = row.id(); let formId = `repositoryRowForm${itemId}`; let requestUrl = $(TABLE.table().node()).data('current-uri'); let rowForm = $(` <form id="${formId}" class="repository-row-edit-form" action="${row.data().recordUpdateUrl}" method="patch" data-remote="true" data-row-id="${itemId}"> <input name="id" type="hidden" value="${itemId}" /> <input name="request_url" type="hidden" value="${requestUrl}" /> </form> `); $row.find('td').first().append(rowForm); TABLE.cells(row.index(), row.columns().eq(0)).every(function() { let $header = $(TABLE.columns(this.index().column).header()); let columnId = $header.attr('id'); let dataType = $header.data('type'); let cell = this; if (!cell.column(cell.index().column).visible()) return true; // return if cell is not visible if (columnId === NAME_COLUMN_ID) { $.fn.dataTable.render.editRowName(formId, cell); } else if (dataType) { $.fn.dataTable.render['edit' + dataType](formId, columnId, cell, $header); } return true; }); initSmartAnnotation($row); initAssetCellActions($row); TABLE.columns.adjust(); } return Object.freeze({ initFormSubmitAction: initFormSubmitAction, validateAndSubmit: validateAndSubmit, switchRowToEditMode: switchRowToEditMode, addNewRow: addNewRow }); }());
JavaScript
0.000001
@@ -2937,24 +2937,54 @@ 'success');%0A +%0A setTimeout(() =%3E %7B%0A wind @@ -3007,16 +3007,18 @@ + left: 0, @@ -3018,16 +3018,18 @@ eft: 0,%0A + @@ -3053,25 +3053,44 @@ th'%0A -%7D + %7D);%0A %7D, 400 );%0A %7D);
98bd54ef5aff77d901ef5e2c118ae4027403b14c
fix sessions relationship in seq block model.
app/models/curriculum-inventory-sequence-block.js
app/models/curriculum-inventory-sequence-block.js
import Ember from 'ember'; import DS from 'ember-data'; const { computed } = Ember; const { alias, equal } = computed; export default DS.Model.extend({ title: DS.attr('string'), description: DS.attr('string'), required: DS.attr('number'), childSequenceOrder: DS.attr('number'), orderInSequence: DS.attr('number'), minimum: DS.attr('number'), maximum: DS.attr('number'), track: DS.attr('boolean'), startDate: DS.attr('date'), endDate: DS.attr('date'), duration: DS.attr('number'), academicLevel: DS.belongsTo('curriculum-inventory-academic-level', {async: true}), parent: DS.belongsTo('curriculum-inventory-sequence-block', {async: true, inverse: 'children'}), children: DS.hasMany('curriculum-inventory-sequence-block', {async: true, inverse: 'parent'}), report: DS.belongsTo('curriculum-inventory-report', {async: true}), sessions: DS.hasMany('curriculum-inventory-sequence-block-session', {async: true}), course: DS.belongsTo('course', {async: true}), isFinalized: alias('report.isFinalized'), isRequired: equal('required', 1), isOptional: equal('required', 2), isRequiredInTrack: equal('required', 3), isOrdered: equal('childSequenceOrder', 1), isUnordered: equal('childSequenceOrder', 2), isParallel: equal('childSequenceOrder', 3), allParents: computed('parent', 'parent.allParents.[]', function(){ return new Promise(resolve => { this.get('parent').then(parent => { let parents = []; if(!parent){ resolve(parents); } else { parents.pushObject(parent); parent.get('allParents').then(allParents => { parents.pushObjects(allParents); resolve(parents); }); } }); }); }), });
JavaScript
0
@@ -877,44 +877,8 @@ ny(' -curriculum-inventory-sequence-block- sess
c70d485afe776fd08fbb4a34157baa480cd9b528
Update common.js
userapp/common.js
userapp/common.js
// Init UserApp with your App Id // https://help.userapp.io/customer/portal/articles/1322336-how-do-i-find-my-app-id- UserApp.initialize({ appId: "YOUR-USERAPP-APP-ID" });
JavaScript
0.000001
@@ -144,27 +144,21 @@ d: %22 -YOUR-USERAPP-APP-ID +57b349611262d %22 %7D)
9b9d4d7c0fd1aa6d934e718dbd9d9570fc9a4ab1
reset XP if it isn't safe int
commands/server_management/giveXP.js
commands/server_management/giveXP.js
/** * @file giveXP command * @author Sankarsan Kampa (a.k.a k3rn31p4nic) * @license GPL-3.0 */ exports.exec = async (Bastion, message, args) => { if (!args.id || !args.points) { return Bastion.emit('commandUsage', message, this.help); } if (message.mentions.users.size) { args.id = message.mentions.users.first().id; } let guildMemberModel = await Bastion.database.models.guildMember.findOne({ attributes: [ 'experiencePoints' ], where: { userID: args.id, guildID: message.guild.id } }); if (!guildMemberModel) { return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'profileNotCreated', `<@${args.id}>`), message.channel); } args.points = `${parseInt(guildMemberModel.dataValues.experiencePoints) + parseInt(args.points)}`; await Bastion.database.models.guildMember.update({ experiencePoints: args.points }, { where: { userID: args.id, guildID: message.guild.id }, fields: [ 'experiencePoints' ] }); await message.channel.send({ embed: { color: Bastion.colors.GREEN, description: `<@${args.id}> has been awarded with **${args.points}** experience points.` } }).catch(e => { Bastion.log.error(e); }); }; exports.config = { aliases: [], enabled: true, guildOwnerOnly: true, argsDefinitions: [ { name: 'id', type: String, defaultOption: true }, { name: 'points', alias: 'n', type: String } ] }; exports.help = { name: 'giveXP', description: 'Give the specified amount of experience points to the specified user and increase their level.', botPermission: '', userTextPermission: '', userVoicePermission: '', usage: 'giveXP <@USER_MENTION | USER_ID> <-n POINTS>', example: [ 'giveXP @user#0001 -n 100', 'giveXP 242621467230268813 -n 150' ] };
JavaScript
0.000002
@@ -801,16 +801,77 @@ ints)%7D%60; +%0A if (!Number.isSafeInteger(args.points)) args.points = '0'; %0A%0A awai
e14bb365dc5346e4680f102aabf5732a3305f345
Add Mat2d
js/AM.Math.js
js/AM.Math.js
AM.Math = AM.Math || {}; AM.Math.ToDeg = function (rad) { return rad * (180 / Math.PI); }; AM.Math.ToRad = function (deg) { return deg * (Math.PI / 180); }; AM.Math.Vec2d = function (x, y) { this.x = x; this.y = y; }; AM.Math.Vec2d.prototype = { x: 0, y: 0, subtract: function (otherVec) { return new AM.Math.Vec2d(this.x - otherVec.x, this.y - otherVec.y); }, add: function (otherVec) { return new AM.Math.Vec2d(this.x + otherVec.x, this.y + otherVec.y); }, scale: function (num) { return new AM.Math.Vec2d(this.x * num, this.y * num); }, dot: function Vec2d$dot(otherVec) { return this.x * otherVec.x + this.y * otherVec.y; }, magnitude: function Vec2d$magnitude() { return Math.sqrt(this.dot(this)); }, norm: function Vec2d$norm() { var mag = this.magnitude(); return new AM.Math.Vec2d(this.x / mag, this.y / mag); }, angle: function Vec2d$angle(other) { var dot = this.dot(other) var angle = Math.acos(dot); if (angle > Math.PI) { angle = Math.PI * 2 - angle; } return angle; }, rotate: function Vec2d$rotate(rads) { var cos = Math.cos(rads); var sin = Math.sin(rads); var x = this.x * cos - this.y * sin; var y = this.x * sin + this.y * cos; return new AM.Math.Vec2d(x, y); }, cross: function (otherVec) { return this.x * otherVec.y - this.y * otherVec.x; } }; AM.Math.Line = function (pointA, pointB) { this.N = pointB.subtract(pointA).norm(); this.A = pointA; }; AM.Math.Line.prototype = { N: null, A: null, vector2LineFromPoint: function (p) { var p2A = this.A.subtract(p); var compA = p2A.dot(this.N); var proj = this.N.scale(compA); return p2A.subtract(proj); } };
JavaScript
0.000006
@@ -1874,16 +1874,682 @@ (proj);%0A %7D%0A%7D; +%0A%0AAM.Math.Mat2d = function(e00, e01, e10, e11)%7B%0A%09%0A%09this.mat = %5B%5Be00,e01%5D,%0A%09 %5Be10,e11%5D%5D;%0A%7D;%0A%0AAM.Math.Mat2d.prototype = %7B%0A%09mat:%5B%5B0,0%5D,%5B0,0%5D%5D,%0A%09%0A%09mult: function(m)%7B%0A%09%09var e00 = this.mat%5B0%5D%5B0%5D*m.mat%5B0%5D%5B0%5D + this.mat%5B0%5D%5B1%5D*m.mat%5B1%5D%5B0%5D;%0A%09%09var e01 = this.mat%5B0%5D%5B0%5D*m.mat%5B0%5D%5B1%5D + this.mat%5B0%5D%5B1%5D*m.mat%5B1%5D%5B1%5D;%0A%09%09var e10 = this.mat%5B1%5D%5B0%5D*m.mat%5B0%5D%5B0%5D + this.mat%5B1%5D%5B1%5D*m.mat%5B1%5D%5B0%5D;%0A%09%09var e11 = this.mat%5B1%5D%5B0%5D*m.mat%5B0%5D%5B1%5D + this.mat%5B1%5D%5B1%5D*m.mat%5B1%5D%5B1%5D;%0A%09%09%0A%09%09return new AM.Math.Mat2d(e00, e01, e10, e11);%0A%09%7D,%0A%09multVec: function(v)%7B%0A%09%09var x = this.mat%5B0%5D%5B0%5D*v.x + this.mat%5B0%5D%5B1%5D*v.y;%0A%09%09var y = this.mat%5B1%5D%5B0%5D*v.x + this.mat%5B1%5D%5B1%5D*v.y;%0A%09%09return new AM.Math.Vec2d(x,y);%0A%09%7D%0A%7D
cab3287e086fd630a0cad28454ed7da16b3f3b59
Allow beforeFn to override indexFile.
js/server/modules/org/arangodb/foxx/swagger.js
js/server/modules/org/arangodb/foxx/swagger.js
/*global ArangoServerState */ 'use strict'; //////////////////////////////////////////////////////////////////////////////// /// @brief Foxx Swagger integration /// /// @file /// /// DISCLAIMER /// /// Copyright 2015 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Alan Plum /// @author Copyright 2015, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// var _ = require('underscore'); var fs = require('fs'); var resultNotFound = require('org/arangodb/actions').resultNotFound; var FoxxManager = require('org/arangodb/foxx/manager'); var jsonSchemaPrimitives = [ 'array', 'boolean', 'integer', 'number', 'null', 'object', 'string' ]; function createSwaggerRouteHandler(appPath, opts) { if (!opts) { opts = {}; } if (typeof opts === 'function') { opts = {before: opts}; } return function (req, res) { var result; if (typeof opts.before === 'function') { result = opts.before.apply(this, arguments); if (result === false) { return; } } var pathInfo = req.suffix.join('/'); if (!pathInfo) { var params = Object.keys(req.parameters || {}).reduce(function (part, name) { return part + encodeURIComponent(name) + '=' + encodeURIComponent(req.parameters[name]) + '&'; }, '?'); params = params.slice(0, params.length - 1); res.status(302); res.set('location', req.absoluteUrl(appPath + req.path(null, 'index.html') + params)); return; } if (pathInfo === 'swagger.json') { res.json(swaggerJson(req, (result && result.appPath) || opts.appPath || appPath)); return; } var path = fs.safeJoin(ArangoServerState.javaScriptPath(), 'server/assets/swagger', pathInfo); if (!fs.exists(path)) { resultNotFound(req, res, 404, "unknown path '" + req.url + "'"); return; } res.sendFile(path); }; } function swaggerJson(req, appPath) { var foxx = FoxxManager.routes(appPath); var app = foxx.appContext.app; var swagger = parseRoutes(appPath, foxx.routes, foxx.models); return { swagger: '2.0', info: { description: app._manifest.description, version: app._manifest.version, title: app._manifest.name, license: app._manifest.license && {name: app._manifest.license} }, basePath: '/_db/' + encodeURIComponent(req.database) + app._mount, schemes: [req.protocol], paths: swagger.paths, // securityDefinitions: {}, definitions: swagger.definitions }; } function fixSchema(model) { if (!model) { return undefined; } if (!model.type) { model.type = 'object'; } if (model.type === 'object') { _.each(model.properties, function (prop, key) { model.properties[key] = fixSchema(prop); }); } else if (model.type === 'array') { if (!model.items) { model.items = { anyOf: _.map(jsonSchemaPrimitives, function (type) { return {type: type}; }) }; } } return model; } function swaggerifyPath(path) { return path.replace(/(?::)([^\/]*)/g, '{$1}'); } function parseRoutes(tag, routes, models) { var paths = {}; var definitions = {}; _.each(routes, function (route) { var path = swaggerifyPath(route.url.match); _.each(route.url.methods, function (method) { if (!paths[path]) { paths[path] = {}; } paths[path][method] = { tags: [tag], summary: route.docs.summary, description: route.docs.notes, operationId: route.docs.nickname, responses: { default: { description: 'undocumented body', schema: {properties: {}, type: 'object'} } }, parameters: route.docs.parameters.map(function (param) { var parameter = { in: param.paramType, name: param.name, description: param.description, required: param.required }; var schema; if (jsonSchemaPrimitives.indexOf(param.dataType) !== -1) { schema = {type: param.dataType}; } else { schema = {'$ref': '#/definitions/' + param.dataType}; if (!definitions[param.dataType]) { definitions[param.dataType] = fixSchema(_.clone(models[param.dataType])); } } if (param.paramType === 'body') { parameter.schema = schema; } else if (schema.type) { parameter.type = schema.type; } else { parameter.type = 'string'; } return parameter; }) }; }); }); return { paths: paths, definitions: definitions }; } exports.swaggerJson = swaggerJson; exports.createSwaggerRouteHandler = createSwaggerRouteHandler;
JavaScript
0
@@ -2218,18 +2218,16 @@ eq, -( result -&& +? res @@ -2241,13 +2241,12 @@ Path -) %7C%7C + : ( opts @@ -2266,16 +2266,17 @@ ppPath)) +) ;%0A @@ -2285,24 +2285,172 @@ turn;%0A %7D%0A + var indexFile = result ? result.indexFile : opts.indexFile;%0A if (pathInfo === 'index.html' && indexFile) %7B%0A pathInfo = indexFile;%0A %7D%0A var path
2a20d0d7db83a304693577495cb692d1d7fdd24a
Correct scoping for variable (linting)
js/app/app.js
js/app/app.js
/** * Main application container for the Legislature Tracker * * An 'e' prefix is referring to editorialized content. */ (function($, w, undefined) { LT.Application = Backbone.Router.extend({ routes: { 'categories': 'routeCategories', 'category/:category': 'routeCategory', 'bill/:bill': 'routeEBill', 'bill-detail/:bill': 'routeOSBill', '*defaultR': 'routeDefault' }, initialize: function(options) { LT.options = _.extend(LT.defaultOptions, options); LT.app = this; // Bind to help with some event callbacks _.bindAll(this); // Main view for application this.mainView = new LT.MainApplicationView(LT.options); this.mainView.router = this; this.mainView.loading(); // Get data from spreadsheets this.tabletop = Tabletop.init({ key: LT.options.eKey, callback: this.loadEBills, callbackContext: this, wanted: LT.options.sheetsWanted }); }, // Function to call when bill data is loaded loadEBills: function(data, tabletop) { var thisRouter = this; // Parse out data from sheets var parsed = LT.parse.eData(tabletop); // Set up collections this.categories = new LT.CategoriesCollection(null); this.bills = new LT.BillsCollection(null); // Add bills and categories models _.each(parsed.bills, function(b) { thisRouter.bills.add(LT.utils.getModel('BillModel', 'bill', b)); }); _.each(parsed.categories, function(c) { thisRouter.categories.add(LT.utils.getModel('CategoryModel', 'id', c)); }); this.bills.each(function(b) { b.loadCategories(); }); // Load up bill count if (LT.options.aggregateURL) { $.jsonp({ url: LT.options.aggregateURL, success: this.loadAggregateCounts }); } else { // Start application/routing this.start(); } }, // Get aggregate counts loadAggregateCounts: function(billCountData) { var thisRouter = this; var recentDate = moment().subtract('days', parseInt(LT.options.recentChangeThreshold, 10)); var recentInt = parseInt(recentDate.format('YYYYMMDD'), 10); var recentUpdated = 0; var recentCreated = 0; _.each(billCountData, function(stat) { if (stat.stat === 'total-bills') { thisRouter.totalBills = parseInt(stat.value, 10); } if (stat.stat.indexOf('updated') !== -1) { recentUpdated += (stat.int >= recentInt) ? parseInt(stat.value, 10) : 0; } if (stat.stat.indexOf('created') !== -1) { recentCreated += (stat.int >= recentInt) ? parseInt(stat.value, 10) : 0; } }); this.recentUpdated = recentUpdated; this.recentCreated = recentCreated; // Start application/routing this.start(); }, // Start application (after data has been loaded) start: function() { // Start handling routing and history Backbone.history.start(); }, // Default route routeDefault: function() { this.navigate('/categories', { trigger: true, replace: true }); this.mainView.render(); }, // Categories view routeCategories: function() { // If we are viewing the categories, we want to get // some basic data about the bills from Open States // but not ALL the data. We can use the bill search // to do this. this.mainView.loading(); this.getOSBasicBills(this.mainView.renderCategories, this.error); }, // Single Category view routeCategory: function(category) { var thisRouter = this; category = decodeURI(category); category = this.categories.get(category); // Load up bill data from open states this.mainView.loading(); category.loadBills(function() { thisRouter.mainView.renderCategory(category); }, thisRouter.error); }, // eBill route routeEBill: function(bill) { var thisRouter = this; bill_id = decodeURI(bill); bill = this.bills.where({ bill: bill_id })[0]; if (!bill) { this.navigate('/bill-detail/' + encodeURI(bill_id), { trigger: true, replace: true }); return; } this.mainView.loading(); bill.loadOSBills(function() { thisRouter.mainView.renderEBill(bill); }, thisRouter.error); }, // osBill route routeOSBill: function(bill) { var thisRouter = this; bill = decodeURI(bill); bill = LT.utils.getModel('OSBillModel', 'bill_id', { bill_id: bill }); this.mainView.loading(); $.when.apply($, [ LT.utils.fetchModel(bill) ]).done(function() { thisRouter.mainView.renderOSBill(bill); }) .fail(thisRouter.error); }, getOSBasicBills: function(callback, error) { var thisRouter = this; var billIDs = []; // Check if we have one this already if (!this.fetchedCategories) { // First collect all the bill id's we need this.bills.each(function(bill) { _.each(['bill_primary', 'bill_companion', 'bill_conference'], function(prop) { if (bill.get(prop)) { billIDs.push(bill.get(prop).get('bill_id')); } }); }); var url = 'http://openstates.org/api/v1/bills/?state=' + LT.options.state + '&search_window=session:' + LT.options.session + '&bill_id__in=' + encodeURI(billIDs.join('|')) + '&apikey=' + LT.options.OSKey + '&callback=?'; $.jsonp({ url: url, success: function(data) { thisRouter.fetchedCategories = true; _.each(data, function(d) { d.created_at = moment(d.created_at); d.updated_at = moment(d.updated_at); LT.utils.getModel('OSBillModel', 'bill_id', d).set(d); }); callback.call(thisRouter); }, error: this.error }); } else { callback.call(thisRouter); } }, error: function(e) { this.mainView.error(e); } }); })(jQuery, window);
JavaScript
0
@@ -4150,30 +4150,27 @@ this;%0A -%0A +var bill_id = d @@ -4177,32 +4177,39 @@ ecodeURI(bill);%0A + %0A bill = thi @@ -4245,17 +4245,16 @@ %7D)%5B0%5D;%0A -%0A if
34ef7196506047b06c3010a4a442fb0bd2a62b71
Remove Joi validation
routes.js
routes.js
const Reporter = require('./src/Reporter'); const PostReporter = require('./src/PostReport'); const Verification = require('./src/Verification'); const Joi = require('joi'); module.exports = [ { method: 'GET', path: '/report/', handler: Reporter, config: { validate: { query: { hipchat: Joi.string().required(), site: Joi.string().uri().required(), } } } }, { method: 'POST', path: '/report/', handler: PostReporter, config: { validate: { payload: Joi.object().keys({ item: Joi.object().required(), }), } } }, { method: 'GET', path: '/verification/{hipchat}/', handler: Verification, config: { validate: { query: { id: Joi.required(), } } } } ]
JavaScript
0
@@ -502,144 +502,8 @@ er,%0A - config: %7B%0A validate: %7B%0A payload: Joi.object().keys(%7B%0A item: Joi.object().required(),%0A %7D),%0A %7D%0A %7D%0A %7D,
ef959ba56e70e14c02986d8fc3feea6a4de39df3
Clean getNestedProp
assets/javascript/script.js
assets/javascript/script.js
"use strict"; var getNestedProp = function (obj, propString, fallback) { if (!propString) return obj; var prop, props = propString.split('.'); //for (var i = 0, iLen = props.length - 1; i < iLen; i++) { for (var i = 0, iLen = props.length - 1; i <= iLen; i++) { prop = props[i]; if (typeof obj == 'object' && obj !== null && prop in obj) { obj = obj[prop]; } else return fallback; } //return obj[props[i]]; return obj; }; angular.module('OpenMining', ["highcharts-ng"]) .factory('LineChart', function($http){ var return_val = { 'getConfig':function(URL){ return $http.post(URL) } }; return return_val; }) .controller('Process', function($scope, $http, $location, $timeout) { $scope.loading = true; $scope.process = []; $scope.init = function(slug) { var API_URL = "ws://"+ location.host +"/process/" + slug + ".ws?"; for (var key in $location.search()){ API_URL += key + "=" + $location.search()[key] + "&"; } var sock = new WebSocket(API_URL); sock.onmessage = function (e) { var data = JSON.parse(e.data); if (data.type == 'columns') { $scope.columns = data.data; }else if (data.type == 'data') { $scope.process.push(data.data); }else if (data.type == 'close') { sock.close(); } $scope.$apply(); $scope.loading = false; }; }; }) .controller('Chart', function($scope, $http, $location, LineChart, $timeout) { $scope.loading = true; $scope.chartConfig = []; $scope.columns = []; $scope.process = []; $scope.filters = {}; $scope.operators =[ {key: 'gte', value : 'gte'}, {key: 'lte', value: 'lte'}, {key: 'is', value: 'is'}, {key: 'in', value: 'in'}, {key: 'between', value: 'between'} ]; $scope.types=[ {key: 'date', value: 'Date'}, {key: 'int', value: 'Integer'}, {key: 'str', value: 'String'} ]; $scope.$watch('filter_type', function(newVal){ if(getNestedProp(newVal, 'key', '') == 'date') $scope.filter_format = ":Y-:m-:d"; else $scope.filter_format = ""; }); $scope.addFilter = function(){ var chave = 'filter__'+$scope.filter_field+"__"+$scope.filter_operator.key+'__'+$scope.filter_type.key; if ($scope.filter_format) chave = chave + '__'+$scope.filter_format $scope.filters[chave] = $scope.filter_value; }; $scope.removeFilter = function(index){ delete $scope.filters[index]; } $scope.applyFilters = function(slug, categorie, type, title){ var API_URL = "ws://"+ location.host +"/process/" + slug + ".ws?"; for (var key in $scope.filters){ API_URL += key + "=" + $scope.filters[key] + "&"; } $scope.columns = []; $scope.process = []; $scope.chartConfig[slug] = { options: { chart: { type: type } }, series: [], title: { text: title }, xAxis: { currentMin: 0, categories: [] } }; var sock = new WebSocket(API_URL); sock.onmessage = function (e) { var data = JSON.parse(e.data); if (data.type == 'columns') { $scope.columns = data.data; }else if (data.type == 'data') { $scope.process.push(data.data); }else if (data.type == 'categories') { $scope.chartConfig[slug].xAxis.categories = data.data; }else if (data.type == 'close') { sock.close(); } var loopseries = {}; for (var j in $scope.process) { for (var c in $scope.process[j]) { if (typeof loopseries[c] == 'undefined'){ loopseries[c] = {}; loopseries[c].data = []; } loopseries[c].name = c; loopseries[c].data.push($scope.process[j][c]); } } $scope.chartConfig[slug].series = []; for (var ls in loopseries){ if (ls != categorie) { $scope.chartConfig[slug].series.push(loopseries[ls]); } } $timeout(function(){ $scope.$apply(); }); $scope.loading = false; }; }; $scope.init = function(slug, categorie, type, title) { var API_URL = "ws://"+ location.host +"/process/" + slug + ".ws?"; for (var key in $location.search()){ API_URL += key + "=" + $location.search()[key] + "&"; } $scope.chartConfig[slug] = { options: { chart: { type: type } }, series: [], title: { text: title }, xAxis: { currentMin: 0, categories: [] } }; var sock = new WebSocket(API_URL); sock.onmessage = function (e) { var data = JSON.parse(e.data); if (data.type == 'columns') { $scope.columns = data.data; }else if (data.type == 'data') { $scope.process.push(data.data); }else if (data.type == 'categories') { $scope.chartConfig[slug].xAxis.categories = data.data; }else if (data.type == 'close') { sock.close(); } var loopseries = {}; for (var j in $scope.process) { for (var c in $scope.process[j]) { if (typeof loopseries[c] == 'undefined'){ loopseries[c] = {}; loopseries[c].data = []; } loopseries[c].name = c; loopseries[c].data.push($scope.process[j][c]); } } $scope.chartConfig[slug].series = []; for (var ls in loopseries){ if (ls != categorie) { $scope.chartConfig[slug].series.push(loopseries[ls]); } } $timeout(function (){ $scope.$apply(); }); $scope.loading = false; }; }; });
JavaScript
0
@@ -147,70 +147,8 @@ );%0A%0A - //for (var i = 0, iLen = props.length - 1; i %3C iLen; i++) %7B%0A fo @@ -361,34 +361,8 @@ %7D%0A%0A - //return obj%5Bprops%5Bi%5D%5D;%0A re
19073b16508fd3e0e3180e5372be4f75f7fbc66b
Fix GlobalSearch result z-index
components/AppLayout/GlobalSearch.js
components/AppLayout/GlobalSearch.js
import React, { useState, useEffect } from 'react'; import { useRouter } from 'next/router'; import { t } from 'ttag'; import { Box, InputAdornment, TextField, ClickAwayListener, makeStyles, } from '@material-ui/core'; import SearchIcon from '@material-ui/icons/Search'; const useStyles = makeStyles(theme => ({ root: { flex: 1, position: 'relative', }, searchWrapper: { padding: '0 8px', width: '100%', [theme.breakpoints.up('md')]: { padding: '0 24px', }, }, input: { padding: '10px 0', cursor: 'pointer', }, adornment: { color: ({ focus }) => (focus ? theme.palette.primary[500] : 'inherit'), }, result: { padding: '0 20px', position: 'absolute', zIndex: 1, display: ({ value }) => (value ? 'block' : 'none'), background: theme.palette.secondary[500], width: '100%', [theme.breakpoints.up('md')]: { marginLeft: 24, marginRight: 24, width: 'calc(100% - 48px)', }, }, resultEntry: { cursor: 'pointer', color: theme.palette.common.white, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', '&:hover': { color: theme.palette.primary[500], }, '&:not(:first-child)': { borderTop: `1px solid ${theme.palette.secondary[400]}`, }, }, iconWithText: { display: 'flex', alignItems: 'center', }, })); function GlobalSearch({ onIconClick }) { const router = useRouter(); const { query } = router; const [expanded, setExpanded] = useState(false); const [focus, setFocus] = useState(false); const [value, setValue] = useState(router.query.q || ''); const classes = useStyles({ focus, value }); const navigate = type => () => router.push({ pathname: '/search', query: { type, q: value } }); useEffect(() => void (query.q !== value && setValue(query.q || '')), [ query.q, ]); const input = ( <TextField id="search" variant="outlined" InputProps={{ startAdornment: ( <InputAdornment className={classes.adornment} position="start"> <SearchIcon /> </InputAdornment> ), classes: { input: classes.input, }, onFocus: () => setFocus(true), }} classes={{ root: classes.searchWrapper }} value={value} onChange={e => { setValue(e.target.value); if (!e.target.value && expanded) setExpanded(false); }} /> ); return ( <ClickAwayListener onClickAway={() => setFocus(false)}> <div className={classes.root}> <Box display={['none', 'none', 'block']}>{input}</Box> <Box display={['block', 'block', 'none']} textAlign="right"> {expanded ? ( input ) : ( <SearchIcon onClick={() => { setExpanded(!expanded); onIconClick(); }} /> )} </Box> {!!value && focus && ( <div className={classes.result}> <div className={classes.resultEntry} onClick={navigate('messages')}> <div className={classes.iconWithText}> <Box component={SearchIcon} mr={1.5} /> {value} </div> <div className={classes.right}>{t`in Messages`}</div> </div> <div className={classes.resultEntry} onClick={navigate('replies')}> <div className={classes.iconWithText}> <Box component={SearchIcon} mr={1.5} /> {value} </div> <div className={classes.right}>{t`in Replies`}</div> </div> </div> )} </div> </ClickAwayListener> ); } export default GlobalSearch;
JavaScript
0.000002
@@ -730,25 +730,25 @@ zIndex: -1 +2 ,%0A displa
023c261748af4fec2c0e00dfb2b6edc714681aa9
Move Ragnar back to original home location
components/character/player/index.js
components/character/player/index.js
'use strict'; var Player = function(playablePlayerName, ctx) { this.ctx = ctx; this.spriteFile = new Image(); this.spriteFile.src = 'components/character/player/sprites.png'; this.tileScale = 3; this.name = playablePlayerName; this.type = 'playable'; // Airship, Boat, etc this.models = this.getModelsForPlayer(playablePlayerName); this.state = { lastTick : 0, currentModel : null, modelState : 0, direction : 'north', position : { x: 1408, //2624 y: 976 // 752 } } window.coords = this.state.position; }; Player.prototype.tick = function() { var currentTime = (new Date()).getTime(); if (currentTime - this.state.lastTick > 250) { this.state.currentModel = this.models[this.state.direction + '-' + this.state.modelState]; this.state.lastTick = currentTime; if (this.state.modelState === 0) { this.state.modelState = 1; } else { this.state.modelState = 0; } } }; Player.prototype.render = function(scale) { if (this.state.currentModel !== null) { this.ctx.drawImage( this.spriteFile, this.state.currentModel.x, this.state.currentModel.y, this.state.currentModel.width, this.state.currentModel.height, 7*16*scale, // Scale x4 7*16*scale, // Scale x4 this.state.currentModel.width*scale, // Scale x4 this.state.currentModel.height*scale // Scale x4 ); } }; Player.prototype.move = function(direction, blocked) { console.log('MOVE: ', direction); if (this.state.direction === direction && !!blocked) { switch(direction) { case 'north': this.state.position.y -= this.state.currentModel.height; break; case 'south': this.state.position.y += this.state.currentModel.height; break; case 'east': this.state.position.x += this.state.currentModel.width; break; case 'west': this.state.position.x -= this.state.currentModel.width; break; } } else { this.state.direction = direction; } console.log(this.state.position.x, this.state.position.y); }; Player.prototype.getModelsForPlayer = function(playablePlayer) { switch(playablePlayer) { case 'Ragnar': return { 'north-0' : { 'x': 1, 'y': 74, 'width': 16, 'height': 16 }, 'north-1' : { 'x': 26, 'y': 74, 'width': 16, 'height': 16 }, 'south-0' : { 'x': 1, 'y': 50, 'width': 16, 'height': 16 }, 'south-1' : { 'x': 26, 'y': 52, 'width': 16, 'height': 16 }, 'east-0' : { 'x': 48, 'y': 52, 'width': 16, 'height': 16 }, 'east-1' : { 'x': 70, 'y': 52, 'width': 16, 'height': 16 }, 'west-0' : { 'x': 48, 'y': 74, 'width': 16, 'height': 16 }, 'west-1' : { 'x': 70, 'y': 74, 'width': 16, 'height': 16 } } break; default: throw 'Invalid character'; } }; module.exports = Player;
JavaScript
0.000001
@@ -480,12 +480,12 @@ x: -1408 +2624 , / @@ -503,11 +503,11 @@ y: -976 +752
ea4350063182f28a3c45451ceb9758d025f96840
add markdown plugin for markdown to html conversion via marked
runner.js
runner.js
const fs = require('fs') const path = require('path') const glob = require('glob') const matter = require('gray-matter') const DEFAULT_OPTIONS = { source: './content', target: './public' } const data = { files: {}, meta: { title: 'test' }, options: DEFAULT_OPTIONS } // util functions const readFile = file => ({ path: file, name: path.basename(file), content: fs.readFileSync(file, {encoding: 'utf-8'}) }) // plugins const readFiles = () => data => ({ files: glob.sync('./content/**/*.md').map(readFile) }) const options = (options) => data => { options = Object.assign(DEFAULT_OPTIONS, options) return {options} } const meta = (meta) => data => ({meta}) const yamlFrontMatter = () => data => { return { files: data.files.map(file => { const {data, content} = matter(file.content) return Object.assign(file, { meta: data, content }) }) } } const render = template => data => { return { files: data.files.map(file => { const pageData = Object.assign({}, data, { page: file }) return Object.assign(file, { content: template(pageData) }) }) } } const logData = () => data => console.log(JSON.stringify(data, null, 2)) const createIndexFile = () => data => { return { files: data.files.concat([{ path: './index.html', name: 'index.html', content: '' }]) } } const writeFiles = () => data => { data.files.forEach(file => { const targetPath = path.join(data.options.target, path.relative(data.options.source, file.path)) fs.writeFileSync(targetPath, file.content) }) } // runner const runner = () => { let plugins = [] let data = {} return { use (plugin) { plugins.push(plugin) return this }, build () { plugins.forEach(plugin => { data = Object.assign(data, plugin(data)) }) } } } runner() .use(options({ testOption: 'test' })) .use(meta({ title: 'Hello World!' })) .use(readFiles()) .use(createIndexFile()) .use(yamlFrontMatter()) .use(render(require('./templates/index.js'))) .use(writeFiles()) .use(logData()) .build()
JavaScript
0
@@ -113,16 +113,49 @@ matter') +%0Aconst marked = require('marked') %0A%0Aconst @@ -947,24 +947,200 @@ %7D)%0A %7D%0A%7D%0A%0A +const markdown = () =%3E data =%3E %7B%0A return %7B%0A files: data.files.map(file =%3E %7B%0A return Object.assign(file, %7B%0A content: marked(file.content)%0A %7D)%0A %7D)%0A %7D%0A%7D%0A%0A const render @@ -2271,24 +2271,41 @@ ntMatter())%0A +.use(markdown())%0A .use(render(
b9a9338d074e868ebbe053e8bbc46aae8fd5edd2
undo last change... who am i kidding, these commits are just tests for webhooks.
src/map.js
src/map.js
/*! ** Created by Jacques Vincilione, Justin Johns - Lucien Consulting, INC ** Requires Google Maps API to be included. ** ** Standard MIT License Copyright (c) 2015 Lucien Consulting, 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. ** */ void function () { "use strict"; var map_marker = { version: "1.0" }, map; /** * [initMap initializes map with custom markers] * @param {object} centerPoint [lat, long coordinates (IE: {lat: 24.2131, lng: 14.45245})] * @param {integer} zoom [Integer of zoom level - Defaults to 12] * @param {array} markers [Array of Map Objects] * @param {string} elementId [DOM Element ID - Defaults to 'map-canvas'] */ var initMap = function (centerPoint, zoom, markers, elementId, mapType) { // throw error if google maps API is not included if (!google.maps) { throw new Error("This plugin requires the google maps api to be included on the page. Visit https://developers.google.com/maps/documentation/javascript/tutorial for instructions."); } // throw error is centerPoint is undefined if (!centerPoint) { throw new Error("mapConfig.centerPoint is not defined, and is required."); } // throw error if markers is not an array if (!markers || markers.length < 1) { throw new Error("mapConfig.markers is not a valid array."); } // set defaults if values are undefined/null zoom = zoom || 12; elementId = elementId || "map-canvas"; var mapOptions = { zoom: zoom, center: new google.maps.LatLng(centerPoint.lat, centerPoint.lng), mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false }; map = new google.maps.Map(document.getElementById(elementId), mapOptions); /* markers requires an image, latLng in each object in the array optional values: mapSize (defaults to {w: 50, h: 50}), title (defaults to 'My Marker') */ for (var i = 0; i < markers.length; i++) { var pos = { lat: markers[i].latLng.lat, lng: markers[i].latLng.lng }, img = markers[i].image, w = markers[i].size.w || 50, h = markers[i].size.h || 50, title = markers[i].title || "My Marker", mapMarker; if (!pos.lat || !img) { throw new Error("mapConfig.markers.latLng or mapConfig.markers.image is not defined. Array Index = " + i); } mapMarker = new google.maps.Marker({ "position": new google.maps.LatLng(pos.lat, pos.lng), "icon": new google.maps.MarkerImage(img, new google.maps.Size(w, h)), "map": map, "zindex": i, "title": title }) } } google.maps.event.addDomListener(window, 'load', function () { initMap(mapConfig.centerPoint, mapConfig.zoom, mapConfig.markers, mapConfig.elementId); }); }();
JavaScript
0
@@ -1217,13 +1217,9 @@ %0A*/%0A -void +( func @@ -3932,9 +3932,10 @@ %7D);%0A%0A%7D() +) ;
43d3284c74ea9cd651b58d90665799440df5d65e
Update mainLucas.js
assetsLucas/js/mainLucas.js
assetsLucas/js/mainLucas.js
$( document ).ready(function() { $(".masthead__menu-item").each( function(){ $( this ).on( "click", function() { //$(".masthead__menu-item").removeClass("links-activeItem"); //$( this ).addClass("links-activeItem"); //console.log("masthead__menu-item:I am caleld"); window.activeNaviItem = $( this ); console.log(window.activeNaviItem ); }); } ); if(window.activeNaviItem) { $(window.activeNaviItem).addClass("links-activeItem"); } });
JavaScript
0.000001
@@ -27,16 +27,42 @@ on() %7B%0A%0A + /*%0A //only for ajax navi%0A $(%22.mas @@ -146,18 +146,16 @@ %7B%0A -// $(%22.mast @@ -211,18 +211,16 @@ ;%0A -// $( this @@ -255,150 +255,8 @@ %22);%0A - //console.log(%22masthead__menu-item:I am caleld%22);%0A window.activeNaviItem = $( this );%0A console.log(window.activeNaviItem );%0A @@ -276,103 +276,12 @@ );%0A -%0A -if(window.activeNaviItem)%0A %7B%0A $(window.activeNaviItem).addClass(%22links-activeItem%22);%0A %7D +*/ %0A%0A%0A%7D
67c98c90debdb0bd878f4d90aee9fd4e15cbc26e
Fix vote id
scripts/offline.js
scripts/offline.js
(function() { var db; databaseOpen() .then(refreshView); function databaseOpen() { return new Promise(function(resolve, reject) { var version = 1; var request = indexedDB.open('bookmarks', version); // Run migrations if necessary request.onupgradeneeded = function(e) { db = e.target.result; e.target.transaction.onerror = reject; db.createObjectStore('bookmark', { keyPath: '_id' }); }; request.onsuccess = function(e) { db = e.target.result; resolve(); }; request.onerror = reject; }); } function onSubmit(e) { e.preventDefault(); var todo = { text: input.value, _id: String(Date.now()) }; databaseTodosPut(todo) .then(function() { input.value = ''; }) .then(refreshView); } function onClick(e) { // We'll assume that any element with an ID // attribute is a to-do item. Don't try this at home! e.preventDefault(); if (e.target.hasAttribute('id')) { databaseTodosGetById(e.target.getAttribute('id')) .then(function(bookmark) { return databaseTodosDelete(bookmark); }) .then(refreshView); } } function databaseBookmarksPut(bookmark) { return new Promise(function(resolve, reject) { var transaction = db.transaction(['bookmark'], 'readwrite'); var store = transaction.objectStore('bookmark'); var request = store.put(bookmark); transaction.oncomplete = resolve; request.onerror = reject; }); } function databaseBookmarksGet() { return new Promise(function(resolve, reject) { var transaction = db.transaction(['bookmark'], 'readonly'); var store = transaction.objectStore('bookmark'); // Get everything in the store var keyRange = IDBKeyRange.lowerBound(0); var cursorRequest = store.openCursor(keyRange); // This fires once per row in the store, so for simplicity collect the data // in an array (data) and send it pass it in the resolve call in one go var data = []; cursorRequest.onsuccess = function(e) { var result = e.target.result; // If there's data, add it to array if (result) { data.push(result.value); result.continue(); // Reach the end of the data } else { resolve(data); } }; }); } function databaseBookmarksGetById(id) { return new Promise(function(resolve, reject) { var transaction = db.transaction(['bookmark'], 'readwrite'); var store = transaction.objectStore('bookmark'); var request = store.get(id); request.onsuccess = function(e) { var result = e.target.result; resolve(result); }; request.onerror = reject; }); } function databaseBookmarksDelete(bookmark) { return new Promise(function(resolve, reject) { var transaction = db.transaction(['bookmark'], 'readwrite'); var store = transaction.objectStore('bookmark'); var request = store.delete(bookmark._id); transaction.oncomplete = resolve; request.onerror = reject; }); } /* All bookmark logic below */ $('.iswc-show-favorites').on('click', function () { if ($(this).hasClass('active')) { showAll(); } else { databaseBookmarksGet().then(filterAllBookmarks); } }); $('.iswc-bookmark').on('click', function (e) { e.preventDefault(); var $star = $(this).children('span'), $item = $(this).parents('.iswc-paper, .iswc-session'), id = $item.attr('id'); if(!$star.hasClass('glyphicon-star')) { databaseBookmarksPut({_id:id}).then(function () { console.log(id, 'bookmarked'); $star.removeClass('glyphicon-star-empty').addClass('glyphicon-star'); }); } else { databaseBookmarksDelete({_id:id}).then(function () { console.log(id, 'no longer bookmarked'); $star.addClass('glyphicon-star-empty').removeClass('glyphicon-star'); if ($('.iswc-show-favorites').hasClass('active')){ $item.hide(); } }); } }); function refreshView() { return databaseBookmarksGet().then(renderAllBookmarks); } function renderAllBookmarks(bookmarks) { bookmarks.forEach(function(bookmark) { $('#' + bookmark._id).find('.iswc-bookmark span').removeClass('glyphicon-star-empty').addClass('glyphicon-star'); }); } function filterAllBookmarks(bookmarks) { $('.iswc-papers .iswc-paper, .iswc-session').hide(); bookmarks.forEach(function(bookmark) { $('#' + bookmark._id).show(); }); } function showAll() { $('.iswc-paper, .iswc-session').show(); } /* All voting logic below */ $('#votingModal').on('hidden.bs.modal', function (e) { $('.iswc-vote-progress').hide(); $('.iswc-vote-code').show(); $('.iswc-vote-success').hide(); $('.iswc-vote-error').hide(); }); $('#votingModal').on('show.bs.modal', function (e) { $('.iswc-vote-submit').show(); $('.iswc-vote-cancel').text('Cancel'); }); $('.iswc-vote-submit').on('click', function () { $('.iswc-vote-progress').show(); $('.iswc-vote-code').hide(); $(this).attr('disabled',"disabled"); $.ajax({ method: "POST", url: votingURL + '?' + $.param({vote: $('.iswc-vode-id').text()}), data: { key: $('.iswc-vote-code input').val() } }) .done(function( msg ) { $('.iswc-vote-success').show(); $('.iswc-vote-progress').hide(); $('.iswc-vote-code').hide(); $('.iswc-vote-submit').hide(); $('.iswc-vote-title').hide(); $('.iswc-vote-cancel').text('Close'); }) .fail(function( jqXHR, textStatus, errorThrown) { $('.iswc-vote-progress').hide(); $('.iswc-vote-code').show(); $('.iswc-vote-submit').removeAttr('disabled'); if (jqXHR.status > 500 ) $('.iswc-vote-error').text('Something went wrong (' + jqXHR.status + '): ' + errorThrown); $('.iswc-vote-error').show(); }); }); $('.iswc-voting').on('click', function() { var $subject = $(this).parents('.iswc-paper'), id = $subject.attr('id'), title = $subject.find('.iswc-paper-title a').text(), PIndex = title.substring(1,4); $('#votingModal .modal-title .iswc-vode-id').text(PIndex); $('#votingModal').find('.iswc-vote-title').html('You are about to vote for <i>' + title + '</i>'); $('#votingModal').find('.iswc-vote-code input').val(''); $('#votingModal').modal('show'); }) }());
JavaScript
0.000001
@@ -6338,22 +6338,18 @@ ').text( -PIndex +id );%0A %09$(
0fd6a77844fce2f201726ae5bf0e77fa2247a29a
add a sanity check
sanity.js
sanity.js
var pad = ' '; var expect = function (actual, expected, message) { if (expected != actual) { print(message + ': ' + actual + ' (expected: ' + expected + ')'); } }; var expectNone = function (collection, field) { var selector = {}; selector[field] = {$exists: true}; expect(db[collection].count(selector), 0, collection + ' ' + field + ' count'); }; var mapReduce = function (collection, map) { db[collection].mapReduce(map, function (key, values) { return Array.sum(values); }, {out: {inline: 1}}).results.forEach(function (result) { print(result._id + pad.substring(0, 40 - result._id.length) + result.value); }); } // Finds documents in the given collection matching the given criteria. If any // documents are found, prints the given message and, for each document, prints // its ID and the value of the given field. var matches = function (collection, field, criteria, message) { message = message || collection + ' with invalid ' + field; var count = db[collection].count(criteria); if (count) { print('\n' + message + ':'); db[collection].find(criteria).forEach(function (obj) { if (field.indexOf('.') === -1) { print(obj._id + ': ' + obj[field]); } else { print(obj._id); } }); } }; // Role matches('memberships', 'role', { role: null, }); // Contact details expectNone('people', 'contact_details.type'); expectNone('organizations', 'contact_details.type'); expectNone('people', 'contact_details.note'); expectNone('organizations', 'contact_details.note'); matches('memberships', 'jurisdiction_id', { contact_details: { $elemMatch: { type: {$nin: ['address', 'cell', 'email', 'fax', 'voice']}, }, }, }, 'memberships: unexpected contact_details.type'); matches('memberships', 'jurisdiction_id', { contact_details: { $elemMatch: { type: {$ne: 'email'}, note: {$nin: ['constituency', 'legislature', 'office', 'residence']}, }, }, }, 'memberships: unexpected contact_details.note'); matches('memberships', 'jurisdiction_id', { contact_details: { $elemMatch: { type: 'email', note: {$ne: null}, }, }, }, 'memberships: email with non-empty note'); matches('memberships', 'jurisdiction_id', { contact_details: { $elemMatch: { type: {$ne: 'email'}, note: null, }, }, }, 'memberships: non-email with empty note'); matches('memberships', 'jurisdiction_id', { $where: function () { var types = ['address', 'cell', 'fax', 'voice']; var notes = ['constituency', 'legislature', 'residence']; for (var k = 0, n = types.length; k < n; k++) { for (var j = 0, m = notes.length; j < m; j++) { var count = 0; for (var i = 0, l = this.contact_details.length; i < l; i++) { var contact_detail = this.contact_details[i]; if (contact_detail.type == types[k] && contact_detail.note == notes[j]) { count += 1; } if (count > 1) { return true; } } } } }, }, 'memberships: multiple contact_details with the same type and note'); // @todo multiple emails // Links expectNone('memberships', 'links.url'); expectNone('organizations', 'links.url'); expectNone('memberships', 'links.note'); expectNone('organizations', 'links.note'); matches('people', 'jurisdiction_id', { 'links.note': { $ne: null, }, }); matches('people', 'links.url', { $where: function () { var urls = [/facebook\.com/, /twitter\.com/, /youtube\.com/]; for (var j = 0, m = urls.length; j < m; j++) { var count = 0; for (var i = 0, l = this.links.length; i < l; i++) { if (urls[j].test(this.links[i].url)) { count += 1; } if (count > 1) { return true; } } } }, }, 'people: multiple links with the same social media url'); // print('\nDistinct people links.url domains for manual review:'); // mapReduce('people', function () { // this.links.forEach(function (link) { // emit(link.url.match('^(?:[a-z]+://)?(?:www\\.)?([^/]+)')[1], 1); // }) // }); // Miscellaneous // print('\nDistinct memberships post_id for manual review:'); // mapReduce('memberships', function () { // if (this.post_id) { // emit(this.post_id, 1); // } // });
JavaScript
0.000013
@@ -2430,32 +2430,402 @@ empty note');%0A%0A +matches('memberships', 'jurisdiction_id', %7B%0A $where: function () %7B%0A var count = 0;%0A for (var i = 0, l = this.contact_details.length; i %3C l; i++) %7B%0A if (this.contact_details%5Bi%5D.type == 'email') %7B%0A count += 1;%0A %7D%0A if (count %3E 1) %7B%0A return true;%0A %7D%0A %7D%0A %7D,%0A%7D, 'memberships: multiple contact_details with the same type: email');%0A%0A matches('members @@ -3538,34 +3538,8 @@ );%0A%0A -// @todo multiple emails%0A%0A // L
2e538754422f4844c854261c52aba8bc9ec87449
add param 'root' to MDSConsole.run callback
js/console.js
js/console.js
var MDSConsole = { /** * Private! * Posts message to console. */ post: function(type, message) { var logRecord = document.createElement('div'); logRecord.classList.add('run_script__console_record'); logRecord.textContent = message; var console = document.getElementById('run_script__console'); console.appendChild(logRecord); console.scrollTop = console.scrollHeight - console.clientHeight; logRecord.classList.add('run_script__console_record--' + type); }, log: function(message) { MDSConsole.post('log', message) }, info: function(message) { MDSConsole.post('info', message) }, warn: function(message) { MDSConsole.post('warn', message) }, system: function(message) { MDSConsole.post('system', message) }, /** * Call this method when one of the subtasks completed with error. But script * does not stopped. */ error: function(message) { MDSConsole.post('error', message) }, /** * Call this method when one of the subtasks successfully completed. */ ok: function(message) { MDSConsole.post('ok', message) }, /** * Script successful completed. Call this method at the and or your script. */ success: function(message) { document.getElementById('run_script__state').classList.remove('fa-spin'); document.getElementById('run_script__state').classList.remove('fa-cog'); document.getElementById('run_script__state').classList.remove('run_script__state--run'); document.getElementById('run_script__state').classList.add('fa-check'); document.getElementById('run_script__state').classList.add('run_script__state--success'); if (message == null) { message = 'The script completed successfully'; } MDSConsole.post('success', message) }, /** * Script failed. Call this method when script finished by error. */ fail: function(message) { if (message == null) { message = 'The script failed'; } document.getElementById('run_script__state').classList.remove('fa-spin'); document.getElementById('run_script__state').classList.remove('fa-cog'); document.getElementById('run_script__state').classList.remove('run_script__state--run'); document.getElementById('run_script__state').classList.add('fa-times'); document.getElementById('run_script__state').classList.add('run_script__state--fail'); MDSConsole.error(message); }, run: function(optionsOrAction, action) { if (typeof optionsOrAction === 'function') { action = optionsOrAction; optionsOrAction = {}; } var options = MDSCommon.extend({ simpleFormat: true, connectAndLogin: true }, optionsOrAction); if (options.simpleFormat) { Mydataspace.registerFormatter('entities.get.res', new EntitySimplifier()); Mydataspace.registerFormatter('entities.change.res', new EntitySimplifier()); Mydataspace.registerFormatter('entities.create.res', new EntitySimplifier()); Mydataspace.registerFormatter('entities.getRoots.res', new EntitySimplifier()); Mydataspace.registerFormatter('entities.getMyRoots.res', new EntitySimplifier()); } if (options.connectAndLogin && !Mydataspace.isLoggedIn()) { MDSConsole.log('Connecting...'); Mydataspace.connect().then(function () { MDSConsole.log('Connected! Logging in...'); return new Promise(function (resolve, reject) { Mydataspace.on('login', function () { MDSConsole.log('Logged In!'); resolve(); }); Mydataspace.on('unauthorized', function () { reject(new Error('Unauthorized')); }); }); }).then(function () { return action(); }).then(function (res) { MDSConsole.success(res); }, function (err) { MDSConsole.fail(err.message); }); } } };
JavaScript
0.000003
@@ -3678,16 +3678,52 @@ action( +Mydataspace.getRoot(MDSConsole.root) );%0A
e69ca52e830f5df2960f737f790cc75dfcb618ed
split name and city strings
script.js
script.js
var iconStar = "img/star.svg"; var iconNostar = "img/nostar.svg"; var iconSearch = "img/search.svg"; loadBusstopsList(); $(document).ready(function() { // Initialize $(".bus-list").hide(); $(".station").removeClass("expanded"); // User Events $(".station").click(function() { if ($(this).hasClass("expanded")) { $(this).children(".bus-list").slideUp(200); $(this).removeClass("expanded"); } else { $(this).children(".bus-list").slideDown(200); $(this).addClass("expanded"); } }); $(".station-star").click(function() { if ($(this).hasClass("js-starred")) { // Remove Favorite $(this).attr("src", iconNostar); $(this).removeClass("js-starred"); $(this).parents(".station").remove(); return false; } else { // Add new Favorite $(this).attr("src", iconStar); $(this).removeClass("nostar").addClass("star"); $(this).addClass("js-starred"); $(".favorites").append($(this).parents(".station").clone()); return false; } }); }); $(".js-search").bind("input", function() { var suggests = matchInput(getBusstopList(), $(".js-search").val()); console.log(suggests); printSuggests(suggests); }); //match input with busstops name and citys function matchInput(list, input) { input = input.split(" "); var suggests = new Array(); var found; var j; for (var i = 0; i < list.length && suggests.length < 3; i++) { j = 0; do { if (input[j] != "") { found = list[i].ORT_GEMEINDE.match(new RegExp(input[j], "i")); if (found == null) found = list[i].ORT_NAME.match(new RegExp(input[j], "i")); } j++; } while (j < input.length && found != null); if (found != null) suggests[suggests.length] = list[i]; } return suggests; } //output suggests function printSuggests(suggests) { if (suggests.length > 0) printNext($(".search-results").find(".station:first"), suggests, 0); } function printNext(el, suggests, i) { el.find(".station-title").text(suggests[i].ORT_NAME); if (el.next(".station").length != 0 && suggests[i + 1] != undefined) printNext(el.next(".station"), suggests, i + 1); } // cache busstops function loadBusstopsList() { console.log("Start Request"); var apiUrl = "http://opensasa.info/SASAplandata/?type=BASIS_VER_GUELTIGKEIT"; request(apiUrl, validitySuccess, "jsonp"); } function validitySuccess(data) { if (!localStorage.version || localStorage.version != data[0].VER_GUELTIGKEIT) { localStorage.clear(); localStorage.version = data[0].VER_GUELTIGKEIT; if (!localStorage.busstops) { console.log("New Data"); var apiUrl = "http://opensasa.info/SASAplandata/?type=REC_ORT"; request(apiUrl, busstopsSuccess, "jsonp"); } } } function busstopsSuccess(data) { localStorage.setItem('busstops', JSON.stringify(data)); } // Return the busstop list as json which is stored in the localStorage function getBusstopList() { return JSON.parse(localStorage.busstops); } // callback is the name of the callback arg function request(urlAPI, success, callback) { $.ajax({ url: urlAPI, dataType: 'jsonp', jsonp: callback, success: function(data) { console.log("success: " + urlAPI); success(data); }, error: function(data) { console.log("Error: " + urlAPI); } }); }
JavaScript
0.000451
@@ -2834,16 +2834,200 @@ data) %7B%0A + for (var i = 0; i %3C data.length; i++) %7B%0A // %5B0%5D is italian %5B1%5D is german%0A data%5Bi%5D.stop = data%5Bi%5D.ORT_NAME.split(%22 - %22);%0A data%5Bi%5D.city = data%5Bi%5D.ORT_GEMEINDE.split(%22 - %22);%0A %7D%0A localS
c934e8f793b71e9b95134ba559240e482995b433
Update content.js
js/content.js
js/content.js
Contents = {}; MainModel = null; $(function() { // have to wait for DOM to load to get templates Contents.github = new Content({ id: "github", title: "GitHub", description: "The full source code for all of my non-work projects is hosted on my GitHub!", color: [0, 0, 190] }); Contents.interball = new Content({ id: "interball", title: "interball", bannerURL: "img/interballbanner.png", description: "A fast-action rotating pinball game with a constantly warping board, made during <a href='http://www.ludumdare.com/compo/ludum-dare-30/?action=preview&uid=36186' target='_blank'>Ludum Dare 30</a>.<br />Click logo to play!", color: [159, 104, 232] }); Contents.nsn = new Content({ id: "nsn", title: "Night Shift Ninja", description: "A 2D stealth-action-puzzle game made during <a href='http://www.srrngames.com/srrn-seventy-two-the-second-jam/' target='_blank'>SRRN Game Jam #2</a>.<br />Inspired by the randomly-chosen past Ludum Dare themes 'sneaking', 'bouncy'.<br />Click logo to play!", color: [255, 8, 50] }); Contents.kawa = new Content({ id: "kawa", title: "Kawaii Aishiteru Wormhole Adventure", bannerURL: "img/kawabanner.png", description: "A dating sim made for <a href='http://fuckthisjam.com/' target='_blank'>Fuck This Jame 2014</a>.<br />The goal was to make a game in a genre that you hate and/or know nothing about.", color: [17, 0, 88] }); Contents.uncivilize = new Content({ id: "uncivilize", title: "Uncivilize", description: "A 2D action-strategy game made during <a href='http://www.srrngames.com/were-jammin/' target='_blank'>SRRN Game Jam #1</a>.<br />Inspired by the randomly-chosen past Ludum Dare themes 'classic roles reversed', 'atmosphere', and 'all natural'.<br />Click logo to play!", color: [221, 168, 91] }); Contents.honeybundles = new Content({ id: "honeybundles", title: "Honey Bundles", description: "A stop-and-go endless runner for <a href='http://www.ludumdare.com/compo/ludum-dare-29/?action=preview&uid=36186'>Ludum Dare 29</a>'s theme: \"Beneath the Surface\".<br />Developed for the Unity web player entirely by myself.", color: [255, 255, 80] }); Contents.srrn1 = new Content({ id: "srrn1", title: "2D Vita Platformer", description: "A yet-to-be-revealed platformer I worked on at SRRN Games using the Unity Vita plugin.", color: [0, 200, 50] }); Contents.sws = new Content({ id: "sws", title: "Stormwater Sentries", description: "An HTML5 educational resource management browser game about reducing stormwater runoff on your property.<br />Developed at SRRN Games in collaboration with local Virginia organizations.<br />Click logo to play!", color: [0, 180, 255] }); Contents.retroverse = new Content({ id: "retroverse", title: "Retroverse", bannerURL: "img/retroversebanner.png", description: "My first complete, shipped game! A 1P/2P roguelike with lots of powerups and levels.<br />Made at the UVA SGD with a team of 7ish.", color: [50, 50, 50] }); Contents.princesstina = new Content({ id: "princesstina", title: "Princess Tina", bannerURL: "img/princesstinabanner.png", description: "A cute, Nintendo-hard platformer for <a href='http://globalgamejam.org/2014/games/princess-tina' target='_blank'>Global Game Jam 2014</a>.<br />Developed for the Unity web player with a team of 7.", color: [255, 100, 255] }); Contents.flappypuzzle = new Content({ id: "flappypuzzle", title: "Flappy Puzzle", bannerURL: "img/flappypuzzlebanner.png", description: "A touch-based game made for the <a href='http://itch.io/jam/flappyjam' target='_blank'>Flappy Jam</a>.<br />Graphics inspired by Tetris, difficulty and controls inspired by Flappy Bird.", color: [202, 206, 80] }); Contents.skylize = new Content({ id: "skylize", title: "Skylize", bannerURL: "img/skylizebanner.png", description: "An experiment with a velocity-based touch control system, made for the <a href='http://itch.io/jam/cyberpunk-jam' target='_blank'>Cyberpunk Jam</a>.<br />Paint the black sky with neon lights and share your creation.", color: [0, 255, 255] }); Contents.cityquake = new Content({ id: "cityquake", title: "City Quake", bannerURL: "img/cityquakebanner.png", description: "My first touch-based web game. An action-puzzle game where you destroy a city with earthquakes.<br />Made in Construct 2 for the Newgrounds <a href='http://www.newgrounds.com/collection/construct2touchjam' target='_blank'>Construct 2 Jam</a>.", color: [110, 70, 0] }); POSSIBLE_SUBTITLES = [ {text: "Game Developer, etc.", weight: 3}, {text: "The .io is ironic", weight: 3}, {text: "Ask about my username", weight: 2}, {text: "My games are better than my web design", weight: 1}, {text: "Donate to 1GfseRZYS6pebUscxv2kYpviwBMY1E8Hdb", weight: 1}, {text: "Can you solve the secret puzzle?", weight: 1}, // hint: there is no secret puzzle {text: "Congratulations, you are the 1st visitor!", weight: 1}, {text: "Achievement Unlocked: Rare and Pointless Random Message", weight: 0.1} ]; MainModel = new Backbone.Model({ secretAntiRobotEmail: "foolmoron@gmail.com", colorString: "rgb(255, 140, 0)", subtitle: "", test: "Testy Test", randomizeSubtitle: function() { var weightTotal = POSSIBLE_SUBTITLES.reduce(function(acc, subtitle) { return acc + subtitle.weight; }, 0); var weightedRandom = Math.random() * weightTotal; var weightSum = 0; for (var i = 0; i < POSSIBLE_SUBTITLES.length; i++) { weightSum += POSSIBLE_SUBTITLES[i].weight; if (weightedRandom < weightSum) { this.set('subtitle', POSSIBLE_SUBTITLES[i].text); break; } } } }); });
JavaScript
0.000001
@@ -669,33 +669,8 @@ /a%3E. -%3Cbr /%3EClick logo to play! %22,%0A
db37aed97b45e3d57013e15598bf15eeebc7fcb4
Allow setting arbitrary image
script.js
script.js
(function () { var $sam, $top; function randomOffset() { var range = 15; return Math.floor(Math.random() * range) - Math.ceil(range / 2); } function wiggle() { setDimensions(); setPosition(); } function setDimensions() { var scaleWidth, scaleHeight, scaleRatio, newWidth, newHeight; scaleWidth = $top.width() / $sam.width(); scaleHeight = $top.height() / $sam.height(); scaleRatio = Math.min(scaleWidth, scaleHeight); newWidth = $sam.width() * scaleRatio; newHeight = $sam.height() * scaleRatio; $sam.css({ width: newWidth, height: newHeight }); } function setPosition() { var baseLeft, baseTop, newTop, newLeft; baseLeft = ($top.width() / 2) - ($sam.width() / 2); baseTop = ($top.height() / 2) - ($sam.height() / 2); newTop = baseTop + randomOffset() + 'px'; newLeft = baseLeft + randomOffset() + 'px'; $sam.css({ marginTop: newTop, marginLeft: newLeft }); } function cacheQueries() { $sam = $('img'); $top = $(window.top); } $(function () { cacheQueries(); setInterval(wiggle, 50); }); }(this));
JavaScript
0.000004
@@ -25,16 +25,23 @@ am, $top +, parms ;%0A%0A fun @@ -1082,40 +1082,546 @@ %0A%0A -$(function () %7B%0A cacheQueries +function setImage() %7B%0A if (parms%5B'img'%5D) %7B%0A $sam.attr('src', parms%5B'img'%5D);%0A %7D%0A %7D%0A%0A function parseParameters() %7B%0A var rawParms;%0A parms = %5B%5D;%0A rawParms = location.href.split('?')%5B1%5D;%0A if (rawParms === undefined) %7B%0A return;%0A %7D%0A $.each(rawParms.split('&'), function() %7B%0A var pair, key, value;%0A pair = this.split('=');%0A key = pair%5B0%5D;%0A value = pair%5B1%5D;%0A parms%5Bkey%5D = value;%0A %7D);%0A %7D%0A%0A $(function () %7B%0A parseParameters();%0A cacheQueries();%0A setImage ();%0A
c33b9f0f6c34996d40dbc3854b4a248dc6b62972
Add background canvas
js/display.js
js/display.js
import { $$ } from 'util/dom'; import settings from 'settings'; var canvas = document.createElement('canvas'); export var ctx = canvas.getContext('2d'); var rows = settings.rows; var cols = settings.cols; var jewelSize = settings.jewelSize; var firstRun = true; function setup () { var boardElement = $$('#game-screen .game-board')[0]; canvas.classList.add('board'); canvas.width = cols * jewelSize; canvas.height = rows * jewelSize; boardElement.appendChild(canvas); } export function initialize (callback) { if (firstRun) { setup(); firstRun = false; } callback(); }
JavaScript
0.000001
@@ -257,16 +257,581 @@ true;%0A%0A +function createBackground () %7B%0A var bg = document.createElement('canvas');%0A var ctx = bg.getContext('2d');%0A var x, y;%0A%0A bg.classList.add('board-bg');%0A bg.width = cols * jewelSize;%0A bg.height = rows * jewelSize;%0A%0A ctx.fillStyle = 'rgba(255,235,255,0.15)';%0A%0A for (x = 0; x %3C cols; ++x) %7B%0A for (y = 0; y %3C cols; ++y) %7B%0A if ((x+y) %25 2) %7B%0A ctx.fillRect(%0A x * jewelSize, y * jewelSize,%0A jewelSize, jewelSize%0A );%0A %7D%0A %7D%0A %7D%0A%0A return bg;%0A%7D%0A%0A function @@ -1008,24 +1008,74 @@ jewelSize;%0A%0A + boardElement.appendChild(createBackground());%0A boardEle
26fd757bee1a2da4a9fae8566269622052afdb9a
allow multiple values in filters
script.js
script.js
$(function() { var app = angular.module('app', []); app.filter('slugify', function() { return function(input) { return input.replace(/[^\w]/g, '').replace(/\s+/g, '-').toLowerCase(); }; }); app.controller('Ctrl', function($scope, $http, $location, $filter) { var all = []; $http.get('data.tsv').then(function(response) { $scope.filters = { }; var reverseFilters = {}; $scope.data = d3.tsv.parse(response.data, (function() { var essentialColumns = ['Titre', 'Chapo', 'Date', 'Lien']; return function(d) { d.Date = new Date(d.Date.split('/').reverse()); // Transform date into Date object // Get filters _.each(d, function(value, key) { if (essentialColumns.indexOf(key) < 0 && value.length > 0) { if ($scope.filters[key] == null) { // Init filter reverseFilters[$filter('slugify')(key)] = key; $scope.filters[key] = { values: ['--'], value: $location.search()[$filter('slugify')(key)] || '--', // Try to load value from URL before using default slug: $filter('slugify')(key) }; } $scope.filters[key].values = _.uniq([value].concat($scope.filters[key].values)); } }); return d; }; })()); // Make sure we're only using existing values _.each($scope.filters, function(filter, key) { if (filter.values.indexOf(filter.value) < 0) { filter.value = '--'; // Reset to default } }); all = _.clone($scope.data); $scope.filter(); }); $scope.filter = function() { var template = { }; _.each($scope.filters, function(filter, key) { if (filter.value !== '--') { template[key] = filter.value; } }); $scope.data = _(_.clone(all)).filter(template).sortByOrder('Date', 'desc').run(); }; $scope.updateURLAndFilter = function() { // Update URL _.each($scope.filters, function(filter, key) { $location.search(filter.slug, filter.value === '--' ? null : filter.value); }); // And filter $scope.filter(true); }; $scope.reset = function() { // Reset every filter _.each($scope.filters, function(filter) { filter.value = '--'; }); $scope.updateURLAndFilter(); }; }); });
JavaScript
0.000002
@@ -902,24 +902,95 @@ ngth %3E 0) %7B%0A + d%5Bkey%5D = _.map(value.split(','), _.trim);%0A%0A @@ -1622,14 +1622,13 @@ niq( -%5Bvalue +d%5Bkey %5D.co @@ -2351,16 +2351,17 @@ %5Bkey%5D = +%5B filter.v @@ -2364,16 +2364,17 @@ er.value +%5D ;%0A
263fdcc3ea8812fd47a505db70dbe0373d8c8f62
Fix bug where last entry would not show.
script.js
script.js
$( document ).ready(function() { var $form = $("form#wiki"); var $output = $('#articles'); var $outputElement = $('<p>'); var pageids = []; /* Setup button handler */ $form.submit(function( event ) { event.preventDefault(); var start_article = $(this).find("input[type=text]").val(); console.log( "Start: ", start_article ); pageids = []; $output.empty(); getWikiSentence(start_article); }); /* Returns the query URL for the Wikipedia API of a given page */ function wikiApiUrl(page) { var wiki_api_base = "https://en.wikipedia.org/w/api.php?" params = { action: "parse", format: "json", page: page, redirects: 1, prop: "text", section: 0, disablelimitreport: 1, disableeditsection: 1, disabletoc: 1, noimages: 1 } /* "callback=?" makes jquery pick a custom name for the callback. JQuery then knows to set the datatype to JSONP. The server wraps the requested JSON in a function call with the callback's name.*/ return wiki_api_base + $.param(params) + "&callback=?"; } /* Returns a parsed structure queryable with JQuery from an HTML string */ function parseToDOM(html_string) { // http://stackoverflow.com/questions/15403600 return $($.parseHTML('<div>' + html_string + '</div>')); } /* Return HTML without elements that should not be rendered */ function cleanWikiHTML(html_string) { temp_dom = parseToDOM(html_string); temp_dom = temp_dom.children('p'); // Remove References of the form '[1]'' temp_dom.children('sup').remove(); // The box showing coordinates is part of the main html temp_dom.find('span#coordinates').remove(); var html = ''; temp_dom.each(function() { html += $(this).html() + ' '; }); return html } /* Returns a text up to a sentence that ends with an <a> tag */ function parseForSentence(html_string) { var divider = '</a>.'; split = html_string.split(divider); if ( split.length == 1 ) { divider = '</a>).'; split = html_string.split(divider); if ( split.length == 1 ) { console.log('No link at the end of a sentence found.') return null } } //TODO make "ADD-level" configurable, e.g. use last possible link return split[0] + divider; } /* Return the name of the page linked to from the last <a> tag */ function getNextEntryName(sentence_dom) { //TODO use first link and cut of the sentence to make it properly ADD. var last_a = sentence_dom.children('a:last'); var next_entry = last_a.attr('href').split('/wiki/')[1]; console.log('Next: ', last_a.attr('title')); return next_entry } /* Append text to the page */ function appendSentences(sentence_dom, include_markup) { if ( include_markup ) { sentence = sentence_dom.html(); } else { sentence = sentence_dom.text(); } $output.append( $outputElement.clone().html(sentence) ); } /* Return whether the id was already queried, also stores passed ids */ function isRepetition(page_id) { if ( pageids.indexOf(page_id) > -1 ) { console.log('Repetition detected.'); return true } pageids.push(page_id); return false } function getWikiSentence(page_title){ var query_url = wikiApiUrl(page_title); console.log(query_url); //TODO save API results to localStorage for caching $.getJSON( query_url ) .done(function(data){ if ( isRepetition(data.parse.pageid) ) { return } var html = cleanWikiHTML(data.parse.text["*"]); var sentence = parseForSentence(html); if (sentence === null) { return } var sentence_dom = parseToDOM(sentence); // TODO checkbox for include_markup appendSentences(sentence_dom, true); var next_entry = getNextEntryName(sentence_dom); getWikiSentence(next_entry); }) .fail(function() { console.log("Error: ", query_url); }); } });
JavaScript
0
@@ -2073,19 +2073,75 @@ %09%09%09%09 -return null +// false: No next wiki page available%0A%09%09%09%09return %5Bsplit%5B0%5D, false%5D; %0A%09%09%09 @@ -2214,16 +2214,68 @@ le link%0A +%09%09// true: Continue, sentence has a link at the end%0A %09%09return @@ -2275,16 +2275,17 @@ %09return +%5B split%5B0%5D @@ -2294,16 +2294,23 @@ divider +, true%5D ;%0A%09%7D%0A%0A%09/ @@ -3512,24 +3512,25 @@ %09%09%09%09var +%5B sentence = parse @@ -3521,16 +3521,39 @@ sentence +, next_entry_available%5D = parse @@ -3575,46 +3575,8 @@ l);%0A -%09%09%09%09if (sentence === null) %7B return %7D%0A %09%09%09%09 @@ -3693,24 +3693,68 @@ dom, true);%0A +%09%09%09%09if ( !next_entry_available ) %7B return %7D%0A %09%09%09%09var next
0bed76f5ab3dd1cda9304226ed09206812887064
Update gruppoc.js
js/gruppoc.js
js/gruppoc.js
gruppo.innerHTML ="<h3>26/5/2017 - Nuovo Badge</h1>Aggiunto un nuovo Badge: il Badge Navigatore. Si ottiene navigando nella piattaforma on line del corso per referenti di sostegno. Il tempo trascorso on line lo potete vedere del registro presenze." gruppo.innerHTML += "<iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/Il4zpiGLxq0\" frameborder=\"0\" allowfullscreen></iframe></p><p><iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/hJdG664iams\" frameborder=\"0\" allowfullscreen></iframe></p><p><iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/hfRKsYbt4S0\" frameborder=\"0\" allowfullscreen></iframe>"
JavaScript
0.000001
@@ -242,16 +242,168 @@ senze.%22%0A +gruppo.innerHTML += %22%3Cimg src='http://www.alberghierocastelnuovocilento.gov.it/moodlekeys/pluginfile.php/41/badges/badgeimage/26/f1?refresh=9437'%3E%3Cbr%3E%22%0A gruppo.i
4f5cfd6e63e7287669573ebce4a70c7d87428e25
Add an externally available deselection
src/tools/tool.select.js
src/tools/tool.select.js
/** * @file Tool definition for the PC dual purpose selection tool. Provides event * handlers and special logic for the selection tool ONLY. Allows selection of * entire objects, rotation, scaling and node/segment adjustment. **/ "use strict"; module.exports = function(paper) { var tool = new paper.Tool(); // Paper global extenders var Path = paper.Path; var Point = paper.Point; var Rectangle = paper.Rectangle; var project = paper.project; // Handy internal vars var selectionRectangle = null; var selectionRectangleScale = null; var selectionRectangleRotation = null; var segment, path; var hitOptions = { segments: true, stroke: true, fill: true, tolerance: 5 }; // Tool identification (for building out tool palette) tool.name = 'tools.select'; tool.key = 'select'; tool.onMouseDown = function(event) { segment = path = null; var hitResult = project.hitTest(event.point, hitOptions); // If we didn't hit anything with hitTest... if (!hitResult) { // Find any items that are Paths (not layers) that contain the point var item = getBoundSelection(event.point); // If we actually found something, fake a fill hitResult if (item) { hitResult = { type: 'fill', // SURE it is ;) item: item }; } else { // Deselect if nothing clicked (feels natural for deselection) if (selectionRectangle !== null) { selectionRectangle.remove(); } return; } } if (event.modifiers.shift) { if (hitResult.type === 'segment') { hitResult.segment.remove(); } return; } if (hitResult) { path = hitResult.item; if (hitResult.type === 'segment') { if (selectionRectangle !== null && path.name === "selection rectangle") { if (hitResult.segment.index >= 2 && hitResult.segment.index <= 4) { // Rotation hitbox selectionRectangleRotation = 0; } else { // Scale hitbox selectionRectangleScale = event.point.subtract(selectionRectangle.bounds.center).length / path.scaling.x; } } else { segment = hitResult.segment; } } else if (hitResult.type === 'stroke' && path !== selectionRectangle) { var location = hitResult.location; segment = path.insert(location.index + 1, event.point); //path.smooth(); } if ((selectionRectangle === null || selectionRectangle.ppath !== path) && selectionRectangle !== path) { initSelectionRectangle(path); } } else { // Nothing hit if (selectionRectangle !== null) selectionRectangle.remove(); } // If a fill hit, move the path if (hitResult.type === 'fill') { project.activeLayer.addChild(hitResult.item); } }; tool.onMouseDrag = function(event) { if (selectionRectangleScale !== null) { // Path scale adjustment var ratio = event.point.subtract(selectionRectangle.bounds.center).length / selectionRectangleScale; var scaling = new Point(ratio, ratio); selectionRectangle.scaling = scaling; selectionRectangle.ppath.scaling = scaling; return; } else if (selectionRectangleRotation !== null) { // Path rotation adjustment var rotation = event.point.subtract(selectionRectangle.pivot).angle + 90; selectionRectangle.ppath.rotation = rotation; selectionRectangle.rotation = rotation; return; } if (segment) { // Individual path segment position adjustment segment.point.x += event.delta.x; segment.point.y += event.delta.y; // Smooth -only- non-polygonal paths if (!path.isPolygonal) path.smooth(); initSelectionRectangle(path); } else if (path) { // Path translate position adjustment if (path !== selectionRectangle) { path.position.x += event.delta.x; path.position.y += event.delta.y; selectionRectangle.position.x += event.delta.x; selectionRectangle.position.y += event.delta.y; } else { selectionRectangle.position.x += event.delta.x; selectionRectangle.position.y += event.delta.y; selectionRectangle.ppath.position.x += event.delta.x; selectionRectangle.ppath.position.y += event.delta.y; } } }; tool.onMouseMove = function(event) { project.activeLayer.selected = false; var boundItem = getBoundSelection(event.point); if (event.item) { event.item.selected = true; paper.setCursor('copy'); } else if (boundItem) { boundItem.selected = true; paper.setCursor('move'); } else { paper.setCursor(); } if (selectionRectangle) { selectionRectangle.selected = true; } }; tool.onMouseUp = function(event) { selectionRectangleScale = null; selectionRectangleRotation = null; }; tool.onKeyDown = function (event) { if (event.key === 'delete' && selectionRectangle) { selectionRectangle.ppath.remove(); selectionRectangle.remove(); selectionRectangle = null; } }; function initSelectionRectangle(path) { if (selectionRectangle !== null) selectionRectangle.remove(); var reset = path.rotation === 0 && path.scaling.x === 1 && path.scaling.y === 1; var bounds; if (reset) { // Actually reset bounding box bounds = path.bounds; path.pInitialBounds = path.bounds; } else { // No bounding box reset bounds = path.pInitialBounds; } var b = bounds.clone().expand(10, 10); selectionRectangle = new Path.Rectangle(b); selectionRectangle.pivot = selectionRectangle.position; selectionRectangle.insert(2, new Point(b.center.x, b.top)); selectionRectangle.insert(2, new Point(b.center.x, b.top - 25)); selectionRectangle.insert(2, new Point(b.center.x, b.top)); if (!reset) { selectionRectangle.position = path.bounds.center; selectionRectangle.rotation = path.rotation; selectionRectangle.scaling = path.scaling; } selectionRectangle.strokeWidth = 2; selectionRectangle.strokeColor = 'blue'; selectionRectangle.name = "selection rectangle"; selectionRectangle.selected = true; selectionRectangle.ppath = path; selectionRectangle.ppath.pivot = selectionRectangle.pivot; } function getBoundSelection(point) { // Check for items that are overlapping a rect around the event point var items = project.getItems({ overlapping: new Rectangle(point.x - 2, point.y - 2,point.x + 2, point.y + 2) }); var item = null; _.each(items, function (i) { if (i instanceof Path) { if (i.contains(point)) { item = i; } } }); return item; } };
JavaScript
0
@@ -712,16 +712,138 @@ 5%0A %7D;%0A%0A + // Externalize deseletion%0A paper.deselect = function() %7B%0A if (selectionRectangle) selectionRectangle.remove();%0A %7D%0A%0A // Too
d654e71867b585b1ebf564891253999d710fdfc6
Fix placeholder being shown instead of selected value on rerender
dist/index.js
dist/index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Dropdown = function (_Component) { _inherits(Dropdown, _Component); function Dropdown(props) { _classCallCheck(this, Dropdown); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Dropdown).call(this, props)); _this.state = { selected: props.value || { label: props.placeholder || 'Select...', value: '' }, isOpen: false }; _this.mounted = true; _this.handleDocumentClick = _this.handleDocumentClick.bind(_this); _this.fireChangeEvent = _this.fireChangeEvent.bind(_this); return _this; } _createClass(Dropdown, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(newProps) { if (newProps.value && newProps.value !== this.state.selected) { this.setState({ selected: newProps.value }); } else if (newProps.placeholder) { this.setState({ selected: { label: newProps.placeholder, value: '' } }); } } }, { key: 'componentDidMount', value: function componentDidMount() { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, false); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.mounted = false; document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, false); } }, { key: 'handleMouseDown', value: function handleMouseDown(event) { if (event.type === 'mousedown' && event.button !== 0) return; event.stopPropagation(); event.preventDefault(); this.setState({ isOpen: !this.state.isOpen }); } }, { key: 'setValue', value: function setValue(value, label) { var newState = { selected: { value: value, label: label }, isOpen: false }; this.fireChangeEvent(newState); this.setState(newState); } }, { key: 'fireChangeEvent', value: function fireChangeEvent(newState) { if (newState.selected !== this.state.selected && this.props.onChange) { this.props.onChange(newState.selected); } } }, { key: 'renderOption', value: function renderOption(option) { var _classNames; var optionClass = (0, _classnames2.default)((_classNames = {}, _defineProperty(_classNames, this.props.baseClassName + '-option', true), _defineProperty(_classNames, 'is-selected', option === this.state.selected), _classNames)); var value = option.value || option.label || option; var label = option.label || option.value || option; return _react2.default.createElement( 'div', { key: value, className: optionClass, onMouseDown: this.setValue.bind(this, value, label), onClick: this.setValue.bind(this, value, label) }, label ); } }, { key: 'buildMenu', value: function buildMenu() { var _this2 = this; var _props = this.props; var options = _props.options; var baseClassName = _props.baseClassName; var ops = options.map(function (option) { if (option.type === 'group') { var groupTitle = _react2.default.createElement( 'div', { className: baseClassName + '-title' }, option.name ); var _options = option.items.map(function (item) { return _this2.renderOption(item); }); return _react2.default.createElement( 'div', { className: baseClassName + '-group', key: option.name }, groupTitle, _options ); } else { return _this2.renderOption(option); } }); return ops.length ? ops : _react2.default.createElement( 'div', { className: baseClassName + '-noresults' }, 'No options found' ); } }, { key: 'handleDocumentClick', value: function handleDocumentClick(event) { if (this.mounted) { if (!_reactDom2.default.findDOMNode(this).contains(event.target)) { this.setState({ isOpen: false }); } } } }, { key: 'render', value: function render() { var _classNames2; var baseClassName = this.props.baseClassName; var placeHolderValue = typeof this.state.selected === 'string' ? this.state.selected : this.state.selected.label; var value = _react2.default.createElement( 'div', { className: baseClassName + '-placeholder' }, placeHolderValue ); var menu = this.state.isOpen ? _react2.default.createElement( 'div', { className: baseClassName + '-menu' }, this.buildMenu() ) : null; var dropdownClass = (0, _classnames2.default)((_classNames2 = {}, _defineProperty(_classNames2, baseClassName + '-root', true), _defineProperty(_classNames2, 'is-open', this.state.isOpen), _classNames2)); return _react2.default.createElement( 'div', { className: dropdownClass }, _react2.default.createElement( 'div', { className: baseClassName + '-control', onMouseDown: this.handleMouseDown.bind(this), onTouchEnd: this.handleMouseDown.bind(this) }, value, _react2.default.createElement('span', { className: baseClassName + '-arrow' }) ), menu ); } }]); return Dropdown; }(_react.Component); Dropdown.defaultProps = { baseClassName: 'Dropdown' }; exports.default = Dropdown;
JavaScript
0
@@ -2954,24 +2954,43 @@ %7D else if ( +!newProps.value && newProps.pla
0ec5383ea4506399be04713c0809f948dd053e38
Change boolean-based options to real booleans
js/hipchat.js
js/hipchat.js
(function() { // Creates an iframe with an embedded HipChat conversation window. // // Options: // url - The url to the room to embed; required // el - The container in which to insert the HipChat panel; required // timezone - The timezone to use in the embedded room; required // width - The width of the iframe; defaults to 100% // height - The height of the iframe; defaults to 400px var parametize = function(params) { var key, toks = []; for (key in params) { toks.push(key + '=' + params[key]); } return toks.join('&'); }; return this.HipChat = function(options) { if (options && options.url && options.el && options.timezone) { var el = document.querySelector(options.el); if (!el) return; var params = { anonymous: 0, timezone: options.timezone, minimal: 1 }; var url = options.url + (options.url.indexOf('?') > 0 ? '&' : '?') + parametize(params); if (url.indexOf('https://') !== 0) { url = 'https://' + url; } var w = options.width || '100%'; var h = options.height || 600; el.innerHTML = '<iframe src="' + url + '" frameborder="' + 0 + '" width="' + w + '" height="' + h + '"></iframe>'; } }; })();
JavaScript
0.999921
@@ -887,17 +887,21 @@ nymous: -0 +false ,%0A @@ -963,17 +963,20 @@ inimal: -1 +true %0A
bf06b9dc4a2508b05c6e7da3b0d8a66a58c04f15
Remove redundant `? true : false`
dist/layzr.js
dist/layzr.js
(function(root, factory) { if(typeof define === 'function' && define.amd) { define([], factory); } else if(typeof exports === 'object') { module.exports = factory(); } else { root.Layzr = factory(); } }(this, function() { 'use strict'; // CONSTRUCTOR function Layzr( options ) { // debounce this._lastScroll = 0; this._ticking = false; // options this._optionsAttr = options.attr || 'data-layzr'; this._optionsAttrRetina = options.retinaAttr || 'data-layzr-retina'; this._optionsThreshold = options.threshold || 0; this._optionsCallback = options.callback || null; // properties this._retina = window.devicePixelRatio > 1 ? true : false; this._imgAttr = this._retina ? this._optionsAttrRetina : this._optionsAttr; // images nodelist this._images = document.getElementsByTagName('img'); // call to create document.addEventListener('DOMContentLoaded', this._create.bind(this), false); } // DEBOUNCE METHODS // adapted from: http://www.html5rocks.com/en/tutorials/speed/animations/ Layzr.prototype._requestScroll = function() { this._lastScroll = window.scrollY || window.pageYOffset; this._requestTick(); } Layzr.prototype._requestTick = function() { if(!this._ticking) { requestAnimationFrame(this.update.bind(this)); this._ticking = true; } } // Layzr METHODS Layzr.prototype._create = function() { // fire scroll event once this._requestScroll(); // bind scroll and resize event window.addEventListener('scroll', this._requestScroll.bind(this), false); window.addEventListener('resize', this._requestScroll.bind(this), false); } Layzr.prototype._destroy = function() { // possibly remove attributes, and set all sources? // unbind scroll and resize event window.removeEventListener('scroll', this._requestScroll.bind(this), false); window.removeEventListener('resize', this._requestScroll.bind(this), false); } // offset helper // borrowed from: http://stackoverflow.com/questions/5598743/finding-elements-position-relative-to-the-document Layzr.prototype._getOffset = function( element ) { var offsetTop = 0; do { if(!isNaN(element.offsetTop)) { offsetTop += element.offsetTop; } } while (element = element.offsetParent); return offsetTop; } Layzr.prototype._inViewport = function( imageNode ) { // get viewport top and bottom offset var viewportTop = this._lastScroll; var viewportBottom = viewportTop + window.innerHeight; // get image top and bottom offset var elementTop = this._getOffset(imageNode); var elementBottom = elementTop + imageNode.offsetHeight; // calculate threshold, convert percentage to pixel value var threshold = (this._optionsThreshold / 100) * window.innerHeight; // return if element in viewport return elementBottom >= viewportTop - threshold && elementBottom <= viewportBottom + threshold; } Layzr.prototype.update = function() { // cache image nodelist length var imagesLength = this._images.length; // loop through images for(var i = 0; i < imagesLength; i++) { // cache image var image = this._images[i]; // check if image has attribute if(image.hasAttribute(this._imgAttr) || image.hasAttribute(this._optionsAttr)) { // check if image in viewport if(this._inViewport(image)) { // reveal image this.reveal(image); } } } // allow for more animation frames this._ticking = false; } Layzr.prototype.reveal = function( imageNode ) { // get image source var source = imageNode.getAttribute(this._imgAttr) || imageNode.getAttribute(this._optionsAttr); // remove image data attributes imageNode.removeAttribute(this._optionsAttr); imageNode.removeAttribute(this._optionsAttrRetina); // set image source, if it has one if(source) { imageNode.setAttribute('src', source); // call the callback if(typeof this._optionsCallback === 'function') { // this will be the image node in the callback this._optionsCallback.call(imageNode); } } } return Layzr; }));
JavaScript
0.001107
@@ -688,23 +688,8 @@ %3E 1 - ? true : false ;%0A
c218779a9c87700f4c38cb2d7d3ab2abf3a603f1
Fix map controls
js/mapView.js
js/mapView.js
//Declare API access Token mapboxgl.accessToken = 'pk.eyJ1IjoibGl6emllZ29vZGluZyIsImEiOiJjaW92cmc1NHYwMWJsdW9tOHowdTA2cnFsIn0.lFq-Wju99kZ_dR_2TMBYCQ'; //Initialize a new map object inside of the #map div function initMap(callback, initialSalary, source){ console.log('initMap'); window.map = new mapboxgl.Map({ container: 'map', //HTML element to initialize the map in (or element id as string) zoom: 3.15, minZoom: 1, //Default of 0 (world) maxZoom: 12, //Default of 20 (local) center: [-80.7129,40.0902], //LatLng array in decimal degrees style: 'mapbox://styles/lizziegooding/ciq1cofi8003ybknqhk5pfruz' //Basemap style; can be a preset from mapbox or a user defined style }); // map.addControl(new mapboxgl.Navigation()); map.addControl(new mapboxgl.Navigation({position: 'bottom-left'})); //Once the map has loaded map.on('load', function () { console.log('load data'); //Create new GeoJSON layer 'affordCountyMHV' map.addSource('affordCountyMHV', { 'type': 'geojson', 'data': affordCountyMHV }); map.addSource('counties', { 'type': 'vector', 'url': 'mapbox://mapbox.82pkq93d' }); //Add loaded data and style map.addLayer({ 'id': 'affordCountyMHV', 'type': 'fill', 'source': 'affordCountyMHV', 'source-layer': 'affordCountyMHV', 'layout': { visibility: 'visible'}, 'paint': { 'fill-color': '#FFF', // property: 'aPayment', // stops: [ // Greens ['#edf8e9','#bae4b3','#74c476','#238b45'] // Reds ['#fee5d9','#fcae91','#fb6a4a','#cb181d'] // [0, '#238b45'], //0-15% affordable // [8100, '#74c476'], //16-20% affordable // [10800, '#bae4b3'], //21-25% affordable // [13500, '#edf8e9'], //26-30% affordable // [16200, '#fee5d9'], //31-35% unaffordable // [18900, '#fcae91'], //36-40% unaffordable // [21600, '#fb6a4a'], //41-45% unaffordable // [24300, '#cb181d'], //>45% unaffordable // ] // }, 'fill-opacity': 1} },'admin-3-4-boundaries-bg'); console.log('Added main affordCountyMHV layer'); map.addLayer({ 'id': 'counties', 'type': 'fill', 'source': 'counties', 'source-layer': 'original', 'paint': { 'fill-color': 'rgba(0,0,0,0)' } }); map.addLayer({ 'id': 'counties-highlighted', 'type': 'fill', 'source': 'counties', 'source-layer': 'original', 'paint': { 'fill-color': '#FFF', 'fill-opacity': 0.7 }, 'filter': ['in', 'FIPS', ''] }); // Create a new popup var popup = new mapboxgl.Popup({ closeButton: false, closeOnClick: false }); map.on('mousemove', function(e) { var features = map.queryRenderedFeatures(e.point, { layers: ['counties'] }); if (features.length) { map.setFilter('counties-highlighted', ['==', 'FIPS', features[0].properties.FIPS]); } else { map.setFilter('counties-highlighted', ['==', 'FIPS', '']); } var affordCountyMHVfeatures = map.queryRenderedFeatures(e.point, { layers: ['affordCountyMHV'] }); if (!affordCountyMHVfeatures.length) { popup.remove(); return; } var feature = affordCountyMHVfeatures[0]; // Populate the popup and set its coordinates // based on the feature found. popup.setLngLat(map.unproject(e.point)) .setHTML('<b>' + feature.properties.Geography + '</b>' + '<br>Median Home Value (Census 2014): $' + parseInt(feature.properties.Median_Hom).toLocaleString('en-US') + '<br>Median Home Value (Zillow 2015): $' + feature.properties.ZHVI.toLocaleString('en-US') ) .addTo(map); }); callback(initialSalary, source); // } });//END onLoad }
JavaScript
0.000001
@@ -465,18 +465,17 @@ axZoom: -12 +9 , //Defa
bff7636d9936fef6905b07b3c8d1c82309de873d
Fix i18n import
src/translation/index.js
src/translation/index.js
import {t, init} from 'i18next'; export default { translate: t, init };
JavaScript
0.000019
@@ -23,16 +23,23 @@ 'i18next +-client ';%0A%0Aexpo
278193fd07101d0f0c92c88892731b144a02f770
fix card url
js/overlay.js
js/overlay.js
/* global TrelloPowerUp */ var Promise = TrelloPowerUp.Promise; var t = TrelloPowerUp.iframe(); var gFormUrl = ''; var cardName = ''; var cardShortLink = ''; var userName = t.arg('user'); // this function we be called once on initial load // and then called each time something changes t.render(function(){ return Promise.all([ t.get('board', 'shared', 'url'), t.card('name', 'shortLink') ]) .spread(function(savedGFormUrl, cardData){ if(savedGFormUrl){ gFormUrl = savedGFormUrl; } else { document.getElementById('overlay-message') .textContent = 'Please add form url on settings'; } if(cardData){ cardName = cardData.name; cardUrl = cardData.shortLink; } }) .then(function(){ document.getElementsByTagName('iframe')[0].src = gFormUrl + "?embedded=true&entry.995291397=" + cardName + "&entry.33315152=" + userName + "&entry.1600294234" + cardUrl; }) }); // close overlay if user clicks outside our content document.addEventListener('click', function(e) { if(e.target.tagName == 'BODY') { t.closeOverlay().done(); } }); // close overlay if user presses escape key document.addEventListener('keyup', function(e) { if(e.keyCode == 27) { t.closeOverlay().done(); } });
JavaScript
0.000001
@@ -382,25 +382,19 @@ name', ' -shortLink +url ')%0A %5D)%0A @@ -696,17 +696,11 @@ ata. -shortLink +url ;%0A @@ -901,16 +901,17 @@ 00294234 += %22 + card
93dc8cc1043b757c2cb1215d82335a7328781245
Add pcr module initiation
src/pcr.js
src/pcr.js
var express = require('express'); var path = require('path'); var PCR = require('pcr'); var app = express(); app.set('port', process.env.PORT || 3000); app.set('view engine', 'ejs'); app.use(express.static('public')); app.get('/', (req, res) => { res.render('index'); }); app.listen(app.get('port'), () => { console.log('Server running on port ' + app.get('port')); });
JavaScript
0
@@ -82,16 +82,95 @@ pcr');%0A%0A +var TOKEN = process.env.PCR_AUTH_TOKEN %7C%7C 'public';%0Avar pcr = new PCR(TOKEN);%0A%0A var app
2878330894a28fd0a7ad3bf5e0f21f9cea3265a3
Improve element check + include scroll position object to set the current scrolling position
scroll.js
scroll.js
import viewport from './viewport'; /** * Find the current scroll position of a HTML Element * @param {HTMLElement|window} [elm = viewport] - The HTML element to find the scrolling position from * @return {Object} - The current scroll information */ export default function scroll(elm = viewport) { // Take the viewport if window is the element if(elm === window) { elm = viewport; } const width = elm.offsetParent ? elm.offsetWidth : window.innerWidth; const height = elm.offsetParent ? elm.offsetHeight : window.innerHeight; return { top: elm.scrollTop, maxTop: elm.scrollHeight - height, left: elm.scrollLeft, leftMax: elm.scrollWidth - width }; }
JavaScript
0
@@ -27,16 +27,185 @@ ewport'; +%0Aimport size from './size';%0Aimport isObject from './isObject';%0Aimport isWindow from './isWindow';%0Aimport isDOMElement from './isDOMElement';%0Aimport inDOM from './inDOM'; %0A%0A/**%0A * @@ -458,255 +458,710 @@ m = -viewport) %7B%0A // Take the viewport if window is the element%0A +window, scrollPos = null) %7B%0A let isWin = isWindow(elm);%0A%0A if(!isWin) %7B%0A if(isObject(elm)) %7B %5Belm, scrollPos%5D = %5Bwindow, elm%5D; %7D%0A%0A if(isDOMElement(elm, 'html', 'body')) %7B elm = elm.ownerDocument; %7D%0A + if( -elm === window) %7B elm = viewport; %7D%0A%0A const width = elm.offsetParent ? elm.offsetWidth : window.innerWidth;%0A const height = elm.offsetParent ? elm.offsetHeight : window.innerHeight +typeof elm.defaultView !== 'undfined') %7B elm = elm.defaultView; %7D%0A%0A isWin = isWindow(elm);%0A%0A if(!(isDOMElement(elm) && inDOM(elm)) %7C%7C isWin) %7B return null; %7D%0A %7D%0A%0A const view = isWin ? viewport(elm) : elm;%0A%0A if(scrollPos) %7B%0A const %7B byX, byY, x, y %7D = scrollPos;%0A%0A if(!isNaN(x)) %7B view.scrollTop = x; %7D%0A else if(!isNaN(byX)) %7B view.scrollTop += byX; %7D%0A%0A if(!isNaN(y)) %7B view.scrollTop = y; %7D%0A else if(!isNaN(byY)) %7B view.scrollTop += byY; %7D%0A %7D%0A%0A const s = size(elm) ;%0A%0A @@ -1178,129 +1178,133 @@ -top: elm +x: view .scroll -Top +Left ,%0A -maxTop: elm.scrollHeight - height,%0A left: elm +xMax: s.contentWidth - s.innerWidth,%0A y: view .scroll -Left +Top ,%0A -left +y Max: -elm.scrollWidth - width +s.contentHeight - s.innerHeight %0A %7D
c35681ea6b8a6e0a0d1c3e6f9b86f161767a1d41
Handle jQuery in noConflict mode.
js/scripts.js
js/scripts.js
// DOM Ready $(function() { // SVG fallback // toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update if (!Modernizr.svg) { var imgs = document.getElementsByTagName('img'); for (var i = 0; i < imgs.length; i++) { if (/.*\.svg$/.test(imgs[i].src)) { imgs[i].src = imgs[i].src.slice(0, -3) + 'png'; } } } });
JavaScript
0
@@ -6,17 +6,38 @@ M Ready%0A -$ +jQuery(document).ready (functio @@ -38,16 +38,17 @@ unction( +$ ) %7B%0A%0A%09//
e4d905bd08aea8a3295f8da41997edb1784c7262
Make types strict-local.
src/utils/testHelpers.js
src/utils/testHelpers.js
/* @flow */ import type { Narrow } from '../types'; export const navStateWithNarrow = (narrow: Narrow): Object => ({ nav: { index: 0, routes: [ { routeName: 'chat', params: { narrow, }, }, ], }, }); export const defaultNav = { index: 0, routes: [{ routeName: 'chat' }], }; export const otherNav = { index: 1, routes: [{ routeName: 'main' }, { routeName: 'account' }], };
JavaScript
0
@@ -2,16 +2,29 @@ * @flow +strict-local */%0Aimpor @@ -115,14 +115,24 @@ w): -Object +%7B%7C nav: mixed %7C%7D =%3E
4af0f0809a5c23f733dde4d08994a10c6ca62262
Add author and license comment
src/videojs-playcount.js
src/videojs-playcount.js
import videojs from 'video.js'; /** * A video.js plugin to handle basic play counting for videos. By default, a * `played` event will be triggered on the player if the video has played for a * cumulative 10% of its total video length. * * Options * playTimer: Number of seconds necessary for a view to be considered a play. * Note that this takes precedence over `playTimerPercent`. If the * given video is shorter than `playTimer`, no plays will be * counted. * playTimerPercent: Percentage (as a decimal between 0 and 1) of a video * necessary for a view to be considered a play. Note that * the `playTimer` option takes precedence. * * Limitations * This is only intended for basic play counting. Anyone with familiarity with * JavaScript and a browser console could adjust values to artificially inflate * the play count. */ const playcount = function(options) { this.ready(function() { options = options || {}; this.on('play', play); this.on('pause', pause); }); var playtime = 0; var neededPlaytime, played, timer; function play() { var player = this; calculateNeededPlaytime(this.duration()); // If the video has been restarted at 0 and was already played, reset the // played flag to allow multiple plays if (played && this.currentTime() === 0) { resetInterval(); played = false; playtime = 0; } // If the video hasn't completed a play (and no timer is running), set up a // timer to track the play time. if (!timer && !played) { // Round everything to 500ms. Every time this interval ticks, add .5s to // the total counted play time. Once we hit the needed play time for a // play, trigger a 'played' event. timer = setInterval(function() { playtime += 0.5; if (playtime >= neededPlaytime) { played = true; player.trigger('played'); resetInterval(); } }, 500); } } // On pause, reset the current timer function pause() { if (timer) resetInterval(timer); } // Clear and nullify the timer function resetInterval() { clearInterval(timer); timer = null; } // Calculate the needed playtime based on any provided options. function calculateNeededPlaytime(duration) { // TODO: Move 0.1 to defaults for playTimerPercent and merge defaults with options var percent = options.playTimerPercent || 0.1; neededPlaytime = neededPlaytime || options.playTimer || (duration * percent); } }; // Register the plugin with video.js. videojs.plugin('playcount', playcount); export default playcount;
JavaScript
0
@@ -235,16 +235,74 @@ gth.%0A *%0A + * Author: Nick Pafundi / Clover Sites%0A * License: MIT%0A *%0A * Optio
9e104db2e1eea685f0f50e8a46b2a91c3b5b2755
Send error messages back to Slack
server.js
server.js
var config = require('config'); var express = require('express'); var bodyParser = require('body-parser'); var ircdispatcher = require('./lib/ircdispatcher'); var messageparser = require('./lib/messageparser'); var l = require('./lib/log')('Server'); var db = require('./lib/db'); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.post('/toirc', function(req, res){ l.debug('Got incoming msg to IRC: ', req.body); messageparser.parseIrcMessage(req.body) .then(function(message) { return ircdispatcher.postMessage(message); }) .then(function(result) { if (result && result.sent) l.verbose('IRC message sent to IRC server'); res.status(200).end(); }, function error (e) { if (e.name !== 'HttpError') l.error('%s\nStack: "%s"', e.toString(), e.stack); res.status(e.statusCode); }) .done(); }); var server = app.listen(config.server.port, function() { db.load(); l.info('Listening on port ' + config.server.port); });
JavaScript
0
@@ -742,9 +742,9 @@ ame -! += == ' @@ -754,16 +754,147 @@ pError') + %7B%0A // Send 200 so that Slack will display the message%0A res.status(200).json(%7Btext: 'Error: ' + e.message%7D);%0A %7D else %7B %0A l @@ -943,24 +943,26 @@ stack);%0A + res.status(e @@ -964,22 +964,19 @@ tus( -e.statusCode); +500);%0A %7D %0A %7D
905db33e46a66a30c8de268238b4ed4e22751936
use time from event
server.js
server.js
var env = process.env.NODE_ENV || 'development'; var express = require('express'); var compression = require('compression'); var bodyParser = require('body-parser'); var redis = require('redis'); var request = require('request'); var chunk = require('lodash/chunk'); var find = require('lodash/find'); var redisURL = process.env.REDIS_URL; var client = redis.createClient(redisURL); client.flushall(); var app = express(); app.set('port', (process.env.PORT || 3000)); app.use(compression({ level: 9 })); app.use(bodyParser.json()); app.use(express.static('public')); var forceSSL = function (req, res, next) { // use req.headers.referrer !startsWith https if (req.headers['x-forwarded-proto'] !== 'https') { return res.redirect(['https://', req.get('Host'), req.url].join('')); } return next(); }; if (env === 'production') { app.use(forceSSL); } // Data storage: // // on load: request list of dogs from api // push display_id's onto list // set display_id to dog list response // // on get: if we know about the dog // havent seen detail dog yet? // request detail dog // set detail dog response to display_id // // on post: // // on put: // // // States: // checked in // in office // out of office // missing // checked out var CHECKIN_EXPIRATION_MS = 60 * 5; function getAllDogs(callback) { client.smembers('dogs', function(err, dogs) { var multi = client.multi(); dogs.forEach(function(dogId) { multi.get('dog:' + dogId); multi.get('dog:' + dogId + ':checked_in'); }); multi.exec(function(err, replies) { var dogs = chunk(replies, 2).map(function(d) { var dog = JSON.parse(d[0]); var checkin = JSON.parse(d[1]); return { display_id: dog.display_id, name: dog.name, owner: dog.owner, avatar: dog.avatar, checked_in: checkin }; }); callback(dogs); }); }); } function getDogById(dogId, callback) { var multi = client.multi(); multi.get('dog:' + dogId); multi.get('dog:' + dogId + ':checked_in'); multi.exec(function(err, d) { var dog = JSON.parse(d[0]); var checkin = JSON.parse(d[1]); if (dog) { callback({ display_id: dog.display_id, name: dog.name, owner: dog.owner, avatar: dog.avatar, checked_in: checkin }); } else { callback(); } }); } function storeDogInRedis(dog) { if (dog && dog.btle_devices && dog.btle_devices.length > 0) { var deviceId = dog.btle_devices[0].device_id; client.sadd('dogs', dog.display_id); client.set('dog:' + dog.display_id, JSON.stringify(dog)); client.set('btle_device:' + deviceId + ':dog', dog.display_id); } } function checkinDeviceAtLocationTime(deviceId, location, time, callback) { client.get('btle_device:' + deviceId + ':dog', function(err, dogId) { if (!err && dogId) { // check dog in at last seen hydrant at time var newCheckin = { location: location, time: time }; // TODO check that time is newer than CHECKIN_EXPIRATION_MS in the past // TODO check that time is newer than our last seen checkin // client.get('dog:' + dogId + ':checked_in', function(err, checkin) { // if (!err && checkin) { // // } // }) client.set('dog:' + dogId + ':checked_in', JSON.stringify(newCheckin), function(err, reply) { // set the key to expire after 5 minutes if (!err && reply == 'OK') { client.expire('dog:' + dogId + ':checked_in', CHECKIN_EXPIRATION_MS); callback(true); } else { callback(false); } }); } else { callback(false); } }); } // load data into redis from isl api var token = process.env.ISL_API_TOKEN; request.get({ url: 'https://api.isl.co/api/v1/pets/', headers: { 'Authorization': 'Token ' + token } }, function(error, response, body) { var dogs; if (!error && response.statusCode == 200) { dogs = JSON.parse(body); } else { // read dogs list from fixture dogs = require('./fixtures/dogs.json'); } // set dogs to redis set // set dog to redis key // set btle_device to redis set // set dog:id to btle_device dogs.forEach(function(dog) { if (dog.display_id && dog.pet_link) { // TODO move detail view to list view and remove this // haven't requested dog detail view yet request.get({ url: dog.pet_link, headers: { 'Authorization': 'Token ' + token } }, function(error, response, body) { var dog; if (!error && response.statusCode == 200) { dog = JSON.parse(body); storeDogInRedis(dog); } else { // read dog from fixture dog = require('./fixtures/dog.json'); dog = find(d, { display_id: dog.display_id}); storeDogInRedis(dog); } }); } }); }); app.get('/api/dogs/:display_id', function(req, res) { getDogById(req.params.display_id, function(dog) { if (dog) { res.json(dog); } else { res.status(404).json({ status: 404, textStatus: 'Not Found' }); } }); }); // app.put('/api/dog/:id', function(req, res) { // res.json({ id: req.params.id }); // }); // app.post('/api/dog', function(req, res) { // res.json({ id: 0 }); // }); app.get('/api/dogs', function(req, res) { getAllDogs(function(dogs) { if (dogs.length) { res.json(dogs); } else { res.status(404).json({ status: 404, textStatus: 'Not Found' }); } }); }); app.post('/api/event', function(req, res) { var events = req.body.events; events.forEach(function(event, index) { var device = event.device; var location = event.location; var time = Date.now(); checkinDeviceAtLocationTime(device, location, time, function() { if (index === events.length - 1) { res.json({ status: 200, textStatus: 'OK' }); } }); }); }); // Redis-specific code and configuration client.on('error', function(err) { console.log('Error: ', err); }); // Starting the express server var server = app.listen(app.get('port'), function() { var host = server.address().address; var port = server.address().port; console.log('paw-api listening at http://%s:%s', host, port); });
JavaScript
0.000073
@@ -5817,18 +5817,18 @@ e = -Date.now() +event.time ;%0A%0A
9e60007fd0ff804d9211a58a53437ee887f6491c
replace action of all matching forms
src/patterns/autosubmit.js
src/patterns/autosubmit.js
define([ 'require', '../lib/jquery', '../lib/jquery.form', '../lib/dist/underscore', './inject', './modal' ], function(require) { // those two for error messages var inject = require('./inject'); // can be called on a form or an element in a form var init = function($el) { // get parameters from markup var $form = $el.is('form') ? $el : $el.parents('form').first(), url = $form.attr('action'); // prepare ajax request and submit function var params = { error: function(jqXHR, textStatus, errorThrown) { var msg = [jqXHR.status, textStatus, $form.attr('action')].join(' '), // XXX: error notification pattern! $error = $('<div class="modal"><h3>Error</h3><div class="error message">'+msg+'</div></div>'); inject.append($error, $('body')); console.error(url, jqXHR, textStatus, errorThrown); }, success: function(data, textStatus, jqXHR) { var ourid = $form.attr('id'); if (data && !ourid) { console.warn('Ignored response data because our has no id', $form); return; } var new_action = $(data).find('#' + ourid).attr('action'); if (new_action) { $form.attr({action: new_action}); } } }; var submit = function(event) { $form.ajaxSubmit(params); }; // submit if a (specific) form element changed $el.on("change", submit); // debounced keyup submit, if enabled if ($el.hasClass('auto-submit-keyup')) { ($el.is('input') ? $el : $el.find('input')) .on("keyup", _.debounce(submit, 400)); } $form.on('keyup', function(ev) { if (ev.which === 13) { ev.preventDefault(); submit(ev); } }); // XXX: test whether on webkit and enable only if supported // XXX: add code to check whether the click actually changed // something ($el.is('input[type=search]') ? $el : $el.find('input[type=search]')) .on("click", submit); // allow for chaining return $el; }; var pattern = { markup_trigger: ".auto-submit, .auto-submit-keyup", initialised_class: "auto-submit", init: init }; return pattern; });
JavaScript
0.000001
@@ -1090,34 +1090,78 @@ -var ourid = $form.attr(' +if (!data) return;%0A var $forms = $(data).find('form%5B id +%5D ');%0A @@ -1180,26 +1180,29 @@ -if (data && !ourid +$forms.each(function( ) %7B%0A @@ -1225,180 +1225,225 @@ -console.warn('Ignored response data because our has no id', $form);%0A return;%0A %7D%0A var new_action = $(data).find('#' + ourid) +var $form = $(this),%0A id = $(this).attr('id'),%0A $ourform = $('#' + id);%0A if ($ourform.length %3E 0) %7B%0A $ourform.attr(%7Baction: $form .att @@ -1453,16 +1453,18 @@ action') +%7D) ;%0A @@ -1477,97 +1477,185 @@ -if (new_action) %7B%0A $form.attr(%7Baction: new_action%7D);%0A %7D + %7D else %7B%0A console.warn(%0A 'Ignored form in respone data: not matching id', $form);%0A %7D%0A %7D); %0A
d32380b9b5e10361a9ca0bbd938d50e3900e33be
Fix IE compatibility issue using latest Stanbol service.
src/xdr.js
src/xdr.js
// Based on [Julian Aubourg's xdr.js](https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js) // Internet Explorer 8 & 9 don't support the cross-domain request protocol known as CORS. // Their solution we use is called XDomainRequest. This module is a wrapper for // XDR using jQuery ajaxTransport, jQuery's way to support such cases. // Author: Szaby Grünwald @ Salzburg Research, 2011 /*global XDomainRequest:false console:false jQuery:false */ var root = this; (function( jQuery ) { if ( root.XDomainRequest ) { jQuery.ajaxTransport(function( s ) { if ( s.crossDomain && s.async ) { if ( s.timeout ) { s.xdrTimeout = s.timeout; delete s.timeout; } var xdr; return { send: function( _, complete ) { function callback( status, statusText, responses, responseHeaders ) { xdr.onload = xdr.onerror = xdr.ontimeout = jQuery.noop; xdr = undefined; complete( status, statusText, responses, responseHeaders ); } xdr = new XDomainRequest(); // For backends supporting header_* in the URI instead of real header parameters, // use the dataType for setting the Accept request header. e.g. Stanbol supports this. if(s.dataType){ var headerThroughUriParameters = "header_Accept=" + encodeURIComponent(s.dataType); s.url = s.url + (s.url.indexOf("?") === -1 ? "?" : "&" ) + headerThroughUriParameters; } xdr.open( s.type, s.url ); xdr.onload = function(e1, e2) { callback( 200, "OK", { text: xdr.responseText }, "Content-Type: " + xdr.contentType ); }; // XDR cannot differentiate between errors, // we call every error 404. Could be changed to another one. xdr.onerror = function(e) { console.error(JSON.stringify(e)); callback( 404, "Not Found" ); }; if ( s.xdrTimeout ) { xdr.ontimeout = function() { callback( 0, "timeout" ); }; xdr.timeout = s.xdrTimeout; } xdr.send( ( s.hasContent && s.data ) || null ); }, abort: function() { if ( xdr ) { xdr.onerror = jQuery.noop(); xdr.abort(); } } }; } }); } })( jQuery );
JavaScript
0
@@ -1370,16 +1370,52 @@ ataType) + + %22&header_Content-Type=text/plain%22 ;%0A
2ea5769ac4a3d2fb338fca27ce66ce40762be596
add interpreter hashbang
server.js
server.js
'use strict'; // Configuration module provides all of the set-up necessary for // starting the database and configuring the express application const config = require('./config'); const db = config.mongoose.init(); const app = config.express.init(); // Once the express app is initialized, the API module will // loop through and set up all of the route callbacks on the app. const routes = require('./api'); routes.setRoutes(app); app.listen(config.environment.PORT, function() { console.log("app listening on port: " + config.environment.PORT); });
JavaScript
0.000013
@@ -1,8 +1,29 @@ +#!/usr/bin/env node%0A%0A 'use str
1fec746d2c7f453f5281dc72fc6dfbaf569f0e5a
Reorder code in top-down fashion
server.js
server.js
#!/usr/bin/env node var express = require('express') var request = require('request') var app = express() var slSystems = require('./src/slSystemsCrawler') var Bacon = require('baconjs').Bacon var _ = require('lodash') var courts = require('./public/courts') var webTimmi = require('./src/webTimmiCrawler') var browserify = require('browserify-middleware') app.use('/front.min.js', browserify(__dirname + '/public/front.js')) app.use(express.static(__dirname + '/public')) var cache = {} app.get('/courts', function (req, res) { var isoDate = req.query.date || todayIsoDate() var expirationInMin = 120 var currentTimeMinusDelta = new Date().getTime() - 1000 * 60 * expirationInMin var cachedValue = cache[isoDate] if (cachedValue && cachedValue.date > currentTimeMinusDelta) { res.send(cachedValue) } else { fetch(isoDate).onValue(function (obj) { cache[isoDate] = obj res.send(obj) }) } }) function fetch(isoDate) { return Bacon.combineTemplate({ meilahti: slSystems.getMeilahti(isoDate), herttoniemi: slSystems.getHerttoniemi(isoDate), kulosaari: slSystems.getKulosaari(isoDate), merihaka: slSystems.getMerihaka(isoDate), tali1: webTimmi.getTali1(isoDate), tali2: webTimmi.getTali2(isoDate), taivallahti1: webTimmi.getTaivallahti1(isoDate), taivallahti2: webTimmi.getTaivallahti2(isoDate), date: new Date().getTime() }).map(function (allDataWithDate) { var allData = _.omit(allDataWithDate, 'date') return { freeCourts: _.flatten((_.map(allData, _.identity))), timestamp: allDataWithDate.date } }) } function todayIsoDate() { var now = new Date() var isoDateTime = now.toISOString() return isoDateTime.split('T')[0] } app.get('/locations', function (req, res) { Bacon.combineAsArray(_.map(courts, function (val, key) { return getLocation(val.address).map(function (location) { return _.extend({title: key}, location, val) }) })).onValue(function (val) { res.send(val) }) }) function getLocation(address) { return Bacon.fromNodeCallback(request.get, { url: 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false' }).map('.body').map(JSON.parse).map('.results.0.geometry.location') } var port = process.env.PORT || 5000 app.listen(port, function () { console.log('Server started at localhost:' + port) })
JavaScript
0.000001
@@ -497,32 +497,213 @@ '/courts', f -unction +reeCourts)%0Aapp.get('/locations', locations)%0Avar port = process.env.PORT %7C%7C 5000%0Aapp.listen(port, function () %7B%0A console.log('Server started at localhost:' + port)%0A%7D)%0A%0Afunction freeCourts (req, res) %7B @@ -1139,17 +1139,16 @@ %0A %7D%0A%7D -) %0A%0Afuncti @@ -1813,21 +1813,16 @@ eCourts: - _.flatt @@ -1877,16 +1877,17 @@ mestamp: + allData @@ -2055,39 +2055,26 @@ %0A%7D%0A%0A -app.get('/locations', func +function loca tion - +s (req @@ -2328,17 +2328,16 @@ al) %7D)%0A%7D -) %0A%0Afuncti @@ -2588,131 +2588,6 @@ n')%0A + %7D%0A -var port = process.env.PORT %7C%7C 5000%0Aapp.listen(port, function () %7B%0A console.log('Server started at localhost:' + port)%0A%7D)%0A
f46055bb4ef88acd1a653e6a8ed3d3045cbf4bc5
Disable rollbar in localhost
server.js
server.js
// https://github.com/zeit/next.js/blob/master/examples/custom-server-koa/server.js // const Koa = require('koa'); const next = require('next'); const Rollbar = require('rollbar'); const send = require('koa-send'); // Server related config & credentials // const serverConfig = { ROLLBAR_SERVER_TOKEN: process.env.ROLLBAR_SERVER_TOKEN, ROLLBAR_ENV: process.env.ROLLBAR_ENV || 'localhost', PORT: process.env.PORT || 3000, }; const rollbar = new Rollbar({ accessToken: serverConfig.ROLLBAR_SERVER_TOKEN, captureUncaught: true, captureUnhandledRejections: true, environment: serverConfig.ROLLBAR_ENV, }); const app = next({ dev: process.env.NODE_ENV !== 'production' }); const routes = require('./routes'); const handler = routes.getRequestHandler(app); app.prepare().then(() => { const server = new Koa(); // Rollbar error handling // server.use(async (ctx, next) => { try { await next(); } catch (err) { rollbar.error(err, ctx.request); } }); // server.use(async (ctx, next) => { if ('/' === ctx.path) { await send(ctx, './static/index.html'); } else { await next(); } }); // Server-side routing // /* Required for hot-reload to work. */ server.use(async (ctx, next) => { ctx.respond = false; ctx.res.statusCode = 200; handler(ctx.req, ctx.res); await next(); }); server.listen(serverConfig.PORT, err => { if (err) throw err; console.log('Listening port', serverConfig.PORT); // eslint-disable-line }); });
JavaScript
0
@@ -436,80 +436,115 @@ nst -rollbar = new Rollbar(%7B%0A accessToken: serverConfig.ROLLBAR_SERVER_TOKEN +enableRollbar = !!serverConfig.ROLLBAR_SERVER_TOKEN;%0Aconst rollbar = new Rollbar(%7B%0A enabled: enableRollbar ,%0A @@ -560,20 +560,29 @@ caught: -true +enableRollbar ,%0A capt @@ -609,12 +609,71 @@ ns: -true +enableRollbar,%0A accessToken: serverConfig.ROLLBAR_SERVER_TOKEN ,%0A
5819d6474614e4ad9fb59c036505c6edabbed32d
enable minify
server.js
server.js
/*eslint-env node*/ // Setup basic express server var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); var cfenv = require('cfenv'); var appEnv = cfenv.getAppEnv(); //var port = process.env.PORT || 3000; var port = appEnv.port; server.listen(port, function () { console.log('Server listening at port %d', port); }); //Compress app.use(require('compression')()); // Routing app.use(express.static(__dirname + '/www')); // Chatroom // usernames which are currently connected to the chat var usernames = {}; var numUsers = 0; io.on('connection', function (socket) { var addedUser = false; // when the client emits 'new message', this listens and executes socket.on('new message', function (data) { // we tell the client to execute 'new message' data.avatar = socket.avatar; socket.broadcast.emit('new message', { username: socket.username, message: data }); }); // when the client emits 'add user', this listens and executes socket.on('add user', function (userInfo) { // we store the username in the socket session for this client var username = userInfo.username socket.username = username; socket.avatar = userInfo.avatar; // add the client's username to the global list usernames[username] = username; ++numUsers; addedUser = true; socket.emit('login', { numUsers: numUsers }); // echo globally (all clients) that a person has connected socket.broadcast.emit('user joined', { username: socket.username, numUsers: numUsers }); }); // when the client emits 'typing', we broadcast it to others socket.on('typing', function () { socket.broadcast.emit('typing', { username: socket.username }); }); // when the client emits 'stop typing', we broadcast it to others socket.on('stop typing', function () { socket.broadcast.emit('stop typing', { username: socket.username }); }); // when the user disconnects.. perform this socket.on('disconnect', function () { // remove the username from global usernames list if (addedUser) { delete usernames[socket.username]; --numUsers; // echo globally that this client has left socket.broadcast.emit('user left', { username: socket.username, numUsers: numUsers }); } }); }); /* Using WebSockets var express = require('express'); var cfenv = require('cfenv'); var app = express(); var appEnv = cfenv.getAppEnv(); var server = require('http').createServer(); var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ server:server }); app.use(express.static(__dirname + '/www')); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); //ws.send(message); //broadcast wss.clients.forEach(function each(client) { client.send(message); }); }); //ws.send('Connection established'); }); server.on('request', app); server.listen(appEnv.port, function () { console.log('Listening on ' + appEnv.url); }); */
JavaScript
0.000049
@@ -450,16 +450,64 @@ ')());%0A%0A +//Minify%0Aapp.use(require('express-minify')());%0A%0A // Routi
da0af6773f05d808cbf7f8d5b6a9d94bff44885e
Add graceful exit from SIGTERM (docker)
server.js
server.js
"use strict"; const path = require("path"); const env = process.env.NODE_ENV || "development"; const config = require(path.join(__dirname, "config/config"))(env); if (env === "test" || process.env.PMX) { require("pmx").init({ http : true }); } const app = require(path.join(__dirname, "app.js"))(config); const port = config.port || 8000; const server = app.listen(port); server.on("clientError", (error, socket) => { if (!socket.destroyed) { socket.end("HTTP/1.1 400 Bad Request\r\n\r\n"); } }); console.log("Postcode API listening on port", port); module.exports = app;
JavaScript
0
@@ -112,38 +112,19 @@ require( -path.join(__dirname, %22 +%22./ config/c @@ -134,165 +134,104 @@ ig%22) -) (env);%0A -%0Aif (env === %22test%22 %7C%7C process.env.PMX) %7B%0A%09require(%22pmx%22).init(%7B%0A%09%09http : true%0A%09%7D);%0A%7D%0A%0Aconst app = require(path.join(__dirname, %22app.js%22))(config +const app = require(%22./app.js%22)(config);%0Aconst %7B logger %7D = require(%22commonlog-bunyan%22 );%0A -%0A cons @@ -261,16 +261,94 @@ 8000;%0A%0A +if (env === %22test%22 %7C%7C process.env.PMX) require(%22pmx%22).init(%7B http : true %7D);%0A%0A const se @@ -372,17 +372,16 @@ (port);%0A -%0A server.o @@ -506,19 +506,113 @@ );%0A%0A -console.log +process.on(%22SIGTERM%22, () =%3E %7B%0A logger.info(%22Quitting Postcode API%22);%0A process.exit(0);%0A%7D);%0A%0Alogger.info (%22Po @@ -672,8 +672,9 @@ = app;%0A +%0A
cd553620e7a7c21c378b8a63fd8ae00fa1c6dbc0
call setAttributeNS if args.length === 3
src/svg.js
src/svg.js
module.exports = function(p5) { p5.prototype.querySVG = function(selector) { var svg = this._graphics && this._graphics.svg; if (!svg) { return null; } var elements = svg.querySelectorAll(selector); return elements.map(function(elt) { return new p5.SVGElement(elt); }); }; function SVGElement(element, pInst) { if (!element) { return null; } return p5.Element.apply(this, arguments); }; SVGElement.prototype = Object.create(p5.Element.prototype); SVGElement.prototype.query = function(selector) { var elements = this.elt.querySelectorAll(selector); return elements.map(function(elt) { return new SVGElement(elt); }); }; p5.SVGElement = SVGElement; };
JavaScript
0.000085
@@ -785,24 +785,297 @@ %7D);%0A %7D;%0A%0A + SVGElement.prototype.attribute = function() %7B%0A var args = arguments;%0A if (args.length === 3) %7B%0A this.elt.setAttributeNS.apply(this.elt, args);%0A return this;%0A %7D%0A p5.Element.prototype.attribute.apply(this, args);%0A %7D;%0A%0A p5.SVGEl
103749041853065c4f220b02dda87e8c87d7bd89
implement base api version
server.js
server.js
/** * Created by godson on 4/9/15. */ var express = require( 'express' ); var app = express(); var mongoose = require( 'mongoose' ); var morgan = require( 'morgan' ); var bodyParser = require( 'body-parser' ); var methodOverride = require( 'method-override' ); mongoose.connect('mongodb://localhost:27017/todo'); app.use(express.static(__dirname + '/web')); app.use(morgan('dev')); app.use(bodyParser.urlencoded({'extended':'true'})); app.use(bodyParser.json()); app.use(bodyParser.json({ type: 'application/vnd.api+json' })); app.use(methodOverride()); app.listen(8080); console.log("App listening on port 8080");
JavaScript
0
@@ -34,16 +34,27 @@ 5.%0A */%0A%0A +//Includes%0A %0Avar exp @@ -313,16 +313,28 @@ e' );%0A%0A%0A +// configs%0A%0A mongoose @@ -621,16 +621,1294 @@ e());%0A%0A%0A +// models%0A%0Avar Todo = mongoose.model('Todo', %7B%0A text : String%0A%7D);%0A%0A%0A// routes%0A%0A// get all todos%0Aapp.get('/api/todos', function(req, res) %7B%0A%0A Todo.find(function(err, todos) %7B%0A if (err) %7B%0A res.send( err )%0A %7D%0A%0A res.json(todos);%0A %7D);%0A%7D);%0A%0A// create todo%0Aapp.post('/api/todos', function(req, res) %7B%0A%0A Todo.create(%0A %7B%0A text : req.body.text,%0A done : false%0A %7D,%0A function(err, todo) %7B%0A if (err) %7B%0A res.send( err );%0A %7D%0A%0A Todo.find(function(err, todos) %7B%0A if (err) %7B%0A res.send( err )%0A %7D%0A res.json(todos);%0A %7D);%0A %7D%0A );%0A%0A%7D);%0A%0A// delete a todo%0Aapp.delete('/api/todos/:todo_id', function(req, res) %7B%0A Todo.remove(%0A %7B%0A _id : req.params.todo_id%0A %7D,%0A function(err, todo) %7B%0A if (err) %7B%0A res.send( err );%0A %7D%0A%0A Todo.find(function(err, todos) %7B%0A if (err) %7B%0A res.send( err )%0A %7D%0A res.json(todos);%0A %7D);%0A %7D%0A );%0A%7D);%0A%0A// web%0Aapp.get('*', function(req, res) %7B%0A res.sendfile('./web/index.html');%0A%7D);%0A%0A%0A// Server start%0A app.list
0b30ea866a01c6aabf8865d6c33ac3c41a9f141e
refactor scrape vars, and fs write outside loop
server.js
server.js
var express = require('express'); var fs = require('fs'); var request = require('request'); var cheerio = require('cheerio'); var app = express(); app.get('/scrape', function(req, res){ var url = [ 'http://www.imdb.com/list/ls052535080/?start=1&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=101&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=201&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=301&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=401&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=501&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=601&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=701&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=801&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=901&view=detail&sort=listorian:asc', 'http://www.imdb.com/list/ls052535080/?start=1001&view=detail&sort=listorian:asc' ]; var list = []; for(var i=0; i < url.length; i++) { request(url[i], function(error, response, html) { if(!error) { var $ = cheerio.load(html); $('.list_item').each(function(index) { var data = $(this); var title, year, rating, description, url; var json = {}; title = data.find('b a').text(); year = data.find('b span').text(); rating = data.find('.rating-rating .value').text(); description = data.find('.item_description').text(); url = data.find('b a').attr('href'); json.title = title; json.year = year; json.rating = rating; json.description = description; json.url = url; list.push(json); }); } fs.writeFile('list.json', JSON.stringify(list, null, 4), function(err){ console.log('Succesfully wrote to file, see list.json.'); }); }); } }); app.listen('8081') exports = module.exports = app;
JavaScript
0
@@ -1471,12 +1471,11 @@ = %7B -%7D;%0A%0A +%0A @@ -1486,17 +1486,23 @@ title -= + : data.fi @@ -1529,22 +1529,31 @@ + year -= + : data.fi @@ -1583,24 +1583,31 @@ + rating -= + : data.fi @@ -1634,32 +1634,34 @@ value').text();%0A + descri @@ -1666,17 +1666,17 @@ ription -= +: data.fi @@ -1699,32 +1699,34 @@ ption').text();%0A + url = @@ -1723,17 +1723,25 @@ url -= + : data.fi @@ -1760,25 +1760,24 @@ tr('href');%0A -%0A js @@ -1778,214 +1778,105 @@ -json.title = title;%0A json.year = year;%0A json.rating = rating;%0A json.description = description; +%7D;%0A %0A list.push(json);%0A%0A %7D);%0A %0A +%7D%0A%0A -json.url = url +%7D) ;%0A - %0A - +%7D%0A +%0A - +if ( list. -push(json);%0A%0A %7D);%0A%0A %7D +length) %7B %0A%0A - fs.w @@ -1943,19 +1943,19 @@ n(err)%7B%0A -%0A +%0A co @@ -2014,19 +2014,19 @@ ');%0A -%0A +%0A %7D);%0A %0A @@ -2021,26 +2021,102 @@ %7D);%0A -%0A +%0A %7D + else %7B%0A %0A console.log('Absolutely zero results successfully scraped!?' );%0A -%0A %7D%0A%0A%7D);
84220d8369bd2c2d62b06b6df382364efed9b9b7
Remove security headers for testing purposes
server.js
server.js
var fs = require('fs') var path = require('path') var hyperstream = require('hyperstream') var app = require('./src/app.js') var store = require('./src/store.js') var httpProxy = require('http-proxy') // var proxy = httpProxy.createProxyServer({target: 'http://elmalvinense.com'}) var proxycake = httpProxy.createProxyServer({target: 'http://192.168.1.64'}) var request = require('request') var oppressor = require('oppressor') var feedme = require('feedme') var ecstatic = require('ecstatic') var st = ecstatic({ root: path.join(__dirname, 'build'), gzip: true, cache: 3600 * 24 * 365, headers: { 'Cache-Control': 'public, max-age=31536000', Expires: new Date().setFullYear(new Date().getFullYear() + 1) } }) var st2 = ecstatic({ root: path.join(__dirname, 'build'), gzip: true, cache: 0, headers: { 'Cache-Control': 'no-cache' } }) var http = require('http') var server = http.createServer(function (req, res) { if (req.url.match('manifest.json')) return st(req, res) if (req.url.match('service-worker.js')) return st2(req, res) if (req.url.match('assets')) return st(req, res) if (req.url.match('api')) { req.url = '/cake/Web-OvnionPanel-Back' + req.url return proxycake.web(req, res) } if (req.url.match('elmalvinense')) { var parser = new feedme(true) request({encoding: 'binary', url: 'http://elmalvinense.com/elmalvinense.xml'}) .on('data', function (d) {parser.write(d)}) .on('end', function () {parser.end()}) .on('error', function (err) {console.log(err)}) return parser.on('end', function () {return res.end(JSON.stringify(parser.done().items))}) // parser.on('end', function () { // res.end()}) } store({type: 'setUrl', payload: req.url}) // if (req.url.match('/noticias')) { // request('http://localhost:8000/elmalvinense', function (req, res, body) { // var payload = JSON.parse(body) // store({type: 'news', payload: payload}) // return render(store.getState()) // }) // } return render(store.getState()) function render (state) { var nonce = Math.random().toString().split('.')[1] res.setHeader('Content-Type', 'text/html; charset=UTF-8') res.setHeader('Cache-Control', 'no-cache') res.setHeader('Max-Age', '0') res.setHeader('Expires', Date.now()) res.setHeader('X-XSS-Protection', '1; mode=block') res.setHeader('X-Frame-Options', 'DENY') res.setHeader('X-Content-Type-Options', 'nosniff') // res.setHeader('Content-Security-Policy', "object-src 'none'; script-src 'nonce-" + nonce + "' 'unsafe-inline' 'strict-dynamic' https: ;") // var state = store.getState() var hyd = JSON.stringify(state) var elem = app(state) read('index.html').pipe(hyperstream({ '#main': { _appendHtml: elem }, '#state': { _html: 'window.state =' + hyd, nonce: {append: nonce} }//, // '#css': { // nonce: {append: nonce} // }, // '#w': { // nonce: {append: nonce} // }, // '#bundle': { // nonce: {append: nonce} // }, // '#ga2': { // nonce: {append: nonce} // } })).pipe(oppressor(req)).pipe(res) } }) server.listen(8000) function read (x) { return fs.createReadStream(path.join(__dirname, 'build', x)) }
JavaScript
0
@@ -2303,24 +2303,27 @@ e.now())%0A + // res.setHead @@ -2361,24 +2361,27 @@ =block')%0A + // res.setHead @@ -2409,24 +2409,27 @@ 'DENY')%0A + // res.setHead
08d560fdaba4ca5c5a7319975ab0f86c76a7b7de
Send content-type header.
server.js
server.js
var fs = require('fs') ,Q = require('q') ,http = require('http') ,less = require('less') ,port = 8000 l = console.log; var parser = new less.Parser(); http.createServer(function (req, res) { var time = process.hrtime(); l("Start request"); readEntireBody(req) .then(parseLess) .then(outputCss(res)) .then(function() { time = process.hrtime(time); var ms = time[0]*1000 + time[1] / 1e6; l("Finished request("+(Math.round(ms*10)/10)+"ms):" + req.url); }) .fail(function(err) { l("Got Error: " + err); res.statusCode=500; res.end(err) }); }).listen(8000); function readEntireBody(stream) { var deferred = Q.defer() var body = '' stream.setEncoding('utf8') stream.on('data', function (chunk) { body += chunk }); stream.on('end', function () { deferred.resolve(body); }); stream.on('close', function (err) { deferred.reject(err); }); return deferred.promise; } function parseLess(body) { var deferred = Q.defer() var parser = new less.Parser(); parser.parse(body, deferred.makeNodeResolver()); return deferred.promise; } function outputCss(res) { return function (parseTree) { var css = parseTree.toCSS(); res.statusCode = 200; res.end(css); return Q.fcall(function(){}); } }
JavaScript
0
@@ -1263,24 +1263,48 @@ res. -statusCode = 200 +writeHead(200, %22Content-Type: text/css%22) ;%0A
6fa172730aeeaf620006087a5007d07786102992
update parks data source
gmaps/app.js
gmaps/app.js
function initMap() { // STARTER VARIABLES // Raleigh parks data var raleighParks = 'http://data-ral.opendata.arcgis.com/datasets/5a211ae2f9974f3b814438d5f3a5d783_12.geojson'; // Map style var darkBaseStyle = new google.maps.StyledMapType(darkMatter, {name: 'Dark Base'}); // Map bounds (Empty) var bounds = new google.maps.LatLngBounds(); // Interaction states var clicked = false; var hover = true; // SETUP MAP var map = new google.maps.Map(document.getElementById('map'), { // center: {lat: 35.779590, lng: -78.638179}, // zoom: 13, fullscreenControl: false, mapTypeControlOptions: { mapTypeIds: ['satellite','hybrid','dark_base'] } }); map.setTilt(45); map.mapTypes.set('dark_base', darkBaseStyle); map.setMapTypeId('dark_base'); // PARKS DATA // Load data map.data.loadGeoJson(raleighParks); // Style data based on zoom level map.addListener('zoom_changed', function() { var zoom = map.getZoom(); if(zoom <= 10){ map.data.setStyle({ fillOpacity: 0, fillColor: 'turquoise', strokeColor: 'whitesmoke', strokeWeight: 1 }); } else { map.data.setStyle({ fillOpacity: 0, fillColor: 'turquoise', strokeColor: 'whitesmoke', strokeWeight: zoom/8 }); } }) // ZOOM MAP TO DATA EXTENT map.data.addListener('addfeature', function(e) { processPoints(e.feature.getGeometry(), bounds.extend, bounds); map.fitBounds(bounds); }); // INTERACTION // Click non-feature in map map.addListener('click', function(){ map.data.revertStyle(); clicked = false; hover = true; }); // Mouseover map.data.addListener('mouseover', function(e){ document.getElementById("info-box-hover").textContent = "Click for " + e.feature.getProperty("NAME"); if(hover && !clicked){ map.data.revertStyle(); map.data.overrideStyle(e.feature, { fillOpacity: 0.5 }); } }); map.data.addListener('mouseout', function(e){ document.getElementById("info-box-hover").textContent = ""; if(!clicked && hover){ map.data.revertStyle(); } }) // Click data feature map.data.addListener("click", function(e) { clicked = true; hover = false; // Change style of clicked feature map.data.revertStyle(); map.data.overrideStyle(e.feature, { strokeWeight: 3, strokeColor: 'turquoise' }); // Zoom to clicked feature bounds = new google.maps.LatLngBounds(); processPoints(e.feature.getGeometry(), bounds.extend, bounds); map.fitBounds(bounds); // Update info-box document.getElementById("info-box-name").textContent = e.feature.getProperty("NAME"); document.getElementById("info-box-type").textContent = "Type: " + e.feature.getProperty("PARK_TYPE"); document.getElementById("info-box-developed").textContent = "Status: " + e.feature.getProperty("DEVELOPED"); document.getElementById("info-box-acres").textContent = "Size: " + e.feature.getProperty("MAP_ACRES").toFixed(2) + " ac."; }); } function processPoints(geometry, callback, thisArg) { if (geometry instanceof google.maps.LatLng) { callback.call(thisArg, geometry); } else if (geometry instanceof google.maps.Data.Point) { callback.call(thisArg, geometry.get()); } else { geometry.getArray().forEach(function(g) { processPoints(g, callback, thisArg); }); } }
JavaScript
0
@@ -165,10 +165,9 @@ 783_ -12 +4 .geo
092bec3b97eca8c2fe5a0786a4cb1b20130d2251
accept 'magic 8 ball' as input
server.js
server.js
var bodyParser = require('body-parser'); var answers = require('./answers.js'); var express = require('express'); var request = require('request'); var app = express(); var port = process.env.PORT || 3000; var postOptions = { url: 'https://api.groupme.com/v3/bots/post', method: 'POST' }; app.use(bodyParser.json()); app.route('/') .get(function(req, res) { sayBot(res); //res.end('Thanks'); }) .post(function(req, res) { if(req.body.name.toLowerCase().indexOf('magic eight ball') < 0 && req.body.text.toLowerCase().indexOf('magic eight ball') > -1) { setTimeout(sayBot(res), 4000); }else { res.send('Thanks'); } }); function sayBot(res) { var botData = { bot_id: process.env.BOT_ID, text: answers[Math.floor(Math.random()*answers.length)] }; postOptions.json = botData; request(postOptions, function(error, response, body) { res.end('Thanks'); }); } app.listen(port, function(){ console.log('The magic happens on port ' + port); }); exports.app = app;
JavaScript
0.999999
@@ -608,16 +608,185 @@ 4000);%0A + %7Delse if(req.body.name.toLowerCase().indexOf('magic 8 ball') %3C 0 && req.body.text.toLowerCase().indexOf('magic 8 ball') %3E -1) %7B%0A setTimeout(sayBot(res), 4000);%0A %7Dels
fd82f6ae159006833191b79e82502665ee0e74ba
Revert "make skip onboarding button appears on slide 2"
assets/js/states/onboarding.js
assets/js/states/onboarding.js
(function (window, Cryptoloji, undefined) { 'use strict' Cryptoloji.states.onboarding = {} Cryptoloji.states.onboarding.root = { enter: function () { $('.next_button_onboarding').css('display', 'none') $('#main_section_onboarding_wrapper').addClass('section-show') // go to step1 if we are headering to root state if (Cryptoloji.stateman.current.name === 'onboarding') { Cryptoloji.stateman.go('onboarding.step1') } }, leave: function () { // hide cross-slide elements $('#main_section_onboarding_wrapper').removeClass('section-show') } } function paginationLogic (slide) { var emoji = $('#pagination #emo > g'); TweenLite.to(emoji, .3, {opacity: 0, scale:.1, transformOrigin: "center center"}) var dot = $(emoji[slide-1]) TweenLite.to(dot, .4, {opacity: 1, scale: 1, transformOrigin: "center center"}) } function showNextBtn(){ $('.next_button_onboarding').css('display', 'inherit') TweenLite.set($('.next_button_onboarding'), {opacity:0, scale:1.3, transformOrigin:'center center', overwrite:true}) TweenLite.to($('.next_button_onboarding'), 1, {opacity:1, scale:1, transformOrigin:'center center', ease:Expo.easeInOut}) } function simpleHideNextBtn(){ TweenLite.to($('.next_button_onboarding'), .75, {opacity:0, scale:1.3, transformOrigin:'center center', ease:Expo.easeInOut, overwrite:true}) } function endOut(n, resolve){ $('[slide-num="'+n+'"]').removeClass('section-show') $('.next_button_onboarding').css('display', 'none') resolve() } function commonSlideEnterBehaviour(n) { $('[slide-num="'+n+'"]').addClass('section-show') // display header Cryptoloji.stateman.emit('header:show') $('#next_button_onboarding').attr('to-state', 'onboarding.step'+(n+1)) paginationLogic(n) } Cryptoloji.states.onboarding.step1 = { enter: function() { commonSlideEnterBehaviour(1) OnBoardingAnimations.scene_01.enter(showNextBtn) }, leave: function() { return new Promise(function(resolve, reject) { simpleHideNextBtn(); OnBoardingAnimations.scene_01.exit(function(){ endOut(1, resolve) }) }) } } Cryptoloji.states.onboarding.step2 = { enter: function() { commonSlideEnterBehaviour(2) OnBoardingAnimations.scene_02.enter(showNextBtn) TweenLite.to($('.onboarding_skip_button'), 1, {opacity:.5}) }, leave: function() { return new Promise(function(resolve, reject) { simpleHideNextBtn(); OnBoardingAnimations.scene_02.exit(function(){ endOut(2, resolve) }) }) } } Cryptoloji.states.onboarding.step3 = { enter: function() { commonSlideEnterBehaviour(3) OnBoardingAnimations.scene_03.enter(showNextBtn) }, leave: function() { return new Promise(function(resolve, reject) { simpleHideNextBtn(); OnBoardingAnimations.scene_03.exit(function(){ endOut(3, resolve) }) }) } } Cryptoloji.states.onboarding.step4 = { enter: function() { commonSlideEnterBehaviour(4) OnBoardingAnimations.scene_04.enter(showNextBtn) }, leave: function() { return new Promise(function(resolve, reject) { simpleHideNextBtn(); OnBoardingAnimations.scene_04.exit(function(){ endOut(4, resolve) }) }) } } Cryptoloji.states.onboarding.step5 = { enter: function() { commonSlideEnterBehaviour(5) $('#next_button_onboarding').text('Next') TweenLite.set($('.onboarding_skip_button'), {opacity:1}) $('#next_button_onboarding').off() OnBoardingAnimations.scene_05.enter(showNextBtn) }, leave: function() { return new Promise(function(resolve, reject) { simpleHideNextBtn(); OnBoardingAnimations.scene_05.exit(function(){ endOut(5, resolve) }) }) } } Cryptoloji.states.onboarding.step6 = { enter: function() { commonSlideEnterBehaviour(6) //TweenLite.to($('.onboarding_skip_button'), 1, {delay:.2, opacity:0}) $('#next_button_onboarding').text('Next') OnBoardingAnimations.scene_06.enter(showNextBtn) }, leave: function() { return new Promise(function(resolve, reject) { simpleHideNextBtn(); OnBoardingAnimations.scene_06.exit(function(){ endOut(6, resolve) }) }) } } Cryptoloji.states.onboarding.step7 = { enter: function () { commonSlideEnterBehaviour(7) TweenLite.to($('.svg_wrapper_pagination'), 1, {opacity:0}) TweenLite.to($('.onboarding_skip_button'), 1, {delay:.2, opacity:0}) $('#next_button_onboarding').text('Go for it!') $('#next_button_onboarding').click(function(){ Cryptoloji.stateman.go('encrypt') return false; }) OnBoardingAnimations.scene_07.enter(showNextBtn) }, leave: function () { return new Promise(function(resolve, reject) { simpleHideNextBtn(); OnBoardingAnimations.scene_07.exit(function(){ Cryptoloji.stateman.emit('header:hide') endOut(7, resolve) }) }) } } })(window, window.Cryptoloji);
JavaScript
0.000001
@@ -1862,24 +1862,45 @@ gic(n)%0A %7D%0A%0A + var timer = null;%0A%0A Cryptoloji @@ -2050,34 +2050,180 @@ -%7D,%0A leave: function() %7B + timer = setTimeout(function()%7B%0A TweenLite.to($('.onboarding_skip_button'), 1, %7Bopacity:.5%7D)%0A %7D, 3000)%0A %7D,%0A leave: function() %7B%0A clearTimeout(timer) %0A @@ -2575,74 +2575,8 @@ tn)%0A - TweenLite.to($('.onboarding_skip_button'), 1, %7Bopacity:.5%7D)%0A
51efb214b79d94808a37618e25abd464d81c85f2
Check two-char ops first
server.js
server.js
const restify = require('restify'); const sessions = require('client-sessions'); const passport = require('passport-restify'); const GoogleStrategy = require('passport-google-oauth20'); const logger = require('./logger'); const User = require('./user'); const {NoteSet, Note} = require('./note'); const {db, Predicate} = require('./database'); /* * app constants and logger */ const app = { name: 'dumpnote', }; /* * configure server */ const server = restify.createServer({ name: app.name, log: logger, }); server.use(sessions({ cookieName: 'session', secret: process.env.DN_SESS_SECRET, duration: 7 * 24 * 60 * 60 * 1000, activeDuration: 7 * 24 * 60 * 1000, })); server.use(passport.initialize()); server.use(passport.session()); server.use((req, res, next) => { console.log('Req: ' + req.httpVersion + ' ' + req.method + ' ' + req.url); res.setHeader('content-type', 'application/json'); return next(); }); server.use(restify.plugins.queryParser()); /* * configure passport */ passport.use(new GoogleStrategy({ clientID: process.env.DN_GOOG_CID, clientSecret: process.env.DN_GOOG_SECRET, callbackURL: process.env.DN_GOOG_CB, }, async (accessToken, refreshToken, profile, done) => { const user = await User.createOrGet({ gid: profile.id, name: profile.displayName, email: profile.emails[0].value, }); done(null, user); })); passport.serializeUser((user, done) => done(null, user.id)); passport.deserializeUser(async (id, done) => { const user = await User.resolve(id); done(null, user); }); /* * util endpoints */ server.get('/ping', (req, res) => res.send(200)); /* * auth endpoints */ server.get('/auth', passport.authenticate('google', {scope: ['email profile']})); server.get('/authcb', passport.authenticate('google', { failureRedirect: '/auth', failureFlash: true, }), (req, res, next) => res.redirect(process.env.DN_AUTH_CB, next)); server.get('/authstatus', (req, res) => res.send(200, {authed: req.isAuthenticated()})); server.get('/unauth', (req, res) => { req.logout(); res.send(200); }); function mwAuthed(req, res, next) { if (req.isAuthenticated()) { return next(); } res.send(401, {error: 'Unauthenticated!'}); } /* * note endpoints */ const singleCharOps = ['=', '>', '<']; const twoCharOps = ['<>', '>=', '<=']; server.get('/notes', mwAuthed, (req, res) => { const predicates = []; function tryAdd(param) { if (req.query[param]) { let operator = null; if (singleCharOps.some((op) => req.query[param].startsWith(op))) { operator = req.query[param].substring(0, 1); req.query[param] = req.query[param].substring(1); } else if (twoCharOps.some((op) => req.query[param].startsWith(op))) { operator = req.query[param].substring(0, 2); if (operator === '!=') { operator = '<>'; } req.query[param] = req.query[param].substring(2); } else { operator = '='; } predicates.push(new Predicate(param, operator, req.query[param])); } } function tryAddBool(param) { if (req.query[param]) { if (req.query[param] === 'true' || req.query[param] === 'false') { predicates.push(new Predicate(param, '=', req.query[param])); } else { res.send(400, { error: `Expected boolean at ${param}=${req.query[param]}`, }); return; } } } tryAdd('id'); tryAdd('set'); tryAdd('timestamp'); tryAddBool('marked'); if (req.query.search) { predicates.push( new Predicate('body', ' LIKE ', `%${req.query.search}%`)); } req.user.getNotes(predicates) .then((notes) => res.send(200, notes.map((note) => note.serialize()))); }); server.post('/notes', mwAuthed, (req, res) => { const chunks = []; req.on('data', (chunk) => chunks.push(chunk)); req.on('end', async () => { const body = JSON.parse(Buffer.concat(chunks).toString()); const note = await req.user.postNote(body.body, body.set); res.send(200, note); }); }); server.get('/notes/:note', mwAuthed, (req, res) => { res.send(501, {error: 'Not implemented!'}); }); server.del('/notes/:note', mwAuthed, (req, res) => { res.send(501, {error: 'Not implemented!'}); }); server.patch('/notes/:note', mwAuthed, (req, res) => { res.send(501, {error: 'Not implemented!'}); }); /* * set endpoints */ server.get('/sets', mwAuthed, (req, res) => { res.send(501, {error: 'Not implemented!'}); }); server.post('/sets', mwAuthed, (req, res) => { res.send(501, {error: 'Not implemented!'}); }); server.get('/sets/:set', mwAuthed, (req, res) => { res.send(501, {error: 'Not implemented!'}); }); server.del('/sets/:set', mwAuthed, (req, res) => { res.send(501, {error: 'Not implemented!'}); }); server.patch('/sets/:set', mwAuthed, (req, res) => { res.send(501, {error: 'Not implemented!'}); }); /* * start server */ (async () => { logger.info('initializing database connection.'); try { await db.connect(); } catch (err) { throw err; } logger.info('starting server.'); await server.listen(process.env.PORT, () => logger.info('server started.')); })();
JavaScript
0
@@ -2492,199 +2492,8 @@ if -(singleCharOps.some((op) =%3E req.query%5Bparam%5D.startsWith(op))) %7B%0A operator = req.query%5Bparam%5D.substring(0, 1);%0A req.query%5Bparam%5D = req.query%5Bparam%5D.substring(1);%0A %7D else if (two @@ -2726,24 +2726,215 @@ bstring(2);%0A + %7D else if (singleCharOps.some((op) =%3E req.query%5Bparam%5D.startsWith(op))) %7B%0A operator = req.query%5Bparam%5D.substring(0, 1);%0A req.query%5Bparam%5D = req.query%5Bparam%5D.substring(1);%0A %7D else
e66ebd9fd829a454a77f65c29fb9728c352afee3
update main file
server.js
server.js
'use strict'; var express = require('express'), app = express(), RouterRoot, config = require('./config'), routes = require('./routes'), bodyParser = require('body-parser'), session = require('express-session'), mongoose = require('mongoose'); mongoose.connect(config.mongo_url, function(err) { if (err) throw err; console.log('Connect database successeful!!! '); }); // Using middleware app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); app.use(session({ resave: false, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'Secret key' })); // Config express app.set('view engine', 'ejs'); app.set('views', __dirname + '/views'); app.use(express.static(__dirname + '/public')); // Using Router RouterRoot = express.Router(); RouterRoot.get('/', routes.index); RouterRoot.get('/login', routes.users.login); RouterRoot.post('/login', routes.users.authen); RouterRoot.get('/register', routes.users.register); RouterRoot.post('/register', routes.users.reguser); RouterRoot.get('/logout', routes.users.logout); RouterRoot.post('/posts', routes.posts.create); RouterRoot.get('/posts', routes.posts.read); RouterRoot.put('/posts/:post_id', routes.posts.update); RouterRoot.delete('/posts/:post_id', routes.posts.del); RouterRoot.all('*', function(req, res) { res.status(404).end(); }); // Declare router app.use('/', RouterRoot); app.listen( config.port, function() { console.log('Express server running at ' + config.port); });
JavaScript
0
@@ -1186,31 +1186,105 @@ gout);%0A%0A -%0ARouterRoot.pos +// RouterRoot.get('/admin', )%0ARouterRoot.post('/cates', routes.cates.add);%0A%0ARouterRoot.ge t('/post @@ -1300,22 +1300,20 @@ s.posts. -c rea -te +d );%0ARoute @@ -1310,34 +1310,35 @@ ad);%0ARouterRoot. -ge +pos t('/posts', rout @@ -1338,36 +1338,38 @@ ', routes.posts. +c rea -d +te );%0ARouterRoot.pu
0358d01f230707e64f9c7298d8a8d34593fb8943
Connect to mongo here so we only do it once
server.js
server.js
var express = require('express'), pages = require('./routes/pages.js'), signup = require('./routes/signup.js'), flash = require('connect-flash'), auth = require('./modules/auth.js'); var app = express(); // Configuration var secret = process.env.COOKIE_SECRET || 'secret'; app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.compress()); app.use(express.methodOverride()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser(secret)); app.use(express.session({ secret: secret, cookie: { httpOnly: true } })); app.use(auth); app.use(flash()); if (app.get('env') === 'development') { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); } else { app.use(express.errorHandler()); } // Routes app.get('/', pages.index); app.get('/contact', pages.contact); app.get('/login', pages.login); app.post('/signup', signup.sendToMailchimp); app.use(express.static(__dirname + '/dist')); // Go app.listen(process.env.port || 3000); console.log("Express server started");
JavaScript
0
@@ -1,12 +1,27 @@ +%22use strict%22;%0A%0A var express @@ -197,16 +197,241 @@ uth.js') +,%0A api = require('./modules/api.js'),%0A mongoose = require('mongoose');%0A%0Amongoose.connect(process.env.MONGODB_CONNECTION_STRING);%0Avar db = mongoose.connection;%0Adb.on('error', console.error.bind(console, 'connection error:')) ;%0A%0Avar a
02a2bef8ac023108a422d5bf7dd01ded0957fc11
Remove unused require
server.js
server.js
// TODO Remove? require('./lib/utils/functional'); // Server var http = require('http'); var app = require('express')(); var config = require('./src/config'); // DB var mongoose = require('mongoose'); // Sub-apps var api = require('./src/server/api'); var pages = require('./src/server/pages'); // Game-logic // TODO Move! var game = require('./lib/server/game').game; var dict = require('./src/dictionary.json'); // Configure if (app.get('env') === 'development') { config.development(app); } if (app.get('env') === 'production') { config.production(app); } config.all(app); // MongoDB mongoose.connect(app.get('db')); // Create some games game.create(Object.keys(dict)); // Save rooms to every page load app.use(function (req, res, next) { req.rooms = game.all(); next(); }); // Mount sub-apps app.use('/', pages); app.use('/api', api); // Create server var server = http.createServer(app); // WebSocket require('./src/server/websockets').listen(server, game); // Start server server.listen(app.get('port'), app.get('ipaddr')); console.log( 'Listening on port %s:%d in %s mode...', app.get('ipaddr'), app.get('port'), app.get('env'));
JavaScript
0.000001
@@ -1,56 +1,4 @@ -// TODO Remove?%0Arequire('./lib/utils/functional');%0A%0A // S
3383f3e6ac2fb8c17409278be903176ef0c3498e
Fix the issue with synchronizing pull requests.
server.js
server.js
"use strict" var format = require('python-format') var request = require('request') var port = +process.env.npm_package_config_webhookport if (!port) { console.error("Start the bot using 'npm start'.") return } var secret = process.env.npm_package_config_secret if (!secret) { console.error("Secret not defined, please use 'npm config set psdevbot:secret value'.") return } var Showdown = require('./showdown') var parameters = {} Object.keys(Showdown.keys).forEach(function (key) { parameters[key] = process.env['npm_package_config_' + key] }) var client = new Showdown(parameters) client.connect() var github = require('githubhook')({ port: port, secret: secret, logger: console }) function shorten(url, callback) { function shortenCallback(error, response, body) { var shortenedUrl = url if (!error && response.headers.location) { shortenedUrl = response.headers.location } callback(shortenedUrl) } request.post('https://git.io', {form: {url: url}}, shortenCallback) } function getRepoName(repo) { switch (repo) { case 'Pokemon-Showdown': return 'server' case 'Pokemon-Showdown-Client': return 'client' default: return repo } } var escape = require('escape-html') github.on('push', function push(repo, ref, result) { var url = result.compare var branch = /[^/]+$/.exec(ref)[0] shorten(url, function pushShortened(url) { var messages = [] var message = result.commits.length === 1 ? "[{}] <font color='909090'>{}</font> pushed <b>{}</b> new commit to <font color='800080'>{}</font>: <a href='{4}'>{4}</a>" : "[{}] <font color='909090'>{}</font> pushed <b>{}</b> new commits to <font color='800080'>{}</font>: <a href='{4}'>{4}</a>" messages.push(format( message, escape(getRepoName(repo)), escape(result.pusher.name), escape(result.commits.length), escape(branch), escape(url) )) result.commits.forEach(function (commit) { messages.push(format( "{}/<font color='800080'>{}</font> <font color='606060'>{}</font> <font color='909090'>{}</font>: {}", escape(getRepoName(repo)), escape(branch), escape(commit.id.substring(0, 8)), escape(commit.author.name), escape(/.+/.exec(commit.message)[0]) )) }) client.report('!htmlbox ' + messages.join("<br>")) }) }) github.on('pull_request', function pullRequest(repo, ref, result) { var url = result.pull_request.html_url shorten(url, function pullRequestShortened(url) { client.report(format( "!htmlbox [<font color='FFC0CB'>{}</font>] <font color='909090'>{}</font> {} pull request #{}: {} {}", escape(getRepoName(repo)), escape(result.pull_request.user.login), escape(result.action), escape(result.pull_request.number), escape(result.pull_request.title), escape(url) )) }) }) github.listen()
JavaScript
0
@@ -2687,24 +2687,124 @@ st.html_url%0A + var action = result.action%0A if (action === 'synchronize') %7B%0A action = 'updated'%0A %7D%0A shorten( @@ -3100,23 +3100,16 @@ escape( -result. action),