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
51eefe3a52ad5a30d6b6d7d387b5cec07d8adcd5
remove county entry from list.
src/app/counties.js
src/app/counties.js
define([], function () { return ['Beaver', 'Box Elder', 'Cache', 'Carbon', 'Counties', 'Daggett', 'Davis', 'Duchesne', 'Emery', 'Garfield', 'Grand', 'Iron', 'Juab', 'Kane', 'Millard', 'Morgan', 'Piute', 'Rich', 'Salt Lake', 'San Juan', 'Sanpete', 'Sevier', 'Summit', 'Tooele', 'Uintah', 'Utah', 'Wasatch', 'Washington', 'Wayne', 'Weber' ]; });
JavaScript
0
@@ -100,28 +100,8 @@ n',%0A - 'Counties',%0A
9fe26a632772cb8a2b5e410f94168264731db773
handle recursive traces
src/core/util/debug.js
src/core/util/debug.js
import config from '../config' import { noop } from 'shared/util' let warn = noop let tip = noop let formatComponentName if (process.env.NODE_ENV !== 'production') { const hasConsole = typeof console !== 'undefined' const classifyRE = /(?:^|[-_])(\w)/g const classify = str => str .replace(classifyRE, c => c.toUpperCase()) .replace(/[-_]/g, '') warn = (msg, vm) => { if (hasConsole && (!config.silent)) { console.error(`[Vue warn]: ${msg}` + ( vm ? generateComponentTrace(vm) : '' )) } } tip = (msg, vm) => { if (hasConsole && (!config.silent)) { console.warn(`[Vue tip]: ${msg}` + ( vm ? generateComponentTrace(vm) : '' )) } } formatComponentName = (vm, includeFile) => { if (vm.$root === vm) { return '<Root>' } let name = typeof vm === 'string' ? vm : typeof vm === 'function' && vm.options ? vm.options.name : vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name const file = vm._isVue && vm.$options.__file if (!name && file) { const match = file.match(/([^/\\]+)\.vue$/) name = match && match[1] } return ( (name ? `<${classify(name)}>` : `<Anonymous>`) + (file && includeFile !== false ? ` at ${file}` : '') ) } const generateComponentTrace = vm => { if (vm._isVue && vm.$parent && String.prototype.repeat) { const tree = [] while (vm) { tree.push(vm) vm = vm.$parent } return '\n\nfound in\n\n' + tree .map((vm, i) => `${ i === 0 ? '---> ' : ' '.repeat(5 + i * 2) }${ formatComponentName(vm) }`) .join('\n') } else { return `\n\n(found in ${formatComponentName(vm)})` } } } export { warn, tip, formatComponentName }
JavaScript
0.000001
@@ -1463,20 +1463,461 @@ -while (vm) %7B +let currentRecursiveSequence = 0%0A while (vm) %7B%0A if (tree.length %3E 0) %7B%0A const last = tree%5Btree.length - 1%5D%0A if (last.constructor === vm.constructor) %7B%0A currentRecursiveSequence++%0A vm = vm.$parent%0A continue%0A %7D else if (currentRecursiveSequence %3E 0) %7B%0A tree%5Btree.length - 1%5D = %5Blast, currentRecursiveSequence%5D%0A currentRecursiveSequence = 0%0A %7D%0A %7D %0A @@ -2098,16 +2098,16 @@ %7D$%7B%0A - @@ -2107,16 +2107,124 @@ + Array.isArray(vm)%0A ? %60$%7BformatComponentName(vm%5B0%5D)%7D... ($%7Bvm%5B1%5D%7D recursive calls)%60%0A : formatC
6f460ca0a08ce7f587c7c85f0ff3539c651ecf0b
Use importNode to avoid issues cloning a template with custom elements in it.
minimalComponent.js
minimalComponent.js
/* * A minimal set of helper functions to go on top of polymer-micro: * * 1. <template> instantiation * 2. Polymer-style automatic node finding */ (function() { // Polymer-style automatic node finding. // See https://www.polymer-project.org/1.0/docs/devguide/local-dom.html#node-finding. // This feature is not available in polymer-micro, so we provide a basic // version of this ourselves. function createReferencesToNodesWithIds(instance) { instance.$ = {}; var nodesWithIds = instance.root.querySelectorAll('[id]'); [].forEach.call(nodesWithIds, function(node) { var id = node.getAttribute('id'); instance.$[id] = node; }); } window.MinimalComponent = { // Use polymer-micro created callback to initialize the component. created: function() { if (this.template) { // Instantiate template. this.root = this.createShadowRoot(); this.root.appendChild(this.template.content.cloneNode(true)); // Create this.$.<id> properties. createReferencesToNodesWithIds(this); } // Initialize property values from attributes. this._marshalAttributes(); }, get ownerDocument() { // Support both polyfilled and native HTML Imports. var currentScript = document._currentScript || document.currentScript; return currentScript.ownerDocument; } }; })();
JavaScript
0
@@ -882,67 +882,103 @@ -this.root.appendChild(this.template.content.cloneNode(true) +var clone = document.importNode(this.template.content, true);%0A this.root.appendChild(clone );%0A%0A
e0fc44b27c24d05daf189f0cb0f8649e6d9fea87
Update controllerUtils.js
src/backend/rest/subscriber/controllerUtils.js
src/backend/rest/subscriber/controllerUtils.js
var enforce = require("enforce"); function validEmail(email){ //use node-enfore library return enforce.patterns.email([email]) } function validPassword(password){ return enforce.range.length(8[, 16[, password ]]) } function validToken(token){ return enforce.ranges.length(36[, 36[, token ]]) } exports.validPassword = validPassword; exports.validEmail = validEmail; exports.validToken = validToken;
JavaScript
0.000001
@@ -123,16 +123,17 @@ %5Bemail%5D) +; %0A%7D%0A%0Afunc @@ -208,24 +208,25 @@ password %5D%5D) +; %0A%7D%0A%0Afunction @@ -294,16 +294,17 @@ oken %5D%5D) +; %0A%7D%0A%0Aexpo
42b39d74d66281a143833afde4e97060bdd4aaab
fix null error
src/botPage/view/blockly/blocks/trade/index.js
src/botPage/view/blockly/blocks/trade/index.js
import { observer as globalObserver } from '../../../../../common/utils/observer'; import { translate } from '../../../../../common/i18n'; import config from '../../../../common/const'; import { setBlockTextColor, findTopParentBlock, deleteBlockIfExists } from '../../utils'; import { defineContract } from '../images'; import { updatePurchaseChoices, fieldGeneratorMapping, dependentFieldMapping } from '../shared'; import { marketDefPlaceHolders } from './tools'; import backwardCompatibility from './backwardCompatibility'; import tradeOptions from './tradeOptions'; const bcMoveAboveInitializationsDown = block => { Blockly.Events.recordUndo = false; Blockly.Events.setGroup('BackwardCompatibility'); const parent = block.getParent(); if (parent) { const initializations = block.getInput('INITIALIZATION').connection; const ancestor = findTopParentBlock(parent); parent.nextConnection.disconnect(); initializations.connect((ancestor || parent).previousConnection); } block.setPreviousStatement(false); Blockly.Events.setGroup(false); Blockly.Events.recordUndo = true; }; const decorateTrade = ev => { const trade = Blockly.mainWorkspace.getBlockById(ev.blockId); if (!trade || trade.type !== 'trade') { return; } if ([Blockly.Events.CHANGE, Blockly.Events.MOVE, Blockly.Events.CREATE].includes(ev.type)) { const symbol = trade.getFieldValue('SYMBOL_LIST'); if (symbol) { globalObserver.emit('bot.init', symbol); } const type = trade.getFieldValue('TRADETYPE_LIST'); if (type) { const oppositesName = type.toUpperCase(); const contractType = trade.getFieldValue('TYPE_LIST'); if (oppositesName && contractType) { updatePurchaseChoices(contractType, oppositesName); } } } }; const replaceInitializationBlocks = (trade, ev) => { if (ev.type === Blockly.Events.CREATE) { ev.ids.forEach(blockId => { const block = Blockly.mainWorkspace.getBlockById(blockId); if (block && block.type === 'trade' && !deleteBlockIfExists(block)) { bcMoveAboveInitializationsDown(block); } }); } }; const forceUpdateField = (trade, fieldName) => { Blockly.Events.fire(new Blockly.Events.Change(trade, 'field', fieldName, '', trade.getFieldValue(fieldName))); }; const setDefaultFields = (trade, parentFieldName) => { if (!Object.keys(dependentFieldMapping).includes(parentFieldName)) return; const childFieldName = dependentFieldMapping[parentFieldName]; const [[, defaultValue]] = fieldGeneratorMapping[childFieldName](trade)(); trade.setFieldValue(defaultValue, childFieldName); if (childFieldName === 'TRADETYPECAT_LIST') forceUpdateField(trade, 'TRADETYPECAT_LIST'); }; const resetTradeFields = (trade, ev) => { if (ev.blockId === trade.id) { if (ev.element === 'field') { setDefaultFields(trade, ev.name); if (ev.name === 'TRADETYPE_LIST') { if (ev.newValue) { trade.setFieldValue('both', 'TYPE_LIST'); } else { trade.setFieldValue('', 'TYPE_LIST'); } } } } }; Blockly.Blocks.trade = { init: function init() { this.appendDummyInput() .appendField(new Blockly.FieldImage(defineContract, 25, 25, 'T')) .appendField(translate('(1) Define your trade contract')); marketDefPlaceHolders(this); this.appendDummyInput().appendField(`${translate('Run Once at Start')}:`); this.appendStatementInput('INITIALIZATION').setCheck(null); this.appendDummyInput().appendField(`${translate('Define Trade Options')}:`); this.appendStatementInput('SUBMARKET').setCheck(null); this.setColour('#2a3052'); this.setTooltip( translate('Define your trade contract and start the trade, add initializations here. (Runs on start)') ); this.setHelpUrl('https://github.com/binary-com/binary-bot/wiki'); }, onchange: function onchange(ev) { setBlockTextColor(this); if (ev.group !== 'BackwardCompatibility') { replaceInitializationBlocks(this, ev); resetTradeFields(this, ev); } const initStatement = this.getInputTargetBlock('INITIALIZATION'); const initChild = initStatement.getChildren(); initChild.forEach(child => { if (child.type === 'total_profit' || child.type === 'total_runs') { child.unplug(true); } }); decorateTrade(ev); }, }; Blockly.JavaScript.trade = block => { const account = $('.account-id') .first() .attr('value'); if (!account) { throw Error('Please login'); } const initialization = Blockly.JavaScript.statementToCode(block, 'INITIALIZATION'); const tradeOptionsStatement = Blockly.JavaScript.statementToCode(block, 'SUBMARKET'); const candleIntervalValue = block.getFieldValue('CANDLEINTERVAL_LIST'); const contractTypeSelector = block.getFieldValue('TYPE_LIST'); const oppositesName = block.getFieldValue('TRADETYPE_LIST').toUpperCase(); const contractTypeList = contractTypeSelector === 'both' ? config.opposites[oppositesName].map(k => Object.keys(k)[0]) : [contractTypeSelector]; const timeMachineEnabled = block.getFieldValue('TIME_MACHINE_ENABLED') === 'TRUE'; const shouldRestartOnError = block.getFieldValue('RESTARTONERROR') === 'TRUE'; const code = ` BinaryBotPrivateInit = function BinaryBotPrivateInit() { Bot.init('${account}', { symbol: '${block.getFieldValue('SYMBOL_LIST')}', contractTypes: ${JSON.stringify(contractTypeList)}, candleInterval: '${candleIntervalValue}', shouldRestartOnError: ${shouldRestartOnError}, timeMachineEnabled: ${timeMachineEnabled}, }); ${initialization.trim()} }; BinaryBotPrivateStart = function BinaryBotPrivateStart() { ${tradeOptionsStatement.trim()} }; `; return code; }; export default () => { backwardCompatibility(); tradeOptions(); };
JavaScript
0.000007
@@ -4366,32 +4366,60 @@ ev);%0A %7D%0A%0A + decorateTrade(ev);%0A%0A const in @@ -4420,24 +4420,20 @@ nst init -Statemen +Inpu t = this @@ -4468,24 +4468,54 @@ LIZATION');%0A +%0A if (initInput) %7B%0A cons @@ -4532,24 +4532,20 @@ d = init -Statemen +Inpu t.getChi @@ -4550,24 +4550,28 @@ hildren();%0A%0A + init @@ -4591,24 +4591,28 @@ (child =%3E %7B%0A + @@ -4695,16 +4695,20 @@ + + child.un @@ -4727,34 +4727,41 @@ -%7D%0A + %7D%0A %7D);%0A%0A @@ -4752,21 +4752,21 @@ + %7D);%0A -%0A deco @@ -4761,34 +4761,17 @@ -decorateTrade(ev); +%7D %0A %7D,%0A
7c78b2af30a8c08cf3783dffd1ce9e266c7ea544
check for close and ready state of socket, implement buffersend
src/javascript/binary/pages/trade/socket.js
src/javascript/binary/pages/trade/socket.js
var TradeSocket = (function () { 'use strict'; var tradeSocket, socketUrl = "wss://www.devbin.io/websockets/contracts"; var status = function () { return tradeSocket && tradeSocket.readyState; }; var isReady = function () { return tradeSocket && tradeSocket.readyState == 1; }; var onOpen = function (token) { tradeSocket.send(JSON.stringify({ authorize: token })); tradeSocket.send(JSON.stringify({ offerings: {hierarchy: 1, contracts: 0} })); }; var onMessage = function (msg) { var response = JSON.parse(msg.data); Message.process(msg); }; var onClose = function (e) { console.log('socket closed', e); }; var onError = function (error) { console.log('socket error', error); }; var init = function (token) { tradeSocket = new WebSocket(socketUrl); tradeSocket.onopen = onOpen(token); tradeSocket.onmessage = onMessage; tradeSocket.onclose = onClose; tradeSocket.onerror = onError; }; var send = function(data) { if (isReady()) { tradeSocket.send(JSON.stringify(data)); } else { } }; return { init: init, status: status, socket: tradeSocket, send: send }; })();
JavaScript
0
@@ -128,16 +128,44 @@ ntracts%22 +,%0A bufferedSends = %5B%5D ;%0A%0A v @@ -339,16 +339,17 @@ State == += 1;%0A @@ -360,22 +360,23 @@ var -onOpen +isClose = funct @@ -372,37 +372,32 @@ ose = function ( -token ) %7B%0A trad @@ -396,85 +396,157 @@ -tradeSocket.send(JSON.stringify(%7B%0A authorize: token%0A %7D));%0A%0A +return tradeSocket && tradeSocket.readyState === 3;%0A %7D;%0A%0A var sendBufferedSends = function () %7B%0A while (bufferedSends.length %3E 0) %7B%0A @@ -581,17 +581,40 @@ ringify( -%7B +bufferedSends.shift())); %0A @@ -618,90 +618,127 @@ +%7D%0A -offerings: %7Bhierarchy: 1, contracts: 0%7D%0A %7D) +%7D;%0A%0A var init = function (token) %7B%0A tradeSocket = new WebSocket(socketUrl );%0A +%0A -%7D;%0A%0A var onMessage + tradeSocket.onopen = f @@ -750,13 +750,14 @@ on ( -msg) +token) %7B%0A @@ -766,45 +766,97 @@ -var response = JSON.parse(msg.data);%0A + sendBufferedSends();%0A %7D;%0A%0A tradeSocket.onmessage = function (msg)%7B%0A @@ -881,16 +881,20 @@ s(msg);%0A + %7D;%0A%0A @@ -901,15 +901,27 @@ -var onC + tradeSocket.onc lose @@ -934,24 +934,28 @@ ction (e) %7B%0A + cons @@ -987,27 +987,44 @@ e);%0A + %7D; +; %0A%0A -var onE + tradeSocket.one rror @@ -1041,24 +1041,28 @@ n (error) %7B%0A + cons @@ -1093,16 +1093,28 @@ error);%0A + %7D;;%0A %7D;%0A%0A @@ -1113,36 +1113,36 @@ %7D;%0A%0A var -init +send = function (tok @@ -1128,39 +1128,37 @@ send = function - (token +(data ) %7B%0A trad @@ -1157,90 +1157,60 @@ -tradeSocket = new WebSocket(socketUrl);%0A%0A tradeSocket.onopen = onOpen(token +if (isClose()) %7B%0A bufferedSends.push(data );%0A @@ -1208,32 +1208,36 @@ (data);%0A + tradeSocket.onme @@ -1236,108 +1236,164 @@ ket. -onmessage = onMessage;%0A tradeSocket.onclose = onClose;%0A tradeSocket.onerror = onError; +init();%0A %7D else if (isReady()) %7B%0A tradeSocket.send(JSON.stringify(data));%0A %7D else %7B%0A bufferedSends.push(data);%0A %7D %0A @@ -1397,36 +1397,37 @@ %7D;%0A%0A var +clo se -nd = function(data @@ -1413,37 +1413,34 @@ close = function + ( -data ) %7B%0A if ( @@ -1435,33 +1435,35 @@ if ( -isReady() +tradeSocket ) %7B%0A @@ -1482,175 +1482,161 @@ ket. -send(JSON.stringify(data));%0A %7D else %7B%0A %7D%0A %7D;%0A%0A return %7B%0A init: init,%0A status: status,%0A socket: tradeSocket,%0A send: send +close();%0A %7D%0A %7D;%0A%0A return %7B%0A init: init,%0A send: send,%0A close: close,%0A socket: function () %7B return tradeSocket; %7D %0A
106e2a0d9a294837c7469a7cce11ae269066ee46
Stop retries after a few errors (#2233)
gui/js/updater.window.js
gui/js/updater.window.js
const Promise = require('bluebird') const WindowManager = require('./window_manager') const { autoUpdater } = require('electron-updater') const { translate } = require('./i18n') const { dialog } = require('electron') const path = require('path') const log = require('../../core/app').logger({ component: 'GUI:autoupdater' }) /** The delay starting from the update info request after which it is skipped. * * Long enough so users with slow connection have chances to start downloading * the update before it is skipped (5s was tried but didn't seem sufficient in * some cases). * * App startup could be slower in case GitHub is down exactly at the same * time. But the delay still seems acceptable for an app starting * automatically on boot. Even in case it is started by hand. * * Except for downtimes, users with fast connection should still get a fast * available or unavailable update answer anyway. */ const UPDATE_CHECK_TIMEOUT = 10000 const UPDATE_RETRY_DELAY = 1000 module.exports = class UpdaterWM extends WindowManager { windowOptions() { return { title: 'UPDATER', width: 500, height: 400 } } humanError(err) { switch (err.code) { case 'EPERM': return translate('Updater Error EPERM') case 'ENOSP': return translate('Updater Error ENOSPC') default: return translate('Updater Error Other') } } constructor(...opts) { autoUpdater.logger = log autoUpdater.autoDownload = false autoUpdater.on('update-available', info => { this.clearTimeoutIfAny() log.info({ update: info, skipped: this.skipped }, 'Update available') // Make sure UI doesn't show up after timeout if (!this.skipped) { const shouldUpdate = dialog.showMessageBoxSync({ icon: path.resolve(__dirname, '..', 'images', 'icon.png'), title: 'Cozy Drive', message: 'Cozy Drive', detail: translate( 'A new version is available, do you want to update?' ), type: 'question', buttons: ['Update', 'Cancel'].map(translate) }) === 0 if (shouldUpdate) { autoUpdater.downloadUpdate() this.show() } else { this.skipUpdate('refused update') } } }) autoUpdater.on('update-not-available', info => { log.info({ update: info }, 'No update available') this.afterUpToDate() }) autoUpdater.on('error', async err => { if (this.skipped) { return } else if (err.code === 'ENOENT') { this.skipUpdate('assuming development environment') } else { await Promise.delay(UPDATE_RETRY_DELAY) await autoUpdater.checkForUpdates() } }) autoUpdater.on('download-progress', progressObj => { log.trace({ progress: progressObj }, 'Downloading...') this.send('update-downloading', progressObj) }) autoUpdater.on('update-downloaded', info => { log.info({ update: info }, 'Update downloaded. Exit and install...') setImmediate(() => this.desktop .stopSync() .then(() => this.desktop.pouch.db.close()) .then(() => autoUpdater.quitAndInstall()) .then(() => this.app.quit()) .then(() => this.app.exit(0)) .catch(err => this.send('error-updating', this.humanError(err))) ) }) super(...opts) } clearTimeoutIfAny() { if (this.timeout) { clearTimeout(this.timeout) this.timeout = null } } onUpToDate(handler) { this.afterUpToDate = () => { this.clearTimeoutIfAny() handler() } } async checkForUpdates() { this.skipped = false this.timeout = setTimeout(() => { this.skipUpdate(`check is taking more than ${UPDATE_CHECK_TIMEOUT} ms`) }, UPDATE_CHECK_TIMEOUT) try { await autoUpdater.checkForUpdates() } catch (err) { // Dealing with the error itself is alreay done via the listener on the // `error` event. log.error({ err }) } } skipUpdate(reason) { log.info({ sentry: true }, `Not updating: ${reason}`) this.skipped = true // Disable handler & warn on future calls const handler = this.afterUpToDate this.afterUpToDate = () => {} if (typeof handler === 'function') handler() } hash() { return '#updater' } ipcEvents() { return {} } }
JavaScript
0
@@ -952,17 +952,16 @@ = 10000%0A -%0A const UP @@ -983,16 +983,41 @@ Y = 1000 +%0Aconst UPDATE_RETRIES = 5 %0A%0Amodule @@ -1067,16 +1067,51 @@ nager %7B%0A + /*::%0A retriesLeft: number%0A */%0A%0A window @@ -2722,33 +2722,86 @@ ')%0A %7D else -%7B +if (this.retriesLeft %3E 0) %7B%0A this.retriesLeft-- %0A await P @@ -2873,24 +2873,118 @@ orUpdates()%0A + %7D else %7B%0A this.retriesLeft = UPDATE_RETRIES%0A this.skipUpdate(err.message)%0A %7D%0A @@ -3648,16 +3648,55 @@ ...opts) +%0A%0A this.retriesLeft = UPDATE_RETRIES %0A %7D%0A%0A
3a578dcf5c671048d8ecaaa0f49af8f805850c38
clean up
src/js/app/controllers/post/PostCardCtrl.js
src/js/app/controllers/post/PostCardCtrl.js
var RichText = require('../../services/RichText') var TimeText = require('../../services/TimeText') var truncate = require('html-truncate') module.exports = function ($scope, $state, $rootScope, $modal, $dialog, $analytics, growl, Post, User, UserCache, CurrentUser) { 'ngInject' $scope.singlePost = $state.current.data && $state.current.data.singlePost $scope.isCommentsCollapsed = !$scope.singlePost $scope.voteTooltipText = '' $scope.followersNotMe = [] $scope.isFollowing = false $scope.eventResponse = '' $scope.joinPostText = '' $scope.onlyAuthorFollowing = false var currentUser = CurrentUser.get() var voteText = "click to <i class='icon-following'></i> me." var unvoteText = "click to un-<i class='icon-following'></i> me." var post = $scope.post $scope.community = Post.relevantCommunity(post, currentUser) $scope.isPostOwner = function () { return CurrentUser.is(post.user && post.user.id) } $scope.markFulfilled = function () { var modalInstance = $modal.open({ templateUrl: '/ui/app/fulfillModal.tpl.html', controller: 'FulfillmentCtrl', keyboard: false, backdrop: 'static', scope: $scope }) modalInstance.result.then(() => $analytics.eventTrack('Post: Fulfill', {post_id: post.id})) } // Voting is the same thing as "liking" $scope.vote = function () { post.myVote = !post.myVote post.votes += (post.myVote ? 1 : -1) $scope.voteTooltipText = post.myVote ? unvoteText : voteText Post.vote({id: post.id}, function () { $analytics.eventTrack('Post: Like', { post_id: post.id, state: (post.myVote ? 'on' : 'off') }) }, function (resp) { if (_.contains([401, 403], resp.status)) { $scope.$emit('unauthorized', {context: 'like'}) } }) } $scope.toggleComments = function () { if ($scope.isCommentsCollapsed) { $analytics.eventTrack('Post: Comments: Show', {post_id: post.id}) } $scope.isCommentsCollapsed = !$scope.isCommentsCollapsed } $scope.toggleFollow = function () { var user = currentUser if (!user) return if (!$scope.isFollowing) { $analytics.eventTrack('Post: Join', {post_id: post.id}) post.followers.push({ id: user.id, name: user.name, avatar_url: user.avatar }) Post.follow({id: post.id}) UserCache.followedPosts.clear(user.id) } else { $analytics.eventTrack('Post: Leave', {post_id: post.id}) post.followers = _.without(post.followers, _.findWhere(post.followers, {id: user.id})) Post.follow({id: post.id}) UserCache.followedPosts.remove(user.id, post.id) } } $scope['delete'] = function () { $dialog.confirm({ message: 'Are you sure you want to remove "' + post.name + '"? This cannot be undone.' }).then(function () { $scope.removeFn({postToRemove: post}) new Post(post).$remove({}) }) } $scope.showMore = function () { setText(true) } $scope.openFollowers = function (isOpen) { if (isOpen) { $analytics.eventTrack('Followers: Viewed List of Followers', {num_followers: $scope.followersNotMe.length}) } } $scope.complain = function () { Post.complain({id: post.id}, function () { growl.addSuccessMessage('Thank you for reporting this. Moderators will address it within 24 hours.') }) } $scope.postImage = function () { return _.find(post.media || [], m => m.type === 'image') } $scope.docs = function () { return _.filter(post.media || [], m => m.type === 'gdoc') } var setText = function (fullLength) { var text = post.description if (!text) text = '' text = RichText.present(text) if (!fullLength && angular.element(text).text().trim().length > 140) { text = truncate(text, 140) $scope.truncated = true } else { $scope.truncated = false } $scope.description = text $scope.hasDescription = angular.element(text).text().trim().length > 0 } $scope.$watchCollection('post.followers', function () { var meInFollowers = (currentUser && _.findWhere(post.followers, {id: currentUser.id})) if (meInFollowers) { $scope.followersNotMe = _.without(post.followers, meInFollowers) $scope.isFollowing = true } else { $scope.followersNotMe = post.followers $scope.isFollowing = false } // If the only person following the post is the author we can hide the following status in the post var firstFollower = _.first(post.followers) $scope.onlyAuthorFollowing = (post.followers.length === 1 && firstFollower.name === post.user.name) }) $scope.canEdit = currentUser && (post.user.id === currentUser.id || currentUser.canModerate(post.communities[0])) $scope.voteTooltipText = post.myVote ? unvoteText : voteText setText($scope.startExpanded) var now = new Date() $scope.showUpdateTime = (now - new Date(post.updated_at)) < (now - new Date(post.created_at)) * 0.8 $scope.truncate = truncate $scope.showTime = function () { var start = new Date(post.start_time) var end = post.end_time && new Date(post.end_time) return TimeText.range(start, end) } $scope.showFullTime = function () { var start = new Date(post.start_time) var end = post.end_time && new Date(post.end_time) return TimeText.rangeFullText(start, end) } $scope.changeEventResponse = function (response) { var user = currentUser if (!user) return if ($scope.eventResponse === response) { $scope.eventResponse = '' $analytics.eventTrack('Event: Unrespond', {post_id: post.id}) Post.respond({id: post.id, response: response}) } else { $scope.eventResponse = response $analytics.eventTrack('Event: Respond', {post_id: post.id, response: response}) Post.respond({id: post.id, response: response}) } /* if (!$scope.isFollowing) { $analytics.eventTrack('Post: Join', {post_id: post.id}) post.followers.push({ id: user.id, name: user.name, avatar_url: user.avatar }) Post.follow({id: post.id}) UserCache.followedPosts.clear(user.id) } else { $analytics.eventTrack('Post: Leave', {post_id: post.id}) post.followers = _.without(post.followers, _.findWhere(post.followers, {id: user.id})) Post.follow({id: post.id}) UserCache.followedPosts.remove(user.id, post.id) } */ } }
JavaScript
0.000001
@@ -5879,572 +5879,8 @@ %7D -%0A%0A /*%0A if (!$scope.isFollowing) %7B%0A $analytics.eventTrack('Post: Join', %7Bpost_id: post.id%7D)%0A post.followers.push(%7B%0A id: user.id,%0A name: user.name,%0A avatar_url: user.avatar%0A %7D)%0A Post.follow(%7Bid: post.id%7D)%0A UserCache.followedPosts.clear(user.id)%0A %7D else %7B%0A $analytics.eventTrack('Post: Leave', %7Bpost_id: post.id%7D)%0A post.followers = _.without(post.followers, _.findWhere(post.followers, %7Bid: user.id%7D))%0A Post.follow(%7Bid: post.id%7D)%0A UserCache.followedPosts.remove(user.id, post.id)%0A %7D%0A */ %0A %7D
9ad44449bdb56a832f53dea502b79f18252c736c
Fix coverage folder for mocha
gulp_tasks/tasks/test.js
gulp_tasks/tasks/test.js
'use strict'; var gulp = require('gulp'); var runSequence = require('run-sequence'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var gutil = require('gulp-util'); var constants = require('../common/constants')(); gulp.task('mocha', 'Runs the mocha tests.', function() { return gulp.src(constants.mocha.libs) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()) .on('finish', function() { gutil.log(__dirname); gulp.src(constants.mocha.tests) .pipe(mocha({ reporter: 'spec', globals: constants.mocha.globals, timeout: constants.mocha.timeout })) .pipe(istanbul.writeReports({ reporters: ['lcov', 'json', 'text', 'text-summary', 'cobertura'] })); }); }); gulp.task('test', 'Runs all the tests.', function(done) { runSequence( 'lint', 'mocha', done ); });
JavaScript
0.000001
@@ -802,16 +802,61 @@ ports(%7B%0A + dir: './coverage/mocha',%0A
71e0a4bf1e250471f29d9e7f7e90a3b81cd5a53d
add account models
src/core/account.js
src/core/account.js
JavaScript
0
@@ -0,0 +1,361 @@ +'use strict'%0A%0Avar BaseModel = require('capital-models').BaseModel;%0A%0Amodule.exports = class Account extends BaseModel %7B%0A constructor(source) %7B%0A super('account', '1.0.0');%0A%0A // Define properties. %0A this.username = '';%0A this.password = '';%0A this.isLocked = false;%0A this.config = %7B%7D;%0A%0A this.copy(source);%0A %7D%0A%7D
05343351e888f09548f5ef9654a4d1f104234db7
Fix disable method for unrendered tooltips. Fixes #565
src/core/disable.js
src/core/disable.js
PROTOTYPE.disable = function(state) { if(this.destroyed) { return this; } if('boolean' !== typeof state) { state = !(this.tooltip.hasClass(CLASS_DISABLED) || this.disabled); } if(this.rendered) { this.tooltip.toggleClass(CLASS_DISABLED, state) .attr('aria-disabled', state); } this.disabled = !!state; return this; }; PROTOTYPE.enable = function() { return this.disable(FALSE); };
JavaScript
0
@@ -115,16 +115,32 @@ ate = !( +this.rendered ? this.too @@ -173,10 +173,9 @@ ED) -%7C%7C +: thi
dda245cca3708336a90423ff1fbab43438a90acd
fix capture ressources avec plusieurs personnes
app/js/controllers/foyer/ressources/ressources.js
app/js/controllers/foyer/ressources/ressources.js
'use strict'; angular.module('ddsApp').controller('FoyerRessourcesCtrl', function($scope, $state, ressourceTypes, SituationService, IndividuService) { $scope.momentDebutAnnee = moment().subtract('years', 1); $scope.momentFinAnnee = moment().startOf('month').subtract('months', 1); $scope.debutAnnee = $scope.momentDebutAnnee.format('MMMM YYYY'); $scope.finAnnee = $scope.momentFinAnnee.format('MMMM YYYY'); $scope.ressourceTypes = ressourceTypes; $scope.months = SituationService.getMonths(); $scope.individuRefs = _.map($scope.situation.individus, function(individu) { return { label: IndividuService.label(individu), selectedRessourceTypes: {}, ressources: [], individu: individu }; }); $scope.selectedRessourceTypes = {}; $scope.$on('selectedRessourceTypes', function() { var hasSelectedRessources = !!_.filter($scope.selectedRessourceTypes).length; if (hasSelectedRessources) { if (1 < $scope.individuRefs.length) { $state.go('foyer.ressources.personnes'); } else { $scope.individuRefs[0].selectedRessourceTypes = $scope.selectedRessourceTypes; $scope.initIndividusRessources(); $state.go('foyer.ressources.montants'); } } else { $state.go('foyer.patrimoine'); } }); $scope.$on('selectedPersonnes', function() { if (!_.filter($scope.individuRefs, 'hasRessources').length) { $state.go('foyer.patrimoine'); return; } $scope.initIndividusRessources(); $state.go('foyer.ressources.montants'); }); $scope.initIndividusRessources = function() { $scope.individuRefs.forEach(function(individuRef) { var previousRessources = individuRef.ressources; individuRef.ressources = []; individuRef.hasRessources = false; individuRef.hasRessourcesMicroTns = false; individuRef.hasRessourcesOtherTns = false; individuRef.hasRessourcesNonTns = false; ressourceTypes.forEach(function(ressourceType) { if (!individuRef.selectedRessourceTypes[ressourceType.id] || !$scope.selectedRessourceTypes[ressourceType.id]) { return; } individuRef.hasRessources = true; if ('caMicroEntreprise' === ressourceType.id) { individuRef.hasRessourcesMicroTns = true; } else if ('autresRevenusTns' === ressourceType.id) { individuRef.hasRessourcesOtherTns = true; } else { individuRef.hasRessourcesNonTns = true; } var ressource = _.find(previousRessources, {type: ressourceType}); if (!ressource) { ressource = {type: ressourceType}; if ('caMicroEntreprise' === ressourceType.id) { ressource.tnsStructureType = 'auto_entrepreneur'; ressource.tnsActiviteType = 'bic'; } ressource.montantAnnuel = 0; if ('tns' !== ressourceType.category) { ressource.months = [ { periode: $scope.months[0].id, montant: 0 }, { periode: $scope.months[1].id, montant: 0 }, { periode: $scope.months[2].id, montant: 0 } ]; } } individuRef.ressources.push(ressource); }); }); }; });
JavaScript
0
@@ -1462,32 +1462,74 @@ ', function() %7B%0A + $scope.initIndividusRessources();%0A if (!_.f @@ -1659,50 +1659,8 @@ %7D%0A - $scope.initIndividusRessources();%0A
4ddd28d7934fab57c4685a1be09fca6bb1eff687
Add React VR and Javascript ES6+ to skillset
src/data/profile.js
src/data/profile.js
const PROFILE = { summary: `Den Temple is a Javascript Developer specializing in Web and Mobile Design. He has additional expertise with SEO consulting, API integration, and Machine Learning analytics.`, email: '[email protected]', forHire: true, location: 'Scranton, PA', year: 'April 2017', clientSkills: [ 'Web Apps', 'UI/UX', 'SEO', 'Social Media APIs', 'Payment APIs', 'Based in U.S.' ], employerSkills: ['React', 'Node.js', 'Agile/Scrum', 'Git/Github'] } export default PROFILE
JavaScript
0
@@ -136,22 +136,22 @@ ith -SEO consulting +VR experiences , AP @@ -173,34 +173,22 @@ and -Machine Learning analytics +SEO consulting .%60,%0A @@ -441,16 +441,57 @@ s: %5B +%0A 'React -', +/React VR',%0A 'Javascript ES6+',%0A 'No @@ -497,16 +497,20 @@ ode.js', +%0A 'Agile/ @@ -516,16 +516,20 @@ /Scrum', +%0A 'Git/Gi @@ -533,16 +533,19 @@ /Github' +%0A %5D%0A%7D%0A%0Aexp
7cd0a80c0b72b2144ca5478f119373d5f6d03110
Add email address #4
form-faker.js
form-faker.js
console.log('form-faker: faking data...'); const dictionary = getDictionary(); var inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; if (input.type.toLowerCase() !== 'text' || input.value) { continue; } var name = input.name.toLowerCase(); var mapping = dictionary.get(name); switch (mapping) { case 'firstName': input.value = faker.name.firstName(); break; case 'lastName': input.value = faker.name.firstName(); break; case 'date-past': var date = faker.date.past(50); input.value = date.toLocaleDateString(); break; case 'account': input.value = faker.finance.account(); break; default: if (input.attributes.required) { input.value = faker.random.word(); } break; } } console.log('form-faker: Done!'); function getDictionary() { return new Map([ // firstName ['firstname', 'firstName'], ['first_name', 'firstName'], ['first-name', 'firstName'], ['fname', 'firstName'], // lastName ['lastname', 'lastName'], ['last_name', 'lastName'], ['last-name', 'lastName'], ['lname', 'lastName'], // date-past ['birthdate', 'date-past'], // account ['mrn', 'account'], ]); }
JavaScript
0.001053
@@ -639,32 +639,107 @@ );%0A break;%0A + case 'email':%0A input.value = faker.internet.email();%0A break;%0A case 'accoun @@ -1278,24 +1278,156 @@ lastName'%5D,%0A + // email%0A %5B'email', 'email'%5D,%0A %5B'emailaddress', 'email'%5D,%0A %5B'email_address', 'email'%5D,%0A %5B'email-address', 'email'%5D,%0A // date- @@ -1509,8 +1509,9 @@ %0A %5D);%0A%7D +%0A
f1710f41b421f0ef91d7081163f7558af564d889
Change yul test to use gas() and identity precompile
packages/debugger/test/data/yul.js
packages/debugger/test/data/yul.js
import debugModule from "debug"; const debug = debugModule("test:data:more-decoding"); import { assert } from "chai"; import Ganache from "ganache-core"; import { prepareContracts, lineOf } from "../helpers"; import Debugger from "lib/debugger"; import solidity from "lib/solidity/selectors"; import * as Codec from "@truffle/codec"; const __YUL = ` pragma solidity ^0.6.6; contract AssemblyTest { function run() public { uint outside = 8; assembly { let u := 3 let v := u let w := add(u, 3) let z := outside let result := staticcall(0, 0, 0, 0, 0, 0) if sgt(z, 0) { let k := shl(1, z) log1(0, 0, k) //BREAK #1 } function twist(a, b) -> c, d { let x1, x2 let y1, y2 x1 := add(a, b) x2 := sub(a, b) y1 := and(a, b) y2 := or(a, b) c := mul(x1, x2) d := xor(y1, y2) log1(0, 0, sdiv(c, d)) //BREAK #2 } let n, m := twist(w, v) log1(0, 0, shl(z, smod(n, m))) //BREAK #3 } } } `; let sources = { "AssemblyTest.sol": __YUL }; describe("Assembly decoding", function() { var provider; var abstractions; var compilations; before("Create Provider", async function() { provider = Ganache.provider({ seed: "debugger", gasLimit: 7000000 }); }); before("Prepare contracts and artifacts", async function() { this.timeout(30000); let prepared = await prepareContracts(provider, sources); abstractions = prepared.abstractions; compilations = prepared.compilations; }); it("Decodes assembly variables", async function() { this.timeout(12000); let instance = await abstractions.AssemblyTest.deployed(); let receipt = await instance.run(); let txHash = receipt.tx; let bugger = await Debugger.forTx(txHash, { provider, compilations }); let sourceId = bugger.view(solidity.current.source).id; let compilationId = bugger.view(solidity.current.source).compilationId; let source = bugger.view(solidity.current.source).source; await bugger.addBreakpoint({ sourceId, compilationId, line: lineOf("BREAK #1", source) }); await bugger.addBreakpoint({ sourceId, compilationId, line: lineOf("BREAK #2", source) }); await bugger.addBreakpoint({ sourceId, compilationId, line: lineOf("BREAK #3", source) }); await bugger.continueUntilBreakpoint(); const numberize = obj => Object.assign( {}, ...Object.entries(obj).map(([key, value]) => ({ [key]: Number(value) })) ); let variables = numberize( Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables()) ); let expectedResult = { outside: 8, u: 3, v: 3, w: 6, z: 8, result: 1, k: 16 }; assert.deepInclude(variables, expectedResult); await bugger.continueUntilBreakpoint(); variables = numberize( Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables()) ); expectedResult = { a: 6, b: 3, x1: 9, x2: 3, y1: 2, y2: 7, c: 27, d: 5 }; assert.deepInclude(variables, expectedResult); await bugger.continueUntilBreakpoint(); variables = numberize( Codec.Format.Utils.Inspect.nativizeVariables(await bugger.variables()) ); expectedResult = { outside: 8, u: 3, v: 3, w: 6, z: 8, result: 1, n: 27, m: 5 }; assert.deepInclude(variables, expectedResult); }); });
JavaScript
0
@@ -574,17 +574,21 @@ ticcall( -0 +gas() , 0, 0, @@ -595,16 +595,30 @@ 0, 0, 0) + //identity fn %0A i
f8a300ecfe680e2d3768671b9bc69280c57571e6
remove some jQuery
user/static/js/es6_modules/contacts/index.js
user/static/js/es6_modules/contacts/index.js
import {teammemberTemplate} from "./templates" import {deleteMemberDialog} from "./manage" import {addDropdownBox, postJson, addAlert, OverviewMenuView} from "../common" import {SiteMenu} from "../menu" import {menuModel} from "./menu" export class ContactsOverview { constructor() { let smenu = new SiteMenu("") // Nothing highlighted. smenu.init() this.menu = new OverviewMenuView(this, menuModel) this.menu.init() this.bind() this.getList() } getList() { postJson('/user/team/list/').then( json => { jQuery('#team-table tbody').append(teammemberTemplate({members: json.team_members})) } ).catch( () => addAlert('error', gettext('Could not obtain contacts list')) ) } bind() { jQuery(document).ready(function() { //delete single user jQuery(document).on('click', '.delete-single-member', function() { deleteMemberDialog([jQuery(this).attr('data-id')]) }) }) } // get IDs of selected contacts getSelected() { return [].slice.call( document.querySelectorAll('.entry-select:checked:not(:disabled)') ).map(el => parseInt(el.getAttribute('data-id'))) } }
JavaScript
0.000002
@@ -595,22 +595,38 @@ -jQuery +document.querySelector ('#team- @@ -643,15 +643,21 @@ y'). -append( +innerHTML += team @@ -700,17 +700,16 @@ embers%7D) -) %0A
1b1b361cb1859f9aa40c07a680aebc6c6aa29064
add topic css
modules/components/topic.js
modules/components/topic.js
/** * Created by natefang on 1/14/16. */ import React, { Component } from 'react'; import { Link } from 'react-router'; import fetch from 'isomorphic-fetch'; import moment from 'moment'; class Topic extends Component { constructor(props) { super(props); this.state = { topic: { strategies:[], owner:{ nickname :'' }, cover: '', score: 0, tryCount :0, description:'' } }; } componentWillMount (){ //var id = document.URL.split("/").slice(-1)[0]; fetch('http://www.iyuanzi.net/topics/'+ this.props.params.id + '?version=v2') .then((response) => response.json()) .then((data) => { this.setState({ topic: data }); var title = data.title || '元子育儿'; var image = data.cover || 'http://share.iyuanzi.net/favicon.ico'; var description = title; const oMeta = document.createElement('meta'); oMeta.setAttribute('property', 'og:title'); oMeta.setAttribute('content', title); document.getElementsByTagName('head')[0].appendChild(oMeta); const oMetaimage = document.createElement('meta'); oMetaimage.setAttribute('property', 'og:image'); oMetaimage.setAttribute('content', image); document.getElementsByTagName('head')[0].appendChild(oMetaimage); const oMetadesc = document.createElement('meta'); oMetadesc.setAttribute('property', 'og:description'); oMetadesc.setAttribute('content', description); document.getElementsByTagName('head')[0].appendChild(oMetadesc); }) .catch((ex) => { console.log('fetch failed', ex); }); } render() { return ( <div className="content"> { <Topics topic = {this.state.topic}/> } </div> ); } } class Topics extends Component { render () { return ( <div className="topics"><img className="coverImg" src={this.props.topic.cover}/> <div className="topicTitle">{this.props.topic.title}</div> <div className="authorWrap"><span> 来自: </span><span className="author">{this.props.topic.owner.nickname}</span></div> <div className="descrption">{this.props.topic.content}</div> <StrategiesCollections strategies={this.props.topic.strategies}/> </div> ); } } class StrategiesCollections extends Component { render () { return ( <div> { this.props.strategies.length ? <div> <div className="sectionTitle"> <span className="sectionName">妙招 </span> <span>({this.props.strategies.length})</span> </div> <ul className="strategyiesCollection"> { this.props.strategies.map(function(item) { return (<StrategyItem key={item.strategyId} {...item}></StrategyItem>); }) } </ul> </div> : null } </div> ); } } class StrategyItem extends Component { render () { return ( <Link to={'/strategies/'+this.props.strategyId+'/view'} > <li className="strategyItem"> <div className="strategyItemWrap"><img src={this.props.cover} alt="" className="strategyCover"/> <div className="title">{this.props.title}</div> <div className="authorWrap"><span>by </span><span className="author">{this.props.owner.nickname}</span></div> <div className="separator"></div> <div className="score">{ this.props.tryCount+'人参与 / ' + this.props.score+'分' } </div> </div></li> </Link> ); }; } export default Topic;
JavaScript
0
@@ -182,16 +182,44 @@ oment';%0A +import './style/topic.css';%0A class To
a3da68fc0d357cdb97dc01dc09e4d8f59c7b5d16
Update scenarios and remove a few to speed up tests (#3720)
packages/ember/config/ember-try.js
packages/ember/config/ember-try.js
'use strict'; const getChannelURL = require('ember-source-channel-url'); const { embroiderSafe } = require('@embroider/test-setup'); module.exports = async function() { return { useYarn: true, scenarios: [ { name: 'ember-lts-3.12', npm: { devDependencies: { 'ember-source': '~3.12.0', }, }, }, { name: 'ember-lts-3.16', npm: { devDependencies: { 'ember-source': '~3.16.0', }, }, }, { name: 'ember-release', npm: { devDependencies: { 'ember-source': await getChannelURL('release'), }, }, }, { name: 'ember-beta', npm: { devDependencies: { 'ember-source': await getChannelURL('beta'), }, }, }, { name: 'ember-canary', allowedToFail: true, npm: { devDependencies: { 'ember-source': await getChannelURL('canary'), }, }, }, embroiderSafe(), // The default `.travis.yml` runs this scenario via `npm test`, // not via `ember try`. It's still included here so that running // `ember try:each` manually or from a customized CI config will run it // along with all the other scenarios. { name: 'ember-default', npm: { devDependencies: {}, }, }, { name: 'ember-default-with-jquery', env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true, }), }, npm: { devDependencies: { '@ember/jquery': '^0.5.1', }, }, }, { name: 'ember-classic', env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'application-template-wrapper': true, 'default-async-observers': false, 'template-only-glimmer-components': false, }), }, npm: { ember: { edition: 'classic', }, }, }, ], }; };
JavaScript
0
@@ -250,166 +250,10 @@ s-3. -12',%0A npm: %7B%0A devDependencies: %7B%0A 'ember-source': '~3.12.0',%0A %7D,%0A %7D,%0A %7D,%0A %7B%0A name: 'ember-lts-3.16 +20 ',%0A @@ -331,10 +331,10 @@ '~3. -16 +20 .0', @@ -723,894 +723,23 @@ -%7B%0A name: 'ember-canary',%0A allowedToFail: true,%0A npm: %7B%0A devDependencies: %7B%0A 'ember-source': await getChannelURL('canary'),%0A %7D,%0A %7D,%0A %7D,%0A embroiderSafe(),%0A // The default %60.travis.yml%60 runs this scenario via %60npm test%60,%0A // not via %60ember try%60. It's still included here so that running%0A // %60ember try:each%60 manually or from a customized CI config will run it%0A // along with all the other scenarios.%0A %7B%0A name: 'ember-default',%0A npm: %7B%0A devDependencies: %7B%7D,%0A %7D,%0A %7D,%0A %7B%0A name: 'ember-default-with-jquery',%0A env: %7B%0A EMBER_OPTIONAL_FEATURES: JSON.stringify(%7B%0A 'jquery-integration': true,%0A %7D),%0A %7D,%0A npm: %7B%0A devDependencies: %7B%0A '@ember/jquery': '%5E0.5.1',%0A %7D,%0A %7D,%0A %7D +embroiderSafe() ,%0A
b930765612687c3d6f9de91b5ff803d93313e5d9
Add option docs
src/edit/options.js
src/edit/options.js
import {defaultSchema} from "../model" import {AssertionError} from "../util/error" import {ParamPrompt} from "../ui/prompt" import {CommandSet, updateCommands} from "./command" class Option { constructor(defaultValue, update, updateOnInit) { this.defaultValue = defaultValue this.update = update this.updateOnInit = updateOnInit !== false } } const options = Object.create(null) // :: (string, any, (pm: ProseMirror, newValue: any, oldValue: any, init: bool), bool) // Define a new option. The `update` handler will be called with the // option's old and new value every time the option is // [changed](#ProseMirror.setOption). When `updateOnInit` is false, it // will not be called on editor init, otherwise it is called with null as the old value, // and a fourth argument of true. export function defineOption(name, defaultValue, update, updateOnInit) { options[name] = new Option(defaultValue, update, updateOnInit) } // :: Schema #path=schema #kind=option // The [schema](#Schema) that the editor's document should use. defineOption("schema", defaultSchema, false) // :: any #path=doc #kind=option // The starting document. Usually a `Node`, but can be in another // format when the `docFormat` option is also specified. defineOption("doc", null, (pm, value) => pm.setDoc(value), false) // :: ?string #path=docFormat #kind=option // The format in which the `doc` option is given. Defaults to `null` // (a raw `Node`). defineOption("docFormat", null) // :: ?union<DOMNode, (DOMNode)> #path=place #kind=option // Determines the placement of the editor in the page. When `null`, // the editor is not placed. When a DOM node is given, the editor is // appended to that node. When a function is given, it is called // with the editor's wrapping DOM node, and is expected to place it // into the document. defineOption("place", null) // :: number #path=historyDepth #kind=option // The amount of history events that are collected before the oldest // events are discarded. Defaults to 100. defineOption("historyDepth", 100) // :: number #path=historyEventDelay #kind=option // The amount of milliseconds that must pass between changes to // start a new history event. Defaults to 500. defineOption("historyEventDelay", 500) // :: CommandSet #path=commands #kind=option // Specifies the set of [commands](#Command) available in the editor // (which in turn determines the base key bindings and items available // in the menus). Defaults to `CommandSet.default`. defineOption("commands", CommandSet.default, updateCommands) // :: ParamPrompt #path=commandParamPrompt #kind=option // A default [parameter prompting](#ui/prompt) class to use when a // command is [executed](#ProseMirror.execCommand) without providing // parameters. defineOption("commandParamPrompt", ParamPrompt) // :: ?string #path=label #kind=option // The label of the editor. When set, the editable DOM node gets an // `aria-label` attribute with this value. defineOption("label", null) export function parseOptions(obj) { let result = Object.create(null) let given = obj ? [obj].concat(obj.use || []) : [] outer: for (let opt in options) { for (let i = 0; i < given.length; i++) { if (opt in given[i]) { result[opt] = given[i][opt] continue outer } } result[opt] = options[opt].defaultValue } return result } export function initOptions(pm) { for (var opt in options) { let desc = options[opt] if (desc.update && desc.updateOnInit) desc.update(pm, pm.options[opt], null, true) } } export function setOption(pm, name, value) { let desc = options[name] if (desc === undefined) throw new AssertionError("Option '" + name + "' is not defined") if (desc.update === false) throw new AssertionError("Option '" + name + "' can not be changed") let old = pm.options[name] pm.options[name] = value if (desc.update) desc.update(pm, value, old, false) }
JavaScript
0.000002
@@ -177,111 +177,472 @@ d%22%0A%0A -class Option %7B%0A constructor(defaultValue, update, updateOnInit) %7B%0A this.defaultValue = defaultValue +// An option encapsulates functionality for an editor instance,%0A// e.g. the amount of history events that the editor should hold%0A// onto or the document's schema.%0Aclass Option %7B%0A constructor(defaultValue, update, updateOnInit) %7B%0A this.defaultValue = defaultValue%0A // A function that will be invoked with the option's old and new%0A // value every time the option is %5Bset%5D(#ProseMirror.setOption).%0A // This function should bootstrap option functionality. %0A
4c9669f95dada19392c7da679476f212ebb11f24
Update help.js
cmd/help.js
cmd/help.js
exports.run = (bot, message, params, config) => { if (!params[0]) { message.channel.sendMessage("check your dms :rocket:").catch(console.error); let modRole = message.guild.roles.find("name", "Staff"); let adminRole = message.guild.roles.find("name", "Owner"); var cmds = ``; cmds += `**Warning this is the dev rep so not all commands are here** \n\n **My Normal Commands are:** \n ${config.client.prefix}membercount \n ${config.client.prefix}serverinfo \n ${config.client.prefix}botservers \n ${config.client.prefix}date \n ${config.client.prefix}sourcecode \n ${config.client.prefix}avatar \n ${config.client.prefix}ping \n ${config.client.prefix}creator \n ${config.client.prefix}help \n ${config.client.prefix}stats \n ${config.client.prefix}myuserinfo`; if (message.member.roles.has(modRole.id) || config.creator.Jimmy.includes(message.author.id)) { cmds += `\n\n **My Staff commands are** \n ${config.client.prefix}embed [what you want to embed] \n ${config.client.prefix}addrole {user} [role] \n ${config.client.prefix}delrole {user} [role] \n ${config.client.prefix}announce [what you want to announce in #announcements] \n ${config.client.prefix}say [what you want to say] \n ${config.client.prefix}kick {user} \n \n more details on how to use these commands coming soon`; } if (message.member.roles.has(adminRole.id) || config.creator.Jimmy.includes(message.author.id)) { cmds += `\n\n **My Owner/Creator Commands are:** \n ${config.client.prefix}setbotavatarurl (only Jimmy) \n ${config.client.prefix}setstatus (only Jimmy) \n ${config.client.prefix}shutdown \n ${config.client.prefix}restart`; } message.author.sendMessage(" ", { embed: { color: 0x00b7c6, title: "Command List", description: cmds, }}).catch(console.error); } else { let command = params[0]; if(bot.commands.has(command)) { command = bot.commands.get(command); message.channel.sendCode("asciidoc", `= ${command.help.name} = \n${command.help.description}\nusage::${command.help.usage}`); } } }; exports.conf = { enabled: true, guildOnly: false, aliases: [], permLevel: 0 }; exports.help = { name : "help", description: "Returns page details from root's awesome bot guide.", usage: "help [command]" };
JavaScript
0.000001
@@ -29,16 +29,23 @@ params, + perms, config)
e344ccb6ec4837462af02f54203de6c5f0710568
convert geojson string to obj
client/shared/placeReference/placeReferenceDirective.js
client/shared/placeReference/placeReferenceDirective.js
angular.module('pteraformer').directive('placeReference', function() { return { restrict: 'E', transclude: 'true', scope: { id: '@', geo: '@' }, template: '<span class="place-ref"> {{geo}} <ng-transclude></ng-transclude></span>', link: function ($scope, element, attrs) { element.bind('click', function () { element.html('<span class="place-ref">You clicked me!</span>'); }); } }; });
JavaScript
0.999999
@@ -212,17 +212,8 @@ ef%22%3E - %7B%7Bgeo%7D%7D %3Cng- @@ -341,24 +341,26 @@ ) %7B%0A +// element.html @@ -411,16 +411,90 @@ pan%3E');%0A + var geoObj = JSON.parse($scope.geo);%0A console.log(geoObj);%0A %7D)
85afff2c4edccaf584cd7b073203c61db898d856
update ColGroup
src/_ColGroup/ColGroup.js
src/_ColGroup/ColGroup.js
/** * @file ColGroup component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; // Statics import TableFragment from '../_statics/TableFragment'; import HorizontalAlign from '../_statics/HorizontalAlign'; import SelectMode from '../_statics/SelectMode'; import SelectAllMode from '../_statics/SelectAllMode'; import SortingType from '../_statics/SortingType'; // Vendors import isEmpty from 'lodash/isEmpty'; import Util from '../_vendors/Util'; import TC from '../_vendors/TableCalculation'; class ColGroup extends Component { static Fragment = TableFragment; static Align = HorizontalAlign; static SelectMode = SelectMode; static SelectAllMode = SelectAllMode; static SortingType = SortingType; constructor(props, ...restArgs) { super(props, ...restArgs); } getColStyle = column => { const {columnKeyField, columnsWidth, useColumnsWidth, defaultColumnWidth} = this.props, result = {}; // width result.width = useColumnsWidth ? (columnsWidth && columnsWidth.get(TC.getColumnKey(column, columnKeyField))) : (column.width || defaultColumnWidth); // min width result.minWidth = column.minWidth ? column.minWidth : result.width; return isEmpty(result) ? null : result; }; render() { const {columns, ignoreColumnSpan} = this.props; return columns ? <colgroup> { columns.map(({column, span}, index) => column ? <col key={index} style={this.getColStyle(column)} span={ignoreColumnSpan ? null : (span && span > 1 ? span : null)}/> : null ) } </colgroup> : null; } } ColGroup.propTypes = { /** * Children passed into table header. */ columns: PropTypes.arrayOf(PropTypes.shape({ /** * unique keyof column. */ key: PropTypes.string, /** * fixed position of column ( 'left' / 'right' ) */ fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * width of column */ width: PropTypes.number, /** * minimum width of column */ minWidth: PropTypes.number, /** * align of current column */ align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The class name of header. */ headClassName: PropTypes.string, /** * Override the styles of header. */ headStyle: PropTypes.object, /** * align of table header cell */ headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table head. * (1) callback: * function (tableData, colIndex) { * return colIndex; * } * * (2) others: * render whatever you pass */ headRenderer: PropTypes.any, /** * column span of table header */ headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * The class name of td. */ bodyClassName: PropTypes.string, /** * Override the styles of td. */ bodyStyle: PropTypes.object, /** * align of table body cell */ bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table body. * (1) callback: * function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) { * return rowData.id; * } * * (2) others: * render whatever you pass */ bodyRenderer: PropTypes.any, /** * column span of table body */ bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * The class name of footer. */ footClassName: PropTypes.string, /** * Override the styles of footer. */ footStyle: PropTypes.object, /** * align of table footer cell */ footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table foot. * (1) callback: * function (tableData, colIndex) { * return colIndex; * } * * (2) others: * render whatever you pass */ footRenderer: PropTypes.any, /** * column span of table foot */ footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * If true,this column can be sorted. */ sortable: PropTypes.bool, /** * Sorting property. */ sortingProp: PropTypes.string, defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)) })).isRequired, columnKeyField: PropTypes.string, columnsWidth: PropTypes.object, useColumnsWidth: PropTypes.bool, /** * column resizable */ isColumnResizable: PropTypes.bool, defaultColumnWidth: PropTypes.number, minColumnWidth: PropTypes.number, ignoreColumnSpan: PropTypes.bool }; ColGroup.defaultProps = { columnKeyField: 'key', useColumnsWidth: false, /** * column resizable */ isColumnResizable: false, defaultColumnWidth: 100, minColumnWidth: 64, ignoreColumnSpan: false }; export default ColGroup;
JavaScript
0
@@ -991,16 +991,32 @@ umnWidth +, minColumnWidth %7D = this @@ -1374,24 +1374,43 @@ %0A + (minColumnWidth %7C%7C result.widt @@ -1410,16 +1410,17 @@ lt.width +) ;%0A%0A
c4b7a32751474e450b45bf72214ccd2bc6673ae6
Add stability annotation to ol.geom.SimpleGeometry
src/ol/geom/simplegeometry.js
src/ol/geom/simplegeometry.js
goog.provide('ol.geom.SimpleGeometry'); goog.require('goog.asserts'); goog.require('goog.functions'); goog.require('goog.object'); goog.require('ol.extent'); goog.require('ol.geom.Geometry'); goog.require('ol.geom.flat'); /** * @constructor * @extends {ol.geom.Geometry} */ ol.geom.SimpleGeometry = function() { goog.base(this); /** * @protected * @type {ol.geom.GeometryLayout} */ this.layout = ol.geom.GeometryLayout.XY; /** * @protected * @type {number} */ this.stride = 2; /** * @protected * @type {Array.<number>} */ this.flatCoordinates = null; }; goog.inherits(ol.geom.SimpleGeometry, ol.geom.Geometry); /** * @param {number} stride Stride. * @private * @return {ol.geom.GeometryLayout} layout Layout. */ ol.geom.SimpleGeometry.getLayoutForStride_ = function(stride) { if (stride == 2) { return ol.geom.GeometryLayout.XY; } else if (stride == 3) { return ol.geom.GeometryLayout.XYZ; } else if (stride == 4) { return ol.geom.GeometryLayout.XYZM; } else { throw new Error('unsupported stride: ' + stride); } }; /** * @param {ol.geom.GeometryLayout} layout Layout. * @private * @return {number} Stride. */ ol.geom.SimpleGeometry.getStrideForLayout_ = function(layout) { if (layout == ol.geom.GeometryLayout.XY) { return 2; } else if (layout == ol.geom.GeometryLayout.XYZ) { return 3; } else if (layout == ol.geom.GeometryLayout.XYM) { return 3; } else if (layout == ol.geom.GeometryLayout.XYZM) { return 4; } else { throw new Error('unsupported layout: ' + layout); } }; /** * @inheritDoc */ ol.geom.SimpleGeometry.prototype.containsXY = goog.functions.FALSE; /** * @inheritDoc */ ol.geom.SimpleGeometry.prototype.getExtent = function(opt_extent) { if (this.extentRevision != this.getRevision()) { this.extent = ol.extent.createOrUpdateFromFlatCoordinates( this.flatCoordinates, this.stride, this.extent); this.extentRevision = this.getRevision(); } goog.asserts.assert(goog.isDef(this.extent)); return ol.extent.returnOrUpdate(this.extent, opt_extent); }; /** * @return {Array.<number>} Flat coordinates. */ ol.geom.SimpleGeometry.prototype.getFlatCoordinates = function() { return this.flatCoordinates; }; /** * @return {ol.geom.GeometryLayout} Layout. */ ol.geom.SimpleGeometry.prototype.getLayout = function() { return this.layout; }; /** * @inheritDoc */ ol.geom.SimpleGeometry.prototype.getSimplifiedGeometry = function(squaredTolerance) { if (this.simplifiedGeometryRevision != this.getRevision()) { goog.object.clear(this.simplifiedGeometryCache); this.simplifiedGeometryMaxMinSquaredTolerance = 0; this.simplifiedGeometryRevision = this.getRevision(); } // If squaredTolerance is negative or if we know that simplification will not // have any effect then just return this. if (squaredTolerance < 0 || (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 && squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance)) { return this; } var key = squaredTolerance.toString(); if (this.simplifiedGeometryCache.hasOwnProperty(key)) { return this.simplifiedGeometryCache[key]; } else { var simplifiedGeometry = this.getSimplifiedGeometryInternal(squaredTolerance); var simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates(); if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) { this.simplifiedGeometryCache[key] = simplifiedGeometry; return simplifiedGeometry; } else { // Simplification did not actually remove any coordinates. We now know // that any calls to getSimplifiedGeometry with a squaredTolerance less // than or equal to the current squaredTolerance will also not have any // effect. This allows us to short circuit simplification (saving CPU // cycles) and prevents the cache of simplified geometries from filling // up with useless identical copies of this geometry (saving memory). this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance; return this; } } }; /** * @param {number} squaredTolerance Squared tolerance. * @return {ol.geom.SimpleGeometry} Simplified geometry. * @protected */ ol.geom.SimpleGeometry.prototype.getSimplifiedGeometryInternal = function(squaredTolerance) { return this; }; /** * @return {number} Stride. */ ol.geom.SimpleGeometry.prototype.getStride = function() { return this.stride; }; /** * @param {ol.geom.GeometryLayout} layout Layout. * @param {Array.<number>} flatCoordinates Flat coordinates. * @protected */ ol.geom.SimpleGeometry.prototype.setFlatCoordinatesInternal = function(layout, flatCoordinates) { this.stride = ol.geom.SimpleGeometry.getStrideForLayout_(layout); this.layout = layout; this.flatCoordinates = flatCoordinates; }; /** * @param {ol.geom.GeometryLayout|undefined} layout Layout. * @param {Array} coordinates Coordinates. * @param {number} nesting Nesting. * @protected */ ol.geom.SimpleGeometry.prototype.setLayout = function(layout, coordinates, nesting) { /** @type {number} */ var stride; if (goog.isDef(layout)) { stride = ol.geom.SimpleGeometry.getStrideForLayout_(layout); } else { var i; for (i = 0; i < nesting; ++i) { if (coordinates.length === 0) { this.layout = ol.geom.GeometryLayout.XY; this.stride = 2; return; } else { coordinates = /** @type {Array} */ (coordinates[0]); } } stride = (/** @type {Array} */ (coordinates)).length; layout = ol.geom.SimpleGeometry.getLayoutForStride_(stride); } this.layout = layout; this.stride = stride; }; /** * @inheritDoc */ ol.geom.SimpleGeometry.prototype.transform = function(transformFn) { if (!goog.isNull(this.flatCoordinates)) { transformFn(this.flatCoordinates, this.flatCoordinates, this.stride); this.dispatchChangeEvent(); } }; /** * @param {ol.geom.SimpleGeometry} simpleGeometry Simple geometry. * @param {goog.vec.Mat4.Number} transform Transform. * @param {Array.<number>=} opt_dest Destination. * @return {Array.<number>} Transformed flat coordinates. */ ol.geom.transformSimpleGeometry2D = function(simpleGeometry, transform, opt_dest) { var flatCoordinates = simpleGeometry.getFlatCoordinates(); if (goog.isNull(flatCoordinates)) { return null; } else { var stride = simpleGeometry.getStride(); return ol.geom.flat.transform2D( flatCoordinates, stride, transform, opt_dest); } };
JavaScript
0.000427
@@ -270,16 +270,48 @@ ometry%7D%0A + * @todo stability experimental%0A */%0Aol.g @@ -2340,32 +2340,64 @@ Layout%7D Layout.%0A + * @todo stability experimental%0A */%0Aol.geom.Simp
5b127aacd86ef3ea1d330629025b0fcb3c9f188e
add appendPlaceContent method to append content to a place
src/plugin/modules/places.js
src/plugin/modules/places.js
/*global define*/ /*jslint white:true,browser:true*/ define([ 'kb/common/html' ], function (html) { 'use strict'; function factory(config) { var root = config.root, places = {}, div = html.tag('div'); // IMPLEMENTATION function addPlace(name) { if (places[name]) { throw new Error('Place already defined: ' + name); } var id = html.genId(); places[name] = { id: id }; return id; } function addPlaceHolder(name) { return div({id: addPlace(name)}); } function getPlace(name) { var place = places[name]; if (place === undefined) { throw new Error('Place not defined: ' + name); } return place; } function getPlaceNode(name) { var place = getPlace(name); if (!place.node) { place.node = document.getElementById(place.id); } if (!place.node) { throw new Error('Place does not exist in the DOM: ' + place + ' : ' + place.id); } return place.node; } function setPlaceContent(name, content) { var place = getPlaceNode(name); place.innerHTML = content; } return { add: addPlace, get: getPlace, getNode: getPlaceNode, setContent: setPlaceContent, addPlaceHolder: addPlaceHolder }; } return { make: function (config) { return factory(config); } }; });
JavaScript
0.000001
@@ -1378,32 +1378,291 @@ tent;%0A %7D%0A + function appendPlaceContent(name, content) %7B%0A var place = getPlaceNode(name),%0A temp = document.createElement('div');%0A %0A temp.innerHTML = content;%0A place.appendChild(temp.firstChild)%0A %7D%0A %0A @@ -1843,16 +1843,63 @@ ceHolder +,%0A appendContent: appendPlaceContent %0A
a2ff3f38b75733dba47e2d6d54e710344c72a218
update TableRow
src/_TableRow/TableRow.js
src/_TableRow/TableRow.js
/** * @file TableRow component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; export default class TableRow extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); this.contentRenderer = ::this.contentRenderer; this.rowTouchTapHandler = ::this.rowTouchTapHandler; this.cellTouchTapHandler = ::this.cellTouchTapHandler; } stringContentRenderer(data, template) { if (!data) { return template; } if (/\$\{.+\}/.test(template)) { // 配置的 renderer 中包含 ${...},用数据替换 let result = template; for (let key in data) { result = result.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), data[key]); } return result; } else { // 直接显示字段 return data[template]; } } contentRenderer(renderer, colIndex) { const {rowIndex, data} = this.props; switch (typeof renderer) { case 'string': return this.stringContentRenderer(data, renderer); case 'function': return renderer(data, rowIndex, colIndex); default: return renderer; } } rowTouchTapHandler(e) { const {data, rowIndex, disabled, onRowTouchTap} = this.props; !disabled && onRowTouchTap && onRowTouchTap(data, rowIndex, e); } cellTouchTapHandler(e, colIndex) { const {data, rowIndex, disabled, onCellTouchTap} = this.props; !disabled && onCellTouchTap && onCellTouchTap(data, rowIndex, colIndex, e); } render() { const {data, columns, isChecked, disabled} = this.props, trClassName = (isChecked ? ' activated' : '') + (data.rowClassName ? ' ' + data.rowClassName : ''); return ( <tr className={'table-row' + trClassName} style={data.rowStyle} disabled={disabled} onTouchTap={this.rowTouchTapHandler}> { columns.map((col, colIndex) => <td key={colIndex} className={col.cellClassName} style={col.cellStyle} onTouchTap={e => { this.cellTouchTapHandler(e, colIndex); }}> {this.contentRenderer(col.renderer, colIndex)} </td> ) } </tr> ); } }; TableRow.propTypes = { rowIndex: PropTypes.number, columns: PropTypes.array, data: PropTypes.object, isChecked: PropTypes.bool, disabled: PropTypes.bool, onRowTouchTap: PropTypes.func, onCellTouchTap: PropTypes.func }; TableRow.defaultProps = { rowIndex: 0, columns: [], data: {}, isChecked: false, disabled: false };
JavaScript
0
@@ -205,24 +205,454 @@ omponent %7B%0A%0A + static propTypes = %7B%0A%0A rowIndex: PropTypes.number,%0A columns: PropTypes.array,%0A data: PropTypes.object,%0A isChecked: PropTypes.bool,%0A disabled: PropTypes.bool,%0A%0A onRowTouchTap: PropTypes.func,%0A onCellTouchTap: PropTypes.func%0A%0A %7D;%0A static defaultProps = %7B%0A rowIndex: 0,%0A columns: %5B%5D,%0A data: %7B%7D,%0A isChecked: false,%0A disabled: false%0A %7D;%0A%0A construc @@ -3075,375 +3075,4 @@ %7D%0A%7D; -%0A%0ATableRow.propTypes = %7B%0A%0A rowIndex: PropTypes.number,%0A columns: PropTypes.array,%0A data: PropTypes.object,%0A isChecked: PropTypes.bool,%0A disabled: PropTypes.bool,%0A%0A onRowTouchTap: PropTypes.func,%0A onCellTouchTap: PropTypes.func%0A%0A%7D;%0A%0ATableRow.defaultProps = %7B%0A rowIndex: 0,%0A columns: %5B%5D,%0A data: %7B%7D,%0A isChecked: false,%0A disabled: false%0A%7D;
45634342da8f58dda572fc8ecd37329827f76e61
Add Link Route component in the Home for example purpose.
src/ui/components/Home/Home.view.js
src/ui/components/Home/Home.view.js
import React from 'react'; function HomeView (props) { return ( <div> <p>Hello {props.user.user || 'empty'}</p> </div> ); } export default HomeView;
JavaScript
0
@@ -19,16 +19,52 @@ 'react'; +%0Aimport %7B Link %7D from 'react-router' %0A%0Afuncti @@ -133,16 +133,33 @@ p%3EHello +%3CLink to=%22Login%22%3E %7Bprops.u @@ -180,16 +180,23 @@ mpty'%7D%3C/ +Link%3E%3C/ p%3E%0A
f27ad3c93fa334e1cbf3f397dd81d98bd8649d39
fix #1187 html char codes for navbar icon
packages/mjml-navbar/src/Navbar.js
packages/mjml-navbar/src/Navbar.js
import { BodyComponent } from 'mjml-core' import crypto from 'crypto' import conditionalTag, { msoConditionalTag, } from 'mjml-core/lib/helpers/conditionalTag' export default class MjNavbar extends BodyComponent { static allowedAttributes = { align: 'enum(left,center,right)', 'base-url': 'string', hamburger: 'string', 'ico-align': 'enum(left,center,right)', 'ico-open': 'string', 'ico-close': 'string', 'ico-color': 'color', 'ico-font-size': 'unit(px,%)', 'ico-font-family': 'string', 'ico-text-transform': 'string', 'ico-padding': 'unit(px,%){1,4}', 'ico-padding-left': 'unit(px,%)', 'ico-padding-top': 'unit(px,%)', 'ico-padding-right': 'unit(px,%)', 'ico-padding-bottom': 'unit(px,%)', 'ico-text-decoration': 'string', 'ico-line-height': 'unit(px,%)', } static defaultAttributes = { align: 'center', 'base-url': null, hamburger: null, 'ico-align': 'center', 'ico-open': '9776', 'ico-close': '8855', 'ico-color': '#000000', 'ico-font-size': '30px', 'ico-font-family': 'Ubuntu, Helvetica, Arial, sans-serif', 'ico-text-transform': 'uppercase', 'ico-padding': '10px', 'ico-text-decoration': 'none', 'ico-line-height': '30px', } headStyle = breakpoint => ` noinput.mj-menu-checkbox { display:block!important; max-height:none!important; visibility:visible!important; } @media only screen and (max-width:${breakpoint}) { .mj-menu-checkbox[type="checkbox"] ~ .mj-inline-links { display:none!important; } .mj-menu-checkbox[type="checkbox"]:checked ~ .mj-inline-links, .mj-menu-checkbox[type="checkbox"] ~ .mj-menu-trigger { display:block!important; max-width:none!important; max-height:none!important; font-size:inherit!important; } .mj-menu-checkbox[type="checkbox"] ~ .mj-inline-links > a { display:block!important; } .mj-menu-checkbox[type="checkbox"]:checked ~ .mj-menu-trigger .mj-menu-icon-close { display:block!important; } .mj-menu-checkbox[type="checkbox"]:checked ~ .mj-menu-trigger .mj-menu-icon-open { display:none!important; } } ` getStyles() { return { div: { align: this.getAttribute('align'), width: '100%', }, label: { display: 'block', cursor: 'pointer', 'mso-hide': 'all', '-moz-user-select': 'none', 'user-select': 'none', align: this.getAttribute('ico-align'), color: this.getAttribute('ico-color'), 'font-size': this.getAttribute('ico-font-size'), 'font-family': this.getAttribute('ico-font-family'), 'text-transform': this.getAttribute('ico-text-transform'), 'text-decoration': this.getAttribute('ico-text-decoration'), 'line-height': this.getAttribute('ico-line-height'), 'padding-top': this.getAttribute('ico-padding-top'), 'padding-right': this.getAttribute('ico-padding-right'), 'padding-bottom': this.getAttribute('ico-padding-bottom'), 'padding-left': this.getAttribute('ico-padding-left'), padding: this.getAttribute('ico-padding'), }, trigger: { display: 'none', 'max-height': '0px', 'max-width': '0px', 'font-size': '0px', overflow: 'hidden', }, icoOpen: { 'mso-hide': 'all', }, icoClose: { display: 'none', 'mso-hide': 'all', }, } } renderHamburger() { const key = crypto.randomBytes(8).toString('hex') return ` ${msoConditionalTag( ` <input type="checkbox" id="${key}" class="mj-menu-checkbox" style="display:none !important; max-height:0; visibility:hidden;" /> `, true, )} <div ${this.htmlAttributes({ class: 'mj-menu-trigger', style: 'trigger', })} > <label ${this.htmlAttributes({ for: key, class: 'mj-menu-label', style: 'label', })} > <span ${this.htmlAttributes({ class: 'mj-menu-icon-open', style: 'icoOpen', })} > ${String.fromCharCode(this.getAttribute('ico-open'))} </span> <span ${this.htmlAttributes({ class: 'mj-menu-icon-close', style: 'icoClose', })} > ${String.fromCharCode(this.getAttribute('ico-close'))} </span> </label> </div> ` } render() { return ` ${this.getAttribute('hamburger') === 'hamburger' ? this.renderHamburger() : ''} <div ${this.htmlAttributes({ class: 'mj-inline-links', style: this.htmlAttributes('div'), })} > ${conditionalTag(` <table role="presentation" border="0" cellpadding="0" cellspacing="0" align="${this.getAttribute( 'align', )}"> <tr> `)} ${this.renderChildren(this.props.children, { attributes: { navbarBaseUrl: this.getAttribute('base-url'), }, })} ${conditionalTag(` </tr></table> `)} </div> ` } }
JavaScript
0
@@ -968,16 +968,18 @@ open': ' +&# 9776',%0A @@ -995,16 +995,18 @@ lose': ' +&# 8855',%0A @@ -4211,36 +4211,16 @@ $%7B -String.fromCharCode( this.get @@ -4240,17 +4240,16 @@ o-open') -) %7D%0A @@ -4434,28 +4434,8 @@ $%7B -String.fromCharCode( this @@ -4460,17 +4460,16 @@ -close') -) %7D%0A
83c97079c6f90b058ce4569e52a83f612c68b078
Refactor sign_up component.
src/open/components/signup.js
src/open/components/signup.js
/* @flow */ const React = require('react') const { connect } = require('react-redux') const { reduxForm } = require('redux-form') const MemberFields = require('../../shared/components/member_fields.js') const { validate, sign_up_required, read_only_sign_up } = require('../../shared/form_fields/member.js') const { identity } = require('ramda') const { next_page, previous_page } = require('../redux/modules/page.js') const { sign_up } = require('../redux/modules/signup.js') const buttons = (props) => <div> <button>Next</button> <button onClick={props.previous_page} type='button'>Back</button> </div> const AddMember = reduxForm( { form: 'sign_up' , validate: validate(sign_up_required) , fields: [] } )(MemberFields) const NewMember = (props) => { return ( <div> <div> <h1>Please fill in your details</h1> <AddMember fields={page_fields[props.page]} Buttons={buttons} button_props={ { previous_page: props.previous_page } } onSubmit={props.page.page === 5 ? props.sign_up : props.next_page} required={sign_up_required} mode='edit' memberSignup read_only={props.page === 5 ? read_only_sign_up : []} /> </div> </div> ) } const page_fields = [ [ 'title', 'first_name', 'last_name', 'initials' ], [ 'address1', 'address2', 'address3', 'address4', 'postcode' ], [ 'home_phone', 'mobile_phone' ], [ 'primary_email', 'password' ], [ 'membership_type' ], [ 'title', 'first_name', 'last_name', 'initials', 'address1', 'address2', 'address3', 'address4', 'postcode', 'home_phone', 'mobile_phone', 'primary_email', 'membership_type' ] ] export default connect(identity, { sign_up, next_page, previous_page })(NewMember)
JavaScript
0
@@ -122,16 +122,54 @@ x-form') +%0Aconst %7B identity %7D = require('ramda') %0A%0Aconst @@ -344,47 +344,8 @@ ')%0A%0A -const %7B identity %7D = require('ramda')%0A%0A cons @@ -478,23 +478,22 @@ %0A%0Aconst -buttons +SignUp = (prop @@ -501,325 +501,159 @@ ) =%3E + %7B %0A -%3Cdiv%3E%0A %3Cbutton%3ENext%3C/button%3E%0A %3Cbutton onClick=%7Bprops.previous_page%7D type='button'%3EBack%3C/button%3E%0A %3C/div%3E%0A%0Aconst AddMember = reduxForm(%0A %7B form: 'sign_up'%0A , validate: validate(sign_up_required)%0A , fields: %5B%5D%0A %7D%0A)(MemberFields)%0A%0Aconst NewMember = (props) =%3E %7B%0A return (%0A %3Cdiv%3E%0A %3Cdiv%3E%0A %3Ch1%3E +return (%0A %3Cdiv%3E%0A %3Cdiv%3E%0A %3Ch2%3E%7Bprops.page === 5 ? 'If your details are correct click %5C'Submit%5C' otherwise go back to change them' : ' Plea @@ -679,12 +679,14 @@ ails +'%7D %3C/h -1 +2 %3E%0A @@ -696,17 +696,18 @@ %3C -AddMember +SignUpForm %0A @@ -835,16 +835,34 @@ ous_page +, page: props.page %7D %7D%0A @@ -888,21 +888,16 @@ ops.page -.page === 5 ? @@ -1129,241 +1129,416 @@ nst -page_fields = %5B%0A %5B 'title', 'first_name', 'last_name', 'initials' %5D,%0A %5B 'address1', 'address2', 'address3', 'address4', 'postcode' %5D,%0A %5B 'home_phone', 'mobile_phone' %5D,%0A %5B 'primary_email', 'password' %5D,%0A %5B 'membership_type' %5D,%0A +SignUpForm = reduxForm(%0A %7B form: 'sign_up'%0A , validate: validate(sign_up_required)%0A , fields: %5B%5D%0A %7D%0A)(MemberFields)%0A%0Aconst buttons = (props) =%3E%0A %3Cdiv%3E%0A %7Bprops.page !== 0 && back_button(props.previous_page)%7D%0A %3Cbutton%3E%7Bprops.page === 5 ? 'Submit' : '%3E'%7D%3C/button%3E%0A %3C/div%3E%0A%0Aconst back_button = (previous_page) =%3E%0A %3Cbutton onClick=%7Bprevious_page%7D type='button'%3E%7B'%3C'%7D%3C/button%3E%0A%0Aconst page_fields =%0A %5B %5B ' @@ -1582,17 +1582,24 @@ nitials' -, + %5D%0A , %5B 'addres @@ -1649,17 +1649,24 @@ ostcode' -, + %5D%0A , %5B 'home_p @@ -1686,17 +1686,24 @@ e_phone' -, + %5D%0A , %5B 'primar @@ -1717,28 +1717,107 @@ ', ' -membership_type' %5D%0A%5D +verify_email', 'password', 'verify_password' %5D%0A , %5B 'membership_type' %5D%0A , read_only_sign_up%0A %5D%0A %0Aexp @@ -1889,15 +1889,12 @@ %7D)( -NewMember +SignUp )%0A
72c85cc2a405af158d7c5097a0d91520f6ef7d44
fix nested scrollbar switching
src/events/touch.js
src/events/touch.js
/** * @module * @prototype {Function} __touchHandler */ import { SmoothScrollbar } from '../smooth-scrollbar'; import { GLOBAL_ENV } from '../shared/'; const MIN_VELOCITY = 100; let activeScrollbar = null; /** * @method * @internal * Touch event handlers builder */ function __touchHandler() { const { targets, movementLocked, __touchRecord, } = this; const { container, } = targets; this.__addEvent(container, 'touchstart', (evt) => { if (this.__isDrag || this.__eventFromChildScrollbar(evt)) return; const { __timerID, movement } = this; // stop scrolling but keep movement for overscrolling cancelAnimationFrame(__timerID.scrollTo); if (!this.__willOverscroll('x')) movement.x = 0; if (!this.__willOverscroll('y')) movement.y = 0; // start records __touchRecord.track(evt); this.__autoLockMovement(); activeScrollbar = this; }); this.__addEvent(container, 'touchmove', (evt) => { if (!activeScrollbar) activeScrollbar = this; if (activeScrollbar !== this || this.__isDrag) return; __touchRecord.update(evt); let { x, y } = __touchRecord.getDelta(); if (this.__shouldPropagateMovement(x, y)) { return this.__updateThrottle(); } const { movement, MAX_OVERSCROLL, options } = this; if (movement.x && this.__willOverscroll('x', x)) { let factor = 2; if (options.overscrollEffect === 'bounce') { factor += Math.abs(10 * movement.x / MAX_OVERSCROLL); } if (Math.abs(movement.x) >= MAX_OVERSCROLL) { x = 0; } else { x /= factor; } } if (movement.y && this.__willOverscroll('y', y)) { let factor = 2; if (options.overscrollEffect === 'bounce') { factor += Math.abs(10 * movement.y / MAX_OVERSCROLL); } if (Math.abs(movement.y) >= MAX_OVERSCROLL) { y = 0; } else { y /= factor; } } this.__autoLockMovement(); evt.preventDefault(); this.__addMovement(x, y); }); this.__addEvent(container, 'touchcancel touchend', (evt) => { if (this.__isDrag || this.__eventFromChildScrollbar(evt)) return; const { speed } = this.options; let { x, y } = __touchRecord.getVelocity(); x = movementLocked.x ? 0 : Math.min(x * GLOBAL_ENV.EASING_MULTIPLIER, 1000); y = movementLocked.y ? 0 : Math.min(y * GLOBAL_ENV.EASING_MULTIPLIER, 1000); this.__addMovement( Math.abs(x) > MIN_VELOCITY ? (x * speed) : 0, Math.abs(y) > MIN_VELOCITY ? (y * speed) : 0 ); this.__unlockMovement(); __touchRecord.release(evt); activeScrollbar = null; }); }; Object.defineProperty(SmoothScrollbar.prototype, '__touchHandler', { value: __touchHandler, writable: true, configurable: true, });
JavaScript
0.000052
@@ -523,47 +523,8 @@ Drag - %7C%7C this.__eventFromChildScrollbar(evt) ) re @@ -901,41 +901,8 @@ t(); -%0A%0A activeScrollbar = this; %0A @@ -978,62 +978,62 @@ if ( -!activeScrollbar) activeScrollbar = this;%0A if ( +this.__isDrag) return;%0A if (activeScrollbar && acti @@ -1056,25 +1056,8 @@ this - %7C%7C this.__isDrag ) re @@ -2189,16 +2189,48 @@ (x, y);%0A + activeScrollbar = this;%0A %7D);%0A @@ -2325,47 +2325,8 @@ Drag - %7C%7C this.__eventFromChildScrollbar(evt) ) re
b87637fee116e6704413f39b529b030c37066701
Add has() utility
src/utilities/functional/get_set.js
src/utilities/functional/get_set.js
'use strict'; const { assignArray } = require('./reduce'); const { result } = require('./result'); // Similar to Lodash get(), but do not mutate, and faster const get = function (obj, keys) { if (keys.length === 0) { return obj; } const [childKey, ...keysA] = keys; const child = obj[childKey]; return get(child, keysA); }; // Similar to Lodash set(), but do not mutate, and faster const set = function (objArr, keys, val) { if (keys.length === 0) { return result(val, objArr, keys); } if (typeof keys[0] === 'number') { return setArray(objArr, keys, val); } return setObject(objArr, keys, val); }; const setObject = function (obj = {}, keys, val) { const { child, childKey } = setVal({ objArr: obj, keys, val }); return { ...obj, [childKey]: child }; }; const setArray = function (arr = [], keys, val) { const { child, childKey } = setVal({ objArr: arr, keys, val }); return [ ...arr.slice(0, childKey), child, ...arr.slice(childKey + 1), ]; }; const setVal = function ({ objArr, keys, val }) { const [childKey, ...keysA] = keys; const child = objArr[childKey]; const childA = set(child, keysA, val); return { child: childA, childKey }; }; // Apply several set() at once, using an array of `paths` const setAll = function (obj, paths, val) { return paths.reduce( (objA, inlineFuncPath) => set(objA, inlineFuncPath, val), obj, ); }; // Retrieves all recursive values (i.e. leaves) of an object, // as a single array of [value, key] elements const getAll = function (value, key = []) { if (value && value.constructor === Object) { return Object.entries(value) .map(([childKey, child]) => getAll(child, [...key, childKey])) .reduce(assignArray, []); } if (Array.isArray(value)) { return value .map((child, childKey) => getAll(child, [...key, childKey])) .reduce(assignArray, []); } return [[value, key]]; }; module.exports = { get, set, getAll, setAll, };
JavaScript
0.000022
@@ -1926,16 +1926,180 @@ %5D%5D;%0A%7D;%0A%0A +// Similar to Lodash has(), but faster%0Aconst has = function (obj, keys) %7B%0A try %7B%0A get(obj, keys);%0A %7D catch (error) %7B%0A return false;%0A %7D%0A%0A return true;%0A%7D;%0A%0A module.e @@ -2143,11 +2143,18 @@ setAll,%0A + has,%0A %7D;%0A
484e78f3928d3d32d5a70394f2e59d496dc3ee14
Send project id on GET request for games
public/javascripts/app/views/projectManager.js
public/javascripts/app/views/projectManager.js
define([ 'Backbone', //Model 'app/models/project', //Collection 'app/collections/projects', //View 'app/views/taskController', 'app/views/projectsController', 'app/views/filterController', 'app/views/gameController', //Templates 'text!templates/project-page/gamePageTemplate.html', 'text!templates/project-page/errorTemplate.html' ], function( Backbone, //Model Project, //Collection Projects, //Views taskController, projectsController, filterController, gameController, //Templates gamePageTemplate, errorTemplate ){ var ProjectManager = Backbone.View.extend({ template: _.template(gamePageTemplate), errorTemplate: _.template(errorTemplate), model: new Project(), initialize: function(){ this.model.clear({silent: true}).off(); this.model.bind('change:error', this.error, this); this.model.bind('change:name', this.render, this); this.model.fetch({data: {id: this.options.projectId}}); this.projectsList = new projectsController({ collection: new Projects(), router: this.options.router }); this.games = new gameController({ projectId: this.options.projectId }); this.taskList = new taskController({ projectId: this.options.projectId }); this.filter = new filterController({ collection: this.taskList.collection }); }, error: function(){ var message = this.model.get('error'); this.$el.html(this.errorTemplate({message: message})); }, render: function(){ this.$el.html(this.template({project: {name: this.model.get('name')}})); this.taskList.setElement('.js-taskList'); this.taskList.collection.fetch(); if(!$('.projects-list li')[0]){ this.projectsList.setElement('.projects-list').start(); } this.filter.setElement('.fn-filter-task'); this.games.setElement('.js-game-list'); } }); return ProjectManager; });
JavaScript
0
@@ -1725,34 +1725,211 @@ his. -taskList.collection.fetch( +filter.setElement('.fn-filter-task');%0A this.games.setElement('.js-game-list');%0A%0A this.taskList.collection.fetch();%0A this.games.collection.fetch(%7Bdata: %7Bproject_id: this.options.projectId%7D%7D );%0A%0A @@ -2043,103 +2043,8 @@ %7D%0A%0A - this.filter.setElement('.fn-filter-task');%0A this.games.setElement('.js-game-list');%0A
8daab4b50747087d779ba89148b3b443aa50343f
Update moving.js
javascripts/moving.js
javascripts/moving.js
/*! * moving.js * * Copyright © 2016 Jorge M. Peláez | MIT license * http://j-pel.github.io/adjustjs * */ (function(exports) { 'use strict'; /* properties */ var storeChanges = function(changes){return(0)}; var ongoingTouches = new Array(); var moving = new Object(); var touchMoving = false; /* client API */ /*! * init(store) * Starts the handling of the proposed feature * A default id is assigned to elements with no id given. * * @param {store} callback to receive the elements' changes. * @api public */ var init = exports.init = function(store) { storeChanges = store; var elementList = document.getElementsByClassName('movable'); for (var i = 0; i < elementList.length; i++) { var ele = elementList[i]; ele.addEventListener('mousedown', handleMouseDown, false); ele.style.cursor = 'move'; if (!ele.id) { ele.id = "nn_m_"+i; } } document.addEventListener('touchstart', handleTouchStart, false); document.addEventListener("touchmove", handleTouchMove, true); document.addEventListener("touchleave", handleTouchEnd, true); document.addEventListener("touchend", handleTouchEnd, true); return 0; } /*! * stop() * Stops the handling of the proposed feature. * * @api public */ var stop = exports.stop = function() { var elementList = document.getElementsByClassName('movable'); for (var i = 0; i < elementList.length; i++) { var ele = elementList[i]; ele.removeEventListener('mousedown', handleMouseDown, false); ele.style.cursor = 'auto'; } document.removeEventListener('touchstart', handleTouchStart, false); document.removeEventListener("touchmove", handleTouchMove, true); document.removeEventListener("touchleave", handleTouchEnd, true); document.removeEventListener("touchend", handleTouchEnd, true); return 0; } /* private helpers */ function log(msg) { var p = document.getElementById('status'); p.innerHTML = msg + "\n" + p.innerHTML; } var handleMouseDown = function (event) { event = event || window.event; moving=this; moving.started = true; //log("Start moving " + this.innerHTML); document.addEventListener("mousemove", handleMouseMove, true); document.addEventListener("mouseup", handleMouseUp, true); event.preventDefault(); if (!window.scrollX) { moving.mouseX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; moving.mouseY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop; } else { moving.mouseX = event.clientX + window.scrollX; moving.mouseY = event.clientY + window.scrollY; } moving.startX = moving.offsetLeft; moving.startY = moving.offsetTop; } var handleMouseMove = function (event) { if (!moving.started) return; event = event || window.event; var x, y; if (!window.scrollX) { x = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; y = event.clientY + document.documentElement.scrollTop + document.body.scrollTop; } else { x = event.clientX + window.scrollX; y = event.clientY + window.scrollY; } x = moving.startX + x - moving.mouseX; y = moving.startY + y - moving.mouseY; //log("Moving x = " + x + ", y = " + y); moving.style.left=(x < 0)? '0px' : x+'px'; moving.style.top=(y < 0)? '0px' : y+'px'; if (moving.firstChild.classList.contains("top-fixed")) { var evt = new CustomEvent("scroll",{detail: {},bubbles: true,cancelable: true}); moving.dispatchEvent(evt); } } var handleMouseUp = function (event) { //log ("Stop moving " + moving.innerText); moving.started = false; var changes = []; if (parseInt(moving.startX) != parseInt(moving.style.left)) { changes.push(moving.id+".style.left="+moving.style.left); } if (parseInt(moving.startY) != parseInt(moving.style.top)) { changes.push(moving.id+".style.top="+moving.style.top); } storeChanges(changes); document.removeEventListener("mousemove", handleMouseMove, true); document.removeEventListener("mouseup", handleMouseUp, true); } var handleTouchStart = function (event) { var touches = event.changedTouches; for (var i=0; i < touches.length; i++) { if (touches[i].target.classList.contains('movable')) { touchMoving = true; ongoingTouches.push(copyTouch(touches[i])); //log("start touch "+i+ " on " +touches[i].target.innerHTML+" ("+touches[i].pageX+", "+touches[i].pageY+")"); } } } var handleTouchMove = function (event) { if (!touchMoving) return; event.preventDefault(); var touches = event.changedTouches; var x = 0; var y = 0; for (var i=0; i < touches.length; i++) { var idx = ongoingTouchIndexById(touches[i].identifier); if(idx >= 0) { x = touches[i].pageX - ongoingTouches[idx].pageX; y = touches[i].pageY - ongoingTouches[idx].pageY; //log("touch moving "+idx+" on "+ongoingTouches[idx].target.innerHTML+" ("+x+", "+y+")"); ongoingTouches[idx].target.style.left = ongoingTouches[idx].target.offsetLeft + x + "px"; ongoingTouches[idx].target.style.top = ongoingTouches[idx].target.offsetTop + y + "px"; ongoingTouches.splice(idx, 1, copyTouch(touches[i])); // swap in the new touch record } else { log("can't figure out which touch to continue"); } } } var handleTouchEnd = function (event) { if (!touchMoving) return; touchMoving = false; event.preventDefault(); var touches = event.changedTouches; for (var i=0; i < touches.length; i++) { var idx = ongoingTouchIndexById(touches[i].identifier); if(idx >= 0) { //log("touch finishing "+idx+" on "+ongoingTouches[idx].target.innerHTML); ongoingTouches.splice(idx, 1); // remove it; we're done } else { log("can't figure out which touch to end"); } } } function copyTouch(touch) { return { identifier: touch.identifier, target: touch.target, pageX: touch.pageX, pageY: touch.pageY }; } function ongoingTouchIndexById(idToFind) { for (var i=0; i < ongoingTouches.length; i++) { var id = ongoingTouches[i].identifier; if (id == idToFind) { return i; } } return -1; // not found } })(typeof exports === 'undefined'? this['moving']={}: exports);
JavaScript
0.000001
@@ -93,16 +93,16 @@ .io/ -adjustjs +dynamize %0A *
e1528572f138d349d625e59abc8311340b5d27f4
____ usual
mongo-scripts/datathon.js
mongo-scripts/datathon.js
const _ = require('lodash'); const nconf = require('nconf'); const Promise = require('bluebird'); const JSDOM = require('jsdom').JSDOM; const debug = require('debug')('datathon'); const moment = require('moment'); const utils = require('../lib/utils'); const mongo = require('../lib/mongo'); const l = require('../parsers/components/linkontime'); const cfgFile = "config/content.json"; nconf.argv().env().file({ file: cfgFile }); const cName = 'finalized'; const CHUNK = nconf.get('amount') ? _.parseInt(nconf.get('amount')) : 500; let max = null; const until = nconf.get('until'); if(!until) { max = new Date("2018-11-30"); debug("`until` not set: using the default %s", max); } else { max = new Date(until); debug("`until` set, it will stop when reach %s", max); } const since = nconf.get('since'); let last = new Date(since); let total = null; let progressive = 0; let initial = 0; const executedAt = moment(); return mongo .readLimit(cName, {}, { savingTime: -1 }, 1, 0) .then(_.first) .then(function(lastSaved) { if(lastSaved) { if(since) { debug("Last reference found to %s but since %s request overrides", lastSaved.savingTime, since); last = new Date(since); } else { debug("Last reference found to %s, and since not configured", lastSaved.savingTime); last = new Date(lastSaved.savingTime); } } else if(!since) { debug("When last reference don't exist, `since` is mandatory"); process.exit(1); } else { last = new Date(since); debug("Starting `since` %s", last); } return last; }) .tap(function(last) { return mongo.count(cName, {}) .tap(function(before) { debug("previously found %d, chunk size configured (with `amount`) is %d", before, CHUNK); initial = before; }); }) .tap(function(last) { return mongo.count(nconf.get('schema').htmls, { savingTime: { $gt: last, $lte: max } }) .tap(function(amount) { total = (amount - initial); debug("The # of htmls between %s and %s is: %d, still TBD %d", moment(last).format(), moment(max).format(), amount, total); }); }) .then(infiniteLoop); function infiniteLoop(last) { let start = moment(); return mongoPipeline(last) .map(enhanceRedact) .then(_.compact) .tap(massSave) .then(function(elements) { if(!_.size(elements)) { console.log("0 elements found"); process.exit(1); } let end = moment(); var secs = moment.duration(end - start).asSeconds(); debug("exec %d secs 1st [%s] last [%s]", secs, _.first(elements) ? moment(_.first(elements).savingTime).format() : "NONE", _.last(elements) ? moment(_.last(elements).savingTime).format() : "NONE" ); return new Date(_.last(elements).savingTime); }) .then(infiniteLoop) .catch(function(error) { console.log("Fatal"); console.error(error); }); }; function massSave(elements) { let copyable = new Object(elements); return Promise.map(elements, function(e) { return mongo .count(cName, { id: e.id }) .tap(function(a) { if(a > 0) copyable = _.reject(copyable, { id: e.id }); }); }, { concurrency: 5 }) .then(function() { progressive += _.size(copyable); const runfor = moment.duration(moment() - executedAt).asSeconds(); const pps = _.round(progressive / runfor, 0) const estim = (total - progressive) / pps; const stillwaitfor = moment.duration({ seconds: estim }).humanize(); debug("Saving %d objects, total %d (still TBD %d) run since %s (%d secs) PPS %d ETA %s", _.size(copyable), progressive, total - progressive, moment.duration(executedAt - moment()).humanize(), runfor, pps, stillwaitfor ); if(_.size(copyable)) return mongo.writeMany(cName, copyable); }); }; function enhanceRedact(e) { try { _.unset(e, '_id'); e.impressionOrder = _.first(e.impressionOrder); e.impressionTime = _.first(e.impressionTime); e.pseudo = utils.pseudonymizeUser(e.userId); const jsdom = new JSDOM(e.html).window.document; e.attributions = attributeOffsets(jsdom, e.html); e.details = l({jsdom}).linkedtime; _.unset(e, 'html'); _.unset(e, 'userId'); } catch(error) { console.error(error); return null; } return e; }; function mongoPipeline(lastSaved) { if(moment(lastSaved).isAfter(max)) { debug("Execution completed, reach %s", max); process.exit(1); } return mongo.aggregate(nconf.get('schema').htmls, [{ /* I use savingTime despite we use the impressionTime, because * savingTime is indexes, impressionTime ensure differencies */ $match: { savingTime: { $gt: lastSaved } }}, { $sort: { savingTime: 1 }}, { $limit: CHUNK }, { $lookup: { from: "impressions2", localField: "id", foreignField: "htmlId", as: "impre" }}, { $project: { html: true, utype: true, permaLink: true, id: true, timelineId: true, userId: true, savingTime: true, impressionOrder: '$impre.impressionOrder', impressionTime: '$impre.impressionTime', }} ]); }; function attributeOffsets(jsdom, htmlstring) { let retval = [] // { h: 'h5' || 'h6', offset: <Int>, name: <String>, display: <String> } const h5s = jsdom.querySelectorAll('h5'); const h6s = jsdom.querySelectorAll('h6'); function finder(initialO, h) { let linked = h.firstChild && h.firstChild.querySelector && h.firstChild.querySelector('a'); if(linked) { let name = h.firstChild.querySelector('a').textContent; let display = h.textContent; let offset = htmlstring.indexOf(h.outerHTML); if(name) { retval.push(_.extend(initialO, { offset, name, display })); } } }; _.each(h5s, _.partial(finder, { h: 'h5' })); _.each(h6s, _.partial(finder, { h: 'h6' })); return retval; };
JavaScript
0.999997
@@ -4013,31 +4013,114 @@ -debug(%22Saving %25d object +const successString = _.size(copyable) ? %60+saving $%7B_.size(copyable)%7D objects%60 : %22_____%22;%0A debug(%22%25 s, t @@ -4193,32 +4193,29 @@ -_.size(copyable) +successString , progre
7e088f242d070a020921aeb4371c1ec832ea9a70
Remove executable flag from JS file.
htdocs/js/wikitoolbar.js
htdocs/js/wikitoolbar.js
function addWikiFormattingToolbar(textarea) { if ((typeof(document["selection"]) == "undefined") && (typeof(textarea["setSelectionRange"]) == "undefined")) { return; } var toolbar = document.createElement("div"); toolbar.className = "wikitoolbar"; function addButton(id, title, fn) { var a = document.createElement("a"); a.href = "#"; a.id = id; a.title = title; a.onclick = function() { try { fn() } catch (e) { } return false }; a.tabIndex = 400; toolbar.appendChild(a); } function encloseSelection(prefix, suffix) { textarea.focus(); var start, end, sel, scrollPos, subst; if (typeof(document["selection"]) != "undefined") { sel = document.selection.createRange().text; } else if (typeof(textarea["setSelectionRange"]) != "undefined") { start = textarea.selectionStart; end = textarea.selectionEnd; scrollPos = textarea.scrollTop; sel = textarea.value.substring(start, end); } if (sel.match(/ $/)) { // exclude ending space char, if any sel = sel.substring(0, sel.length - 1); suffix = suffix + " "; } subst = prefix + sel + suffix; if (typeof(document["selection"]) != "undefined") { var range = document.selection.createRange().text = subst; textarea.caretPos -= suffix.length; } else if (typeof(textarea["setSelectionRange"]) != "undefined") { textarea.value = textarea.value.substring(0, start) + subst + textarea.value.substring(end); if (sel) { textarea.setSelectionRange(start + subst.length, start + subst.length); } else { textarea.setSelectionRange(start + prefix.length, start + prefix.length); } textarea.scrollTop = scrollPos; } } addButton("strong", "Bold text: '''Example'''", function() { encloseSelection("'''", "'''"); }); addButton("em", "Italic text: ''Example''", function() { encloseSelection("''", "''"); }); addButton("heading", "Heading: == Example ==", function() { encloseSelection("\n== ", " ==\n", "Heading"); }); addButton("link", "Link: [http://www.example.com/ Example]", function() { encloseSelection("[", "]"); }); addButton("code", "Code block: {{{ example }}}", function() { encloseSelection("\n{{{\n", "\n}}}\n"); }); addButton("hr", "Horizontal rule: ----", function() { encloseSelection("\n----\n", ""); }); textarea.parentNode.insertBefore(toolbar, textarea); } // Add the toolbar to all <textarea> elements on the page with the class // 'wikitext'. var re = /\bwikitext\b/; var textareas = document.getElementsByTagName("textarea"); for (var i = 0; i < textareas.length; i++) { var textarea = textareas[i]; if (textarea.className && re.test(textarea.className)) { addWikiFormattingToolbar(textarea); } }
JavaScript
0.002005
07c13a431a386f31e5dab84cb42233991dc81019
Remove executable flag from JS file.
htdocs/js/wikitoolbar.js
htdocs/js/wikitoolbar.js
function addWikiFormattingToolbar(textarea) { if ((typeof(document["selection"]) == "undefined") && (typeof(textarea["setSelectionRange"]) == "undefined")) { return; } var toolbar = document.createElement("div"); toolbar.className = "wikitoolbar"; function addButton(id, title, fn) { var a = document.createElement("a"); a.href = "#"; a.id = id; a.title = title; a.onclick = function() { try { fn() } catch (e) { } return false }; a.tabIndex = 400; toolbar.appendChild(a); } function encloseSelection(prefix, suffix) { textarea.focus(); var start, end, sel, scrollPos, subst; if (typeof(document["selection"]) != "undefined") { sel = document.selection.createRange().text; } else if (typeof(textarea["setSelectionRange"]) != "undefined") { start = textarea.selectionStart; end = textarea.selectionEnd; scrollPos = textarea.scrollTop; sel = textarea.value.substring(start, end); } if (sel.match(/ $/)) { // exclude ending space char, if any sel = sel.substring(0, sel.length - 1); suffix = suffix + " "; } subst = prefix + sel + suffix; if (typeof(document["selection"]) != "undefined") { var range = document.selection.createRange().text = subst; textarea.caretPos -= suffix.length; } else if (typeof(textarea["setSelectionRange"]) != "undefined") { textarea.value = textarea.value.substring(0, start) + subst + textarea.value.substring(end); if (sel) { textarea.setSelectionRange(start + subst.length, start + subst.length); } else { textarea.setSelectionRange(start + prefix.length, start + prefix.length); } textarea.scrollTop = scrollPos; } } addButton("strong", "Bold text: '''Example'''", function() { encloseSelection("'''", "'''"); }); addButton("em", "Italic text: ''Example''", function() { encloseSelection("''", "''"); }); addButton("heading", "Heading: == Example ==", function() { encloseSelection("\n== ", " ==\n", "Heading"); }); addButton("link", "Link: [http://www.example.com/ Example]", function() { encloseSelection("[", "]"); }); addButton("code", "Code block: {{{ example }}}", function() { encloseSelection("\n{{{\n", "\n}}}\n"); }); addButton("hr", "Horizontal rule: ----", function() { encloseSelection("\n----\n", ""); }); textarea.parentNode.insertBefore(toolbar, textarea); } // Add the toolbar to all <textarea> elements on the page with the class // 'wikitext'. var re = /\bwikitext\b/; var textareas = document.getElementsByTagName("textarea"); for (var i = 0; i < textareas.length; i++) { var textarea = textareas[i]; if (textarea.className && re.test(textarea.className)) { addWikiFormattingToolbar(textarea); } }
JavaScript
0.005383
a0cb3c76154fb010a44c0d8d5dc5c9defb523964
remove crap
src/filter/index.js
src/filter/index.js
const DocumentDBClient = require('documentdb').DocumentClient; const config = { DatabaseId: "mean-dev", CollectionId: "users", Host: process.env.DocDb_Host, AuthKey: process.env.DocDb_AuthKey, }; config.CollLink = 'dbs/' + config.DatabaseId + '/colls/' + config.CollectionId module.exports = function (context, message) { let err = null; const docDbClient = new DocumentDBClient(config.Host, { masterKey: config.AuthKey }); const querySpec = { query: 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = \'@userid\' AND \'twitter\' = \'@platform\')',// OR (c.instagram[\'$id\'] = \'@userid\' AND \'instagram\' = \'@platform\') OR (c.facebook[\'$id\'] = \'@userid\' AND \'facebook\' = \'@platform\')', parameters: [{ name: '@userid', value: message.userid }, { name: '@platform', value: message.platform }] }; const query = 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = \'' + message.userid + '\' AND \'twitter\' = \'' + message.platform + '\') OR (c.instagram[\'$id\'] = \'' + message.userid + '\' AND \'instagram\' = \'' + message.platform + '\') OR (c.facebook[\'$id\'] = \'' + message.userid + '\' AND \'facebook\' = \'' + message.platform + '\')'; context.log(querySpec); docDbClient.queryDocuments(config.CollLink, query).toArray(function (err, results) { context.log(err); context.log(results); let userdata = results[0]; if (!userdata || userdata == undefined) { context.log('Not tracking user'); err = new Error('Not tracking user'); return; } if ((!userdata.twitter || userdata.twitter == undefined) && (!userdata.facebook || userdata.facebook == undefined) || (!userdata.instagram || userdata.instagram == undefined)) { context.log('No social profiles'); err = new Error('No social profiles'); return; } if (!userdata.id) { context.log('No user id'); err = new Error('No social profiles'); return; } let data = new Object(); if (!err) { data.userid = userdata.id; data.platform = message.platform; data.mediaid = message.mediaid; if (message.twitter) { context.log('adding twitter'); data.twitter = { id: message.twitter.$id, token: message.twitter.token, username: message.twitter.username, }; } if (message.instagram) { context.log('adding instagram'); data.instagram = { id: message.instagram.$id, token: message.instagram.token, username: message.instagram.username, }; } if (message.facebook) { context.log('adding facebook'); data.facebook = { id: message.facebook.$id, token: message.facebook.token, username: message.facebook.email, }; } } context.done(err, data); }); };
JavaScript
0.00005
@@ -334,17 +334,16 @@ age) %7B%0A%0A -%0A let @@ -449,482 +449,8 @@ %7D);%0A - const querySpec = %7B%0A query: 'SELECT * FROM c WHERE (c.twitter%5B%5C'$id%5C'%5D = %5C'@userid%5C' AND %5C'twitter%5C' = %5C'@platform%5C')',// OR (c.instagram%5B%5C'$id%5C'%5D = %5C'@userid%5C' AND %5C'instagram%5C' = %5C'@platform%5C') OR (c.facebook%5B%5C'$id%5C'%5D = %5C'@userid%5C' AND %5C'facebook%5C' = %5C'@platform%5C')',%0A parameters: %5B%7B%0A name: '@userid',%0A value: message.userid%0A %7D,%0A %7B%0A name: '@platform',%0A value: message.platform%0A %7D%5D%0A %7D;%0A%0A @@ -796,36 +796,8 @@ ';%0A%0A - context.log(querySpec);%0A @@ -885,63 +885,8 @@ ) %7B%0A - context.log(err);%0A context.log(results); %0A
efcca8a064a5c6b29abf6bde0ed52f2745a69c9d
implement sprite pooling for player lasers
src/entities/Player.js
src/entities/Player.js
/** * Player.js * * Foofighter.js — Player entity * * This class represents the data model and display entity for a * Player's startship in the game environment. */ ;(function( FooFighter ){ 'use strict'; function Player ( gameState, group ) { this.gameState = gameState; this.config = {}; this.sprite = {}; this.movementVelocity = 300; this.displayStates = { neutral: 'player.png', left: 'playerLeft.png', right: 'playerRight.png' }; this.fireTimer = 250; this.canFire = true; this.lastFired = new Date().getTime(); this.group = group; this.config.laser = { velocity: -500, fireTimer: 250 }; this.lasers = gameState.groups.lasers; this.bindEvents(); } var proto = Player.prototype; proto.bindEvents = function(){ var vent = this.gameState.vent; vent.on('create', this.create.bind(this)); vent.on('update', function(){ this.movementHandler(); this.weaponHandler(); }.bind(this)); return this; }; proto.create = function(){ var game = this.gameState.game; // Build the sprite entitiy this.sprite = game.add.sprite( game.world.centerX, game.world.centerY, 'sprites', this.displayStates.neutral ); // Anchor in the center of the sprite this.sprite.anchor = { x: 0.5, y: 0.5 }; // Add it to the correct display group this.group.add(this.sprite); this.sprite.events.onKilled.add(this.onKill.bind(this)); return this; }; proto.movementHandler = function(){ var game = this.gameState.game, magnitude = this.movementVelocity, modifier = 1, axis, cursors = this.gameState.cursors; // Reset any prior velocity vals this.sprite.body.velocity.setTo(0, 0); // Detect which cursor keys are pressed and modify the sprite // display frame texture for X axis directions if ( cursors.up.isDown ) { modifier = -1; axis = 'y'; } else if ( cursors.down.isDown ) { modifier = 1; axis = 'y'; } else if ( cursors.left.isDown ) { this.sprite.loadTexture('sprites', this.displayStates.left); modifier = -1; axis = 'x'; } else if ( cursors.right.isDown ) { this.sprite.loadTexture('sprites', this.displayStates.right); modifier = 1; axis = 'x'; } else { this.sprite.loadTexture('sprites', this.displayStates.neutral); } // This is just the movement speed + directional modifier this.sprite.body.velocity[axis] = (modifier * magnitude); return this; }; proto.weaponHandler = function(){ var game = this.gameState.game, cursors = this.gameState.cursors, keyboard = this.gameState.keyboard, currTime = new Date().getTime(), lastFired = this.lastFired, throttleVal = this.config.laser.fireTimer, laser; // If we're dead, don't fire a got damn laser if ( !this.sprite.alive ) { return false; } // If spacebar is pressed in this loop step, create a laser and // make sure we can't fire again for N milliseconds if ( keyboard.isDown(Phaser.Keyboard.SPACEBAR) ) { if ( currTime - lastFired >= throttleVal ) { this.createLaser(); this.gameState.updateScore(-2); this.lastFired = currTime; } } return this; }; proto.createLaser = function(){ var game = this.gameState.game, velocity = this.config.laser.velocity, laser; // Create our laser sprite entity laser = game.add.sprite( this.sprite.body.x + this.sprite.body.width/2, this.sprite.body.y - 10, 'sprites', 'laserGreen.png' ); // Keep track of all our onscreen lasers (for collision detection) this.lasers.add(laser); // Anchor to the center of the sprite laser.anchor = { x: 0.5, y: 0.5 }; // Set the movement speed laser.body.velocity.y = velocity; // Clean up any lasers that leave the game scence laser.events.onOutOfBounds.add(laser.kill, laser); return this; }; proto.onKill = function(){ var vent = this.gameState.vent; vent.emit('game-over'); }; FooFighter.Player = Player; })(FooFighter);
JavaScript
0
@@ -3549,90 +3549,48 @@ -laser;%0A%0A // Create our laser sprite entity%0A laser = game.add.sprite( +pos,%0A laser;%0A%0A pos = %7B %0A thi @@ -3577,32 +3577,35 @@ pos = %7B%0A + x: this.sprite.bod @@ -3636,32 +3636,34 @@ idth/2,%0A +y: this.sprite.body @@ -3673,152 +3673,256 @@ - 10 -, %0A - 'sprites', 'laserGreen.png'%0A );%0A // Keep track of all our onscreen lasers (for collision detection)%0A this.lasers.add(laser);%0A +%7D;%0A%0A laser = this.lasers.getFirstExists(false);%0A%0A if ( !laser ) %7B%0A // Create our laser sprite entity%0A laser = this.lasers.create(%0A pos.x,%0A pos.y,%0A 'sprites', 'laserGreen.png'%0A );%0A @@ -3955,24 +3955,28 @@ the sprite%0A + laser.an @@ -3976,32 +3976,36 @@ aser.anchor = %7B%0A + x: 0.5,%0A @@ -4004,32 +4004,36 @@ x: 0.5,%0A + y: 0.5%0A %7D;%0A @@ -4023,27 +4023,35 @@ y: 0.5%0A + + %7D;%0A + // Set t @@ -4076,42 +4076,8 @@ -laser.body.velocity.y = velocity;%0A @@ -4126,16 +4126,20 @@ scence%0A + lase @@ -4185,16 +4185,148 @@ laser);%0A + %7D else %7B%0A laser.x = pos.x;%0A laser.y = pos.y%0A laser.revive();%0A %7D%0A%0A laser.body.velocity.y = velocity;%0A%0A retu
701dfff2352dad2eff5df92897d1c0a848dc2041
remove useless code
src/entities/player.js
src/entities/player.js
"use strict"; var axisUp = new THREE.Vector3(0, 1, 0), PI_2 = Math.PI / 2; var Player = function Player (camera, input, pointer) { this.height = 100; this.width = 100; this.jumpCount = 0; this.jumpStrength = 5; this.currentJumpStrength = 0; this.position = new THREE.Vector3(0, 0, 0); this.movement = new THREE.Vector3(0, 0, 0); this.actionCommand = input.commands.action; this.leftCommand = input.commands.left; this.rightCommand = input.commands.right; this.upCommand = input.commands.up; this.downCommand = input.commands.down; this.viewZCommand = input.commands.viewZ; this.viewXCommand = input.commands.viewX; this.viewYMinusCommand = input.commands.viewYPlus; this.viewYPlusCommand = input.commands.viewYMinus; this.pointer = pointer; this.camera = camera; }; Player.prototype.update = function (dt, gravity, checkCollision) { //MOVEMENTS this.movement.x = this.leftCommand.active ? this.leftCommand.value : -this.rightCommand.value; this.movement.z = this.upCommand.active ? this.upCommand.value : -this.downCommand.value; this.movement.y = 0; if (this.movement.x || this.movement.z) { // TODO the theta and phi should be calculated on the player entity and then passed to the camera this.movement.normalize(); this.movement.applyAxisAngle(axisUp, -this.camera.theta + PI_2); } if (this.viewYPlusCommand.active) { this.movement.y = this.viewYPlusCommand.value * 2.5; } else { this.movement.y = -this.viewYMinusCommand.value * 2; } if (this.actionCommand.down && this.jumpCount === 0) { this.currentJumpStrength = this.jumpStrength; this.jumpCount++; } if (this.currentJumpStrength > 0.001) { this.movement.y += this.currentJumpStrength; this.currentJumpStrength *= 0.9; } else { this.currentJumpStrength = 0; } this.movement.add(gravity); this.movement.multiplyScalar(dt); this.camera.setMousePosition( this.pointer.movementX + Math.sign(this.viewXCommand.value) * Math.pow(this.viewXCommand.value, 2) * 25, this.pointer.movementY + Math.sign(this.viewZCommand.value) * Math.pow(this.viewZCommand.value, 2) * 25, dt ); this.position.z = this.position.z + this.movement.z; this.position.x = this.position.x + this.movement.x; this.position.y = this.position.y + this.movement.y; checkCollision(this); this.camera.position.z = this.position.z; this.camera.position.x = this.position.x; this.camera.position.y = this.position.y; this.camera.position.y+= this.height * 0.25; }; module.exports = Player;
JavaScript
0.000006
@@ -1520,82 +1520,8 @@ %7D - else %7B%0A this.movement.y = -this.viewYMinusCommand.value * 2;%0A %7D %0A%0A
b47f0ae3ac50e7b85af395e2fa79edfa8e50fb2d
fix end
src/game/history.js
src/game/history.js
// @flow import React, { Component } from 'react'; import styled from 'styled-components'; type Props = { history: string[], index: number, onChangeIndex: (index: number) => any, }; const isFirst = (index: number): boolean => index === -1; const isLast = <T>(history: T[], index: number) => index >= history.length; class History extends Component<Props> { goBack = () => { const { index, onChangeIndex } = this.props; if (isFirst(index)) { return; } onChangeIndex(index - 1); }; goForward = () => { const { history, index, onChangeIndex } = this.props; if (isLast(history, index)) { return; } onChangeIndex(index + 1); }; render() { const { history, index } = this.props; return ( <div> <Controls> <Control active={!isFirst(index)} onClick={this.goBack} >&#xab; prev</Control> <Control active={!isLast(history, index)} onClick={this.goForward} >next &#xbb;</Control> </Controls> </div> ); } } const Controls = styled.div` display: flex; margin: 20px 0; `; type ControlProps = { active: boolean, }; const Control = styled.div` margin-right: 10px; cursor: ${({ active }: ControlProps) => active ? 'pointer' : 'auto'}; color: ${({ active }: ControlProps) => active ? '#000' : '#aaa'}; pointer-events: ${({ active }: ControlProps) => active ? 'auto' : 'none'}; `; export default History;
JavaScript
0.000295
@@ -316,16 +316,20 @@ y.length + - 1 ;%0A%0Aclass
f45862868974c1ef4320e6bfc4ef603a5a34bd1e
Fix log typo
src/globalStream.js
src/globalStream.js
/* Opt-in, convenience construct used to update a global stream imperatively and in a type safe fashion */ import most from 'most'; import defaultLog from './log'; /* * A stream piloted by type-safe messages. Meant to be a global (application wide), never ending stream. */ export function GlobalStream(initialState, registerHandlers, log) { if (log === undefined) log = defaultLog.stream; const handlers = {}; let dispatching = false; const on = (msg, fn) => { handlers[msg._id] = fn } registerHandlers(on); if (log) console.log('%cInitial state:', 'color: green', initialState); const stream = most.create((add, end, error) => { stream.emit = function(message) { const { _id, _name, payload } = message; // TODO: Is it even useful to prevent redispatching since we have async redraws? We could push to a temp queue. // The scenario would be: in the middle of a msg handling, we want to conditionally dispatch another msg. if (dispatching) throw new Error( 'Cannot dispatch a Msg in the middle of another msg\'s dispatch'); const handler = handlers[_id]; if (!handler) { throw new Error('globalStream.emit: Unknown message: ', _name); return; } dispatching = true; let newState; try { newState = handler(stream.value, payload); } finally { if (log) console.log(`%cNew PushStream state:`, 'color: blue', newState); dispatching = false; } if (newState !== stream.value) { stream.value = newState; add(newState); } } }) stream.value = initialState; stream.drain(); return stream; }
JavaScript
0.000008
@@ -1423,12 +1423,14 @@ New -Push +Global Stre
a91192dfd41761ba1292e7444247db4c1a13fb68
Disable Dragging
static/assets/javascripts/common.js
static/assets/javascripts/common.js
// Copyright (c) 2013 Ryan Clark // https://gist.github.com/rclark/5779673 L.TopoJSON = L.GeoJSON.extend({ addData: function (jsonData) { if (jsonData.type === "Topology") { for (key in jsonData.objects) { geojson = topojson.feature(jsonData, jsonData.objects[key]); L.GeoJSON.prototype.addData.call(this, geojson); } } else { L.GeoJSON.prototype.addData.call(this, jsonData); } } }); var spreadsheetID = "1mxcmAbjrVTU9c3zDy-Mz7PfziEtKNI1PejGuvwD4PW4"; var jsonurl = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/1/public/values?alt=json"; $.getJSON(jsonurl, function(datas) { $entrys = datas.feed.entry; $($entrys).each(function(){ if(this.gsx$district.$t.toLowerCase()=="total") { if (this.gsx$nagarpalika.$t == '') { this.gsx$nagarpalika.$t = 0 } if (this.gsx$gaupalika.$t == '') { this.gsx$gaupalika.$t = 0 } if (this.gsx$upamahanarpalika.$t == '') { this.gsx$upamahanarpalika.$t = 0 } if (this.gsx$mahanarpalika.$t == '') { this.gsx$mahanarpalika.$t = 0 } if (this.gsx$totalnumberofregisteredvoters.$t == '') { this.gsx$mahanarpalika.$t = "NULL" } document.getElementById("nagar").innerHTML = this.gsx$nagarpalika.$t; document.getElementById("upnagar").innerHTML = this.gsx$upamahanarpalika.$t; document.getElementById("mahanagar").innerHTML = this.gsx$mahanarpalika.$t; document.getElementById("gau").innerHTML = this.gsx$gaupalika.$t; document.getElementById("tp").innerHTML = this.gsx$totalpopulation.$t; document.getElementById("rpp").innerHTML = this.gsx$registeredpoliticalparties.$t; document.getElementById("trv").innerHTML = this.gsx$totalnumberofregisteredvoters.$t; } }); }); function getUpdate(e) { $($entrys).each(function(){ if(this.gsx$district.$t.toLowerCase()==e.toLowerCase()) { if (this.gsx$nagarpalika.$t == '') { this.gsx$nagarpalika.$t = 0 } if (this.gsx$gaupalika.$t == '') { this.gsx$gaupalika.$t = 0 } if (this.gsx$upamahanarpalika.$t == '') { this.gsx$upamahanarpalika.$t = 0 } if (this.gsx$mahanarpalika.$t == '') { this.gsx$mahanarpalika.$t = 0 } if (this.gsx$totalnumberofregisteredvoters.$t == '') { this.gsx$mahanarpalika.$t = "NULL" } document.getElementById("nagar").innerHTML = this.gsx$nagarpalika.$t; document.getElementById("upnagar").innerHTML = this.gsx$upamahanarpalika.$t; document.getElementById("mahanagar").innerHTML = this.gsx$mahanarpalika.$t; document.getElementById("gau").innerHTML = this.gsx$gaupalika.$t; document.getElementById("district").innerHTML = e; document.getElementById("tp").innerHTML = this.gsx$totalpopulation.$t; document.getElementById("rpp").innerHTML = this.gsx$registeredpoliticalparties.$t; document.getElementById("trv").innerHTML = this.gsx$totalnumberofregisteredvoters.$t; } }); } (function () { var map = L.map('map', {maxZoom: 6.9, minZoom: 6.9 }), topoLayer = new L.TopoJSON(), colorScale = chroma .scale(['#D5E3FF', '#003171']) .domain([0, 1]); map.setView([28.1999999, 84.100140], 6.9); $.getJSON('static/assets/javascripts/nepal-districts.topo.json').done(addTopoData); function addTopoData(topoData) { topoLayer.addData(topoData); topoLayer.addTo(map); topoLayer.eachLayer(handleLayer); } function highlightFeature(e) { var layer = e.target; layer.setStyle( { weight: 1, color: 'black', fillColor: 'blue', } ); if (!L.Browser.ie && !L.Browser.opera) { layer.bringToFront(); } } function resetHighlight(e) { var layer = e.target; var setColor=layer.feature.properties.pradesh_no layer.setStyle( { fillColor: getProvinceColor(setColor), weight: 2, opacity: 1, color: 'white', dashArray: 3, fillOpacity: 0.7 } ); if (!L.Browser.ie && !L.Browser.opera) { layer.bringToFront(); } } function handleLayer(layer) { layer.bindLabel(layer.feature.properties.name, {noHide: true}) var code = layer.feature.properties.name; var setColor=layer.feature.properties.pradesh_no; layer.setStyle({ fillColor: getProvinceColor(setColor), weight: 2, opacity: 1, color: 'white', dashArray: 3, fillOpacity: 0.7 }); layer.on({ mouseover: highlightFeature, mouseout: resetHighlight, }); layer.on('click', function (e) { getUpdate(layer.feature.properties.name); }); } function getProvinceColor(state) { if (state == 7) { return 'red'; } else if (state == 6) { return '#c1a73e'; } else if (state == 5) { return '#da8b4a'; } else if (state == 4) { return '#26a9e8'; } else if (state == 3) { return '#40a500'; } else if (state == 2) { return '#e271a1'; } else if (state == 1) { return '#900e94'; } } var legend = L.control({position: 'topright'}); legend.onAdd = function (map) { var div = L.DomUtil.create('div', 'legend'); var labels = [ "Province No. 1", "Province No. 2", "Province No. 3", "Province No. 4", "Province No. 5", "Province No. 6", "Province No. 7" ]; var grades = [1, 2, 3, 4, 5, 6, 7]; div.innerHTML = '<div><h6>Province Index</h6></div>'; for (var i = 0; i < grades.length; i++) { div.innerHTML += '<i style="background:' + getProvinceColor(grades[i]) + '">&nbsp;&nbsp;&nbsp;&nbsp;</i>&nbsp;&nbsp;' + labels[i] + '<br />'; } return div; } legend.addTo(map); }());
JavaScript
0.000003
@@ -3560,17 +3560,17 @@ xZoom: -6 +7 .9, minZ @@ -3733,24 +3733,66 @@ in(%5B0, 1%5D);%0A + map.dragging.disable();%0A%0A map.
c2026b15d22f2ef16f43ec4822c4ac00e85cef65
remove redundant code
motion/js/motion.js
motion/js/motion.js
function start() { if(animating) return; animating = true; var ctx = canvas.getContext('2d'); var path = knownPath[pathSelect.value]; var x = path[0].x; //x coordinate var y = path[0].y; //y coordinate var dir = atan2(path[1].y-path[0].y, path[1].x-path[0].x); //orientation in radians var motionModel = new OdometryModel(getTurnNoise(), getStrideNoise(), getTurnNoise(), getTurnNoise()); var filter = new ParticleFilter(getParticleCount(), motionModel, undefined, new RobotState(x, y, dir)); robot = new Robot(filter, path); robot.draw(ctx); animating = true; lastFrame = Date.now(); requestAnimationFrame(frame); }
JavaScript
0.999999
@@ -555,35 +555,16 @@ w(ctx);%0A -%09animating = true;%0A %09lastFra
812ddf0a3599497b6422fda421d6920e265d4707
Remove useless variable
lib/Client.js
lib/Client.js
var Chrome = require('chrome-remote-interface'); var events = require('events'); var util = require('util'); var common = require('./common.js'); var Page = require('./Page.js'); var CLEANUP_SCRIPT = 'chrome.benchmarking.closeConnections();' + 'chrome.benchmarking.clearHostResolverCache();'; var Client = function (urls, options) { var self = this; var currentPageIndex = -1; self.pages = []; Chrome(function (chrome) { function loadNextURL() { var id = ++currentPageIndex; var url = urls[id]; if (url) { if (!url.match(/^http[s]?:/)) { url = 'http://' + url; } var page = new Page(id, url); self.emit('pageStart', url); page.start(); chrome.Runtime.evaluate({'expression': CLEANUP_SCRIPT}); chrome.Page.navigate({'url': url}); self.pages.push(page); } return url; } // start! self.emit('connect'); chrome.Page.enable(); chrome.Network.enable(); chrome.Network.setCacheDisabled({'cacheDisabled': true}); loadNextURL(); var messages = []; chrome.on('event', function (message) { messages.push(message); if (message.method) { var page = self.pages[currentPageIndex]; if (message.method == 'Page.domContentEventFired') { common.dump('<-- ' + message.method + ': ' + page.url); page.domLoaded(); } else if (message.method == 'Page.loadEventFired') { common.dump('<-- ' + message.method + ': ' + page.url); page.end(); } else if (message.method.match(/^Network./)) { page.processMessage(message); } else { common.dump('Unhandled message: ' + message.method); } // check done with current URL if (page.isDone()) { self.emit(page.isOk() ? 'pageEnd' : 'pageError', page.url); if (!loadNextURL()) { common.dump("Emitting 'end' event"); chrome.close(); self.emit('end', getHAR.call(self), messages); } } } else { common.dump('<-- #' + message.id + ' ' + JSON.stringify(message.result)); } }); }).on('error', function (error) { common.dump("Emitting 'error' event: " + error.message); self.emit('error'); }); } util.inherits(Client, events.EventEmitter); function getHAR() { var self = this; var har = { 'log': { 'version' : '1.2', 'creator' : { 'name': 'Chrome HAR Capturer', 'version': '0.3.1' }, 'pages': [], 'entries': [] } }; // merge pages in one HAR for (var i in self.pages) { var page = self.pages[i]; if (page.isOk()) { var pageHAR = page.getHAR(); har.log.pages.push(pageHAR.info); Array.prototype.push.apply(har.log.entries, pageHAR.entries); } } return har; } module.exports = Client;
JavaScript
0.000433
@@ -360,39 +360,8 @@ his; -%0A var currentPageIndex = -1; %0A%0A @@ -407,24 +407,69 @@ (chrome) %7B%0A + // load the next URL or exit if done%0A func @@ -514,26 +514,25 @@ d = -++currentPageIndex +self.pages.length ;%0A @@ -1406,25 +1406,20 @@ ages -%5BcurrentPageIndex +.slice(-1)%5B0 %5D;%0A%0A
577e9feb213a09cd2e05dfdfb00cca0a3394eb54
Remove restivus package version
packages/rocketchat-api/package.js
packages/rocketchat-api/package.js
Package.describe({ name: 'rocketchat:api', version: '0.0.1', summary: 'Rest API', git: '' }); Package.onUse(function(api) { api.versionsFrom('1.0'); api.use([ 'coffeescript', 'underscore', 'rocketchat:lib', 'nimble:[email protected]' ]); api.addFiles('server/api.coffee', 'server'); api.addFiles('server/routes.coffee', 'server'); }); Package.onTest(function(api) { });
JavaScript
0
@@ -236,14 +236,8 @@ ivus [email protected] '%0A%09%5D
0a75035996204c5a6f73fde9041fa7304274a8af
Fix site URL maybe 🦆
packages/site/docusaurus.config.js
packages/site/docusaurus.config.js
module.exports = { title: 'Mrm', tagline: 'Codemods for your project config files', url: 'https://github.com/sapegin/mrm', baseUrl: '/', favicon: 'img/favicon.png', organizationName: 'sapegin', projectName: 'mrm', themeConfig: { disableDarkMode: true, prism: { theme: require('prism-react-renderer/themes/nightOwlLight'), }, navbar: { hideOnScroll: false, title: 'Mrm', links: [ { to: 'docs/getting-started', activeBasePath: 'docs', label: 'Docs', position: 'left', }, { to: 'docs/mrm-preset-default', activeBasePath: 'docs', label: 'Presets', position: 'left', }, { to: 'docs/mrm-task-codecov', activeBasePath: 'docs', label: 'Tasks', position: 'left', }, { href: 'https://github.com/sapegin/mrm', label: 'GitHub', position: 'right', }, ], }, footer: { style: 'dark', links: [ { title: 'Docs', items: [ { label: 'Changelog', href: 'https://github.com/sapegin/mrm/releases', }, { label: 'Contributing', href: 'https://github.com/sapegin/mrm/blob/master/Contributing.md', }, ], }, { title: 'Social', items: [ { label: 'Twitter', href: 'https://twitter.com/iamsapegin', }, { label: 'GitHub', href: 'https://github.com/sapegin/mrm', }, ], }, { title: 'Sponsor', items: [ { label: 'Buy me a coffee', href: 'https://www.buymeacoffee.com/sapegin', }, ], }, ], copyright: `Made with coffee in Berlin by <a href="https://sapegin.me/" class="footer__link-item" target="_blank" rel="noopener noreferrer">Artem Sapegin</a> and <a href="https://github.com/sapegin/mrm/graphs/contributors" class="footer__link-item" target="_blank" rel="noopener noreferrer">contributors</a>`, }, }, presets: [ [ '@docusaurus/preset-classic', { docs: { sidebarPath: require.resolve('./sidebars.js'), remarkPlugins: require('./remark'), }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }, ], ], };
JavaScript
0
@@ -94,38 +94,33 @@ https:// -github.com/sapegin/mrm +mrmjs.netlify.app ',%0A%09base
18ff97377640393e91d3da5f904b49935c6e94d4
Remove library property which was namespacing library.bundled
packages/truffle/webpack.config.js
packages/truffle/webpack.config.js
const path = require("path"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const webpack = require("webpack"); const pkg = require("./package.json"); const rootDir = path.join(__dirname, "../.."); const outputDir = path.join(__dirname, "build"); const truffleLibraryDirectory = path.join( __dirname, "../..", "node_modules", "@truffle/resolver", "solidity" ); module.exports = { mode: "production", entry: { cli: path.join( __dirname, "../..", "node_modules", "@truffle/core", "cli.js" ), chain: path.join( __dirname, "../..", "node_modules", "@truffle/environment", "chain.js" ), analytics: path.join( __dirname, "../..", "node_modules", "@truffle/core", "lib", "services", "analytics", "main.js" ), library: path.join( __dirname, "../..", "node_modules", "@truffle/core", "index.js" ), consoleChild: path.join( __dirname, "../..", "node_modules", "@truffle/core", "lib", "console-child.js" ), commands: path.join( __dirname, "../..", "node_modules", "@truffle/core", "lib", "commands/index.js" ) }, target: "node", node: { // For this option, see here: https://github.com/webpack/webpack/issues/1599 __dirname: false, __filename: false }, context: rootDir, output: { path: outputDir, filename: "[name].bundled.js", library: "truffle", libraryTarget: "commonjs", chunkLoading: "require" }, // There are many source map options we can choose. Choosing an option with // "nosources" allows us to reduce the size of the bundle while still allowing // high quality source maps. devtool: "nosources-source-map", optimization: { minimize: false, splitChunks: { // The following two items splits the bundle into pieces ("chunks"), // where each chunk is less than 5 million bytes (shorthand for roughly // 5 megabytes). The first option, `chunks: all`, is the main powerhouse: // it'll look at common chunks (pieces of code) between each entry point // and separates them its own bundle. When an entry point is run, // the necessary chunks will be automatically required as needed. // This significantly speeds up bundle runtime because a) chunks can be // cached by node (e.g., within the `require` infrastructure) and b) we // won't `require` any chunks not needed by the command run by the user. // It also reduces the total bundle size since chunks can be shared // between entry points. chunks: "all", // I chose 5000000 based on anecdotal results on my machine. Limiting // the size to 5000000 bytes shaved off a few hundreths of a milisecond. // The negative here is creates more chunks. We can likely remove it and // let webpack decide with `chunks: all` if we prefer. maxSize: 5000000 } }, module: { rules: [ // ignores "#!/bin..." lines inside files { test: /\.js$/, include: [ path.resolve(__dirname, "../core"), path.resolve(__dirname, "../environment") ], use: "shebang-loader" } ] }, externals: [ // truffle-config uses the original-require module. // Here, we leave it as an external, and use the original-require // module that's a dependency of Truffle instead. /^original-require$/, /^mocha$/, /^@truffle\/debugger/, //no longer part of the bundle to keep size down // this is the commands portion shared by cli.js and console-child.js /^\.\/commands.bundled.js$/ ], resolve: { alias: { "ws": path.join(__dirname, "./nil.js"), "bn.js": path.join( __dirname, "../..", "node_modules", "bn.js", "lib", "bn.js" ), "original-fs": path.join(__dirname, "./nil.js"), "scrypt": "js-scrypt" } }, stats: { warnings: false }, plugins: [ new webpack.DefinePlugin({ BUNDLE_VERSION: JSON.stringify(pkg.version), BUNDLE_CHAIN_FILENAME: JSON.stringify("chain.bundled.js"), BUNDLE_ANALYTICS_FILENAME: JSON.stringify("analytics.bundled.js"), BUNDLE_LIBRARY_FILENAME: JSON.stringify("library.bundled.js"), BUNDLE_CONSOLE_CHILD_FILENAME: JSON.stringify("consoleChild.bundled.js") }), // Put the shebang back on. new webpack.BannerPlugin({ banner: "#!/usr/bin/env node\n", raw: true }), // `truffle test` new CopyWebpackPlugin({ patterns: [ { from: path.join( __dirname, "../..", "node_modules", "@truffle/core", "lib", "commands", "init", "initSource" ), to: "initSource" }, { from: path.join(truffleLibraryDirectory, "Assert.sol") }, { from: path.join(truffleLibraryDirectory, "AssertAddress.sol") }, { from: path.join(truffleLibraryDirectory, "AssertAddressArray.sol") }, { from: path.join(truffleLibraryDirectory, "AssertBalance.sol") }, { from: path.join(truffleLibraryDirectory, "AssertBool.sol") }, { from: path.join(truffleLibraryDirectory, "AssertBytes32.sol") }, { from: path.join(truffleLibraryDirectory, "AssertBytes32Array.sol") }, { from: path.join(truffleLibraryDirectory, "AssertGeneral.sol") }, { from: path.join(truffleLibraryDirectory, "AssertInt.sol") }, { from: path.join(truffleLibraryDirectory, "AssertIntArray.sol") }, { from: path.join(truffleLibraryDirectory, "AssertString.sol") }, { from: path.join(truffleLibraryDirectory, "AssertUint.sol") }, { from: path.join(truffleLibraryDirectory, "AssertUintArray.sol") }, { from: path.join(truffleLibraryDirectory, "SafeSend.sol") }, { from: path.join( __dirname, "../..", "node_modules", "@truffle/core", "lib", "commands", "create", "templates/" ), to: "templates" } ] }), new CleanWebpackPlugin(), // Make web3 1.0 packable new webpack.IgnorePlugin({ resourceRegExp: /^electron$/ }) ] };
JavaScript
0.000015
@@ -1598,32 +1598,8 @@ s%22,%0A - library: %22truffle%22,%0A
2e57cd497d4e4ca9b4a85ed501adf84cc766d81b
Add comment
step-capstone/src/components/Map.js
step-capstone/src/components/Map.js
import React, { createRef } from 'react' /** * Props: * zoom : 13 - higher the number, the more zoomed the map is on center * center: {lat:0.0, lng:0.0} - coordinates for center of map */ class MapComponent extends React.Component { constructor(props) { super(props); this.state = { finalized: this.props.finalized, unfinalized: this.props.unfinalized, finalizedMarkers: new Map(), unfinalizedMarkers: new Map(), geoPaths: [] } this.googleMapRef = createRef(); this.googleMap = undefined } componentDidMount() { const loadGoogleMapScript = document.createElement('script'); loadGoogleMapScript.src = 'https://maps.googleapis.com/maps/api/js?key=' + process.env.REACT_APP_API_KEY + '&libraries=place'; window.document.body.appendChild(loadGoogleMapScript); loadGoogleMapScript.addEventListener('load', () => { this.googleMap = this.createMap(); let bounds = this.drawMap(this.googleMap) this.googleMap.fitBounds(bounds); }); } createMap() { return new window.google.maps.Map(this.googleMapRef.current, { zoom: this.props.zoom, center: this.props.center, }) } addMarker(map, coordinates, bounds, type) { // TODO: firebase will provide coordinates as a GeoPoint --> convert to {lat, lng} // { lat: coordinates.lat(), lng: coordinates.lng() } bounds.extend(coordinates); var iconUrl; if (type === "flight") { iconUrl = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png" } else if (type === "event") { iconUrl = "http://maps.google.com/mapfiles/ms/icons/green-dot.png" } else { iconUrl = "http://maps.google.com/mapfiles/ms/icons/red-dot.png" } var newMarker = new window.google.maps.Marker({ position: coordinates, map: map, animation: window.google.maps.Animation.DROP, icon: { url: iconUrl } }) // zoom to marker when clicked newMarker.addListener('click', function () { map.setZoom(15); map.setCenter(newMarker.getPosition()); }); return newMarker; } addPath(map, path) { // dotted line var lineSymbol = { path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 4 }; let geoPath = new window.google.maps.Polyline({ path: path.path, strokeColor: '#FF0000', strokeOpacity: path.type === "normal" ? 0.0 : 1.0, icons: path.type === "normal" ? [{ icon: lineSymbol, offset: '0', repeat: '20px' }] : [], strokeWeight: 2, }); geoPath.setMap(map); return geoPath; } drawUnfinalizedMarkers(map, bounds) { return this.state.unfinalized.reduce((hashMap, item) => { hashMap.set(item.id, this.addMarker(map, item.coordinates, bounds, item.type)); return hashMap; }, new Map()) // return this.state.unfinalized.map((item) => { // this.addMarker(map, item.coordinates, bounds, item.type); // }) } drawPaths(map, bounds) { // Connect finalized components // First: separate into different segments: flight vs non-flight var paths = []; var curPath = []; var finalizedMarkers = new Map(); for (let i = 0; i < this.state.finalized.length; i++) { let item = this.state.finalized[i]; // found flight -> create new path segment if (item.type === "flight") { if (paths.length !== 0) { curPath.push(item.departureCoordinates) paths.push({ path: curPath, type: "normal" }); curPath = []; } curPath.push(item.departureCoordinates); curPath.push(item.arrivalCoordinates); paths.push({ path: curPath, type: "flight" }); // start of next path is arrival location of flight curPath = [item.arrivalCoordinates]; finalizedMarkers.set(item.id, this.addMarker(map, item.departureCoordinates, bounds, item.type)); finalizedMarkers.set(item.id, this.addMarker(map, item.arrivalCoordinates, bounds, item.type)); } else { curPath.push(item.coordinates); finalizedMarkers.set(item.id, this.addMarker(map, item.coordinates, bounds, item.type)); } } if (curPath.length > 1) { paths.push({ path: curPath, type: "normal" }); } return { geoPaths: paths.map((path) => { return this.addPath(map, path); }), finalizedMarkers: finalizedMarkers } } drawMap(map) { var bounds = new window.google.maps.LatLngBounds(); // unfinalized places are disconnected markers let unfinalizedMarkers = this.drawUnfinalizedMarkers(map, bounds); let pathArr = this.drawPaths(map, bounds); this.setState({ unfinalizedMarkers: unfinalizedMarkers, finalizedMarkers: pathArr.finalizedMarkers, geoPaths: pathArr.geoPaths }); return bounds; } render() { return ( <div id='map' ref={this.googleMapRef} /> ) } } export default MapComponent;
JavaScript
0
@@ -2673,24 +2673,97 @@ , bounds) %7B%0A + // construct hashmap with key: travelObject id, value: marker object%0A return t @@ -2942,138 +2942,8 @@ ())%0A - // return this.state.unfinalized.map((item) =%3E %7B%0A // this.addMarker(map, item.coordinates, bounds, item.type);%0A // %7D)%0A %7D%0A
897b17358e9ee24c72b199500b390afbb8764045
Remove redundant call for reset camera
src/gl/planeFeature.js
src/gl/planeFeature.js
////////////////////////////////////////////////////////////////////////////// /** * Create a new instance of planeFeature * * @class * Create a plane feature given a lower left corner point {geo.latlng} * and and upper right corner point {geo.latlng} * @param lowerleft * @param upperright * @returns {geo.planeFeature} */ ////////////////////////////////////////////////////////////////////////////// ggl.planeFeature = function(arg) { "use strict"; if (!(this instanceof ggl.planeFeature)) { return new ggl.planeFeature(arg); } geo.planeFeature.call(this, arg); var m_this = this, m_actor = null; //////////////////////////////////////////////////////////////////////////// /** * Gets the coordinates for this plane * * @returns {Array} [[origin], [upper left] [lower right]] */ //////////////////////////////////////////////////////////////////////////// this.coords = function() { return [this.origin(), this.upperLeft(), this.lowerRight()]; }; //////////////////////////////////////////////////////////////////////////// /** * Build this feature * * @override */ //////////////////////////////////////////////////////////////////////////// this._build = function() { var or = this.origin(), ul = this.upperLeft(), lr = this.lowerRight(), image = null, imageSrc = this.style().image, texture = null; if (m_actor) { this.renderer()._contextRenderer().removeActor(m_actor); } if (imageSrc) { image = new Image(); image.src = imageSrc; m_actor = vgl.utils.createTexturePlane(or[0], or[1], or[2], lr[0], lr[1], lr[2], ul[0], ul[1], ul[2], true); m_this.renderer()._contextRenderer().addActor(m_actor); image.onload = function() { texture = vgl.texture(); texture.setImage(image); m_actor.material().addAttribute(texture); m_this.renderer()._contextRenderer().resetCamera(); m_this.renderer()._render(); } } else { m_actor = vgl.utils.createPlane(or[0], or[1], or[2], ul[0], ul[1], ul[2], lr[0], lr[1], lr[2]); } this.buildTime().modified(); }; //////////////////////////////////////////////////////////////////////////// /** * Update * * @override */ //////////////////////////////////////////////////////////////////////////// this._update = function() { if (this.buildTime().getMTime() <= this.dataTime().getMTime()) { this._build(); } if (this.updateTime().getMTime() <= this.getMTime()) { // TODO Implement this } this.updateTime().modified(); }; return this; }; inherit(ggl.planeFeature, geo.planeFeature); // Now register it geo.registerFeature('webgl', 'planeFeature', ggl.planeFeature);
JavaScript
0
@@ -1952,68 +1952,8 @@ e);%0A - m_this.renderer()._contextRenderer().resetCamera();%0A
2dd02fa601324a52ee0509aec340fd02739c6625
add judgement for ns
lib/legacy.js
lib/legacy.js
var ElementType = require("domelementtype"); var isTag = exports.isTag = ElementType.isTag; exports.testElement = function(options, element){ for(var key in options){ if(!options.hasOwnProperty(key)); else if(key === "tag_name"){ if(!isTag(element) || !options.tag_name(element.name)){ return false; } } else if(key === "tag_type"){ if(!options.tag_type(element.type)) return false; } else if(key === "tag_contains"){ if(isTag(element) || !options.tag_contains(element.data)){ return false; } } else if(!element.attribs || !options[key](element.attribs[key])){ return false; } } return true; }; var Checks = { tag_name: function(name){ if(typeof name === "function"){ return function(elem){ return isTag(elem) && name(elem.name); }; } else if(name === "*"){ return isTag; } else { return function(elem) { return isTag(elem) && elem.name === name && !elem.ns; }; } }, tag_name_ns: function(href, name){ return function(elem) { if(!elem.doc || !isTag(elem) || elem.name !== name) return false; if(href == null && elem.ns == null) return true; var nsList = elem.doc.namespaces.hrefMap[href]; var isNSEqual = false; for(var i = 0; i < nsList.length; ++i) if(nsList[i] === elem.ns) isNSEqual = true; return isNSEqual; }; }, tag_type: function(type){ if(typeof type === "function"){ return function(elem){ return type(elem.type); }; } else { return function(elem){ return elem.type === type; }; } }, tag_contains: function(data){ if(typeof data === "function"){ return function(elem){ return !isTag(elem) && data(elem.data); }; } else { return function(elem){ return !isTag(elem) && elem.data === data; }; } } }; function getAttribCheck(attrib, value){ if(typeof value === "function"){ return function(elem){ return elem.attribs && value(elem.attribs[attrib]); }; } else { return function(elem){ return elem.attribs && elem.attribs[attrib] === value; }; } } function combineFuncs(a, b){ return function(elem){ return a(elem) || b(elem); }; } exports.getElements = function(options, element, recurse, limit){ var funcs = Object.keys(options).map(function(key){ var value = options[key]; return key in Checks ? Checks[key](value) : getAttribCheck(key, value); }); return funcs.length === 0 ? [] : this.filter( funcs.reduce(combineFuncs), element, recurse, limit ); }; exports.getElementById = function(id, element, recurse){ if(!Array.isArray(element)) element = [element]; return this.findOne(getAttribCheck("id", id), element, recurse !== false); }; exports.getElementsByTagName = function(name, element, recurse, limit){ return this.filter(Checks.tag_name(name), element, recurse, limit); }; exports.getElementsByTagNameNS = function(nsHref, name, element, recurse, limit){ return this.filter(Checks.tag_name_ns(nsHref, name), element, recurse, limit); }; exports.getElementsByTagType = function(type, element, recurse, limit){ return this.filter(Checks.tag_type(type), element, recurse, limit); };
JavaScript
0.000724
@@ -1167,16 +1167,71 @@ %5Bhref%5D;%0A +%09%09%09if(nsList == null && elem.ns != null) return false;%0A %09%09%09var i
c4b7f1d1627683875ad98b82d04ec67c4027266a
Update loki-storage.js
src/provider/loki-storage.js
src/provider/loki-storage.js
var WinJS = require('winjs'), base = require('./base'), ioc = require('../ioc'), log = require("../log"); var _constructor = function(options) { base.call(this, arguments); this._lokiStorageKey = "-lokiStorage.json"; this._storageProvider = ioc.getProvider("localStorage"); }; var instanceMembers = { loadDatabase: function(dbname, callback) { log.info("LokiStorage:loadDatabase"); var dbStorageKey = dbname + this._lokiStorageKey; this._storageProvider.get({ filename: dbStorageKey }, function(err, resp) { if (err) { if (err === 'does-not-exist') return callback(); return callback(err); } var resultStr = ""; if (!(typeof(resp.data) === 'string')) resultStr = JSON.stringify(resp.data); else resultStr = String(resp.data); return callback(resultStr); }); }, saveDatabase: function(dbname, dbstring, callback) { log.info("LokiStorage:saveDatabase"); var dbStorageKey = dbname + this._lokiStorageKey; var storageStr = ""; if (!(typeof(dbstring) === 'string')) storageStr = JSON.stringify(dbstring); else storageStr = String(dbstring); this._storageProvider.createOrUpdate({ fileName: dbStorageKey, data: storageStr }, function(err) { if (err) return callback(err); return callback(); }); } }; module.exports = WinJS.Class.derive(base, _constructor, instanceMembers);
JavaScript
0
@@ -353,36 +353,35 @@ back) %7B%0A log. -info +log (%22LokiStorage:lo @@ -976,12 +976,11 @@ log. -info +log (%22Lo
000705f6e8c90c6752fbb07ea5da287e010eec0d
fix child data access
lib/mailer.js
lib/mailer.js
'use strict'; // --- Dependencies --- var debug = require('debug')('arkivo:mailer'); var assert = require('assert'); var slice = Array.prototype.slice; var properties = Object.defineProperties; var config = require('arkivo/lib/config'); var common = require('arkivo/lib/common'); var extend = common.extend; var md5 = common.md5; var B = require('bluebird'); var co = B.coroutine; var nm = require('nodemailer'); var version = require('../package.json').version; /** * Arkivo Mailer. * * @class Mailer * @constructor */ function Mailer(options, sync) { assert(sync); assert(sync.subscription); this.options = extend({}, Mailer.defaults); if (config.has('mailer')) extend(this.options, config.get('mailer')); extend(this.options, options); this.sync = sync; } /** * Mailer default configuration. * * @property defaults * @type Object * @static */ Mailer.defaults = { from: '[email protected]', subject: 'Zotero Update', mimetypes: [ 'application/pdf' ] }; properties(Mailer.prototype, { /** * @property created * @type Array */ created: { get: function get$created() { return this.collect(this.sync.created); } }, /** * @property updated * @type Array */ updated: { get: function get$updated() { return this.collect(this.sync.updated); } }, transport: { get: function () { return nm.createTransport(this.options.transport); } }, name: { get: function () { return 'Arkivo-Mailer ' + version; } } }); /** * Send the given item. * * @method send * @return {Promise} */ Mailer.prototype.send = function (item) { this.debug('sending item %s...', item.key); return new B(function (resolve, reject) { this.transport.sendMail({ headers: { Mailer: this.name }, to: this.options.recipient, from: this.options.from, subject: this.options.subject, text: this.options.text, html: this.options.html, attachments: item.attachments }, function (error) { if (error) return reject(error); resolve(); }); }.bind(this)); }; /** * Downloads the item's attachment. * @method download * @return {Promise} */ Mailer.prototype.download = function (item) { this.debug('downloading attachment %s...', item.key); return this .sync .attachment(item) .then(function (message) { if (!message.data) throw Error('attachment is blank'); if (md5(message.data) !== item.data.md5) throw Error('attachment checksum mismatch'); return message.data; }); }; /** * Collect Zotero items with attachments that can * be sent by mail. * * @method collect * @param {Array} keys The list of Zotero keys to look at. * * @return {Promise<Array>} The collected items. */ Mailer.prototype.collect = co(function* (keys) { var i, ii, item, child, data, collection = []; for (i = 0, ii = keys.length; i < ii; ++i) { try { item = this.expand(keys[i]); if (!item) { this.debug('cannot expand "%s": item missing', keys[i]); continue; } // Duplicate items are possible, because child items are // expanded to their parents; therefore, if a sync session // includes an item and one or more of its children, we // might process the item multiple times! if (collection[item.key]) continue; // Skip items without attachments! if (!item.children) continue; child = this.select(item.children); if (!child) { this.debug('skipping "%s": no suitable attachments found', item.key); continue; } data = yield this.download(child); collection.push(this.convert(item, child, data)); } catch (error) { this.debug('failed to collect item: %s', error.message); debug(error.stack); continue; } } return collection; }); /** * Converts items to syntax used by the mailer. * * @method convert * @return Object The converted item. */ Mailer.prototype.convert = function (item, child, data) { return { attachments: [ { filename: child.filename, contentType: child.contentType, content: data } ] }; }; /** * Selects the first suitable attachment item. * * @method select * @param {Array} items * @return {Object} */ Mailer.prototype.select = function (items) { if (!items) return undefined; if (!items.length) return undefined; var i, ii, item, next; for (i = 0, ii = items.length; i < ii; ++i) { next = items[i]; if (next.data.itemType !== 'attachment') continue; if (next.data.linkMode !== 'imported_file') continue; if (this.options.mimetypes.indexOf(next.data.contentType) < 0) continue; if (item) { if (item.dateAdded < next.dateAdded) continue; } item = next; } return item; }; /** * Returns the Zotero item for key; if the item has * a parent, returns parent item instead. * * @method expand * @private */ Mailer.prototype.expand = function (key) { var item = this.sync.items[key]; if (item && item.data.parentItem) return this.expand(item.data.parentItem); return item; }; Mailer.prototype.debug = function (message) { debug.apply(null, [ '[%s] ' + message, this.sync.id ].concat(slice.call(arguments, 1))); return this; }; // --- Exports --- module.exports = Mailer;
JavaScript
0.000001
@@ -342,16 +342,44 @@ mon.md5; +%0Avar base64 = common.base64; %0A%0Avar B @@ -1842,22 +1842,26 @@ +'X- Mailer +' : this.n @@ -2103,24 +2103,30 @@ ction (error +, info ) %7B%0A if @@ -2156,16 +2156,71 @@ error);%0A +%0A // Todo: check mail was delivered to recipient%0A%0A re @@ -2225,16 +2225,20 @@ resolve( +info );%0A %7D @@ -4280,16 +4280,21 @@ : child. +data. filename @@ -4322,16 +4322,21 @@ : child. +data. contentT @@ -4357,20 +4357,56 @@ ontent: -data +base64(data),%0A encoding: 'base64' %0A %7D
7431bfd58c9e911ee56c602f9ad7ac2c12cfa335
changing to geo_lat_lon
lib/models.js
lib/models.js
"use strict" var puree = require('../index'), glob = require("glob"), debug = require('debug')('koala-puree:models'), waterline = require('waterline'), fdbsql = require("sails-fdbsql"); var DEFAULTCONFIG = { "base": "app/model/", adapters: { 'sails-fdbsql': fdbsql }, connections: { fdbsql: { adapter: 'sails-fdbsql' } } } function genModel(file, base, remove) { var name = file.substr(base.length, file.length-(base.length+3)); remove = remove === undefined ? false : remove; var path = require('path').join(process.cwd(),file), schema; if ( remove ) { delete require.cache[path]; } schema = require(path); schema.connection = 'fdbsql' schema.tableName = name.toLowerCase(); schema.collection = name; schema.identity = name; return schema; } var pureeorm = exports = module.exports = function(){ var orm; return { setup: function (app) { return new Promise(function(resolve, reject) { debug(`beginning model middleware`); var dburl; if ( !app._config.db || !app._config.db.url ) { let config = app._config.db || {} let username = config.username || "root"; let password = config.password || "root"; let host = config.host || "localhost"; let port = config.port || "15432"; let dbname = config.dbname || app._config.name; if ( !dbname ) { return reject("dbname or package name has to be provided"); } if ( app._app.env !== "production" ) { dbname = `${dbname}-${app._app.env}`; } dburl = `fdb://${username}:${password}@${host}:${port}/${dbname}`; } else { dburl = app._config.db.url } var config = require('extend')({},DEFAULTCONFIG); config.connections.fdbsql.url = dburl; orm = app._orm = new waterline(); var update = function(){ var fs = require('fs'); glob(config.base+"*.js", function (er, files) { if ( er ) { return reject(er); } var schemas = []; for ( var f of files ) { let schema = genModel(f, config.base, app._app.env !== "production") orm.loadCollection(require('waterline').Collection.extend(schema)) schemas.push(schema); debug(`loaded ${f} into app.models`); } debug(`initalizing orm`); orm.initialize(config, function(err, models) { if ( err ) { debug(`failed to initalize orm ${err}`); return reject(err); } // now lets call the special things for ( var i = 0; i < schemas.length; i++) { if ( require('util').isFunction(schemas[i].afterSchemaCreate)) { schemas[i] = (function(schema){ var ExtraSchema = { index: function(){ var args = arguments; return new Promise(function(resolve){ var columns = []; var collection = models.collections[schema.tableName], indexName = ['idx']; for(let column of args) { if ( require('util').isArray(column) ) { if ( "spatial" === column[0] ) { indexName.push(`z_${column[1]}_${column[2]}`); column = `z_order_lat_lon(${column[1]},${column[2]})`; } else { throw `${column[0]} is not a supported type`; } } else { indexName.push(column); } columns.push(column); } indexName = indexName.join("_"); columns = columns.join(","); var query = `CREATE INDEX ${indexName} ON ${schema.tableName}(${columns});`; debug(query); collection.query(query, function(err){ if ( err ) { return reject(err); } resolve(); }) }); } } var p = schema.afterSchemaCreate(ExtraSchema); delete schema.afterSchemaCreate; return p; })(schemas[i]); } else { schemas[i] = true; } } Promise.all(schemas).then(function(){ app.models = models.collections; debug(`completed initializaing orm`); if ( resolve ) { var tr = resolve; resolve = undefined; return tr();} }).catch(function(err){ reject(err); }) }); }) } update(); }); }, teardown: function (app) { return new Promise(function(resolve, reject){ debug(`beginning teardown`); app._orm.teardown(function(err){ debug(`completing teardown`); if ( err ) { return reject(err); } resolve(); }) }) } } };
JavaScript
0.999874
@@ -3074,15 +3074,11 @@ = %60 -z_order +geo _lat
56dd84e46a79d3ff851576b63973d1395914c553
remove [WARNING] and [ERROR]
lib/statis.js
lib/statis.js
var http = require('http') var socket = require('net') var mysql = require('mysql') var events = require('events'); var eventEmitter = new events.EventEmitter(); module.id = 'statis' var Statis = { // events: eventEmitter, notify: function(message) { eventEmitter.emit('result', message) // Statis.events.emit('result', message) }, doHttp: function(node) { var node_label = node.label var request = http.request( node.http, function(res) { request.destroy() if (res.statusCode >= 400) { Statis.notify({"status": "error", "label": node_label, "message": node_label + " [ERROR] Status " + res.statusCode}) } else { Statis.notify({"status": "success", "label": node_label, "message": node_label + " [OK]"}) } } ) request.setTimeout(2 * 1000, function() { request.destroy() Statis.notify({"status": "error", "label": node_label, "message": node_label + " [WARNING] Reached timeout"}) }) request.on('error', function(e) { Statis.notify({"status": "error", "label": node_label, "message": node_label + " [ERROR] " + e.message}) }) request.end() }, doSocket: function(node) { var node_label = node.label var s = socket.connect(node.socket.port, node.socket.host) s.on('connect', function() { s.destroy() Statis.notify({"status": "success", "label": node_label, "message": node_label + " [OK] "}) }).on('error', function(e) { Statis.notify({"status": "error", "label": node_label, "message": node_label + " [ERROR] " + e.message}) }) }, doMysql: function(node) { var node_label = node.label var connection = mysql.createConnection(node.mysql) connection.connect(function(err) { connection.destroy() if (!err) { Statis.notify({"status": "success", "label": node_label, "message": node_label + " [OK] "}) } else { Statis.notify({"status": "error", "label": node_label, "message": node_label + " [ERROR] " + err.message}) } }) } } module.exports.http = function(node) { Statis.doHttp(node) } module.exports.socket = function(node) { Statis.doSocket(node) } module.exports.mysql = function(node) { Statis.doMysql(node) } module.exports.on = function(event, listener) { eventEmitter.on(event, listener) } module.exports.removeListener = function(event, listener) { eventEmitter.removeListener(event, listener) }
JavaScript
0.000024
@@ -600,24 +600,16 @@ abel + %22 - %5BERROR%5D Status @@ -1892,32 +1892,24 @@ de_label + %22 - %5BERROR%5D %22 + err.mes
33450b00dbcc282df35a38a5b17aa9f98e71c8af
allow implementers to provide highWaterMark option
lib/stream.js
lib/stream.js
var util = require('util'); var async = require('async'); var Transform = require('readable-stream').Transform; /** * @param {Object} options * @param {Number} [options.concurrency] * @constructor */ function ParallelWriteStream(options) { options = options || {}; this._concurrency = typeof options.concurrency == 'undefined' ? 1 : options.concurrency; this._storage = []; delete options.concurrency; options.highWaterMark = this._concurrency; options.objectMode = true; Transform.call(this, options); this.once('pipe', function () { this.resume(); }.bind(this)); } util.inherits(ParallelWriteStream, Transform); ParallelWriteStream.prototype._transform = function (doc, encoding, callback) { this.push(doc); this._storage.push(doc); if (this._storage.length >= this._concurrency) { this._flush(callback); } else { callback(null); } }; ParallelWriteStream.prototype._flush = function (callback) { var storage = this._storage; this._storage = []; async.each(storage, this._save.bind(this), function (err) { process.nextTick(function () { callback(err); }); }); }; ParallelWriteStream.prototype._save = function (doc, callback) { callback(new Error('_save method is not implemented yet.')); }; module.exports = exports = ParallelWriteStream;
JavaScript
0
@@ -430,16 +430,41 @@ erMark = + options.highWaterMark %7C%7C this._c
dea8a4ab090ac2395314ee12ef93604ecb2063dd
add blog link to nav
packages/vx-demo/components/nav.js
packages/vx-demo/components/nav.js
import Link from 'next/link'; import GithubButton from 'react-github-button'; export default () => ( <div className='nav'> <div className='nav-inner'> <Link href="/"> <div className="logo" /> </Link> <ul> <Item href="/">Home</Item> <Item href="/docs">Docs</Item> <Item href="/gallery">Gallery</Item> </ul> <GithubButton type="stargazers" namespace="hshoff" repo="vx" /> </div> <style jsx>{` .nav-inner { width: 95vw; margin: 0 auto; display: flex; flex-direction: row; align-items: center; justify-content: center; } .nav { display: flex; flex-direction: row; flex: 1; align-items: center; justify-content: center; padding: 0 10px; font-size: 14px; z-index: 3; position: fixed; top: 0; left: 0; right: 0; margin: 0; background: #ffffff; } ul { list-style-type: none; display: flex; flex: 1; flex-direction: row; padding: 0; margin: 0; color: white; justify-content: flex-start; align-items: center; } @media (max-width: 600px) { .github-buttons { display: none; } .Item { float: left; } } `}</style> </div> ) const Item = ({ href, children, className }) => ( <li className="Item"> <Link prefetch href={href}> <a className={className}>{ children }</a> </Link> <style jsx>{` .Item a { display: inline-block; padding: 10px; text-decoration: none; color: #fc2e1c; font-weight: 600; } .Item .github { font-weight: 600; color: #fc2e1c; } @media (max-width: 600px) { .Item { display: block; float: left; } .Item .github { margin-top: 0; } } `}</style> </li> )
JavaScript
0
@@ -346,24 +346,84 @@ lery%3C/Item%3E%0A + %3CItem href=%22https://medium.com/vx-code%22%3EBlog%3C/Item%3E%0A %3C/ul%3E%0A
a19154bc3a74bd1450e199c5bc49365d0f63cfc8
copy typings to lib #466
packages/web/scripts/copy-types.js
packages/web/scripts/copy-types.js
const path = require('path'); const fse = require('fs-extra'); // eslint-disable-line const glob = require('glob'); // eslint-disable-line function typescriptCopy(from, to) { const files = glob.sync('**/*.d.ts', { cwd: from }); const cmds = files.map(file => fse.copy(path.resolve(from, file), path.resolve(to, file))); return Promise.all(cmds); } async function run() { const from = path.resolve(__dirname, '../src'); await typescriptCopy(from, path.resolve(__dirname, '../lib')); } run();
JavaScript
0
@@ -204,10 +204,8 @@ */*. -d. ts',
e720ee05045e715b84d1edcad6dea4f9b74703f8
Call google analytics event logger
src/hook/controller.js
src/hook/controller.js
/* eslint camelcase: 0 */ const { get, assign } = require('lodash') const { accessTokenForInstallation, branchHasFixup, createCommitStatus } = require('../github') const { log } = require('../logging') /* POST Github hook * Accepts a webhook call from Github details a Git Push. * Analyses the push and sets a status to indicate if the * branch if belongs to has a fixup commit * 'success' indicates no fixups * 'failure' indicates branch contains a fixup */ async function postHook (req, res, next) { try { const eventType = get(req, 'headers.x-github-event', 'n/a') if (eventType !== 'push') { log({ text: `Invalid event, ignoring: ${eventType}` }) return res.status(202).send('Invalid event, ignoring') } const pushData = req.body const { default_branch: defaultBranch, full_name: repoName } = pushData.repository const branch = pushData.ref.substr(11) const headCommit = get(pushData, 'head_commit.id') const installationId = get(pushData, 'installation.id') if (!headCommit) { log({ text: 'Ignoring event, no commits to analyse' }) return res.status(202).send('Ignoring event, no commits to analyse') } if (branch === defaultBranch) { log({ text: 'Ignoring event, default branch' }) return res.status(202).send('Ignoring event, default branch') } log({ text: 'Processing hook', fields: { 'Repository': repoName, 'Branch': branch } }) const token = await accessTokenForInstallation(installationId) const hasFixup = await branchHasFixup({ token, repoName, branch, defaultBranch }) const baseStatus = { token, repoName, sha: headCommit } const status = hasFixup ? assign({}, baseStatus, { state: 'failure', description: 'Branch contains fixup!' }) : assign({}, baseStatus, { state: 'success', description: 'No fixups found' }) log({ text: status.description, status: status.state, fields: { 'Repository': repoName, 'Branch': branch } }) await createCommitStatus(status) } catch (error) { await log({ error }) return res.status(500).send(error.message) } res.status(200).send('Webhook handled successfully') } module.exports = { postHook }
JavaScript
0
@@ -176,16 +176,26 @@ st %7B log +, logEvent %7D = req @@ -1903,24 +1903,68 @@ nd' %7D)%0A%0A +await createCommitStatus(status)%0A%0A await log(%7B%0A @@ -2120,33 +2120,29 @@ ait -createCommitStatus +logEvent (status +.state )%0A
fae0d8889e4abddca8d91695440a12b3322f5030
Fix get group permissions in authorize
src/hooks/authorize.js
src/hooks/authorize.js
import { Forbidden } from 'feathers-errors'; import fp from 'mostly-func'; import { AceBuilder, Aces, toMongoQuery } from 'playing-permissions'; import { getHookDataAsArray } from '../helpers'; function getPermissions(user) { if (user) { const groupPermissions = fp.flatMap(fp.path(['group', 'permissions']), user.groups || []); return fp.concat(groupPermissions, user.permissions || []); } return []; } function defineAcesFor(permissions, { TypeKey = 'type' }) { const builder = new AceBuilder(); for (const permission of permissions) { builder.allow(permission); } return new Aces(builder.rules, { TypeKey }); } export default function authorize(name = null, opts = {}) { const TypeKey = opts.TypeKey || 'type'; return async function(context) { if (context.type !== 'before') { throw new Error(`The 'authorize' hook should only be used as a 'before' hook.`); } let params = fp.assign({ query: {} }, context.params); // If it was an internal call then skip this hook if (!params.provider) return context; const action = params.__action || context.method; const serviceName = name || context.path; const userPermissions = getPermissions(params.user); const userAces = defineAcesFor(userPermissions , { TypeKey }); const throwDisallowed = (action, resources) => { let disallow = true; // reverse loop to check inheritance for (let i = resources.length - 1; i >= 0; i--) { if (!resources[i]) break; const resource = fp.assoc(TypeKey, resources[i][TypeKey] || serviceName, resources[i]); disallow = disallow && userAces.disallow(action, resource); if (!resource.inherited) break; } if (disallow) { throw new Forbidden(`You are not allowed to ${action} ${resources[0] && resources[0].id}, with ${context.path}/${context.id}`); } }; if (context.method === 'create') { throwDisallowed('create', [context.data]); } // find, multi update/patch/remove if (!context.id) { const rules = userAces.rulesFor(action, serviceName); const query = toMongoQuery(rules); if (query) { params.query = fp.assign(params.query, query); } else { params.query.$limit = 0; // TODO skip the mongoose query } context.params = params; return context; } // get, update, patch, remove, action else { // get the resource by id for checking permissions const resource = await context.service.get(context.id, { query: { $select: 'ancestors,*' } }); throwDisallowed(action, fp.concat(resource && resource.ancestors || [], [resource])); return context; } }; }
JavaScript
0
@@ -281,17 +281,23 @@ (fp.path -( +Or(%5B%5D, %5B'group' @@ -2256,64 +2256,283 @@ -params.query.$limit = 0; // TODO skip the mongoose query +context.result = %7B%0A message: 'No data found for your account permissions',%0A metadata: %7B%0A total: 0,%0A limit: context.params.query.$limit %7C%7C 10,%0A skip: context.params.query.$skip %7C%7C 0,%0A %7D,%0A data: %5B%5D%0A %7D; %0A
fc33aef8241cdb1e19dc9ea66c78ed812ccdde42
Allow calling all master methods from worker
lib/worker.js
lib/worker.js
/*! * Cluster - Worker * Copyright(c) 2011 LearnBoost <[email protected]> * MIT Licensed */ /** * Module dependencies. */ var EventEmitter = require('events').EventEmitter , spawn = require('child_process').spawn , binding = process.binding('net') , utils = require('./utils') , net = require('net'); // COMPAT: net.Socket = net.Stream; /** * Node binary. */ var node = process.execPath; /** * Initialize a new `Worker` with the given `master`. * * Signals: * * - `SIGINT` immediately exit * - `SIGTERM` immediately exit * - `SIGQUIT` graceful exit * * @param {Master} master * @api private */ var Worker = module.exports = function Worker(master) { this.master = master; this.server = master.server; this.uid = Date.now() + Math.random(); }; /** * Inherit from `EventEmitter.prototype`. */ Worker.prototype.__proto__ = EventEmitter.prototype; /** * Worker is a receiver. */ require('./mixins/receiver')(Worker.prototype); /** * Start worker. * * @api private */ Worker.prototype.start = function(){ var self = this , call = this.master.call; // proxy to provide worker id this.master.call = function(){ var args = utils.toArray(arguments); args.unshift(self.id); return call.apply(this, args); }; // stdin this.stdin = new net.Socket(0, 'unix'); this.stdin.setEncoding('ascii'); this.stdin.on('data', function(chunk){ self.frame(chunk, self.uid); }); this.stdin.resume(); // demote usr/group if (this.server) { this.server.on('listening', function(){ var group = self.options.group; if (group) process.setgid(group); var user = self.options.user; if (user) process.setuid(user); }); // stdin this.stdin.on('fd', this.server.listenFD.bind(this.server)); } // signal handlers process.on('SIGINT', this.destroy.bind(this)); process.on('SIGTERM', this.destroy.bind(this)); process.on('SIGQUIT', this.close.bind(this)); // conditionally handle uncaughtException if (!process.listeners('uncaughtException').length) { process.on('uncaughtException', function(err){ // stderr for logs console.error(err.stack || err.message); // report exception self.master.call('workerException', err); // exit process.nextTick(function(){ self.destroy(); }); }); } }; /** * Received connect event, set the worker `id` * and `options`. * * @param {String} id * @param {Object} options * @api private */ Worker.prototype.connect = function(id, options){ this.options = options; // worker id this.id = id; // timeout this.timeout = options.timeout; // title process.title = options['worker title'].replace('{n}', id); // notify master of connection this.master.call('connect'); }; /** * Immediate shutdown. * * @api private */ Worker.prototype.destroy = function(){ process.exit(); }; /** * Perform graceful shutdown. * * @api private */ Worker.prototype.close = function(){ var self = this , server = this.server; if (server && server.connections) { // stop accepting server.watcher.stop(); // check pending connections setInterval(function(){ self.master.call('workerWaiting', server.connections); server.connections || self.destroy(); }, 2000); // timeout if (this.timeout) { setTimeout(function(){ self.master.call('workerTimeout', self.timeout); self.destroy(); }, this.timeout); } } else { this.destroy(); } }; /** * Spawn the worker with the given `id`. * * @param {Number} id * @return {Worker} for chaining * @api private */ Worker.prototype.spawn = function(id){ var fds = binding.socketpair() , customFds = [fds[0]].concat(this.master.customFds) , env = {}; // merge env for (var key in process.env) { env[key] = process.env[key]; } this.id = env.CLUSTER_WORKER = id; // spawn worker process this.proc = spawn( node , this.master.cmd , { customFds: customFds, env: env }); // unix domain socket for ICP + fd passing this.sock = new net.Socket(fds[1], 'unix'); // saving file descriptors for later use this.fds = fds; return this; }; /** * Invoke worker's `method` (called from Master). * * @param {String} method * @param {...} args * @api private */ Worker.prototype.call = function(method){ this.sock.write(utils.frame({ args: utils.toArray(arguments, 1) , method: method }), 'ascii'); };
JavaScript
0.997724
@@ -1212,24 +1212,132 @@ arguments);%0A + // Allow calling master methods that don't take worker as first argument%0A if (args%5B0%5D !== false) %7B%0A args.uns @@ -1351,16 +1351,22 @@ lf.id);%0A + %7D%0A retu
5f1ec2cfe856b505c38fdaa655cef4cdf41242d2
make the compiler respect the NODE_PATH environment variable
compiler.js
compiler.js
var fs = require('fs'), path = require('path'), util = require('./lib/util') module.exports = { compile: compileFile, compileHTML: compileHTMLFile, compileCode: compileCode, dontAddClosureForModule: dontAddClosureForModule, dontIncludeModule: dontIncludeModule, addPath: addPath, addFile: addFile, addReplacement: addReplacement } var _ignoreClosuresFor = [] function dontAddClosureForModule(searchFor) { _ignoreClosuresFor.push(searchFor) return module.exports } var _ignoreModules = [] function dontIncludeModule(module) { _ignoreModules.push(module) return module.exports } function addReplacement(searchFor, replaceWith) { util.addReplacement.apply(util, arguments) return module.exports } function addPath() { util.addPath.apply(util, arguments) return module.exports } function addFile() { util.addFile.apply(util, arguments) return module.exports } /* api *****/ function compileFile(filePath, opts) { filePath = path.resolve(filePath) opts = util.extend(opts, { basePath:path.dirname(filePath), toplevel:true }) var code = util.getCode(filePath) return _compile(code, opts, filePath) } function compileCode(code, opts) { opts = util.extend(opts, { basePath:process.cwd(), toplevel:true }) return _compile(code, opts, '<code passed into compiler.compile()>') } function compileHTMLFile(filePath, opts) { var html = fs.readFileSync(filePath).toString() while (match = html.match(/<script src="\/require\/([\/\w\.]+)"><\/script>/)) { var js = compileFile(match[1].toString(), opts) var BACKREFERENCE_WORKAROUND = '____________backreference_workaround________' js = js.replace('\$\&', BACKREFERENCE_WORKAROUND) html = html.replace(match[0], '<script>'+js+'</script>') html = html.replace(BACKREFERENCE_WORKAROUND, '\$\&') } return html } var _compile = function(code, opts, mainModule) { var code = 'var __require__ = {}, require=function(){}\n' + _compileModule(code, opts.basePath, mainModule) if (opts.minify === false) { return code } // TODO use uglifyjs' beautifier? if (opts.max_line_length == null) { opts.max_line_length = 120 } var uglifyJS = require('uglify-js') var ast = uglifyJS.parser.parse(code, opts.strict_semicolons), ast = uglifyJS.uglify.ast_mangle(ast, opts) ast = uglifyJS.uglify.ast_squeeze(ast, opts) var result = uglifyJS.uglify.gen_code(ast, opts) if (opts.max_line_length) { result = uglifyJS.uglify.split_lines(result, opts.max_line_length) } return result } /* util ******/ var _compileModule = function(code, pathBase, mainModule) { var modules = [mainModule] _replaceRequireStatements(mainModule, code, modules, pathBase) code = _concatModules(modules) code = _minifyRequireStatements(code, modules) return code } var _minifyRequireStatements = function(code, modules) { for (var i=0, modulePath; modulePath = modules[i]; i++) { var escapedPath = modulePath.replace(/\//g, '\\/').replace('(','\\(').replace(')','\\)'), regex = new RegExp('__require__\\["'+ escapedPath +'"\\]', 'g') code = code.replace(regex, '__require__["_'+ i +'"]') } return code } var _pathnameGroupingRegex = /require\s*\(['"]([\w\/\.-]*)['"]\)/ var _replaceRequireStatements = function(modulePath, code, modules, pathBase) { var requireStatements = util.getRequireStatements(code) if (!requireStatements.length) { modules[modulePath] = code return } for (var i=0, requireStatement; requireStatement = requireStatements[i]; i++) { var rawModulePath = requireStatement.match(_pathnameGroupingRegex)[1], subModulePath = util.resolve(rawModulePath, pathBase).replace(/\.js$/, '') if (!subModulePath) { throw new Error("Require Compiler Error: Cannot find module '"+ rawModulePath +"' (in '"+ modulePath +"')") } code = code.replace(requireStatement, '__require__["' + subModulePath + '"].exports') if (!modules[subModulePath]) { modules[subModulePath] = true var newPathBase = path.dirname(subModulePath), newModuleCode = util.getCode(subModulePath + '.js') _replaceRequireStatements(subModulePath, newModuleCode, modules, newPathBase) modules.push(subModulePath) } } modules[modulePath] = code } var _concatModules = function(modules) { var code = function(modulePath) { for (var i=0; i<_ignoreModules.length; i++) { if (modulePath.match(_ignoreModules[i])) { return '' } } var ignoreClosure = false for (var i=0; i<_ignoreClosuresFor.length; i++) { if (modulePath.match(_ignoreClosuresFor[i])) { ignoreClosure = true break } } return [ ignoreClosure ? '' : ';(function() {', ' // ' + modulePath, ' var module = __require__["'+modulePath+'"] = {exports:{}}, exports = module.exports;', modules[modulePath], ignoreClosure ? '' : '})()' ].join('\n') } var moduleDefinitions = [] for (var i=1, modulePath; modulePath = modules[i]; i++) { moduleDefinitions.push(code(modulePath)) } moduleDefinitions.push(code(modules[0])) // __main__ return moduleDefinitions.join('\n\n') } var _repeat = function(str, times) { if (times < 0) { return '' } return new Array(times + 1).join(str) }
JavaScript
0.000003
@@ -3077,24 +3077,74 @@ urn code%0A%7D%0A%0A +var _nodePaths = process.env.NODE_PATH.split(':')%0A var _pathnam @@ -3197,17 +3197,16 @@ %5B'%22%5D%5C)/%0A -%0A var _rep @@ -3498,19 +3498,19 @@ %7B%0A%09%09var -raw +sub ModulePa @@ -3518,135 +3518,65 @@ h = -requireStatement.match(_pathnameGroupingRegex)%5B1%5D,%0A%09%09%09subModulePath = util.resolve(rawModulePath, pathBase).replace(/%5C.js$/, '' +util.resolveRequireStatement(requireStatement, modulePath )%0A%0A%09 @@ -3921,16 +3921,16 @@ ePath),%0A + %09%09%09%09newM @@ -3971,16 +3971,8 @@ Path - + '.js' )%0A%09%09
9ade886fc2644829ba95c4d8a01f54d1a9e4a458
Make link to webpack context explanation permanent
compiler.js
compiler.js
/* eslint-disable prefer-arrow-callback, func-names, class-methods-use-this */ import loader from 'graphql-tag/loader'; export default class GraphQLCompiler { processFilesForTarget(files) { // Fake webpack context // @see https://github.com/apollographql/graphql-tag/blob/master/loader.js#L43 const context = { cacheable() {}, }; files .forEach(file => { const path = `${file.getPathInPackage()}.js`; const content = file.getContentsAsString().trim(); try { const data = loader.call(context, content); file.addJavaScript({ data, path, }); } catch (e) { if (e.locations) { file.error({ message: e.message, line: e.locations[0].line, column: e.locations[0].column, }); return null; } throw e; } }); } }
JavaScript
0
@@ -280,14 +280,48 @@ lob/ -master +57a258713acecde5ebef0c5771a975d6446703c7 /loa
d8646e8fb70b4b87f7ed36e9de09330e07c395ae
Use disableViewBox option
src/react/components/Line.js
src/react/components/Line.js
import LeaderLine from 'leader-line'; import React from 'react'; function shimPointAnchor (point) { return point instanceof Element ? LeaderLine.pointAnchor( point, { x: 0, y: 0 } ) : LeaderLine.pointAnchor( document.body, point ) ; } export default class Line extends React.Component { componentWillUnmount () { if (this.line) { const { svg } = this.line.getProps(); const { parentNode } = svg; if (parentNode) parentNode.removeChild(svg); this.line.remove(); } } initLine() { const { start, end } = this.props; const startPoint = shimPointAnchor(start); const endPoint = shimPointAnchor(end); this.line = new LeaderLine({ start: startPoint, end: endPoint, path: 'fluid', dash: true, }); const { svg } = this.line.getProps(); const { parentNode } = this.mockSvg; svg.leaderLine = this.line; if (parentNode) parentNode.appendChild(svg); if (typeof(this.props.onLoad) === 'function') this.props.onLoad(this.line); } shouldComponentUpdate (nextProps) { if (!this.line && this.mockSvg && this.props.start && this.props.end) { this.initLine(); return false; } if (this.line) { if (this.props.start != nextProps.start) { this.line.start = shimPointAnchor(nextProps.start); } if (this.props.end != nextProps.end) { this.line.end = shimPointAnchor(nextProps.end); } this.line.position(false); } return false; } render() { return <svg ref={ ref => this.mockSvg = ref } />; } }
JavaScript
0.000001
@@ -784,16 +784,44 @@ : true,%0A + disableViewBox: true,%0A %7D);%0A @@ -1523,21 +1523,16 @@ osition( -false );%0A %7D
ca52f84ee58dc21855ac7033bf553795d7c488a7
Use window.addEventListener() to support multiple keydown listeners
assets/crx/js/embed.js
assets/crx/js/embed.js
// Get webview element var webview = document.getElementById('webview'); // Get find box elements var findBox = document.getElementById('find-box'); var findInput = document.getElementById('find-text'); // Get dialog box elements var dialogBox = document.getElementById("dialog-box"); var dialogOk = document.getElementById("dialog-box-ok"); var dialogText = document.getElementById("dialog-box-text"); var dialogInput = document.getElementById("dialog-box-input"); var dialogCancel = document.getElementById("dialog-box-cancel"); // Initial page zoom factor var zoomFactor = 1.0; // Listen to keydown event window.onkeydown = function (e) { // Check whether CTRL on Windows or CMD on Mac is pressed var modifierActive = (navigator.platform.startsWith('Mac')) ? e.metaKey : e.ctrlKey; var altModifierActive = (navigator.platform.startsWith('Mac')) ? e.ctrlKey : e.altKey; // Enter full screen mode (CMD/ALT + CTRL + F) if (modifierActive && altModifierActive && e.keyCode == 'F'.charCodeAt(0)) { // Get current focused window var window = chrome.app.window.current(); // Check if currently full screen if (!window.isFullscreen()) { // Enter full screen mode window.fullscreen(); } else { // Exit full screen mode window.restore(); } // Prevent other shortcut checks return; } // Refresh the page (CTRL/CMD + R) if (modifierActive && e.keyCode == 'R'.charCodeAt(0)) { webview.reload(); } // Find in page (CTRL/CMD + F) if (modifierActive && e.keyCode == 'F'.charCodeAt(0)) { // Show the find box findBox.style.display = 'block'; // Focus the find input findInput.focus(); // Select all existing text (if any) findInput.select(); } // Copy URL (CTRL/CMD + L) if (modifierActive && e.keyCode == 'L'.charCodeAt(0)) { // Copy webview source to clipboard copyToClipboard(webview.src, 'text/plain'); } // Print (CTRL/CMD + P) if (modifierActive && e.keyCode == 'P'.charCodeAt(0)) { webview.print(); } // Zoom in (CTRL/CMD +) if (modifierActive && e.keyCode == 187) { zoomFactor += 0.1; webview.setZoom(zoomFactor); } // Zoom out (CTRL/CMD -) if (modifierActive && e.keyCode == 189) { zoomFactor -= 0.1; // Don't let zoom drop below 0.2 if (zoomFactor <= 0.2) { zoomFactor = 0.2; } webview.setZoom(zoomFactor); } // Reset zoom (CTRL/CMD + 0) if (modifierActive && e.keyCode == '0'.charCodeAt(0)) { zoomFactor = 1.0; webview.setZoom(zoomFactor); } }; // Listen for webview load event webview.addEventListener('contentload', function () { // Execute JS script within webview webview.executeScript({ // Send a Chrome runtime message every time the keydown event is fired within webview code: `window.addEventListener('keydown', function (e) { chrome.runtime.sendMessage({ event: 'keydown', params: { ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, keyCode: e.keyCode } }); });`}); }); // Listen for Chrome runtime messages chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) { // Check for keydown event if (request.event === 'keydown') { // Invoke the local window's keydown event handler window.onkeydown(request.params); } } ); // Find input: listen to keydown event findInput.addEventListener('keyup', function (e) { // Search for current input text webview.find(findInput.value, { matchCase: false }); // Escape key if (e.keyCode === 27) { webview.stopFinding(); findBox.style.display = 'none'; } }); function copyToClipboard(str, mimetype) { // Listen for 'oncopy' event document.oncopy = function (event) { event.clipboardData.setData(mimetype, str); event.preventDefault(); }; // Execute browser command 'Copy' document.execCommand("Copy", false, null); } // Custom alert dialog popup var dialogController; // Listen for dialog cancellation button click dialogCancel.addEventListener('click', function () { // Send cancellation dialogController.cancel(); // Hide dialog box dialogBox.style.display = 'none'; }); // Listen for dialog OK button click dialogOk.addEventListener('click', function () { // Send OK value dialogController.ok(dialogInput.value); // Hide dialog box dialogBox.style.display = 'none'; }); // Listen for dialog event on webview for new alert dialogs webview.addEventListener('dialog', function (e) { // Prevent default logic e.preventDefault(); // Extract dialog type and text var text = e.messageText; var dialogType = e.messageType; // Keep a reference to dialog object dialogController = e.dialog; // Set dialog text dialogText.innerHTML = text; // Reset dialog input dialogInput.value = ''; // Hide it by default dialogInput.style.display = 'none'; // Alert? if (dialogType == 'alert') { // Hide cancel button dialogCancel.style.display = 'none'; } else { // Another type of dialog, show cancel button dialogCancel.style.display = 'block'; // Prompt? if (dialogType == 'prompt') { // Show text input field dialogInput.style.display = 'block'; } } // Show dialog box dialogBox.style.display = 'block'; });
JavaScript
0.000001
@@ -616,19 +616,35 @@ dow. -on +addEventListener(' keydown - = +', fun @@ -2759,16 +2759,17 @@ %0A %7D%0A%7D +) ;%0A%0A// Li
7d09f05c966b32a06b4704034c63376e69361003
add resolve alias for assets and components
template/build/webpack.base.conf.js
template/build/webpack.base.conf.js
var path = require('path') var config = require('../config') var cssLoaders = require('./css-loaders') var projectRoot = path.resolve(__dirname, '../') module.exports = { entry: { app: './src/main.js' }, output: { path: config.build.assetsRoot, publicPath: config.build.assetsPublicPath, filename: '[name].js' }, resolve: { extensions: ['', '.js', '.vue'], fallback: [path.join(__dirname, '../node_modules')], alias: { 'src': path.resolve(__dirname, '../src') } }, resolveLoader: { fallback: [path.join(__dirname, '../node_modules')] }, module: { preLoaders: [ { test: /\.vue$/, loader: 'eslint', include: projectRoot, exclude: /node_modules/ }, { test: /\.js$/, loader: 'eslint', include: projectRoot, exclude: /node_modules/ } ], loaders: [ { test: /\.vue$/, loader: 'vue' }, { test: /\.js$/, loader: 'babel', include: projectRoot, exclude: /node_modules/ }, { test: /\.json$/, loader: 'json' }, { test: /\.html$/, loader: 'vue-html' }, { test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url', query: { limit: 10000, name: path.join(config.build.assetsSubDirectory, '[name].[ext]?[hash:7]') } } ] }, vue: { loaders: cssLoaders() }, eslint: { formatter: require('eslint-friendly-formatter') } }
JavaScript
0
@@ -497,16 +497,140 @@ ../src') +,%0A 'assets': path.resolve(__dirname, '../src/assets'),%0A 'components': path.resolve(__dirname, '../src/components') %0A %7D%0A
ff56bf3f3fe1541ada0e7105cad1bdae1d6dc20c
Revert "Move section creation logic to Section instead of inside Collapse constructor"
src/jquery.collapse.js
src/jquery.collapse.js
/* * Collapse plugin for jQuery * -- * source: http://github.com/danielstocks/jQuery-Collapse/ * site: http://webcloud.se/jQuery-Collapse * * @author Daniel Stocks (http://webcloud.se) * Copyright 2013, Daniel Stocks * Released under the MIT, BSD, and GPL Licenses. */ (function($) { // Constructor function Collapse (el, options) { options = options || {}; var _this = this, query = options.query || "> :even"; $.extend(_this, { $el: el, options : options, sections: [], isAccordion : options.accordion || false, db : options.persist ? jQueryCollapseStorage(el[0].id) : false }); // Figure out what sections are open if storage is used _this.states = _this.db ? _this.db.read() : []; // For every pair of elements in given // element, create a section _this.$el.find(query).each(function() { _this.sections.push(new Section($(this), _this)); }); // Capute ALL the clicks! (function(scope) { _this.$el.on("click", "[data-collapse-summary]", $.proxy(_this.handleClick, scope)); }(_this)); } Collapse.prototype = { handleClick: function(e) { e.preventDefault(); var sections = this.sections, l = sections.length; while(l--) { if($.contains(sections[l].$summary[0], e.target)) { sections[l].toggle(); break; } } }, open : function(eq) { if(isFinite(eq)) return this.sections[eq].open(); $.each(this.sections, function() { this.open(); }); }, close: function(eq) { if(isFinite(eq)) return this.sections[eq].close(); $.each(this.sections, function() { this.close(); }); } }; // Section constructor function Section($el, parent) { var _this = this; $.extend(_this, { isOpen : false, $summary : $el .attr("data-collapse-summary", "") .wrapInner('<a href="#"/>'), $details : $el.next(), options: parent.options, parent: parent }); // Check current state of section var state = parent.states[_this._index()]; if(state === 0) { _this.$summary.removeClass("open"); } if(state === 1) { _this.$summary.addClass("open"); } _this.$summary.hasClass("open") ? _this.open(true) : _this.close(true); } Section.prototype = { toggle : function() { if(this.isOpen) this.close(); else this.open(); }, close: function(bypass) { this._changeState("close", bypass); }, open: function(bypass) { var _this = this; if(_this.options.accordion && !bypass) { $.each(_this.parent.sections, function() { this.close(); }); } _this._changeState("open", bypass); }, _index: function() { return $.inArray(this, this.parent.sections); }, _changeState: function(state, bypass) { var _this = this; _this.isOpen = state == "open"; if($.isFunction(_this.options[state]) && !bypass) { _this.options[state].apply(_this.$details); } else { if(_this.isOpen) _this.$details.show(); else _this.$details.hide(); } _this.$summary.removeClass("open close").addClass(state); _this.$details.attr("aria-hidden", state == "close"); _this.parent.$el.trigger(state, _this); if(_this.parent.db) { _this.parent.db.write(_this._index(), _this.isOpen); } } }; // Expose in jQuery API $.fn.extend({ collapse: function(options, scan) { var nodes = (scan) ? $("body").find("[data-collapse]") : $(this); return nodes.each(function() { var settings = (scan) ? {} : options, values = $(this).attr("data-collapse") || ""; $.each(values.split(" "), function(i,v) { if(v) settings[v] = true; }); new Collapse($(this), settings); }); } }); //jQuery DOM Ready $(function() { $.fn.collapse(false, true); }); // Expose constructor to // global namespace jQueryCollapse = Collapse; jQueryCollapseSection = Section; })(window.jQuery);
JavaScript
0
@@ -886,57 +886,497 @@ -_this.sections.push(new Section($(this), _this)); +var section = new Section($(this), _this);%0A _this.sections.push(section);%0A%0A // Check current state of section%0A var state = _this.states%5Bsection._index()%5D;%0A if(state === 0) %7B%0A section.$summary.removeClass(%22open%22);%0A %7D%0A if(state === 1) %7B%0A section.$summary.addClass(%22open%22);%0A %7D%0A%0A // Show or hide accordingly%0A if(section.$summary.hasClass(%22open%22)) %7B%0A section.open(true);%0A %7D%0A else %7B%0A section.close(true);%0A %7D %0A @@ -2241,38 +2241,16 @@ rent) %7B%0A - var _this = this;%0A $.ex @@ -2246,33 +2246,32 @@ %7B%0A $.extend( -_ this, %7B%0A is @@ -2470,316 +2470,15 @@ ent%0A + %7D); -%0A%0A // Check current state of section%0A var state = parent.states%5B_this._index()%5D;%0A%0A if(state === 0) %7B%0A _this.$summary.removeClass(%22open%22);%0A %7D%0A if(state === 1) %7B%0A _this.$summary.addClass(%22open%22);%0A %7D%0A%0A _this.$summary.hasClass(%22open%22) ? _this.open(true) : _this.close(true); %0A %7D
b0e586c9e5f28df9b6e856e748c17bd812ede17b
Use include for es6-promise polyfill (#1027)
src/ie-compat/ie.js
src/ie-compat/ie.js
/* eslint-disable no-extend-native */ require('es6-promise').polyfill() if (!Number.isInteger) { Number.isInteger = function (value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value } } (function (arr) { arr.forEach(function (item) { if (item.hasOwnProperty('remove')) { return } Object.defineProperty(item, 'remove', { configurable: true, enumerable: true, writable: true, value: function remove () { return this.parentNode ? this.parentNode.removeChild(this) : this } }) }) })([Element.prototype, CharacterData.prototype, DocumentType.prototype]) if (!Array.prototype.findIndex) { Object.defineProperty(Array.prototype, 'findIndex', { value (predicate) { 'use strict' if (this == null) { throw new TypeError('Array.prototype.findIndex called on null or undefined') } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function') } var list = Object(this) var length = list.length >>> 0 var thisArg = arguments[1] for (var i = 0; i < length; i++) { if (predicate.call(thisArg, list[i], i, list)) { return i } } return -1 } }) }
JavaScript
0
@@ -36,16 +36,36 @@ */%0A%0A -require( +import * as es6Promise from 'es6 @@ -73,17 +73,28 @@ promise' -) +%0A%0Aes6Promise .polyfil
e757c027294cf84ce51f56e5224fc02de4c1604c
Revert "make Dom accessible in Context for plugins"
src/js/base/Context.js
src/js/base/Context.js
define([ 'jquery', 'summernote/base/core/func', 'summernote/base/core/list', 'summernote/base/core/dom' ], function ($, func, list, dom) { /** * @param {jQuery} $note * @param {Object} options * @return {Context} */ var Context = function ($note, options) { var self = this; var ui = $.summernote.ui; this.memos = {}; this.modules = {}; this.layoutInfo = {}; this.options = options; this.dom = dom; /** * create layout and initialize modules and other resources */ this.initialize = function () { this.layoutInfo = ui.createLayout($note, options); this._initialize(); $note.hide(); return this; }; /** * destroy modules and other resources and remove layout */ this.destroy = function () { this._destroy(); $note.removeData('summernote'); ui.removeLayout($note, this.layoutInfo); }; /** * destory modules and other resources and initialize it again */ this.reset = function () { var disabled = self.isDisabled(); this.code(dom.emptyPara); this._destroy(); this._initialize(); if (disabled) { self.disable(); } }; this._initialize = function () { // add optional buttons var buttons = $.extend({}, this.options.buttons); Object.keys(buttons).forEach(function (key) { self.memo('button.' + key, buttons[key]); }); var modules = $.extend({}, this.options.modules, $.summernote.plugins || {}); // add and initialize modules Object.keys(modules).forEach(function (key) { self.module(key, modules[key], true); }); Object.keys(this.modules).forEach(function (key) { self.initializeModule(key); }); }; this._destroy = function () { // destroy modules with reversed order Object.keys(this.modules).reverse().forEach(function (key) { self.removeModule(key); }); Object.keys(this.memos).forEach(function (key) { self.removeMemo(key); }); }; this.code = function (html) { var isActivated = this.invoke('codeview.isActivated'); if (html === undefined) { this.invoke('codeview.sync'); return isActivated ? this.layoutInfo.codable.val() : this.layoutInfo.editable.html(); } else { if (isActivated) { this.layoutInfo.codable.val(html); } else { this.layoutInfo.editable.html(html); } $note.val(html); this.triggerEvent('change', html); } }; this.isDisabled = function () { return this.layoutInfo.editable.attr('contenteditable') === 'false'; }; this.enable = function () { this.layoutInfo.editable.attr('contenteditable', true); this.invoke('toolbar.activate', true); }; this.disable = function () { // close codeview if codeview is opend if (this.invoke('codeview.isActivated')) { this.invoke('codeview.deactivate'); } this.layoutInfo.editable.attr('contenteditable', false); this.invoke('toolbar.deactivate', true); }; this.triggerEvent = function () { var namespace = list.head(arguments); var args = list.tail(list.from(arguments)); var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')]; if (callback) { callback.apply($note[0], args); } $note.trigger('summernote.' + namespace, args); }; this.initializeModule = function (key) { var module = this.modules[key]; module.shouldInitialize = module.shouldInitialize || func.ok; if (!module.shouldInitialize()) { return; } // initialize module if (module.initialize) { module.initialize(); } // attach events if (module.events) { dom.attachEvents($note, module.events); } }; this.module = function (key, ModuleClass, withoutIntialize) { if (arguments.length === 1) { return this.modules[key]; } this.modules[key] = new ModuleClass(this); if (!withoutIntialize) { this.initializeModule(key); } }; this.removeModule = function (key) { var module = this.modules[key]; if (module.shouldInitialize()) { if (module.events) { dom.detachEvents($note, module.events); } if (module.destroy) { module.destroy(); } } delete this.modules[key]; }; this.memo = function (key, obj) { if (arguments.length === 1) { return this.memos[key]; } this.memos[key] = obj; }; this.removeMemo = function (key) { if (this.memos[key] && this.memos[key].destroy) { this.memos[key].destroy(); } delete this.memos[key]; }; this.createInvokeHandler = function (namespace, value) { return function (event) { event.preventDefault(); self.invoke(namespace, value || $(event.target).closest('[data-value]').data('value')); }; }; this.invoke = function () { var namespace = list.head(arguments); var args = list.tail(list.from(arguments)); var splits = namespace.split('.'); var hasSeparator = splits.length > 1; var moduleName = hasSeparator && list.head(splits); var methodName = hasSeparator ? list.last(splits) : list.head(splits); var module = this.modules[moduleName || 'editor']; if (!moduleName && this[methodName]) { return this[methodName].apply(this, args); } else if (module && module[methodName] && module.shouldInitialize()) { return module[methodName].apply(module, args); } }; return this.initialize(); }; return Context; });
JavaScript
0
@@ -428,28 +428,8 @@ ons; -%0A this.dom = dom; %0A%0A
d4e2d545388d58b5ede62a9f8b07ca4b9b1bb576
improve docs
src/js/common/index.js
src/js/common/index.js
/**************************************************** * * All the code in this file will be bundled into a * 'common.js' file. By separating code that won't * change much as you push updates into production, * users' browsers can keep the common.js bundle * cached (as long as no changes were made to it), * allowing for faster repeat page load speeds. * ****************************************************/ window.libs = {} // Import the following libraries in other files like this: // // const { $, throttle } = libs // libs.$ = libs.jQuery = require('jquery') libs.sanitizeHTML = require('sanitize-html') // Dump static code here require('./helpers.js') require('./errors.js') require('./scroll-animations.js')
JavaScript
0.000004
@@ -512,72 +512,32 @@ t %7B -$, throttle %7D = libs%0A//%0Alibs.$ = libs.jQuery = require('jquery') +sanitizeHTML %7D = libs%0A// %0Alib
c21c28800fcee74c0c1ce341aa4316c2dd9a927e
add contextmenu on input field
src/js/pages/Layout.js
src/js/pages/Layout.js
import React, { Component } from 'react'; import { observer, inject } from 'mobx-react'; import { ipcRenderer } from 'electron'; import Loader from 'components/Loader'; import Snackbar from 'components/Snackbar'; import Header from './Header'; import Footer from './Footer'; import Login from './Login'; import UserInfo from './UserInfo'; import AddFriend from './AddFriend'; import NewChat from './NewChat'; import Members from './Members'; import AddMember from './AddMember'; import Forward from './Forward'; @inject(stores => ({ isLogin: () => !!stores.session.auth, loading: stores.session.loading, message: stores.snackbar.text, show: stores.snackbar.show, close: () => stores.snackbar.toggle(false), })) @observer export default class Layout extends Component { render() { if (!this.props.isLogin()) { return <Login />; } ipcRenderer.send('logined'); return ( <div> <Snackbar close={this.props.close} show={this.props.show} text={this.props.message} /> <Loader show={this.props.loading} /> <Header location={this.props.location} /> <div style={{ height: 'calc(100vh - 100px)', overflow: 'hidden', overflowY: 'auto', background: `rgba(255,255,255,.8)`, }}> {this.props.children} </div> <Footer location={this.props.location} /> <UserInfo /> <AddFriend /> <NewChat /> <Members /> <AddMember /> <Forward /> </div> ); } }
JavaScript
0.000001
@@ -103,16 +103,24 @@ Renderer +, remote %7D from @@ -794,16 +794,1164 @@ onent %7B%0A + componentDidMount() %7B%0A var templates = %5B%0A %7B%0A label: 'Undo',%0A role: 'undo',%0A %7D, %7B%0A label: 'Redo',%0A role: 'redo',%0A %7D, %7B%0A type: 'separator',%0A %7D, %7B%0A label: 'Cut',%0A role: 'cut',%0A %7D, %7B%0A label: 'Copy',%0A role: 'copy',%0A %7D, %7B%0A label: 'Paste',%0A role: 'paste',%0A %7D, %7B%0A type: 'separator',%0A %7D, %7B%0A label: 'Select all',%0A role: 'selectall',%0A %7D,%0A %5D;%0A var menu = new remote.Menu.buildFromTemplate(templates);%0A%0A document.body.addEventListener('contextmenu', e =%3E %7B%0A e.preventDefault();%0A%0A let node = e.target;%0A%0A while (node) %7B%0A if (node.nodeName.match(/%5E(input%7Ctextarea)$/i) %7C%7C node.isContentEditable) %7B%0A menu.popup(remote.getCurrentWindow());%0A break;%0A %7D%0A node = node.parentNode;%0A %7D%0A %7D);%0A %7D%0A%0A rend
682cd20a3fcf2560dd9f5cd901684176ba826d78
Remove TITLE from interpolated strings
src/languages/swift.js
src/languages/swift.js
/* Language: Swift Author: Chris Eidhof <[email protected]> */ function(hljs) { var SWIFT_KEYWORDS = 'class deinit enum extension func import init let protocol static ' + 'struct subscript typealias var break case continue default do ' + 'else fallthrough if in for return switch where while as dynamicType ' + 'is new super self Self Type __COLUMN__ __FILE__ __FUNCTION__ ' + '__LINE__ associativity didSet get infix inout left mutating none ' + 'nonmutating operator override postfix precedence prefix right set '+ 'unowned unowned safe unsafe weak willSet'; var TYPE = { className: 'type', begin: '\\b[A-Z][\\w\']*', relevance: 0 }; var BLOCK_COMMENT = { className: 'comment', begin: '/\\*', end: '\\*/', contains: [hljs.PHRASAL_WORDS_MODE, 'self'] }; var SUBST = { className: 'subst', begin: /\\\(/, end: '\\)', keywords: SWIFT_KEYWORDS, contains: [] // assigned later }; var QUOTE_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, { contains: [SUBST, hljs.BACKSLASH_ESCAPE] }); SUBST.contains = [hljs.C_NUMBER_MODE, hljs.TITLE_MODE, QUOTE_STRING_MODE]; return { keywords: { keyword: SWIFT_KEYWORDS, literal: 'true false nil' }, contains: [ QUOTE_STRING_MODE, hljs.C_LINE_COMMENT_MODE, BLOCK_COMMENT, TYPE, hljs.C_NUMBER_MODE, { className: 'func', beginKeywords: 'func', end: /(\{)|(\->)/, excludeEnd: true, contains: [ hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/}), { className: 'generics', begin: /\</, end: /\>/, illegal: /\>/ }, { className: 'params', begin: /\(/, end: /\)/, contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE ], illegal: /["'\(]/ } ], illegal: /\[|%/ }, ] }; }
JavaScript
0.000129
@@ -1110,25 +1110,8 @@ ODE, - hljs.TITLE_MODE, QUO
98ca05e0670bf499056f69e5ee9e9e479199bf23
fix lint error
src/adapters/sequelize.js
src/adapters/sequelize.js
import _ from 'lodash' import Promise from 'bluebird' import util from 'util' export const ID_SEPARATOR = '--' export const PATH_SEPARATOR = '.' export const VALUE_SEPARATOR = ',' export function idQuery(model, id) { const fields = primaryKeys(model) const values = id.split(ID_SEPARATOR) if (fields.length !== values.length) { throw new Error('The number of ID parameter values does not match the number of ID fields') } return _.zipObject(fields, values) } function primaryKeys(model) { return _.keys(model.primaryKeys) } export function id(model, document) { const fields = primaryKeys(model) const values = _.map(fields, field => document[field]) return values.join(ID_SEPARATOR) } export function type(model) { return _.kebabCase(model.name) } function foreignKeys(model) { return _.reject( _.map(model.attributes, (attribute, key) => { return _.has(attribute, 'references') ? key : undefined }), _.isEmpty ) } function attributeKeys(model) { const foreign = foreignKeys(model) const primary = primaryKeys(model) const excludeKeys = primary.concat(foreign) return _.without(_.keys(model.attributes), ...excludeKeys) } export function attributes(model, document) { const keys = attributeKeys(model) return _.pick(document, keys) } function relationshipKeys(model) { return _.keys(model.associations) } export function relationships(model, document) { const relationships = {} const keys = relationshipKeys(model) _.forEach(keys, key => { if (!document[key]) { return } relationships[key] = document[key] }) return relationships } export function hasAssociation(model, path) { const parts = path.split(PATH_SEPARATOR) let result = true let part while (part = parts.shift()) { const target = `associations.${part}.target` if (!_.has(model, target)) { result = false break; } model = _.get(model, target) } return result } export function getAssociationModel(model, path) { const parts = path.split(PATH_SEPARATOR) let part while (part = parts.shift()) { const target = `associations.${part}.target` if (!_.has(model, target)) { throw new Error('Association does not exist') } model = _.get(model, target) } return model } export function isIncluded(model, path, include) { const params = _.filter(include.split(VALUE_SEPARATOR), value => { return hasAssociation(model, value) }) let result = false _.forEach(params, value => { const includeParts = value.split(PATH_SEPARATOR) const pathParts = path.split(PATH_SEPARATOR) let match = true for (let i = 0; i < pathParts.length; i += 1) { if (includeParts[i] !== pathParts[i]) { match = false break } } if (match) { result = match return false } }) return result } export function includePath(model, path) { const parts = path.split(PATH_SEPARATOR) const part = parts.shift() const associationModel = getAssociationModel(model, part) if (parts.length === 0) { return { model: associationModel, as: part } } return { model: associationModel, as: part, include: [includePath(associationModel, parts.join(PATH_SEPARATOR))] } } function merge(paths, include) { return paths.reduce((include, path) => { const exists = include.find(element => element.model === path.model && element.as === path.as) if (!exists) { include.push(path) return include } if (!_.isArray(exists.include)) { exists.include = [] } if (_.isArray(path.include)) { exists.include.push(...path.include) } exists.include = merge(exists.include, []) return include }, include) } export function include(model, include) { if (!_.isString(include)) { throw new Error('"include" must be string') } include = include.split(VALUE_SEPARATOR) const paths = include.map(path => includePath(model, path)) return merge(paths, []) } export function setRelationship({model, document, path, resourceIdentifiers, transaction}) { if (!_.isArray(resourceIdentifiers)) { resourceIdentifiers = [resourceIdentifiers] } const associationModel = getAssociationModel(model, path) // TODO support composite primary keys const ids = _.map(resourceIdentifiers, resourceIdentifier => resourceIdentifier.id) const associationType = model.associations[path].associationType return associationModel .findAll({ where: {id: {$in: ids}}, transaction }) .then(relatedDocuments => { // TODO sequelize docs say we should be able todo sth like this document.set('projects', documents) switch (associationType) { case 'HasOne': return document[`set${_.capitalize(path)}`](relatedDocuments.shift(), {transaction}) case 'HasMany': return document[`set${_.capitalize(path)}`](relatedDocuments, {transaction}) default: console.warn('Associations different than "HasOne" and "HasMany" are not supported') } }) }
JavaScript
0.000164
@@ -1896,17 +1896,16 @@ break -; %0A %7D%0A
6f9cd7c548b09971f7830bec637bd36551b61352
Allow custom measure assignment function.
src/aggregate/measures.js
src/aggregate/measures.js
var util = require('../util'); var stats = require('../stats'); var countmap = require('./countmap'); var types = { "count": measure({ name: "count", set: "this.cell.num" }), "nulls": measure({ name: "nulls", set: "this.cell.num - this.cell.valid" }), "valid": measure({ name: "valid", set: "this.cell.valid" }), "data": measure({ name: "data", init: "this.data = [];", add: "this.data.push(t);", rem: "this.data.splice(this.data.indexOf(t), 1);", set: "this.data", idx: -1 }), "distinct": measure({ name: "distinct", init: "this.distinct = new this.map();", add: "this.distinct.add(v);", rem: "this.distinct.rem(v);", set: "this.distinct.size()", idx: -1 }), "sum": measure({ name: "sum", init: "this.sum = 0;", add: "this.sum += v;", rem: "this.sum -= v;", set: "this.sum" }), "mean": measure({ name: "mean", init: "this.mean = 0;", add: "var d = v - this.mean; this.mean += d / this.cell.num;", rem: "var d = v - this.mean; this.mean -= d / this.cell.num;", set: "this.mean" }), "var": measure({ name: "var", init: "this.dev = 0;", add: "this.dev += d * (v - this.mean);", rem: "this.dev -= d * (v - this.mean);", set: "this.dev / (this.cell.num-1)", req: ["mean"], idx: 1 }), "varp": measure({ name: "varp", set: "this.dev / this.cell.num", req: ["var"], idx: 2 }), "stdev": measure({ name: "stdev", set: "Math.sqrt(this.dev / (this.cell.num-1))", req: ["var"], idx: 2 }), "stdevp": measure({ name: "stdevp", set: "Math.sqrt(this.dev / this.cell.num)", req: ["var"], idx: 2 }), "median": measure({ name: "median", set: "this.stats.median(this.data, this.get)", req: ["data"], idx: 3 }), "argmin": measure({ name: "argmin", add: "if (v < this.min) this.argmin = t;", rem: "this.argmin = null;", set: "this.argmin || this.data[this.stats.extent.index(this.data, this.get)[0]]", req: ["min", "data"], idx: 3 }), "argmax": measure({ name: "argmax", add: "if (v > this.max) this.argmax = t;", rem: "this.argmax = null;", set: "this.argmax || this.data[this.stats.extent.index(this.data, this.get)[1]]", req: ["max", "data"], idx: 3 }), "min": measure({ name: "min", init: "this.min = +Infinity;", add: "if (v < this.min) this.min = v;", rem: "this.min = null;", set: "this.min != null ? this.min : this.stats.extent(this.data, this.get)[0]", req: ["data"], idx: 4 }), "max": measure({ name: "max", init: "this.max = -Infinity;", add: "if (v > this.max) this.max = v;", rem: "this.max = null;", set: "this.max != null ? this.max : this.stats.extent(this.data, this.get)[1]", req: ["data"], idx: 4 }) }; function measure(base) { return function(out) { var m = util.extend({init:"", add:"", rem:"", idx:0}, base); m.out = out || base.name; return m; }; } function resolve(agg) { function collect(m, a) { (a.req || []).forEach(function(r) { if (!m[r]) collect(m, m[r] = types[r]()); }); return m; } var map = agg.reduce( collect, agg.reduce(function(m, a) { return (m[a.name] = a, m); }, {}) ); var all = []; for (var k in map) all.push(map[k]); all.sort(function(a,b) { return a.idx - b.idx; }); return all; } function compile(agg, accessor) { var all = resolve(agg), ctr = "this.tuple = t; this.cell = c; c.valid = 0;", add = "if (!this.valid(v)) return; this.cell.valid++;", rem = "if (!this.valid(v)) return; this.cell.valid--;", set = "var t = this.tuple;"; all.forEach(function(a) { if (a.idx < 0) { ctr = a.init + ctr; add = a.add + add; rem = a.rem + rem; } else { ctr += a.init; add += a.add; rem += a.rem; } }); agg.forEach(function(a) { set += "this.assign(t,'"+a.out+"',"+a.set+");"; }); set += "return t;"; ctr = Function("c", "t", ctr); ctr.prototype.assign = assign; ctr.prototype.add = Function("t", "var v = this.get(t);" + add); ctr.prototype.rem = Function("t", "var v = this.get(t);" + rem); ctr.prototype.set = Function(set); ctr.prototype.get = accessor; ctr.prototype.mod = mod; ctr.prototype.map = countmap; ctr.prototype.stats = stats; ctr.prototype.valid = util.isNotNull; return ctr; } function assign(x, name, val) { x[name] = val; } function mod(v_new, v_old) { if (v_old === undefined || v_old === v_new) return; this.rem(v_old); this.add(v_new); }; types.create = compile; module.exports = types;
JavaScript
0
@@ -3442,21 +3442,20 @@ nction c -ompil +reat e(agg, a @@ -3461,16 +3461,25 @@ accessor +, mutator ) %7B%0A va @@ -4096,16 +4096,27 @@ assign = + mutator %7C%7C assign; @@ -4663,13 +4663,12 @@ = c -ompil +reat e;%0Am
91db74b669d4e815b8b05fea58ddb4a3d8000009
fix exception if this.options is null
aurelia-bootstrap-tagsinput/src/abp-tags-input.js
aurelia-bootstrap-tagsinput/src/abp-tags-input.js
import {inject, bindable, bindingMode, DOM} from 'aurelia-framework'; import $ from 'jquery'; import 'bootstrap-tagsinput/dist/bootstrap-tagsinput'; import {globalExtraOptions, globalPickerOptions} from './picker-global-options'; @inject(Element) export class AbpTagsInputCustomElement { @bindable({defaultBindingMode: bindingMode.twoWay}) element; @bindable({defaultBindingMode: bindingMode.twoWay}) value; // plugin own variables @bindable bootstrapVersion = globalExtraOptions.bootstrapVersion; @bindable placeholder = ''; // picker options @bindable options; // events (from the View) @bindable onBeforeItemAdd; @bindable onBeforeItemRemove; @bindable onItemAdded; @bindable onItemAddedOnInit; @bindable onItemRemoved; // variables events = {}; methods = {}; options = {}; suppressValueChanged; constructor(elm) { this.elm = elm; // ensure the element exposes a "focus" method for Aurelia-Validation elm.focus = () => this.input.focus(); } attached() { // reference to the DOM element this.domElm = $(this.elm).find('input'); // Bootstrap 3 & 4 have different class names //if tagClass isn't yet configured we will define the tagClass depending on the version let pickerOptions = this.options || {}; if (!this.options.tagClass) { pickerOptions.tagClass = this.bootstrapVersion === 3 ? 'label label-info' : 'badge badge-info'; } // create TagsInput this.applyExposeEvents(); this.exposeMethods(); // finally create the tagsinput with all options pickerOptions = Object.assign({}, globalPickerOptions, pickerOptions); this.domElm.tagsinput(pickerOptions); // expose the element object to the outside // this will be useful for calling events/methods/options from the outside this.element = { events: this.events, options: this.options, methods: this.methods }; } /** * Apply/expose tagsinput events * Each event has 2 ways of triggering an event (from the View as an attribute or from the ViewModel has a function call) */ applyExposeEvents() { this.domElm.on('beforeItemAdd', (e) => { if (typeof this.onBeforeItemAdd === 'function') { this.onBeforeItemAdd(e); } if (typeof this.events.onBeforeItemAdd === 'function') { this.events.onBeforeItemAdd(e); } }); this.domElm.on('beforeItemRemove', (e) => { if (typeof this.onBeforeItemRemove === 'function') { this.onBeforeItemRemove(e); } if (typeof this.events.onBeforeItemRemove === 'function') { this.events.onBeforeItemRemove(e); } }); this.domElm.on('itemAdded', (e) => { // refresh the value attribute (except when we explicitly don't want it) if (!e.options || !e.options.preventRefresh) { this.suppressValueChanged = true; this.value = this.domElm.tagsinput('items'); } if (typeof this.onItemAdded === 'function') { this.onItemAdded(e); } if (typeof this.events.onItemAdded === 'function') { this.events.onItemAdded(e); } }); this.domElm.on('itemAddedOnInit', (e) => { if (typeof this.onItemAddedOnInit === 'function') { this.onItemAddedOnInit(e); } if (typeof this.events.onItemAddedOnInit === 'function') { this.events.onItemAddedOnInit(e); } }); this.domElm.on('itemRemoved', (e) => { // refresh the value attribute (except when we explicitly don't want it) if (!e.options || !e.options.preventRefresh) { this.suppressValueChanged = true; this.value = this.domElm.tagsinput('items'); } if (typeof this.onItemRemoved === 'function') { this.onItemRemoved(e); } if (typeof this.events.onItemRemoved === 'function') { this.events.onItemRemoved(e); } }); } /** * forward "blur" events to the custom element * As described in Aurelia-Validation * https://www.danyow.net/aurelia-validation-alpha/ */ blur() { const event = DOM.createCustomEvent('blur'); this.elm.dispatchEvent(event); } /** * Expose tagsinput methods */ exposeMethods() { let methods = { add: (value) => this.domElm.tagsinput('add', value), destroy: () => this.domElm.tagsinput('destroy'), focus: () => this.domElm.tagsinput('focus'), input: () => { return this.domElm.tagsinput('input'); }, refresh: () => this.domElm.tagsinput('refresh'), remove: (value) => this.domElm.tagsinput('remove', value), removeAll: () => { this.suppressValueChanged = true; this.domElm.tagsinput('removeAll'); this.value = this.domElm.tagsinput('items'); } }; this.methods = methods; } detached() { this.domElm.tagsinput('destroy'); } /** A simple array compare */ areEqualArray(arr1, arr2) { if (arr1 === null && arr2 === null) { return true; } if (!Array.isArray(arr1) || !Array.isArray(arr2) || (arr1.length !== arr2.length)) { return false; } for (let i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) { return false; } } return true; } /** * because of a bug which still has an open issue on Github for the `refresh` not working correctly * https://github.com/bootstrap-tagsinput/bootstrap-tagsinput/issues/98 * we need to `removeAll` and then loop on each new item to add them back as new tag * however we want to avoid recursive call on valueChanged by using preventRefresh flag & comparing split values * @param newValue * @param oldValue */ valueChanged(newValue, oldValue) { // tagsinput deals with the values as csv, while the value could also be an array of values // let's make them all on the same type as array of string which will be easier to deal with let newValueSplit = (typeof newValue === 'string') ? newValue.split(',') : newValue; let oldValueSplit = (typeof oldValue === 'string') ? oldValue.split(',') : oldValue; // check the newValue vs oldValue but also the split result // because in some cases we might have tagsinput saying the value is "tag1, tag2" while the newValue is ["tag1", "tag2"] // which are equivalent and so we check that too if (newValue && this.domElm && (newValue !== oldValue) && !this.areEqualArray(newValueSplit, oldValueSplit)) { if (this.suppressValueChanged) { this.suppressValueChanged = false; return; } if (!this.suppressValueChanged) { this.domElm.tagsinput('removeAll'); if (Array.isArray(newValue)) { newValue.forEach(value => this.domElm.tagsinput('add', value, {preventRefresh: true})); } else { this.domElm.tagsinput('add', newValue, {preventRefresh: true}); } } } } }
JavaScript
0.998306
@@ -1289,22 +1289,23 @@ if (! -this.o +pickerO ptions.t @@ -1866,22 +1866,23 @@ ptions: -this.o +pickerO ptions,%0A
218c58f002b92d3b6d5a49b4f22ea2ccc9b43cd2
Remove unneeded code
redux/src/main/renderer/registries/electron.js
redux/src/main/renderer/registries/electron.js
import { remote } from 'electron' export const twitterCredential = remote.getGlobal('twitterCredential');remote.getGlobal('twitterCredential'); export const credential = remote.getGlobal('credential');
JavaScript
0.000018
@@ -103,46 +103,8 @@ l'); -remote.getGlobal('twitterCredential'); %0Aexp
cdf64fb60bdd79545eb8056d3e83cee47659be0e
Remove unused dependencies
backend/authenticatedroutes/gitHubProxyHelpers.js
backend/authenticatedroutes/gitHubProxyHelpers.js
const config = require('../../config'); const https = require('https'); const url = require('url'); const request = require('request'); const GITHUB_API_ROOT = 'https://api.github.com'; // const getlocalAppRootUrl = request => { // return process.env.NODE_ENV == 'production' // ? url.format({ // protocol: 'https', // request.protocol returns http for now since the node server itself is only using http. However the api is used over https thanks to azure / IIS // host: request.hostname, // // port: request.port, // pathname: '' // }) // : 'https://localhost:3000'; // hard coded value in development because the request came through the webpack dev server on a different port and via https. // }; const getProxyRequestOptions = url => ({ url: GITHUB_API_ROOT + url.replace('/api', ''), headers: { Authorization: `token ${config.github.botToken}` //,"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36" ,"accept-encoding": "identity", } }); // const rewriteResponseHeaders = (request, response) => { // if (response.headers.link) { // response.headers.link = response.headers.link.replace(GITHUB_API_ROOT, getlocalAppRootUrl(request) + '/api'); // console.log(`Request App: Rewritten response.headers.link: ${JSON.stringify(response.headers.link)}`); // } else { // console.log(`Request App: response.headers.link falsy, nothing to rewrite`); // } // }; const genericErrorHandler = (error, response, body) => { if (error) { if (error.code === 'ECONNREFUSED') { console.error('Refused connection'); } else if (error.code === 'ETIMEDOUT') { console.error('Connection timed out'); } else { throw error; } } }; // const validateRepository = (organisation, repo, projects) => { // if (projects.filter(p => p.organisation == organisation && p.repository == repo).length == 0) { // console.error(`Request App: Repository not found : ${organisation}/${repo}`); // return false; // } else { // console.log(`Request App: Valid repository: ${organisation}/${repo}`); // return true; // } // }; module.exports = { getProxyRequestOptions, //rewriteResponseHeaders, genericErrorHandler//, //validateRepository };
JavaScript
0.000002
@@ -43,2296 +43,779 @@ nst -https = require('https');%0Aconst url = require('url');%0Aconst request = require('request');%0A%0Aconst GITHUB_API_ROOT = 'https://api.github.com';%0A%0A// const getlocalAppRootUrl = request =%3E %7B%0A// return process.env.NODE_ENV == 'production'%0A// ? url.format(%7B%0A// protocol: 'https', // request.protocol returns http for now since the node server itself is only using http. However the api is used over https thanks to azure / IIS%0A// host: request.hostname,%0A// // port: request.port,%0A// pathname: ''%0A// %7D)%0A// : 'https://localhost:3000'; // hard coded value in development because the request came through the webpack dev server on a different port and via https.%0A// %7D;%0A%0Aconst getProxyRequestOptions = url =%3E (%7B%0A url: GITHUB_API_ROOT + url.replace('/api', ''),%0A headers: %7B%0A Authorization: %60token $%7Bconfig.github.botToken%7D%60%0A //,%22user-agent%22: %22Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36%22%0A ,%22accept-encoding%22: %22identity%22,%0A %7D%0A%7D);%0A%0A// const rewriteResponseHeaders = (request, response) =%3E %7B%0A// if (response.headers.link) %7B%0A// response.headers.link = response.headers.link.replace(GITHUB_API_ROOT, getlocalAppRootUrl(request) + '/api');%0A// console.log(%60Request App: Rewritten response.headers.link: $%7BJSON.stringify(response.headers.link)%7D%60);%0A// %7D else %7B%0A// console.log(%60Request App: response.headers.link falsy, nothing to rewrite%60);%0A// %7D%0A// %7D;%0A%0Aconst genericErrorHandler = (error, response, body) =%3E %7B%0A if (error) %7B%0A if (error.code === 'ECONNREFUSED') %7B%0A console.error('Refused connection');%0A %7D else if (error.code === 'ETIMEDOUT') %7B%0A console.error('Connection timed out');%0A %7D else %7B%0A throw error;%0A %7D%0A %7D%0A%7D;%0A%0A// const validateRepository = (organisation, repo, projects) =%3E %7B%0A// if (projects.filter(p =%3E p.organisation == organisation && p.repository == repo).length == 0) %7B%0A// console.error(%60Request App: Repository not found : $%7Borganisation%7D/$%7Brepo%7D%60);%0A// return false;%0A// %7D else %7B%0A// console.log(%60Request App: Valid repository: $%7Borganisation%7D/$%7Brepo%7D%60);%0A// return true;%0A// %7D%0A// %7D;%0A%0Amodule.exports = %7B%0A getProxyRequestOptions,%0A //rewriteResponseHeaders,%0A genericErrorHandler//,%0A //validateRepository +url = require('url');%0A%0Aconst GITHUB_API_ROOT = 'https://api.github.com';%0A%0Aconst getProxyRequestOptions = url =%3E (%7B%0A url: GITHUB_API_ROOT + url.replace('/api', ''),%0A headers: %7B%0A Authorization: %60token $%7Bconfig.github.botToken%7D%60%0A //,%22user-agent%22: %22Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36%22%0A ,%22accept-encoding%22: %22identity%22,%0A %7D%0A%7D);%0A%0Aconst genericErrorHandler = (error, response, body) =%3E %7B%0A if (error) %7B%0A if (error.code === 'ECONNREFUSED') %7B%0A console.error('Refused connection');%0A %7D else if (error.code === 'ETIMEDOUT') %7B%0A console.error('Connection timed out');%0A %7D else %7B%0A throw error;%0A %7D%0A %7D%0A%7D;%0A%0Amodule.exports = %7B%0A getProxyRequestOptions,%0A genericErrorHandler %0A%7D;
8a7091e4f0af12ec178218e177ddb657eb6daea7
Add missing space
projects/bugpack-registry/js/src/BugPackKey.js
projects/bugpack-registry/js/src/BugPackKey.js
//------------------------------------------------------------------------------- // Annotations //------------------------------------------------------------------------------- //@Package('bugpack') //@Export('BugPackKey') //@Require('Class') //@Require('Obj') //------------------------------------------------------------------------------- // Common Modules //------------------------------------------------------------------------------- var bugpack = require('bugpack').context(); //------------------------------------------------------------------------------- // BugPack //------------------------------------------------------------------------------- var Class = bugpack.require('Class'); var Obj = bugpack.require('Obj'); //------------------------------------------------------------------------------- // Declare Class //------------------------------------------------------------------------------- var BugPackKey= Class.extend(Obj, { //------------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------------- /** * @constructs * @param {string} key */ _constructor: function(key) { this._super(); //------------------------------------------------------------------------------- // Private Properties //------------------------------------------------------------------------------- /** * @private * @type {string} */ this.key = key; var keyParts = key.split('.'); var packageName = "."; var exportName = keyParts.pop(); if (keyParts.length > 0) { packageName = keyParts.join('.'); } /** * @private * @type {string} */ this.exportName = exportName; /** * @private * @type {String} */ this.packageName = packageName; }, //------------------------------------------------------------------------------- // Getters and Setters //------------------------------------------------------------------------------- /** * @return {string} */ getKey: function() { return this.key; }, /** * @return {string} */ getExportName: function() { return this.exportName; }, /** * @return {string} */ getPackageName: function() { return this.packageName; }, /** * @return {boolean} */ isWildCard: function() { return (this.exportName === "*"); } }); //------------------------------------------------------------------------------- // Exports //------------------------------------------------------------------------------- bugpack.export('bugpack.BugPackKey', BugPackKey);
JavaScript
0.999999
@@ -966,16 +966,17 @@ gPackKey + = Class.
b2d1c7194bab2d2a2f22e5a56d3526a11861bd6e
update time
assets/js/countdown.js
assets/js/countdown.js
var ringer = { countdown_to: "6/13/2015", rings: { 'DAYS': { s: 86400000, // mseconds in a day, max: 365 }, 'HOURS': { s: 3600000, // mseconds per hour, max: 24 }, 'MINUTES': { s: 60000, // mseconds per minute max: 60 }, 'SECONDS': { s: 1000, max: 60 }, 'MICROSEC': { s: 10, max: 100 } }, r_count: 5, r_spacing: 10, // px r_size: 100, // px r_thickness: 2, // px update_interval: 16, // ms init: function(){ $r = ringer; $r.cvs = document.getElementById('countdown-timer'); $r.size = { w: ($r.r_size + $r.r_thickness) * $r.r_count + ($r.r_spacing*($r.r_count-1)), h: ($r.r_size + $r.r_thickness) }; $r.cvs.setAttribute('width',$r.size.w); $r.cvs.setAttribute('height',$r.size.h); $r.ctx = $r.cvs.getContext('2d'); // $(document.body).append($r.cvs); $r.cvs = $($r.cvs); $r.ctx.textAlign = 'center'; $r.actual_size = $r.r_size + $r.r_thickness; $r.countdown_to_time = new Date($r.countdown_to).getTime(); $r.cvs.css({ width: $r.size.w+"px", height: $r.size.h+"px" }); $r.go(); }, ctx: null, go: function(){ var idx=0; $r.time = (new Date().getTime()) - $r.countdown_to_time; for(var r_key in $r.rings) $r.unit(idx++,r_key,$r.rings[r_key]); setTimeout($r.go,$r.update_interval); }, unit: function(idx,label,ring) { var x,y, value, ring_secs = ring.s; value = parseFloat($r.time/ring_secs); $r.time-=Math.round(parseInt(value)) * ring_secs; value = Math.abs(value); x = ($r.r_size*.5 + $r.r_thickness*.5); x +=+(idx*($r.r_size+$r.r_spacing+$r.r_thickness)); y = $r.r_size*.5; y += $r.r_thickness*.5; // calculate arc end angle var degrees = 360-(value / ring.max) * 360.0; var endAngle = degrees * (Math.PI / 180); $r.ctx.save(); $r.ctx.translate(x,y); $r.ctx.clearRect($r.actual_size*-0.5,$r.actual_size*-0.5,$r.actual_size,$r.actual_size); // first circle $r.ctx.strokeStyle = "rgba(128,128,128,0.4)"; $r.ctx.beginPath(); $r.ctx.arc(0,0,$r.r_size/2,0,2 * Math.PI, 2); $r.ctx.lineWidth =$r.r_thickness; $r.ctx.stroke(); // second circle $r.ctx.strokeStyle = "rgba(250, 253, 50, 1)"; $r.ctx.beginPath(); $r.ctx.arc(0,0,$r.r_size/2,0,endAngle, 1); $r.ctx.lineWidth =$r.r_thickness; $r.ctx.stroke(); // label $r.ctx.fillStyle = "#ffffff"; $r.ctx.font = '12px Helvetica'; $r.ctx.fillText(label, 0, 23); $r.ctx.fillText(label, 0, 23); $r.ctx.font = 'bold 40px Helvetica'; $r.ctx.fillText(Math.floor(value), 0, 10); $r.ctx.restore(); } } ringer.init();
JavaScript
0
@@ -29,12 +29,13 @@ o: %22 -6/13 +10/17 /201
6e8ab7b4deb7bee289434418db7c342e3ad1b270
Fix night mode
assets/js/dark-mode.js
assets/js/dark-mode.js
(function () { const themeStorage = new Proxy(localStorage, { get: function (target, prop) { return function (...args) { return target[prop + "Item"]("dark-mode", ...args); }; }, }); const skin_dir = "/assets/css/skins/"; const themes = { dark: "dark.css", light: "default.css", }; const systemColorDark = window.matchMedia("(prefers-color-scheme: dark)"); systemColorDark.addListener(function (e) { changeTheme(e.matches, false); }); let toggleButton; document.addEventListener("DOMContentLoaded", function () { const theme = themeStorage.get(); toggleButton = document.getElementById("theme-toggle"); toggleButton.checked = theme ? theme == "dark" : systemColorDark.matches; toggleButton.addEventListener("change", function (e) { changeTheme(e.target.checked, true); }); }); window.addEventListener("storage", function (e) { if (e.storageArea == localStorage && e.key == theme_setting_key) { changeTheme(e.newValue || systemColorDark.matches, !!e.newValue); } }); function changeTheme(theme, persistent) { if (typeof theme == "boolean") { theme = theme ? "dark" : "light"; } document.querySelector(`link[rel="stylesheet"][href^="${skin_dir}"]`).href = skin_dir + themes[theme]; if (persistent) { themeStorage.set(theme); } if (toggleButton != null) { toggleButton.checked = theme == "dark"; } } changeTheme( themeStorage.get() || systemColorDark.matches, !!themeStorage.get() ); })();
JavaScript
0.000065
@@ -420,16 +420,21 @@ Dark.add +Event Listener @@ -434,16 +434,26 @@ istener( +'change', function @@ -455,24 +455,57 @@ ction (e) %7B%0A + if (!themeStorage.get()) %7B%0A changeTh @@ -527,16 +527,22 @@ false);%0A + %7D%0A %7D);%0A%0A
c04220c317e9917f572bb012029541cfb824b1d0
_ is an allowed first character of mqlkeys
webapp/WEB-INF/js/mjt/src/freebase/mqlkey.js
webapp/WEB-INF/js/mjt/src/freebase/mqlkey.js
(function (mjt) { /** * * routines to quote and unquote javascript strings as valid mql keys * */ var mqlkey_start = 'A-Za-z0-9'; var mqlkey_char = 'A-Za-z0-9_-'; var MQLKEY_VALID = new RegExp('^[' + mqlkey_start + '][' + mqlkey_char + ']*$'); var MQLKEY_CHAR_MUSTQUOTE = new RegExp('([^' + mqlkey_char + '])', 'g'); /** * quote a unicode string to turn it into a valid mql /type/key/value * */ mjt.freebase.mqlkey_quote = function (s) { if (MQLKEY_VALID.exec(s)) // fastpath return s; var convert = function(a, b) { var hex = b.charCodeAt(0).toString(16).toUpperCase(); if (hex.length == 2) hex = '00' + hex; return '$' + hex; }; x = s.replace(MQLKEY_CHAR_MUSTQUOTE, convert); if (x.charAt(0) == '-' || x.charAt(0) == '_') { x = convert(x,x.charAt(0)) + x.substr(1); } // TESTING /* if (mjt.debug && mqlkey_unquote(x) !== s) { mjt.log('failed roundtrip mqlkey quote', s, x); } */ return x; } /** * unquote a /type/key/value string to a javascript string * */ mjt.freebase.mqlkey_unquote = function (x) { x = x.replace(/\$([0-9A-Fa-f]{4})/g, function (a,b) { return String.fromCharCode(parseInt(b, 16)); }); return x; } // convert a mql id to an id suitable for embedding in a url path. // UNTESTED // and DEPRECATED var mqlid_to_mqlurlid = function (id) { if (id.charAt(0) === '~') { return id; } if (id.charAt(0) === '#') { return '%23' + id.substr(1); } if (id.charAt(0) !== '/') { return 'BAD-ID'; } // requote components as keys and rejoin. var segs = id.split('/'); var keys = []; for (var i = 1; i < segs.length; i++) { var seg = segs[i]; // conservative uri encoding for now keys.push(encodeURIComponent(mqlkey_unquote(seg))); } // urlids do not have leading slashes!!! return '/'.join(keys); } })(mjt);
JavaScript
0.998455
@@ -784,30 +784,8 @@ '-' - %7C%7C x.charAt(0) == '_' ) %7B%0A
75f4f50ddb3cfd052e170bc516aca34ae93e5266
set default date format to ISO
webapps/client/scripts/camunda-cockpit-ui.js
webapps/client/scripts/camunda-cockpit-ui.js
define('camunda-cockpit-ui', [ './directives/main', './filters/main', './pages/main', './resources/main', './services/main', 'camunda-commons-ui', 'camunda-bpm-sdk-js', 'ngDefine' ], function () { 'use strict'; var APP_NAME = 'cam.cockpit'; var pluginPackages = window.PLUGIN_PACKAGES || []; var pluginDependencies = window.PLUGIN_DEPENDENCIES || []; require.config({ packages: pluginPackages }); var dependencies = [].concat(pluginDependencies.map(function(plugin) { return plugin.requirePackageName; })); require(dependencies, function() { var ngDependencies = [ 'ng', 'ngResource', require('camunda-commons-ui').name, require('./directives/main').name, require('./filters/main').name, require('./pages/main').name, require('./resources/main').name, require('./services/main').name ].concat(pluginDependencies.map(function(el){ return el.ngModuleName; })); var angular = require('angular'); var $ = require('jquery'); var appNgModule = angular.module(APP_NAME, ngDependencies); var ModuleConfig = [ '$routeProvider', 'UriProvider', function( $routeProvider, UriProvider ) { $routeProvider.otherwise({ redirectTo: '/dashboard' }); function getUri(id) { var uri = $('base').attr(id); if (!id) { throw new Error('Uri base for ' + id + ' could not be resolved'); } return uri; } UriProvider.replace(':appName', 'cockpit'); UriProvider.replace('app://', getUri('href')); UriProvider.replace('adminbase://', getUri('app-root') + '/app/admin/'); UriProvider.replace('cockpit://', getUri('cockpit-api')); UriProvider.replace('admin://', getUri('cockpit-api') + '../admin/'); UriProvider.replace('plugin://', getUri('cockpit-api') + 'plugin/'); UriProvider.replace('engine://', getUri('engine-api')); UriProvider.replace(':engine', [ '$window', function($window) { var uri = $window.location.href; var match = uri.match(/\/app\/cockpit\/(\w+)(|\/)/); if (match) { return match[1]; } else { throw new Error('no process engine selected'); } }]); }]; appNgModule.config(ModuleConfig); require([ 'domReady!' ], function () { angular.bootstrap(document, [ appNgModule.name ]); var html = document.getElementsByTagName('html')[0]; html.setAttribute('ng-app', appNgModule.name); if (html.dataset) { html.dataset.ngApp = appNgModule.name; } if (top !== window) { window.parent.postMessage({ type: 'loadamd' }, '*'); } }); /* live-reload // loads livereload client library (without breaking other scripts execution) require(['jquery'], function($) { $('body').append('<script src="//' + location.hostname + ':LIVERELOAD_PORT/livereload.js?snipver=1"></script>'); }); /* */ }); });
JavaScript
0
@@ -2320,24 +2320,469 @@ leConfig);%0A%0A + appNgModule.config(%5B%0A 'camDateFormatProvider',%0A function(%0A camDateFormatProvider%0A ) %7B%0A var formats = %7B%0A monthName: 'MMMM',%0A day: 'DD',%0A abbr: 'lll',%0A normal: 'YYYY-MM-DD%5BT%5DHH:mm:SS', // yyyy-MM-dd'T'HH:mm:ss =%3E 2013-01-23T14:42:45%0A long: 'LLLL',%0A short: 'LL'%0A %7D;%0A%0A for (var f in formats) %7B%0A camDateFormatProvider.setDateFormat(formats%5Bf%5D, f);%0A %7D%0A %7D%5D);%0A%0A require(
1687c7e2744a025ad461e69fa3c2c2ddbd7d55eb
Fix minor bugs
src/visits.js
src/visits.js
import url from "url"; import Clipboard from "clipboard"; import "whatwg-fetch"; import "./common.css"; import "./visits.css"; function hookCopyPaste(element) { new Clipboard(element); element.disabled = false; } function timeout(delay) { return new Promise(resolve => { setTimeout(resolve, delay); }); } function fetchUpdates(baseUrl, cursor, interval, callback) { const parsedUrl = url.parse(baseUrl, true); parsedUrl.query.cursor = cursor; const updateUrl = url.format(parsedUrl); timeout(interval) .then(() => fetch(updateUrl)) .then(response => response.json()) .then( json => { const visits = json.visits; if (visits.length > 0) { callback(null, visits); } fetchUpdates(baseUrl, json.cursor, interval, callback); }, err => { callback(err, null); } ); } function col(row, text) { const element = document.createElement("td"); element.textContent = text.trim() || "\u00a0"; row.appendChild(element); } function updateTable(element, counts) { const baseUrl = element.dataset.updateUrl; const cursor = element.dataset.updateCursor; fetchUpdates(baseUrl, cursor, 1000, function(err, visits) { if (err) { console.error(err); return; } const body = element.tBodies[0]; visits.forEach(visit => { const row = document.createElement("tr"); col(row, visit.timestamp); col(row, (visit.country.emoji || "") + "\u00a0" + visit.ip); col(row, visit.asns.map(asn => { return asn.asn + " " + asn.names.join(", "); }).join("\n")); col(row, visit.userAgent); body.insertBefore(row, body.firstChild); }); counts.textContent = body.children.length; }); } hookCopyPaste(document.getElementById("trap-copy")); updateTable(document.getElementById("visit-table"), document.getElementById("visit-count"));
JavaScript
0.000007
@@ -1054,24 +1054,115 @@ (%22td%22);%0A +if (text && text.trim()) %7B%0A element.textContent = text.trim();%0A %7D else %7B%0A element.text @@ -1174,23 +1174,8 @@ nt = - text.trim() %7C%7C %22%5Cu @@ -1181,16 +1181,22 @@ u00a0%22;%0A + %7D%0A row.
60bb65402520984d51abcd05991c1c953fa194f7
Fix typo in comment
jquery.still-alive.js
jquery.still-alive.js
/*! * StillAlive v1.0 * http://github.com/sidewaysmilk/still-alive * * Copyright 2011, Justin Force * Licensed under the 3-clause BSD License */ /*jslint browser: true, indent: 2 */ /*global jQuery */ (function ($) { 'use strict'; // default values for optional arguments var DEFAULT_WAKEEVENTS = 'mousemove mousedown mouseup keydown keyup', DEFAULT_INTERVAL = 60000, DEFAULT_IMMEDIATELY = true; // sugar. Just get the current time in milliseconds function getTime() { return (new Date()).getTime(); } $.stillAlive = function (callback, interval, immediately, wakeEvents) { var args, // object containing optional arguments awake = true, // awake status. Are we awake? lastSeen = getTime(); // the last time the user was seen (a wake event triggered) // For named arguments, copy the arguments object and assign its supported // properties. if (typeof interval === 'object') { args = interval; interval = args.interval; immediately = args.immediately; wakeEvents = args.wakeEvents; } // set default values for optional arguments if (interval === undefined) { interval = DEFAULT_INTERVAL; } if (immediately === undefined) { immediately = DEFAULT_IMMEDIATELY; } if (wakeEvents === undefined) { wakeEvents = DEFAULT_WAKEEVENTS; } // true if it's been (1.5 x interval) milliseconds function timeToSleep() { return (getTime() - lastSeen > (interval + (interval / 2))); } // set status to awake and update the lastSeen time. If we're waking and // we're supposed to run immediately, execute the callback. function wake() { if (!awake && immediately) { callback(); } awake = true; lastSeen = getTime(); } // set status to !awake (asleep) function sleep() { awake = false; } $(window).bind(wakeEvents, wake); // if enough time has passed without a wake event, sleep. If we happen to // be awake, execute the callback. setInterval(function () { if (timeToSleep()) { sleep(); } if (awake) { callback(); } }, interval); // if we're supposed to run immediately, execute the callback once if (immediately) { callback(); } }; }(jQuery));
JavaScript
0.000917
@@ -118,21 +118,21 @@ the +BSD 3- -c +C lause -BSD Lice
66580f6c6f269e25e6bd9cd9379419a73277a9af
add beforeSend function
jquery.typesuggest.js
jquery.typesuggest.js
(function($) { function TypeSuggest(el, data, options, callback){ var defaults = { min_characters: 2, display_key: undefined, search_key: undefined, ignored: [ ' ', ',', '.' ], ajax: false, url: '', param: 'q' }; this.config = $.extend({}, defaults, options); // set parent element this.$el = $(el).addClass("typesuggest"); this.data = data; // set callback this.callback = typeof callback === "function" && callback || false; this.init(); this.events(); } TypeSuggest.prototype.init = function(){ var self = this; self.$fields = self.$el.find("input").addClass("typesuggest-input").attr('autocomplete', 'off'); self.$suggest = $('<div class="typesuggest-list">').appendTo(self.$el); } TypeSuggest.prototype.events = function(){ var self = this; self.$fields.on('keydown', function(e){ var $field = $(this); var key = e.keyCode || e.which; // if up or down arrows, scroll thru list. if enter key, select item if(key == 40 || key == 38 || key == 13){ if(e.keyCode == 40){ // down arrow self.$suggest.addClass("selecting"); self.move(+1); // prevent caret from moving return false; }else if(e.keyCode == 38){ // up arrow self.$suggest.addClass("selecting"); self.move(-1); // prevent caret from moving return false; }else if(e.keyCode == 13){ // enter var $selectedItem = self.$suggest.find(".selected"); var data = $selectedItem.data(); self.selectItem(data); // prevent caret from moving return false; }else{ // everything else self.$suggest.removeClass("selecting"); } } }) self.$fields.on('keyup', function(e){ var $field = $(this); var key = e.keyCode || e.which; self.$currentField = $field; // if not up or down arrows or enter key, fill suggestion if(key !== 40 && key !== 38 && key !== 13){ if(!self.debounce){ // get value var val = $field.val(); self.options = []; if(val.length && val.length >= self.config.min_characters){ self.startDebounce(); if(self.config.ajax){ var url = self.config.url + "?" + self.config.param + "=" + val $.ajax({ url: url, type: 'GET', dataType: 'json', success: function(data, textStatus, xhr){ self.options = data[self.config.results_key]; self.updateList(); } }) }else{ // compare value to provided list $.each(self.data, function(i, item){ var valLower = val.toLowerCase(); var itemLower; if(self.config.search_key){ itemLower = item[self.config.search_key].toLowerCase(); }else{ itemLower = item.toLowerCase(); } if(itemLower.search(valLower) > -1){ self.options.push(item); } }) } } self.updateList(); } }else{ // prevent caret from moving return false; } }) self.$suggest.on('click', 'li', function(){ var data = $(this).data(); self.selectItem(data); self.callback && self.callback(data); }) self.$suggest.on('mouseover', 'li', function(){ var $li = $(this); self.$suggest.find("li").removeClass("selected"); $li.addClass("selected"); }) } TypeSuggest.prototype.move = function(where){ var self = this; var $selectedItem = self.$suggest.find(".selected"); var firstSelected = self.$suggest.find("li:first").hasClass("selected"); var lastSelected = self.$suggest.find("li:last").hasClass("selected"); if($selectedItem.length && where > 0){ if(lastSelected){ // select first $selectedItem.removeClass("selected"); self.$suggest.find("li:first").addClass("selected"); }else{ // selection exists, go to next $selectedItem.removeClass("selected").next("li").addClass("selected") } } else if($selectedItem.length && where < 0){ if(firstSelected){ // select last $selectedItem.removeClass("selected"); self.$suggest.find("li:last").addClass("selected"); }else{ // selection exists, go to prev $selectedItem.removeClass("selected").prev("li").addClass("selected") } } else{ // select first self.$suggest.find("li:first").addClass("selected"); } } TypeSuggest.prototype.updateList = function(){ var self = this; var $list = $('<ul>'); if(self.options.length){ self.$suggest.addClass("selecting"); var options = self.options; $.each(options, function(i, option){ var $listItem = $("<li>").data("option", option); if(self.config.display_keys){ var output = ''; $.each(self.config.display_keys, function(i, key){ output += '<span class="' + key + '">' + option[key] + '</span>' }) $listItem.html(output); }else{ $listItem.html(option); } $list.append($listItem); }) self.$suggest.html($list); }else{ self.$suggest.removeClass("selecting") } } TypeSuggest.prototype.selectItem = function(data){ var self = this; self.options = []; self.updateList(); if(!self.config.display_keys){ self.$currentField.val(data.option); } self.callback && self.callback(data); } TypeSuggest.prototype.startDebounce = function(){ var self = this; self.debounce = true; setTimeout(function(){ self.debounce = false; }, 250) } $.fn.suggest = function(data, options, callback){ var suggest = new TypeSuggest(this, data, options, callback); return this; } })(jQuery);
JavaScript
0.000001
@@ -281,16 +281,45 @@ ram: 'q' +,%0A beforeSend: undefined %0A %7D;%0A @@ -2398,16 +2398,126 @@ .ajax)%7B%0A + if(self.config.beforeSend)%7B%0A val = self.config.beforeSend(val);%0A %7D%0A%0A @@ -2585,16 +2585,18 @@ =%22 + val +;%0A %0A
de10dff7d3e7e0c0dbcbabb507bbc8e4b71adb7e
rename parentContainerTagName --> containerTagName, https://github.com/phetsims/scenery/issues/748
js/AquaRadioButton.js
js/AquaRadioButton.js
// Copyright 2013-2017, University of Colorado Boulder /** * Radio button with a pseudo-Aqua (Mac OS) look. See "options" comment for list of options. * * @author Chris Malley (PixelZoom, Inc.) */ define( function( require ) { 'use strict'; // modules var AquaRadioButtonIO = require( 'SUN/AquaRadioButtonIO' ); var ButtonListener = require( 'SCENERY/input/ButtonListener' ); var Circle = require( 'SCENERY/nodes/Circle' ); var inherit = require( 'PHET_CORE/inherit' ); var Node = require( 'SCENERY/nodes/Node' ); var Rectangle = require( 'SCENERY/nodes/Rectangle' ); var sun = require( 'SUN/sun' ); var Tandem = require( 'TANDEM/Tandem' ); // constants var DEFAULT_RADIUS = 7; /** * @param property * @param value the value that corresponds to this button, same type as property * @param {Node} node that will be vertically centered to the right of the button * @param {Object} [options] * @constructor */ function AquaRadioButton( property, value, node, options ) { options = _.extend( { cursor: 'pointer', enabled: true, selectedColor: 'rgb( 143, 197, 250 )', // color used to fill the button when it's selected deselectedColor: 'white', // color used to fill the button when it's deselected centerColor: 'black', // color used to fill the center of teh button when it's selected radius: DEFAULT_RADIUS, // radius of the button xSpacing: 8, // horizontal space between the button and the node stroke: 'black', // color used to stroke the outer edge of the button tandem: Tandem.required, phetioType: AquaRadioButtonIO, // a11y tagName: 'input', inputType: 'radio', parentContainerTagName: 'li', labelTagName: 'label', prependLabels: true, a11yNameAttribute: 'aquaRadioButton' }, options ); var self = this; // @private this._enabled = options.enabled; // selected node creation var selectedNode = new Node(); var innerCircle = new Circle( options.radius / 3, { fill: options.centerColor } ); var outerCircleSelected = new Circle( options.radius, { fill: options.selectedColor, stroke: options.stroke } ); // @private this.selectedCircleButton = new Node( { children: [ outerCircleSelected, innerCircle ] } ); selectedNode.addChild( this.selectedCircleButton ); selectedNode.addChild( node ); node.left = outerCircleSelected.right + options.xSpacing; node.centerY = outerCircleSelected.centerY; // deselected node var deselectedNode = new Node(); // @private this.deselectedCircleButton = new Circle( options.radius, { fill: options.deselectedColor, stroke: options.stroke } ); deselectedNode.addChild( this.deselectedCircleButton ); deselectedNode.addChild( node ); node.left = this.deselectedCircleButton.right + options.xSpacing; node.centerY = this.deselectedCircleButton.centerY; Node.call( this ); //Add an invisible node to make sure the layout for selected vs deselected is the same var background = new Rectangle( selectedNode.bounds.union( deselectedNode.bounds ) ); selectedNode.pickable = deselectedNode.pickable = false; // the background rectangle suffices this.addChild( background ); this.addChild( selectedNode ); this.addChild( deselectedNode ); // sync control with model var syncWithModel = function( newValue ) { selectedNode.visible = ( newValue === value ); deselectedNode.visible = !selectedNode.visible; }; property.link( syncWithModel ); // set property value on fire var fire = function() { options.tandem.isSuppliedAndEnabled() && self.startEvent( 'user', 'fired', { value: property.phetioType.elementType.toStateObject( value ) } ); property.set( value ); options.tandem.isSuppliedAndEnabled() && self.endEvent(); }; var buttonListener = new ButtonListener( { fire: fire } ); this.addInputListener( buttonListener ); // a11y - input listener so that updates the state of the radio button with keyboard interaction var changeListener = this.addAccessibleInputListener( { change: function() { fire(); } } ); // a11y - Specify the default value for assistive technology. This attribute is needed in addition to // the 'checked' property to mark this element as the default selection since 'checked' may be set before // we are finished adding RadioButtons to the containing group, and the browser will remove the boolean // 'checked' flag when new buttons are added. if ( property.value === value ) { this.setAccessibleAttribute( 'checked', 'checked' ); } // a11y - when the property changes, make sure the correct radio button is marked as 'checked' so that this button // receives focus on 'tab' var accessibleCheckedListener = function( newValue ) { self.accessibleChecked = newValue === value; }; property.link( accessibleCheckedListener ); // @private this.disposeRadioButton = function() { self.removeInputListener( buttonListener ); self.removeAccessibleInputListener( changeListener ); property.unlink( accessibleCheckedListener ); property.unlink( syncWithModel ); }; // a11y - allow consistent a11y naming for radio button types this.setAccessibleAttribute( 'name', options.a11yNameAttribute ); this.mutate( options ); } sun.register( 'AquaRadioButton', AquaRadioButton ); return inherit( Node, AquaRadioButton, { /** * Sets whether the circular part of the radio button will be displayed. * @param {boolean} circleButtonVisible * @public */ setCircleButtonVisible: function( circleButtonVisible ) { this.deselectedCircleButton.visible = circleButtonVisible; this.selectedCircleButton.visible = circleButtonVisible; }, // @public - Provide dispose() on the prototype for ease of subclassing. dispose: function() { this.disposeRadioButton(); Node.prototype.dispose.call( this ); }, /** * Sets the enabled state * @param {boolean} enabled * @public */ setEnabled: function( enabled ) { this._enabled = enabled; this.opacity = enabled ? 1 : 0.3; this.pickable = enabled; // NOTE: This is a side-effect. If you set pickable independently, it will be changed when you set enabled. }, set enabled( value ) { this.setEnabled( value ); }, /** * Gets the enabled state * @returns {boolean} * @public */ getEnabled: function() { return this._enabled; }, get enabled() { return this.getEnabled(); } }, { DEFAULT_RADIUS: DEFAULT_RADIUS } ); } );
JavaScript
0
@@ -1709,15 +1709,9 @@ -parentC +c onta
827cc6c7bf50b3b8a7c159f5e478e443d4d7b830
drop old comment
js/chart/ChartView.js
js/chart/ChartView.js
var React = require('react'); import PureComponent from '../PureComponent'; import {showWizard} from './utils'; var _ = require('../underscore_ext').default; var isBinary = (codes, data) => !codes && data && _.flatten(data).every(c => _.indexOf([0, 1], c) !== -1 || c == null); // XXX should we cache this for larger datasets? Or // compute it when we load data? function castBinary(appState) { var {columns, data} = appState; // Using this pattern instead of mapObject to avoid creating a new // object if there are no updates. Not sure it matters. Object.keys(columns).forEach(id => { if (isBinary(_.getIn(columns, [id, 'codes']), _.getIn(data, [id, 'req', 'values']))) { appState = _.assocIn(appState, ['columns', id, 'codes'], ['0', '1']); } }); return appState; } class ChartView extends PureComponent { state = {}; componentDidMount() { Promise.all([ import('./ChartWizard'), import('./chart')]).then(([{default: ChartWizard}, {default: Chart}]) => { this.setState({Chart, ChartWizard}); }); } render() { var {appState, ...otherProps} = this.props, {Chart, ChartWizard} = this.state, Mode = showWizard(appState) ? ChartWizard : Chart; // XXX Why do we pick chart vs. wizard here, and also in the wizard? // Also see note in Chart::render() return Mode ? <Mode appState={castBinary(appState)} {...otherProps}/> : <span/>; } } module.exports = ChartView;
JavaScript
0
@@ -1187,117 +1187,8 @@ rt;%0A -%09%09// XXX Why do we pick chart vs. wizard here, and also in the wizard?%0A%09%09// Also see note in Chart::render()%0A %09%09re
a991f21aa472d597ec1200fbf6ea07954ef3dd13
Make method to get the key value of module-data
js/components/body.js
js/components/body.js
(function(app) { 'use strict'; var helper = app.helper || require('../helper.js'); var dom = app.dom || require('../dom.js'); var Component = app.Component || require('./component.js'); var Content = app.Content || require('./content.js'); var Sidebar = app.Sidebar || require('./sidebar.js'); var ModuleData = function(props) { this.packageName = props.packageName || ''; this.label = props.label || ''; this.description = props.description || ''; this.src = props.src || ''; this.visiblePortNames = props.visiblePortNames || []; }; var ModuleDataCollection = function() { this.data = {}; }; ModuleDataCollection.prototype.load = function() { return this.loadPackageNames().then(function(packageNames) { return Promise.all(packageNames.map(function(packageName) { return this.loadModuleDatas(packageName).then(function(moduleDatas) { moduleDatas.forEach(function(moduleData) { this.data[packageName + '/' + moduleData.src] = moduleData; }.bind(this)); }.bind(this)); }.bind(this))); }.bind(this)); }; ModuleDataCollection.prototype.loadPackageNames = function() { return dom.ajax({ type: 'GET', url: 'modular_modules/index.json', }).then(function(text) { return JSON.parse(text); }); }; ModuleDataCollection.prototype.loadModuleDatas = function(packageName) { return dom.ajax({ type: 'GET', url: 'modular_modules/' + packageName + '/index.json', }).then(function(text) { return JSON.parse(text).map(function(props) { return new ModuleData(helper.extend(helper.clone(props), { packageName: packageName })); }); }); }; var Body = helper.inherits(function() { Body.super_.call(this, { element: dom.body() }); this.moduleDataCollection = this.prop(new ModuleDataCollection()); this.dragCount = this.prop(0); this.content = new Content({ element: dom.el('.content'), sidebarCollapser: Body.prototype.sidebarCollapser.bind(this), sidebarExpander: Body.prototype.sidebarExpander.bind(this), moduleDragStarter: Body.prototype.moduleDragStarter.bind(this), moduleDragEnder: Body.prototype.moduleDragEnder.bind(this), }); this.sidebar = new Sidebar({ element: dom.el('.sidebar'), moduleDragStarter: Body.prototype.moduleDragStarter.bind(this), moduleDragEnder: Body.prototype.moduleDragEnder.bind(this), moduleDropper: Body.prototype.moduleDropper.bind(this), }); dom.ready(Body.prototype.onready.bind(this)); }, Component); Body.prototype.incrementDragCount = function() { this.dragCount(this.dragCount() + 1); }; Body.prototype.decrementDragCount = function() { this.dragCount(this.dragCount() - 1); }; Body.prototype.redraw = function() { this.redrawDragCount(); }; Body.prototype.redrawDragCount = function() { var dragCount = this.dragCount(); var cache = this.cache(); if (dragCount === cache.dragCount) { return; } dom.toggleClass(this.element(), 'module-dragging', dragCount > 0); cache.dragCount = dragCount; }; Body.prototype.onready = function() { this.content.redraw(); }; Body.prototype.sidebarCollapser = function() { return new Promise(function(resolve, reject) { var element = this.element(); var ontransitionend = function() { dom.off(element, 'transitionend', ontransitionend); resolve(); }; dom.on(element, 'transitionend', ontransitionend); dom.addClass(element, 'no-sidebar'); }.bind(this)); }; Body.prototype.sidebarExpander = function() { return new Promise(function(resolve, reject) { var element = this.element(); var ontransitionend = function() { dom.off(element, 'transitionend', ontransitionend); resolve(); }; dom.on(element, 'transitionend', ontransitionend); dom.removeClass(element, 'no-sidebar'); }.bind(this)); }; Body.prototype.moduleDragStarter = function() { this.incrementDragCount(); }; Body.prototype.moduleDragEnder = function() { this.decrementDragCount(); }; Body.prototype.moduleDropper = function(name, x, y) { /* TODO: load dropped module */ }; if (typeof module !== 'undefined' && module.exports) { module.exports = Body; } else { app.Body = Body; } })(this.app || (this.app = {}));
JavaScript
0.000007
@@ -562,24 +562,118 @@ %7C %5B%5D;%0A %7D;%0A%0A + ModuleData.prototype.key = function() %7B%0A return this.packageName + '/' + this.src;%0A %7D;%0A%0A var Module @@ -1065,36 +1065,16 @@ is.data%5B -packageName + '/' + moduleDa @@ -1076,19 +1076,21 @@ uleData. -src +key() %5D = modu
56ad907a3766a40c3daf2170882b19ddeeab06e7
Refactor code for scrolling of list
js/components/list.js
js/components/list.js
(function(app) { 'use strict'; var IScroll = require('iscroll'); var dom = app.dom || require('./dom.js'); var Location = app.Location || require('../models/location.js'); var List = function(el, props) { this.el = el; this.scroll = null; this._locations = props.locations; this._selectedLocations = props.selectedLocations; this._itemElements = {}; }; List.prototype.init = function() { this.el.addEventListener(dom.supportsTouch() ? 'tap' : 'click', this._onclick.bind(this)); this._locations.on('reset', this._resetLocations.bind(this)); this._selectedLocations.on('reset', this._resetSelectedLocations.bind(this)); this._selectedLocations.on('add', this._addSelectedLocation.bind(this)); this._selectedLocations.on('remove', this._removeSelectedLocation.bind(this)); if (dom.supportsTouch()) { this._disableNativeScroll(); this._disableDoubleTapZoom(); } }; List.prototype._resetLocations = function(locations) { var container = document.createElement('div'); this._itemElements = locations.slice().sort(function(a, b) { return (a.name < b.name || a.key === Location.KEY_CURRENT_LOCATION ? -1 : 1); }).reduce(function(ret, location) { var el = this._createItemElement(location); container.appendChild(el); ret[location.key] = el; return ret; }.bind(this), {}); this.el.replaceChild(container, this.el.firstElementChild); if (dom.supportsTouch()) { if (this.scroll) { this.scroll.destroy(); } this.scroll = new IScroll(this.el, { tap: true, scrollbars: true, shrinkScrollbars: 'scale', fadeScrollbars: true, }); } }; List.prototype._resetSelectedLocations = function(selectedLocations) { this._locations.forEach(function(location) { var el = this._itemElements[location.key]; if (selectedLocations.indexOf(location) !== -1) { el.classList.add('list-selected'); } else { el.classList.remove('list-selected'); } }.bind(this)); }; List.prototype._addSelectedLocation = function(location) { var el = this._itemElements[location.key]; if (el) { el.classList.add('list-selected'); } }; List.prototype._removeSelectedLocation = function(location) { var el = this._itemElements[location.key]; if (el) { el.classList.remove('list-selected'); } }; List.prototype._createItemElement = function(location) { var el = document.createElement('div'); el.classList.add('list-item'); el.setAttribute('data-key', location.key); var textLength = location.name.length; if (textLength >= 20) { el.style.fontSize = '11px'; } else if (textLength >= 17) { el.style.fontSize = '14px'; } el.textContent = location.name; return el; }; List.prototype._onclick = function(event) { event.preventDefault(); var target = event.target; if (!target.classList.contains('list-item')) { return; } var key = target.getAttribute('data-key'); if (!Location.isValidKey(key)) { return; } var location = this._locations.find(function(location) { return (location.key === key); }); if (!location) { return; } // toggle selection of location if (this._selectedLocations.includes(location)) { this._selectedLocations.remove(location); } else { this._selectedLocations.add(location); } }; List.prototype._disableNativeScroll = function() { this.el.style.overflowY = 'hidden'; }; List.prototype._disableDoubleTapZoom = function() { this.el.addEventListener('touchstart', function(event) { event.preventDefault(); }); }; if (typeof module !== 'undefined' && module.exports) { module.exports = List; } else { app.List = List; } })(this.app || (this.app = {}));
JavaScript
0.000001
@@ -232,32 +232,8 @@ el;%0A - this.scroll = null;%0A @@ -351,16 +351,42 @@ s = %7B%7D;%0A + this._iScroll = null;%0A %7D;%0A%0A @@ -1497,25 +1497,27 @@ if (this. -s +_iS croll) %7B%0A @@ -1522,25 +1522,27 @@ this. -s +_iS croll.destro @@ -1554,17 +1554,16 @@ %7D%0A -%0A th @@ -1569,17 +1569,19 @@ his. -s +_iS croll = new @@ -1580,148 +1580,28 @@ l = -new IScroll(this.el, %7B%0A tap: true,%0A scrollbars: true,%0A shrinkScrollbars: 'scale',%0A fadeScrollbars: true,%0A %7D +this._createIScroll( );%0A @@ -2745,32 +2745,229 @@ eturn el;%0A %7D;%0A%0A + List.prototype._createIScroll = function() %7B%0A return new IScroll(this.el, %7B%0A tap: true,%0A scrollbars: true,%0A shrinkScrollbars: 'scale',%0A fadeScrollbars: true,%0A %7D);%0A %7D;%0A%0A List.prototype
81b92a1eab0bd5ac4c43493ea9f27043e2d49c53
Update index.js
test/index.js
test/index.js
import test from 'ava'; import module, {boilerplate} from '../dist'; test('should return default', t => { const moduleResponse = module(); t.is(moduleResponse, "default"); }); test('should return boilerplate', t => { const boilerplateResponse = boilerplate(); t.is(boilerplateResponse, "boilerplate"); });
JavaScript
0.000002
@@ -4,74 +4,278 @@ ort -test from 'ava';%0Aimport module, %7Bboilerplate%7D from '../dist';%0A%0Ates +chai, %7Bexpect%7D from 'chai';%0Aimport chaiAsPromised from 'chai-as-promised';%0Aimport %7B it, before, after, beforeEach, afterEach %7D from 'arrow-mocha/es5'%0Aimport module, %7Bboilerplate%7D from '../dist';%0A%0Achai.use(chaiAsPromised);%0A%0Adescribe('boilerplate test',function () %7B%0A%09%0A i t('s @@ -297,25 +297,26 @@ fault', -t +() =%3E %7B%0A const mo @@ -303,24 +303,26 @@ , () =%3E %7B%0A + + const module @@ -345,20 +345,24 @@ e();%0A%0A -t.is + expect (moduleR @@ -372,29 +372,41 @@ onse -, %22 +).to.equal(' default -%22 +' );%0A + %7D);%0A -tes +%0A i t('s @@ -436,15 +436,18 @@ e', -t +() =%3E %7B%0A + co @@ -494,12 +494,16 @@ %0A%0A -t.is + expect (boi @@ -522,11 +522,20 @@ onse -, %22 +).to.equal(' boil @@ -545,12 +545,18 @@ late -%22 +' );%0A + %7D);%0A +%0A%7D)%0A
8fcd51659d861a783f41e779bbb8944d9b9a5e44
set timer back to 60 sec.
js/countdown_timer.js
js/countdown_timer.js
/* config */ // seconds to countdown from var countdownSeconds = 15; // countdown function Counter(options) { var timer; var instance = this; var seconds = options.seconds || 10; var onUpdateStatus = options.onUpdateStatus || function() {}; var onCounterEnd = options.onCounterEnd || function() {}; var onCounterStart = options.onCounterStart || function() {}; function decrementCounter() { onUpdateStatus(seconds); if (seconds === 0) { stopCounter(); onCounterEnd(); return; } seconds--; }; function startCounter() { onCounterStart(); clearInterval(timer); timer = 0; decrementCounter(); timer = setInterval(decrementCounter, 1000); }; function stopCounter() { clearInterval(timer); }; function restartCounter() { seconds = countdownSeconds; onCounterStart(); clearInterval(timer); timer = 0; decrementCounter(); timer = setInterval(decrementCounter, 1000); }; return { start : function() { startCounter(); }, stop : function() { stopCounter(); }, restart : function() { restartCounter(); } } }; //countdown.start();
JavaScript
0
@@ -63,10 +63,10 @@ s = -15 +60 ;%0A%0A%0A
762c796c6851ca2075b5afbae24bfa7e5b66687a
Fix index test
test/index.js
test/index.js
'use strict'; var isFunction = require('es5-ext/lib/Function/is-function') , convert = require('es5-ext/lib/String/prototype/hyphen-to-camel') , path = require('path') , readdir = require('fs').readdir , indexTest = require('tad/lib/utils/index-test') , dir = path.dirname(__dirname); module.exports = { "": indexTest(indexTest.readDir(dir)(function (o) { delete o.benchmark; delete o.deferred; delete o.examples; delete o.ext; delete o.promise; delete o.profiler; return o; }), ['Deferred', 'callAsync', 'delay', 'extend', 'gate', 'profile', 'profileEnd', 'promisify', 'promisifySync', 'reject', 'map', 'reduce', 'some']), "isPromise": function (t, a) { a(t.isPromise(t(null)), true); a(t.isPromise({}), false); }, "InvokeAsync": function (t, a, d) { var x = {}; t.invokeAsync({}, function (cb) { setTimeout(function () { cb(null, x); }, 0); return {}; })(function (r) { a(r, x); }).done(d, d); }, "CallAsync": function (t, a, d) { var x = {}; t.callAsync(function (cb) { setTimeout(function () { cb(null, x); }, 0); return {}; })(function (r) { a(r, x); }).done(d, d); }, "Delay": function (t, a, d) { var x = {}; t.delay(function (r) { return r; }, 5)(x)(function (r) { a(r, x); }).done(d, d); }, "Gate": function (t, a) { var fn, dx, dy, ready; fn = t.gate(function (p) { return p; }, 1); dx = t(); fn(dx.promise); dy = t(); fn(dy.promise).done(function () { a(ready, true); }); dy.resolve({}); ready = true; dx.resolve({}); ready = false; }, "Profile": function (t, a) { a(typeof t.profile, 'function', "Profile"); a(typeof t.profileEnd, 'function', "ProfileEnd"); }, "Promisify": function (t, a, d) { var x = {}; t.promisify(function (cb) { setTimeout(function () { cb(null, x); }, 0); return {}; })()(function (r) { a(r, x); }).done(d, d); }, "PromisifySync": function (t, a, d) { t.promisifySync(function () { return; })()(function (r) { a(r, undefined); }).done(d, d); }, "Map": function (t, a, d) { t.map([t(1), t(2), 3], function (res) { return t(res * res); })(function (r) { a.deep(r, [1, 4, 9]); }, a.never).done(d, d); }, "Reduce": function (t, a, d) { t.reduce([t(1), t(2), 3], function (arg1, arg2) { return t(arg1 * arg2); }, 1)(function (r) { a(r, 6); }, a.never).done(d, d); }, "Some": function (t, a, d) { var count = 0; t.some([t(1), t(2), 3], function (res, index) { ++count; return index; })(function (r) { a(r, true); a(count, 2, "Count"); }, a.never).done(d, d); }, "Deferred function is main object": function (t, a) { var d = t(); d.resolve({}); a.ok(isFunction(d.resolve) && isFunction(d.promise.then)); }, "Ports are loaded": function (t, a, d) { var p = t().resolve(); readdir(dir + '/ext/promise', function (err, files) { if (err) { d(err); return; } files.map(function (file) { if ((file.slice(-3) === '.js') && (file[0] !== '_')) { return convert.call(file.slice(0, -3)); } }).filter(Boolean).forEach(function (file) { a(isFunction(p[file]), true, file); }); d(); }); } };
JavaScript
0.00001
@@ -376,16 +376,39 @@ n (o) %7B%0A +%09%09delete o.assimilate;%0A %09%09delete
9cd681e5f8109b8db0b4e502819bb8ed2e07ab77
revert back time changes
modules/team-data-parser.js
modules/team-data-parser.js
const R = require('ramda'); const removeUserNameAndLevelTime = (rawString) => R.replace(/\(.*?\)/g, ',', rawString); const parseLevelTime = (str) => R.pipe( R.split('.'), R.dropLast(1), R.insert(3, 'T'), R.join('') )(str); const getCorrectTimeFromString = (type, strArray) => R.pipe( R.indexOf(type), R.flip(R.subtract)(1), R.of, R.flip(R.path)(strArray), parseInt )(strArray); const convertStringToTime = (strArray) => ({ days: R.contains('д', strArray) ? getCorrectTimeFromString('д', strArray) : 0, hours: R.contains('ч', strArray) ? getCorrectTimeFromString('ч', strArray) : 0, minutes: R.contains('м', strArray) ? getCorrectTimeFromString('м', strArray) : 0, seconds: R.contains('с', strArray) ? getCorrectTimeFromString('с', strArray) : 0, }); const parseBonusPenaltyTime = (str) => R.pipe( R.replace('бонус ', ''), R.split(' '), convertStringToTime )(str); const getBonusesPenaltiesTime = (str) => { if (R.test(/бонус/, str)) { return { bonus: parseBonusPenaltyTime(str) }; } else if (R.test(/штраф/, str)) { return { penalty: parseBonusPenaltyTime(str) }; } return undefined; }; const parseBonusesAndPenalties = (str) => R.pipe( R.replace('таймаут', ''), getBonusesPenaltiesTime )(str); const parseTeamString = (teamString) => ({ name: R.pathOr('', [0], teamString), time: R.isNil(R.path([1], teamString)) ? null : parseLevelTime(teamString[1]), additions: R.isNil(R.path([2], teamString)) ? null : parseBonusesAndPenalties(teamString[2]), }); const getTeamData = (team) => R.pipe( R.slice(1, -1), R.map(removeUserNameAndLevelTime), R.map(R.split(',')), R.map(parseTeamString) )(team); exports.getTeamData = (stat) => R.map(getTeamData, stat);
JavaScript
0.000002
@@ -167,31 +167,13 @@ plit -('.'),%0A R.dropLas +A t(1 +0 ),%0A @@ -188,9 +188,9 @@ ert( -3 +1 , 'T
3d191615fc74dd359cf219d19eefc8294657929a
set initial cursor position in html body
js/editors/editors.js
js/editors/editors.js
//= require "codemirror" //= require "mobileCodeMirror" //= require "library" //= require "unsaved" var focusPanel = 'javascript'; var editors = {}; window.editors = editors; editors.html = CodeMirror.fromTextArea(document.getElementById('html'), { parserfile: [], tabMode: 'shift', mode: 'text/html', onChange: changecontrol, theme: jsbin.settings.theme || 'jsbin' }); editors.javascript = CodeMirror.fromTextArea(document.getElementById('javascript'), { mode: 'css', tabMode: 'shift', onChange: changecontrol, theme: jsbin.settings.theme || 'jsbin' }); setupEditor('javascript'); setupEditor('html'); var editorsReady = setInterval(function () { if (editors.html.ready && editors.javascript.ready) { clearInterval(editorsReady); editors.ready = true; if (typeof editors.onReady == 'function') editors.onReady(); var scrollers = { html: $(editors.html.getScrollerElement()), javascript: $(editors.javascript.getScrollerElement()) }; $document.bind('sizeeditors', function () { var top = 0, //$el.offset().top, height = $('#bin').height(); scrollers.html.height(height - top); scrollers.javascript.height(height - top - $error.filter(':visible').height()); editors.javascript.refresh(); editors.html.refresh(); }); $(window).resize(function () { setTimeout(function () { $document.trigger('sizeeditors'); }, 100); }); $document.trigger('sizeeditors'); $document.trigger('jsbinReady'); } }, 100); // $('#javascript').replaceWith('<div id="javascript"></div>'); // $('#javascript').css({ height: '100%', width: '100%' }); // $('#html').replaceWith('<div id="html"></div>'); // $('#html').css({ height: '100%', width: '100%' }); // // editors.javascript = ace.edit("javascript"); // editors.html = ace.edit("html"); // // var JavaScriptMode = require("ace/mode/javascript").Mode, // HTMLMode = require("ace/mode/html").Mode; // // setupAce(editors, 'javascript'); // setupAce(editors, 'html'); // // function setupAce(editor, type) { // var session = editors[type].getSession(), // renderer = editors[type].renderer; // if (type == 'javascript') { // session.setMode(new JavaScriptMode()); // } else { // session.setMode(new HTMLMode()); // } // // editors[type].setHighlightActiveLine(false); // session.setUseWrapMode(true); // session.setUseSoftTabs(true); // session.setWrapLimitRange(null, null); // // renderer.setShowPrintMargin(false); // renderer.setShowGutter(false); // renderer.setHScrollBarAlwaysVisible(false); // } function focused(editor, event) { focusPanel = editor.id; } function getFocusedPanel() { return focusPanel; } function setupEditor(panel) { var e = editors[panel], focusedPanel = sessionStorage.getItem('panel'); // overhang from CodeMirror1 e.setCode = function (str) { e.setValue(str); }; e.getCode = function () { return e.getValue(); }; e.currentLine = function () { var pos = e.getCursor(); return pos.line; }; e.setOption('onChange', changecontrol); e.setOption('onKeyEvent', keycontrol); e.setOption('onFocus', focused); e.id = panel; e.win = e.getWrapperElement(); e.scroller = $(e.getScrollerElement()); $(e.win).click(function () { e.focus(); }); var $label = $('.code.' + panel + ' > .label'); if (document.body.className.indexOf('ie6') === -1) { e.scroller.scroll(function (event) { if (this.scrollTop > 10) { $label.stop().animate({ opacity: 0 }, 50, function () { $(this).hide(); }); } else { $label.show().stop().animate({ opacity: 1 }, 250); } }); } populateEditor(panel); e.ready = true; if (focusedPanel == panel || focusedPanel == null && panel == 'javascript') { // e.selectLines(e.nthLine(sessionStorage.getItem('line')), sessionStorage.getItem('character')); e.focus(); e.setCursor({ line: (sessionStorage.getItem('line') || 0) * 1, ch: (sessionStorage.getItem('character') || 0) * 1 }); } } function populateEditor(panel) { // populate - should eventually use: session, saved data, local storage var data = sessionStorage.getItem(panel), // session code saved = localStorage.getItem('saved-' + panel), // user template sessionURL = sessionStorage.getItem('url'), changed = false; if (data == template[panel]) { // restored from original saved editors[panel].setCode(data); } else if (data && sessionURL == template.url) { // try to restore the session first - only if it matches this url editors[panel].setCode(data); // tell the document that it's currently being edited, but check that it doesn't match the saved template // because sessionStorage gets set on a reload changed = data != saved; } else if (saved !== null && !/edit/.test(window.location) && !window.location.search) { // then their saved preference editors[panel].setCode(saved); } else { // otherwise fall back on the JS Bin default editors[panel].setCode(template[panel]); } if (changed) { $(document).trigger('codeChange', [ /* revert triggered */ false, /* don't use fade */ true ]); } } // work out the browser platform var ua = navigator.userAgent; if (/macintosh|mac os x/.test(ua)) { $.browser.platform = 'mac'; } else if (/windows|win32/.test(ua)) { $.browser.platform = 'win'; } else if (/linux/.test(ua)) { $.browser.platform = 'linux'; } else { $.browser.platform = ''; } function changecontrol(event) { // sends message to the document saying that a key has been pressed, we'll ignore the control keys // if (! ({ 16:1, 17:1, 18:1, 20:1, 27:1, 37:1, 38:1, 39:1, 40:1, 91:1, 93:1 })[event.which] ) { $(document).trigger('codeChange'); // } return true; } //= require "keycontrol"
JavaScript
0.000001
@@ -716,24 +716,60 @@ pt.ready) %7B%0A +%0A editors.html.setCursor(7, 8);%0A%0A clearInt
e2b4b99ab4a7601c3e6db635f15ed548c0085387
work in IE8
csv-line.js
csv-line.js
module.exports = function (options) { var separator = options && options.separator ? options.separator : ',' , escapeNewlines = options && options.escapeNewlines === true , regexp = new RegExp('[' + separator + '\r\n"]') , escape = function (cell) { if (typeof(cell) === 'string') { if (escapeNewlines) { cell = cell.replace(/\n/g, '\\n') } cell = regexp.test(cell) ? '"' + cell.replace(/"/g, '""') + '"' : cell } return cell } return function (array) { return array.map(escape).join(separator) } }
JavaScript
0
@@ -1,8 +1,196 @@ +var map = function (input, fn) %7B%0A var result = Array(input.length)%0A%0A for(var i = 0; i %3C input.length; ++i) %7B%0A result%5Bi%5D = fn(input%5Bi%5D)%0A %7D%0A%0A return result%0A %7D%0A%0A module.e @@ -742,18 +742,19 @@ urn +map( array -.map( +, esca
7bf6ab3f8f2eb146b09c6506cd0007946425630e
Fix for thumbnail view loading multiple pages
js/infinite-scroll.js
js/infinite-scroll.js
/* global jQuery:true */ /* * Fuel UX Infinite Scroll * https://github.com/ExactTarget/fuelux * * Copyright (c) 2014 ExactTarget * Licensed under the BSD New license. */ // -- BEGIN UMD WRAPPER PREFACE -- // For more information on UMD visit: // https://github.com/umdjs/umd/blob/master/jqueryPlugin.js (function umdFactory (factory) { if (typeof define === 'function' && define.amd) { // if AMD loader is available, register as an anonymous module. define(['jquery', 'fuelux/loader'], factory); } else if (typeof exports === 'object') { // Node/CommonJS module.exports = factory(require('jquery'), require('./loader')); } else { // OR use browser globals if AMD is not present factory(jQuery); } }(function InfiniteScrollWrapper ($) { // -- END UMD WRAPPER PREFACE -- // -- BEGIN MODULE CODE HERE -- var old = $.fn.infinitescroll; // INFINITE SCROLL CONSTRUCTOR AND PROTOTYPE var InfiniteScroll = function (element, options) { this.$element = $(element); this.$element.addClass('infinitescroll'); this.options = $.extend({}, $.fn.infinitescroll.defaults, options); this.curScrollTop = this.$element.scrollTop(); this.curPercentage = this.getPercentage(); this.fetchingData = false; this.$element.on('scroll.fu.infinitescroll', $.proxy(this.onScroll, this)); this.onScroll(); }; InfiniteScroll.prototype = { constructor: InfiniteScroll, destroy: function () { this.$element.remove(); // any external bindings // [none] // empty elements to return to original markup this.$element.empty(); return this.$element[0].outerHTML; }, disable: function () { this.$element.off('scroll.fu.infinitescroll'); }, enable: function () { this.$element.on('scroll.fu.infinitescroll', $.proxy(this.onScroll, this)); }, end: function (content) { var end = $('<div class="infinitescroll-end"></div>'); if (content) { end.append(content); } else { end.append('---------'); } this.$element.append(end); this.disable(); }, getPercentage: function () { var height = (this.$element.css('box-sizing') === 'border-box') ? this.$element.outerHeight() : this.$element.height(); var scrollHeight = this.$element.get(0).scrollHeight; // If we cannot compute the height, then we end up fetching all pages (ends up #/0 = Infinity). // This can happen if the repeater is loaded, but is not in the dom if (scrollHeight === 0 || scrollHeight - this.curScrollTop === 0) { return 0; } return (height / (scrollHeight - this.curScrollTop)) * 100; }, fetchData: function (force) { var load = $('<div class="infinitescroll-load"></div>'); var self = this; var moreBtn; var fetch = function () { var helpers = { percentage: self.curPercentage, scrollTop: self.curScrollTop }; var $loader = $('<div class="loader"></div>'); load.append($loader); $loader.loader(); if (self.options.dataSource) { self.options.dataSource(helpers, function (resp) { var end; load.remove(); if (resp.content) { self.$element.append(resp.content); } if (resp.end) { end = (resp.end !== true) ? resp.end : undefined; self.end(end); } self.fetchingData = false; }); } }; this.fetchingData = true; this.$element.append(load); if (this.options.hybrid && force !== true) { moreBtn = $('<button type="button" class="btn btn-primary"></button>'); if (typeof this.options.hybrid === 'object') { moreBtn.append(this.options.hybrid.label); } else { moreBtn.append('<span class="glyphicon glyphicon-repeat"></span>'); } moreBtn.on('click.fu.infinitescroll', function () { moreBtn.remove(); fetch(); }); load.append(moreBtn); } else { fetch(); } }, onScroll: function (e) { this.curScrollTop = this.$element.scrollTop(); this.curPercentage = this.getPercentage(); if (!this.fetchingData && this.curPercentage >= this.options.percentage) { this.fetchData(); } } }; // INFINITE SCROLL PLUGIN DEFINITION $.fn.infinitescroll = function (option) { var args = Array.prototype.slice.call(arguments, 1); var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('fu.infinitescroll'); var options = typeof option === 'object' && option; if (!data) { $this.data('fu.infinitescroll', (data = new InfiniteScroll(this, options))); } if (typeof option === 'string') { methodReturn = data[option].apply(data, args); } }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.infinitescroll.defaults = { dataSource: null, hybrid: false,//can be true or an object with structure: { 'label': (markup or jQuery obj) } percentage: 95//percentage scrolled to the bottom before more is loaded }; $.fn.infinitescroll.Constructor = InfiniteScroll; $.fn.infinitescroll.noConflict = function () { $.fn.infinitescroll = old; return this; }; // NO DATA-API DUE TO NEED OF DATA-SOURCE // -- BEGIN UMD WRAPPER AFTERWORD -- })); // -- END UMD WRAPPER AFTERWORD --
JavaScript
0
@@ -2474,16 +2474,43 @@ op === 0 + %7C%7C height === scrollHeight ) %7B%0A%09%09%09%09
3cb1cfc098c9e009970f3e26ce54fbf18ef8ba07
Remove unused space
js/live-validation.js
js/live-validation.js
$('document').ready(function(){ // Listen to the username input field $('#username').blur( checkUsername ); }); function checkUsername() { // Obtain the username var username = $(this).val(); // Leave if the username is blank if( username.length < 5 ) { $('#username-message').html('Needs to be at least 5 characters'); return; } else { $('#username-message').html(''); } // Send the username to the server $.ajax({ type: 'post', url: 'app/validate-username.php', data: { username: username }, success: function(dataFromServer) { $('#username-message').html(dataFromServer); }, error: function(){ console.log('cannot find the php file'); } }); }
JavaScript
0.000877
@@ -686,17 +686,9 @@ %7D%0A%09%7D);%0A%0A -%0A%0A%0A%0A%0A%0A%0A%0A %7D
004c42ee893476b3b07f5e65cb29f7b85dc08db0
fix start job types|
js/pages/start_job.js
js/pages/start_job.js
var onPageLoad = require('../shared/pageload'); var FLImage = require('../models/image'); var Thumbnail = require('../views/thumbnail'); var Executable = require('../views/executable'); $(function(){ onPageLoad('start_job'); var gallery = $('#gallery'); api.getImages(function(data) { if (data.res) { _.each(data.images, function(img) { var image = new FLImage({ src: api.url + 'img?id=' + img.imageid }); var thumb = new Thumbnail({ model: image }); thumb.render().$el.appendTo(gallery); }); } }); api.getExecutables(function(data) { if (data.res) { if (data.execs.length === 0) { $('#exelist').text('No executables to run. Please upload one.'); } else { _.each(data.execs, function(exec) { console.log(exec); var exe = new Executable({ name: exec.name }); exe.render().$el.appendTo('#exelist ul'); }); } } }); $('#start').on('click', function() { console.log($('input[type=radio]:checked')); var exe = 1; var images = [1, 2, 3]; api.startJob(exe, images, function(data) { console.log(data); }); }); });
JavaScript
0.000001
@@ -1327,40 +1327,136 @@ e = -1;%0A var images = %5B1, 2, 3 +'4dafc690d01355d335169c52609bf08e';%0A var images = %5B'b3639a00751454b1fa0f0cc39fb5992c', '11d70a64fee30a8dacb58f7bdfcf25f3' %5D;%0A%0A
82f0802a759cc54431ddf18c9e494fbedaa03256
change font sizes on comments
src/manager/components/CommentList/style.js
src/manager/components/CommentList/style.js
const commentItem = { display: 'flex', paddingBottom: '5px', WebkitFontSmoothing: 'antialiased', transition: 'opacity 0.5s', } export default { wrapper: { flex: 1, overflow: 'auto', padding: '7px 15px', }, commentItem: { ...commentItem, }, commentItemloading: { ...commentItem, opacity: 0.25, }, commentAside: { margin: '5px 10px 0 0', }, commentAvatar: { width: 32, height: 32, borderRadius: 5, }, commentContent: { flex: 1, }, commentHead: { // }, commentUser: { fontFamily: 'sans-serif', fontSize: 12, lineHeight: 1, fontWeight: 'bold', marginRight: 5, }, commentTime: { fontFamily: 'sans-serif', fontSize: 11, lineHeight: 1, color: 'rgb(150, 150, 150)', }, commentText: { fontFamily: 'sans-serif', fontSize: 11, lineHeight: 1, }, }
JavaScript
0
@@ -590,17 +590,17 @@ tSize: 1 -2 +3 ,%0A li @@ -837,33 +837,33 @@ %0A fontSize: 1 -1 +3 ,%0A lineHeight @@ -861,21 +861,23 @@ ineHeight: 1 +.7 ,%0A %7D,%0A%7D%0A
2652b2cb886ef87be2115f63ab9847e35bddd79d
Set lastPopup-Date only if readed
src/js/adminInfo.js
src/js/adminInfo.js
/* global socket, systemLang */ function InfoAdapter(main) { var that = this; this.main = main; this.checkVersion = function (smaller, bigger) { smaller = smaller.split('.'); bigger = bigger.split('.'); smaller[0] = parseInt(smaller[0], 10); bigger[0] = parseInt(bigger[0], 10); if (smaller[0] > bigger[0]) { return false; } else if (smaller[0] === bigger[0]) { smaller[1] = parseInt(smaller[1], 10); bigger[1] = parseInt(bigger[1], 10); if (smaller[1] > bigger[1]) { return false; } else if (smaller[1] === bigger[1]) { smaller[2] = parseInt(smaller[2], 10); bigger[2] = parseInt(bigger[2], 10); return (smaller[2] < bigger[2]); } else { return true; } } else { return true; } }; this.checkVersionBetween = function (inst, vers1, vers2) { return inst === vers1 || inst === vers2 || (that.checkVersion(vers1, inst) && that.checkVersion(inst, vers2)); }; this.showPopup = function (obj) { that.main.socket.emit('getState', 'info.0.last_popup', function (err, dateObj) { if (!err && dateObj) { that.checkAndSetData(obj, dateObj.val); } }); }; this.checkAndSetData = async function (messagesObj, date) { const messages = await that.checkMessages(messagesObj, date); if (messages.length === 1) { const message = messages[0]; that.main.showMessage(message.content, message.title, message.class); } else if (messages.length > 1) { let content = "<ol>"; const idArray = []; messages.forEach(function (message) { if (idArray.indexOf(message.id) === -1) { content += "<li>"; content += "<h5>" + message.title + "</h5>"; content += "<p>" + message.content + "</p>"; content += "</li>"; idArray.push(message.id); } }); content += "</ol>"; that.main.showMessage(content, _("Please read these important notes:"), "error"); } that.main.socket.emit('setState', 'info.0.last_popup', {val: new Date().toISOString(), ack: true}); }; this.checkMessages = async function (obj, date) { const messagesToShow = []; try { const messages = JSON.parse(obj); const today = new Date().getTime(); let lastMessage = 0; if (date) { lastMessage = new Date(date).getTime(); } if (messages.length > 0) { await asyncForEach(messages, async function (message) { let showIt = true; if (showIt && message['created'] && new Date(message['created']).getTime() < lastMessage) { showIt = false; } else if (showIt && message['date-start'] && new Date(message['date-start']).getTime() > today) { showIt = false; } else if (showIt && message['date-end'] && new Date(message['date-end']).getTime() < today) { showIt = false; } else if (showIt && message.conditions && Object.keys(message.conditions).length > 0) { const adapters = that.main.tabs.adapters.curInstalled; await asyncForEach(Object.keys(message.conditions), function (key) { const adapter = adapters[key]; const condition = message.conditions[key]; if (!adapter && condition !== "!installed") { showIt = false; } else if (adapter && condition === "!installed") { showIt = false; } else if (adapter && condition.startsWith("equals")) { const vers = condition.substring(7, condition.length - 1).trim(); showIt = (adapter.version === vers); } else if (adapter && condition.startsWith("bigger")) { const vers = condition.substring(7, condition.length - 1).trim(); showIt = that.checkVersion(vers, adapter.version); } else if (adapter && condition.startsWith("smaller")) { const vers = condition.substring(8, condition.length - 1).trim(); showIt = that.checkVersion(adapter.version, vers); } else if (adapter && condition.startsWith("between")) { const vers1 = condition.substring(8, condition.indexOf(',')).trim(); const vers2 = condition.substring(condition.indexOf(',') + 1, condition.length - 1).trim(); showIt = that.checkVersionBetween(adapter.version, vers1, vers2); } }); } if (showIt) { messagesToShow.push({"id": message.id, "title": message.title[systemLang], "content": message.content[systemLang], "class": message.class, "icon": message['fa-icon'], "created": message.created}); } }); } } catch (err) { } return messagesToShow; }; this.init = function () { if (that.main.objects["info.0.newsfeed"] && that.main.objects["info.0.last_popup"]) { that.main.socket.emit('subscribe', 'info.0.newsfeed'); that.main.socket.on('stateChange', function (id, obj) { if (id === "info.0.newsfeed") { that.showPopup(obj.val); } }); that.main.socket.emit('getState', 'info.0.newsfeed', async function (err, obj) { if (!err && obj) { that.showPopup(obj.val); } }); } }; }
JavaScript
0
@@ -2304,32 +2304,71 @@ or%22);%0A %7D%0A + if (messages.length %3E 0) %7B%0A that.mai @@ -2455,24 +2455,34 @@ ck: true%7D);%0A + %7D%0A %7D;%0A%0A
bf3691071ddce26f8f77fa4bf06483d087574149
Update functions.js
src/js/functions.js
src/js/functions.js
// button handler document.getElementById("searchButton").addEventListener("click", buttonHandler); // button handler function buttonHandler() { var acronym = document.getElementById("acronymInput").value; var definition = lookupAcronym(acronym); console.log("The meaning of " + acronym + " is " + definition); document.getElementById("result").innerHTML = definition; } // function to look up for acronym's def function lookupAcronym(acronym) { if (acronym) { var xmlhttp = new XMLHttpRequest(); var url = "https://raw.githubusercontent.com/bichdiep1802/demoApp/master/src/fakedAcronyms.JSON"; xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var arr = JSON.parse(xmlhttp.responseText); return arr[acronym]; } } xmlhttp.open("GET", url, true); xmlhttp.send(); } return "sorry!"; }
JavaScript
0.000002
@@ -1,27 +1,9 @@ -// button handler%0A document @@ -359,17 +359,16 @@ ion;%0A%7D%0A%0A -%0A // func @@ -435,16 +435,34 @@ onym) %7B%0A +%09var def = %22...%22;%0A %09if (acr @@ -471,24 +471,25 @@ ym) %7B%0A%09 +%09 var xmlhttp @@ -517,16 +517,17 @@ );%0A%09 +%09 var url @@ -620,24 +620,25 @@ N%22;%0A +%09 xmlhttp.onre @@ -785,22 +785,23 @@ %09 -return +%09%09def = arr%5Bacr @@ -820,24 +820,25 @@ %09%09%7D%0A%09 +%09 xmlhttp.open @@ -862,16 +862,17 @@ );%0A%09 +%09 xmlhttp. @@ -894,16 +894,11 @@ urn -%22sorry!%22 +def ;%0A%7D%0A
81844346138041e31542104299b398b97345efc2
Use let instead of var
src/js/utils/app.js
src/js/utils/app.js
import nedb from 'nedb'; import fs from 'fs'; import path from 'path'; import teeny from 'teeny-conf'; import AppActions from '../actions/AppActions'; const remote = electron.remote; const app = remote.app; const screen = remote.screen; /* |-------------------------------------------------------------------------- | Some variables |-------------------------------------------------------------------------- */ var browserWindows = {}; browserWindows.main = remote.getCurrentWindow(); var pathUserData = app.getPath('userData'), pathSrc = __dirname; /* |-------------------------------------------------------------------------- | Config |-------------------------------------------------------------------------- */ var conf = teeny.loadOrCreateSync(path.join(pathUserData, 'config.json'), {}); /* |-------------------------------------------------------------------------- | supported Formats |-------------------------------------------------------------------------- */ var supportedFormats = [ 'audio/mp3', 'audio/mp4', 'audio/mpeg3', 'audio/x-mpeg-3', 'audio/mpeg', 'audio/wav', 'audio-wave', 'audio/x-wav', 'audio/x-pn-wav', 'audio/ogg' ]; /* |-------------------------------------------------------------------------- | Audio |-------------------------------------------------------------------------- */ // What plays the music var audio = new Audio(); var audioOptions = conf.get('audio'); audio.volume = audioOptions.volume; audio.playbackRate = audioOptions.playbackRate; audio.addEventListener('ended', AppActions.player.next); audio.addEventListener('error', AppActions.player.audioError); /* |-------------------------------------------------------------------------- | Database |-------------------------------------------------------------------------- */ var db = new nedb({ filename: path.join(pathUserData, 'library.db'), autoload: true }); db.reset = function() { db.remove({}, { multi: true }, function (err, numRemoved) { db.loadDatabase(function (err) { if(err) throw err; }); }); }; // WTFix, db.loadDatabase() throw an error if the line below is not here fs.writeFile(path.join(pathUserData, '.init'), "", (err) => { if(err) throw err; }); /* |-------------------------------------------------------------------------- | Export |-------------------------------------------------------------------------- */ export default { version : app.getVersion, // Museeks version config : conf, // teeny-conf initialConfig : conf.getAll(), // the config at the start of the application db : db, // database supportedFormats : supportedFormats, // supported audio formats audio : audio, // HTML5 audio tag pathSrc : pathSrc, // path of the app browserWindows : browserWindows // Object containing all the windows };
JavaScript
0.000001
@@ -424,19 +424,19 @@ ---%0A*/%0A%0A -var +let browser @@ -503,19 +503,19 @@ dow();%0A%0A -var +let pathUse @@ -756,19 +756,19 @@ ---%0A*/%0A%0A -var +let conf = @@ -1017,19 +1017,19 @@ ---%0A*/%0A%0A -var +let support @@ -1426,19 +1426,19 @@ e music%0A -var +let audio = @@ -1452,19 +1452,19 @@ dio();%0A%0A -var +let audioOp @@ -1876,19 +1876,19 @@ ---%0A*/%0A%0A -var +let db = ne