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
0e8ab95c87396060610b76bf29bf08b0088b4750
Update Data Util
test/data-util/inventory/finishing-printing/fp-shipment-document-data-util.js
test/data-util/inventory/finishing-printing/fp-shipment-document-data-util.js
'use strict' var helper = require("../../../helper"); var ShipmentDocumentManager = require("../../../../src/managers/inventory/finishing-printing/fp-shipment-document-manager"); //Data Util var ProductionOrderDataUtil = require("../../sales/production-order-data-util"); var BuyerDataUtil = require("../../master/buyer-data-util"); var StorageDataUtil = require('../../master/storage-data-util'); var InventoryDocumentDataUtil = require('../inventory-document-data-util'); var codeGenerator = require('../../../../src/utils/code-generator'); // DB Models var Models = require("dl-models"); var Map = Models.map; var FPShipmentDocumentModels = Models.inventory.finishingPrinting.FPShipmentDocument; class FPShipmentDocumentDataUtil { getNewData() { return Promise.all([ProductionOrderDataUtil.getNewTestData(), BuyerDataUtil.getTestData(), StorageDataUtil.getPackingTestData(), InventoryDocumentDataUtil.getPackingNewTestData()]) .then((results) => { var productionOrder1 = results[0]; var buyer = results[1]; var storage = results[2]; var inventoryDocument = results[3]; var data = { code: codeGenerator(), deliveryDate: new Date(), shipmentNumber: "UT/No-1", deliveryCode: "UT/No-1", deliveryReference: "UT/Ref-01", productIdentity: "UT/ID-1", buyerId: buyer._id, buyerCode: buyer.code, buyerName: buyer.name, buyerAddress: buyer.address, buyerType: buyer.type, details: [ { productionOrderId: productionOrder1._id, productionOrderNo: productionOrder1.orderNo, productionOrderType: productionOrder1.orderType.name, designCode: productionOrder1.designCode, designNumber: productionOrder1.designNumber, items: [ { productId: inventoryDocument.items[0].productId, productCode: inventoryDocument.items[0].productCode, productName: inventoryDocument.items[0].productName, designCode: productionOrder1.designCode, designNumber: productionOrder1.designNumber, colorType: productionOrder1.details[0].colorType.name, uomId: productionOrder1.uomId, uomUnit: productionOrder1.uom.unit, quantity: inventoryDocument.items[0].quantity, length: 1, weight: 1 } ] } ], }; return Promise.resolve(data); }) } getNewTestData() { return helper .getManager(ShipmentDocumentManager) .then((manager) => { return this.getNewData().then((data) => { return manager.create(data) .then((id) => { return manager.getSingleById(id) }); }); }); } } module.exports = new FPShipmentDocumentDataUtil();
JavaScript
0
@@ -332,73 +332,8 @@ %22);%0A -var StorageDataUtil = require('../../master/storage-data-util');%0A var @@ -789,46 +789,8 @@ a(), - StorageDataUtil.getPackingTestData(), Inv @@ -966,50 +966,8 @@ 1%5D;%0A - var storage = results%5B2%5D;%0A @@ -1014,9 +1014,9 @@ lts%5B -3 +2 %5D;%0A%0A
16202fa9a696547c9995489fa9b5b602276e9746
Remove a few unused rows
quasar/quasar.conf.js
quasar/quasar.conf.js
/* * This file runs in a Node context (it's NOT transpiled by Babel), so use only * the ES6 features that are supported by your Node version. https://node.green/ */ // Configuration for your app // https://quasar.dev/quasar-cli/quasar-conf-js /* eslint-env node */ module.exports = function (/* ctx */) { return { // https://quasar.dev/quasar-cli/supporting-ts supportTS: false, // https://quasar.dev/quasar-cli/prefetch-feature // preFetch: true, // app boot file (/src/boot) // --> boot files are part of "main.js" // https://quasar.dev/quasar-cli/boot-files boot: [ 'axios', ], // https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-css css: [ 'app.scss' ], // https://github.com/quasarframework/quasar/tree/dev/extras extras: [ // 'ionicons-v4', // 'mdi-v5', // 'fontawesome-v5', // 'eva-icons', // 'themify', // 'line-awesome', // 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both! 'roboto-font', // optional, you are not bound to it 'material-icons', // optional, you are not bound to it ], // Full list of options: https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-build build: { vueRouterMode: 'history', // available values: 'hash', 'history' // transpile: false, // Add dependencies for transpiling with Babel (Array of string/regex) // (from node_modules, which are by default not transpiled). // Applies only if "transpile" is set to true. // transpileDependencies: [], // rtl: false, // https://quasar.dev/options/rtl-support // preloadChunks: true, // showProgress: false, // gzip: true, // analyze: true, // Options below are automatically set depending on the env, set them if you want to override // extractCSS: false, // https://quasar.dev/quasar-cli/handling-webpack extendWebpack (cfg) { cfg.module.rules.push({ enforce: 'pre', test: /\.(js|vue)$/, loader: 'eslint-loader', exclude: /node_modules/ }) }, }, // Full list of options: https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-devServer devServer: { https: false, port: 8080, open: true, // opens browser window automatically proxy: { // proxy all requests starting with /api to jsonplaceholder '/api': { // target: 'https://menu.dckube.scilifelab.se/api/', target: 'https://menu.dckube.scilifelab.se/api/', changeOrigin: true, pathRewrite: { '^/api': '' } } } }, // https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-framework framework: { iconSet: 'material-icons', // Quasar icon set lang: 'en-us', // Quasar language pack config: {}, // Possible values for "importStrategy": // * 'auto' - (DEFAULT) Auto-import needed Quasar components & directives // * 'all' - Manually specify what to import importStrategy: 'auto', // Quasar plugins plugins: [] }, // animations: 'all', // --- includes all animations // https://quasar.dev/options/animations animations: [], // https://quasar.dev/quasar-cli/developing-ssr/configuring-ssr ssr: { pwa: false }, // https://quasar.dev/quasar-cli/developing-pwa/configuring-pwa pwa: { workboxPluginMode: 'GenerateSW', // 'GenerateSW' or 'InjectManifest' workboxOptions: {}, // only for GenerateSW manifest: { name: `Lunch Menus`, short_name: `Lunch Menus`, description: `Lunch menus for the restaurants near SciLifeLab Solna and Uppsala`, display: 'standalone', orientation: 'portrait', background_color: '#ffffff', theme_color: '#027be3', icons: [ { src: 'icons/icon-128x128.png', sizes: '128x128', type: 'image/png' }, { src: 'icons/icon-192x192.png', sizes: '192x192', type: 'image/png' }, { src: 'icons/icon-256x256.png', sizes: '256x256', type: 'image/png' }, { src: 'icons/icon-384x384.png', sizes: '384x384', type: 'image/png' }, { src: 'icons/icon-512x512.png', sizes: '512x512', type: 'image/png' } ] } }, // Full list of options: https://quasar.dev/quasar-cli/developing-cordova-apps/configuring-cordova cordova: { // noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing }, // Full list of options: https://quasar.dev/quasar-cli/developing-capacitor-apps/configuring-capacitor capacitor: { hideSplashscreen: true }, // Full list of options: https://quasar.dev/quasar-cli/developing-electron-apps/configuring-electron electron: { bundler: 'packager', // 'packager' or 'builder' packager: { // https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options // OS X / Mac App Store // appBundleId: '', // appCategoryType: '', // osxSign: '', // protocol: 'myapp://path', // Windows only // win32metadata: { ... } }, builder: { // https://www.electron.build/configuration/configuration appId: 'lunch-menu' }, // More info: https://quasar.dev/quasar-cli/developing-electron-apps/node-integration nodeIntegration: true, extendWebpack (/* cfg */) { // do something with Electron main process Webpack cfg // chainWebpack also available besides this extendWebpack } } } }
JavaScript
0.000006
@@ -820,225 +820,8 @@ : %5B%0A - // 'ionicons-v4',%0A // 'mdi-v5',%0A // 'fontawesome-v5',%0A // 'eva-icons',%0A // 'themify',%0A // 'line-awesome',%0A // 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!%0A%0A
4a917ab832fbd0eaa9ddcd41f3bf4b1e19328a7f
Use internal reference for hydration flag
src/render.js
src/render.js
import { EMPTY_OBJ, EMPTY_ARR } from './constants'; import { commitRoot, diff } from './diff/index'; import { createElement, Fragment } from './create-element'; import options from './options'; /** * Render a Preact virtual node into a DOM element * @param {import('./index').ComponentChild} vnode The virtual node to render * @param {import('./internal').PreactElement} parentDom The DOM element to * render into * @param {Element | Text} [replaceNode] Attempt to re-use an * existing DOM tree rooted at `replaceNode` */ export function render(vnode, parentDom, replaceNode) { if (options._root) options._root(vnode, parentDom); let oldVNode = replaceNode && replaceNode._children || parentDom._children; let isHydrating = replaceNode === null; vnode = createElement(Fragment, null, [vnode]); let mounts = []; diff( parentDom, (replaceNode || parentDom)._children = vnode, oldVNode || EMPTY_OBJ, EMPTY_OBJ, parentDom.ownerSVGElement !== undefined, replaceNode ? [replaceNode] : oldVNode ? null : EMPTY_ARR.slice.call(parentDom.childNodes), mounts, false, replaceNode || EMPTY_OBJ, isHydrating, ); commitRoot(mounts, vnode); } /** * Update an existing DOM element with data from a Preact virtual node * @param {import('./index').ComponentChild} vnode The virtual node to render * @param {import('./internal').PreactElement} parentDom The DOM element to * update */ export function hydrate(vnode, parentDom) { parentDom._children = null; render(vnode, parentDom, null); }
JavaScript
0
@@ -188,16 +188,47 @@ ions';%0A%0A +const IS_HYDRATE = EMPTY_OBJ;%0A%0A /**%0A * R @@ -660,24 +660,71 @@ arentDom);%0A%0A +%09let isHydrating = replaceNode === IS_HYDRATE;%0A %09let oldVNod @@ -763,24 +763,40 @@ children %7C%7C +!isHydrating && parentDom._c @@ -806,49 +806,8 @@ dren -;%0A%09let isHydrating = replaceNode === null ;%0A%09v @@ -1030,24 +1030,40 @@ %09replaceNode + && !isHydrating %0A%09%09%09? %5Brepla @@ -1533,37 +1533,8 @@ ) %7B%0A -%09parentDom._children = null;%0A %09ren @@ -1555,17 +1555,23 @@ entDom, -null +IS_HYDRATE );%0A%7D%0A
37b60bf0040203784d1270ed6f6299319cedb78c
Add color
src/render.js
src/render.js
import d3 from 'd3'; const render = (options) => { const {width, height, timeDomain, temperatureDomain} = options, leftMargin = 50, rightMargin = 50, topMargin = 50, bottomMargin = 50, contentsWidth = width - leftMargin - rightMargin, contentsHeight = height - topMargin - bottomMargin, ratio = 20, timeScale = d3.time.scale() .domain(timeDomain) .range([0, contentsWidth * ratio]) .nice(), temperatureScale = d3.scale.linear() .domain(temperatureDomain) .range([contentsHeight, 0]), timeAxis = d3.svg.axis() .scale(timeScale) .ticks(240) .orient('bottom'), temperatureAxis = d3.svg.axis() .scale(temperatureScale) .orient('left'); return (selection) => { selection.each(function (records) { console.log(records); const element = d3.select(this); if (element.select('g.contents').empty()) { element.append('g') .classed('contents', true) .attr('transform', `translate(${leftMargin - contentsWidth * (ratio - 1)},${topMargin})`); element.append('g') .classed('time-axis', true) .attr('transform', `translate(${leftMargin - contentsWidth * (ratio - 1)},${height - bottomMargin})`) .call(timeAxis); element.append('g') .classed('temperature-axis', true) .attr('transform', `translate(${leftMargin},${topMargin})`) .call(temperatureAxis); element.selectAll('g.tick line') .attr('stroke', 'black'); element.selectAll('path.domain') .attr({ stroke: 'black', fill: 'none' }); const zoom = d3.behavior.zoom() .scaleExtent([1, 1]) .translate([leftMargin - contentsWidth * (ratio - 1), topMargin]) .on('zoom', function () { const e = d3.event; let x = e.translate[0]; if (x < leftMargin - contentsWidth * (ratio - 1)) { x = leftMargin - contentsWidth * (ratio - 1); zoom.translate([x, topMargin]); } element.select('g.contents') .attr('transform', `translate(${x},${topMargin})`); element.select('g.time-axis') .attr('transform', `translate(${x},${height - bottomMargin})`); }); element.call(zoom); } element.select('g.contents') .selectAll('g.points') .data(records, (d) => d.$id) .enter() .append('g') .classed('points', true) .attr('transform', (d) => `translate(${timeScale(d.timestamp)},${height - topMargin - bottomMargin})`) .append('circle') .attr({ r: 5 }); }); selection.selectAll('g.points') .attr('transform', (d) => `translate(${timeScale(d.timestamp)},${temperatureScale(d.temperature)})`); selection.select('g.time-axis') .call(timeAxis); selection.select('g.temperature-axis') .call(temperatureAxis); }; }; export default render;
JavaScript
0.000043
@@ -602,16 +602,364 @@ t, 0%5D),%0A + temperatureColor = d3.scale.quantize()%0A .domain(%5B10, 30%5D)%0A .range(%5B%0A d3.hsl(240, 0.8, 0.5),%0A d3.hsl(200, 0.8, 0.5),%0A d3.hsl(160, 0.8, 0.5),%0A d3.hsl(120, 0.8, 0.5),%0A d3.hsl(80, 0.8, 0.5),%0A d3.hsl(40, 0.8, 0.5),%0A d3.hsl(0, 0.8, 0.5)%0A %5D),%0A @@ -975,32 +975,32 @@ = d3.svg.axis()%0A - .scale @@ -1191,16 +1191,16 @@ n) =%3E %7B%0A + sele @@ -1235,36 +1235,8 @@ ) %7B%0A - console.log(records);%0A @@ -3104,32 +3104,88 @@ .attr(%7B%0A + fill: (d) =%3E temperatureColor(d.temperature),%0A r: 5%0A
05e3c77e5b236ee6d500d3ed8839c03642afd770
Fix simple button isActing state
addon/components/form-button.js
addon/components/form-button.js
import Component from '@glimmer/component'; import { action } from '@ember/object'; export default class FormButtonComponent extends Component { @action handleClick() { if (!this.args.isActing && this.args.onClick) { return this.args.onClick(); } } }
JavaScript
0.001562
@@ -229,14 +229,19 @@ -return +const ret = thi @@ -257,16 +257,150 @@ Click(); +%0A%0A if (ret.finally) %7B%0A this.isActing = true;%0A ret.finally(() =%3E (this.isActing = false));%0A %7D%0A return ret; %0A %7D%0A
11830ab5e69b5e6265638fe2d594832bac9a994e
remove debug
src/router.js
src/router.js
var router = require('express').Router() , ArduinoCompiler = require('./make') , ProjectManager = require('borgnix-project-manager/lib/project-manager') , path = require('path') // , boards = require('./lib/board') , fs = require('fs-extra') , walk = require('walk') , unzip = require('unzip') , _ = require('underscore') var compiler, pm, boards = require('../data/boards.json') router.post('/compile', async function(req, res) { // console.log(req.body) var info = { owner: req.session.user.uid , type: req.body.type , name: req.body.name } try { var sketch = await pm.findProject(info) compiler.compile(sketch, req.body.board, function(err, stdout, stderr) { var memoryUsage = stdout.slice(stdout.lastIndexOf('AVR Memory Usage')) res.json({ status: err ? 1 : 0 , content: { error: err , stdout: memoryUsage , stderr: stderr } }) }) } catch (e) { res.json({status: 1, content: e.toString()}) } }) router.get('/boards', function(req, res) { // res.json(Object.keys(boards.data())) res.json(boards) }) router.get('/hex/:filename', async function(req, res) { var info = { owner: req.session.user.uid , type: req.body.type , name: req.body.name } try { var sketch = await pm.findProject(info) , hexFile = path.join( sketch.dir , 'build-' + (req.query.board || 'uno') , req.params.filename ) if (fs.existsSync(hexFile)) { res.sendFile(hexFile) } else { res.json({status: 1, content: 'Hex Not Found'}) } } catch (e) { res.json({status: 1, content: 'Hex Not Found'}) } }) router.post('/upload-zip-lib', function(req, res) { _.map(req.files, function(file, key) { // console.log(file) if (file.extension !== 'zip') return null var outPath = path.join( pm.projectDir, req.session.user.uid , 'arduino/libraries' , path.basename(file.originalname, '.zip') ) fs.createReadStream(file.path).pipe(unzip.Extract({ path: outPath })) }) res.json({ status: 0 }) }) router.get('/libs', function(req, res) { var userLibPath = path.join( pm.projectDir, req.session.user.uid , 'arduino/libraries') console.log(userLibPath) var ideLibPath = path.join(compiler.arduinoDir, 'libraries') console.log(ideLibPath) var avrLibPath = path.join( compiler.arduinoDir , 'hardware/arduino/avr/libraries') console.log(avrLibPath) try { var userLibs = getLibs(userLibPath, 'user') var ideLibs = getLibs(ideLibPath, 'ide') var avrLibs = getLibs(avrLibPath, 'ide') res.json({ status: 0, content: { userLibs: userLibs, ideLibs: ideLibs.concat(avrLibs) } }) } catch (e) { res.json({ status: 1, content: e }) } }) function getLibs(libPath, type) { var libs = [] fs.readdirSync(libPath).map(function(file) { var fullPath = path.join(libPath, file) var stat = fs.lstatSync(fullPath) var lib = { name: file, headers: [] } if (type === 'ide') { lib.type = 'ide' } else if (stat.isSymbolicLink()) { lib.type = 'public' } else if (stat.isDirectory()) { lib.type = 'private' } else { return null } var opt = { followLinks: true, listeners: { file: function(root, stat, next) { // console.log(path.extname(stat.name), root) if (path.relative(fullPath, root).indexOf('example') != -1) return next() if (path.extname(stat.name) === '.h') { console.log(path.relative(fullPath, root), stat.name) var header = path.join(path.relative(fullPath, root), stat.name) if (header.indexOf('src/') === 0) header = header.slice(4) if (header.indexOf('extras/') === 0) return next() lib.headers.push(header) } next() }, error: function() { console.error('walking error') throw new Error('walking error') }, end: function() { libs.push(lib) } } } var walker = walk.walkSync(fullPath, opt) }) return libs } module.exports = function(config) { var opt = {} if (config.projectRoot) opt.root = config.projectRoot else throw new Error('config.projectRoot is missing') if (config.arduinoLibs) opt.arduinoLibs = config.arduinoLibs else throw new Error('config.arduinoLibs is missing') pm = new ProjectManager({ projectDir: config.projectRoot , tplDir: path.join(__dirname, '../project-tpl') , store: config.store }) compiler = new ArduinoCompiler(config) return router }
JavaScript
0.000002
@@ -3657,74 +3657,8 @@ ) %7B%0A - console.log(path.relative(fullPath, root), stat.name)%0A
cd350288ddf5d7f8652bbebdf2ce9600b1050eef
Use new `content` array for each service instance (#279)
addon/services/notifications.js
addon/services/notifications.js
import Service from '@ember/service'; import { assign, merge } from '@ember/polyfills'; import { A } from '@ember/array'; import { isEmpty } from '@ember/utils'; import EmberObject, { getWithDefault, set } from '@ember/object'; import { run } from '@ember/runloop'; import config from 'ember-get-config'; const notificationAssign = assign || merge; const globals = config['ember-cli-notifications'] || {}; // Import app config object export default Service.extend({ content: A(), // Method for adding a notification addNotification(options) { // If no message is set, throw an error if (!options.message) { throw new Error("No notification message set"); } const notification = EmberObject.create({ message: options.message, type: options.type || 'info', autoClear: (isEmpty(options.autoClear) ? getWithDefault(globals, 'autoClear', false) : options.autoClear), clearDuration: options.clearDuration || getWithDefault(globals, 'clearDuration', 3200), onClick: options.onClick, htmlContent: options.htmlContent || false, cssClasses: options.cssClasses }); this.content.pushObject(notification); if (notification.autoClear) { notification.set('remaining', notification.get('clearDuration')); this.setupAutoClear(notification); } return notification; }, // Helper methods for each type of notification error(message, options) { return this.addNotification(notificationAssign({ message: message, type: 'error' }, options)); }, success(message, options) { return this.addNotification(notificationAssign({ message: message, type: 'success' }, options)); }, info(message, options) { return this.addNotification(notificationAssign({ message: message, type: 'info' }, options)); }, warning(message, options) { return this.addNotification(notificationAssign({ message: message, type: 'warning' }, options)); }, removeNotification(notification) { if (!notification) { return; } notification.set('dismiss', true); // Delay removal from DOM for dismissal animation run.later(this, () => { this.content.removeObject(notification); }, 500); }, setupAutoClear(notification) { notification.set('startTime', Date.now()); const timer = run.later(this, () => { // Hasn't been closed manually if (this.content.indexOf(notification) >= 0) { this.removeNotification(notification); } }, notification.get('remaining')); notification.set('timer', timer); }, pauseAutoClear(notification) { run.cancel(notification.get('timer')); const elapsed = Date.now() - notification.get('startTime'); const remaining = notification.get('clearDuration') - elapsed; notification.set('remaining', remaining); }, clearAll() { this.get('content').forEach(notification => { this.removeNotification(notification); }); return this; }, setDefaultAutoClear(autoClear) { set(globals, 'autoClear', autoClear); }, setDefaultClearDuration(clearDuration) { set(globals, 'clearDuration', clearDuration); } });
JavaScript
0
@@ -468,20 +468,81 @@ %7B%0A +init() %7B%0A this._super(...arguments);%0A this.set(' content -: +', A() +);%0A %7D ,%0A%0A
a9887d2f7a4ab556832129fb26250194732d849d
clean code
src/routes.js
src/routes.js
import React from 'react'; import { Provider } from 'react-redux'; import store from './stores'; import { BrowserRouter as Router, hashHistory, Route, Link, Redirect, withRouter } from 'react-router-dom'; import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux'; import createHistory from 'history/createBrowserHistory' import App from './components/App'; import About from './components/About'; import HeaderBar from './components/HeaderBar'; import Albums from './components/Albums'; import Login from './components/Login'; import UserInfo from './components/UserInfo'; const Protected = () => <div><p>Protected Content</p><UserInfo /></div> const fakeAuth = { isAuthenticated: false, authenticate(cb) { this.isAuthenticated = true; setTimeout(cb, 100) //fake async }, signout(cb) { this.isAuthenticated = false; setTimeout(cb, 100) } }; const AuthButton = withRouter(({ history }) => ( fakeAuth.isAuthenticated ? ( <p> Welcome! <button onClick={() => { fakeAuth.signout(() => history.push('/')) }}>Sign out</button> </p> ) : ( <p>You are not logged in.</p> ) )); const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => { if (fakeAuth.isAuthenticated) { return <Component {...props}/> } else { return <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> } }} /> ); const history = createHistory(); const routes = <Provider store={store}> { /* ConnectedRouter will use the store from Provider automatically */ } <ConnectedRouter history={history}> <div> <HeaderBar /> <AuthButton /> <App /> <Route exact path="/" render={()=><h2>HOME PAGE</h2>} /> <Route path="/about" component={About} /> <Route path="/contact" render={() => ( <div> <Link to="/">HOME</Link> <hr /> <h1>CONTACT INFO</h1> </div> )} /> <Route path="/albums" component={Albums} /> <Route path="/login" component={Login}/> <PrivateRoute path="/protected" component={Protected} /> </div> </ConnectedRouter> </Provider> ; export {routes, fakeAuth};
JavaScript
0.000008
@@ -119,29 +119,8 @@ r as - Router, hashHistory, Rou @@ -205,32 +205,8 @@ uter -, routerMiddleware, push %7D f
5de009cd49b36cd942450bd9e7631c4d490bf0d6
change profile for username in server
src/server.js
src/server.js
var express = require('express'); var fs = require("fs"); var less = require("less"); var Path = require("path"); var http = require('http'); var url = require("url"); var prompt = require("prompt") var _3vot = require("3vot") var argv = require('optimist').argv; var devDomain = null; var Server = {} var Builder = require("./builder"); var Transform = require("./transform") module.exports = Server; Server.prompt = function(){ prompt.start(); prompt.get( [ { name: 'domain', description: 'Domain: ( If you are on nitrous.io type the preview domain with out http:// or trailing slashes / ) ' }], function (err, result) { Server.startServer( result.domain ) } ); }, Server.startServer = function( domain, callback ){ Server.serverCallback = callback; var app = express(); var pck = require( Path.join( process.cwd(), "3vot.json" ) ); var profile = pck.profile; // all environments app.set('port', 3000); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.get("/", function(req,res){ res.send("<h1>Congratulations 3VOT Local Server is Running</h1><h2>Now head to your app @ /YOURORG/YOURAPP</h2>"); }); app.get("/" + profile + "/:appName/assets/:asset", function(req, res) { var asset = req.params.asset; var appName = req.params.appName; var filePath = Path.join( process.cwd() , "apps", appName, "app", "assets", asset ); res.sendfile(filePath); }); app.get("/" + profile + "/dependencies/:name", function(req, res) { res.setHeader("Content-Type", "text/javascript"); fs.readFile( Path.join( process.cwd(), "apps", "dependencies", req.params.name ) , function(err, file){ if(err){ //get App Name From req.Host var urlParts = req.headers.referer.split("/") var appName = "" if( urlParts[ urlParts.length -1 ] === "" ){ appName = urlParts[ urlParts.length -2 ] } else{ appName = urlParts[ urlParts.length -1 ] } return res.redirect("/" + profile + "/dependencies/" + appName + "/build"); } return res.send(file); } ); }); app.get("/" + profile + "/dependencies/:appName/build", function(req, res) { res.setHeader("Content-Type", "text/javascript"); var appName = req.params.appName Builder.buildDependency( appName ) .then( function( contents ){ return res.send(contents); } ); } ); app.get("/" + profile + "/:appName/:device", function(req, res) { res.setHeader("Content-Type", "text/javascript"); var device = req.params.device; var appName = req.params.appName; fs.readFile( Path.join( process.cwd() , "apps", appName, "app", device) , function(err, contents){ if(err){ res.status(500); return res.send(err); } res.send(contents) } ); }); app.get("/" + profile + "/:appName", function(req, res) { var appName = req.params.appName; pck = require( Path.join( process.cwd(), "apps", appName, "package.json" ) ); Builder.buildApp( appName ) .then( function( html ){ //Tranforming Index to Localhost html = Transform.transformToLocalhost(html, pck, domain); return res.send( html ); } ).fail( function(err){ res.send( err.toString() ) } ); } ); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); if(Server.serverCallback) Server.serverCallback(); }); }
JavaScript
0
@@ -888,22 +888,23 @@ e = pck. -profil +usernam e;%0A //
eeb1a27408b6216927ef5f0f72417c342308e8da
migrate to express: continue 14
src/server.js
src/server.js
/** @file server.js @brief Node.JS Server. @author Oleg Kertanov <okertanov@gmail.com> @date May 2012 @copyright Copyright (C) 2012 Oleg Kertanov <okertanov@gmail.com> @license BSD @see LICENSE file */ (function() { // Strict mode by default "use strict"; // System modules var os = require('os'), fs = require('fs'), path = require('path'), express = require('express'); // App modules var ApiController = require('./api-controller.js').ApiController; // Pathes var ServerRoot = __filename, ProjectRoot = path.normalize(ServerRoot + '/../'), WWWRoot = path.normalize(ProjectRoot + '/wwwroot/'); // Configuration var Port = 8882; // Express application var app = express.createServer(); app.configure(function () { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); ApiController.Initialize(); ApiController.Route(app); // Server app.listen(Port); process.on('exit', function () { ApiController.Terminate(); }); })()
JavaScript
0.999218
@@ -1082,16 +1082,43 @@ on('exit +, uncaughtException, SIGINT ', funct @@ -1126,16 +1126,20 @@ on () %7B%0A + ApiC @@ -1161,16 +1161,20 @@ nate();%0A + %7D);%0A%0A%7D)(
40d394b4237c34d88b8bbef87579b7987b2f5b09
Fix session middleware signature
src/server.js
src/server.js
const bodyParser = require('body-parser'); const compression = require('compression'); const cookieParser = require('cookie-parser'); const cors = require('cors'); const csrf = require('csurf'); const session = require('express-session'); const passport = require('passport'); const auth = require('./auth'); const debug = require('debug')('cmyk:server'); const server = require('express')(); server.locals.port = process.env.PORT || 3000; server.locals.domain = process.env.NODE_ENV === 'production' ? 'https://api.cmyk.nyc' : `http://localhost:${server.locals.port}`; // Redirect for HTTPS server.set('trust proxy', true); server.use(function (req, res, next) { if (process.env.NODE_ENV !== 'production') return next(); // If https terminated by heroku, or express asserts the conn. is encrypted, // or the protocol matches https, then we're good! if (req.secure || req.headers['x-forwarded-proto'] === 'https' || req.connection.encrypted || req.protocol === 'https') { res.header( 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); next(); } else res.redirect(`https://${req.get('host')}${req.url}`); }); server.use(cors({origin: true, credentials: true})); server.use(compression()); server.use(bodyParser.json()); server.use(session({secret: auth.SECRET, cookie: auth.COOKIE})); server.use(cookieParser(auth.SECRET, auth.COOKIE)); server.use(csrf({cookie: true})); server.use(passport.initialize()); server.use(passport.session()); auth.github.connect(server); server.get('/logout', function logout (request, response) { request.logout(); response.clearCookie('authorization', { path: '/' }); response.redirect(request.get('referrer') || '/'); }); server.use('/', auth.requireUser, function (req, res, next) { res.send(req.user); next(); }); var connection = server.listen(server.locals.port, () => debug(`Listening at port ${connection.address().port}`));
JavaScript
0.000011
@@ -1336,24 +1336,19 @@ SECRET, -cookie: +... auth.COO
6d51a2607569ffb28db55dba42531b4939ca56f3
fix #573
src/csv_export_util.js
src/csv_export_util.js
/* eslint block-scoped-var: 0 */ /* eslint vars-on-top: 0 */ /* eslint no-var: 0 */ /* eslint no-unused-vars: 0 */ import Util from './util'; if (Util.canUseDOM()) { const filesaver = require('./filesaver'); var saveAs = filesaver.saveAs; } function toString(data, keys) { let dataString = ''; if (data.length === 0) return dataString; dataString += keys.map(x => x.header).join(',') + '\n'; data.map(function(row) { keys.map(function(col, i) { const { field, format } = col; const value = typeof format !== 'undefined' ? format(row[field]) : row[field]; const cell = typeof value !== 'undefined' ? ('"' + value + '"') : ''; dataString += cell; if (i + 1 < keys.length) dataString += ','; }); dataString += '\n'; }); return dataString; } const exportCSV = function(data, keys, filename) { const dataString = toString(data, keys); if (typeof window !== 'undefined') { saveAs(new Blob([ dataString ], { type: 'text/plain;charset=utf-8' }), filename); } }; export default exportCSV;
JavaScript
0.000001
@@ -564,16 +564,21 @@ w%5Bfield%5D +, row ) : row%5B
3035ece2b3cf95f8b686b31196412d30455f0516
add debug logs :
src/backend/models/users.js
src/backend/models/users.js
import { validate } from '../../common/schemas/user.js'; import { BadRequestError } from '../../common/errors.js'; import config from '../config.js'; import { getLogger } from '../log.js'; const log = getLogger('backend:models:users'); /** * Initialize the QueueManager data model * * @class */ export default class User { constructor(db) { this._db = db; } async create(user) { console.debug(`Creating user: ${user}`) try { const isValid = await validate(user); if (isValid) { return this._db.transaction(async trx => { const query = { username: user.username, role_name: user.role_name, }; log.debug('Inserting user'); await trx('users').insert(query); return trx('users') .select() .where({ username: user.username }) .first(); }); } else { throw new BadRequestError('User information is not valid.'); } } catch (err) { throw new BadRequestError('Failed to create user: ', err); } } async update(user) { try { const isValid = await validate(user); if (isValid) { return this._db.transaction(async trx => { const query = { username: user.username, role_name: user.role_name, }; log.debug('Updating user'); await trx('users') .update(query, ['id', 'username', 'role_name']) .where({ username: user.username }); return trx('users') .select() .where({ username: user.username }) .first(); }); } else { throw new BadRequestError('User information is not valid.'); } } catch (err) { throw new BadRequestError('Failed to create user: ', err); } } /** * Find user by Id * * @param {integer} id - Find user by id */ // eslint-disable-next-line no-unused-vars async findById(id) { if (config.authStrategy === 'oauth2') { return this._db .select({ id: 'users.id', username: 'users.username', role: 'users.role_name', }) .from('users') .where({ 'users.id': parseInt(id) }) .first(); } else { if (id === 1) { return { id: 1, username: config.adminUsername, password: config.adminPassword, role: 'admins', }; } else if (id === 2) { return { id: 2, username: config.viewerUsername, password: config.viewerPassword, role: 'viewers', }; } } } /** * Find user by username * * @param {integer} username - Find user by username */ // eslint-disable-next-line no-unused-vars async findByUsername(username) { if (config.authStrategy === 'oauth2') { return this._db .select({ id: 'users.id', username: 'users.username', role: 'users.role_name', }) .from('users') .where({ 'users.username': username }) .first(); } else { if (username === config.adminUsername) { return { id: 1, username: config.adminUsername, password: config.adminPassword, role: 'admins', }; } else if (username === config.viewerUsername) { return { id: 2, username: config.viewerUsername, password: config.viewerPassword, role: 'viewers', }; } } } /** * Find all users */ async findAll() { if (config.authStrategy === 'oauth2') { return this._db .select({ id: 'users.id', username: 'users.username', role: 'users.role_name', }) .from('users'); } else { return [ { id: 1, username: config.adminUsername, password: config.adminPassword, role: 'admins', }, { id: 2, username: config.viewerUsername, password: config.viewerPassword, role: 'viewers', }, ]; } } async isMemberOf(role, uid) { if (config.authStrategy === 'oauth2') { const user = await this._db .select({ id: 'users.id', username: 'users.username', role: 'users.role_name', }) .from('users') .where({ 'users.id': parseInt(uid) }) .first(); log.debug('User: ', user); log.debug('Role: ', role); return user.role ? user.role === role : false; } else { if ((role === 'admins' || role === 'editors') && uid === 1) return true; if (role === 'viewers' && uid === 2) return true; return false; } } /** * Stub for Oauth2 authentication */ async findOrCreateUser(user) { log.debug('findOrCreateUser: ', user); try { const exists = await this.findByUsername(user.username); if (!exists) { log.debug('User does not exist, creating'); return this.create(user); } else if (user.role_name !== exists.role) { log.debug('User role has changed, updating'); return this.update(user); } else { log.debug('Returning existing user'); return exists; } } catch (err) { throw new BadRequestError('Failed to create user: ', err); } } }
JavaScript
0
@@ -393,52 +393,8 @@ ) %7B%0A - console.debug(%60Creating user: $%7Buser%7D%60)%0A @@ -457,32 +457,77 @@ if (isValid) %7B%0A + log.debug(%60Creating user: $%7Buser%7D%60);%0A return t @@ -902,32 +902,73 @@ %0A %7D else %7B%0A + log.debug(%60Cannot create user%60);%0A throw ne
b3e06efba05fb82a0ce0c439ffc102fd0f65cb95
Fix error in Store
react-ui/src/index.js
react-ui/src/index.js
import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'react-redux'; import rootReducer from './reducers'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; import './styles/index.css'; const devTools = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() const store = createStore(rootReducer, devTools) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
JavaScript
0.000006
@@ -90,38 +90,32 @@ teStore %7D from ' -react- redux';%0Aimport r
25e40e7e8632dd2fe1ccf7bb5cc5f1cd952ba3a3
Remove android tests
protractor.conf.js
protractor.conf.js
var config = { baseUrl: 'http://localhost:4200/', specs: ['test/e2e/**/*.spec.js'], directConnect: false, exclude: [], allScriptsTimeout: 110000, getPageTimeout: 100000, framework: 'jasmine2', jasmineNodeOpts: { isVerbose: false, showColors: true, includeStackTrace: false, defaultTimeoutInterval: 400000, helpers: ['node_modules/jasmine-expect/index.js'] }, /** * ng2 related configuration * * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching * `rootEl` * */ useAllAngular2AppRoots: true }; if (process.env.TRAVIS) { var capabilities = [ // [platform, browsername, version] ['macOS 10.12', 'chrome', '59.0'], ['macOS 10.12', 'chrome', '58.0'], ['macOS 10.12', 'chrome', '49.0'], ['Windows 10', 'MicrosoftEdge', '14.14393'], ['Windows 10', 'MicrosoftEdge', '13.10586'], ['Linux', 'android', '6.0'] // TODO Selenium Driver problem for the following // ['macOS 10.12', 'safari', '10.0'], // ['Windows 10', 'internet explorer', '11.103'], // ['Windows 10', 'firefox', '50.0'], // TODO Problem calculating the target position in tests // ['OS X 10.10', 'iphone', '10.0'], // ['OS X 10.10', 'iphone', '9.3'] ]; // Override the baseUrl, as the port is a different one config.baseUrl = 'http://localhost:8000/'; config.multiCapabilities = capabilities.map(function (capability) { return { browserName: capability[1], platform: capability[0], version: capability[2], shardTestFiles: true, name: 'Ng2PageScroll', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER } }); config.sauceUser = process.env.SAUCE_USERNAME; config.sauceKey = process.env.SAUCE_ACCESS_KEY; config.sauceBuild = 'travis-build#' + process.env.TRAVIS_BUILD_NUMBER; } else { config.multiCapabilities = [{browserName: 'chrome'}]; } exports.config = config;
JavaScript
0
@@ -1006,16 +1006,101 @@ %0A + // TODO Check why getting window height does not work in android any more%0A // %5B'Linux
c4938c6ab09cce13785a5fd40fa1ff28312406d9
fix response details page
imports/startup/client/routes/responses.js
imports/startup/client/routes/responses.js
import { Clients } from '/imports/api/clients/clients'; import { PendingClients } from '/imports/api/pendingClients/pendingClients'; import Responses from '/imports/api/responses/responses'; import Surveys from '/imports/api/surveys/surveys'; import { AppController } from './controllers'; import '/imports/ui/responses/responsesListView'; import '/imports/ui/responses/responsesNew'; import '/imports/ui/responses/responsesEdit'; Router.route('adminDashboardresponsesView', { path: '/responses', template: Template.responsesListView, controller: AppController, waitOn() { return [ Meteor.subscribe('responses.all'), Meteor.subscribe('surveys.all'), ]; }, data() { return { title: 'Responses', subtitle: 'View', }; }, }); Router.route('adminDashboardresponsesNew', { path: '/responses/new', template: Template.responsesNew, controller: AppController, waitOn() { const { clientId, schema } = this.params.query; if (schema) { return [ Meteor.subscribe('clients.one', clientId, schema), Meteor.subscribe('surveys.all'), Meteor.subscribe('questions.all'), ]; } return [ Meteor.subscribe('pendingClients.one', clientId), Meteor.subscribe('surveys.all'), Meteor.subscribe('questions.all'), ]; }, data() { const { clientId, surveyId } = this.params.query; const survey = Surveys.findOne(surveyId); const client = PendingClients.findOne(clientId) || Clients.findOne(clientId); return { title: 'Responses', subtitle: 'New', survey, client, }; }, }); Router.route('adminDashboardresponsesEdit', { path: '/responses/:_id/edit', template: Template.responsesEdit, controller: AppController, waitOn() { return [ Meteor.subscribe('responses.one', this.params._id), Meteor.subscribe('surveys.all'), ]; }, data() { const response = Responses.findOne(this.params._id); return { title: 'Responses', subtitle: 'Edit', response, survey: response && Surveys.findOne(response.surveyID), }; }, });
JavaScript
0.000001
@@ -1883,32 +1883,73 @@ 'surveys.all'),%0A + Meteor.subscribe('questions.all'),%0A %5D;%0A %7D,%0A da
b7769c8897d47f625ae88d4880d0bc6f5fc96e95
Revert "Prefer NODE_ENV if it's there"
script/dist-info.js
script/dist-info.js
'use strict' const path = require('path') const os = require('os') const fs = require('fs') const projectRoot = path.join(__dirname, '..') const appPackage = require(path.join(projectRoot, 'app', 'package.json')) function getDistPath() { return path.join( projectRoot, 'dist', `${getProductName()}-${process.platform}-x64` ) } function getProductName() { const productName = appPackage.productName return process.env.NODE_ENV === 'development' ? `${productName}-dev` : productName } function getCompanyName() { return appPackage.companyName } function getVersion() { return appPackage.version } function getOSXZipName() { const productName = getProductName() return `${productName}.zip` } function getOSXZipPath() { return path.join(getDistPath(), '..', getOSXZipName()) } function getWindowsInstallerName() { const productName = getProductName() return `${productName}Setup.msi` } function getWindowsInstallerPath() { return path.join(getDistPath(), '..', 'installer', getWindowsInstallerName()) } function getWindowsStandaloneName() { const productName = getProductName() return `${productName}Setup.exe` } function getWindowsStandalonePath() { return path.join(getDistPath(), '..', 'installer', getWindowsStandaloneName()) } function getWindowsFullNugetPackageName() { return `${getWindowsIdentifierName()}-${getVersion()}-full.nupkg` } function getWindowsFullNugetPackagePath() { return path.join( getDistPath(), '..', 'installer', getWindowsFullNugetPackageName() ) } function getBundleID() { return appPackage.bundleID } function getUserDataPath() { if (process.platform === 'win32') { return path.join(process.env.APPDATA, getProductName()) } else if (process.platform === 'darwin') { const home = os.homedir() return path.join(home, 'Library', 'Application Support', getProductName()) } else { console.error(`I dunno how to review for ${process.platform} :(`) process.exit(1) } } function getWindowsIdentifierName() { return 'GitHubDesktop' } function getBundleSizes() { const rendererStats = fs.statSync( path.join(projectRoot, 'out', 'renderer.js') ) const mainStats = fs.statSync(path.join(projectRoot, 'out', 'main.js')) return { rendererSize: rendererStats.size, mainSize: mainStats.size } } function getReleaseChannel() { let branchName = '' if (process.platform === 'darwin') { branchName = process.env.TRAVIS_BRANCH } else if (process.platform === 'win32') { branchName = process.env.APPVEYOR_REPO_BRANCH } // Branch name format: __release-CHANNEL-DEPLOY_ID const pieces = branchName.split('-') if (pieces.length < 3 || pieces[0] !== '__release') { return process.env.NODE_ENV || 'development' } return pieces[1] } function getUpdatesURL() { return `https://central.github.com/api/deployments/desktop/desktop/latest?version=${getVersion()}&env=${getReleaseChannel()}` } module.exports = { getDistPath, getProductName, getCompanyName, getVersion, getOSXZipName, getOSXZipPath, getWindowsInstallerName, getWindowsInstallerPath, getWindowsStandaloneName, getWindowsStandalonePath, getWindowsFullNugetPackageName, getWindowsFullNugetPackagePath, getBundleID, getUserDataPath, getWindowsIdentifierName, getBundleSizes, getReleaseChannel, getUpdatesURL, }
JavaScript
0
@@ -2730,32 +2730,8 @@ turn - process.env.NODE_ENV %7C%7C 'de
5c2ce103004ed318c8b8ba826ed050840ef4e630
remove console.log
imports/startup/client/routes/responses.js
imports/startup/client/routes/responses.js
import { Clients } from '/imports/api/clients/clients'; import { PendingClients } from '/imports/api/pendingClients/pendingClients'; import Responses from '/imports/api/responses/responses'; import Surveys from '/imports/api/surveys/surveys'; import { ResponsesAccessRoles, PendingClientsAccessRoles, } from '/imports/config/permissions'; import { fullName } from '/imports/api/utils'; import { AppController } from './controllers'; import '/imports/ui/responses/responsesListView'; import '/imports/ui/responses/responsesNew'; import '/imports/ui/responses/responsesEdit'; import '/imports/ui/responses/responsesArchive'; Router.route('adminDashboardresponsesView', { path: '/responses', template: Template.responsesListView, controller: AppController, authorize: { allow() { return Roles.userIsInRole(Meteor.userId(), ResponsesAccessRoles); }, }, waitOn() { const { clientId, schema } = this.params.query; console.log('const { clientId, schema } = this.params.query;', clientId, schema); const subscriptions = [ Meteor.subscribe('responses.all', clientId, schema), Meteor.subscribe('surveys.all'), Meteor.subscribe('surveys.v1'), ]; if (clientId) { if (schema) { subscriptions.push(Meteor.subscribe('clients.one', clientId, schema, false)); } else { subscriptions.push(Meteor.subscribe('pendingClients.one', clientId)); } } return subscriptions; }, data() { const { clientId } = this.params.query; const client = PendingClients.findOne(clientId) || Clients.findOne(clientId); return { title: 'Responses', subtitle: clientId ? fullName(client) : 'View', client, clientId, }; }, }); Router.route('adminDashboardresponsesNew', { path: '/responses/new', template: Template.responsesNew, controller: AppController, authorize: { allow() { return Roles.userIsInRole(Meteor.userId(), PendingClientsAccessRoles); }, }, waitOn() { const { clientId, schema } = this.params.query; if (schema) { return [ Meteor.subscribe('clients.one', clientId, schema), Meteor.subscribe('surveys.all'), // Meteor.subscribe('questions.all'), ]; } return [ Meteor.subscribe('pendingClients.one', clientId), Meteor.subscribe('surveys.all'), // Meteor.subscribe('questions.all'), ]; }, data() { const { clientId, surveyId } = this.params.query; const survey = Surveys.findOne(surveyId); const client = PendingClients.findOne(clientId) || Clients.findOne(clientId); return { title: 'Responses', subtitle: 'New', survey, client, }; }, }); Router.route('adminDashboardresponsesEdit', { path: '/responses/:_id/edit', template: Template.responsesEdit, controller: AppController, authorize: { allow() { return Roles.userIsInRole(Meteor.userId(), PendingClientsAccessRoles); }, }, waitOn() { // TODO: subscribe client details return [ Meteor.subscribe('responses.one', this.params._id), Meteor.subscribe('surveys.all'), // TODO: we need survey id from response to sub just one Meteor.subscribe('questions.all'), ]; }, onBeforeAction() { // Redirect External Surveyor if (Roles.userIsInRole(Meteor.userId(), 'External Surveyor')) { const pausedResponse = Responses.findOne({ _id: Router.current().params._id, status: 'paused', }); if (!pausedResponse) { Bert.alert('This client has already been surveyed', 'danger', 'growl-top-right'); Router.go('dashboard'); } } this.next(); }, data() { const response = Responses.findOne(this.params._id); if (!response) return {}; const { clientId, clientSchema } = response; const clientStub = { // TODO: get client data via subscription _id: clientId, schema: clientSchema, }; if (clientSchema) { Meteor.subscribe('clients.one', clientId, clientSchema); } if (response.version < 2) { Router.go('responsesArchive', { _id: this.params._id }); return {}; } const survey = Surveys.findOne(response.surveyId); return { title: 'Responses', subtitle: 'Edit', response, survey, client: Clients.findOne(clientId) || clientStub, }; }, }); Router.route('responsesArchive', { path: '/responses/:_id/archive', template: Template.responsesArchive, controller: AppController, authorize: { allow() { return Roles.userIsInRole(Meteor.userId(), ResponsesAccessRoles); }, }, waitOn() { // TODO: subscribe client details return [ Meteor.subscribe('responses.one', this.params._id), Meteor.subscribe('surveys.v1'), Meteor.subscribe('questions.v1'), ]; }, data() { const response = Responses.findOne(this.params._id); if (!response) { return {}; } const survey = Surveys.findOne(response.surveyId); return { title: 'Responses', subtitle: 'Archive', response, survey, client: { // TODO: get client data via subscription _id: response.clientId, schema: response.clientSchema, }, }; }, });
JavaScript
0.000006
@@ -942,94 +942,8 @@ y;%0A%0A - console.log('const %7B clientId, schema %7D = this.params.query;', clientId, schema);%0A
de58628b61438197b5e0999ce95494f261539cd8
Make sure both lat & lng present
addon/components/street-view.js
addon/components/street-view.js
/* global google */ import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['street-view-container'], map: null, panorama: null, lat: null, lng: null, zoom: 0, pov: null, height: null, width: null, // controls panControl: null, panControlOptions: null, zoomControl: null, zoomControlOptions: null, addressControl: null, addressControlOptions: null, linksControl: null, // events panoDidChange: Ember.K, _panoChanged() { this.panoDidChange(); let panorama = this.get('panorama'); this.sendAction('panoChanged', panorama); }, linksDidChange: Ember.K, _linksChanged() { this.linksDidChange(); let panorama = this.get('panorama'); this.sendAction('linksChanged', panorama); }, povDidChange: Ember.K, _povChanged() { this.povDidChange(); let panorama = this.get('panorama'); this.sendAction('povChanged', panorama); }, positionDidChange: Ember.K, _positionChanged() { this.positionDidChange(); let panorama = this.get('panorama'); let position = panorama.getPosition(); this.sendAction('positionChanged', { lat: position.lat(), lng: position.lng() }, panorama); }, updatePanoramaPosition: Ember.observer('lat', 'lng', function() { let lat = this.get('lat'); let lng = this.get('lng'); let panorama = this.get('panorama'); if (panorama) { panorama.setPosition({lat, lng}); } }), didInsertElement() { this.createStreetView(); }, createOptionsObject() { let position = new google.maps.LatLng(this.lat, this.lng); let optionsKeys = [ "pov", "zoom", "panControl", "panControlOptions", "zoomControl", "zoomControlOptions", "addressControl", "addressControlOptions", "linksControl" ]; let optionsProperties = [ this.pov, this.zoom, this.panControl, this.panControlOptions, this.zoomControl, this.zoomControlOptions, this.addressControl, this.addressControlOptions, this.linksControl ]; let options = { position: position }; for(let i=0; i < optionsProperties.length; i++) { if( optionsProperties[i] !== null ) { options[optionsKeys[i]] = optionsProperties[i]; } } return options; }, createStreetView() { let options = this.createOptionsObject(); let width = this.width; let height = this.height; this.$().css({width: width, height: height}); let panorama = new google.maps.StreetViewPanorama(this.$().get(0), options); panorama.addListener('pano_changed', Ember.run.bind(this, '_panoChanged')); panorama.addListener('links_changed', Ember.run.bind(this, '_linksChanged')); panorama.addListener('position_changed', Ember.run.bind(this, '_positionChanged')); panorama.addListener('pov_changed', Ember.run.bind(this, '_povChanged')); this.set('panorama', panorama); let map = this.get('map'); if (map) { map.setStreetView(panorama); panorama.setPosition(map.getCenter()); } } });
JavaScript
0.000002
@@ -41,16 +41,71 @@ mber';%0A%0A +const %7B%0A K,%0A on,%0A observer,%0A Component%0A%7D = Ember;%0A%0A export d @@ -111,22 +111,16 @@ default -Ember. Componen @@ -498,30 +498,24 @@ oDidChange: -Ember. K,%0A _panoCh @@ -657,30 +657,24 @@ sDidChange: -Ember. K,%0A _linksC @@ -813,38 +813,32 @@ povDidChange: -Ember. K,%0A _povChanged @@ -980,22 +980,16 @@ Change: -Ember. K,%0A _po @@ -1266,22 +1266,27 @@ sition: -Ember. +on('init', observer @@ -1433,16 +1433,30 @@ panorama + && lat && lng ) %7B pano @@ -1491,16 +1491,17 @@ ; %7D%0A %7D) +) ,%0A%0A did
f4329297d1d4dec948d2a4e77ddcc12d9d2ef381
Update authors
js/LevelSelectionItemNode.js
js/LevelSelectionItemNode.js
// Copyright 2014-2017, University of Colorado Boulder /** * Button for selecting a game level. * Also depicts the progress made on each level. * * @author John Blanco * @author Chris Malley */ define( function( require ) { 'use strict'; // modules var Dimension2 = require( 'DOT/Dimension2' ); var GameTimer = require( 'VEGAS/GameTimer' ); var inherit = require( 'PHET_CORE/inherit' ); var Node = require( 'SCENERY/nodes/Node' ); var PhetFont = require( 'SCENERY_PHET/PhetFont' ); var ScoreDisplayDiscreteStars = require( 'VEGAS/ScoreDisplayDiscreteStars' ); var ScoreDisplayNumberAndStar = require( 'VEGAS/ScoreDisplayNumberAndStar' ); var ScoreDisplayTextAndNumber = require( 'VEGAS/ScoreDisplayTextAndNumber' ); var Rectangle = require( 'SCENERY/nodes/Rectangle' ); var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' ); var Tandem = require( 'TANDEM/Tandem' ); var Text = require( 'SCENERY/nodes/Text' ); var vegas = require( 'VEGAS/vegas' ); // constants var SCALING_TOLERANCE = 1E-4; // Empirically chosen as something the human eye is unlikely to notice. /** * @param {Node} icon Scenery node that appears on the button above the progress indicator, scaled to fit * @param {number} numStars Number of stars to show in the progress indicator at the bottom of the button * @param {function} fireFunction Called when the button fires * @param {Property.<number>} scoreProperty * @param {number} perfectScore * @param {Object} [options] * @constructor */ function LevelSelectionItemNode( icon, numStars, fireFunction, scoreProperty, perfectScore, options ) { // TODO: numStars and perfectScore not necessarily necessary assert && assert( icon instanceof Node ); assert && assert( typeof numStars === 'number' ); options = _.extend( { // score display type scoreDisplayType: 'discreteStars', // or 'numberAndStar' or 'textAndNumber' // button size and appearance buttonWidth: 150, buttonHeight: 150, cornerRadius: 10, baseColor: 'rgb( 242, 255, 204 )', buttonXMargin: 10, buttonYMargin: 10, // progress indicator (stars) progressIndicatorProportion: 0.2, // percentage of the button height occupied by the progress indicator, (0,0.5] progressIndicatorMinXMargin: 10, progressIndicatorMinYMargin: 5, iconToProgressIndicatorYSpace: 10, // best time (optional) bestTimeProperty: null, // null if no best time || {Property.<number>} best time in seconds bestTimeVisibleProperty: null, // null || Property.<boolean>} controls visibility of best time bestTimeFill: 'black', bestTimeFont: new PhetFont( 24 ), bestTimeYSpacing: 10, // vertical space between drop shadow and best time // Tandem tandem: Tandem.required }, options ); Node.call( this ); assert && assert( options.progressIndicatorProportion > 0 && options.progressIndicatorProportion <= 0.5, 'progressIndicatorProportion value out of range' ); var maxContentWidth = options.buttonWidth - 2 * options.buttonXMargin; // Progress indicator (stars), scaled to fit var progressIndicatorBackground = new Rectangle( 0, 0, maxContentWidth, options.buttonHeight * options.progressIndicatorProportion, options.cornerRadius, options.cornerRadius, { fill: 'white', stroke: 'black', lineWidth: 1, pickable: false } ); var scoreDisplayOptions = { pickable: false }; // TODO: assert options.scoreDisplayType provided is right if ( options.scoreDisplayType === 'discreteStars' ) { var progressIndicator = new ScoreDisplayDiscreteStars( scoreProperty, _.extend( {}, scoreDisplayOptions, { numStars: numStars, perfectScore: perfectScore, } ) ); } else if ( options.scoreDisplayType === 'numberAndStar' ) { progressIndicator = new ScoreDisplayNumberAndStar( scoreProperty, scoreDisplayOptions ); } else { progressIndicator = new ScoreDisplayTextAndNumber( scoreProperty, scoreDisplayOptions ); } progressIndicator.scale( Math.min( ( progressIndicatorBackground.width - 2 * options.progressIndicatorMinXMargin ) / progressIndicator.width, ( progressIndicatorBackground.height - 2 * options.progressIndicatorMinYMargin ) / progressIndicator.height ) ); // Icon, scaled and padded to fit and to make the button size correct. var iconSize = new Dimension2( maxContentWidth, options.buttonHeight - progressIndicatorBackground.height - 2 * options.buttonYMargin - options.iconToProgressIndicatorYSpace ); var adjustedIcon = LevelSelectionItemNode.createSizedImageNode( icon, iconSize ); adjustedIcon.pickable = false; // TODO: is this needed? // Assemble the content. var contentNode = new Node(); if ( progressIndicatorBackground.width > adjustedIcon.width ) { adjustedIcon.centerX = progressIndicatorBackground.centerX; } else { progressIndicatorBackground.centerX = adjustedIcon.centerX; } progressIndicatorBackground.top = adjustedIcon.bottom + options.iconToProgressIndicatorYSpace; progressIndicator.center = progressIndicatorBackground.center; contentNode.addChild( adjustedIcon ); contentNode.addChild( progressIndicatorBackground ); contentNode.addChild( progressIndicator ); // Create the button var buttonOptions = { content: contentNode, xMargin: options.buttonXMargin, yMargin: options.buttonYMargin, baseColor: options.baseColor, cornerRadius: options.cornerRadius, listener: fireFunction, // TODO: if LevelSelectionItemNode changes to inheritance, this will have to change, see https://github.com/phetsims/vegas/issues/56 tandem: options.tandem.createTandem( 'button' ) }; var button = new RectangularPushButton( buttonOptions ); this.addChild( button ); // Best time (optional), centered below the button, does not move when button is pressed if ( options.bestTimeProperty ) { var bestTimeNode = new Text( '', { font: options.bestTimeFont, fill: options.bestTimeFill } ); this.addChild( bestTimeNode ); options.bestTimeProperty.link( function( bestTime ) { bestTimeNode.text = ( bestTime ? GameTimer.formatTime( bestTime ) : '' ); bestTimeNode.centerX = button.centerX; bestTimeNode.top = button.bottom + options.bestTimeYSpacing; } ); if ( options.bestTimeVisibleProperty ) { options.bestTimeVisibleProperty.linkAttribute( bestTimeNode, 'visible' ); } } // Pass options to parent class this.mutate( options ); } vegas.register( 'LevelSelectionItemNode', LevelSelectionItemNode ); return inherit( Node, LevelSelectionItemNode, {}, { /** * Creates a new the same dimensions as size with the specified icon. The icon will be scaled to fit, and a * background with the specified size may be added to ensure the bounds of the returned node are correct. * @public * * @param {Node} icon * @param {Dimension2} size * @returns {Node} */ createSizedImageNode: function( icon, size ) { icon.scale( Math.min( size.width / icon.bounds.width, size.height / icon.bounds.height ) ); if ( Math.abs( icon.bounds.width - size.width ) < SCALING_TOLERANCE && Math.abs( icon.bounds.height - size.height ) < SCALING_TOLERANCE ) { // The aspect ratio of the icon matched that of the specified size, so no padding is necessary. return icon; } // else padding is needed in either the horizontal or vertical direction. var background = Rectangle.dimension( size, { fill: null } ); icon.center = background.center; background.addChild( icon ); return background; } } ); } );
JavaScript
0
@@ -190,16 +190,38 @@ Malley%0A + * @author Andrea Lin%0A */%0Adefi
47f7a0d3f72afe9613f40e7e51bc27aca80dcb5a
Create basic Boid class with properties
src/sketch.js
src/sketch.js
function setup() { // put setup code here } function draw() { // put drawing code here }
JavaScript
0
@@ -18,30 +18,31 @@ %7B%0A -// put setup code here +createCanvas(640, 480); %0A%7D%0A%0A @@ -65,31 +65,197 @@ %7B%0A -// put drawing code here +ellipse(50, 50, 80, 80);%0A%7D%0A%0A/**%0A * Boid class%0A */%0Afunction Boid() %7B%0A this.location = createVector();%0A this.velocity = createVector();%0A this.acceleration = createVector();%0A this.mass = 0; %0A%7D%0A
6bc7e898fa68f0770b916a4da2f17407f2fc1c82
Add protractor reporters
protractor.conf.js
protractor.conf.js
exports.config = { baseUrl: 'https://t7h-ci-kit.herokuapp.com', capabilities: { 'browserName': 'chrome' }, sauceUser: 'stremann', sauceKey: '0ecb489b-6279-4011-9fad-9ccf73037f2e', specs: ['test/e2e/*.js'] };
JavaScript
0
@@ -61,16 +61,54 @@ p.com',%0A + reporters: %5B'dots', 'saucelabs'%5D,%0A capa
4106ab94e178db2aea48033e28678a62bf4ddafc
extend jQuery for non case sensitive contains; add ELR utility functions
js/assets/elr-tablefilter.js
js/assets/elr-tablefilter.js
const $ = require('jquery'); const elrTableFilter = function(params) { const self = {}; const spec = params || {}; const tableClass = spec.tableClass || 'elr-searchable-table'; const searchInput = spec.searchInput || 'elr-search-table'; const $table = $(`.${tableClass}`); const getFilterValues = function($inputs) { let filterValues = []; $.each($inputs, function(k,v) { const $that = $(v); if ( $.trim($that.val()).length ) { filterValues.push(v); } return filterValues; }); return filterValues; }; const getRows = function($fullRows, filterValues) { let $newRows; $.each(filterValues, function(k,v) { const $that = $(v); const input = $.trim($that.val()).toLowerCase(); const columnNum = $that.closest('th').index(); if ( filterValues.length === 1 ) { $newRows = $fullRows.has(`td:eq(${columnNum}):containsNC(${input})`); } else if ( k === 0 ) { $newRows = $fullRows.has(`td:eq(${columnNum}):containsNC(${input})`); } else { $newRows = $newRows.has(`td:eq(${columnNum}):containsNC(${input})`); } return $newRows; }); return $newRows; }; const filterRows = function($fullRows, filterValues) { if ( filterValues.length === 0 ) { return $fullRows; } else { return getRows($fullRows, filterValues); } }; const renderTable = function($table, $filteredRows) { const $tableBody = $table.find('tbody').empty(); $.each($filteredRows, function(k,v) { $tableBody.append(v); }); }; $table.each(function() { const $that = $(this); const $fullRows = $that.find('tbody tr'); const $inputs = $that.find('th').find(`.${searchInput}`); $that.on('keyup', `input.${searchInput}`, function() { const filterValues = getFilterValues($inputs); const $filteredRows = filterRows($fullRows, filterValues); renderTable($that, $filteredRows); }); }); return self; }; export default elrTableFilter;
JavaScript
0
@@ -1,30 +1,295 @@ -const $ = require('jquery' +import elrUtlities from './elr-utilities';%0Aconst $ = require('jquery');%0A%0Alet elr = elrUtlities();%0A%0A$.extend($.expr%5B':'%5D, %7B%0A containsNC: function(elem, i, match) %7B%0A return (elem.textContent %7C%7C elem.innerText %7C%7C '').toLowerCase().indexOf((match%5B3%5D %7C%7C '').toLowerCase()) %3E= 0;%0A %7D%0A%7D );%0A%0A @@ -637,25 +637,27 @@ %5D;%0A%0A -$ +elr .each($input @@ -725,17 +725,19 @@ if ( -$ +elr .trim($t @@ -977,25 +977,27 @@ s;%0A%0A -$ +elr .each(filter @@ -1078,17 +1078,19 @@ input = -$ +elr .trim($t @@ -1971,17 +1971,19 @@ -$ +elr .each($f
3c483bca3b4c7356e5ec73f5ffbb3da095e472a3
Add ability to define several mappings for same action
src/solean.js
src/solean.js
'use strict'; angular.module('solean', []) .provider('soleanConfig', function(){ var config = { 'mapping':{ 'moveBackward': 37, 'moveForward': 39, 'carriageReturn': 13 }, 'promptLabel': '$ ', 'welcomeMessage': null, 'handleCommand': function(command) { return command; } }; return { config: config, $get: function() { return config; } } }) .directive('soleanTerminal', ['soleanConfig', function(config) { return { restrict: 'AEC', scope: true, template: '<span class="solean-welcome-message" ng-if="welcomeMessage">{{ welcomeMessage }}</span>' + '<div class="solean-command-block" ng-repeat="command in commands track by $index">' + '<div>' + '<span class="solean-prompt-label">{{ promptLabel }}</span>' + '<span ng-if="!$last" class="solean-command">{{ command.command }}</span>' + '<span ng-if="$last" class="solean-command"><span ng-repeat="character in command.command track by $index" ng-class="{\'solean-cursor\':$index==cursorIndex}">{{ character === " " ? "&nbsp;" : character }}</span></span>' + '<span ng-if="$last && cursorIndex === null" class="solean-cursor" ng-init="scrollDown();">&nbsp;</span>' + '</div>' + '<div>' + '<span ng-if="command.valid" class="solean-valid-{{ command.valid.code }}">{{ command.valid.message }}</span>' + '<span ng-if="command.invalid" class="solean-invalid-{{ command.invalid.code }}">{{ command.invalid.message }}</span>' + '</div>' + '</div>' + '<textarea style="position:fixed;left:-9999px;" ng-keyup="handleInput($event);" ng-model="commands[commands.length-1].command" class="solean-typer" ng-trim="false"></textarea>', link: function link(scope, element) { scope.promptLabel = config.promptLabel; scope.welcomeMessage = config.welcomeMessage; scope.cursorIndex = null; var handleCommand = config.handleCommand; scope.handleInput = function(event) { switch(event.keyCode) { case config.mapping.carriageReturn: normalizeCurrentCommand(); newCommand(); break; case config.mapping.moveForward: moveCursorForward(); break; case config.mapping.moveBackward: moveCursorBackward(); break; default: followTyping(); } }; scope.scrollDown = function() { element[0].scrollTop = element[0].scrollHeight; }; var normalizeCurrentCommand = function() { var command = scope.commands[scope.commands.length - 1]; command.command = command.command.replace('\n',''); if(handleCommand) { command = handleCommand(command); } scope.commands[scope.commands.length - 1] = command; }; var newCommand = function() { scope.commands.push({'command':''}); }; var moveCursorForward = function() { scope.cursorIndex = scope.cursorIndex !== null && scope.cursorIndex + 1 < element.find('textarea')[0].value.length ? element.find('textarea')[0].selectionStart : null; }; var moveCursorBackward = function() { scope.cursorIndex = element.find('textarea')[0].selectionStart; }; var followTyping = function() { scope.cursorIndex = scope.cursorIndex !== null ? element.find('textarea')[0].selectionStart : null; }; element.on('click', function() { element.find('textarea')[0].focus(); }); scope.commands = []; newCommand(); } }; }]);
JavaScript
0
@@ -118,24 +118,28 @@ g':%7B%0A + 37: 'moveBackwa @@ -145,12 +145,8 @@ ard' -: 37 ,%0A @@ -150,16 +150,20 @@ %0A + 39: 'moveFo @@ -172,12 +172,8 @@ ard' -: 39 ,%0A @@ -177,16 +177,20 @@ %0A + 13: 'carria @@ -202,12 +202,8 @@ urn' -: 13 %0A @@ -2086,24 +2086,25 @@ on(event) %7B%0A +%0A sw @@ -2108,16 +2108,31 @@ switch( +config.mapping%5B event.ke @@ -2136,16 +2136,17 @@ .keyCode +%5D )%0A @@ -2166,31 +2166,17 @@ case -config.mapping. +' carriage @@ -2181,16 +2181,17 @@ geReturn +' :%0A @@ -2279,39 +2279,25 @@ case -config.mapping. +' moveForward: @@ -2291,24 +2291,25 @@ 'moveForward +' :%0A @@ -2369,23 +2369,9 @@ ase -config.mapping. +' move @@ -2378,16 +2378,17 @@ Backward +' :%0A
5d67805864b6c7464c6ff6b6e73c0e6ec45ff976
simplify getting unique sim/version array algorithm, https://github.com/phetsims/perennial/issues/131
js/grunt/printPhetioLinks.js
js/grunt/printPhetioLinks.js
// Copyright 2019, University of Colorado Boulder /** * Print the list of production sims for clients. * * @author Michael Kauzmann (PhET Interactive Simulations) * @author Sam Reid (PhET Interactive Simulations) * @author Chris Klusendorf (PhET Interactive Simulations) */ 'use strict'; const getDependencies = require( '../common/getDependencies' ); const gitCheckout = require( '../common/gitCheckout' ); const gitIsAncestor = require( '../common/gitIsAncestor' ); const simPhetioMetadata = require( '../common/simPhetioMetadata' ); module.exports = async () => { // {Array.<Object>} get sim metadata via metadata api, here is an example of what an entry might look like: /* { "versionMaintenance": 12, "name": "molarity", "active": true, "versionMajor": 1, "versionMinor": 4, "versionSuffix": "", "latest": true, "timestamp": "2019-10-25" } */ const allSimsData = await simPhetioMetadata( { active: true, latest: true } ); const filtered = allSimsData.filter( simData => simData.active && simData.latest ); // store only the latest version per sim in this map const oneVersionPerSimMap = {}; // go through all versions and assign it to the map if it is a "later version" that that which is currently stored. for ( const simData of filtered ) { const simName = simData.name; oneVersionPerSimMap[ simName ] = oneVersionPerSimMap[ simName ] || simData; if ( compareVersionNumber( oneVersionPerSimMap[ simName ], simData ) < 0 ) { oneVersionPerSimMap[ simName ] = simData; } } // convert the map into an array of the sim versions const oneVersionPerSimList = Object.keys( oneVersionPerSimMap ).sort().map( name => oneVersionPerSimMap[ name ] ); const phetioLinks = []; for ( const simData of oneVersionPerSimList ) { const useTopLevelIndex = await usesTopLevelIndex( simData.name, getBranch( simData ) ); phetioLinks.push( `https://phet-io.colorado.edu/sims/${simData.name}/${getVersion( simData )}/${useTopLevelIndex ? '' : 'wrappers/index/'}` ); } console.log( 'Latest Links:' ); console.log( `\n${phetioLinks.join( '\n' )}` ); }; /** * Returns whether phet-io Studio is being used instead of deprecated instance proxies wrapper. * * @param {string} repo * @param {string} branch * @returns {Promise.<boolean>} */ async function usesTopLevelIndex( repo, branch ) { await gitCheckout( repo, branch ); const dependencies = await getDependencies( repo ); const sha = dependencies.chipper.sha; await gitCheckout( repo, 'master' ); return await gitIsAncestor( 'chipper', '8db0653ee0cbb6ed716fa3b4d4759bcb75d8118a', sha ); } // {Object} metadata -> version string const getVersion = simData => `${simData.versionMajor}.${simData.versionMinor}`; // {Object} metadata -> branch name const getBranch = simData => { let branch = `${simData.versionMajor}.${simData.versionMinor}`; if ( simData.versionSuffix.length ) { branch += '-' + simData.versionSuffix; // additional dash required } return branch; }; /** * See SimVersion.compareNumber() * @param {Object} version1 - value returned by the phet-io metadata client. * @param {Object} version2 * @returns {number} */ const compareVersionNumber = ( version1, version2 ) => { if ( version1.versionMajor < version2.versionMajor ) { return -1; } if ( version1.versionMajor > version2.versionMajor ) { return 1; } if ( version1.versionMinor < version2.versionMinor ) { return -1; } if ( version1.versionMinor > version2.versionMinor ) { return 1; } if ( version1.versionMaintenance < version2.versionMaintenance ) { return -1; } if ( version1.versionMaintenance > version2.versionMaintenance ) { return 1; } return 0; // equal };
JavaScript
0.000001
@@ -290,16 +290,94 @@ rict';%0A%0A +const _ = require( 'lodash' ); // eslint-disable-line require-statement-match%0A const ge @@ -1071,762 +1071,379 @@ %0A%0A -const filtered = allSimsData.filter( simData =%3E simData.active && simData.latest );%0A%0A // store only the latest version per sim in this map%0A const oneVersionPerSimMap = %7B%7D;%0A%0A // go through all versions and assign it to the map if it is a %22later version%22 that that which is currently stored.%0A for ( const s +// Get a list of sim versions where the highest versions of each sim are first.%0A const sortedAndReversed = _.sortBy( allS im +s Data - of filtered ) %7B%0A const simName = simData.name;%0A oneVersionPerSimMap%5B simName %5D = oneVersionPerSimMap%5B simName %5D %7C%7C simData;%0A if ( compareVersionNumber( oneVersionPerSimMap%5B simName %5D, simData ) %3C 0 ) %7B%0A oneVersionPerSimMap%5B simName %5D = simData;%0A %7D%0A %7D%0A%0A // convert the map into an array of the sim versions%0A const oneVersionPerSimList = Object.keys( oneVersionPerSimMap ).sort().map( name =%3E oneVersionPerSimMap%5B name %5D +, simData =%3E %60$%7BsimData.name%7D$%7BgetVersion( simData )%7D%60 ).reverse();%0A%0A // Get rid of all lower versions, then reverse back to alphabetical sorting.%0A const oneVersionPerSimList = _.uniqBy( sortedAndReversed, simData =%3E simData.name ).reverse( );%0A%0A @@ -2750,695 +2750,4 @@ ;%0A%7D; -%0A%0A/**%0A * See SimVersion.compareNumber()%0A * @param %7BObject%7D version1 - value returned by the phet-io metadata client.%0A * @param %7BObject%7D version2%0A * @returns %7Bnumber%7D%0A */%0Aconst compareVersionNumber = ( version1, version2 ) =%3E %7B%0A if ( version1.versionMajor %3C version2.versionMajor ) %7B return -1; %7D%0A if ( version1.versionMajor %3E version2.versionMajor ) %7B return 1; %7D%0A if ( version1.versionMinor %3C version2.versionMinor ) %7B return -1; %7D%0A if ( version1.versionMinor %3E version2.versionMinor ) %7B return 1; %7D%0A if ( version1.versionMaintenance %3C version2.versionMaintenance ) %7B return -1; %7D%0A if ( version1.versionMaintenance %3E version2.versionMaintenance ) %7B return 1; %7D%0A return 0; // equal%0A%7D;
bbc0cdab50790d20eb95a46ecb011dd252bf56a1
Use proper value center (not middle) for `<FlexParent horizontalAlignment>` attribute
src/splash.js
src/splash.js
/* eslint-disable import/no-unresolved */ import React from 'react'; import ReactDOM from 'react-dom'; // Styling import { FlexParent, FlexChild } from 'react-foundation-components/lib/flex'; import './splash.css'; import './logo.png'; import './splashFilters.jpg'; import 'react-foundation-components/lib/_typography.scss'; const App = () => { return ( <FlexParent id="splashContainer" horizontalAlignment="middle" verticalAlignment="middle"> <FlexChild> <a href="http://localhost:3000/#mapSummer"> <img id="map" role="presentation" src="http://localhost:3000/splashFilters.jpg" /> </a> </FlexChild> </FlexParent> ); }; ReactDOM.render(<App />, document.getElementById('app'));
JavaScript
0.000001
@@ -411,22 +411,22 @@ gnment=%22 -middle +center %22 vertic
d8117ba87fab063efb72004f643582fb908ac43b
Update master
js/i18n/grid.locale-pt-br.js
js/i18n/grid.locale-pt-br.js
;(function($){ /** * jqGrid Brazilian-Portuguese Translation * Sergio Righi sergio.righi@gmail.com * http://curve.com.br * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = $.jgrid || {}; $.extend($.jgrid,{ defaults : { recordtext: "Ver {0} - {1} of {2}", emptyrecords: "Nenhum registro para visualizar", loadtext: "Carregando...", pgtext : "Página {0} de {1}" }, search : { caption: "Procurar...", Find: "Procurar", Reset: "Resetar", odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], matchText: " iguala", rulesText: " regras" }, edit : { addCaption: "Incluir", editCaption: "Alterar", bSubmit: "Enviar", bCancel: "Cancelar", bClose: "Fechar", saveData: "Os dados foram alterados! Salvar alterações?", bYes : "Sim", bNo : "Não", bExit : "Cancelar", msg: { required:"Campo obrigatório", number:"Por favor, informe um número válido", minValue:"valor deve ser igual ou maior que ", maxValue:"valor deve ser menor ou igual a", email: "este e-mail não é válido", integer: "Por favor, informe um valor inteiro", date: "Por favor, informe uma data válida", url: "não é uma URL válida. Prefixo obrigatório ('http://' or 'https://')", nodefined : " não está definido!", novalue : " um valor de retorno é obrigatório!", customarray : "Função customizada deve retornar um array!", customfcheck : "Função customizada deve estar presente em caso de validação customizada!" } }, view : { caption: "Ver Registro", bClose: "Fechar" }, del : { caption: "Apagar", msg: "Apagar registros selecionado(s)?", bSubmit: "Apagar", bCancel: "Cancelar" }, nav : { edittext: " ", edittitle: "Alterar registro selecionado", addtext:" ", addtitle: "Incluir novo registro", deltext: " ", deltitle: "Apagar registro selecionado", searchtext: " ", searchtitle: "Procurar registros", refreshtext: "", refreshtitle: "Recarrgando Tabela", alertcap: "Aviso", alerttext: "Por favor, selecione um registro", viewtext: "", viewtitle: "Ver linha selecionada" }, col : { caption: "Mostrar/Esconder Colunas", bSubmit: "Enviar", bCancel: "Cancelar" }, errors : { errcap : "Erro", nourl : "Nenhuma URL defenida", norecords: "Sem registros para exibir", model : "Comprimento de colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "R$ ", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado" ], monthNames: [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez", "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['º', 'º', 'º', 'º'][Math.min((j - 1) % 10, 3)] : 'º'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }); })(jQuery);
JavaScript
0
@@ -117,16 +117,69 @@ .com.br%0A + * %0A * Updated by Jonnas Fonini%0A * http://fonini.net%0A * Dual @@ -219,16 +219,16 @@ censes:%0A - * http: @@ -408,10 +408,10 @@ %7B1%7D -of +de %7B2%7D @@ -637,199 +637,187 @@ : %5B' -eq +ig ual', ' -not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not +diferente', 'menor', 'menor ou igual','maior','maior ou igual', 'inicia com','n%C3%A3o inicia com','est%C3%A1 em','n%C3%A3o est%C3%A1 em','termina com','n%C3%A3o termina com','cont%C3%A9m','n%C3%A3o cont -ain +%C3%A9m '%5D,%0A @@ -911,16 +911,17 @@ %22 igual + a%22,%0A%09%09ru @@ -2013,17 +2013,19 @@ registro -s +(s) selecio @@ -2396,15 +2396,16 @@ carr +e gando -T +t abel @@ -2702,17 +2702,17 @@ URL def -e +i nida%22,%0A%09
e0960422be24e43e502cd0b24769e106cb5f8736
Make more stable
content/composeOverlay.js
content/composeOverlay.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var ReplyToAllAsCc = { isReplyAll: function() { return gMsgCompose.type == Components.interfaces.nsIMsgCompType.ReplyAll; }, getOriginalSender: function() { var originalHdr = this.getMsgHdrFromURI(gMsgCompose.originalMsgURI); var sender = this.extractAddresses(originalHdr.mime2DecodedAuthor); return sender.length > 0 ? sender[0] : null ; }, getMsgHdrFromURI: function(aURI) { return Components.classes['@mozilla.org/messenger;1'] .getService(Components.interfaces.nsIMessenger) .msgHdrFromURI(aURI); }, extractAddresses: function(aAddressesWithComments) { var parser = Components.classes['@mozilla.org/messenger/headerparser;1'] .getService(Components.interfaces.nsIMsgHeaderParser); var addresses = {}; var names = {}; var fullNames = {}; var count = {}; parser.parseHeadersWithArray(aAddressesWithComments, addresses, names, fullNames, count); return addresses.value; }, get addressingWidget() { return document.getElementById('addressingWidget'); }, get awRecipientItems() { var menulists = this.addressingWidget.querySelectorAll('listitem.addressingWidgetItem'); return Array.slice(menulists, 0); }, getRecipientTypeChooser: function(aItem) { return aItem.querySelector('menulist'); }, getRecipientValue: function(aItem) { return aItem.querySelector('textbox').value; }, init: function() { if (!this.isReplyAll()) return; var sender = this.getOriginalSender(); this.awRecipientItems.forEach(function(aItem) { var chooser = this.getRecipientTypeChooser(aItem); var recipient = this.getRecipientValue(aItem); var addresses = this.extractAddresses(recipient); if (chooser.value == 'addr_to' && addresses[0] != sender) chooser.value = 'addr_cc'; }, this); } }; window.addEventListener('DOMContentLoaded', function ReplyToAllAsCcSetup() { window.removeEventListener('DOMContentLoaded', ReplyToAllAsCcSetup, false); let (source = window.stateListener.NotifyComposeBodyReady.toSource()) { eval('window.stateListener.NotifyComposeBodyReady = '+source.replace( /(\}\)?)$/, 'ReplyToAllAsCc.init(); $1' )); } }, false);
JavaScript
0.012454
@@ -2074,382 +2074,149 @@ %0A %7D -%0A%7D;%0A%0Awindow.addEventListener('DOMContentLoaded', function ReplyToAllAsCcSetup() %7B%0A window.removeEventListener('DOMContentLoaded', ReplyToAllAsCcSetup, false);%0A%0A let (source = window.stateListener.NotifyComposeBodyReady.toSource()) %7B%0A eval('window.stateListener.NotifyComposeBodyReady = '+source.replace(%0A /(%5C%7D%5C)?)$/,%0A 'ReplyToAllAsCc.init(); $1'%0A ));%0A %7D%0A%7D +,%0A%0A handleEvent: function(aEvent) %7B%0A this.init();%0A %7D%0A%7D;%0A%0Adocument.documentElement.addEventListener('compose-window-init', ReplyToAllAsCc , fa
c2d8b8d9309bbcdb0580602b8834a88e382e733f
CHANGE addon-knob to allow for setting of knob after loading from URL
addons/knobs/src/KnobManager.js
addons/knobs/src/KnobManager.js
/* eslint no-underscore-dangle: 0 */ import deepEqual from 'fast-deep-equal'; import escape from 'escape-html'; import { getQueryParams } from '@storybook/client-api'; import KnobStore from './KnobStore'; import { SET } from './shared'; import { deserializers } from './converters'; const knobValuesFromUrl = Object.entries(getQueryParams()).reduce((acc, [k, v]) => { if (k.includes('knob-')) { return { ...acc, [k.replace('knob-', '')]: v }; } return acc; }, {}); // This is used by _mayCallChannel to determine how long to wait to before triggering a panel update const PANEL_UPDATE_INTERVAL = 400; const escapeStrings = obj => { if (typeof obj === 'string') { return escape(obj); } if (obj == null || typeof obj !== 'object') { return obj; } if (Array.isArray(obj)) { const newArray = obj.map(escapeStrings); const didChange = newArray.some((newValue, key) => newValue !== obj[key]); return didChange ? newArray : obj; } return Object.entries(obj).reduce((acc, [key, oldValue]) => { const newValue = escapeStrings(oldValue); return newValue === oldValue ? acc : { ...acc, [key]: newValue }; }, obj); }; export default class KnobManager { constructor() { this.knobStore = new KnobStore(); this.options = {}; } setChannel(channel) { this.channel = channel; } setOptions(options) { this.options = options; } getKnobValue({ value }) { return this.options.escapeHTML ? escapeStrings(value) : value; } knob(name, options) { this._mayCallChannel(); const { knobStore } = this; const existingKnob = knobStore.get(name); // We need to return the value set by the knob editor via this. // But, if the user changes the code for the defaultValue we should set // that value instead. if (existingKnob && deepEqual(options.value, existingKnob.defaultValue)) { return this.getKnobValue(existingKnob); } const knobInfo = { ...options, name, }; if (knobValuesFromUrl[name]) { const value = deserializers[options.type](knobValuesFromUrl[name]); knobInfo.defaultValue = value; knobInfo.value = value; } else { knobInfo.defaultValue = options.value; } knobStore.set(name, knobInfo); return this.getKnobValue(knobStore.get(name)); } _mayCallChannel() { // Re rendering of the story may cause changes to the knobStore. Some new knobs maybe added and // Some knobs may go unused. So we need to update the panel accordingly. For example remove the // unused knobs from the panel. This function sends the `setKnobs` message to the channel // triggering a panel re-render. if (this.calling) { // If a call to channel has already registered ignore this call. // Once the previous call is completed all the changes to knobStore including the one that // triggered this, will be added to the panel. // This avoids emitting to the channel within very short periods of time. return; } this.calling = true; const timestamp = +new Date(); setTimeout(() => { this.calling = false; // emit to the channel and trigger a panel re-render this.channel.emit(SET, { knobs: this.knobStore.getAll(), timestamp }); }, PANEL_UPDATE_INTERVAL); } }
JavaScript
0
@@ -2160,24 +2160,63 @@ lue = value; +%0A%0A delete knobValuesFromUrl%5Bname%5D; %0A %7D else
8c3dbab59065346e90b5ed376b03efd9c0f22ef1
add tests
test/buffer-utils.spec.js
test/buffer-utils.spec.js
import {toBuffer} from '../src/lib/buffer-utils'; const arrData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]; function copyData(from, to) { let i = 0; while (i < from.length) { to[i] = from[i]; i++ } } describe('buffer-utils', () => { it('can convert Buffer to Buffer', (done) => { const input = Buffer.from(arrData) const actual = toBuffer(input); const actualArr = Array.prototype.slice.call(actual, 0); (actual.length).should.be.eql(arrData.length); (actualArr).should.be.eql(arrData); done(); }); it('can convert Uint8Array to Buffer', (done) => { const input = new Uint8Array(arrData) const actual = toBuffer(input); const actualArr = Array.prototype.slice.call(actual, 0); (actual.length).should.be.eql(arrData.length); (actualArr).should.be.eql(arrData); done(); }); it('can convert Uint8ClampedArray to Buffer', (done) => { const input = new Uint8ClampedArray(arrData) const actual = toBuffer(input); const actualArr = Array.prototype.slice.call(actual, 0); (actual.length).should.be.eql(arrData.length); (actualArr).should.be.eql(arrData); done(); }); it('can convert ArrayBuffer to Buffer', (done) => { const buffer = new ArrayBuffer(arrData.length); const view = new Uint8Array(buffer); copyData(arrData, view) const actual = toBuffer(buffer); const actualArr = Array.prototype.slice.call(actual, 0); (actual.length).should.be.eql(arrData.length); (actualArr).should.be.eql(arrData); done(); }); });
JavaScript
0
@@ -1,24 +1,25 @@ import %7B + toBuffer %7D from ' @@ -10,16 +10,32 @@ toBuffer +, toArrayBuffer %7D from ' @@ -391,32 +391,33 @@ r.from(arrData)%0A +%0A const actual @@ -428,33 +428,32 @@ oBuffer(input);%0A -%0A const actual @@ -696,32 +696,33 @@ 8Array(arrData)%0A +%0A const actual @@ -733,33 +733,32 @@ oBuffer(input);%0A -%0A const actual @@ -1023,16 +1023,17 @@ rrData)%0A +%0A cons @@ -1060,17 +1060,16 @@ input);%0A -%0A cons @@ -1620,12 +1620,463 @@ %0A %7D);%0A%0A + it('can convert ArrayBuffer to ArrayBuffer', (done) =%3E %7B%0A const buffer = new ArrayBuffer(arrData.length);%0A const view = new Uint8Array(buffer);%0A copyData(arrData, view)%0A%0A const actual = toArrayBuffer(buffer);%0A const actualView = new Uint8Array(actual);%0A const actualArr = Array.prototype.slice.call(actualView, 0);%0A%0A (actual.byteLength).should.be.eql(arrData.length);%0A (actualArr).should.be.eql(arrData);%0A%0A done();%0A %7D);%0A%0A %7D);%0A
ce101bdb027de826482fca12506cf9554d50017b
Allow hyphens in Wikipedia subdomain
js/id/ui/preset/wikipedia.js
js/id/ui/preset/wikipedia.js
iD.ui.preset.wikipedia = function(field, context) { var event = d3.dispatch('change'), wikipedia = iD.wikipedia(), link, entity, lang, title; function i(selection) { var langcombo = d3.combobox() .fetcher(function(value, cb) { var v = value.toLowerCase(); cb(iD.data.wikipedia.filter(function(d) { return d[0].toLowerCase().indexOf(v) >= 0 || d[1].toLowerCase().indexOf(v) >= 0 || d[2].toLowerCase().indexOf(v) >= 0; }).map(function(d) { return { value: d[1] }; })); }); var titlecombo = d3.combobox() .fetcher(function(value, cb) { if (!value) value = context.entity(entity.id).tags.name || ''; var searchfn = value.length > 7 ? wikipedia.search : wikipedia.suggestions; searchfn(language()[2], value, function(query, data) { cb(data.map(function(d) { return { value: d }; })); }); }); lang = selection.selectAll('input.wiki-lang') .data([0]); lang.enter().append('input') .attr('type', 'text') .attr('class', 'wiki-lang') .value('English'); lang .call(langcombo) .on('blur', changeLang) .on('change', changeLang); title = selection.selectAll('input.wiki-title') .data([0]); title.enter().append('input') .attr('type', 'text') .attr('class', 'wiki-title') .attr('id', 'preset-input-' + field.id); title .call(titlecombo) .on('blur', change) .on('change', change); link = selection.selectAll('a.wiki-link') .data([0]); link.enter().append('a') .attr('class', 'wiki-link button-input-action minor') .attr('target', '_blank') .append('span') .attr('class', 'icon out-link'); } function language() { var value = lang.value().toLowerCase(); return _.find(iD.data.wikipedia, function(d) { return d[0].toLowerCase() === value || d[1].toLowerCase() === value || d[2].toLowerCase() === value; }) || iD.data.wikipedia[0]; } function changeLang() { lang.value(language()[1]); change(); } function change() { var value = title.value(), m = value.match(/https?:\/\/([a-z]+)\.wikipedia\.org\/wiki\/(.+)/), l = m && _.find(iD.data.wikipedia, function(d) { return m[1] === d[2]; }); if (l) { // Normalize title http://www.mediawiki.org/wiki/API:Query#Title_normalization value = m[2].replace(/_/g, ' '); value = value.slice(0, 1).toUpperCase() + value.slice(1); lang.value(l[1]); title.value(value); } var t = {}; t[field.key] = value ? language()[2] + ':' + value : undefined; event.change(t); } i.tags = function(tags) { var value = tags[field.key] || '', m = value.match(/([^:]+):(.+)/), l = m && _.find(iD.data.wikipedia, function(d) { return m[1] === d[2]; }); // value in correct format if (l) { lang.value(l[1]); title.value(m[2]); link.attr('href', 'http://' + m[1] + '.wikipedia.org/wiki/' + m[2]); // unrecognized value format } else { title.value(value); link.attr('href', 'http://en.wikipedia.org/wiki/Special:Search?search=' + value); } }; i.entity = function(_) { entity = _; }; i.focus = function() { title.node().focus(); }; return d3.rebind(i, event, 'on'); };
JavaScript
0.000001
@@ -2654,16 +2654,17 @@ ?:%5C/%5C/(%5B +- a-z%5D+)%5C.
d8058a0c0b817fda977cf2f17bd76103525e1c04
Fix button-group tests
test/button-group-spec.js
test/button-group-spec.js
/** * brightwheel * * Copyright © 2016 Allen Smith &lt;loranallensmith@github.com&gt;. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import { expect } from 'chai'; import ButtonGroup from '../src/button-group'; import Button from '../src/button'; describe('ButtonGroup', () => { describe('render method', () => { it('should create the right element', () => { let myButtonGroup = new ButtonGroup({}, []); expect(myButtonGroup.virtualElement.tagName).to.equal('DIV'); }); it('should render the correct class', () => { let myButtonGroup = new ButtonGroup({}, []); expect(myButtonGroup.virtualElement.properties.className).to.include('btn-group'); }); it('should include extra classes', () => { let myButtonGroup = new ButtonGroup({ classNames:['extra-class', 'another-class'] }, []); expect(myButtonGroup.virtualElement.properties.className).to.contain('extra-class another-class'); }); it('should render children', () => { let myButton = new Button({ text: 'My Button' }, []) let myButtonGroup = new ButtonGroup({}, [myButton]); expect(myButtonGroup.children[0].constructor.name).to.equal('Button'); }); }); });
JavaScript
0.000001
@@ -551,32 +551,25 @@ ButtonGroup. -virtualE +e lement.tagNa @@ -730,33 +730,15 @@ oup. -virtualElement.properties +element .cla @@ -953,33 +953,15 @@ oup. -virtualElement.properties +element .cla @@ -1204,16 +1204,24 @@ onGroup. +element. children @@ -1228,21 +1228,12 @@ %5B0%5D. -constructor.n +tagN ame) @@ -1244,21 +1244,21 @@ equal('B -utton +UTTON ');%0A
0a6ab98b53c8589fce41e350cd99390b72b5da2c
update DraggableTreeNodeList
src/_DraggableTreeNodeList/DraggableTreeNodeList.js
src/_DraggableTreeNodeList/DraggableTreeNodeList.js
/** * @file DraggableTreeNodeList component * @author liangxiaojun(liangxiaojun@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {Droppable} from 'react-beautiful-dnd'; import TreeNode from '../_TreeNode/TreeNode'; class DraggableTreeNodeList extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); } render() { const {depth, path, data, collapsed} = this.props; return ( <Droppable droppableId="droppable"> {provided => ( <div ref={provided.innerRef} className={'draggable-tree-node-list' + (collapsed ? ' collapsed' : '')}> { data && data.length > 0 ? ( data.map((item, index) => <TreeNode {...this.props} key={index} data={item} index={index} depth={depth + 1} path={path ? [...path, {index, value: item}] : [{ index, value: item }]}/> ) ) : null } {provided.placeholder} </div> )} </Droppable> ); } }; DraggableTreeNodeList.propTypes = { depth: PropTypes.number, path: PropTypes.array, data: PropTypes.array, collapsed: PropTypes.bool }; DraggableTreeNodeList.defaultProps = { depth: -1, path: null, data: [], collapsed: false }; export default DraggableTreeNodeList;
JavaScript
0
@@ -266,16 +266,78 @@ Node';%0A%0A +import PureRender from '../_vendors/PureRender';%0A%0A@PureRender%0A class Dr @@ -1866,24 +1866,66 @@ %0A%0A %7D%0A%7D;%0A%0A +process.env.NODE_ENV !== 'production' && ( DraggableTre @@ -2066,16 +2066,17 @@ .bool%0A%0A%7D +) ;%0A%0ADragg @@ -2128,24 +2128,8 @@ -1, -%0A path: null, %0A%0A
e8ac2529e134c49727d3a652f19141a658bb1674
update to fix jshint errors
js/sky/src/page/docs/demo.js
js/sky/src/page/docs/demo.js
/*global angular */ (function () { 'use strict'; function PageTestController($scope, $timeout, bbPage, $location) { var self = this, testLoading = false; function simulateLoading() { testLoading = true; self.pageStatus = bbPage.pageStatuses.LOADING; $timeout(function () { testLoading = false; self.pageStatus = bbPage.pageStatuses.LOADED; }, 1500); } function simulateNotAuthorized() { self.pageStatus = bbPage.pageStatuses.NOT_AUTHORIZED; } function simulateNotFound() { self.pageStatus = bbPage.pageStatuses.NOT_FOUND; } function returnHome() { simulateLoading(); $location.path('/').replace(); } self.pageStatus = bbPage.pageStatuses.LOADED; self.simulateLoading = simulateLoading; self.simulateNotAuthorized = simulateNotAuthorized; self.simulateNotFound = simulateNotFound; self.returnHome = returnHome; } PageTestController.$inject = ['$scope', '$timeout', 'bbPage', '$location']; function bbPageSetup(bbPageConfig, $stateProvider, $urlRouterProvider) { bbPageConfig.redirectUrl = '/components'; bbPageConfig.notFoundUrl = '/notfound'; $stateProvider .state('default', { url: '/', templateUrl: 'demo/page/buttons.html' }) .state('notFoundState', { url: '/notfound', templateUrl: 'demo/page/notfound.html' }); $urlRouterProvider.otherwise('/'); } bbPageSetup.$inject = ['bbPageConfig', '$stateProvider', '$urlRouterProvider']; angular.module('stache') .controller('PageTestController', PageTestController) .config(bbPageSetup); }());
JavaScript
0
@@ -1367,17 +1367,16 @@ - $statePr @@ -1661,16 +1661,25 @@ +%0A $urlRout
83969fef4c330027996c322c16ab55b98ed8afd3
Add a version number and bump it to 0.1.1
src/svgene.js
src/svgene.js
/* Copyright 2012 Kai Blin. Licensed under the Apache License v2.0, see LICENSE file */ var svgene = { }; svgene.geneArrowPoints = function (orf, height, offset, scale) { var top_ = 0 + offset; var bottom = height - offset; if (orf.strand == 1) { var start = scale(orf.start); var box_end = Math.max(scale(orf.end) - (2*offset), start); var point_end = scale(orf.end); points = "" + start + "," + top_; points += " " + box_end + "," + top_; points += " " + point_end + "," + (height/2); points += " " + box_end + "," + bottom; points += " " + start + "," + bottom; return points; } if (orf.strand == -1) { var point_start = scale(orf.start); var end = scale(orf.end); var box_start = Math.min(scale(orf.start) + (2*offset), end); points = "" + point_start + "," + (height/2); points += " " + box_start + "," + top_; points += " " + end + "," + top_; points += " " + end + "," + bottom; points += " " + box_start + "," + bottom; return points; } }; svgene.drawCluster = function(id, cluster, height, width) { var chart = d3.select("#"+id).append("svg") .attr("height", height) .attr("width", width); var offset = height/10; var x = d3.scale.linear() .domain([cluster.start, cluster.end]) .range([0, width]); chart.append("line") .attr("x1", 0) .attr("y1", height/2) .attr("x2", cluster.end - cluster.start) .attr("y2", height/2) .attr("class", "geneline"); chart.selectAll("polygon") .data(cluster.orfs) .enter().append("polygon") .attr("points", function(d) { return svgene.geneArrowPoints(d, height, offset, x); }) .attr("class", function(d) { return "genetype-" + d.type; }) .attr("id", function(d) { return cluster.idx + "-" + d.locus_tag; }); };
JavaScript
0
@@ -96,17 +96,38 @@ gene = %7B - +%0A version: %220.1.1%22%0A %7D;%0A%0Asvge
cb33302f10044fd0d495f4c3fec34852da459422
add spanish & dutch
scripts/copy-res.js
scripts/copy-res.js
#!/usr/bin/env node // copies the resources into the webapp directory. // // Languages are listed manually so we can choose when to include // a translation in the app (because having a translation with only // 3 strings translated is just frustrating) // This could readily be automated, but it's nice to explicitly // control when we languages are available. const INCLUDE_LANGS = [ //'be' Omitted because no translations in react-sdk 'en_EN', 'da', 'de_DE', 'fr', 'be', 'pt', 'pt_BR', 'ru', ]; // cpx includes globbed parts of the filename in the destination, but excludes // common parents. Hence, "res/{a,b}/**": the output will be "dest/a/..." and // "dest/b/...". const COPY_LIST = [ ["res/manifest.json", "webapp"], ["res/{media,vector-icons}/**", "webapp"], ["res/flags/*", "webapp/flags/"], ["src/skins/vector/{fonts,img}/**", "webapp"], ["node_modules/emojione/assets/svg/*", "webapp/emojione/svg/"], ["node_modules/emojione/assets/png/*", "webapp/emojione/png/"], ["./config.json", "webapp", { directwatch: 1 }], ]; INCLUDE_LANGS.forEach(function(l) { COPY_LIST.push([ l, "webapp/i18n/", { lang: 1 }, ]); }); const parseArgs = require('minimist'); const Cpx = require('cpx'); const chokidar = require('chokidar'); const fs = require('fs'); const rimraf = require('rimraf'); const argv = parseArgs( process.argv.slice(2), {} ); var watch = argv.w; var verbose = argv.v; function errCheck(err) { if (err) { console.error(err.message); process.exit(1); } } // Check if webapp exists if (!fs.existsSync('webapp')) { fs.mkdirSync('webapp'); } // Check if i18n exists if (!fs.existsSync('webapp/i18n/')) { fs.mkdirSync('webapp/i18n/'); } function next(i, err) { errCheck(err); if (i >= COPY_LIST.length) { return; } const ent = COPY_LIST[i]; const source = ent[0]; const dest = ent[1]; const opts = ent[2] || {}; let cpx = undefined; if (!opts.lang) { cpx = new Cpx.Cpx(source, dest); } if (verbose && cpx) { cpx.on("copy", (event) => { console.log(`Copied: ${event.srcPath} --> ${event.dstPath}`); }); cpx.on("remove", (event) => { console.log(`Removed: ${event.path}`); }); } const cb = (err) => { next(i + 1, err) }; if (watch) { if (opts.directwatch) { // cpx -w creates a watcher for the parent of any files specified, // which in the case of config.json is '.', which inevitably takes // ages to crawl. So we create our own watcher on the files // instead. const copy = () => { cpx.copy(errCheck) }; chokidar.watch(source) .on('add', copy) .on('change', copy) .on('ready', cb) .on('error', errCheck); } else if (opts.lang) { const reactSdkFile = 'node_modules/matrix-react-sdk/src/i18n/strings/' + source + '.json'; const riotWebFile = 'src/i18n/strings/' + source + '.json'; const translations = {}; const makeLang = () => { genLangFile(source, dest) }; [reactSdkFile, riotWebFile].forEach(function(f) { chokidar.watch(f) .on('add', makeLang) .on('change', makeLang) //.on('ready', cb) We'd have to do this when both files are ready .on('error', errCheck); }); next(i + 1, err); } else { cpx.on('watch-ready', cb); cpx.on("watch-error", cb); cpx.watch(); } } else if (opts.lang) { genLangFile(source, dest); next(i + 1, err); } else { cpx.copy(cb); } } function genLangFile(lang, dest) { const reactSdkFile = 'node_modules/matrix-react-sdk/src/i18n/strings/' + lang + '.json'; const riotWebFile = 'src/i18n/strings/' + lang + '.json'; const translations = {}; [reactSdkFile, riotWebFile].forEach(function(f) { if (fs.existsSync(f)) { Object.assign( translations, JSON.parse(fs.readFileSync(f).toString()) ); } }); fs.writeFileSync(dest + lang + '.json', JSON.stringify(translations, null, 4)); if (verbose) { console.log("Generated language file: " + lang); } } function genLangList() { const languages = {}; INCLUDE_LANGS.forEach(function(lang) { const normalizedLanguage = lang.toLowerCase().replace("_", "-"); const languageParts = normalizedLanguage.split('-'); if (languageParts.length == 2 && languageParts[0] == languageParts[1]) { languages[languageParts[0]] = lang + '.json'; } else { languages[normalizedLanguage] = lang + '.json'; } }); fs.writeFile('webapp/i18n/languages.json', JSON.stringify(languages, null, 4)); if (verbose) { console.log("Generated language list"); } } genLangList(); next(0);
JavaScript
0.999949
@@ -472,16 +472,26 @@ de_DE',%0A + 'es',%0A 'fr' @@ -502,16 +502,26 @@ 'be',%0A + 'nl',%0A 'pt'
ef5c394d92bb1897340649bb1a93c151a4ece03e
Fix last oversights
src/tagada.js
src/tagada.js
/* Noeud, the extreme minimal CSS selector engine Version : 0.1.0a Author : Aurélien Delogu (dev@dreamysource.fr) URL : https://github.com/pyrsmk/noeud License : MIT TODO [ ] cache [ ] unit testing [ ] benchmark against qwery */ noeud=function(selectors,context){ // Format if(!context){ context=document; } // No selectors? Goodbye! if(!selectors){ return new Array; } // Init vars var nodes=new Array(context), getNodesByClassName=function(name,context){ // Init vars var nodes=new Array, j=context.childNodes.length; // Browe children for(var i=0;i<j;++i){ if(classname=context.childNodes[i].className){ // Match the class if(classname.match(new RegExp('(^|\s+)'+name+'($|\s+)'))){ nodes.push(context.childNodes[i]); } } // Browse child children nodes=nodes.concat(getNodesByClassName(name,context.childNodes[i])); } return nodes; }, pieces, elements; // Browse selectors selectors=selectors.split(/\s+/); for(var i in selectors){ // Get nodes for that selector pieces=selectors[i].match(/^([#.])?(.*)/); elements=new Array(); for(var j in nodes){ if(typeof nodes[j]=='object'){ switch(pieces[1]){ // Get elements by class case '.': elements=elements.concat( nodes[j].getElementsByClassName? Array.prototype.slice.call(nodes[j].getElementsByClassName(pieces[2])): getNodesByClassName(pieces[2],nodes[j]) ); break; // Get elements by id case '#': elements=elements.concat(new Array(document.getElementById(pieces[2]))); break; // Get elements by tag default: elements=elements.concat(Array.prototype.slice.call(nodes[j].getElementsByTagName(pieces[2]))); } } } // Add the new node ones nodes=elements; } return nodes; };
JavaScript
0.998488
@@ -4,13 +4,14 @@ -Noeud +tagada , th @@ -278,21 +278,22 @@ wery%0A*/%0A -noeud +tagada =functio
03b0da663547888ead9475731ea6ab61c9637271
fix when localStorage visited apps empty
apollo-portal/src/main/resources/static/scripts/controller/IndexController.js
apollo-portal/src/main/resources/static/scripts/controller/IndexController.js
index_module.controller('IndexController', ['$scope', '$window', 'toastr', 'AppService', 'AppUtil', 'EnvService', function ($scope, $window, toastr, AppService, AppUtil, EnvService) { $scope.envs = []; $scope.selectedEnv = ''; EnvService.find_all_envs().then(function (result) { $scope.envs = result; //default select first env $scope.switchEnv($scope.envs[0]); }, function (result) { toastr.error(AppUtil.errorMsg(result), "load env error"); }); $scope.switchEnv = function (env) { $scope.selectedEnv = env; loadApps(env); }; var sourceApps = []; function loadApps(env){ AppService.find_all_app(env).then(function (result) { sourceApps = sortApps(result); $scope.apps = sourceApps; $scope.appsCount = sourceApps.length; $scope.selectedEnv = env; }, function (result) { toastr.error(AppUtil.errorMsg(result), "load apps error"); }); } var VISITED_APPS_STORAGE_KEY = "VisitedApps"; //访问过的App放在列表最前面,方便用户选择 function sortApps(sourceApps) { var visitedApps = JSON.parse(localStorage.getItem(VISITED_APPS_STORAGE_KEY)); if (!visitedApps){ return; } var existedVisitedAppsMap = {}; visitedApps.forEach(function (app) { existedVisitedAppsMap[app] = true; }); var sortedApps = []; sourceApps.forEach(function (app) { if (existedVisitedAppsMap[app.appId]){ sortedApps.push(app); } }); sourceApps.forEach(function (app) { if (!existedVisitedAppsMap[app.appId]){ sortedApps.push(app); } }); return sortedApps; } $scope.search = function () { var key = $scope.searchKey.toLocaleLowerCase(); if (key == '') { $scope.apps = sourceApps; return; } var result = []; sourceApps.forEach(function (item) { if (item.appId.toLocaleLowerCase().indexOf(key) >= 0 || item.name.toLocaleLowerCase().indexOf(key) >= 0) { result.push(item); } }); $scope.apps = result; }; }]);
JavaScript
0.000001
@@ -1496,32 +1496,43 @@ return + sourceApps ;%0A
cd8389361ea42539f728782b8037ee642e070d0b
Add a try guard around git description
jupyterlab/webpack.config.js
jupyterlab/webpack.config.js
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. // Support for Node 0.10 // See https://github.com/webpack/css-loader/issues/144 require('es6-promise').polyfill(); var childProcess = require('child_process'); var buildExtension = require('@jupyterlab/extension-builder/lib/builder').buildExtension; var webpack = require('webpack'); console.log('Generating bundles...'); var notice = childProcess.execSync('git describe', { encoding: 'utf8' }); buildExtension({ name: 'main', entry: './build/main', outputDir: './build', config: { output: { publicPath: 'lab/', }, module: { noParse: [/xterm\.js/] // Xterm ships a UMD module }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'GIT_DESCRIPTION': JSON.stringify(notice.trim()) } }) ] } }); module.exports = { entry: { loader: './build/loader' }, output: { path: __dirname + '/build', filename: '[name].bundle.js', libraryTarget: 'this', library: 'jupyter' }, node: { fs: 'empty' }, debug: true, bail: true, devtool: 'source-map' }
JavaScript
0.000001
@@ -420,24 +420,32 @@ dles...');%0A%0A +try %7B%0A var notice = @@ -506,16 +506,55 @@ f8' %7D);%0A +%7D catch %7B%0A var notice = 'unknown';%0A%7D%0A%0A %0AbuildEx
4c9beb59e74be1bb9a3990ff9a7077b67bde561a
Fix DownloadSupplementaryFileTool
src/article/shared/DownloadSupplementaryFileTool.js
src/article/shared/DownloadSupplementaryFileTool.js
import { platform, domHelpers } from 'substance' import { Tool } from '../../kit' export default class DownloadSupplementaryFileTool extends Tool { render ($$) { let el = super.render($$) el.append( $$('a').ref('link') .attr('target', '_blank') // ATTENTION: stop propagation, otherwise infinite loop .on('click', domHelpers.stop) ) return el } getClassNames () { return 'sc-download-supplementary-file-tool' } _onClick (e) { e.stopPropagation() e.preventDefault() const url = this._generateUrlLink() if (url) { this.refs.link.el.attr({ 'href': url }) this.refs.link.el.click() if (platform.inBrowser) { window.URL.revokeObjectURL(url) } } } _generateUrlLink () { const editorSession = this.context.editorSession const selectionState = editorSession.getSelectionState() const node = selectionState.node const remote = node.remote if (remote) { return node.href } else { const archive = this.context.archive if (archive.hasAsset(node.href)) { const blob = archive.getBlob(node.href) if (blob) { if (platform.inBrowser) { return window.URL.createObjectURL(blob.blob) } else { // TODO: what to do in node? maybe a file:// URL? return node.href } } else { // TODO: Some error should be displayed to the user console.error('Blob missing for a file', node.href) } } else { // TODO: this should not only be on the console, but displayed as an error // maybe it should be done as a validator task in future console.error('File not found in archive: ' + node.href) } } } }
JavaScript
0
@@ -5,18 +5,8 @@ rt %7B - platform, dom @@ -527,266 +527,101 @@ -const url = this._generateUrlLink()%0A if (url) %7B%0A this.refs.link.el.attr(%7B%0A 'href': url%0A %7D)%0A this.refs.link.el.click()%0A%0A if (platform.inBrowser) %7B%0A window.URL.revokeObjectURL(url)%0A %7D%0A %7D%0A %7D%0A%0A _generateUrlLink () %7B +this._triggerDownload()%0A %7D%0A%0A _triggerDownload () %7B%0A const archive = this.context.archive %0A @@ -782,17 +782,19 @@ nst -remote +isLocal = +! node @@ -809,160 +809,56 @@ -if (remote) %7B%0A return node.href%0A %7D else %7B%0A const archive = this.context.archive%0A if (archive.hasAsset(node.href)) %7B%0A const blob +let url = node.href%0A if (isLocal) %7B%0A url = a @@ -867,20 +867,28 @@ hive.get -Blob +DownloadLink (node.hr @@ -895,24 +895,26 @@ ef)%0A +%7D%0A if ( blob) %7B%0A @@ -905,20 +905,19 @@ if ( -blob +url ) %7B%0A @@ -922,603 +922,93 @@ - if (platform.inBrowser) %7B%0A return window.URL.createObjectURL(blob.blob)%0A %7D else %7B%0A // TODO: what to do in node? maybe a file:// URL?%0A return node.href%0A %7D%0A %7D else %7B%0A // TODO: Some error should be displayed to the user%0A console.error('Blob missing for a file', node.href)%0A %7D%0A %7D else %7B%0A // TODO: this should not only be on the console, but displayed as an error%0A // maybe it should be done as a validator task in future%0A console.error('File not found in archive: ' + node.href)%0A %7D +this.refs.link.el.attr(%7B%0A 'href': url%0A %7D)%0A this.refs.link.el.click() %0A
cdf32096dccced4f376196887cd6d1440ffc6c9a
create subscription list service
static/app/scripts/services/billingservices.js
static/app/scripts/services/billingservices.js
function notFoundHandle(resp, $scope) { if (resp.code === 401) { if (resp.message === "Invalid grant") { $scope.refreshToken(); } } } angular.module('crmEngine.billingservices', []).factory('Billing', function () { var Billing = function (data) { angular.extend(this, data); }; Billing.getSubscription = function ($scope) { $scope.isLoading = true; gapi.client.request({ 'root': ROOT, 'path': '/crmengine/v1/subscription/get', 'method': 'GET', 'body': {}, 'callback': (function (resp) { if (!resp.code) { $scope.subscription = resp; $scope.subscription.is_auto_renew =parseInt(resp.is_auto_renew); } else { notFoundHandle(resp, $scope); } $scope.isLoading = false; $scope.apply(); }) }); }; Billing.getOrganizationSubscription = function ($scope) { $scope.isLoading = true; gapi.client.request({ 'root': ROOT, 'path': '/crmengine/v1/subscription/organization_get', 'method': 'GET', 'body': {}, 'callback': (function (resp) { if (!resp.code) { $scope.org_subscription = resp; $scope.org_subscription.is_auto_renew =parseInt(resp.is_auto_renew); } else { notFoundHandle(resp, $scope); } $scope.isLoading = false; $scope.apply(); }) }); }; Billing.disableAutoRenew = function ($scope) { $scope.isLoading = true; $scope.apply(); gapi.client.crmengine.subscription.disable_auto_renew({}).execute( function (resp) { if (!resp.code) { window.location.reload(); } else { notFoundHandle(resp, $scope); } $scope.isLoading = false; $scope.apply(); }) }; Billing.enableAutoRenew = function ($scope) { $scope.isLoading = true; $scope.apply(); gapi.client.crmengine.subscription.enable_auto_renew({}).execute( function (resp) { if (!resp.code) { window.location.reload(); } else { notFoundHandle(resp, $scope); } $scope.isLoading = false; $scope.apply(); }) }; Billing.byNewLicences = function ($scope, params) { $scope.isLoading = true; $scope.apply(); gapi.client.crmengine.subscription.by_new_licences(params).execute( function (resp) { if (!resp.code) { window.location.reload(); } else { notFoundHandle(resp, $scope); } $scope.isLoading = false; $scope.apply(); }); }; return Billing; });
JavaScript
0.000002
@@ -965,32 +965,931 @@ %7D)%0A %7D);%0A + %7D%0A Billing.listSubscription = function ($scope) %7B%0A $scope.isLoading = true;%0A gapi.client.request(%7B%0A 'root': ROOT,%0A 'path': '/crmengine/v1/subscription/list',%0A 'method': 'GET',%0A 'body': %7B%7D,%0A 'callback': (function (resp) %7B%0A if (!resp.code) %7B%0A var data = resp.data;%0A var users_subscriptions = %7B%7D;%0A for (var i = 0; i %3C data.length; i++) %7B%0A var element = data%5Bi%5D;%0A element.is_auto_renew =parseInt(element.is_auto_renew);%0A users_subscriptions%5Belement%5B'email'%5D%5D = element;%0A %7D%0A %7D else %7B%0A notFoundHandle(resp, $scope);%0A %7D%0A $scope.isLoading = false;%0A $scope.apply();%0A %7D)%0A %7D);%0A %7D;%0A Billi
0d66aca67169ed23990b00eab0977baea1861d92
slugify should mimic jekyll function. closes #10
scripts/src/util.js
scripts/src/util.js
import $ from 'jquery' export function queryByHook (hook, container) { return $('[data-hook~=' + hook + ']', container) } export function setContent (container, content) { return container.empty().append(content) } export function setParams (params) { const newUrl = `${window.location.href.split('?')[0]}?${$.param(params)}` window.history.replaceState(null, null, newUrl) } export function slugify (text) { return text.toString().toLowerCase().trim() .replace(/\s+/g, '-') // Replace spaces with - .replace(/&/g, '-and-') // Replace & with 'and' .replace(/[^\w\-]+/g, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, '') // Trim - from end of text }
JavaScript
0.997295
@@ -377,24 +377,141 @@ newUrl)%0A%7D%0A%0A +// Meant to mimic Jekyll's slugify function%0A// https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils.rb#L142%0A export funct @@ -595,19 +595,28 @@ ce(/ -%5Cs+ +%5B%5Ea-zA-Z0-9%5D /g, '-') @@ -611,25 +611,16 @@ /g, '-') - // Rep @@ -628,146 +628,37 @@ ace -spaces with -%0A .replace(/&/g, '-and-') // Replace & with 'and'%0A .replace(/%5B%5E%5Cw%5C-%5D+/g, '') // Remove all non-word chars +non-alphanumeric chars with - %0A @@ -741,19 +741,24 @@ place(/%5E --+/ +%5C-%7C%5C-$/i , '') @@ -766,103 +766,40 @@ - - // -Trim - from start of text%0A .replace(/-+$/, '') // Trim - from end of text +Remove leading/trailing hyphen %0A%7D%0A
5c3cb6e2435058bc05a02eb8b7325eccc75b1706
Simplify FlightBooker demo.
src/com/google/foam/demos/sevenguis/FlightBooker.js
src/com/google/foam/demos/sevenguis/FlightBooker.js
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'com.google.foam.demos.sevenguis', name: 'FlightBooker', extends: 'foam.u2.Element', requires: [ 'foam.u2.DateView', 'foam.u2.tag.Select' ], imports: [ 'window' ], exports: [ 'as data' ], css: ` ^ { padding: 10px; } ^ .error { border: 2px solid red; } ^title { font-size: 18px; } ^title, ^ button, ^ input, ^ select { width: 160px; height: 24px; margin: 8px 0; display: block; } `, properties: [ { class: 'Boolean', name: 'isReturn', value: true, view: { class: 'foam.u2.view.ChoiceView', choices: [ [ false, 'one-way flight' ], [ true, 'return flight' ] ] } }, { class: 'Date', name: 'departDate', factory: function() { return new Date(Date.now()+3600000*24); }, validateObj: function(departDate) { var today = new Date(); today.setHours(0,0,0,0); if ( foam.Date.compare(departDate, today) < 0 ) return 'Must not be in the past.'; } }, { class: 'Date', name: 'returnDate', factory: function() { return new Date(Date.now()+2*3600000*24); }, validateObj: function(isReturn, returnDate, departDate) { if ( isReturn && foam.Date.compare(returnDate, departDate) < 0 ) return 'Must not be before depart date.'; } }, { name: 'returnDateMode', expression: function(isReturn) { return isReturn ? 'rw' : 'disabled'; } } ], methods: [ function initE() { this.SUPER(); this.nodeName = 'div'; this. addClass(this.myClass()). start('div').addClass(this.myClass('title')).add('Book Flight').end(). add(this.IS_RETURN). add(this.DEPART_DATE). start(this.RETURN_DATE).show(this.isReturn$).end(). add(this.BOOK); } ], actions: [ { name: 'book', isEnabled: function(errors_) { return ! errors_; }, code: function() { var depart = this.departDate.toLocaleDateString(); this.window.alert('You have booked a ' + (this.isReturn ? 'flight departing on ' + depart + ' and returning ' + this.returnDate.toLocaleDateString(): 'one-way flight on ' + depart) + '.'); } } ] });
JavaScript
0
@@ -2003,129 +2003,8 @@ %7D%0A - %7D,%0A %7B%0A name: 'returnDateMode',%0A expression: function(isReturn) %7B return isReturn ? 'rw' : 'disabled'; %7D%0A
9e0e22f1292aaf7f74fd170bca6b20df04553faf
animal command: changed API for cats and added API for birds
src/commands/Fun/animals.js
src/commands/Fun/animals.js
const snekfetch = require('snekfetch') const CATS = /^c(at(s)?)?$/i const DOGS = /^d(og(s)?)?$/i exports.run = async (bot, msg, args) => { const parsed = bot.utils.parseArgs(args, ['u']) if (!parsed.leftover.length) { throw new Error('You must specify a type! Available types: `cats`, `dogs`.') } const type = parsed.leftover[0] const cats = (CATS.test(type) ? true : (DOGS.test(type) ? false : null)) if (cats === null) { throw new Error('That type is not available!') } await msg.edit(`🔄\u2000Fetching a random ${cats ? 'cat' : 'dog'} image\u2026`) const res = await snekfetch.get(cats ? 'http://www.random.cat/meow' : 'http://random.dog/woof') const image = cats ? res.body.file : `http://random.dog/${res.body}` if (parsed.options.u) { await msg.channel.send({ files: [ image ] }) return msg.delete() } else { return msg.edit(image) } } exports.info = { name: 'animals', usage: 'animals [-u] <cats|dogs>', description: 'Shows you random pictures of cats or dogs', aliases: ['a', 'animal'], options: [ { name: '-u', usage: '-u', description: 'Attempts to send the image as an attachment instead' } ] }
JavaScript
0.9982
@@ -43,59 +43,574 @@ nst -CATS = /%5Ec(at(s)?)?$/i%0Aconst DOGS = /%5Ed(og(s)?)?$/i +animals = %5B%0A %7B%0A name: 'cat',%0A regex: /%5Ec(at(s)?)?$/i,%0A api: 'http://thecatapi.com/api/images/get?format=xml&type=jpg,png,gif',%0A action: %7B%0A type: 'regex',%0A data: /%3Curl%3E%5Cs*(.+?)%5Cs*%3C%5C/url%3E/i%0A %7D%0A %7D,%0A %7B%0A name: 'dog',%0A regex: /%5Ed(og(s)?)?$/i,%0A api: 'http://random.dog/woof',%0A action: %7B%0A type: 'append',%0A data: 'http://random.dog/'%0A %7D%0A %7D,%0A %7B%0A name: 'bird',%0A regex: /%5Eb(ird(s)?)?$/i,%0A api: 'http://random.birb.pw/tweet/',%0A action: %7B%0A type: 'append',%0A data: 'http://random.birb.pw/img/'%0A %7D%0A %7D%0A%5D %0A%0Aex @@ -857,163 +857,94 @@ %5B0%5D%0A +%0A -const cats = (CATS.test(type) ? true : (DOGS.test(type) ? false : null))%0A%0A if (cats === null) %7B%0A throw new Error('That type is not available!')%0A %7D%0A%0A +let image%0A for (const animal of animals) %7B%0A if (animal.regex.test(type)) %7B%0A aw @@ -988,28 +988,19 @@ m $%7B -cats ? 'cat' : 'dog' +animal.name %7D im @@ -1011,16 +1011,20 @@ u2026%60)%0A + const @@ -1053,142 +1053,493 @@ get( -cats ? 'http://www.random.cat/meow' : 'http://random.dog/woof')%0A const image = cats ? res.body.file : %60http://random.dog/$%7Bres.body%7D%60 +animal.api)%0A if (animal.action && animal.action.type === 'regex') %7B%0A const exec = animal.action.data.exec(res.body)%0A if (exec && exec%5B1%5D) %7B%0A image = exec%5B1%5D%0A %7D%0A %7D else if (animal.action && animal.action.type === 'append') %7B%0A image = animal.action.data + res.body%0A %7D else %7B%0A image = res.body%0A %7D%0A break%0A %7D%0A %7D%0A%0A if (!image) %7B%0A throw new Error('Failed to fetch image or that type is possibly not available!')%0A %7D %0A%0A
01c2c5b57e429b933852983a05db36e638ab33ec
Remove debug logs. Fixes #1947 (#1948)
src/common/CodeGenerator.js
src/common/CodeGenerator.js
/*globals define*/ define([ 'blob/BlobClient', 'q', ], function( BlobClient, Q, ) { class UnimplementedError extends Error { constructor(name, className) { let msg = `${name} is not implemented`; if (className) { msg += ` for ${className}`; } super(msg); } } const CodeGen = { Operation: { pluginId: 'GenerateJob', namespace: 'pipeline' } }; class CodeGeneratorBase { constructor(core, rootNode, logger, blobClient) { this.core = core; this.rootNode = rootNode; this.logger = logger; this.blobClient = blobClient || new BlobClient({logger}); } getCodeGenPluginId (node) { var base = this.core.getBase(node), name = this.core.getAttribute(node, 'name'), namespace = this.core.getNamespace(node), pluginId; pluginId = (this.core.getOwnRegistry(node, 'validPlugins') || '').split(' ').shift(); if (this.core.isMetaNode(node) && CodeGen[name]) { pluginId = CodeGen[name].pluginId || CodeGen[name]; namespace = CodeGen[name].namespace; } if (pluginId) { return { namespace: namespace, pluginId: pluginId }; } else if (base) { return this.getCodeGenPluginId(base); } else { return null; } } async getCodeHash (nodeId, config={}) { const node = await this.core.loadByPath(this.rootNode, nodeId); const info = this.getCodeGenPluginId(node); if (info && info.pluginId) { // Load and run the plugin const context = { namespace: info.namespace, activeNode: nodeId, }; const result = await this.executePlugin(info.pluginId, config, context); console.log('>> result:', result); return result.artifacts[0]; } else { var metanode = this.core.getMetaType(node), type = this.core.getAttribute(metanode, 'name'); this.logger.warn(`Could not find plugin for ${type}. Will try to proceed anyway`); return null; } } async getCode (/*nodeId, config={}*/) { const hash = await this.getCodeHash(...arguments); return await this.blobClient.getObjectAsString(hash); } async executePlugin(/*pluginId, config, context*/) { throw new UnimplementedError('executePlugin'); } static async fromClient(client, logger) { const {core, rootNode} = await Q.ninvoke(client, 'getCoreInstance', logger); return new ClientCodeGenerator(client, rootNode, core, logger); } static fromPlugin(plugin) { const {core, rootNode, project, currentHash, logger} = plugin; const {blobClient} = plugin; return new CoreCodeGenerator(core, rootNode, project, currentHash, logger, blobClient); } } class ClientCodeGenerator extends CodeGeneratorBase { constructor(client, rootNode, core, logger) { super(core, rootNode, logger); this.client = client; } async executePlugin (pluginId, config, context) { const pluginContext = this.client.getCurrentPluginContext(pluginId); pluginContext.managerConfig = Object.assign(pluginContext.managerConfig, context); pluginContext.pluginConfig = config; const result = await Q.ninvoke(this.client, 'runBrowserPlugin', pluginId, pluginContext); return result; } } class CoreCodeGenerator extends CodeGeneratorBase { constructor(core, rootNode, project, currentHash, logger, blobClient) { super(core, rootNode, logger, blobClient); this.project = project; this.currentHash = currentHash; } async executePlugin (pluginId, config, context) { context.project = this.project; context.commitHash = this.currentHash; const manager = this.getPluginManager(); const result = await Q.ninvoke( manager, 'executePlugin', pluginId, config, context ); console.log('FINISHED EXECUTING PLUGIN', pluginId); console.log(result); return result; } getPluginManager () { if (!this.manager) { const webgme = require('webgme'); const gmeConfig = require('deepforge/gmeConfig'); const PluginManager = webgme.PluginCliManager; this.manager = new PluginManager(null, this.logger, gmeConfig); } return this.manager; } } return CodeGeneratorBase; });
JavaScript
0
@@ -2100,59 +2100,8 @@ t);%0A - console.log('%3E%3E result:', result);%0A @@ -4569,105 +4569,8 @@ );%0A - console.log('FINISHED EXECUTING PLUGIN', pluginId);%0A console.log(result);%0A
d3c6e8f4f2f6b1de00b9ce0c1bc9d5fedfbf8c90
implement updateRenderObject
src/common/DynamicObject.js
src/common/DynamicObject.js
"use strict"; const Point= require('incheon').Point; const Serializable= require('incheon').serialize.Serializable; const Serializer= require('incheon').serialize.Serializer; /** * Defines an objects which can move about in the game world */ class DynamicObject extends Serializable { static get netScheme(){ return { id: { type: Serializer.TYPES.UINT8 }, playerId: { type: Serializer.TYPES.UINT8 }, x: { type: Serializer.TYPES.INT16 }, y: { type: Serializer.TYPES.INT16 }, velX: { type: Serializer.TYPES.FLOAT32 }, velY: { type: Serializer.TYPES.FLOAT32 }, angle: { type: Serializer.TYPES.INT16 } } } constructor(id, x, y){ super(); this.id = id; //instance id this.playerId = 0; this.x = x; this.y = y; this.velX = 0; this.velY = 0; this.angle = 90; this.rotationSpeed = 3; this.acceleration = 0.1; this.deceleration = 0.99; this.maxSpeed = 2; //todo deal with what goes over the wire this.velocity = new Point(); this.temp={ accelerationVector: new Point() }; }; copyFrom(sourceObj){ this.id = sourceObj.id; this.playerId = sourceObj.playerId; this.isPlayerControlled = sourceObj.isPlayerControlled; this.x = sourceObj.x; this.y = sourceObj.y; this.velX = sourceObj.velX; this.velY = sourceObj.velY; this.velocity.set(sourceObj.velX, sourceObj.velY); this.angle = sourceObj.angle; this.rotationSpeed = sourceObj.rotationSpeed; this.acceleration = sourceObj.acceleration; this.deceleration = sourceObj.deceleration; this.maxSpeed = sourceObj.maxSpeed; } step(worldSettings){ if (this.isRotatingRight){ this.angle += this.rotationSpeed; } if (this.isRotatingLeft){this.angle -= this.rotationSpeed; } if(this.angle>360){ this.angle -= 360; } if(this.angle<0){ this.angle += 360; } if (this.isAccelerating) { this.temp.accelerationVector.set( Math.cos( this.angle * (Math.PI / 180) ), Math.sin( this.angle * (Math.PI / 180) ) ).setMagnitude(this.acceleration); } else{ this.temp.accelerationVector.set(0,0); } // console.log(this.temp.accelerationVector.x,this.temp.accelerationVector.y); // console.log(this.temp.accelerationVector.x, this.temp.accelerationVector.y); // console.log(this.temp.accelerationVector.x, this.temp.accelerationVector.y); //constant velocity, like a missile if (this.constantVelocity){ this.velocity.set( Math.cos( this.angle * (Math.PI / 180) ), Math.sin( this.angle * (Math.PI / 180) ) ).setMagnitude(this.constantVelocity); } else{ //acceleration Point.add(this.velocity,this.temp.accelerationVector, this.velocity); this.velocity.multiply(this.deceleration, this.deceleration); this.velocity.x = Math.round(this.velocity.x * 100)/100; this.velocity.y = Math.round(this.velocity.y * 100)/100; } this.velX = this.velocity.x; this.velY = this.velocity.y; this.isAccelerating = false; this.isRotatingLeft = false; this.isRotatingRight = false; this.x = this.x + this.velocity.x; this.y = this.y + this.velocity.y; if (this.x>=worldSettings.width){ this.x = worldSettings.width - this.x;} else if (this.y>=worldSettings.height){ this.y = worldSettings.height - this.y;} else if (this.x < 0){ this.x = worldSettings.width + this.x;} else if (this.y<0){ this.y = worldSettings.width + this.y;} }; init(options) { Object.assign(this, options); } initRenderObject(renderer) { this.renderer = renderer; this.renderObject = this.renderer.addObject(this); } updateRenderObject() {} interpolate(prevObj, nextObj, playPercentage) { // update other objects with interpolation // TODO refactor into general interpolation class // TODO: this interpolate function should not care about worldSettings. if (this.isPlayerControlled != true){ if (Math.abs(nextObj.x - prevObj.x) > this.renderer.worldSettings.height /2){ //fix for world wraparound this.renderObject.x = nextObj.x; } else{ this.renderObject.x = (nextObj.x - prevObj.x) * playPercentage + prevObj.x; } if (Math.abs(nextObj.y - prevObj.y) > this.renderer.worldSettings.height/2) { //fix for world wraparound this.renderObject.y = nextObj.y; } else{ this.renderObject.y = (nextObj.y - prevObj.y) * playPercentage + prevObj.y; } var shortest_angle=((((nextObj.angle - prevObj.angle) % 360) + 540) % 360) - 180; //todo wrap this in a util this.renderObject.angle = prevObj.angle + shortest_angle * playPercentage; } } // release resources destroy() { console.log(`destroying object ${this.id}`); // destroy the renderObject if (this.renderObject) { this.renderer.removeObject(this.renderObject); } } } module.exports = DynamicObject;
JavaScript
0.000001
@@ -4135,16 +4135,143 @@ ject() %7B +%0A this.renderObject.x = this.x;%0A this.renderObject.y = this.y;%0A this.renderObject.angle = this.angle;%0A %7D%0A%0A i
ba0fbca43d33e464b760d5eccb02a43bbf0b997a
make newRoles -> roles tab
scripts/ui-state.js
scripts/ui-state.js
var Store = require('./store') module.exports = UIState function UIState(dispatcher) { Store.mixin(this) this.tab = 'setup' this.selectedPlayer = null this.selectionConfirmed = false this.missionRevealed = false dispatcher.onAction(function(payload) { var actions = UIState.actions if (_.isFunction(actions[payload.action])) { actions[payload.action].call(this, payload) this.save() } }.bind(this)) } var PERSIST_KEYS = ['tab', 'selectedPlayer', 'selectionConfirmed'] UIState.prototype.save = function() { var persist = {} PERSIST_KEYS.forEach(key => persist[key] = this[key]) store.set('store.uistate', persist) } UIState.prototype.load = function() { var persist = store.get('store.uistate') if (persist !== undefined) { PERSIST_KEYS.forEach(key => this[key] = persist[key]) } } UIState.actions = {} UIState.actions.changeTab = function({tab}) { this.tab = tab this.selectedPlayer = null this.selectionConfirmed = false this._emitChange() } UIState.actions.selectPlayer = function({name}) { console.log('selecting', name) this.selectedPlayer = name this.selectionConfirmed = false this._emitChange() } UIState.actions.confirmPlayer = function({name}) { console.log('confirming', name) this.selectedPlayer = name this.selectionConfirmed = true this._emitChange() } UIState.actions.deselectPlayer = function() { console.log('deselecting') this.selectedPlayer = null this.selectionConfirmed = false this._emitChange() } UIState.actions.missionReveal = function() { this.missionRevealed = true this._emitChange() } UIState.actions.missionReset = function() { this.missionRevealed = false this._emitChange() }
JavaScript
0
@@ -1783,28 +1783,184 @@ se%0A this._emitChange()%0A%7D%0A +%0AUIState.actions.newRoles = function() %7B%0A this.tab = 'roles'%0A this.selectedPlayer = null%0A this.selectionConfirmed = false%0A this._emitChange()%0A%7D%0A
823d60484a8c07e41a2240460fc6fd023de7130f
remove cyclonic burst to add elsewhere
src/common/SPELLS_HUNTER.js
src/common/SPELLS_HUNTER.js
/** * All Hunter abilities except talents go in here. You can also put a talent in here if you want to override something imported in the `./talents` folder, but that should be extremely rare. * You need to do this manually, usually an easy way to do this is by opening a WCL report and clicking the icons of spells to open the relevant Wowhead pages, here you can get the icon name by clicking the icon, copy the name of the spell and the ID is in the URL. * You can access these entries like other entries in the spells files by importing `common/SPELLS` and using the assigned property on the SPELLS object. Please try to avoid abbreviating properties. */ export default { // Beast Mastery: // ... // ------------- // Marksmanship: // ------------- // Marksmanship spells WINDBURST: { id: 204147, name: 'Windburst', icon: 'inv_bow_1h_artifactwindrunner_d_02', }, WINDBURST_MOVEMENT_SPEED: { id: 204477, name: 'Windburst', icon: 'ability_hunter_focusedaim', }, AIMED_SHOT: { id: 19434, name: 'Aimed Shot', //TODO: T204p cost reduction (46 focus instead of 50) icon: 'inv_spear_07', }, ARCANE_SHOT: { id: 185358, name: 'Arcane Shot', icon: 'ability_impalingbolt', }, MARKED_SHOT: { id: 185901, name: 'Marked Shot', icon: 'ability_hunter_markedshot', }, DISENGAGE: { id: 781, name: 'Disengage', icon: 'ability_rogue_feint', }, TRUESHOT: { id: 193526, name: 'Trueshot', icon: 'ability_trueshot', }, MULTISHOT: { id: 2643, name: 'Multi-Shot', icon: 'ability_upgrademoonglaive', }, EXHILARATION: { id: 109304, name: 'Exhilaration', icon: 'ability_hunter_onewithnature', }, ASPECT_OF_THE_CHEETAH: { id: 186257, name: 'Aspect of the Cheetah', icon: 'ability_mount_jungletiger', }, ASPECT_OF_THE_TURTLE: { id: 186265, name: 'Aspect of the Turtle', icon: 'ability_hunter_pet_turtle', }, BURSTING_SHOT: { id: 224729, name: 'Bursting Shot', icon: 'ability_hunter_burstingshot', }, CONCUSSIVE_SHOT: { id: 27634, name: 'Concussive Shot', icon: 'spell_frost_stun', }, COUNTER_SHOT: { id: 147362, name: 'Counter Shot', icon: 'inv_ammo_arrow_03', }, MISDIRECTION: { id: 34477, name: 'Misdrection', icon: 'ability_hunter_misdirection', }, FREEZING_TRAP: { id: 187650, name: 'Freezing Trap', icon: 'spell_frost_chainsofice', }, TAR_TRAP: { id: 187698, name: 'Tar Trap', icon: 'spell_yorsahj_bloodboil_black', }, VULNERABLE: { id: 187131, name: 'Vulnerable', icon: 'ability_hunter_mastermarksman', }, // Marksmanship tier sets HUNTER_MM_T20_2P_BONUS: { id: 242242, name: 'T20 2 set bonus', icon: 'ability_hunter_focusedaim', }, HUNTER_MM_T20_2P_BONUS_BUFF: { id: 242243, name: 'T20 2 set bonus', icon: 'inv_misc_ammo_arrow_03', }, HUNTER_MM_T20_4P_BONUS: { id: 242241, name: 'T20 4 set bonus', icon: 'ability_hunter_focusedaim', }, HUNTER_MM_T20_4P_BONUS_BUFF: { id: 246153, name: 'T20 4 set bonus', icon: 'inv_spear_07', }, // Marksmanship artifact traits BULLSEYE_BUFF: { id: 204090, name: 'Bullseye', icon: 'ability_hunter_focusedaim', }, CYCLONIC_BURST_TRAIT: { id: 238124, name: 'Cyclonic burst', icon: 'inv_bow_1h_artifactwindrunner_d_02', }, QUICK_SHOT_TRAIT: { id: 190462, name: 'Quick shot', icon: 'ability_trueshot', }, // Survival: // ... // Shared: // ... NETHERWINDS: { id: 160452, name: 'Netherwinds', icon: 'spell_arcane_massdispel', }, ANCIENT_HYSTERIA: { id: 90355, name: 'Ancient Hysteria', icon: 'spell_shadow_unholyfrenzy', }, };
JavaScript
0
@@ -3315,131 +3315,8 @@ %7D,%0A - CYCLONIC_BURST_TRAIT: %7B%0A id: 238124,%0A name: 'Cyclonic burst',%0A icon: 'inv_bow_1h_artifactwindrunner_d_02',%0A %7D,%0A QU
f8cd6f21521d8b5632744e73dc020740f40cd3c8
Remove jQuery dependency from zeitlens.js Fix execution of javascript on page load
scripts/zeitlens.js
scripts/zeitlens.js
jQuery("document").ready(function($) { // convert obfuscated mail addresses into clickable "mailto:" links var mailAddressClass = "obfuscated-mail-address"; $("."+mailAddressClass).each(function() { if (!$(this).hasClass("dont-touch")) { var address = $(this).attr("data-user") + "@" + $(this).attr("data-domain"); $(this).html($("<a href=\"mailto:" + address + "\">" + address + "</a>", {})); $(this).removeClass(mailAddressClass); } }); });
JavaScript
0.000001
@@ -1,226 +1,823 @@ -jQuery(%22document%22).ready(function($) %7B%0A // convert obfuscated mail addresses into clickable %22mailto:%22 links%0A var mailAddressClass = %22obfuscated- +var zeitlens = (function() %7B%0A function removeAllChildNodes(node) %7B%0A while (node.firstChild) %7B%0A node.removeChild(node.firstChild);%0A %7D%0A return node;%0A %7D;%0A%0A function hasClass(node, className) %7B%0A return node.className.match(new RegExp(%22%5C%5Cb%22 + className + %22%5C%5Cb%22));%0A %7D%0A%0A function createMailtoLink(address) %7B%0A var link = document.createElement(%22a%22);%0A link.href = %22mailto:%22 + address;%0A link.textContent = address;%0A return link;%0A %7D%0A%0A // convert obfuscated mail addresses into clickable %22mailto:%22 links%0A deobfuscateMailAddresses = function(mailAddressSelector, dontTouchClass) %7B%0A var obfuscatedAddresses = document.querySelectorAll( mail --a +A ddress -%22;%0A $(%22.%22+mailAddressClass).each(function() %7B +Selector);%0A for (var i = 0; i %3C obfuscatedAddresses.length; i++) %7B%0A var node = obfuscatedAddresses%5Bi%5D;%0A console.log(node); %0A + if (! -$(this). hasC @@ -825,25 +825,99 @@ ass( -%22 +node, dont --t +T ouch -%22)) %7B%0A +Class)) %7B%0A removeAllChildNodes(node);%0A node.className = %22%22;%0A @@ -936,33 +936,25 @@ s = -$(this).attr(%22data- +node.dataset. user -%22) + %22 @@ -962,43 +962,35 @@ %22 + -$(this).attr(%22data- +node.dataset. domain -%22) ;%0A $(th @@ -989,141 +989,345 @@ -$(this).html($(%22%3Ca href=%5C%22mailto:%22 + address + %22%5C%22%3E%22 + address + %22%3C/a%3E%22, %7B + node.appendChild(createMailtoLink(address));%0A %7D%0A %7D%0A %7D;%0A%0A return %7B%0A deobfuscateMailAddresses: deobfuscateMailAddresses%0A %7D;%0A %7D) +( );%0A - $(this).removeClass(mailAddressClass);%0A %7D%0A %7D +%0Adocument.addEventListener(%22readystatechange%22, function(event) %7B%0A var mailAddressClass = %22obfuscated-mail-address%22;%0A zeitlens.deobfuscateMailAddresses(%22.obfuscated-mail-address%22, %22dont-touch%22 );%0A%7D
c2db64d0f7f4eab4c8732b1f4fbdec287e558cc8
Remove brackets and className
src/components/ErrorPage.js
src/components/ErrorPage.js
import React from 'react'; import styled from 'styled-components'; import StyledButton from './StyledButton'; const StyledErrorMessage = styled.div` margin: auto; max-width: 720px; padding: 3rem; text-align: center; .message-content { margin-bottom: 2rem; } `; export default function ErrorPage() { return ( <StyledErrorMessage> <h2>Page not found!</h2> <p className="message-content">Sorry, but the page you were looking for could not be found.</p> <StyledButton to={'/'}>Go Home</StyledButton> </StyledErrorMessage> ); }
JavaScript
0.000285
@@ -226,24 +226,9 @@ %0A%0A -.message-content +p %7B%0A @@ -377,36 +377,8 @@ %3Cp - className=%22message-content%22 %3ESor @@ -466,13 +466,11 @@ to= -%7B'/'%7D +%22/%22 %3EGo
b1a463d7fb305cd9853e8b7f8f6950d4d31103f5
Make grid elements keys unique to avoid unnecessary repaints
src/components/Grid/Grid.js
src/components/Grid/Grid.js
import React from 'react'; import Square from './Square'; import './Grid.css'; const Grid = ({ size, }) => { const [height, width] = size.split('x').map(el => Number(el)); if (!Number.isInteger(height) || !Number.isInteger(width)) { return ( <span className="error"> <span role="img" aria-label="warning">⚠</span>️ Try again with positive integers. </span> ); } if (height <= 0 || width <= 0) { return ( <span className="error"> <span role="img" aria-label="warning">⚠</span>️ Elements have been painted in another dimension. Try again with positive integers. </span> ); } if (height * width > 10_000) { return ( <span className="error"> ⚠️ Sorry, there are too many elements to paint. Try again with a smaller size. </span> ); } const squareNodes = [...new Array(height * width)].map( (_, index) => <Square key={index} rowIndex={~~(index / width)} columnIndex={index % width} /> ); const gridStyle = { display: 'grid', gridTemplateColumns: `repeat(${width}, 50px)`, gridTemplateRows: `repeat(${height}, 50px)`, gridGap: '5px', }; return ( <div className="Grid" style={gridStyle} > {squareNodes} </div> ); }; export default Grid;
JavaScript
0
@@ -1083,17 +1083,152 @@ ndex) =%3E + %7B %0A + const rowIndex = ~~(index / width);%0A const columnIndex = index %25 width;%0A%0A return (%0A @@ -1267,20 +1267,51 @@ + + key=%7B -index%7D%0A +%60$%7BrowIndex%7D,$%7BcolumnIndex%7D%60%7D%0A @@ -1340,27 +1340,22 @@ ex=%7B -~~(index / width)%7D%0A +rowIndex%7D%0A @@ -1383,29 +1383,27 @@ nIndex=%7B -index %25 width +columnIndex %7D%0A @@ -1416,10 +1416,46 @@ -/%3E + /%3E%0A )%0A %7D %0A
3df6004f8d975c23efe28d17c8afc2e15c3af1cb
Add px to Hero
src/components/Hero/Hero.js
src/components/Hero/Hero.js
import React from 'react' import PropTypes from 'prop-types' //import styled from 'styled-components' import {Banner, Heading} from 'rebass' /* styled-component extending is now working const ExtenedBanner = styled(Banner).attrs({ alignItems: props => props.alignItems || 'center', justifyContent: props => props.justifyContent || 'center', minHeight: props => props.minHeight || '100vh', })` align-items: ${props => props.alignItems} justify-content: ${props => props.justifyContent} min-height: ${props => props.minHeight} ` */ const getLocation = messageLoc => { let style = {} if (messageLoc === 'left') { style = { alignItems: 'flex-start', } } else if (messageLoc === 'right') { style = { alignItems: 'flex-end', } } return style } /** Hero */ function Hero({backgroundImage, message, messageLoc, messageSizes}) { return ( <Banner style={getLocation(messageLoc)} backgroundImage={backgroundImage}> <Heading f={messageSizes}>{message}</Heading> </Banner> ) } Hero.propTypes = { /** Background Image */ backgroundImage: PropTypes.string, /** message */ message: PropTypes.string, /** message location */ messageLoc: PropTypes.string, /** message size in array */ messageSizes: PropTypes.array, } Hero.defaultProps = { message: 'world', messageLoc: 'center', messageSizes: [4, 5, 6, 7], } export default Hero
JavaScript
0
@@ -864,16 +864,20 @@ ageSizes +, px %7D) %7B%0A r @@ -895,16 +895,22 @@ %3CBanner +%0A style=%7B @@ -933,16 +933,22 @@ ageLoc)%7D +%0A backgro @@ -973,16 +973,30 @@ ndImage%7D +%0A px=%7Bpx%7D %3E%0A @@ -1312,16 +1312,72 @@ .array,%0A + /** padding x axis in array */%0A px: PropTypes.array,%0A %7D%0A%0AHero. @@ -1467,16 +1467,36 @@ 6, 7%5D,%0A + px: %5B1, 3, 4, 4%5D,%0A %7D%0A%0Aexpor
30d55bc4f31ff383aa623601c6088485f9081c26
Add hover effect to Workshops
src/components/Workshops.js
src/components/Workshops.js
import React from 'react' import { Box, Card, Link as A, Heading, Text } from '@hackclub/design-system' import Link from 'gatsby-link' import { map } from 'lodash' A.link = A.withComponent(Link) Box.section = Box.withComponent('section') const WorkshopGrid = Box.withComponent('ol').extend` display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); grid-auto-rows: 1fr; grid-gap: ${props => props.theme.space[3]}px; counter-reset: li; list-style: none; padding: 0; ` const WorkshopCard = Card.withComponent('li').extend` background-size: cover; background-position: center; background-repeat: no-repeat; background-image: url('${props => props.img}'); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.32); position: relative; height: 100%; &:before { content: counter(li); counter-increment: li; box-sizing: border-box; position: absolute; right: ${props => props.theme.space[3]}px; display: inline-block; width: 1.25rem; height: 1.25rem; border-radius: 1rem; background-color: ${props => props.theme.colors.white}; color: ${props => props.theme.colors.black}; font-size: ${props => props.theme.fontSizes[0]}px; line-height: 1.5; text-align: center; text-shadow: none; font-weight: bold; } h3 { line-height: 1.125; margin-bottom: 0.125rem; } p { line-height: 1.375; } ` const WorkshopItem = ({ data: { fields: { slug, bg }, frontmatter: { name, description } }, ...props }) => ( <A.link to={slug} {...props}> <WorkshopCard p={3} boxShadowSize="md" bg="accent" img={bg}> <Heading.h3 color="white" f={3} children={name} /> <Text color="snow" f={2} children={description} /> </WorkshopCard> </A.link> ) const Workshops = ({ name, data, ...props }) => ( <Box.section id={name} mb={4} {...props}> {name && <Heading.h2 color="black" f={4} mb={1} caps children={name} />} <WorkshopGrid> {map(data, (edge, ii) => ( <WorkshopItem data={edge.node} key={`workshops-${name}-${ii}`} /> ))} </WorkshopGrid> </Box.section> ) export default Workshops
JavaScript
0
@@ -688,16 +688,54 @@ img%7D');%0A + height: 100%25;%0A position: relative;%0A text-s @@ -776,46 +776,8 @@ 2);%0A - position: relative;%0A height: 100%25;%0A &: @@ -1290,16 +1290,98 @@ ld;%0A %7D%0A + &:hover %7B%0A transition: all .125s ease-in;%0A transform: scale(1.03125);%0A %7D%0A h3 %7B%0A
b69c8e1e20396431556c3a00b9a39ff309dfacf2
Disable days before today for selection
src/components/MeetingDaysField/MeetingDaysField.js
src/components/MeetingDaysField/MeetingDaysField.js
import React from "react"; import DayPicker, {DateUtils} from "react-day-picker"; import "./MeetingDaysField.scss"; class MeetingDaysField extends React.Component { static propTypes = { days: React.PropTypes.array.isRequired, month: React.PropTypes.object.isRequired, onDayChange: React.PropTypes.func.isRequired, onMonthChange: React.PropTypes.func.isRequired }; handleDayClick(e, day, {selected, disabled}){ // We need to pass it upwards if(disabled){ return; } this.props.onDayChange(selected, day); } isDaySelected(day){ return this.props.days.findIndex((d) => DateUtils.isSameDay(d, day)) > -1; } render(){ let { month, onMonthChange } = this.props; return ( <div className="MeetingDaysField form-group clearfix"> <label htmlFor="meeting-name" className="col-form-label col-xs-3">Wybierz dni</label> <div className="col-xs-4"> <DayPicker initialMonth={month} firstDayOfWeek={1} selectedDays={this.isDaySelected.bind(this)} onDayClick={this.handleDayClick.bind(this)} onMonthChange={onMonthChange} /> </div> <div className="col-xs-5"> {this.props.children} </div> </div> ); } } export default MeetingDaysField;
JavaScript
0
@@ -75,16 +75,45 @@ icker%22;%0A +import moment from 'moment';%0A import %22 @@ -683,16 +683,96 @@ 1;%0A %7D%0A%0A + isDayBeforeToday(day) %7B%0A return moment(day).add(1, 'day').isBefore();%0A %7D%0A%0A render @@ -1131,16 +1131,108 @@ (this)%7D%0A + disabledDays=%7Bthis.isDayBeforeToday.bind(this)%7D fromMonth=%7Bnew Date()%7D%0A
41e77203d3ee7b119ac3e5b5b9a6cc603f9155ee
fix checkbox ui not updating when view is rendered
src/components/task/task.js
src/components/task/task.js
import { ObservableWrapper } from 'angular2/src/facade/async'; import { ComponentAnnotation as Component, ViewAnnotation as View, onDestroy } from 'angular2/angular2'; import { JitChangeDetection } from 'angular2/change_detection'; import { InjectAnnotation as Inject } from 'angular2/di'; import { NgIf } from 'angular2/directives'; import { DefaultValueAccessor, CheckboxControlValueAccessor, ControlDirective, ControlGroupDirective, FormBuilder, Validators } from 'angular2/forms'; import { Chores } from 'services'; @Component({ selector: 'task', properties: { 'chore': 'model' }, // changeDetection: JitChangeDetection, appInjector: [ FormBuilder, Chores ], lifecycle: [ onDestroy ] }) @View({ templateUrl: 'components/task/task.html', directives: [ DefaultValueAccessor, CheckboxControlValueAccessor, ControlDirective, ControlGroupDirective ] }) export class Task { constructor(@Inject(FormBuilder) builder, @Inject(Chores) chores) { let that = this; this.chores = chores; this.task = builder.group({ status: [false], desc: [''] }); this.status = this.task.controls.status; this.desc = this.task.controls.desc; this._subs = [ ObservableWrapper.subscribe(this.status.valueChanges, function (value) { that.chores.update( that.chore.key, Object.assign({}, that.chore, { completed: value }) ); }), ObservableWrapper.subscribe(this.desc.valueChanges, function (value) { that.chores.update( that.chore.key, Object.assign({}, that.chore, { desc: value }) ); }) ]; } remove(event) { event.preventDefault(); this.chores.remove(this.chore.key); } onDestroy() { for (let sub of this._subs) { ObservableWrapper.dispose(sub); } } }
JavaScript
0.000011
@@ -165,72 +165,8 @@ 2';%0A -import %7B JitChangeDetection %7D from 'angular2/change_detection';%0A impo @@ -525,49 +525,8 @@ %09%7D,%0A -%09// changeDetection: JitChangeDetection,%0A %09app @@ -1479,16 +1479,148 @@ %09%5D;%0A%09%7D%0A%0A +%09set chore(value) %7B%0A%09%09this._model = value;%0A%09%09this.status.updateValue(value.completed);%0A%09%7D%0A%0A%09get chore() %7B%0A%09%09return this._model;%0A%09%7D%0A%0A %09remove(
62dc1f17fe2dc0844264a134014768c8deddf227
Refactor Sizing for ButtonToggle
src/components/button-toggle/button-toggle.style.js
src/components/button-toggle/button-toggle.style.js
import PropTypes from 'prop-types'; import styled, { css } from 'styled-components'; import { THEMES } from '../../style/themes'; const StyledButtonToogle = styled.div` display: inline-block; &:not(:first-of-type) { margin-left: 10px; } `; const StyledButtonToogleLabel = styled.label` display: inline-block; height: 40px; padding: 0 24px; border: 1px solid ${({ theme }) => theme.colors.border}; font-size: 14px; font-weight: 600; input:checked ~ & { color: ${({ theme }) => theme.colors.white}; background-color: ${({ theme }) => theme.colors.tertiary}; } &:hover { background-color: ${({ theme }) => theme.colors.whiteMix}; border-color: ${({ theme }) => theme.colors.tertiary}; } &:focus { outline: 3px solid ${({ theme }) => theme.colors.focus}; } .content-wrapper { display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; } ${({ buttonIconSize }) => buttonIconSize === 'large' && css` min-width: 104px; height: 104px; padding: 0 16px; .content-wrapper { flex-direction: column; } `} /* CLASSIC STYLES */ ${({ theme }) => theme.name === THEMES.classic && css` height: 47px; input:checked ~ & { color: ${theme.colors.white}; background-color: #1573e6; } &:hover { border-color: #1e499f; color: ${theme.colors.white}; background-color: #1e499f; } &:focus { outline: 0; } `}; ${({ theme, size }) => theme.name === THEMES.classic && size === 'small' && css` height: auto; padding: 5px 8px; font-weight: 700; font-size: 12px; `}; `; const iconFontSizes = { classic: { smallIcon: 16, largeIcon: 60 }, modern: { smallIcon: 16, largeIcon: 32 } }; const StyledButtonToggleIcon = styled.div` .carbon-icon::before { font-size: ${`${iconFontSizes.modern.smallIcon}px`}; line-height: ${`${iconFontSizes.modern.smallIcon}px`}; } ${({ buttonIconSize }) => buttonIconSize === 'large' && css` .carbon-icon::before { font-size: ${`${iconFontSizes.modern.largeIcon}px`}; line-height: ${`${iconFontSizes.modern.largeIcon}px`}; } .carbon-icon { margin-bottom: 8px; } `} ${({ theme, buttonIconSize }) => theme.name === THEMES.classic && css` .carbon-icon::before { font-size: ${`${iconFontSizes.classic[`${buttonIconSize}Icon`]}px`}; line-height: ${`${iconFontSizes.classic[`${buttonIconSize}Icon`]}px`}; } `}; `; StyledButtonToogle.propTypes = { buttonSize: PropTypes.string }; StyledButtonToggleIcon.propTypes = { buttonIconSize: PropTypes.string }; export { StyledButtonToogle, StyledButtonToogleLabel, StyledButtonToggleIcon };
JavaScript
0
@@ -956,34 +956,60 @@ %7B buttonIcon -Size %7D) =%3E +, buttonIconSize %7D) =%3E buttonIcon && buttonIconS @@ -1254,24 +1254,28 @@ ight: 47px;%0A + %0A input:c @@ -1527,29 +1527,20 @@ %7D -%0A -%60%7D; %0A%0A + $%7B(%7B - theme, siz @@ -1550,41 +1550,8 @@ ) =%3E - theme.name === THEMES.classic && siz @@ -1568,32 +1568,34 @@ ll' && css%60%0A + height: auto;%0A @@ -1592,16 +1592,18 @@ : auto;%0A + padd @@ -1616,24 +1616,26 @@ px 8px;%0A + + font-weight: @@ -1640,24 +1640,26 @@ t: 700;%0A + font-size: 1 @@ -1667,16 +1667,283 @@ px;%0A + %60%7D;%0A %0A $%7B(%7B size, buttonIcon, buttonIconSize %7D) =%3E buttonIcon && size === 'large' && buttonIconSize === 'large' && css%60%0A height: auto;%0A padding-top: $%7Bsize === 'large' ? '15px' : '0'%7D;%0A padding-bottom: $%7Bsize === 'large' ? '15px' : '0'%7D;%0A %60%7D;%0A %60%7D;%0A -%0A%0A %60;%0A%0A @@ -2127,151 +2127,29 @@ %60%0A -.carbon-icon::before %7B%0A font-size: $%7B%60$%7BiconFontSizes.modern.smallIcon%7Dpx%60%7D;%0A line-height: $%7B%60$%7BiconFontSizes.modern.smallIcon%7Dpx%60%7D +margin-right: 8px ;%0A -%7D%0A %0A $ @@ -2200,32 +2200,107 @@ 'large' && css%60%0A + .carbon-icon %7B%0A margin-right: 0;%0A margin-bottom: 8px;%0A %7D%0A%0A .carbon-icon @@ -2348,34 +2348,49 @@ Sizes.modern -.large +%5B%60$%7BbuttonIconSize%7D Icon +%60%5D %7Dpx%60%7D;%0A @@ -2432,74 +2432,38 @@ dern -.largeIcon%7Dpx%60%7D;%0A %7D%0A .carbon-icon %7B%0A margin-bottom: 8px +%5B%60$%7BbuttonIconSize%7DIcon%60%5D%7Dpx%60%7D ;%0A @@ -2537,32 +2537,98 @@ classic && css%60%0A + margin-right: $%7BbuttonIconSize === 'large' ? '0' : '3px'%7D;%0A %0A .carbon-icon
39a9dcf7a5fa5c7683ff2f4d8f6c67b7bd963012
Remove logging
src/components/search/input/searchInputDirective.js
src/components/search/input/searchInputDirective.js
'use strict'; // @ngInject var searchInputDirective = function () { return { scope: { options: '=', feed: '=' }, template: require('./searchInput.html'), // @ngInject controller: function ($scope, $location, NpdcSearchService, npdcAppConfig) { $scope.options = $scope.options || {}; Object.assign($scope.options, npdcAppConfig.search.local, $scope.options, $scope.feed ? {facets: $scope.feed.facets} : {}); $scope.query = { q: $location.search().q }; $scope.isFiltersOpen = false; $scope.$watch('query.q', (newVal, oldVal) => { console.time('watch'); if (newVal !== oldVal) { let query = Object.assign({}, $location.search(), {q: newVal}); NpdcSearchService.search(query); } console.timeEnd('watch'); }); $scope.$watch('feed', (newVal, oldVal) => { if (newVal && newVal.facets) { $scope.options.facets = newVal.facets; } }); $scope.toggleFilters = function () { $scope.isFiltersOpen = !$scope.isFiltersOpen; }; } }; }; module.exports = searchInputDirective;
JavaScript
0.000001
@@ -614,39 +614,8 @@ %3E %7B%0A - console.time('watch');%0A @@ -798,42 +798,8 @@ %7D%0A - console.timeEnd('watch');%0A
ef45c0ebafb288a72365a4ea091266b80cc61af9
Use new react root api
client/src/index.js
client/src/index.js
import { ApolloProvider } from "@apollo/client" import API from "api" import "bootstrap/dist/css/bootstrap.css" import { jumpToTop } from "components/Page" import "locale-compare-polyfill" import App from "pages/App" import React from "react" import ReactDOM from "react-dom" import { Provider } from "react-redux" import { BrowserRouter, Route } from "react-router-dom" import { persistStore } from "redux-persist" import { PersistGate } from "redux-persist/lib/integration/react" import "./bootstrapOverrides.css" import "./index.css" import configureStore from "./store/configureStore" const store = configureStore() const persistor = persistStore(store) window.onerror = function(message, url, lineNumber, columnNumber) { API.logOnServer("ERROR", url, lineNumber + ":" + columnNumber, message) return false } ReactDOM.render( <Provider store={store}> <PersistGate persistor={persistor}> <ApolloProvider client={API.client}> <BrowserRouter onUpdate={jumpToTop}> <Route path="/" component={App} /> </BrowserRouter> </ApolloProvider> </PersistGate> </Provider>, document.getElementById("root") )
JavaScript
0
@@ -243,24 +243,30 @@ %0Aimport -ReactDOM +%7B createRoot %7D from %22r @@ -269,24 +269,31 @@ m %22react-dom +/client %22%0Aimport %7B P @@ -830,16 +830,70 @@ %0A%7D%0A%0A -ReactDOM +const root = createRoot(document.getElementById(%22root%22))%0A%0Aroot .ren @@ -1182,42 +1182,7 @@ der%3E -,%0A document.getElementById(%22root%22) %0A)%0A
c2558193e7ddb2b5e41e3cd46106f00ffd132827
Add alternate callback for Heroku
client/src/index.js
client/src/index.js
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { browserHistory, Router } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { configure } from 'redux-auth'; import routes from './routes'; import registerServiceWorker from './registerServiceWorker'; import './stylesheets/main.css'; import configureStore from './redux/configureStore'; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); store.dispatch(configure( { apiUrl: 'http://localhost:3001', authProviderPaths: { facebook: '/auth/facebook', google: '/auth/google_oauth2' } }, { isServer: false, cookies: document.cookie, currentLocation: window.location.href, cleanSession: true, clientOnly: true } )).then(() => { render(( <Provider store={store}> <Router history={history} routes={routes} /> </Provider> ), document.getElementById('root')); registerServiceWorker(); });
JavaScript
0.000001
@@ -565,16 +565,61 @@ apiUrl: + process.env.REACT_APP_GOOGLE_CALLBACK_URL %7C%7C 'http:/
7749875a0d9a90978467cae4a605dd6f1eaf939c
Fix 'Search only shows the app name of the first app'
search/js/result.js
search/js/result.js
OC.search.catagorizeResults=function(results){ var types={}; for(var i=0;i<results.length;i++){ var type=results[i].type; if(!types[type]){ types[type]=[]; } types[type].push(results[i]); } return types; } OC.search.hide=function(){ $('#searchresults').hide(); if($('#searchbox').val().length>2){ $('#searchbox').val(''); }; } OC.search.showResults=function(results){ if(results.length==0){ return; } if(!OC.search.showResults.loaded){ var parent=$('<div/>'); $('body').append(parent); parent.load(OC.filePath('search','templates','part.results.php'),function(){ OC.search.showResults.loaded=true; $('#searchresults').click(function(event){ event.stopPropagation(); }); $(window).click(function(event){ OC.search.hide(); }); OC.search.lastResults=results; OC.search.showResults(results); }); }else{ var types=OC.search.catagorizeResults(results); $('#searchresults').show(); $('#searchresults tr.result').remove(); var index=0; for(var name in types){ var type=types[name]; if(type.length>0){ for(var i=0;i<type.length;i++){ var row=$('#searchresults tr.template').clone(); row.removeClass('template'); row.addClass('result'); if (index == 0){ row.children('td.type').text(name); } row.find('td.result a').attr('href',type[i].link); row.find('td.result div.name').text(type[i].name); row.find('td.result div.text').text(type[i].text); row.data('index',index); index++; if(OC.search.customResults[name]){//give plugins the ability to customize the entries in here OC.search.customResults[name](row,type[i]); } $('#searchresults tbody').append(row); } } } } } OC.search.showResults.loaded=false; OC.search.renderCurrent=function(){ if($('#searchresults tr.result')[OC.search.currentResult]){ var result=$('#searchresults tr.result')[OC.search.currentResult]; $('#searchresults tr.result').removeClass('current'); $(result).addClass('current'); } }
JavaScript
0.000013
@@ -1228,20 +1228,16 @@ %09%09%09if (i -ndex == 0)%7B%0A
1f0ad080aecae247918c1d5bcf6288f3eaf16052
Add 'delay' ability to Animations.
src/foam/animation/Animation.js
src/foam/animation/Animation.js
/** * @license * Copyright 2016 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ // Experimental Animation Support // What about nested objects? foam.LIB({ name: 'foam.Animation', methods: [ function animate(obj, f, duration) { var argNames = foam.Function.argNames(f); var janitor = foam.FObject.create(); var l = function() { console.log(arguments); }; var initialValues = new Array(argNames.length); var endValues = new Array(argNames.length); for ( var i = 0 ; i < argNames ; i++ ) { initialValues[i] = obj[argNames[i]]; // janitor.onDetach(obj.propertyChange(argNames[i])); } // foam.Function.withArgs(f, obj) { // } for ( var i = 0 ; i < argNames ; i++ ) { endValues[i] = obj[argNames[i]]; obj[argNames[i]] = initialValues[i]; } for ( var i = 0 ; i < argNames ; i++ ) { obj[argNames[i]] = endValues[i]; } // janitor.detach(); } ] }); foam.CLASS({ package: 'foam.animation', name: 'Animation', // TODO: add support for interpolating colours properties: [ { class: 'Int', name: 'duration', units: 'ms', value: 1000 }, { name: 'f', }, { class: 'Array', name: 'objs' }, { name: 'onEnd', value: function() {} }, { name: 'startTime_' }, { class: 'Map', name: 'slots_' }, { class: 'Boolean', name: 'stopped' }, { name: 'interp', value: foam.animation.Interp.linear } ], methods: [ function start() { var self = this; var cleanup = foam.core.FObject.create(); this.objs.forEach(function(o) { cleanup.onDetach(o.propertyChange.sub(self.propertySet)); }); this.f(); cleanup.detach(); this.startTime_ = Date.now(); this.animateValues(); this.tick(); this.onDetach(() => this.stopped = true); return this; }, function animateValues() { for ( var key in this.slots_ ) { var s = this.slots_[key]; var slot = s[0], startValue = s[1], endValue = s[2]; var time = Math.min(1, (Date.now() - this.startTime_) / this.duration); var value = startValue + (endValue-startValue) * this.interp(time); slot.set(value); } } ], listeners: [ { name: 'propertySet', code: function(_, __, __, slot) { if ( this.slots_[slot] ) return; var oldValue = slot.getPrev(), newValue = slot.get(); if ( ! foam.Number.isInstance(oldValue) || Number.isNaN(oldValue) ) return; this.slots_[slot] = [ slot, oldValue, newValue ]; } }, { name: 'tick', isFramed: true, code: function() { this.animateValues(); if ( Date.now() < this.startTime_ + this.duration ) { this.tick(); } else { this.onEnd(); } } } ] });
JavaScript
0
@@ -1114,16 +1114,46 @@ tion',%0A%0A + imports: %5B 'setTimeout' %5D,%0A%0A // TOD @@ -1231,24 +1231,96 @@ ass: 'Int',%0A + name: 'delay',%0A units: 'ms'%0A %7D,%0A %7B%0A class: 'Int',%0A name: @@ -1717,35 +1717,32 @@ e: f -oam.animation.Interp.linear +unction(t) %7B return t; %7D %0A @@ -1782,24 +1782,195 @@ n start() %7B%0A + if ( this.delay %3E 0 ) %7B%0A window.setTimeout(this.start_.bind(this), this.delay);%0A %7D else %7B%0A this.start_();%0A %7D%0A %7D,%0A%0A function start_() %7B%0A var se
19bdc9e0926d33a96f38d5bb590d05b7ec251fee
Fix issue with post with no tag
server/api/posts.js
server/api/posts.js
import needle from 'needle'; import { SiteConf, getDate } from 'base'; export const postsApiHandler = (req, res) => { needle('get', SiteConf.PostsApi) .then(resp => { const data = resp.body; const filter = req.params.filter; const pagination = data.meta.pagination; const posts = PostList(data.posts, filter); const result = { posts, pagination }; res.json(result); }) .catch(err => { console.log(333, err); res.status(500).json(err); }); }; export const PostList = (posts, filter) => { return posts.filter((post) => { const reg = new RegExp(`^(.+?)${ SiteConf.postOpeningSplitChar }`); const result = reg.exec(post.html); if (result) post.opening = result[1]; else { let i = 0; let max = SiteConf.postOpeningChars; const words = post.html.split(' '); post.opening = ''; for (i; i <= max ; i++) { post.opening += `${words[i]} `; } post.opening += '...</p>'; } post.html = null; post.markdown = null; post.published_at = getDate(post.published_at); if (filter && post.tags[0]) { if (post.tags[0].slug === filter.split(':')[1]) return post; else return false; } else return post; } ); };
JavaScript
0
@@ -1116,38 +1116,38 @@ lter - && post.tags%5B0%5D) %7B%0A if ( +) %7B%0A if (post.tags%5B0%5D && post
41e619df9fa69e4e18cd5a3c8160c4d5f017429e
Test push
src/commands/go/goFish.js
src/commands/go/goFish.js
const goFish = (stopClient, msg, cmd, subcmd, richEmbed, fishList) => { if (subcmd === 'fish') { // Arrays of fish names, emojis names, and db names const fishEmojis = [':fish:', ':fish_cake:', ':fishing_pole_and_fish:', ':tropical_fish:', ':blowfish:']; const fishNames = ['Fish', 'Fish Cake', 'Fish on a Fishing Pole', 'Tropical Fish', 'Blowfish']; const dbNames = ['fish', 'cake', 'fishpole', 'tropical', 'blowfish']; const rareFishEmojis = [':whale:', ':whale2:', ':dolphin:', ':octopus:', ':unicorn:']; const dbRare = ['cutewhale', 'bluewhale', 'dolphin', 'octopus', 'unicorn']; const rareFishNames = ['Cute Whale', 'Blue Whale', 'Dolphin', 'Octopus', 'Unicorn']; const allFishEmojis = fishEmojis.concat(fishEmojis).concat(fishEmojis).concat(rareFishEmojis); const allFishNames = fishNames.concat(fishNames).concat(fishNames).concat(rareFishNames); const allDBNames = dbNames.concat(dbNames).concat(dbNames).concat(dbRare); // Reset to empty array on every "!go fish" message const fishCaught = []; // Get random fish and random number of fish const fishType = Math.floor(Math.random() * 20); const fishNumber = Math.floor(Math.random() * 5) + 1; // Push emojis to temp array to join for message for (let times = 0; times < fishNumber; times++) { fishCaught.push(allFishEmojis[fishType]); } msg.channel.send(fishCaught.join(' ')); msg.channel.send('You caught ' + fishNumber + ' ' + allFishNames[fishType] + '!'); // Update database with amount stopClient.query(`UPDATE fish_lists SET ${allDBNames[fishType]} = ${allDBNames[fishType]} + ${fishNumber} WHERE userid=${msg.author.id}`); } else if (subcmd === 'inv') { // Rich embed message of inventory const embed = richEmbed .setColor('#ff0000') .setDescription(`${msg.author}'s inventory **${fishList['fish']}** x :fish: **${fishList['cake']}** x :fish_cake: **${fishList['fishpole']}** x :fishing_pole_and_fish: **${fishList['tropical']}** x :tropical_fish: **${fishList['blowfish']}** x :blowfish: **${fishList['cutewhale']}** x :whale: **${fishList['bluewhale']}** x :whale2: **${fishList['dolphin']}** x :dolphin: **${fishList['octopus']}** x :octopus: `); msg.channel.send({embed}); } } export default goFish;
JavaScript
0
@@ -1152,17 +1152,16 @@ () * 20) -; %0A con
d1bbdfc6a09b6d6ef473b77b33cf1a48f8f50737
Iterate through a premade list
src/commands/man/index.js
src/commands/man/index.js
const Discord = require("discord.js"); const MSS = require("./../../functions/"); const config = require("./../../config.json"); const fs = require("fs"); var commands = []; var print = "What manual page do you want?\n" + config.MSS.prefix + "man <command>\n" + config.MSS.prefix + "man all\n"; //Get all .json files in this directory to read the man data. fs.readdir("./commands/", function(err, items) { items.forEach(function(item) { var file = item.replace(/['"]+/g, ""); print += "> " + file + "\n"; //Include the meta.json files in the commands directory commands[file] = require("./../" + file + "/meta.json"); }); }); module.exports = function manpages(message) { let input = message.content.replace(/\n/g, " ").split(" "); //Return the usage of the man command if no attributes were given if(!input[1]) { message.reply(print); return false; } //Return an entire list of commands via DM if(input[1] === "all") { message.reply("I sent a message via Direct Messaging with details enclosed."); console.dir(commands); commands.forEach(function(item, index) { console.log(item); console.log(index); var embed = new Discord.RichEmbed() .setTitle(item.meta.name) .setAuthor("MSS Man Pages", "http://moustacheminer.com/mss.png") .setColor("#00AE86") .setDescription(item.meta.description) .setFooter("MSS-Discord, " + config.MSS.version, "") .setTimestamp() .setURL(item.meta.url); item.meta.examples.forEach(function(element) { //!!command <var> <var> //Description embed.addField(config.MSS.prefix + index + " " + element.var, element.description); }); message.author.sendEmbed(embed, "" , { disableEveryone: true }); console.log(index); }); return false; } //Return if it doesn't exist if (!commands[input[1]]) { MSS.msg.react(message, false, "link"); message.reply("No manual entry for " + input[1]); return false; } var embed = new Discord.RichEmbed() .setTitle(commands[input[1]].meta.name) .setAuthor("MSS Man Pages", "http://moustacheminer.com/mss.png") .setColor("#00AE86") .setDescription(commands[input[1]].meta.description) .setFooter("MSS-Discord, " + config.MSS.version, "") .setTimestamp() .setURL(commands[input[1]].meta.url); commands[input[1]].meta.examples.forEach(function(element) { embed.addField(config.MSS.prefix + input[1] + " " + element.var, element.description); }); message.channel.sendEmbed(embed, input[1], { disableEveryone: true }); }
JavaScript
0.999944
@@ -167,16 +167,31 @@ s = %5B%5D;%0A +var list = %5B%5D;%0A var prin @@ -577,16 +577,35 @@ rectory%0A +%09%09list.push(file);%0A %09%09comman @@ -1056,121 +1056,40 @@ %22);%0A +%0A %09%09 -console.dir(commands);%0A%0A%09%09commands.forEach(function(item, index) %7B%0A%09%09%09console.log(item);%0A%09%09%09console.log(index); +list.forEach(function(item) %7B %0A%09%09%09 @@ -1138,20 +1138,37 @@ etTitle( +commands%5Binput%5B item +%5D%5D .meta.na @@ -1285,20 +1285,37 @@ ription( +commands%5Binput%5B item +%5D%5D .meta.de @@ -1414,20 +1414,37 @@ .setURL( +commands%5Binput%5B item +%5D%5D .meta.ur @@ -1451,20 +1451,37 @@ l);%0A%0A%09%09%09 +commands%5Binput%5B item +%5D%5D .meta.ex @@ -1519,54 +1519,8 @@ ) %7B%0A -%09%09%09%09//!!command %3Cvar%3E %3Cvar%3E%0A%09%09%09%09//Description%0A %09%09%09%09 @@ -1556,19 +1556,25 @@ fix + in -dex +put%5Bitem%5D + %22 %22 + @@ -1632,14 +1632,15 @@ age. -author +channel .sen @@ -1657,11 +1657,19 @@ ed, -%22%22 +input%5Bitem%5D , %7B @@ -1697,32 +1697,8 @@ %7D); -%0A%0A%09%09%09console.log(index); %0A%09%09%7D
0a92f8c6bdd9ae7b9dd6bad4ebcf242f0d5bb70a
Make use of veccy index.js
src/common/veccy/index.js
src/common/veccy/index.js
JavaScript
0.000002
@@ -1 +1,76 @@ +exports.Vector = require(%22./Vector%22);%0Aexports.Matrix = require(%22./Matrix%22); %0A
911cbb3bfba594464dc521e77166ea3b96551a07
improve event_emitter - add once - _signal = fast _emit without side effects (preventdefault) - capturing argument for addListener
lib/ace/lib/event_emitter.js
lib/ace/lib/event_emitter.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define(function(require, exports, module) { "use strict"; var EventEmitter = {}; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry = this._eventRegistry || {}; this._defaultHandlers = this._defaultHandlers || {}; var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) { e.stopPropagation = function() { this.propagationStopped = true; }; } if (!e.preventDefault) { e.preventDefault = function() { this.defaultPrevented = true; }; } for (var i=0; i<listeners.length; i++) { listeners[i](e); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e); }; EventEmitter.setDefaultHandler = function(eventName, callback) { this._defaultHandlers = this._defaultHandlers || {}; if (this._defaultHandlers[eventName]) throw new Error("The default handler for '" + eventName + "' is already set"); this._defaultHandlers[eventName] = callback; }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners.push(callback); }; EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; });
JavaScript
0.000005
@@ -1752,16 +1752,153 @@ er = %7B%7D; +%0Avar stopPropagation = function() %7B this.propagationStopped = true; %7D;%0Avar preventDefault = function() %7B this.defaultPrevented = true; %7D; %0A%0AEventE @@ -1983,34 +1983,36 @@ ._eventRegistry -= +%7C%7C ( this._eventRegis @@ -2015,21 +2015,21 @@ egistry -%7C%7C += %7B%7D +) ;%0A th @@ -2040,34 +2040,36 @@ defaultHandlers -= +%7C%7C ( this._defaultHan @@ -2074,21 +2074,21 @@ andlers -%7C%7C += %7B%7D +) ;%0A%0A v @@ -2360,21 +2360,16 @@ ntName;%0A - %0A if ( @@ -2387,18 +2387,16 @@ agation) - %7B %0A @@ -2420,86 +2420,24 @@ n = -function() %7B%0A this.propagationStopped = true;%0A %7D;%0A %7D%0A +stopPropagation; %0A @@ -2459,18 +2459,16 @@ Default) - %7B %0A @@ -2491,79 +2491,67 @@ t = -function() %7B%0A this.defaultPrevented = true;%0A %7D;%0A %7D +preventDefault;%0A if (!e.target)%0A e.target = this; %0A%0A @@ -2763,24 +2763,508 @@ ler(e);%0A%7D;%0A%0A +%0AEventEmitter._signal = function(eventName, e) %7B%0A var listeners = (this._eventRegistry %7C%7C %7B%7D)%5BeventName%5D;%0A if (!listeners)%0A return;%0A%0A for (var i=0; i%3Clisteners.length; i++)%0A listeners%5Bi%5D(e);%0A%7D;%0A%0AEventEmitter.once = function(eventName, callback) %7B%0A var _self = this;%0A var newCallback = function() %7B%0A fun && fun.apply(null, arguments);%0A _self.removeEventListener(event, newCallback);%0A %7D;%0A this.addEventListener(event, newCallback);%0A%7D;%0A%0A%0A EventEmitter @@ -3639,32 +3639,43 @@ ntName, callback +, capturing ) %7B%0A this._ev @@ -3910,13 +3910,40 @@ ners -. +%5Bcapturing ? %22unshift%22 : %22 push +%22%5D (cal
8711eebe22285aa2156548fd41678f885de9fa93
Customize UI theme
src/components/App/App.js
src/components/App/App.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component, PropTypes } from 'react'; import emptyFunction from 'fbjs/lib/emptyFunction'; import s from './App.scss'; import Header from '../Header'; import Footer from '../Footer'; class App extends Component { static propTypes = { context: PropTypes.shape({ insertCss: PropTypes.func, onSetTitle: PropTypes.func, onSetMeta: PropTypes.func, onPageNotFound: PropTypes.func, }), children: PropTypes.element.isRequired, error: PropTypes.object, }; static childContextTypes = { insertCss: PropTypes.func.isRequired, onSetTitle: PropTypes.func.isRequired, onSetMeta: PropTypes.func.isRequired, onPageNotFound: PropTypes.func.isRequired, }; getChildContext() { const context = this.props.context; return { insertCss: context.insertCss || emptyFunction, onSetTitle: context.onSetTitle || emptyFunction, onSetMeta: context.onSetMeta || emptyFunction, onPageNotFound: context.onPageNotFound || emptyFunction, }; } componentWillMount() { const { insertCss } = this.props.context; this.removeCss = insertCss(s); } componentWillUnmount() { this.removeCss(); } render() { return !this.props.error ? ( <div> <Header /> {this.props.children} <Footer /> </div> ) : this.props.children; } } export default App;
JavaScript
0.000001
@@ -453,16 +453,963 @@ oter';%0A%0A +import %7B%0A cyan500, cyan700,%0A pinkA200,%0A grey100, grey300, grey400, grey500,%0A white, darkBlack, fullBlack,%0A%7D from 'material-ui/styles/colors';%0A%0Aimport %7Bfade%7D from 'material-ui/utils/colorManipulator';%0Aimport spacing from 'material-ui/styles/spacing';%0A%0Aimport MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';%0Aimport getMuiTheme from 'material-ui/styles/getMuiTheme';%0Aimport RaisedButton from 'material-ui/RaisedButton';%0A%0Aconst muiTheme = getMuiTheme(%7B%0A palette: %7B%0A primary1Color: cyan500,%0A primary2Color: cyan700,%0A primary3Color: grey400,%0A accent1Color: '#F2DF83',%0A accent2Color: grey100,%0A accent3Color: grey500,%0A textColor: darkBlack,%0A alternateTextColor: white,%0A canvasColor: white,%0A borderColor: grey300,%0A disabledColor: fade(darkBlack, 0.3),%0A pickerHeaderColor: cyan500,%0A clockCircleColor: fade(darkBlack, 0.07),%0A shadowColor: fullBlack,%0A %7D,%0A appBar: %7B%0A color: '#F2DF83',%0A %7D%0A%7D);%0A%0A class Ap @@ -2443,16 +2443,61 @@ ror ? (%0A + %3CMuiThemeProvider muiTheme=%7BmuiTheme%7D%3E%0A %3Cd @@ -2564,24 +2564,24 @@ %3CFooter /%3E%0A - %3C/div%3E @@ -2577,24 +2577,50 @@ %3C/div%3E%0A + %3C/MuiThemeProvider%3E%0A ) : this
2a6faabeeaf2a3211a3686b51d48591769ff71a1
Add link to channel
src/components/Channel.js
src/components/Channel.js
import React, { Component } from 'react'; import { ListItem } from 'material-ui/List'; import Actions from '../actions'; const Channel = (props) => { function onClick () { Actions.channelOpened(props.channel); } let style = {}; if (props.channel.selected) { style.backgroundColor = '#f0f0f0'; } return ( <ListItem onClick={ onClick } style={ style }> { props.channel.name } </ListItem> ); } export default Channel;
JavaScript
0
@@ -31,24 +31,58 @@ om 'react';%0A +import Actions from '../actions';%0A import %7B Lis @@ -125,34 +125,37 @@ ort -Actions from '../actions'; +%7B Link %7D from 'react-router'%0A %0A%0Aco @@ -185,79 +185,8 @@ %3E %7B%0A - function onClick () %7B%0A Actions.channelOpened(props.channel);%0A %7D%0A%0A le @@ -281,49 +281,170 @@ %0A%0A -return (%0A %3CListItem onClick=%7B onClick +let linkStyle = %7B%0A textDecoration: 'none',%0A color: '#155063' %0A %7D%0A%0A return (%0A %3CListItem style=%7B style %7D%3E%0A %3CLink to=%7B%60/chat/$%7Bprops.channel.key%7D%60 %7D st @@ -445,33 +445,37 @@ %7D%60%7D style=%7B -s +linkS tyle %7D%3E%0A %7B prop @@ -458,24 +458,26 @@ inkStyle %7D%3E%0A + %7B prop @@ -493,16 +493,30 @@ .name %7D%0A + %3C/Link%3E%0A %3C/Li
3ae6f089a26937face548e86adacb88780015d38
Fix typo in ctrl-enter-clicked feature
src/extension/features/accounts/ctrl-enter-cleared/index.js
src/extension/features/accounts/ctrl-enter-cleared/index.js
import { Feature } from 'toolkit/extension/features/feature'; import { isCurrentRouteAccountsPage } from 'toolkit/extension/utils/ynab'; export class CtrlEnterCleared extends Feature { shouldInvoke() { return isCurrentRouteAccountsPage() && $('.ynab-grid-body-row.is-adding').length; } invoke() { const addRow = document.querySelector('.ynab-grid-body-row.is-adding'); const memoInput = addRow.querySelector('.ynab-grid-cell-memo input'); const outflowInput = addRow.querySelector('.ynab-grid-cell-outflow input'); const inflowInput = addRow.querySelector('.ynab-grid-cell-inflow input'); if (!memoInput.getAttribute('data-toolkit-ctrl-behavior')) { memoInput.setAttribute('data-toolkit-ctrl-behavior', true); memoInput.addEventListener('keydown', this.applyCtrlEnter); } if (!outflowInput.getAttribute('data-toolkit-ctrl-behavior')) { outflowInput.setAttribute('data-toolkit-ctrl-behavior', true); outflowInput.addEventListener('keydown', this.applyCtrlEnter); } if (!inflowInput.getAttribute('data-toolkit-ctrl-behavior')) { inflowInput.setAttribute('data-toolkit-ctrl-behavior', true); inflowInput.addEventListener('keydown', this.applyCtrlEnter); } } applyCtrlEnter(event) { if (event.keyCode === 13 && (event.metaKey || event.ctrlKey)) { let markClearedButton = document.querySelector('.is-adding .ynab-cleared:not(.is-cleared)'); if (markClearedButton) { markClearedButton[0].click(); } } } observe(changedNodes) { if (!changedNodes.has('ynab-grid-add-rows')) return; if (this.shouldInvoke()) { this.invoke(); } } }
JavaScript
0.000453
@@ -1495,11 +1495,8 @@ tton -%5B0%5D .cli
74aa1e1e306250625977cd4c91eeffdffd5b97dd
Include TestRPC URL in truffle develop initial output
packages/truffle-core/lib/commands/develop.js
packages/truffle-core/lib/commands/develop.js
var command = { command: 'develop', description: 'Open a console with a local TestRPC', builder: { log: { type: "boolean", default: false } }, runConsole: function(config, testrpcOptions, done) { var Console = require("../console"); var Environment = require("../environment"); var commands = require("./index") var excluded = [ "console", "init", "watch", "serve", "develop" ]; var available_commands = Object.keys(commands).filter(function(name) { return excluded.indexOf(name) == -1; }); var console_commands = {}; available_commands.forEach(function(name) { console_commands[name] = commands[name]; }); Environment.develop(config, testrpcOptions, function(err) { if (err) return done(err); var c = new Console(console_commands, config.with({ noAliases: true })); c.start(done); c.on("exit", function() { process.exit(); }); }); }, run: function (options, done) { var Config = require("truffle-config"); var Develop = require("../develop"); var config = Config.detect(options); var ipcOptions = { log: options.log }; var testrpcOptions = { host: "localhost", port: 9545, network_id: 4447, seed: "yum chocolate", gasLimit: config.gas }; Develop.connectOrStart(ipcOptions, testrpcOptions, function(started) { if (started) { config.logger.log("Truffle Develop started."); config.logger.log(); } else { config.logger.log("Connected to exiting Truffle Develop session."); config.logger.log(); } if (!options.log) { command.runConsole(config, testrpcOptions, done); } }); } } module.exports = command;
JavaScript
0
@@ -1453,24 +1453,98 @@ (started) %7B%0A + var url = %60http://$%7BtestrpcOptions.host%7D:$%7BtestrpcOptions.port%7D/%60;%0A%0A if (st @@ -1578,17 +1578,17 @@ ger.log( -%22 +%60 Truffle @@ -1602,18 +1602,27 @@ started -.%22 + at $%7Burl%7D%60 );%0A @@ -1686,17 +1686,17 @@ ger.log( -%22 +%60 Connecte @@ -1735,10 +1735,19 @@ sion -.%22 + at $%7Burl%7D%60 );%0A
6066a0425b671275a3f7d3c3d8947867b75fa353
Format data smaller in logger
packages/truffle-debugger/lib/store/common.js
packages/truffle-debugger/lib/store/common.js
import debugModule from "debug"; const debug = debugModule("debugger:store:common"); const reduxDebug = debugModule("debugger:redux"); import { compose, createStore, applyMiddleware } from "redux"; import createSagaMiddleware from "redux-saga"; import createLogger from "redux-cli-logger"; export default function configureStore (reducer, saga, initialState, composeEnhancers) { const sagaMiddleware = createSagaMiddleware(); if (!composeEnhancers) { composeEnhancers = compose; } const loggerMiddleware = createLogger({ log: reduxDebug, stateTransformer: (state) => ({ ...state, context: { list: ["..."], indexForAddress: {"...": "..."}, indexForBinary: {"...": "..."}, }, trace: { ...state.trace, steps: ["..."] } }) }); let store = createStore( reducer, initialState, composeEnhancers( applyMiddleware( sagaMiddleware, loggerMiddleware ) ) ); sagaMiddleware.run(saga); return store; }
JavaScript
0.000014
@@ -600,24 +600,635 @@ ...state,%0A%0A + data: %7B%0A ...Object.assign(%0A %7B%7D,%0A ...Object.entries(state.data)%0A .map( (%5Bcontext, scope%5D) =%3E (%7B%0A %5Bcontext%5D: %7B%0A ...Object.assign(%0A %7B%7D,%0A ...Object.entries(scope)%0A .filter( (%5Bid, %7Bvariables%7D%5D) =%3E variables && variables.length %3E 0 )%0A .map(%0A (%5Bid, %7Bvariables%7D%5D) =%3E (%7B%0A %5Bid%5D: (variables %7C%7C %5B%5D).map( (v) =%3E v.name )%0A %7D)%0A )%0A )%0A %7D%0A %7D))%0A )%0A %7D,%0A%0A contex
5f600ef0f81f133b3b4dca1c61960c6ae8e82d0b
添加必要的空格。
src/data/utils/utf8.js
src/data/utils/utf8.js
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// @Copyright ~2016 ☜Samlv9☞ and other contributors /// @MIT-LICENSE | 1.0.0 | http://apidev.guless.com/ /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// }| /// }| /// }|   へ    /| /// _______ _______ ______ }| / │   / / /// / ___ | |_ __ \ .' ____ '. }| │ Z _,< /   /`ヽ /// | (__ \_| | |__) | | (____) | }| │     ヽ   /  〉 /// '.___`-. | __ / '_.____. | }| Y     `  /  / /// |`\____) | _| | \ \_ | \____| | }| イ● 、 ●  ⊂⊃〈  / /// |_______.' |____| |___| \______,' }| ()  v    | \〈 /// |=========================================\|  >ー 、_  ィ  │ // /// |> LESS IS MORE || / へ   / ノ<|\\ /// `=========================================/| ヽ_ノ  (_/  │// /// }| 7       |/ /// }| >―r ̄ ̄`ー―_` /// }| /// }| /// 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. function sizeof( s ) { for ( var start = 0, total = 0; start < s.length; ++start ) { var charcode = s.charCodeAt(start); total += (charcode >= 0xD800) && (charcode <= 0xDBFF) ? (++start >= s.length ? -1 : 2) : (charcode > 0x7F) ? (charcode <= 0x7FF ? 1 : 2) : 0; } return s.length + total; } export default function utf8( s ) { var output = new Uint8Array(sizeof(s)); for ( var start = 0, offset = 0; start < s.length; ++start ) { var charcode = s.charCodeAt(start); if ( (charcode >= 0xDC00) && (charcode <= 0xDFFF) ) { throw new Error(`Encounter an unpaired surrogate. [charcode="${charcode}"]`); } if ( (charcode >= 0xD800) && (charcode <= 0xDBFF) ) { if ( ++start >= s.length ) { throw new Error(`Encounter an unpaired surrogate. [charcode="${charcode}"]`); } var tailcode = s.charCodeAt(start); if ( (tailcode < 0xDC00) || (tailcode > 0xDFFF) ) { throw new Error(`Encounter an unpaired surrogate. [charcode="${charcode}", tailcode="${tailcode}"]`); } charcode = ((charcode & 0x3FF) << 10 | (tailcode & 0x3FF)) + 0x10000; } if ( charcode <= 0x7F ) { output[offset++] = (charcode); } else if ( charcode <= 0x7FF ) { output[offset++] = ((charcode >>> 6) + 0xC0); output[offset++] = ((charcode & 0x3F) + 0x80); } else if ( charcode <= 0xFFFF ) { output[offset++] = ((charcode >>> 12) + 0xE0); output[offset++] = (((charcode >>> 6) & 0x3F) + 0x80); output[offset++] = ((charcode & 0x3F) + 0x80); } else { output[offset++] = ((charcode >>> 18) + 0xF0); output[offset++] = (((charcode >>> 12) & 0x3F) + 0x80); output[offset++] = (((charcode >>> 6) & 0x3F) + 0x80); output[offset++] = ((charcode & 0x3F) + 0x80); } } return output; }
JavaScript
0
@@ -2409,24 +2409,47 @@ zeof( s ) %7B%0A + var total = 0%0A %0A for ( va @@ -2461,19 +2461,8 @@ rt = - 0, total = 0; @@ -2491,16 +2491,25 @@ art ) %7B +%0A var char @@ -2536,16 +2536,34 @@ start); +%0A %0A total += @@ -2608,17 +2608,33 @@ 0xDBFF) -? +%0A ? (++star @@ -2712,17 +2712,27 @@ 2) : 0; -%7D +%0A %7D%0A %0A ret
65f82ae61d8f53d3819c79fe41204c7d6880d29c
Fix codacy issues
src/deep-fs/test/FS.js
src/deep-fs/test/FS.js
'use strict'; import chai from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import {FS} from '../lib.compiled/FS'; import {UnknownFolderException} from '../lib.compiled/Exception/UnknownFolderException'; import Kernel from 'deep-kernel'; chai.use(sinonChai); suite('FS', function() { let fs = new FS('tempBucket', 'publicBucket', 'systemBucket'); test('Class FS exists in FS', function() { chai.expect(typeof FS).to.equal('function'); }); test('Check TMP static getter returns \'temp\'', function() { chai.expect(FS.TMP).to.be.equal('temp'); }); test('Check PUBLIC static getter returns \'public\'', function() { chai.expect(FS.PUBLIC).to.be.equal('public'); }); test('Check SYSTEM static getter returns \'system\'', function() { chai.expect(FS.SYSTEM).to.be.equal('system'); }); test('Check FOLDERS static getter returns array of levels', function() { chai.expect(FS.FOLDERS.length).to.be.equal(3); chai.expect(FS.FOLDERS).to.be.include(FS.TMP); chai.expect(FS.FOLDERS).to.be.include(FS.PUBLIC); chai.expect(FS.FOLDERS).to.be.include(FS.SYSTEM); }); test('Check getFolder() method throws \'UnknownFolderException\' exception for invalid value', function() { let error = null; try { fs.getFolder('invalidPath'); } catch (e) { error = e; } chai.expect(error).to.be.not.equal(null); chai.expect(error).to.be.an.instanceof(UnknownFolderException); }); test('Check getFolder() method returns valid value', function() { let error = null; let actualResult = null; try { actualResult = fs.getFolder(FS.TMP); } catch (e) { error = e; } //todo - bucket issue here //chai.expect(error).to.be.equal(null); //chai.expect(actualResult).to.be.an.contains(FS.TMP); }); test('Check _getTmpDir() static method returns valid value', function() { let error = null; let actualResult = null; try { actualResult = FS._getTmpDir(FS.TMP); } catch (e) { error = e; } chai.expect(error).to.be.equal(null); chai.expect(actualResult).to.be.an.contains(FS.TMP); }); test('Check tmp() getter returns valid mounted tmp folder', function() { let error = null; let actualResult = null; try { actualResult = fs.tmp; } catch (e) { error = e; } // todo - AssertionError: expected [Error: bucket is required] to equal null //chai.expect(error).to.be.equal(null); //chai.expect(actualResult).to.be.an.contains(FS.TMP); }); test('Check public() getter returns valid mounted tmp folder', function() { let error = null; let actualResult = null; try { actualResult = fs.public; } catch (e) { error = e; } // todo - AssertionError: expected [Error: bucket is required] to equal null //chai.expect(error).to.be.equal(null); //chai.expect(actualResult).to.be.an.contains(FS.PUBLIC); }); test('Check system() getter returns valid mounted tmp folder', function() { let error = null; let actualResult = null; try { actualResult = fs.system; } catch (e) { error = e; } // todo - AssertionError: expected [Error: bucket is required] to equal null //chai.expect(error).to.be.equal(null); //chai.expect(actualResult).to.be.an.contains(FS.SYSTEM); }); test('Check boot() method boots a certain service', function() { let error = null; let actualResult = null; let deepServices = {serviceKey: 'ServiceName'}; let spyCallback = sinon.spy(); let kernel = null; try { kernel = new Kernel(deepServices, Kernel.FRONTEND_CONTEXT); kernel.config.buckets = fs._buckets; actualResult = fs.boot(kernel, spyCallback); } catch (e) { error = e; } }); });
JavaScript
0.000002
@@ -3817,8 +3817,9 @@ %7D);%0A%7D); +%0A
1580441fd9a8c0cb9b75764b33efdfb4ede8db19
Update ReverseInteger.js
algorithms/ReverseInteger.js
algorithms/ReverseInteger.js
// Source : https://oj.leetcode.com/problems/reverse-integer/ // Author : Dean Shi // Date : 2015-06-03 /********************************************************************************** * * Reverse digits of an integer. * * Example1: x = 123, return 321 * Example2: x = -123, return -321 * * * Have you thought about this? * * Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! * * > If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. * * > Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, * then the reverse of 1000000003 overflows. How should you handle such cases? * * > Throw an exception? Good, but what if throwing an exception is not an option? * You would then have to re-design the function (ie, add an extra parameter). * * **********************************************************************************/ /** * @param {number} x * @return {number} */ var reverse = function(x) { var result; var overflow = 2147483648; // Math.pow(2, 31) var arr = (x + '').split(''); if (x < 0) { arr.shift(); result = -arr.reverse().join(''); } else { result = +arr.reverse().join(''); } if (result <= -overflow || result >= overflow - 1) { result = 0; } return result; }; // Test cases console.log(reverse(1563847412) === 0); // true console.log(reverse(-2147483648) === 0); // true console.log(reverse(32768) === 86723); // true
JavaScript
0
@@ -1075,247 +1075,106 @@ -var +let result -;%0A var overflow = 2147483648; // Math.pow(2, 31)%0A var arr = (x + '').split('');%0A%0A if (x %3C 0) %7B%0A arr.shift();%0A result = -arr.reverse().join('');%0A %7D else %7B%0A result = +arr.reverse().join(''); + = 0%0A while(x) %7B%0A result = result * 10 + x %25 10 %0A x = ~~(x / 10) %0A %7D%0A -%0A @@ -1188,57 +1188,45 @@ ult -%3C= -overflow %7C%7C result %3E= overflow - 1) %7B%0A +%3E 2147483648 %7C%7C result %3C -2147483649) res @@ -1236,15 +1236,13 @@ = 0 -; %0A -%7D %0A @@ -1255,17 +1255,16 @@ n result -; %0A%7D;%0A%0A//
34895b22fec3646a29efd32e314aa16b706e8059
Remove test code
node_modules/fd/ui/tree/node.js
node_modules/fd/ui/tree/node.js
var h = require('fd/html') var property = require('fd/property') function Node(tree, parent, model) { this.tree = tree this.parent = parent this.model = model this.open = false this.loaded = false this.children = null this._selected = false this.el = h('.node', [ this.item = h('.item', [ this.disclosureButton = model.isGroup ? h('button.disclosure') : h('.disclosure placeholder'), this.icon = h('.icon'), this.title = h('.title'), this.lock = h('button.lock'), this.hide = h('button.hide'), ]), this.container = h('.children'), ]) this.updateIcon() this.updateTitle() this.updateHidden() model.on('nameChange', this.updateName) model.on('hiddenChange', this.updateHidden) this.disclosureButton.addEventListener('click', this.onDisclosureClick.bind(this)) this.item.addEventListener('mousedown', this.onClick.bind(this)) tree.nodes.set(model, this) if (this.model.name === 'Group 20') this.toggle() } Node.prototype.updateIcon = function() {} Node.prototype.updateTitle = function() { this.title.textContent = this.model.name } Node.prototype.updateHidden = function() {} Node.prototype.onDisclosureClick = function() { this.toggle() } Node.prototype.onClick = function(e) { if (this.model.isGroup && e.target === this.disclosureButton) return this.tree.editor.selection = this.model } Node.prototype.update = function(c) { if (!this.loaded) return switch (c.kind) { case 'append': this.container.appendChild(this.makeNode(c.child).el) return case 'insert': this.container.insertBefore(this.makeNode(c.child).el, this.container.childNodes[c.index]) return case 'replace': this.container.replaceChild(this.makeNode(c.child).el, this.tree.nodes.get(c.old).detach().el) return case 'replaceWithAll': var f = document.createDocumentFragment() c.children.forEach(function(child) { f.appendChild(this.makeNode(child).el) }, this) this.container.replaceChild(f, this.tree.nodes.get(c.old).detach().el) return case 'remove': this.container.removeChild(this.tree.nodes.get(c.child).detach().el) return default: console.warn('unhandled change:', c) } } Node.prototype.detach = function() { this.model.unlisten('nameChange', this.updateName) this.model.unlisten('hiddenChange', this.updateHidden) this.tree.nodes.delete(this) this.parent.children.delete(this) return this } Node.prototype.toggle = function() { this.item.classList.toggle('open', this.open = !this.open) if (this.loaded || !this.open) { this.container.style.display = this.open ? '' : 'none' return } this.loaded = true this.children = new Set this.model.children.forEach(function(child) { var n = this.makeNode(child) this.container.appendChild(n.el) return n }, this) } Node.prototype.makeNode = function(child) { var n = new Node(this.tree, this, child) this.children.add(n) return n } property(Node.prototype, 'selected', {didSet: function(value) { this.item.classList.toggle('selected', !!value) }}) module.exports = Node
JavaScript
0.000004
@@ -929,60 +929,8 @@ is)%0A - if (this.model.name === 'Group 20') this.toggle()%0A %7D%0A%0AN
6b8a2c39e0321f8317fa621d1ed4aa31b6d7220c
remove blankImage option from simple version
src/jquery.lazyloadxt.simple.js
src/jquery.lazyloadxt.simple.js
/*jslint browser:true, plusplus:true, vars:true */ /*jshint browser:true, jquery:true */ (function ($, window, document) { 'use strict'; // options var options = { selector: 'img', srcAttr: 'data-src', classNojs: 'lazy', blankImage: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', edgeX: 0, edgeY: 0, throttle: 99, visibleOnly: true, loadEvent: 'pageshow', // check AJAX-loaded content in jQueryMobile updateEvent: 'load orientationchange resize scroll' // page-modified events }, $window = $(window), elements = [], viewportTop, viewportBottom, viewportLeft, viewportRight, topLazy = 0, /* waitingMode=0 : no setTimeout waitingMode=1 : setTimeout, no deferred events waitingMode=2 : setTimeout, deferred events */ waitingMode = 0; $.lazyLoadXT = $.extend(options, $.lazyLoadXT); /** * Add element to lazy-load list * Call: addElement(idx, el) or addElement(el) * @param idx * @param {HTMLElement} [el] */ function addElement(idx, el) { var $el = $(el || idx); // prevent duplicates if ($el.data('lazied')) { return; } $el .data('lazied', 1) .removeClass(options.classNojs); if (options.blankImage && !$el.attr('src')) { $el.attr('src', options.blankImage); } elements.unshift($el); // push it in the first position as we iterate elements in reverse order } /** * Save visible viewport boundary to viewportXXX variables */ function calcViewport() { var scrollTop = $window.scrollTop(), scrollLeft = window.pageXOffset || 0, edgeX = options.edgeX, edgeY = options.edgeY; viewportTop = scrollTop - edgeY; viewportBottom = scrollTop + (window.innerHeight || $window.height()) + edgeY; viewportLeft = scrollLeft - edgeX; viewportRight = scrollLeft + (window.innerWidth || $window.width()) + edgeX; } /** * Load visible elements */ function checkLazyElements() { if (!elements.length) { return; } topLazy = Infinity; calcViewport(); var i = elements.length - 1, srcAttr = options.srcAttr; for (; i >= 0; i--) { var $el = elements[i], el = $el[0]; // remove items that are not in DOM if (!$.contains(document.body, el)) { elements.splice(i, 1); } else if (!options.visibleOnly || el.offsetWidth > 0 || el.offsetHeight > 0) { var offset = $el.offset(), elTop = offset.top, elLeft = offset.left; if ((elTop < viewportBottom) && (elTop + $el.height() > viewportTop) && (elLeft < viewportRight) && (elLeft + $el.width() > viewportLeft)) { var src = $el.attr(srcAttr); if (src) { $el.attr('src', src); } elements.splice(i, 1); } else { if (elTop < topLazy) { topLazy = elTop; } } } } } /** * Run check of lazy elements after timeout */ function timeoutLazyElements() { if (waitingMode > 1) { waitingMode = 1; checkLazyElements(); setTimeout(timeoutLazyElements, options.throttle); } else { waitingMode = 0; } } /** * Queue check of lazy elements because of event e * @param {Event} [e] */ function queueCheckLazyElements(e) { if (!elements.length) { return; } // fast check for scroll event without new visible elements if (e && e.type === 'scroll') { calcViewport(); if (topLazy >= viewportBottom) { return; } } if (!waitingMode) { setTimeout(timeoutLazyElements, 0); } waitingMode = 2; } /** * Initialize list of hidden elements */ function initLazyElements() { $(options.selector).each(addElement); queueCheckLazyElements(); } /** * Initialization */ $(document).ready(function () { $window .on(options.loadEvent, initLazyElements) .on(options.updateEvent, queueCheckLazyElements); initLazyElements(); // standard initialization }); })(window.jQuery || window.Zepto, window, document);
JavaScript
0.000001
@@ -279,115 +279,8 @@ ',%0D%0A - blankImage: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',%0D%0A @@ -1400,126 +1400,8 @@ %0D%0A%0D%0A - if (options.blankImage && !$el.attr('src')) %7B%0D%0A $el.attr('src', options.blankImage);%0D%0A %7D%0D%0A%0D%0A
bad79d1bb33e483b7cf166b3fd9c9c10598cd130
Remove unused height variable - closes #16
src/jquery.textarea_autosize.js
src/jquery.textarea_autosize.js
/*! * jQuery Textarea AutoSize plugin * Author: Javier Julio * Licensed under the MIT license */ ;(function ($, window, document, undefined) { var pluginName = "textareaAutoSize"; var pluginDataName = "plugin_" + pluginName; var containsText = function (value) { return (value.replace(/\s/g, '').length > 0); }; function Plugin(element, options) { this.element = element; this.$element = $(element); this.init(); } Plugin.prototype = { init: function() { var height = this.$element.outerHeight(); var diff = parseInt(this.$element.css('paddingBottom')) + parseInt(this.$element.css('paddingTop')) || 0; if (containsText(this.element.value)) { this.$element.height(this.element.scrollHeight - diff); } // keyup is required for IE to properly reset height when deleting text this.$element.on('input keyup', function(event) { var $window = $(window); var currentScrollPosition = $window.scrollTop(); $(this) .height(0) .height(this.scrollHeight - diff); $window.scrollTop(currentScrollPosition); }); } }; $.fn[pluginName] = function (options) { this.each(function() { if (!$.data(this, pluginDataName)) { $.data(this, pluginDataName, new Plugin(this, options)); } }); return this; }; })(jQuery, window, document);
JavaScript
0
@@ -494,56 +494,8 @@ ) %7B%0A - var height = this.$element.outerHeight();%0A
5e9e1a28b74ffc62583f31389324cf2294238b17
Update src/js/config/02.config.gapi.js
src/js/config/02.config.gapi.js
src/js/config/02.config.gapi.js
var OAUTH_CLIENT_ID = "776189517355-6bjjleaopdes0fe57f8gsf4i1ncgflpb.apps.googleusercontent.com"; var gaConfig = { views: [ //{ // 'name': 'T', // 'abbr': 'ts', // 'view': '14912375', // 'colors': { // 1: '#fff', // 2: '#1c5976' // } //}, { 'name': 'W', 'abbr': 'ws', 'view': '14554529', 'colors': { 1: '#000', 2: '#fc0' } }, { 'name': 'GE', 'abbr': 'ge', 'view': '172855204', 'colors': { 1: '#fff', 2: '#5CA1C4' } }, { 'name': 'ST', 'abbr': 'st', 'view': '2783821', 'colors': { 1: '#fff', 2: '#c26625' } }, { 'name': 'R', 'abbr': 'r', 'view': '11560419', 'colors': { 1: '#fff', 2: '#0057a3' } }, { 'name': 'UINT', 'abbr': 'uint', 'view': '63269926', 'colors': { 1: '#fff', 2: '#c00' } }, { 'name': 'UZA', 'abbr': 'uza', 'view': '74801518', 'colors': { 1: '#fff', 2: '#c00' } }, { 'name': 'UTH', 'abbr': 'uth', 'view': '74790785', 'colors': { 1: '#fff', 2: '#c00' } }, { 'name': 'RS', 'abbr': 'rs', 'view': '118702555', 'colors': { 1: '#fff', 2: '#a82081' } }, { 'name': 'VHN', 'abbr': 'vhn', 'view': '100568033', 'colors': { 1: '#fff', 2: '#919296' } }, { 'name': 'IV', 'abbr': 'iv', 'view': '125131939', 'colors': { 1: '#fff', 2: '#919296' } } ], reportRequests: [ { dateRanges: [ { startDate: '7daysAgo', endDate: 'today' } ], metrics: [ {expression: 'ga:sessions'}, {expression: 'ga:transactionRevenue'} ], dimensions: [ {name: "ga:deviceCategory"}, {name: "ga:browser"}, {name: "ga:browserVersion"} ] } ] };
JavaScript
0.000001
@@ -852,38 +852,42 @@ %7D%0A %7D,%0A +// %7B%0A +// 'name': 'UINT' @@ -884,32 +884,34 @@ e': 'UINT',%0A +// 'abbr': 'uint' @@ -908,32 +908,34 @@ r': 'uint',%0A +// 'view': '63269 @@ -940,24 +940,26 @@ 69926',%0A +// 'colors': @@ -956,32 +956,34 @@ 'colors': %7B%0A +// 1: '#fff',%0A @@ -977,32 +977,34 @@ 1: '#fff',%0A +// 2: '#c00'%0A @@ -1001,32 +1001,34 @@ '#c00'%0A +// %7D%0A %7D,%0A %7B%0A @@ -1011,37 +1011,43 @@ // %7D%0A +// %7D,%0A +// %7B%0A +// 'name': 'U @@ -1051,24 +1051,26 @@ 'UZA',%0A +// 'abbr': 'u @@ -1074,24 +1074,26 @@ 'uza',%0A +// 'view': '7 @@ -1102,24 +1102,26 @@ 01518',%0A +// 'colors': @@ -1118,32 +1118,34 @@ 'colors': %7B%0A +// 1: '#fff',%0A @@ -1139,32 +1139,34 @@ 1: '#fff',%0A +// 2: '#c00'%0A @@ -1163,32 +1163,34 @@ '#c00'%0A +// %7D%0A %7D,%0A %7B%0A @@ -1173,37 +1173,43 @@ // %7D%0A +// %7D,%0A +// %7B%0A +// 'name': 'U @@ -1213,24 +1213,26 @@ 'UTH',%0A +// 'abbr': 'u @@ -1236,24 +1236,26 @@ 'uth',%0A +// 'view': '7 @@ -1260,32 +1260,34 @@ '74790785',%0A +// 'colors': %7B%0A @@ -1280,32 +1280,34 @@ 'colors': %7B%0A +// 1: '#fff',%0A @@ -1301,32 +1301,34 @@ 1: '#fff',%0A +// 2: '#c00'%0A @@ -1325,32 +1325,34 @@ '#c00'%0A +// %7D%0A %7D,%0A %7B%0A @@ -1331,32 +1331,34 @@ '%0A // %7D%0A +// %7D,%0A %7B%0A '
58dcb70e4ff9866b4e289a083b129191d7b6c381
add load state assets to preloader
src/js/game/states/preloader.js
src/js/game/states/preloader.js
var preloader = {}; preloader.preload = function () { this.load.image('ground', 'images/ground.png'); this.game.load.image('starfield', 'images/starfield.png'); this.game.load.image('seat', 'images/Seat_Large_1.png'); this.game.load.image('shop1', 'images/Shop_Large_1.png'); this.game.load.image('shop2', 'images/Shop_Large_2.png'); this.game.load.image('box1', 'images/GUI_Box_1.png'); this.game.load.image('chatBox', 'images/Chat_phone_1.png'); this.game.load.image('rock1', 'images/Rock_Large_1.png'); this.game.load.image('rock2', 'images/Rock_Large_2.png'); this.game.load.image('drinkSmall', 'images/Drink_Small_1.png'); this.game.load.image('sakeSmall', 'images/Sake_Small_1.png'); this.game.load.image('sakeLarge', 'images/Sake_Large_1.png'); this.game.load.image('smallLeaf', 'images/Leaf_Small_1.png'); this.game.load.image('ship', 'images/tanukifly1.png'); this.game.load.image('tanuki2', 'images/tanukifly2.png'); // this.load.spritesheet('tanuki', 'images/tanukisheet.png', 115, 100, 2); // for splash state this.game.load.image('splash-1', 'images/splash/splash-main.png'); this.game.load.image('shop', 'images/splash/all-shops.png'); this.game.load.image('splash-text', 'images/splash/go-home-tanuki-text.png'); this.game.load.image('splash-phone', 'images/splash/phone.png'); this.game.load.image('splash-message-box', 'images/splash/phone-message.png'); }; // go to splash screen preloader.create = function () { this.game.state.start('splash'); }; module.exports = preloader;
JavaScript
0
@@ -252,32 +252,39 @@ shop1', 'images/ +splash/ Shop_Large_1.png @@ -327,16 +327,23 @@ 'images/ +splash/ Shop_Lar @@ -453,16 +453,23 @@ 'images/ +splash/ Chat_pho @@ -1439,16 +1439,232 @@ png');%0A%0A + // for load state%0A this.game.load.image('plaque', 'images/load/load-list.png');%0A this.game.load.image('checkmark', 'images/load/checkmark.png');%0A this.game.load.image('underline', 'images/load/underline.png');%0A%0A %7D;%0A%0A%0A// @@ -1741,22 +1741,20 @@ .start(' -splash +load ');%0A%7D;%0A%0A
6ec30c7ae811890aa512ecd49b5e29acd94d8411
Change forecast values
src/js/pages/ForecastWeather.js
src/js/pages/ForecastWeather.js
'use strict'; const template = require('../../views/pages/ForecastWeather.hbs'); const Button = require('../../js/components/Button'); class ForecastWeather { constructor(search) { this.container = document.createElement('div'); this.container.classList.add('forecast-weather-container'); this.render(); } render() { this.container.innerHTML = template(); this.button(); } button() { const button = new Button('Go to Current Weather'); this.container.appendChild(button.container); button.container.addEventListener('click', () => { this.hidden(); this.container.previousElementSibling.classList.add('show'); }); } show(data) { this.container.classList.add('show'); this.printWeather(data); } hidden() { this.container.classList.remove('show'); } //ToDo: Move this data to appropriate files. printWeather(data) { console.log(data); const forecastData = data.forecast.forecastday; console.log('forecastData ', forecastData); forecastData.forEach(days => { console.log(days.hour[0]); document.querySelector('.forecast-weather .content').innerHTML += ` <div class="hour"> <span class="city-name">${days.hour[0]}</span> </div> ` }); } } module.exports = ForecastWeather;
JavaScript
0.000001
@@ -1033,23 +1033,20 @@ og(days. -hour%5B0%5D +date );%0A%09%09%09do @@ -1172,15 +1172,239 @@ ays. -hour%5B0%5D +date%7D%3C/span%3E%0A%09%09%09%09%3Cspan class=%22city-name%22%3E$%7Bdata.location.name%7D%3C/span%3E%0A%09%09%09%09%3Cimg src=%22$%7Bdays.day.condition.icon%7D%22%3E%0A%09%09%09%09%3Cspan class=%22city-name%22%3E$%7Bdays.day.avgtemp_c + %22 %C2%B0C%22%7D%3C/span%3E%0A%09%09%09%09%3Cspan class=%22city-name%22%3E$%7Bdays.day.condition.text %7D%3C/s
ab87f48f1bc851323177459f26f6494a8be4b143
Bump dynamic-import package version before republishing.
packages/dynamic-import/package.js
packages/dynamic-import/package.js
Package.describe({ name: "dynamic-import", version: "0.4.0", summary: "Runtime support for Meteor 1.5 dynamic import(...) syntax", documentation: "README.md" }); Package.onUse(function (api) { // Do not allow this package to be used in pre-Meteor 1.5 apps. api.use("isobuild:dynamic-import@1.5.0"); api.use("modules"); api.use("promise"); api.use("http"); api.use("modern-browsers"); api.mainModule("client.js", "client"); api.mainModule("server.js", "server"); });
JavaScript
0
@@ -54,17 +54,17 @@ n: %220.4. -0 +1 %22,%0A sum
d7ebccf4ba6cc8489cceea71f5ea3c4d1b7db9c8
Update to better monitor the state of the async queue
dynamoDbQueueSource.js
dynamoDbQueueSource.js
'use strict'; var _ = require('lodash'); var AWS = require('aws-sdk'); var dynamoDb = new AWS.DynamoDB(); var dynamoDbQueueSource = { }; dynamoDbQueueSource._processResult = function(err, data, task) { // Did we have an error? If so, pass it through to the callback, indicate // that we should stop iterating, and return if (err) { task.error = err; task.callback(err); return; } // Push the items from the scan into the queue and update the total item count task.queue.push(data.Items); task.results.itemCount += data.Items.length; // Are we done? If so, trigger the callback for the scan and return if (!data.LastEvaluatedKey) { task.hasMoreItems = false; task.callback(null, task.results); return; } // If we have more rows to scan, repeat the scan with the new exclusive // start key task.options.ExclusiveStartKey = data.LastEvaluatedKey; setImmediate(task.executor); }; dynamoDbQueueSource._executeScanTask = function(scanTask) { dynamoDb.scan(scanTask.options, scanTask.processor); }; dynamoDbQueueSource._executeQueryTask = function(queryTask) { dynamoDb.query(queryTask.options, queryTask.processor); }; dynamoDbQueueSource._isRunning = function(scanTask) { return ( !scanTask.error && (scanTask.queue.length > 0 || scanTask.hasMoreItems) ); }; dynamoDbQueueSource._createTask = function(queue, options, callback, executor) { var task = { queue: queue, options: options, callback: callback, hasMoreItems: true, results: { itemCount: 0 } }; // The callback for scanToQueue is optional, but everything else is simpler // if we ensure that a function is always available as the callback, so we // just use the identity function from lodash if we didn't get a real // callback function if (!_.isFunction(task.callback)) { task.callback = _.identity; } task.processor = _.partialRight(dynamoDbQueueSource._processResult, task); task.executor = _.partialRight(executor, task); task.isRunning = _.partial(dynamoDbQueueSource._isRunning, task); return task; }; dynamoDbQueueSource.scanToQueue = function(queue, options, callback) { var scanTask = dynamoDbQueueSource._createTask( queue, options, callback, dynamoDbQueueSource._executeScanTask ); setImmediate(scanTask.executor); return scanTask; }; dynamoDbQueueSource.queryToQueue = function(queue, options, callback) { var queryTask = dynamoDbQueueSource._createTask( queue, options, callback, dynamoDbQueueSource._executeQueryTask ); setImmediate(queryTask.executor); return queryTask; }; module.exports = dynamoDbQueueSource;
JavaScript
0
@@ -1265,16 +1265,17 @@ &&%0A ( +! scanTask @@ -1285,18 +1285,14 @@ eue. -length %3E 0 +idle() %7C%7C
9f84fb4efddde82a3bde0eb156dca080f3773bd8
Fix exiting driverLauncher
src/driver-launcher.js
src/driver-launcher.js
var http = require('http'); var spawn = require('child_process').spawn; var url = require('url'); var lodash = require('lodash'); var DEFAULT_START_TIMEOUT_MS = 30 * 1000; var POLL_TIMEOUT = 100; var defaultOptions = { port: 0, hostname: 'localhost', args: [], path: '/', env: process.env, stdio: 'ignore', waitTimeout: DEFAULT_START_TIMEOUT_MS }; module.exports = function(executable, options) { var processOptions = lodash.merge({}, defaultOptions, options); return { _process: null, _getStatus: function(url, callback) { http.get(url, function(response) { callback(null, response.statusCode); }).on('error', function(error) { callback(error); }); }, _waitForServer: function(url, timeout, callback) { var start = Date.now(); var getStatus = this._getStatus.bind(this, url + '/status', onStatus); getStatus(); function onStatus(error, statusCode) { if (!error && statusCode > 199 && statusCode < 300) { callback(null, url); } else if (Date.now() - start > timeout) { callback(new Error('Timed out waiting for server with URL: ' + url)); } else { setTimeout(function() { getStatus(); }, POLL_TIMEOUT); } }; }, start: function(callback) { var exitFunc = function(error) { callback(new Error([ 'Failed starting process: "', (executable + processOptions.args.join(' ')), '"', error ? '\nError : ' + error.stack : '' ].join(''))); }; var serverUrl = url.format({ protocol: 'http', hostname: processOptions.hostname, port: processOptions.port, pathname: processOptions.path }); var process = this._process = spawn(executable, processOptions.args, { stdio: processOptions.stdio }); process.once('exit', exitFunc); process.once('error', exitFunc); this._waitForServer(serverUrl, processOptions.waitTimeout, callback); return this; }, stop: function(callback) { this._process.kill('SIGTERM'); callback(null); } }; };
JavaScript
0.000004
@@ -1461,16 +1461,22 @@ utable + + ' ' + process @@ -1789,25 +1789,30 @@ ;%0A var -p +childP rocess = thi @@ -1909,33 +1909,38 @@ %7D);%0A -p +childP rocess.once('exi @@ -1960,17 +1960,22 @@ ;%0A -p +childP rocess.o @@ -2064,24 +2064,187 @@ imeout, -callback +function(error, url) %7B%0A childProcess.removeListener('exit', exitFunc);%0A childProcess.removeListener('error', exitFunc);%0A callback(error, url);%0A %7D );%0A
9793be4f419caa7b47a39bd5f8adb0c13a19e6b8
remove merge conflict
src/larissa/redux/middleware.js
src/larissa/redux/middleware.js
import { CREATE_BLOCK, CREATE_BLOCK_WITH_CONNECTION, CREATE_PIPELINE, DELETE_NODE, RESET_PIPELINE, RUN_ERROR, RUN_PIPELINE, SET_BLOCK_OPTIONS, UPDATE_GRAPH, SET_CURRENT_PIPELINE } from './actions'; export const memoryMiddleware = env => store => { // Create root pipeline const rootPipeline = env.newPipeline(); let currentPipeline = rootPipeline; // Create dummy node on the pipeline const ten = rootPipeline.newNode('number', {value: 10}); const pIn = env.newPipeline(); const five = pIn.newNode('number', {value: 5}); const prod = pIn.newNode('product'); pIn.connect(five, prod); pIn.linkInput(prod.input(), 'number'); pIn.linkOutput(prod.output(), 'result'); rootPipeline.addNode(pIn); rootPipeline.connect(ten, pIn.input('number')); // Listen to status changes in the pipeline to dispatch actions rootPipeline.on('child-status', function () { store.dispatch(createUpdateGraphAction(rootPipeline)); }); rootPipeline.on('runError', function (err) { console.log(err); // eslint-disable-line no-console store.dispatch({ type: RUN_ERROR, payload: { message: err.message } }); }); // Update on initialization store.dispatch(createUpdateGraphAction(rootPipeline)); return next => action => { if (action.type.startsWith('@@larissa/')) { switch (action.type) { case CREATE_BLOCK: { currentPipeline.newNode(action.payload.type); return next(createUpdateGraphAction(currentPipeline)); } case CREATE_BLOCK_WITH_CONNECTION: { const nodeId = action.payload.node; const newNode = currentPipeline.newNode(action.payload.type); try { const node = currentPipeline.getNode(nodeId); if (node) { if (action.payload.portType === 'input') { currentPipeline.connect(newNode, node.input(action.payload.name)); } if (action.payload.portType === 'output') { currentPipeline.connect(node.output(action.payload.name), newNode); } } } catch (e) { // TODO: dispatch action to notify user of failure } return next(createUpdateGraphAction(currentPipeline)); } case SET_BLOCK_OPTIONS: { const node = currentPipeline.getNode(action.payload.id); if (node.kind !== 'block') throw new Error('Setting options on not-a-block'); node.setOptions(action.payload.options); // No need for dispatching. Listener will detect the reset of the Block return null; } case RUN_PIPELINE: { currentPipeline.run().catch((err) => { console.error(err); // eslint-disable-line no-console rootPipeline.run().catch((err) => { next({ type: RUN_ERROR, payload: { message: err.message } }); }); return null; }); break; } case RESET_PIPELINE: { currentPipeline.reset(); return null; } case CREATE_PIPELINE: { const newPipeline = env.newPipeline(); currentPipeline.addNode(newPipeline); return next(createUpdateGraphAction(currentPipeline)); } case UPDATE_GRAPH: // Just pass the action to the end user case RUN_ERROR: next(action); return null; case DELETE_NODE: currentPipeline.deleteNode(currentPipeline.getNode(action.payload)); next(action); return next(createUpdateGraphAction(currentPipeline)); case SET_CURRENT_PIPELINE: { const newCurrentPipeline = rootPipeline.findNode(action.payload.id); if (!newCurrentPipeline) { throw new Error(`Pipeline with id ${action.payload.id} was not found`); } if (newCurrentPipeline.kind !== 'pipeline') { throw new Error('Setting pipeline to be not-a-pipeline'); } currentPipeline = newCurrentPipeline; next(action); return next(createUpdateGraphAction(currentPipeline)); } default: { throw new Error(`Unexpected action: ${action.type}`); } } } return next(action); }; }; function createUpdateGraphAction(pipeline) { return { type: UPDATE_GRAPH, payload: stateFromPipeline(pipeline) }; } function stateFromPipeline(pipeline) { const state = { nodes: {}, graph: JSON.parse(pipeline.graph.toJSON()) }; for (let [id, vertex] of pipeline.graph.vertices()) { state.nodes[id] = vertex.toJSON(); } return state; }
JavaScript
0.000002
@@ -3252,72 +3252,8 @@ ole%0A - rootPipeline.run().catch((err) =%3E %7B%0A @@ -3279,20 +3279,16 @@ next(%7B%0A - @@ -3344,36 +3344,32 @@ - payload: %7B%0A @@ -3387,36 +3387,32 @@ - - message: err.mes @@ -3448,109 +3448,36 @@ - %7D%0A %7D);%0A %7D);%0A return null +%7D%0A %7D) ;%0A
7637d9a63f61f9736f719084eb72cba5ee51facf
update import in spec
test/messenger-wrapper.js
test/messenger-wrapper.js
import { expect } from 'chai'; import MessengerWrapper from '../messenger-wrapper'; describe('MessengerWrapper', () => { describe('new', () => { describe('with all attributes', () => { it('initializes correctly', () => { const wrapper = new MessengerWrapper({ verifyToken: 'verify_token', pageAccessToken: 'page_access_token' }); expect(wrapper).to.be.ok; }); }); describe('with one attribute missing', () => { it('throws an error', () => { expect(() => { new MessengerWrapper({ verifyToken: 'verify_token' }) }).to.throw(Error, 'VERIFY_TOKEN or PAGE_ACCESS_TOKEN are missing.'); }); }); }); });
JavaScript
0
@@ -58,16 +58,20 @@ rom '../ +lib/ messenge
2b5a66edcc329cab388fd269f4b452a5bc127823
Append text based on current_line number
main/static/js/javascript.js
main/static/js/javascript.js
//jQuery all client side $(document).ready(function(){ $('#txt').bind('keypress', function(e) { if(e.keyCode==13){ console.log('test'); $.getJSON('/check_code', { text : $('textarea#txt').val() }, function(data) { appendGutter(); $('#append_text').append("<h1>" + data + "</h1>"); return false; }); }; }); }); //Track number of rows. The number of the current row would be used to append to certain element. function appendGutter() { var textArea = document.getElementById("txt"); var arrayOfLines = textArea.value.split("\n"); var line_number = textArea.value.substr(0, textArea.selectionStart).split("\n").length; console.log(arrayOfLines[line_number-2]); console.log(line_number); }
JavaScript
0.00143
@@ -238,16 +238,31 @@ %0A%09%09 %09 +current_text = appendGu @@ -266,16 +266,20 @@ dGutter( +data );%0A%09%09 @@ -314,20 +314,28 @@ %3Ch1%3E%22 + -data +current_text + %22%3C/h1 @@ -515,16 +515,20 @@ dGutter( +data ) %7B%0A%09var @@ -544,37 +544,11 @@ = d -ocument.getElementById(%22txt%22) +ata ;%0A%09v @@ -574,22 +574,16 @@ extArea. -value. split(%22%5C @@ -623,14 +623,8 @@ rea. -value. subs @@ -678,28 +678,115 @@ th;%0A -console.log( +if (line_number==1)%7B%0A %09var current_text = arrayOfLines%5B0%5D;%0A %7D else %7B%0A %09var current_text = arrayOfL @@ -806,40 +806,39 @@ ber- -2%5D) +1%5D ;%0A -console.log(line_number); +%7D%0A return current_text %0A%7D
da91aa912e10460d61d93a20bb9a9fa261899034
Update jquery.qrcode.js
apps/huischeck/jquery.qrcode.js
apps/huischeck/jquery.qrcode.js
(function( $ ){ $.fn.qrcode = function(options) { // if options is string, if( typeof options === 'string' ){ options = { text: options }; } // set default values // typeNumber < 1 for automatic calculation options = $.extend( {}, { render : "canvas", width : 256, height : 256, typeNumber : -1, correctLevel : QRErrorCorrectLevel.H, background : "#ffffff", foreground : "#000000" }, options); var createCanvas = function(){ // create the qrcode itself var qrcode = new QRCode(options.typeNumber, options.correctLevel); qrcode.addData(options.text); qrcode.make(); // create canvas element var canvas = document.createElement('canvas'); canvas.width = options.width; canvas.height = options.height; var ctx = canvas.getContext('2d'); // compute tileW/tileH based on options.width/options.height var tileW = options.width / qrcode.getModuleCount(); var tileH = options.height / qrcode.getModuleCount(); // draw in the canvas for( var row = 0; row < qrcode.getModuleCount(); row++ ){ for( var col = 0; col < qrcode.getModuleCount(); col++ ){ ctx.fillStyle = qrcode.isDark(row, col) ? options.foreground : options.background; var w = (Math.ceil((col+1)*tileW) - Math.floor(col*tileW)); var h = (Math.ceil((row+1)*tileH) - Math.floor(row*tileH)); ctx.fillRect(Math.round(col*tileW),Math.round(row*tileH), w, h); } } // return just built canvas return canvas; } // from Jon-Carlos Rivera (https://github.com/imbcmdth) var createTable = function(){ // create the qrcode itself var qrcode = new QRCode(options.typeNumber, options.correctLevel); qrcode.addData(options.text); qrcode.make(); // create table element var $table = $('<table></table>') .css("width", options.width+"px") .css("height", options.height+"px") .css("border", "0px") .css("border-collapse", "collapse") .css('background-color', options.background); // compute tileS percentage var tileW = options.width / qrcode.getModuleCount(); var tileH = options.height / qrcode.getModuleCount(); // draw in the table for(var row = 0; row < qrcode.getModuleCount(); row++ ){ var $row = $('<tr></tr>').css('height', tileH+"px").appendTo($table); for(var col = 0; col < qrcode.getModuleCount(); col++ ){ $('<td></td>') .css('width', tileW+"px") .css('background-color', qrcode.isDark(row, col) ? options.foreground : options.background) .appendTo($row); } } // return just built canvas return $table; } return this.each(function(){ var element = options.render == "canvas" ? createCanvas() : createTable(); $(element).appendTo(this); }); }; })( jQuery );
JavaScript
0
@@ -275,27 +275,27 @@ %09%09%09width%09%09: -256 +180 ,%0A%09%09%09height%09 @@ -301,11 +301,11 @@ %09%09: -256 +180 ,%0A%09%09
9fc041823d09ecf16730ccc3e03ad0bf04d6a35a
fix for copy-pasta derp
deletefromcommenthistory.user.js
deletefromcommenthistory.user.js
// ==UserScript== // @name Delete comments from comment history // @version 0.2 // @author Undo // @description To delete stuff faster // @license GNU GPL v3 (http://www.gnu.org/copyleft/gpl.html) // @include *://*stackoverflow.com/admin/users/*/post-comments* // @include *://*superuser.com/admin/users/*/post-comments* // @include *://*serverfault.com/admin/users/*/post-comments* // @include *://*stackexchange.com/admin/users/*/post-comments* // @include *://discuss.area51.com/admin/users/*/post-comments* // ==/UserScript== function with_jquery(f) { var script = document.createElement("script"); script.type = "text/javascript"; script.textContent = "(" + f.toString() + ")(jQuery)"; document.body.appendChild(script); }; with_jquery(function($){ $('document').ready(function(){ $('.meta-row .creation-date').each( function(){ if ($($(".meta-row .creation-date")[0].closest('tr.meta-row')).hasClass("deleted-row") == false){ $(this).append($('<span class="lsep">|</span><a class="delete-comment" href="javascript:void(0)" title="Delete comment">(delete)</a>')); }else{ $(this).append($('<span class="lsep">|</span><a class="delete-comment" href="javascript:void(0)" title="Delete comment">(undelete)</a>')); }} ); $('.delete-comment').bind("click",function(){ var deleteButton = $(this) var commentid=$(this).closest('tr.meta-row').data('id'); console.log(commentid) var postid = $(this).closest('tr.meta-row').data('postid'); console.log(postid) if ($(this).closest('tr.meta-row').hasClass("deleted-row") == true){ var url = "/admin/posts/" + postid + "/comments/" + commentid + "/undelete" $(this).html("<strong>(working...)</strong>"); $.post(url, {'fkey':StackExchange.options.user.fkey, 'sendCommentBackInMessage':'true'}, function(data){ deleteButton.html("(delete)"); deleteButton.closest('tr.meta-row').removeClass('deleted-row') } ); }else{ var url = '/posts/comments/'+commentid+'/vote/10' $.post(url, {'fkey':StackExchange.options.user.fkey, 'sendCommentBackInMessage':'true'}, function(data){ console.log(data); if (data.Success == true) { deleteButton.html("(undelete)"); deleteButton.closest('tr.meta-row').addClass('deleted-row') } } ); $(this).html("<strong>(working...)</strong>"); } }); return false; }); });
JavaScript
0
@@ -866,40 +866,12 @@ ($( -$(%22.meta-row .creation-date%22)%5B0%5D +this .clo @@ -889,17 +889,16 @@ ta-row') -) .hasClas
7187de6d557613509af4c015a8b47bd88bab99b4
update docs
demo/demoPages/TimePickerPage.js
demo/demoPages/TimePickerPage.js
import React, { Component } from 'react'; import { injectIntl } from 'react-intl'; import { messages } from '../translations/defaultMessages'; import { TimePicker, Select } from '../../index'; class TimePickerPage extends Component { constructor(props){ super(props); this.state = { timepickerValue1 : null, timepickerValue2 : null, timepickerValue3 : null }; } render() { const { intl } = this.props; const { inputState, timepickerValue1, timepickerValue2, timepickerValue3 } = this.state; // ======================Internationalization Example========================= // intl prop is injected by the injectIntl() at the bottom of the page... // Provider Context wraps the root element in demo.js. // do the intl string replacement... const text = { textInputInfoMessage : intl.formatMessage(messages.textInputInfoMessage), textInputErrorMessage : intl.formatMessage(messages.textInputErrorMessage) }; return ( <div className="displaySection"> <h1><a href="http://pearson-higher-ed.github.io/design/c/time-picker/v1.0.0">TimePicker - current design (v1.0.0)</a></h1> <div className="elementContainer"> <div className="code"> <h2>TimePicker:</h2> <h3>Props:</h3> <ul> <li>className:String === "styles to pass to datepicker"</li> <li>id:String === "A unique name for the datepicker"</li> <li>twentyFourHour:Boolean === "render timepicker in 24 hour format"</li> <li>dateFormat:String === "format for date/time entry"</li> <li>inputState:String === "styles for input state, one of 'error','disabled','readOnly','default'"</li> <li>labelText:String === "unique lable for the input field"</li> <li>timepickerValue:Date/Time === "value to be displayed by the datepicker/timepicker"</li> <li>changeHandler:Function === "function to pass values on change"</li> <li>infoMessage:String === "an optional info message displayed below the input"</li> <li>errorMessage:String === "an optional error message displayed below the input"</li> </ul> <h3>Configure Props:</h3> <Select id="select" changeHandler={e => this.setState({inputState:`${e.target.value}`}) } selectedOption={inputState} labelText="Select An inputState:" options={["default", "error", "readOnly", "disabled"]} /> </div> <h2>TimePicker (basic time): </h2> <TimePicker disableLabel id = "someGiantId1" timeFormat = "hh:mm" inputState = {inputState} labelText = "Select time" timePickerValue = {timepickerValue1} changeHandler = {e => this.setState({timepickerValue1})} infoMessage = {text.textInputInfoMessage} errorMessage = {text.textInputErrorMessage} /> <p className="code">{`<TimePicker id = "someGiantId" timeFormat = "hh:mm" inputState = "default" labelText = "Select time" timepickerValue = {this.state.timepickerValue3} changeHandler = {() => console.log("TimePicker-(basic)-changed!!")} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p> <h2>TimePicker (basic time range): </h2> <TimePicker id = "someGiantId2" timeFormat = "hh:mm" inputState = {inputState} labelText = "Select time" timePickerValue = {timepickerValue2} changeHandler = {e => this.setState({timepickerValue2})} infoMessage = {text.textInputInfoMessage} errorMessage = {text.textInputErrorMessage} /> <TimePicker id = "someGiantId3" timeFormat = "hh:mm" inputState = {inputState} labelText = "Select time" timePickerValue = {timepickerValue3} changeHandler = {e => this.setState({timepickerValue3})} infoMessage = {text.textInputInfoMessage} errorMessage = {text.textInputErrorMessage} /> <p className="code">{`<TimePicker fancy = {true} id = "someGiantId" dateFormat = "hh:mm" inputState = "default" labelText = "Select time" datepickerValue = {this.state.datepickerValue4} changeHandler = {() => console.log("TimePicker-(basic)-changed!!")} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p> </div> </div> ) } } export default injectIntl(TimePickerPage);
JavaScript
0.000874
@@ -2235,32 +2235,209 @@ the input%22%3C/li%3E%0A + %3Cli%3EdisableLabel:Boolean === %22Allows visually disabling of the label. Text must still be passed to the labelText even if this is present for a11y purposes.%22%3C/li%3E%0A %3C/ul @@ -2790,33 +2790,8 @@ ker%0A - disableLabel%0A
e1b63c5665941ae46ff7a0330c76c3dcd3a9807e
Update join.js
src/expression/join.js
src/expression/join.js
import { isString } from 'lodash' import Expression from './base' import Table from './table' /** * @class JoinExpression */ export default class Join extends Expression { /** * * @param {String|Table} table * @param {String} type * @param {Criteria} crirteria * @constructor */ constructor(table, type = 'inner', criteria = null) { super() if ( isString(table) ) table = new Table(table) if (! (table instanceof Table) ) throw new TypeError("Invalid join table name") // TODO ensure the criteria this.type = type this.table = table this.criteria = criteria } /** * * @param {Compiler} compiler * @return string */ compile(compiler) { var sql = this.type +' join '+ this.table.compile(compiler) if ( this.criteria ) sql += ' on ' + this.criteria.compile(compiler) return sql } /** * * @param {Any} expr * @return boolean */ isEqual(expr) { return super.isEqual() || ( expr instanceof Join && expr.type === this.type && this.table.isEqual(expr.table) ) } }
JavaScript
0.000078
@@ -63,36 +63,8 @@ ase' -%0Aimport Table from './table' %0A%0A/* @@ -430,21 +430,26 @@ tanceof -Table +Expression ) )%0A @@ -1113,8 +1113,9 @@ %7D%0A %0A%7D +%0A
b2abed41099839cdee85514f381f6cdfa0c3095c
fix filter
src/filter/is-empty.js
src/filter/is-empty.js
/** * @ngdoc filter * @name removeSpaces * @kind function * * @description * remove spaces from string, replace with "-" or given argument */ angular.module('is-empty', []) .filter('isEmpty', [function () { } ]);
JavaScript
0.000151
@@ -195,17 +195,16 @@ Empty', -%5B function @@ -213,15 +213,154 @@ ) %7B%0A -%0A + return function(collection) %7B%0A return (isObject(collection)) ?%0A !toArray(collection).length :%0A !collection.length;%0A %7D%0A -%5D +%7D );%0A
b04656ecfddfcdd58ae01857cc36a8317b17cc8c
fix issue with captions not clearing out correctly
lib/components/FigCaption.js
lib/components/FigCaption.js
var React = require('react/addons'); var PureRenderMixin = React.addons.PureRenderMixin; var cx = require('classnames'); require('../stylesheets/FigCaption.scss'); var KEY_CODES = { 'return': 13, 'bspace': 8 }; var { string } = React.PropTypes; var FigCaption = React.createClass({ mixins: [PureRenderMixin], propTypes: { text: string }, getInitialState() { return { empty: this.props.text.length === 0, } }, // handle clicking out without setting a caption componentDidMount() { document.addEventListener("click", this.handleDocumentClick); }, componentWillUnmount() { document.removeEventListener("click", this.handleDocumentClick); }, handleDocumentClick(e) { var caption = React.findDOMNode(this.refs.figCaption); if (!e.target.classList.contains('ic-Editor-FigCaption__placeholder') && e.target !== caption && !caption.contains(e.target)) { this.setState({empty: this.props.text.trim().length === 0}); } }, handleClickPlaceholder(e) { if (this.state.empty) { this.setState({empty: false}); } }, // don't allow us to move outside of caption text handleKeyDown(e) { this.handleClickPlaceholder(e); var sel = document.getSelection(); var beg = sel.anchorOffset === 0 && sel.type === 'Caret'; var noBspace = beg && e.keyCode === KEY_CODES.bspace; if (noBspace || e.keyCode === KEY_CODES.return) { e.preventDefault(); e.stopPropagation(); } }, classNames() { return cx({ 'ic-Editor-FigCaption': true, 'ic-Editor-FigCaption--empty': this.props.text.trim().length === 0 }); }, render() { var placeholder = "Type caption for image (optional)"; return ( <figcaption ref="figCaption" contentEditable="true" className={this.classNames()} onKeyDown={this.handleKeyDown} tabIndex="-1" > {!this.state.empty && (this.props.text.length > 0 ? this.props.text : "\u00a0") } {this.state.empty && <span className="ic-Editor-FigCaption__placeholder" onClick={this.handleClickPlaceholder} data-placeholder={placeholder}> {placeholder} </span> } </figcaption> ); } }); module.exports = FigCaption;
JavaScript
0.000001
@@ -423,18 +423,17 @@ th === 0 -, %0A + %7D%0A @@ -756,20 +756,17 @@ is.refs. -figC +c aption); @@ -986,16 +986,49 @@ %7D%0A %7D,%0A%0A +%0A // clear out placeholder text%0A handle @@ -1044,17 +1044,16 @@ eholder( -e ) %7B%0A @@ -1121,24 +1121,281 @@ %7D%0A %7D,%0A%0A + // don't save placeholder text%0A handleKeyUp(e) %7B%0A var caption = React.findDOMNode(this.refs.caption);%0A var pholder = caption.getAttribute('data-placeholder');%0A if (pholder === caption.textContent.trim()) %7B%0A e.stopPropagation();%0A %7D%0A %7D,%0A%0A // don't a @@ -1487,17 +1487,16 @@ eholder( -e );%0A%0A @@ -2047,12 +2047,9 @@ ef=%22 -figC +c apti @@ -2160,16 +2160,136 @@ eyDown%7D%0A + onKeyUp=%7Bthis.handleKeyUp%7D%0A onClick=%7Bthis.handleClickPlaceholder%7D%0A data-placeholder=%7Bplaceholder%7D%0A @@ -2463,28 +2463,16 @@ %3Cspan -%0A classNa @@ -2513,101 +2513,8 @@ der%22 -%0A onClick=%7Bthis.handleClickPlaceholder%7D%0A data-placeholder=%7Bplaceholder%7D %3E%0A
8db36271c0a957441bc56dcb47c38910cb638159
Update crooz.js
public/js/crooz.js
public/js/crooz.js
"use strict"; var socket; var mapper; function main() { socket = io(); mapper = Mapper.init(document.getElementById('mapCard')); socket.on('connected', function (users) { socket.emit('subscribe', users[0]); }); socket.on('newPacket', function (packet) { mapper.addPackets([packet]); mapper.render(); var car = mapper.car; document.getElementById('songCard').innerText = car.song; document.getElementById('moodCard').innerText = Object.keys(car.mood).reduce( function(a, b) { return car.mood[a] > car.mood[b] ? a : b } ); }); }
JavaScript
0
@@ -287,34 +287,101 @@ -mapper.addPackets(%5Bpacket%5D +console.log(packet);%0A mapper.addPackets(%5Bpacket%5D);%0A console.log(mapper._packets );%0A
9743d2f1da8f4e52c0e952d8a98e6641bc0dacc0
add missing style dimension
src/containers/AlbumView.js
src/containers/AlbumView.js
import React, {PropTypes, Component} from 'react'; import { connect } from 'react-redux'; import { addToPlaylist } from '../actions/playlistActions'; import { getAlbum, getAlbumInfo } from '../reducers'; import GlyphIcon from '../components/GlyphIcon'; import SplitButton from '../components/SplitButton'; import { sanitizeHtml, getLastFmThumbnail, getCoverUrl, LASTFM_IMG_SIZE_XLARGE } from '../components/utils'; function PlusIcon() { return <GlyphIcon iconName='share-alt'/>; } function Song({index, title, addAlbumSongToPlaylist}){ return ( <div> <SplitButton size="extra-small" defaultLabel="" defaultIcon={<PlusIcon/>} defaultOnClick={() => addAlbumSongToPlaylist(index, false)} actions={ [ { label: 'add song to top of playlist', onClick: () => addAlbumSongToPlaylist(index, true)}, { label: 'add songs to end of playlist', onClick: () => addAlbumSongToPlaylist(index, false)} ] } /> &nbsp;&nbsp; {title} </div> ); } const AlbumView = ({album, lastFmInfo, addToPlaylist}) => { console.log('AlbumView.render() album=%o, lastFmInfo=%o', album, lastFmInfo); function addAlbumSongToPlaylist(index, top=false) { let songs; if(index === null) { songs = album.songs.map(s => ({song: s.title, url: s.mp3 })); } else { const song = album.songs[index]; songs = [{ song: song.title, url: song.mp3}]; } addToPlaylist(album.artist, album.album, songs, top); } function renderSongs () { if(album.songs) { const splitButtonProps = { actions: [ {label: 'add all songs to top of playlist', onClick: () => addAlbumSongToPlaylist(null, true)}, {label: 'add all songs to end of playlist', onClick: () => addAlbumSongToPlaylist(null, false)} ], defaultLabel: 'Add album to playlist', defaultIcon: <PlusIcon/>, defaultOnClick: () => addAlbumSongToPlaylist(null, false) }; return ( <div> <h4>Songs: <span className="pull-right"> <SplitButton {...splitButtonProps} size="extra-small"/> </span> </h4> { album.songs.map((s, i) => ( <Song index={i} key={i} track={s.track} title={s.title} addAlbumSongToPlaylist={addAlbumSongToPlaylist}/> )) } </div> ); } } const renderThumbnail = () => { const url = getLastFmThumbnail(lastFmInfo, LASTFM_IMG_SIZE_XLARGE) || getCoverUrl(album); if(url) { return ( <div> <img src={url} className="img-responsiv img-rounded" style={{maxWidth: '300', maxHeight: 'auto'}}/> </div> ); } }; const renderWiki = () => { const summary = lastFmInfo && lastFmInfo.wiki && lastFmInfo.wiki.summary; if(summary) { return <div dangerouslySetInnerHTML={sanitizeHtml(summary)}/>; } }; return ( <div className="panel panel-default"> <div className="panel-heading"> <h3>Album: { album.album }</h3> {renderThumbnail()} </div> <div className="panel-body"> { renderWiki() } { renderSongs() } </div> </div> ); }; AlbumView.propTypes = { album: PropTypes.shape({ artist: PropTypes.string, album: PropTypes.string, songs: PropTypes.arrayOf(PropTypes.object) }), lastFmInfo: PropTypes.shape({ name: PropTypes.string, artist: PropTypes.string, wiki: PropTypes.object }), addToPlaylist: PropTypes.func.isRequired }; function mapStateToProps(state) { const {selection} = state; const selectedArtist = selection.artist || {}; const selectedAlbum = selection.album || {}; const album = getAlbum(state, selectedArtist.index, selectedAlbum.index) || {}; return { album, lastFmInfo: getAlbumInfo(state, album.artist, album.album) }; } export default connect(mapStateToProps, { addToPlaylist })(AlbumView);
JavaScript
0.000001
@@ -3212,16 +3212,18 @@ th: '300 +px ', maxHe
b3fc638f04cf21384a91859cea726cb44494580d
Reset first test scene to tilemap
src/game/boot/index.js
src/game/boot/index.js
import * as v from 'engine'; import data from './data.json'; // Which test to run after resources load import AnimatedSpirteTest from 'game/test/animated-sprite'; import AnimationTest from 'game/test/animation'; import InputTest from 'game/test/input'; import PhysicsTest from 'game/test/physics'; import TilemapTest from 'game/test/tilemap'; import SoundTest from 'game/test/sound'; import CoaTest from 'game/test/coa'; const FirstScene = CoaTest; export default class Boot extends v.Node2D { static instance() { const width = v.scene_tree.viewport_rect.size.x; const height = v.scene_tree.viewport_rect.size.y; const bar_width = Math.floor(width * 0.5); const bar_height = Math.floor(bar_width * 0.075); data.children[0].width = data.children[1].width = bar_width; data.children[0].height = data.children[1].height = bar_height; data.children[0].x = data.children[1].x = Math.floor((width - bar_width) * 0.5); data.children[0].y = data.children[1].y = Math.floor((height - bar_height) * 0.5); return v.assemble_scene(new Boot(), data); } _enter_tree() { let progress_bind = undefined; const bar = this.get_node('bar'); bar.scale.x = 0; const load_progress = () => { bar.scale.x = v.loader.progress * 0.01; }; const load_complete = () => { bar.scale.x = 1; if (progress_bind) { progress_bind.detach(); } v.scene_tree.change_scene_to(FirstScene); } if (v.loader._queue._tasks.length > 0) { progress_bind = v.loader.onProgress.add(load_progress); v.loader.load(load_complete); } else { load_complete(); } } _ready() {} _process(delta) {} _exit_tree() {} }
JavaScript
0
@@ -437,19 +437,23 @@ Scene = -Coa +Tilemap Test;%0A%0A%0A
786c17fa853e5fb4ddc8cf564bc2afa4c5b24fb2
Outputting giant list. om nom nom.
public/js/index.js
public/js/index.js
// When the DOM is ready $(function () { // // Create our List // var bookmarkList = document.getElementById('bookmark-list'), // options = { // valueNames: ['description', 'uri'], // item: 'bookmark-template' // }, // list = new List(bookmarkList, options); // // When the list is updated // list.on('updated', function () { // // Iterate over each of the li's // $(bookmarkList).find('li > a').each(function () { // // Set the href to the innerHTML // this.setAttribute('href', this.innerHTML); // }); // }); // Grab our template var template = $('#bookmark-template').html(); // Mock bookmarks var bookmarks = [ { "title": "fxn/tkn - Terminal keynote presentation", "dateAdded": 1349313664591754, "lastModified": 1349313676308463, "description": "tkn - Terminal Keynote - A hack for terminal-based talks", "uri": "https://github.com/fxn/tkn" }, { "title": "pedalboard.js - Open-source JavaScript framework for developing audio effects", "dateAdded": 1349417966733927, "lastModified": 1349417969037920, "description": "pedalboard.js - Open-source JavaScript framework for developing audio e", "uri": "http://dashersw.github.com/pedalboard.js/demo/" } ]; // Iterate over the bookmarks var bookmarkHtmlArr = bookmarks.map(function (bookmark) { var html = templatez(template, bookmark); return html; }), bookmarkHtml = bookmarkHtmlArr.join(''); // Append the content to our table var bookmarkList = document.getElementById('bookmark-list'); bookmarkList.innerHTML = bookmarkHtml; // Performify the list var options = { valueNames: ['description', 'uri'] }, list = new List('bookmark-list-container', options); // // Load in our bookmarks // $.getJSON('bookmarks.min.json', function (bookmarks, success, res) { // bookmarks.forEach(function (bookmark) { // list.add(bookmark); // }); // }); });
JavaScript
0.999999
@@ -651,16 +651,119 @@ );%0A%0A // + Load in our bookmarks%0A $.getJSON('bookmarks.min.json', function (bookmarks, success, res) %7B%0A // // Mock bo @@ -763,32 +763,37 @@ Mock bookmarks%0A + // var bookmarks = @@ -796,16 +796,21 @@ ks = %5B%0A + // %7B%0A @@ -802,36 +802,41 @@ %0A // %7B%0A +// + %22title%22: %22fxn/tk @@ -868,24 +868,29 @@ entation%22,%0A + // %22date @@ -916,16 +916,21 @@ 91754,%0A + // %22 @@ -963,16 +963,21 @@ 08463,%0A + // %22 @@ -1047,24 +1047,29 @@ ed talks%22,%0A + // %22uri%22 @@ -1100,16 +1100,21 @@ n/tkn%22%0A + // %7D,%0A @@ -1115,19 +1115,29 @@ %7D,%0A -%7B%0A +// %7B%0A // %22 @@ -1222,24 +1222,29 @@ effects%22,%0A + // %22date @@ -1273,20 +1273,25 @@ 27,%0A +// + %22lastMod @@ -1319,21 +1319,26 @@ 920,%0A + // + %22descrip @@ -1420,16 +1420,21 @@ io e%22,%0A + // %22 @@ -1493,19 +1493,31 @@ /%22%0A + // %7D%0A + // %5D;%0A%0A + // @@ -1544,16 +1544,18 @@ okmarks%0A + var bo @@ -1610,24 +1610,26 @@ ) %7B%0A + var html = t @@ -1658,16 +1658,18 @@ kmark);%0A + @@ -1691,12 +1691,16 @@ + %7D),%0A + @@ -1739,24 +1739,26 @@ .join('');%0A%0A + // Append @@ -1782,16 +1782,18 @@ r table%0A + var bo @@ -1847,16 +1847,18 @@ list');%0A + bookma @@ -1891,16 +1891,18 @@ kHtml;%0A%0A + // Per @@ -1918,16 +1918,18 @@ he list%0A + var op @@ -1938,16 +1938,18 @@ ons = %7B%0A + @@ -1985,24 +1985,26 @@ uri'%5D%0A + %7D,%0A lis @@ -1996,24 +1996,26 @@ %7D,%0A + + list = new L @@ -2059,204 +2059,9 @@ s);%0A -%0A // // Load in our bookmarks%0A // $.getJSON('bookmarks.min.json', function (bookmarks, success, res) %7B%0A // bookmarks.forEach(function (bookmark) %7B%0A // list.add(bookmark);%0A // %7D);%0A // + %7D);
b33426ac3d4856bfea177d4a84add4ab96ab2fe9
properly match mail.google.com
chrome/background.js
chrome/background.js
/* Detect GMail's URL */ chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { console.log(changeInfo.status); if (changeInfo.status === "complete") { checkForValidUrl(tab); } }); chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInfo) { chrome.tabs.getSelected(null, function(tab) { //checkForValidUrl(tab); }); }); /* Manage storage between ext & content script */ chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { // local storage request if (request.storage) { if (typeof request.value !== 'undefined') { localStorage[request.storage] = request.value; console.log(localStorage); } sendResponse({storage: localStorage[request.storage]}); } else { sendResponse({}); } }); function checkForValidUrl(tab) { if (tab.url.indexOf('/mail.google.com/') >= 0) { chrome.pageAction.show(tab.id); console.log(tab.url); chrome.tabs.sendMessage( //Selected tab id tab.id, //Params inside a object data {message: "initialize"}, //Optional callback function function(response) { //console.log(response); //update panel status //app.tabs[tab.id].panel.visible = response.status; //updateIconStatus(tab.id) } ); } }
JavaScript
0.999053
@@ -899,16 +899,23 @@ ndexOf(' +https:/ /mail.go @@ -930,9 +930,9 @@ /') -%3E += = 0)
5f748e85153cee7787aba401e45b28e28242872d
test update script
public/js/robot.js
public/js/robot.js
var Robot = { timer : null, init : function() { $(document).ready(this.handleDocumentReady.bind(this)); }, handleDocumentReady : function() { this.update(); }, update : function() { $.get('/robot/configuration', this.handleUpdateSuccess.bind(this)).fail(this.handleUpdateFail.bind(this)); }, handleUpdateSuccess : function(data) { $('.header-nav .navbar-brand span').attr('class', 'glyphicon glyphicon-flash'); setTimeout(this.update.bind(this), 200); }, handleUpdateFail : function(data) { $('.header-nav .navbar-brand span').attr('class', 'glyphicon glyphicon-repeat'); console.log(data); setTimeout(this.update.bind(this), 200); } }; Robot.init();
JavaScript
0.000001
@@ -389,33 +389,33 @@ ) %7B%0A%0A $(' -. +# header-nav .navb @@ -585,17 +585,17 @@ $(' -. +# header-n
631dd4c64586c3a3c5c8a964ccb9ede666755571
Fix spotify connector
src/connectors/spotify.js
src/connectors/spotify.js
'use strict'; Connector.playerSelector = '.Root__now-playing-bar'; Connector.artistSelector = '.track-info__artists a'; Connector.trackSelector = '.Root__now-playing-bar .track-info__name a'; Connector.trackArtSelector = '.now-playing__cover-art .cover-art-image-loaded'; Connector.playButtonSelector = '.control-button[class*="spoticon-play-"]'; Connector.currentTimeSelector = '.Root__now-playing-bar .playback-bar__progress-time:first-child'; Connector.durationSelector = '.Root__now-playing-bar .playback-bar__progress-time:last-child'; Connector.applyFilter(MetadataFilter.getSpotifyFilter()); Connector.isScrobblingAllowed = () => !isAdPlaying(); Connector.isPodcast = () => artistUrlIncludes('/show/'); /* * When ad is playing, artist URL is like "https://shrt.spotify.com/XXX", * otherwise URL leads to: * a) an artist page https://open.spotify.com/artist/YYY; * b) a podcast page https://open.spotify.com/show/ZZZ. */ function isAdPlaying() { return artistUrlIncludes('shrt.spotify.com'); } function artistUrlIncludes(str) { const artistUrl = $(Connector.artistSelector).attr('href'); return artistUrl && artistUrl.includes(str); }
JavaScript
0
@@ -4,24 +4,132 @@ e strict';%0A%0A +const adUrls = %5B%0A%09'utm_source=display',%0A%09'ad.doubleclick.net',%0A%09'spotify:playlist',%0A%09'shrt.spotify.com'%0A%5D;%0A%0A Connector.pl @@ -826,264 +826,108 @@ );%0A%0A -/*%0A * When ad is playing, artist URL is like %22https://shrt.spotify.com/XXX%22,%0A * otherwise URL leads to:%0A * a) an artist page https://open.spotify.com/artist/YYY;%0A * b) a podcast page https://open.spotify.com/show/ZZZ.%0A */%0A%0Afunction isAdPlaying( +function isAdPlaying() %7B%0A%09for (const adUrl of adUrls) %7B%0A%09%09if (artistUrlIncludes(adUrl) ) %7B%0A +%09%09 %09return arti @@ -926,45 +926,35 @@ urn -artistUrlIncludes('shrt.spotify.com') +true;%0A%09%09%7D%0A%09%7D%0A%0A%09return false ;%0A%7D%0A
901581d8180e4e78f2682c50ec9f79657a0ae90c
Update youtube connector
src/connectors/youtube.js
src/connectors/youtube.js
'use strict'; const CATEGORY_MUSIC = '/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ'; const CATEGORY_ENTERTAINMENT = '/channel/UCi-g4cjqGV7jvU8aeSuj0jQ'; const CATEGORY_PENDING = 'YT_DUMMY_CATEGORY_PENDING'; /** * Array of categories allowed to be scrobbled. * @type {Array} */ let allowedCategories = []; /** * "Video Id=Category" map. * @type {Map} */ let categoryCache = new Map(); /** * CSS selector of video element. It's common for both players. * @type {String} */ const videoSelector = '.html5-main-video'; readConnectorOptions(); setupMutationObserver(); Connector.getArtistTrack = () => { const videoTitle = $('.html5-video-player .ytp-title-link').first().text(); const byLineMatch = $('#meta-contents #owner-name a').text().match(/(.+) - Topic/); if (byLineMatch) { return { artist: byLineMatch[1], track: videoTitle }; } let { artist, track } = Util.processYoutubeVideoTitle(videoTitle); if (!artist) { artist = $('#meta-contents #owner-name').text(); } return { artist, track }; }; /* * Because player can be still present in the page, we need to detect * that it's invisible and don't return current time. Otherwise resulting * state may not be considered empty. */ Connector.getCurrentTime = () => { return $(videoSelector).prop('currentTime'); }; Connector.getDuration = () => { return $(videoSelector).prop('duration'); }; Connector.isPlaying = () => { return $('.html5-video-player').hasClass('playing-mode'); }; Connector.getUniqueID = () => { /* * Youtube doesn't update video title immediately in fullscreen mode. * We don't return video ID until video title is shown. */ if (Connector.isFullscreenMode()) { let videoTitle = $('.html5-video-player.playing-mode .ytp-title-link').text(); if (!videoTitle) { return null; } } let videoId = $('ytd-watch-flexy').attr('video-id'); if (!videoId) { let videoUrl = $('.html5-video-player.playing-mode .ytp-title-link').attr('href'); videoId = Util.getYoutubeVideoIdFromUrl(videoUrl); } return videoId; }; Connector.isScrobblingAllowed = () => { if ($('.videoAdUi').length > 0) { return false; } // FIXME: Workaround to prevent scrobbling the vidio opened in a background tab. if (Connector.getCurrentTime() < 1) { return false; } if (allowedCategories.length === 0) { return true; } let videoCategory = getVideoCategory(Connector.getUniqueID()); if (videoCategory !== null) { return allowedCategories.includes(videoCategory); } return false; }; Connector.applyFilter(MetadataFilter.getYoutubeFilter()); Connector.isFullscreenMode = () => { return $('.html5-video-player').hasClass('ytp-fullscreen'); }; /** * Get video category. * @param {String} videoId Video ID * @return {String} Video category */ function getVideoCategory(videoId) { if (videoId === null) { return null; } if (!categoryCache.has(videoId)) { /* * Add dummy category for videoId to prevent * fetching category multiple times. */ categoryCache.set(videoId, CATEGORY_PENDING); fetchCategoryId(videoId).then((category) => { if (category === null) { Util.debugLog(`Failed to resolve category for ${videoId}`, 'warn'); } categoryCache.set(videoId, category); }); return null; } return categoryCache.get(videoId); } async function fetchCategoryId() { await fillMoreSection(); return $('.ytd-metadata-row-renderer .yt-formatted-string[href^="/channel/"]').attr('href'); } async function fillMoreSection() { function waitForClick(ms = 0) { return new Promise((resolve) => setTimeout(resolve, ms)); } const ytShowLessText = $('yt-formatted-string.less-button').text(); const ytShowMoreText = $('yt-formatted-string.more-button').text(); // Apply global style to prevent "More/Less" button flickering. $('yt-formatted-string.less-button').text(ytShowMoreText); let styleTag = $(` <style id="tmp-style"> ytd-metadata-row-container-renderer { visibility: hidden; } ytd-metadata-row-container-renderer #collapsible { height: 0; } ytd-expander > #content.ytd-expander { overflow: hidden; max-height: var(--ytd-expander-collapsed-height); } yt-formatted-string.less-button { margin-top: 0 !important; } </style> `); $('html > head').append(styleTag); // Open "More" section. $('yt-formatted-string.more-button').click(); await waitForClick(); // Close "More" section. $('yt-formatted-string.less-button').click(); // Remove global style. $('yt-formatted-string.less-button').text(ytShowLessText); $('#tmp-style').remove(); } function setupMutationObserver() { let isEventListenerSetUp = false; function onMutation() { let videoElement = $(videoSelector); if (videoElement.length > 0) { if (!videoElement.is(':visible')) { Connector.resetState(); return; } if (isEventListenerSetUp) { return; } videoElement.on('timeupdate', Connector.onStateChanged); isEventListenerSetUp = true; Util.debugLog('Setup "timeupdate" event listener'); } else { Connector.resetState(); isEventListenerSetUp = false; Util.debugLog('Video element is missing', 'warn'); } } let observer = new MutationObserver(Util.throttle(onMutation, 500)); observer.observe(document, { subtree: true, childList: true, attributes: false, characterData: false }); } /** * Asynchronously read connector options. */ async function readConnectorOptions() { if (await Util.getOption('YouTube', 'scrobbleMusicOnly')) { allowedCategories.push(CATEGORY_MUSIC); } if (await Util.getOption('YouTube', 'scrobbleEntertainmentOnly')) { allowedCategories.push(CATEGORY_ENTERTAINMENT); } }
JavaScript
0
@@ -680,27 +680,25 @@ %0A%09const -byLineMatch +ownerName = $('#m @@ -732,16 +732,49 @@ ).text() +;%0A%0A%09const byLineMatch = ownerName .match(/ @@ -968,46 +968,17 @@ t = -$('#meta-contents # owner --n +N ame -').text() ;%0A%09%7D