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
031d6c10db031735a2576c9b9bcc0023198dd497
fix pointerLock error on iOS
packages/core/input/GestureObserver.js
packages/core/input/GestureObserver.js
import Vector2 from '../math/Vector2.js'; class GestureObserver { /** * @typedef Gesture * @property {HTMLElement} target - The target DOM Element * @property {number} movementX - Movement on the X axis * @property {number} movementY - Movement on the Y axis * @property {number} movementScale - Pinch-zoom movement * @property {number} movementRotation - Angular movement in radians * @property {boolean} isSwipe - Is the gesture a swipe */ /** * @callback GestureObserverCallback * @param {Gesture} gesture - Current gesture changes */ /** * @param {GestureObserverCallback} callback */ constructor(callback, { pointerLock = false, pointerCapture = false } = {}) { this.pointerLock = pointerLock; this.pointerCapture = pointerCapture; this._elementsData = new Map(); this._callback = callback; this._onPointerDownBinded = this._onPointerDown.bind(this); this._onPointerMoveBinded = this._onPointerMove.bind(this); this._onPointerUpBinded = this._onPointerUp.bind(this); } /** * Observe gesture changes on the specified target element. * @param {HTMLElement|Window} element Element to observe */ observe(element) { if (this._elementsData.has(element)) { return; } element.addEventListener('pointerdown', this._onPointerDownBinded); this._elementsData.set(element, { pointers: new Map(), gestureVector: new Vector2(), previousSize: 0, previousX: 0, previousY: 0, previousMovementX: 0, previousMovementY: 0, timeStamp: 0, }); } /** * Stop observing gesture changes on the specified target element. * @param {HTMLElement|Window} element Element to unobserve */ unobserve(element) { if (!this._elementsData.has(element)) { return; } element.removeEventListener('pointerdown', this._onPointerDownBinded); element.removeEventListener('pointermove', this._onPointerMoveBinded); this._elementsData.delete(element); } /** * Stops watching all of its target elements for gesture changes. */ disconnect() { for (const element of this._elementsData.keys()) { this.unobserve(element); } } _resetElementData(element) { const data = this._elementsData.get(element); data.gestureVector.set(0, 0); data.previousSize = 0; data.previousX = 0; data.previousY = 0; data.previousRotation = 0; data.timeStamp = 0; } _onPointerDown(event) { const element = event.currentTarget; const data = this._elementsData.get(element); if (this.pointerLock) { element.requestPointerLock(); } else if (this.pointerCapture) { element.setPointerCapture(event.pointerId); } this._resetElementData(element); if (!data.pointers.size) { element.addEventListener('pointermove', this._onPointerMoveBinded); element.addEventListener('pointerup', this._onPointerUpBinded); element.addEventListener('pointerout', this._onPointerUpBinded); data.timeStamp = Date.now(); } data.pointers.set(event.pointerId, event); } _onPointerMove(event) { const data = this._elementsData.get(event.currentTarget); data.pointers.set(event.pointerId, event); let x = 0; let y = 0; let index = 0; for (const pointer of data.pointers.values()) { if (index === 1) { data.gestureVector.x = x - pointer.screenX; data.gestureVector.y = y - pointer.screenY; } x += pointer.screenX; y += pointer.screenY; index++; } x /= data.pointers.size; y /= data.pointers.size; if (!data.previousX && !data.previousY) { data.previousX = x; data.previousY = y; return; } const movementX = x - data.previousX; const movementY = y - data.previousY; data.previousX = x; data.previousY = y; data.previousMovementX = movementX; data.previousMovementY = movementY; const size = data.gestureVector.size; const movementScale = data.previousSize ? size - data.previousSize : 0; data.previousSize = size; const rotation = Math.atan2(data.gestureVector.y, data.gestureVector.x); let movementRotation = data.previousRotation ? rotation - data.previousRotation : 0; if (movementRotation > Math.PI) { movementRotation -= Math.PI * 2; } else if (movementRotation < -Math.PI) { movementRotation += Math.PI * 2; } data.previousRotation = rotation; this._callback({ target: event.currentTarget, movementX: this.pointerLock ? event.movementX / devicePixelRatio : movementX, movementY: this.pointerLock ? event.movementY / devicePixelRatio : movementY, movementScale, movementRotation, isSwipe: false, }); } _onPointerUp(event) { const element = event.currentTarget; const data = this._elementsData.get(element); if (data) { if (Date.now() - data.timeStamp < 1000) { this._callback({ target: event.currentTarget, movementX: data.previousMovementX, movementY: data.previousMovementY, movementScale: 0, movementRotation: 0, isSwipe: true, }); } data.pointers.delete(event.pointerId); this._resetElementData(element); } element.releasePointerCapture(event.pointerId); document.exitPointerLock(); if (!data || !data.pointers.size) { element.removeEventListener('pointermove', this._onPointerMoveBinded); element.removeEventListener('pointerup', this._onPointerUpBinded); element.removeEventListener('pointerout', this._onPointerUpBinded); } } } export default GestureObserver;
JavaScript
0
@@ -5353,24 +5353,62 @@ pointerId);%0A + if (document.exitPointerLock) %7B%0A document @@ -5423,24 +5423,30 @@ nterLock();%0A + %7D%0A if (!dat
49b9177ea41227d92943b72d077d7e9f2a578a81
Add test presence for link.port before join it.
packages/ember-simple-auth/lib/core.js
packages/ember-simple-auth/lib/core.js
'use strict'; /** The main namespace for Ember.SimpleAuth @class SimpleAuth @namespace Ember @static **/ Ember.SimpleAuth = {}; /** Sets up Ember.SimpleAuth for your application; invoke this method in a custom initializer like this: ```javascript Ember.Application.initializer({ name: 'authentication', initialize: function(container, application) { Ember.SimpleAuth.setup(container, application); } }); ``` @method setup @static @param {Container} container The Ember.js container, see http://git.io/ed4U7Q @param {Ember.Application} application The Ember.js application instance @param {Object} [options] @param {String} [options.routeAfterLogin] route to redirect the user to after successfully logging in - defaults to `'index'` @param {String} [options.routeAfterLogout] route to redirect the user to after logging out - defaults to `'index'` @param {String} [options.loginRoute] route to redirect the user to when login is required - defaults to `'login'` @param {String} [options.serverTokenRoute] the server endpoint used to obtain the access token - defaults to `'/token'` @param {String} [options.autoRefreshToken] enable/disable automatic token refreshing (if the server supports it) - defaults to `true` @param {Array[String]} [options.crossOriginWhitelist] list of origins that (besides the origin of the Ember.js application) send the authentication token to - defaults to `[]` **/ Ember.SimpleAuth.setup = function(container, application, options) { options = options || {}; this.routeAfterLogin = options.routeAfterLogin || 'index'; this.routeAfterLogout = options.routeAfterLogout || 'index'; this.loginRoute = options.loginRoute || 'login'; this.serverTokenEndpoint = options.serverTokenEndpoint || '/token'; this.autoRefreshToken = Ember.isEmpty(options.autoRefreshToken) ? true : !!options.autoRefreshToken; this.crossOriginWhitelist = Ember.A(options.crossOriginWhitelist || []); var session = Ember.SimpleAuth.Session.create(); application.register('simple_auth:session', session, { instantiate: false, singleton: true }); Ember.$.each(['model', 'controller', 'view', 'route'], function(i, component) { application.inject(component, 'session', 'simple_auth:session'); }); Ember.$.ajaxPrefilter(function(options, originalOptions, jqXHR) { if (!Ember.isEmpty(session.get('authToken')) && Ember.SimpleAuth.includeAuthorizationHeader(options.url)) { jqXHR.setRequestHeader('Authorization', 'Bearer ' + session.get('authToken')); } }); /** @method includeAuthorizationHeader @private */ this.includeAuthorizationHeader = function(url) { this._links = this._links || {}; var link = Ember.SimpleAuth._links[url] || function() { var link = document.createElement('a'); link.href = url; Ember.SimpleAuth._links[url] = link; return link; }(); var linkUrl = link.protocol+'//'+link.hostname+':'+link.port; var windowLocationUrl = window.location.protocol+'//'+window.location.hostname+':'+window.location.port; return this.crossOriginWhitelist.indexOf(linkUrl) > -1 || linkUrl === windowLocationUrl; }, /** Call this method when an external login was successful. Typically you would have a separate window in which the user is being presented with the external provider's authentication UI and eventually being redirected back to your application. When that redirect occured, the application needs to call this method on its opener window, e.g.: ```html <html> <head></head> <body> <script> window.opener.Ember.SimpleAuth.externalLoginSucceeded({ access_token: 'secret token!' }); window.close(); </script> </body> </html> ``` This method will then set up the session (see [Session#setup](#Ember.SimpleAuth.Session_setup) and invoke the [Ember.SimpleAuth.ApplicationRouteMixin#loginSucceeded](#Ember.SimpleAuth.ApplicationRouteMixin_loginSucceeded) callback. @method externalLoginSucceeded @param {Object} sessionData The data to setup the session with (see [Session#setup](#Ember.SimpleAuth.Session_setup))) */ this.externalLoginSucceeded = function(sessionData) { session.setup(sessionData); container.lookup('route:application').send('loginSucceeded'); }; /** Call this method when an external login fails, e.g.: ```html <html> <head></head> <body> <script> window.opener.Ember.SimpleAuth.externalLoginFailed('something went wrong!'); window.close(); </script> </body> </html> ``` The argument you pass here will be forwarded to the [Ember.SimpleAuth.ApplicationRouteMixin#loginSucceeded](#Ember.SimpleAuth.ApplicationRouteMixin_loginFailed) callback. @method externalLoginFailed @param {Object} error Any optional error that will be forwarded to the [Ember.SimpleAuth.ApplicationRouteMixin#loginSucceeded](#Ember.SimpleAuth.ApplicationRouteMixin_loginFailed) callback */ this.externalLoginFailed = function(error) { container.lookup('route:application').send('loginFailed', error); }; };
JavaScript
0
@@ -2993,24 +2993,44 @@ nk.hostname+ +(link.port !== '' ? ':'+link.por @@ -3026,24 +3026,30 @@ :'+link.port + : '') ;%0A var wi @@ -3121,16 +3121,47 @@ ostname+ +(window.location.port !== '' ? ':'+wind @@ -3176,16 +3176,22 @@ ion.port + : '') ;%0A re
43648de7e54d557ad032f3f4eb4ec3dbf1c4bc93
Use array of args when `apply`ing reconnect
packages/follower-livedata/follower.js
packages/follower-livedata/follower.js
var fs = Npm.require('fs'); var Future = Npm.require('fibers/future'); var MONITOR_INTERVAL = 5*1000; // every 5 seconds /** * Follower.connect() replaces DDP.connect() for connecting to DDP services that * implement a leadership set. The follower connection tries to keep connected * to the leader, and fails over as the leader changes. * * Options: { * group: The name of the leadership group to connect to. Default "package.leadershipLivedata" * } * * A Follower connection implements the following interfaces over and above a * normal DDP connection: * * onLost(callback): calls callback when the library considers itself to have * tried all its known options for the leadership group. * * onFound(callback): Called when the follower was previously lost, but has now * successfully connected to something in the right leadership group. */ Follower = { connect: function (urlSet, options) { var electorTries; options = _.extend({ group: "package.leadershipLivedata" }, options); // start each elector as untried/assumed connectable. var makeElectorTries = function (urlSet) { electorTries = {}; if (typeof urlSet === 'string') { urlSet = _.map(urlSet.split(','), function (url) {return url.trim();}); } _.each(urlSet, function (url) { electorTries[url] = 0; }); }; makeElectorTries(urlSet); var tryingUrl = null; var outstandingGetElectorate = false; var conn = null; var prevReconnect = null; var prevDisconnect = null; var prevApply = null; var leader = null; var connectedTo = null; var intervalHandle = null; // Used to defer all method calls until we're sure that we connected to the // right leadership group. var connectedToLeadershipGroup = new Future(); var lost = false; var lostCallbacks = []; var foundCallbacks = []; var findFewestTries = function () { var min = 10000; var minElector = null; _.each(electorTries, function (tries, elector) { if (tries < min) { min = tries; minElector = elector; } }); if (min > 1 && !lost) { // we've tried everything once; we just became lost. lost = true; _.each(lostCallbacks, function (f) { f(); }); } return minElector; }; var updateElectorate = function (res) { leader = res.leader; electorTries = {}; _.each(res.electorate, function (elector) { electorTries[elector] = 0; // verified that this is in the current elector set. }); }; var tryElector = function (url) { if (tryingUrl) { electorTries[tryingUrl]++; } url = url || findFewestTries(); //console.log("trying", url, electorTries, tryingUrl, process.env.GALAXY_JOB); // Don't keep trying the same url as fast as we can if it's not working. if (electorTries[url] > 2) { Meteor._sleepForMs(3 * 1000); } if (conn) { prevReconnect.apply(conn, { url: url }); } else { conn = DDP.connect(url); prevReconnect = conn.reconnect; prevDisconnect = conn.disconnect; prevApply = conn.apply; } tryingUrl = url; if (!outstandingGetElectorate) { outstandingGetElectorate = true; conn.call('getElectorate', options.group, function (err, res) { outstandingGetElectorate = false; connectedTo = tryingUrl; if (err) { tryElector(); return; } if (!_.contains(res.electorate, connectedTo)) { Log.warn("electorate " + res.electorate + " does not contain " + connectedTo); } tryingUrl = null; if (! connectedToLeadershipGroup.isResolved()) { connectedToLeadershipGroup["return"](); } // we got an answer! Connected! electorTries[url] = 0; if (res.leader === connectedTo) { // we're good. if (lost) { // we're found. lost = false; _.each(foundCallbacks, function (f) { f(); }); } } else { // let's connect to the leader anyway, if we think it // is connectable. if (electorTries[res.leader] == 0) { tryElector(res.leader); } else { // XXX: leader is probably down, we're probably going to elect // soon. Wait for the next round. } } updateElectorate(res); }); } }; tryElector(); var checkConnection = function () { if (conn.status().status !== 'connected' || connectedTo !== leader) { tryElector(); } else { conn.call('getElectorate', options.group, function (err, res) { if (err) { electorTries[connectedTo]++; tryElector(); } else if (res.leader !== leader) { // update the electorate, and then definitely try to connect to the leader. updateElectorate(res); tryElector(res.leader); } else { if (! connectedToLeadershipGroup.isResolved()) { connectedToLeadershipGroup["return"](); } //console.log("updating electorate with", res); updateElectorate(res); } }); } }; var monitorConnection = function () { return Meteor.setInterval(checkConnection, MONITOR_INTERVAL); }; intervalHandle = monitorConnection(); conn.disconnect = function () { if (intervalHandle) Meteor.clearInterval(intervalHandle); intervalHandle = null; prevDisconnect.apply(conn); }; conn.reconnect = function () { if (!intervalHandle) intervalHandle = monitorConnection(); if (arguments[0] && arguments[0].url) { makeElectorTries(arguments[0].url); tryElector(); } else { prevReconnect.apply(conn, arguments); } }; conn.getUrl = function () { return _.keys(electorTries).join(','); }; conn.tries = function () { return electorTries; }; // Assumes that `call` is implemented in terms of `apply`. All method calls // should be deferred until we are sure we've connected to the right // leadership group. conn.apply = function (/* arguments */) { var args = _.toArray(arguments); if (typeof args[args.length-1] === 'function') { // this needs to be independent of this fiber if there is a callback. Meteor.defer(function () { connectedToLeadershipGroup.wait(); return prevApply.apply(conn, args); }); return null; // if there is a callback, the return value is not used } else { connectedToLeadershipGroup.wait(); return prevApply.apply(conn, args); } }; conn.onLost = function (callback) { lostCallbacks.push(callback); }; conn.onFound = function (callback) { foundCallbacks.push(callback); }; return conn; } };
JavaScript
0.000002
@@ -3047,16 +3047,17 @@ y(conn, +%5B %7B%0A @@ -3070,32 +3070,33 @@ l: url%0A %7D +%5D );%0A %7D else
2c84010efe4d929750bde5e0448aeb2086a87608
fix typo
api/apiserv.js
api/apiserv.js
#!/usr/bin/env node /* require node modules */ var fs = require("fs"); var path = require("path"); var http = require("http"); /* require npm modules */ var cradle = require("cradle"); var express = require("express"); /* require local modules */ var log = require(path.resolve(__dirname, "lib/log.js")); /* import config */ var config = require(path.resolve(__dirname, "../config.js")); /* setup couchdb connection */ var db = null; (function(){ /* connect to couchdb */ db = new cradle.Connection(config.db.host, config.db.port, config.db.options).database(config.db.database); /* create database if not existing*/ db.exists(function(err, exists) { if (err) { log.critical("Database Connection Failed", err); } else if (!exists) { db.create(function(err){ if (err) log.critical("Could not create Database", err); log.info("Database Created"); }); } else { log.info("Database ready.") } }); })(); /* setup express */ var app = express(); /* api: events */ app.get('/events', function(req, res){ db.view('events/id', {include_docs: true, descending: true}, function(err, data){ /* FIXME: handle some errors */ var result = []; data.forEach(function(d){ result.push({ "id": d.id, "label": d.label, "title": d.title, "date": d.date, "locations": d.locations, "url": d.url }); }); res.json(result); }); }); app.get('/events/:id', function(req, res){ db.view('events/id', {include_docs: true, descending: true, key: req.params.id}, function(err, data){ if (err || data.length !== 1) return res.json({}); var data = data.pop().doc; res.json({ "id": data.id, "label": data.label, "title": data.title, "date": data.date, "locations": data.locations, "url": data.url }); }); }); app.get('*', function(req, res){ res.json({"rp-api", config.version}); }); /* listen on either tcp or socket according to config */ if ("port" in config.app) { app.listen(config.app.port, config.app.host, function(){ log.info("Server ready, Listening on TCP/IP", config.app.host+':'+config.app.port); }); } else if("socket" in config.app) { app.listen(config.app.socket, function(){ log.info("Server ready, Listening on Socket", config.app.socket); }); }
JavaScript
0.999991
@@ -1832,17 +1832,17 @@ %22rp-api%22 -, +: config.
9494ce3faf614483079b6bfe85ae1f48e8373e22
Refactor to better define data helper
data/clothing.js
data/clothing.js
const request = require('request'); /** * Function checks that a string given is string with some number of * characters * * @params {string} str string value to check for validity * @return true if the string is valid; otherwise, return false */ function isValidString(str) { if ((str === undefined) || (typeof(str) !== "string") || (str.length <= 0)) { return false; } return true; } let user = exports = module.exports = { retrieveClothingInfo: (clothing_url) => { return new Promise((accept, reject) => { if (!isValidString(clothing_url)) { return reject("No clothing_url provided"); } const options = { headers: {'user-agent': 'node.js'} } request(clothing_url, options, function (error, response, body) { if (error || !response || response.statusCode !== 200) { console.log(body); return reject("Invalid clothing_url"); } const price = body.match(/\$([\d.]+)/); const image = body.match(/<meta[\S ]+og:image[\S ]+content="(\S+)"/); accept({ price: price && parseFloat(price[1]), image: image && image[1], }); }); }); } }
JavaScript
0.000002
@@ -398,20 +398,24 @@ %0A%7D%0A%0Alet -user +clothing = expor @@ -1158,32 +1158,16 @@ S+)%22/);%0A - %0A @@ -1343,8 +1343,9 @@ %0A %7D%0A%7D +%0A
f18d3dcb453ef93efaa42d472c087bf3f10520e0
fix (webpack): import missing app-root-path
config/webpack/browser/webpack.browser.prod.js
config/webpack/browser/webpack.browser.prod.js
/* * @author: @AngularClass */ const webpackMerge = require('webpack-merge'); // used to merge webpack configs const commonConfig = require('./webpack.browser.common.js'); // the settings that are common to prod and dev const { PROD_OPTIONS } = require('./../options'); /* * Webpack Plugins */ const { DefinePlugin, IgnorePlugin, LoaderOptionsPlugin, NormalModuleReplacementPlugin, ProvidePlugin, } = require('webpack'); const { DedupePlugin, UglifyJsPlugin } = require('webpack').optimize; const WebpackMd5Hash = require('webpack-md5-hash'); module.exports = function(env) { const _env = Object.assign({}, PROD_OPTIONS, env); return webpackMerge(commonConfig(_env), { /** * Developer tool to enhance debugging * * See: http://webpack.github.io/docs/configuration.html#devtool * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps */ devtool: 'source-map', /** * Options affecting the output of the compilation. * * See: http://webpack.github.io/docs/configuration.html#output */ output: { /** * The output directory as absolute path (required). * * See: http://webpack.github.io/docs/configuration.html#output-path */ path: appRoot.resolve('dist'), /** * Specifies the name of each output file on disk. * IMPORTANT: You must not specify an absolute path here! * * See: http://webpack.github.io/docs/configuration.html#output-filename */ filename: '[name].[chunkhash].bundle.js', /** * The filename of the SourceMaps for the JavaScript files. * They are inside the output.path directory. * * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename */ sourceMapFilename: '[name].[chunkhash].bundle.map', /** * The filename of non-entry chunks as relative path * inside the output.path directory. * * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename */ chunkFilename: '[id].[chunkhash].chunk.js' }, /** * Add additional plugins to the compiler. * * See: http://webpack.github.io/docs/configuration.html#plugins */ plugins: [ /** * Plugin: WebpackMd5Hash * Description: Plugin to replace a standard webpack chunkhash with md5. * * See: https://www.npmjs.com/package/webpack-md5-hash */ new WebpackMd5Hash(), /** * Plugin: DedupePlugin * Description: Prevents the inclusion of duplicate code into your bundle * and instead applies a copy of the function at runtime. * * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin * See: https://github.com/webpack/docs/wiki/optimization#deduplication */ // new DedupePlugin(), // see: https://github.com/angular/angular-cli/issues/1587 /** * Plugin: DefinePlugin * Description: Define free variables. * Useful for having development builds with debug logging or adding global constants. * * Environment helpers * * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin */ // NOTE: when adding more properties make sure you include them in custom-typings.d.ts new DefinePlugin({ 'ENV': JSON.stringify(_env.ENV), 'HMR': _env.HMR, 'process.env': { 'ENV': JSON.stringify(_env.ENV), 'NODE_ENV': JSON.stringify(_env.ENV), 'HMR': _env.HMR, } }), /** * Plugin: UglifyJsPlugin * Description: Minimize all JavaScript output of chunks. * Loaders are switched into minimizing mode. * * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin */ // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines new UglifyJsPlugin({ // beautify: true, //debug // mangle: false, //debug // dead_code: false, //debug // unused: false, //debug // deadCode: false, //debug // compress: { // screw_ie8: true, // keep_fnames: true, // drop_debugger: false, // dead_code: false, // unused: false // }, // debug // comments: true, //debug beautify: false, //prod mangle: { screw_ie8 : true, keep_fnames: true }, //prod compress: { screw_ie8: true }, //prod comments: false //prod }), /** * Plugin: NormalModuleReplacementPlugin * Description: Replace resources that matches resourceRegExp with newResource * * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin */ new NormalModuleReplacementPlugin( /angular2-hmr/, appRoot.resolve('config/modules/angular2-hmr-prod.js') ), /** * Plugin: IgnorePlugin * Description: Don’t generate modules for requests matching the provided RegExp. * * See: http://webpack.github.io/docs/list-of-plugins.html#ignoreplugin */ // new IgnorePlugin(/angular2-hmr/), /** * Plugin: CompressionPlugin * Description: Prepares compressed versions of assets to serve * them with Content-Encoding * * See: https://github.com/webpack/compression-webpack-plugin */ // install compression-webpack-plugin // new CompressionPlugin({ // regExp: /\.css$|\.html$|\.js$|\.map$/, // threshold: 2 * 1024 // }) new LoaderOptionsPlugin({ /** * Switch loaders to debug mode. * * See: http://webpack.github.io/docs/configuration.html#debug */ debug: false, options: { /** * Static analysis linter for TypeScript advanced options configuration * Description: An extensible linter for the TypeScript language. * * See: https://github.com/wbuchwalter/tslint-loader */ tslint: { emitErrors: true, failOnHint: true, resourcePath: 'src' }, /** * Html loader advanced options * * See: https://github.com/webpack/html-loader#advanced-options */ // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor htmlLoader: { minimize: true, removeAttributeQuotes: false, caseSensitive: true, customAttrSurround: [ [/#/, /(?:)/], [/\*/, /(?:)/], [/\[?\(?/, /(?:)/] ], customAttrAssign: [/\)?\]?=/] }, }, }), ], /* * Include polyfills or mocks for various node stuff * Description: Node configuration * * See: https://webpack.github.io/docs/configuration.html#node */ node: { global: true, crypto: 'empty', process: false, module: false, clearImmediate: false, setImmediate: false } }); }
JavaScript
0.000001
@@ -27,16 +27,58 @@ ss%0A */%0A%0A +const appRoot = require('app-root-path');%0A const we @@ -149,16 +149,17 @@ configs%0A +%0A const co
4732bc29341e304878eb419dc06423c3e54b39dd
Update BackButton.js
twitter-example/components/BackButton.js
twitter-example/components/BackButton.js
import React, { StyleSheet, Image } from 'react-native'; export default class BackButton extends React.Component { render() { return ( <Image source={require('../images/back_button.png')} style={styles.backButton} /> ); } } var styles = StyleSheet.create({ backButton: { width: 10, height: 17, marginLeft: 10, marginTop: 3, marginRight: 10, }, });
JavaScript
0.000001
@@ -241,11 +241,13 @@ %0A%7D%0A%0A -var +const sty
7220f7215af06ffc190846ba1403f1f17e44813c
Fix (hopefully) for broken path
files/static/js/splash/main.js
files/static/js/splash/main.js
var lastClick , docLocHref = document.location.href , pageRequest = docLocHref.substring(docLocHref.indexOf('#') + 1, docLocHref.length) , open_window , change_page , date = new Date() // +100 because javascript 0-indexes months huehuehue , today = parseInt(date.getMonth()+''+date.getDate()) + 100; open_window = function (section_id) { var guide_background = document.createElement('div') , guide = document.createElement('div') , guide_inner = document.createElement('div') , guide_close = document.createElement('div'); guide_inner.innerHTML = $(section_id).html(); guide_close.innerHTML = '<img src="graphics/close.png" alt="close">'; guide_background.setAttribute('id', 'guide_background'); guide.setAttribute('id', 'guide'); guide_inner.setAttribute('class', 'guide_inner'); guide_close.setAttribute('class', 'guide_close'); guide.appendChild(guide_inner); guide_background.appendChild(guide_close); guide_background.appendChild(guide); $('body').append(guide_background).hide().fadeIn(400); $(guide_background).click(function() { $(guide_background).fadeOut(300, function() { $(this).remove(); }); }); $(guide_close).click(function() { $(guide_background).fadeOut(300, function() { $(this).remove(); }); }); $(guide).click(function(e) { e.stopPropagation(); }); innerScroll = new iScroll(guide_inner); }; change_page = function(name) { $('#content').fadeOut(180, function() { $('#content').html( $('#'+name).html()).fadeIn(); }); lastClick.removeClass('on'); lastClick = $('#link_'+name); lastClick.addClass('on'); var active = 0; if (name === 'cal') { $('.cal-left ul li').each(function () { if ($(this).data('date') === today) { $(this).addClass('active'); $('#cal-content').html($('article', this).html()); active = 1; } }); if (active === 0) { $('.cal-left ul li:first-child').addClass('active'); $('#cal-content').html($('.cal-left ul li:first-child article').html()); } } }; update_page = function (name) { $('#'+name).html($('#content').html()); }; /* Stuff bellow --- functions above -------------------------------------------------------------- */ lastClick = $('#link_online'); switch (pageRequest) { case 'join': change_page('join'); break; case 'mer': change_page('mer'); break; case 'fadderukene': change_page('fadderukene'); break; case 'cal': change_page('cal'); break; default: change_page('online'); } $('nav a').click(function(event) { switch (this.id) { case 'link_online': change_page('online'); break case 'link_join': change_page('join'); break; case 'link_fadderukene': change_page('fadderukene'); break; case 'link_mer': change_page('mer'); break; case 'link_cal': change_page('cal'); break; case 'hovedsiden': break; default: change_page('online'); } }); var isIOS = navigator.userAgent.match(/(iPod|iPhone|iPad)/) , click_event = isIOS ? 'touchend' : 'click' , active = 0; $('.cal-left ul').children('li').each(function () { if (parseInt($(this).data('date')) < today) { $(this).addClass('inactive'); } }); $(document).on(click_event, '.cal-left ul li', function (e) { if ($(this).hasClass('inactive')) return; var that = this; $('#cal-content').fadeOut(100, function () { $('#cal-content').html($('article', that).html()).fadeIn(100); $('.cal-left ul').children('li').each(function () { $(this).removeClass('active'); }); $(that).addClass('active'); }); });
JavaScript
0
@@ -697,16 +697,26 @@ rc=%22 -graphics +/static/img/splash /clo
ef8d1960d64b42afdc1ec8f0d6b86e8dbfae6d3a
remove dead code in pubchem
chemistry/PubChem.js
chemistry/PubChem.js
import ui from 'src/util/ui'; const pubchemURL = 'https://pubchem.cheminfo.org/molecules/mf?mf='; async function getMolecules(mf) { let response = await fetch(`${pubchemURL}${mf}`); let results = (await response.json()).result; return new Promise(function(resolve, reject) { resolve(results); }); } module.exports = { choose: function(mf, options = {}) { let promise = getMolecules(mf); return ui .choose([{ promise }], { autoSelect: false, asynchronous: true, noConfirmation: true, returnRow: false, dialog: { width: 1000, height: 800 }, columns: [ { id: 'iupac', name: 'Name', jpath: [], rendererOptions: { forceType: 'object', twig: ` {{iupac}} ` } }, { id: 'structure', name: 'Structure', jpath: ['ocl', 'id'], rendererOptions: { forceType: 'oclID' }, maxWidth: 500 }, { id: 'url', name: 'Pubchem', jpath: [], rendererOptions: { forceType: 'object', twig: ` <a href="https://pubchem.ncbi.nlm.nih.gov/compound/{{_id}}" onclick="event.stopPropagation()" target="_blank">&#x2B08;</a> ` }, maxWidth: 70 } ], idField: 'id', slick: { rowHeight: 140 } }) .catch(function(e) { console.error(e); // eslint-disable-line no-console ui.showNotification('search failed', 'error'); }); } }; function listTemplate(val, prop) { return ` <div style="height: 100%; line-height: initial; vertical-align: middle"> <table style="width: 100%; text-align: center;"> {% for n in ${val} %} <tr><td>{{ n${prop} }}</td></tr> {% endfor %} </table> </div> `; }
JavaScript
0.000389
@@ -256,16 +256,17 @@ function + (resolve @@ -345,16 +345,17 @@ function + (mf, opt @@ -1621,14 +1621,15 @@ tion + (e) %7B%0A - @@ -1757,333 +1757,7 @@ %7D%0A + %7D;%0A -%0Afunction listTemplate(val, prop) %7B%0A return %60%0A %3Cdiv style=%22height: 100%25; line-height: initial; vertical-align: middle%22%3E%0A %3Ctable style=%22width: 100%25; text-align: center;%22%3E%0A %7B%25 for n in $%7Bval%7D %25%7D%0A %3Ctr%3E%3Ctd%3E%7B%7B n$%7Bprop%7D %7D%7D%3C/td%3E%3C/tr%3E%0A %7B%25 endfor %25%7D%0A %3C/table%3E%0A %3C/div%3E%0A %60;%0A%7D%0A
ace21569ff83ed3b29ef07c6c46693e5c8228b2f
Update sockets.js
app/sockets.js
app/sockets.js
import socketio from 'socket.io-client' import Enemy from './classes/Enemy' import Player from './classes/Player' /* global StackQuest */ export const socket = socketio.connect() export const GamePlayers = {} export const GameEnemies = {} export let collisionArrayStatus = false const socketFunctions = socket => { socket.on('getPlayers', getPlayers) socket.on('addPlayer', addPlayer) socket.on('updatePlayer', updatePlayer) socket.on('removePlayer', removePlayer) socket.on('enemyCreated', enemyCreated) socket.on('foundPath', foundPath) socket.on('getEnemies', getEnemies) socket.on('createdCollisionArray', createdCollisionArray) socket.on('removeEnemy', removeEnemy) } const getPlayers = players => { for (const player in GamePlayers) delete GamePlayers[player] Object.keys(players).forEach(playerSocketId => { GamePlayers[playerSocketId] = new Player(StackQuest.game, players[playerSocketId].userName, players[playerSocketId]) }) } const addPlayer = (socketId, player) => { console.log('adding player', player) GamePlayers[socketId] = new Player(StackQuest.game, player.userName, player) } const updatePlayer = (socketId, playerPos) => { GamePlayers[socketId].moveOther(playerPos.x, playerPos.y) // GamePlayers[socketId].position.y = playerPos.y } const removePlayer = socketId => { const player = GamePlayers[socketId] if (player) { player.destroy() delete GamePlayers[socketId] } } const enemyCreated = enemy => { GameEnemies[enemy.name] = new Enemy(StackQuest.game, enemy.name, { x: enemy.x, y: enemy.y }, enemy.key) } const foundPath = (newPos, name) => { if (GameEnemies[name]) GameEnemies[name].move(newPos) } const getEnemies = enemies => { for (const enemy in GameEnemies) delete GameEnemies[enemy] Object.keys(enemies).forEach(enemyName => { const enemy = enemies[enemyName] GameEnemies[enemyName] = new Enemy(StackQuest.game, enemyName, { x: enemy.x, y: enemy.y }, enemy.key) }) } const removeEnemy = name => { GameEnemies[name].destroy() delete GameEnemies[name] } const createdCollisionArray = (state) => { collisionArrayStatus = true } socketFunctions(socket) export default socketFunctions
JavaScript
0.000001
@@ -1009,47 +1009,8 @@ %3E %7B%0A - console.log('adding player', player)%0A Ga
be5228176e54f0e068dd155ee6c052351b0c02d5
remove time zone offset and use UTC getters
src/plots/cartesian/align_period.js
src/plots/cartesian/align_period.js
/** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var isNumeric = require('fast-isnumeric'); var Lib = require('../../lib'); var ms2DateTime = Lib.ms2DateTime; var dateTime2ms = Lib.dateTime2ms; var incrementMonth = Lib.incrementMonth; var constants = require('../../constants/numerical'); var ONEDAY = constants.ONEDAY; var ONEAVGMONTH = constants.ONEAVGMONTH; var ONEAVGYEAR = constants.ONEAVGYEAR; module.exports = function alignPeriod(trace, ax, axLetter, vals) { if(ax.type !== 'date') return vals; var alignment = trace[axLetter + 'periodalignment']; if(!alignment) return vals; var period = trace[axLetter + 'period']; var mPeriod; if(isNumeric(period)) { period = +period; if(period <= 0) return vals; } else if(typeof period === 'string' && period.charAt(0) === 'M') { var n = +(period.substring(1)); if(n > 0 && Math.round(n) === n) { mPeriod = n; period = n * ONEAVGMONTH; } else return vals; } if(period > 0) { var calendar = ax.calendar; var isStart = 'start' === alignment; // var isMiddle = 'middle' === alignment; var isEnd = 'end' === alignment; var offset = (new Date()).getTimezoneOffset() * 60000; var period0 = trace[axLetter + 'period0']; var base = (dateTime2ms(period0, calendar) || 0) - offset; var newVals = []; var len = vals.length; for(var i = 0; i < len; i++) { var v = vals[i] - base; var dateStr = ms2DateTime(v, 0, calendar); var d = new Date(dateStr); var year = d.getFullYear(); var month = d.getMonth(); var day = d.getDate(); var newD; var startTime; var endTime; var nMonths = Math.floor(period / ONEAVGMONTH) % 12; var nYears = Math.floor((period - nMonths * ONEAVGMONTH) / ONEAVGYEAR); var nDays = Math.floor((period - nMonths * ONEAVGMONTH - nYears * ONEAVGYEAR) / ONEDAY); if(nYears && nMonths) nDays = 0; var y1 = year + nYears; var m1 = month + nMonths; var d1 = day + nDays; if(nDays || nMonths || nYears) { if(nDays) { startTime = (new Date(year, month, day)).getTime(); var monthDays = new Date(y1, m1 + 1, 0).getDate(); if(d1 > monthDays) { d1 -= monthDays; m1 += 1; if(m1 > 11) { m1 -= 12; y1 += 1; } } endTime = (new Date(y1, m1, d1)).getTime(); } else if(nMonths) { startTime = (new Date(year, nYears ? month : roundMonth(month, nMonths))).getTime(); endTime = incrementMonth(startTime, mPeriod ? mPeriod : nMonths, calendar); } else { startTime = (new Date(year, 0)).getTime(); endTime = (new Date(y1, 0)).getTime(); } newD = new Date( isStart ? startTime : isEnd ? endTime : (startTime + endTime) / 2 ); } newVals[i] = newD ? newD.getTime() + base : vals[i]; } return newVals; } return vals; }; var monthSteps = [2, 3, 4, 6]; function roundMonth(month, step) { return (monthSteps.indexOf(step) === -1) ? month : Math.floor(month / step) * step; }
JavaScript
0
@@ -1356,71 +1356,8 @@ t;%0A%0A - var offset = (new Date()).getTimezoneOffset() * 60000;%0A @@ -1422,17 +1422,16 @@ base = -( dateTime @@ -1461,18 +1461,8 @@ %7C%7C 0 -) - offset ;%0A%0A @@ -1715,16 +1715,19 @@ = d.get +UTC FullYear @@ -1759,16 +1759,19 @@ = d.get +UTC Month(); @@ -1794,24 +1794,27 @@ day = d.get +UTC Date();%0A%0A @@ -2390,33 +2390,32 @@ startTime = -(new Date +.UTC (year, month @@ -2420,27 +2420,16 @@ th, day) -).getTime() ;%0A @@ -2485,16 +2485,19 @@ , 0).get +UTC Date();%0A @@ -2798,33 +2798,32 @@ endTime = -(new Date +.UTC (y1, m1, d1) @@ -2822,27 +2822,16 @@ m1, d1) -).getTime() ;%0A @@ -2889,33 +2889,32 @@ startTime = -(new Date +.UTC (year, nYear @@ -2952,27 +2952,16 @@ Months)) -).getTime() ;%0A @@ -3111,36 +3111,24 @@ e = -(new Date(year, 0)).getTime( +Date.UTC(year, 0 );%0A @@ -3160,34 +3160,22 @@ e = -(new Date(y1, 0)).getTime( +Date.UTC(y1, 0 );%0A
058688ba57e4a80c7019cf35414f2594f4a7a426
use current 2d theme for embed
ui/site/src/standalones/embed-analyse.js
ui/site/src/standalones/embed-analyse.js
function toYouTubeEmbedUrl(url) { if (!url) return; var m = url.match(/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch)?(?:\?v=)?([^"&?\/ ]{11})(?:\?|&|)(\S*)/i); if (!m) return; var start = 1; m[2].split('&').forEach(function(p) { var s = p.split('='); if (s[0] === 't' || s[0] === 'start') { if (s[1].match(/^\d+$/)) start = parseInt(s[1]); else { var n = s[1].match(/(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/); start = (parseInt(n[1]) || 0) * 3600 + (parseInt(n[2]) || 0) * 60 + (parseInt(n[3]) || 0); } } }); var params = 'modestbranding=1&rel=0&controls=2&iv_load_policy=3&start=' + start; return 'https://www.youtube.com/embed/' + m[1] + '?' + params; } $(function() { var domain = window.location.host; var studyRegex = new RegExp(domain + '/study/(?:embed/)?(\\w{8})/(\\w{8})(#\\d+)?\\b'); var gameRegex = new RegExp(domain + '/(?:embed/)?(\\w{8})(?:(?:/(white|black))|\\w{4}|)(#\\d+)?\\b'); var notGames = ['training', 'analysis', 'insights', 'practice', 'features', 'password', 'streamer']; var parseLink = function(a) { var yt = toYouTubeEmbedUrl(a.href); if (yt) return { type: 'youtube', src: yt }; var matches = a.href.match(studyRegex); if (matches && matches[2] && a.text.match(studyRegex)) return { type: 'study', src: '/study/embed/' + matches[1] + '/' + matches[2] + (matches[3] || '') }; var matches = a.href.match(gameRegex); if (matches && matches[1] && !notGames.includes(matches[1]) && a.text.match(gameRegex)) { var src = '/embed/' + matches[1]; if (matches[2]) src += '/' + matches[2]; // orientation if (matches[3]) src += matches[3]; // ply hash return { type: 'game', src: src }; } }; var expandYoutube = function(a) { var $iframe = $('<div class="embed"><iframe src="' + a.src + '"></iframe></div>'); $(a.element).replaceWith($iframe); return $iframe; }; var expandYoutubes = function(as, wait) { var a = as.shift(), wait = Math.min(1500, wait || 100); if (a) expandYoutube(a).on('load', function() { setTimeout(function() { expandYoutubes(as, wait + 200); }, wait); }); }; var expand = function(a) { var $iframe = $('<iframe>').addClass('analyse ' + a.type).attr('src', a.src); $(a.element).replaceWith($('<div class="embed"></div>').html($iframe)); return $iframe.on('load', function() { if (this.contentDocument.title.startsWith("404")) this.style.height = '100px'; }).on('mouseenter', function() { $(this).focus(); }); }; var expandStudies = function(as, wait) { var a = as.shift(), wait = Math.min(1500, wait || 100); if (a) expand(a).on('load', function() { setTimeout(function() { expandStudies(as, wait + 200); }, wait); }); }; function groupByParent(as) { var groups = []; var current = { parent: null, index: -1 }; as.forEach(function(a) { if (a.parent === current.parent) groups[current.index].push(a); else { current = { parent: a.parent, index: current.index + 1 }; groups[current.index] = [a]; } }); return groups; }; var expandGames = function(as) { groupByParent(as).forEach(function(group) { if (group.length < 3) group.forEach(expand); else group.forEach(function(a) { a.element.title = 'Click to expand'; a.element.classList.add('text'); a.element.setAttribute('data-icon', '='); a.element.addEventListener('click', function(e) { if (e.button === 0) { e.preventDefault(); expand(a); } }); }); }); }; var configureSrc = function(url) { if (url.includes('://')) return url; // youtube, img, etc var parsed = new URL(url, window.location.href); parsed.searchParams.append('bg', $('body').data('theme')); return parsed.href; } var as = $('.embed_analyse a').toArray().map(function(el) { var parsed = parseLink(el); if (!parsed) return false; return { element: el, parent: el.parentNode, type: parsed.type, src: configureSrc(parsed.src) }; }).filter(function(a) { return a; }); expandYoutubes(as.filter(function(a) { return a.type === 'youtube' })); expandStudies(as.filter(function(a) { return a.type === 'study' }).map(function(a) { a.element.classList.add('embedding_analyse'); a.element.innerHTML = lichess.spinnerHtml; return a; })); expandGames(as.filter(function(a) { return a.type === 'game' })); }); lichess.startEmbeddedAnalyse = function(opts) { opts.socketSend = $.noop opts.initialPly = 'url'; opts.trans = lichess.trans(opts.i18n); LichessAnalyse.start(opts); window.addEventListener('resize', function() { lichess.dispatchEvent(document.body, 'chessground.resize'); }); }
JavaScript
0
@@ -3789,24 +3789,188 @@ %7D);%0A %7D;%0A%0A + var themes = %5B'blue', 'blue2', 'blue3', 'canvas', 'wood', 'wood2', 'wood3', 'maple', 'green', 'marble', 'brown', 'leather', 'grey', 'metal', 'olive', 'purple'%5D;%0A%0A var config @@ -4145,29 +4145,180 @@ nd(' -bg', $('body').data(' +theme', themes.find(function (theme) %7B%0A return document.body.classList.contains(theme);%0A %7D));%0A parsed.searchParams.append('bg', document.body.getAttribute('data- them
95cabba40f01bdbae802e1fb40da60206f94a4c1
make linter happy
ui/src/data_explorer/components/Table.js
ui/src/data_explorer/components/Table.js
import React, {PropTypes} from 'react' import {Table, Column, Cell} from 'fixed-data-table' import Dimensions from 'react-dimensions' import fetchTimeSeries from 'shared/apis/timeSeries' import _ from 'lodash' import moment from 'moment' const {oneOfType, number, string, shape, arrayOf} = PropTypes const CustomCell = React.createClass({ propTypes: { data: oneOfType([number, string]).isRequired, columnName: string.isRequired, }, render() { const {columnName, data} = this.props if (columnName === 'time') { const date = moment(new Date(data)).format('MM/DD/YY hh:mm:ssA') return <span>{date}</span> } return <span>{data}</span> }, }) const ChronoTable = React.createClass({ propTypes: { query: shape({ host: arrayOf(string.isRequired).isRequired, text: string.isRequired, }), containerWidth: number.isRequired, height: number, }, getInitialState() { return { cellData: { columns: [], values: [], }, columnWidths: {}, } }, getDefaultProps() { return { height: 600, } }, fetchCellData(query) { this.setState({isLoading: true}) // second param is db, we want to leave this blank fetchTimeSeries(query.host, undefined, query.text).then((resp) => { const cellData = _.get(resp.data, ['results', '0', 'series', '0'], false) if (!cellData) { return this.setState({isLoading: false}) } this.setState({ cellData, isLoading: false, }) }) }, componentDidMount() { this.fetchCellData(this.props.query) }, componentWillReceiveProps(nextProps) { if (this.props.query.text !== nextProps.query.text) { this.fetchCellData(nextProps.query) } }, handleColumnResize(newColumnWidth, columnKey) { this.setState(({columnWidths}) => ({ columnWidths: Object.assign({}, columnWidths, { [columnKey]: newColumnWidth, }), })) }, // Table data as a list of array. render() { const {containerWidth, height} = this.props const {cellData, columnWidths, isLoading} = this.state const {columns, values} = cellData // adjust height to proper value by subtracting the heights of the UI around it // tab height, graph-container vertical padding, graph-heading height, multitable-header height const stylePixelOffset = 136 const rowHeight = 34 const width = columns.length > 1 ? 200 : containerWidth const headerHeight = 30 const minWidth = 70 const styleAdjustedHeight = height - stylePixelOffset if (!isLoading && !values.length) { return <div className="generic-empty-state">Your query returned no data</div> } return ( <Table onColumnResizeEndCallback={this.handleColumnResize} isColumnResizing={false} rowHeight={rowHeight} rowsCount={values.length} width={containerWidth} ownerHeight={styleAdjustedHeight} height={styleAdjustedHeight} headerHeight={headerHeight}> {columns.map((columnName, colIndex) => { return ( <Column isResizable={true} key={columnName} columnKey={columnName} header={<Cell>{columnName}</Cell>} cell={({rowIndex}) => { return <CustomCell columnName={columnName} data={values[rowIndex][colIndex]} /> }} width={columnWidths[columnName] || width} minWidth={minWidth} /> ) })} </Table> ) }, }) export default Dimensions({elementResize: true})(ChronoTable)
JavaScript
0.000001
@@ -2422,16 +2422,51 @@ ht = 34%0A + const defaultColumnWidth = 200%0A cons @@ -2496,19 +2496,34 @@ h %3E 1 ? -200 +defaultColumnWidth : conta
0da69fbccb9e1cdaa4617ae9db09d9e36f32c576
Improve headers
lib/middleware/apiGatewayProxyRest/lib/headers.js
lib/middleware/apiGatewayProxyRest/lib/headers.js
const { COMMA } = require("./constant.js"); class Headers { constructor(headers) { for (const key in headers) { if (headers[key].indexOf(COMMA)) { headers[key] = headers[key].split(COMMA); headers[key] = headers[key].map((item) => item.trim()); } } Object.assign(this, headers); } lastOf(header) { if (this[header]) { if (Array.isArray(this[header])) { return [...this[header]].pop(); } return this[header]; } return null; } firstOf(header) { if (this[header]) { if (Array.isArray(this[header])) { return [...this[header]].shift(); } return this[header]; } return null; } } module.exports = Headers;
JavaScript
0.000003
@@ -136,16 +136,62 @@ .indexOf + && headers%5Bkey%5D.split && headers%5Bkey%5D.indexOf (COMMA))
2de8b6cfd6c731194958295139a5a3d8f6e096a7
Support environments lacking a `window` global
lib/node_modules/@stdlib/utils/keys/lib/window.js
lib/node_modules/@stdlib/utils/keys/lib/window.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // EXPORTS // module.exports = window;
JavaScript
0.000002
@@ -626,16 +626,91 @@ rict';%0A%0A +// MAIN //%0A%0Avar w = ( typeof window === 'undefined' ) ? void 0 : window;%0A%0A%0A // EXPOR @@ -733,16 +733,11 @@ ports = -windo w;%0A
a4426a4de61b60da28b296edfa0f1f7b074b39c6
Include path
webpack.config.prod.babel.js
webpack.config.prod.babel.js
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ import webpack from 'webpack'; import CopyWebpackPlugin from 'copy-webpack-plugin'; import HtmlWebpackPlugin from 'html-webpack-plugin'; export default { context: __dirname, entry: './index.jsx', output: { path: `${__dirname}/__dist__`, publicPath: '/', filename: 'bundle.js', }, module: { loaders: [ { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ 'file?hash=sha512&digest=hex&name=[hash].[ext]', 'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false' ] }, { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.scss$/, loaders: [ 'style-loader', 'css-loader', 'sass-loader?includePaths[]=' + path.resolve(__dirname, './node_modules/compass-mixins/lib') ]}, ], }, resolve: { extensions: ['.js', '.jsx'], }, plugins: [ new CopyWebpackPlugin([ { from: 'CNAME' }, { from: '404.html' }, { from: 'img', to: 'img' }, { from: 'fonts', to: 'fonts' } ]), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.UglifyJsPlugin({ output: { comments: false, }, }), new HtmlWebpackPlugin({ template: 'index.template.ejs', inject: 'body' }), ], };
JavaScript
0
@@ -78,16 +78,41 @@ ue%7D%5D */%0A +import path from 'path';%0A import w
b70c7b88ba3ae674b40502503062431ea99bb3f8
update webpack config
webpack.production.config.js
webpack.production.config.js
var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var path = require('path'); module.exports = { entry: { app: [ './public/src/containers/app', ], // vendors: [ // 'i18Next', // 'jqueryLazyload' // ] }, output: { path: path.resolve(__dirname, 'public'), filename: './asset/js/bundle/bundle.min.js', chunkFilename: "./asset/js/bundle/chunk.[name].min.js" }, // devtool: "source-map", resolve: { alias: { jqueryLazyload: './public/asset/js/jquery/jquery.lazyload.min.js', i18Next: './public/asset/js/i18Next/i18Next.min.js' }, "extensions": ["", ".js", ".jsx"] }, module: { loaders: [ { test: /\.js?$/, loader: 'babel', include: path.resolve(__dirname, 'public'), exclude: /node_modules/ }, { test: /\.json$/, loader: "json-loader" }, { test: /\.scss$/, loader: ExtractTextPlugin.extract( "style-loader", 'css-loader!sass-loader?includePaths[]=' + path.resolve(__dirname, './node_modules/compass-mixins/lib') ) }, { test: /\.(jpe?g|png|gif|svg)$/i, loader: 'url-loader?limit=8192&name=./asset/img/[name].[ext]' }] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }}), // new webpack.optimize.CommonsChunkPlugin('vendors', 'asset/js/vendors.min.js'), new ExtractTextPlugin('./asset/css/bundle/bundle.min.css', { allChunks: true }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }) ] };
JavaScript
0.000001
@@ -1114,16 +1114,22 @@ est: /%5C. +css%7C%5C. scss$/,%0A
02925c00eab83482f04a38da703546abf37ccdb2
branche input sur le chatter
src/presenters/message_presenter.js
src/presenters/message_presenter.js
'use strict'; function chatterPresenter(element, options) { element = $(element); var message_template = options.message_template, chatter = options.model, $messagesListElement = element.find('#messages-list'); element.on('keyup', '#new-message', function (e) { var val = $.trim(this.value); if (val && e.which === 13) { // todo.add(val); this.value = ''; console.log("message= " + val); } }); // Listen to model events chatter.on("add", add); // Private functions function add(message) { var messageElement = $(riot.render(message_template, {id: 1, message: message})); $messagesListElement.append(messageElement); } };
JavaScript
0.00002
@@ -347,21 +347,14 @@ ) %7B%0A -// -todo. add( @@ -386,46 +386,8 @@ '';%0A - console.log(%22message= %22 + val);%0A
989a705f204a2a6078475493650d30e569cdaf0d
Fix error in element name for showing unauthorized alert using jQuery
views/js/helpers/login/loginsubmitter.js
views/js/helpers/login/loginsubmitter.js
/** * Created by Omnius on 6/27/16. */ const submitForm = () => { // TODO: Supposedly needs sanitation using ESAPI.encoder().encodeForJavascript() or some other sanitation // mechanism on inputUsername and inputPassword const username = $('#inputUsername').val(); const password = $('#inputPassword').val(); $.ajax({ type: 'GET', beforeSend: function (request) { request.setRequestHeader('Authorization', 'Basic ' + btoa(username + ':' + password)); }, url: '/auth/basic', processData: false, success: function(data, textStatus, jQxhr){ $('#formLogin').attr('action', '/user/welcome'); $('#formLogin').submit(); }, error: function (xhr, textStatus, errorThrown) { if (xhr.status === 401) { $('#formUnauthorized').removeClass('hidden'); } } }); };
JavaScript
0.000001
@@ -839,20 +839,21 @@ $('# -form +alert Unauthor
21f60e31c8f4582ad73241b1f626ac9ee53480a5
change trailing slash config to false
website/docusaurus.config.js
website/docusaurus.config.js
module.exports = { title: 'Tech Interview Handbook', tagline: 'Free curated interview preparation materials for busy people', url: 'https://www.techinterviewhandbook.org', baseUrl: '/', trailingSlash: true, favicon: 'img/favicon.png', organizationName: 'yangshun', projectName: 'tech-interview-handbook', themeConfig: { announcementBar: { id: 'algomonster', // Increment on change content: `Stop the grind and study with a plan! Developed by Google engineers, <a href="https://shareasale.com/r.cfm?b=1873647&u=3114753&m=114505&urllink=&afftrack=" target="_blank" rel="noopener">AlgoMonster</a> is the fastest way to get a software engineering job. <a href="https://shareasale.com/r.cfm?b=1873647&u=3114753&m=114505&urllink=&afftrack=" target="_blank" rel="noopener">Check it out now!</a>`, isCloseable: false, }, prism: { theme: require('prism-react-renderer/themes/github'), darkTheme: require('prism-react-renderer/themes/dracula'), }, navbar: { title: 'Tech Interview Handbook', logo: { alt: '', src: 'img/logo.svg', }, items: [ { label: 'Start reading', href: '/introduction', position: 'left', }, { label: 'Coding', href: '/coding-interview', }, { label: 'Algorithms', href: '/algorithms/introduction', }, {label: 'Blog', to: 'blog', position: 'left'}, { label: 'Grind 75', href: 'https://www.techinterviewhandbook.org/grind75', position: 'left', }, // {label: 'Advertise', to: '/advertise', position: 'left'}, { href: 'https://github.com/yangshun/tech-interview-handbook', position: 'right', className: 'navbar-icon navbar-icon-github', 'aria-label': 'GitHub repository', }, { href: 'https://t.me/techinterviewhandbook', position: 'right', className: 'navbar-icon navbar-icon-telegram', 'aria-label': 'Telegram channel', }, { href: 'https://twitter.com/techinterviewhb', position: 'right', className: 'navbar-icon navbar-icon-twitter', 'aria-label': 'Twitter page', }, { href: 'https://www.facebook.com/techinterviewhandbook', position: 'right', className: 'navbar-icon navbar-icon-facebook', 'aria-label': 'Facebook page', }, ], }, footer: { copyright: `Copyright © ${new Date().getFullYear()} Tech Interview Handbook. Built with Docusaurus.`, links: [ { title: 'General', items: [ { label: 'Start reading', href: '/introduction', }, { label: 'Resume preparation', href: '/resume/guide', }, { label: 'Algorithms', href: '/algorithms/introduction', }, { label: 'Blog', href: '/blog', }, ], }, { title: 'Interviews', items: [ { label: 'Interview cheatsheet', href: '/cheatsheet', }, { label: 'Coding interviews', href: '/coding-interview', }, { label: 'System design interviews', href: '/system-design', }, { label: 'Behavioral interviews', href: '/behavioral-interview', }, ], }, { title: 'About', items: [ { label: 'GitHub', href: 'https://github.com/yangshun/tech-interview-handbook', }, { label: 'Telegram', href: 'https://t.me/techinterviewhandbook', }, { label: 'Facebook', href: 'https://www.facebook.com/techinterviewhandbook', }, { label: 'Twitter', href: 'https://twitter.com/techinterviewhb', }, ], }, { title: 'More', items: [ { label: 'Grind 75', href: 'https://www.techinterviewhandbook.org/grind75', }, {label: 'Advertise', href: '/advertise'}, { label: 'Contact us', href: 'mailto:contact@techinterviewhandbook.org', }, ], }, ], }, algolia: { appId: 'Y09P1J4IPV', apiKey: 'e12588cbae68d752469921cc46e9cb66', indexName: 'techinterviewhandbook', }, metadata: [ {name: 'fo-verify', content: '2cc93525-ece8-402e-a4b8-d1d0853175e8'}, ], }, presets: [ [ '@docusaurus/preset-classic', { docs: { path: '../contents', routeBasePath: '/', sidebarPath: require.resolve('./sidebars.js'), // showLastUpdateAuthor: true, showLastUpdateTime: true, }, theme: { customCss: require.resolve('./src/css/custom.css'), }, gtag: { trackingID: 'UA-44622716-2', }, }, ], ], plugins: [ [ '@docusaurus/plugin-client-redirects', { redirects: [ { from: '/coding-round-overview', to: '/coding-interview', }, { from: '/behavioral-round-overview', to: '/behavioral-interview', }, ], }, ], ], };
JavaScript
0.020451
@@ -204,19 +204,20 @@ gSlash: -tru +fals e,%0A fav
9c00efaafa7d6f669f501d7665baf58b8ea4b25a
update bar api page
website/src/pages/bar/api.js
website/src/pages/bar/api.js
/* * This file is part of the nivo project. * * Copyright 2016-present, Raphaël Benitte. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import React from 'react' import SEO from '../../components/seo' import ApiClient from '../../components/components/api-client/ApiClient' import { groups } from '../../data/components/bar/props' import meta from '../../data/components/bar/meta.yml' import mapper from '../../data/components/bar/mapper' import { generateLightDataSet } from '../../data/components/bar/generator' const { data, keys } = generateLightDataSet() const BarApi = () => { return ( <> <SEO title="Bar HTTP API" keywords={[...meta.Bar.tags, 'HTTP API']} /> <ApiClient componentName="Bar" chartClass="bar" apiPath="/charts/bar" flavors={meta.flavors} dataProperty="data" controlGroups={groups} propsMapper={mapper} defaultProps={{ width: 1200, height: 500, margin: { top: 40, right: 50, bottom: 40, left: 50, }, data: JSON.stringify(data, null, ' '), keys: keys, indexBy: 'country', colors: { scheme: 'nivo' }, colorBy: 'id', borderRadius: 0, borderWidth: 0, borderColor: { from: 'color', modifiers: [['darker', 1.6]], }, padding: 0.2, innerPadding: 0, minValue: 'auto', maxValue: 'auto', groupMode: 'stacked', layout: 'vertical', reverse: false, valueScale: { type: 'linear' }, indexScale: { type: 'band', round: true }, axisTop: { enable: false, tickSize: 5, tickPadding: 5, tickRotation: 0, legend: '', legendOffset: 36, }, axisRight: { enable: false, tickSize: 5, tickPadding: 5, tickRotation: 0, legend: '', legendOffset: 0, }, axisBottom: { enable: true, tickSize: 5, tickPadding: 5, tickRotation: 0, legend: 'country', legendPosition: 'middle', legendOffset: 36, }, axisLeft: { enable: true, tickSize: 5, tickPadding: 5, tickRotation: 0, legend: 'food', legendPosition: 'middle', legendOffset: -40, }, enableGridX: false, enableGridY: true, enableLabel: true, labelSkipWidth: 12, labelSkipHeight: 12, labelTextColor: { from: 'color', modifiers: [['darker', 1.6]], }, }} /> </> ) } export default BarApi
JavaScript
0.000004
@@ -2167,16 +2167,81 @@ true %7D, +%0A valueFormat: %7B format: '', enabled: false %7D, %0A%0A
04aefd9933aab3949bf45c7fb5dd270fe01ca4b8
Remove whitespace
tests/coordinateTransformTests.js
tests/coordinateTransformTests.js
var CoordinateTransforms = require('../www/CoordinateTransforms'); var expect = require('chai').expect; var PRECISION_FOR_COORDINATES = 6; var floorPlan = { "name":"Floor 4", "floorLevel":4, "bearing":177.21051025390625, "bitmapHeight":3307, "bitmapWidth":2339, "heightMeters":42.54764175415039, "widthMeters":30.09341812133789, "metersToPixels":77.72463989257812, "pixelsToMeters":0.012865932658314705, "bottomLeft":[24.9459358245201,60.17076602968721], "center":[24.94568377884345,60.170568730967204], "topLeft":[24.9459731869549,60.17038459999831], "topRight":[24.9454317331668,60.17037143224721] } var testData = { test1: { point: { x: 0, y: 0 }, coordinates: { lat: 60.17038459999831, lon: 24.9459731869549 } }, test2: { point: { x: 10, y: 10 }, coordinates: { lat: 60.170385697102745, lon: 24.94597075908071 } }, test3: { point: { x: 100, y: 200 }, coordinates: { lat: 60.170407105052, lon: 24.945947778414514 } }, test4: { point: { x: 1000, y: 1000 }, coordinates: { lat: 60.170494310441825, lon: 24.945730399535538 } }, test5: { point: { x: 0, y: 200 }, coordinates: { lat: 60.17040766801699, lon: 24.945970927357997 } } }; var boundingBox = { scale: [floorPlan.widthMeters, floorPlan.heightMeters], location: [floorPlan.center[1], floorPlan.center[0]] , rotation: (floorPlan.bearing * Math.PI) / 180, dimensions: [floorPlan.bitmapWidth, floorPlan.bitmapHeight] }; describe('pointToCoordinate', function() { it('should transform pixel point to WGS coordinates', function() { comparePointToCoordinate(boundingBox, testData.test1); comparePointToCoordinate(boundingBox, testData.test2); comparePointToCoordinate(boundingBox, testData.test3); comparePointToCoordinate(boundingBox, testData.test4); comparePointToCoordinate(boundingBox, testData.test5); }); }); describe('coordinateToPoint', function() { it('should transform WGS coordinates to pixel point', function() { compareCoordinateToPoint(boundingBox, testData.test1); compareCoordinateToPoint(boundingBox, testData.test2); compareCoordinateToPoint(boundingBox, testData.test3); compareCoordinateToPoint(boundingBox, testData.test4); compareCoordinateToPoint(boundingBox, testData.test5); }); }); function precisionRound(number, precision) { var factor = Math.pow(10, precision); return Math.round(number * factor) / factor; }; /** * Compares that given point returns correct coordinate * @param boundingBox * @param data */ function comparePointToCoordinate(boundingBox, data) { var x = data.point.x; var y = data.point.y; var coords = CoordinateTransforms.pixToWgs(boundingBox, [x, y]); expect(precisionRound(coords.latitude, PRECISION_FOR_COORDINATES)).to.be.equal(precisionRound(data.coordinates.lat, PRECISION_FOR_COORDINATES)); expect(precisionRound(coords.longitude, PRECISION_FOR_COORDINATES)).to.be.equal(precisionRound(data.coordinates.lon, PRECISION_FOR_COORDINATES)); }; /** * Compares that given coordinate returns correct pixel point * @param boundingBox * @param data */ function compareCoordinateToPoint(boundingBox, data) { var lat = data.coordinates.lat; var lon = data.coordinates.lon; var point = CoordinateTransforms.wgsToPix(boundingBox, [lat, lon]); expect(Math.round(point.x)).to.be.equal(Math.round(data.point.x)); expect(Math.round(point.y)).to.be.equal(Math.round(data.point.y)); };
JavaScript
0.999999
@@ -2672,33 +2672,32 @@ aram boundingBox - %0A * @param data @@ -2687,33 +2687,32 @@ x%0A * @param data - %0A */%0Afunction co @@ -3258,17 +3258,16 @@ ndingBox - %0A * @par @@ -3273,17 +3273,16 @@ ram data - %0A */%0Afun @@ -3472,18 +3472,16 @@ lon%5D);%0A - %0A expec
2719a0e17f3d01ba4645221df56c1391ffa2f079
Fix missing e parameter when handling HTTP errors
src/rexsterclient.js
src/rexsterclient.js
'use strict'; var http = require('http'); var querystring = require('querystring'); var Q = require("q"); var _ = require("lodash"); var GremlinScript = require('./gremlinscript'); var Graph = require("./objects/graph"); var Pipeline = require('./objects/pipeline'); var classes = require("./classes/classes"); var ResultFormatter = require("./resultformatter"); module.exports = (function(){ function RexsterClient(options) { this.defaultOptions = { host: 'localhost', port: 8182, graph: 'tinkergraph' }; this.options = _.defaults(options, this.defaultOptions); this.resultFormatter = new ResultFormatter(); _.extend(this, classes); this.ClassTypes = classes; } Object.defineProperty(RexsterClient.prototype, 'g', { get: function() { var graph = new Graph('g'); return graph; } }); Object.defineProperty(RexsterClient.prototype, '_', { get: function() { return function() { return new Pipeline('_()'); }; } }); /** * Establish a connection with Rexster server. * While this method currently has an asynchronous behavior, it actually * does synchronous stuff. * * Accept the double promise/callback API. * * @param {Function} callback */ RexsterClient.prototype.connect = function(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } this.options = _.defaults(options || {}, this.defaultOptions); this.fetchHandler = this.options.fetched || this.defaultFetchHandler; return Q.fcall(function() { return this; }.bind(this)) .nodeify(callback); }; /** * Send a GremlinScript script to Rexster for execution via HTTP, fetch and format * results. * * @param {GremlinScript} gremlin A Gremlin-Groovy script to execute */ RexsterClient.prototype.exec = function(gremlin) { var deferred = Q.defer(); var qs = { script: gremlin.script.replace(/\$/g, "\\$"), 'rexster.showTypes': true }; // Build custom bound parameters string var paramString = '&'+ _.map(gremlin.params, function(value, key) { return 'params.'+ key +'='+ value; }).join('&'); var options = { hostname: this.options.host, port: this.options.port, path: '/graphs/' + this.options.graph + '/tp/gremlin?' + querystring.stringify(qs) + paramString, headers: { 'Content-type': 'application/json' } }; var req = http.get(options, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { body = JSON.parse(body); var transformedResults = this.transformResults(body.results); body.results = transformedResults.results; body.typeMap = transformedResults.typeMap; return deferred.resolve(body); }.bind(this)); }.bind(this)); req.on('error', function() { return deferred.reject(e); }); return deferred.promise; }; /** * Send a Gremlin script to Rexster for execution via HTTP, fetch and format * results as instantiated elements (typically Vertices and Edges). * * @param {GremlinScript} gremlin */ RexsterClient.prototype.fetch = function(gremlin) { return this.exec(gremlin) .then(function(response) { return this.fetchHandler(response, response.results); }.bind(this)); }; /** * A noop, default handler for RexsterClient.fetch(). * * @param {String} response - the complete HTTP response body * @param {Array} results - array of results, shorthand for response.results */ RexsterClient.prototype.defaultFetchHandler = function(response, results) { return results; }; Object.defineProperty(RexsterClient.prototype, 'gremlin', { get: function() { return this.createGremlinScript.bind(this) } }) /** * Instantiate a new GremlinScript and return a function responsible * for appending bits of Gremlin to this GremlinScript. * * @return {Function} appender */ RexsterClient.prototype.createGremlinScript = function(statement) { var gremlinScript = new GremlinScript(this); var appender = gremlinScript.getAppender(); appender.apply(appender, arguments); return appender; }; RexsterClient.prototype.transformResults = function(results) { return this.resultFormatter.formatResults(results); }; return RexsterClient; })();
JavaScript
0.000013
@@ -2975,32 +2975,33 @@ rror', function( +e ) %7B%0A return
07137a11ac5a14f3b4d660b936802e484e14af05
Remove logUrlCache from project dashboard log feed.
website/static/js/logFeed.js
website/static/js/logFeed.js
'use strict'; var $ = require('jquery'); // jQuery var m = require('mithril'); // exposes mithril methods, useful for redraw etc. var $osf = require('js/osfHelpers'); var Raven = require('raven-js'); var LogText = require('js/logTextParser'); var mC = require('js/mithrilComponents'); /* Send with ajax calls to work with api2 */ var xhrconfig = function (xhr) { xhr.withCredentials = window.contextVars.isOnRootDomain, xhr.setRequestHeader('Content-Type', 'application/vnd.api+json;'); xhr.setRequestHeader('Accept', 'application/vnd.api+json; ext=bulk'); }; var LogFeed = { controller: function(options) { var self = this; self.node = options.node; self.activityLogs = m.prop(); self.logRequestPending = false; self.showMoreActivityLogs = m.prop(null); self.logUrlCache = {}; self.getLogs = function _getLogs (url, addToExistingList) { var cachedResults; if(!addToExistingList){ self.activityLogs([]); // Empty logs from other projects while load is happening; self.showMoreActivityLogs(null); } function _processResults (result){ self.logUrlCache[url] = result; result.data.map(function(log){ log.attributes.formattableDate = new $osf.FormattableDate(log.attributes.date); if(addToExistingList){ self.activityLogs().push(log); } }); if(!addToExistingList){ self.activityLogs(result.data); // Set activity log data } self.showMoreActivityLogs(result.links.next); // Set view for show more button } if(self.logUrlCache[url]){ cachedResults = self.logUrlCache[url]; _processResults(cachedResults); } else { self.logRequestPending = true; var promise = m.request({method : 'GET', url : url, config : xhrconfig}); promise.then(_processResults); promise.then(function(){ self.logRequestPending = false; }); return promise; } }; self.getCurrentLogs = function _getCurrentLogs (node){ if(!self.logRequestPending) { if (!node.is_retracted) { var urlPrefix = node.is_registration ? 'registrations' : 'nodes'; var query = node.link ? { 'page[size]': 6, 'embed': ['original_node', 'user', 'linked_node', 'template_node'], 'view_only': node.link} : { 'page[size]': 6, 'embed': ['original_node', 'user', 'linked_node', 'template_node']}; var url = $osf.apiV2Url(urlPrefix + '/' + node.id + '/logs/', { query: query}); var promise = self.getLogs(url); return promise; } } }; self.getCurrentLogs(self.node); }, view : function (ctrl) { return m('.db-activity-list.m-t-md', [ ctrl.activityLogs() ? ctrl.activityLogs().map(function(item){ if (ctrl.node.anonymous) { item.anonymous = true; } var image = m('i.fa.fa-desktop'); if (!item.anonymous && item.embeds.user && item.embeds.user.data) { image = m('img', { src : item.embeds.user.data.links.profile_image}); } else if (!item.anonymous && item.embeds.user && item.embeds.user.errors[0].meta){ image = m('img', { src : item.embeds.user.errors[0].meta.profile_image}); } return m('.db-activity-item', [ m('', [ m('.db-log-avatar.m-r-xs', image), m.component(LogText, item)]), m('.text-right', m('span.text-muted.m-r-xs', item.attributes.formattableDate.local))]); }) : '', m('.db-activity-nav.text-center', [ ctrl.showMoreActivityLogs() ? m('.btn.btn-sm.btn-link', { onclick: function(){ ctrl.getLogs(ctrl.showMoreActivityLogs(), true); $osf.trackClick('myProjects', 'information-panel', 'show-more-activity'); }}, [ 'Show more', m('i.fa.fa-caret-down.m-l-xs')]) : '' ]) ]); } }; module.exports = { LogFeed: LogFeed };
JavaScript
0
@@ -166,41 +166,8 @@ ');%0A -var Raven = require('raven-js');%0A var @@ -209,51 +209,8 @@ ');%0A -var mC = require('js/mithrilComponents');%0A%0A %0A/* @@ -572,17 +572,16 @@ = this;%0A -%0A @@ -737,39 +737,8 @@ ll); -%0A self.logUrlCache = %7B%7D; %0A%0A @@ -807,39 +807,8 @@ ) %7B%0A - var cachedResults;%0A @@ -1052,56 +1052,8 @@ t)%7B%0A - self.logUrlCache%5Burl%5D = result;%0A @@ -1585,175 +1585,8 @@ %7D%0A%0A - if(self.logUrlCache%5Burl%5D)%7B%0A cachedResults = self.logUrlCache%5Burl%5D;%0A _processResults(cachedResults);%0A %7D else %7B%0A @@ -1624,20 +1624,16 @@ = true;%0A - @@ -1714,36 +1714,32 @@ %7D);%0A - promise.then(_pr @@ -1757,36 +1757,32 @@ s);%0A - - promise.then(fun @@ -1782,36 +1782,32 @@ hen(function()%7B%0A - @@ -1838,36 +1838,16 @@ false;%0A - %7D);%0A @@ -1875,33 +1875,34 @@ e;%0A %7D -%0A +); %0A %7D;%0A%0A @@ -2686,17 +2686,16 @@ ctrl) %7B%0A -%0A @@ -3729,32 +3729,32 @@ ck: function()%7B%0A + @@ -3810,102 +3810,8 @@ e);%0A - $osf.trackClick('myProjects', 'information-panel', 'show-more-activity');%0A
4ee9bfc5520448e8fa8547a2ed1577c4bdf6488f
Fix settings for tests
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, contentSecurityPolicy: { 'default-src': "'none'", 'script-src': "'self'", 'font-src': "'self' https://maxcdn.bootstrapcdn.com", 'connect-src': "'self'", 'img-src': "'self'", 'style-src': "'self' 'unsafe-inline' https://maxcdn.bootstrapcdn.com", 'media-src': "'self'" } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; ENV.API_URL = ''; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-cli-simple-auth-token'; ENV.API_URL = 'https://simple-auth-token-server.herokuapp.com'; } ENV['simple-auth'] = { authorizer: 'simple-auth-authorizer:token', applicationRootUrl: ENV.baseURL, crossOriginWhitelist: [ENV.API_URL] }; ENV['simple-auth-token'] = { serverTokenEndpoint: ENV['API_URL'] + '/api/api-token-auth/', serverTokenRefreshEndpoint: ENV['API_URL'] + '/api/api-token-refresh/', timeFactor: 1000, refreshLeeway: 5 }; return ENV; };
JavaScript
0
@@ -831,232 +831,324 @@ -// ENV.APP.LOG_RESOLVER = true;%0A // ENV.APP.LOG_ACTIVE_GENERATION = true;%0A // ENV.APP.LOG_TRANSITIONS = true;%0A // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;%0A // ENV.APP.LOG_VIEW_LOOKUPS = true;%0A ENV.API_URL = '' +ENV%5B'simple-auth'%5D = %7B%0A authorizer: 'simple-auth-authorizer:token',%0A applicationRootUrl: ENV.baseURL%0A %7D;%0A%0A ENV%5B'simple-auth-token'%5D = %7B%0A serverTokenEndpoint: '/api/api-token-auth/',%0A serverTokenRefreshEndpoint: '/api/api-token-refresh/',%0A timeFactor: 1000,%0A refreshLeeway: 5%0A %7D ;%0A @@ -1594,21 +1594,19 @@ p.com';%0A +%0A -%7D%0A%0A ENV%5B's @@ -1618,24 +1618,26 @@ -auth'%5D = %7B%0A + authoriz @@ -1672,24 +1672,26 @@ token',%0A + + applicationR @@ -1711,16 +1711,18 @@ aseURL,%0A + cros @@ -1755,20 +1755,24 @@ _URL%5D%0A + + %7D;%0A%0A + ENV%5B's @@ -1794,24 +1794,26 @@ n'%5D = %7B%0A + serverTokenE @@ -1858,24 +1858,26 @@ ken-auth/',%0A + serverTo @@ -1940,24 +1940,26 @@ resh/',%0A + timeFactor: @@ -1964,24 +1964,26 @@ : 1000,%0A + + refreshLeewa @@ -1989,18 +1989,24 @@ ay: 5%0A + %7D;%0A %7D -; %0A%0A retu
76f3ef9df6be4ec2edf3d08dc103059cbd4f943a
switch to 'hash' location for gh-pages
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { // For github pages ENV.baseURL = '/ember-cli-nouislider'; } return ENV; };
JavaScript
0.000005
@@ -1108,16 +1108,46 @@ lider';%0A + ENV.locationType = 'hash'%0A %7D%0A%0A r
a06bf49054cef8924dad070d24309ba6c5cf0fbe
add name to sound
audio/Sound.js
audio/Sound.js
let sounds = new Set(); let soundsMap = new Map(); let muted = false; let loopMuted = false; export default class Sound { static set muted(value) { muted = value; for (let sound of sounds) { sound.muted = sound.muted; } } static get muted() { return muted; } static set loopMuted(value) { loopMuted = value; for (let sound of sounds) { sound.muted = sound.muted; } } static get loopMuted() { return loopMuted; } static add(src) { let sound = new Sound(src); return sound; } static get(name) { return soundsMap.get(name); } constructor(src, { name = /([^\\\/]*)\..*$/.exec(src)[1], amplification = 1 } = {}) { sounds.add(this); soundsMap.set(name, this); this._audio = document.createElement("audio"); this._audio.src = src; this.amplification = amplification; this.volume = 1; this.muted = muted; } get src() { return this._audio.src; } set src(value) { this._audio.src = value; } get muted() { return this._audio.muted; } set muted(value) { this._muted = value; this._audio.muted = muted || loopMuted && this.loop ? true : value; } get loop() { return this._audio.loop; } set loop(value) { this.muted = this.muted; this._audio.loop = value; } get currentTime() { return this._audio.currentTime; } set currentTime(value) { this._audio.currentTime = value; } get volume() { return this._volume; } set volume(value) { this._volume = value; this._audio.volume = this._volume * this.amplification; } play() { this._audio.play(); } stop() { this.currentTime = 0; this.pause(); } pause() { this._audio.pause(); } cloneNode() { let sound = new Sound(this.src); sound.volume = this.volume; sound.muted = this.muted; sound.loop = this.loop; sound.currentTime = this.currentTime; return sound; } } Sound.muted = /\bmuted\b/.test(window.location.search); Sound.loopMuted = /\bloopmuted\b/.test(window.location.search);
JavaScript
0.000007
@@ -698,24 +698,47 @@ %7D = %7B%7D) %7B%0A + this.name = name;%0A%0A sounds.a @@ -765,16 +765,21 @@ Map.set( +this. name, th @@ -1083,30 +1083,24 @@ eturn this._ -audio. muted;%0A %7D%0A%0A
0ae27c8cde25764d10dc32478bed347541bb8f32
Use localhost instead of 127.0.0.1
nightwatch.e2e.conf.js
nightwatch.e2e.conf.js
var seleniumServer = require('selenium-server-standalone-jar') , chromedriver = require('chromedriver') , phantomjs = require('phantomjs-prebuilt'); var launchUrl = (process.env.LAUNCH_URL) ? process.env.LAUNCH_URL : 'http://localhost:3000'; module.exports = { src_folders: ['test/e2e'], output_folder: '.reports', globals_path: 'nightwatch.globals.js', test_workers: { enabled: true, workers: 'auto' }, selenium : { start_process : true, server_path: seleniumServer.path, log_path : '', host : '127.0.0.1', port : 4444 }, test_settings: { default: { launch_url: launchUrl, selenium_port: 4444, selenium_host: 'localhost', silent: true, screenshots: { enabled: true, on_failure: true, on_error: true, path: '.screenshots' }, desiredCapabilities: { browserName: 'phantomjs', javascriptEnabled: true, acceptSslCerts: true, 'phantomjs.binary.path' : phantomjs.path } }, chrome: { desiredCapabilities: { browserName: 'chrome', javascriptEnabled: true, acceptSslCerts: true, chromeOptions: { args: ['--no-sandbox'] }, cli_args: { 'webdriver.chrome.driver': chromedriver.path } } }, firefox: { desiredCapabilities: { browserName: 'firefox', javascriptEnabled: true, acceptSslCerts: true } } } };
JavaScript
0.004915
@@ -536,17 +536,17 @@ : ' -127.0.0.1 +localhost ',%0A
aa29ed9b2fe70bfae24da8dbaafd462191b2a385
fix reset
addon/multiton-services/ember-theater/director/scene/curtain-pulley.js
addon/multiton-services/ember-theater/director/scene/curtain-pulley.js
import Ember from 'ember'; import multitonService from 'ember-theater/macros/ember-theater/multiton-service'; import BusPublisherMixin from 'ember-theater/mixins/bus-publisher'; import BusSubscriberMixin from 'ember-theater/mixins/bus-subscriber'; import MultitonIdsMixin from 'ember-theater/mixins/ember-theater/multiton-ids'; const { get, getProperties, isEmpty, isPresent, on } = Ember; export default Ember.Object.extend(BusPublisherMixin, BusSubscriberMixin, MultitonIdsMixin, { saveStateManager: multitonService('ember-theater/save-state-manager', 'theaterId'), sceneManager: multitonService('ember-theater/director/scene-manager', 'theaterId', 'windowId'), setupEvents: on('init', function() { const { theaterId, windowId } = getProperties(this, 'theaterId', 'windowId'); this.on(`et:${theaterId}:${windowId}:gameIsResetting`, this, this.toInitialScene); this.on(`et:${theaterId}:${windowId}:saveIsLoading`, this, this.loadScene); }), loadLatestScene: async function() { const saveStateManager = get(this, 'saveStateManager'); const options = { autosave: false }; const save = await saveStateManager.get('mostRecentSave'); if (isPresent(save)) { const sceneId = get(save, 'activeState.sceneId'); this.loadScene(save, sceneId, options); } else { this.toInitialScene(); } }, toInitialScene() { const sceneId = get(this, 'sceneManager.initialScene'); get(this, 'sceneManager').toScene(sceneId, { autosave: false }); }, loadScene(save, sceneId, options) { const { saveStateManager, sceneManager, theaterId } = getProperties(this, 'saveStateManager', 'sceneManager', 'theaterId'); saveStateManager.loadRecord(save); this.publish(`et:${theaterId}:reseting`); options.sceneRecord = saveStateManager.getStateValue('_sceneRecord') || {}; sceneManager.toScene(sceneId, options); } });
JavaScript
0.000002
@@ -722,18 +722,16 @@ const - %7B theater @@ -736,36 +736,14 @@ erId -, windowId %7D = getProperties + = get (thi @@ -756,28 +756,16 @@ eaterId' -, 'windowId' );%0A%0A @@ -789,28 +789,16 @@ aterId%7D: -$%7BwindowId%7D: gameIsRe @@ -868,20 +868,8 @@ Id%7D: -$%7BwindowId%7D: save
6834f73d95e4ded66c2729507c714d1ac34dacd0
Reconnect on connection losses
azureiothub.js
azureiothub.js
module.exports = function (RED) { var Client = require('azure-iot-device').Client; var Registry = require('azure-iothub').Registry; var Message = require('azure-iot-device').Message; var Protocols = { amqp: require('azure-iot-device-amqp').Amqp, mqtt: require('azure-iot-device-mqtt').Mqtt, http: require('azure-iot-device-http').Http, amqpWs: require('azure-iot-device-amqp-ws').AmqpWs }; var client = null; var clientConnectionString = ""; var newConnectionString = ""; var newProtocol = ""; var clientProtocol = ""; var statusEnum = { disconnected: { color: "red", text: "Disconnected" }, connected: { color: "green", text: "Connected" }, sent: { color: "blue", text: "Sent message" }, received: { color: "yellow", text: "Received" }, error: { color: "grey", text: "Error" } }; var setStatus = function (node, status) { node.status({ fill: status.color, shape: "dot", text: status.text }); } var sendData = function (node, data) { node.log('Sending Message to Azure IoT Hub :\n Payload: ' + JSON.stringify(data)); // Create a message and send it to the IoT Hub every second var message = new Message(JSON.stringify(data)); client.sendEvent(message, function (err, res) { if (err) { node.error('Error while trying to send message:' + err.toString()); setStatus(node, statusEnum.error); } else { node.log('Message sent.'); node.send({payload: "Message sent."}); setStatus(node, statusEnum.sent); } }); }; var sendMessageToIoTHub = function (node, message, reconnect) { if (!client || reconnect) { node.log('Connection to IoT Hub not established or configuration changed. Reconnecting.'); // Update the connection string clientConnectionString = newConnectionString; // update the protocol clientProtocol = newProtocol; // If client was previously connected, disconnect first if (client) disconnectFromIoTHub(node); // Connect the IoT Hub connectToIoTHub(node, message); } else { sendData(node, message); } }; var connectToIoTHub = function (node, pendingMessage) { node.log('Connecting to Azure IoT Hub:\n Protocol: ' + newProtocol + '\n Connection string :' + newConnectionString); client = Client.fromConnectionString(newConnectionString, Protocols[newProtocol]); client.open(function (err) { if (err) { node.error('Could not connect: ' + err.message); setStatus(node, statusEnum.disconnected); } else { node.log('Connected to Azure IoT Hub.'); setStatus(node, statusEnum.connected); // Check if a message is pending and send it if (pendingMessage) { node.log('Message is pending. Sending it to Azure IoT Hub.'); // Send the pending message sendData(node, pendingMessage); } client.on('message', function (msg) { // We received a message node.log('Message received from Azure IoT Hub\n Id: ' + msg.messageId + '\n Payload: ' + msg.data); var outpuMessage = new Message(); outpuMessage.payload = msg.data; setStatus(node, statusEnum.received); node.log(JSON.stringify(outpuMessage)); node.send(outpuMessage); client.complete(msg, printResultFor(node,'Completed')); }); client.on('error', function (err) { node.error(err.message); }); client.on('disconnect', function () { disconnectFromIoTHub(node); }); } }); }; var disconnectFromIoTHub = function (node) { if (client) { node.log('Disconnecting from Azure IoT Hub'); client.removeAllListeners(); client.close(printResultFor('close')); client = null; setStatus(node, statusEnum.disconnected); } }; function nodeConfigUpdated(cs, proto) { return ((clientConnectionString != cs) || (clientProtocol != proto)); } // Main function called by Node-RED function AzureIoTHubNode(config) { // Store node for further use var node = this; //nodeConfig = config; // Create the Node-RED node RED.nodes.createNode(this, config); node.on('input', function (msg) { var messageJSON = null; if (typeof (msg.payload) != "string") { node.log("JSON"); messageJSON = msg.payload; } else { node.log("String"); //Converting string to JSON Object //Sample string: {"deviceId": "name", "key": "jsadhjahdue7230-=13", "protocol": "amqp", "data": "25"} messageJSON = JSON.parse(msg.payload); } //Creating connectionString //Sample //HostName=sample.azure-devices.net;DeviceId=sampleDevice;SharedAccessKey=wddU//P8fdfbSBDbIdghZAoSSS5gPhIZREhy3Zcv0JU= newConnectionString = "HostName=" + node.credentials.hostname + ";DeviceId=" + messageJSON.deviceId + ";SharedAccessKey=" + messageJSON.key newProtocol = messageJSON.protocol; // Sending data to Azure IoT Hub Hub using specific connectionString sendMessageToIoTHub(node, messageJSON.data, nodeConfigUpdated(newConnectionString, newProtocol)); }); node.on('close', function () { disconnectFromIoTHub(node, this); }); } function IoTHubRegistry(config) { RED.nodes.createNode(this, config); var node = this; node.on('input', function (msg) { if (typeof (msg.payload) == 'string') { msg.payload = JSON.parse(msg.payload); } var registry = Registry.fromConnectionString(node.credentials.connectionString); registry.create(msg.payload, function (err, device) { if (err) { node.error('Error while trying to create a new device: ' + err.toString()); setStatus(node, statusEnum.error); } else { node.log("Device created: " + JSON.stringify(device)); node.log("Device ID: " + device.deviceId + " - primaryKey: " + device.authentication.SymmetricKey.primaryKey + " - secondaryKey: " + device.authentication.SymmetricKey.secondaryKey); node.send("Device ID: " + device.deviceId + " - primaryKey: " + device.authentication.SymmetricKey.primaryKey + " - secondaryKey: " + device.authentication.SymmetricKey.secondaryKey); } }); }); node.on('close', function () { disconnectFromIoTHub(node, this); }); } // Registration of the node into Node-RED RED.nodes.registerType("azureiothub", AzureIoTHubNode, { credentials: { hostname: { type: "text" } }, defaults: { name: { value: "Azure IoT Hub" }, protocol: { value: "amqp" } } }); // Registration of the node into Node-RED RED.nodes.registerType("azureiothubregistry", IoTHubRegistry, { credentials: { connectionString: { type: "text" } }, defaults: { name: { value: "Azure IoT Hub Registry" }, } }); // Helper function to print results in the console function printResultFor(node, op) { return function printResult(err, res) { if (err) node.error(op + ' error: ' + err.toString()); if (res) node.log(op + ' status: ' + res.constructor.name); }; } }
JavaScript
0
@@ -2839,32 +2839,102 @@ .disconnected);%0A + // works for me..%0A client = undefined;%0A %7D el @@ -8296,8 +8296,9 @@ %0A %7D%0A%7D +%0A
94a91d9c5a65edf166dbae6dae60fb427cfa05ed
add forgotten string to pt-BR localisation file.
actor-apps/app-web/src/app/l18n/pt-BR.js
actor-apps/app-web/src/app/l18n/pt-BR.js
export default { 'locales': 'pt-BR', 'messages': { // Login 'login': { 'signIn': 'Entrar', 'wrong': 'Errado?', 'phone': 'Numero do celular', 'authCode': 'Código de autenticação', 'yourName': 'Seu nome', 'errors': { 'numberInvalid': 'Numero inválido', 'nameInvalid': 'Nome inválido', 'codeInvalid': 'Código inválido', 'codeExpired': 'Este código expirou', 'codeWait': 'Try to request code later' } }, // Menus 'menu': { // Sidebar menu 'editProfile': 'Editar perfil', 'addToContacts': 'Adicionar contato', 'configureIntegrations': 'Configure Integrações', 'helpAndFeedback': 'Ajuda & Feedback', 'twitter': 'Nosso twitter', 'preferences': 'Preferências', 'signOut': 'Sair' }, // Buttons 'button': { 'ok': 'Ok', 'cancel': 'Cancelar', 'done': 'Feito', 'requestCode': 'Requesitar código', 'checkCode': 'Checar código', 'signUp': 'Cadastrar', 'add': 'Adicionar' }, // Messages 'message': { 'download': 'Download', 'delete': 'Deletar' }, // Toolbar 'search': 'Busca', // Compose 'compose': { 'sendFile': 'Enviar arquivo', 'sendPhoto': 'Enviar foto', 'send': 'Enviar', 'markdown': { 'bold': 'bold', 'italic': 'italico', 'preformatted': 'pré formatado' } }, // Modals 'modal': { 'profile': { 'title': 'Perfil', 'name': 'Nome completo', 'nick': 'Apelido', 'phone': 'Numero de celular', 'about': 'Sobre', 'avatarChange': 'Mudar foto', 'avatarRemove': 'Remover' }, 'group': { 'title': 'Editar grupo', 'name': 'Nome do grupo', 'about': 'Sobre o grupo', 'avatarChange': 'Mudar imagem', 'avatarRemove': 'Remover' }, 'crop': { 'title': 'Cortat imagem' } }, // Profiles 'createdBy': 'сriado por', 'addPeople': 'Adicionar pessoas', 'more': 'Mais', 'actions': 'Ações', 'addToContacts': 'Adicionar a contatos', 'removeFromContacts': 'Remover dos contatos', 'setGroupPhoto': 'Escolhe uma imagem do grupo', 'addIntegration': 'Adicionar um serviço integrado', 'editGroup': 'Editar Grupo', 'clearGroup': 'Limpar Grupo', 'deleteGroup': 'Deletar Grupo', 'clearConversation': 'Limpar Conversa', 'deleteConversation': 'Deletar Conversa', 'leaveGroup': 'Sair do Grupo', 'sharedMedia': 'Media Compartilhada', 'notifications': 'Notificações', 'integrationTokenCopied': 'Link de integração.', 'membros': '{numMembers, plural,' + '=0 {sem Membros}' + '=1 {# Membro}' + 'other {# Membros}' + '}', // Modals 'inviteModalTitle': 'Adicionar mais pessoas', 'inviteModalSearch': 'Procure por contatos ou usuarios', 'inviteModalNotFound': 'Desculpe, sem usuários encontrados.', 'inviteByLink': 'Convidar para o grupo via link', 'inviteByLinkModalTitle': 'Convidar por link', 'inviteByLinkModalDescription': 'Qualquer pessoa na web será capaz de juntar-se a ”{groupName}” Abrindo este link:', 'inviteByLinkModalCopyButton': 'Copiar link', 'inviteByLinkModalRevokeButton': 'Revogar link', 'inviteLinkCopied': 'Link de convite copiado.', 'preferencesModalTitle': 'Preferências', 'preferencesGeneralTab': 'Geral', 'preferencesNotificationsTab': 'Notificaões & Sons', 'preferencesSecurityTab': 'Segurança', 'preferencesSendMessageTitle': 'Enviar Mensagem', 'preferencesSendMessage': 'enviar mensagem', 'preferencesNewLine': 'nova linha', 'preferencesEffectsTitle': 'Efeitos', 'preferencesEnableEffects': 'Habilitar sons e efeitos', 'preferencesNotificationsTitle': 'Notificações', 'preferencesNotificationsGroup': 'Habilitar notificações do grupo', 'preferencesNotificationsOnlyMention': 'Ativar apenas notificações com menções', 'preferencesNotificationsOnlyMentionHint': 'Você pode ativar as notificações apenas para mensagens que contém menções a você.', 'preferencesPrivacyTitle': 'Privacidade', 'preferencesMessagePreview': 'Preview de mensagens', 'preferencesMessagePreviewHint': 'Remover textos das notificações.', 'preferencesSessionsTitle': 'Sessões ativas', 'preferencesSessionsCurrentSession': 'Sessão atual', 'preferencesSessionsAuthTime': 'Tempo logado', 'preferencesSessionsTerminate': 'Matar sessão', 'preferencesSessionsTerminateAll': 'Terminar todas seções', 'createGroupModalTitle': 'Criar Grupo', 'createGroupButton': 'Criar grupo', 'createGroupGroupName': 'Grupo', 'createGroupAddMembers': 'Adicionar usuários', 'addContactModalTitle': 'Adicionar contato', 'addContactPhoneNumber': 'Numero do celular', 'addContactAdd': 'Add', 'addContactNotRegistered': 'Este numero não esta registrado no Actor.', 'addContactInContacts': 'Você ja possui esta pessoa em seus contatos.' } };
JavaScript
0
@@ -619,24 +619,60 @@ r contato',%0A + 'createGroup': 'Criar Grupo',%0A 'confi
592c45f7a548dd7374013612a34ed6757b41d637
fix webpack dev build
actor-apps/app-web/webpack.config.dev.js
actor-apps/app-web/webpack.config.dev.js
import path from 'path'; import webpack from 'webpack'; export default { cache: true, debug: true, devtool: 'inline-source-map', hotComponents: true, entry: { app: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/dev-server', './src/app/index.js' ], styles: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/dev-server', './src/styles' ] }, output: { path: path.join(__dirname, 'dist/assets'), publicPath: 'assets/', filename: '[name].js', chunkFilename: '[chunkhash].js', sourceMapFilename: '[name].map' }, resolve: { modulesDirectories: ['node_modules'], root: [ path.join(__dirname, 'src/app') ] }, module: { preLoaders: [ { test: /\.js$/, loaders: ['eslint', 'source-map'], exclude: /node_modules/ } ], loaders: [ // Styles { test: /\.(scss|css)$/, loaders: [ 'react-hot', 'style', 'css', 'autoprefixer?browsers=last 3 versions', 'sass?outputStyle=expanded&indentedSyntax' + 'includePaths[]=' + (path.resolve(__dirname, './node_modules')) ] }, // JavaScript { test: /\.js$/, loaders: [ 'react-hot', 'babel?optional[]=es7.classProperties' + '&optional[]=es7.decorators' ], exclude: /(node_modules)/ },{ test: /\.json$/, loaders: ['json'] }, // Assets { test: /\.(png|mp3)$/, loaders: ['file?name=[name].[ext]'] }, // Fonts { test: /\.(ttf|eot|svg|woff|woff2)$/, loaders: ['file?name=fonts/[name].[ext]'] } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('development') } }), new webpack.ResolverPlugin([ new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('package.json', ['main']) ]), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], eslint: { configFile: './.eslintrc' } };
JavaScript
0.000088
@@ -2044,16 +2044,29 @@ '%5D)%0A +%5D, %5B'context' %5D),%0A
15e398d3486ed44238089ed7ee836eb332a5312e
add spot for stdout test in second command.
src/tap/ingestion.js
src/tap/ingestion.js
/** * ingestion.js * expects: * 1. path of directory * 2. parentpid * 3. namespace * 4. model * (note: basic image,large image,audio,video, collection, pdf, binary -- all require * the "ibsp" in the command string, book requires the "ibbp" part in the drush command.) * output: * log of drush run * errors: * if parameters missing * if first command did not run * if first command did run but did not prep ingest * if first command ran with a good ingest but second command did not run * if second ran but did not ingest * * @param target directory path * @param parentpid * @param namespace * @param model * @return $message * */ // for testing // var param = process.argv; console.log('hi'); target = String(param[2]); parentpid = String(param[3]); namespace = String(param[4]); model = String(param[5]); function ingestion(target,parentpid,namespace,model) { // build command pieces // serveruri is the location of the drupal_home on the drupal server let drupalhome = '/vhosts/dlwork/web/collections'; let serveruri = 'http://dlwork.lib.utk.edu/dev/'; console.log('parentpid = '.parentpid.'\n'); // namespace console.log('namespace = '.namespace.'\n'); // target is the local directory holding the ingest files console.log('target = '.target.'\n'); // make mongo connection /* var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/ibu'); var conn = mongoose.connection; */ // var $message = 'ingest did not happen'; var contentmodel = ''; if ((model)&& (model==='basic')) { contentmodel = 'islandora:sp_basic_image'; } if ((model)&&(model==='large')) { contentmodel = 'islandora:sp_Large_image'; } console.log('model = '.model.'\n'); // execute first drush command var exec = require('child_process').exec; var cmd = 'drush -r '.drupalhome.'-v -u=1 --uri='.serveruri.' ibsp --content_models='.contentmodel.' --type=directory --parent='.parentpid.' --namespace='.namespace.' --target='target; if ((target!='')&&(contentmodel!='')&&(parentpid!='')&&(namespace!='')) { exec(cmd, function(error, stdout, stderr) { // command output is in stdout //console.log(stdout); // test command log for success indication // test for substr in stdout $message = 'ingest prep drush command success'; status.push("$message"); }); }// end if else { console.log('parameters for first command missing\n'); $message = 'parameters for first command missing'; return $message; } // exec second drush command //var exec2 = require('child_process').exec; var cmd2 = 'drush -r '.drupalhome.'-v -u=1 --uri='.serveruri.' islandora_batch_ingest'; if ($message = 'ingest prep drush command success') { exec(cmd2, function(error, stdout, stderr) { // command output is in stdout console.log(stdout); $message = 'ingest drush command success'; status.push("$message"); }); }// end if return $message; }// end function //export default ingestion; ingestion();
JavaScript
0
@@ -2175,18 +2175,16 @@ ut%0A -// console. @@ -2868,24 +2868,106 @@ og(stdout);%0A + // test command log for success indication%0A // test for substr in stdout%0A $messag
b4431bf182f48a4e6336cc48a8ce9b32615e229c
make countdown to be 3 secs
app/js/main.js
app/js/main.js
// Deal with web components before anything else require('webcomponents-lite'); require('./moz-select').register('moz-select'); var Boo = require('./Boo.js'); window.onload = function () { var boo; var videoEffectSelector = document.getElementById('videoEffect'); var audioEffectSelector = document.getElementById('audioEffect'); var downloadButton = document.getElementById('download'); var recordButton = document.getElementById('record'); var countdown = document.getElementById('countdown'); var videoData; navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function (stream) { var boo = new Boo( stream, document.getElementById('booth-original'), document.getElementById('booth-filtered'), document.getElementById('booth-progress') ); boo.on('ready', function () { recordButton.disabled = false; downloadButton.disabled = true; countdown.style = 'display:none'; videoEffectSelector.options = boo.getVideoEffects(); // 0 is none--start with some effect applied already! videoEffectSelector.selectedIndex = 1; videoEffectSelector.disabled = false; videoEffectSelector.addEventListener('selectedIndex', function(ev) { boo.selectVideoEffect(ev.detail.value); }); audioEffectSelector.options = boo.getAudioEffects(); audioEffectSelector.addEventListener('selectedIndex', function(ev) { boo.selectAudioEffect(ev.detail.value); }); }); boo.on('finished', function (data) { recordButton.disabled = false; downloadButton.disabled = false; videoData = data; }); recordButton.addEventListener('click', function () { videoData = null; recordButton.disabled = true; downloadButton.disabled = true; countdown.style = ''; var number = countdown.querySelector('.number'); var countdownTime = 5; // seconds number.innerHTML = countdownTime; var interval = setInterval(function () { countdownTime--; number.innerHTML = countdownTime; if (countdownTime <= 0) { clearInterval(interval); countdown.style = 'display:none'; boo.record(); } }, 1000); }); downloadButton.addEventListener('click', function () { downloadButton.disabled = true; var link = document.createElement('a'); link.setAttribute('href', window.URL.createObjectURL(videoData)); link.setAttribute('download', 'video.webm'); link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); }); }); };
JavaScript
0.999993
@@ -1555,19 +1555,16 @@ %09%09%7D);%0A%0A%0A -%09%09%09 %0A @@ -2054,9 +2054,9 @@ e = -5 +3 ; //
a3386893a8a525c8bb6a53f974c571b79ea8eedb
Remove baseUrl
app/js/main.js
app/js/main.js
require.config({ paths: { angular: '../../bower_components/angular/angular', angularRoute: '../../bower_components/angular-route/angular-route', angularMocks: '../../bower_components/angular-mocks/angular-mocks', text: '../../bower_components/requirejs-text/text' }, baseUrl: 'app/js', shim: { 'angular' : {'exports' : 'angular'}, 'angularRoute': ['angular'], 'angularMocks': { deps:['angular'], 'exports':'angular.mock' } }, priority: [ "angular" ] }); require( [ 'angular', 'app', 'routes' ], function(angular, app, routes) { 'use strict'; var $html = angular.element(document.getElementsByTagName('html')[0]); angular.element().ready(function() { $html.addClass('ng-app'); angular.bootstrap($html, [app['name']]); }); });
JavaScript
0
@@ -274,28 +274,8 @@ %09%7D,%0A -%09baseUrl: 'app/js',%0A %09shi
78f8fad3046bf5f8f32e31f4554e6cf35aefda99
Refactor onload function for less nesting
app/js/main.js
app/js/main.js
// Deal with web components before anything else require('webcomponents-lite'); require('./moz-select').register('moz-select'); var Boo = require('./Boo.js'); window.onload = function () { var boo; var videoEffectSelector = document.getElementById('videoEffect'); var audioEffectSelector = document.getElementById('audioEffect'); var downloadButton = document.getElementById('download'); var recordButton = document.getElementById('record'); var countdown = document.getElementById('countdown'); var videoData; navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function (stream) { var boo = new Boo( stream, document.getElementById('booth-filtered'), document.getElementById('booth-progress') ); boo.on('ready', function () { recordButton.disabled = false; downloadButton.disabled = true; countdown.style = 'display:none'; videoEffectSelector.options = boo.getVideoEffects(); // 0 is none--start with some effect applied already! videoEffectSelector.selectedIndex = 1; videoEffectSelector.disabled = false; videoEffectSelector.addEventListener('selectedIndex', function(ev) { boo.selectVideoEffect(ev.detail.value); }); audioEffectSelector.options = boo.getAudioEffects(); audioEffectSelector.addEventListener('selectedIndex', function(ev) { boo.selectAudioEffect(ev.detail.value); }); // Set the listener for resize events, but also // make sure we're making the best use of the space already window.addEventListener('resize', function() { updateSize(); }); updateSize(); }); boo.on('finished', function (data) { recordButton.disabled = false; recordButton.classList.remove('active'); downloadButton.disabled = false; videoData = data; }); recordButton.addEventListener('click', function () { videoData = null; recordButton.disabled = true; downloadButton.disabled = true; countdown.style = ''; var number = countdown.querySelector('.number'); var countdownTime = 3; // seconds number.innerHTML = countdownTime; var interval = setInterval(function () { countdownTime--; number.innerHTML = countdownTime; if (countdownTime <= 0) { clearInterval(interval); countdown.style = 'display:none'; recordButton.classList.add('active'); boo.record(); } }, 1000); }); downloadButton.addEventListener('click', function () { downloadButton.disabled = true; var link = document.createElement('a'); link.setAttribute('href', window.URL.createObjectURL(videoData)); link.setAttribute('download', 'video_' + generateTimestamp() + '.webm'); link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); }); function updateSize() { boo.setSize(window.innerWidth, window.innerHeight); } function generateTimestamp() { var now = new Date() var ymd = now.getFullYear() + ("00" + (now.getMonth() + 1)).substr(-2) + ("00" + now.getDate()).substr(-2); var hms = ("00" + now.getHours()).substr(-2) + ("00" + now.getMinutes()).substr(-2) + ("00" + now.getSeconds()).substr(-2) return ymd + '_' + hms; } }); };
JavaScript
0
@@ -535,16 +535,17 @@ oData;%0A%0A +%0A navi @@ -631,25 +631,52 @@ %7D).then( -function +initBooth);%0A%0A%0A function initBooth (stream) @@ -682,27 +682,32 @@ ) %7B%0A -var +%0A boo = new B @@ -3415,21 +3415,23 @@ %7D);%0A%0A -%0A +%7D%0A%0A func @@ -3446,28 +3446,24 @@ ateSize() %7B%0A - boo. @@ -3510,31 +3510,23 @@ eight);%0A - %7D%0A%0A - func @@ -3554,28 +3554,24 @@ p() %7B%0A - var now = ne @@ -3581,28 +3581,24 @@ ate()%0A - - var ymd = no @@ -3693,20 +3693,16 @@ tr(-2);%0A - va @@ -3829,20 +3829,16 @@ %0A%0A - - return y @@ -3861,22 +3861,9 @@ - - %7D%0A%0A %7D); +%7D %0A%7D;%0A
a13c8e476f483506dff4fec2fe9f3e60298ab0bf
Remove debug trace in package "header"
www/assets/header.brython.js
www/assets/header.brython.js
__BRYTHON__.use_VFS = true; var scripts = {"$timestamp": 1602345685948, "header": [".py", "from browser import bind,console,html,window,document,alert\nimport browser.widgets.menu as menu\n\nhref=document.location.href\nprotocol,rest=href.split(\"://\")\nhost,addr=rest.split(\"/\",1)\n\n\nif protocol ==\"http\"and host.endswith(\"brython.info\"):\n document.location.href=f\"https://{rest}\"\n \nMenu=menu.Menu\n\ntrans_menu={\n\"menu_console\":{\"en\":\"Console\",\"es\":\"Consola\",\"fr\":\"Console\"},\n\"menu_editor\":{\"en\":\"Editor\",\"es\":\"Editor\",\"fr\":\"Editeur\"},\n\"menu_demo\":{\"en\":\"Demo\",\"es\":\"Demo\",\"fr\":\"D\u00e9mo\"},\n\"menu_gallery\":{\"en\":\"Gallery\",\"es\":\"Galer\u00eda\",\"fr\":\"Galerie\"},\n\"menu_doc\":{\"en\":\"Documentation\",\"es\":\"Documentaci\u00f3n\",\"fr\":\"Documentation\"},\n\"menu_download\":{\"en\":\"Download\",\"es\":\"Descargas\",\"fr\":\"T\u00e9l\u00e9chargement\"},\n\"menu_dev\":{\"en\":\"Development\",\"es\":\"Desarrollo\",\"fr\":\"D\u00e9veloppement\"},\n\"menu_ex\":{\"en\":\"Examples\",\"es\":\"Ejemplos\",\"fr\":\"Exemples\"},\n\"menu_groups\":{\"en\":\"Community\",\"es\":\"Comunidad\",\"fr\":\"Communaut\u00e9\"},\n\"menu_ref\":{\"en\":\"Reference\",\"es\":\"Referencia\",\"fr\":\"R\u00e9f\u00e9rence\"},\n\"menu_resources\":{\"en\":\"Resources\",\"es\":\"Recursos\",\"fr\":\"Ressources\"},\n\"menu_tutorial\":{\"en\":\"Tutorial\",\"es\":\"Tutorial\",\"fr\":\"Tutoriel\"}\n}\nlinks={\n\"home\":\"/index.html\",\n\"console\":\"/tests/console.html\",\n\"demo\":\"/demo.html\",\n\"editor\":\"/tests/editor.html\",\n\"gallery\":\"/gallery/gallery_{language}.html\",\n\"doc\":\"/static_doc/{language}/intro.html\",\n\"download\":\"https://github.com/brython-dev/brython/releases\",\n\"dev\":\"https://github.com/brython-dev/brython\",\n\"groups\":\"/groups.html\",\n\"tutorial\":\"/static_tutorial/{language}/index.html\"\n}\n\nlanguages=[\n[\"en\",\"English\"],\n[\"fr\",\"Fran\u00e7ais\"],\n[\"es\",\"Espa\u00f1ol\"]\n]\n\ndef show(language=None ):\n ''\n \n has_req=False\n qs_lang=None\n tuto_language=None\n \n prefix=\"/\"\n \n if language is None :\n qs_lang=document.query.getfirst(\"lang\")\n if qs_lang and qs_lang in [\"en\",\"fr\",\"es\"]:\n has_req=True\n language=qs_lang\n elif addr.startswith(\"gallery\"):\n elts=addr.split(\"/\")\n if len(elts)>1:\n elt1=elts[1].split(\".\")[0].split(\"_\")\n if len(elt1)==2:\n language=elt1[1]\n else :\n lang=__BRYTHON__.language\n if lang in [\"en\",\"fr\",\"es\"]:\n language=lang\n if addr.startswith(\"static_tutorial\"):\n elts=addr.split(\"/\")\n if len(elts)>1:\n tuto_language=elts[1]\n if tuto_language in [\"en\",\"fr\",\"es\"]:\n language=tuto_language\n \n language=language or \"en\"\n \n _banner=document[\"banner_row\"]\n \n loc=window.location.href\n current=None\n for key in [\"home\",\"console\",\"demo\",\"editor\",\"groups\"]:\n if links[key]in loc:\n current=key\n break\n \n if current is None :\n if \"gallery\"in loc:\n current=\"gallery\"\n elif \"static_doc\"in loc:\n current=\"doc\"\n \n def load_page(key):\n def f(e):\n href=links[key].format(language=language)\n window.location.href=href+f\"?lang={language}\"\n return f\n \n menu=Menu(_banner,default_css=False )\n \n menu.add_link(trans_menu[\"menu_tutorial\"][language],\n href=links[\"tutorial\"].format(language=language))\n \n menu.add_link(trans_menu[\"menu_demo\"][language],\n href=links[\"demo\"]+f\"?lang={language}\")\n \n menu.add_link(trans_menu[\"menu_doc\"][language],\n href=links[\"doc\"].format(language=language))\n \n menu.add_link(trans_menu[\"menu_console\"][language],\n href=links[\"console\"]+f\"?lang={language}\")\n \n menu.add_link(trans_menu[\"menu_editor\"][language],\n href=links[\"editor\"]+f\"?lang={language}\")\n \n menu.add_link(trans_menu[\"menu_gallery\"][language],\n href=links[\"gallery\"].format(language=language))\n \n ex_resources=menu.add_menu(trans_menu[\"menu_resources\"][language])\n ex_resources.add_link(trans_menu[\"menu_download\"][language],\n href=links[\"download\"])\n ex_resources.add_link(trans_menu[\"menu_dev\"][language],\n href=links[\"dev\"])\n ex_resources.add_link(trans_menu[\"menu_groups\"][language],\n href=links[\"groups\"])\n \n \n sel_lang=html.DIV(Class=\"sel_lang\")\n \n document.body.insertBefore(sel_lang,_banner.nextElementSibling)\n select=html.SELECT(Class=\"language\")\n sel_lang <=select\n selected_lang=tuto_language or language\n for lang1,lang2 in languages:\n print(\"fill language select\",lang1,language)\n select <=html.OPTION(lang2,value=lang1,\n selected=lang1 ==selected_lang)\n \n @bind(select,\"change\")\n \n def change_language(ev):\n sel=ev.target\n new_lang=sel.options[sel.selectedIndex].value\n head=f\"{protocol}://{host}\"\n new_href=href\n if addr.startswith(\"index.html\")or addr ==\"\":\n new_href=f\"{head}/index.html?lang={new_lang}\"\n elif addr.startswith((\"static_tutorial\",\"static_doc\")):\n elts=addr.split(\"/\")\n elts[1]=new_lang\n new_href=f\"{head}/{'/'.join(elts)}\"\n elif addr.startswith(\"gallery\"):\n new_href=links[\"gallery\"].format(language=new_lang)\n elif addr.startswith((\"demo.html\",\n \"tests/console.html\",\n \"tests/editor.html\")):\n elts=addr.split(\"?\")\n new_href=f\"{head}/{elts[0]}?lang={new_lang}\"\n document.location.href=new_href\n \n return qs_lang,language\n", ["browser", "browser.widgets.menu"]]} __BRYTHON__.update_VFS(scripts)
JavaScript
0
@@ -58,15 +58,15 @@ 1602 -3456859 +4938282 48, @@ -4534,58 +4534,8 @@ %5Cn -print(%5C%22fill language select%5C%22,lang1,language)%5Cn sele
3f6671fe27b1b83058930c1b641b13112ba79cab
include user and auth in middleware
src/utils/helpers.js
src/utils/helpers.js
const { Types } = require('mongoose'); const HTTPStatus = require('http-status'); const { ObjectId } = Types; /** * Check an parameter is a string or throw an error. */ function checkString(chars, { method, message } = {}) { if (typeof chars !== 'string') { throw new Error(message || `String parameter must be given to the ${method || 'unknown'} method.`); } } module.exports.checkString = checkString; /** * Check that the resource is compiled before proceeding. */ function checkCompile(compile) { if (compile) { throw new Error('Resource can not be change once it has been compiled.'); } } module.exports.checkCompile = checkCompile; /** * Check if the id of an item is a valid. */ function checkObjectId(id, { message } = {}) { if (!id || !ObjectId.isValid(id)) { const error = new Error(message || 'Request did not contain a valid id.'); error.code = HTTPStatus.BAD_REQUEST; throw error; } } module.exports.checkObjectId = checkObjectId; /** * Check that an item exists. */ function checkExists(value, { message } = {}) { if (!value) { const error = new Error(message || 'No items were found for the given request.'); error.code = HTTPStatus.NOT_FOUND; throw error; } } module.exports.checkExists = checkExists; /** * Format response. */ function formatResponse(data, debug) { if (data instanceof Error) { const error = { status: data.status || 'error', code: data.code || HTTPStatus.INTERNAL_SERVER_ERROR, message: data.message || 'There was an error on the server.', data: { ...(typeof data.data === 'object' ? data.data : {}), stack: debug && data.stack ? data.stack : {}, }, }; return error; } return { status: 'success', code: HTTPStatus.OK, data, }; } module.exports.formatResponse = formatResponse; /** * Format middleware to match express infrastructure. */ function middlify(middleware, resources, end = false) { return (req, res, next) => (async () => middleware({ req, res, next, params: req.params, body: req.body, query: req.query, ...resources, }))() .then(data => end ? res.status(200).json(formatResponse(data)) : next()) .catch(error => res.status(error.code || HTTPStatus.INTERNAL_SERVER_ERROR).json(formatResponse(error))); } module.exports.middlify = middlify; /** * Format hooks and execute work. */ function hookify(key, handler, preHooks, postHooks) { return async (...args) => { if (preHooks.has(key)) { const tasks = preHooks.get(key).map(hook => hook(...args)); await Promise.all(tasks); } let data; try { data = await handler(...args); } catch (e) { if (e && e.name === 'ValidationError') { const error = new Error(e._message || 'Request validation failed'); error.code = HTTPStatus.BAD_REQUEST; error.data = e.errors; error.status = 'fail'; throw error; } throw e; } if (postHooks.has(key)) { const tasks = postHooks.get(key).map(hook => hook({ ...args[0], data }, ...args.slice(1))); await Promise.all(tasks); } return data; }; } module.exports.hookify = hookify; /** * Check permissions. */ function permissionify(key, permissions) { return async (...args) => { let checks = []; if (permissions.has(key)) { checks = permissions.get(key).map(check => check(...args)); } const status = await Promise.all(checks); if (!status.find(outcome => !!outcome)) { const error = new Error('Permission denied to access route.'); error.code = HTTPStatus.UNAUTHORIZED; error.status = 'fail'; throw error; } }; } module.exports.permissionify = permissionify; /** * Order express routes correctly so they execute correctly */ function orderRoutes(a, b) { const aSegments = a[1].path.split('/').filter(segment => segment.length); const bSegments = b[1].path.split('/').filter(segment => segment.length); if (aSegments.length && aSegments.length === bSegments.length) { let index = 0; while (index < aSegments.length) { if (aSegments[index].charAt(0) === ':' && bSegments[index].charAt(0) !== ':') { return 1; } if (bSegments[index].charAt(0) === ':' && aSegments[index].charAt(0) !== ':') { return -1; } index += 1; } } return bSegments.length - aSegments.length; } module.exports.orderRoutes = orderRoutes;
JavaScript
0.000001
@@ -2115,16 +2115,56 @@ .query,%0A + user: req.user,%0A auth: req.auth,%0A ...r
b16167a5fe0b0dd7329039892acf035af33ef8bc
add base path /c-desk
app/js/urls.js
app/js/urls.js
let basePath=''; let imagePath = `${basePath}img`; export default { // Routes homePage: basePath, addParcelPage: 'addParcel', // Other static assets path imagePath, // i18n Translations translationFolder: 'locale', }
JavaScript
0.000001
@@ -7,16 +7,23 @@ sePath=' +/c-desk ';%0Alet i
385680e74513fb852543003980069bed9a76dee2
Use setProperty() to avoid NPE
taglibs/core/TagHandlerNode.js
taglibs/core/TagHandlerNode.js
/* * Copyright 2011 eBay Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var objects = require('raptor-objects'); var extend = require('raptor-util').extend; var forEachEntry = require('raptor-util').forEachEntry; var stringify = require('raptor-json/stringify'); var Expression = require('../../compiler').Expression; var raptorModulesResolver = require('raptor-modules/resolver'); function addHandlerVar(template, renderer) { var handlerVars = template._handlerVars || (template._handlerVars = {}); var handlerVar = handlerVars[renderer]; if (!handlerVar) { handlerVars[renderer] = handlerVar = renderer.replace(/[.\-\/]/g, '_').replace(/^[_]+/g, ''); template.addStaticVar(handlerVar, 'require(' + stringify(renderer) + ')'); } return handlerVar; } function getPropsStr(props, template) { var propsArray = []; if (props) { template.indent(function () { forEachEntry(props, function (name, value) { if (value instanceof Expression) { var expressionStr; template.indent(function () { expressionStr = value.expression.toString(); }); propsArray.push(template.indentStr() + stringify(name) + ': ' + expressionStr); } else if (typeof value === 'string' || typeof value === 'object') { propsArray.push(template.indentStr() + stringify(name) + ': ' + stringify(value)); } else { propsArray.push(template.indentStr() + stringify(name) + ': ' + value); } }); }); if (propsArray.length) { return '{\n' + propsArray.join(',\n') + '\n' + template.indentStr() + '}'; } else { return '{}'; } } else { return '{}'; } } function TagHandlerNode(tag) { if (!this.nodeType) { TagHandlerNode.$super.call(this); } this.tag = tag; this.dynamicAttributes = null; this.preInvokeCode = []; this.postInvokeCode = []; this.inputExpression = null; } TagHandlerNode.convertNode = function (node, tag) { extend(node, TagHandlerNode.prototype); TagHandlerNode.call(node, tag); }; TagHandlerNode.prototype = { addDynamicAttribute: function (name, value) { if (!this.dynamicAttributes) { this.dynamicAttributes = {}; } this.dynamicAttributes[name] = value; }, setDynamicAttributesProperty: function(name) { this.dynamicAttributesProperty = name; }, addPreInvokeCode: function (code) { this.preInvokeCode.push(code); }, addPostInvokeCode: function (code) { this.postInvokeCode.push(code); }, setInputExpression: function (expression) { this.inputExpression = expression; }, doGenerateCode: function (template) { var rendererPath = raptorModulesResolver.deresolve(this.tag.renderer, template.dirname); var handlerVar = addHandlerVar(template, rendererPath); this.tag.forEachImportedVariable(function (importedVariable) { this.setProperty(importedVariable.targetProperty, new Expression(importedVariable.expression)); }, this); var namespacedProps = extend({}, this.getPropertiesByNS()); delete namespacedProps['']; var hasNamespacedProps = !objects.isEmpty(namespacedProps); var _this = this; var variableNames = []; _this.tag.forEachVariable(function (v) { var varName; if (v.nameFromAttribute) { var possibleNameAttributes = v.nameFromAttribute.split(/\s+or\s+|\s*,\s*/i); for (var i = 0, len = possibleNameAttributes.length; i < len; i++) { var attrName = possibleNameAttributes[i]; var keep = false; if (attrName.endsWith('|keep')) { keep = true; attrName = attrName.slice(0, 0 - '|keep'.length); possibleNameAttributes[i] = attrName; } varName = this.getAttribute(attrName); if (varName) { if (!keep) { this.removeProperty(attrName); } break; } } if (!varName) { this.addError('Attribute ' + possibleNameAttributes.join(' or ') + ' is required'); varName = '_var'; // Let it continue with errors } } else { varName = v.name; if (!varName) { this.addError('Variable name is required'); varName = '_var'; // Let it continue with errors } } variableNames.push(varName); }, this); if (_this.preInvokeCode.length) { _this.preInvokeCode.forEach(function (code) { template.indent().code(code).code('\n'); }); } template.contextMethodCall('t', function () { template.code('\n').indent(function () { template.line(handlerVar + ',').indent(); if (_this.inputExpression) { template.code(_this.inputExpression); } else { if (_this.dynamicAttributes) { template.indent(function() { _this.getProperties()[_this.dynamicAttributesProperty] = template.makeExpression(getPropsStr(_this.dynamicAttributes, template)); }); } template.code(getPropsStr(_this.getProperties(), template)); } if (_this.hasChildren()) { var bodyParams = []; variableNames.forEach(function (varName) { bodyParams.push(varName); }); template.code(',\n').line('function(' + bodyParams.join(',') + ') {').indent(function () { _this.generateCodeForChildren(template); }).indent().code('}'); } else { if (hasNamespacedProps) { template.code(',\n').indent().code('null'); } } if (hasNamespacedProps) { template.code(',\n').line('{').indent(function () { var first = true; forEachEntry(namespacedProps, function (namespace, props) { if (!first) { template.code(',\n'); } template.code(template.indentStr() + '"' + namespace + '": ' + getPropsStr(props, template)); first = false; }); }).indent().code('}'); } }); }); if (_this.postInvokeCode.length) { _this.postInvokeCode.forEach(function (code) { template.indent().code(code).code('\n'); }); } } }; require('raptor-util').inherit(TagHandlerNode, require('../../compiler').Node); module.exports = TagHandlerNode;
JavaScript
0.000001
@@ -6123,25 +6123,25 @@ _this. -g +s etProperties @@ -6141,14 +6141,10 @@ pert -ies()%5B +y( _thi @@ -6170,19 +6170,17 @@ Property -%5D = +, templat @@ -6235,32 +6235,33 @@ utes, template)) +) ;%0A
7408348deef335de07b4b155b474333b78953e28
Remove máscara do input-floating-label, utilizar talent-input-mask
addon/components/input-floating-label.js
addon/components/input-floating-label.js
import Ember from 'ember'; export default Ember.TextField.extend({ classNames: ['form-control'], didInsertElement() { this.floatLabel(); this.addMask(); }, onChangeValue: Ember.observer('value', function () { this.floatLabel(); }), floatLabel() { let input = Ember.$('#' + this.get('elementId')); if (this.get('value') || this.get('value') === 0) { input.addClass('static').addClass('dirty'); } else { input.removeClass('static').removeClass('dirty'); } }, addMask(){ let mask = this.get('mask'); let input = Ember.$('#' + this.get('elementId')); if (!mask) { return; } input.inputmask(mask); } });
JavaScript
0.000001
@@ -144,28 +144,8 @@ ();%0A - this.addMask();%0A %7D, @@ -488,170 +488,8 @@ %7D%0A - %7D,%0A%0A addMask()%7B%0A let mask = this.get('mask');%0A let input = Ember.$('#' + this.get('elementId'));%0A%0A if (!mask) %7B return; %7D%0A%0A input.inputmask(mask);%0A %7D%0A
4659d097621bbb0684093aadf51ca5f1cec7dbe7
Add nprogress to comment submission too
redux/articleDetail.js
redux/articleDetail.js
import { createDuck } from 'redux-duck' import { fromJS, Map, List, OrderedMap } from 'immutable' import gql from '../util/gql' const {defineType, createAction, createReducer} = createDuck('articleDetail'); // Action Types // const LOAD = defineType('LOAD'); const SET_STATE = defineType('SET_STATE'); const RESET = defineType('RESET'); // Action creators // const fragments = { articleFields: ` fragment articleFields on Article { id text replyRequestCount replyCount createdAt references { type } } `, replyConnectionAndUserFields: ` fragment userFields on User { name avatarUrl } fragment replyConnectionFields on ReplyConnection { id reply { id versions(limit: 1) { user { name avatarUrl } type text reference createdAt } } feedbackCount user { ...userFields } } `, }; const loadData = createAction(LOAD); const setState = createAction(SET_STATE); export const load = (id) => dispatch => { dispatch(setState({key: 'isLoading', value: true})); return gql` query($id: String!) { GetArticle(id: $id) { ...articleFields user { ...userFields } replyConnections { ...replyConnectionFields } relatedArticles(filter: {replyCount: {GT: 0}}) { edges { node { ...articleFields user { ...userFields } replyCount replyConnections { ...replyConnectionFields } } score } } } } ${ fragments.articleFields } ${ fragments.replyConnectionAndUserFields } `({ id }).then(resp => { dispatch(loadData(resp.getIn(['data', 'GetArticle']))); dispatch(setState({key: 'isLoading', value: false})); }); } export const reset = () => createAction(RESET); const reloadReply = articleId => dispatch => (gql` query($id: String!) { GetArticle(id: $id) { replyConnections { ...replyConnectionFields } } } ${ fragments.replyConnectionAndUserFields } `({ id: articleId })).then( resp => { dispatch(loadData(resp.getIn(['data', 'GetArticle']))); dispatch(setState({key: 'isReplyLoading', value: false})); }) export const connectReply = (articleId, replyId) => dispatch => { dispatch(setState({key: 'isReplyLoading', value: true})); return gql`mutation($articleId: String!, $replyId: String!) { CreateReplyConnection( articleId: $articleId, replyId: $replyId, ) { id } }`({articleId, replyId}).then(() => dispatch(reloadReply(articleId))) } export const submitReply = params => dispatch => { dispatch(setState({key: 'isReplyLoading', value: true})); return gql`mutation( $articleId: String!, $text: String!, $type: ReplyTypeEnum!, $reference: String ) { CreateReply( articleId: $articleId, text: $text, type: $type, reference: $reference ) { id } }`(params).then(() => dispatch(reloadReply(params.articleId))) } // Reducer // const initialState = fromJS({ state: {isLoading: false}, data: { // data from server article: null, replyConnections: [], // reply & its connection to this article relatedArticles: [], relatedReplies: [], // related articles' replies }, }); export default createReducer({ [SET_STATE]: (state, {payload: {key, value}}) => state.setIn(['state', key], value), [LOAD]: (state, {payload}) => { const articleEdges = payload.getIn(['relatedArticles', 'edges']) || List(); const replyConnections = OrderedMap( articleEdges.flatMap(edge => (edge.getIn(['node', 'replyConnections']) || List()).map(conn => // we need to encode articleId into each replyConnection, // so that we can show link to the article in the related reply item. conn.set('articleId', edge.getIn(['node', 'id'])) ) ).map(conn => [conn.get('id'), conn]) ).toList(); return state.withMutations(s => s .updateIn(['data', 'article'], (article) => (article || Map()).merge(payload.filterNot((v, key) => key === 'replyConnections' || key === 'relatedArticles'))) .setIn(['data', 'replyConnections'], payload.get('replyConnections')) .updateIn(['data', 'relatedArticles'], articles => !articleEdges.size ? articles : articleEdges.map(edge => edge.get('node'))) .updateIn(['data', 'relatedReplies'], replies => !replyConnections.size ? replies : replyConnections.map(conn => // get reply and articleId conn.get('reply').set('articleId', conn.get('articleId')) ).filter(reply => { const replyVersion = reply.getIn(['versions', 0]); return replyVersion.get('type') !== 'NOT_ARTICLE' && replyVersion.get('reference') !== '' })) ) }, [RESET]: (state) => state.set('data', initialState.get('data')), }, initialState);
JavaScript
0
@@ -120,16 +120,51 @@ til/gql' +%0Aimport NProgress from 'nprogress'; %0A%0Aconst @@ -2520,32 +2520,53 @@ value: true%7D));%0A + NProgress.start();%0A return gql%60mut @@ -2609,24 +2609,24 @@ String!) %7B%0A - CreateRe @@ -2740,32 +2740,38 @@ yId%7D).then(() =%3E + %7B%0A dispatch(reload @@ -2783,24 +2783,51 @@ (articleId)) +;%0A NProgress.done();%0A %7D )%0A%7D%0A%0Aexport @@ -2922,32 +2922,53 @@ value: true%7D));%0A + NProgress.start();%0A return gql%60mut @@ -3199,24 +3199,30 @@ ).then(() =%3E + %7B%0A dispatch(re @@ -3249,16 +3249,43 @@ icleId)) +;%0A NProgress.done();%0A %7D )%0A%7D%0A%0A//
5fdad766de1ee5a20f5112545b7a1119be61b9b6
Make grid lines and labels clearer.
webapp/public/javascript/meterstanden.js
webapp/public/javascript/meterstanden.js
$(function() { var makeLabels = function(measurements) { return _.map(measurements, function(value, i) { var time_stamp = new Date(value.time_stamp); if (time_stamp.getHours() % 3 == 0) { return moment(time_stamp).format("HH:mm"); } else { return ""; } }); } var render = function(url) { $.getJSON(url).then( function( measurements ) { var data = { labels : makeLabels(measurements), datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : _.pluck(measurements, "stroom_piek") }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : _.pluck(measurements, "stroom_dal") }, { datasetStroke: false, datasetFill: false, fillColor : "rgba(255,120,120,0)", strokeColor : "rgba(255,120,120,1)", pointColor : "rgba(255,120,120,1)", pointStrokeColor : "#fff", data : _.pluck(measurements, "gas") }, ] } var ctx = document.getElementById("chart").getContext("2d"); new Chart(ctx).Line(data, {}); }); }; $('.today').on('click', function() { var now = new Date(); var url = "/day/today" render(url); }); $('.this_month').on('click', function() { var now = new Date(); var url = "/month/"+now.getFullYear()+"/"+(now.getMonth()+1); render(url); }); });
JavaScript
0
@@ -306,16 +306,308 @@ );%0A %7D%0A%0A + var determineMaxGridSteps = function(measurements, stepSize) %7B%0A var allValues = %5B_.pluck(measurements, %22stroom_piek%22), _.pluck(measurements, %22stroom_dal%22), _.pluck(measurements, %22gas%22)%5D;%0A var maxValue = _.max(_.flatten(allValues));%0A%0A return (maxValue / stepSize) + stepSize;%0A %7D;%0A%0A var re @@ -1585,24 +1585,228 @@ %5D%0A %7D%0A +%0A var options = %7B%0A scaleOverride: true,%0A scaleStepWidth: 0.25,%0A scaleSteps: determineMaxGridSteps(measurements, 0.25),%0A%0A scaleGridLineColor: %22rgba(0, 0, 0, 0.2)%22%0A %7D%0A%0A var ct @@ -1896,10 +1896,15 @@ ta, -%7B%7D +options );%0A
8512709251722200ebc31ebd79238825588e2ca0
Fix benchmark picker touch target size in Safari
packages/benchmarks/src/app/App.js
packages/benchmarks/src/app/App.js
/* eslint-disable react/prop-types */ import Benchmark from './Benchmark'; import { Picker, StyleSheet, ScrollView, TouchableOpacity, View } from 'react-native'; import React, { Component } from 'react'; import Button from './Button'; import { IconClear, IconEye } from './Icons'; import ReportCard from './ReportCard'; import Text from './Text'; import Layout from './Layout'; import { colors } from './theme'; const Overlay = () => <View style={[StyleSheet.absoluteFill, { zIndex: 2 }]} />; export default class App extends Component { static displayName = '@app/App'; constructor(props, context) { super(props, context); const currentBenchmarkName = Object.keys(props.tests)[0]; this.state = { currentBenchmarkName, currentLibraryName: 'react-native-web', status: 'idle', results: [] }; } render() { const { tests } = this.props; const { currentBenchmarkName, status, currentLibraryName, results } = this.state; const currentImplementation = tests[currentBenchmarkName][currentLibraryName]; const { Component, Provider, getComponentProps, sampleCount } = currentImplementation; return ( <Layout actionPanel={ <View> <View style={styles.pickers}> <View style={styles.pickerContainer}> <Text style={styles.pickerTitle}>Library</Text> <Text style={{ fontWeight: 'bold' }}>{currentLibraryName}</Text> <Picker enabled={status !== 'running'} onValueChange={this._handleChangeLibrary} selectedValue={currentLibraryName} style={styles.picker} > {Object.keys(tests[currentBenchmarkName]).map(libraryName => ( <Picker.Item key={libraryName} label={libraryName} value={libraryName} /> ))} </Picker> </View> <View style={{ width: 1, backgroundColor: colors.fadedGray }} /> <View style={styles.pickerContainer}> <Text style={styles.pickerTitle}>Benchmark</Text> <Text>{currentBenchmarkName}</Text> <Picker enabled={status !== 'running'} onValueChange={this._handleChangeBenchmark} selectedValue={currentBenchmarkName} style={styles.picker} > {Object.keys(tests).map(test => ( <Picker.Item key={test} label={test} value={test} /> ))} </Picker> </View> </View> <View style={{ flexDirection: 'row', height: 50 }}> <View style={styles.grow}> <Button onPress={this._handleStart} style={styles.button} title={status === 'running' ? 'Running…' : 'Run'} /> </View> </View> {status === 'running' ? <Overlay /> : null} </View> } listPanel={ <View style={styles.listPanel}> <View style={styles.grow}> <View style={styles.listBar}> <View style={styles.iconClearContainer}> <TouchableOpacity onPress={this._handleClear}> <IconClear /> </TouchableOpacity> </View> </View> <ScrollView ref={this._setScrollRef} style={styles.grow}> {results.map((r, i) => ( <ReportCard benchmarkName={r.benchmarkName} key={i} libraryName={r.libraryName} libraryVersion={r.libraryVersion} mean={r.mean} meanLayout={r.meanLayout} meanScripting={r.meanScripting} runTime={r.runTime} sampleCount={r.sampleCount} stdDev={r.stdDev} /> ))} {status === 'running' ? ( <ReportCard benchmarkName={currentBenchmarkName} libraryName={currentLibraryName} /> ) : null} </ScrollView> </View> {status === 'running' ? <Overlay /> : null} </View> } viewPanel={ <View style={styles.viewPanel}> <View style={styles.iconEyeContainer}> <TouchableOpacity onPress={this._handleVisuallyHideBenchmark}> <IconEye style={styles.iconEye} /> </TouchableOpacity> </View> <Provider> {status === 'running' ? ( <React.Fragment> <View ref={this._setBenchWrapperRef}> <Benchmark component={Component} forceLayout={true} getComponentProps={getComponentProps} onComplete={this._createHandleComplete({ sampleCount, benchmarkName: currentBenchmarkName, libraryName: currentLibraryName })} ref={this._setBenchRef} sampleCount={sampleCount} timeout={20000} type={Component.benchmarkType} /> </View> </React.Fragment> ) : ( <Component {...getComponentProps({ cycle: 10 })} /> )} </Provider> {status === 'running' ? <Overlay /> : null} </View> } /> ); } _handleChangeBenchmark = value => { this.setState(() => ({ currentBenchmarkName: value })); }; _handleChangeLibrary = value => { this.setState(() => ({ currentLibraryName: value })); }; _handleStart = () => { this.setState( () => ({ status: 'running' }), () => { if (this._shouldHideBenchmark && this._benchWrapperRef) { this._benchWrapperRef.setNativeProps({ style: { opacity: 0 } }); } this._benchmarkRef.start(); this._scrollToEnd(); } ); }; // hide the benchmark as it is performed (no flashing on screen) _handleVisuallyHideBenchmark = () => { this._shouldHideBenchmark = !this._shouldHideBenchmark; if (this._benchWrapperRef) { this._benchWrapperRef.setNativeProps({ style: { opacity: this._shouldHideBenchmark ? 0 : 1 } }); } }; _createHandleComplete = ({ benchmarkName, libraryName, sampleCount }) => results => { this.setState( state => ({ results: state.results.concat([ { ...results, benchmarkName, libraryName, libraryVersion: this.props.tests[benchmarkName][libraryName].version } ]), status: 'complete' }), this._scrollToEnd ); // console.log(results); // console.log(results.samples.map(sample => sample.elapsed.toFixed(1)).join('\n')); }; _handleClear = () => { this.setState(() => ({ results: [] })); }; _setBenchRef = ref => { this._benchmarkRef = ref; }; _setBenchWrapperRef = ref => { this._benchWrapperRef = ref; }; _setScrollRef = ref => { this._scrollRef = ref; }; // scroll the most recent result into view _scrollToEnd = () => { window.requestAnimationFrame(() => { if (this._scrollRef) { this._scrollRef.scrollToEnd(); } }); }; } const styles = StyleSheet.create({ viewPanel: { flex: 1, justifyContent: 'center', alignItems: 'center', overflow: 'hidden', backgroundColor: 'black' }, iconEye: { color: 'white', height: 32 }, iconEyeContainer: { position: 'absolute', top: 10, right: 10, zIndex: 1 }, iconClearContainer: { height: '100%', marginLeft: 5 }, grow: { flex: 1 }, listPanel: { flex: 1, width: '100%', marginHorizontal: 'auto' }, listBar: { padding: 5, alignItems: 'center', flexDirection: 'row', backgroundColor: colors.fadedGray, borderBottomWidth: 1, borderBottomColor: colors.mediumGray, justifyContent: 'flex-end' }, pickers: { flexDirection: 'row' }, pickerContainer: { flex: 1, padding: 5 }, pickerTitle: { fontSize: 12, color: colors.deepGray }, picker: { ...StyleSheet.absoluteFillObject, opacity: 0, width: '100%' }, button: { borderRadius: 0, fontSize: 32, flex: 1 } });
JavaScript
0
@@ -8647,16 +8647,40 @@ Object,%0A + appearance: 'none',%0A opac
7165a6650079128131c4c81a163c7b747e4a3bfe
Fix knex link in cohorts.js route file.
routes/api/cohorts.js
routes/api/cohorts.js
const router = require('express').Router(); const knex = require('../knex'); router.get('/', (req,res,next) => { res.send('GET ALL ROUTE'); }); router.get('/:id', (req,res,next) => { res.send('GET ROUTE FOR ID' + req.params.id); }); router.post('/', (req,res,next) => { res.send('POST ROUTE'); }); router.patch('/:id', (req,res,next) => { res.send('PATCH ROUTE'); }); router.delete('/:id', (req,res,next) => { res.send('DELETE ROUTE'); }); module.exports = router;
JavaScript
0
@@ -62,16 +62,19 @@ ire('../ +../ knex');%0A
bfd54d481a97b131a123c79da91736d73ec41ed7
Remove nonexisting import
packages/cp-frontend/src/router.js
packages/cp-frontend/src/router.js
import React from 'react'; import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom'; import styled from 'styled-components'; import { Header, Breadcrumb, Menu } from '@containers/navigation'; import { ServiceScale, ServiceDelete } from '@containers/service'; import Manifest from '@containers/manifest'; import Environment from '@containers/environment'; import { DeploymentGroupList, DeploymentGroupCreate, DeploymentGroupImport } from '@containers/deployment-groups'; import { ServiceList, ServicesTopology, ServicesMenu, ServicesQuickActions } from '@containers/services'; import { InstanceList, InstancesTooltip } from '@containers/instances'; import { Tooltip } from '@containers/tooltip'; import { DeploymentGroupDelete } from '@containers/deployment-group'; import { NotFound } from '@components/navigation'; const Container = styled.div` display: flex; flex: 1 1 auto; position: relative; flex-flow: column; `; const rootRedirect = p => <Redirect to="/deployment-groups" />; const servicesListRedirect = p => <Redirect to={`/deployment-groups/${p.match.params.deploymentGroup}/services-list`} />; const servicesTopologyRedirect = p => <Redirect to={`/deployment-groups/${p.match.params.deploymentGroup}/services-topology`} />; const serviceRedirect = p => <Redirect to={`/deployment-groups/${p.match.params.deploymentGroup}/services/${p.match .params.service}/instances`} />; const App = p => <div> <Switch> <Route path="/deployment-groups/:deploymentGroup/services/:service" component={Breadcrumb} /> <Route path="/deployment-groups/:deploymentGroup" component={Breadcrumb} /> <Route path="/deployment-groups" component={Breadcrumb} /> </Switch> <Switch> <Route path="/deployment-groups/:deploymentGroup/delete" exact component={DeploymentGroupDelete} /> <Route path="/deployment-groups/:deploymentGroup/services/:service" component={Menu} /> <Route path="/deployment-groups/:deploymentGroup" component={Menu} /> </Switch> <Route path="/deployment-groups" exact component={DeploymentGroupList} /> <Route path="/deployment-groups/:deploymentGroup/services-list" component={ServicesMenu} /> <Route path="/deployment-groups/:deploymentGroup/services-topology" component={ServicesMenu} /> <Route path="/deployment-groups/:deploymentGroup/services-list" component={ServicesQuickActions} /> <Route path="/deployment-groups/:deploymentGroup/services-topology" component={ServicesQuickActions} /> <Route path="/deployment-groups/:deploymentGroup/instances" exact component={InstancesTooltip} /> <Route path="/deployment-groups/:deploymentGroup/services/:service/instances" exact component={InstancesTooltip} /> <Switch> <Route path="/deployment-groups/:deploymentGroup/delete" exact component={DeploymentGroupList} /> <Route path="/deployment-groups/~create/:stage?" exact component={DeploymentGroupCreate} /> <Route path="/deployment-groups/~import/:slug" exact component={DeploymentGroupImport} /> <Route path="/deployment-groups/:deploymentGroup/instances" exact component={InstanceList} /> <Route path="/deployment-groups/:deploymentGroup/manifest/:stage?" exact component={Manifest} /> <Route path="/deployment-groups/:deploymentGroup/environment" exact component={Environment} /> <Route path="/deployment-groups/:deploymentGroup/services-list" component={ServiceList} /> <Route path="/deployment-groups/:deploymentGroup/services-topology" component={ServicesTopology} /> <Route path="/deployment-groups/:deploymentGroup/services/:service/instances" exact component={InstanceList} /> <Route path="/deployment-groups/:deploymentGroup/services/:service" component={serviceRedirect} /> <Route path="/deployment-groups/:deploymentGroup" component={servicesListRedirect} /> </Switch> <Switch> <Route path="/deployment-groups/:deploymentGroup/services-list/:service/scale" exact component={ServiceScale} /> <Route path="/deployment-groups/:deploymentGroup/services-list/:service/delete" exact component={ServiceDelete} /> <Route path="/deployment-groups/:deploymentGroup/services-topology/:service/scale" exact component={ServiceScale} /> <Route path="/deployment-groups/:deploymentGroup/services-topology/:service/delete" exact component={ServiceDelete} /> <Route path="/deployment-groups/:deploymentGroup/services-list" component={servicesListRedirect} /> <Route path="/deployment-groups/:deploymentGroup/services-topology" component={servicesTopologyRedirect} /> </Switch> </div>; const Router = ( <BrowserRouter> <Container> <Route path="/" component={Header} /> <Switch> <Route path="/deployment-groups" component={App} /> <Route path="/" exact component={rootRedirect} /> <Route path="/*" component={NotFound} /> </Switch> </Container> </BrowserRouter> ); export default Router;
JavaScript
0.000003
@@ -685,58 +685,8 @@ ';%0A%0A -import %7B%0A Tooltip%0A%7D from '@containers/tooltip';%0A%0A impo
a42e33ae2f202a0d560d1692e0848d932d299540
Fix wrong statusCode
application.js
application.js
'use strict'; const co = require('co'); const _ = require('lodash'); const http = require('http'); const compose = require('koa-compose'); const filter = require('filter-match').filter; const Router = require('./lib/router/router'); const resolver = require('resolve-keypath').resolver; const requireDir = require('require-dir'); const onFinished = require('on-finished'); const parse = require('parseurl'); const exceptions = require('./exceptions'); const statuses = require('statuses'); const path = require('path'); class BayApplication { constructor(options) { if (!options) { options = {}; } this.env = process.env.NODE_ENV || 'development'; this.subdomainOffset = 2; this.middleware = []; this.getVersion = options.getVersion; this.proxy = options.proxy; this.base = options.base; if (!this.base) { throw new Error('missing base path'); } this.router = new Router(); this.getController = resolver(requireDir(path.join(this.base, 'controllers'), { recurse: true }), '/'); this.getVersionTransformer = resolver(requireDir(path.join(this.base, 'versions'), { recurse: true }), '/'); } /** * Use the given middleware `fn`. * * @param {GeneratorFunction} fn * @return {Application} self * @api public */ use(fn) { this.middleware.push(fn); return this; } listen() { const server = http.createServer(this.callback()); return server.listen.apply(server, arguments); } /** * Return JSON representation. * We only bother showing settings. * * @return {Object} * @api public */ toJSON() { return _.pick(this, ['subdomainOffset', 'proxy', 'env']); } callback() { const self = this; return function (req, res) { res.statusCode = 404; // Find the matching route const match = self.router.match(parse(req).pathname, req.method); if (!match) { return self.handleError(req, res, new exceptions.RoutingError('No route matches')); } // Resolve the controller const actionName = match.handler.action; const controllerName = match.handler.controller; const ControllerClass = self.getController(controllerName); if (!ControllerClass) { return self.handleError(req, res, new exceptions.RoutingError(`Controller ${controllerName} not found`)); } if (!ControllerClass.prototype[actionName]) { return self.handleError(req, res, new exceptions.RoutingError(`Action ${controllerName}#${actionName} not found`)); } onFinished(res, function (err) { if (err) { self.handleError(req, res, convertToError(err)); } }); const controller = new ControllerClass(self, req, res); controller.route = match; controller.params = match.params; const middlewares = self.middleware.slice(); if (self.getVersion) { const version = self.getVersion(controller); const versionTransformer = self.getVersionTransformer(`${version}/${controllerName}`); if (versionTransformer && versionTransformer[actionName]) { middlewares.push(versionTransformer[actionName]); } } if (controller._middleware) { filter(actionName, controller._middleware).forEach(v => { middlewares.push(typeof v.name === 'function' ? v.name : controller[v.name]); }); } middlewares.push(function *fillRespondBody(next) { const body = yield controller[actionName]; if (typeof body !== 'undefined') { controller.body = body; } yield next; }); co.wrap(compose(middlewares)).call(controller).then(function () { controller.respond(); }).catch(function (err) { self.handleError(req, res, convertToError(err)); }); }; } handleError(req, res, err) { if (res.headerSent || !res.socket || !res.socket.writable) { err.headerSent = true; return; } // unset all headers res._headers = {}; // force text/plain res.setHeader('Content-Type', 'text/plain'); // ENOENT support if (err.code === 'ENOENT') { err.status = 404; } // default to 500 if (typeof err.status !== 'number' || !statuses[err.status]) { err.status = 500; } // respond const code = statuses[err.status]; const msg = err.expose ? err.message : code; res.statusCode = code; res.setHeader('Content-Length', Buffer.byteLength(msg)); res.end(msg); } } function convertToError(err) { return err instanceof Error ? err : new Error(`non-error thrown: ${err}`); } module.exports = BayApplication; exports.exceptions = exceptions;
JavaScript
0.999912
@@ -4464,20 +4464,26 @@ sCode = -code +err.status ;%0A re
090a79ad82d9f99c230f137bf2211ca5a40323d9
remove console.log
client/javascript/modules/components/counter.js
client/javascript/modules/components/counter.js
/** @jsx React.DOM */ 'use strict'; var React = require('react'); module.exports = React.createClass({ displayName: 'Counter', getInitialState: function () { return {count: this.props.initialCount}; }, handleClick: function () { console.log('current count: ' + this.state.count); this.setState({count: this.state.count + 1}); }, render: function () { return ( <div className="well" onClick={this.handleClick}> Click me to increment! {this.state.count} </div> ); } });
JavaScript
0.000006
@@ -257,67 +257,8 @@ ) %7B%0A - console.log('current count: ' + this.state.count);%0A
439cccad86e2782b63361d30113914097cc22515
add error handling.
convert.js
convert.js
var http = require('http'); var im = require('imagemagick'); var url = require('url'); var querystring = require('querystring'); http.createServer(function (req, res) { var postData = ''; var objectUrl = url.parse(req.url); var objectQuery = querystring.parse(objectUrl.query); var type = objectQuery['type']; if (typeof type === 'undefined') { res.writeHead(400, {'Content-Type': 'text/plain'}); res.end('Missing required parameters: type'); return; } req.setEncoding('binary'); req.addListener('data', function (postDataChunk) { postData += postDataChunk; }); // 所有数据包接收完毕 req.addListener('end', function () { if (postData.length === 0) { res.writeHead(400, {'Content-Type': 'text/plain'}); res.end('Missing post src data.'); return; } im.resize({ srcData: postData, format: type, density: 240, quality: 1.0, antialias: false }, function(err, stdout) { if (err) { res.writeHead(500, {'Content-Type': 'text/plain'}); res.end(err); } else { res.writeHead(200, {'Content-Type': 'application/octet-stream'}); res.end(stdout, 'binary'); } }); }); }).listen(1337); console.log('Server running at port 1337');
JavaScript
0
@@ -158,13 +158,22 @@ (req +uest , res +ponse ) %7B%0A @@ -228,16 +228,20 @@ arse(req +uest .url);%0A @@ -334,16 +334,192 @@ ype'%5D;%0A%0A + if (request.method !== 'POST') %7B%0A response.writeHead(405, %7B'Content-Type': 'text/plain'%7D);%0A response.end('Only allowed POST method.');%0A return;%0A %7D%0A%0A if ( @@ -552,32 +552,37 @@ ') %7B%0A res +ponse .writeHead(400, @@ -617,32 +617,37 @@ '%7D);%0A res +ponse .end('Missing re @@ -669,16 +669,17 @@ rs: type +. ');%0A @@ -704,16 +704,20 @@ %0A req +uest .setEnco @@ -731,32 +731,36 @@ inary');%0A req +uest .addListener('da @@ -858,16 +858,20 @@ %0A req +uest .addList @@ -940,32 +940,37 @@ %0A res +ponse .writeHead(400, @@ -1013,24 +1013,29 @@ res +ponse .end('Missin @@ -1076,32 +1076,51 @@ turn;%0A %7D%0A +%0A try %7B%0A im.resiz @@ -1123,16 +1123,20 @@ esize(%7B%0A + @@ -1170,16 +1170,20 @@ + + format: @@ -1188,16 +1188,20 @@ : type,%0A + @@ -1230,16 +1230,20 @@ + + quality: @@ -1248,16 +1248,20 @@ y: 1.0,%0A + @@ -1289,16 +1289,20 @@ + + %7D, funct @@ -1328,24 +1328,28 @@ + if (err) %7B%0A @@ -1355,35 +1355,44 @@ + + res +ponse .writeHead(500, @@ -1444,19 +1444,47 @@ -res.end(err + response.end('Image convert error.' );%0A @@ -1494,16 +1494,20 @@ + + %7D else %7B @@ -1523,19 +1523,28 @@ -res + response .writeHe @@ -1614,19 +1614,28 @@ + + res +ponse .end(std @@ -1662,18 +1662,26 @@ -%7D%0A + %7D%0A @@ -1680,24 +1680,170 @@ %7D);%0A + %7D catch (err) %7B%0A response.writeHead(500, %7B'Content-Type': 'text/plain'%7D);%0A response.end('server error.');%0A %7D%0A %7D);%0A%7D).l
3254eeccf2e03282e1bf340ea8ef33e61b4972cf
Deal with mis-matched brackets
convert.js
convert.js
function convert() { var input = document.getElementById("input").value; var italic = document.getElementById("italic").checked; var output = stringify(tokenize(input), italic); document.getElementById("htmloutput").innerHTML = output; document.getElementById("phpbboutput").innerHTML = output.replace(/</g, "[").replace(/>/g, "]"); return false; } function autoconvert() { if (document.getElementById("auto").checked) return convert(); return true; } function tokenize(string) { var tokens = []; for (var i=0; i<string.length; i++) { var token = string[i]; if (token == "\\" && i+1 < string.length) { while (i+1 < string.length && isletter(string[i+1])) token += string[++i]; if (token == "\\" && i+1 < string.length) // Non-letter followed backslash token += string[++i]; while (i+1 < string.length && string[i+1] == " ") i += 1; } tokens.push(symbol(token)); } return tokens; } function symbol(key) { var s = SYMBOLS[key]; return (s === undefined) ? key : s; } function isletter(char) { var code = char.charCodeAt(0); return (64 < code && code < 91) || (96 < code && code < 123); } MARKUPS = { "_": "sub", "^": "sup", "\\mathit": "i", "\\mathbf": "b", } function stringify(tokens, italicize_latin) { var string = ""; var pending = []; var bracket_close = []; for (var i=0; i<tokens.length; i++) { if ((tokens[i] == "_" || tokens[i] == "^") && string.substr(-1, 1) == " ") // U+202F string = string.slice(0,-1); var markup = MARKUPS[tokens[i]]; if (markup !== undefined) { pending.push(markup); continue; } if (tokens[i] == "OPEN{") { bracket_close.push(pending); string += open_tags(pending); pending = []; continue; } if (tokens[i] == "CLOSE}") { string += close_tags(bracket_close.pop()); pending = []; // Should already be empty continue; } if (tokens[i].length == 1 && isletter(tokens[i]) && italicize_latin) pending.push("i"); string += open_tags(pending) + tokens[i] + close_tags(pending); pending = []; } return string; } function open_tags(pending) { return pending.length ? "<" + pending.join("><") + ">" : ""; } function close_tags(pending) { return pending.length ? "</" + pending.reverse().join("></") + ">" : ""; }
JavaScript
0.000001
@@ -2033,24 +2033,70 @@ %22CLOSE%7D%22) %7B%0A + if (bracket_close.length %3E 0)%0A @@ -2432,32 +2432,120 @@ ing = %5B%5D;%0A %7D%0A + while (bracket_close.length %3E 0)%0A string += close_tags(bracket_close.pop());%0A return strin
1b74e146d3bf794d33e65cbcce57b0e2028f684e
remove logo
project/app/vendor.js
project/app/vendor.js
'use strict'; // jquery require('jquery'); require('bootstrap'); require('availity-uikit'); require('select2'); require('velocity'); require('moment'); require('bootstrap-datepicker'); // utils require('lodash'); // angular require('angular'); require('angular-sanitize'); require('angular-ui-router'); // availity require('availity-angular'); // images require('availity-uikit/dist/images/logo-availity.png'); // css require('angular/angular-csp.css');
JavaScript
0.000001
@@ -346,76 +346,8 @@ );%0A%0A -// images%0Arequire('availity-uikit/dist/images/logo-availity.png');%0A%0A // c
172006109662d1f4ff69b27ccc0a1ed47de6d9ae
fix ceylon/ceylon-js#486
runtime-js/flatten.js
runtime-js/flatten.js
function flatten(tf, $$$mptypes) { if (tf.$unflattened$)return tf.$unflattened$; if (tf.jsc$)tf=tf.jsc$; var mm=getrtmm$$(tf); function rf() { var argc = arguments.length; var last = argc>0 ? arguments[argc-1] : undefined; var tlast = last!=null && typeof(last)==='object'; if (tlast && typeof(last.Args$flatten) === 'object' && (last.Args$flatten.t==='T'||typeof(last.Args$flatten.t) === 'function')) { argc--; } else if (tf.$$targs$$ && tlast) { var ks=Object.keys(tf.$$targs$$); var all=true; for (var i=0;i<ks.length;i++) { if (last[ks[i]]===undefined)all=false; } if (all)argc--; } var t = []; for (var i=0;i<argc;i++) { t.push(arguments[i]); } if (t.length===1 && is$(t[0],{t:Tuple}) &&mm&&mm.ps.length===t[0].size){ //It's already a Tuple return tf(t[0]); } return tf(tpl$(t)); }; if (mm) { rf.$crtmm$={$t:mm.$t,ps:[]}; if (mm.ps.length===1 && mm.ps[0].$t.t==='T') { for(var i=0;i<mm.ps[0].$t.l.length;i++){ rf.$crtmm$.ps.push(mm.ps[0].$t.l[i]); } } } rf.$$targs$$={Return$Callable:$$$mptypes.Return$flatten,Arguments$Callable:$$$mptypes.Args$flatten}; rf.$flattened$=tf; return rf; }
JavaScript
0.000007
@@ -799,18 +799,17 @@ s.length -== +%3C =t%5B0%5D.si
bfd2dfccc67716fa411f075727f113147e19b464
Add command line option --email to define the default user auth email
bin/codebox.js
bin/codebox.js
#!/usr/bin/env node var Q = require('q'); var _ = require('underscore'); var cli = require('commander'); var path = require('path') var open = require("open"); var Gittle = require('gittle'); var pkg = require('../package.json'); var codebox = require("../index.js"); // Codebox git repo: use to identify the user var codeboxGitRepo = new Gittle(path.resolve(__dirname, "..")) // Options cli.option('-p, --port [http port]', 'Port to run the IDE'); cli.option('-t, --title [project title]', 'Title for the project.'); cli.option('-o, --open', 'Open the IDE in your favorite browser') // Command 'run' cli.command('run [folder]') .description('Run a Codebox into a specific folder.') .action(function(projectDirectory) { var that = this; var prepare = Q(); // Codebox.io settings that.box = process.env.CODEBOXIO_BOXID; that.key = process.env.CODEBOXIO_TOKEN; that.codeboxio = process.env.CODEBOXIO_HOST || "https://api.codebox.io"; // Default options that.directory = projectDirectory || process.env.WORKSPACE_DIR || "./"; that.title = that.title || process.env.WORKSPACE_NAME; that.port = that.port || process.env.PORT || 8000; var config = { 'root': that.directory, 'title': that.title, 'server': { 'port': parseInt(that.port) } }; // Use Codebox.io if (that.box && that.codeboxio && that.key) { _.extend(config, { 'workspace': { 'id': that.box }, 'hooks': { 'auth': that.codeboxio+"/api/box/"+that.box+"/auth", 'events': that.codeboxio+"/api/box/"+that.box+"/events", 'settings': that.codeboxio+"/api/account/settings" }, 'webhook': { 'authToken': that.key }, 'proc': { 'urlPattern': 'http://web-%d.' + that.box + '.vm1.dynobox.io' } }); } else { // get GIT settings for defining default user prepare = prepare.then(function() { return codeboxGitRepo.identity().then(function(actor) { console.log("Use GIT actor for auth: ", actor.email); _.extend(config, { 'users': { 'defaultEmail': actor.email } }); }) }); } // Auth user using git prepare.fin(function() { // Start Codebox return codebox.start(config).then(function() { var url = "http://localhost:"+that.port; console.log("\nCodebox is running at",url); if (that.open) { open(url); } }, function(err) { console.error('Error initializing CodeBox'); console.error(err); console.error(err.stack); // Kill process process.exit(1); }); }) }); cli.on('--help', function(){ console.log(' Examples:'); console.log(''); console.log(' $ codebox run'); console.log(' $ codebox run ./myProject'); console.log(''); console.log(' Use option --open to directly open the IDE in your browser:'); console.log(' $ codebox run ./myProject --open'); console.log(''); }); cli.version(pkg.version).parse(process.argv); if (!cli.args.length) cli.help();
JavaScript
0.000001
@@ -580,17 +580,113 @@ rowser') +;%0Acli.option('-e, --email %5Bemail address%5D', 'Email address to use as a default authentication'); %0A - %0A// Comm @@ -1407,16 +1407,85 @@ t.port)%0A + %7D,%0A 'users': %7B%0A 'defaultEmail': that.email%0A @@ -2113,24 +2113,24 @@ %7D);%0A - %7D else %7B @@ -2127,16 +2127,33 @@ %7D else + if (!that.email) %7B%0A
cb9ce1e791abac7fcb2eb784bf54affbb26a00ae
Fix closing of stdin.
npm_scripts/release.js
npm_scripts/release.js
// Execute this script in the target branch to release to npm! const exec = require('./exec'); const readline = require('readline'); const semver = require('semver'); const pkg = require('../package.json'); const branchName = exec('git rev-parse --abbrev-ref HEAD', true); const currentVersion = pkg.version; const stdin = readline.createInterface({ input: process.stdin, output: process.stdout }); const syncRemote = (branchName, nextVersion) => { exec(`git push origin ${branchName}`); if (nextVersion) { exec(`git push --tags`); console.log(`TravisCI will now release to npm on the tagged commit ${nextVersion} for the pearson-ux account.`); } }; const exitFailure = (message) => { console.error(message); process.exit(1); }; if (!branchName.startsWith('v')) { exitFailure('You must be on the official version branch in order to release to npm.'); } // *** Releaser provides the target SEMVER-compliant version *** stdin.question(`Next version (current is ${currentVersion})? `, (nextVersion) => { if (!semver.valid(nextVersion)) { exitFailure(`Version '${nextVersion}' is not valid: requires a semver-compliant version. See http://semver.org/`); } if (!semver.gt(nextVersion, currentVersion)) { exitFailure(`Version '${nextVersion}' is not valid: it must be greater than the current version.`); } if (nextVersion.startsWith('v')) { nextVersion = nextVersion.slice(1); } // Ensure unit tests pass before continuing! exec('npm test'); // Ensure the build will successfully generate exec('npm run build-dist'); // Order of operations: // 1. Bump the version update in package.json and npm-shrinkwrap.json // 2. The 'version' custom npm script (defined in package.json) executes changelog generation and adding to commit // 3. Locally commit and tag exec(`npm version ${nextVersion}`); // push commit and tag on target release branch syncRemote(branchName, nextVersion); // Generate gh-pages branch and sync with remote exec('npm run gh-pages'); exec('git pull -s recursive -Xours --no-edit'); syncRemote('gh-pages'); // Go back from whence you came exec(`git checkout ${branchName}`); }); stdin.close();
JavaScript
0.000002
@@ -2181,13 +2181,10 @@ );%0A%0A -%7D);%0A%0A + stdi @@ -2194,8 +2194,13 @@ lose();%0A +%0A%7D);%0A
95e02b98b47de2d43ef9aa50c34b61b4f09c140e
fix low contrast markup (#3899)
packages/components/src/components/notification/notification.config.js
packages/components/src/components/notification/notification.config.js
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const { prefix } = require('../../globals/js/settings'); /* eslint-disable max-len */ const items = [ { type: 'info', title: 'Notification title', subtitle: 'Subtitle text goes here.', timestamp: 'Time stamp [00:00:00]', }, { type: 'error', title: 'Notification title', subtitle: 'Subtitle text goes here.', timestamp: 'Time stamp [00:00:00]', }, { type: 'success', title: 'Notification title', subtitle: 'Our goal is to become better at our craft and raise our collective knowledge by sharing experiences, best practices, what we have recently learned or what we are working on.', timestamp: 'Time stamp [00:00:00]', }, { type: 'warning', title: 'Notification title', subtitle: 'Subtitle text goes here.', timestamp: 'Time stamp [00:00:00]', }, ]; /* eslint-enable max-len */ module.exports = { context: { prefix, }, variants: [ { name: 'default', label: 'Inline Notification', context: { variant: 'inline', items, }, }, { name: 'low-contrast', label: 'Inline Notification (Low contrast)', context: { variant: 'inline', lowContrast: true, items, }, }, { name: 'toast', label: 'Toast Notification', notes: ` Toast notifications are typically passive, meaning they won't affect the user's workflow if not addressed. Toast Notifications use 'kind' props to specify the kind of notification that should render (error, info, success, warning). `, context: { variant: 'toast', items, }, }, { name: 'low-contrast', label: 'Toast Notification (Low contrast)', notes: ` Toast notifications are typically passive, meaning they won't affect the user's workflow if not addressed. Toast Notifications use 'kind' props to specify the kind of notification that should render (error, info, success, warning). `, context: { variant: 'toast', lowContrast: true, items, }, }, ], };
JavaScript
0
@@ -1266,32 +1266,39 @@ %7B%0A name: ' +inline- low-contrast',%0A @@ -1884,16 +1884,22 @@ name: ' +toast- low-cont
fce9eb87fac77a66a76012bd9db40560085cbca0
remove some dead code
ui/cockpit/client/scripts/pages/dashboard.js
ui/cockpit/client/scripts/pages/dashboard.js
'use strict'; var fs = require('fs'); var template = fs.readFileSync(__dirname + '/dashboard.html', 'utf8'); var series = require('camunda-commons-ui/node_modules/camunda-bpm-sdk-js').utils.series; function prioritySort(a, b) { return a.priority > b.priority ? 1 : (a.priority < b.priority ? -1 : 0); } function resultsCb(cb) { return function(err, data) { if (err) { return cb(err); } cb(null, data.count); }; } var Controller = [ '$scope', 'camAPI', '$injector', 'Views', 'hasPlugin', 'page', function( $scope, camAPI, $injector, Views, hasPlugin, page ) { $scope.hasProcessSearch = hasPlugin('cockpit.processes.dashboard', 'search-process-instances'); $scope.hasCaseSearch = hasPlugin('cockpit.cases.dashboard', 'case-instances-search'); $scope.hasTaskSearch = hasPlugin('cockpit.tasks.dashboard', 'search-tasks'); $scope.mainPlugins = []; $scope.miscPlugins = []; Views.getProviders({ component: 'cockpit.dashboard.section' }).forEach(function(plugin) { (plugin.priority >= 0 ? $scope.mainPlugins : $scope.miscPlugins).push(plugin); if (plugin.getSparklineData) { if (typeof plugin.getSparklineData === 'function') { plugin.sparklineData = plugin.getSparklineData(); } else if (Array.isArray(plugin.getSparklineData)) { plugin.sparklineData = $injector.invoke(plugin.getSparklineData); } } }); // old plugins are still shown on the dashboard $scope.dashboardVars = { read: [ 'processData' ] }; $scope.deprecateDashboardProviders = Views.getProviders({ component: 'cockpit.dashboard'}); // reset breadcrumbs page.breadcrumbsClear(); page.titleSet('Dashboard'); // ---------------------------------------------------------------------------------------- var caseDefResource = camAPI.resource('case-definition'); var caseInstResource = camAPI.resource('case-instance'); var decisionDefResource = camAPI.resource('decision-definition'); var deploymentResource = camAPI.resource('deployment'); var historyResource = camAPI.resource('history'); var procDefResource = camAPI.resource('process-definition'); var procInstResource = camAPI.resource('process-instance'); var taskResource = camAPI.resource('task'); function fetchActual(cb) { // 1: GET /process-instance/count (query param for link is "unfinished") // 2: GET /history/process-instance/count?withIncidents=true&incidentStatus=open // 3: GET /case-instance/count // 4: GET: /task/count series({ runningProcessInstances: function(next) { procInstResource.count({}, resultsCb(next)); }, openIncidents: function(next) { historyResource.processInstanceCount({ withIncidents: true, incidentStatus: 'open' }, resultsCb(next)); }, caseInstances: function(next) { caseInstResource.count({}, next); }, tasks: function(next) { taskResource.count({}, next); } }, function(err, results) { if (err) { throw err; } cb(err, results); }); } function fetchDeployed(cb) { // 5: GET /process-definition/count?latestVersion=true // 6: GET /decision-definition/count?latestVersion=true // 7: GET /case-definition/count?latestVersion=true // 8: GET /deployment/count series({ processDefinitions: function(next) { procDefResource.count({ latestVersion: true }, next); }, decisionDefinitions: function(next) { decisionDefResource.count({ latestVersion: true }, next); }, caseDefinitions: function(next) { caseDefResource.count({ latestVersion: true }, next); }, deploymentDefinitions: function(next) { deploymentResource.count({}, next); } }, function(err, results) { if (err) { throw err; } cb(err, results); }); } $scope.loading = false; function fetchData() { $scope.loading = true; series({ actual: fetchActual, deployed: fetchDeployed }, function(err, results) { $scope.loading = false; if (err) { throw err; } $scope.data = results; }); } fetchData(); // ---------------------------------------------------------------------------------------- $scope.metricsPeriod = 'day'; $scope.setMetricsPeriod = function(period) { $scope.metricsPeriod = period; }; $scope.metricsVars = { read: [ 'metricsPeriod' ] }; $scope.metricsPlugins = Views.getProviders({ component: 'cockpit.dashboard.metrics' }).sort(prioritySort); }]; var RouteConfig = [ '$routeProvider', function($routeProvider) { $routeProvider.when('/dashboard', { template: template, controller: Controller, authentication: 'required', reloadOnSearch: false }); }]; module.exports = RouteConfig;
JavaScript
0.000082
@@ -931,527 +931,8 @@ %5D;%0A%0A - Views.getProviders(%7B%0A component: 'cockpit.dashboard.section'%0A %7D).forEach(function(plugin) %7B%0A (plugin.priority %3E= 0 ? $scope.mainPlugins : $scope.miscPlugins).push(plugin);%0A if (plugin.getSparklineData) %7B%0A if (typeof plugin.getSparklineData === 'function') %7B%0A plugin.sparklineData = plugin.getSparklineData();%0A %7D%0A else if (Array.isArray(plugin.getSparklineData)) %7B%0A plugin.sparklineData = $injector.invoke(plugin.getSparklineData);%0A %7D%0A %7D%0A %7D);%0A%0A //
92ebc1a29e34da592682539a57701a03ffec8ba8
Fix typo
.clusternator/docker-build.js
.clusternator/docker-build.js
'use strict'; const CLUSTERNATOR_PREFIX = 'clusternator-'; const DOCKER_CMD = 'docker'; const CLUSTERNATOR_FILE = 'clusternator.json'; const AWS_FILE = CLUSTERNATOR_PREFIX + 'aws.json'; const CLUSTERNATOR_TOKEN = CLUSTERNATOR_PREFIX + 'project-credentials.json'; const API_VERSION = '2015-09-21'; const path = require('path'); const AWS = require('aws-sdk'); const spawn = require('child_process').spawn; const notify = require('./notify'); main(); function main() { const config = getConfig(); const privatePath = path.normalize('../' + config.private); const awsConfig = getAwsConfig(privatePath); const registryId = awsConfig.registryId; const region = awsConfig.region; const credentials = getCredentials(privatePath, region); const clusternatorToken = getClusternatorToken(privatePath); getToken(credentials, registryId) .then((tokenObj) => { const imageName = buildImageName(config.projectId); return login(tokenObj) .then(() => wipePrivate(privatePath)) .then(() => dockerBuild(imageName)) .then(() => dockerTag(tokenObj.proxyEndpoint, imageName)) .then((fullImageName) => dockerPush(fullImageName) .then(decrypt) .then(() => notify( config.projectId, clusternatorToken, fullImageName))); }) .then(() => process.exit(0)) .catch((err) => { console.log(`Error: ${err.message}`); process.exit(1); }); } /** * @param {string} projectId * @returns {string} */ function buildImageName(projectId) { const PR = process.env.CIRCLE_PR_NUMBER || 0; const BUILD = process.env.CIRCLE_BUILD_NUM || 0; const IMAGE=`${CLUSTERNATOR_PREFIX}${projectId}:pr-${PR}-${BUILD}`; return IMAGE; } /** * @param {Object} creds * @param {string} registryId * @returns {Promise} */ function getToken(creds, registryId) { const ecr = new AWS.ECR(creds); return new Promise((resolve, reject) => { ecr.getAuthorizationToken({ registryIds: [registryId] }, (err, result) => { if (err) { reject(err); return; } if (!result.authorizationData[0]) { reject(new Error('no AWS authorization data returned')); return; } resolve(result.authorizationData[0]); }); }); } /** * @param {base64string} data * @returns {{user: string, token: string}} */ function decodeToken(data) { const decoded = new Buffer(data.authorizationToken, 'base64') .toString('utf8').split(':'); return { user: decoded[0], token: decoded[1] }; } /** * @param {{ token: base64String, proxyEndpoint: string }} data * @return {Promise<{{ token: base64string, proxyEndpoint: string}}>} */ function login(data) { const decoded = decodeToken(data); const end = data.proxyEndpoint; const args = [ 'login', '-u', decoded.user, '-p', decoded.token, '-e', 'none', end]; return spawnOutput(DOCKER_CMD, args); } /** * @param {string} path * @param {string} label * @returns {string} * exits */ function safeReq(path, label) { try { return require(path); } catch (err) { console.log(`Error loading ${label}: ${err.message}`); process.exit(3); } } /** * @param {string} privatePath * @param {string} region * @returns {string} */ function getCredentials(privatePath, region) { const fileName = 'aws-project-credentials'; const creds = safeReq(path.join(privatePath, fileName + '.json'), fileName); creds.region = region; creds.apiVersin = API_VERSION; return creds; } function getClusternatorToken(privatePath) { return safeReq(path .join(privatePath, CLUSTERNATOR_TOKEN), CLUSTERNATOR_TOKEN).token || null; } function getConfig() { return safeReq(path.join('..', CLUSTERNATOR_FILE) , CLUSTERNATOR_FILE); } function getAwsConfig(privatePath) { return safeReq(path.join(privatePath, AWS_FILE)); } /** * @param {string} command * @param {*[]} args * @returns {Promise} */ function spawnOutput(command, args) { args = Array.isArray(args) ? args : []; const child = spawn(command, args); let err = ''; child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); child.stdout.on('data', (data) => console.log(data)); child.stderr.on('data', (data) => err += data); return new Promise((resolve, reject) => { child.on('close', (code) => { if (+code) { reject(new Error(`${err} code: ${code}`)); } else { resolve(); } }); }); } /** * @param {string} endPoint * @returns {string} */ function cleanEndPoint(endPoint) { if (endPoint.indexOf('https://') === 0) { return endPoint.slice(8); } return endPoint; } /** * @param {string} endPoint * @param {string} imageName * @returns {Promise} */ function dockerTag(endPoint, imageName) { const target = `${cleanEndPoint(endPoint)}/${imageName}`; return spawnOutput(DOCKER_CMD, ['tag', imageName, target]) .then(() => target); } /** * @param {string} fullImageName * @returns {Promise} */ function dockerPush(fullImageName) { return spawnOutput(DOCKER_CMD, ['push', fullImageName]); } /** * @param {string} imageName * @return {Promise} */ function dockerBuild(imageName) { const cwd = process.cwd(); process.chdir(path.join(__dirname, '..')); return spawnOutput(DOCKER_CMD, ['build', '-t', imageName, './']) .then(() => process.chdir(cwd)); } /** * @returns {Promise} */ function decrypt() { return spawnOutput(path.join(__dirname, 'decrypt.sh'), []); } /** * @param {string} privatePath * @returns {Promise} */ function wipePrivate(privatePath) { return spawnOutput('rm', ['-rf', privatePath]); }
JavaScript
0.999999
@@ -3459,16 +3459,17 @@ apiVersi +o n = API_
d168b0f9aeba57ceb18c0908e7e00961e446bf68
fix an issue that might get twice language files
src/scripts/config/configuration.js
src/scripts/config/configuration.js
(function () { 'use strict'; angular.module('ariaNg').config(['$qProvider', '$translateProvider', 'localStorageServiceProvider', 'NotificationProvider', 'ariaNgConstants', 'ariaNgLanguages', function ($qProvider, $translateProvider, localStorageServiceProvider, NotificationProvider, ariaNgConstants, ariaNgLanguages) { $qProvider.errorOnUnhandledRejections(false); localStorageServiceProvider .setPrefix(ariaNgConstants.appPrefix) .setStorageType('localStorage') .setStorageCookie(365, '/'); var supportedLangs = []; var languageAliases = {}; for (var langName in ariaNgLanguages) { if (!ariaNgLanguages.hasOwnProperty(langName)) { continue; } var language = ariaNgLanguages[langName]; var aliases = language.aliases; supportedLangs.push(langName); if (!angular.isArray(aliases) || aliases.length < 1) { continue; } for (var i = 0; i < aliases.length; i++) { var langAlias = aliases[i]; languageAliases[langAlias] = langName; } } $translateProvider.useLoader('ariaNgLanguageLoader') .useLoaderCache(true) .registerAvailableLanguageKeys(supportedLangs, languageAliases) .determinePreferredLanguage() .fallbackLanguage(ariaNgConstants.defaultLanguage) .useSanitizeValueStrategy('escapeParameters'); NotificationProvider.setOptions({ delay: ariaNgConstants.notificationInPageTimeout }); }]); }());
JavaScript
0.000004
@@ -1372,50 +1372,8 @@ es)%0A - .determinePreferredLanguage()%0A
df3fafe81b2aea8cad284cee7078f768954eb98e
fix a bug a null that chrom.notifications is dealt with errorly
background/others.js
background/others.js
"use strict"; if (Settings.get("vimSync") === true) setTimeout(function() { Settings.Sync = { storage: chrome.storage.sync, doNotSync: ["settingsVersion", "previousVersion", "keyboard"], fetchAsync: function() { var _this = this; this.storage.get(null, function(items) { var key, value, hasOwn; if (chrome.runtime.lastError) { return chrome.runtime.lastError; } hasOwn = Object.prototype.hasOwnProperty; for (key in items) { if (!hasOwn.call(items, key)) continue; value = items[key]; _this.storeAndPropagate(key, value); } }); }, HandleStorageUpdate: function(changes) { var change, key; var _this = Settings.Sync, func = Object.prototype.hasOwnProperty; for (key in changes) { if (!func.call(changes, key)) continue; change = changes[key]; _this.storeAndPropagate(key, change != null ? change.newValue : undefined); } }, storeAndPropagate: function(key, value) { var defaultValue, defaultValueJSON; if (!(key in Settings.defaults)) { return; } if (!this.shouldSyncKey(key)) { return; } if (value && key in localStorage && localStorage[key] === value) { return; } defaultValue = Settings.defaults[key]; defaultValueJSON = JSON.stringify(defaultValue); if (value && value !== defaultValueJSON) { value = JSON.parse(value); } else { value = defaultValue; } Settings.set(key, value); }, set: function(key, value) { if (this.shouldSyncKey(key)) { var settings = {}; settings[key] = value; this.storage.set(settings); } }, clear: function(key) { if (this.shouldSyncKey(key)) { this.storage.remove(key); } }, shouldSyncKey: function(key) { return this.doNotSync.index(key) < 0; } }; chrome.storage.onChanged.addListener(Settings.Sync.HandleStorageUpdate); Settings.Sync.fetchAsync(); }, 100); if (chrome.browserAction && chrome.browserAction.setIcon) setTimeout(function() { var func; g_requestHandlers.SetIcon = function(tabId, type, pass) { chrome.browserAction.setIcon({ tabId: tabId, path: Settings.icons[type || (pass === null ? "enabled" : pass ? "partial" : "disabled")] }); }; func = Settings.updateHooks.showActionIcon; Settings.updateHooks.showActionIcon = function (value) { func.call(Settings, value); if (value) { chrome.browserAction.setTitle({ title: "Vimium++" }); chrome.browserAction.enable(); } else { chrome.browserAction.disable(); chrome.browserAction.setTitle({ title: "Vimium++\nThis icon is not in use" }); } }; Settings.postUpdate("showActionIcon"); }, 50); // According to tests: onInstalled will be executed after 0 ~ 16 ms if needed chrome.runtime.onInstalled.addListener(function(details) { window.b = setTimeout(function() { var reason = details.reason, func; if (reason === "install") { reason = ""; } else if (reason === "update") { reason = details.previousVersion; } else { return; } if (Settings.CONST.Timer > 0) { clearTimeout(Settings.CONST.Timer); Settings.CONST.Timer = 0; } chrome.tabs.query({ status: "complete" }, function(tabs) { var _i = tabs.length, tabId, _j, _len, callback, url, t = chrome.tabs, ref, contentScripts, js; callback = function() { return chrome.runtime.lastError; }; contentScripts = chrome.runtime.getManifest().content_scripts[0]; ref = {file: "", allFrames: contentScripts.all_frames}; js = contentScripts.js; js.pop(); for (; 0 <= --_i; ) { url = tabs[_i].url; if (url.startsWith("chrome") || url.indexOf("://") === -1) continue; tabId = tabs[_i].id; for (_j = 0, _len = js.length; _j < _len; ++_j) { ref.file = js[_j]; t.executeScript(tabId, ref, callback); } } console.log("%cVimium++%c has %cinstalled%c", "color:blue", "color:auto" , "color:red", "color:auto;", "with", details, "."); }); if (!reason && chrome.notifications && chrome.notifications.create) { return; } func = function(versionA, versionB) { var a, b, i, _ref; versionA = versionA.split('.'); versionB = versionB.split('.'); for (i = 0, _ref = Math.max(versionA.length, versionB.length); i < _ref; ++i) { a = parseInt(versionA[i] || 0, 10); b = parseInt(versionB[i] || 0, 10); if (a < b) { return -1; } else if (a > b) { return 1; } } return 0; }; if (func(Settings.CONST.CurrentVersion, reason) <= 0) { return; } reason = "vimium++_upgradeNotification"; chrome.notifications.create(reason, { type: "basic", iconUrl: chrome.runtime.getURL("icons/icon128.png"), title: "Vimium++ Upgrade", message: "Vimium++ has been upgraded to version " + Settings.CONST.CurrentVersion + ". Click here for more information.", isClickable: true }, function(notificationId) { if (chrome.runtime.lastError) { return chrome.runtime.lastError; } reason = notificationId || reason; chrome.notifications.onClicked.addListener(function(id) { if (id !== reason) { return; } g_requestHandlers.focusOrLaunch({ url: "https://github.com/gdh1995/vimium-plus#release-notes" }); }); }); }, 500); }); setTimeout(function() { chrome.runtime.onInstalled.removeListener(window.b); window.b = null; }, 200); //* #if DEBUG var a, b, c, cb, log; cb = function(b) { a = b; console.log(b); }; setTimeout(function() { a = c = null; b = cb; log = function() { console.log.apply(console, arguments); }; }, 2000); // #endif */
JavaScript
0
@@ -2109,40 +2109,8 @@ tion - && chrome.browserAction.setIcon ) se @@ -4165,35 +4165,12 @@ son -&& chrome.notifications && +%7C%7C ! chro @@ -4185,23 +4185,16 @@ ications -.create ) %7B retu
84cdb10449c8bb996f01627602e9b13ce08d930c
update / delete resolvers fixes
packages/oors-mongodb/src/libs/graphql/createResolvers.js
packages/oors-mongodb/src/libs/graphql/createResolvers.js
/* eslint-disable no-case-declarations */ import invariant from 'invariant'; import identity from 'lodash/identity'; import omit from 'lodash/omit'; import withSchema from 'oors-graphql/build/decorators/withSchema'; const createPaginationSchema = ({ maxPerPage, defaultPerPage } = {}) => ({ skip: { type: 'integer', minimum: 0, default: 0, }, after: { isObjectId: true, }, before: { isObjectId: true, }, first: { type: 'integer', minimum: 1, maximum: maxPerPage, default: defaultPerPage, }, last: { type: 'integer', minimum: 1, maximum: maxPerPage, }, }); export const buildConfig = config => { if (typeof config === 'string') { return buildConfig({ repositoryName: config, }); } const { wrapPipeline, nodeVisitors, getInitialPipeline, repositoryName } = { wrapPipeline: () => identity, getInitialPipeline: (_, args, ctx, info, pipeline) => pipeline, canDelete: () => true, canUpdate: () => true, nodeVisitors: [], ...config, pagination: { maxPerPage: 20, defaultPerPage: 10, ...(config.pagination || {}), }, }; if (repositoryName) { if (!config.getRepository) { Object.assign(config, { getRepository: ({ getRepository }) => getRepository(repositoryName), }); } if (!config.getLoaders) { Object.assign(config, { getLoaders: ({ app, loaders }) => loaders[app.modules.get('oors.rad').getLoadersName(repositoryName)], }); } } invariant( typeof config.getRepository === 'string' || typeof config.getRepository === 'function', `Invalid required getRepository parameter (needs to be a repository name or a function that will receive a resolver context as argument)`, ); invariant( typeof config.getLoaders === 'function', `Invalid required getLoaders parameter (needs to be a function that will receive a resolver context as argument and returns DataLoader instances)`, ); const getRepository = typeof config.getRepository === 'string' ? ctx => ctx.getRepository(config.getRepository) : config.getRepository; const createPipeline = (_, args, ctx, info) => { const repository = getRepository(ctx); const pipeline = args.pipeline || getInitialPipeline(_, args, ctx, info, repository.createPipeline()); return wrapPipeline(_, args, ctx)( ctx.gqlQueryParser.toPipeline(args, { repository, pipeline, nodeVisitors, }), ); }; return { createPipeline, getRepository, ...config, }; }; export const findById = config => { const { getLoaders } = buildConfig(config); return (_, { id }, ctx) => getLoaders(ctx).findById.load(id); }; export const findOne = config => { const { getLoaders, createPipeline } = buildConfig(config); return withSchema({ type: 'object', properties: { where: { type: 'object', default: {}, }, }, required: ['where'], })(async (_, args, ctx, info) => { const results = await getLoaders(ctx).aggregate.load( createPipeline(_, args, ctx, info).limit(1), ); return results.length > 0 ? ctx.fromMongo(results[0]) : null; }); }; export const findMany = config => { const { getLoaders, createPipeline, pagination } = buildConfig(config); return withSchema({ type: 'object', properties: { ...createPaginationSchema(pagination), where: { type: 'object', default: {}, }, }, })(async (_, args, ctx, info) => { const pivot = args.before || args.after; if (pivot) { Object.assign(args, { pivot: await getLoaders(ctx).findById.load(pivot), }); } return getLoaders(ctx) .aggregate.load(createPipeline(_, args, ctx, info)) .then(ctx.fromMongoArray); }); }; export const count = config => { const { getLoaders, createPipeline } = buildConfig(config); return async (_, args, ctx, info) => { const results = await getLoaders(ctx).aggregate.load( createPipeline(_, args, ctx, info).count(), ); return Array.isArray(results) && results.length > 0 ? results[0].count : 0; }; }; export const createOne = config => { const { getRepository } = buildConfig(config); return async (_, { input }, ctx) => ctx.fromMongo(await getRepository(ctx).createOne(input)); }; export const createMany = config => { const { getRepository } = buildConfig(config); return async (_, args, ctx) => (await getRepository(ctx).createMany(args.input)).map(ctx.fromMongo); }; export const updateOne = config => { const { getRepository, getLoaders, createPipeline, canUpdate } = buildConfig(config); return async (_, args, ctx, info) => { const { input } = args; const Repository = getRepository(ctx); let { item } = args.item; if (item === undefined) { const results = await getLoaders(ctx).aggregate.load( createPipeline(_, args, ctx, info).limit(1), ); item = Array.isArray(results) && results.length > 0 ? results[0] : undefined; } if (!item) { throw new Error('Unable to find item!'); } if (!canUpdate(_, args, ctx, info, item)) { throw new Error('Not Allowed!'); } await Repository.validate( omit( { ...item, ...input, }, ['_id'], ), ); return ctx.fromMongo( await Repository.updateOne({ query: { _id: item._id, }, update: { $set: input, }, }), ); }; }; export const deleteOne = config => { const { getRepository, getLoaders, createPipeline, canDelete } = buildConfig(config); return async (_, args, ctx, info) => { const Repository = getRepository(ctx); let { item } = args.item; if (item === undefined) { const results = await getLoaders(ctx).aggregate.load( createPipeline(_, args, ctx, info).limit(1), ); item = Array.isArray(results) && results.length > 0 ? results[0] : undefined; } if (!item) { throw new Error('Unable to find item!'); } if (!canDelete(_, args, ctx, info, item)) { throw new Error('Not Allowed!'); } return ctx.fromMongo(await Repository.deleteOne({ query: { _id: item._id } })); }; }; export default config => ({ findById: findById(config), findOne: findOne(config), findMany: findMany(config), count: count(config), createOne: createOne(config), createMany: createMany(config), updateOne: updateOne(config), deleteOne: deleteOne(config), });
JavaScript
0
@@ -4798,16 +4798,41 @@ = args;%0A + let %7B item %7D = args;%0A cons @@ -4869,38 +4869,8 @@ tx); -%0A let %7B item %7D = args.item; %0A%0A @@ -5836,21 +5836,16 @@ %7D = args -.item ;%0A%0A i
d02efc0556df898c4e8d9742830c209c84c21041
change frag var name to adFragment...update comments
wordpress/webpack/entry_FRONTPAGE_ADS.js
wordpress/webpack/entry_FRONTPAGE_ADS.js
/* * entry_FRONTPAGE_ADS.js * * Module for loading styles and scripts related to front page ads only * */ define( ["jquery"], function( $ ) { // matchMedia() polyfill files var matchMediaArray = [ "/wp-content/themes/kaidez-swiss/js/libs/matchMedia.addListener.js", "/wp-content/themes/kaidez-swiss/js/libs/matchMedia.js" ]; /* * If the browser doesn't support matchMedia(), load in polyfill * files via a forEach() loop */ if ( !window.matchMedia ) { return matchMediaArray.forEach( function( index ){ $.getScript( index ); }); } // Lynda promo ad var lyndaPromo = { pageElement: "ad-spot-one", link: "http://www.lynda.com/promo/trial/Default.aspx?lpk35=7840&utm_medium=ldc-partner&utm_source=SSPRC&utm_content=753&utm_campaign=CD2146&cid=l0:en:pt:le:prosb:s0:0:ind:ssprc:CD2146&bid=753&aid=CD2146", imageSource: "http://lynda.directtrack.com/42/2146/753/", alt: "10-day free trial" }; // Lynda gift ad var lyndaGift = { pageElement: "ad-spot-two", link: "https://www.lynda.com/giftsubscription/index.aspx?utm_medium=ldc-partner&utm_source=SSPRC&utm_content=11900&utm_campaign=CD2146&cid=l0:en:pt:le:prosb:s0:0:ind:ssprc:CD2146&bid=11900&aid=CD2146", imageSource : "http://lynda.directtrack.com/42/2146/11900/", alt: "Give lynda.com" }; function buildAd( obj, opts ) { var adPageTarget = document.getElementById( obj.pageElement ), adLink = obj.link, adImageSource = obj.imageSource, adAltTag = obj.alt; var setAnchor = document.createElement( "a" ), setImage = document.createElement( "img" ), frag = document.createDocumentFragment(); setAnchor.setAttribute( "href", adLink ); $( setImage ).attr({ "src": adImageSource, "alt": adAltTag }); setAnchor.appendChild( setImage ); // START CONFIGURING ANY PASSED OPTIONS opts = opts || {}; if( opts.getTarget === "img" ) { $( setImage ).attr( opts.getAttr, opts.setAttr ); } frag.appendChild( setAnchor ); adPageTarget.appendChild( frag ); }; // end buildAd() buildAd( lyndaPromo, { getTarget: "img", getAttr: "border", setAttr: 0 }); buildAd( lyndaGift, { getTarget: "img", getAttr: "border", setAttr: 0 }); // Set a base media query value that enquire.js always checks enquire.register( "( min-width: 768px )", { match : function() {}, unmatch : function() {}, setup : function() {}, deferSetup : true }); }); // end "define()"
JavaScript
0
@@ -1374,16 +1374,94 @@ %22%0A %7D;%0A%0A + /*%0A * buildAd(): Dynamically build and place ads on the front page.%0A */%0A functi @@ -1762,20 +1762,26 @@ -frag +adFragment = docum @@ -2058,16 +2058,17 @@ %7B%7D;%0A%0A + if( opts @@ -2088,24 +2088,26 @@ = %22img%22 ) %7B%0A + $( setIm @@ -2155,18 +2155,78 @@ %0A -%7D%0A%0A frag + %7D else %7B%0A if( opts.getTarget === %22link%22 ) %7B%0A %7D%0A%0A adFragment .app @@ -2281,12 +2281,18 @@ ld( -frag +adFragment );%0A
7e81450b0e944baf1cbea19dcad789e6a96f4a84
add routes to the router
client/app/router.js
client/app/router.js
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { }); export default Router;
JavaScript
0.000003
@@ -160,16 +160,85 @@ ion() %7B%0A + this.route('task');%0A this.route('user');%0A this.route('sign-in');%0A %7D);%0A%0Aexp
8d2b6bd39ec4a9feb5cb294138e5acb09dcb81da
add unittest, helper.string.replaceAll
dp_tornado/engine/static/js/dp.test.js
dp_tornado/engine/static/js/dp.test.js
if (!dp) var dp = {}; dp.test = { failed: false, init: function() { var wait = 10; dp_assert(function() { return _el('#input-test').length; }, 'test-el'); dp_assert(dp.helper.string.uniqid(), 'test-uniqid'); dp_assert(dp.helper.string.uniqid('prefix_'), 'test-uniqid-with-prefix'); dp_assert(dp.helper.string.uniqid('prefix_', true), 'test-uniqid-with-entropy'); dp_assert(dp.helper.string.uniqid('prefix_', true, '-'), 'test-uniqid-with-entropy-separator'); dp_assert( function() { return dp.test.ui.element.input.delegate.on_focus_called; }, 'test-ui-element-input-delegate-on-focus', function() { _el('#input-test').focus(); }, wait ); dp_assert( function() { return dp.test.ui.element.input.delegate.on_return_called; }, 'test-ui-element-input-delegate-on-return', function() { var e = dp_jqlib.Event('keypress'); e.keyCode = 13; _el('#input-test').trigger(e); }, wait ); setTimeout(function() { dp_assert(!dp.test.failed, 'all-test-cases'); }, wait * 2); }, ui: { element: { input: { delegate: { on_return_called: false, on_return: function() { dp.test.ui.element.input.delegate.on_return_called = true; console.log('* dp.test.ui.element.input.delegate.on_return called.'); }, on_focus_called: false, on_focus: function() { dp.test.ui.element.input.delegate.on_focus_called = true; console.log('* dp.test.ui.element.input.delegate.on_focus called.'); } } } } } }; var dp_assert = function(eq, identifier, before, delay) { if (before) { before(); } if (delay) { setTimeout(function() { dp_assert(eq, identifier); }, delay); return; } if (typeof eq == 'function') { eq = eq(); } if (!eq) { if (dp.test.failed) return; console.log('* Assertion Failed, ' + identifier); dp_jqlib('body').append(dp_jqlib('<p />').addClass('assert').addClass('fail').text('* Assertion Failed, ' + identifier)); dp.test.failed = true; throw new Error('* Assertion Failed, ' + identifier); } else { console.log('* Assertion Succeed, ' + identifier); dp_jqlib('body').append(dp_jqlib('<p />').addClass('assert').addClass('succ').text('* Assertion Succeed, ' + identifier)); } }; dp_init(function() { dp.test.init(); });
JavaScript
0.000002
@@ -528,24 +528,135 @@ parator');%0A%0A + dp_assert(dp.helper.string.replaceAll('abcd', 'a', '-') === '-bcd', 'text-helper-string-replaceAll');%0A%0A dp_a
e4d1f155407a6f7bd7c7c392d91420fb2cf48e07
Add wrapDateLine option to OL.
client/js/app.map.js
client/js/app.map.js
/** * View: MapView * * The map preview for a project. */ var MapView = Backbone.View.extend({ id: 'map-preview', initialize: function() { _.bindAll(this, 'render', 'activate', 'controlZoom', 'reload', 'fullscreen', 'minimize', 'maximize'); this.render(); this.model.bind('save', this.reload); window.app.bind('ready', this.activate); }, events: { 'click a.map-fullscreen': 'fullscreen' }, render: function() { $(this.el).html(ich.MapView({ id: this.model.id })); }, activate: function() { var options = { projection: new OpenLayers.Projection('EPSG:900913'), displayProjection: new OpenLayers.Projection('EPSG:4326'), units: 'm', numZoomLevels: 23, maxResolution: 156543.0339, maxExtent: new OpenLayers.Bounds( -20037500, -20037500, 20037500, 20037500 ), controls: [] }; // Retrieve stored centerpoint from model and convert to map units. var center = this.model.get('center') || {lat: 0, lon: 0, zoom: 2}; var lonlat = new OpenLayers.LonLat(center.lon, center.lat) lonlat.transform( new OpenLayers.Projection('EPSG:4326'), new OpenLayers.Projection('EPSG:900913') ); center.lat = lonlat.lat; center.lon = lonlat.lon; // Nav control images. // @TODO: Store locally so the application is portable/usable offline? OpenLayers.ImgPath = 'images/openlayers_dark/'; this.map = new OpenLayers.Map('map-preview-' + this.model.id, options); this.layer = new OpenLayers.Layer.TMS('Preview', this.model.layerURL(), { layername: this.model.project64({signed: true}), type: 'png', buffer: 0, transitionEffect: 'resize' }); this.map.addLayers([this.layer]); // Set the map's initial center point this.map.setCenter(new OpenLayers.LonLat(center.lon, center.lat), center.zoom); // Add custom controls var navigation = new OpenLayers.Control.Navigation({ zoomWheelEnabled: true }); this.map.addControl(navigation); navigation.activate(); this.controlZoom({element: this.map.div}); this.map.events.register('moveend', this.map, this.controlZoom); this.map.events.register('zoomend', this.map, this.controlZoom); // Stop event propagation to the OL map. $('#zoom-display div, a.map-fullscreen').mousedown(function(e) { e.stopPropagation(); }); $('#zoom-display div, a.map-fullscreen').mouseup(function(e) { e.stopPropagation(); }); $('#zoom-display .zoom-in').click($.proxy(function(e) { e.stopPropagation(); this.map.zoomIn(); }, this)); $('#zoom-display .zoom-out').click($.proxy(function(e) { e.stopPropagation(); this.map.zoomOut(); }, this)); return this; }, xport: function(method, collection) { if (typeof exportMethods[method] === 'function') { var view = new exportMethods[method]({ model: new ExportJob({ mapfile: this.model.project64({signed: false}), type: method }), project: this.model, collection: collection, map: this }); } }, fullscreen: function() { $(this.el).toggleClass('fullscreen'); this.map.updateSize(); return false; }, maximize: function() { $(this.el).addClass('fullscreen'); this.map.updateSize(); return false; }, minimize: function() { $(this.el).removeClass('fullscreen'); this.map.updateSize(); return false; }, controlZoom: function(e) { // Set the model center whenever the map is moved. // Retrieve centerpoint from map and convert to lonlat units. var center = this.map.getCenter(); var zoom = this.map.getZoom(); var lonlat = new OpenLayers.LonLat(center.lon, center.lat); lonlat.transform( this.map.projection, new OpenLayers.Projection("EPSG:4326") ); this.model.set({ center: { lat: lonlat.lat, lon: lonlat.lon, zoom: zoom } }, { silent: true }); (e.element.id && $('#zoom-display h4', e.element).size()) && $('#zoom-display h4', e.element) .text('Zoom level ' + this.map.getZoom()); }, reload: function() { if (this.map.layers && this.map.layers && this.map.layers[0]) { this.map.layers[0].layername = this.model.project64({signed: true}); this.map.layers[0].redraw(); } } });
JavaScript
0
@@ -1942,16 +1942,48 @@ 'resize' +,%0A wrapDateLine: true %0A
922d5aaff7a6121fce99a4b948cef5453f9639a1
use Meteor.userLoaded()
client/lib/router.js
client/lib/router.js
SimpleRouter = FilteredRouter.extend({ initialize: function() { FilteredRouter.prototype.initialize.call(this); this.filter(this.require_login, {only: ['submit']}); this.filter(this.start_request); this.filter(this.require_profile); this.filter(this.requirePost, {only: ['post_page']}); }, start_request: function(page){ // runs at every new page change Session.set("openedComments", null); document.title = getSetting("title"); // set all errors who have been seen to not show anymore clearSeenErrors(); // log this request with mixpanel, etc instrumentRequest(); return page; }, require_login: function(page) { if (Meteor.user()) { return page; } else { return 'signin'; } }, // if the user is logged in but their profile isn't filled out enough require_profile: function(page) { var user = Meteor.user(); if (user && ! user.loading && ! userProfileComplete(user)){ Session.set('selectedUserId', user._id); return 'user_email'; } else { return page; } }, // if we are on a page that requires a post, as set in selectedPostId requirePost: function(page) { if (Posts.findOne(Session.get('selectedPostId'))) { return 'post_page'; } else if (! Session.get('postReady')) { return 'loading'; } else { return 'not_found'; } }, // wait for the subscription to be ready, this one is only used manually awaitSubscription: function(page, subName) { return Session.get(subName) ? page : 'loading'; }, routes: { '': 'top', 'top':'top', 'top/':'top', 'top/:page':'top', 'new':'new', 'new/':'new', 'new/:page':'new', 'digest/:year/:month/:day':'digest', 'digest':'digest', 'digest/':'digest', 'test':'test', 'signin':'signin', 'signup':'signup', 'submit':'submit', 'invite':'invite', 'posts/deleted':'post_deleted', 'posts/:id/edit':'post_edit', 'posts/:id/comment/:comment_id':'post', 'posts/:id':'post', 'comments/deleted':'comment_deleted', 'comments/:id':'comment', 'comments/:id/reply':'comment_reply', 'comments/:id/edit':'comment_edit', 'settings':'settings', 'admin':'admin', 'categories':'categories', 'users':'users', 'account':'user_edit', 'forgot_password':'forgot_password', 'users/:id': 'user_profile', 'users/:id/edit':'user_edit' }, top: function() { var self = this; // XXX: where do we go if not? Should the if be in the goto (so it's reactive?) if(canView(Meteor.user(), 'replace')) { self.goto(function() { return self.awaitSubscription('posts_top', 'topPostsReady'); }); } }, new: function(page) { var self = this; if(canView(Meteor.user(), 'replace')) { self.goto(function() { return self.awaitSubscription('posts_new', 'newPostsReady'); }); } }, digest: function(year, month, day){ var self = this; if(canView(Meteor.user(), 'replace')) { if(typeof day === 'undefined'){ // if day is not defined, just use today // and change the URL to today's date var date = new Date(); var mDate = moment(date); this.navigate(getDigestURL(mDate)); }else{ var date=new Date(year, month-1, day); } sessionSetObject('currentDate', date); self.goto(function() { return self.awaitSubscription('posts_digest', 'digestPostsReady'); }); } }, signup: function() { this.goto('signup'); }, signin: function() { this.goto('signin'); }, invite: function() { this.goto('no_invite'); }, submit: function() { this.goto('post_submit'); }, settings: function() { this.goto('settings'); }, users: function() { this.goto('users'); }, post_deleted: function() { this.goto('post_deleted'); }, comment_deleted: function() { this.goto('comment_deleted'); }, forgot_password: function() { this.goto('user_password'); }, admin: function() { this.goto('admin'); }, categories: function() { this.goto('categories'); }, post: function(id, commentId) { Session.set('selectedPostId', id); if(typeof commentId !== 'undefined') Session.set('scrollToCommentId', commentId); this.goto('post_page'); // on post page, we show the comment recursion window.repress_recursion=false; // reset the new comment time at each new request of the post page window.newCommentTimestamp=new Date(); }, post_edit: function(id) { Session.set('selectedPostId', id); this.goto('post_edit'); }, comment: function(id) { Session.set('selectedCommentId', id); window.repress_recursion=true; window.newCommentTimestamp=new Date(); this.goto('comment_page'); }, comment_reply: function(id) { Session.set('selectedCommentId', id); window.repress_recursion=true; window.newCommentTimestamp=new Date(); this.goto('comment_reply'); }, comment_edit: function(id) { Session.set('selectedCommentId', id); window.newCommentTimestamp=new Date(); this.goto('comment_edit'); }, user_profile: function(id){ if(typeof id !== undefined){ Session.set('selectedUserId', id); } this.goto('user_profile'); }, user_edit: function(id){ if(typeof id !== undefined){ Session.set('selectedUserId', id); } this.goto('user_edit'); } }); var Router = new SimpleRouter(); Meteor.startup(function() { });
JavaScript
0
@@ -932,22 +932,27 @@ && -! +Meteor. user -.loading +Loaded() &&
822e69620906a2963fcfa086cc52ceea7780bc60
fix saving to app_configuration.json
modules/background/api/configHelper.js
modules/background/api/configHelper.js
import Promise from 'bluebird'; import path from 'path'; let fs = Promise.promisifyAll(require('fs')); const configHelper = () => { let config = 'config/app_configuration.min.JSON' let innerRepresentation; const getData = () => { if(!innerRepresentation || innerRepresentation.changed) { return fs.readFileAsync(path.join(process.cwd(), config), 'utf8') .then(data => JSON.parse(data)) .then(config => { innerRepresentation = config; return config; }) .catch(err => { return err; }); } return new Promise(resolve => { resolve(innerRepresentation); }); } const getTasks = (folderName, folderPath, taskId) => getFolder(folderName, folderPath) .then(folder => folder.tasks.filter(task => { if(taskId === undefined || taskId === null) { return true; } if(task.id === parseInt(taskId, 10)) { return true; } return false; }) ) .catch(err => {throw err;}); const getFolder = (folderName, folderPath) => { if(!folderName || !folderPath) { throw new Error('Parameters are wrong'); } return getData() .then(config => config.folders.filter(folder => { if(folder.folder.name === folderName && folder.folder.path === folderPath) { return true; } return false; })[0]) .then(folder => { if(folder) { return folder; } throw new Error('No folder found'); }) .catch(err => {throw err;}); } const saveFolder = (data) => getData() .then(config => { config.push(data); return config; }) .then(config => save(config)) .catch(err => err); let save = (data) => fs.writeFileAsync(path.join(process.cwd(), configName), JSON.stringify(data)) .catch(err => err); const saveTask = (folderName, folderPath, data) => getData() .then(config => config.map(folder => { if(folder.folder.name === folderName && folder.folder.path === folderPath) { if(!folder.tasks) { folder.tasks = []; } let id = 1; for(let i = 0; i < folder.tasks.length; i++) { id = folder.tasks[i].id+1; } data.id = id; folder.tasks.push(data); } return folder; })) .then(config => save(config)) .catch(err => {throw err}); const deleteTask = (folderName, folderPath) => { getData() .then(config => config.forEach(folder => { if(folder.folder.name === folderName && folder.folder.path === folderPath) { folder.tasks.filter(task => { /*if(/* Verify that the task is the correct one to delete) { return false; } */ return true; }); } }) ) }; const get = () => { return getData(); }; return { get: get, saveFolder: saveFolder, saveTask: saveTask, getTasks: getTasks } } module.exports = configHelper();
JavaScript
0.000002
@@ -696,17 +696,16 @@ skId) =%3E - %0A get @@ -754,17 +754,16 @@ older =%3E - %0A f @@ -1027,19 +1027,16 @@ err;%7D); -%0A %0A%0A cons @@ -1209,17 +1209,16 @@ onfig =%3E - %0A c @@ -1584,33 +1584,576 @@ lder = (data +, folderName, folderPath ) =%3E + %7B %0A +if(folderName %7C%7C folderPath) %7B%0A return getData()%0A .then(config =%3E %7Bconsole.log(config); return config;%7D)%0A .then(config =%3E config.folders.map(folder =%3E %7B%0A if(folder.folder.name === folderName && folder.folder.path === folderPath) %7B%0A return data;%0A %7D %0A return folder;%0A %7D))%0A .then(config =%3E %7Bconsole.log(%22new data:%22); console.log(config); return config;%7D)%0A .then(newConfig =%3E save(newConfig))%0A .catch(err =%3E %7B%0A throw err;%0A %7D);%0A %7D%0A return getData()%0A @@ -2282,16 +2282,20 @@ =%3E err); +%0A %7D %0A%0A let @@ -2360,20 +2360,16 @@ , config -Name ),%0A @@ -2470,16 +2470,19 @@ %3E err);%0A + %0A%0A const @@ -2529,142 +2529,44 @@ ) =%3E -%0A getData()%0A .then(config =%3E%0A config.map(folder =%3E %7B%0A if(folder.folder.name === folderName && folder.folder.path === + %7B%0A%0A return getFolder(folderName, fol @@ -2577,242 +2577,72 @@ ath) - %7B %0A - if(!folder.tasks) %7B%0A folder.tasks = %5B%5D;%0A %7D%0A let id = 1;%0A for(let i = 0; i %3C folder.tasks.length; i++) %7B%0A id = folder.tasks%5Bi%5D.id+1;%0A %7D%0A data.id = id;%0A +.then(folder =%3E %7B%0A folder.tasks = folder.tasks %7C%7C %5B%5D;%0A @@ -2674,20 +2674,16 @@ ;%0A - -%7D return f @@ -2685,33 +2685,30 @@ urn folder;%0A - %7D) -) %0A .then(c @@ -2720,53 +2720,207 @@ =%3E -save(config))%0A .catch(err =%3E %7Bthrow err%7D); +%7Bconsole.log(%22new folder:%22); console.log(config); return config;%7D)%0A .then(folder =%3E %7B%0A console.log(folderName, folderPath);%0A return saveFolder(folder, folderName, folderPath);%0A %7D)%0A %7D %0A%0A @@ -3429,20 +3429,8 @@ %0A - saveFolder: sav @@ -3454,33 +3454,13 @@ Task -: saveTask,%0A getTasks: +,%0A get
3362e68fe38b849930436612eb965772b8cb5fb5
Add missing license heading
gulpfile.babel.js
gulpfile.babel.js
"use strict"; import gulp from "gulp"; import exit from "gulp-exit"; import babel from "gulp-babel"; import sourcemaps from "gulp-sourcemaps"; import babelRegister from "babel-register"; // Import testing modules. import mocha from "gulp-mocha"; import istanbul from "gulp-istanbul"; const isparta = require('isparta'); // Runs the Mocha test suite. gulp.task('test', () => { gulp.src('src/**/*.js') .on('finish', () => { gulp.src('test/**/*.js') .pipe(mocha({ reporter: 'spec', timeout: 2000, compilers: { js: babelRegister } })) }); }); // Instrument for coverage. gulp.task('coverage', () => { gulp.src('src/**/*.js') .pipe(istanbul({ instrumenter: isparta.Instrumenter })) .pipe(istanbul.hookRequire()) .on('finish', () => { gulp.src('test/**/*.js') .pipe(mocha({ reporter: 'spec', timeout: 2000, compilers: { js: babelRegister } })) .pipe(istanbul.writeReports()) }); }); // Transpile with Babel. gulp.task('dist', () => { gulp.src('src/**/*.js') .pipe(sourcemaps.init()) .pipe(babel()) .pipe(sourcemaps.write('.', {sourceRoot: '../src/'})) .pipe(gulp.dest('dist')); }); gulp.task('default', ['test', 'dist']);
JavaScript
0.000001
@@ -1,8 +1,620 @@ +/*%0A * Copyright 2015 Google Inc. All Rights Reserved.%0A *%0A * Licensed under the Apache License, Version 2.0 (the %22License%22);%0A * you may not use this file except in compliance with the License.%0A * You may obtain a copy of the License at%0A *%0A * http://www.apache.org/licenses/LICENSE-2.0%0A *%0A * Unless required by applicable law or agreed to in writing, software%0A * distributed under the License is distributed on an %22AS IS%22 BASIS,%0A * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A * See the License for the specific language governing permissions and%0A * limitations under the License.%0A */%0A %22use str
d03e40cc13d76156c2afd6a5e6f9d720e3652b59
Add jquery-migrate in admin.
core/app/assets/javascripts/admin/spree_core.js
core/app/assets/javascripts/admin/spree_core.js
//= require jquery-ui //= require modernizr //= require jquery.cookie //= require jquery.delayedobserver //= require jquery.jstree/jquery.jstree //= require jquery.alerts/jquery.alerts //= require jquery.powertip //= require jquery.vAlign //= require css_browser_selector_dev //= require spin //= require trunk8 //= require jquery.adaptivemenu //= require equalize //= require responsive-tables //= require jquery.horizontalNav //= require_tree . var Spree = {};
JavaScript
0
@@ -1,24 +1,57 @@ +//= require jquery-migrate-1.0.0%0A //= require jquery-ui%0A//
e12c47b769255eca949780472e4a45c9553d72de
Fix nightwatch server URL routing
gulpfile.babel.js
gulpfile.babel.js
/*eslint one-var: 0 */ // Core deps // Use require() because of rollup const gulp = require('gulp'); const notify = require('gulp-notify'); const gulpif = require('gulp-if'); const size = require('gulp-size'); const plumber = require('gulp-plumber'); const lazypipe = require('lazypipe'); const filter = require('gulp-filter'); const gulprun = require('run-sequence'); const yargs = require('yargs'); const browserSync = require('browser-sync'); const wct = require('web-component-tester'); // HTML const inline = require('gulp-inline-source'); const processInline = require('gulp-process-inline'); const minify = require('gulp-htmlmin'); // JS const eslint = require('gulp-eslint'); const rollup = require('gulp-rollup-file'); const resolve = require('rollup-plugin-node-resolve'); const commonJs = require('rollup-plugin-commonjs'); const babel = require('rollup-plugin-babel'); const json = require('rollup-plugin-json'); // CSS const postcss = require('gulp-postcss'); const autoprefixer = require('autoprefixer'); const cssImport = require('postcss-import'); const bs = browserSync.create(), nightwatchServer = browserSync.create(), argv = yargs.boolean(['debug']).argv, errorNotifier = () => plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }), OPTIONS = { rollup: { plugins: [ resolve({ main: true, browser: true }), commonJs(), json(), babel({ exclude: 'node_modules/**/*' }) ], format: 'iife' }, postcss: [ cssImport(), autoprefixer() ], inline: { compress: false, swallowErrors: true }, HTMLmin: { removeComments: true, removeCommentsFromCDATA: true, collapseWhitespace: true, conservativeCollapse: true, caseSensitive: true, keepClosingSlash: true, customAttrAssign: [/\$=/], minifyCSS: true, minifyJS: true }, browserSync: { server: { baseDir: './', index: 'demo/index.html', routes: { '/': './bower_components' } }, open: false, notify: false }, nightwatchServer: { server: { baseDir: './', index: 'nightwatch/server/index.html', routes: { '/components': './bower_components', '/node_modules': './node_modules', '/components/simpla-text/simpla-text.html': './simpla-text.html', '/components/simpla-text/simpla-text-editor.html': './simpla-text-editor.html', '/': 'nightwatch/server' } }, open: false, notify: false, port: 3333, ui: { port: false } }, nightwatch: { configFile: 'nightwatch.conf.js' } }; const processJs = lazypipe() .pipe(eslint) .pipe(eslint.format) .pipe(() => gulpif(!argv.debug, eslint.failAfterError())) .pipe(rollup, OPTIONS.rollup); gulp.task('build', () => { let styles = processInline(), scripts = processInline(); return gulp.src(['src/*.html']) .pipe(errorNotifier()) // Inline assets .pipe(inline(OPTIONS.inline)) // JS .pipe(scripts.extract('script')) .pipe(processJs()) .pipe(scripts.restore()) // CSS .pipe(styles.extract('style')) .pipe(postcss(OPTIONS.postcss)) .pipe(styles.restore()) .pipe(gulpif(!argv.debug, minify(OPTIONS.HTMLmin))) .pipe(size({ gzip: true })) .pipe(gulp.dest('.')) }); gulp.task('build:tests', () => { const js = filter((file) => /\.(js)$/.test(file.path), { restore: true }), html = filter((file) => /\.(html)$/.test(file.path), { restore: true }), scripts = processInline(); return gulp.src(['test/**/*']) .pipe(errorNotifier()) .pipe(html) .pipe(inline(OPTIONS.inline)) .pipe(scripts.extract('script')) .pipe(processJs()) .pipe(scripts.restore()) .pipe(html.restore) .pipe(js) .pipe(processJs()) .pipe(js.restore) .pipe(gulp.dest('.test')); }); wct.gulp.init(gulp); gulp.task('serve:nightwatch', () => nightwatchServer.init(OPTIONS.nightwatchServer)); gulp.task('serve:demo', () => bs.init(OPTIONS.browserSync)); gulp.task('serve', ['serve:demo', 'serve:nightwatch']); gulp.task('refresh', () => bs.reload()); gulp.task('test', () => gulprun('build', 'build:tests', 'test:local')); gulp.task('watch:src', () => gulp.watch(['src/**/*'], () => gulprun('build', 'refresh'))); gulp.task('watch:tests', () => gulp.watch(['test/**/*'], () => gulprun('build:tests'))) gulp.task('watch', ['watch:src', 'watch:tests']); gulp.task('default', ['build', 'build:tests', 'serve', 'watch']);
JavaScript
0.000001
@@ -2609,140 +2609,14 @@ ext/ -simpla-text.html': './simpla-text.html',%0A '/components/simpla-text/simpla-text-editor.html': './simpla-text-editor.html +': './ ',%0A
c4712514da56f395838647f8e39ce417b5a5bdaf
Add registrationTypeOptions; cleanup
client/templates/registerWizard/steps/accommodations/accommodations.js
client/templates/registerWizard/steps/accommodations/accommodations.js
Template.wizardAccommodations.helpers({ "requiresAccommodations": function () { /* * Determine if registration type requires accommodations. * If accommodations are required, return true. */ // // Get current age value from form let registrationType = AutoForm.getFieldValue("registrationType") // If daily or weekly, return true, otherwise return false if (registrationType === 'daily' || registrationType === 'weekly') { return true; } else { return false; } } });
JavaScript
0
@@ -313,16 +313,17 @@ onType%22) +; %0A%0A // @@ -514,16 +514,360 @@ ;%0A %7D%0A + %7D,%0A 'registrationTypeOptions': function () %7B%0A // registration types used on the registration form%0A return %5B%0A %7Blabel: %22Commuter (sleeping elsewhere)%22, value: %22commuter%22%7D,%0A %7Blabel: %22Daily (staying overnight)%22, value: %22daily%22%7D,%0A %7Blabel: %22Full Week (staying overnight all nights)%22, value: %22weekly%22%7D%0A %5D;%0A %7D%0A%7D);%0A
9f662ace52d1883c19fd5eb894d26046de5cf29f
Fix formatting of tests
test/elegant-pair.js
test/elegant-pair.js
'use strict'; 'use strict'; const should = require('should'); describe('Elegant Pair Tests', function() { it('should load the Elegant Pair library', function(done) { try { const elegantPair = require('../index'); done(); } catch (err) { done(err); } }); it('should generate an elegant pair: x >= y', function(done) { try { const elegantPair = require('../index'); let x = 92; let y = 23; let z = elegantPair.pair(x, y); should.equal(z, 8579); done(); } catch (err) { done(err); } }); it('should generate an elegant pair: x >= y', function(done) { try { const elegantPair = require('../index'); let x = 23; let y = 92; let z = elegantPair.pair(x, y); should.equal(z, 8487); done(); } catch (err) { done(err); } }); it('should inverse an elegant pair: l < q', function(done) { try { const elegantPair = require('../index'); let z = 8487; let xy = elegantPair.unpair(z); should.deepEqual(xy, [23, 92]); done(); } catch (err) { done(err); } }); it('should inverse an elegant pair: l >= q', function(done) { try { const elegantPair = require('../index'); let z = 8579; let xy = elegantPair.unpair(z); should.deepEqual(xy, [92, 23]); done(); } catch (err) { done(err); } }); });
JavaScript
0.001388
@@ -102,17 +102,18 @@ ion() %7B%0A -%09 + it('shou @@ -156,33 +156,34 @@ unction(done) %7B%0A -%09 + try %7B%0A co @@ -227,33 +227,34 @@ ;%0A done();%0A -%09 + %7D catch (err) @@ -247,33 +247,34 @@ %7D catch (err) %7B%0A -%09 + done(err);%0A%09 @@ -268,37 +268,40 @@ done(err);%0A -%09 + %7D%0A -%09 + %7D);%0A%09%0A -%09 + it('should g @@ -343,33 +343,34 @@ unction(done) %7B%0A -%09 + try %7B%0A co @@ -517,33 +517,34 @@ ;%0A done();%0A -%09 + %7D catch (err) @@ -537,37 +537,38 @@ %7D catch (err) %7B%0A -%09 + done(err);%0A%09 %7D%0A @@ -558,37 +558,40 @@ done(err);%0A -%09 + %7D%0A -%09 + %7D);%0A%09%0A -%09 + it('should g @@ -633,33 +633,34 @@ unction(done) %7B%0A -%09 + try %7B%0A co @@ -807,33 +807,34 @@ ;%0A done();%0A -%09 + %7D catch (err) @@ -827,33 +827,34 @@ %7D catch (err) %7B%0A -%09 + done(err);%0A%09 @@ -848,30 +848,32 @@ done(err);%0A -%09 + %7D%0A -%09 + %7D);%0A%09%0A it(' @@ -921,33 +921,34 @@ unction(done) %7B%0A -%09 + try %7B%0A co @@ -1088,33 +1088,34 @@ ;%0A done();%0A -%09 + %7D catch (err) @@ -1108,37 +1108,38 @@ %7D catch (err) %7B%0A -%09 + done(err);%0A%09 %7D%0A @@ -1137,21 +1137,24 @@ r);%0A -%09 + %7D%0A -%09 + %7D);%0A%09%0A -%09 + it(' @@ -1211,17 +1211,18 @@ done) %7B%0A -%09 + try %7B%0A @@ -1378,17 +1378,18 @@ done();%0A -%09 + %7D catc @@ -1398,17 +1398,18 @@ (err) %7B%0A -%09 + done @@ -1419,14 +1419,16 @@ r);%0A -%09 + %7D%0A -%09 + %7D);%0A
e9d8648dbe3eceeb8effa058b4d6838010becf09
Fix tests for unhandled rejections on more recent Ember versions.
tests/unit/unhandled-rejection-test.js
tests/unit/unhandled-rejection-test.js
import { Promise as RSVPPromise } from 'rsvp'; import { module, test } from 'qunit'; const HAS_NATIVE_PROMISE = typeof Promise !== 'undefined'; const HAS_UNHANDLED_REJECTION_HANDLER = 'onunhandledrejection' in window; module('unhandle promise rejections', function(hooks) { hooks.beforeEach(function(assert) { let originalPushResult = assert.pushResult; assert.pushResult = function(resultInfo) { // Inverts the result so we can test failing assertions resultInfo.result = !resultInfo.result; resultInfo.message = `Failed: ${resultInfo.message}`; originalPushResult(resultInfo); }; }); test('RSVP promises cause an unhandled rejection', function(assert) { let done = assert.async(); // ensure we do not exit this test until the assertion has happened setTimeout(done, 10); new RSVPPromise(resolve => { setTimeout(resolve); }).then(function() { throw new Error('whoops!'); }); }); if (HAS_NATIVE_PROMISE && HAS_UNHANDLED_REJECTION_HANDLER) { test('native promises cause an unhandled rejection', function(assert) { let done = assert.async(); // ensure we do not exit this test until the assertion has happened setTimeout(done, 10); new self.Promise(resolve => { setTimeout(resolve); }).then(function() { throw new Error('whoops!'); }); }); } });
JavaScript
0
@@ -269,16 +269,39 @@ ooks) %7B%0A + let WINDOW_ONERROR;%0A%0A hooks. @@ -334,20 +334,534 @@ ) %7B%0A -let +// capturing this outside of module scope to ensure we grab%0A // the test frameworks own window.onerror to reset it%0A WINDOW_ONERROR = window.onerror;%0A%0A // this catches the native promise unhandled rejection case because QUnit%0A // dispatches these to %60assert.pushResult%60, so we handle the failure being%0A // pushed and convert it to a passing assertion%0A //%0A // Also, on Ember %3C 2.17 this is called for the RSVP unhandled rejection%0A // case (because it goes through Adapter.exception).%0A assert._ original @@ -1113,16 +1113,22 @@ ;%0A +this._ original @@ -1165,16 +1165,91 @@ %0A %7D);%0A%0A + hooks.afterEach(function() %7B%0A window.onerror = WINDOW_ONERROR;%0A %7D);%0A%0A test(' @@ -1340,24 +1340,433 @@ t.async();%0A%0A + window.onerror = message =%3E %7B%0A assert._originalPushResult(%7B%0A result: /whoops!/.test(message),%0A actual: message,%0A expected: 'to include %60whoops!%60',%0A message:%0A 'error should bubble out to window.onerror, and therefore fail tests (due to QUnit implementing window.onerror)',%0A %7D);%0A%0A return true; // prevent %22bubbling%22 and therefore failing the test%0A %7D;%0A%0A // ensur
ff5a9c279ac117b120eadec94341e15136c01d95
use toLowerCase instead of toUpperCase
src/support/valid-custom-element.js
src/support/valid-custom-element.js
export default function (name) { const reservedNames = [ 'annotation-xml', 'color-profile', 'font-face', 'font-face-src', 'font-face-uri', 'font-face-format', 'font-face-name', 'missing-glyph' ]; return name.indexOf('-') > 0 && name.toUpperCase() === name && reservedNames.indexOf(name) < 0; }
JavaScript
0.000033
@@ -271,11 +271,11 @@ e.to -Upp +Low erCa
5121f780f0af43e6736338360e392dca3cff7f47
Add helper method
collect-web/collect-webapp/src/main/webapp/js/openforis/of-ui-forms.js
collect-web/collect-webapp/src/main/webapp/js/openforis/of-ui-forms.js
OF.UI.Forms = function() {}; /** * Populate a select using a list of items * Option value is set according to the specified valueKey and * option text content is set according to the specified labelKey * * @param $select * @param items * @param valueKey (optional, default value will be item.toString()) * @param labelKeyOrFunction (optional, default is valueKey, if specified) * @param callback */ OF.UI.Forms.populateSelect = function($select, items, valueKey, labelKeyOrFunction, addEmptyOption) { $select.empty(); if (addEmptyOption) { $select.append($("<option />").val("").text("")); } $.each(items, function(i, item) { var value = item.hasOwnProperty(valueKey) ? item[valueKey]: item; var label = null; if (labelKeyOrFunction) { var typeOfLabelKey = typeof labelKeyOrFunction; switch (typeOfLabelKey) { case "function": label = labelKeyOrFunction(item); break; case "string": label = OF.Objects.getProperty(item, labelKeyOrFunction); break; } } if (label == null || label == "") { label = value; } $select.append($("<option />").val(value).text(label)); }); $select.val([]); }; OF.UI.Forms.populateDropdown = function($dropdownContainer, items, valueKey, labelKey) { var dropdownMenu = $dropdownContainer.find(".dropdown-menu"); dropdownMenu.empty(); $.each(items, function(i, item) { var value = item.hasOwnProperty(valueKey) ? item[valueKey]: item; var label = item.hasOwnProperty(labelKey) ? item[labelKey]: value; var item = $('<li role="presentation" />'); var link = $('<a role="menuitem" tabindex="-1" href="#" />'); link.text(label); item.append(link); dropdownMenu.append(item); }); }; OF.UI.Forms.toJSON = function($form) { var result = {}; var array = $form.serializeArray(); $.each(array, function() { var correctedValue; if (this.value == null) { correctedValue = ''; } else if (typeof this.value === 'string') { correctedValue = this.value.trim(); } else { correctedValue = this.value; } result[this.name] = correctedValue; }); return result; }; OF.UI.Forms.getFieldNames = function(form) { var fields = []; var array = form.serializeArray(); $.each(array, function() { fields.push(this.name); }); return fields; }; OF.UI.Forms.getParentForm = function(inputField) { if (typeof inputField == "form") { return inputField; } else { var form = inputField.closest("form"); return form; } }; OF.UI.Forms.getInputFields = function($form, fieldName) { var fieldNames = []; var inputFields = []; if (fieldName) { fieldNames.push(fieldName); } else { fieldNames = OF.UI.Forms.getFieldNames($form); } fieldNames.each(function(i, fieldName) { var field = $('[name='+fieldName+']', $form); if ( field.length == 1 ) { inputFields.push(field); } else { field.each(function(i, $inputField) { inputFields.push($inputField); }); } }); return inputFields; } /** * Set the specified values into a form according to the field names * * @param $form * @param $data */ OF.UI.Forms.fill = function($form, $data) { $.each($data, function(fieldName, value) { OF.UI.Forms.setFieldValue($form, fieldName, value); }); }; /** * Sets the metadata "visited" on the field with the specified value */ OF.UI.Forms.setFieldVisited = function(field, visited) { field.data("visited", typeof visited == 'undefined' || visited); }; OF.UI.Forms.setAllFieldsVisited = function(form, visited) { var fieldNames = OF.UI.Forms.getFieldNames(form); $.each(fieldNames, function(i, fieldName) { var fields = OF.UI.Forms.getInputFields(form, fieldName); fields.each(function(i, field) { field.data("visited", typeof visited == 'undefined' || visited); }); }); }; OF.UI.Forms.setFieldValue = function($form, fieldName, value) { var $inputFields = $('[name='+fieldName+']', $form); if ( $inputFields.length == 1 ) { var inputFieldEl = $inputFields[0]; switch(OF.UI.Forms.getInputType(inputFieldEl)) { case "hidden": case "text" : case "textarea": inputFieldEl.value = value; break; } } else { $inputFields.each(function(i, $inputField) { switch(OF.UI.Forms.getInputType($inputField)) { case "radio" : case "checkbox": var checked = $(this).attr('value') == value; $(this).attr("checked", checked); break; } }); } }; /** * Returns the input type of a field. * If the field is not a "input" element, then returns the node name of the element. * * @param inputField * @returns */ OF.UI.Forms.getInputType = function(inputField) { if ( inputField instanceof jQuery ) { if ( inputField.length == 1 ) { var field = inputField.get(0); return OF.UI.Forms.getInputType(field); } else { //no single input field found return null; } } var type = inputField.type; if ( ! type ) { //e.g. textarea element type = inputField.nodeName.toLowerCase(); } return type; }; /** * Returns the label associated to the specified field * * @param $field * @returns */ OF.UI.Forms.getFieldLabel = function($field) { var $formGroup = $field.closest('.form-group'); var $labelEl = $formGroup.find('.control-label'); return $labelEl == null ? "": $labelEl.text(); };
JavaScript
0.000004
@@ -1193,16 +1193,337 @@ %0D%0A%7D;%0D%0A%0D%0A +OF.UI.Forms.selectOptionsInSelect = function($select, items, valueKey) %7B%0D%0A%09var options = $select.find(%22option%22);%0D%0A%09$.each(options, function(i, option) %7B%0D%0A%09%09var item = OF.Arrays.findItem(items, valueKey, option.value);%0D%0A%09%09var selected = item != null;%0D%0A%09%09$(option).attr('selected', selected ? 'selected': null);%0D%0A%09%7D);%0D%0A%7D;%0D%0A %0D%0AOF.UI.
737c97f2354d336d8ee447ef4e53315d9c4ac7b9
Update api.js
backend/api.js
backend/api.js
var mysql = require('mysql'), express = require('express'), app = express(), http = require('http'), multer = require('multer'), jwt = require('jsonwebtoken'), crypto = require('crypto'), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), myConnection = require('express-myconnection'), bodyParser = require('body-parser'), server = http.createServer(app), secret = require('./config/secret'), io = require('socket.io'), routes = require('./routes.js'); io = io.listen(server); require('./sockets/base')(io); var connectionPool = { host : 'localhost', user : 'root', password : '', database : 'Enviromap' }; var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res) { console.log(req); res.send('respond with a resource'); }); // optional - set socket.io logging level io.set('log level', 1000); app.use(multer( { dest: '../frontend/photos/large' })); app.use(bodyParser()); app.use(cookieParser()); app.use(bodyParser()); app.use(myConnection(mysql, connectionPool, 'pool')); app.use('/',express.static('../frontend')); //console.log(__dirname); app.all('*', function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); res.set('Access-Control-Allow-Credentials', true); res.set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT'); res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization'); if ('OPTIONS' === req.method) return res.send(200); next(); }); //user app.get('/api/problems', routes.getProblems); app.get('/api/problems/:id', routes.getProblemId); app.get('/api/users/:idUser', routes.getUserId); app.get('/api/activities/:idUser', routes.getUserActivity); app.post('/api/problempost', routes.postProblem); app.post('/api/vote', routes.postVote); app.get('/api/getTitles',routes.getTitles); app.get('/api/resources/:name',routes.getResource); //new api for adding new photos to existed problem app.post('/api/photo/:id',routes.addNewPhotos); app.post('/api/login', routes.logIn); app.get('/api/logout', routes.logOut); app.post('/api/register', routes.register); //admin app.get('/api/not_approved', routes.notApprovedProblems); app.delete('/api/problem/:id', routes.deleteProblem); app.delete('/api/user/:id', routes.deleteUser); app.delete('/api/activity/:id', routes.deleteComment); app.delete('/api/photo/:id', routes.deletePhoto); app.put('/api/edit', routes.editProblem); app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); server.listen(8090); console.log('Rest Demo Listening on port 8090');
JavaScript
0.000001
@@ -717,16 +717,20 @@ word : ' +root ',%0D%0A
6980a8383d1902e93829cc5e91a398b6dc8bc64b
Fix codepan preview errors.
website/uiw/src/components/Markdown/index.js
website/uiw/src/components/Markdown/index.js
import React, { useEffect, useState } from 'react'; import ReactDOM from 'react-dom'; import CodePreview from '@uiw/react-code-preview'; import MarkdownPreview from '@uiw/react-markdown-preview'; import Heading from './Heading'; import Footer from './Footer'; import styles from './index.module.less'; const components = new Map(); export default function CreatePage(props = {}) { const { renderPage, dependencies, path } = props; const [mdStr, setMdStr] = useState(''); async function getMarkdown() { if (!renderPage || typeof renderPage !== 'function') return; components.clear(); const md = await props.renderPage(); const markdown = md.replace( /<!--\s?DemoStart\s?(.*)-->([^]+?)<!--\s?End\s?-->/g, (match, parame, code, offset) => { parame = parame.replace(/(^,*)|(,*$)/g, ''); parame = parame ? parame.split(',') : []; const bgWhite = parame.indexOf('bgWhite') > -1; const noCode = parame.indexOf('noCode') > -1; const noPreview = parame.indexOf('noPreview') > -1; const noScroll = parame.indexOf('noScroll') > -1; const codePen = parame.indexOf('codePen') > -1; const id = offset.toString(36); const codeStr = code.match(/```(.*)\n([^]+)```/); // eslint-disable-next-line const version = VERSION || '2.0.0'; const codePenOption = !codePen ? undefined : { title: `uiw${version} - demo`, js: codeStr[2].replace( '_mount_', 'document.getElementById("container")', ) || '', html: '<div id="container" style="padding: 24px"></div>', css_external: `https://unpkg.com/uiw@${version}/dist/uiw.min.css`, js_external: `https://unpkg.com/react@16.x/umd/react.development.js;https://unpkg.com/react-dom@16.x/umd/react-dom.development.js;https://unpkg.com/classnames@2.2.6/index.js;https://unpkg.com/uiw@${version}/dist/uiw.min.js;https://unpkg.com/@uiw/codepen-require-polyfill@1.0.0/index.js`, }; components.set( id, React.createElement( CodePreview, Object.assign({ code: codeStr[2], dependencies: dependencies || {}, noPreview, bgWhite, noCode, noScroll, codePenOption, }), codeStr[2], ), ); return `<div id=${id}></div>`; }, ); await setMdStr(markdown); renderDOM(); } function renderDOM() { for (const [id, component] of components) { const div = document.getElementById(id); if (div instanceof HTMLElement) { // ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(div)); ReactDOM.render(component, div); } } } useEffect(() => { getMarkdown(); return () => { if (components) { components.clear(); } }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <div> <MarkdownPreview renderers={{ heading: Heading }} source={mdStr} /> <div className={styles.docinfo}> <Footer path={path} /> </div> </div> ); }
JavaScript
0
@@ -2062,17 +2062,17 @@ ill@1.0. -0 +2 /index.j
dd27660d466883f52a256a75b7b6e79e2a55fb4b
add more logging
src/read-fs-albums.js
src/read-fs-albums.js
import { basename, dirname, extname } from 'path' import log from 'npmlog' import readTracks from './read-fs-tracks.js' import { Artist, Cover, Cuesheet, MultitrackAlbum as Multitrack, SingletrackAlbum as Singletrack, Track } from '@packard/model' function extractTypeFromTree (type, tree, visit) { for (let e of tree) { if (Array.isArray(e)) extractTypeFromTree(type, e, visit) else if (e instanceof type) visit(e) } } export default function readAlbums (root) { const cues = new Map() const covers = new Map() const albums = new Set() return readTracks(root).then(postprocess) function postprocess (tree) { extractTypeFromTree( Cover, tree, e => covers.set(basename(e.path, extname(e.path)), e) ) extractTypeFromTree( Cuesheet, tree, e => cues.set(basename(e.path, extname(e.path)), e) ) return simplify(tree) } function simplify (tree) { return makeAlbum(filterMixes(tree)) } function filterMixes (tree) { const remaining = new Set(tree) for (let thing of tree) { if (Array.isArray(thing)) { remaining.delete(thing) simplify(thing) } else if (thing instanceof Track) { const base = basename(thing.file.path, extname(thing.file.path)) if (cues.get(base) || covers.get(base)) { remaining.delete(thing) const mix = Singletrack.fromTrack(thing) albums.add(mix) const cuesheet = cues.get(base) if (cuesheet) { remaining.delete(cuesheet) mix.cuesheet = cuesheet.path } const cover = covers.get(base) if (cover) { remaining.delete(cover) mix.pictures.push(cover) } } } } return remaining } function makeAlbum (tracks) { const artistNames = new Set() const albumNames = new Set() const pictures = new Set() const tracklisting = [] for (let track of tracks) { if (!(track instanceof Track)) { if (track instanceof Cover) { tracks.delete(track) pictures.add(track) } else { console.error('whut', track) } continue } tracks.delete(track) artistNames.add(track.artist.name) albumNames.add(track.album.name) tracklisting.push(track) } if (tracks.size > 0) { log.warn( 'makeAlbum', tracks.size + ' leftover tracks after assembling album!' ) } if (tracklisting.length > 0) { if (albumNames.size > 1) throw new Error('too many album names!') let artistName if (artistNames.size > 1) { artistName = 'Various Artists' } else { artistName = [...artistNames][0] } const albumName = [...albumNames][0] const directory = dirname(tracklisting[0].path) const artist = new Artist(artistName) const album = new Multitrack( albumName, artist, { path: directory, tracks: tracklisting } ) album.pictures = album.pictures.concat([...pictures]) albums.add(album) } return albums } }
JavaScript
0
@@ -639,24 +639,66 @@ ss (tree) %7B%0A + log.silly('readAlbums', 'tree', tree)%0A extractT @@ -706,24 +706,24 @@ peFromTree(%0A - Cover, @@ -797,24 +797,70 @@ ), e)%0A )%0A + log.silly('readAlbums', 'covers', covers)%0A extractT @@ -958,21 +958,68 @@ h)), e)%0A - ) +%0A log.silly('readAlbums', 'cuesheets', cues) %0A%0A re @@ -2303,27 +2303,49 @@ -console.error('whut +log.warn('makeAlbum', 'unknown file found ', t
98dd082bf30909328b3441d1c6f94a7da1dbd0ef
add item to front of list instead of end
src/reducers/items.js
src/reducers/items.js
import { append, slice } from 'ramda' // const initialState = { // expenseItems: [] // } export default (state = [], action) => { switch (action.type) { case 'ADD_ITEM': return append({ id: action.id, title: action.title, cost: action.cost }, state) case 'REMOVE_ITEM': return slice(0, -1, state) default: return state } }
JavaScript
0
@@ -2,18 +2,19 @@ mport %7B -a p +re pend, sl @@ -192,10 +192,11 @@ urn -a p +re pend
4c2960400d428e8029537849c57d681b6678601b
Update trait render view
src/trait_manager/view/TraitView.js
src/trait_manager/view/TraitView.js
var Backbone = require('backbone'); module.exports = Backbone.View.extend({ events:{ 'change': 'onChange' }, initialize(o) { var md = this.model; this.config = o.config || {}; this.pfx = this.config.stylePrefix || ''; this.ppfx = this.config.pStylePrefix || ''; this.target = md.target; this.className = this.pfx + 'trait'; this.labelClass = this.ppfx + 'label'; this.fieldClass = this.ppfx + 'field ' + this.ppfx + 'field-' + md.get('type'); this.inputhClass = this.ppfx + 'input-holder'; md.off('change:value', this.onValueChange); this.listenTo(md, 'change:value', this.onValueChange); this.tmpl = '<div class="' + this.fieldClass +'"><div class="' + this.inputhClass +'"></div></div>'; }, /** * Fires when the input is changed * @private */ onChange() { this.model.set('value', this.getInputEl().value); }, getValueForTarget() { return this.model.get('value'); }, /** * On change callback * @private */ onValueChange() { var m = this.model; var trg = this.target; var name = m.get('name'); var value = this.getValueForTarget(); // Chabge property if requested otherwise attributes if(m.get('changeProp')){ trg.set(name, value); }else{ var attrs = _.clone(trg.get('attributes')); attrs[name] = value; trg.set('attributes', attrs); } }, /** * Render label * @private */ renderLabel() { this.$el.html('<div class="' + this.labelClass + '">' + this.getLabel() + '</div>'); }, /** * Returns label for the input * @return {string} * @private */ getLabel() { var model = this.model; var label = model.get('label') || model.get('name'); return label.charAt(0).toUpperCase() + label.slice(1).replace(/-/g,' '); }, /** * Returns input element * @return {HTMLElement} * @private */ getInputEl() { if(!this.$input) { var md = this.model; var trg = this.target; var name = md.get('name'); const plh = md.get('placeholder') || md.get('default'); const type = md.get('type') || 'text'; const attrs = trg.get('attributes'); const min = md.get('min'); const max = md.get('max'); const value = md.get('changeProp') ? trg.get(name) : md.get('value') || attrs[name]; const input = $(`<input type="${type} placeholder="${plh}" value="${value}">`); if (min) { input.prop('min', min); } if (max) { input.prop('max', max); } this.$input = input; } return this.$input.get(0); }, getModelValue() { var value; var model = this.model; var target = this.target; var name = model.get('name'); if (model.get('changeProp')) { value = target.get(name); } else { var attrs = target.get('attributes'); value = model.get('value') || attrs[name]; } return value; }, /** * Renders input * @private * */ renderField() { if(!this.$input){ this.$el.append(this.tmpl); var el = this.getInputEl(); this.$el.find('.' + this.inputhClass).prepend(el); } }, render() { this.renderLabel(); this.renderField(); this.el.className = this.className; return this; }, });
JavaScript
0
@@ -2087,16 +2087,22 @@ efault') + %7C%7C '' ;%0A @@ -2391,16 +2391,17 @@ %22$%7Btype%7D +%22 placeho @@ -2417,29 +2417,76 @@ lh%7D%22 - value=%22$%7Bvalue%7D%22%3E%60); +%3E%60);%0A%0A if (value) %7B%0A input.prop('value', value);%0A %7D %0A%0A
c6627ab57bebcdb1be74d761cf85283be43388ae
Fix to non-broken deploy version
src/renderGraphiQL.js
src/renderGraphiQL.js
/* @flow */ /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ type GraphiQLData = { query: ?string, variables: ?Object, result?: Object }; // Current latest version of GraphiQL. const GRAPHIQL_VERSION = '0.4.8'; /** * When express-graphql receives a request which does not Accept JSON, but does * Accept HTML, it may present GraphiQL, the in-browser GraphQL explorer IDE. * * When shown, it will be pre-populated with the result of having executed the * requested query. */ export function renderGraphiQL(data: GraphiQLData): string { const queryString = data.query; const variablesString = data.variables ? JSON.stringify(data.variables, null, 2) : null; const resultString = data.result ? JSON.stringify(data.result, null, 2) : null; /* eslint-disable max-len */ return `<!-- The request to this GraphQL server provided the header "Accept: text/html" and as a result has been presented GraphiQL - an in-browser IDE for exploring GraphQL. If you wish to receive JSON, provide the header "Accept: application/json" or add "&raw" to the end of the URL within a browser. --> <!DOCTYPE html> <html> <head> <link href="//cdn.jsdelivr.net/graphiql/${GRAPHIQL_VERSION}/graphiql.css" rel="stylesheet" /> <script src="//cdn.jsdelivr.net/fetch/0.9.0/fetch.min.js"></script> <script src="//cdn.jsdelivr.net/react/0.14.7/react.min.js"></script> <script src="//cdn.jsdelivr.net/react/0.14.7/react-dom.min.js"></script> <script src="//cdn.jsdelivr.net/graphiql/${GRAPHIQL_VERSION}/graphiql.min.js"></script> </head> <body> <script> // Collect the URL parameters var parameters = {}; window.location.search.substr(1).split('&').forEach(function (entry) { var eq = entry.indexOf('='); if (eq >= 0) { parameters[decodeURIComponent(entry.slice(0, eq))] = decodeURIComponent(entry.slice(eq + 1)); } }); // Produce a Location query string from a parameter object. function locationQuery(params) { return '?' + Object.keys(params).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); }).join('&'); } // Derive a fetch URL from the current URL, sans the GraphQL parameters. var graphqlParamNames = { query: true, variables: true, operationName: true }; var otherParams = {}; for (var k in parameters) { if (parameters.hasOwnProperty(k) && graphqlParamNames[k] !== true) { otherParams[k] = parameters[k]; } } var fetchURL = locationQuery(otherParams); // Defines a GraphQL fetcher using the fetch API. function graphQLFetcher(graphQLParams) { return fetch(fetchURL, { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(graphQLParams), credentials: 'include', }).then(function (response) { return response.text(); }).then(function (responseBody) { try { return JSON.parse(responseBody); } catch (error) { return responseBody; } }); } // When the query and variables string is edited, update the URL bar so // that it can be easily shared. function onEditQuery(newQuery) { parameters.query = newQuery; updateURL(); } function onEditVariables(newVariables) { parameters.variables = newVariables; updateURL(); } function updateURL() { history.replaceState(null, null, locationQuery(parameters)); } // Render <GraphiQL /> into the body. React.render( React.createElement(GraphiQL, { fetcher: graphQLFetcher, onEditQuery: onEditQuery, onEditVariables: onEditVariables, query: ${JSON.stringify(queryString)}, response: ${JSON.stringify(resultString)}, variables: ${JSON.stringify(variablesString)} }), document.body ); </script> </body> </html>`; }
JavaScript
0.000027
@@ -463,9 +463,9 @@ 0.4. -8 +9 ';%0A%0A
34808b5bf767071f249cc9565890f86efcb7448d
Fix lint errors
src/report/compare.js
src/report/compare.js
/* @flow */ import { formatLeft, formatRight } from './format'; import type { BenchmarkSuiteResult } from '../runner'; import { tTest } from 'experiments.js'; import { mean } from 'simple-statistics'; const defaultSignificanceThreshold = 0.05; const defaultConfidenceLevel = 0.95; /** * Compare the results of two benchmarks, outputting the differences based * on statistical significance. */ export function compareMemoryResults( result1: BenchmarkSuiteResult, result2: BenchmarkSuiteResult, outputFn: (...x: any) => void, significanceThreshold: number = defaultSignificanceThreshold, confidenceLevel: number = defaultConfidenceLevel ): void { const marginOfErrorSize = 3; const marginOfErrorUnits = '%'; const marginOfErrorPrefix = ' ±'; const memorySize = 10; const memoryUnits = ' b'; const changeSize = 5; const changeUnits = '%'; const asyncColumnSize = 1; const benchmarkColumnSize = 40; const memoryColumnSize = memorySize + memoryUnits.length; const changeColumnSize = changeSize + changeUnits.length + marginOfErrorPrefix.length + marginOfErrorSize + marginOfErrorUnits.length; const toPercent = 100; // Sort the input results into a base result (before) and // test result (after) let baseResult; let testResult; if (result1.startTime > result2.startTime) { baseResult = result2; testResult = result1; } else { baseResult = result1; testResult = result2; } outputFn( formatLeft('A', asyncColumnSize), formatLeft('Benchmark', benchmarkColumnSize), formatRight('Memory', memoryColumnSize), formatRight('Change', changeColumnSize) ); outputFn( '-'.repeat(asyncColumnSize), '-'.repeat(benchmarkColumnSize), '-'.repeat(memoryColumnSize), '-'.repeat(changeColumnSize) ); let insignificantBenchmarks = 0; for (let i = 0; i < baseResult.results.length; i++) { const memory = tTest( baseResult.results[i].memorySamples, testResult.results[i].memorySamples, confidenceLevel ); if (memory.probabilityLevel > significanceThreshold) { insignificantBenchmarks += 1; continue; } const asyncColumn = formatLeft(baseResult.results[i].isAsynchronous ? '*' : '', asyncColumnSize); const benchmarkColumn = formatLeft( baseResult.results[i].name, benchmarkColumnSize ); const memoryDifference = Math.round(memory.meanDifference); const memoryColumn = formatRight(memoryDifference, memorySize) + memoryUnits; const baseMean = mean(baseResult.results[i].timingSamples); const change = Math.round(memory.meanDifference * toPercent / baseMean); const interval = memory.confidenceInterval[1] - memory.meanDifference; const marginOfError = Math.round(interval * toPercent / baseMean); const changeColumn = formatRight(change, changeSize) + changeUnits + marginOfErrorPrefix + formatRight(marginOfError, marginOfErrorSize) + marginOfErrorUnits; outputFn(asyncColumn, benchmarkColumn, memoryColumn, changeColumn); } if (insignificantBenchmarks > 0) { outputFn( ` ${insignificantBenchmarks} benchmarks not different ` + `(p > ${significanceThreshold})` ); } } /** * Compare the results of two benchmarks, outputting the differences based * on statistical significance. */ export function compareTimeResults( result1: BenchmarkSuiteResult, result2: BenchmarkSuiteResult, outputFn: (...x: any) => void, significanceThreshold: number = defaultSignificanceThreshold, confidenceLevel: number = defaultConfidenceLevel ): void { const marginOfErrorSize = 3; const marginOfErrorUnits = '%'; const marginOfErrorPrefix = ' ±'; const timeSize = 8; const timeUnits = ' ns'; const changeSize = 5; const changeUnits = '%'; const asyncColumnSize = 1; const benchmarkColumnSize = 40; const timeColumnSize = timeSize + timeUnits.length; const changeColumnSize = changeSize + changeUnits.length + marginOfErrorPrefix.length + marginOfErrorSize + marginOfErrorUnits.length; const toPercent = 100; // Sort the input results into a base result (before) and // test result (after) let baseResult; let testResult; if (result1.startTime > result2.startTime) { baseResult = result2; testResult = result1; } else { baseResult = result1; testResult = result2; } outputFn( formatLeft('A', asyncColumnSize), formatLeft('Benchmark', benchmarkColumnSize), formatRight('Time', timeColumnSize), formatRight('Change', changeColumnSize) ); outputFn( '-'.repeat(asyncColumnSize), '-'.repeat(benchmarkColumnSize), '-'.repeat(timeColumnSize), '-'.repeat(changeColumnSize) ); let insignificantBenchmarks = 0; for (let i = 0; i < baseResult.results.length; i++) { const time = tTest( baseResult.results[i].timingSamples, testResult.results[i].timingSamples, confidenceLevel ); if (time.probabilityLevel > significanceThreshold) { insignificantBenchmarks += 1; continue; } const asyncColumn = formatLeft(baseResult.results[i].isAsynchronous ? '*' : '', asyncColumnSize); const benchmarkColumn = formatLeft( baseResult.results[i].name, benchmarkColumnSize ); const timeDifference = Math.round(time.meanDifference); const timeColumn = formatRight(timeDifference, timeSize) + timeUnits; const baseMean = mean(baseResult.results[i].timingSamples); const change = Math.round(time.meanDifference * toPercent / baseMean); const interval = time.confidenceInterval[1] - time.meanDifference; const marginOfError = Math.round(interval * toPercent / baseMean); const changeColumn = formatRight(change, changeSize) + changeUnits + marginOfErrorPrefix + formatRight(marginOfError, marginOfErrorSize) + marginOfErrorUnits; outputFn(asyncColumn, benchmarkColumn, timeColumn, changeColumn); } if (insignificantBenchmarks > 0) { outputFn( ` ${insignificantBenchmarks} benchmarks not different ` + `(p > ${significanceThreshold})` ); } }
JavaScript
0.000396
@@ -129,21 +129,20 @@ ort %7B%0A -tTest +mean %0A%7D from @@ -146,21 +146,24 @@ om ' -experiments.j +simple-statistic s';%0A @@ -165,36 +165,37 @@ cs';%0Aimport %7B%0A -mean +tTest %0A%7D from 'simple- @@ -187,32 +187,29 @@ %7D from ' -simple-statistic +experiments.j s';%0A%0Acon @@ -2051,20 +2051,16 @@ %0A );%0A - %0A if
7b38f72faf55c80916f90f8a0dd353b51e0e2c47
Copy delegates before listeners are fired, as listeners may unbind delegates before they are called
src/mixin.events.js
src/mixin.events.js
// mixin.listeners // .on(types, fn, [args...]) // Binds a function to be called on events in types. The // callback fn is called with this object as the first // argument, followed by arguments passed to .trigger(), // followed by arguments passed to .on(). // .on(object) // Registers object as a propagation target. Handlers bound // to the propagation target are called with 'this' set to // this object, and the target object as the first argument. // .off(types, fn) // Unbinds fn from given event types. // .off(types) // Unbinds all functions from given event types. // .off(fn) // Unbinds fn from all event types. // .off(object) // Stops propagation of all events to given object. // .off() // Unbinds all functions and removes all propagation targets. // .trigger(type, [args...]) // Triggers event of type. (function(ns) { "use strict"; var mixin = ns.mixin || (ns.mixin = {}); var eventObject = {}; var slice = Function.prototype.call.bind(Array.prototype.slice); function getListeners(object) { if (!object.listeners) { Object.defineProperty(object, 'listeners', { value: {} }); } return object.listeners; } function getDelegates(object) { if (!object.delegates) { Object.defineProperty(object, 'delegates', { value: [] }); } return object.delegates; } function setupPropagation(object1, object2) { var delegates = getDelegates(object1); // Make sure delegates stays unique if (delegates.indexOf(object2) === -1) { delegates.push(object2); } } function teardownPropagation(object1, object2) { var delegates = getDelegates(object1); if (object2 === undefined) { delegates.length = 0; return; } var i = delegates.indexOf(object2); if (i === -1) { return; } delegates.splice(i, 1); } function triggerListeners(object, listeners, args) { var i = -1; var l = listeners.length; var params, result; while (++i < l && result !== false) { params = args.concat(listeners[i][1]); result = listeners[i][0].apply(object, params); } return result; } mixin.events = { // .on(type, fn) // // Callback fn is called with this set to the current object // and the arguments (target, triggerArgs..., onArgs...). on: function(types, fn) { // If types is an object with a trigger method, set it up so that // events propagate from this object. if (arguments.length === 1 && types.trigger) { setupPropagation(this, types); return this; } if (!fn) { throw new Error('Sparky: calling .on("' + types + '", fn) but fn is ' + typeof fn); } var events = getListeners(this); var type, item; if (typeof types === 'string') { types = types.trim().split(/\s+/); item = [fn, slice(arguments, 2)]; } else { return this; } while (type = types.shift()) { // If the event has no listener queue, create one using a copy // of the all events listener array. if (!events[type]) { events[type] = []; } // Store the listener in the queue events[type].push(item); } return this; }, // Remove one or many callbacks. If `context` is null, removes all callbacks // with that function. If `callback` is null, removes all callbacks for the // event. If `events` is null, removes all bound callbacks for all events. off: function(types, fn) { var type, calls, list, i, listeners; // If no arguments passed in, unbind everything. if (arguments.length === 0) { teardownPropagation(this); if (this.listeners) { for (type in this.listeners) { this.listeners[type].length = 0; delete this.listeners[type]; } } return this; } // If types is an object with a trigger method, stop propagating // events to it. if (arguments.length === 1 && types.trigger) { teardownPropagation(this, types); return this; } // No events. if (!this.listeners) { return this; } if (typeof types === 'string') { // .off(types, fn) types = types.trim().split(/\s+/); } else { // .off(fn) fn = types; types = Object.keys(this.listeners); } while (type = types.shift()) { listeners = this.listeners[type]; if (!listeners) { continue; } if (!fn) { this.listeners[type].length = 0; delete this.listeners[type]; continue; } listeners.forEach(function(v, i) { if (v[0] === fn) { listeners.splice(i, i+1); } }); } return this; }, trigger: function(e) { var events = getListeners(this); var args = slice(arguments); var type, target, i, l, params, result; if (typeof e === 'string') { type = e; target = this; } else { type = e.type; target = e.target; } if (events[type]) { args[0] = target; // Use a copy of the event list in case it gets mutated // while we're triggering the callbacks. If a handler // returns false stop the madness. if (triggerListeners(this, events[type].slice(), args) === false) { return this; } } if (!this.delegates) { return this; } // Copy delegates. We may be about to mutate the delegates list. var delegates = this.delegates.slice(); i = -1; l = delegates.length; args[0] = eventObject; if (typeof e === 'string') { // Prepare the event object. It's ok to reuse a single object, // as trigger calls are synchronous, and the object is internal, // so it does not get exposed. eventObject.type = type; eventObject.target = target; } while (++i < l) { delegates[i].trigger.apply(delegates[i], args); } // Return this for chaining return this; } }; })(this);
JavaScript
0
@@ -4545,24 +4545,139 @@ ners(this);%0A +%09%09%09// Copy delegates. We may be about to mutate the delegates list.%0A%09%09%09var delegates = getDelegates(this).slice();%0A %09%09%09var args @@ -5181,21 +5181,16 @@ %09%09%09if (! -this. delegate @@ -5190,16 +5190,23 @@ elegates +.length ) %7B retu @@ -5221,120 +5221,8 @@ %7D%0A%0A -%09%09%09// Copy delegates. We may be about to mutate the delegates list.%0A%09%09%09var delegates = this.delegates.slice();%0A%0A %09%09%09i
2e4d6b3e0b8ca756d8caf77400d52b1ea5276808
fix bad syntax in rollbar call
config/bootstrap.js
config/bootstrap.js
/** * Bootstrap * (sails.config.bootstrap) * * An asynchronous bootstrap function that runs before your Sails app gets lifted. * This gives you an opportunity to set up your data model, run jobs, or perform some special logic. * * For more information on bootstrapping your app, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.bootstrap.html */ require('dotenv').load() var fs = require('fs') var path = require('path') var root = require('root-path') var util = require('util') // very handy, these global.format = util.format global.Promise = require('bluebird') global._ = require('lodash') // override Sails' old version of lodash module.exports.bootstrap = function (done) { var knex = require('knex')(require('../knexfile')[process.env.NODE_ENV]) if (process.env.DEBUG_MEMORY) { require('colors') sails.log.info('memwatch: starting'.red) var memwatch = require('memwatch-next') memwatch.on('leak', info => sails.log.info('memwatch: memory leak!'.red, info)) memwatch.on('stats', stats => { sails.log.info('memwatch: stats:'.red + '\n' + util.inspect(stats)) }) } // log SQL queries if (process.env.DEBUG_SQL) { require('colors') knex.on('query', function (data) { var args = (_.clone(data.bindings) || []).map(function (s) { if (s === null) return 'null'.blue if (s === undefined) return 'undefined'.red if (typeof (s) === 'object') return JSON.stringify(s).blue return s.toString().blue }) args.unshift(data.sql.replace(/\?/g, '%s')) // TODO fix missing limit and boolean values var query = util.format.apply(util, args) .replace(/^(select)/, '$1'.cyan) .replace(/^(insert)/, '$1'.green) .replace(/^(update)/, '$1'.yellow) .replace(/^(delete)/, '$1'.red) sails.log.info(query) }) } if (sails.config.environment === 'production') { var rollbar = require('rollbar') knex.on('query', function (data) { if (_.includes(data.bindings, 'undefined')) { rollbar.handleErrorWithPayloadData('undefined value in SQL query', { custom: { sql: data.sql, bindings: data.bindings } }) } }) } // add bookshelf and each model to global namespace global.bookshelf = require('bookshelf')(knex) _.each(fs.readdirSync(root('api/models')), function (filename) { if (path.extname(filename) === '.js') { var modelName = path.basename(filename, '.js') global[modelName] = require(root('api/models/' + modelName)) } }) // add presenters to global namespace _.each(fs.readdirSync(root('api/presenters')), function (filename) { if (path.extname(filename) === '.js') { var modelName = path.basename(filename, '.js') global[modelName] = require(root('api/presenters/' + modelName)) } }) // It's very important to trigger this callback method when you are finished // with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap) done() }
JavaScript
0.000114
@@ -2076,42 +2076,29 @@ -rollbar.handleErrorWithPayloadData +const err = new Error ('un @@ -2128,11 +2128,9 @@ ery' -, %7B +) %0A @@ -2138,17 +2138,47 @@ - custom: +rollbar.handleErrorWithPayloadData(err, %7B%0A @@ -2186,18 +2186,25 @@ - +custom: %7B sql: dat @@ -2213,20 +2213,8 @@ sql, -%0A bin @@ -2233,27 +2233,16 @@ bindings -%0A %7D%0A
b819bed4bc0745da0ce079ac990a1522693f6f48
add iframe base url
config/container.js
config/container.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ // Default container configuration. To change the configuration, you have two options: // // A. If you run the Java server: Create your own "myContainer.js" file and // modify the value in web.xml. // // B. If you run the PHP server: Create a myContainer.js, copy the contents of container.js to it, // change // {"gadgets.container" : ["default"], // to // {"gadgets.container" : ["myContainer"], // And make your changes that you need to myContainer.js. // Just make sure on the iframe URL you specify &container=myContainer // for it to use that config. // // All configurations will automatically inherit values from this // config, so you only need to provide configuration for items // that you require explicit special casing for. // // Please namespace your attributes using the same conventions // as you would for javascript objects, e.g. gadgets.features // rather than "features". // NOTE: Please _don't_ leave trailing commas because the php json parser // errors out on this. // Container must be an array; this allows multiple containers // to share configuration. {"gadgets.container" : ["default"], // Set of regular expressions to validate the parent parameter. This is // necessary to support situations where you want a single container to support // multiple possible host names (such as for localized domains, such as // <language>.example.org. If left as null, the parent parameter will be // ignored; otherwise, any requests that do not include a parent // value matching this set will return a 404 error. "gadgets.parent" : null, // Should all gadgets be forced on to a locked domain? "gadgets.lockedDomainRequired" : false, // DNS domain on which gadgets should render. "gadgets.lockedDomainSuffix" : "-a.example.com:8080", // Origins for CORS requests and/or Referer validation // Indicate a set of origins or an entry with * to indicate that all origins are allowed "gadgets.parentOrigins" : ["*"], // Various urls generated throughout the code base. // iframeBaseUri will automatically have the host inserted // if locked domain is enabled and the implementation supports it. // query parameters will be added. "gadgets.iframeBaseUri" : "/gadgets/ifr", // jsUriTemplate will have %host% and %js% substituted. // No locked domain special cases, but jsUriTemplate must // never conflict with a lockedDomainSuffix. "gadgets.jsUriTemplate" : "http://%host%/gadgets/js/%js%", // Callback URL. Scheme relative URL for easy switch between https/http. "gadgets.oauthGadgetCallbackTemplate" : "//%host%/gadgets/oauthcallback", // Use an insecure security token by default "gadgets.securityTokenType" : "insecure", // Config param to load Opensocial data for social // preloads in data pipelining. %host% will be // substituted with the current host. "gadgets.osDataUri" : "http://%host%/rpc", // Uncomment these to switch to a secure version // //"gadgets.securityTokenType" : "secure", //"gadgets.securityTokenKeyFile" : "/path/to/key/file.txt", // Default concat Uri config; used for testing. "gadgets.uri.concat.host" : "localhost:9003", "gadgets.uri.concat.path" : "/gadgets/concat", // This config data will be passed down to javascript. Please // configure your object using the feature name rather than // the javascript name. // Only configuration for required features will be used. // See individual feature.xml files for configuration details. "gadgets.features" : { "shindig.connect-1.0" : { "metadataUrl" : "/gadgets/metadata" }, "core.io" : { // Note: /proxy is an open proxy. Be careful how you expose this! // Note: Here // is replaced with the current protocol http/https "proxyUrl" : "//%host%/gadgets/proxy?container=default&refresh=%refresh%&url=%url%%rewriteMime%", "jsonProxyUrl" : "//%host%/gadgets/makeRequest" }, "views" : { "profile" : { "isOnlyVisible" : false, "urlTemplate" : "http://localhost/gadgets/profile?{var}", "aliases": ["DASHBOARD", "default"] }, "canvas" : { "isOnlyVisible" : true, "urlTemplate" : "http://localhost/gadgets/canvas?{var}", "aliases" : ["FULL_PAGE"] } }, "rpc" : { // Path to the relay file. Automatically appended to the parent // parameter if it passes input validation and is not null. // This should never be on the same host in a production environment! // Only use this for TESTING! "parentRelayUrl" : "/container/rpc_relay.html", // If true, this will use the legacy ifpc wire format when making rpc // requests. "useLegacyProtocol" : false }, // Skin defaults "skins" : { "properties" : { "BG_COLOR": "", "BG_IMAGE": "", "BG_POSITION": "", "BG_REPEAT": "", "FONT_COLOR": "", "ANCHOR_COLOR": "" } }, "opensocial" : { // Path to fetch opensocial data from // Must be on the same domain as the gadget rendering server "path" : "http://%host%/social/rpc", // Path to issue invalidate calls "invalidatePath" : "http://%host%/rpc", "domain" : "shindig", "enableCaja" : false, "supportedFields" : { "person" : ["id", {"name" : ["familyName", "givenName", "unstructured"]}, "thumbnailUrl", "profileUrl"], "activity" : ["id", "title"] } }, "osapi.services" : { // Specifying a binding to "container.listMethods" instructs osapi to dynamicaly introspect the services // provided by the container and delay the gadget onLoad handler until that introspection is // complete. // Alternatively a container can directly configure services here rather than having them // introspected. Simply list out the available servies and omit "container.listMethods" to // avoid the initialization delay caused by gadgets.rpc // E.g. "gadgets.rpc" : ["activities.requestCreate", "messages.requestSend", "requestShareApp", "requestPermission"] "gadgets.rpc" : ["container.listMethods"] }, "osapi" : { // The endpoints to query for available JSONRPC/REST services "endPoints" : [ "http://%host%/rpc" ] }, "osml": { // OSML library resource. Can be set to null or the empty string to disable OSML // for a container. "library": "config/OSML_library.xml" } }}
JavaScript
0.000001
@@ -2980,24 +2980,45 @@ BaseUri%22 : %22 +http://localhost:8080 /gadgets/ifr
ca5fb09fc6ac3d747faec00f75d5d584890f05e9
Change decode/encodeURI to URIComponent
src/scripts/script.js
src/scripts/script.js
/* * Copyright (C) 2016 Jones Magloire @Joxit * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ var registryUI = {} registryUI.URL_QUERY_PARAM_REGEX = /[&?]url=/; registryUI.URL_PARAM_REGEX = /^url=/; registryUI.url = function() { if (!registryUI._url) { var url = registryUI.getUrlQueryParam(); if (url) { try { registryUI._url = registryUI.decodeURI(url); return registryUI._url; } catch (e) { console.log(e); } } registryUI._url = registryUI.getRegistryServer(0); } return registryUI._url; } registryUI.getRegistryServer = function(i) { try { var res = JSON.parse(localStorage.getItem('registryServer')); if (res instanceof Array) { return (!isNaN(i)) ? res[i] : res.map(function(url) { return url.trim().replace(/\/*$/, ''); }); } } catch (e) {} return (!isNaN(i)) ? '' : []; } registryUI.addServer = function(url) { var registryServer = registryUI.getRegistryServer(); url = url.trim().replace(/\/*$/, ''); var index = registryServer.indexOf(url); if (index != -1) { return; } registryServer.push(url); if (!registryUI._url) { registryUI.updateHistory(url); } localStorage.setItem('registryServer', JSON.stringify(registryServer)); } registryUI.changeServer = function(url) { var registryServer = registryUI.getRegistryServer(); url = url.trim().replace(/\/*$/, ''); var index = registryServer.indexOf(url); if (index == -1) { return; } registryServer.splice(index, 1); registryServer = [url].concat(registryServer); registryUI.updateHistory(url); localStorage.setItem('registryServer', JSON.stringify(registryServer)); } registryUI.removeServer = function(url) { var registryServer = registryUI.getRegistryServer(); url = url.trim().replace(/\/*$/, ''); var index = registryServer.indexOf(url); if (index == -1) { return; } registryServer.splice(index, 1); localStorage.setItem('registryServer', JSON.stringify(registryServer)); } registryUI.updateHistory = function(url) { history.pushState(null, '', '?url=' + registryUI.encodeURI(url) + window.location.hash); registryUI._url = url; } registryUI.getUrlQueryParam = function () { var search = window.location.search; if (registryUI.URL_QUERY_PARAM_REGEX.test(search)) { var param = search.split(/^\?|&/).find(function(param) { return param && registryUI.URL_PARAM_REGEX.test(param); }); return param ? param.replace(registryUI.URL_PARAM_REGEX, '') : param; } }; registryUI.encodeURI = function(url) { return url.indexOf('&') < 0 ? window.encodeURI(url) : btoa(url); }; registryUI.decodeURI = function(url) { return url.startsWith('http') ? window.decodeURI(url) : atob(url); }; registryUI.isImageRemoveActivated = true; registryUI.catalog = {}; registryUI.taglist = {}; riot.mount('add'); riot.mount('change'); riot.mount('remove'); riot.mount('menu'); riot.mount('app');
JavaScript
0.000002
@@ -3222,24 +3222,33 @@ ow.encodeURI +Component (url) : btoa @@ -3343,24 +3343,33 @@ ow.decodeURI +Component (url) : atob
4cbea0396bdaea04ab81fb44fd0b86cd3255acfb
support text_html
src/models/posts.js
src/models/posts.js
module.exports = function(mongoose) { var schema = new mongoose.Schema({ text:String, app:{type:mongoose.Schema.Types.ObjectId,ref:"apps"}, user:{type:mongoose.Schema.Types.ObjectId,ref:"users"} },{ timestamps:true }) schema.methods.toResponseObject = function(){ var obj = this.toObject(); obj.id = this._id; obj._id = undefined; obj.__v = undefined; if(this.user.toResponseObject) obj.user=this.user.toResponseObject(); if(this.app && this.app.toResponseObject){ obj.app=this.app.toResponseObject(); delete obj.app.appKey; delete obj.app.appSecret; } return obj; } return mongoose.model("posts",schema) };
JavaScript
0.000004
@@ -701,24 +701,614 @@ %0A %7D%0D%0A + obj.text_html = obj.text;%0D%0A obj.text_html = obj.text_html.split('&').join(%22&amp;%22)%0D%0A obj.text_html = obj.text_html.split(%22%3C%22).join(%22&lt;%22)%0D%0A obj.text_html = obj.text_html.split(%22%3E%22).join(%22&gt;%22)%0D%0A // obj.text_html = obj.text_html.split('%22').join(%22&quot;%22)%0D%0A obj.text_html = obj.text_html.replace(/(%5E%7C %7C%E3%80%80)@(%5BA-Za-z0-9_%5D+)/g,'$1%3Ca href=%22/u/$2%22%3E@$2%3C/a%3E');%0D%0A obj.text_html = obj.text_html.replace(/(https?:%5C/%5C/%5Ba-zA-Z0-9-%5C.%5D+(:%5B0-9%5D+)?(%5C/?%5Ba-zA-Z0-9-%5C._~%5C!#$&'%5C(%5C)%5C*%5C+,%5C/:;=%5C?@%5C%5B%5C%5D%5D*))/g,'%3Ca href=%22$1%22 rel=%22nofollow%22 target=%22_blank%22%3E$1%3C/a%3E');%0D%0A retu
7a97fef486dc09d07c1c32d051b45ad1cdf944e1
Handle server-side redirects.
src/server/reactor.js
src/server/reactor.js
import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { StaticRouter, matchPath } from 'react-router-dom'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import { App } from '../app'; import Document from './document'; const scripts = [ '/bundle.js' ]; export function reactor( routes, reducer, middleware = [] ) { return ( req, res, next ) => { const store = createStore( reducer, req.initialState, applyMiddleware( ...middleware ) ); // TODO: Pre-fetch data for matched route. const handlers = routes .map( route => ({ match: matchPath( req.url, route ), route }) ) .filter( ({ match, route }) => !!match && route.fetch ); const tasks = handlers.map( ({ match, route }) => store.dispatch( route.fetch( match ) ) ); Promise.all( tasks ) .then( () => { const state = store.getState(); const context = {}; const content = process.env.NODE_ENV === "production" ? ReactDOMServer.renderToString( <StaticRouter location={ req.url } context={ context }> <Provider store={ store }> <App routes={ routes } /> </Provider> </StaticRouter> ) : ''; // TODO: Handle redirects. res.send( "<!DOCTYPE html>\n" + ReactDOMServer.renderToStaticMarkup( React.createElement( Document, { content, state, scripts } ) ) ); }, err => next( err ) // TODO: Better error handling (how to gracefully support error handling without prescribing application structure). ); } } export default reactor;
JavaScript
0
@@ -979,60 +979,8 @@ nt = - process.env.NODE_ENV === %22production%22%0A ? Rea @@ -1007,20 +1007,16 @@ String(%0A - @@ -1089,20 +1089,16 @@ - - %3CProvide @@ -1132,20 +1132,16 @@ - %3CApp rou @@ -1172,20 +1172,16 @@ - - %3C/Provid @@ -1180,28 +1180,24 @@ %3C/Provider%3E%0A - @@ -1222,21 +1222,19 @@ - - ) +);%0A %0A @@ -1240,54 +1240,101 @@ - : '';%0A%0A // TODO: Handle redirects.%0A +if ( context.url ) %7B%0A res.redirect( context.url );%0A %7D%0A else %7B%0A @@ -1448,16 +1448,70 @@ content +: process.env.NODE_ENV === %22production%22 ? content : '' , state, @@ -1524,24 +1524,36 @@ ts %7D ) ) );%0A + %7D%0A %7D,%0A
6f333298e81fd60bdbe6d733ccf57aa43e17c60b
add new line
www/codemirror/codemirror-range-utilities.js
www/codemirror/codemirror-range-utilities.js
const ItemRange = require('./codemirror-range-objects').ItemRange const ItemLocation = require('./codemirror-range-objects').ItemLocation const getItemRangeFromSelection = (codeMirror) => { const fromCursor = codeMirror.getCursor('from') const toCursor = codeMirror.getCursor('to') const fromLocation = new ItemLocation(fromCursor.line, fromCursor.ch) const toLocation = new ItemLocation(toCursor.line, toCursor.ch) const selectionRange = new ItemRange(fromLocation, toLocation) return selectionRange } const getMarkupItemsIntersectingSelection = (codeMirror, markupItems, selectionRange) => { const itemIntersectsSelection = item => item.outerRange.intersectsRange(selectionRange, true) const itemDoesNotStartsAtSelectionEnd = item => !item.openingMarkupRange().startLocation.equals(selectionRange.endLocation) const itemDoesNotEndAtSelectionStart = item => !item.closingMarkupRange().endLocation.equals(selectionRange.startLocation) return markupItems .filter(itemIntersectsSelection) .filter(itemDoesNotStartsAtSelectionEnd) .filter(itemDoesNotEndAtSelectionStart) } const getButtonNamesFromMarkupItems = (markupItems) => markupItems.map(item => item.buttonName) /* TODO: add generic (non-regex or otherwise string aware) functional methods here for: - unwrapping existing markup item (i.e. turning off something like bold) would simply look at the item's inner and outer range and replace the code mirror string from the outer range with the code mirror string from the inner range, - others t.b.d. - need to think a bit more about best way to implement wrapping related method(s) */ exports.getItemRangeFromSelection = getItemRangeFromSelection exports.getMarkupItemsIntersectingSelection = getMarkupItemsIntersectingSelection exports.getButtonNamesFromMarkupItems = getButtonNamesFromMarkupItems
JavaScript
0.002414
@@ -1820,28 +1820,29 @@ etButtonNamesFromMarkupItems +%0A
bececab2c9138d3321227a175e75fdc302210d54
comment analyzeSensors.jsp"
ocean/analyzeSensor.js
ocean/analyzeSensor.js
function olapSensor(){ var usr = document.querySelector('input[name="subToAnal"]:checked').value; document.cookie = 'modsid="' + usr + '";'; writeOLAPcookies(); window.setTimeout('window.location="analyzeSensor.jsp"; ',50); } function updateOLAPcookies(){ document.cookie = 'olapYR="' + document.getElementById("year").value + '";'; document.cookie = 'olapQU="' + document.getElementById("quarter").value + '";';; document.cookie = 'olapMO="' + document.getElementById("month").value + '";';; document.cookie = 'olapWK="' + document.getElementById("week").value + '";';; document.cookie = 'olapDY="' + document.getElementById("day").value + '";';; window.setTimeout('window.location="analyzeSensor.jsp"; ',50); } function writeOLAPcookies(){ document.cookie = 'olapYR="0"'; document.cookie = 'olapQU="0"'; document.cookie = 'olapMO="0"'; document.cookie = 'olapWK="0"'; document.cookie = 'olapDY="0"'; } function updateRollup(){ if(document.getElementById("year").value == 0){ document.getElementById("emptyQU").selected = 'selected'; } if(document.getElementById("quarter").value == 0){ document.getElementById("emptyMO").selected = 'selected'; } if((document.getElementById("month").value == 0)){ document.getElementById("emptyWK").selected = 'selected'; } if(document.getElementById("week").value == 0){ document.getElementById("emptyDY").selected = 'selected'; } cascadeLocks(); } function cascadeLocks(){ if(document.getElementById("quarter").value != 1){ document.getElementById("mo1").disabled = "disabled"; document.getElementById("mo2").disabled = "disabled"; document.getElementById("mo3").disabled = "disabled"; } else { document.getElementById("mo1").disabled = ""; document.getElementById("mo2").disabled = ""; document.getElementById("mo3").disabled = ""; } if(document.getElementById("quarter").value != 2){ document.getElementById("mo4").disabled = "disabled"; document.getElementById("mo5").disabled = "disabled"; document.getElementById("mo6").disabled = "disabled"; } else { document.getElementById("mo4").disabled = ""; document.getElementById("mo5").disabled = ""; document.getElementById("mo6").disabled = ""; } if(document.getElementById("quarter").value != 3){ document.getElementById("mo7").disabled = "disabled"; document.getElementById("mo8").disabled = "disabled"; document.getElementById("mo9").disabled = "disabled"; } else { document.getElementById("mo7").disabled = ""; document.getElementById("mo8").disabled = ""; document.getElementById("mo9").disabled = ""; } if(document.getElementById("quarter").value != 4){ document.getElementById("mo10").disabled = "disabled"; document.getElementById("mo11").disabled = "disabled"; document.getElementById("mo12").disabled = "disabled"; } else { document.getElementById("mo10").disabled = ""; document.getElementById("mo11").disabled = ""; document.getElementById("mo12").disabled = ""; } } function dtoDate(code){ if(code == 1){return "Sunday";} if(code == 2){return "Monday";} if(code == 3){return "Tuesday";} if(code == 4){return "Wednesday";} if(code == 5){return "Thursday";} if(code == 6){return "Friday";} if(code == 7){return "Saturday";} }
JavaScript
0
@@ -1,12 +1,100 @@ %0A%0A%0A +//called from a button. This will grab detect which row is wanted and create the cookies %0A - function @@ -316,32 +316,74 @@ jsp%22; ',50);%0A%7D%0A%0A +//creates cookies from current olap depth%0A function updateO @@ -851,24 +851,50 @@ ; ',50);%0A%7D%0A%0A +//initialize olap cookies%0A function wri @@ -1069,24 +1069,75 @@ DY=%220%22';%0A%7D%0A%0A +//collapses levels when the higher level is absent%0A function upd @@ -1621,24 +1621,76 @@ ocks();%0A%0A%7D%0A%0A +//locks months that are not in the selected quarter%0A function cas @@ -3220,16 +3220,48 @@ %0A%09%7D%0A%09%0A%7D%0A +//converts nubmer to date string %0Afunctio
b2908d7aa0db7d9cb7b13980c38879b9eb8e102f
Remove unnecessary doubleClick enabling
src/modes/static.js
src/modes/static.js
module.exports = function(ctx) { return { stop: function() { ctx.map.doubleClickZoom.enable(); }, start: function() {}, render: function(geojson, push) { push(geojson); } }; };
JavaScript
0.000001
@@ -19,19 +19,16 @@ unction( -ctx ) %7B%0A re @@ -60,53 +60,8 @@ () %7B -%0A ctx.map.doubleClickZoom.enable();%0A %7D,%0A
3df54f3382c364ba01b471c42e3a52de2f9a84db
Use better method names
hypem-resolver.js
hypem-resolver.js
/** * Copyright 2015 Fabian Dietenberger * Available under MIT license */ function HypemResolver() { "use strict"; var request = require('request'), url = require('url'), _ = require('lodash'); /** Used for the requests */ var FIVE_SECONDS_IN_MILLIS = 5000, COOKIE = "AUTH=03%3A406b2fe38a1ab80a2953869a475ff110%3A1412624464%3A1469266248%3A01-DE", HYPEM_TRACK_URL = "http://hypem.com/track/", HYPEM_GO_URL = "http://hypem.com/go/sc/", HYPEM_SERVE_URL = "http://hypem.com/serve/source/"; /** * Extract the hypem id from a song's url. * * @param {string} hypemUrl the url to extract the id * @returns {string} the id or "" if no id was found */ function urlToId(hypemUrl) { var trimmedUrl = _.trim(hypemUrl); if (_.startsWith(trimmedUrl, HYPEM_TRACK_URL)) { var parsedUrl = url.parse(hypemUrl); var pathname = parsedUrl.pathname; // '/trach/31jfi/...' var hypemId = pathname.split("/")[2]; return hypemId; } return ""; } /** * Get the soundcloud or mp3 url from a song's id. * * @param hypemId {string} the id of the song * @param {Function}[callback] callback function * @param {Error} callback.err null if no error occurred * @param {string} callback.url the soundcloud or mp3 url */ function getById(hypemId, callback) { var options = { method: 'HEAD', url: HYPEM_GO_URL + hypemId, followRedirect: false, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (error || response.statusCode !== 302) { callback(error, null); return; } var songUrl = response.headers.location; if (isSoundcloudUrl(songUrl)) { var soundcloudUrl = getNormalizedSoundcloudUrl(songUrl); callback(null, soundcloudUrl); } else { getHypemKey(hypemId, function (error, hypemKey) { if (error) { callback(error, null); return; } getMp3Url(hypemId, hypemKey, callback); }); } }); } return { urlToId: urlToId, getById: getById }; /** * Get the key for hypem. The key is necessary to request * the hypem serve url which gives us the mp3 url. We dont * need a key if the song is hosted on soundcloud. * * @private * @param {string} hypemId the id of the song * @param {Function}[callback] callback function * @param {Error} callback.err null if no error occurred * @param {string} callback.url the key to request a hypem song url */ function getHypemKey(hypemId, callback) { var options = { method: "GET", url: HYPEM_TRACK_URL + hypemId, headers: {"Cookie": COOKIE}, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (!error && response.statusCode === 200) { var bodyLines = response.body.split('\n'); _.forIn(bodyLines, function (bodyLine) { if (bodyLine.indexOf('key') !== -1) { // first hit should be the correct one // fix if hypem changes that try { var key = JSON.parse(bodyLine.replace('</script>', '')).tracks[0].key; callback(null, key); } catch (error) { // if an error happen here do nothing and parse // the rest of the document } } }); } else { callback(new Error("Nothing found: " + options.url), null); } }); } /** * Get the mp3 url of the song's id with a given key. * * @private * @param {string} hypemId the id of the song * @param {string} hypemKey the key to make the request succeed * @param {Function}[callback] callback function * @param {Error} callback.err null if no error occurred * @param {string} callback.url the mp3 url */ function getMp3Url(hypemId, hypemKey, callback) { var options = { method: "GET", url: HYPEM_SERVE_URL + hypemId + "/" + hypemKey, headers: {"Cookie": COOKIE}, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (!error && response.statusCode === 200) { try { // the request got a json from hypem // where the link to the mp3 file is saved var jsonBody = JSON.parse(response.body); var mp3Url = jsonBody.url; callback(null, mp3Url); } catch (error) { callback(error, null); } } else { callback(new Error("Nothing found: " + options.url), null); } }); } /** * Check if the url is a soundlcoud url. The test is very simple because * hypem either returns the complete url or a 'not found' url. * * @param {string} songUrl the url to check * @returns {boolean} true if its a soundcloud url */ function isSoundcloudUrl(songUrl) { return songUrl !== "http://soundcloud.com/not/found" && songUrl !== "https://soundcloud.com/not/found" } /** * Get the normalized soundcloud url. This means that every * parameter or path which is not necessary gets removed. * * @private * @param {string} soundcloudUrl the url to normalize * @returns {string} the normalized soundcloud url */ function getNormalizedSoundcloudUrl(soundcloudUrl) { var parsedUrl = url.parse(soundcloudUrl); var protocol = parsedUrl.protocol; var host = parsedUrl.host; var pathname = parsedUrl.pathname; var splitHostname = pathname.split('/'); var normalizedUrl = protocol + "//" + host + "/" + splitHostname[1] + "/" + splitHostname[2]; return normalizedUrl; } } module.exports = new HypemResolver();
JavaScript
0.986644
@@ -2071,18 +2071,22 @@ -ge +reques tHypemKe @@ -2279,18 +2279,22 @@ -ge +reques tMp3Url( @@ -2915,18 +2915,22 @@ unction -ge +reques tHypemKe @@ -4485,18 +4485,22 @@ unction -ge +reques tMp3Url(
924807c757cf510798f28b9543db1c31f19b5e22
fix 'CommentDecorationsController' test warnings
lib/controllers/editor-comment-decorations-controller.js
lib/controllers/editor-comment-decorations-controller.js
import React, {Fragment} from 'react'; import PropTypes from 'prop-types'; import {Range} from 'atom'; import {EndpointPropType} from '../prop-types'; import {addEvent} from '../reporter-proxy'; import Marker from '../atom/marker'; import Decoration from '../atom/decoration'; import ReviewsItem from '../items/reviews-item'; import CommentGutterDecorationController from '../controllers/comment-gutter-decoration-controller'; export default class EditorCommentDecorationsController extends React.Component { static propTypes = { endpoint: EndpointPropType.isRequired, owner: PropTypes.string.isRequired, repo: PropTypes.string.isRequired, number: PropTypes.number.isRequired, workdir: PropTypes.string.isRequired, workspace: PropTypes.object.isRequired, editor: PropTypes.object.isRequired, threadsForPath: PropTypes.arrayOf(PropTypes.shape({ rootCommentID: PropTypes.string.isRequired, position: PropTypes.number, threadID: PropTypes.string.isRequired, })).isRequired, commentTranslationsForPath: PropTypes.shape({ diffToFilePosition: PropTypes.shape({ get: PropTypes.func.isRequired, }).isRequired, fileTranslations: PropTypes.shape({ get: PropTypes.func.isRequired, }), removed: PropTypes.bool.isRequired, digest: PropTypes.string, }), } constructor(props) { super(props); this.rangesByRootID = new Map(); } shouldComponentUpdate(nextProps) { return translationDigestFrom(this.props) !== translationDigestFrom(nextProps); } render() { if (!this.props.commentTranslationsForPath) { return null; } if (this.props.commentTranslationsForPath.removed && this.props.threadsForPath.length > 0) { const [firstThread] = this.props.threadsForPath; return ( <Marker editor={this.props.editor} exclusive={true} invalidate="surround" bufferRange={Range.fromObject([[0, 0], [0, 0]])}> <Decoration type="block" editor={this.props.editor} className="github-EditorComment-omitted"> <p> This file has review comments, but its patch is too large for Atom to load. </p> <p> Review comments may still be viewed within <button className="btn" onClick={() => this.openReviewThread(firstThread.threadID)}>the review tab</button>. </p> </Decoration> </Marker> ); } return this.props.threadsForPath.map(thread => { const range = this.getRangeForThread(thread); if (!range) { return null; } return ( <Fragment key={`github-editor-review-decoration-${thread.rootCommentID}`}> <Marker editor={this.props.editor} exclusive={true} invalidate="surround" bufferRange={range} didChange={evt => this.markerDidChange(thread.rootCommentID, evt)}> <Decoration type="line" editor={this.props.editor} className="github-editorCommentHighlight" omitEmptyLastRow={false} /> </Marker> <CommentGutterDecorationController commentRow={range.start.row} threadId={thread.threadID} editor={this.props.editor} workspace={this.props.workspace} endpoint={this.props.endpoint} owner={this.props.owner} repo={this.props.repo} number={this.props.number} workdir={this.props.workdir} parent={this.constructor.name} /> </Fragment> ); }); } markerDidChange(rootCommentID, {newRange}) { this.rangesByRootID.set(rootCommentID, Range.fromObject(newRange)); } getRangeForThread(thread) { const translations = this.props.commentTranslationsForPath; if (thread.position === null) { this.rangesByRootID.delete(thread.rootCommentID); return null; } let adjustedPosition = translations.diffToFilePosition.get(thread.position); if (!adjustedPosition) { this.rangesByRootID.delete(thread.rootCommentID); return null; } if (translations.fileTranslations) { adjustedPosition = translations.fileTranslations.get(adjustedPosition).newPosition; if (!adjustedPosition) { this.rangesByRootID.delete(thread.rootCommentID); return null; } } const editorRow = adjustedPosition - 1; let localRange = this.rangesByRootID.get(thread.rootCommentID); if (!localRange) { localRange = Range.fromObject([[editorRow, 0], [editorRow, Infinity]]); this.rangesByRootID.set(thread.rootCommentID, localRange); } return localRange; } openReviewThread = async threadId => { const uri = ReviewsItem.buildURI({ host: this.props.endpoint.getHost(), owner: this.props.owner, repo: this.props.repo, number: this.props.number, workdir: this.props.workdir, }); const reviewsItem = await this.props.workspace.open(uri, {searchAllPanes: true}); reviewsItem.jumpToThread(threadId); addEvent('open-review-thread', {package: 'github', from: this.constructor.name}); } } function translationDigestFrom(props) { const translations = props.commentTranslationsForPath; return translations ? translations.digest : null; }
JavaScript
0.000001
@@ -897,38 +897,104 @@ ntID: PropTypes. -string +oneOfType(%5B%0A PropTypes.string,%0A PropTypes.number,%0A %5D) .isRequired,%0A
e481ba046bdb08336263727d80831d758dc152ac
fix crash and preemptively fix possible second crash
src/Parser/Shaman/Elemental/Modules/Items/EchoesOfTheGreatSundering.js
src/Parser/Shaman/Elemental/Modules/Items/EchoesOfTheGreatSundering.js
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import ItemIcon from 'common/ItemIcon'; import ItemLink from 'common/ItemLink'; import { formatPercentage } from 'common/format'; import ItemDamageDone from 'Main/ItemDamageDone'; class EchoesOfTheGreatSundering extends Analyzer { static dependencies = { combatants: Combatants, }; buffedEarthquakeCasts = 0; echoesProcsCounter = 0; totalEarthquakeDamage = 0; totalEarthquakeCasts = 0; get estimate_bonus_damage() { // Sorry for the magic number, but the goal is to estimate the bonus damage from buffed EQs by ~roughly~ calculating // what fraction of EQ damage can be considered a result of the shoulder buff's 100% increase. return (0.5 * this.totalEarthquakeDamage * (this.buffedEarthquakeCasts / this.totalEarthquakeCasts)); } on_initialized() { this.active = this.combatants.selected.hasShoulder(ITEMS.ECHOES_OF_THE_GREAT_SUNDERING.id); } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.EARTHQUAKE.id) { return; } if (this.combatants.selected.hasBuff(SPELLS.ECHOES_OF_THE_GREAT_SUNDERING_BUFF.id, event.timestamp)) { this.buffedEarthquakeCasts += 1; } this.totalEarthquakeCasts += 1; } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId === SPELLS.EARTHQUAKE_DAMAGE.id) { this.totalEarthquakeDamage += event.amount; } } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId === SPELLS.ECHOES_OF_THE_GREAT_SUNDERING_BUFF.id) { this.echoesProcsCounter += 1; } } item() { return { id: `item=${ITEMS.ECHOES_OF_THE_GREAT_SUNDERING.id}`, icon: <ItemIcon id={ITEMS.ECHOES_OF_THE_GREAT_SUNDERING.id} />, title: <ItemLink id={ITEMS.ECHOES_OF_THE_GREAT_SUNDERING.id} />, result: ( <dfn data-tip={`Your utilization of Echoes of the Great Sundering: <ul> <li> Buffed Earthquakes: ${this.buffedEarthquakeCasts}.</li> <li> Total procs: ${this.echoesProcsCounter}.</li></ul> `}> Earthquake procs used: {formatPercentage(this.buffedEarthquakeCasts / this.echoesProcsCounter)}%<br /> <ItemDamageDone amount={this.estimate_bonus_damage()} /> </dfn> ), }; } } export default EchoesOfTheGreatSundering;
JavaScript
0.000001
@@ -985,16 +985,21 @@ eCasts)) + %7C%7C 0 ;%0A %7D%0A @@ -2576,18 +2576,16 @@ s_damage -() %7D /%3E%0A
46ce3317c31a7e59077ca713c2bcc6cd4da65980
enable running the campaign in non-ES6 browsers
packages/router/karma-test-shim.js
packages/router/karma-test-shim.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /*global jasmine, __karma__, window*/ Error.stackTraceLimit = 5; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; __karma__.loaded = function() {}; function isJsFile(path) { return path.slice(-3) == '.js'; } function isSpecFile(path) { return path.slice(-7) == 'spec.js'; } function isBuiltFile(path) { var builtPath = '/base/dist/'; return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath); } var allSpecFiles = Object.keys(window.__karma__.files).filter(isSpecFile).filter(isBuiltFile); // Load our SystemJS configuration. System.config({ baseURL: '/base', }); System.config({ map: {'rxjs': 'node_modules/rxjs', '@angular': 'dist/all/@angular'}, packages: { '@angular/core/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/core': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler': {main: 'index.js', defaultExtension: 'js'}, '@angular/common/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/common': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser-dynamic/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser-dynamic': {main: 'index.js', defaultExtension: 'js'}, '@angular/router/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/router': {main: 'index.js', defaultExtension: 'js'}, 'rxjs': {main: 'Rx.js', defaultExtension: 'js'}, } }); Promise .all([ System.import('@angular/core/testing'), System.import('@angular/platform-browser-dynamic/testing') ]) .then(function(providers) { var testing = providers[0]; var testingBrowser = providers[1]; testing.TestBed.initTestEnvironment( testingBrowser.BrowserDynamicTestingModule, testingBrowser.platformBrowserDynamicTesting()); }) .then(function() { // Finally, load all spec files. // This will run the tests directly. return Promise.all( allSpecFiles.map(function(moduleName) { return System.import(moduleName); })); }) .then(__karma__.start, (v) => console.error(v));
JavaScript
0
@@ -2524,14 +2524,21 @@ rt, +function (v) -=%3E +%7B con @@ -2550,11 +2550,14 @@ error(v) +; %7D );%0A
8eb3fae93ea422a0104d73564b4a568f0f075848
Change localhost url
map_system/static/map_system/local/libraries/services.js
map_system/static/map_system/local/libraries/services.js
'use strict'; /** * Created by tmkasun on 1/14/17. */ var request = require('superagent'); // var utils = require('./utils'); /** * This is an abstract parent class for all types of map services, This initialize the axios connection with base URI for * knnect APIs */ class MapService { /** * Create single instance of axios client to make connections with back end apis */ constructor() { this.service_endpoint = "/apis/"; this.baseURL = 'http://localhost:8000/apis'; this.client = request; // this.client.domain = this.baseURL; } } /** * LK Stands for Last Known and LKState retrive the Last Know states of an object or get current states of all available * spatial objects */ class LKStates extends MapService { /** * Get all the spatial objects last know state from the persistent storage * @param callback {function} A function to call in the success call to the api * @returns {Promise} Always return an promise object which may chained the a callback method if given when invoking */ getAll(callback = false) { var response = this.client.get(this.baseURL + '/lk_states'); if (callback) { return response.then(callback); } else { return response; } } } /** * This class handle and wrap all the backend service calls related to Spatial Object Activities */ class SpatialActivityService extends MapService { /** * * @param object_id {String} Id of an object i:e: IMEI , Registration number or UUID * @param limit {Number} Number of records needs to be fetched. */ getHistory(object_id, limit) { var response = this.client.get(this.baseURL + '/session_path/' + object_id).query({limit: limit}); return response; } } window.LKStates = LKStates; window.SpatialActivityService = SpatialActivityService; module.exports.LKStates = LKStates; module.exports.SpatialActivityService = SpatialActivityService;
JavaScript
0.999916
@@ -485,22 +485,22 @@ p:// -localhost:8000 +geo.knnect.com /api
0b71a058336c81a3946244ad07bcc63fd4abbcce
fix missing `pool` namespace
src/system/pooling.js
src/system/pooling.js
/** * @classdesc * This object is used for object pooling - a technique that might speed up your game if used properly.<br> * If some of your classes will be instantiated and removed a lot at a time, it is a * good idea to add the class to this object pool. A separate pool for that class * will be created, which will reuse objects of the class. That way they won't be instantiated * each time you need a new one (slowing your game), but stored into that pool and taking one * already instantiated when you need it.<br><br> * This object is also used by the engine to instantiate objects defined in the map, * which means, that on level loading the engine will try to instantiate every object * found in the map, based on the user defined name in each Object Properties<br> * <img src="images/object_properties.png"/><br> * @see {@link pool} a default global instance of ObjectPool */ class ObjectPool { constructor() { this.objectClass = {}; this.instance_counter = 0; } /** * register an object to the pool. <br> * Pooling must be set to true if more than one such objects will be created. <br> * (Note: for an object to be poolable, it must implements a `onResetEvent` method) * @param {string} className as defined in the Name field of the Object Properties (in Tiled) * @param {object} classObj corresponding Class to be instantiated * @param {boolean} [recycling=false] enables object recycling for the specified class * @example * // implement CherryEntity * class CherryEntity extends Spritesheet { * onResetEvent() { * // reset object mutable properties * this.lifeBar = 100; * } * }; * // add our users defined entities in the object pool and enable object recycling * me.pool.register("cherryentity", CherryEntity, true); */ register(className, classObj, recycling = false) { if (typeof (classObj) !== "undefined") { this.objectClass[className] = { "class" : classObj, "pool" : (recycling ? [] : undefined) }; } else { throw new Error("Cannot register object '" + className + "', invalid class"); } } /** * Pull a new instance of the requested object (if added into the object pool) * @param {string} name as used in {@link pool.register} * @param {object} [...arguments] arguments to be passed when instantiating/reinitializing the object * @returns {object} the instance of the requested object * @example * me.pool.register("bullet", BulletEntity, true); * me.pool.register("enemy", EnemyEntity, true); * // ... * // when we need to manually create a new bullet: * var bullet = me.pool.pull("bullet", x, y, direction); * // ... * // params aren't a fixed number * // when we need new enemy we can add more params, that the object construct requires: * var enemy = me.pool.pull("enemy", x, y, direction, speed, power, life); * // ... * // when we want to destroy existing object, the remove * // function will ensure the object can then be reallocated later * me.game.world.removeChild(enemy); * me.game.world.removeChild(bullet); */ pull(name) { var args = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var className = this.objectClass[name]; if (className) { var proto = className["class"], poolArray = className.pool, obj; if (poolArray && ((obj = poolArray.pop()))) { // pull an existing instance from the pool args.shift(); // call the object onResetEvent function if defined if (typeof(obj.onResetEvent) === "function") { obj.onResetEvent.apply(obj, args); } this.instance_counter--; } else { // create a new instance args[0] = proto; obj = new (proto.bind.apply(proto, args))(); if (poolArray) { obj.className = name; } } return obj; } throw new Error("Cannot instantiate object of type '" + name + "'"); } /** * purge the object pool from any inactive object <br> * Object pooling must be enabled for this function to work<br> * note: this will trigger the garbage collector */ purge() { for (var className in this.objectClass) { if (this.objectClass[className]) { this.objectClass[className].pool = []; } } this.instance_counter = 0; } /** * Push back an object instance into the object pool <br> * Object pooling for the object class must be enabled, * and object must have been instantiated using {@link pool#pull}, * otherwise this function won't work * @throws will throw an error if the object cannot be recycled * @param {object} obj instance to be recycled * @param {boolean} [throwOnError=true] throw an exception if the object cannot be recycled * @returns {boolean} true if the object was successfully recycled in the object pool */ push(obj, throwOnError = true) { if (!this.poolable(obj)) { if (throwOnError === true ) { throw new Error("me.pool: object " + obj + " cannot be recycled"); } else { return false; } } // store back the object instance for later recycling this.objectClass[obj.className].pool.push(obj); this.instance_counter++; return true; } /** * Check if an object with the provided name is registered * @param {string} name of the registered object class * @returns {boolean} true if the classname is registered */ exists(name) { return name in this.objectClass; }; /** * Check if an object is poolable * (was properly registered with the recycling feature enable) * @see register * @param {object} obj object to be checked * @returns {boolean} true if the object is poolable * @example * if (!me.pool.poolable(myCherryEntity)) { * // object was not properly registered * } */ poolable(obj) { var className = obj.className; return (typeof className !== "undefined") && (typeof obj.onResetEvent === "function") && (className in this.objectClass) && (this.objectClass[className].pool !== "undefined"); } /** * returns the amount of object instance currently in the pool * @returns {number} amount of object instance */ getInstanceCount() { return this.instance_counter; } }; /** * a default global object pool instance * @public * @type {ObjectPool} */ var pool = new ObjectPool(); export default pool;
JavaScript
0.000025
@@ -7015,16 +7015,47 @@ %7D%0A%7D;%0A%0A +%0Avar pool = new ObjectPool();%0A%0A /**%0A * a @@ -7070,24 +7070,23 @@ global -o +O bject - p +P ool inst @@ -7098,55 +7098,30 @@ * @ -public%0A * @type %7BObjectP +namespace p ool -%7D %0A * -/%0Avar pool = new + @see Obj @@ -7127,20 +7127,20 @@ jectPool -();%0A +%0A */ %0Aexport
471b8ff4cf3dbbc22310d1d1409720e73cd94a57
initial value of height can be 0 (#9660)
packages/table/src/table-layout.js
packages/table/src/table-layout.js
import scrollbarWidth from 'element-ui/src/utils/scrollbar-width'; import Vue from 'vue'; class TableLayout { constructor(options) { this.observers = []; this.table = null; this.store = null; this.columns = null; this.fit = true; this.showHeader = true; this.height = null; this.scrollX = false; this.scrollY = false; this.bodyWidth = null; this.fixedWidth = null; this.rightFixedWidth = null; this.tableHeight = null; this.headerHeight = 44; // Table Header Height this.appendHeight = 0; // Append Slot Height this.footerHeight = 44; // Table Footer Height this.viewportHeight = null; // Table Height - Scroll Bar Height this.bodyHeight = null; // Table Height - Table Header Height this.fixedBodyHeight = null; // Table Height - Table Header Height - Scroll Bar Height this.gutterWidth = scrollbarWidth(); for (let name in options) { if (options.hasOwnProperty(name)) { this[name] = options[name]; } } if (!this.table) { throw new Error('table is required for Table Layout'); } if (!this.store) { throw new Error('store is required for Table Layout'); } } updateScrollY() { const height = this.height; if (typeof height !== 'string' && typeof height !== 'number') return; const bodyWrapper = this.table.bodyWrapper; if (this.table.$el && bodyWrapper) { const body = bodyWrapper.querySelector('.el-table__body'); this.scrollY = body.offsetHeight > this.bodyHeight; } } setHeight(value, prop = 'height') { const el = this.table.$el; if (typeof value === 'string' && /^\d+$/.test(value)) { value = Number(value); } this.height = value; if (!el && value) return Vue.nextTick(() => this.setHeight(value, prop)); if (typeof value === 'number') { el.style[prop] = value + 'px'; this.updateElsHeight(); } else if (typeof value === 'string') { el.style[prop] = value; this.updateElsHeight(); } } setMaxHeight(value) { return this.setHeight(value, 'max-height'); } updateElsHeight() { if (!this.table.$ready) return Vue.nextTick(() => this.updateElsHeight()); const { headerWrapper, appendWrapper, footerWrapper } = this.table.$refs; this.appendHeight = appendWrapper ? appendWrapper.offsetHeight : 0; if (this.showHeader && !headerWrapper) return; const headerHeight = this.headerHeight = !this.showHeader ? 0 : headerWrapper.offsetHeight; if (this.showHeader && headerWrapper.offsetWidth > 0 && headerHeight < 2) { return Vue.nextTick(() => this.updateElsHeight()); } const tableHeight = this.tableHeight = this.table.$el.clientHeight; if (this.height !== null && (!isNaN(this.height) || typeof this.height === 'string')) { const footerHeight = this.footerHeight = footerWrapper ? footerWrapper.offsetHeight : 0; this.bodyHeight = tableHeight - headerHeight - footerHeight + (footerWrapper ? 1 : 0); } this.fixedBodyHeight = this.scrollX ? this.bodyHeight - this.gutterWidth : this.bodyHeight; const noData = !this.table.data || this.table.data.length === 0; this.viewportHeight = this.scrollX ? tableHeight - (noData ? 0 : this.gutterWidth) : tableHeight; this.updateScrollY(); this.notifyObservers('scrollable'); } getFlattenColumns() { const flattenColumns = []; const columns = this.table.columns; columns.forEach((column) => { if (column.isColumnGroup) { flattenColumns.push.apply(flattenColumns, column.columns); } else { flattenColumns.push(column); } }); return flattenColumns; } updateColumnsWidth() { const fit = this.fit; const bodyWidth = this.table.$el.clientWidth; let bodyMinWidth = 0; const flattenColumns = this.getFlattenColumns(); let flexColumns = flattenColumns.filter((column) => typeof column.width !== 'number'); flattenColumns.forEach((column) => { // Clean those columns whose width changed from flex to unflex if (typeof column.width === 'number' && column.realWidth) column.realWidth = null; }); if (flexColumns.length > 0 && fit) { flattenColumns.forEach((column) => { bodyMinWidth += column.width || column.minWidth || 80; }); const scrollYWidth = this.scrollY ? this.gutterWidth : 0; if (bodyMinWidth <= bodyWidth - scrollYWidth) { // DON'T HAVE SCROLL BAR this.scrollX = false; const totalFlexWidth = bodyWidth - scrollYWidth - bodyMinWidth; if (flexColumns.length === 1) { flexColumns[0].realWidth = (flexColumns[0].minWidth || 80) + totalFlexWidth; } else { const allColumnsWidth = flexColumns.reduce((prev, column) => prev + (column.minWidth || 80), 0); const flexWidthPerPixel = totalFlexWidth / allColumnsWidth; let noneFirstWidth = 0; flexColumns.forEach((column, index) => { if (index === 0) return; const flexWidth = Math.floor((column.minWidth || 80) * flexWidthPerPixel); noneFirstWidth += flexWidth; column.realWidth = (column.minWidth || 80) + flexWidth; }); flexColumns[0].realWidth = (flexColumns[0].minWidth || 80) + totalFlexWidth - noneFirstWidth; } } else { // HAVE HORIZONTAL SCROLL BAR this.scrollX = true; flexColumns.forEach(function(column) { column.realWidth = column.minWidth; }); } this.bodyWidth = Math.max(bodyMinWidth, bodyWidth); } else { flattenColumns.forEach((column) => { if (!column.width && !column.minWidth) { column.realWidth = 80; } else { column.realWidth = column.width || column.minWidth; } bodyMinWidth += column.realWidth; }); this.scrollX = bodyMinWidth > bodyWidth; this.bodyWidth = bodyMinWidth; } const fixedColumns = this.store.states.fixedColumns; if (fixedColumns.length > 0) { let fixedWidth = 0; fixedColumns.forEach(function(column) { fixedWidth += column.realWidth || column.width; }); this.fixedWidth = fixedWidth; } const rightFixedColumns = this.store.states.rightFixedColumns; if (rightFixedColumns.length > 0) { let rightFixedWidth = 0; rightFixedColumns.forEach(function(column) { rightFixedWidth += column.realWidth || column.width; }); this.rightFixedWidth = rightFixedWidth; } this.notifyObservers('columns'); } addObserver(observer) { this.observers.push(observer); } removeObserver(observer) { const index = this.observers.indexOf(observer); if (index !== -1) { this.observers.splice(index, 1); } } notifyObservers(event) { const observers = this.observers; observers.forEach((observer) => { switch (event) { case 'columns': observer.onColumnsChange(this); break; case 'scrollable': observer.onScrollableChange(this); break; default: throw new Error(`Table Layout don't have event ${event}.`); } }); } } export default TableLayout;
JavaScript
0.99992
@@ -1750,21 +1750,38 @@ (!el && +( value + %7C%7C value === 0) ) return
03798cebe4db42ac20ab486bef7452771c545aad
add text display
bin/jxc.bin.js
bin/jxc.bin.js
#!/usr/bin/env jx // Copyright & License details are available under JXCORE_LICENSE file var jxtools = require('jxtools'); var fs = require('fs'); var path = require('path'); if (jxtools.onlyForJXcore()) return; if (process.argv.length <= 2) { console.log("Too little arguments."); process.exit(); } var argv2 = process.argv[2].replace("--", ""); var files = fs.readdirSync(path.join(__dirname, '../lib/commands')); if (files.indexOf(argv2 + '.js') === -1) { jxcore.utils.console.error('Unknown command', argv2); process.exit(-1); } require(path.join('../lib/commands', argv2 + '.js')).run(function(err) { if (err) jxcore.utils.console.error(err); });
JavaScript
0.000004
@@ -614,16 +614,21 @@ tion(err +, txt ) %7B%0A if @@ -671,12 +671,58 @@ r(err);%0A + if (txt)%0A jxcore.utils.console.log(txt);%0A %7D);%0A
6c45700fd42be969bea3450c4d77493af0719817
add desc
Algorithms/JS/trees/findLeavesOfBinaryTree.js
Algorithms/JS/trees/findLeavesOfBinaryTree.js
findLeavesOfBinaryTree.js
JavaScript
0.000001
@@ -1,26 +1,796 @@ -findLeavesOfBinaryTree.js +// Given a binary tree, collect a tree's nodes as if you were doing this:%0A%0A// Collect and remove all leaves, repeat until the tree is empty.%0A%0A// Example:%0A// Given binary tree%0A// 1%0A// / %5C%0A// 2 3%0A// / %5C%0A// 4 5%0A// Returns %5B4, 5, 3%5D, %5B2%5D, %5B1%5D.%0A%0A// Explanation:%0A// 1. Removing the leaves %5B4, 5, 3%5D would result in this tree:%0A%0A// 1%0A// /%0A// 2%0A// 2. Now removing the leaf %5B2%5D would result in this tree:%0A%0A// 1%0A// 3. Now removing the leaf %5B1%5D would result in the empty tree:%0A%0A// %5B%5D%0A// Returns %5B4, 5, 3%5D, %5B2%5D, %5B1%5D.%0A%0A/**%0A * Definition for a binary tree node.%0A * function TreeNode(val) %7B%0A * this.val = val;%0A * this.left = this.right = null;%0A * %7D%0A */%0A/**%0A * @param %7BTreeNode%7D root%0A * @return %7Bnumber%5B%5D%5B%5D%7D%0A */%0A%0A %0A
f2cc5cd30e4b5cdba7f929619ea9df197bd5edc3
Update widget.js
controllers/widget.js
controllers/widget.js
var moment = require("alloy/moment"), _initted = false, _toolbar, _data, _picker, _properties = {}; if (arguments[0]) { var args = arguments[0]; if (args.id) { exports.id = args.id; delete args.id; } delete args.__parentSymbol; delete args.__itemTemplate; delete args['$model']; applyProperties(arguments[0]); } else { var args = {}; } /** * Setup method for the widget its look & feel * * @param properties */ function applyProperties(properties) { var _apply = {}; properties = properties || {}; _.extend(_properties, properties); if (!_initted) { _initted = true; if (OS_IOS && _properties.toolbar) { _properties.__parent = $; _toolbar = Widget.createController('toolbar', _properties); } if (_toolbar) { $.widget.add(_toolbar.toolbar); $.widget.addEventListener('pickerCloseClick', hide); } if (_properties.type && _properties.type == 'PICKER_TYPE_DATE') { $.picker.setType(Ti.UI.PICKER_TYPE_DATE); if (!_properties.dateFormat) { _properties.dateFormat = 'DD-MM-YYYY'; } _apply = _.pick(_properties, 'minDate', 'maxDate', 'value'); if (_.size(_apply)) { $.picker.applyProperties(_apply); } } } else { if (OS_IOS && _toolbar) { _toolbar.applyProperties(_properties); } _apply = _.pick(_properties, 'minDate', 'maxDate', 'value'); if (_.size(_apply)) { $.picker.applyProperties(_apply); } } } /** * Setup the data collection to be used in the PICKER_TYPE_PLAIN * This method is ignored when using PICKER_TYPE_DATE * * @param data */ function setDataCollection(data, selectedIndex) { if (isDate()) { Ti.API.info('Set data collection cannot be used in combination with dates'); return; } _data = data; selectedIndex = selectedIndex || 0; if (OS_IOS) { var opts = []; _data.map(function(model) { opts.push(Ti.UI.createPickerRow({id: model.get('id'), title: model.get('title')})); }); $.picker.add(opts); $.picker.setSelectedRow(0, selectedIndex); } else if (OS_ANDROID) { var opts = { options: _data.pluck('title'), selectedIndex: selectedIndex }; $.picker.hide(); _picker = Ti.UI.createOptionDialog(opts); _picker.addEventListener('click', triggerUpdate); } } /** * Show picker, on iOS in the bottom and Android as dialog */ function show() { if (OS_IOS) { $.widget.animate(Ti.UI.createAnimation({ bottom: 0, duration: 300 })); } else { if (isDate()) { $.picker.showDatePickerDialog({ callback: function(e) { triggerUpdate(e); }}); } else { _picker.show(); } } } /** * Hide the picker by moving below bottom, and trigger update for callback */ function hide() { $.widget.animate(Ti.UI.createAnimation({ bottom: '-'+ $.widget.getHeight(), duration: 300 })); triggerUpdate(); $.trigger('close', { type: "close", source: $ }); } /** * Check if the current constructed picker is of type PICKER_TYPE_DATE * * @returns {boolean} */ function isDate() { return ($.picker.getType() == Ti.UI.PICKER_TYPE_DATE); } /** * * @param event */ function triggerUpdate(event) { var value; if (OS_IOS) { if (isDate()) { value = moment($.picker.getValue()).format(_properties.dateFormat) } else { value = _data.get($.picker.getSelectedRow(0).id); } } else if (OS_ANDROID) { if (isDate()) { value = moment(event.value).format(_properties.dateFormat); } else { value = _data.at(_picker.getSelectedIndex()); } } $.trigger('change', { type: "change", source: $, model: value }); } function cleanup() { if (OS_IOS && _properties.toolbar) { $.widget.removeEventListener('pickerCloseClick', hide); } } /*** EXPORTS ***/ exports.applyProperties = applyProperties; exports.show = show; exports.hide = hide; exports.cleanup = cleanup; exports.setDataCollection = setDataCollection; Object.defineProperties($, { "_data": { set: setDataCollection } }); // EVENTS exports.addEventListener = $.on; exports.removeEventListener = $.off; exports.fireEvent = $.trigger;
JavaScript
0.000002
@@ -3280,24 +3280,46 @@ 0%0A %7D));%0A%0A + if (OS_IOS) %7B%0A triggerU @@ -3323,24 +3323,30 @@ erUpdate();%0A + %7D%0A $.trigge @@ -4195,16 +4195,134 @@ %7D);%0A + if (OS_ANDROID) %7B%0A $.trigger('close', %7B%0A type: %22close%22,%0A source: $%0A %7D);%0A %7D%0A %7D%0A%0Afunct